【问题标题】:Stop scanning after few seconds, BLE Scanning using react-native-ble-plx几秒钟后停止扫描,使用 react-native-ble-plx 进行 BLE 扫描
【发布时间】:2020-07-29 08:58:41
【问题描述】:

我目前正在使用 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);
};

输出: Output Image

【问题讨论】:

    标签: bluetooth-lowenergy beacon scanning


    【解决方案1】:

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

    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);
    };
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 2020-11-25
      相关资源
      最近更新 更多