2017-09-13 355 views
0

我設法發佈了幾個主題並閱讀其中的一個。我需要做的是聽取並閱讀所有已發佈的主題並獲取消息。這是我的代碼使用方法:訂閱並使用python閱讀mqtt mosquitto上的幾個主題paho

  1. 發佈消息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(); 
    
  2. 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() 
    
+0

還擁有您的發佈代碼的一個問題,你需要調用客戶端。循環函數在每次發佈之間確保它們全部被刷新到網絡堆棧,或使用單/多發佈函數(https://pypi.python.org/pypi/paho-mqtt/1.1#id17) – hardillb

回答

0

您可以撥打client.subscribe()功能多次訂閱多個主題。

此外,您應該將呼叫移動到訂閱on_connect回調以刪除第一個循環的需要。

#!/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") 
     client.subscribe("topic/1") 
     client.subscribe("topic/2") 
     client.subscribe("topic/3") 
     client.subscribe("topic/4") 

    else: 
     print("Connection failed") 

def on_message(client, userdata, message): 
    print("Message received : " + str(message.payload) + " on " + message.topic) 


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() 


try: 
    while True: 
     time.sleep(1) 

except KeyboardInterrupt: 
    print("exiting") 
    client.disconnect() 
    client.loop_stop() 

編輯:

您也可以訂閱多個主題一次性使用的語法如下

client.subscribe([("topic/1", 0), ("topic/2", 0), ("topic/3", 0),("topic/4", 0)]) 
+0

感謝您的建議。似乎仍然沒有按預期工作,因爲我只得到話題/ 1的回覆。我會盡力弄清楚爲什麼,但是再次感謝 –

+0

我已經編輯它來添加訂閱多個主題的替代方法。 – hardillb

+0

有人想給出downvote的理由嗎? – hardillb