MQTT與ESP32-MicroPython¶
在ESP32上安裝MQTT庫¶
首先,我們需要在ESP32上面安裝mqtt的庫。(MQTT客戶端在ESP32上面的實現)
首先確認ESP32-MicroPython已經連接上了熱點!!!, 通過REPL控制ESP32。
引入upip
包管理器
>>> import upip >>> upip.install('micropython-umqtt.simple') Installing to: /lib/ Installing micropython-umqtt.simple 1.3.4 from https://files.pythonhosted.org/packages/bd/cf/697e3418b2f44222b3e848078b1e33ee76aedca9b6c2430ca1b1aec1ce1d/micropython-umqtt.simple-1.3.4.tar.gz
這樣umqtt.simple這個包就安裝好了。
使用umqtt實現接收者¶
esp32/subscriber.py from umqtt.simple import MQTTClient import time SERVER = '192.168.43.16' CLIENT_ID = 'PYESPCAR_A0' TOPIC = b'pyespcar_basic_control' def mqtt_callback(topic, msg): print('topic: {}'.format(topic)) print('msg: {}'.format(msg)) client = MQTTClient(CLIENT_ID, SERVER) client.set_callback(mqtt_callback) client.connect() client.subscribe(TOPIC) while True: # 查看是否有數據傳入 # 有的話就執行 mqtt_callback client.check_msg() time.sleep(1)
使用umqtt實現發送者¶
esp32/publisher.py from umqtt.simple import MQTTClient import time SERVER = '192.168.43.16' CLIENT_ID = 'PYESPCAR_A0' # 客戶端的ID TOPIC = b'pyespcar_basic_control' # TOPIC的ID client = MQTTClient(CLIENT_ID, SERVER) client.connect() while True: client.publish(TOPIC, 'helloworld') time.sleep(1)
注意在Esp32里面TOPIC
需要是bytes
類型。
現在我們修改 boot.py
原來的
from emp_wifi import Wifi from emp_webrepl import WebREPL from emp_utils import webrepl_pass from emp_utils import post_ip if __name__ == '__main__': Wifi.connect() try: post_ip(Wifi.ifconfig()[0][0]) except ImportError: pass WebREPL.start(password=webrepl_pass()) from emp_ide import *
新的
from emp_wifi import Wifi from emp_webrepl import WebREPL from emp_utils import webrepl_pass from emp_utils import post_ip import ubinascii import machine #mqtt 服務器相應的信息 mqtt_server = '*.*.*.*' client_id = b'Q1'+ubinascii.hexlify(machine.unique_id()).upper() mqtt_user = b'Q1' mqtt_pwd = b'' topic_sub = client_id topic_pub = b'Hongwans_EMQ' if __name__ == '__main__': Wifi.connect() try: post_ip(Wifi.ifconfig()[0][0]) except ImportError: pass WebREPL.start(password=webrepl_pass()) from emp_ide import *
main.py 可以這樣寫
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) led.on() 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消息 def sub_cb(topic, msg): global iswhile msg = bytes.decode(msg) print((topic, msg))
try: #5小時重啟一次 last_reset = time.time() reset_interval = 60 * 60 * 5 #通知服務器我在 last_message = 0 message_interval = 1 client = connect_and_subscribe() print('HwClient_SN:'+client_id.decode()) except OSError as e: restart_and_reconnect() while True: try: client.check_msg() if (time.time() - last_reset) > reset_interval: restart_and_reconnect() if (time.time() - last_message) > message_interval: jsonData = '{"TheSender":"'+client_id.decode()+'","Receiver":"'+topic_pub.decode()+'","MessTpye":"string","Content":"ian"}'; client.publish(topic_pub, jsonData) last_message = time.time() except OSError as e: restart_and_reconnect()
MQTT 服務器必須發送信息給一個主題。如果一直讀取沒有發送,MQTT會中斷。