From 89b0bb8ee3bf1e2fa078121f77c2dfa77ba0cdeb Mon Sep 17 00:00:00 2001 From: Christoffer Sandberg Date: Fri, 12 Jan 2024 17:12:16 +0100 Subject: [PATCH] Device: Change cleanup approach Disconnect cannot be used for cleanup as it actually has the property of disconnecting already connected devices. This commit removes listener removal from disconnect and places it in its own function that should be called on a Device object after instantiating it and before discarding it. --- src/Adapter.js | 2 ++ src/Device.js | 9 ++++++++- src/index.d.ts | 1 + 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/Adapter.js b/src/Adapter.js index f18f26c..be80427 100644 --- a/src/Adapter.js +++ b/src/Adapter.js @@ -109,6 +109,8 @@ class Adapter { /** * Init a device instance and returns it. + * Caller is responsible of calling cleanup() on the + * returned Device before discarding it to free resources. * @param {string} uuid - Device Name. * @async * @returns {Device} diff --git a/src/Device.js b/src/Device.js index 23154c6..8c9630e 100644 --- a/src/Device.js +++ b/src/Device.js @@ -119,7 +119,7 @@ class Device extends EventEmitter { */ async disconnect () { await this.helper.callMethod('Disconnect') - this.helper.removeListeners() + await this.cleanup() } /** @@ -142,6 +142,13 @@ class Device extends EventEmitter { return `${name} [${address}]` } + + /** + * Cleanup when discarding device object + */ + async cleanup () { + this.helper.removeListeners() + } } /** diff --git a/src/index.d.ts b/src/index.d.ts index b9a3507..73b5b9d 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -45,6 +45,7 @@ declare namespace NodeBle { disconnect(): Promise; gatt(): Promise; toString(): Promise; + cleanup(): Promise; on(event: 'connect', listener: (state: ConnectionState) => void): this; on(event: 'disconnect', listener: (state: ConnectionState) => void): this;