Matthias Nott
2026-03-22 cb80205ffa208782eec8957a3152288e80f398d9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/widgets.dart';
import 'package:path_provider/path_provider.dart' as pp;
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
import '../models/server_config.dart';
import 'websocket_service.dart' show ConnectionStatus;
import 'wol_service.dart';
// Debug log to file (survives release builds)
Future<void> _mqttLog(String msg) async {
  try {
    final dir = await pp.getApplicationDocumentsDirectory();
    final file = File('${dir.path}/mqtt_debug.log');
    final ts = DateTime.now().toIso8601String().substring(11, 19);
    await file.writeAsString('[$ts] $msg\n', mode: FileMode.append);
  } catch (_) {}
}
/// MQTT client for PAILot, replacing WebSocketService.
///
/// Connects to the AIBroker daemon's embedded aedes broker.
/// Subscribes to all pailot/ topics and dispatches messages
/// through the same callback interface as WebSocketService.
class MqttService with WidgetsBindingObserver {
  MqttService({required this.config});
  ServerConfig config;
  MqttServerClient? _client;
  ConnectionStatus _status = ConnectionStatus.disconnected;
  bool _intentionalClose = false;
  String? _clientId;
  StreamSubscription? _updatesSub;
  // Message deduplication
  final Set<String> _seenMsgIds = {};
  final List<String> _seenMsgIdOrder = [];
  static const int _maxSeenIds = 500;
  // Callbacks — same interface as WebSocketService
  void Function(ConnectionStatus status)? onStatusChanged;
  void Function(Map<String, dynamic> message)? onMessage;
  void Function()? onOpen;
  void Function()? onClose;
  void Function()? onReconnecting;
  void Function(String error)? onError;
  ConnectionStatus get status => _status;
  bool get isConnected => _status == ConnectionStatus.connected;
  void _setStatus(ConnectionStatus newStatus) {
    if (_status == newStatus) return;
    _status = newStatus;
    onStatusChanged?.call(newStatus);
  }
  /// Get or create a persistent client ID for this device.
  Future<String> _getClientId() async {
    if (_clientId != null) return _clientId!;
    final prefs = await SharedPreferences.getInstance();
    var id = prefs.getString('mqtt_client_id');
    // Regenerate if old format (too long for MQTT 3.1.1)
    if (id == null || id.length > 23) {
      // MQTT 3.1.1 client IDs: max 23 chars, alphanumeric
      id = 'pailot${const Uuid().v4().replaceAll('-', '').substring(0, 16)}';
      await prefs.setString('mqtt_client_id', id);
    }
    _clientId = id;
    return id;
  }
  /// Connect to the MQTT broker.
  /// Tries local host first (2.5s timeout), then remote host.
  Future<void> connect() async {
    if (_status == ConnectionStatus.connected ||
        _status == ConnectionStatus.connecting) {
      return;
    }
    _intentionalClose = false;
    _setStatus(ConnectionStatus.connecting);
    // Send Wake-on-LAN if MAC configured
    if (config.macAddress != null && config.macAddress!.isNotEmpty) {
      try {
        await WolService.wake(config.macAddress!, localHost: config.localHost);
      } catch (_) {}
    }
    final clientId = await _getClientId();
    final hosts = _getHosts();
    for (final host in hosts) {
      if (_intentionalClose) return;
      _mqttLog('MQTT: trying $host:${config.port}');
      try {
        final connected = await _tryConnect(
          host,
          clientId,
          timeout: host == hosts.first && hosts.length > 1 ? 2500 : 5000,
        );
        _mqttLog('MQTT: $host result=$connected');
        if (connected) return;
      } catch (e) {
        _mqttLog('MQTT: $host error=$e');
        continue;
      }
    }
    // All hosts failed
    debugPrint('MQTT: all hosts failed');
    _setStatus(ConnectionStatus.disconnected);
    onError?.call('Failed to connect to MQTT broker');
  }
  /// Returns [localHost, remoteHost] for dual-connect attempts.
  List<String> _getHosts() {
    if (config.localHost != null &&
        config.localHost!.isNotEmpty &&
        config.localHost != config.host) {
      return [config.localHost!, config.host];
    }
    return [config.host];
  }
  Future<bool> _tryConnect(String host, String clientId, {int timeout = 5000}) async {
    try {
      final client = MqttServerClient.withPort(host, clientId, config.port);
      client.keepAlivePeriod = 30;
      client.autoReconnect = true;
      client.connectTimeoutPeriod = timeout;
      client.logging(on: true);
      client.onConnected = _onConnected;
      client.onDisconnected = _onDisconnected;
      client.onAutoReconnect = _onAutoReconnect;
      client.onAutoReconnected = _onAutoReconnected;
      // Persistent session (cleanSession = false) for offline message queuing
      final connMessage = MqttConnectMessage()
          .withClientIdentifier(clientId)
          .authenticateAs('pailot', config.mqttToken ?? '')
          .startClean(); // Use clean session for now; persistent sessions require broker support
      // For persistent sessions, replace startClean() with:
      // .withWillQos(MqttQos.atLeastOnce);
      // and remove startClean()
      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) {
        return true;
      }
      _client = null;
      client.disconnect();
      return false;
    } catch (e) {
      _mqttLog('MQTT: connect exception=$e');
      return false;
    }
  }
  void _onConnected() {
    _mqttLog('MQTT: _onConnected fired');
    _setStatus(ConnectionStatus.connected);
    _subscribe();
    _listenMessages();
    onOpen?.call();
  }
  void _onDisconnected() {
    _updatesSub?.cancel();
    _updatesSub = null;
    if (_intentionalClose) {
      _setStatus(ConnectionStatus.disconnected);
      onClose?.call();
    } else {
      _setStatus(ConnectionStatus.reconnecting);
      onReconnecting?.call();
    }
  }
  void _onAutoReconnect() {
    _setStatus(ConnectionStatus.reconnecting);
    onReconnecting?.call();
  }
  void _onAutoReconnected() {
    _setStatus(ConnectionStatus.connected);
    _subscribe();
    _listenMessages();
    onOpen?.call();
  }
  void _subscribe() {
    final client = _client;
    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);
    client.subscribe('pailot/+/out', MqttQos.atLeastOnce);
    client.subscribe('pailot/+/typing', MqttQos.atMostOnce);
    client.subscribe('pailot/+/screenshot', MqttQos.atLeastOnce);
    client.subscribe('pailot/control/out', MqttQos.atLeastOnce);
    client.subscribe('pailot/voice/transcript', MqttQos.atLeastOnce);
  }
  void _listenMessages() {
    _updatesSub?.cancel();
    _updatesSub = _client?.updates?.listen(_onMqttMessage);
  }
  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,
      );
      Map<String, dynamic> json;
      try {
        json = jsonDecode(payload) as Map<String, dynamic>;
      } catch (_) {
        continue; // Skip non-JSON
      }
      // Dedup by msgId
      final msgId = json['msgId'] as String?;
      if (msgId != null) {
        if (_seenMsgIds.contains(msgId)) continue;
        _seenMsgIds.add(msgId);
        _seenMsgIdOrder.add(msgId);
        _evictOldIds();
      }
      // Dispatch: parse topic to enrich the message with routing info
      _dispatchMessage(msg.topic, json);
    }
  }
  /// Route incoming MQTT messages to the onMessage callback.
  /// Translates MQTT topic structure into the flat message format
  /// that chat_screen expects (same as WebSocket messages).
  void _dispatchMessage(String topic, Map<String, dynamic> json) {
    final parts = topic.split('/');
    // pailot/sessions
    if (topic == 'pailot/sessions') {
      json['type'] = 'sessions';
      onMessage?.call(json);
      return;
    }
    // pailot/status
    if (topic == 'pailot/status') {
      json['type'] = 'status';
      onMessage?.call(json);
      return;
    }
    // pailot/projects
    if (topic == 'pailot/projects') {
      json['type'] = 'projects';
      onMessage?.call(json);
      return;
    }
    // pailot/control/out — command responses (session_switched, session_renamed, error, unread)
    if (topic == 'pailot/control/out') {
      onMessage?.call(json);
      return;
    }
    // pailot/voice/transcript
    if (topic == 'pailot/voice/transcript') {
      json['type'] = 'transcript';
      onMessage?.call(json);
      return;
    }
    // pailot/<sessionId>/out — text, voice, image messages
    if (parts.length == 3 && parts[2] == 'out') {
      final sessionId = parts[1];
      json['sessionId'] ??= sessionId;
      onMessage?.call(json);
      return;
    }
    // pailot/<sessionId>/typing
    if (parts.length == 3 && parts[2] == 'typing') {
      final sessionId = parts[1];
      json['type'] = 'typing';
      json['sessionId'] ??= sessionId;
      // Map 'active' field to the 'typing'/'isTyping' fields chat_screen expects
      final active = json['active'] as bool? ?? true;
      json['typing'] = active;
      onMessage?.call(json);
      return;
    }
    // pailot/<sessionId>/screenshot
    if (parts.length == 3 && parts[2] == 'screenshot') {
      final sessionId = parts[1];
      json['type'] = 'screenshot';
      json['sessionId'] ??= sessionId;
      // Map imageBase64 to 'data' for compatibility with chat_screen handler
      json['data'] ??= json['imageBase64'];
      onMessage?.call(json);
      return;
    }
  }
  void _evictOldIds() {
    while (_seenMsgIdOrder.length > _maxSeenIds) {
      final oldest = _seenMsgIdOrder.removeAt(0);
      _seenMsgIds.remove(oldest);
    }
  }
  /// Generate a UUID v4 for message IDs.
  String _uuid() => const Uuid().v4();
  /// Current timestamp in milliseconds.
  int _now() => DateTime.now().millisecondsSinceEpoch;
  /// Publish a JSON payload to an MQTT topic.
  void _publish(String topic, Map<String, dynamic> payload, MqttQos qos) {
    final client = _client;
    if (client == null || client.connectionStatus?.state != MqttConnectionState.connected) {
      onError?.call('Not connected');
      return;
    }
    try {
      final builder = MqttClientPayloadBuilder();
      builder.addString(jsonEncode(payload));
      client.publishMessage(topic, qos, builder.payload!);
    } catch (e) {
      onError?.call('Send failed: $e');
    }
  }
  /// Send a message — routes to the appropriate MQTT topic based on content.
  /// Accepts the same message format as WebSocketService.send().
  void send(Map<String, dynamic> message) {
    final type = message['type'] as String?;
    final sessionId = message['sessionId'] as String?;
    if (type == 'command' || (message.containsKey('command') && type == null)) {
      // Command messages go to pailot/control/in
      final command = message['command'] as String? ?? '';
      final args = message['args'] as Map<String, dynamic>? ?? {};
      final payload = <String, dynamic>{
        'msgId': _uuid(),
        'type': 'command',
        'command': command,
        'ts': _now(),
        ...args,
      };
      _publish('pailot/control/in', payload, MqttQos.atLeastOnce);
      return;
    }
    if (type == 'voice' && sessionId != null) {
      // Voice message
      _publish('pailot/$sessionId/in', {
        'msgId': _uuid(),
        'type': 'voice',
        'sessionId': sessionId,
        'audioBase64': message['audioBase64'] ?? '',
        'ts': _now(),
      }, MqttQos.atLeastOnce);
      return;
    }
    if (type == 'image' && sessionId != null) {
      // Image message
      _publish('pailot/$sessionId/in', {
        'msgId': _uuid(),
        'type': 'image',
        'sessionId': sessionId,
        'imageBase64': message['imageBase64'] ?? '',
        'mimeType': message['mimeType'] ?? 'image/jpeg',
        'caption': message['caption'] ?? '',
        'ts': _now(),
      }, MqttQos.atLeastOnce);
      return;
    }
    if (type == 'tts' && sessionId != null) {
      // TTS request — route as command
      _publish('pailot/control/in', {
        'msgId': _uuid(),
        'type': 'command',
        'command': 'tts',
        'text': message['text'] ?? '',
        'sessionId': sessionId,
        'ts': _now(),
      }, MqttQos.atLeastOnce);
      return;
    }
    // Default: plain text message (content + sessionId)
    if (sessionId != null) {
      final content = message['content'] as String? ?? '';
      _publish('pailot/$sessionId/in', {
        'msgId': _uuid(),
        'type': 'text',
        'sessionId': sessionId,
        'content': content,
        'ts': _now(),
      }, MqttQos.atLeastOnce);
      return;
    }
    onError?.call('Cannot send message: missing sessionId');
  }
  /// Disconnect intentionally.
  void disconnect() {
    _intentionalClose = true;
    _updatesSub?.cancel();
    _updatesSub = null;
    try {
      _client?.disconnect();
    } catch (_) {}
    _client = null;
    _setStatus(ConnectionStatus.disconnected);
    onClose?.call();
  }
  /// Update config and reconnect.
  Future<void> updateConfig(ServerConfig newConfig) async {
    config = newConfig;
    disconnect();
    await Future.delayed(const Duration(milliseconds: 100));
    await connect();
  }
  /// Dispose all resources.
  void dispose() {
    disconnect();
  }
  // App lifecycle integration
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        if (_status != ConnectionStatus.connected && !_intentionalClose) {
          connect();
        }
      case AppLifecycleState.paused:
        // Keep connection alive — MQTT handles keepalive natively
        break;
      default:
        break;
    }
  }
}