paho-mqtt发布-订阅无法在Python中的单独文件中使用

时间:2019-05-23 22:08:31

标签: python python-3.x mqtt publish-subscribe paho

我有两个单独的文件,用于发布和订阅以测试mqtt协议。我维护一个配置文件来存储 client_id 经纪人名称和主题之类的常用参数。

config.py

broker = "iot.eclipse.org"

# Random alphanumeric string
uid = "id-sfgjrs45ys4jQPlk"

appliances = {
    "room1": [
        "appliance1",
        "appliance2",
        "appliance3",
        "appliance4",
        "appliance5"
    ],
    "room2": [
        "appliance1",
        "appliance2",
        "appliance3"
    ]
}

subscriber.py

import time
import paho.mqtt.client as mqtt
import config

broker = config.broker
client_id = config.uid

topics = list()
for room, appliances in config.appliances.items():
    for appliance in appliances:
        topics.append(room + "/" + appliance)

def on_message(client, userdata, message):
    print("Topic: " + message.topic)
    print("Message: " + message.payload.decode('utf-8'))

client = mqtt.Client(client_id=client_id)
client.on_message = on_message

print("Connecting to broker... " + broker)
client.connect(broker)

print("Subscribing ")
for topic in topics:
    client.subscribe(topic)

print("Listening")
client.loop_forever()

publisher.py

import time
import paho.mqtt.client as mqtt
import config

broker = config.broker
client_id = config.uid

topic = "room1/appliance1"
message = "off"

client = mqtt.Client(client_id=client_id)

print("Connecting to broker... " + broker)
client.connect(broker)

print("Publishing ")
client.publish(
    topic=topic,
    payload=message
)
time.sleep(1)
client.disconnect()

如果将 subscriber.py publisher.py 保留在同一文件中,则它们似乎可以正常工作,例如:

client.loop_start()
client.publish(
    topic=topic,
    payload=message
)
time.sleep(10)
client.loop_stop()

这是同时执行的日志:

登录Publisher.py

(在subscriber.py运行时运行)

Connecting to broker... iot.eclipse.org
Publishing 
Sending PUBLISH (d0, q0, r0, m1), 'b'room1/appliance1'', ... (3 bytes)
Sending DISCONNECT

登录subsciber.py

Connecting to broker... iot.eclipse.org
Sending CONNECT (u0, p0, wr0, wq0, wf0, c1, k60) client_id=b'id-sfgjrs45ys4jQPlk'
Subscribing 
Sending SUBSCRIBE (d0, m1) [(b'room1/appliance1', 0)]
Sending SUBSCRIBE (d0, m2) [(b'room1/appliance2', 0)]
Sending SUBSCRIBE (d0, m3) [(b'room1/appliance3', 0)]
Sending SUBSCRIBE (d0, m4) [(b'room1/appliance4', 0)]
Sending SUBSCRIBE (d0, m5) [(b'room1/appliance5', 0)]
Sending SUBSCRIBE (d0, m6) [(b'room2/appliance1', 0)]
Sending SUBSCRIBE (d0, m7) [(b'room2/appliance2', 0)]
Sending SUBSCRIBE (d0, m8) [(b'room2/appliance3', 0)]
Listening
Received CONNACK (0, 0)
Received SUBACK
Received SUBACK
Received SUBACK
Received SUBACK
Received SUBACK
Received SUBACK
Received SUBACK
Received SUBACK
Sending PINGREQ
Received PINGRESP
Sending PINGREQ
Received PINGRESP
Sending CONNECT (u0, p0, wr0, wq0, wf0, c1, k60) client_id=b'id-sfgjrs45ys4jQPlk'
Received CONNACK (0, 0)

我无法弄清楚我在做什么错,以致订户不会收到我的消息。

1 个答案:

答案 0 :(得分:3)

这是因为您试图从两个具有相同客户端ID uid的单独代码进行连接。

根据规范here

  

每个连接到服务器的客户端都有唯一的ClientId。

尝试使用不同的客户端ID,代码应该可以正常工作