私はESP8266によって新しいメッセージが発行されたときに、特定のトピックを聞いて反応するプログラムを実装しています。新しいメッセージがESP8266から受信されると、私のプログラムはコールバックをトリガして一連のタスクを実行します。私はArduinoが聞いているトピックにコールバック関数で2つのメッセージを公開しています。ただし、メッセージは、関数が終了した後にのみ公開されます。Python Paho MQTT:すぐに関数に公開することができない
ありがとうございます。
私はコールバック関数の中で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()
コールバックでもloop()を呼び出すべきではありません。 – ralight
お返事ありがとうございます。ほんとうにありがとう!私は、目的のon_messageコールバックと少し混乱していたと思います。 – Zen