开始前的准备
首先,你需要下载umqtt库文件到esp32,并将wifi.py里面的网络信息改为自己的
编写代码
你需要向在本地创建一个文件,比如main.py并写入以下内容
import time
from umqtt.simple import MQTTClient
# 定义pub客户端的连接信息
server = "192.168.31.55"
ClientID = f'esp32'
topic = "esp32"#凡是订阅了这个主题的,就可以收到消息
msg = b'{"msg":"hello"}'
# 创建连接,参数分别为客户端ID,broker地址,broker端口号,认证信息
def connect():
print('已连接到MQTT代理服务器 "%s"' % (server))
client = MQTTClient(ClientID, server, 1883)
client.connect()
return client
def reconnect():
# 若无法连接到broker,打印一条消息以通知连接不成功,并且等待5秒发起重连
print('连接MQTT代理服务器失败,正在重新连接...')
time.sleep(5)
client.reconnect()
# 定义接收消息的回调函数
def on_message_received(topic, msg):
print('接收到消息: 主题 = {}, 消息 = {}'.format(topic.decode('utf - 8'), msg.decode('utf - 8')))
# 若能连接到broker,调用connect(),反之调用reconnect()
try:
client = connect()
client.set_callback(on_message_received)
client.subscribe(topic)
except OSError as e:
reconnect()
# 每隔1秒给主题raspberry/mqtt发送一条消息,并检查是否有新消息到达
while True:
print('在主题%s上发送消息%s' % (topic, msg))
client.publish(topic, msg, qos=0)
client.check_msg()
time.sleep(1)
© 版权声明
THE END
暂无评论内容