flutter reactive ble library
flutter library that handles ble operations for multiple devices.
usage
the reactive ble lib supports the following:
- ble device discovery
- observe host device ble status
- establishing a ble connection
- maintaining connection status of multiple ble devices
- discover services(will be implicit)
- read / write a characteristic
- subscribe to a characteristic
- clear gatt cache
- negotiate mtu size
initialization
initializing the library should be done the following:
final flutterreactiveble = flutterreactiveble();
device discovery
discovering ble devices should be done like this:
flutterreactiveble.scanfordevices(withservices: [serviceid], scanmode: scanmode.lowlatency).listen((device) {
//code for handling results
}, onerror: () {
//code for handling error
});
the withservices
parameter specifies the advertised service ids to look for. if an empty list is passed, all the advertising devices will be reported. the parameter scanmode
is only used on android and follows the conventions described on scansettings android reference page. if scanmode
is omitted the balanced scan mode will be used.
observe host device ble status
use statusstream
to retrieve updates about the ble status of the host device (the device running the app) . this stream can be used in order to determine if the ble is turned on, on the device or if the required permissions are granted. example usage:
_ble.statusstream.listen((status) {
//code for handling status update
});
use _ble.status
to get the current status of the host device.
see blestatus for
more info about the meaning of the different statuses.
establishing connection
to interact with a device you first need to establish a connection:
flutterreactiveble.connecttodevice(
id: founddeviceid,
serviceswithcharacteristicstodiscover: {serviceid: [char1, char2]},
connectiontimeout: const duration(seconds: 2),
).listen((connectionstate) {
// handle connection state updates
}, onerror: (object error) {
// handle a possible error
});
for the required id
parameter use a device id retrieved through device discovery. on ios the device id is a uuid and on android it is a mac address (which may also be randomized, depending on the android version). supplying a map with service and characteristic ids you want to discover may speed up the connection on ios (otherwise all services and characteristics will be discovered). you can specify a connectiontimeout
when the client will provide an error in case the connection cannot be established within the specified time.
there are numerous issues on the android ble stack that leave it hanging when you try to connect to a device that is not in range. to work around this
issue use the method connecttoadvertisingdevice
to first scan for the device and only if it is found connect to it.
flutterreactiveble.connecttoadvertisingdevice(
id: founddeviceid,
withservices: [serviceuuid],
prescanduration: const duration(seconds: 5),
serviceswithcharacteristicstodiscover: {serviceid: [char1, char2]},
connectiontimeout: const duration(seconds: 2),
).listen((connectionstate) {
// handle connection state updates
}, onerror: (dynamic error) {
// handle a possible error
});
besides the normal connection parameters that are described above this function also has 2 additional required parameters: withservices
and prescanduration
. prescanduration is the amount of time the ble stack will scan for the device before it attempts to connect (if the device is found)
read / write characteristics
read characteristic
final characteristic = qualifiedcharacteristic(serviceid: serviceuuid, characteristicid: characteristicuuid, deviceid: founddeviceid);
final response = await flutterreactiveble.readcharacteristic(characteristic);
write with response
write a value to characteristic and await the response. the “response” in “write characteristic with response” means “an acknowledgement of reception”. the write can either be acknowledged (success) or failed (an exception is thrown), thus the return type is void
and there is nothing to print (though you can print("write successful")
and in a catch-clause print("write failed: $e")
).
ble does not provide a request-response mechanism like you may know from http out of the box. if you need to perform request-response calls, you will need to implement a custom mechanism on top of the basic ble functionality. a typical approach is to implement a “control point”: a characteristic that is writable and delivers notifications or indications, so that a request is written to it and a response is delivered back as a notification or an indication.
final characteristic = qualifiedcharacteristic(serviceid: serviceuuid, characteristicid: characteristicuuid, deviceid: founddeviceid);
await flutterreactiveble.writecharacteristicwithresponse(characteristic, value: [0x00]);
write without response
use this operation if you want to execute multiple consecutive write operations in a small timeframe (e.g uploading firmware to device) or if the device does not provide a response. this is performance wise the fastest way of writing a value but there’s a chance that the ble device cannot handle that many consecutive writes in a row, so do a writewithresponse
once in a while.
final characteristic = qualifiedcharacteristic(serviceid: serviceuuid, characteristicid: characteristicuuid, deviceid: founddeviceid);
flutterreactiveble.writecharacteristicwithoutresponse(characteristic, value: [0x00]);
subscribe to characteristic
instead of periodically reading the characteristic you can also listen to the notifications (in case the specific service supports it) in case the value changes.
final characteristic = qualifiedcharacteristic(serviceid: serviceuuid, characteristicid: characteristicuuid, deviceid: founddeviceid);
flutterreactiveble.subscribetocharacteristic(characteristic).listen((data) {
// code to handle incoming data
}, onerror: (dynamic error) {
// code to handle errors
});
negotiate mtu size
you can increase or decrease the mtu size to reach a higher throughput. this operation will return the actual negotiated mtu size, but it is no guarantee that the requested size will be successfully negotiated. ios has a default mtu size which cannot be negotiated, however you can still use this operation to get the current mtu.
final mtu = await flutterreactiveble.requestmtu(deviceid: founddeviceid, mtu: 250);
android specific operations
the following operations will only have effect for android and are not supported by ios. when using these operations on ios the library will throw an unsupportedoperationexception.
request connection priority
on android you can send a connection priority update to the ble device. the parameter priority
is an enum that uses the same spec
as the bluetoothgatt android spec.
using highperformance
will increase battery usage but will speed up gatt operations. be cautious when setting the priority when communicating with multiple devices because if you set highperformance for all devices the effect of increasing the priority will be lower.
await flutterreactiveble.requestconnectionpriority(deviceid: founddeviceid, priority: connectionpriority.highperformance);
clear gatt cache
the android os maintains a table per device of the discovered service in cache. sometimes it happens that after a firmware update a new service is introduced but the cache is not updated. to invalidate the cache you can use the cleargattcache operation.
this is a hidden ble operation and should be used with extreme caution since this operation is on the greylist.
await flutterreactiveble.cleargattcache(founddeviceid);
faq
how to handle the ble undeliverable exception
on android side we use the rxandroidble library of polidea. after migration towards rxjava 2 some of the errors are not routed properly to their listeners and thus this will result in a ble undeliverable exception. the root cause lies in the threading of the android os. as workaround rxjava has a hook where you can set the global errorhandler. for more info see rxjava docs .
a default workaround implementation in the flutter app (needs to be in the java / kotlin part e.g. mainactivity) is shown below. for an example (in java) see polidea rxandroidble sample.
bleexception is coming from polidea rxandroidble, so make sure your application declares the following depedency: implementation "com.polidea.rxandroidble2:rxandroidble:1.11.1"
rxjavaplugins.seterrorhandler { throwable ->
if (throwable is undeliverableexception && throwable.cause is bleexception) {
[email protected] // ignore bleexceptions since we do not have subscriber
}
else {
throw throwable
}
}
which permissions are needed?
android
for android the library uses the following permissions:
- access_fine_location : this permission is needed because old nexus devices need location services in order to provide reliable scan results
- bluetooth : allows apps to connect to a paired bluetooth device
- bluetooth_admin: allows apps to discover and pair bluetooth devices
these permissions are already added in the manifest of the this library and thus should automatically merge
into the manifest of your app. it is not needed to add the permissions in your manifest.
ios
for ios it is required you add the following entries to the info.plist
file of your app. it is not allowed to access core bluetooth without this. see our example app on how to implement this. for more indepth details: blog post on ios bluetooth permissions
ios13 and higher
- nsbluetoothalwaysusagedescription
ios12 and lower
- nsbluetoothperipheralusagedescription
how to adjust proguard (android)
in case you are using proguard add the following snippet to your proguard-rules.pro
file:
-keep class com.signify.hue.** { *; }
this will prevent issues like #131.
why doesn’t the ble stack directly connect to my peripheral
before you are able to execute ble operations the ble-stack of the device makes sure everything is setup correctly and then reports ready for operation. for some devices this takes a bit longer than for others. when starting the app make sure that the ble-stack is properly initialized before you execute ble operations. the safest way to do this is by listening to the statusstream
and wait for blestatus.ready
.
this will prevent issues like #147.
unofficial example apps
example implementation uart over ble:link
Comments are closed.