FoodTech mobile apps: What is important to know about?
13 minutes
Business
Mobile
Mar 22, 2024
15 minutes
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();
}
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);
}
});
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 } });