Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding new method for listing all available (powered) adapters #45

Merged
merged 1 commit into from
Oct 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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')
})
})