0
我正在使用MQTT來監視我訂閱的一些頻道。現在我想實現發送消息作爲對狀態的反應。我用下面的代碼運行它,在那裏我只是在on_message回調中做出反應(代碼1在最後)。但是這段代碼使用MQTT:如何發送消息而無需調用loop_forever()
loop_forever()
在阻塞的主要代碼中。
我想要做的是隻發送一條消息到MQTT。
import paho.mqtt.client as mqtt
if __name__ == "__main__":
mqtt_client = mqtt.Client()
mqtt_client.connect("192.168.178.204", 1883, 60)
mqtt_client.username_pw_set(username="test", password="test")
mqtt_client.publish(topic='TEST', payload='CCCCCCCCC', retain=False)
mqtt_client.loop_write()
# mqtt_client.loop()
# mqtt_client.loop_start()
mqtt_client.disconnect()
我如何將消息發送給MQTT不擋住過程:當我嘗試以下方法(與所有不同的循環功能),沒有什麼是由MQTT服務器接收?
代碼1:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, rc):
topic_list = [("TEST_MS", 1)]
if rc == 0:
print("Successful connected and subscribed to: {}".format(topic_list))
client.subscribe(topic_list)
def on_message(client, userdata, msg):
print(msg.payload)
client.publish(topic='TEST_MS2', payload=msg.payload, retain=False)
def on_publish(client, userdata, mid):
print("message published")
def on_subscribe(mosq, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
if __name__ == "__main__":
mqtt_client = mqtt.Client()
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_client.on_publish = on_publish
mqtt_client.on_subscribe = on_subscribe
mqtt_client.connect("192.168.178.204", 1883, 60)
mqtt_client.username_pw_set(username="test", password="test")
# mqtt_client.publish(topic='TEST_MS', payload='CCCCCCCCC', retain=False)
mqtt_client.loop_forever()
mqtt_client.disconnect()
非常好,非常感謝你 – mstuebner