forked from pauldemarco/flutter_blue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflutter_blue.dart
203 lines (174 loc) · 5.94 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
// 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 EventChannel _scanResultChannel =
const EventChannel('$NAMESPACE/scanResult');
final EventChannel _servicesDiscoveredChannel =
const EventChannel('$NAMESPACE/servicesDiscovered');
final EventChannel _characteristicReadChannel =
const EventChannel('$NAMESPACE/characteristicRead');
final EventChannel _descriptorReadChannel =
const EventChannel('$NAMESPACE/descriptorRead');
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) {
_methodStreamController.add(call);
});
// Send the log level to the underlying platforms.
setLogLevel(logLevel);
}
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);
/// Gets the current state of the Bluetooth module
Future<BluetoothState> get state {
return _channel
.invokeMethod('state')
.then((buffer) => new protos.BluetoothState.fromBuffer(buffer))
.then((s) => BluetoothState.values[s.state.value]);
}
/// Occurs when the bluetooth state has changed
Stream<BluetoothState> onStateChanged() {
return _stateChannel
.receiveBroadcastStream()
.map((buffer) => new protos.BluetoothState.fromBuffer(buffer))
.map((s) => BluetoothState.values[s.state.value]);
}
/// Starts a scan for Bluetooth Low Energy devices
/// Timeout closes the stream after a specified [Duration]
Stream<ScanResult> scan({
ScanMode scanMode = ScanMode.lowLatency,
List<Guid> withServices = const [],
List<Guid> withDevices = const [],
Duration timeout,
}) async* {
var settings = protos.ScanSettings.create()
..androidScanMode = scanMode.value
..serviceUuids.addAll(withServices.map((g) => g.toString()).toList());
StreamSubscription subscription;
StreamController controller;
controller = new StreamController(
onListen: () {
if (timeout != null) {
new Future.delayed(timeout, () => controller.close());
}
},
onCancel: () {
_stopScan();
subscription.cancel();
},
);
await _channel.invokeMethod('startScan', settings.writeToBuffer());
subscription = _scanResultChannel.receiveBroadcastStream().listen(
controller.add,
onError: controller.addError,
onDone: controller.close,
);
yield* controller.stream
.map((buffer) => new protos.ScanResult.fromBuffer(buffer))
.map((p) => new ScanResult.fromProto(p));
}
/// Stops a scan for Bluetooth Low Energy devices
Future _stopScan() => _channel.invokeMethod('stopScan');
/// 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 {
const ScanResult({this.device, this.advertisementData, this.rssi});
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;
}
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(
{this.localName,
this.txPowerLevel,
this.connectable,
this.manufacturerData,
this.serviceData,
this.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;
}