Skip to content

Instantly share code, notes, and snippets.

@Naveen-spritle
Last active June 22, 2023 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Naveen-spritle/4a7f952f4766809a4b3a328fb6957816 to your computer and use it in GitHub Desktop.
Save Naveen-spritle/4a7f952f4766809a4b3a328fb6957816 to your computer and use it in GitHub Desktop.
startDeviceScan() Method to scan the available BLE devices and setTimeout() function to stop the scanning after 2seconds by using stopDeviceScan() Method.
//SCANNING BLUETOOTH DEVICES
function scanAvailableBleDevice() {
let devicesObj = {};
// _BleManager is the BleManager instance, We already import and initialize the instance in _BleManager variable
// If you need any clarification please check the "Usage" section, we already discussed above in this blog.
_BleManager.startDeviceScan(
[null],
{ allowDuplicates: false },
(error, device) => {
if (error) {
let errorCode = JSON.stringify(error.errorCode);
let errorMessage = JSON.stringify(error.reason);
if (errorCode == "600") {
if (errorMessage.startsWith(`"Undocumented scan`)) {
alert("Too Many attempts to scan,please try again later");
} else {
console.log(errorMessage)
alert("Something went wrong in scanning devices")
}
}
} else {
console.log(device)
// Store the device object in the "deviceObj" variable of key-value pair, Key is device ID, Value is entire device object
// Because of due to the scanning time period(I used 2seconds for scanning devices by using setTimeout()) it scan the same device repeatedly over the time period,
// So store Key-value pair to remove the duplicate device by using device ID after completed the scanning time period
devicesObj[device.id] = device;
}
}
);
//stop scanning device after 2seconds
setTimeout(() => {
let devices = [];
_BleManager.stopDeviceScan();
let deviceIds = Object.keys(devicesObj);
if (deviceIds.length) {
let noDuplicateDevices = new Set(deviceIds);
noDuplicateDevices.forEach((deviceId) => {
devices.push(devicesObj[deviceId]);
});
console.log(devices) // After remove the duplicate devices, Duplicate devices means same device is stored repeatedly in the scanning
}
else {
alert("No available BLE devices") //After stops the scanning no available devices
}
}, 2000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment