Using react-native-ble-manager in a Mobile Application
Overview
In this article, we will learn how to use the react-native-ble-manager library to communicate with Bluetooth low energy (BLE) devices in our React Native app. By the end of this article, you will have a better understanding of how to use react-native-ble-manager in your React Native app and how to interact with BLE devices.
What is BLE (Bluetooth low energy)?
BLE is a wireless technology that allows low-power devices to communicate with each other over short distances. It is a subset of Bluetooth that is designed for low-power applications that require high-performance and long-range wireless communication.
BLE consists of two types of devices: central and peripheral. A central device is a device that initiates and controls the communication with other devices. A peripheral device is a device that advertises its presence and responds to requests from central devices.
BLE is ideal for applications that require low-power, high-performance, and long-range wireless communication. Some examples of BLE applications are:
- Health and fitness: BLE devices can monitor and track various health and fitness parameters, such as heart rate, blood pressure, calories burned, steps taken, etc.
- Smart home: BLE devices can control and automate various smart home devices, such as lights, thermostats, locks, cameras, etc.
- Location and proximity: BLE devices can provide location and proximity information, such as indoor navigation, asset tracking, geofencing, etc.
- Internet of Things (IoT): BLE devices can connect to the internet and exchange data with cloud services or other IoT devices.
As you can see, React Native Bluetooth has many potential uses for mobile apps. The question is- how can we use BLE in our React Native app? This is where react-native-ble-manager comes in.
To use React Native Bluetooth in our app, we need to implement both the central and peripheral roles. We need to scan for nearby peripheral devices that offer the services and characteristics we are interested in. We also need to connect to those peripheral devices and read or write their characteristics or subscribe to their notifications or indications.
Prerequisites for our React Native Bluetooth project
Before we start using react-native-ble-manager in our React Native app, we need to make sure we have the following prerequisites:
- A React Native app: We need to have a React Native app that we want to add BLE functionality to. If you don’t have one, you can create one using the React Native CLI or Expo CLI.
- A BLE device: We need to have a BLE device that we want to communicate with in our React Native app. It can be any device that supports BLE, such as a smartwatch, fitness tracker, sensor, etc. For this article, we will use a BLE device simulator app called LightBlue Explorer that is available for iOS and Android. This app allows us to create and simulate various BLE devices and services on our smartphone.
- A smartphone: We need to have a smartphone that supports BLE and can run our React Native app and the LightBlue Explorer app. It can be an iOS or Android device, but make sure it has Bluetooth enabled and is not paired with any other BLE device.
- A code editor: We need to have a code editor that we can use to write and edit our React Native code. You can use any code editor you prefer, but we recommend using Visual Studio Code as it has many features and extensions that make React Native development easier.
Installing react-native-ble-manager
Now that we have the prerequisites ready, we can install react-native-ble-manager in our React Native app. react-native-ble-manager is a library that provides an easy-to-use interface for managing BLE devices in React Native. It supports both iOS and Android platforms and offers various methods and events for scanning, connecting, reading, writing, and subscribing to BLE devices.
To install react-native-ble-manager, we need to run the following command in our terminal:
This will download and save the library in our node_modules folder and update our package.json file. The library supports the react native autolink feature.
For manual linking guidelines kindly refer to the official documentation: react-native-ble-manager
Finally, we need to import the library in our React Native code using the following statement:
Building the BLE manager for our React Native app
Now that we have installed react-native-ble-manager in our React Native app, we can start building the BLE manager for our app. The BLE manager is a component that will handle all the logic and functionality related to BLE devices in our app. It will use the methods and events of react-native-ble-manager to scan, connect, read, write, and subscribe to BLE devices.
To create the BLE manager component, we need to follow these steps:
- Create a new file called BleManager.js in our src folder.
- Import React, useState, useEffect, BleManager, and NativeEventEmitter from their respective modules.
- Create a functional component called BleManager that takes props as an argument.
-
Declare some state variables using useState hooks to store the following data:
- peripherals: an array of peripheral objects that contains information about the scanned devices.
- connectedPeripheral: an object that contains information about the connected device.
- scanning: a boolean value that indicates whether the scanning is in progress or not.
- error: a string value that contains any error message from the BLE operations.
-
Declare some helper functions using const declarations to perform the following tasks:
- init: a function that initializes the BleManager module and adds event listeners for various BLE events.
- scan: a function that starts scanning for nearby peripheral devices that match a given service UUID filter.
- stopScan: a function that stops scanning for peripheral devices.
- connect: a function that connects to a given peripheral device by its ID.
- disconnect: a function that disconnects from the connected peripheral device.
- read: a function that reads a characteristic value from the connected peripheral device by its service UUID and characteristic UUID.
- write: a function that writes a characteristic value to the connected peripheral device by its service UUID and characteristic UUID.
- subscribe: a function that subscribes to notifications or indications from a characteristic of the connected peripheral device by its service UUID and characteristic UUID.
- unsubscribe: a function that unsubscribes from notifications or indications from a characteristic of the connected peripheral device by its service UUID and characteristic UUID.
- Use useEffect hooks to call the init function when the component mounts and to remove the event listeners when the component unmounts.
- Use the state variables and helper functions to render the UI of the BLE manager component. The UI should consist of the following elements:
- A button that toggles the scanning state and calls the scan or stopScan function accordingly.
- A list that displays the peripherals array and shows the ID, name, RSSI, and services of each peripheral device. The list should also allow the user to select a peripheral device and call the connect function with its ID as an argument.
- A text that displays the connectedPeripheral object and shows the ID, name, RSSI, services, and characteristics of the connected device.
- A button that calls the disconnect function to disconnect from the connected device.
- A text input that allows the user to enter a service UUID and a characteristic UUID for reading or writing operations.
- A button that calls the read function with the entered service UUID and characteristic UUID as arguments and displays the read value in a text element.
- A text input that allows the user to enter a value for writing operations.
- A button that calls the write function with the entered service UUID, characteristic UUID, and value as arguments and displays a confirmation message in a text element.
- A switch that toggles the subscription state and calls the subscribe or unsubscribe function with the entered service UUID and characteristic UUID as arguments. The switch should also display a notification message in a text element when a notification or indication is received from the subscribed characteristic.
- Export the functional component
Reviewing our full React Native BLE Application
Now that we have completed the code for the BleManager component, we can review our full React Native BLE application. The application consists of two files: App.js and BleManager.js.
The App.js file is the main entry point of our application. It imports the BleManager component from the BleManager.js file and renders it inside a View element. It also sets the background color of the View element to white.
The BleManager.js file contains the code for the BleManager component that we have written in the previous section. It imports React, useState, useEffect, BleManager, and NativeEventEmitter from their respective modules. It also imports some UI components from react-native, such as View, Text, Button, FlatList, TextInput, and Switch.
The BleManager component is a functional component that takes props as an argument. It declares some state variables using useState hooks to store the peripherals array, the connectedPeripheral object, the scanning boolean, and the error string. It also declares some helper functions using const declarations to perform various BLE operations, such as init, scan, stopScan, connect, disconnect, read, write, subscribe, and unsubscribe.
The code for the App.js file is shown below:
Using the enableBluetooth() Method
The enableBluetooth() method is a method of the BleManager module that enables the Bluetooth adapter on the device. It returns a promise that resolves if the Bluetooth adapter is enabled or rejects if the Bluetooth adapter is not enabled or an error occurs.
This method is useful for checking and requesting the Bluetooth permission on Android devices. On iOS devices, this method does nothing as the React Native Bluetooth permission is handled by the system.
To use this method, we can call it before starting the scanning process and handle the promise resolution or rejection accordingly. For example:
Using the start() method
The start() method is a method of the BleManager module that initializes the BleManager module with some optional options. It returns a promise that resolves if the initialization is successful or rejects if an error occurs.
This method is required for using the BleManager module and should be called before any other BLE operation. The options parameter is an object that can have the following properties:
- showAlert: a boolean value that indicates whether to show system alerts for Bluetooth events. The default value is true.
- restoreIdentifierKey: a string value that identifies the app state to be restored by the system when the app is killed or suspended. This is useful for background mode on iOS devices. The default value is null.
- forceLegacy: a boolean value that indicates whether to force the use of legacy scan API on Android devices. The default value is false.
To use this method, we can call it inside the init function and handle the promise resolution or rejection accordingly. For example:
Using the scan() Method
The scan() method is a method of the BleManager module that starts scanning for nearby peripheral devices that match a given service UUID filter. It takes three parameters: serviceUUIDs, seconds, and allowDuplicates. It returns a promise that resolves if the scanning starts successfully or rejects if an error occurs.
The serviceUUIDs parameter is an array of strings that specifies the service UUIDs to filter by. If this parameter is empty or null, all peripheral devices will be scanned.
The seconds parameter is a number that specifies the duration of the scanning in seconds. If this parameter is zero or negative, the scanning will not stop until the stopScan() method is called.
The allowDuplicates parameter is a boolean value that indicates whether to allow duplicate peripheral devices to be scanned. If this parameter is true, all peripheral devices will be scanned regardless of whether they have been scanned before or not. If this parameter is false, only new peripheral devices will be scanned.
To use this method, we can call it inside the scan function and handle the promise resolution or rejection accordingly. For example:
Using the getConnectedPeripherals() Method
The getConnectedPeripherals() method is a method of the BleManager module that returns a promise that resolves with an array of peripheral objects that are currently connected to the device. It takes one parameter: serviceUUIDs, which is an array of strings that specifies the service UUIDs to filter by. If this parameter is empty or null, all connected peripheral devices will be returned.
This method is useful for retrieving the information of the connected peripheral devices without having to connect to them again.
To use this method, we can call it inside the connect function and handle the promise resolution accordingly. For example:
Connecting to and disconnecting from a BLE device
Here’s an example of how to connect and disconnect from a BLE device using react-native-ble-manager
Here, peripheralId is the unique identifier of the BLE device you want to connect or disconnect from. The connect() method establishes a connection with the device, while the disconnect() method terminates the connection.
You can also use the BleManager.isPeripheralConnected(peripheralId) method to check if a device is currently connected.
Conclusion
Some key learning points from the article are:
- BLE is a low-power, high-performance, long-range wireless technology that is a subset of Bluetooth.
- react-native-ble-manager is a library that manages BLE devices in React Native with various methods and events.
- To use react-native-ble-manager, we need to install, link, import, and initialize the library, and create an event emitter and add event listeners.
- To scan for devices, we need to use the scan() method and the BleManagerDiscoverPeripheral and BleManagerStopScan events.
- To connect to a device and get its information, we need to use the connect() and retrieveServices() methods and the BleManagerConnectPeripheral event.
- To read or write a characteristic value, we need to use the read() or write() method and display the value or confirmation message.
- To subscribe to notifications or indications from a characteristic, we need to use the startNotification() method and the BleManagerDidUpdateValueForCharacteristic event and display the notification message.
- To disconnect from a device, we need to use the disconnect() method and the BleManagerDisconnectPeripheral event.
We hope you gained the insights that you were looking for in this article about react-native-ble-manager. Thank you for reading!