From 8b82df83d3773bcc8fafc5e925ef2ca05e5c9472 Mon Sep 17 00:00:00 2001
From: Matthias Nott <mnott@mnsoft.org>
Date: Mon, 06 Apr 2026 16:06:45 +0200
Subject: [PATCH] fix: re-enable autoReconnect, simple resume handler, stable connection lifecycle

---
 lib/services/mqtt_service.dart |   26 +++++---------------------
 1 files changed, 5 insertions(+), 21 deletions(-)

diff --git a/lib/services/mqtt_service.dart b/lib/services/mqtt_service.dart
index 4ec3ae9..018fa55 100644
--- a/lib/services/mqtt_service.dart
+++ b/lib/services/mqtt_service.dart
@@ -440,9 +440,7 @@
       );
       _mqttLog('MQTT: connect result=${result?.state}');
       if (result?.state == MqttConnectionState.connected) {
-        // Don't enable autoReconnect — we handle reconnection ourselves
-        // in didChangeAppLifecycleState(resumed). The library's autoReconnect
-        // competes with our force-reconnect and causes connection flickering.
+        client.autoReconnect = true;
         return true;
       }
       _client = null;
@@ -800,24 +798,10 @@
     switch (state) {
       case AppLifecycleState.resumed:
         if (_intentionalClose) break;
-        _mqttLog('MQTT: app resumed — reconnecting to last host');
-        // Kill old client completely (disable autoReconnect first to prevent
-        // the MQTT library from spawning its own reconnect attempt)
-        final oldClient = _client;
-        if (oldClient != null) {
-          oldClient.autoReconnect = false;
-          try { oldClient.disconnect(); } catch (_) {}
-        }
-        _updatesSub?.cancel();
-        _updatesSub = null;
-        _client = null;
-        _setStatus(ConnectionStatus.reconnecting);
-        onReconnecting?.call();
-        if (connectedHost != null) {
-          _fastReconnect(connectedHost!);
-        } else {
-          connect();
-        }
+        _mqttLog('MQTT: app resumed');
+        // Let autoReconnect handle dead connections (keepalive timeout).
+        // Just trigger catch_up to fetch missed messages and rebuild UI.
+        onResume?.call();
       case AppLifecycleState.paused:
         break;
       default:

--
Gitblit v1.3.1