-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathflutter_blue.dart
295 lines (252 loc) · 9.02 KB
/
flutter_blue.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
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
// 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 FlutterBlue {
final MethodChannel _channel = const MethodChannel('$NAMESPACE/methods');
final EventChannel _stateChannel = const EventChannel('$NAMESPACE/state');
final StreamController<MethodCall> _methodStreamController =
new StreamController.broadcast(); // ignore: close_sinks
Stream<MethodCall> get _methodStream => _methodStreamController
.stream; // Used internally to dispatch methods from platform.
/// Singleton boilerplate
FlutterBlue._() {
_channel.setMethodCallHandler((MethodCall call) async {
_methodStreamController.add(call);
});
_setLogLevelIfAvailable();
}
static FlutterBlue _instance = new FlutterBlue._();
static FlutterBlue get instance => _instance;
/// Log level of the instance, default is all messages (debug).
LogLevel _logLevel = LogLevel.debug;
LogLevel get logLevel => _logLevel;
/// Checks whether the device supports Bluetooth
Future<bool> get isAvailable =>
_channel.invokeMethod('isAvailable').then<bool>((d) => d);
/// Checks if Bluetooth functionality is turned on
Future<bool> get isOn => _channel.invokeMethod('isOn').then<bool>((d) => d);
BehaviorSubject<bool> _isScanning = BehaviorSubject.seeded(false);
Stream<bool> get isScanning => _isScanning.stream;
BehaviorSubject<List<ScanResult>> _scanResults = BehaviorSubject.seeded([]);
/// Returns a stream that is a list of [ScanResult] results while a scan is in progress.
///
/// The list emitted is all the scanned results as of the last initiated scan. When a scan is
/// first started, an empty list is emitted. The returned stream is never closed.
///
/// One use for [scanResults] is as the stream in a StreamBuilder to display the
/// results of a scan in real time while the scan is in progress.
Stream<List<ScanResult>> get scanResults => _scanResults.stream;
PublishSubject _stopScanPill = new PublishSubject();
/// Gets the current state of the Bluetooth module
Stream<BluetoothState> get state async* {
yield await _channel
.invokeMethod('state')
.then((buffer) => new protos.BluetoothState.fromBuffer(buffer))
.then((s) => BluetoothState.values[s.state.value]);
yield* _stateChannel
.receiveBroadcastStream()
.map((buffer) => new protos.BluetoothState.fromBuffer(buffer))
.map((s) => BluetoothState.values[s.state.value]);
}
/// Retrieve a list of connected devices
Future<List<BluetoothDevice>> get connectedDevices {
return _channel
.invokeMethod('getConnectedDevices')
.then((buffer) => protos.ConnectedDevicesResponse.fromBuffer(buffer))
.then((p) => p.devices)
.then((p) => p.map((d) => BluetoothDevice.fromProto(d)).toList());
}
_setLogLevelIfAvailable() async {
if (await isAvailable) {
// Send the log level to the underlying platforms.
setLogLevel(logLevel);
}
}
/// Starts a scan for Bluetooth Low Energy devices and returns a stream
/// of the [ScanResult] results as they are received.
///
/// timeout calls stopStream after a specified [Duration].
/// You can also get a list of ongoing results in the [scanResults] stream.
/// If scanning is already in progress, this will throw an [Exception].
Stream<ScanResult> scan({
ScanMode scanMode = ScanMode.lowLatency,
List<Guid> withServices = const [],
List<Guid> withDevices = const [],
Duration? timeout,
bool allowDuplicates = false,
}) async* {
var settings = protos.ScanSettings.create()
..androidScanMode = scanMode.value
..allowDuplicates = allowDuplicates
..serviceUuids.addAll(withServices.map((g) => g.toString()).toList());
if (_isScanning.value == true) {
throw Exception('Another scan is already in progress.');
}
// Emit to isScanning
_isScanning.add(true);
final killStreams = <Stream>[];
killStreams.add(_stopScanPill);
if (timeout != null) {
killStreams.add(Rx.timer(null, timeout));
}
// Clear scan results list
_scanResults.add(<ScanResult>[]);
try {
await _channel.invokeMethod('startScan', settings.writeToBuffer());
} catch (e) {
print('Error starting scan.');
_stopScanPill.add(null);
_isScanning.add(false);
throw e;
}
yield* FlutterBlue.instance._methodStream
.where((m) => m.method == "ScanResult")
.map((m) => m.arguments)
.takeUntil(Rx.merge(killStreams))
.doOnDone(stopScan)
.map((buffer) => new protos.ScanResult.fromBuffer(buffer))
.map((p) {
final result = new ScanResult.fromProto(p);
final list = _scanResults.value ?? [];
int index = list.indexOf(result);
if (index != -1) {
list.removeAt(index);
}
list.add(result);
_scanResults.add(list);
return result;
});
}
/// Starts a scan and returns a future that will complete once the scan has finished.
///
/// Once a scan is started, call [stopScan] to stop the scan and complete the returned future.
///
/// timeout automatically stops the scan after a specified [Duration].
///
/// To observe the results while the scan is in progress, listen to the [scanResults] stream,
/// or call [scan] instead.
Future startScan({
ScanMode scanMode = ScanMode.lowLatency,
List<Guid> withServices = const [],
List<Guid> withDevices = const [],
Duration? timeout,
bool allowDuplicates = false,
}) async {
await scan(
scanMode: scanMode,
withServices: withServices,
withDevices: withDevices,
timeout: timeout,
allowDuplicates: allowDuplicates)
.drain();
return _scanResults.value;
}
/// Stops a scan for Bluetooth Low Energy devices
Future stopScan() async {
await _channel.invokeMethod('stopScan');
_stopScanPill.add(null);
_isScanning.add(false);
}
/// The list of connected peripherals can include those that are connected
/// by other apps and that will need to be connected locally using the
/// device.connect() method before they can be used.
// Stream<List<BluetoothDevice>> connectedDevices({
// List<Guid> withServices = const [],
// }) =>
// throw UnimplementedError();
/// Sets the log level of the FlutterBlue instance
/// Messages equal or below the log level specified are stored/forwarded,
/// messages above are dropped.
void setLogLevel(LogLevel level) async {
await _channel.invokeMethod('setLogLevel', level.index);
_logLevel = level;
}
void _log(LogLevel level, String message) {
if (level.index <= _logLevel.index) {
print(message);
}
}
}
/// Log levels for FlutterBlue
enum LogLevel {
emergency,
alert,
critical,
error,
warning,
notice,
info,
debug,
}
/// State of the bluetooth adapter.
enum BluetoothState {
unknown,
unavailable,
unauthorized,
turningOn,
on,
turningOff,
off
}
class ScanMode {
const ScanMode(this.value);
static const lowPower = const ScanMode(0);
static const balanced = const ScanMode(1);
static const lowLatency = const ScanMode(2);
static const opportunistic = const ScanMode(-1);
final int value;
}
class DeviceIdentifier {
final String id;
const DeviceIdentifier(this.id);
@override
String toString() => id;
@override
int get hashCode => id.hashCode;
@override
bool operator ==(other) =>
other is DeviceIdentifier && compareAsciiLowerCase(id, other.id) == 0;
}
class ScanResult {
ScanResult.fromProto(protos.ScanResult p)
: device = new BluetoothDevice.fromProto(p.device),
advertisementData =
new AdvertisementData.fromProto(p.advertisementData),
rssi = p.rssi;
final BluetoothDevice device;
final AdvertisementData advertisementData;
final int rssi;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is ScanResult &&
runtimeType == other.runtimeType &&
device == other.device;
@override
int get hashCode => device.hashCode;
@override
String toString() {
return 'ScanResult{device: $device, advertisementData: $advertisementData, rssi: $rssi}';
}
}
class AdvertisementData {
final String localName;
final int? txPowerLevel;
final bool connectable;
final Map<int, List<int>> manufacturerData;
final Map<String, List<int>> serviceData;
final List<String> serviceUuids;
AdvertisementData.fromProto(protos.AdvertisementData p)
: localName = p.localName,
txPowerLevel =
(p.txPowerLevel.hasValue()) ? p.txPowerLevel.value : null,
connectable = p.connectable,
manufacturerData = p.manufacturerData,
serviceData = p.serviceData,
serviceUuids = p.serviceUuids;
@override
String toString() {
return 'AdvertisementData{localName: $localName, txPowerLevel: $txPowerLevel, connectable: $connectable, manufacturerData: $manufacturerData, serviceData: $serviceData, serviceUuids: $serviceUuids}';
}
}