forked from pauldemarco/flutter_blue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth_characteristic.dart
220 lines (195 loc) · 8.15 KB
/
bluetooth_characteristic.dart
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
// Copyright 2017, Paul DeMarco.
// All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
part of flutter_blue;
class BluetoothCharacteristic {
final Guid uuid;
final DeviceIdentifier deviceId;
final Guid serviceUuid;
final Guid? secondaryServiceUuid;
final CharacteristicProperties properties;
final List<BluetoothDescriptor> descriptors;
bool get isNotifying {
try {
var cccd =
descriptors.singleWhere((d) => d.uuid == BluetoothDescriptor.cccd);
return ((cccd.lastValue[0] & 0x01) > 0 || (cccd.lastValue[0] & 0x02) > 0);
} catch (e) {
return false;
}
}
BehaviorSubject<List<int>> _value;
Stream<List<int>> get value => Rx.merge([
_value.stream,
_onValueChangedStream,
]);
List<int> get lastValue => _value.value ?? [];
BluetoothCharacteristic.fromProto(protos.BluetoothCharacteristic p)
: uuid = new Guid(p.uuid),
deviceId = new DeviceIdentifier(p.remoteId),
serviceUuid = new Guid(p.serviceUuid),
secondaryServiceUuid = (p.secondaryServiceUuid.length > 0)
? new Guid(p.secondaryServiceUuid)
: null,
descriptors = p.descriptors
.map((d) => new BluetoothDescriptor.fromProto(d))
.toList(),
properties = new CharacteristicProperties.fromProto(p.properties),
_value = BehaviorSubject.seeded(p.value);
Stream<BluetoothCharacteristic> get _onCharacteristicChangedStream =>
FlutterBlue.instance._methodStream
.where((m) => m.method == "OnCharacteristicChanged")
.map((m) => m.arguments)
.map(
(buffer) => new protos.OnCharacteristicChanged.fromBuffer(buffer))
.where((p) => p.remoteId == deviceId.toString())
.map((p) => new BluetoothCharacteristic.fromProto(p.characteristic))
.where((c) => c.uuid == uuid)
.map((c) {
// Update the characteristic with the new values
_updateDescriptors(c.descriptors);
return c;
});
Stream<List<int>> get _onValueChangedStream =>
_onCharacteristicChangedStream.map((c) => c.lastValue);
void _updateDescriptors(List<BluetoothDescriptor> newDescriptors) {
for (var d in descriptors) {
for (var newD in newDescriptors) {
if (d.uuid == newD.uuid) {
d._value.add(newD.lastValue);
}
}
}
}
/// Retrieves the value of the characteristic
Future<List<int>> read() async {
var request = protos.ReadCharacteristicRequest.create()
..remoteId = deviceId.toString()
..characteristicUuid = uuid.toString()
..serviceUuid = serviceUuid.toString();
FlutterBlue.instance._log(LogLevel.info,
'remoteId: ${deviceId.toString()} characteristicUuid: ${uuid.toString()} serviceUuid: ${serviceUuid.toString()}');
await FlutterBlue.instance._channel
.invokeMethod('readCharacteristic', request.writeToBuffer());
return FlutterBlue.instance._methodStream
.where((m) => m.method == "ReadCharacteristicResponse")
.map((m) => m.arguments)
.map((buffer) =>
new protos.ReadCharacteristicResponse.fromBuffer(buffer))
.where((p) =>
(p.remoteId == request.remoteId) &&
(p.characteristic.uuid == request.characteristicUuid) &&
(p.characteristic.serviceUuid == request.serviceUuid))
.map((p) => p.characteristic.value)
.first
.then((d) {
_value.add(d);
return d;
});
}
/// Writes the value of a characteristic.
/// [CharacteristicWriteType.withoutResponse]: the write is not
/// guaranteed and will return immediately with success.
/// [CharacteristicWriteType.withResponse]: the method will return after the
/// write operation has either passed or failed.
Future<Null> write(List<int> value, {bool withoutResponse = false}) async {
final type = withoutResponse
? CharacteristicWriteType.withoutResponse
: CharacteristicWriteType.withResponse;
var request = protos.WriteCharacteristicRequest.create()
..remoteId = deviceId.toString()
..characteristicUuid = uuid.toString()
..serviceUuid = serviceUuid.toString()
..writeType =
protos.WriteCharacteristicRequest_WriteType.valueOf(type.index)!
..value = value;
var result = await FlutterBlue.instance._channel
.invokeMethod('writeCharacteristic', request.writeToBuffer());
if (type == CharacteristicWriteType.withoutResponse) {
return result;
}
return FlutterBlue.instance._methodStream
.where((m) => m.method == "WriteCharacteristicResponse")
.map((m) => m.arguments)
.map((buffer) =>
new protos.WriteCharacteristicResponse.fromBuffer(buffer))
.where((p) =>
(p.request.remoteId == request.remoteId) &&
(p.request.characteristicUuid == request.characteristicUuid) &&
(p.request.serviceUuid == request.serviceUuid))
.first
.then((w) => w.success)
.then((success) => (!success)
? throw new Exception('Failed to write the characteristic')
: null)
.then((_) => null);
}
/// Sets notifications or indications for the value of a specified characteristic
Future<bool> setNotifyValue(bool notify) async {
var request = protos.SetNotificationRequest.create()
..remoteId = deviceId.toString()
..serviceUuid = serviceUuid.toString()
..characteristicUuid = uuid.toString()
..enable = notify;
await FlutterBlue.instance._channel
.invokeMethod('setNotification', request.writeToBuffer());
return FlutterBlue.instance._methodStream
.where((m) => m.method == "SetNotificationResponse")
.map((m) => m.arguments)
.map((buffer) => new protos.SetNotificationResponse.fromBuffer(buffer))
.where((p) =>
(p.remoteId == request.remoteId) &&
(p.characteristic.uuid == request.characteristicUuid) &&
(p.characteristic.serviceUuid == request.serviceUuid))
.first
.then((p) => new BluetoothCharacteristic.fromProto(p.characteristic))
.then((c) {
_updateDescriptors(c.descriptors);
return (c.isNotifying == notify);
});
}
@override
String toString() {
return 'BluetoothCharacteristic{uuid: $uuid, deviceId: $deviceId, serviceUuid: $serviceUuid, secondaryServiceUuid: $secondaryServiceUuid, properties: $properties, descriptors: $descriptors, value: ${_value.value}';
}
}
enum CharacteristicWriteType { withResponse, withoutResponse }
@immutable
class CharacteristicProperties {
final bool broadcast;
final bool read;
final bool writeWithoutResponse;
final bool write;
final bool notify;
final bool indicate;
final bool authenticatedSignedWrites;
final bool extendedProperties;
final bool notifyEncryptionRequired;
final bool indicateEncryptionRequired;
CharacteristicProperties(
{this.broadcast = false,
this.read = false,
this.writeWithoutResponse = false,
this.write = false,
this.notify = false,
this.indicate = false,
this.authenticatedSignedWrites = false,
this.extendedProperties = false,
this.notifyEncryptionRequired = false,
this.indicateEncryptionRequired = false});
CharacteristicProperties.fromProto(protos.CharacteristicProperties p)
: broadcast = p.broadcast,
read = p.read,
writeWithoutResponse = p.writeWithoutResponse,
write = p.write,
notify = p.notify,
indicate = p.indicate,
authenticatedSignedWrites = p.authenticatedSignedWrites,
extendedProperties = p.extendedProperties,
notifyEncryptionRequired = p.notifyEncryptionRequired,
indicateEncryptionRequired = p.indicateEncryptionRequired;
@override
String toString() {
return 'CharacteristicProperties{broadcast: $broadcast, read: $read, writeWithoutResponse: $writeWithoutResponse, write: $write, notify: $notify, indicate: $indicate, authenticatedSignedWrites: $authenticatedSignedWrites, extendedProperties: $extendedProperties, notifyEncryptionRequired: $notifyEncryptionRequired, indicateEncryptionRequired: $indicateEncryptionRequired}';
}
}