Skip to content

Commit

Permalink
fix: filter for correct usage/usagePage when finding xkeys devices
Browse files Browse the repository at this point in the history
  • Loading branch information
Julusian committed Nov 1, 2023
1 parent 2f52197 commit 68f3e86
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions packages/webhid/src/methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,32 @@ import { WebHIDDevice } from './web-hid-wrapper'

/** Prompts the user for which X-keys panel to select */
export async function requestXkeysPanels(): Promise<HIDDevice[]> {
return navigator.hid.requestDevice({
const allDevices = await navigator.hid.requestDevice({
filters: [
{
vendorId: XKEYS_VENDOR_ID,
},
],
})
return allDevices.filter(isValidXkeysUsage)
}
/**
* Reopen previously selected devices.
* The browser remembers what the user previously allowed your site to access, and this will open those without the request dialog
*/
export async function getOpenedXKeysPanels(): Promise<HIDDevice[]> {
return await navigator.hid.getDevices()
const allDevices = await navigator.hid.getDevices()
return allDevices.filter(isValidXkeysUsage)
}

function isValidXkeysUsage(device: HIDDevice): boolean {
return device.vendorId === XKEYS_VENDOR_ID && !!device.collections.find((collection) => collection.usagePage === 12)
}

/** Sets up a connection to a HID device (the X-keys panel) */
export async function setupXkeysPanel(browserDevice: HIDDevice): Promise<XKeys> {
if (!browserDevice?.collections?.length) throw Error(`device collections is empty`)
if (!isValidXkeysUsage(browserDevice)) throw new Error(`Device has incorrect usage/interface`)
if (!browserDevice.productId) throw Error(`Device has no productId!`)

const productId = browserDevice.productId
Expand All @@ -43,7 +50,12 @@ export async function setupXkeysPanel(browserDevice: HIDDevice): Promise<XKeys>
)

// Wait for the device to initialize:
await xkeys.init()
try {
await xkeys.init()

return xkeys
return xkeys
} catch (e) {
await deviceWrap.close()
throw new Error('Failed to initialise device')
}
}

0 comments on commit 68f3e86

Please sign in to comment.