【问题标题】:Python Paho MQTT: Unable to publish immediately in a functionPython Paho MQTT:无法在函数中立即发布
【发布时间】: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()

【问题讨论】:

    标签: python mqtt paho


    【解决方案1】:

    您不能这样做,在您调用发布时,您已经处于消息处理循环(即所谓的 on_message 函数)中。这会将传出的消息排队等待循环的下一次迭代处理,这就是为什么它们会在 on_message 返回时发送。

    当你调用循环方法时它会挂起,因为循环已经在运行了。

    无论如何,您不应该在 on_message 回调中进行阻塞(睡眠)调用,如果您需要做一些需要时间的事情,请启动第二个线程来执行这些操作。通过这样做,您可以释放网络循环,以便在发布后立即处理它们。

    【讨论】:

    • 你也不应该在回调中调用 loop()。
    • 感谢您的回复。对此,我真的非常感激!我想我对 on_message 回调的目的有点困惑。
    猜你喜欢
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多