forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevice_provider.dart
More file actions
1063 lines (949 loc) · 40.3 KB
/
Copy pathdevice_provider.dart
File metadata and controls
1063 lines (949 loc) · 40.3 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:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:omi/backend/http/api/device.dart';
import 'package:omi/gen/pigeon_communicator.g.dart';
import 'package:omi/utils/l10n_extensions.dart';
import 'package:omi/backend/preferences.dart';
import 'package:omi/backend/schema/bt_device/bt_device.dart';
import 'package:omi/app_globals.dart';
import 'package:omi/pages/home/firmware_update.dart';
import 'package:omi/pages/home/omiglass_ota_update.dart';
import 'package:omi/providers/capture_provider.dart';
import 'package:omi/providers/local_recordings_provider.dart';
import 'package:omi/services/devices.dart';
import 'package:omi/services/devices/connectors/device_connection.dart';
import 'package:omi/services/devices/connectors/omi_connection.dart';
import 'package:omi/services/bridges/ble_bridge.dart';
import 'package:omi/services/notifications.dart';
import 'package:omi/services/services.dart';
import 'package:omi/services/battery_widget_service.dart';
import 'package:omi/services/wals/wal_syncs.dart';
import 'package:omi/services/wals/recording_transfer_coordinator.dart';
import 'package:omi/utils/device.dart';
import 'package:omi/utils/firmware_update_build_policy.dart';
import 'package:omi/utils/firmware_update_check_session.dart';
import 'package:omi/utils/firmware_update_prompt_coordinator.dart';
import 'package:omi/utils/logger.dart';
import 'package:omi/utils/other/debouncer.dart';
import 'package:omi/utils/platform/platform_manager.dart';
import 'package:omi/widgets/confirmation_dialog.dart';
typedef BleDiagnosticsLoader = Future<BleDeviceDiagnostics> Function(String deviceId);
typedef FindDeviceRunner = Future<bool> Function(BtDevice device);
class DeviceProvider extends ChangeNotifier implements IDeviceServiceSubsciption {
CaptureProvider? captureProvider;
LocalRecordingsProvider? localRecordingsProvider;
bool isConnecting = false;
bool isConnected = false;
bool isDeviceStorageSupport = false;
bool supportsMultiFileSync = SharedPreferencesUtil().deviceSupportsMultiFileSync;
// Latest on-device ring-buffer storage snapshot (firmware 3.0.20+ only).
// Surfaced on the Auto Sync page as a storage-usage indicator. Null when the
// device predates the ring protocol or hasn't been read yet.
RingStatus? _ringStatus;
RingStatus? get ringStatus => _ringStatus;
BtDevice? connectedDevice;
BtDevice? pairedDevice;
DateTime? _deviceSessionStartedAt;
final BleDiagnosticsLoader _bleDiagnosticsLoader;
final FindDeviceRunner _findDeviceRunner;
Future<bool>? _findDeviceRequest;
StreamSubscription<List<int>>? _bleBatteryLevelListener;
StreamSubscription? _bleChargingStatusListener;
int batteryLevel = -1;
bool isCharging = false;
int _lastNotifiedBatteryLevel = -1;
DateTime? _lastBatteryNotifyTime;
bool _hasLowBatteryAlerted = false;
bool _hasFullyChargedAlerted = false;
bool _havingNewFirmware = false;
bool get havingNewFirmware =>
_havingNewFirmware && pairedDevice != null && isConnected && _allowsFirmwareUpdateForPairedDevice;
// Track firmware update state to prevent showing dialog during updates
final FirmwareUpdateCheckSessionGuard _firmwareUpdateCheckSessionGuard = FirmwareUpdateCheckSessionGuard();
FirmwareUpdateCheckSession? _checkingFirmwareSession;
String? _firmwareUpdateDeviceId;
final FirmwareUpdatePromptCoordinator _firmwareUpdatePromptCoordinator = FirmwareUpdatePromptCoordinator();
bool _pairingLostDialogShowing = false;
bool _isFirmwareUpdateInProgress = false;
bool get isFirmwareUpdateInProgress => _isFirmwareUpdateInProgress;
// Current and latest firmware versions for UI display
String get currentFirmwareVersion => pairedDevice?.firmwareRevision ?? 'Unknown';
String _latestFirmwareVersion = '';
String get latestFirmwareVersion => _latestFirmwareVersion;
// Latest stable firmware version (for rollback comparison)
String _latestStableFirmwareVersion = '';
String get latestStableFirmwareVersion => _latestStableFirmwareVersion;
// OmiGlass firmware update details from GitHub releases
Map<String, dynamic> _latestOmiGlassFirmwareDetails = {};
Map<String, dynamic> get latestOmiGlassFirmwareDetails => _latestOmiGlassFirmwareDetails;
Timer? _discoveryTimer;
final Debouncer _disconnectDebouncer = Debouncer(delay: const Duration(milliseconds: 500));
final Debouncer _connectDebouncer = Debouncer(delay: const Duration(milliseconds: 100));
void Function(BtDevice device)? onDeviceConnected;
void Function(BtDevice device, int fileCount, int totalBytes)? onOfflineDataDetected;
DeviceProvider({BleDiagnosticsLoader? bleDiagnosticsLoader, FindDeviceRunner? findDeviceRunner})
: _bleDiagnosticsLoader = bleDiagnosticsLoader ?? BleHostApi().getDeviceDiagnostics,
_findDeviceRunner = findDeviceRunner ?? _defaultFindDeviceRunner {
ServiceManager.instance().device.subscribe(this, this);
BleBridge.instance.pairingLostCallback = _showPairingLostDialog;
}
void _showPairingLostDialog() {
if (_pairingLostDialogShowing) return;
final context = globalNavigatorKey.currentContext;
if (context == null || !context.mounted) return;
_pairingLostDialogShowing = true;
showDialog<void>(
context: context,
barrierDismissible: false,
builder: (dialogContext) => ConfirmationDialog(
title: dialogContext.l10n.bluetooth,
description: dialogContext.l10n.deviceUnpairedMessage,
confirmText: dialogContext.l10n.gotIt,
onConfirm: () => Navigator.of(dialogContext).pop(),
onCancel: () {},
),
).whenComplete(() => _pairingLostDialogShowing = false);
}
void setProviders(CaptureProvider provider, LocalRecordingsProvider recordingsProvider) {
captureProvider = provider;
localRecordingsProvider = recordingsProvider;
notifyListeners();
}
Future<void> setConnectedDevice(BtDevice? device) async {
final endedDevice = device == null ? (pairedDevice ?? connectedDevice) : null;
final sessionStartedAt = _deviceSessionStartedAt;
final now = DateTime.now();
final isNewConnection = device != null && connectedDevice?.id != device.id;
connectedDevice = device;
pairedDevice = device;
if (isNewConnection) {
if (_firmwareUpdateDeviceId != null && _firmwareUpdateDeviceId != device.id) {
_firmwareUpdatePromptCoordinator.clearAvailableVersion(invalidateDeferral: true);
}
_firmwareUpdateDeviceId = device.id;
_firmwareUpdateCheckSessionGuard.start(device.id);
_deviceSessionStartedAt = now;
} else if (device == null) {
_firmwareUpdateCheckSessionGuard.invalidate();
_deviceSessionStartedAt = null;
}
await getDeviceInfo();
if (isNewConnection) {
PlatformManager.instance.analytics.deviceConnected(device);
}
if (device != null) {
final firstPairedAt = await _markDevicePaired(device.id);
if (firstPairedAt != null) {
PlatformManager.instance.analytics.devicePaired(firstPairedAt);
}
}
if (endedDevice != null && sessionStartedAt != null) {
BleDisconnectEvent? disconnect;
try {
final diagnostics = await _bleDiagnosticsLoader(endedDevice.id);
final sessionStartMs = sessionStartedAt.millisecondsSinceEpoch;
for (final event in diagnostics.disconnectHistory.reversed) {
if (event.timestamp >= sessionStartMs) {
disconnect = event;
break;
}
}
} catch (_) {
// Native diagnostics are best-effort; local timing still makes the event useful.
}
PlatformManager.instance.analytics.deviceSessionEnded(
device: endedDevice,
duration: disconnect != null && disconnect.connectionDurationMs > 0
? Duration(milliseconds: disconnect.connectionDurationMs)
: now.difference(sessionStartedAt),
reason: disconnect?.reason,
hciReasonCode: disconnect?.reasonCode,
);
}
Logger.debug('setConnectedDevice: $device');
notifyListeners();
}
Future<String?> _markDevicePaired(String deviceId) async {
final preferences = SharedPreferencesUtil();
final uid = preferences.uid;
if (uid.isEmpty || deviceId.isEmpty) return null;
final pairedDevicesKey = 'pairedDeviceIds:$uid';
final pairedDeviceIds = preferences.getStringList(pairedDevicesKey);
if (pairedDeviceIds.contains(deviceId)) return null;
final firstPairedAtKey = 'firstPairedAt:$uid';
var firstPairedAt = preferences.getString(firstPairedAtKey);
if (firstPairedAt.isEmpty) {
firstPairedAt = DateTime.now().toUtc().toIso8601String();
await preferences.saveString(firstPairedAtKey, firstPairedAt);
}
if (!await preferences.saveStringList(pairedDevicesKey, [...pairedDeviceIds, deviceId])) return null;
return preferences.uid == uid ? firstPairedAt : null;
}
Future getDeviceInfo() async {
if (connectedDevice != null) {
if (pairedDevice?.firmwareRevision != null && pairedDevice?.firmwareRevision != 'Unknown') {
SharedPreferencesUtil().btDevice = pairedDevice!;
return;
}
var connection = await ServiceManager.instance().device.ensureConnection(connectedDevice!.id);
pairedDevice = await connectedDevice?.getDeviceInfo(connection);
SharedPreferencesUtil().btDevice = pairedDevice!;
} else {
if (SharedPreferencesUtil().btDevice.id.isEmpty) {
pairedDevice = BtDevice.empty();
} else {
pairedDevice = SharedPreferencesUtil().btDevice;
}
}
notifyListeners();
}
Future<bool> findDevice() {
final device = connectedDevice ?? pairedDevice;
if (!isConnected ||
device == null ||
device.type != DeviceType.omi ||
FirmwareUpdateBuildPolicy.current.isOpenGlassDevice(device)) {
return Future.value(false);
}
final existingRequest = _findDeviceRequest;
if (existingRequest != null) return existingRequest;
late final Future<bool> request;
request = _runFindDevice(device).whenComplete(() {
if (identical(_findDeviceRequest, request)) {
_findDeviceRequest = null;
}
});
_findDeviceRequest = request;
return request;
}
Future<bool> _runFindDevice(BtDevice device) async {
try {
return await _findDeviceRunner(device);
} catch (e) {
Logger.debug('DeviceProvider: Failed to play find-device pattern: $e');
return false;
}
}
static Future<bool> _defaultFindDeviceRunner(BtDevice device) async {
final connection = await ServiceManager.instance().device.ensureConnection(device.id).timeout(
const Duration(seconds: 5),
onTimeout: () {
Logger.debug('DeviceProvider: Timed out finding the active device connection');
return null;
},
);
return await connection?.playFindDevicePattern() ?? false;
}
Future _bleDisconnectDevice(BtDevice btDevice) async {
await ServiceManager.instance().device.disconnectDevice();
}
Future<int> _retrieveBatteryLevel(String deviceId) async {
var connection = await ServiceManager.instance().device.ensureConnection(deviceId);
if (connection == null) {
return -1;
}
return connection.retrieveBatteryLevel();
}
Future<StreamSubscription<List<int>>?> _getBleBatteryLevelListener(
String deviceId, {
void Function(int)? onBatteryLevelChange,
}) async {
{
var connection = await ServiceManager.instance().device.ensureConnection(deviceId);
if (connection == null) {
return Future.value(null);
}
return connection.getBleBatteryLevelListener(onBatteryLevelChange: onBatteryLevelChange);
}
}
Future<List<int>> _getStorageList(String deviceId) async {
var connection = await ServiceManager.instance().device.ensureConnection(deviceId);
if (connection == null) {
return [];
}
return connection.getStorageList();
}
initiateBleBatteryListener() async {
if (connectedDevice == null) {
return;
}
_bleBatteryLevelListener?.cancel();
_bleBatteryLevelListener = await _getBleBatteryLevelListener(
connectedDevice!.id,
onBatteryLevelChange: (int value) {
batteryLevel = value;
BatteryWidgetService().updateBatteryInfo(
deviceName: connectedDevice?.name ?? '',
batteryLevel: value,
deviceType: connectedDevice?.type.name ?? 'omi',
isConnected: true,
);
if (batteryLevel < 20 && !_hasLowBatteryAlerted) {
_hasLowBatteryAlerted = true;
final ctx = globalNavigatorKey.currentContext;
NotificationService.instance.createNotification(
title: ctx?.l10n.lowBatteryAlertTitle ?? "Low Battery Alert",
body: ctx?.l10n.lowBatteryAlertBody(value) ?? "Your battery is at $value%. Time for a recharge! 🔋",
);
} else if (batteryLevel > 20) {
_hasLowBatteryAlerted = false;
}
if (isCharging && batteryLevel >= 100 && !_hasFullyChargedAlerted) {
_hasFullyChargedAlerted = true;
final ctx = globalNavigatorKey.currentContext;
NotificationService.instance.createNotification(
title: ctx?.l10n.batteryFullyChargedTitle ?? "Omi is fully charged",
body: ctx?.l10n.batteryFullyChargedBody ?? "Your Omi device is fully charged. Feel free to unplug!",
);
} else if (!isCharging || batteryLevel < 100) {
_hasFullyChargedAlerted = false;
}
// Throttle notifyListeners to reduce battery drain from excessive UI rebuilds
// Only notify when: first reading, >=5% change, 15min elapsed, or crosses 20% threshold
final delta = (_lastNotifiedBatteryLevel - value).abs();
final elapsed = _lastBatteryNotifyTime == null
? const Duration(minutes: 999)
: DateTime.now().difference(_lastBatteryNotifyTime!);
final crossedLowBatteryThreshold =
(value < 20 && _lastNotifiedBatteryLevel >= 20) || (value >= 20 && _lastNotifiedBatteryLevel < 20);
final shouldNotify =
_lastNotifiedBatteryLevel == -1 || delta >= 5 || elapsed.inMinutes >= 15 || crossedLowBatteryThreshold;
if (shouldNotify) {
_lastNotifiedBatteryLevel = value;
_lastBatteryNotifyTime = DateTime.now();
notifyListeners();
}
},
);
notifyListeners();
}
Future<void> initiateChargingStatusListener() async {
if (connectedDevice == null) return;
_bleChargingStatusListener?.cancel();
var connection = await ServiceManager.instance().device.ensureConnection(connectedDevice!.id);
if (connection == null) return;
if (connection is! OmiDeviceConnection) return;
final currentStatus = await connection.readChargingStatus();
if (isCharging != currentStatus) {
isCharging = currentStatus;
notifyListeners();
}
_bleChargingStatusListener = await connection.getChargingStatusListener(
onChargingStatusChange: (bool charging) {
if (isCharging != charging) {
isCharging = charging;
if (!charging) {
_hasFullyChargedAlerted = false;
} else if (batteryLevel >= 100 && !_hasFullyChargedAlerted) {
_hasFullyChargedAlerted = true;
final ctx = globalNavigatorKey.currentContext;
NotificationService.instance.createNotification(
title: ctx?.l10n.batteryFullyChargedTitle ?? "Omi is fully charged",
body: ctx?.l10n.batteryFullyChargedBody ?? "Your Omi device is fully charged. Feel free to unplug!",
);
}
notifyListeners();
}
},
);
}
/// Updates battery level with throttling logic. Returns true if notifyListeners was called.
/// This method is exposed for testing the throttling behavior.
@visibleForTesting
bool updateBatteryLevelForTesting(int value, {DateTime? now}) {
batteryLevel = value;
final currentTime = now ?? DateTime.now();
// Throttle notifyListeners to reduce battery drain from excessive UI rebuilds
// Only notify when: first reading, >=5% change, 15min elapsed, or crosses 20% threshold
final delta = (_lastNotifiedBatteryLevel - value).abs();
final elapsed =
_lastBatteryNotifyTime == null ? const Duration(minutes: 999) : currentTime.difference(_lastBatteryNotifyTime!);
final crossedLowBatteryThreshold =
(value < 20 && _lastNotifiedBatteryLevel >= 20) || (value >= 20 && _lastNotifiedBatteryLevel < 20);
final shouldNotify =
_lastNotifiedBatteryLevel == -1 || delta >= 5 || elapsed.inMinutes >= 15 || crossedLowBatteryThreshold;
if (shouldNotify) {
_lastNotifiedBatteryLevel = value;
_lastBatteryNotifyTime = currentTime;
notifyListeners();
return true;
}
return false;
}
/// Resets battery throttling state for testing.
@visibleForTesting
void resetBatteryThrottlingForTesting() {
_lastNotifiedBatteryLevel = -1;
_lastBatteryNotifyTime = null;
}
/// Kicks off a single connection attempt. Native handles auto-reconnect after this.
Future<void> initiateConnection(String caller, {bool boundDeviceOnly = false}) async {
final pairedDeviceId = SharedPreferencesUtil().btDevice.id;
// Already connected — nothing to do
if (isConnected || connectedDevice != null) return;
// No paired device (onboarding) — start periodic scanning so devices
// turned on after the page loads are still discovered.
if (pairedDeviceId.isEmpty) {
if (boundDeviceOnly) return;
_startDiscoveryScanning();
return;
}
// Known device — use ensureConnection which creates the NativeBleTransport,
// then connects natively. If native is already connected, it just re-notifies Dart.
// force: true ensures we retry even if a previous attempt left a stale connection.
try {
await ServiceManager.instance().device.ensureConnection(pairedDeviceId, force: true);
} catch (e) {
// Timeout or transport failure — native keeps trying in the background.
// NativeBleTransport's BleBridge registration persists, so auto-reconnect still works.
Logger.debug('initiateConnection ($caller): ensureConnection failed: $e');
}
}
void _startDiscoveryScanning() {
_discoveryTimer?.cancel();
_runDiscoveryScan();
_discoveryTimer = Timer.periodic(const Duration(seconds: 10), (_) => _runDiscoveryScan());
}
Future<void> _runDiscoveryScan() async {
if (SharedPreferencesUtil().btDevice.id.isNotEmpty || isConnected) {
_discoveryTimer?.cancel();
return;
}
final deviceService = ServiceManager.instance().device;
if (deviceService.status == DeviceServiceStatus.ready) {
try {
await deviceService.discover();
} catch (e) {
Logger.debug('_runDiscoveryScan: discover failed: $e');
}
}
}
Future scanAndConnectToDevice() async {
updateConnectingStatus(true);
if (isConnected && connectedDevice != null) {
updateConnectingStatus(false);
return;
}
final pairedDeviceId = SharedPreferencesUtil().btDevice.id;
if (pairedDeviceId.isEmpty) {
updateConnectingStatus(false);
return;
}
try {
var connection = await ServiceManager.instance().device.ensureConnection(pairedDeviceId, force: true);
if (connection != null) {
await setConnectedDevice(connection.device);
setisDeviceStorageSupport();
SharedPreferencesUtil().deviceName = connection.device.name;
setIsConnected(true);
}
} catch (e) {
Logger.debug('scanAndConnectToDevice: connection failed: $e');
}
updateConnectingStatus(false);
notifyListeners();
}
void updateConnectingStatus(bool value) {
isConnecting = value;
notifyListeners();
}
void setIsConnected(bool value) {
isConnected = value;
if (isConnected) {
_discoveryTimer?.cancel();
}
notifyListeners();
}
@override
void dispose() {
_firmwareUpdatePromptCoordinator.invalidatePresentation();
if (BleBridge.instance.pairingLostCallback == _showPairingLostDialog) {
BleBridge.instance.pairingLostCallback = null;
}
_bleBatteryLevelListener?.cancel();
_bleChargingStatusListener?.cancel();
_discoveryTimer?.cancel();
_disconnectDebouncer.cancel();
_connectDebouncer.cancel();
ServiceManager.instance().device.unsubscribe(this);
super.dispose();
}
void onDeviceDisconnected() async {
Logger.debug('onDisconnected inside: $connectedDevice');
_havingNewFirmware = false;
_firmwareUpdatePromptCoordinator.invalidatePresentation();
_bleChargingStatusListener?.cancel();
isCharging = false;
setConnectedDevice(null);
setisDeviceStorageSupport();
setIsConnected(false);
updateConnectingStatus(false);
captureProvider?.updateRecordingDevice(null);
// Batch mode: the native writer finalizes the in-progress recording on
// disconnect (.bin.part -> .bin). Rescan shortly after the rename completes
// so the new recording shows up in the conversations list.
Future.delayed(const Duration(seconds: 1), () {
localRecordingsProvider?.refresh();
});
// Wals
ServiceManager.instance().wal.getSyncs().sdcard.setDevice(null);
ServiceManager.instance().wal.getSyncs().flashPage.setDevice(null);
PlatformManager.instance.crashReporter.logInfo('Omi Device Disconnected');
PlatformManager.instance.analytics.deviceDisconnected();
BatteryWidgetService().updateBatteryInfo(
deviceName: SharedPreferencesUtil().deviceName,
batteryLevel: -1,
deviceType: 'omi',
isConnected: false,
);
// Notify interactive device onboarding of disconnect
captureProvider?.deviceOnboardingProvider?.onDeviceDisconnected();
}
Future<(String, bool, String, Map)> shouldUpdateFirmware() async {
if (pairedDevice == null || connectedDevice == null) {
return ('No paired device is connected', false, '', {});
}
var device = pairedDevice!;
if (device.firmwareRevision.isEmpty) {
// BLE read of the firmware-revision characteristic failed. Skip the
// upgrade check rather than asking the backend what's "newer than
// unknown" — that path returns a misleading legacy version.
return ('Unable to determine current firmware version', false, '', {});
}
var latestFirmwareDetails = await getLatestFirmwareVersion(
deviceModelNumber: device.modelNumber,
firmwareRevision: device.firmwareRevision,
hardwareRevision: device.hardwareRevision,
manufacturerName: device.manufacturerName,
);
var (message, hasUpdate, version) = await DeviceUtils.shouldUpdateFirmware(
currentFirmware: device.firmwareRevision,
latestFirmwareDetails: latestFirmwareDetails,
);
return (message, hasUpdate, version, latestFirmwareDetails);
}
void _onDeviceConnected(BtDevice device) async {
Logger.debug('_onConnected inside: $connectedDevice');
final deviceSetup = setConnectedDevice(device);
final connectionSession = _firmwareUpdateCheckSessionGuard.capture();
await deviceSetup;
if (connectionSession == null || !_isCurrentDeviceSession(connectionSession)) {
Logger.debug('Discarding device setup continuation from a stale connection session');
return;
}
if (captureProvider != null) {
captureProvider?.updateRecordingDevice(device);
}
setisDeviceStorageSupport();
setIsConnected(true);
// Read initial battery level
int currentLevel = await _retrieveBatteryLevel(device.id);
if (currentLevel != -1) {
batteryLevel = currentLevel;
BatteryWidgetService().updateBatteryInfo(
deviceName: device.name,
batteryLevel: currentLevel,
deviceType: device.type.name,
isConnected: true,
);
}
// Then set up listeners for battery changes and charging status
await initiateBleBatteryListener();
await initiateChargingStatusListener();
if (batteryLevel != -1 && batteryLevel < 20) {
_hasLowBatteryAlerted = false;
}
updateConnectingStatus(false);
await captureProvider?.streamDeviceRecording(device: device);
await getDeviceInfo();
SharedPreferencesUtil().deviceName = device.name;
// Wals — pass the firmware resolved by getDeviceInfo() above so background
// discovery routes ring-buffer devices correctly; `device` here is the raw
// connect object whose firmwareRevision is often still 'Unknown'.
final syncs = ServiceManager.instance().wal.getSyncs();
syncs.setDevice(device, firmwareVersion: currentFirmwareVersion);
syncs.sdcard.setDevice(device);
syncs.flashPage.setDevice(device);
syncs.storage.setDevice(device);
syncs.ring.setDevice(device);
// Device connection and inventory are a recovery wake, even when the
// home page is not mounted. The coordinator serializes it with every
// other foreground trigger and applies the auto-sync preference itself.
unawaited(RecordingTransferCoordinator.instance.wake(WakeTrigger.deviceConnected));
// Auto-sync: check if device has offline files
_checkAndStartAutoSync(device);
notifyListeners();
// Check firmware updates
_checkFirmwareUpdates();
if (Platform.isAndroid) {
_ensureCompanionAssociation(device);
}
onDeviceConnected?.call(device);
// Notify interactive device onboarding of reconnect
captureProvider?.deviceOnboardingProvider?.onDeviceReconnected();
}
/// Check firmware version to determine multi-file sync support.
/// Firmware >= 3.0.17 supports the new LittleFS multi-file protocol.
static bool _isFirmwareVersionSupported(String? version) {
if (version == null || version.isEmpty || version == 'Unknown') return false;
final parts = version.split('.').map((p) => int.tryParse(p) ?? 0).toList();
if (parts.length < 3) return false;
// Compare against 3.0.17
if (parts[0] > 3) return true;
if (parts[0] < 3) return false;
if (parts[1] > 0) return true;
if (parts[1] < 0) return false;
return parts[2] >= 17;
}
Future<void> _checkAndStartAutoSync(BtDevice device) async {
try {
// Use firmware version as the reliable signal for multi-file support
// Read from pairedDevice which has firmwareRevision populated by getDeviceInfo()
final fwVersion = pairedDevice?.firmwareRevision ?? device.firmwareRevision;
supportsMultiFileSync = _isFirmwareVersionSupported(fwVersion);
SharedPreferencesUtil().deviceSupportsMultiFileSync = supportsMultiFileSync;
notifyListeners();
if (!supportsMultiFileSync) return;
var connection = await ServiceManager.instance().device.ensureConnection(device.id);
if (connection == null) return;
// fw >= 3.0.20 speaks the ring-buffer protocol; auto-detect via the 16-byte
// ring status read instead of the multi-file file-list endpoint (which the
// ring firmware no longer serves).
if (WalSyncs.isRingBufferFirmware(fwVersion)) {
final ringStatus = await connection.getRingStatus();
if (ringStatus != null) {
_ringStatus = ringStatus;
notifyListeners();
}
if (ringStatus == null || ringStatus.unreadPackets <= 0) return;
Logger.debug(
'DeviceProvider: Ring auto-sync detected ${ringStatus.unreadPackets} unread packets (${ringStatus.usedBytes} bytes)',
);
onOfflineDataDetected?.call(device, ringStatus.unreadPackets, ringStatus.usedBytes);
return;
}
final status = await connection.getStorageFileStats();
if (status == null || status.fileCount == 0) return;
Logger.debug('DeviceProvider: Auto-sync detected ${status.fileCount} files (${status.totalUsedBytes} bytes)');
onOfflineDataDetected?.call(device, status.fileCount, status.totalUsedBytes);
} catch (e) {
Logger.debug('DeviceProvider: Auto-sync check failed: $e');
}
}
/// Refresh the on-device ring-buffer storage snapshot for the storage-usage
/// indicator. No-op on firmware < 3.0.20 (the ring protocol isn't served) or
/// when there's no active connection. Safe to call from UI (e.g. on page open).
Future<void> refreshRingStorageStatus() async {
try {
final fwVersion = pairedDevice?.firmwareRevision ?? connectedDevice?.firmwareRevision;
if (!WalSyncs.isRingBufferFirmware(fwVersion)) return;
final deviceId = pairedDevice?.id ?? connectedDevice?.id;
if (deviceId == null) return;
final connection = await ServiceManager.instance().device.ensureConnection(deviceId);
if (connection == null) return;
final status = await connection.getRingStatus();
if (status != null) {
_ringStatus = status;
notifyListeners();
}
} catch (e) {
Logger.debug('DeviceProvider: refreshRingStorageStatus failed: $e');
}
}
Future<void> _ensureCompanionAssociation(BtDevice device) async {
try {
if (SharedPreferencesUtil().companionAssociationPrompted) return;
if (await BleHostApi().hasCompanionDeviceAssociation()) return;
final ctx = globalNavigatorKey.currentContext;
if (ctx == null || !ctx.mounted) return;
SharedPreferencesUtil().companionAssociationPrompted = true;
await showDialog(
context: ctx,
builder: (context) => AlertDialog(
title: Text(context.l10n.improveConnectionTitle),
content: Text(context.l10n.improveConnectionContent),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(context.l10n.improveConnectionAction, style: const TextStyle(color: Colors.white)),
),
],
),
);
} catch (e) {
Logger.debug('CompanionDevice association check failed: $e');
}
}
void _handleDeviceConnected(String deviceId) async {
var connection = await ServiceManager.instance().device.ensureConnection(deviceId);
if (connection == null) {
return;
}
_onDeviceConnected(connection.device);
}
void _checkFirmwareUpdates() async {
if (!_allowsFirmwareUpdateForPairedDevice) {
_havingNewFirmware = false;
_firmwareUpdatePromptCoordinator.clearAvailableVersion(invalidateDeferral: true);
return;
}
final checkSession = _firmwareUpdateCheckSessionGuard.capture();
if (checkSession == null || !_isCurrentFirmwareCheckSession(checkSession)) {
return;
}
if (_isFirmwareUpdateInProgress ||
(_checkingFirmwareSession != null && _firmwareUpdateCheckSessionGuard.isCurrent(_checkingFirmwareSession!))) {
return;
}
_checkingFirmwareSession = checkSession;
try {
final hasUpdate = await checkFirmwareUpdates(session: checkSession);
if (!_isCurrentFirmwareCheckSession(checkSession)) {
Logger.debug('Discarding firmware update prompt from a stale device session');
return;
}
// Show firmware update dialog if needed
if (hasUpdate && _havingNewFirmware) {
// Use a small delay to ensure the UI is ready
Future.delayed(const Duration(milliseconds: 500), () {
if (!_isCurrentFirmwareCheckSession(checkSession)) return;
final context = globalNavigatorKey.currentContext;
if (context != null && context.mounted) {
showFirmwareUpdateDialog(context);
}
});
}
} finally {
if (identical(_checkingFirmwareSession, checkSession)) {
_checkingFirmwareSession = null;
}
}
}
bool _isCurrentFirmwareCheckSession(FirmwareUpdateCheckSession session) {
return _isCurrentDeviceSession(session) && isConnected;
}
bool _isCurrentDeviceSession(FirmwareUpdateCheckSession session) {
return _firmwareUpdateCheckSessionGuard.isCurrent(session) &&
connectedDevice?.id == session.deviceId &&
pairedDevice?.id == session.deviceId;
}
bool get _isOmiGlassDevice => FirmwareUpdateBuildPolicy.current.isOpenGlassDevice(pairedDevice);
bool get _allowsFirmwareUpdateForPairedDevice =>
FirmwareUpdateBuildPolicy.current.allowsFirmwareUpdateForDevice(pairedDevice);
Future<bool> checkFirmwareUpdates({FirmwareUpdateCheckSession? session}) async {
final checkSession = session ?? _firmwareUpdateCheckSessionGuard.capture();
if (checkSession == null || !_isCurrentFirmwareCheckSession(checkSession)) {
return false;
}
if (!_allowsFirmwareUpdateForPairedDevice) {
_havingNewFirmware = false;
_firmwareUpdatePromptCoordinator.clearAvailableVersion(invalidateDeferral: true);
return false;
}
int retryCount = 0;
const maxRetries = 3;
const retryDelay = Duration(seconds: 3);
while (retryCount < maxRetries) {
if (!_isCurrentFirmwareCheckSession(checkSession)) {
return false;
}
try {
var (message, hasUpdate, version, firmwareDetails) = await shouldUpdateFirmware();
if (!_isCurrentFirmwareCheckSession(checkSession)) {
Logger.debug('Discarding firmware update result from a stale device session');
return false;
}
final latestFirmwareVersion = version.isNotEmpty ? version : message;
Map<String, dynamic>? latestOmiGlassFirmwareDetails;
// For OmiGlass devices, populate the firmware details for the OTA UI
if (_isOmiGlassDevice && firmwareDetails.isNotEmpty) {
// Map backend response to OmiGlass OTA UI expected format
final versionStr = firmwareDetails['version']?.toString() ?? '';
final cleanVersion = versionStr.startsWith('v') ? versionStr.substring(1) : versionStr;
final changelog = firmwareDetails['changelog'];
final changelogStr = changelog is List ? changelog.join('\n') : (changelog?.toString() ?? '');
latestOmiGlassFirmwareDetails = {
'version': cleanVersion,
'download_url': firmwareDetails['zip_url'] ?? '',
'changelog': changelogStr,
};
}
// Fetch latest stable version for rollback comparison
String? latestStableFirmwareVersion;
try {
var stableDetails = await getStableFirmwareVersion(deviceModelNumber: pairedDevice?.modelNumber ?? '');
if (!_isCurrentFirmwareCheckSession(checkSession)) {
Logger.debug('Discarding stable firmware result from a stale device session');
return false;
}
var stableVersion = stableDetails['version']?.toString() ?? '';
if (stableVersion.startsWith('v')) stableVersion = stableVersion.substring(1);
latestStableFirmwareVersion = stableVersion;
} catch (e) {
if (!_isCurrentFirmwareCheckSession(checkSession)) {
Logger.debug('Discarding firmware update result from a stale device session');
return false;
}
Logger.debug('Error fetching stable firmware version: $e');
}
if (!_isCurrentFirmwareCheckSession(checkSession)) {
return false;
}
_havingNewFirmware = hasUpdate;
_latestFirmwareVersion = latestFirmwareVersion;
if (hasUpdate) {
_firmwareUpdatePromptCoordinator.setAvailableVersion(latestFirmwareVersion);
} else {
_firmwareUpdatePromptCoordinator.clearAvailableVersion();
}
if (latestOmiGlassFirmwareDetails != null) {
_latestOmiGlassFirmwareDetails = latestOmiGlassFirmwareDetails;
}
if (latestStableFirmwareVersion != null) {
_latestStableFirmwareVersion = latestStableFirmwareVersion;
}
notifyListeners();
return hasUpdate;
} catch (e) {
if (!_isCurrentFirmwareCheckSession(checkSession)) {
Logger.debug('Discarding firmware check failure from a stale device session');
return false;
}
retryCount++;
Logger.debug('Error checking firmware update (attempt $retryCount): $e');
if (retryCount == maxRetries) {
Logger.debug('Max retries reached, giving up');
_havingNewFirmware = false;
_firmwareUpdatePromptCoordinator.clearAvailableVersion();
notifyListeners();
return false;
}
await Future.delayed(retryDelay);
if (!_isCurrentFirmwareCheckSession(checkSession)) {
return false;
}
}
}
return false;
}
// Track if user is currently viewing a firmware update page
bool _isOnFirmwareUpdatePage = false;
void setOnFirmwareUpdatePage(bool value) {
_isOnFirmwareUpdatePage = value;
if (value) {
_firmwareUpdatePromptCoordinator.invalidatePresentation();
}
}
void showFirmwareUpdateDialog(BuildContext context) {
if (!_allowsFirmwareUpdateForPairedDevice ||
!_havingNewFirmware ||
!SharedPreferencesUtil().showFirmwareUpdateDialog ||
_isFirmwareUpdateInProgress ||
_isOnFirmwareUpdatePage) {
return;
}
final prompt = _firmwareUpdatePromptCoordinator.beginPresentation();
if (prompt == null) return;
showDialog<void>(
context: context,
barrierDismissible: false,
builder: (dialogContext) {
final route = ModalRoute.of(dialogContext);
final navigator = Navigator.of(dialogContext);
_firmwareUpdatePromptCoordinator.attachDismissal(prompt, () {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!dialogContext.mounted || route == null || !route.isActive) return;
if (route.isCurrent) {
navigator.pop();
} else {
navigator.removeRoute(route);
}
});
});
return ConfirmationDialog(
title: dialogContext.l10n.firmwareUpdateAvailable,
description: dialogContext.l10n.firmwareUpdateAvailableDescription(_latestFirmwareVersion),
confirmText: dialogContext.l10n.update,
cancelText: dialogContext.l10n.later,
onConfirm: () {
if (!_firmwareUpdatePromptCoordinator.accept(prompt)) return;
Logger.info('Firmware update prompt accepted');
setFirmwareUpdateInProgress(true);
if (_isOmiGlassDevice) {
navigator.push(
MaterialPageRoute(
builder: (context) =>
OmiGlassOtaUpdate(device: pairedDevice, latestFirmwareDetails: _latestOmiGlassFirmwareDetails),
),
);
} else {
navigator.push(MaterialPageRoute(builder: (context) => FirmwareUpdate(device: pairedDevice)));
}
},
onCancel: () {
if (_firmwareUpdatePromptCoordinator.defer(prompt)) {
Logger.info('Firmware update prompt deferred by user');
}
},
);
},
).whenComplete(() {
_firmwareUpdatePromptCoordinator.complete(prompt);