Share

engineering

6min read

How to code Bluetooth Low Energy device with React-Native

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 Bluetooth Low Energy library.

Motivation & design

Our new React Native BLE 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, the implementation of this React Native Bluetooth Low Energy library 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.

Check if React Native
is the right tech for your project

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:

import { BleManager } from "react-native-ble-plx"
// ...
const manager = new BleManager()

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

{
    "uuid": string,                         // Characteristic UUID
    "serviceUUID": string,                  // Service UUID which owns this characteristic
    "deviceUUID": string,                   // Device identifier which owns this characteristic
    "isReadable": boolean,                  // Is characteristic readable
    "isWriteableWithResponse": boolean,     // Is characteristic writeable when writing with response
    "isWriteableWithoutResponse": boolean,  // Is characteristic writeable when writing without response
    "isNotifiable": boolean,                // Is characteristic notifiable
    "isNotifying": boolean,                 // Current status of notification for this characteristic
    "isIndictable": boolean,                // Is characteristic indictable
    "value": string,                        // Base64 value, may be null

    // Utility functions
    // ...
}

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:

var device // we got it by calling connectToDevice
var service // we got it by calling servicesForDevice
var characteristic // we got it by calling characteristicsForDevice

manager.readCharacteristicForDevice(deviceUUID, serviceUUID, characteristicUUID)
device.readCharacteristicForService(serviceUUID, characteristicUUID)
service.readCharacteristic(characteristicUUID)
characteristic.read()

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 the user of our React Native bluetooth library 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.

import React, { Component } from 'react';
import { Platform, View, Text } from 'react-native';
import { BleManager } from 'react-native-ble-plx';

export default class SensorsComponent extends Component {

  constructor() {
    super()
    this.manager = new BleManager()
    this.state = {info: "", values: {}}
    this.prefixUUID = "f000aa"
    this.suffixUUID = "-0451-4000-b000-000000000000"
    this.sensors = {
      0: "Temperature",
      1: "Accelerometer",
      2: "Humidity",
      3: "Magnetometer",
      4: "Barometer",
      5: "Gyroscope"
    }
  }

  serviceUUID(num) {
    return this.prefixUUID + num + "0" + this.suffixUUID
  }

  notifyUUID(num) {
    return this.prefixUUID + num + "1" + this.suffixUUID
  }

  writeUUID(num) {
    return this.prefixUUID + num + "2" + this.suffixUUID
  }

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:

  info(message) {
    this.setState({info: message})
  }

  error(message) {
    this.setState({info: "ERROR: " + message})
  }

  updateValue(key, value) {
    this.setState({values: {...this.state.values, [key]: value}})
  }

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:

 componentWillMount() {
    if (Platform.OS === 'ios') {
      this.manager.onStateChange((state) => {
        if (state === 'PoweredOn') this.scanAndConnect()
      })
    } else {
      this.scanAndConnect()
    }
  }

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.

  scanAndConnect() {
    this.manager.startDeviceScan(null,
                                 null, (error, device) => {
      this.info("Scanning...")
      console.log(device)

      if (error) {
        this.error(error.message)
        return
      }

      if (device.name === 'TI BLE Sensor Tag' || device.name === 'SensorTag') {
        this.info("Connecting to TI Sensor")
        this.manager.stopDeviceScan()
        device.connect()
          .then((device) => {
            this.info("Discovering services and characteristics")
            return device.discoverAllServicesAndCharacteristics()
          })
          .then((device) => {
            this.info("Setting notifications")
            return this.setupNotifications(device)
          })
          .then(() => {
            this.info("Listening...")
          }, (error) => {
            this.error(error.message)
          })
      }
    });
  }

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:

async setupNotifications(device) {
    for (const id in this.sensors) {
      const service = this.serviceUUID(id)
      const characteristicW = this.writeUUID(id)
      const characteristicN = this.notifyUUID(id)

      const characteristic = await device.writeCharacteristicWithResponseForService(
        service, characteristicW, "AQ==" /* 0x01 in hex */
      )

      device.monitorCharacteristicForService(service, characteristicN, (error, characteristic) => {
        if (error) {
          this.error(error.message)
          return
        }
        this.updateValue(characteristic.uuid, characteristic.value)
      })
    }
  }

Lastly, we need rendering code to see our results:

  render() {
    return (
      <View>
        <Text>{this.state.info}</Text>
        {Object.keys(this.sensors).map((key) => {
          return <Text key={key}>
                   {this.sensors[key] + ": " + (this.state.values[this.notifyUUID(key)] || "-")}
                 </Text>
        })}
      </View>
    )
  }
}

And this is only a beginning. At Polidea, we are now actively involving ourselves in the React-Native movement, and there’s more to it than just React Native Bluetooth Low Energy. 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…

Share

Przemek

Staff Software Engineer

Did you enjoy the read?

If you have any questions, don’t hesitate to ask!

Did you enjoy the read?

If you have any questions, don’t hesitate to ask!