我有两个单独的文件,用于发布和订阅以测试mqtt协议。我维护一个配置文件来存储 client_id ,经纪人名称和主题之类的常用参数。
broker = "iot.eclipse.org"
# Random alphanumeric string
uid = "id-sfgjrs45ys4jQPlk"
appliances = {
"room1": [
"appliance1",
"appliance2",
"appliance3",
"appliance4",
"appliance5"
],
"room2": [
"appliance1",
"appliance2",
"appliance3"
]
}
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()
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()
这是同时执行的日志:
Connecting to broker... iot.eclipse.org
Publishing
Sending PUBLISH (d0, q0, r0, m1), 'b'room1/appliance1'', ... (3 bytes)
Sending DISCONNECT
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)
我无法弄清楚我在做什么错,以致订户不会收到我的消息。
答案 0 :(得分:3)