Esp32笔记(4)MQTT通信入门之循环发送消息

it2024-03-27  49

Esp32笔记(4)MQTT通信

编写代码完成esp32上的mqtt客户端, 每隔1秒钟发布如下消息: 消息主题:“id” 消息内容:“你的学号”

1.代码

#Hardware Platform: FireBeetle-ESP32 #Result: input MQTTlibrary and remote controls LED by mqtt communication. from umqtt.simple import MQTTClient from machine import Pin import network import time SSID="xlu" PASSWORD="111222333" led=Pin(2, Pin.OUT, value=0) SERVER = "你的mqtt服务器ip CLIENT_ID = "你的id" # 如果有两个id一样的,可能会发生一些意想不到的申请 TOPIC = b"你的主题" # 主题主题主题 username='你的mqtt服务器账号' password='你的mqtt服务器密码' state = 0 c=None def sub_cb(topic, msg): global state print((topic, msg)) if msg == b"on": led.value(1) state = 0 print("1") elif msg == b"off": led.value(0) state = 1 print("0") elif msg == b"toggle": # LED is inversed, so setting it to current state # value will make it toggle led.value(state) state = 1 - state def connectWifi(ssid,passwd): global wlan wlan=network.WLAN(network.STA_IF) #create a wlan object wlan.active(True) #Activate the network interface wlan.disconnect() #Disconnect the last connected WiFi wlan.connect(ssid,passwd) #connect wifi while(wlan.ifconfig()[0]=='0.0.0.0'): time.sleep(1) #Catch exceptions,stop program if interrupted accidentally in the 'try' try: connectWifi(SSID,PASSWORD) server=SERVER c = MQTTClient(CLIENT_ID, server,0,username,password) #create a mqtt client c.set_callback(sub_cb) #set callback c.connect() #connect mqtt c.subscribe(TOPIC) #client subscribes to a topic print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) while True: c.publish(TOPIC, '发送的消息') # 循环发送消息 time.sleep(1)# 休息一秒 finally: if(c is not None): c.disconnect() wlan.disconnect() wlan.active(False)

设置回调函数

c.set_callback(sub_cb) #set callback

配置服务器参数

SERVER = "你的mqtt服务器ip CLIENT_ID = "你的id" # 如果有两个id一样的,可能会发生一些意想不到的申请 TOPIC = b"你的主题" # 主题主题主题 username='你的mqtt服务器账号' password='你的mqtt服务器密码'

发送消息

while True: c.publish(TOPIC, '发送的消息') # 循环发送消息 time.sleep(1)# 休息一秒

结果,一秒一次

最新回复(0)