首页 > 解决方案 > 找不到 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)

标签: pythonflaskmqttpaho

解决方案


可以使用装饰器的 Flask-MQTT 扩展

如果您想从一开始就订阅主题,请确保等待订阅,直到客户端连接到代理。为此使用flask_mqtt.Mqtt.on_connect()装饰器。

@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
    mqtt.subscribe('home/mytopic')

推荐阅读