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

fix: filter for correct usage/usagePage when finding xkeys devices #93

Merged
merged 3 commits into from
Nov 2, 2023
Merged
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
27 changes: 23 additions & 4 deletions packages/webhid/src/methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,39 @@ 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 {
if (device.vendorId !== XKEYS_VENDOR_ID) return false

return !!device.collections.find((collection) => {
if (collection.usagePage !== 12) return false

// Check the write-length of the device is > 20
return !!collection.outputReports?.find((report) => !!report.items?.find((item) => item.reportCount ?? 0 > 20))
})
}

/** 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 +57,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 e
}
}