最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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(`

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论