【得捷电子Follow me第1期】MQTT数据收发
[复制链接]
1、安装umqtt,点击菜单工具->管理包
2、搜索umqtt
3、在查找结果里面点击按装:
4、然后在已安装的包里就看到umqtt了。
5、书如程序代码如下:
from umqtt.simple import MQTTClient
from machine import Pin
import network
import time
ssid='ssid'
passwd='wifipwd'
client_id = "po20t"
mserver = 'ip'
port=1883
mqttuser = "user"
mqttpwd = "pwd"
topic_ctl = b'led_ctl'#设备订阅的主题,客户端推送消息的主题
topic_sta = b'led_sta'#客户端订阅的主题,设备推送消息的主题
client = None
wlan = None
led1=Pin(2, Pin.OUT, value=1)
led2=Pin(5, Pin.OUT, value=1)
def sub_callback(topic, msg):
"""
收到订阅消息回调
"""
global client
print((topic_ctl, msg))
if msg == b'led1 ON' or msg == b'led1 on':
pub_msg = 'LED1: ON-state'
led1.value(0)
elif msg == b'led1 OFF' or msg == b'led1 off':
pub_msg = 'LED1: OFF-state'
led1.value(1)
elif msg == b'led2 ON' or msg == b'led2 on':
pub_msg = 'LED2: ON-state'
led2.value(0)
elif msg == b'led2 OFF' or msg == b'led2 off':
pub_msg = 'LED2: OFF-state'
led2.value(1)
else:
pub_msg = 'other msg'
client.publish(topic_sta, pub_msg, retain=True)
def connectWiFi():
"""
连接到WiFi网络
"""
global wlan
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.disconnect()
wlan.connect('HUAWEI-H10R9U', "18977381885@")
while(wlan.ifconfig()[0]=='0.0.0.0'):
time.sleep(1)
print(wlan.ifconfig())
try:
connectWiFi()
client = MQTTClient(client_id, mserver, port=1883,user=mqttuser,password=mqttpwd)
client.set_callback(sub_callback)
client.connect()
client.subscribe(topic_ctl)
client.publish(topic_sta, 'ESP32 Device online', retain=True)
print("Connected to %s, subscribed to %s topic" % (mserver, topic_ctl))
while True:
client.wait_msg()
finally:
if client is not None:
print('off line')
client.disconnect()
wlan.disconnect()
wlan.active(False)
5、保存到开发板,然后执行:
6、打开mqttx发送消息:
这样连接到远程的Mqtt就愉快的完成了,后面可以完成一些数据交换与控制了。
|