MQTT實務

MQTT是一個非常方便的訊息傳輸協定,很棒的是,NodeMCU的MicroPython居然也有支援相關的模組可以直接套用喔。

先來段程式碼:

from umqtt.simple import MQTTClient
from machine import Pin, Timer
import time
import dht
def m(t):
d.measure()
c = MQTTClient("umqtt_client", "your IP")
c.connect()
c.publish(b"skynettw/dorm",
b"{},{}%".format(
d.temperature(), d.humidity()))
c.disconnect()
d = dht.DHT11(Pin(5))
t = Timer(0)
t.init(period=5000, mode=Timer.PERIODIC, callback=m)
try:
pass
except:
d.dinit()