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

标签 python-3.x mqtt publish-subscribe

我正在尝试使用单个订阅者客户端订阅三个不同的主题。但通过下面提到的代码,我只能从一台服务器获取数据。 请建议对我的代码进行 ant 修改,以便从不同的发布者客户端获取所需的数据。

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

最佳答案

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

来自doc :

String and integer tuple

e.g. subscribe(("my/topic", 1))

topic

a tuple of (topic, qos). Both topic and qos must be present in the tuple.

qos

not used.

例如

MQTT_TOPIC = [("服务器1/kpi1",0),("服务器2/kpi2",0),("服务器3/kpi3",0)]

关于python-3.x - 如何在 python 上使用 PAHO-MQTT 订阅多个主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48942538/

相关文章:

c# - 如何检查Redis channel 是否已通过StackExchange.Redis订阅?

publish-subscribe - CQRS + 事件溯源 : (is it correct that) Commands are generally communicated point-to-point, 而领域事件通过发布/订阅进行通信?

python - 为什么从过滤器创建集合比创建列表或元组快得多?

python-3.x - 用于各种维度输入的高效 PyTorch DataLoader collat​​e_fn 函数

python - apply_async 回调函数未被调用

node.js - Nodejs 安全 MQTT 连接

python - 如何在python 3中找到任意列表中缺失的数字?

c# - M2Mqtt消息缓冲

node.js - mqtt.js Node - 通过消息传递 qos

c# - 如何在不需要任何管理员参与的情况下使用发布/订阅?