diff --git a/src/Bluetooth.js b/src/Bluetooth.js index 9946976..b8e841b 100644 --- a/src/Bluetooth.js +++ b/src/Bluetooth.js @@ -51,6 +51,24 @@ class Bluetooth { return new Adapter(this.dbus, adapter) } + + /** + * List all available (powered) adapters + * @async + * @returns {Promise} + */ + async activeAdapters () { + const adapterNames = await this.adapters() + const allAdapters = await Promise.allSettled(adapterNames.map(async name => { + const adapter = await this.getAdapter(name) + const isPowered = await adapter.isPowered() + return { adapter, isPowered } + })) + + return allAdapters + .filter(item => item.status === 'fulfilled' && item.value.isPowered) + .map(item => item.value.adapter) + } } module.exports = Bluetooth diff --git a/test/Bluetooth.spec.js b/test/Bluetooth.spec.js index f4b2e9b..99d6a9f 100644 --- a/test/Bluetooth.spec.js +++ b/test/Bluetooth.spec.js @@ -44,3 +44,26 @@ describe('defaultAdapter', () => { expect(Adapter).toHaveBeenCalledWith(dbus, 'hci0') }) }) + +describe('getActiveAdapters', () => { + it('should return only active adapters', async () => { + const hci0 = new Adapter(dbus, 'hci0') + hci0.isPowered = async () => false + hci0.getName = async () => 'hci0' + + const hci1 = new Adapter(dbus, 'hci1') + hci1.isPowered = async () => true + hci1.getName = async () => 'hci1' + + const bluetooth = new Bluetooth(dbus) + + const adapters = { hci0, hci1 } + bluetooth.getAdapter = async name => adapters[name] + bluetooth.helper.children.mockReturnValue(['hci0', 'hci1']) + + const result = await bluetooth.activeAdapters() + + expect(result.length).toEqual(1) + await expect(result[0].getName()).resolves.toEqual('hci1') + }) +})