Search code examples
javascriptbluetoothbluetooth-lowenergybluezraspberry-pi4

BLE Scan stops after discovering few devices


After running the following code for the first time that is from one of the examples given here on my Raspberry Pi 4, it works fine and finds many devices. But when I rerun the scanning function is broken and only finds few devices:

noble.on('stateChange', function(state) {
  if (state === 'poweredOn') {
    noble.startScanning();
  } else {
    noble.stopScanning();
  }
});

noble.on('discover', function(peripheral) {
  console.log('peripheral discovered (' + peripheral.id +
              ' with address <' + peripheral.address +  ', ' + peripheral.addressType + '>,' +
              ' connectable ' + peripheral.connectable + ',' +
              ' RSSI ' + peripheral.rssi + ':');
  console.log('\thello my local name is:');
  console.log('\t\t' + peripheral.advertisement.localName);
  console.log('\tcan I interest you in any of the following advertised services:');
  console.log('\t\t' + JSON.stringify(peripheral.advertisement.serviceUuids));

  var serviceData = peripheral.advertisement.serviceData;
  if (serviceData && serviceData.length) {
    console.log('\there is my service data:');
    for (var i in serviceData) {
      console.log('\t\t' + JSON.stringify(serviceData[i].uuid) + ': ' + JSON.stringify(serviceData[i].data.toString('hex')));
    }
  }
  if (peripheral.advertisement.manufacturerData) {
    console.log('\there is my manufacturer data:');
    console.log('\t\t' + JSON.stringify(peripheral.advertisement.manufacturerData.toString('hex')));
  }
  if (peripheral.advertisement.txPowerLevel !== undefined) {
    console.log('\tmy TX power level is:');
    console.log('\t\t' + peripheral.advertisement.txPowerLevel);
  }

  console.log();
});

If I reset the device, the issue disappear. If I scan via bluetoothctl then scan on, there is no issue at all. I can scan on and off as I want. So my guess is that the issue is related to noble.js

Here is the output of sudo btmon where scanning stops.sudo btmon output

Here is the image of how the scan on hangs.scan on hanging

The BlueZ version is 5.50.


Solution

  • The issue was I was just exiting the script without stopping the scanning while duplicates set to false. Hence, when I rerun, only a few new devices were found.