"""
MicroPython MQTT LED light control and temp&humid sensor report Example for Wokwi.com
To control the led:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Public, set the Topic to "wokwi-light"
4. in the Message field type (json format): {"command": true}
5. click "Publish"
to get the temp&humid:
6. Under subscribe, set the Topic to "wokwi-sensor"
7. click "subscribe"
Copyright (C) 2022, Uri Shaked
Reference:
https://wokwi.com/arduino/projects/315787266233467457
umqtt.simple参考:
https://mpython.readthedocs.io/en/master/library/mPython/umqtt.simple.html
https://pypi.org/project/micropython-umqtt.simple/
"""
import network
from machine import Pin
from time import sleep
import ujson
from umqtt.simple import MQTTClient
import dht
# MQTT Server Parameters
MQTT_CLIENT_ID = ""
MQTT_BROKER = "thingsboard.cloud"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_SUB_TOPIC = "v1/devices/me/rpc/request/+"
MQTT_PUB_TOPIC = "v1/devices/me/telemetry"
# 延时次数计数变量,每次延时0.2秒,10次延时是2秒钟
counter=0
sensor = dht.DHT22(Pin(25))
# LED灯连接在ESP32的D13引脚
led = Pin(13, Pin.OUT)
# mqtt回调函数,当收到订阅主体的MQTT消息时执行
def mqtt_message(topic, msg):
print("Incoming message:", msg)
print("Incoming topic:", topic)
responseTopic = topic
responseTopic = responseTopic.replace(b"request",b"response")
try:
msg = ujson.loads(msg)
print(msg)
if(msg['method']=='command' and msg['params']):
led.on()
client.publish(responseTopic,'''{"light": "on"}''')
else:
led.off()
client.publish(responseTopic,'''{"light": "off"}''')
except Exception as e:
print("Error:", e)
# 连接WiFi
print("Connecting to WiFi...", end="")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "")
while not wifi.isconnected():
sleep(0.5)
print(".", end="")
print("Wifi Connection Done")
# 连接 MQTT服务器
print("Connecting to MQTT...")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(mqtt_message)
client.connect()
client.subscribe(MQTT_SUB_TOPIC)
print("MQTT Connected!")
prev_message = ""
# 如下循环执行两个周期性事务
# 1. 调用mqtt的check_msg()方法检查是否有来自MQTT服务器的消息
# 2. 每2秒钟,上报一个数据
while True:
if (counter<10): counter=counter+1
elif (counter>=10):
counter=0
# client.publish("wokwi2","hello from esp32")
print("Measuring temperature & humidity... ", end="")
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
})
if message != prev_message:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_PUB_TOPIC, message))
client.publish(MQTT_PUB_TOPIC, message)
prev_message = message
else:
print("No change")
client.check_msg()
sleep(0.2)