capacitor-community/bluetooth-le

Ability to remove onDisconnected callback after connecting to device.

abdulraheemawan opened this issue · 1 comments

Discussed in #547

Originally posted by abdulraheemawan June 15, 2023
First of all, great work @pwespi. The plugin is so cool.

I have been reading the docs up & down for quite some time and couldn't find a way to disable the ondisconnect callback provided during the connect call after the fact.

The problem is that I have implemented a functionality where the device auto connects if the connection drops using a exponential backoff function but if the user disconnects device manually then this auto connect stuff should not happen.
Here's how this happens.

async function connect(){
  var self = this
  await BleClient.connect(self.bluetoothDevice.deviceId, (deviceId) => {
    self.onDisconnected(deviceId)
  });
  
  await BleClient.startNotifications(
    self.bluetoothDevice.deviceId,
    UHF_READER_SERVICE,
    UHF_READER_RFID_CHARACTERISTIC,
    (value) => {
      self.handleNotifications(value);
      
    }
  );
}

async function disconnectDevice(forget=false) {
  var self = this
  if (this.uhfRfidConnectedStatus) {
    console.log('> Notifications stopped')
    await BleClient.stopNotifications(
      self.bluetoothDevice.deviceId,
      UHF_READER_SERVICE,
      UHF_READER_RFID_CHARACTERISTIC
    );
    await BleClient.disconnect(self.bluetoothDevice.deviceId);
    self.uhfRfidConnectedStatus = false;
    if(forget){
      self.bluetoothDevice = null;
    }
  }
}



async function onDisconnected(){
  var self = this;
  console.log('Bluetooth Device disconnected');
  this.uhfRfidConnectedStatus = false;

  setTimeout(function() {
    self.exponentialBackoff(5, 3, self.connect())
  }, 2000);
}

async function exponentialBackoff(max, delay, toTry) {
  var self = this;
  if(this.uhfRfidConnectedStatus==false){
    this.connect();
    console.log('Retrying in ' + delay + 's... (' + max + ' tries left)');
    setTimeout(function() {
      if(max>1){
        self.exponentialBackoff(--max, delay * 2, toTry);
      }
    }, delay * 1000);
  }
}


The problem is using normal WebBluetoothAPI we could do something like

self.bluetoothDevice.addEventListener('gattserverdisconnected', self.onDisconnected);

and in the disconnect function we could remove this listener so that if the user had manually disconnected we'll not try to connect to the device using the onDisconnected callback.

But here I couldn't find a way to reproduce this functionality.
The app is vueJS so please ignore the this and self keywords.
Any help is greatly appreciated. Happy coding.

pwespi commented

closing as duplicate of #547