Matthias Nott
2026-03-22 cb80205ffa208782eec8957a3152288e80f398d9
fix: set MQTT client before connect, debug logging for message flow
1 files modified
changed files
lib/services/mqtt_service.dart patch | view | blame | history
lib/services/mqtt_service.dart
....@@ -155,13 +155,16 @@
155155
156156 client.connectionMessage = connMessage;
157157
158
+ // Set _client BEFORE connect() so _onConnected can subscribe
159
+ _client = client;
160
+
158161 _mqttLog('MQTT: connecting to $host:${config.port} as $clientId');
159162 final result = await client.connect();
160163 _mqttLog('MQTT: connect result=${result?.state}');
161164 if (result?.state == MqttConnectionState.connected) {
162
- _client = client;
163165 return true;
164166 }
167
+ _client = null;
165168 client.disconnect();
166169 return false;
167170 } catch (e) {
....@@ -171,6 +174,7 @@
171174 }
172175
173176 void _onConnected() {
177
+ _mqttLog('MQTT: _onConnected fired');
174178 _setStatus(ConnectionStatus.connected);
175179 _subscribe();
176180 _listenMessages();
....@@ -204,8 +208,11 @@
204208
205209 void _subscribe() {
206210 final client = _client;
207
- if (client == null) return;
208
-
211
+ if (client == null) {
212
+ _mqttLog('MQTT: _subscribe called but client is null');
213
+ return;
214
+ }
215
+ _mqttLog('MQTT: subscribing to topics...');
209216 client.subscribe('pailot/sessions', MqttQos.atLeastOnce);
210217 client.subscribe('pailot/status', MqttQos.atLeastOnce);
211218 client.subscribe('pailot/projects', MqttQos.atLeastOnce);
....@@ -222,7 +229,9 @@
222229 }
223230
224231 void _onMqttMessage(List<MqttReceivedMessage<MqttMessage>> messages) {
232
+ _mqttLog('MQTT: received ${messages.length} message(s)');
225233 for (final msg in messages) {
234
+ _mqttLog('MQTT: topic=${msg.topic}');
226235 final pubMsg = msg.payload as MqttPublishMessage;
227236 final payload = MqttPublishPayload.bytesToStringAsString(
228237 pubMsg.payload.message,