首先把miropython的mqtt库拷贝进入单片机,然后改写单片机程序,
我提前设定好了两个用户hanmeimei和lilei,注意他们的权限。下面是通过单片机订阅mqtt服务器的数据的程序。
import network,time,os
import usocket as socket # 引用socket模块
from machine import UART
import select,json
import lcdmain
from simply import MQTTClient
def sub_cb(topic, msg):
global statemqtt
print((topic, msg)) #打印收到信息
if msg == b"on":
lcdmain.my_text_out("mqtt"+":on",0,32)#单片机显示接收的信息
statemqtt = 1
elif msg == b"off":
lcdmain.my_text_out("mqtt"+":off",0,32)
statemqtt = 0
elif msg == b"toggle":
# LED is inversed, so setting it to current state
# value will make it toggle
lcdmain.my_text_out("mqtt"+":tog",0,32)
statemqtt = 1 - statemqtt
main
c = MQTTClient("umqtt_client", "192.168.1.108",1883,"hanmeimei","密码")
#建立一个MQTT客户端
c.set_callback(sub_cb) #设置回调函数
c.connect() #建立连接
c.subscribe(b"test") #监控ledctl这个通道,接收控制命令