MicroPython – MQTT 與 ESP32/ESP8266
在這個教程中,將會學習如何使用MQTT在ESP8266與MQTT 伺服器之間進行數據交換。最為一個簡單的例子,我將使用一個ESP32開發板向MQTT服
務器發送消息,同時從MQTT伺服器訂閱一個消息。
發布消息的主題(topic)為hello,定於的主題為notification。
我在這裡使用的MQTT伺服器為mosquitto,在我的Windows10系統的電腦上安裝了虛擬機,虛擬機安裝Ubuntu系統,在Ubuntu系統裡安裝的mosquitto。當然也可以安裝在樹莓派上。
準備工作:
首先需要為ESP32安裝micropython固件,MQTT伺服器已經設置好,我這裡MQTT伺服器已經安裝完成,IP位址為192.168.1.121,同時設置了連接MQTT伺服器的帳號與密碼,帳號為miss,密碼為123456。
準備ESP32:
導入umqtttsimple 庫,庫下載地址:https://raw.githubusercontent.com/RuiSantosdotme/ESP-MicroPython/master/code/MQTT/umqttsimple.py
複製代碼,在uPyCraft中新建一個文件,粘貼,保存為umqttsimple.py文件
導入必要的庫:
import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
設置debug為None,激活垃圾收集器。
esp.osdebug(None)
import gc
gc.collect()
定義一些必要的變量,包括本地WiFi帳號與密碼,mqtt伺服器IP位址,MQTT用戶名與密碼,mqtt客戶端id,發布與訂閱的主題,接收消息的時間間隔等。
ssid = 'your-ssid'
password = 'your-pwd'
mqtt_server = '192.168.1.121'
mqtt_user='miss'
mqtt_pwd='123456'
client_id = ubinascii.hexlify(machine.unique_id())
topic_sub = b'notification'
topic_pub = b'hello'
last_message = 0
message_interval = 5
counter = 0
將ESP32連接到網絡:
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
準備main.py
定義一個訂閱回調函數:
def sub_cb(topic, msg):
print((topic, msg))
if topic == b'notification' and msg == b'received':
print('ESP received hello message')
定義一個連接MQTT伺服器和訂閱主題的函數:
def connect_and_subscribe():
global client_id, mqtt_server, topic_sub,mqtt_user,mqtt_pwd
client = MQTTClient(client_id, mqtt_server,user=mqtt_user, password=mqtt_pwd, keepalive=60)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub)
print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
return client
定義一個重啟和重新連接的函數:
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
開始使用上面定義的函數連接MQTT伺服器,訂閱notification主題,並向hello主題發布消息:
try:
client = connect_and_subscribe()
except OSError as e:
restart_and_reconnect()
while True:
try:
client.check_msg()
if (time.time() - last_message) > message_interval:
msg = b'Hello #%d' % counter
client.publish(topic_pub, msg)
last_message = time.time()
counter += 1
except OSError as e:
restart_and_reconnect()
完整boot.py與main.py代碼可以查看下面的騰訊文檔連結
https://docs.qq.com/doc/DS1pqd25qSUdIQ3dN
運行程序與效果圖:
啟動虛擬機上的mqtt伺服器
2.上傳umqttsimple.py
3.上傳boot.py
4.上傳main.py
5.使用mosquitto_sbu命令訂閱ESP32發送的消息
6.使用mosquitto_pub命令發布消息到notification,ESP32訂閱該消息
更多教程請關注: