flutterblelib
a library for all your bluetooth low energy needs in flutter. internally utilises polidea’s
multiplatformbleadapter,
which runs on rxandroidble
and rxbluetoothkit.
ble simulator
this library supports blemulator, the ble simulator.
the simulation allows one to develop without physical smartphone or ble peripheral and use one’s production ble–related code in automated testing.
installation
to use this plugin, add flutter_ble_lib
as a dependency in your pubspec.yaml file.
android
set minsdkversion
in [project]/android/app/build.gradle
file to 18.
defaultconfig {
...
minsdkversion 18
...
}
support for bluetooth low energy has been added in api 18, hence the library requires minsdkversion
to be set to 18. if ble is not core to your application, you can override it and handle support detection in your code.
notice: you don’t need to add any permissions related to ble to the androidmanifest.xml
, because they are already declared in the library’s native module. however, you still need to request access_fine_location
permission at runtime to be able to scan for peripheral. see example’s code and example’s pubspec.
ios
go to [project]/ios
directory and run pod install
.
add privacy – bluetooth always usage description key to [project]/ios/runner/info.plist
file.
...
<key>nsbluetoothalwaysusagedescription</key>
<string>your own description of the purpose.</string>
...
background mode
to support background capabilities add the bluetooth-central
background execution mode key to [project]/ios/runner/info.plist
file.
...
<key>uibackgroundmodes</key>
<array>
<string>bluetooth-central</string>
</array>
...
usage
the library is organised around a few base entities, which are:
- blemanager
- peripheral
- service
- characteristic
- descriptor
you have to create an instance blemanager and initialise underlying native resources.
using that instance you then obtain an instance of peripheral,
which can be used to run operations on the corresponding peripheral.
all operations passing the dart-native bridge are asynchronous,
hence all operations in the plugin return either future or stream.
for more informations, see reference.
notice: this library will not handle any permissions for you. to be able to scan for peripherals on android you need access_fine_location
according to android developer guide.
initialising
blemanager blemanager = blemanager();
await blemanager.createclient(); //ready to go!
// your peripheral logic
blemanager.destroyclient(); //remember to release native resources when you're done!
following snippets assume the library has been initialised.
handling bluetooth adapter state
enum bluetoothstate {
unknown,
unsupported,
unauthorized,
powered_on,
powered_off,
resetting,
}
blemanager.enableradio(); //android-only turns on bt. note: doesn't check permissions
blemanager.disableradio() //android-only turns off bt. note: doesn't check permissions
bluetoothstate currentstate = await blemanager.bluetoothstate();
blemanager.observebluetoothstate().listen((btstate) {
print(btstate);
//do your bt logic, open different screen, etc.
});
scanning for peripherals
blemanager.startperipheralscan(
uuids: [
"f000aa00-0451-4000-b000-000000000000",
],
).listen((scanresult) {
//scan one peripheral and stop scanning
print("scanned peripheral ${scanresult.peripheral.name}, rssi ${scanresult.rssi}");
blemanager.stopperipheralscan();
});
the snippet above starts peripheral scan and stops it after receiving first result.
it filters the scan results to those that advertise a service with specified uuid.
note: isconnectable
and overflowserviceuuids
fields of scanresult
are ios-only and remain null
on android.
connecting to saved peripheral
you can try to connect to a peripheral with known id, be it previously scanned uuid on ios or a mac address on android, and avoid the whole scanning operation in your application. to do so, you need to create an instance of peripheral
using:
peripheral myperipheral = blemanager.createunsafeperipheral("< known id >");
once you have the instance of the peripheral, you may proceed with the connection. but keep in mind
that android may still not find the peripheral without scanning it first.
connecting to peripheral
first you must obtain a scanresult from blemanager.startperipheralscan().
peripheral peripheral = scanresult.peripheral;
peripheral.observeconnectionstate(emitcurrentvalue: true, completeondisconnect: true)
.listen((connectionstate) {
print("peripheral ${scanresult.peripheral.identifier} connection state is $connectionstate");
});
await peripheral.connect();
bool connected = await peripheral.isconnected();
await peripheral.disconnectorcancelconnection();
the snippet above starts observing the state of the connection to the peripheral,
connects to it, checks if it’s connected and then disconnects from it.
transactions
methods that do not have counterpart with opposite effect and are asynchronous accept
string transactionid
as an optional argument, to allow the user to cancel such an operation.
the future returned to dart will then finish with a bleerror(bleerrorcode.operationcancelled…),
but this will only discard the result of the operation, the operation itself will be executed either way.
for example, if i decided that i no longer want to run discovery on the selected peripheral:
//assuming peripheral is connected
peripheral.discoverallservicesandcharacteristics(transactionid: "discovery");
//will return operation cancelled error after calling the below
blemanager.canceltransaction("discovery");
each new operation with the same transactionid will cause the previous one to be cancelled with error, if it hasn’t finished yet.
if transactionid is set to null or it isn’t specified at all, the library sets unique integer transactionid to such operation.
note:
do not to set integers as transactionid as they are used by the library.
obtaining characteristics
to be able to operate on the peripheral, discovery of its services and characteristics must be run first.
//assuming peripheral is connected
await peripheral.discoverallservicesandcharacteristics();
list<service> services = await peripheral.services(); //getting all services
list<characteristic> characteristics1 = await peripheral.characteristics("f000aa00-0451-4000-b000-000000000000");
list<characteristic> characteristics2 = await services.firstwhere(
(service) => service.uuid == "f000aa00-0451-4000-b000-000000000000").characteristics();
//characteristics1 and characteristics2 have the same contents
objects representing characteristics have a unique identifer, so they point to one specific characteristic,
even if there are multiple service/characteristic uuid matches.
manipulating characteristics
below are 3 methods of writing to a characteristic, which all result in the same effect given
there’s only one service with specified uuid and only one characteristic with specified uuid.
peripheral.writecharacteristic(
"f000aa00-0451-4000-b000-000000000000",
"f000aa02-0451-4000-b000-000000000000",
uint8list.fromlist([0]),
false); //returns characteristic to chain operations more easily
service.writecharacteristic(
"f000aa02-0451-4000-b000-000000000000",
uint8list.fromlist([0]),
false); //returns characteristic to chain operations more easily
characteristic.write(uint8list.fromlist([0]), false); //returns void
monitoring or reading a characteristic from peripheral/service level
return characteristicwithvalue object, which is characteristic with additional uint8list value
property.
descriptor operations
list of descriptors from a single characteristic can be obtained in a similar fashion to a list of characteristics from a single service, either from peripheral, service or characteristic object.
descriptors can be read/written from peripheral, service or characteristic by supplying necessary uuids, or from descriptor object.
note: to enable monitoring of characteristic you should use characteristic.monitor()
or (peripheral/service).monitorcharacteristic()
instead of changing the value of the underlying descriptor yourself.
facilitated by frontside
frontside provided architectural advice and financial support for this library on behalf of resideo.
maintained by
this library is maintained by polidea
learn more about polidea’s ble services.
maintainers
tbd
license
copyright 2019 polidea sp. z o.o
licensed under the apache license, version 2.0 (the “license”);
you may not use this file except in compliance with the license.
you may obtain a copy of the license at
http://www.apache.org/licenses/license-2.0
unless required by applicable law or agreed to in writing, software
distributed under the license is distributed on an “as is” basis,
without warranties or conditions of any kind, either express or implied.
see the license for the specific language governing permissions and
limitations under the license.
more from polidea
check out other polidea’s ble libraries:
Comments are closed.