From d54c53dc7190dca0d3d327b86be4061c9019b1da Mon Sep 17 00:00:00 2001 From: Heiko Rothe Date: Fri, 18 Dec 2020 12:32:52 +0100 Subject: [PATCH] fix(bluetooth-low-energy): only disconnect from connected devices --- .../bluetooth/bluetooth.service.spec.ts | 14 ++++++++++++++ src/integrations/bluetooth/bluetooth.service.ts | 4 ++++ 2 files changed, 18 insertions(+) diff --git a/src/integrations/bluetooth/bluetooth.service.spec.ts b/src/integrations/bluetooth/bluetooth.service.spec.ts index d1b0e9f..9660c27 100644 --- a/src/integrations/bluetooth/bluetooth.service.spec.ts +++ b/src/integrations/bluetooth/bluetooth.service.spec.ts @@ -411,6 +411,7 @@ Requesting information ... it('should disconnect from a peripheral', async () => { const peripheral = { + state: 'connected', disconnectAsync: jest.fn().mockResolvedValue(undefined), }; @@ -421,6 +422,19 @@ Requesting information ... expect(peripheral.disconnectAsync).toHaveBeenCalled(); }); + it('should not try to disconnect from a peripheral that is not connected', async () => { + const peripheral = { + state: 'disconnected', + disconnectAsync: jest.fn().mockResolvedValue(undefined), + }; + + await service.disconnectLowEnergyDevice( + (peripheral as unknown) as Peripheral + ); + + expect(peripheral.disconnectAsync).not.toHaveBeenCalled(); + }); + it('should restart scanning if nothing has been detected for a while', async () => { jest.useFakeTimers('modern'); diff --git a/src/integrations/bluetooth/bluetooth.service.ts b/src/integrations/bluetooth/bluetooth.service.ts index 9678b67..0b1d819 100644 --- a/src/integrations/bluetooth/bluetooth.service.ts +++ b/src/integrations/bluetooth/bluetooth.service.ts @@ -112,6 +112,10 @@ export class BluetoothService { * @param peripheral - BLE peripheral to disconnect from */ async disconnectLowEnergyDevice(peripheral: Peripheral): Promise { + if (!['connecting', 'connected'].includes(peripheral.state)) { + return; + } + this.logger.debug( `Disconnecting from BLE device at address ${peripheral.address}` );