android - How to improve BLE device sampling in React Native so disconnected devices reappear in the scan list? - Stack Overflow

I am working on a React Native app using react-native-ble-plx to scan for BLE devices. However, I am en

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信