// Keyboards, found and read through `@openmouse/keyboard-protocol`. Every board // shows what it says about itself. Brand-specific editors use the same // native transport. // // A driver is only offered a board whose report collections it claims: there is // no guessing by vendor, so nothing unknown is ever opened. Any vendor can ship // VIA, so those are found by VIA's own collection. import { invoke } from "@tauri-apps/api/core"; import { VIA_USAGE, VIA_USAGE_PAGE } from "@openmouse/keyboard-protocol/via"; import { WUQUE_FEATURES, wuqueOp } from "./keyboard-wuque"; import { isMchoseKeyboardControl, MCHOSE_FEATURES, mchoseOp, mchoseSections, writeMchoseKeyboard } from "./keyboard-mchose"; import { DEVICE_DRIVERS, type DeviceDriver } from "@openmouse/keyboard-protocol/drivers/registry"; import { SUPPORTED_HID_FILTERS } from "@openmouse/keyboard-protocol/drivers/vendors"; import { listHidInterfaces, TauriHidDevice, type HidInterfaceInfo } from "./native-hid/tauri-hid-device"; import { isHidBusyError, withHidOpenLock } from "./native-hid/hid-open-lock"; import { isLogitechKeyboardControl, logitechKeyboardSections, writeLogitechKeyboard } from "./keyboard-logitech"; type KeyboardInterface = HidInterfaceInfo & { receiverKey?: string }; export interface KeyboardCandidate { info: KeyboardInterface; brands: string[]; kind: "keyboard"; } type Filter = { vendorId?: number; productId?: number; usagePage?: number; usage?: number }; const filters = SUPPORTED_HID_FILTERS as Filter[]; /** Longest a board may take to describe itself. */ const READ_TIMEOUT_MS = 20000; const RATES: Record = { r8khz: 8000, r4khz: 4000, r2khz: 2000, r1khz: 1000, r500hz: 500, r250hz: 250, r125hz: 125, }; function deviceFor(info: HidInterfaceInfo): TauriHidDevice { // The board's own entry first; VIA's, which names no vendor, otherwise. const filter = filters.find( (f) => f.vendorId === info.vendorId && (f.productId === undefined || f.productId === info.productId), ) ?? filters.find((f) => f.vendorId === undefined); const preferred = filter?.usagePage !== undefined && filter.usage !== undefined ? { usagePage: filter.usagePage, usage: filter.usage } : undefined; return new TauriHidDevice(info, preferred); } function driverFor(info: HidInterfaceInfo): DeviceDriver | undefined { const device = deviceFor(info); return DEVICE_DRIVERS.find((driver) => { try { return driver.supports(device); } catch { return false; } }); } /** How long a keyboard found on a shared receiver stays listed before it is asked again. */ const RECEIVER_KEYBOARD_TTL_MS = 60000; const receiverKeyboards = new Map(); /** * Names the G915 X TKL paired to a shared receiver. Listing runs on every * rescan, so a recent answer is reused and a new one reads the identity only. */ async function sharedReceiverKeyboard(info: HidInterfaceInfo, listed: string | undefined): Promise { const known = receiverKeyboards.get(info.key); if (listed && known && Date.now() - known.at < RECEIVER_KEYBOARD_TTL_MS) return known.name; try { const name = await withKeyboard(info, async client => { // Drivers older than identify() can only answer with a full status read. const identity = typeof client.identify === "function" ? await client.identify() : await client.readStatus().then((status: any) => ({ productId: status.logitech?.productId, name: status.name })); return identity?.productId === 0x40b6 ? identity.name as string : undefined; }); if (name) receiverKeyboards.set(info.key, { name, at: Date.now() }); else receiverKeyboards.delete(info.key); return name; } catch (error) { // The mouse on the same receiver is being read. Keep what was listed. if (isHidBusyError(error)) return listed; receiverKeyboards.delete(info.key); return undefined; } } /** Lists keyboards, including the keyboard endpoint of a shared receiver. */ export async function listKeyboards(taken: Set, previous: ReadonlyMap): Promise { const via = await invoke("hid_vendors_with_usage", { usagePage: VIA_USAGE_PAGE, usage: VIA_USAGE }); const vendors = [...new Set([...filters.flatMap((f) => (f.vendorId === undefined ? [] : [f.vendorId])), ...via])]; const found: KeyboardCandidate[] = []; for (const info of await listHidInterfaces(vendors)) { if (taken.has(info.key)) { if (info.vendorId === 0x046d && info.productId === 0xc547) { const key = `${info.key}/keyboard`; const name = await sharedReceiverKeyboard(info, previous.get(key)?.info.productString); if (name) { found.push({ info: { ...info, key, receiverKey: info.key, productString: name }, brands: ["Logitech"], kind: "keyboard" }); } } continue; } const driver = driverFor(info); if (driver) found.push({ info, brands: [driver.brand], kind: "keyboard" }); } return found; } /** Opens the board, does one thing with its driver, and closes it again. */ async function withKeyboard(info: KeyboardInterface, work: (client: any, brand: string) => Promise): Promise { return withHidOpenLock(info.receiverKey ?? info.key, async () => { const driver = driverFor(info); const client = driver?.create(deviceFor(info)) as any; if (!driver || !client) throw new Error("No keyboard driver claims this device."); let timer: ReturnType | undefined; try { return await Promise.race([ (async () => { await client.open(); return work(client, driver.brand); })(), new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("The keyboard took too long to answer.")), READ_TIMEOUT_MS); }), ]); } finally { clearTimeout(timer); if (!client.keepOpen) await client.close().catch(() => undefined); } }); } /** The current rate and the ones on offer, where this app can set them. */ async function polling(client: any): Promise<{ pollingRateHz: number | null; supportedPollingRates: number[] }> { if (typeof client.readReportRates !== "function" || typeof client.writeReportRate !== "function") { return { pollingRateHz: null, supportedPollingRates: [] }; } const names: (string | null)[] = await client.readReportRates(); const current: string | null = await client.readReportRate(); return { pollingRateHz: (current && RATES[current]) || null, supportedPollingRates: names.flatMap((name) => (name && RATES[name]) || []).sort((a, b) => a - b), }; } /** A board's status in the shape the app's pages read. */ export function describeKeyboard(key: string, brand: string, status: any) { const info = status.wuque?.device?.info; const facts: [string, string | null | undefined][] = [ ["Serial number", status.serial ?? info?.sn], ["App version", info?.appVersion], ["Circuit board version", info?.pcbVersion], ["Layout", status.layout], ["Active profile", status.activeProfile == null ? null : String(Number(status.activeProfile) + 1 || status.activeProfile)], ]; if (status.via) { facts.push(["VIA protocol", String(status.via.protocolVersion)]); facts.push(["Layers", status.via.layerCount == null ? null : String(status.via.layerCount)]); } const controls = facts .filter(([, value]) => value) .map(([label, value], i) => ({ id: `kb.info.${i}`, label, kind: "info", current: String(value) })); const version = status.firmwareVersion; return { key, brand, driver: "Keyboard", displayBrand: status.brand || brand, status: { ...status, firmware: version ? [version] : status.firmware ?? [], keyboardFeatures: brand === "Wuque Studio" ? WUQUE_FEATURES : brand === "MCHOSE" ? MCHOSE_FEATURES : null, }, controls: null, tabs: { performance: [], buttons: [], advanced: controls.length ? [{ title: "Keyboard", controls }] : [], lighting: null, }, }; } export async function connectKeyboard(info: KeyboardInterface) { return withKeyboard(info, async (client, brand) => { const status = await client.readStatus(); const rates = status.logitech ?? await polling(client); const sections = status.logitech?.onboardMemory ? await logitechKeyboardSections(client, info.key, status.logitech) : brand === "MCHOSE" ? await mchoseSections(client) : []; const readout = describeKeyboard(info.key, brand, { ...status, pollingRateHz: rates.pollingRateHz, supportedPollingRates: rates.supportedPollingRates, // These controls are offered only after the hardware returns a profile. ui: sections.length ? { ...status.ui, settingsReady: true, statusNote: undefined } : status.ui, }); readout.tabs.advanced.unshift(...sections); return readout; }); } /** Keys, actuation and lighting, where this app can change them (Wuque Studio; MCHOSE lighting). */ export async function keyboardOp(info: HidInterfaceInfo, op: string, args: any): Promise { return withKeyboard(info, async (client, brand) => { if (brand === "Wuque Studio") return wuqueOp(client, op, args); if (brand === "MCHOSE") return mchoseOp(client, op, args); throw new Error("This app can't change that on this keyboard yet."); }); } /** Writes a keyboard setting and resolves to what the board then reports. */ export async function writeKeyboard(info: KeyboardInterface, action: string, value: unknown): Promise { if (isLogitechKeyboardControl(action)) { return withKeyboard(info, async (client, brand) => { if (brand !== "Logitech") throw new Error("This control requires a Logitech keyboard."); await writeLogitechKeyboard(client, info.key, action, value); const status = await client.readStatus(); const readout = describeKeyboard(info.key, brand, status); const sections = await logitechKeyboardSections(client, info.key, status.logitech); return { tabs: { ...readout.tabs, advanced: [...sections, ...readout.tabs.advanced] } }; }); } if (isMchoseKeyboardControl(action)) { return withKeyboard(info, async (client, brand) => { if (brand !== "MCHOSE") throw new Error("This control requires an MCHOSE keyboard."); await writeMchoseKeyboard(client, action, value); const status = await client.readStatus(); const readout = describeKeyboard(info.key, brand, status); return { tabs: { ...readout.tabs, advanced: [...await mchoseSections(client), ...readout.tabs.advanced] } }; }); } if (action !== "pollingRate") throw new Error("This app can't change that on a keyboard yet."); return withKeyboard(info, async (client, brand) => { if (brand === "Logitech") { const { logitech } = await client.readStatus(); const rate = Number(value); if (!logitech?.supportedPollingRates.includes(rate)) throw new Error(`This keyboard can't be set to ${value} Hz here.`); await client.setPollingRate(rate); if ((await client.readStatus()).logitech?.pollingRateHz !== rate) throw new Error("The keyboard did not confirm the polling rate."); return rate; } const name = Object.keys(RATES).find((key) => RATES[key] === Number(value)); if (!name || typeof client.writeReportRate !== "function") { throw new Error(`This keyboard can't be set to ${value} Hz here.`); } if (!(await client.writeReportRate(name))) throw new Error("The keyboard did not accept the polling rate."); const { pollingRateHz } = await polling(client); if (pollingRateHz !== Number(value)) throw new Error(`The keyboard still reports ${pollingRateHz ?? "no"} Hz.`); return pollingRateHz; }); }