diff --git a/docs/logitech-support.md b/docs/logitech-support.md index 181bc08..611fcf2 100644 --- a/docs/logitech-support.md +++ b/docs/logitech-support.md @@ -77,6 +77,68 @@ legacy zones; it advertises `0x8060` report rate, which this driver does not implement. No write path was exercised, so the catalog entries stay `verified: false`. +### K400 / K400 Plus + +The K400 (wpids `0x400E`, `0x4024`) and K400 Plus (`0x404D`) are Unifying +office keyboards, catalogued from [Solaar's device descriptors](https://github.com/pwr-Solaar/Solaar/blob/master/lib/logitech_receiver/descriptors.py) +rather than G HUB. They have no USB product id of their own, so they are only +reached through a Unifying receiver (`0xC52B`, `0xC532`). Older firmware may +not implement `0x0003` deviceInformation; when no slot names a catalogued +keyboard that way, the driver reads the receiver's HID++ 1.0 pairing register +(`0x83 0xB5`, sub-address `0x20 + slot - 1`, wpid at bytes 3–4 of the reply) +and addresses the slot whose wpid is catalogued, as Solaar does. + +Battery comes from the original `0x1000` batteryStatus (`[level%, next%, +status]`, read with fn 0) when neither `0x1004` nor `0x1001` is advertised. +Fn inversion (`0x40A0`, or `0x40A2` when that is absent) reads bit 0 of fn 0 +and writes `[state]` with fn 1, verified by a read-back. State 1 means the top +row sends media keys without Fn and F1–F12 need Fn; the K400 Plus reads +`01 01` (state, then power-on default) after a power cycle. `0x40A3` (K375s-style +Fn swap with a `0xFF` prefix) is not implemented. + +A K400 Plus (wpid `0x404D`, HID++ 4.1) on a `0xC52B` receiver was probed +read-only and then driven through OpenMouse. It advertises `0x0003`, `0x0005`, +`0x1000`, `0x1B04`, `0x2005`, `0x40A2`, `0x4100`, `0x4521`, `0x6100`, `0x6501` +and engineering features. Fn inversion over `0x40A2` was switched in the app +and the F-row behaviour changed. Further settings follow Solaar's handling: + +- `0x4521` keyboardDisableKeys: fn 0 capability mask, fn 1 disabled mask, fn 2 + writes the mask (bits 1 Caps Lock, 2 Num Lock, 4 Scroll Lock, 8 Insert, 16 + Win). This board reports `0x1D` (no Num Lock). Writes are read back. +- `0x6501` gesture2: fn 0 pages eight `[high, low]` fields per call until + `high == 0x01`; enable bits are numbered in field order over gestures that + can be enabled or default on. Fn 1 `[offset, 1, 0xFF]` reads an enable byte, + fn 2 `[offset, 1, mask, value]` (long report) writes one bit. Parameter 4 is + the pointer scale factor, big-endian, 256 = normal: fn 7 `[index, 0xFF]` + reads it, fn 6 the default, fn 8 `[index, value…, 0xFF]` writes it. Only + gesture 34 (Fn+click suppression) is flagged persistent; the other gesture + settings are lost when the keyboard powers off. + +Only gesture 34 survives a power cycle. Fn inversion and the disabled keys +are lost as well, though neither feature reports persistence; Logi Options+ +and Solaar keep these settings on the host and write them again after each +reconnect. + +Results on that K400 Plus, Windows 11, through the OpenMouse UI: + +| Setting | Result | +| --- | --- | +| Fn inversion (`0x40A2`) | Works; lost when the keyboard powers off | +| Disable keys (`0x4521`) | Works; lost when the keyboard powers off (mask read back as `0x00`) | +| Pointer speed (`0x6501` parameter 4) | Works; lost when the keyboard powers off | +| Natural scrolling (gesture 45) | Works; lost when the keyboard powers off | +| Taps (gestures 1, 2, 10, 30) | Bits change and read back, no effect. The firmware does not flag them `showInUi`; tapping follows gesture 34 instead | +| Edge swipes (64, 65, 67), pinch zoom (84) | Bits change and read back, no visible effect. Flagged `showInUi`, but these are Windows 8 charm gestures | + +The status reports every switchable gesture with its `showInUi` flag; the +OpenMouse panel offers natural scrolling, the two scroll axes and gesture 34 +only. Battery was read at 90% over `0x1000`. +- `0x1B04` lists 20 controls, all in group 0 with no remap targets, so there is + no firmware remap. Logi Options+ reassigns those keys by diverting them to + host software, which a web page cannot keep running. +- `0x2005` (swap button cancel) and `0x6100` (raw touchpad reports) have no + setting here. + ## Transport HID++ 2.0 rides on usage page `0xFF00` (USB) or `0xFF43` (Bluetooth). Requests @@ -95,6 +157,9 @@ transport. | --- | --- | --- | --- | | Identity | `0x0003` | `getDeviceInfo`, `getFwInfo`, `getSerialNumber` | Unit id, transport bits, model ids, firmware version, serial when advertised. | | Battery | `0x1004` | `getBatteryCapabilities`, `getBatteryInfo` | Percentage only when the gauge capability is set; otherwise the coarse level. | +| Battery (legacy) | `0x1001`, `0x1000` | `getBatteryVoltage`, `getBatteryLevelStatus` | Voltage curve for `0x1001`; reported percentage and charge status for `0x1000` (K400 family). | +| Fn inversion | `0x40A0`, `0x40A2` | `getFnInversion`, `setFnInversion` | Reads and toggles whether F1–F12 or the media keys are the default, with read-back. | +| Unifying pairing | Receiver register `0xB5` | HID++ 1.0 long register read | Names a paired keyboard by wpid when it lacks `0x0003`. | | Polling rate | `0x8061` | `getActualReportRateList`, `getReportRate`, `setReportRate` | Reads the advertised mask, writes a discriminant and verifies the read-back. | | Brightness and illumination | `0x8040` | functions 0–4 | Reads the range and current brightness; writes big-endian brightness and verifies it. When the illumination capability is advertised, reads and toggles backlight power independently, with read-back. | | Receiver | HID++ pairing slots 1–6 | Root `getFeature` + `0x0003` device information | Probes each slot, matches the reported model ids against the keyboard catalog, and addresses that device index. | diff --git a/src/drivers/logitech/hid.test.ts b/src/drivers/logitech/hid.test.ts index e4fb250..cbf339b 100644 --- a/src/drivers/logitech/hid.test.ts +++ b/src/drivers/logitech/hid.test.ts @@ -916,3 +916,265 @@ test("closing a receiver endpoint discards a late feature lookup before it can s await result; assert.deepEqual(requests, [0]); }); + +/** + * A Unifying receiver with one K400-family keyboard that, like the older + * firmware, does not implement 0x0003 deviceInformation. Only the receiver's + * HID++ 1.0 pairing register can name it. + */ +class FakeUnifyingK400 { + vendorId = LOGITECH_VENDOR_ID; + productId = 0xc52b; + productName = "USB Receiver"; + opened = false; + slot = 2; + wpid = 0x404d; + fnFeature: 0x40a0 | 0x40a2 | null = 0x40a0; + fnInverted = false; + ignoreFnWrite = false; + battery = [70, 50, 0]; + supportsSettings = true; + disableCapabilities = 0x1d; + disabledMask = 0x00; + // 0x6501 fn 0 fields as read from a K400 Plus (firmware on wpid 0x404d). + gestureFields: [number, number][] = [ + [0x42, 3], [0x41, 1], [0x41, 2], [0x04, 0], [0x22, 4], [0x80, 20], [0x8c, 33], [0xa3, 1], + [0xa3, 2], [0xa1, 30], [0xa3, 10], [0x41, 5], [0x82, 44], [0x85, 45], [0xad, 42], [0xad, 43], + [0x8f, 64], [0x8f, 65], [0x8f, 67], [0x42, 4], [0xaf, 84], [0x91, 34], [0x82, 85], [0x82, 100], + [0x01, 0], + ]; + gestureBitmap = [0x6f, 0x00]; + pointerScale = 256; + /** Keyboard requests to ignore after the slot is named, as a dozing keyboard does. */ + dropAfterPairing = 0; + private paired = false; + collections = [ + { usagePage: 0xff00, usage: 1, inputReports: [], outputReports: [], featureReports: [], children: [] }, + { usagePage: 0xff00, usage: 2, inputReports: [], outputReports: [], featureReports: [], children: [] }, + ]; + writes: { deviceIndex: number; featureIndex: number; functionByte: number; params: number[] }[] = []; + private listeners = new Set<(event: HIDInputReportEvent) => void>(); + + async open(): Promise { this.opened = true; } + async close(): Promise { this.opened = false; } + addEventListener(_type: "inputreport", listener: (event: HIDInputReportEvent) => void): void { this.listeners.add(listener); } + removeEventListener(_type: "inputreport", listener: (event: HIDInputReportEvent) => void): void { this.listeners.delete(listener); } + + private emit(bytes: readonly number[]): void { + const data = new Uint8Array(19); + data.set(bytes); + const event = { reportId: LOGITECH_LONG_REPORT_ID, data: new DataView(data.buffer), device: this } as unknown as HIDInputReportEvent; + for (const listener of this.listeners) listener(event); + } + + async sendReport(_reportId: number, source: BufferSource): Promise { + const data = source instanceof ArrayBuffer + ? new Uint8Array(source) + : new Uint8Array(source.buffer, source.byteOffset, source.byteLength); + const [deviceIndex = 0, featureIndex = 0, functionByte = 0] = data; + const params = [...data.slice(3)]; + this.writes.push({ deviceIndex, featureIndex, functionByte, params }); + if (deviceIndex === 0xff && featureIndex === 0x83 && functionByte === 0xb5) { + const sub = params[0] ?? 0; + if (this.wpid !== null && sub === 0x20 + this.slot - 1) { + this.emit([0xff, 0x83, 0xb5, sub, 0x11, 0x08, this.wpid >> 8, this.wpid & 0xff, 0x00, 0x00, 0x01]); + this.paired = true; + } else { + this.emit([0xff, 0x8f, 0x83, 0xb5, 0x02]); + } + return; + } + if (deviceIndex !== this.slot) { + // HID++ 1.0 "unknown device" from the receiver. + this.emit([deviceIndex, 0x8f, featureIndex, functionByte, 0x08]); + return; + } + if (this.paired && this.dropAfterPairing > 0) { + this.dropAfterPairing -= 1; + return; + } + const functionId = functionByte >> 4; + const reply = (index: number, values: readonly number[]) => this.emit([this.slot, index, functionByte, ...values]); + if (featureIndex === 0 && functionId === 0) { + const featureId = ((params[0] ?? 0) << 8) | (params[1] ?? 0); + const index = featureId === 0x1000 ? 2 : featureId === this.fnFeature ? 3 + : this.supportsSettings && featureId === 0x4521 ? 4 : this.supportsSettings && featureId === 0x6501 ? 5 : 0; + reply(0, [index, 0x00, 0x00]); + return; + } + if (featureIndex === 4) { + if (functionId === 0) { reply(4, [this.disableCapabilities]); return; } + if (functionId === 1) { reply(4, [this.disabledMask]); return; } + if (functionId === 2) { this.disabledMask = (params[0] ?? 0) & this.disableCapabilities; reply(4, []); return; } + } + if (featureIndex === 5) { + if (functionId === 0) { + const start = ((params[0] ?? 0) << 8) | (params[1] ?? 0); + const page = this.gestureFields.slice(start, start + 8); + while (page.length < 8) page.push([0x01, 0x00]); + reply(5, page.flat()); + return; + } + if (functionId === 1) { reply(5, [this.gestureBitmap[params[0] ?? 0] ?? 0]); return; } + if (functionId === 2) { + const [offset = 0, , mask = 0, value = 0] = params; + this.gestureBitmap[offset] = ((this.gestureBitmap[offset] ?? 0) & ~mask) | (value & mask); + reply(5, []); + return; + } + if (functionId === 6) { reply(5, [0x01, 0x00]); return; } + if (functionId === 7) { reply(5, [this.pointerScale >> 8, this.pointerScale & 0xff]); return; } + if (functionId === 8) { + if ((params[3] ?? 0) === 0xff) this.pointerScale = ((params[1] ?? 0) << 8) | (params[2] ?? 0); + reply(5, []); + return; + } + } + if (featureIndex === 2 && functionId === 0) { reply(2, this.battery); return; } + if (featureIndex === 3 && functionId === 0) { reply(3, [Number(this.fnInverted)]); return; } + if (featureIndex === 3 && functionId === 1) { + if (!this.ignoreFnWrite) this.fnInverted = ((params[0] ?? 0) & 1) === 1; + reply(3, []); + return; + } + // HID++ 2.0 "invalid function" for anything else. + this.emit([this.slot, 0xff, featureIndex, functionByte, 0x07]); + } + + async sendFeatureReport(): Promise { throw new Error("not used"); } + async receiveFeatureReport(): Promise { throw new Error("not used"); } +} + +test("a K400 Plus without 0x0003 is found through the Unifying pairing register", async () => { + const device = new FakeUnifyingK400(); + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + const status = await client.readStatus(); + assert.equal(status.name, "K400 Plus"); + assert.equal(status.connectionDetail, "Unifying receiver"); + assert.equal(status.logitech?.productId, 0x404d); + assert.equal(status.logitech?.receiverProductId, 0xc52b); + assert.deepEqual(status.logitech?.battery, { percent: 70, level: "good", status: "discharging" }); + assert.equal(status.logitech?.fnInversion, false); + assert.match(status.ui?.statusNote ?? "", /Solaar's device descriptors/); + // The keyboard slot, not the receiver, answers the HID++ 2.0 requests. + assert.ok(device.writes.some(write => write.deviceIndex === 2 && write.featureIndex === 2)); +}); + +test("Fn inversion is written and confirmed by a read-back", async () => { + const device = new FakeUnifyingK400(); + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + assert.equal(await client.setFnInversion(true), true); + assert.equal(device.fnInverted, true); + assert.deepEqual(device.writes.find(write => write.featureIndex === 3 && write.functionByte >> 4 === 1)?.params.slice(0, 1), [1]); + assert.equal(await client.setFnInversion(false), false); +}); + +test("the newer 0x40A2 Fn inversion is used when 0x40A0 is absent", async () => { + const device = new FakeUnifyingK400(); + device.fnFeature = 0x40a2; + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + assert.equal((await client.readStatus()).logitech?.fnInversion, false); + assert.equal(await client.setFnInversion(true), true); +}); + +test("an Fn inversion the keyboard does not apply is reported, and a missing feature refuses to write", async () => { + const device = new FakeUnifyingK400(); + device.ignoreFnWrite = true; + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + await assert.rejects(client.setFnInversion(true), /did not confirm/); + + const bare = new FakeUnifyingK400(); + bare.fnFeature = null; + const bareClient = new LogitechKeyboardHidClient(bare as unknown as HIDDevice); + assert.equal((await bareClient.readStatus()).logitech?.fnInversion, null); + await assert.rejects(bareClient.setFnInversion(true), /does not expose an Fn-inversion feature/); + assert.ok(!bare.writes.some(write => write.featureIndex === 3)); +}); + +test("a Unifying receiver with only an unknown wpid paired has no supported keyboard", async () => { + const device = new FakeUnifyingK400(); + device.wpid = 0x4051; // Not a catalogued keyboard. + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + await assert.rejects(client.readStatus(), /no supported keyboard paired/); +}); + +test("K400 Plus status lists disableable keys and the switchable touchpad gestures", async () => { + const device = new FakeUnifyingK400(); + device.disabledMask = 0x10; + const status = await new LogitechKeyboardHidClient(device as unknown as HIDDevice).readStatus(); + assert.deepEqual(status.logitech?.disabledKeys, { supported: ["capsLock", "scrollLock", "insert", "windows"], disabled: ["windows"] }); + const gestures = status.logitech?.touchpad?.gestures ?? []; + // Twelve gestures can be switched; fixed ones (tracking, tap group, raw data) are left out. + assert.deepEqual(gestures.map(gesture => gesture.id), [1, 2, 30, 10, 45, 42, 43, 64, 65, 67, 84, 34]); + const enabled = Object.fromEntries(gestures.map(gesture => [gesture.id, gesture.enabled])); + // Bitmap 0x6f: taps, drag, double tap and both two-finger scrolls on; natural scrolling off. + assert.equal(enabled[1], true); + assert.equal(enabled[45], false); + assert.equal(enabled[43], true); + assert.equal(enabled[84], false); + assert.equal(gestures.find(gesture => gesture.id === 34)?.persistent, true); + // The firmware flags scrolling, edge swipes and zoom for a settings UI, but not the taps. + assert.deepEqual(gestures.filter(gesture => gesture.showInUi).map(gesture => gesture.id), [45, 42, 43, 64, 65, 67, 84]); + assert.deepEqual(status.logitech?.touchpad?.pointerSpeed, { value: 256, defaultValue: 256, min: 0x2e, max: 0x1ff }); +}); + +test("disabled keys are written as one mask and confirmed; unsupported keys are refused", async () => { + const device = new FakeUnifyingK400(); + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + assert.deepEqual((await client.setDisabledKeys(["capsLock", "windows"])).disabled, ["capsLock", "windows"]); + assert.equal(device.disabledMask, 0x11); + await assert.rejects(client.setDisabledKeys(["numLock"]), /cannot disable: numLock/); + assert.equal(device.disabledMask, 0x11); +}); + +test("a gesture change writes [offset, 1, mask, value] in a long report and reads the bit back", async () => { + const device = new FakeUnifyingK400(); + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + // Natural scrolling is enable index 4; zoom is index 10 (byte 1, bit 2). + assert.equal(await client.setGesture(45, true), true); + assert.equal(device.gestureBitmap[0], 0x7f); + assert.equal(await client.setGesture(84, true), true); + assert.equal(device.gestureBitmap[1], 0x04); + assert.equal(await client.setGesture(1, false), false); + assert.equal(device.gestureBitmap[0], 0x7e); + const write = device.writes.find(entry => entry.featureIndex === 5 && entry.functionByte >> 4 === 2); + assert.deepEqual(write?.params.slice(0, 4), [0, 1, 0x10, 0x10]); + // A gesture the firmware does not let the host switch is refused. + await assert.rejects(client.setGesture(20, true), /does not let gesture 20 be switched/); +}); + +test("pointer speed is written big-endian with the 0xFF terminator and range-checked", async () => { + const device = new FakeUnifyingK400(); + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + assert.equal(await client.setPointerSpeed(384), 384); + assert.equal(device.pointerScale, 384); + const write = device.writes.find(entry => entry.featureIndex === 5 && entry.functionByte >> 4 === 8); + assert.deepEqual(write?.params.slice(0, 4), [0, 0x01, 0x80, 0xff]); + await assert.rejects(client.setPointerSpeed(0x200), RangeError); + await assert.rejects(client.setPointerSpeed(10), RangeError); +}); + +test("keyboards without 0x4521 or 0x6501 report neither setting", async () => { + const device = new FakeUnifyingK400(); + device.supportsSettings = false; + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + const status = await client.readStatus(); + assert.equal(status.logitech?.disabledKeys, null); + assert.equal(status.logitech?.touchpad, null); + await assert.rejects(client.setDisabledKeys([]), /does not expose a disable-keys feature/); + await assert.rejects(client.setPointerSpeed(256), /does not expose a pointer-speed setting/); +}); + +test("a keyboard dozing behind a direct Unifying receiver gets one identity retry", async () => { + const device = new FakeUnifyingK400(); + // The first keyboard request after the slot is named goes unanswered. + device.dropAfterPairing = 1; + const status = await new LogitechKeyboardHidClient(device as unknown as HIDDevice).readStatus(); + assert.equal(status.name, "K400 Plus"); + assert.equal(status.logitech?.fnInversion, false); + + // Two missed identity reads in a row still fail instead of retrying forever. + const asleep = new FakeUnifyingK400(); + asleep.dropAfterPairing = 2; + await assert.rejects(new LogitechKeyboardHidClient(asleep as unknown as HIDDevice).readStatus(), { name: "TimeoutError" }); +}); diff --git a/src/drivers/logitech/hid.ts b/src/drivers/logitech/hid.ts index da4b4a9..c414084 100644 --- a/src/drivers/logitech/hid.ts +++ b/src/drivers/logitech/hid.ts @@ -11,8 +11,23 @@ import { LOGITECH_RECEIVER_PRODUCTS, LOGITECH_SHORT_REPORT_ID, LOGITECH_VENDOR_ID, + LOGITECH_GET_LONG_REGISTER, + LOGITECH_RECEIVER_PAIRING_REGISTER, decodeLogitechBattery, + decodeLogitechBatteryStatus, decodeLogitechBatteryVoltage, + decodeLogitechFnInversion, + decodeLogitechPairingInfo, + decodeLogitechDisableKeyMask, + decodeLogitechGestureLayout, + encodeLogitechDisableKeyMask, + LOGITECH_GESTURE_PARAM_SCALE, + LOGITECH_POINTER_SCALE_MAX, + LOGITECH_POINTER_SCALE_MIN, + type LogitechDisableKey, + type LogitechDisabledKeys, + type LogitechGestureLayout, + type LogitechTouchpadState, decodeLogitechBrightness, decodeLogitechBrightnessInfo, decodeLogitechDeviceInformation, @@ -73,6 +88,7 @@ const RGB_BOOT_EFFECT = 1; const RGB_HOST_CONTROL = 3; const RGB_ACTIVITY_EVENTS = 6; const RGB_EDIT_PREVIEW_MS = 5000; +const UNIFYING_RECEIVERS = new Set([0xc52b, 0xc532]); function rgbChannels(color: LogitechRgbColor): number[] { const values = [color.red, color.green, color.blue]; @@ -171,6 +187,7 @@ export class LogitechKeyboardHidClient { private deviceIndex = LOGITECH_DIRECT_DEVICE_INDEX; private readonly featureIndexes = new Map(); private gameModeKeys: Pick | null = null; + private gestureLayout: LogitechGestureLayout | null = null; private longReports = false; private keyboardProductId: number | null = null; private receiver = false; @@ -302,6 +319,7 @@ export class LogitechKeyboardHidClient { async close(): Promise { this.session += 1; this.gameModeKeys = null; + this.gestureLayout = null; const pending = this.pending; this.pending = null; if (pending) { @@ -416,9 +434,39 @@ export class LogitechKeyboardHidClient { // Empty slot or a device that does not answer HID++. } } + if (UNIFYING_RECEIVERS.has(this.device.productId) && await this.resolveUnifyingPairing()) return; + this.deviceIndex = LOGITECH_DIRECT_DEVICE_INDEX; throw new Error("The Logitech receiver has no supported keyboard paired."); } + /** + * Older Unifying keyboards (K400 family) may not implement `0x0003` + * deviceInformation, so their slot cannot be named from HID++ 2.0 alone. + * The receiver's own HID++ 1.0 pairing register still reports each slot's + * wireless product id and device kind, as Solaar reads it. + */ + private async resolveUnifyingPairing(): Promise { + for (let slot = 1; slot <= 6; slot += 1) { + this.deviceIndex = LOGITECH_DIRECT_DEVICE_INDEX; + try { + // `(0x0B << 4) | software id 5` is the register address byte 0xB5. + const params = await this.rawRequest( + LOGITECH_GET_LONG_REGISTER, LOGITECH_RECEIVER_PAIRING_REGISTER >> 4, [0x20 + slot - 1, 0x00, 0x00], 350, false, + ); + const pairing = decodeLogitechPairingInfo(params, slot); + // The wpid alone names the model; the kind nibble is not needed to match. + if (!pairing || !LOGITECH_KEYBOARD_PRODUCTS.has(pairing.wirelessProductId)) continue; + this.deviceIndex = slot; + this.keyboardProductId = pairing.wirelessProductId; + this.indexResolved = true; + return true; + } catch { + // Empty pairing slot: the receiver answers with a HID++ 1.0 error. + } + } + return false; + } + private async getFeature(featureId: number): Promise { const cached = this.featureIndexes.get(featureId); if (cached !== undefined) return cached; @@ -438,8 +486,9 @@ export class LogitechKeyboardHidClient { }; const { index, params } = await readInfo().catch(error => { // The radio link can still be coming up during either mandatory read. - // Retry only while reading this identity over a shared receiver. - if (!this.endpoint || !(error instanceof Error) || error.name !== "TimeoutError") throw error; + // Retry only while reading this identity through a receiver, shared or + // direct: a dozing Unifying keyboard (K400 Plus) misses the first read. + if (!(this.endpoint || this.receiver) || !(error instanceof Error) || error.name !== "TimeoutError") throw error; return readInfo(); }); if (!params) return { device: { entityCount: 0, unitId: "", transport: [], modelIds: [], extendedModelId: 0, serialNumber: false }, firmware: null, serial: null }; @@ -469,8 +518,172 @@ export class LogitechKeyboardHidClient { } // Older boards (G915 and siblings) expose only the voltage feature. const voltageIndex = await this.getFeature(LOGITECH_FEATURE.batteryVoltage); - if (!voltageIndex) return null; - return decodeLogitechBatteryVoltage(await this.request(voltageIndex, 0x00, [0x00, 0x00, 0x00])); + if (voltageIndex) return decodeLogitechBatteryVoltage(await this.request(voltageIndex, 0x00, [0x00, 0x00, 0x00])); + // Unifying office keyboards (K400 family) report the original batteryStatus. + const statusIndex = await this.getFeature(LOGITECH_FEATURE.batteryStatus); + if (!statusIndex) return null; + return decodeLogitechBatteryStatus(await this.request(statusIndex, 0x00, [0x00, 0x00, 0x00])); + } + + /** The advertised Fn-inversion feature index, preferring the original `0x40A0`. */ + private async fnInversionIndex(): Promise { + return (await this.getFeature(LOGITECH_FEATURE.fnInversion)) + || this.getFeature(LOGITECH_FEATURE.newFnInversion); + } + + private async readFnInversion(): Promise { + const index = await this.fnInversionIndex(); + if (!index) return null; + return decodeLogitechFnInversion(await this.request(index, 0x00, [0x00, 0x00, 0x00])); + } + + private async readDisabledKeys(): Promise { + const index = await this.getFeature(LOGITECH_FEATURE.disableKeys); + if (!index) return null; + const [capabilities = 0] = await this.request(index, 0x00, [0x00, 0x00, 0x00]); + const [disabled = 0] = await this.request(index, 0x01, [0x00, 0x00, 0x00]); + return { supported: decodeLogitechDisableKeyMask(capabilities), disabled: decodeLogitechDisableKeyMask(disabled & capabilities) }; + } + + /** Replace the set of disabled keys (`0x4521` fn 2) and confirm it with a read-back. */ + setDisabledKeys(keys: readonly LogitechDisableKey[]): Promise { + return this.serialized(async () => { + await this.open(); + const current = await this.readDisabledKeys(); + if (!current) throw new Error("This Logitech keyboard does not expose a disable-keys feature."); + const unsupported = keys.filter(key => !current.supported.includes(key)); + if (unsupported.length) throw new RangeError(`This keyboard cannot disable: ${unsupported.join(", ")}.`); + const mask = encodeLogitechDisableKeyMask(keys); + await this.request(await this.getFeature(LOGITECH_FEATURE.disableKeys), 0x02, [mask, 0x00, 0x00]); + const confirmed = await this.readDisabledKeys(); + if (!confirmed || encodeLogitechDisableKeyMask(confirmed.disabled) !== mask) { + throw new Error("The Logitech keyboard did not confirm the disabled keys."); + } + return confirmed; + }); + } + + /** Enumerate `0x6501` fields eight at a time until the end marker. */ + private async readGestureLayout(index: number): Promise { + if (this.gestureLayout) return this.gestureLayout; + const fields: (readonly [number, number])[] = []; + // A generous bound: real devices list a few dozen fields. + for (let start = 0; start < 256; start += 8) { + const page = await this.requestMode(index, 0x00, [start >> 8, start & 0xff], true); + let ended = false; + for (let offset = 0; offset < 8; offset += 1) { + const high = page[offset * 2] ?? 0x01; + const low = page[offset * 2 + 1] ?? 0x00; + fields.push([high, low]); + if (high === 0x01) { + ended = true; + break; + } + } + if (ended) break; + } + this.gestureLayout = decodeLogitechGestureLayout(fields); + return this.gestureLayout; + } + + /** Read one enable-bitmap byte (`0x6501` fn 1 `[offset, count, mask]`). */ + private async readGestureEnableByte(index: number, offset: number): Promise { + const [value = 0] = await this.request(index, 0x01, [offset, 0x01, 0xff]); + return value; + } + + private async readGestureParam(index: number, paramIndex: number, size: number, functionId: 0x06 | 0x07): Promise { + const params = await this.requestMode(index, functionId, [paramIndex, 0xff], true); + let value = 0; + for (let byte = 0; byte < size; byte += 1) value = (value << 8) | (params[byte] ?? 0); + return value; + } + + private async readTouchpad(): Promise { + const index = await this.getFeature(LOGITECH_FEATURE.gesture2); + if (!index) return null; + const layout = await this.readGestureLayout(index); + const bytes = new Map(); + const gestures = []; + for (const gesture of layout.gestures) { + // Only gestures the host may switch; fixed ones are not settings. + if (gesture.enableIndex === null || !gesture.canEnable) continue; + const offset = gesture.enableIndex >> 3; + if (!bytes.has(offset)) bytes.set(offset, await this.readGestureEnableByte(index, offset)); + gestures.push({ + id: gesture.id, + enabled: ((bytes.get(offset) ?? 0) & (1 << (gesture.enableIndex & 7))) !== 0, + canEnable: gesture.canEnable, + showInUi: gesture.showInUi, + defaultEnabled: gesture.defaultEnabled, + persistent: gesture.persistent, + }); + } + const scale = layout.params.find(param => param.id === LOGITECH_GESTURE_PARAM_SCALE); + const pointerSpeed = scale + ? { + value: await this.readGestureParam(index, scale.index, scale.size, 0x07), + defaultValue: await this.readGestureParam(index, scale.index, scale.size, 0x06).catch(() => null), + min: LOGITECH_POINTER_SCALE_MIN, + max: LOGITECH_POINTER_SCALE_MAX, + } + : null; + return { gestures, pointerSpeed }; + } + + /** Enable or disable one touchpad gesture (`0x6501` fn 2), verified by a read-back. */ + setGesture(id: number, enabled: boolean): Promise { + return this.serialized(async () => { + await this.open(); + const index = await this.getFeature(LOGITECH_FEATURE.gesture2); + if (!index) throw new Error("This Logitech keyboard does not expose touchpad gestures."); + const gesture = (await this.readGestureLayout(index)).gestures.find(entry => entry.id === id); + if (!gesture || !gesture.canEnable || gesture.enableIndex === null) { + throw new RangeError(`This keyboard does not let gesture ${id} be switched.`); + } + const offset = gesture.enableIndex >> 3; + const mask = 1 << (gesture.enableIndex & 7); + // `[offset, count, mask, value]` is four bytes, so it needs a long report. + await this.requestMode(index, 0x02, [offset, 0x01, mask, enabled ? mask : 0x00], true); + const confirmed = ((await this.readGestureEnableByte(index, offset)) & mask) !== 0; + if (confirmed !== enabled) throw new Error("The Logitech keyboard did not confirm the gesture change."); + return confirmed; + }); + } + + /** Set the touchpad pointer scale factor (`0x6501` fn 8), verified by a read-back. */ + setPointerSpeed(value: number): Promise { + return this.serialized(async () => { + await this.open(); + if (!Number.isInteger(value) || value < LOGITECH_POINTER_SCALE_MIN || value > LOGITECH_POINTER_SCALE_MAX) { + throw new RangeError(`Pointer speed must be a whole number from ${LOGITECH_POINTER_SCALE_MIN} to ${LOGITECH_POINTER_SCALE_MAX}.`); + } + const index = await this.getFeature(LOGITECH_FEATURE.gesture2); + const scale = index ? (await this.readGestureLayout(index)).params.find(param => param.id === LOGITECH_GESTURE_PARAM_SCALE) : undefined; + if (!index || !scale) throw new Error("This Logitech keyboard does not expose a pointer-speed setting."); + const bytes: number[] = []; + for (let byte = scale.size - 1; byte >= 0; byte -= 1) bytes.push((value >> (byte * 8)) & 0xff); + await this.requestMode(index, 0x08, [scale.index, ...bytes, 0xff], true); + const confirmed = await this.readGestureParam(index, scale.index, scale.size, 0x07); + if (confirmed !== value) throw new Error("The Logitech keyboard did not confirm the pointer-speed change."); + return confirmed; + }); + } + + /** + * Make F1–F12 the default (`true`) or the media keys (`false`). Writes + * `setFnInversion` and confirms the change with a read-back. + */ + setFnInversion(inverted: boolean): Promise { + return this.serialized(async () => { + await this.open(); + const index = await this.fnInversionIndex(); + if (!index) throw new Error("This Logitech keyboard does not expose an Fn-inversion feature."); + await this.request(index, 0x01, [inverted ? 0x01 : 0x00, 0x00, 0x00]); + const confirmed = await this.readFnInversion(); + if (confirmed !== inverted) throw new Error("The Logitech keyboard did not confirm the Fn-inversion change."); + return confirmed; + }); } private async readPollingRate(): Promise<{ hz: number | null; supported: number[] }> { @@ -1431,6 +1644,7 @@ export class LogitechKeyboardHidClient { if (refreshFeatures) { this.featureIndexes.clear(); this.gameModeKeys = null; + this.gestureLayout = null; } const { device, firmware, serial } = await this.readDeviceInformation(); if (this.rgbHost?.releasePending) await this.releaseRgbHost().catch(() => undefined); @@ -1440,6 +1654,9 @@ export class LogitechKeyboardHidClient { const analog = await this.readAnalog().catch(() => null); const lighting = await this.readLightingZones().catch(() => null); const gameMode = await this.readGameModeRaw().catch(() => null); + const fnInversion = await this.readFnInversion().catch(() => null); + const disabledKeys = await this.readDisabledKeys().catch(() => null); + const touchpad = await this.readTouchpad().catch(() => null); const onboardMemory = this.isG915XTklLightspeed() && Boolean(await this.getFeature(RGB_PROFILE_MANAGEMENT).catch(() => 0)); const productId = this.keyboardProductId ?? this.device.productId; const product = LOGITECH_KEYBOARD_PRODUCTS.get(productId); @@ -1467,9 +1684,13 @@ export class LogitechKeyboardHidClient { controls: null, gameMode, onboardMemory, + fnInversion, + disabledKeys, + touchpad, wireless, verified: product.verified, }; + const receiverName = this.receiver ? LOGITECH_RECEIVER_PRODUCTS.get(this.device.productId) : undefined; return { brand: "Logitech", name: product.name, @@ -1477,10 +1698,10 @@ export class LogitechKeyboardHidClient { family: "logitech", settingsReady: false, defaultDisplayName: product.name, - statusNote: product.verified ? undefined : "HID++ support is transcribed from Logitech's public documentation and G HUB's catalog; this model has not been tested through OpenMouse.", + statusNote: product.verified ? undefined : `HID++ support is transcribed from Logitech's public documentation and ${product.source ?? "G HUB's catalog"}; this model has not been tested through OpenMouse.`, }, connectionType: wireless ? "Wireless" : "Wired", - connectionDetail: wireless ? "LIGHTSPEED / Bluetooth" : "USB", + connectionDetail: wireless ? (receiverName === "Unifying receiver" ? receiverName : "LIGHTSPEED / Bluetooth") : "USB", firmware: lines, firmwareVersion: firmware, layout: null, diff --git a/src/logitech/index.ts b/src/logitech/index.ts index 56a0ac6..524a2a1 100644 --- a/src/logitech/index.ts +++ b/src/logitech/index.ts @@ -29,12 +29,17 @@ export const LOGITECH_FEATURE = { featureSet: 0x0001, deviceInformation: 0x0003, deviceName: 0x0005, + batteryStatus: 0x1000, batteryVoltage: 0x1001, unifiedBattery: 0x1004, + fnInversion: 0x40a0, + newFnInversion: 0x40a2, reprogControls: 0x1b04, analogKeys: 0x1b08, controlList: 0x1b10, + disableKeys: 0x4521, disableControls: 0x4523, + gesture2: 0x6501, keyboardLayout: 0x4540, brightnessControl: 0x8040, colorLedEffects: 0x8070, @@ -61,6 +66,8 @@ export interface LogitechKeyboardProduct { wireless: boolean; /** False until the model is exercised through this package on hardware. */ verified: boolean; + /** Where the model's ids and features come from, when not G HUB's catalog. */ + source?: string; } /** @@ -68,6 +75,8 @@ export interface LogitechKeyboardProduct { * identified RAPID PIDs. Bluetooth (`b3xx`) and regional (`40xx`) SKUs share * the name with their wired (`c3xx`) sibling. */ +const SOLAAR_SOURCE = "Solaar's device descriptors"; + export const LOGITECH_KEYBOARD_PRODUCTS: ReadonlyMap = new Map([ [0xc351, { name: "PRO X 60", wireless: true, verified: false }], [0xb37b, { name: "PRO X 60", wireless: true, verified: false }], @@ -100,6 +109,15 @@ export const LOGITECH_KEYBOARD_PRODUCTS: ReadonlyMap 0 && raw <= 100 ? raw : null; + const level: LogitechBattery["level"] = percent === null + ? null + : percent >= 90 ? "full" : percent >= 50 ? "good" : percent >= 20 ? "low" : "critical"; + return { percent, level, status: BATTERY_STATUSES[params[2] ?? 0xff] ?? null }; +} + +/** + * `0x40A0` fnInversion / `0x40A2` newFnInversion `getFnInversion` reply. + * Bit 0 of byte 0 is set when the F-row sends F1–F12 without Fn held. + */ +export function decodeLogitechFnInversion(params: Uint8Array): boolean | null { + if (params.length < 1) return null; + return ((params[0] ?? 0) & 0x01) !== 0; +} + +/** + * `0x4521` keyboardDisableKeys bits. Fn 0 returns the capability mask, fn 1 + * the disabled mask and fn 2 replaces it, one byte each (as in Solaar). + */ +export const LOGITECH_DISABLE_KEY = { + capsLock: 0x01, + numLock: 0x02, + scrollLock: 0x04, + insert: 0x08, + windows: 0x10, +} as const; + +export type LogitechDisableKey = keyof typeof LOGITECH_DISABLE_KEY; + +export interface LogitechDisabledKeys { + /** Keys the firmware can disable. */ + supported: readonly LogitechDisableKey[]; + /** Keys currently disabled. */ + disabled: readonly LogitechDisableKey[]; +} + +/** Name the set bits of a `0x4521` mask; unknown bits are dropped. */ +export function decodeLogitechDisableKeyMask(mask: number): LogitechDisableKey[] { + return (Object.keys(LOGITECH_DISABLE_KEY) as LogitechDisableKey[]).filter(key => (mask & LOGITECH_DISABLE_KEY[key]) !== 0); +} + +export function encodeLogitechDisableKeyMask(keys: readonly LogitechDisableKey[]): number { + return keys.reduce((mask, key) => { + const bit = LOGITECH_DISABLE_KEY[key]; + if (bit === undefined) throw new RangeError(`Unknown disable-key name: ${String(key)}.`); + return mask | bit; + }, 0); +} + +/** + * `0x6501` gesture2 gesture ids with a user-facing meaning. Names follow + * Solaar's GestureId table; other ids still decode, without a name. + */ +export const LOGITECH_GESTURE = { + tap: 1, + twoFingerTap: 2, + threeFingerTap: 3, + doubleTap: 10, + twoFingerDoubleTap: 11, + tapAndDrag: 30, + twoFingerTapAndDrag: 31, + fnClickSuppression: 34, + oneFingerScroll: 40, + twoFingerScroll: 41, + twoFingerHorizontalScroll: 42, + twoFingerVerticalScroll: 43, + naturalScrolling: 45, + leftEdgeSwipe: 64, + rightEdgeSwipe: 65, + bottomEdgeSwipe: 66, + topEdgeSwipe: 67, + twoFingerZoom: 80, + twoFingerZoomStateless: 84, +} as const; + +/** `0x6501` parameter id 4: pointer scale factor, 256 = normal speed. */ +export const LOGITECH_GESTURE_PARAM_SCALE = 4; +/** The scale factor for normal (100%) pointer speed. */ +export const LOGITECH_POINTER_SCALE_NORMAL = 256; +/** Scale-factor bounds Solaar uses for the same parameter. */ +export const LOGITECH_POINTER_SCALE_MIN = 0x2e; +export const LOGITECH_POINTER_SCALE_MAX = 0x1ff; + +export interface LogitechGestureField { + id: number; + canEnable: boolean; + canDivert: boolean; + showInUi: boolean; + persistent: boolean; + defaultEnabled: boolean; + /** Bit position in the enable bitmap, when the gesture has one. */ + enableIndex: number | null; +} + +export interface LogitechGestureParamField { + id: number; + /** Value size in bytes. */ + size: number; + /** Parameter index for fn 6–8. */ + index: number; +} + +export interface LogitechGestureLayout { + gestures: readonly LogitechGestureField[]; + params: readonly LogitechGestureParamField[]; +} + +/** + * Decode `0x6501` fn 0 field pairs `[high, low]` in order. `high == 0x01` + * ends the list; bit 7 marks a gesture, `0x2x`/`0x3x` a parameter, `0x4x` a + * spec and `0x04` a grouping. Enable and parameter indexes are assigned in + * field order exactly as Solaar does. + */ +export function decodeLogitechGestureLayout(fields: readonly (readonly [number, number])[]): LogitechGestureLayout { + const gestures: LogitechGestureField[] = []; + const params: LogitechGestureParamField[] = []; + let enableIndex = 0; + for (const [high, low] of fields) { + if (high === 0x01) break; + if (high & 0x80) { + const canEnable = (high & 0x01) !== 0; + const defaultEnabled = (high & 0x20) !== 0; + const indexed = canEnable || defaultEnabled; + gestures.push({ + id: low, + canEnable, + canDivert: (high & 0x02) !== 0, + showInUi: (high & 0x04) !== 0, + persistent: (high & 0x10) !== 0, + defaultEnabled, + enableIndex: indexed ? enableIndex : null, + }); + if (indexed) enableIndex += 1; + } else if ((high & 0xf0) === 0x20 || (high & 0xf0) === 0x30) { + params.push({ id: low, size: high & 0x0f, index: params.length }); + } + } + return { gestures, params }; +} + +export interface LogitechGestureState { + id: number; + enabled: boolean; + /** Whether the firmware lets the host change it. */ + canEnable: boolean; + /** + * The firmware's own "show in settings UI" flag. On a K400 Plus the + * individual tap gestures are switchable but not flagged, and toggling them + * has no effect; tap-to-click follows gesture 34 (Fn + left click) instead. + */ + showInUi: boolean; + defaultEnabled: boolean; + /** Whether the firmware keeps the setting across power cycles. */ + persistent: boolean; +} + +export interface LogitechTouchpadState { + gestures: readonly LogitechGestureState[]; + /** Pointer scale factor (256 = normal), when parameter 4 is advertised. */ + pointerSpeed: { value: number; defaultValue: number | null; min: number; max: number } | null; +} + +/** HID++ 1.0 receiver register `0xB5` pairing information, sub-address `0x20 + slot - 1`. */ +export const LOGITECH_RECEIVER_PAIRING_REGISTER = 0xb5; +/** HID++ 1.0 sub-id for a long register read. */ +export const LOGITECH_GET_LONG_REGISTER = 0x83; + +export interface LogitechPairingInfo { + /** Wireless product id (wpid) of the paired device. */ + wirelessProductId: number; + /** Device kind nibble: 1 keyboard, 2 mouse, 3 numpad, … */ + kind: number; +} + +/** + * Unifying pairing-information reply, starting at the echoed sub-address: + * `[0x2n, destinationId, reportInterval, wpidHi, wpidLo, ?, ?, kind, …]`. + * The layout matches what Solaar reads from the same register. + */ +export function decodeLogitechPairingInfo(params: Uint8Array, slot: number): LogitechPairingInfo | null { + if (params.length < 8 || params[0] !== 0x20 + slot - 1) return null; + const wirelessProductId = ((params[3] ?? 0) << 8) | (params[4] ?? 0); + if (wirelessProductId === 0) return null; + return { wirelessProductId, kind: (params[7] ?? 0) & 0x0f }; +} + /** Extended report-rate bit mask in reply byte 1, bits 0..6. */ export function decodeLogitechReportRates(params: Uint8Array): number[] { const mask = params[1] ?? 0; @@ -647,6 +860,17 @@ export interface LogitechKeyboardState { /** Game Mode button state. The firmware does not return the disabled-key bitmap. */ gameMode?: import("./game-mode.js").LogitechGameModeState | null; onboardMemory?: boolean; + /** + * `0x40A0`/`0x40A2` Fn inversion: true when the top row sends its media or + * special functions without Fn and F1–F12 need Fn (the K400 Plus default, + * Solaar's "swap Fx function"); false when F1–F12 work without Fn. Absent or + * null when the keyboard does not advertise it. + */ + fnInversion?: boolean | null; + /** `0x4521` keys the firmware can disable, and which are disabled. */ + disabledKeys?: LogitechDisabledKeys | null; + /** `0x6501` touchpad gestures and pointer speed. */ + touchpad?: LogitechTouchpadState | null; wireless: boolean; verified: boolean; } diff --git a/src/logitech/protocol.test.ts b/src/logitech/protocol.test.ts index 094bb17..931fd8e 100644 --- a/src/logitech/protocol.test.ts +++ b/src/logitech/protocol.test.ts @@ -10,7 +10,13 @@ import { LOGITECH_SHORT_REPORT_ID, LOGITECH_SOFTWARE_ID, decodeLogitechBattery, + decodeLogitechBatteryStatus, decodeLogitechBatteryVoltage, + decodeLogitechFnInversion, + decodeLogitechPairingInfo, + decodeLogitechDisableKeyMask, + decodeLogitechGestureLayout, + encodeLogitechDisableKeyMask, estimateLogitechBatteryPercent, decodeLogitechBrightness, decodeLogitechBrightnessInfo, @@ -193,3 +199,65 @@ test("the keyboard catalog carries no duplicate product ids and marks nothing ve assert.ok(product.name.length > 0); } }); + +// Replies captured from a K400 Plus (wpid 0x404D) on a C52B Unifying receiver, +// read with a read-only hidapi probe; parameters start after `[devIx, feat, fn]`. +const K400_PLUS = { + pairingSlot1: [0x20, 0x07, 0x08, 0x40, 0x4d, 0x04, 0x02, 0x01, 0x47, 0x00, 0x00, 0x00], + batteryStatus: [0x5a, 0x32, 0x00, 0x00, 0x00, 0x00], + newFnInversion: [0x01, 0x01, 0x00, 0x00, 0x00, 0x00], + disableKeysCapabilities: 0x1d, +}; + +test("captured K400 Plus replies decode to its real state", () => { + assert.deepEqual(decodeLogitechPairingInfo(bytes(K400_PLUS.pairingSlot1), 1), { wirelessProductId: 0x404d, kind: 1 }); + assert.deepEqual(decodeLogitechBatteryStatus(bytes(K400_PLUS.batteryStatus)), { percent: 90, level: "full", status: "discharging" }); + assert.equal(decodeLogitechFnInversion(bytes(K400_PLUS.newFnInversion)), true); + // Caps Lock, Scroll Lock, Insert and Win; this board cannot disable Num Lock. + assert.deepEqual(decodeLogitechDisableKeyMask(K400_PLUS.disableKeysCapabilities), ["capsLock", "scrollLock", "insert", "windows"]); +}); + +test("0x1000 batteryStatus decodes a percentage and a charging status", () => { + assert.deepEqual(decodeLogitechBatteryStatus(bytes([70, 50, 0])), { percent: 70, level: "good", status: "discharging" }); + assert.deepEqual(decodeLogitechBatteryStatus(bytes([95, 90, 1])), { percent: 95, level: "full", status: "charging" }); + // A zero level means the firmware does not report a percentage. + assert.deepEqual(decodeLogitechBatteryStatus(bytes([0, 0, 0])), { percent: null, level: null, status: "discharging" }); + assert.equal(decodeLogitechBatteryStatus(bytes([70, 50])), null); +}); + +test("0x40A0 Fn inversion reads bit 0 of the first byte", () => { + assert.equal(decodeLogitechFnInversion(bytes([0x01, 0, 0])), true); + assert.equal(decodeLogitechFnInversion(bytes([0x00, 0x01, 0])), false); + assert.equal(decodeLogitechFnInversion(bytes([])), null); +}); + +test("Unifying pairing information yields the slot's wpid and kind", () => { + const reply = bytes([0x21, 0x11, 0x08, 0x40, 0x4d, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0]); + assert.deepEqual(decodeLogitechPairingInfo(reply, 2), { wirelessProductId: 0x404d, kind: 1 }); + // A reply for another slot, an empty slot or a short frame is ignored. + assert.equal(decodeLogitechPairingInfo(reply, 1), null); + assert.equal(decodeLogitechPairingInfo(bytes([0x20, 0, 0, 0, 0, 0, 0, 0]), 1), null); + assert.equal(decodeLogitechPairingInfo(bytes([0x20, 0, 0]), 1), null); +}); + +test("the K400 family is catalogued by its Unifying wpids", () => { + assert.equal(LOGITECH_KEYBOARD_PRODUCTS.get(0x400e)?.name, "K400"); + assert.equal(LOGITECH_KEYBOARD_PRODUCTS.get(0x4024)?.name, "K400"); + assert.equal(LOGITECH_KEYBOARD_PRODUCTS.get(0x404d)?.name, "K400 Plus"); + assert.equal(LOGITECH_KEYBOARD_PRODUCTS.get(0x404d)?.verified, false); +}); + +test("0x4521 masks round-trip through key names", () => { + assert.deepEqual(decodeLogitechDisableKeyMask(0x1d), ["capsLock", "scrollLock", "insert", "windows"]); + assert.equal(encodeLogitechDisableKeyMask(["capsLock", "windows"]), 0x11); + assert.deepEqual(decodeLogitechDisableKeyMask(0xe0), []); +}); + +test("0x6501 layout assigns enable and parameter indexes in field order", () => { + const layout = decodeLogitechGestureLayout([ + [0x42, 3], [0x22, 4], [0x80, 20], [0xa3, 1], [0x85, 45], [0x82, 44], [0x91, 34], [0x01, 0], [0xa3, 2], + ]); + assert.deepEqual(layout.params, [{ id: 4, size: 2, index: 0 }]); + assert.deepEqual(layout.gestures.map(gesture => [gesture.id, gesture.enableIndex]), [[20, null], [1, 0], [45, 1], [44, null], [34, 2]]); + assert.equal(layout.gestures.find(gesture => gesture.id === 34)?.persistent, true); +});