首页 > 解决方案 > 几秒钟后停止扫描,使用 react-native-ble-plx 进行 BLE 扫描

问题描述

我目前正在使用 polidea 的 react-native-ble-plx 库进行 BLE 扫描。我不想让它继续扫描,我只想在指定的时间限制后捕获那些扫描的。有没有办法做到这一点?

代码:

export const scan = function scan() {
  const subscription = DeviceManager.onStateChange((state) => {
    if (state === 'PoweredOn') {
      DeviceManager.startDeviceScan(null, null, (error, device) => {
        if (error) {
          console.log('error', error);
        }
        if (device !== null) {
          console.log('device found ----> [id,name]', device.id, device.name);
        }
      });

      subscription.remove();
    }
  }, true);
};

输出: 输出图像

标签: bluetooth-lowenergybeaconscanning

解决方案


我会简单地通过在这个函数范围之外创建一个计时器变量来做到这一点,扫描回调处理程序的每次迭代都会检查经过了多少时间,如果超过一定时间就停止扫描。

let startTime = new Date();

export const scan = function scan() {
  const subscription = DeviceManager.onStateChange((state) => {
    if (state === 'PoweredOn') {
      DeviceManager.startDeviceScan(null, null, (error, device) => {
        endTime = new Date();
        var timeDiff = endTime - startTime; //in ms
        // strip the ms
        timeDiff /= 1000;

        // get seconds 
        var seconds = Math.round(timeDiff);

        if (error) {
          console.log('error', error);
        }
        if (device !== null) {
          console.log('device found ----> [id,name]', device.id, device.name);
        }
        if (seconds > 5) {
          DeviceManager.stopDeviceScan(); //stop scanning if more than 5 secs passed
        }
      });

      subscription.remove();
    }
  }, true);
};


推荐阅读