订阅并使用python阅读mqtt mosquitto上的几个主题paho

问题描述:

我设法发布了几个主题并阅读其中的一个。我需要做的是听取并阅读所有已发布的主题并获取消息。这是我的代码使用方法:订阅并使用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

您可以拨打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