Matthias Nott
2026-03-25 a7b094a1284fd1fa9c8aaf84598e5ee12ed6041d
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:bonsoir/bonsoir.dart';
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 'wol_service.dart';
/// Connection status for the MQTT client.
enum ConnectionStatus {
  disconnected,
  connecting,
  connected,
  reconnecting,
}
// 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.
///
/// Connects to the AIBroker daemon's embedded aedes broker.
/// Subscribes to all pailot/ topics and dispatches messages
/// through the onMessage callback interface.
class MqttService with WidgetsBindingObserver {
  MqttService({required this.config});
  ServerConfig config;
  MqttServerClient? _client;
  ConnectionStatus _status = ConnectionStatus.disconnected;
  bool _intentionalClose = false;
  String? _clientId;
  String? _lastDiscoveredHost;
  StreamSubscription? _updatesSub;
  // Message deduplication
  final Set<String> _seenMsgIds = {};
  final List<String> _seenMsgIdOrder = [];
  static const int _maxSeenIds = 500;
  // Callbacks
  void Function(ConnectionStatus status)? onStatusChanged;
  void Function(Map<String, dynamic> message)? onMessage;
  void Function()? onOpen;
  void Function()? onClose;
  void Function()? onReconnecting;
  void Function()? onResume;
  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();
    // Connection order: local → cached discovery → Bonjour/scan → VPN → remote
    final attempts = <MapEntry<String, int>>[];  // host → timeout ms
    if (config.localHost != null && config.localHost!.isNotEmpty) {
      attempts.add(MapEntry(config.localHost!, 2500));
    }
    // Try cached discovered host before scanning again
    if (_lastDiscoveredHost != null) {
      attempts.add(MapEntry(_lastDiscoveredHost!, 3000));
    }
    if (config.vpnHost != null && config.vpnHost!.isNotEmpty) {
      attempts.add(MapEntry(config.vpnHost!, 3000));
    }
    if (config.host.isNotEmpty) {
      attempts.add(MapEntry(config.host, 5000));
    }
    _mqttLog('MQTT: attempts=${attempts.map((e) => e.key).join(", ")} port=${config.port}');
    for (final attempt in attempts) {
      if (_intentionalClose) return;
      _mqttLog('MQTT: trying ${attempt.key}:${config.port}');
      try {
        if (await _tryConnect(attempt.key, clientId, timeout: attempt.value)) return;
      } catch (e) {
        _mqttLog('MQTT: ${attempt.key} error=$e');
      }
    }
    // All configured hosts failed — try Bonjour/subnet scan (only once, not on retry)
    if (_lastDiscoveredHost == null && !_intentionalClose) {
      _mqttLog('MQTT: trying Bonjour/subnet discovery...');
      final discovered = await _discoverViaMdns();
      if (discovered != null && !_intentionalClose) {
        _lastDiscoveredHost = discovered;
        _mqttLog('MQTT: discovered $discovered, connecting...');
        try {
          if (await _tryConnect(discovered, clientId, timeout: 3000)) return;
        } catch (e) {
          _mqttLog('MQTT: discovered host $discovered error=$e');
        }
      } else {
        _mqttLog('MQTT: discovery returned nothing');
      }
    }
    // All hosts failed — retry after delay
    _mqttLog('MQTT: all attempts failed, retrying in 5s');
    _setStatus(ConnectionStatus.reconnecting);
    Future.delayed(const Duration(seconds: 5), () {
      if (!_intentionalClose && _status != ConnectionStatus.connected) {
        connect();
      }
    });
  }
  /// Discover AIBroker on local network via Bonjour/mDNS.
  /// Falls back to subnet scan if Bonjour fails (iOS blocks mDNS on Personal Hotspot).
  /// Returns the IP address or null if not found within timeout.
  Future<String?> _discoverViaMdns({Duration timeout = const Duration(seconds: 3)}) async {
    // Try Bonjour first
    try {
      final discovery = BonsoirDiscovery(type: '_mqtt._tcp');
      await discovery.initialize();
      final completer = Completer<String?>();
      StreamSubscription? sub;
      sub = discovery.eventStream?.listen((event) {
        switch (event) {
          case BonsoirDiscoveryServiceResolvedEvent():
            final ip = event.service.host;
            _mqttLog('MQTT: Bonjour resolved: ${event.service.name} at $ip:${event.service.port}');
            if (ip != null && ip.isNotEmpty && !completer.isCompleted) {
              completer.complete(ip);
            }
          case BonsoirDiscoveryServiceFoundEvent():
            _mqttLog('MQTT: Bonjour found: ${event.service.name}');
          default:
            break;
        }
      });
      await discovery.start();
      final ip = await completer.future.timeout(timeout, onTimeout: () => null);
      await sub?.cancel();
      await discovery.stop();
      if (ip != null) return ip;
    } catch (e) {
      _mqttLog('MQTT: Bonjour discovery error: $e');
    }
    // Fallback: scan local subnet for MQTT port (handles Personal Hotspot)
    _mqttLog('MQTT: Bonjour failed, trying subnet scan...');
    return _scanSubnetForMqtt();
  }
  /// Scan the local subnet for an MQTT broker by probing the configured port.
  /// Useful when iOS Personal Hotspot blocks mDNS.
  Future<String?> _scanSubnetForMqtt() async {
    try {
      // Get device's own IP to determine the subnet
      final interfaces = await NetworkInterface.list(type: InternetAddressType.IPv4);
      for (final iface in interfaces) {
        for (final addr in iface.addresses) {
          final parts = addr.address.split('.');
          if (parts.length != 4) continue;
          // Skip loopback
          if (parts[0] == '127') continue;
          // Only scan small subnets (hotspot = /28, max 14 hosts)
          final subnet = '${parts[0]}.${parts[1]}.${parts[2]}';
          _mqttLog('MQTT: scanning $subnet.0/24 on ${iface.name}');
          // Probe all hosts in parallel — 1s timeout each, runs concurrently
          final futures = <Future<String?>>[];
          for (int i = 1; i <= 254; i++) {
            final probe = '$subnet.$i';
            if (probe == addr.address) continue; // skip self
            futures.add(_probeHost(probe, config.port));
          }
          final results = await Future.wait(futures);
          final found = results.firstWhere((r) => r != null, orElse: () => null);
          if (found != null) {
            _mqttLog('MQTT: subnet scan found broker at $found');
            return found;
          }
        }
      }
    } catch (e) {
      _mqttLog('MQTT: subnet scan error: $e');
    }
    return null;
  }
  /// Probe a single host:port with a TCP connection attempt (1s timeout).
  Future<String?> _probeHost(String host, int port) async {
    try {
      final socket = await Socket.connect(host, port,
          timeout: const Duration(seconds: 1));
      await socket.close();
      return host;
    } catch (_) {
      return null;
    }
  }
  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 = false; // Don't auto-reconnect during trial — enable after success
      client.connectTimeoutPeriod = timeout;
      // client.maxConnectionAttempts is final — can't set it
      client.logging(on: false);
      client.onConnected = _onConnected;
      client.onDisconnected = _onDisconnected;
      client.onAutoReconnect = _onAutoReconnect;
      client.onAutoReconnected = _onAutoReconnected;
      // Clean session: we handle offline delivery ourselves via catch_up protocol.
      // Persistent sessions cause the broker to flood all queued QoS 1 messages
      // on reconnect, which overwhelms the client with large voice payloads.
      final connMessage = MqttConnectMessage()
          .withClientIdentifier(clientId)
          .startClean()
          .authenticateAs('pailot', config.mqttToken ?? '');
      client.connectionMessage = connMessage;
      // Set _client BEFORE connect() so _onConnected can subscribe
      _client = client;
      _mqttLog('MQTT: connecting to $host:${config.port} as $clientId (timeout=${timeout}ms)');
      final result = await client.connect().timeout(
        Duration(milliseconds: timeout + 1000),
        onTimeout: () {
          _mqttLog('MQTT: connect timed out for $host');
          return null;
        },
      );
      _mqttLog('MQTT: connect result=${result?.state}');
      if (result?.state == MqttConnectionState.connected) {
        client.autoReconnect = true; // Now enable auto-reconnect for the live connection
        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.
  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.
  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'] ?? '',
        'messageId': message['messageId'] ?? '',
        'ts': _now(),
      }, MqttQos.atLeastOnce);
      return;
    }
    if (type == 'image' && sessionId != null) {
      _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 == 'bundle' && sessionId != null) {
      // Atomic multi-attachment message
      _publish('pailot/$sessionId/in', {
        'msgId': _uuid(),
        'type': 'bundle',
        'sessionId': sessionId,
        'caption': message['caption'] ?? '',
        if (message['audioBase64'] != null) 'audioBase64': message['audioBase64'],
        if (message['voiceMessageId'] != null) 'voiceMessageId': message['voiceMessageId'],
        'attachments': message['attachments'] ?? [],
        'ts': _now(),
      }, MqttQos.atLeastOnce);
      return;
    }
    if (type == 'file' && sessionId != null) {
      _publish('pailot/$sessionId/in', {
        'msgId': _uuid(),
        'type': 'file',
        'sessionId': sessionId,
        'fileBase64': message['fileBase64'] ?? '',
        'fileName': message['fileName'] ?? 'file',
        'mimeType': message['mimeType'] ?? 'application/octet-stream',
        'fileSize': message['fileSize'] ?? 0,
        '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 (_intentionalClose) break;
        _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;
          _setStatus(ConnectionStatus.reconnecting);
          connect();
        } else {
          // Appears connected — notify listener to fetch missed messages
          // via catch_up. Don't call onOpen (it resets sessionReady and causes flicker).
          _mqttLog('MQTT: appears connected on resume, triggering catch_up');
          onResume?.call();
        }
      case AppLifecycleState.paused:
        break;
      default:
        break;
    }
  }
}