python - 找不到 MQTT python 应用程序不订阅或接收消息的原因
问题描述
MQTT 和烧瓶应用程序没有收到消息我不确定它是否只是没有被订阅,或者我的设备没有收到消息。发布消息有效我已经测试过了,但接收它们没有。我在这里做错了什么吗。
from flask import Flask, render_template
import paho.mqtt.client as mqtt
import time
def on_message(client, userdata, message):
print((message.payload.decode("utf-8")))
broker = "broker.hivemq.com"
client = mqtt.Client("mypc")
client.on_message=on_message
client.connect(broker)
client.loop_start()
client.subscribe('class/ledToggle')
app = Flask(__name__)
@app.route("/")
def index():
return render_template('home.html')
@app.route('/led/<state>')
def led(state):
if (state == "on"):
client.publish('class/ledToggle','1')
elif (state == "off"):
client.publish('class/ledToggle','0')
time.sleep(5)
return render_template('led.html', title = 'Led')
client.loop_stop()
if __name__ == "__main__":
app.run(debug=True)
解决方案
可以使用装饰器的 Flask-MQTT 扩展
如果您想从一开始就订阅主题,请确保等待订阅,直到客户端连接到代理。为此使用flask_mqtt.Mqtt.on_connect()
装饰器。
@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
mqtt.subscribe('home/mytopic')
推荐阅读
- java - 无法获取设备位置
- javascript - Javascript/React onClick 向下/向上滚动设置量
- dialogflow-es - 应用程序超时并退出对话需要多长时间
- php - 函数后在 2 个不同的自定义帖子类型中创建 2 个不同的帖子
- c++ - 使用 Ubuntu 对 Clion 进行 lncurses
- python - 在csv中写入数据的Python程序取决于列的存在
- javascript - 从 firebase 数据库中检索数据(在控制台中工作,但在代码中不起作用)
- performance - O(log n) 澄清
- windows - Git 尝试在 Windows 上暂存 5000 多个文档**
- php - Laravel DataTables 多选复选框