diff --git a/gateway/gateway.py b/gateway/gateway.py index ec34879..103250a 100644 --- a/gateway/gateway.py +++ b/gateway/gateway.py @@ -79,11 +79,21 @@ class Gateway: else: log.error(f"Failed to connect to MQTT broker — reason code: {reason_code}") + # Callback triggered on disconnection — exit so systemd restarts the gateway. + # This handles cases where the broker becomes unreachable after the initial + # connection (e.g. network instability). Systemd will restart the gateway + # after RestartSec=10 seconds, retrying the connection automatically. + def on_disconnect(client, userdata, flags, reason_code, properties): + log.error(f"Disconnected from MQTT broker — reason code: {reason_code}") + log.error("Exiting — systemd will restart the gateway") + raise SystemExit(1) + # Callback to confirm message delivery to broker def on_publish(client, userdata, mid, reason_code, properties): log.info(f"Message confirmed by broker — mid: {mid}") self.mqttc.on_connect = on_connect + self.mqttc.on_disconnect = on_disconnect self.mqttc.on_publish = on_publish self.mqttc.connect(self.mqtt_broker, self.mqtt_port)