Integrate BLE Technology In Mobile Apps With React Native BLE Manager

In a previous blog, I talked about BLE and its basic concepts. In it, we learned what BLE is, how it works, important basic terms, the difference between BLE and Bluetooth Classic, the function of BLE, and the role of GAP. This blog describes integrating BLE technology in a mobile app using react native BLE manager. Learn how to perform basic operations using central and peripheral devices.

If you don’t understand the basics of BLE, check out the full blog on Getting Started With BLE.

Required Libraries And Device Information

We used the react native ble manager library to integrate react-native mobile apps with BLE technology. I used Mansaa Smart Bulb to create a demo app and operated it. I used the react native color picker library to display a color picker.

How Do You Implement It?

1. Go to your project and run the following command to install libraries

yarn add react-native-ble-manager react-native-color-picker

2. For iOS, install the pods by using the below command.

cd ios && pod install OR cd ios && arch -x86_64 pod install

3. In the Android platform, you need to update AndroidManifest.xml file as per the given format. Learn more about (Android-Configuration)

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    package="YOUR_PACKAGE_NAME">

    <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />

    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="28"/>

    <uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION" tools:targetApi="Q"/>

    <!-- Only when targeting Android 12 or higher -->

    <!-- Please make sure you read the following documentation to have a

         better understanding of the new permissions.

         https://developer.android.com/guide/topics/connectivity/bluetooth/permissions#assert-never-for-location

         -->

    <!-- If your app doesn't use Bluetooth scan results to derive physical location information,

         you can strongly assert that your app

         doesn't derive physical location. -->

    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" 

                     android:usesPermissionFlags="neverForLocation"

                     tools:targetApi="s" />

    <!-- Needed only if your app looks for Bluetooth devices. -->

    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />

    <!-- Needed only if your app makes the device discoverable to Bluetooth devices. -->

    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />

4. For iOS, you need to add the NSBluetoothAlwaysUsageDescription string key to the info.plist file

5. First, we have to initialize the BLE module before performing any operation or action.

  useEffect(() => {

        BleManager.start({ showAlert: false, forceLegacy: true });

    }, []);

6. After initializing the BLE module, you need to check the Bluetooth permission. If the permit is unavailable, you will need to request and obtain it.

const checkForBluetoothPermission = () => {

        if (Platform.OS === 'android' && Platform.Version >= 23) {

            let finalPermission = Platform.Version >= 29

                ? PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION

                : PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION;

            PermissionsAndroid.check(finalPermission).then((result) => {

                if (result) {

                    enableBluetoothInDevice()

                } else {

                    PermissionsAndroid.request(finalPermission).then((result) => {

                        if (result) {

                            enableBluetoothInDevice()

                        } else {

                            console.log("User refuse");

                        }

                    });

                }

            });

        }

        else {

            console.log("IOS");

            enableBluetoothInDevice()

        }

    }

7. If you have permission, you should enable Bluetooth before you start scanning for nearby BLE peripherals.

const enableBluetoothInDevice = () => {

        BleManager.enableBluetooth()

            .then(() => {

                setBluetoothtoggle(true)

                startScan()

            })

            .catch((error) => {

                console.log("Error--->", error);

            });

    }
const startScan = () => {

        if (!isScanning) {

            BleManager.scan([], 10, true).then((results) => {

                console.log('Scanning...');

                setIsScanning(true);

            }).catch(err => {

                console.error(err);

            });

        }

    }

8. After scanning, you can get a list of nearby BLE peripherals. You can use FlatList to display the elements of the list as needed. For this demo, I created the following screen.

9. Now, we can connect to any peripheral device from the list and perform different operations. So first, we need to check if the peripheral device is connected with our app (central device) or not. If a device is not connected, we need to connect, and then we can go ahead.

 const connectBLEDevice = (item, index) => {

        toggleConnecting(true, index)   

        BleManager.isPeripheralConnected(item.id, []).then((res) => {

            if (res == false) {

                BleManager.connect(item.id)

                    .then((res7) => {

                        redirectUserToNext(item, index)

                    }).catch((error) => {

                        console.log("Error---BLE connect--->", error);

                        toggleConnecting(false, index)

                        ToastAndroid.show("Something went wrong while connecting..", ToastAndroid.SHORT)

                    })

            }

            else {

                redirectUserToNext(item, index)

            }

        }).catch((error) => {

            toggleConnecting(false, index)

            ToastAndroid.show("Something went wrong while connecting..", ToastAndroid.SHORT)

        })

    }

10. You can also add a listener to your lifecycle method to detect peripherals, stop scanning, and get a score for your BLE device when an update occurs. The name of the event is assigned to the library used.

useEffect(() => {

        BleManager.start({ showAlert: false, forceLegacy: true });

        const ble1 = bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', handleDiscoverPeripheral);

        const ble2 = bleManagerEmitter.addListener('BleManagerStopScan', handleStopScan);

        const ble3 = bleManagerEmitter.addListener('BleManagerDisconnectPeripheral', handleDisconnectedPeripheral);

        const ble4 = bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', handleUpdateValueForCharacteristic);

        checkForBluetoothPermission()

        return (() => {

            ble1.remove()

            ble2.remove()

            ble3.remove()

            ble4.remove()

        })

    }, []);

11. You can now implement reads and writes using BLE devices. Describes read and write operations. First, you must get all the services and characteristics needed to perform read and write operations. If the required services and characteristics are unavailable, you will not be able to perform the operation on the BLE device.

12. You should now see a list of services available on your BLE device. Here you need to pass a unique ID for the peripheral. The Blemanager library has a method called retriveServices.

const getAllServiceForBLEDevice = () => {

        let item = route.params && route.params.peripheral ? route.params.peripheral : null

        var tempdata = [];

        BleManager.retrieveServices(item.id).then((res1) => {

            console.log("Res1===>", res1);

        }).catch((err) => {console.log("err-->", err);})

    }

13. After fetching the service, you can execute the required logic. And here, we check if the required services and characteristics are available in the specified list. Here we have defined the service UUID and property UUID required to perform a write operation using Smart Bulb. To do this, it detects if it is available. You need to get all the information and parameters needed for the hardware performing the operation.

const serviceUUIDForWriteBlubColor = "ffb0"

const characteristicUUIDForWriteBlubColor = "ffb2"

    const getAllServiceForBLEDevice = () => {

        let item = route.params && route.params.peripheral ? route.params.peripheral : null

        var tempdata = [];

        BleManager.retrieveServices(item.id).then((res1) => {

            console.log("Res1===>", res1);

            let data = res1.characteristics;

            var seen = {};

            tempdata = data.filter(function (entry) {

                var previous;

                if (seen.hasOwnProperty(entry.service)) {

                                       previous = seen[entry.service];

                    previous.characteristicList.push({

                        characteristic: entry.characteristic,

                        properties: entry.properties,

                    });

                    return false;

                }

                if (!Array.isArray(entry.characteristicList)) {

                    entry.characteristicList = [{

                        characteristic: entry.characteristic,

                        properties: entry.properties,

                    }];

                }

                seen[entry.service] = entry;

                delete entry.characteristic;

                delete entry.properties;

                delete entry.descriptors;

                return true;

            });

            console.log("tempdata-0----->", tempdata);

            setServiceAndCharList(tempdata)

            let isListContainBlubChangeColorService = tempdata.filter((obj) => obj.service == serviceUUIDForWriteBlubColor);

            console.log("isListContainBlubChangeColorService---->", isListContainBlubChangeColorService);

            if (isListContainBlubChangeColorService.length > 0) {

                let isListContainBlubChangeColorChar = isListContainBlubChangeColorService[0].characteristicList.filter((obj) => obj.characteristic == characteristicUUIDForWriteBlubColor);

                console.log("isListContainBlubChangeColorChar---->", isListContainBlubChangeColorChar);

                if (isListContainBlubChangeColorChar.length) {

                    setAvaibility(true)

                }

                else {

                    setAvaibility(false)

                }

            }

            else {

                setAvaibility(false)

            }

        }).catch((err) => {

            console.log("err-->", err);

        })

    }

14. We need to change the bulb color with the write operation. Here, I created the following screen. In that, I used a color picker to pick colors to change the bulb color. I have also added some shades of main colors to change the bulb color. 

15. Now, when we pick a color at that time. First, we need to check that the service and characteristics we require are available, then we can go ahead; otherwise, not. When we pick a color from the color picker OR predefined shade of color, it will be in HEX format. Therefore, it needs to be converted to RGB format.

export function hexToRgb(hex) {

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);

    return result ? {

        r: parseInt(result[1], 16),

        g: parseInt(result[2], 16),

        b: parseInt(result[3], 16)

    } : null;

}
const fullBrightNessHexValue = 49; // 1

  const zeroBrightNessHexValue = 48; // 0

    const onColorPicked = (color) => {

        if (isServiceAndCharAvailable) {

            let item = route.params && route.params.peripheral ? route.params.peripheral : null

            let hexToRgbValue = hexToRgb(color)

            let { r, g, b } = hexToRgbValue

            let tempObj = {

                id: item.id,

                name: item.name,

                service: serviceUUIDForWriteBlubColor,

                characteristic: characteristicUUIDForWriteBlubColor,

                writeValueData: [fullBrightNessHexValue, r, g, b]

            }

            setLastColor(color)

            readAndWriteData(tempObj)

        }

        else {

            ToastAndroid.show("Bulb change color service is not available.", ToastAndroid.SHORT)

        }

    }

16. I created an obj to pass to perform a write operation. You need to pass a byte array of length 4 (writeValueData). This first element requires you to pass the brightness value in hexadecimal code, and the other three parameters are for R, G, B.

17. Then check if the BLE peripheral is connected to the app. If you are connected, you can continue, but if you are not connected, you cannot continue.

const readAndWriteData = (peripheral, isRead, isToggleBlub) => {

        BleManager.isPeripheralConnected(peripheral.id, []).then((res) => {

            if (res == false) {

                BleManager.connect(peripheral.id)

                    .then((res7) => {

                        if (isRead) readCharData(peripheral)

                        else writeCharData(peripheral, isToggleBlub)

                    })

                    .catch((error) => { console.log("error---456464454->", error); });

            }

            else {

                if (isRead) readCharData(peripheral)

                else writeCharData(peripheral, isToggleBlub)

            }

        }).catch((error) => { console.log("Error--->", error) })

    }

18. Next, let’s perform the final write using the write method of the BleManager library. To write, you must pass a unique peripheral ID, service udid, property udid, and byte array. (I already have the item.)

const writeCharData = (peripheral, isToggleBlub) => {

        try {

            BleManager.write(peripheral.id,

                peripheral.service,

                peripheral.characteristic,

                peripheral.writeValueData  

            ).then((response) => {

                if (isToggleBlub == "1") {

                    ToastAndroid.show("Blub is now Turned On", ToastAndroid.SHORT)

                }

                else if (isToggleBlub == "2") {

                    ToastAndroid.show("Blub is now Turned Off", ToastAndroid.SHORT)

                }

                else {

                }

            }).catch(error => {

                console.log("Error--->", error);

                ToastAndroid.show(JSON.stringify(error), ToastAndroid.SHORT)

            })

        } catch (error) {

            console.log("Error---123123123-<", error);

        }

    }

19. If everything works fine, the bulb will change color after writing. Then perform a read operation. To do this, use BleManager’s read method to get the name of the light bulb. To get the name of the smart light bulb, you need to pass the unique ID of the peripheral, the serviceUDID, and the characteristic UDID. To get the response in a byte array from the read method, we first need to convert it to a human-readable format. Then you can view the name you got after the conversion.

 const serviceUUIDForWriteBlubColor = "ffb0"

    const characteristicUUIDForWriteBlubColor = "ffb2"

    const characteristicUUIDForChangeBlubName = "ffb7"

            BleManager.read(item.id, serviceUUIDForWriteBlubColor, characteristicUUIDForChangeBlubName).then((characteristic) => {

                const bytesString = String.fromCharCode(...characteristic)

                setBlubName(bytesString)

            }).catch((error) => {

                console.log("Error--write name->", error);

            })

20. Now, let’s look at the whole scenario in a diagram that is the normal flow of all technical disciplines. This is a common flow for all developers.

 react native BLE manager flowchart

  1. There are two types of devices, central and peripheral.
  2. When you open the peripheral, the ad will start.
  3. When the app opens on a central device, it first checks permissions and asks if it’s available. Then, after gaining permission, start scanning for a few seconds.
  4. The central device will now search for ad packages and find a list of nearby BLE peripherals.
  5. To perform a BLE operation on a peripheral device, you need to check if the selected device is connected to the app. If it is not connected, you need to connect first.
  6. Once the connection is established, all resources need to be acquired; based on that, the services needed for the literacy process need to be acquired.
  7. If a service is available, you need to look at all the characteristics associated with that service and, based on that, find the characteristics needed for reading and writing.
  8. You should handle the error accordingly if there is no performance or functionality.
  9. Once you find the feature, you can perform read, write, and notification operations.

 BLE Demo Code 

SmartBulb Color Change Demo

coma

Conclusion

This article may be useful for developers who want to learn to integrate BLE technology into a mobile app using react native BLE manager. First, you need BLE hardware or a BLE simulator app to operate.

However, most importantly, we need the hardware-related information for BLE because we need some preliminary information to perform the BLE operation. B. Service and characteristic UDID, a data format for writing.

Therefore, with BLE technology, you can use React Native to create interesting applications. The final flow chart provides a basic understanding of BLE features.

!! Enjoy, Keep and Do Delicious Coding !! 🙂🙂

Ronak K

React-Native Developer

Ronak is a React-Native developer with more than 4 years of experience in developing mobile applications for Android and iOS. He is dedicated to his work and passion. He worked in different kinds of application industries that have responsive designs. He also has knowledge of how to make an app with expo cli and react-native web and some basic understanding of react.js.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?