KQR
KQR

Reputation: 11

Stop scanning after few seconds, BLE Scanning using react-native-ble-plx

I'm currently using polidea's react-native-ble-plx library to do BLE scanning. I do not want it to continue scanning, I just want to capture those scanned after a specified time limit. Is there a way to do this?

Code:

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: Output Image

Upvotes: 1

Views: 1635

Answers (1)

rattybag
rattybag

Reputation: 421

I would do this simply by creating a timer variable outside the scope of this function, with each iteration of the scan callback handler checking to see how much time is passed, stopping the scanning if it is over a certain amount.

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

Upvotes: 1

Related Questions