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.
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.
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.
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 !! 🙂🙂
The team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
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.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
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.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork