forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevices.dart
More file actions
327 lines (278 loc) · 10.1 KB
/
Copy pathdevices.dart
File metadata and controls
327 lines (278 loc) · 10.1 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
import 'dart:async';
import 'package:collection/collection.dart';
import 'package:omi/backend/preferences.dart';
import 'package:omi/backend/schema/bt_device/bt_device.dart';
import 'package:omi/services/devices/connectors/device_connection.dart';
import 'package:omi/services/devices/discovery/apple_watch_discoverer.dart';
import 'package:omi/services/devices/discovery/rayban_meta_discoverer.dart';
import 'package:omi/services/devices/discovery/device_discoverer.dart';
import 'package:omi/services/devices/discovery/native_bluetooth_discoverer.dart';
import 'package:omi/utils/debug_log_manager.dart';
import 'package:omi/utils/logger.dart';
import 'package:omi/utils/mutex.dart';
enum DeviceServiceStatus { init, ready, scanning, stop }
enum DeviceConnectionState { connected, connecting, disconnected }
/// Feature flags for Omi device capabilities
/// Must match the firmware definitions in features.h
class OmiFeatures {
static const int speaker = 1 << 0;
static const int accelerometer = 1 << 1;
static const int button = 1 << 2;
static const int battery = 1 << 3;
static const int usb = 1 << 4;
static const int haptic = 1 << 5;
static const int offlineStorage = 1 << 6;
static const int ledDimming = 1 << 7;
static const int micGain = 1 << 8;
}
abstract class IDeviceServiceSubsciption {
void onDevices(List<BtDevice> devices);
void onStatusChanged(DeviceServiceStatus status);
void onDeviceConnectionStateChanged(
String deviceId,
DeviceConnectionState state,
);
}
class DeviceService {
DeviceServiceStatus _status = DeviceServiceStatus.init;
List<BtDevice> _devices = [];
Future<void>? _activeDiscovery;
Future<void>? _queuedDiscovery;
final List<DeviceDiscoverer> _discoverers = [
NativeBluetoothDiscoverer(),
AppleWatchDiscoverer(),
RayBanMetaDiscoverer(),
];
final Map<Object, IDeviceServiceSubsciption> _subscriptions = {};
DeviceConnection? _connection;
DeviceConnection? get connection => _connection;
List<BtDevice> get devices => _devices;
DeviceServiceStatus get status => _status;
DateTime? _firstConnectedAt;
/// Runs one follow-up scan when a caller retries while the current scan is
/// still winding down. In particular, this makes the Bluetooth-enable
/// recovery action reliable instead of silently returning while a blocked
/// scan still owns the service.
Future<void> discover({String? desirableDeviceId, int timeout = 5}) {
if (_queuedDiscovery != null) return _queuedDiscovery!;
if (_status == DeviceServiceStatus.scanning) {
final activeDiscovery = _activeDiscovery;
if (activeDiscovery == null) return Future.value();
return _queuedDiscovery ??= activeDiscovery.then<void>(
(_) => _runQueuedDiscovery(desirableDeviceId: desirableDeviceId, timeout: timeout),
onError: (_, __) => _runQueuedDiscovery(desirableDeviceId: desirableDeviceId, timeout: timeout),
);
}
if (_status != DeviceServiceStatus.ready) {
Logger.debug('Device service is not ready, may busying or stop');
return Future.value();
}
return _discover(desirableDeviceId: desirableDeviceId, timeout: timeout);
}
Future<void> _runQueuedDiscovery({String? desirableDeviceId, required int timeout}) async {
_queuedDiscovery = null;
await discover(desirableDeviceId: desirableDeviceId, timeout: timeout);
}
Future<void> _discover({String? desirableDeviceId, required int timeout}) async {
Logger.debug("Device discovering...");
final completion = Completer<void>();
_activeDiscovery = completion.future;
_status = DeviceServiceStatus.scanning;
try {
final discoveredDevices = <BtDevice>[];
final supportedDiscoverers = _discoverers.where((d) => d.isSupported).toList();
final discoveryFutures = supportedDiscoverers.map((d) async {
try {
final result = await d.discover(timeout: timeout);
return result.devices;
} catch (e, st) {
Logger.debug('Discovery failed for ${d.name}: $e');
Logger.debug('$st');
return <BtDevice>[];
}
});
// Wait for all discoveries to complete
final results = await Future.wait(discoveryFutures);
// Combine all discovered devices
for (final devices in results) {
discoveredDevices.addAll(devices);
}
_devices = discoveredDevices;
onDevices(devices);
if (desirableDeviceId != null && desirableDeviceId.isNotEmpty) {
await ensureConnection(desirableDeviceId, force: true);
}
} finally {
_status = DeviceServiceStatus.ready;
if (!completion.isCompleted) completion.complete();
_activeDiscovery = null;
}
}
Future<void> _connectToDevice(String id) async {
// Clean up existing connection — disconnect if active, then dispose transport
if (_connection != null) {
if (_connection!.status == DeviceConnectionState.connected) {
await _connection!.disconnect();
}
await _connection!.transport.dispose();
}
_connection = null;
var device = _devices.firstWhereOrNull((f) => f.id == id);
Logger.debug(
'[DeviceService] device lookup result: ${device?.name ?? "NULL"} (locator: ${device?.locator?.kind})',
);
// If device not in discovered list, try to get it from SharedPreferences
// This allows background reconnection without scanning
if (device == null) {
Logger.debug(
'[DeviceService] Device not in discovered list, checking stored device',
);
device = _getStoredDevice(id);
if (device != null) {
Logger.debug('[DeviceService] Using stored device: ${device.name}');
if (!_devices.any((d) => d.id == device!.id)) {
_devices.add(device);
}
} else {
Logger.debug(
'[DeviceService] No stored device available for $id, returning',
);
return;
}
}
_connection = DeviceConnectionFactory.create(device);
if (_connection != null) {
await _connection!.connect(
onConnectionStateChanged: onDeviceConnectionStateChanged,
);
} else {
Logger.debug(
'[DeviceService] Failed to create device connection for ${device.id}',
);
}
}
void subscribe(IDeviceServiceSubsciption subscription, Object context) {
_subscriptions.remove(context.hashCode);
_subscriptions.putIfAbsent(context.hashCode, () => subscription);
// Retains
subscription.onDevices(_devices);
subscription.onStatusChanged(_status);
}
void unsubscribe(Object context) {
_subscriptions.remove(context.hashCode);
}
void start() {
_status = DeviceServiceStatus.ready;
// TODO: Start watchdog to discover automatically, re-connect automatically
}
void stop() {
_status = DeviceServiceStatus.stop;
onStatusChanged(_status);
// Stop all discoverers to prevent resource leaks and battery drain
for (final discoverer in _discoverers) {
discoverer.stop();
}
_subscriptions.clear();
_devices.clear();
}
void onStatusChanged(DeviceServiceStatus status) {
for (var s in _subscriptions.values) {
s.onStatusChanged(status);
}
}
void onDeviceConnectionStateChanged(
String deviceId,
DeviceConnectionState state,
) {
Logger.debug("device connection state changed...$deviceId...$state");
DebugLogManager.logEvent('device_connection_state', {
'device_id': deviceId,
'state': state.name,
});
for (var s in _subscriptions.values) {
s.onDeviceConnectionStateChanged(deviceId, state);
}
}
void onDevices(List<BtDevice> devices) {
for (var s in _subscriptions.values) {
s.onDevices(devices);
}
}
final Mutex _mutex = Mutex();
Future<DeviceConnection?> ensureConnection(
String deviceId, {
bool force = false,
}) async {
await _mutex.acquire();
try {
Logger.debug(
"ensureConnection ${_connection?.device.id} ${_connection?.status} $force",
);
// Connected to this device — return it
if (_connection?.device.id == deviceId && _connection?.status == DeviceConnectionState.connected) {
return _connection;
}
// Transport exists for this device but disconnected — native handles reconnection.
// Don't dispose and recreate the transport; that would cancel native's auto-reconnect.
// But if force=true (user-initiated), reconnect explicitly.
if (!force && _connection?.device.id == deviceId) {
return null;
}
// No connection or different device — only connect on force (user-initiated)
if (!force) return null;
try {
await _connectToDevice(deviceId);
} on DeviceConnectionException catch (e) {
Logger.debug(e.cause);
return null;
}
_firstConnectedAt ??= DateTime.now();
return _connection;
} finally {
_mutex.release();
}
}
DateTime? getFirstConnectedAt() {
return _firstConnectedAt;
}
// Helper method to get stored device from SharedPreferences
BtDevice? _getStoredDevice(String id) {
try {
final storedDevice = SharedPreferencesUtil().btDevice;
if (storedDevice.id == id && storedDevice.id.isNotEmpty) {
return storedDevice;
}
} catch (e) {
Logger.debug('Error getting stored device: $e');
}
return null;
}
Future<void> disconnectDevice() async {
if (_connection != null) {
Logger.debug("DeviceService: Disconnecting device...");
await _connection?.disconnect();
_connection = null;
}
}
Future<void> forgetDevice(String deviceId) async {
Logger.debug("DeviceService: Forgetting device $deviceId");
if (_connection != null) {
if (_connection!.status == DeviceConnectionState.connected) {
try {
await _connection!.disconnect();
} catch (e) {
Logger.debug("DeviceService: disconnect during forget failed: $e");
}
}
try {
await _connection!.transport.dispose();
} catch (e) {
Logger.debug(
"DeviceService: transport dispose during forget failed: $e",
);
}
_connection = null;
}
_devices.removeWhere((d) => d.id == deviceId);
}
}