I am working on a React Native app using react-native-ble-plx to scan for BLE devices. However, I am encountering an issue where disconnected devices do not reappear in the device list when I return to the "Devices Found" screen.
Here are the functions that handle the scanning, connecting and disconnecting:
export const DeviceProvider: React.FC<{ children: React.ReactNode }> = ({ children })
=> {
const [devices, setDevices] = useState<Map<string, DeviceWithTimestamp>>(new Map())
let bleManager = React.useMemo(() => new BleManager(), [])
const devicesRef = useRef(new Map())
//PERMISSIONS
useEffect(() => {
requestBluetoothPermission()
}, []);
//SCANNER
const startScan = useCallback(() => {
bleManager.stopDeviceScan();
requestBluetoothPermission();
const newDevices = new Map<string, DeviceWithTimestamp>();
bleManager.startDeviceScan(null, { scanMode: ScanMode.Balanced }, (error, device) => {
if (error) {
console.error('Error scanning:', error)
Alert.alert("Error scanning, check your Bluetooth settings and restart the app")
return
}
if (device && device.id && device.name?.includes('PA')) {
newDevices.set(device.id, { device, lastSeen: Date.now() });
};
setDevices(newDevices); // Update state once after scanning
})
}, [bleManager]);
const getDeviceById = useCallback((id: string) => devices.get(id), [devices])
//OLD DECVICE REMOVE
useEffect(() => {
const intervalId = setInterval(() => {
const currentTime = Date.now();
setDevices((prevDevices) => {
const updatedDevices = new Map(prevDevices);
updatedDevices.forEach((device, id) => {
if (currentTime - device.lastSeen >= 40000) {
updatedDevices.delete(id); // Remove devices not seen in the last 40 seconds
}
});
return updatedDevices;
});
}, 10000); // Check every 10 seconds
return () => {
clearInterval(intervalId)
bleManager.stopDeviceScan()
};
}, [bleManager])
//CONNECTION
const connectDevice = async (id: string) => {
try {
const device = await bleManager.connectToDevice(id, { refreshGatt: 'OnConnected' })
console.log('Connected to device:', device.name)
await device.discoverAllServicesAndCharacteristics()
return device.services()
} catch (error) {
console.error('Error connecting to device:', error)
bleManager = new BleManager() // Reset BleManager on failure
return connectDevice(id)
}
}
//DISCONNECTION
const disconnectFromDevice = async (id: string) => {
try {
console.log(`
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744961596a4603419.html
评论列表(0条)