Python Paho MQTT: Unable to publish immediately in a function

ぐ巨炮叔叔 提交于 2019-12-20 03:13:57

问题


I am implementing a program that listen to a specific topic and react to it when a new message is published by my ESP8266. When a new message is received from ESP8266, my program will trigger the callback and perform a set of tasks. I am publishing two messages in my callback function back to the topic that the Arduino is listening. However, the messages are published only after the function exits.

Thank you for all your time in advance.

I have tried to use loop(1) with a timeout of 1 second inside the callback function. The program will publish the message immediately, but it seems to stuck in the loop. Will someone be able to give me some pointers how can I execute each publish function immediately in my callback function, instead of when the whole callback completes and return to the main 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()

回答1:


You can't do this, you are already in the message handling loop (that's what called the on_message function) at the point you call publish. This will queue the outgoing messages to be handled by the next iteration of the loop, that's why they are sent once on_message returns.

It hangs when you call the loop method because the loop is already running.

You should not be making blocking (sleep) calls in the on_message callback anyway, if you need to do thing that take time, start up a second thread to do these. By doing this you free up the network loop to handle the outgoing publishes as soon as they are made.



来源:https://stackoverflow.com/questions/36961758/python-paho-mqtt-unable-to-publish-immediately-in-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!