"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# Device setup
DEVICE_ID = "wokwi001"
# MQTT Setup
MQTT_CLIENT = DEVICE_ID
#MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_BROKER = "mqtt-dashboard.com"
MQTT_TELEMETRY_TOPIC = "iot/device/{0}/telemetry".format(DEVICE_ID)
MQTT_CONTROL_TOPIC = "iot/device/{0}/control".format(DEVICE_ID)
# DHT Sensor Setup
sensor = dht.DHT22(Pin(15))
# LED Setup
RED_LED = Pin(12, Pin.OUT)
BLUE_LED = Pin(13, Pin.OUT)
RED_LED.on()
BLUE_LED.on()
#Methods
def did_recieve_callback(topic, message):
print('\n\nData Recieved! \ntopic = {0}, message = {1}'.format(topic, message))
if topic == MQTT_CONTROL_TOPIC.encode():
#Get the command message from json command.
command_message = ujson.loads(message.decode())["command"]
if command_message == "lamp/red/on":
RED_LED.on()
elif command_message == "lamp/red/off":
RED_LED.off()
elif command_message == "lamp/blue/on":
BLUE_LED.on()
elif command_message == "lamp/blue/off":
BLUE_LED.off()
elif command_message == "lamp/on":
RED_LED.on()
BLUE_LED.on()
elif command_message == "lamp/off":
RED_LED.off()
BLUE_LED.off()
elif command_message == "status":
global telemetry_data_old
mqtt_client_publish(MQTT_TELEMETRY_TOPIC, telemetry_data_old)
else:
return
send_led_status()
def mqtt_connect():
print("Connecting to MQTT broker ...", end="")
mqtt_client = MQTTClient(MQTT_CLIENT, MQTT_BROKER, user="", password="")
mqtt_client.set_callback(did_recieve_callback)
mqtt_client.connect()
print("Connected.")
mqtt_client.subscribe(MQTT_CONTROL_TOPIC)
return mqtt_client
def create_control_json_data(command, command_id):
data = ujson.dumps({
"device_id": DEVICE_ID,
"command_id": command_id,
"command": command,
})
return data
def create_json_data(temperature, humidity):
data = ujson.dumps({
"device_id": DEVICE_ID,
"temp": temperature,
"humidity": humidity,
"type": "senor",
})
return data
def mqtt_client_publish(topic, data):
print("\nUpdating MQTT Broker.")
client.publish(topic,data)
print(data)
def send_led_status():
data = ujson.dumps({
"device_id": DEVICE_ID,
"red_led": "ON" if RED_LED.value() == 1 else "OFF",
"blue_led": "ON" if BLUE_LED.value() == 1 else "OFF",
"type": "lamp",
})
mqtt_client_publish(MQTT_TELEMETRY_TOPIC, data)
# Application Logic
# Connect to WiFi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
# Wait until WiFi is Connected
print("Connecting")
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print("WiFi Connected!")
print(sta_if.ifconfig())
# Connect to MQTT
client = mqtt_connect()
mqtt_client_publish(MQTT_CONTROL_TOPIC, create_control_json_data('lamp/off', 'DEVICE-RESET-00'))
telemetry_data_old = ""
print("Measuring weather conditions... ", end="")
while True:
client.check_msg()
print(". ", end="")
try:
sensor.measure()
except:
pass
time.sleep(0.2)
telemetry_data_new = create_json_data(sensor.temperature(), sensor.humidity())
if telemetry_data_new != telemetry_data_old:
mqtt_client_publish(MQTT_TELEMETRY_TOPIC, telemetry_data_new)
telemetry_data_old = telemetry_data_new
time.sleep(0.1)