使用python paho订阅和阅读有关mqtt mosquitto的几个主题

时间:2017-09-13 07:14:48

标签: python mqtt mosquitto

我设法发布了几个主题并阅读了其中一个主题。我需要做的是倾听和阅读所有已发布的主题并获取消息。这是我使用的代码:

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

1 个答案:

答案 0 :(得分: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)])