in src/bluetooth/Bluetooth.tsx [170:232]
function useBluetoothDevicesList(shouldScan: boolean) {
const [devices, setDevices] = React.useState<Device[]>([]);
const deviceMap = React.useRef<Map<UUID, Device> | null>(null);
if (deviceMap.current === null) {
deviceMap.current = new Map();
}
const bleManager = IotcBleManager.getInstance();
React.useEffect(() => {
async function scan() {
if (!shouldScan) {
return;
}
if (Platform.OS === 'android') {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Bluetooth Permission',
message:
'Application would like to use bluetooth and location permissions',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
throw new Error('Permission rejected');
}
}
const sub = bleManager.onStateChange(s => {
if (s === State.PoweredOn) {
sub.remove();
bleManager.startDeviceScan(null, {scanMode: 2}, (e, device) => {
if (e) {
console.error(e);
}
if (!device?.name) {
return;
}
deviceMap.current?.set(device.id, device);
setDevices(Array.from(deviceMap.current?.values() ?? []));
});
}
}, true);
}
bleManager.setResetDeviceListCallback(() => {
deviceMap.current?.clear();
setDevices([]);
});
scan().catch(console.error);
}, [bleManager, setDevices, shouldScan]);
return {devices};
}