野路子学习esp32(十六) MQTT与ESP32-MicroPython @a.宏万
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会中断。