我設法發佈了幾個主題並閱讀其中的一個。我需要做的是聽取並閱讀所有已發佈的主題並獲取消息。這是我的代碼使用方法:訂閱並使用python閱讀mqtt mosquitto上的幾個主題paho
發佈消息3個主題:
#!/usr/bin/env python3 import paho.mqtt.client as mqtt client = mqtt.Client() client.connect("localhost",1883,60) client.publish("topic/1", "400 | 350 | 320 | 410"); client.publish("topic/2", "200 | 350 | 420 | 110"); client.publish("topic/3", "200 | 350 | 420 | 110"); client.disconnect();
1個主題訂閱和閱讀郵件
#!/usr/bin/env python3 import paho.mqtt.client as mqttClient import time def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to broker") global Connected #Use global variable Connected = True #Signal connection else: print("Connection failed") def on_message(client, userdata, message): print "Message received : " + message.payload Connected = False broker_address= "localhost" port = 1883 client = mqttClient.Client("Python") client.on_connect= on_connect client.on_message= on_message client.connect(broker_address, port=port) client.loop_start() while Connected != True: time.sleep(0.1) client.subscribe("topic/2") try: while True: time.sleep(1) except KeyboardInterrupt: print "exiting" client.disconnect() client.loop_stop()
還擁有您的發佈代碼的一個問題,你需要調用客戶端。循環函數在每次發佈之間確保它們全部被刷新到網絡堆棧,或使用單/多發佈函數(https://pypi.python.org/pypi/paho-mqtt/1.1#id17) – hardillb