How to code Bluetooth Low Energy device with React-Native

At Polidea we work extensively with Bluetooth Low Energy devices, and we care how well they cooperate with our mobile apps. Therefore we decided to create dedicated ReactiveX based libraries for iOS and Android which allows user to highly reduce their implementation boilerplate required by native stacks. They are RxBluetoothKit and RxAndroidBLE. However our work is not done yet, because there is a new player on a field. React Native is a framework developed by Facebook which lets you build mobile apps using only JavaScript language. So here come our first-(but not last )-born React-Native library.

Motivation & design

Our new library is called react-native-ble-plx and has been developed to work with BLE devices on your pure JavaScript mobile apps. Its implementation is based on previously mentioned RxBluetoothKit and RxAndroidBLE libraries. That allows all platform specific issues to be solved by separate teams and the effort required to to do so is not doubled. Additionally due to Rx composability and great centralized error handling mechanisms, react-native-ble-plx implementation takes very little time, which can allow us to reduce the number of bugs resulting in a greater confidence about the overall correctness of the code.

As the current state of the following API is not yet stable, we decided to not support RxJS and use Promises instead. This approach carry few advantages. First, we don’t require any external dependencies. Second, the use of Promises is very straightforward for new users. Furthermore lays a technical reason, which is a direct limitation of bridging values between JS interpreter and native modules. We can only pass basic types such as numbers, strings, arrays and object and use oneshot callbacks or events for broadcasting. In consequence these restrictions forced us to use Promises, pass UUIDs as strings and values in Base64 format, which is not ideal, but still working.

API overview

Detailed information about the configuration, installation, and all API calls can be found on the project’s GitHub page. There are two categories of API definitions which are currently used :

  • Asynchronous promises which when fulfilled return newly created object with utility functions which allows chaining of operations and when rejected return error describing a reason. Additionally in some functions optional transactionId parameter is passed which allows user to cancel a promise by using cancelTransaction method.
  • Callback based calls, which accepts listeners in a form of (error, result). When error is not null, value is guaranteed to be defined and other way around. Such API functions return subscription object which can cancel observation of stream of values by calling remove() on it. When error is emitted to listener it's automatically unsubscribed. Some API calls of that kind can accept transactionId parameter as well.

All of functions are defined in BleManager object which has to be imported and created before use:

Most of values returned by API calls are in a form of an object. For example a characteristic is defined as follows:

It’s worth to notice that there are utility functions included in each object which have partially filled parameters. All four methods below do the same thing:

Last thing which is crucial to know before moving to an example is that all errors are bubbled from most basic calls to most specific calls. For example an error that device was disconnected will be propagated also to read call if it’s not finished yet. That way user will not need to cancel any promise manually when such situation takes place.

Example

As an example we will present parts of a very simple program which connects to TI CC2541 SensorTag and reads all value changes from temperature, accelerometer, humidity, magnetometer, barometer and gyroscope sensors. For each of them there are two characteristics: one for enabling sensors and one for reading values.

As a initial step we create BleManager object and component state, which will store additional information in text form and hashmap of sensor's current values. Utility functions will help with updating them:

First of all we need to wait for BLE stack to init properly. This step is required on iOS if we want to use it very early. After this event scanning is triggered and we are searching for sensor tag device:

Function scanAndConnect uses promises to chain multiple asynchronous operations and handle potential error in one place for convenience. We are scanning without applying any service UUID filters and looking for devices called "SensorTag". As it's not the most bulletproof solution it will be sufficient for this example. When device is found, scanning is stopped and we try to connect to it, discover characteristics and setup notifications.

Function setupNotifications is implemented as a promise. It's role is to enable notifications for specified sensor by writing value of 0x01 to configuration characteristic. After write is completed sensor is activated and ready for listening to it's values:

Lastly, we need rendering code to see our results:

And this is only a beginning. At Polidea, we are now actively involving ourselves in the React-Native movement. We believe this piece of tech to become preponderant within the years to come and want to take a pole position of React-Native specialist. Stay tuned for more open-source projects involving React-Native…


Originally published at www.polidea.com By Przemek Lenart

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.