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 Oct 25, 2023
1 parent f29e903 commit 7e3f0f1
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions packages/webhid/src/methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<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.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<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 +52,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 7e3f0f1

Please sign in to comment.