-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathmeshcore_connector.dart
More file actions
3352 lines (2949 loc) · 105 KB
/
meshcore_connector.dart
File metadata and controls
3352 lines (2949 loc) · 105 KB
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:convert';
import 'package:crypto/crypto.dart' as crypto;
import 'package:pointycastle/export.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:wakelock_plus/wakelock_plus.dart';
import '../models/channel.dart';
import '../models/channel_message.dart';
import '../models/contact.dart';
import '../models/message.dart';
import '../models/path_selection.dart';
import '../helpers/reaction_helper.dart';
import '../helpers/smaz.dart';
import '../services/app_debug_log_service.dart';
import '../utils/battery_utils.dart';
import '../services/ble_debug_log_service.dart';
import '../services/message_retry_service.dart';
import '../services/path_history_service.dart';
import '../services/app_settings_service.dart';
import '../services/background_service.dart';
import '../services/notification_service.dart';
import '../storage/channel_message_store.dart';
import '../storage/channel_order_store.dart';
import '../storage/channel_settings_store.dart';
import '../storage/channel_store.dart';
import '../storage/contact_settings_store.dart';
import '../storage/contact_store.dart';
import '../storage/message_store.dart';
import '../storage/unread_store.dart';
import '../utils/app_logger.dart';
import 'meshcore_protocol.dart';
class MeshCoreUuids {
static const String service = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
static const String rxCharacteristic = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";
static const String txCharacteristic = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
}
enum MeshCoreConnectionState {
disconnected,
scanning,
connecting,
connected,
disconnecting,
}
class MeshCoreConnector extends ChangeNotifier {
// Message windowing to limit memory usage
static const int _messageWindowSize = 200;
MeshCoreConnectionState _state = MeshCoreConnectionState.disconnected;
BluetoothDevice? _device;
BluetoothCharacteristic? _rxCharacteristic;
BluetoothCharacteristic? _txCharacteristic;
String? _deviceDisplayName;
String? _deviceId;
BluetoothDevice? _lastDevice;
String? _lastDeviceId;
String? _lastDeviceDisplayName;
bool _manualDisconnect = false;
final List<ScanResult> _scanResults = [];
final List<Contact> _contacts = [];
final List<Channel> _channels = [];
final Map<String, List<Message>> _conversations = {};
final Map<int, List<ChannelMessage>> _channelMessages = {};
final Set<String> _loadedConversationKeys = {};
final Map<int, Set<String>> _processedChannelReactions =
{}; // channelIndex -> Set of "targetHash_emoji"
final Map<String, Set<String>> _processedContactReactions =
{}; // contactPubKeyHex -> Set of "targetHash_emoji"
StreamSubscription<List<ScanResult>>? _scanSubscription;
StreamSubscription<BluetoothConnectionState>? _connectionSubscription;
StreamSubscription<List<int>>? _notifySubscription;
Timer? _selfInfoRetryTimer;
Timer? _reconnectTimer;
Timer? _batteryPollTimer;
int _reconnectAttempts = 0;
final StreamController<Uint8List> _receivedFramesController =
StreamController<Uint8List>.broadcast();
Uint8List? _selfPublicKey;
String? _selfName;
int? _currentTxPower;
int? _maxTxPower;
int? _currentFreqHz;
int? _currentBwHz;
int? _currentSf;
int? _currentCr;
int? _batteryMillivolts;
String? _reportedBatteryChemistry; // From firmware, if available
double? _selfLatitude;
double? _selfLongitude;
bool _isLoadingContacts = false;
bool _isLoadingChannels = false;
bool _hasLoadedChannels = false;
bool _batteryRequested = false;
bool _awaitingSelfInfo = false;
bool _preserveContactsOnRefresh = false;
static const int _defaultMaxContacts = 32;
static const int _defaultMaxChannels = 8;
int _maxContacts = _defaultMaxContacts;
int _maxChannels = _defaultMaxChannels;
bool _isSyncingQueuedMessages = false;
bool _queuedMessageSyncInFlight = false;
bool _didInitialQueueSync = false;
bool _pendingQueueSync = false;
Timer? _queueSyncTimeout;
int _queueSyncRetries = 0;
static const int _maxQueueSyncRetries = 3;
static const int _queueSyncTimeoutMs = 5000; // 5 second timeout
Map<String, String>? _currentCustomVars;
// Channel syncing state (sequential pattern)
bool _isSyncingChannels = false;
bool _channelSyncInFlight = false;
Timer? _channelSyncTimeout;
int _channelSyncRetries = 0;
int _nextChannelIndexToRequest = 0;
int _totalChannelsToRequest = 0;
List<Channel> _previousChannelsCache = [];
static const int _maxChannelSyncRetries = 3;
static const int _channelSyncTimeoutMs = 2000; // 2 second timeout per channel
static const Duration _batteryPollInterval = Duration(seconds: 120);
// Services
MessageRetryService? _retryService;
PathHistoryService? _pathHistoryService;
AppSettingsService? _appSettingsService;
BackgroundService? _backgroundService;
final NotificationService _notificationService = NotificationService();
BleDebugLogService? _bleDebugLogService;
AppDebugLogService? _appDebugLogService;
final ChannelMessageStore _channelMessageStore = ChannelMessageStore();
final MessageStore _messageStore = MessageStore();
final ChannelOrderStore _channelOrderStore = ChannelOrderStore();
final ChannelSettingsStore _channelSettingsStore = ChannelSettingsStore();
final ContactSettingsStore _contactSettingsStore = ContactSettingsStore();
final ContactStore _contactStore = ContactStore();
final ChannelStore _channelStore = ChannelStore();
final UnreadStore _unreadStore = UnreadStore();
List<Channel> _cachedChannels = [];
final Map<int, bool> _channelSmazEnabled = {};
bool _lastSentWasCliCommand =
false; // Track if last sent message was a CLI command
final Map<String, bool> _contactSmazEnabled = {};
final Set<String> _knownContactKeys = {};
final Map<String, int> _contactUnreadCount = {};
bool _unreadStateLoaded = false;
final Map<String, _RepeaterAckContext> _pendingRepeaterAcks = {};
String? _activeContactKey;
int? _activeChannelIndex;
List<int> _channelOrder = [];
// Getters
MeshCoreConnectionState get state => _state;
BluetoothDevice? get device => _device;
String? get deviceId => _deviceId;
String get deviceIdLabel => _deviceId ?? 'Unknown';
String get deviceDisplayName {
if (_selfName != null && _selfName!.isNotEmpty) {
return _selfName!;
}
final platformName = _device?.platformName;
if (platformName != null && platformName.isNotEmpty) {
return platformName;
}
if (_deviceDisplayName != null && _deviceDisplayName!.isNotEmpty) {
return _deviceDisplayName!;
}
return 'Unknown Device';
}
List<ScanResult> get scanResults => List.unmodifiable(_scanResults);
List<Contact> get contacts {
final selfKey = _selfPublicKey;
if (selfKey == null) {
return List.unmodifiable(_contacts);
}
return List.unmodifiable(
_contacts.where((contact) => !listEquals(contact.publicKey, selfKey)),
);
}
List<Channel> get channels => List.unmodifiable(_channels);
bool get isConnected => _state == MeshCoreConnectionState.connected;
bool get isLoadingContacts => _isLoadingContacts;
bool get isLoadingChannels => _isLoadingChannels;
Stream<Uint8List> get receivedFrames => _receivedFramesController.stream;
Uint8List? get selfPublicKey => _selfPublicKey;
String? get selfName => _selfName;
double? get selfLatitude => _selfLatitude;
double? get selfLongitude => _selfLongitude;
int? get currentTxPower => _currentTxPower;
int? get maxTxPower => _maxTxPower;
int? get currentFreqHz => _currentFreqHz;
int? get currentBwHz => _currentBwHz;
int? get currentSf => _currentSf;
int? get currentCr => _currentCr;
Map<String, String>? get currentCustomVars => _currentCustomVars;
int? get batteryMillivolts => _batteryMillivolts;
int get maxContacts => _maxContacts;
int get maxChannels => _maxChannels;
bool get isSyncingQueuedMessages => _isSyncingQueuedMessages;
bool get isSyncingChannels => _isSyncingChannels;
int get channelSyncProgress =>
_isSyncingChannels && _totalChannelsToRequest > 0
? ((_nextChannelIndexToRequest / _totalChannelsToRequest) * 100).round()
: 0;
int? get batteryPercent => _batteryMillivolts == null
? null
: _estimateBatteryPercent(
_batteryMillivolts!,
_batteryChemistryForDevice(),
);
String _batteryChemistryForDevice() {
// Prefer firmware-reported chemistry if available
if (_reportedBatteryChemistry != null) return _reportedBatteryChemistry!;
// Fall back to user setting
final deviceId = _device?.remoteId.toString();
if (deviceId == null || _appSettingsService == null) return 'lipo';
return _appSettingsService!.batteryChemistryForDevice(deviceId);
}
// Uses shared utility from battery_utils.dart
int? _estimateBatteryPercent(int millivolts, String chemistry) {
return estimateBatteryPercent(millivolts, chemistry);
}
List<Message> getMessages(Contact contact) {
return _conversations[contact.publicKeyHex] ?? [];
}
Future<void> deleteMessage(Message message) async {
final contactKeyHex = message.senderKeyHex;
final messages = _conversations[contactKeyHex];
if (messages == null) return;
final removed = messages.remove(message);
if (!removed) return;
await _messageStore.saveMessages(contactKeyHex, messages);
notifyListeners();
}
Future<void> _loadMessagesForContact(String contactKeyHex) async {
if (_loadedConversationKeys.contains(contactKeyHex)) return;
_loadedConversationKeys.add(contactKeyHex);
final allMessages = await _messageStore.loadMessages(contactKeyHex);
if (allMessages.isNotEmpty) {
// Keep only the most recent N messages in memory to bound memory usage
final windowedMessages = allMessages.length > _messageWindowSize
? allMessages.sublist(allMessages.length - _messageWindowSize)
: allMessages;
_conversations[contactKeyHex] = windowedMessages;
notifyListeners();
}
}
/// Load older messages for a contact (pagination)
Future<List<Message>> loadOlderMessages(
String contactKeyHex, {
int count = 50,
}) async {
final allMessages = await _messageStore.loadMessages(contactKeyHex);
final currentMessages = _conversations[contactKeyHex] ?? [];
if (allMessages.length <= currentMessages.length) {
return []; // No more messages to load
}
final currentOffset = allMessages.length - currentMessages.length;
final fetchCount = count.clamp(0, currentOffset);
final startIndex = currentOffset - fetchCount;
final olderMessages = allMessages.sublist(startIndex, currentOffset);
// Prepend to current conversation
_conversations[contactKeyHex] = [...olderMessages, ...currentMessages];
notifyListeners();
return olderMessages;
}
List<ChannelMessage> getChannelMessages(Channel channel) {
return _channelMessages[channel.index] ?? [];
}
Future<void> deleteChannelMessage(ChannelMessage message) async {
final channelIndex = message.channelIndex;
if (channelIndex == null) return;
final messages = _channelMessages[channelIndex];
if (messages == null) return;
final removed = messages.remove(message);
if (!removed) return;
await _channelMessageStore.saveChannelMessages(channelIndex, messages);
notifyListeners();
}
int getUnreadCountForContact(Contact contact) {
if (contact.type == advTypeRepeater) return 0;
return getUnreadCountForContactKey(contact.publicKeyHex);
}
int getUnreadCountForContactKey(String contactKeyHex) {
if (!_unreadStateLoaded) return 0;
if (!_shouldTrackUnreadForContactKey(contactKeyHex)) return 0;
return _contactUnreadCount[contactKeyHex] ?? 0;
}
int getUnreadCountForChannel(Channel channel) {
return getUnreadCountForChannelIndex(channel.index);
}
int getUnreadCountForChannelIndex(int channelIndex) {
if (!_unreadStateLoaded) return 0;
return _findChannelByIndex(channelIndex)?.unreadCount ?? 0;
}
int getTotalUnreadCount() {
if (!_unreadStateLoaded) return 0;
var total = 0;
// Count unread contact messages
for (final contact in _contacts) {
total += getUnreadCountForContact(contact);
}
// Count unread channel messages
for (final channelIndex in _channelMessages.keys) {
total += getUnreadCountForChannelIndex(channelIndex);
}
return total;
}
bool isChannelSmazEnabled(int channelIndex) {
return _channelSmazEnabled[channelIndex] ?? false;
}
bool isContactSmazEnabled(String contactKeyHex) {
return _contactSmazEnabled[contactKeyHex] ?? false;
}
void ensureContactSmazSettingLoaded(String contactKeyHex) {
_ensureContactSmazSettingLoaded(contactKeyHex);
}
Future<void> loadUnreadState() async {
_contactUnreadCount
..clear()
..addAll(await _unreadStore.loadContactUnreadCount());
_unreadStateLoaded = true;
notifyListeners();
}
Future<void> loadCachedChannels() async {
_cachedChannels = await _channelStore.loadChannels();
}
void setActiveContact(String? contactKeyHex) {
if (contactKeyHex != null &&
!_shouldTrackUnreadForContactKey(contactKeyHex)) {
_activeContactKey = null;
return;
}
_activeContactKey = contactKeyHex;
if (contactKeyHex != null) {
markContactRead(contactKeyHex);
}
}
void setActiveChannel(int? channelIndex) {
_activeChannelIndex = channelIndex;
if (channelIndex != null) {
markChannelRead(channelIndex);
}
}
void markContactRead(String contactKeyHex) {
if (!_shouldTrackUnreadForContactKey(contactKeyHex)) return;
final previousCount = _contactUnreadCount[contactKeyHex] ?? 0;
if (previousCount > 0) {
_contactUnreadCount[contactKeyHex] = 0;
_appDebugLogService?.info(
'Contact $contactKeyHex marked as read (was $previousCount unread)',
tag: 'Unread',
);
_unreadStore.saveContactUnreadCount(
Map<String, int>.from(_contactUnreadCount),
);
notifyListeners();
}
}
void markChannelRead(int channelIndex) {
final channel = _findChannelByIndex(channelIndex);
if (channel != null && channel.unreadCount > 0) {
final previousCount = channel.unreadCount;
channel.unreadCount = 0;
_appDebugLogService?.info(
'Channel ${channel.name.isNotEmpty ? channel.name : channelIndex} marked as read (was $previousCount unread)',
tag: 'Unread',
);
unawaited(
_channelStore.saveChannels(
_channels.isNotEmpty ? _channels : _cachedChannels,
),
);
notifyListeners();
}
}
Future<void> setChannelSmazEnabled(int channelIndex, bool enabled) async {
_channelSmazEnabled[channelIndex] = enabled;
await _channelSettingsStore.saveSmazEnabled(channelIndex, enabled);
notifyListeners();
}
Future<void> setContactSmazEnabled(String contactKeyHex, bool enabled) async {
_contactSmazEnabled[contactKeyHex] = enabled;
await _contactSettingsStore.saveSmazEnabled(contactKeyHex, enabled);
notifyListeners();
}
Future<void> _loadChannelOrder() async {
_channelOrder = await _channelOrderStore.loadChannelOrder();
_applyChannelOrder();
notifyListeners();
}
/// Load persisted channel messages for a specific channel
Future<void> _loadChannelMessages(int channelIndex) async {
final allMessages = await _channelMessageStore.loadChannelMessages(
channelIndex,
);
if (allMessages.isNotEmpty) {
// Keep only the most recent N messages in memory to bound memory usage
final windowedMessages = allMessages.length > _messageWindowSize
? allMessages.sublist(allMessages.length - _messageWindowSize)
: allMessages;
_channelMessages[channelIndex] = windowedMessages;
notifyListeners();
}
}
/// Load older channel messages (pagination)
Future<List<ChannelMessage>> loadOlderChannelMessages(
int channelIndex, {
int count = 50,
}) async {
final allMessages = await _channelMessageStore.loadChannelMessages(
channelIndex,
);
final currentMessages = _channelMessages[channelIndex] ?? [];
if (allMessages.length <= currentMessages.length) {
return []; // No more messages to load
}
final currentOffset = allMessages.length - currentMessages.length;
final fetchCount = count.clamp(0, currentOffset);
final startIndex = currentOffset - fetchCount;
final olderMessages = allMessages.sublist(startIndex, currentOffset);
// Prepend to current conversation
_channelMessages[channelIndex] = [...olderMessages, ...currentMessages];
notifyListeners();
return olderMessages;
}
/// Load all persisted channel messages on startup
Future<void> loadAllChannelMessages({int? maxChannels}) async {
final channelCount = maxChannels ?? _maxChannels;
// Load messages for all known channels (0-7 by default)
for (int i = 0; i < channelCount; i++) {
await _loadChannelMessages(i);
}
}
void initialize({
required MessageRetryService retryService,
required PathHistoryService pathHistoryService,
AppSettingsService? appSettingsService,
BleDebugLogService? bleDebugLogService,
AppDebugLogService? appDebugLogService,
BackgroundService? backgroundService,
}) {
_retryService = retryService;
_pathHistoryService = pathHistoryService;
_appSettingsService = appSettingsService;
_bleDebugLogService = bleDebugLogService;
_appDebugLogService = appDebugLogService;
_backgroundService = backgroundService;
// Initialize notification service
_notificationService.initialize();
_loadChannelOrder();
// Initialize retry service callbacks
_retryService?.initialize(
sendMessageCallback: _sendMessageDirect,
addMessageCallback: _addMessage,
updateMessageCallback: _updateMessage,
clearContactPathCallback: clearContactPath,
setContactPathCallback: setContactPath,
calculateTimeoutCallback: (pathLength, messageBytes) =>
calculateTimeout(pathLength: pathLength, messageBytes: messageBytes),
getSelfPublicKeyCallback: () => _selfPublicKey,
prepareContactOutboundTextCallback: prepareContactOutboundText,
appSettingsService: appSettingsService,
debugLogService: _appDebugLogService,
recordPathResultCallback: _recordPathResult,
);
}
Future<void> loadContactCache() async {
final cached = await _contactStore.loadContacts();
_knownContactKeys
..clear()
..addAll(cached.map((c) => c.publicKeyHex));
for (final contact in cached) {
_ensureContactSmazSettingLoaded(contact.publicKeyHex);
}
}
Future<void> loadChannelSettings({int? maxChannels}) async {
_channelSmazEnabled.clear();
final channelCount = maxChannels ?? _maxChannels;
for (int i = 0; i < channelCount; i++) {
_channelSmazEnabled[i] = await _channelSettingsStore.loadSmazEnabled(i);
}
}
void _sendMessageDirect(
Contact contact,
String text,
int attempt,
int timestampSeconds,
) async {
if (!isConnected || text.isEmpty) return;
final outboundText = prepareContactOutboundText(contact, text);
await sendFrame(
buildSendTextMsgFrame(
contact.publicKey,
outboundText,
attempt: attempt,
timestampSeconds: timestampSeconds,
),
);
}
void _updateMessage(Message message) {
final contactKey = pubKeyToHex(message.senderKey);
final messages = _conversations[contactKey];
if (messages != null) {
final index = messages.indexWhere(
(m) => m.messageId == message.messageId,
);
if (index != -1) {
messages[index] = message;
_messageStore.saveMessages(contactKey, messages);
notifyListeners();
}
}
}
void _recordPathResult(
String contactPubKeyHex,
PathSelection selection,
bool success,
int? tripTimeMs,
) {
if (_pathHistoryService == null) return;
_pathHistoryService!.recordPathResult(
contactPubKeyHex,
selection,
success: success,
tripTimeMs: tripTimeMs,
);
}
Contact _applyAutoSelection(Contact contact, PathSelection? selection) {
if (selection == null ||
selection.useFlood ||
selection.pathBytes.isEmpty) {
return contact;
}
return Contact(
publicKey: contact.publicKey,
name: contact.name,
type: contact.type,
pathLength: selection.hopCount >= 0
? selection.hopCount
: contact.pathLength,
path: Uint8List.fromList(selection.pathBytes),
latitude: contact.latitude,
longitude: contact.longitude,
lastSeen: contact.lastSeen,
lastMessageAt: contact.lastMessageAt,
);
}
Future<void> startScan({
Duration timeout = const Duration(seconds: 10),
}) async {
if (_state == MeshCoreConnectionState.scanning) return;
_scanResults.clear();
_setState(MeshCoreConnectionState.scanning);
// Ensure any previous scan is fully stopped
await FlutterBluePlus.stopScan();
await _scanSubscription?.cancel();
// On iOS/macOS, wait for Bluetooth to be powered on before scanning
if (defaultTargetPlatform == TargetPlatform.iOS ||
defaultTargetPlatform == TargetPlatform.macOS) {
// Wait for adapter state to be powered on
final adapterState = await FlutterBluePlus.adapterState.first;
if (adapterState != BluetoothAdapterState.on) {
// Wait for the adapter to turn on, with timeout
await FlutterBluePlus.adapterState
.firstWhere((state) => state == BluetoothAdapterState.on)
.timeout(
const Duration(seconds: 5),
onTimeout: () {
_setState(MeshCoreConnectionState.disconnected);
throw Exception('Bluetooth adapter not available');
},
);
}
// Add a small delay to allow BLE stack to fully initialize
await Future.delayed(const Duration(milliseconds: 300));
}
_scanSubscription = FlutterBluePlus.scanResults.listen((results) {
_scanResults.clear();
for (var result in results) {
if (result.device.platformName.startsWith("MeshCore-") ||
result.advertisementData.advName.startsWith("MeshCore-")) {
_scanResults.add(result);
}
}
notifyListeners();
});
await FlutterBluePlus.startScan(
timeout: timeout,
androidScanMode: AndroidScanMode.lowLatency,
);
await Future.delayed(timeout);
await stopScan();
}
Future<void> stopScan() async {
await FlutterBluePlus.stopScan();
await _scanSubscription?.cancel();
_scanSubscription = null;
if (_state == MeshCoreConnectionState.scanning) {
_setState(MeshCoreConnectionState.disconnected);
}
}
Future<void> connect(BluetoothDevice device, {String? displayName}) async {
if (_state == MeshCoreConnectionState.connecting ||
_state == MeshCoreConnectionState.connected) {
return;
}
await stopScan();
_setState(MeshCoreConnectionState.connecting);
_device = device;
_deviceId = device.remoteId.toString();
if (displayName != null && displayName.trim().isNotEmpty) {
_deviceDisplayName = displayName.trim();
} else if (device.platformName.isNotEmpty) {
_deviceDisplayName = device.platformName;
}
_lastDevice = device;
_lastDeviceId = _deviceId;
_lastDeviceDisplayName = _deviceDisplayName;
_manualDisconnect = false;
_cancelReconnectTimer();
unawaited(_backgroundService?.start());
notifyListeners();
try {
_connectionSubscription = device.connectionState.listen((state) {
if (state == BluetoothConnectionState.disconnected && isConnected) {
_handleDisconnection();
}
});
await device.connect(
timeout: const Duration(seconds: 15),
mtu: null,
license: License.free,
);
// Request larger MTU for sending larger frames
try {
final mtu = await device.requestMtu(185);
debugPrint('MTU set to: $mtu');
} catch (e) {
debugPrint('MTU request failed: $e, using default');
}
List<BluetoothService> services = await device.discoverServices();
BluetoothService? uartService;
for (var service in services) {
if (service.uuid.toString().toLowerCase() == MeshCoreUuids.service) {
uartService = service;
break;
}
}
if (uartService == null) {
throw Exception("MeshCore UART service not found");
}
for (var characteristic in uartService.characteristics) {
String uuid = characteristic.uuid.toString().toLowerCase();
if (uuid == MeshCoreUuids.rxCharacteristic) {
_rxCharacteristic = characteristic;
} else if (uuid == MeshCoreUuids.txCharacteristic) {
_txCharacteristic = characteristic;
}
}
if (_rxCharacteristic == null || _txCharacteristic == null) {
throw Exception("MeshCore characteristics not found");
}
// Retry setNotifyValue with increasing delays
bool notifySet = false;
for (int attempt = 0; attempt < 3 && !notifySet; attempt++) {
try {
if (attempt > 0) {
await Future.delayed(Duration(milliseconds: 500 * attempt));
}
await _txCharacteristic!.setNotifyValue(true);
notifySet = true;
} catch (e) {
debugPrint('setNotifyValue attempt ${attempt + 1}/3 failed: $e');
if (attempt == 2) rethrow;
}
}
_notifySubscription = _txCharacteristic!.onValueReceived.listen(
_handleFrame,
);
_setState(MeshCoreConnectionState.connected);
// Enable wake lock to prevent BLE disconnection when screen turns off
await WakelockPlus.enable();
await _requestDeviceInfo();
_startBatteryPolling();
final gotSelfInfo = await _waitForSelfInfo(
timeout: const Duration(seconds: 3),
);
if (!gotSelfInfo) {
await refreshDeviceInfo();
await _waitForSelfInfo(timeout: const Duration(seconds: 3));
}
// Keep device clock aligned on every connection.
await syncTime();
// Fetch channels so we can track unread counts for incoming messages
unawaited(getChannels());
} catch (e) {
debugPrint("Connection error: $e");
await disconnect(manual: false);
rethrow;
}
}
Future<bool> _waitForSelfInfo({required Duration timeout}) async {
if (_selfPublicKey != null) return true;
if (!isConnected) return false;
final completer = Completer<bool>();
late final VoidCallback listener;
listener = () {
if (_selfPublicKey != null) {
if (!completer.isCompleted) {
completer.complete(true);
}
} else if (!isConnected) {
if (!completer.isCompleted) {
completer.complete(false);
}
}
};
addListener(listener);
final timer = Timer(timeout, () {
if (!completer.isCompleted) {
completer.complete(false);
}
});
final result = await completer.future;
timer.cancel();
removeListener(listener);
return result;
}
bool get _shouldAutoReconnect => !_manualDisconnect && _lastDeviceId != null;
void _cancelReconnectTimer() {
_reconnectTimer?.cancel();
_reconnectTimer = null;
_reconnectAttempts = 0;
}
int _nextReconnectDelayMs() {
final attempt = _reconnectAttempts < 6 ? _reconnectAttempts : 6;
_reconnectAttempts += 1;
final delayMs = 1000 * (1 << attempt);
return delayMs > 30000 ? 30000 : delayMs;
}
void _scheduleReconnect() {
if (!_shouldAutoReconnect) return;
if (_reconnectTimer?.isActive == true) return;
final delayMs = _nextReconnectDelayMs();
_reconnectTimer = Timer(Duration(milliseconds: delayMs), () async {
if (!_shouldAutoReconnect) return;
if (_state == MeshCoreConnectionState.connecting ||
_state == MeshCoreConnectionState.connected) {
return;
}
final device =
_lastDevice ??
(_lastDeviceId == null
? null
: BluetoothDevice.fromId(_lastDeviceId!));
if (device == null) return;
try {
await connect(device, displayName: _lastDeviceDisplayName);
} catch (_) {
_scheduleReconnect();
}
});
}
Future<void> disconnect({bool manual = true}) async {
if (_state == MeshCoreConnectionState.disconnecting) return;
if (manual) {
_manualDisconnect = true;
_cancelReconnectTimer();
unawaited(_backgroundService?.stop());
} else {
_manualDisconnect = false;
}
_setState(MeshCoreConnectionState.disconnecting);
_stopBatteryPolling();
// Disable wake lock when disconnecting
await WakelockPlus.disable();
await _notifySubscription?.cancel();
_notifySubscription = null;
await _connectionSubscription?.cancel();
_connectionSubscription = null;
_selfInfoRetryTimer?.cancel();
_selfInfoRetryTimer = null;
_queueSyncTimeout?.cancel();
_queueSyncTimeout = null;
_queueSyncRetries = 0;
_channelSyncTimeout?.cancel();
_channelSyncTimeout = null;
_channelSyncRetries = 0;
try {
// Skip queued BLE operations so disconnect doesn't get stuck behind them.
await _device?.disconnect(queue: false);
} catch (e) {
debugPrint("Disconnect error: $e");
}
_device = null;
_rxCharacteristic = null;
_txCharacteristic = null;
_deviceDisplayName = null;
_deviceId = null;
_contacts.clear();
_conversations.clear();
_loadedConversationKeys.clear();
_selfPublicKey = null;
_selfName = null;
_selfLatitude = null;
_selfLongitude = null;
_batteryMillivolts = null;
_reportedBatteryChemistry = null;
_batteryRequested = false;
_awaitingSelfInfo = false;
_maxContacts = _defaultMaxContacts;
_maxChannels = _defaultMaxChannels;
_isSyncingQueuedMessages = false;
_queuedMessageSyncInFlight = false;
_didInitialQueueSync = false;
_pendingQueueSync = false;
_isSyncingChannels = false;
_channelSyncInFlight = false;
_hasLoadedChannels = false;
_setState(MeshCoreConnectionState.disconnected);
if (!manual) {
_scheduleReconnect();
}
}
Future<void> sendFrame(Uint8List data) async {
if (!isConnected || _rxCharacteristic == null) {
throw Exception("Not connected to a MeshCore device");
}
_bleDebugLogService?.logFrame(data, outgoing: true);
// Prefer write without response when supported; fall back to write with response.
final properties = _rxCharacteristic!.properties;
final canWriteWithoutResponse = properties.writeWithoutResponse;
final canWriteWithResponse = properties.write;
if (!canWriteWithoutResponse && !canWriteWithResponse) {
throw Exception("MeshCore RX characteristic does not support write");
}
await _rxCharacteristic!.write(
data.toList(),
withoutResponse: canWriteWithoutResponse,
);
}
Future<void> requestBatteryStatus({bool force = false}) async {
if (!isConnected) return;
if (_batteryRequested && !force) return;
_batteryRequested = true;
await sendFrame(buildGetBattAndStorageFrame());
}
void _startBatteryPolling() {
_batteryPollTimer?.cancel();
_batteryPollTimer = Timer.periodic(_batteryPollInterval, (timer) {
if (!isConnected) {
timer.cancel();
return;
}
unawaited(requestBatteryStatus(force: true));
});
}
void _stopBatteryPolling() {
_batteryPollTimer?.cancel();
_batteryPollTimer = null;
}
Future<void> refreshDeviceInfo() async {
if (!isConnected) return;
_awaitingSelfInfo = true;
await sendFrame(buildDeviceQueryFrame());
await sendFrame(buildAppStartFrame());
await requestBatteryStatus(force: true);
await sendFrame(buildGetRadioSettingsFrame());
await sendFrame(buildGetCustomVarsFrame());
_scheduleSelfInfoRetry();
}
Future<void> _requestDeviceInfo() async {
if (!isConnected || _awaitingSelfInfo) return;
_awaitingSelfInfo = true;
await sendFrame(buildDeviceQueryFrame());
await sendFrame(buildAppStartFrame());
await sendFrame(buildGetCustomVarsFrame());
await requestBatteryStatus();
_scheduleSelfInfoRetry();
}
void _scheduleSelfInfoRetry() {