【发布时间】:2016-05-01 00:34:50
【问题描述】:
我正在实现一个程序,它会在我的 ESP8266 发布新消息时侦听特定主题并对其做出反应。当收到来自 ESP8266 的新消息时,我的程序将触发回调并执行一组任务。我在回调函数中将两条消息发布回 Arduino 正在收听的主题。但是,消息仅在函数退出后发布。
提前感谢您的所有时间。
我尝试在回调函数中使用具有 1 秒超时时间的 loop(1)。程序会立即发布消息,但似乎卡在了循环中。有人可以给我一些指示,我如何在我的回调函数中立即执行每个发布函数,而不是在整个回调完成并返回到主 loop_forever() 时?
import paho.mqtt.client as mqtt
import subprocess
import time
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("ESP8266")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client.publish("cooking", '4')
client.loop(1)
print("Busy status published back to ESP8266")
time.sleep(5)
print("Starting playback.")
client.publish("cooking", '3')
client.loop(1)
print("Free status published published back to ESP8266")
time.sleep(5)
print("End of playback.")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("192.168.1.9", 1883, 60)
#client.loop_start()
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
【问题讨论】: