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 how to integrate 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 performed an operation. 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 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 kind of 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 not available, 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 BLE peripherals available nearby. You can use FlatList to display the elements of the list as needed. For the purpose of this demo, I created the following screen.

9. Now we can connect to any peripheral device from the list and perform different kinds of 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 then 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 need to get all the services and characteristics needed to perform read and write operations. If the required services and characteristics are not available, 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 serviceUUID 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 that is 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. Now 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 which 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 again 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 take a look at the whole scenario in a diagram that is the normal flow of all kinds of 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 BLE peripherals available nearby.
  5. Now, in order to perform a BLE operation on a peripheral device, you need to check if the selected peripheral 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 and 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. If there is no performance or functionality, you should handle the error accordingly.
  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 perform the operation. However, again, 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 2 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.

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks
coma

Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.

author
George Hodulik
CEO, Stealth Startup, Ex-Google