From cb80205ffa208782eec8957a3152288e80f398d9 Mon Sep 17 00:00:00 2001
From: Matthias Nott <mnott@mnsoft.org>
Date: Sun, 22 Mar 2026 19:04:54 +0100
Subject: [PATCH] fix: set MQTT client before connect, debug logging for message flow

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

diff --git a/lib/services/mqtt_service.dart b/lib/services/mqtt_service.dart
index 9f5526e..8538a68 100644
--- a/lib/services/mqtt_service.dart
+++ b/lib/services/mqtt_service.dart
@@ -155,13 +155,16 @@
 
       client.connectionMessage = connMessage;
 
+      // Set _client BEFORE connect() so _onConnected can subscribe
+      _client = client;
+
       _mqttLog('MQTT: connecting to $host:${config.port} as $clientId');
       final result = await client.connect();
       _mqttLog('MQTT: connect result=${result?.state}');
       if (result?.state == MqttConnectionState.connected) {
-        _client = client;
         return true;
       }
+      _client = null;
       client.disconnect();
       return false;
     } catch (e) {
@@ -171,6 +174,7 @@
   }
 
   void _onConnected() {
+    _mqttLog('MQTT: _onConnected fired');
     _setStatus(ConnectionStatus.connected);
     _subscribe();
     _listenMessages();
@@ -204,8 +208,11 @@
 
   void _subscribe() {
     final client = _client;
-    if (client == null) return;
-
+    if (client == null) {
+      _mqttLog('MQTT: _subscribe called but client is null');
+      return;
+    }
+    _mqttLog('MQTT: subscribing to topics...');
     client.subscribe('pailot/sessions', MqttQos.atLeastOnce);
     client.subscribe('pailot/status', MqttQos.atLeastOnce);
     client.subscribe('pailot/projects', MqttQos.atLeastOnce);
@@ -222,7 +229,9 @@
   }
 
   void _onMqttMessage(List<MqttReceivedMessage<MqttMessage>> messages) {
+    _mqttLog('MQTT: received ${messages.length} message(s)');
     for (final msg in messages) {
+      _mqttLog('MQTT: topic=${msg.topic}');
       final pubMsg = msg.payload as MqttPublishMessage;
       final payload = MqttPublishPayload.bytesToStringAsString(
         pubMsg.payload.message,

--
Gitblit v1.3.1