forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeviceProvider.swift
More file actions
683 lines (557 loc) · 22.3 KB
/
Copy pathDeviceProvider.swift
File metadata and controls
683 lines (557 loc) · 22.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
import Combine
@preconcurrency import CoreBluetooth
import Foundation
import SwiftUI
@preconcurrency import UserNotifications
import os.log
// MARK: - Notification Names
extension Notification.Name {
/// Posted when device has storage data available to sync
static let storageSyncAvailable = Notification.Name("storageSyncAvailable")
}
/// State management for Bluetooth device connectivity
/// Ported from: omi/app/lib/providers/device_provider.dart
@MainActor
final class DeviceProvider: ObservableObject {
// MARK: - Singleton
static let shared = DeviceProvider(bluetoothManager: BluetoothManager.shared)
typealias ConnectionFactory = @MainActor (BtDevice, UInt64) -> DeviceConnection?
typealias StorageDataChecker = @MainActor () async -> (totalBytes: Int, currentOffset: Int)?
// MARK: - Published State
/// Whether currently scanning for devices
@Published private(set) var isScanning = false
/// The canonical Bluetooth lifecycle state. UI-facing convenience
/// properties below are read-only projections of this snapshot.
@Published private(set) var sessionSnapshot: DeviceSessionSnapshot
var isConnecting: Bool { sessionSnapshot.phase.isConnecting }
var isConnected: Bool { sessionSnapshot.phase.isReady }
var connectedDevice: BtDevice? { sessionSnapshot.connectedDevice }
var pairedDevice: BtDevice? { sessionSnapshot.pairedDevice }
var isConnectedPublisher: AnyPublisher<Bool, Never> {
$sessionSnapshot
.map { $0.phase.isReady }
.removeDuplicates()
.eraseToAnyPublisher()
}
/// Current battery level (0-100, or -1 if unavailable)
@Published private(set) var batteryLevel: Int = -1
/// List of discovered devices during scan
@Published private(set) var discoveredDevices: [BtDevice] = []
/// Current Bluetooth state
@Published private(set) var bluetoothState: CBManagerState = .unknown
/// Whether the device supports storage
@Published private(set) var isDeviceStorageSupported = false
/// Whether a firmware update is available
@Published private(set) var hasFirmwareUpdate = false
/// Latest firmware version (if update available)
@Published private(set) var latestFirmwareVersion: String = ""
/// Whether firmware update is in progress
@Published private(set) var isFirmwareUpdateInProgress = false
/// Error message for UI display
@Published var errorMessage: String?
// MARK: - Private Properties
private let bluetoothManager: DeviceBluetoothManaging
private let userDefaults: UserDefaults
private let notificationCenter: NotificationCenter
private let storageDataChecker: StorageDataChecker
private let sessionCoordinator: DeviceSessionCoordinator
/// The active connection is owned by the session coordinator. This
/// projection remains internal for AudioSourceManager access.
var activeConnection: DeviceConnection? { sessionCoordinator.activeConnection }
private var batterySubscription: Task<Void, Never>?
private var cancellables = Set<AnyCancellable>()
nonisolated(unsafe) private var disconnectNotificationTimer: Timer?
private var hasLowBatteryAlerted = false
private let logger = Logger(subsystem: "me.omi.desktop", category: "DeviceProvider")
// MARK: - UserDefaults Keys
private enum UserDefaultsKeys {
static let pairedDeviceId = "pairedDeviceId"
static let pairedDeviceName = "pairedDeviceName"
static let pairedDeviceType = "pairedDeviceType"
static let analyticsPairedDeviceIds = "analyticsPairedDeviceIds"
static let analyticsFirstPairedAt = "analyticsFirstPairedAt"
}
// MARK: - Initialization
private var hasSetupBluetoothBindings = false
init(
bluetoothManager: DeviceBluetoothManaging,
userDefaults: UserDefaults = .standard,
notificationCenter: NotificationCenter = .default,
connectionFactory: @escaping ConnectionFactory = {
DeviceConnectionFactory.create(device: $0, sessionGeneration: $1)
},
storageDataChecker: @escaping StorageDataChecker = { await StorageSyncService.shared.checkForStorageData() },
sessionScheduler: (any DeviceSessionScheduling)? = nil,
reconnectDelay: Duration = .seconds(15),
autoReconnectEnabled: Bool = true
) {
let persistedDevice = Self.loadPairedDevice(from: userDefaults)
if let persistedDevice {
Self.seedPairingAnalyticsState(for: persistedDevice, in: userDefaults)
}
let coordinator = DeviceSessionCoordinator(
pairedDevice: persistedDevice,
connectionFactory: connectionFactory,
scheduler: sessionScheduler ?? DeviceSessionTaskScheduler(),
reconnectDelay: reconnectDelay,
autoReconnectEnabled: autoReconnectEnabled
)
self.bluetoothManager = bluetoothManager
self.userDefaults = userDefaults
self.notificationCenter = notificationCenter
self.storageDataChecker = storageDataChecker
self.sessionCoordinator = coordinator
self.sessionSnapshot = coordinator.snapshot
coordinator.onSnapshotChanged = { [weak self] snapshot in
self?.sessionSnapshot = snapshot
}
coordinator.onReconnectRequested = { [weak self] request in
Task { @MainActor in
await self?.connect(
to: request.device,
reconnectRequest: request
)
}
}
coordinator.onDiscoveryRequested = { [weak self] in
self?.startDiscovery(timeout: 5)
}
coordinator.onSessionEnded = { [weak self] in
// Authoritative disconnect telemetry: one event per ended session.
// Unpair of an already-disconnected device does not fire this callback,
// so it cannot emit a phantom Device Disconnected.
AnalyticsManager.shared.deviceDisconnected()
self?.resetSessionPresentation()
}
coordinator.onFallDetected = { [weak self] data in
self?.sendFallDetectionNotification(data: data)
}
if let persistedDevice {
logger.info("Loaded paired device: \(persistedDevice.displayName)")
}
}
/// Initialize Bluetooth bindings - call this when Bluetooth features are needed
/// This is separate from init to avoid triggering Bluetooth permission dialog at app startup
func initializeBluetoothBindingsIfNeeded() {
guard !hasSetupBluetoothBindings else { return }
hasSetupBluetoothBindings = true
bluetoothManager.prepareForStateUpdates()
bluetoothState = bluetoothManager.currentBluetoothState
isScanning = bluetoothManager.currentIsScanning
discoveredDevices = bluetoothManager.currentDiscoveredDevices
// Observe Bluetooth state changes
bluetoothManager.bluetoothStatePublisher
.receive(on: DispatchQueue.main)
.sink { [weak self] state in
self?.bluetoothState = state
}
.store(in: &cancellables)
// Observe scanning state
bluetoothManager.isScanningPublisher
.receive(on: DispatchQueue.main)
.sink { [weak self] scanning in
self?.isScanning = scanning
}
.store(in: &cancellables)
// Observe discovered devices
bluetoothManager.discoveredDevicesPublisher
.receive(on: DispatchQueue.main)
.sink { [weak self] devices in
self?.discoveredDevices = devices
}
.store(in: &cancellables)
}
// MARK: - Persistence
private static func loadPairedDevice(from userDefaults: UserDefaults) -> BtDevice? {
guard let deviceId = userDefaults.string(forKey: UserDefaultsKeys.pairedDeviceId),
!deviceId.isEmpty
else {
return nil
}
let deviceName = userDefaults.string(forKey: UserDefaultsKeys.pairedDeviceName) ?? "Unknown Device"
let deviceTypeRaw = userDefaults.string(forKey: UserDefaultsKeys.pairedDeviceType) ?? "omi"
let deviceType = DeviceType(rawValue: deviceTypeRaw) ?? .omi
return BtDevice(
id: deviceId,
name: deviceName,
type: deviceType,
rssi: 0
)
}
private func savePairedDevice(_ device: BtDevice?) {
if let device = device {
userDefaults.set(device.id, forKey: UserDefaultsKeys.pairedDeviceId)
userDefaults.set(device.name, forKey: UserDefaultsKeys.pairedDeviceName)
userDefaults.set(device.type.rawValue, forKey: UserDefaultsKeys.pairedDeviceType)
logger.info("Saved paired device: \(device.displayName)")
} else {
userDefaults.removeObject(forKey: UserDefaultsKeys.pairedDeviceId)
userDefaults.removeObject(forKey: UserDefaultsKeys.pairedDeviceName)
userDefaults.removeObject(forKey: UserDefaultsKeys.pairedDeviceType)
logger.info("Cleared paired device")
}
}
private static func seedPairingAnalyticsState(
for device: BtDevice,
in userDefaults: UserDefaults
) {
guard userDefaults.stringArray(forKey: UserDefaultsKeys.analyticsPairedDeviceIds) == nil else {
return
}
userDefaults.set([device.id], forKey: UserDefaultsKeys.analyticsPairedDeviceIds)
}
private func recordPairingAnalytics(for device: BtDevice) {
var pairedDeviceIds = Set(
userDefaults.stringArray(forKey: UserDefaultsKeys.analyticsPairedDeviceIds) ?? [])
let isNewPair = pairedDeviceIds.insert(device.id).inserted
let isFirstPair = isNewPair && pairedDeviceIds.count == 1
var firstPairedAt = userDefaults.object(forKey: UserDefaultsKeys.analyticsFirstPairedAt) as? Date
if isNewPair {
userDefaults.set(
pairedDeviceIds.sorted(),
forKey: UserDefaultsKeys.analyticsPairedDeviceIds
)
if isFirstPair {
firstPairedAt = Date()
userDefaults.set(firstPairedAt, forKey: UserDefaultsKeys.analyticsFirstPairedAt)
}
}
AnalyticsManager.shared.devicePairingReady(
device: device,
isNewPair: isNewPair,
isFirstPair: isFirstPair,
firstPairedAt: firstPairedAt
)
}
// MARK: - Discovery
/// Start scanning for devices
/// - Parameter timeout: Scan duration in seconds
func startDiscovery(timeout: TimeInterval = 5.0) {
// Initialize Bluetooth bindings if not already done
initializeBluetoothBindingsIfNeeded()
guard bluetoothState == .poweredOn else {
errorMessage = "Bluetooth is not available"
return
}
bluetoothManager.startScanning(timeout: timeout)
}
/// Stop scanning for devices
func stopDiscovery() {
initializeBluetoothBindingsIfNeeded()
bluetoothManager.stopScanning()
}
// MARK: - Connection
/// Connect to a device
/// - Parameter device: The device to connect to
func connect(to device: BtDevice) async {
await connect(to: device, reconnectRequest: nil)
}
private func connect(
to device: BtDevice,
reconnectRequest: DeviceReconnectRequest?
) async {
errorMessage = nil
do {
let connection: DeviceConnection
if let reconnectRequest {
connection = try await sessionCoordinator.reconnect(reconnectRequest)
} else {
connection = try await sessionCoordinator.connect(to: device)
}
let generation = connection.sessionGeneration
// Save as paired device
savePairedDevice(connection.device)
recordPairingAnalytics(for: connection.device)
// Start battery monitoring
await startBatteryMonitoring(connection: connection, generation: generation)
guard sessionCoordinator.isReady(generation: generation) else { return }
// Check storage support
await checkStorageSupport(connection: connection, generation: generation)
guard sessionCoordinator.isReady(generation: generation) else { return }
// Check for firmware updates
await checkFirmwareUpdates(generation: generation)
guard sessionCoordinator.isReady(generation: generation) else { return }
// Clear any pending disconnect notification
disconnectNotificationTimer?.invalidate()
disconnectNotificationTimer = nil
logger.info("Connected to \(device.displayName)")
AnalyticsManager.shared.deviceConnected(device: device)
} catch DeviceSessionCoordinatorError.connectionAlreadyActive {
logger.debug("Ignored duplicate connection request for \(device.displayName)")
} catch DeviceSessionCoordinatorError.superseded {
logger.debug("Connection attempt for \(device.displayName) was superseded")
} catch {
logger.error("Failed to connect to \(device.displayName): \(error.localizedDescription)")
errorMessage = "Failed to connect: \(error.localizedDescription)"
}
}
/// Disconnect from the current device
func disconnect() async {
guard activeConnection != nil else {
logger.warning("No active connection to disconnect")
return
}
await sessionCoordinator.disconnect(reconnectAfter: .zero)
logger.info("Disconnected from device")
}
/// Unpair the current device (disconnect and clear pairing)
func unpair() async {
await sessionCoordinator.unpair()
// Unpair is an intentional teardown: do not arm (and cancel any pending)
// "device disconnected — please reconnect" notification, which would be
// misleading for a device the user deliberately removed.
resetSessionPresentation(scheduleReconnectNotification: false)
savePairedDevice(nil)
logger.info("Unpaired device")
}
/// Test seam: whether a "please reconnect" disconnect notification is armed.
var hasScheduledDisconnectNotification: Bool { disconnectNotificationTimer != nil }
/// - Parameter scheduleReconnectNotification: arm the reconnect prompt (true
/// for an unexpected disconnect) or cancel any pending one (false for an
/// intentional unpair).
private func resetSessionPresentation(scheduleReconnectNotification: Bool = true) {
// Cancel battery monitoring
batterySubscription?.cancel()
batterySubscription = nil
batteryLevel = -1
isDeviceStorageSupported = false
hasFirmwareUpdate = false
hasLowBatteryAlerted = false
if scheduleReconnectNotification {
scheduleDisconnectNotification()
} else {
disconnectNotificationTimer?.invalidate()
disconnectNotificationTimer = nil
}
}
// MARK: - Auto-Reconnection
/// Begin the coordinator-owned reconnection policy.
func startReconnecting() {
sessionCoordinator.startReconnecting()
}
/// Stop pending coordinator-owned reconnection work.
func stopReconnecting() {
sessionCoordinator.stopReconnecting()
}
// MARK: - Battery Monitoring
private func startBatteryMonitoring(
connection: DeviceConnection,
generation: UInt64
) async {
// Get initial battery level
let level = await connection.getBatteryLevel()
if sessionCoordinator.isReady(generation: generation), level >= 0 {
batteryLevel = level
checkLowBattery()
}
guard sessionCoordinator.isReady(generation: generation) else { return }
// Start listening for battery updates
batterySubscription?.cancel()
batterySubscription = Task { [weak self, weak connection] in
guard let connection else { return }
do {
for try await level in connection.getBatteryLevelStream() {
guard !Task.isCancelled, let self else { return }
guard self.sessionCoordinator.isReady(generation: generation) else { return }
self.batteryLevel = level
self.checkLowBattery()
}
} catch {
self?.logger.debug("Battery stream ended: \(error.localizedDescription)")
}
}
}
private func checkLowBattery() {
guard batteryLevel >= 0 && batteryLevel < 20 && !hasLowBatteryAlerted else {
if batteryLevel >= 20 {
hasLowBatteryAlerted = false
}
return
}
hasLowBatteryAlerted = true
// Send low battery notification
let content = UNMutableNotificationContent()
content.title = "Low Battery Alert"
content.body = "Your omi device is running low on battery. Time for a recharge! 🔋"
content.sound = .default
let request = UNNotificationRequest(
identifier: "lowBattery",
content: content,
trigger: nil
)
UNUserNotificationCenter.current().add(request)
}
// MARK: - Storage Support
private func checkStorageSupport(
connection: DeviceConnection,
generation: UInt64
) async {
let storageList = await connection.getStorageList()
guard sessionCoordinator.isReady(generation: generation) else { return }
isDeviceStorageSupported = !storageList.isEmpty
// Check for pending storage data to sync
if isDeviceStorageSupported {
await checkPendingStorageSync(generation: generation)
}
}
/// Check if device has pending storage data to sync
private func checkPendingStorageSync(generation: UInt64) async {
guard let (totalBytes, currentOffset) = await storageDataChecker() else {
return
}
guard sessionCoordinator.isReady(generation: generation) else { return }
let bytesToSync = totalBytes - currentOffset
// Only notify if there's significant data (more than 10 seconds worth)
let minBytesThreshold = 80 * 100 * 10 // 80 bytes/frame * 100 fps * 10 seconds
if bytesToSync >= minBytesThreshold {
let mbToSync = Double(bytesToSync) / (1024 * 1024)
logger.info("Device has \(String(format: "%.1f", mbToSync)) MB of audio data pending sync")
// Post notification that storage sync is available
notificationCenter.post(
name: .storageSyncAvailable,
object: nil,
userInfo: ["bytesToSync": bytesToSync]
)
}
}
// MARK: - Firmware Updates
private func checkFirmwareUpdates(generation: UInt64) async {
guard !isFirmwareUpdateInProgress else { return }
guard sessionCoordinator.isReady(generation: generation) else { return }
guard let device = connectedDevice else { return }
// TODO: Implement firmware update check via API
// For now, just log that we would check
logger.debug("Would check firmware updates for \(device.displayName)")
// Example implementation:
// let (hasUpdate, version) = await APIClient.shared.checkFirmwareUpdate(
// modelNumber: device.modelNumber,
// currentFirmware: device.firmwareRevision
// )
// hasFirmwareUpdate = hasUpdate
// latestFirmwareVersion = version
}
/// Set firmware update in progress state
func setFirmwareUpdateInProgress(_ inProgress: Bool) {
isFirmwareUpdateInProgress = inProgress
}
/// Prepare for DFU (firmware update)
func prepareDFU() async {
guard connectedDevice != nil else { return }
await sessionCoordinator.disconnect(reconnectAfter: .seconds(30))
}
// MARK: - Notifications
private func scheduleDisconnectNotification() {
disconnectNotificationTimer?.invalidate()
disconnectNotificationTimer = Timer.scheduledTimer(
withTimeInterval: 30.0,
repeats: false
) { [weak self] _ in
Task { @MainActor in
self?.sendDisconnectNotification()
}
}
}
private func sendDisconnectNotification() {
let content = UNMutableNotificationContent()
content.title = "Your omi Device Disconnected"
content.body = "Please reconnect to continue using your omi."
content.sound = .default
let request = UNNotificationRequest(
identifier: "deviceDisconnected",
content: content,
trigger: nil
)
UNUserNotificationCenter.current().add(request)
}
private func sendFallDetectionNotification(data: AccelerometerData) {
logger.warning("Fall detected! Magnitude: \(data.magnitude)")
let content = UNMutableNotificationContent()
content.title = "Fall Detected"
content.body = "A potential fall was detected by your omi device."
content.sound = .default
let request = UNNotificationRequest(
identifier: "fallDetected-\(Date().timeIntervalSince1970)",
content: content,
trigger: nil
)
UNUserNotificationCenter.current().add(request)
}
// MARK: - Audio Stream
/// Get an audio stream from the connected device
func getAudioStream() -> AsyncThrowingStream<Data, Error>? {
guard let connection = activeConnection else { return nil }
return connection.getAudioStream()
}
/// Get the audio codec of the connected device
func getAudioCodec() async -> BleAudioCodec {
guard let connection = activeConnection else { return .pcm8 }
return await connection.getAudioCodec()
}
// MARK: - Device Features
/// Get the features supported by the connected device
func getFeatures() async -> OmiFeatures {
guard let connection = activeConnection else { return [] }
return await connection.getFeatures()
}
/// Check if the connected device supports WiFi sync
func isWifiSyncSupported() async -> Bool {
guard let connection = activeConnection else { return false }
return await connection.isWifiSyncSupported()
}
// MARK: - Device Settings
/// Set the LED dim ratio (0-100)
func setLedDimRatio(_ ratio: Int) async {
guard let connection = activeConnection else { return }
await connection.setLedDimRatio(ratio)
}
/// Get the LED dim ratio
func getLedDimRatio() async -> Int? {
guard let connection = activeConnection else { return nil }
return await connection.getLedDimRatio()
}
/// Set the microphone gain (0-100)
func setMicGain(_ gain: Int) async {
guard let connection = activeConnection else { return }
await connection.setMicGain(gain)
}
/// Get the microphone gain
func getMicGain() async -> Int? {
guard let connection = activeConnection else { return nil }
return await connection.getMicGain()
}
// MARK: - WiFi Sync
/// Setup WiFi sync with credentials
func setupWifiSync(ssid: String, password: String) async -> WifiSyncSetupResult {
guard let connection = activeConnection else {
return .connectionFailed()
}
return await connection.setupWifiSync(ssid: ssid, password: password)
}
/// Start WiFi sync
func startWifiSync() async -> Bool {
guard let connection = activeConnection else { return false }
return await connection.startWifiSync()
}
/// Stop WiFi sync
func stopWifiSync() async -> Bool {
guard let connection = activeConnection else { return false }
return await connection.stopWifiSync()
}
// MARK: - Button Stream
/// Get a stream of button press events
func getButtonStream() -> AsyncThrowingStream<[UInt8], Error>? {
guard let connection = activeConnection else { return nil }
return connection.getButtonStream()
}
// MARK: - Accelerometer Stream
/// Get a stream of accelerometer data
func getAccelerometerStream() -> AsyncThrowingStream<AccelerometerData, Error>? {
guard let connection = activeConnection else { return nil }
return connection.getAccelerometerStream()
}
// MARK: - Cleanup
deinit {
disconnectNotificationTimer?.invalidate()
batterySubscription?.cancel()
}
}