| .. | .. |
|---|
| 155 | 155 | |
|---|
| 156 | 156 | client.connectionMessage = connMessage; |
|---|
| 157 | 157 | |
|---|
| 158 | + // Set _client BEFORE connect() so _onConnected can subscribe |
|---|
| 159 | + _client = client; |
|---|
| 160 | + |
|---|
| 158 | 161 | _mqttLog('MQTT: connecting to $host:${config.port} as $clientId'); |
|---|
| 159 | 162 | final result = await client.connect(); |
|---|
| 160 | 163 | _mqttLog('MQTT: connect result=${result?.state}'); |
|---|
| 161 | 164 | if (result?.state == MqttConnectionState.connected) { |
|---|
| 162 | | - _client = client; |
|---|
| 163 | 165 | return true; |
|---|
| 164 | 166 | } |
|---|
| 167 | + _client = null; |
|---|
| 165 | 168 | client.disconnect(); |
|---|
| 166 | 169 | return false; |
|---|
| 167 | 170 | } catch (e) { |
|---|
| .. | .. |
|---|
| 171 | 174 | } |
|---|
| 172 | 175 | |
|---|
| 173 | 176 | void _onConnected() { |
|---|
| 177 | + _mqttLog('MQTT: _onConnected fired'); |
|---|
| 174 | 178 | _setStatus(ConnectionStatus.connected); |
|---|
| 175 | 179 | _subscribe(); |
|---|
| 176 | 180 | _listenMessages(); |
|---|
| .. | .. |
|---|
| 204 | 208 | |
|---|
| 205 | 209 | void _subscribe() { |
|---|
| 206 | 210 | 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...'); |
|---|
| 209 | 216 | client.subscribe('pailot/sessions', MqttQos.atLeastOnce); |
|---|
| 210 | 217 | client.subscribe('pailot/status', MqttQos.atLeastOnce); |
|---|
| 211 | 218 | client.subscribe('pailot/projects', MqttQos.atLeastOnce); |
|---|
| .. | .. |
|---|
| 222 | 229 | } |
|---|
| 223 | 230 | |
|---|
| 224 | 231 | void _onMqttMessage(List<MqttReceivedMessage<MqttMessage>> messages) { |
|---|
| 232 | + _mqttLog('MQTT: received ${messages.length} message(s)'); |
|---|
| 225 | 233 | for (final msg in messages) { |
|---|
| 234 | + _mqttLog('MQTT: topic=${msg.topic}'); |
|---|
| 226 | 235 | final pubMsg = msg.payload as MqttPublishMessage; |
|---|
| 227 | 236 | final payload = MqttPublishPayload.bytesToStringAsString( |
|---|
| 228 | 237 | pubMsg.payload.message, |
|---|