Python 如何使用MQTT和Flask在web上做出响应?
我对MQTT lib()有问题 我希望为多个请求提供异步和同步任务,但似乎我无法回避一个问题,即在收到实际订阅的消息时,在web上对请求的url/mqtt做出响应,因为on_消息是一个回调函数Python 如何使用MQTT和Flask在web上做出响应?,python,flask,mqtt,iot,paho,Python,Flask,Mqtt,Iot,Paho,我对MQTT lib()有问题 我希望为多个请求提供异步和同步任务,但似乎我无法回避一个问题,即在收到实际订阅的消息时,在web上对请求的url/mqtt做出响应,因为on_消息是一个回调函数 @app.route('/mqtt', methods=['POST', 'GET']) def main(): client = mqtt.Client() client.on_connect = on_connect client
@app.route('/mqtt', methods=['POST', 'GET'])
def main():
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
test = on_message
client.username_pw_set('x', 'x')
client.connect("x", 1883, 60)
client.subscribe("/message/1")
client.loop_forever()
# how do I get the message from callback function on_message and then stop loop_forever?
#I thought about: return msg but it doesn't work.
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
#how to pass this msg to the main function?
print(msg.topic + " " + str(msg.payload))
要在收到消息时永远停止循环,您可以使用
客户端。断开连接
示例代码:
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
client.disconnect() # disconnect when get message
要将消息传递给main函数,只需使用全局变量。但我的建议是为mqtt客户机启动另一个进程,通过共享内存传递变量。每次获得GET或POST时,连接到mqtt代理都会产生大量开销