-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathble_manager.dart
More file actions
382 lines (331 loc) · 11.2 KB
/
ble_manager.dart
File metadata and controls
382 lines (331 loc) · 11.2 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
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:universal_ble/universal_ble.dart';
import '../../open_earable_flutter.dart';
/// A class that establishes and manages Bluetooth Low Energy (BLE)
/// communication with OpenEarable devices.
class BleManager extends BleGattManager {
static const int _desiredMtu = 60;
int _mtu = _desiredMtu; // Largest Byte package sent is 42 bytes for IMU
int get mtu => _mtu;
final Map<String, StreamController<List<int>>> _streamControllers = {};
/// A stream of discovered devices during scanning.
StreamController<DiscoveredDevice>? _scanStreamController;
Stream<DiscoveredDevice> get scanStream => _scanStreamController!.stream;
String _getCharacteristicKey(String deviceId, String characteristicId) =>
"$deviceId||$characteristicId";
final Map<String, Completer> _connectionCompleters = {};
final Map<String, VoidCallback> _connectCallbacks = {};
final Map<String, VoidCallback> _disconnectCallbacks = {};
final List<String> _connectedDevicesIds = [];
bool _firstScan = true;
BleManager() {
_init();
}
@override
bool isConnected(String deviceId) {
return _connectedDevicesIds.contains(deviceId);
}
void _closeAndRemoveStreamsForDevice(String deviceId) {
final prefix = "$deviceId||";
final keys =
_streamControllers.keys.where((key) => key.startsWith(prefix)).toList();
for (final key in keys) {
logger.d("Closing stream for $key due to device disconnection");
_streamControllers.remove(key)?.close();
}
}
void _init() {
_scanStreamController = StreamController<DiscoveredDevice>.broadcast();
UniversalBle.onConnectionChange = (
String deviceId,
bool isConnected,
String? error,
) {
logger.d("Connection change for $deviceId: $isConnected");
if (isConnected) {
_connectedDevicesIds.add(deviceId);
_connectCallbacks[deviceId]?.call();
_connectCallbacks.remove(deviceId);
} else {
_connectedDevicesIds.remove(deviceId);
_closeAndRemoveStreamsForDevice(deviceId);
_disconnectCallbacks[deviceId]?.call();
_disconnectCallbacks.remove(deviceId);
}
};
UniversalBle.onValueChange = (
String deviceId,
String characteristicId,
Uint8List value,
) {
String streamIdentifier =
_getCharacteristicKey(deviceId, characteristicId);
if (!_streamControllers.containsKey(streamIdentifier)) {
return;
}
if (_streamControllers[streamIdentifier] == null) {
logger.w("Stream controller for $streamIdentifier is null");
return;
}
_streamControllers[streamIdentifier]!.add(value);
};
}
static Future<bool> checkAndRequestPermissions() async {
bool permGranted = false;
// Don't run `Platform.is*` on web
if (!kIsWeb && Platform.isAndroid) {
Map<Permission, PermissionStatus> statuses = await [
Permission.bluetoothScan,
Permission.bluetoothConnect,
Permission.location,
].request();
permGranted = (statuses[Permission.bluetoothScan]!.isGranted &&
statuses[Permission.bluetoothConnect]!.isGranted &&
statuses[Permission.location]!.isGranted);
} else {
permGranted = true;
}
return permGranted;
}
static Future<bool> checkPermissions() async {
if (kIsWeb) {
return true; // Permissions are not required on web
}
return await Permission.bluetoothScan.isGranted &&
await Permission.bluetoothConnect.isGranted &&
await Permission.location.isGranted;
}
/// Initiates the BLE device scan to discover nearby Bluetooth devices.
Future<void> startScan({
bool checkAndRequestPermissions = true,
}) async {
bool? permGranted;
if (checkAndRequestPermissions) {
permGranted = await BleManager.checkAndRequestPermissions();
}
if (permGranted == true || !checkAndRequestPermissions) {
// Workaround for iOS, otherwise we need to press the scan button twice for it
for (int i = 0;
i < ((!kIsWeb && Platform.isIOS && _firstScan) ? 2 : 1);
++i) {
if (i == 1) {
await Future.delayed(const Duration(seconds: 1));
}
await UniversalBle.stopScan();
UniversalBle.onScanResult = (bleDevice) {
_scanStreamController?.add(
DiscoveredDevice(
id: bleDevice.deviceId,
name: bleDevice.name ?? "",
manufacturerData:
bleDevice.manufacturerDataList.firstOrNull?.toUint8List() ??
Uint8List.fromList([]),
rssi: bleDevice.rssi ?? -1,
serviceUuids: bleDevice.services,
),
);
};
if (!kIsWeb) {
List<DiscoveredDevice> devices = await getSystemDevices();
for (var device in devices) {
_scanStreamController?.add(device);
}
}
await UniversalBle.startScan();
}
_firstScan = false;
}
}
/// Retrieves a list of system devices.
/// Throws an exception if called on web.
/// If no devices are found, returns an empty list.
/// If the platform is not web, it uses `UniversalBle.getSystemDevices`.
Future<List<DiscoveredDevice>> getSystemDevices({
bool checkAndRequestPermissions = true,
}) async {
if (checkAndRequestPermissions &&
!await BleManager.checkAndRequestPermissions()) {
throw Exception("Permissions not granted");
}
if (kIsWeb) {
throw Exception("getSystemDevices is not supported on web");
}
return UniversalBle.getSystemDevices().then((devices) {
return devices.map((device) {
return DiscoveredDevice(
id: device.deviceId,
name: device.name ?? "",
manufacturerData:
device.manufacturerDataList.firstOrNull?.toUint8List() ??
Uint8List.fromList([]),
rssi: device.rssi ?? -1,
serviceUuids: device.services,
);
}).toList();
});
}
/// Connects to the specified Earable device.
Future<(bool, List<BleService>)> connectToDevice(
DiscoveredDevice device,
VoidCallback onDisconnect,
) {
// Multi-device setup: only reset stale streams for the device that is
// being connected, not globally for all devices.
_closeAndRemoveStreamsForDevice(device.id);
Completer<(bool, List<BleService>)> completer =
Completer<(bool, List<BleService>)>();
_connectionCompleters[device.id] = completer;
_connectCallbacks[device.id] = () async {
if (!kIsWeb && !Platform.isLinux) {
_mtu = await UniversalBle.requestMtu(device.id, _desiredMtu);
}
bool connectionResult = false;
List<BleService> services = [];
services = await UniversalBle.discoverServices(device.id);
connectionResult = true;
_connectionCompleters[device.id]?.complete((connectionResult, services));
_connectionCompleters.remove(device.id);
};
_disconnectCallbacks[device.id] = () {
_connectionCompleters[device.id]?.complete((false, <BleService>[]));
_connectionCompleters.remove(device.id);
onDisconnect();
};
UniversalBle.connect(device.id);
return completer.future;
}
/// Checks if the connected device has a specific service.
@override
Future<bool> hasService({
required String deviceId,
required String serviceId,
}) async {
if (!isConnected(deviceId)) {
throw Exception("Device is not connected");
}
List<BleService> services = await UniversalBle.discoverServices(deviceId);
for (final service in services) {
if (service.uuid.toLowerCase() == serviceId.toLowerCase()) {
return true;
}
}
return false;
}
/// Checks if the connected device has a specific characteristic.
@override
Future<bool> hasCharacteristic({
required String deviceId,
required String serviceId,
required String characteristicId,
}) async {
if (!isConnected(deviceId)) {
throw Exception("Device is not connected");
}
List<BleService> services = await UniversalBle.discoverServices(deviceId);
for (final service in services) {
if (service.uuid.toLowerCase() == serviceId.toLowerCase()) {
for (final characteristic in service.characteristics) {
if (characteristic.uuid.toLowerCase() ==
characteristicId.toLowerCase()) {
return true;
}
}
}
}
return false;
}
/// Writes byte data to a specific characteristic of the connected Earable device.
@override
Future<void> write({
required String deviceId,
required String serviceId,
required String characteristicId,
required List<int> byteData,
}) async {
if (!isConnected(deviceId)) {
throw Exception("Write failed because no Earable is connected");
}
await UniversalBle.write(
deviceId,
serviceId,
characteristicId,
Uint8List.fromList(byteData),
);
}
/// Subscribes to a specific characteristic of the connected Earable device.
@override
Stream<List<int>> subscribe({
required String deviceId,
required String serviceId,
required String characteristicId,
}) {
logger.d(
"Subscribing to $deviceId, service $serviceId, characteristic $characteristicId",
);
String streamIdentifier = _getCharacteristicKey(
deviceId,
characteristicId,
);
StreamController<List<int>>? streamController =
_streamControllers[streamIdentifier];
streamController ??= StreamController<List<int>>.broadcast();
if (!_streamControllers.containsKey(streamIdentifier)) {
UniversalBle.subscribeNotifications(
deviceId,
serviceId,
characteristicId,
);
_streamControllers[streamIdentifier] = streamController;
}
streamController.onCancel = () {
if (_streamControllers.containsKey(streamIdentifier)) {
_streamControllers.remove(streamIdentifier)?.close();
UniversalBle.unsubscribe(
deviceId,
serviceId,
characteristicId,
);
_streamControllers.remove(streamIdentifier);
}
};
return streamController.stream;
}
/// Reads data from a specific characteristic of the connected Earable device.
@override
Future<List<int>> read({
required String deviceId,
required String serviceId,
required String characteristicId,
}) async {
if (!isConnected(deviceId)) {
throw Exception("Read failed because no Earable is connected");
}
final response = await UniversalBle.read(
deviceId,
serviceId,
characteristicId,
);
return response.toList();
}
@override
Future<void> disconnect(String deviceId) {
return UniversalBle.disconnect(deviceId);
}
/// Cancel connection state subscription
void dispose() {
UniversalBle.onConnectionChange = (
String deviceId,
bool isConnected,
String? error,
) {};
UniversalBle.stopScan();
UniversalBle.onScanResult = (_) {};
_scanStreamController?.close();
for (var controller in _streamControllers.values) {
controller.close();
}
}
}