-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathng_command_state.dart
More file actions
65 lines (55 loc) · 1.64 KB
/
Copy pathng_command_state.dart
File metadata and controls
65 lines (55 loc) · 1.64 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
import 'dart:async';
import 'dart:typed_data';
import 'package:badgemagic/others/globals.dart';
import 'package:universal_ble/universal_ble.dart';
import 'base_ble_state.dart';
import 'completed_state.dart';
class NgCommandState extends NormalBleState {
final BleDevice device;
final List<int> command;
NgCommandState({required this.device, required this.command});
@override
Future<BleState?> processState() async {
final deviceId = device.deviceId;
final completer = Completer<int>();
await UniversalBle.discoverServices(deviceId);
await UniversalBle.setNotifiable(
deviceId,
ngServiceUuid,
ngNotifyCharUuid,
BleInputProperty.notification,
);
late final StreamSubscription sub;
sub = UniversalBle.characteristicValueStream(deviceId, ngNotifyCharUuid)
.listen(
(Uint8List value) {
if (!completer.isCompleted) {
completer.complete(value.isNotEmpty ? value[0] : 0xff);
}
},
onError: (error) {
if (!completer.isCompleted) {
completer.completeError(error);
}
},
);
try {
await UniversalBle.write(
deviceId,
ngServiceUuid,
ngWriteCharUuid,
Uint8List.fromList(command),
withoutResponse: false,
);
final code = await completer.future.timeout(const Duration(seconds: 5));
if (code != 0x00) {
throw Exception(
"Command rejected by badge (code 0x${code.toRadixString(16)})");
}
return CompletedState(
isSuccess: true, message: "Command executed", isNextGen: true);
} finally {
await sub.cancel();
}
}
}