← Back to the chapter · Previous detail
Technical detail · MQTT Python: Reliable Client Patterns
Silent operations screen diagnostic fixture
I’ll trace the fixture from subscription acceptance to actual message receipt, then check the repair after reconnecting.
# Terminal 1: Subscribe to the intended sensor branch; -d prints CONNACK/SUBACK evidence
mosquitto_sub -d -h test.mosquitto.org -t 'plant/+/temperature' -v
# A successful SUBACK proves the subscription was accepted; wait for sensor traffic.
A successful SUBACK can coexist with no sensor traffic. A bare # filter is restricted on this public test service and would not include \$SYS topics in any case.
# The boiler sensor publishes 83.4 C to:
"plant/boiler7/temperature" # ESP32 code
# The operations screen subscribes to:
"plant/+/temperature" # Python code - this SHOULD match
# But wait - check for typos!
print(f"Subscribing to: {TOPIC}") # Add debug print
The runtime output was Subscribing to: plant//temperature. The intended filter matched; the actual filter contained a double slash from a string-formatting error.
# A QoS-capable publisher sends at QoS 1
publisher.publish(topic, payload, qos=1)
# Python operations screen subscribes with QoS 0
operations_screen.subscribe("plant/+/temperature", qos=0)
The broker can acknowledge QoS 1 reception from the publisher and deliver to this subscriber at QoS 0. QoS 0 has no MQTT acknowledgement on the subscriber leg. Changing QoS does not repair a wrong topic filter. A link-loss percentage does not determine MQTT message loss because TCP retransmits packets.
# BAD: Developer forgot to call loop
def main():
client.connect(BROKER, 1883)
client.subscribe("plant/+/temperature")
while True:
time.sleep(1) # WRONG: No network processing!
# GOOD: Call loop to process incoming packets
def main():
client.connect(BROKER, 1883)
client.subscribe("plant/+/temperature")
client.loop_forever() # Blocks and processes messages
The sleeping application leaves network work undone. The corrected listener keeps it moving.
# Corrected operations screen code
BROKER = "test.mosquitto.org"
TOPIC = "plant/+/temperature" # Fixed double-slash typo
def on_connect(client, userdata, flags, reason_code, properties):
print(f"Connected. Subscribing to: {TOPIC}")
client.subscribe(TOPIC, qos=1) # Match publisher QoS
def on_message(client, userdata, msg):
print(f"Received: {msg.topic} = {msg.payload.decode()}")
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_connect = on_connect
client.on_message = on_message
client.connect(BROKER, 1883)
client.loop_forever() # Ensures callbacks are invoked
The corrected filter, assigned callbacks and running loop explain the repair. Received topic and payload output after reconnect provide evidence that receipt resumed.