Skip to content

Commit

Permalink
Merge pull request #45 from altaircunhajr/main
Browse files Browse the repository at this point in the history
Adding new method for listing all available (powered) adapters
  • Loading branch information
chrvadala committed Oct 28, 2022
2 parents a7fd08e + 7cd09de commit 4c7f575
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Bluetooth.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,24 @@ class Bluetooth {

return new Adapter(this.dbus, adapter)
}

/**
* List all available (powered) adapters
* @async
* @returns {Promise<Adapter[]>}
*/
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
23 changes: 23 additions & 0 deletions test/Bluetooth.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})
})

0 comments on commit 4c7f575

Please sign in to comment.