Esp32笔记(4)MQTT通信
编写代码完成esp32上的mqtt客户端, 每隔1秒钟发布如下消息: 消息主题:“id” 消息内容:“你的学号”
1.代码
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"
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
.value
(state
)
state
= 1 - state
def connectWifi(ssid
,passwd
):
global wlan
wlan
=network
.WLAN
(network
.STA_IF
)
wlan
.active
(True)
wlan
.disconnect
()
wlan
.connect
(ssid
,passwd
)
while(wlan
.ifconfig
()[0]=='0.0.0.0'):
time
.sleep
(1)
try:
connectWifi
(SSID
,PASSWORD
)
server
=SERVER
c
= MQTTClient
(CLIENT_ID
, server
,0,username
,password
)
c
.set_callback
(sub_cb
)
c
.connect
()
c
.subscribe
(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
)
配置服务器参数
SERVER
= "你的mqtt服务器ip
CLIENT_ID
= "你的id"
TOPIC
= b
"你的主题"
username
='你的mqtt服务器账号'
password
='你的mqtt服务器密码'
发送消息
while True:
c
.publish
(TOPIC
, '发送的消息')
time
.sleep
(1)
结果,一秒一次
转载请注明原文地址: https://lol.8miu.com/read-15054.html