diff --git a/packages/webhid/src/methods.ts b/packages/webhid/src/methods.ts index 4156db9..f81e50d 100644 --- a/packages/webhid/src/methods.ts +++ b/packages/webhid/src/methods.ts @@ -3,25 +3,34 @@ import { WebHIDDevice } from './web-hid-wrapper' /** Prompts the user for which X-keys panel to select */ export async function requestXkeysPanels(): Promise { - 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 { - return await navigator.hid.getDevices() + const allDevices = await navigator.hid.getDevices() + return allDevices.filter(isValidXkeysUsage) +} + +function isValidXkeysUsage(device: HIDDevice): boolean { + return !!device.collections.find( + (collection) => collection.type === 1 && collection.usage === 1 && collection.usagePage === 12 + ) } /** Sets up a connection to a HID device (the X-keys panel) */ export async function setupXkeysPanel(browserDevice: HIDDevice): Promise { 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 @@ -43,7 +52,12 @@ export async function setupXkeysPanel(browserDevice: HIDDevice): Promise ) // 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') + } }