← Back to the chapter · Previous detail · Next detail →
Technical detail · MQTT Python: Reliable Client Patterns
Python callback and network-loop example
# Requires paho-mqtt 2.0+
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, reason_code, properties):
if reason_code == 0:
print("Connected successfully")
client.subscribe("plant/+/temperature")
else:
print(f"Connection failed with reason code {reason_code}")
def on_message(client, userdata, msg):
print(f"Topic: {msg.topic}, Payload: {msg.payload.decode()}")
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_connect = on_connect
client.on_message = on_message
client.connect("test.mosquitto.org", 1883, 60)
client.loop_forever()
The subscription lives in on_connect, so it is restored on reconnect. loop_forever() keeps processing traffic and retries a lost connection; an initial blocking connect() can still fail before the loop starts.