如何在python上使用PAHO-MQTT订阅多个主题

Abh*_*ngh 5 publish-subscribe python-3.x mqtt

我正在尝试使用单个订户客户端订阅三个不同的主题。但是使用下面提到的代码,我只能从一台服务器获取数据。请在我的代码中建议蚂蚁修改,可以实施该修改以从不同的发布者客户端获取所需的数据。

# Define Variables
MQTT_BROKER = "10.97.143.44"
MQTT_PORT = 11883
MQTT_TOPIC = [("Server1/kpi1"),("Server2/kpi2"),("Server3/kpi3")


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):
    data = message.payload
    receive=data.decode("utf-8")
    m_decode = json.loads(receive)
    #print(m_decode)
    #print (m_decode['Server_name'])
    print ("Message received: "  + str(m_decode))


Connected = False   #global variable for the state of the connection

client = mqttClient.Client("Python")               #create new instance
client.on_connect= on_connect                      #attach function to callback
client.on_message= on_message                      #attach function to callback
client.connect(MQTT_BROKER,MQTT_PORT)              #connect to broker         



client.loop_start()        #start the loop

while Connected != True:    #Wait for connection

    time.sleep(0.1)

client.subscribe(MQTT_TOPIC)

try:

    while True:

        time.sleep(1)

except KeyboardInterrupt:

    print ("exiting")

List item

    client.disconnect()

    client.loop_stop()
Run Code Online (Sandbox Code Playgroud)

har*_*llb 8

您的MQTT_TOPIC阵列应包含QOS级别以及主题名称。

文档

字符串和整数元组

例如Subscribe((“ my / topic”,1))

话题

(topic,qos)的元组。元组中必须同时存在topic和qos。

服务质量

未使用。

例如

MQTT_TOPIC = [("Server1/kpi1",0),("Server2/kpi2",0),("Server3/kpi3",0)]