From 45898e1e305b2278d688cb771deae89e78c8f909 Mon Sep 17 00:00:00 2001
From: Matthias Nott <mnott@mnsoft.org>
Date: Tue, 24 Mar 2026 03:03:11 +0100
Subject: [PATCH] fix: gentle resume - refresh sessions instead of force-disconnect

---
 lib/services/mqtt_service.dart |   29 ++++++++++++++---------------
 1 files changed, 14 insertions(+), 15 deletions(-)

diff --git a/lib/services/mqtt_service.dart b/lib/services/mqtt_service.dart
index 34e638c..41df849 100644
--- a/lib/services/mqtt_service.dart
+++ b/lib/services/mqtt_service.dart
@@ -515,23 +515,22 @@
     switch (state) {
       case AppLifecycleState.resumed:
         if (_intentionalClose) break;
-        _mqttLog('MQTT: app resumed, status=$_status');
-        // iOS kills TCP sockets during suspend. Always force a clean
-        // reconnect to avoid the "looks connected but dead" state.
-        final resumeClient = _client;
-        if (resumeClient != null) {
-          _intentionalClose = true; // Prevent _onDisconnected from cascading
-          resumeClient.autoReconnect = false;
-          resumeClient.disconnect();
+        _mqttLog('MQTT: app resumed, status=$_status client=${_client != null} mqttState=${_client?.connectionStatus?.state}');
+        final client = _client;
+        if (client == null || client.connectionStatus?.state != MqttConnectionState.connected) {
+          // Clearly disconnected — just reconnect
+          _mqttLog('MQTT: not connected on resume, reconnecting...');
           _client = null;
-          _updatesSub?.cancel();
-          _updatesSub = null;
-          _intentionalClose = false;
+          _setStatus(ConnectionStatus.reconnecting);
+          connect();
+        } else {
+          // Thinks it's connected — send a sync command to verify.
+          // If the connection is dead, the MQTT library will detect it
+          // via the next keepalive cycle and auto-reconnect will fire.
+          // Also re-request sessions to refresh the drawer.
+          _mqttLog('MQTT: appears connected, refreshing sessions...');
+          onOpen?.call();
         }
-        _setStatus(ConnectionStatus.reconnecting);
-        Future.delayed(const Duration(milliseconds: 300), () {
-          if (!_intentionalClose) connect();
-        });
       case AppLifecycleState.paused:
         break;
       default:

--
Gitblit v1.3.1