Using BLE technology when working with beacon in React Native
Hi! This is dev.family. We are a friendly bunch of developers who treat each other like family. We are really good at food tech. Today we will tell you about using BLE technology when working with a beacon in React Native.
Do you still think that when a McDonald’s waiter finds you in the most hidden corner of the restaurant and brings your order, it’s magic? I don’t want to upset you, but this is technology. Moreover, they are not that difficult, but very interesting. The whole secret is in special beacons and BLE technology. Let’s figure out how to set everything up and what cases can be used for using them for catering and retail.
For what?
Navigation in large retail spaces
The trick is that we can determine in three-dimensional space, with an accuracy of up to a centimeter, where a person is.
We can tell the courier where the goods are located in the warehouse. Build a path in the shopping center to the desired establishment. After all, unlike GPS, this technology sees you not just in a building, but on a specific floor.
We can send push notifications at the desired stand and show something specific in the application. For example, I went to the shelves with rum or tequila, watched a video in the application, what cocktails can be prepared, what ingredients are needed. I built a route to the shelves with the necessary goods.
In general, build analytics of customer movements: where they went, where they stayed longer. And then, based on this, make a layout and sell the best places to suppliers.
Personalized approach
A guest approaches a restaurant, his phone tracks a beacon installed in the establishment and “wakes up” the application, it sends a request to a backend, and the backend can do anything. For example, we can show hostesses the names and preferences of those who enter the restaurant, if this is in our database. Or, on the contrary, we can show the guest that there is a promotion in the cafe he is passing by today. And if this is a store, remind them that there is an unpaid item in the cart.
Sounds interesting? Let’s dive a little into the technology, and then talk about business opportunities.
What is BLE?
No matter what anyone says, Bluetooth Low Energy (BLE) technology, also known as Bluetooth 4.0 and higher, still has no equal. It has become especially popular for developing Internet of Things (IoT) applications.
BLE is a version of Bluetooth optimized for minimal power consumption. It’s not difficult to guess that they love it precisely for this and use it to its fullest in devices that operate on batteries without recharging for a long time.
Unlike traditional Bluetooth, which is designed for exchanging large amounts of data (such as audio files), BLE is optimized for transferring small data packets with maximum energy efficiency. This allows devices such as fitness bracelets, smart watches, medical sensors and beacons to operate on a single battery for months, and sometimes years. Everyone’s favorite airtag immediately comes to mind, which is thrown into suitcases and backpacks, hung on keys, etc., to keep track of their property.
So, sometimes behind some devices that amaze us with their genius are such simple technologies. BLE is constantly being used to develop new types of devices and applications due to its energy efficiency, wide compatibility, low cost and ease of use.
Beacon
Beacons are small wireless devices that transmit signals over short distances using Bluetooth Low Energy (BLE) technology. They are designed to convey a unique identifier that can be recognized by smartphones and other devices nearby.
This mechanism allows:
- determine location indoors
- provide contextual information
- use yourself as a trigger for certain actions of applications on a smartphone when a specific beacon is detected
Distance tracking using BLE and RSSI
RSSI (Received Signal Strength Indicator) is based on measuring the signal strength between two devices: the closer the devices are to each other, the stronger the signal.
In other words, when you bring your smartphone closer to a BLE beacon, the smartphone notices that the signal from the beacon is getting stronger, and based on the change in signal strength, it can estimate the distance to the beacon.
However, the accuracy of this measurement method can vary greatly due to various factors. First, physical obstacles such as walls or furniture weaken the signal, making the beacon appear further away than it actually is. Secondly, interference from other signal sources, such as other BLE devices or Wi-Fi networks, can also distort measurements. In addition, different device models have different receiver sensitivity, which also affects the accuracy of distance determination.
To improve the accuracy of RSSI-based distance tracking, various filtering and correction algorithms are often used to take into account and minimize these influencing factors. For example, methods are used to average RSSI values over a period of time or algorithms that analyze changes in signal strength to refine distance estimates.
Why should this be used in business?
We will, of course, as always, use the example of food technology. Beacons are used here to improve customer service, optimize processes and increase business efficiency. For example:
Improving customer experience
- Place beacons inside a restaurant or cafe to automatically detect a customer’s stay and provide personalized offers through a mobile application.
- Implement a self-service system where customers can place orders and pay through a mobile application, and beacons will help determine their location for accurate delivery of the order.
Optimizing processes in a restaurant
- Use beacons to track staff movements to optimize task distribution and improve overall work efficiency.
- Automate warehouse inventory processes and warn about the need for restocking when beacons detect inventory levels below a certain threshold.
Increasing customer loyalty
- Use beacons to provide bonuses, discounts or special offers to customers who visit your establishment regularly.
- Create loyalty programs where beacons track customer purchases, providing bonuses or discounts when a certain consumption level is reached.
Analytics and data collection
- Collect data on the movement of customers within the establishment to optimize table placement, improve room design and manage customer flow.
- Analyze data about customer preferences based on their location to improve menus and offer more relevant dishes.
Delivery and to-go service
- Use beacons to track orders and locate couriers, which can help optimize the delivery process.
- Notify customers about order status and provide delivery information in real time through mobile apps.
How to implement this technically?
If you decide that you want to use this solution in your project, you will need
- Beacon: Select a suitable BLE beacon that meets your range requirements. You can find a large number of beacons on Aliexpress, we used HOLY-IOT.
- BLE-enabled smartphone or tablet: A device to test and use your application that is compatible with Bluetooth Low Energy technology. For our solution, iPhone with iOS 9.0 and higher, Android with 7 and higher are suitable.
- Development tools for your application, such as VSCode, as well as React Native and the react-native-ble-plx library.
Now you can start implementation.
Data collection
To collect RSSI data we will use the `react-native-ble-plx` library. We use the startDeviceScan method. This method allows you to scan BLE devices within range and obtain information about them, including RSSI. Here's an example of how you can implement RSSI data collection for specific devices:
import { BleManager } from "react-native-ble-plx";
const NAME = "HOLY-IOT";
const bleManager = new BleManager();
// Function to start scanning BLE devices
function startScanning() {
// The first parameter is the UUIDs of services (null if you want to scan all devices)
// Second parameter - scanning options
// The third parameter is a callback called when a device is detected
bleManager.startDeviceScan(null, null, (error, scannedDevice) => {
if (error) {
console.warn(error);
return;
}
if (scannedDevice && scannedDevice.name === NAME) {
console.log(scannedDevice.name, scannedDevice.rssi); // to find the device we need
// hereinafter we will process RSSI
}
});
}
// Stop scanning if necessary
function stopScanning() {
bleManager.stopDeviceScan();
}
Also be sure to request location permissions if you're on Android, as this is required to scan BLE devices starting with Android 6.0 (API level 23).
In this example, all available BLE devices are scanned every time a device with a given UUID is detected. The console will display the device name and its RSSI.
Please note that Bluetooth on iOS and Android may require permissions and privacy settings, including a request for location access and an explanation of why your app needs this permission in the `Info.plist` (iOS) and `AndroidManifest.xml` files (Android) respectively.
Distance estimation based on RSSI
To calculate the distance between the BLE device and the beacon based on the RSSI value, we use this formula:
where:
d — distance to the device (beacon),
TX Power — signal power measured at a standard distance (usually 1 meter) from the beacon,
RSSI — signal strength,
n — is the signal attenuation factor (environmental factor), reflecting the loss of the signal in the environment; typical values range from 2 to 4.
This formula allows you to estimate the distance between two devices using the logarithmic relationship between the change in signal strength and distance.
The value of the signal attenuation coefficient n depends on the specific environmental conditions in which the signal is transmitted.
Open space without obstacles: An n value of about 2. This condition assumes minimal signal attenuation when there are no significant obstacles between devices and the signal can travel in a straight line.
Indoors with obstacles: The n value can vary from 2.5 to 3.5 or even higher. Indoors, the signal can be reflected from walls, ceilings and other objects, which increases attenuation. Higher values of n are used to account for this additional attenuation.
Challenging environments with many obstacles: In environments with a high density of obstacles, such as warehouses, manufacturing facilities, or urban environments with many reflective surfaces, the n value can be set in the range of 4 to 5. These environments require a higher attenuation factor to compensate for significant signal losses.
It is important to understand that determining the most appropriate value for n often requires an empirical approach. This means running tests in the target environment to measure the actual signal distribution and tailoring the attenuation factor to achieve the best accuracy in distance estimation.
What will this look like in practice?
We have already obtained RSSI values from scanning devices as shown in the previous example. Now let's add a function to calculate the distance:
function calculateDistance(rssi, measure = -69, multiplier = 2) {
return Math.pow(10, (measure - rssi) / (10 * multiplier));
}
bleManager.startDeviceScan(null, null, (error, scannedDevice) => {
if (error) {
console.warn(error);
return;
}
if (scannedDevice && scannedDevice.name === NAME) {
const distance = calculateDistance(scannedDevice.rssi);
}
});
Increasing measurement accuracy
Factors such as physical obstructions, interference from other signal sources, and hardware differences can distort RSSI. Various filtering techniques are used to improve measurement accuracy.
We will use a simple moving average method, which is used to smooth out time series data and reduce random fluctuations.
To implement this technique, we will store the last few RSSI measurements for the device and calculate the average of them.
const rssiValues = {}; // object for storing arrays of RSSI values
function addRssiValueAndGetAverage(deviceId, newValue, maxSize = 3) {
if (!rssiValues[deviceId]) {
rssiValues[deviceId] = []; // Initialize the array if this is the first value
}
const values = rssiValues[deviceId];
values.push(newValue); // Add a new value
// Remove the oldest value if the maximum array size is exceeded
if (values.length > maxSize) {
values.shift();
}
// Calculate the average value
const averageRssi = values.reduce((acc, value) => acc + value, 0) / values.length;
return averageRssi;
}
bleManager.startDeviceScan(null, null, (error, scannedDevice) => {
if (error) {
console.warn(error);
return;
}
if (scannedDevice && scannedDevice.name === NAME) {
const averageRssi = addRssiValueAndGetAverage(scannedDevice.id, scannedDevice.rssi);
console.log(`Average RSSI value for device ${scannedDevice.name}: ${averageRssi}`);
}
}); // Here you can use the average RSSI value to estimate the distance } });
Why did we do all this?
It is worth noting that this method allows you to achieve an approximate estimate of the distance to the beacons. Despite the introduction of algorithms to improve measurement accuracy, it must be recognized that the results obtained remain approximate. Also, a feature of this implementation is that it works only when the application is in the active state (foreground state), which imposes certain restrictions on the scope of its application.
However, even in its current form, this system can find wide application in various scenarios. Examples include localization and navigation indoors, such as shopping malls, museums, warehouses, where it is important to provide users or employees with information about nearby objects and traffic routes.
In the future, we plan to develop an improved version that will be able to function not only when the application is active, but also in the background state. This will expand the scope of the technology, making it suitable for real-time monitoring and tracking tasks without the need for constant user interaction with the application.
The development and improvement of the tracking system using BLE and RSSI opens up new prospects for creating effective and convenient solutions in a variety of areas, from retail to food tech, providing a new level of user experience. But that’s a completely different story…