share

ENGINEERING

7min read

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


PrzemekStaff Software Engineer

LEARN MORE

Contact us if you have any questions regarding the article or just want to chat about technology, our services, job offers and more!

POLIDEA NEWSLETTER

Sign in and expect sharp insights, recommendations, ebooks and fascinating project stories delivered to your inbox

The controller of the personal data that you are about to provide in the above form will be Polidea sp. z o.o. with its registered office in Warsaw at ul. Przeskok 2, 00-032 Warsaw, KRS number: 0000330954, tel.: 0048 795 536 436, email: hello@polidea.com (“Polidea”). We will process your personal data based on our legitimate interest and/or your consent. Providing your personal data is not obligatory, but necessary for Polidea to respond to you in relation to your question and/or request. If you gave us consent to call you on the telephone, you may revoke the consent at any time by contacting Polidea via telephone or email. You can find detailed information about the processing of your personal data in relation to the above contact form, including your rights relating to the processing, HERE.

Data controller:

The controller of your personal data is Polidea sp. z o.o. with its registered office in Warsaw at ul. Przeskok 2, 00-032 Warsaw, KRS number: 0000330954, tel.: [0048795536436], email: [hello@polidea.com] (“Polidea”)

Purpose and legal bases for processing:

 

Used abbreviations:

GDPR – Regulation (EU) 2016/679 of the European Parliament and of the Council of 27 April 2016
on the protection of natural persons with regard to the processing of personal data and on the free movement
of such data, and repealing Directive 95/46/EC (General Data Protection Regulation)

ARES – Polish Act on Rendering Electronic Services dated 18 July 2002

TL – Polish Telecommunications Law dated 16 July 2004

1)        sending to the given email address a newsletter including information on Polidea’s new projects, products, services, organised events and/or general insights from the mobile app business world |art. 6.1 a) GDPR, art. 10.2 ARES and art. 172.1 TL (upon your consent)

Personal data:name, email address

2)       statistical, analytical and reporting purposes |art. 6. 1 f) GDPR (based on legitimate interests pursued by Polidea, consisting in analysing the way our services are used and adjusting them to our clients’ needs, as well as developing new services)

Personal data:name, email address

Withdrawal of consent:

You may withdraw your consent to process your personal data at any time.

Withdrawal of the consent is possible solely in the scope of processing performed based on the consent. Polidea is authorised to process your personal data after you withdraw your consent if it has another legal basis for the processing, for the purposes covered by that legal basis.

Categories of recipients:

Your personal data may be shared with:

1)       authorised employees and/or contractors of Polidea

2)       persons or entities providing particular services to Polidea (accounting, legal, IT, marketing and advertising services) – in the scope required for those persons or entities to provide those services to Polidea

 

Retention period:

1)       For the purpose of sending newsletter to the given email address – for as long as the relevant consent is not withdrawn

2)       For statistical, analytical and reporting purposes – for as long as the relevant consent is not withdrawn

Your rights:

 

Used abbreviation:

GDPR – Regulation (EU) 2016/679 of the European Parliament and of the Council of 27 April 2016
on the protection of natural persons with regard to the processing of personal data and on the free movement
of such data, and repealing Directive 95/46/EC (General Data Protection Regulation)

According to GDPR, you have the following rights relating to the processing of your personal data, exercised by contacting Polidea via [e-mail, phone].

1)       to access to your personal data (art. 15 GDPR) by requesting sharing and/or sending a copy of all your personal data processed by Polidea

2)       to request rectification of inaccurate personal data
(art. 16 GDPR) by indicating the data requiring rectification

3)       to request erasure of your persona data (art. 17 GDPR); Polidea has the rights to refuse erasing the personal data in specific circumstances provided by law

4)       to request restriction of processing of your personal data (art. 18 GDPR) by indicating the data which should be restricted

5)       to move your personal data (art. 20 GDPR) by requesting preparation and transfer by Polidea of the personal data that you provided to Polidea to you or another controller in a structured, commonly used machine-readable format

6)       to object to processing your personal data conducted based on art. 6.1 e) or f) GDPR, on grounds relating to your particular situation (art. 21 GDPR)

7)       to lodge a complaint with a supervisory authority,
in particular in the EU member state of your habitual residence, place of work or place of the alleged infringement if you consider that the processing
of personal data relating to you infringes the GDPR
(art. 77.1 GDPR)

No obligation to provide data:

Providing your personal data is not obligatory, but necessary for Polidea to provide you the newsletter service

Refusal to provide the above data will result in inability to receive the newsletter service.

Profiling

In the process of providing the newsletter service, we make decisions in an automated way, including profiling, based on the data you provide.

 

“Profiling” means automated processing of personal data consisting of the use of your personal data to evaluate certain personal aspects relating to you, in particular to analyze or predict aspects concerning your personal preferences and interests.

 

The automated decisions are taken based on the analysis of clicked and viewed content. They affect the targeting of specific newsletter content to selected users registered to receive the newsletter service, based on the anticipated interests of the recipient.