У меня есть два отдельных файла для публикации и подписки для тестирования протокола mqtt. Я поддерживаю один файл конфигурации для хранения общих параметров, таких как client_id , broker name и themes .
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)
Я не могу понять, что я делаю неправильно, так что подписчик не поймает мои сообщения.