From 1c12975ad7cf50a823d797bd921abff48502a333 Mon Sep 17 00:00:00 2001 From: ruvelro Date: Thu, 3 Dec 2026 10:59:19 +0100 Subject: [PATCH 1/2] feat(logitech): add G915 X TKL Game Mode and onboard profiles Adds the 0x8101 onboard filesystem for the G915 X TKL over LIGHTSPEED: the three profile slots, key and logo lighting in active and idle states, timers, base-layer key assignments, stored animations and Game Mode key blocks. Saves stage a verified copy before the directory is replaced. Also adds wave direction, live per-key frames, identify() for listing a shared receiver without a status read, C547 identity retries, and stops LIGHTSYNC retries once the client closes. Rebased onto main after #19, #21 and #22. Co-Authored-By: Claude Fable 5.2 --- docs/logitech-support.md | 40 +- src/drivers/logitech/hid.test.ts | 205 +++++++++- src/drivers/logitech/hid.ts | 315 +++++++++++++++- src/logitech/game-mode.ts | 50 +++ src/logitech/index.ts | 18 + src/logitech/onboard-animation.test.ts | 23 ++ src/logitech/onboard-animation.ts | 107 ++++++ src/logitech/onboard.test.ts | 163 ++++++++ src/logitech/onboard.ts | 504 +++++++++++++++++++++++++ 9 files changed, 1398 insertions(+), 27 deletions(-) create mode 100644 src/logitech/game-mode.ts create mode 100644 src/logitech/onboard-animation.test.ts create mode 100644 src/logitech/onboard-animation.ts create mode 100644 src/logitech/onboard.test.ts create mode 100644 src/logitech/onboard.ts diff --git a/docs/logitech-support.md b/docs/logitech-support.md index 8f665a5..181bc08 100644 --- a/docs/logitech-support.md +++ b/docs/logitech-support.md @@ -30,6 +30,12 @@ Coverage ledger for the Logitech HID++ 2.0 keyboard driver. No physical-unit conversion is inferred from their raw u16 values. - OpenLogi's `0x8081` per-key lighting and `0x1B04` control pages for the zone and remap framing. +- The [PeriHub G HUB captures](https://github.com/hex-dump/perihub/issues/30#issuecomment-6928039301) + and the Logitech agent confirm the `0x4523` Game Mode bitmap. Logitech's + G915 X TKL device metadata identifies the physical controls. On the C547 + receiver the driver read Game Mode state and the 128-entry control list, + sent a Caps Lock change and restored the five factory blocks. The keyboard + acknowledged both writes. - [OpenLogi's `0x8040` wire reference](https://openlogi.org/hidpp/features/x8040-brightness-control) for the illumination capability bit and functions 3–4. - [OpenLogi's `0x8081` wire reference](https://openlogi.org/hidpp/features/x8081-per-key-lighting) @@ -97,6 +103,38 @@ transport. | RGB effects | `0x8071` | Device and cluster info, effects, power modes, startup colors | The G915 X TKL runs live LIGHTSYNC in host mode using `0x8101` fn 6 and subscribes to hardware activity notifications. The driver returns control when closing the client and retries an interrupted handoff when that client can communicate again. It reads and verifies the two startup colors in `0x8071` nonvolatile configuration and preserves device flags when writing inactivity timers. | | Legacy LED zones | `0x8070` | info, zone info, effect info, set zone effect, get zone effect | Enumerates per-zone ordinals; reads the active RAM effect, applies a fixed color or a caller-supplied ten-byte *raw* effect for any advertised zone-local effect ID, and verifies the ordinal and all ten RAM parameter bytes when fn 14 is advertised. No EEPROM writes or undocumented effect-specific parameter encoding. | | Key remapping | `0x1B04` | count, info, reporting, set-reporting | Reads controls, their groups and legal targets, and remaps a control with device read-back. | +| Game Mode | `0x4523`, `0x1B10` | state and disabled-key bitmap, control count and pages | G915 X TKL over LIGHTSPEED. `0x4523` fn 1 bit 0 reports the physical button state. Fn 0 replaces the whole 16-byte bitmap, with an LSB-first bit per `0x1B10` index. Fn 1 of `0x1B10` returns eight big-endian control IDs per page. The driver preserves the five factory blocks and the keyboard acknowledges each write. The firmware does not return the current bitmap. | +| Onboard memory | `0x8101` | capabilities, slot selection, user directory and profile files | G915 X TKL over LIGHTSPEED. Reads and selects the three slots with read-back. Edits name, key and logo lighting in active and idle states, timers, base-layer shortcuts and optional Game Mode blocks. Native Ripple is available on active keys. | +| Onboard lighting storage | `0x8071`, `0x00D0` | animation metadata, RGB frame upload | Stores user-generated key colors or timed lighting frames in either of the two animation slots. A profile can reference a stored animation. | + +For `0x8101`, fn 8 loads a sector and fn 12 reads sixteen buffer bytes at a +big-endian offset. Fn 2 sizes the write buffer, fn 3 appends up to sixteen +bytes and returns a one-based page number. Fn 7 commits `[bank, sector, +sizeBE16, crc32BE32]`. The directory CRC covers its count and entries through +the terminator. Profile CRCs cover the entire 99-byte payload. The driver +stages and verifies a copy in an unreferenced user sector before updating +the directory. Fn 6 reads or switches mode and fn 9 selects the slot using +its CRC. Activation enables firmware power management and hands LIGHTSYNC +zones and power back to the keyboard via `0x8071` fn 5. When saving a +zone effect the driver clears the combined-lighting bit for its power state, +so the firmware uses independent zone effects instead of a combined preset. +In independent mode the profile stores logo at byte 30 and keys at byte 41, +then idle logo at 52 and idle keys at 63. Live LIGHTSYNC reports keys as +cluster 0 (location 1) and logo as cluster 1 (location 2) on this model. +A LIGHTSPEED test saved and re-read a temporary third profile, +activated it and verified restoration of all original slots and the mode. +The [public G915 X captures](https://github.com/theo-antonescu/logi-ghub-linux/blob/main/docs/g915x-profile-management.md) +document the read and selection commands. + +Base-layer assignments use a `0x1B05` kind-1 file with a reference at byte 93 +of the verified profile layout. OpenMouse stages the updated table and profile +before publishing their directory entries together. An F5 shortcut, all four +lighting targets and native Ripple were saved and read back on the TKL. The +keyboard also acknowledged an Aurora upload, reported it after reconnection +and accepted activating a profile referencing that animation. [PeriHub's +assignment captures](https://github.com/hex-dump/perihub/blob/main/docs/protocols/logitech-keyboard-lighting.md#key-assignments-and-game-mode-what-g-hub-sends-issue-30-captures) +and the [public animation capture](https://github.com/theo-antonescu/logi-ghub-linux/blob/main/docs/g915x-profile-management.md#custom-animations-implemented-in-featuresrgb_storepy) +document the corresponding payloads. ## Not implemented @@ -123,5 +161,5 @@ transport. The driver never writes a feature the keyboard did not advertise. Setters with a getter read the value back before reporting success; write-only frames -(`0x8081` zone paint / `frame_end`, `0x1B08` key-travel events) are identified +(`0x8081` zone paint / `frame_end`, `0x1B08` key-travel events, `0x4523` bitmap) are identified as such. diff --git a/src/drivers/logitech/hid.test.ts b/src/drivers/logitech/hid.test.ts index ba58de6..b78b753 100644 --- a/src/drivers/logitech/hid.test.ts +++ b/src/drivers/logitech/hid.test.ts @@ -30,6 +30,7 @@ class FakeLogitechKeyboard { illuminationEnabled = true; supportsIllumination = true; controlIds = [0x00e4, 0x00e5]; + gameControls: number[] | null = null; controlMap = new Map([[0x00e4, 0x00e4], [0x00e5, 0x00e5]]); brightnessMax = 1000; supportsLegacyLighting = true; @@ -45,10 +46,12 @@ class FakeLogitechKeyboard { rgbTimers: number[] | null = null; rgbBoot: number[] | null = null; shortRgbConfigFails = false; + onShortRgbConfigFailure: (() => void) | null = null; reachable = true; profileMode: number | null = null; rgbPower = 1; rgbEffectIds = [0, 1]; + perKeyMask = 0b00001110; writes: { reportId: number; featureIndex: number; functionId: number; params: number[] }[] = []; private listeners = new Set<(event: HIDInputReportEvent) => void>(); @@ -75,6 +78,7 @@ class FakeLogitechKeyboard { const params = [...data.slice(3)]; this.writes.push({ reportId, featureIndex, functionId, params }); if (this.shortRgbConfigFails && reportId === LOGITECH_SHORT_REPORT_ID && featureIndex === 8 && (functionId === 3 || functionId === 7)) { + this.onShortRgbConfigFailure?.(); throw new Error("Short report timed out"); } const reply = this.reply(featureIndex, functionId, params); @@ -82,12 +86,13 @@ class FakeLogitechKeyboard { for (const listener of this.listeners) listener(event); } - private reply(featureIndex: number, functionId: number, params: number[]): DataView { + reply(featureIndex: number, functionId: number, params: number[]): DataView { if (featureIndex === 0 && functionId === 0) { const featureId = ((params[0] ?? 0) << 8) | (params[1] ?? 0); const unifiedBattery = this.batteryVoltageMv === null ? 2 : 0; const voltageBattery = this.batteryVoltageMv === null ? 0 : 2; - const index = new Map([[0x0003, 1], [0x1004, unifiedBattery], [0x1001, voltageBattery], [0x8061, 3], [0x8040, 4], [0x1b08, 5], [0x1b04, 7], [0x8071, this.supportsRgbEffects ? 8 : 0]]).get(featureId) + const index = new Map([[0x0003, 1], [0x1004, unifiedBattery], [0x1001, voltageBattery], [0x8061, 3], [0x8040, 4], [0x1b08, 5], [0x1b04, 7], [0x8071, this.supportsRgbEffects ? 8 : 0], + [0x1b10, this.gameControls ? 11 : 0], [0x4523, this.gameControls ? 12 : 0], [0x4540, this.gameControls ? 13 : 0]]).get(featureId) ?? (this.profileMode !== null && featureId === 0x8101 ? 10 : this.supportsPerKeyLighting && featureId === 0x8081 ? 6 : this.supportsLegacyLighting && featureId === 0x8070 ? 9 : 0); return response(0x00, 0, [index, 0x00, 0x01], this.deviceIndex); } @@ -103,6 +108,13 @@ class FakeLogitechKeyboard { return response(1, 2, [...text("LT-0001"), 0], this.deviceIndex); } } + if (featureIndex === 11 && this.gameControls) { + if (functionId === 0) return response(11, 0, [this.gameControls.length], this.deviceIndex); + const start = params[0] ?? 0; + return response(11, 1, this.gameControls.slice(start, start + 8).flatMap(id => [id >> 8, id & 0xff]), this.deviceIndex); + } + if (featureIndex === 12) return response(12, functionId, functionId === 1 ? [5] : [], this.deviceIndex); + if (featureIndex === 13) return response(13, 0, [15], this.deviceIndex); if (featureIndex === 2) { if (functionId === 0) { if (this.batteryVoltageMv !== null) { @@ -136,6 +148,7 @@ class FakeLogitechKeyboard { if (featureIndex === 10 && functionId === 6) { if (params[0] === 5) this.profileMode = 0; if (params[0] === 3) this.profileMode = 1; + if (params[0] === 15) this.profileMode = 3; return response(10, 6, [this.profileMode ?? 0, 0, 1], this.deviceIndex); } if (featureIndex === 8) { @@ -143,7 +156,8 @@ class FakeLogitechKeyboard { if ((params[0] ?? 0) === 0xff) return response(8, 0, [0, 0, 1, 0, this.rgbBoot ? 1 : 0], this.deviceIndex); if ((params[1] ?? 0) === 0xff) return response(8, 0, [0, 0, 0, 1, this.rgbEffectIds.length, 0, 0, 0], this.deviceIndex); const effect = params[1] ?? 0; - return response(8, 0, [0, effect, 0, this.rgbEffectIds[effect] ?? 0, 0, 0, 0, 30], this.deviceIndex); + const id = this.rgbEffectIds[effect] ?? 0; + return response(8, 0, [0, effect, 0, id, ...(id === 0x16 ? [0xdc, 0xe1] : [0, 0]), 0, 30], this.deviceIndex); } if (functionId === 3 && this.rgbBoot) { const mode = params[0] ?? 0; @@ -209,7 +223,7 @@ class FakeLogitechKeyboard { if (featureIndex === 6) { if (functionId === 0) { const page = params[1] ?? 0; - return response(6, 0, [0, 0, page === 0 ? 0b00001110 : 0, ...new Array(11).fill(0)], this.deviceIndex); + return response(6, 0, [0, 0, page === 0 ? this.perKeyMask : 0, ...new Array(11).fill(0)], this.deviceIndex); } if (functionId === 6) return response(6, 6, [...params], this.deviceIndex); // fn 1 only acknowledges the setter: no zone echo in the reply. @@ -265,6 +279,31 @@ test("the Logitech client reads identity, battery, report rate and brightness ov await client.close(); }); +test("G915 X TKL Game Mode writes a long bitmap in reported control order and preserves factory blocks", async () => { + const device = new FakeLogitechKeyboard(); + device.productId = 0xc547; + device.deviceIndex = 2; + device.modelIds = [0x40b6]; + device.gameControls = new Array(128).fill(0); + for (const [position, id] of [[58, 0x010d], [98, 0x004f], [102, 0x018c], [115, 0x0159], [116, 0x0184], [123, 0x018a]] as const) { + device.gameControls[position] = id; + } + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + const status = await client.readStatus(); + assert.deepEqual(status.logitech?.gameMode, { active: true, controls: device.gameControls, layoutCode: 15 }); + const gameWrites = () => device.writes.filter(packet => packet.featureIndex === 12 && packet.functionId === 0); + assert.equal(gameWrites().length, 0); + await assert.rejects(client.setGameModeDisabledKeys([0x0187]), /not available/); + assert.equal(gameWrites().length, 0); + await client.setGameModeDisabledKeys([0x010d]); + await client.setGameModeDisabledKeys([]); + const [withCaps, factory] = gameWrites(); + assert.equal(withCaps?.reportId, LOGITECH_LONG_REPORT_ID); + assert.deepEqual(withCaps?.params, [0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0x44, 0, 0x18, 8]); + assert.deepEqual(factory?.params, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x44, 0, 0x18, 8]); + await client.close(); +}); + test("An explicit status refresh retries RGB discovery after an incomplete read", async () => { const device = new FakeLogitechKeyboard(); device.supportsPerKeyLighting = false; @@ -426,13 +465,13 @@ test("G915 X TKL claims host mode, encodes new effects, dims, turns off and repl device.rgbTimers = [0, 0, 0, 10, 0, 1]; device.rgbEffectIds = [0, 1, 0x15, 0x16]; const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); - await client.setRgbEffect("Wave", undefined, 3011); + await client.setRgbEffect("Wave", undefined, 3011, { direction: 3 }); assert.equal(device.profileMode, 0); assert.equal(device.rgbControl, 3); assert.equal(device.rgbEvents, 6); assert.equal(device.rgbPower, 1); const original = device.writes.find(write => write.featureIndex === 8 && write.functionId === 1); - assert.deepEqual(original?.params.slice(0, 13), [0, 3, 0, 255, 0, 0, 0, 0, 11, 195, 100, 1, 1]); + assert.deepEqual(original?.params.slice(0, 13), [0, 3, 0, 255, 0, 0, 0, 0, 11, 195, 100, 3, 1]); await client.setRgbEffect("Static", { red: 0, green: 255, blue: 255 }, undefined, { target: "idle", intensity: 30 }); const idle = device.writes.find(write => write.featureIndex === 8 && write.functionId === 1 && write.params[12] === 5); assert.deepEqual(idle?.params.slice(0, 6), [0, 1, 0, 77, 77, 2]); @@ -450,7 +489,12 @@ test("G915 X TKL claims host mode, encodes new effects, dims, turns off and repl await client.readStatus(); assert.equal(device.rgbPower, 1); assert.equal(device.writes.filter(write => write.featureIndex === 8 && write.functionId === 1 && write.params[12] === 1).length, 2); - await client.setZoneColors([{ zone: 1, red: 255, green: 0, blue: 0 }]); + const key = { zone: 1, red: 255, green: 0, blue: 0 }; + await client.setZoneColors([key]); + key.green = 255; + await client.updateZoneColors([{ zone: 1, red: 0, green: 0, blue: 255 }]); + const painted = device.writes.filter(write => write.featureIndex === 6 && write.functionId === 1).at(-1); + assert.deepEqual(painted?.params.slice(0, 4), [1, 0, 0, 255]); await client.setRgbEffect("Static", { red: 0, green: 255, blue: 0 }); assert.deepEqual(device.writes.filter(write => write.featureIndex === 10 && write.params[0] !== 0).map(write => write.params[0]), [5, 3, 5]); await client.close(); @@ -499,6 +543,19 @@ test("closing a LIGHTSYNC session cancels queued edits before releasing RGB owne assert.equal(device.writes.filter(write => write.featureIndex === 8 && write.functionId === 1).length, 1); }); +test("closing during a failed short LIGHTSYNC read does not retry on the closed device", async () => { + const device = new FakeLogitechKeyboard(); + device.rgbTimers = [0, 0, 0, 60, 1, 44]; + device.shortRgbConfigFails = true; + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + let closing: Promise | undefined; + device.onShortRgbConfigFailure = () => { closing ??= client.close(); }; + await assert.rejects(client.setRgbTimers({ dimAfterSeconds: 30, offAfterDimSeconds: 300 }), /keyboard disconnected/); + await closing; + assert.equal(device.opened, false); + assert.equal(device.writes.filter(write => write.reportId === LOGITECH_LONG_REPORT_ID && write.featureIndex === 8 && write.functionId === 7).length, 0); +}); + test("G915 X TKL leaves a previously active host profile in host mode on close", async () => { const device = new FakeLogitechKeyboard(); device.productId = 0xc357; @@ -513,6 +570,74 @@ test("G915 X TKL leaves a previously active host profile in host mode on close", assert.ok(device.writes.every(write => write.featureIndex !== 10 || write.params[0] !== 3)); }); +test("activating a G915 X TKL onboard profile returns LIGHTSYNC to the keyboard", async () => { + const device = new FakeLogitechKeyboard(); + device.productId = 0xc547; + device.deviceIndex = 2; + device.opened = true; + device.profileMode = 0; + device.rgbControl = 3; + device.rgbEvents = 5; + const directory = Buffer.from("b83806b203018101406331dc3109080281014063f502350e090381014063006734cc0aff", "hex"); + const profile = Buffer.from("0101003c012cffffffffffffffffffffffffffffffffffffffffffffffff18ff008180aaff00006400000000000000000000000019ff008180aaff0000640000000000000000000000000300000000000000000000000044001808ffffffffffffffff", "hex"); + let file = directory; + let reclaimOnSelect = false; + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice, { + slot: 2, + productId: 0x40b6, + longReports: true, + async request(_reportId, body) { + const feature = body[1]; + const fn = body[2] >> 4; + const params = [...body.subarray(3)]; + const reply = (data: readonly number[]) => response(feature, fn, data, device.deviceIndex); + if (feature === 10 && fn === 8) { + file = params[1] === 0 ? directory : profile; + return new Uint8Array(reply([]).buffer); + } + if (feature === 10 && fn === 12) { + const offset = (params[0] << 8) | params[1]; + return new Uint8Array(reply([...file.subarray(offset, offset + 16)]).buffer); + } + if (feature === 10 && fn === 9) { + assert.equal(device.rgbControl, 0, "LIGHTSYNC must be handed back before selecting the stored profile"); + if (reclaimOnSelect) device.rgbControl = 3; + return new Uint8Array(reply([]).buffer); + } + return new Uint8Array(device.reply(feature, fn, params).buffer); + }, + }); + await assert.rejects(client.activateOnboardProfile(4), RangeError); + assert.equal(device.rgbControl, 3); + assert.deepEqual(await client.activateOnboardProfile(1), { enabled: true, activeSlot: 1 }); + assert.equal(device.profileMode, 3); + assert.equal(device.rgbControl, 0); + assert.equal(device.rgbEvents, 0); + + reclaimOnSelect = true; + await assert.rejects(client.activateOnboardProfile(1), /Software still controls the keyboard lighting/); + await client.close(); +}); + +test("G915 X TKL groups matching live colors into one volatile lighting frame", async () => { + const device = new FakeLogitechKeyboard(); + device.productId = 0xc357; + device.modelIds = [0xc357]; + device.profileMode = 1; + device.rgbTimers = [0, 0, 0, 60, 1, 44]; + device.perKeyMask = 0b01111110; + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + const zones = [1, 2, 3, 4, 5, 6]; + await client.setZoneColors(zones.map(zone => ({ zone, red: 0, green: 0, blue: 0 }))); + const before = device.writes.length; + await client.updateZoneColors(zones.map(zone => ({ zone, red: 0, green: 255, blue: 40 })), false); + const writes = device.writes.slice(before); + assert.deepEqual(writes.map(({ featureIndex, functionId }) => [featureIndex, functionId]), [[6, 6], [6, 7]]); + assert.deepEqual(writes[0]?.params.slice(0, 9), [0, 255, 40, ...zones]); + assert.equal(writes[1]?.params[0], 0); + await client.close(); +}); + test("G915 X TKL encodes reactive ripple with its advertised effect and explicit period", async () => { const device = new FakeLogitechKeyboard(); device.productId = 0xc357; @@ -651,6 +776,27 @@ test("0x1001 battery voltage is used when unifiedBattery is absent", async () => await client.close(); }); +test("C547 discovery uses the G915 LIGHTSPEED identity when Bluetooth is listed first", async () => { + const device = new FakeLogitechKeyboard(); + device.productId = 0xc547; + device.deviceIndex = 1; + device.modelIds = [0xb38b, 0x40b6, 0xc357]; + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + assert.equal((await client.readStatus()).logitech?.productId, 0x40b6); + await client.close(); +}); + +test("identify names the receiver's keyboard from its identity block alone", async () => { + const device = new FakeLogitechKeyboard(); + device.productId = 0xc547; + device.deviceIndex = 1; + device.modelIds = [0xb38b, 0x40b6, 0xc357]; + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice); + assert.deepEqual(await client.identify(), { productId: 0x40b6, name: "G915 X LIGHTSPEED TKL" }); + assert.equal(device.writes.length, 2); + await client.close(); +}); + test("a Logitech mouse product id is rejected", () => { const device = { ...new FakeLogitechKeyboard(), productId: 0xc094 }; assert.equal(LogitechKeyboardHidClient.isSupported(device as unknown as HIDDevice), false); @@ -670,6 +816,51 @@ test("a G915 receiver slot resolves to the catalogued G915 model ids", async () await client.close(); }); +for (const failingRead of ["lookup", "value"]) { + test(`shared receiver retries a timed-out identity ${failingRead} once and leaves setters alone`, async () => { + const device = new FakeLogitechKeyboard(); + device.productId = 0xc547; + device.deviceIndex = 2; + device.modelIds = [0x40b6, 0xc357]; + device.opened = true; + let identityReads = 0; + let brightnessWrites = 0; + let persistentFailure = false; + const timeout = () => Object.assign(new Error("radio timeout"), { name: "TimeoutError" }); + const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice, { + slot: 2, + productId: 0x40b6, + longReports: true, + async request(_reportId, body) { + assert.equal(body[0], 2); + const feature = body[1]; + const fn = body[2] >> 4; + const identityLookup = feature === 0 && fn === 0 && body[3] === 0 && body[4] === 3; + const identityValue = feature === 1 && fn === 0; + if (failingRead === "lookup" ? identityLookup : identityValue) { + identityReads += 1; + if (identityReads === 1 || persistentFailure) throw timeout(); + } + if (feature === 4 && fn === 2) { + brightnessWrites += 1; + throw timeout(); + } + return new Uint8Array(device.reply(feature, fn, [...body.subarray(3)]).buffer); + }, + }); + assert.equal((await client.readStatus()).name, "G915 X LIGHTSPEED TKL"); + assert.equal(identityReads, 2); + await assert.rejects(client.setBrightness(300), { name: "TimeoutError" }); + assert.equal(brightnessWrites, 1); + await client.close(); + assert.equal(device.opened, true); + persistentFailure = true; + await assert.rejects(client.readStatus(), { name: "TimeoutError" }); + assert.equal(identityReads, 4); + await client.close(); + }); +} + test("the first setter initializes the receiver slot without taking ownership of the physical handle", async () => { const receiver = new FakeLogitechKeyboard(); receiver.productId = 0xc547; diff --git a/src/drivers/logitech/hid.ts b/src/drivers/logitech/hid.ts index 99ef378..a3edaaa 100644 --- a/src/drivers/logitech/hid.ts +++ b/src/drivers/logitech/hid.ts @@ -1,4 +1,5 @@ import type { KeyboardStatus } from "../keyboard-types.ts"; +import { buildG915XTklGameModeBitmap, GAME_MODE_CONTROL_COUNT, GAME_MODE_CONTROLS_PER_PAGE, hasG915XTklGameModeControls } from "../../logitech/game-mode.js"; import { LOGITECH_DIRECT_DEVICE_INDEX, LOGITECH_FEATURE, @@ -24,6 +25,7 @@ import { decodeLogitechLegacyZoneInfo, decodeLogitechLegacyEffectInfo, logitechRgbMode, + logitechSupportsWaveDirection, isLogitechG915XTkl, buildLogitechControlRemap, decodeLogitechControlInfo, @@ -39,12 +41,21 @@ import { type LogitechBattery, type LogitechBrightnessInfo, type LogitechDeviceInformation, + type LogitechGameModeState, + type LogitechOnboardMemory, + type LogitechOnboardLightingTarget, + type LogitechOnboardProfile, + type LogitechOnboardProfileChanges, + type LogitechAnimation, + type LogitechAnimationSlot, + G915_X_TKL_GAME_MODE_KEYS, type LogitechKeyboardState, type LogitechLightingState, type LogitechLegacyLightingInfo, type LogitechLegacyActiveEffect, type LogitechRgbMode, type LogitechRgbColor, + type LogitechRgbWaveDirection, type LogitechStartupLighting, type LogitechRgbTarget, type LogitechRgbTimers, @@ -71,7 +82,7 @@ function rgbChannels(color: LogitechRgbColor): number[] { return values; } -function rgbEffectParameters(id: number, color: LogitechRgbColor, period: number, intensity: number): number[] { +function rgbEffectParameters(id: number, color: LogitechRgbColor, period: number, intensity: number, direction = 1): number[] { const values = new Array(10).fill(0); if (id === 1 || id === 0x0a || id === 0x17) values.splice(0, 3, ...rgbChannels(color)); if (id === 1) { @@ -90,7 +101,7 @@ function rgbEffectParameters(id: number, color: LogitechRgbColor, period: number } if (id === 4) { values[6] = period & 255; - values[7] = 1; + values[7] = direction; values[8] = intensity; values[9] = period >> 8; } @@ -99,7 +110,7 @@ function rgbEffectParameters(id: number, color: LogitechRgbColor, period: number values[6] = period >> 8; values[7] = period & 255; values[8] = intensity; - if (id === 0x16) values[9] = 1; + if (id === 0x16) values[9] = direction; } if (id === 0x17) { values[3] = 255; @@ -159,6 +170,7 @@ export class LogitechKeyboardHidClient { private pending: PendingRequest | null = null; private deviceIndex = LOGITECH_DIRECT_DEVICE_INDEX; private readonly featureIndexes = new Map(); + private gameModeKeys: Pick | null = null; private longReports = false; private keyboardProductId: number | null = null; private receiver = false; @@ -199,6 +211,13 @@ export class LogitechKeyboardHidClient { } const pending = this.pending; if (!pending) return; + if (this.receiver && response.featureIndex === 0x8f && data[2] === pending.featureIndex + && data[3] === ((pending.functionId << 4) | pending.softwareId)) { + this.pending = null; + clearTimeout(pending.timer); + pending.reject(new Error(`The Logitech receiver rejected that request (HID++ 1.0 error 0x${data[4]!.toString(16)}).`)); + return; + } const isError = response.featureIndex === 0xff; if (isError) { if (response.requestFeatureIndex !== pending.featureIndex) return; @@ -220,14 +239,12 @@ export class LogitechKeyboardHidClient { this.keyboardProductId = this.endpoint.productId; this.receiver = true; this.longReports = this.endpoint.longReports; + this.listen(); return; } if (!LogitechKeyboardHidClient.isSupported(this.device)) throw new Error("Not a supported Logitech HID++ keyboard."); if (!this.device.opened) await this.device.open(); - if (!this.listening) { - this.device.addEventListener("inputreport", this.onInputReport); - this.listening = true; - } + this.listen(); this.longReports = LogitechKeyboardHidClient.hasLongCollection(this.device.collections) || LogitechKeyboardHidClient.hasCollectionPage(this.device.collections, LOGITECH_HIDPP_BLUETOOTH_USAGE_PAGE); if (!this.indexResolved) { @@ -240,6 +257,13 @@ export class LogitechKeyboardHidClient { } } + private listen(): void { + if (!this.listening) { + this.device.addEventListener("inputreport", this.onInputReport); + this.listening = true; + } + } + private static hasLongCollection(collections: readonly HIDCollectionInfo[]): boolean { for (const collection of collections) { if (collection.usagePage === LOGITECH_HIDPP_USAGE_PAGE && collection.usage === 2) return true; @@ -277,6 +301,7 @@ export class LogitechKeyboardHidClient { async close(): Promise { this.session += 1; + this.gameModeKeys = null; const pending = this.pending; this.pending = null; if (pending) { @@ -320,7 +345,9 @@ export class LogitechKeyboardHidClient { const response = await new Promise((resolve, reject) => { const timer = setTimeout(() => { if (this.pending?.timer === timer) this.pending = null; - reject(new Error(`The Logitech keyboard did not answer feature 0x${featureIndex.toString(16)} function 0x${functionId.toString(16)}.`)); + const error = new Error(`The Logitech keyboard did not answer feature 0x${featureIndex.toString(16)} function 0x${functionId.toString(16)}.`); + error.name = "TimeoutError"; + reject(error); }, timeoutMs); this.pending = { reportId, featureIndex, functionId, softwareId: (data[2] ?? 0) & 0x0f, resolve, reject, timer }; void this.device.sendReport(reportId, data).catch((error: unknown) => { @@ -359,15 +386,27 @@ export class LogitechKeyboardHidClient { * error rather than a client that silently invents a keyboard. */ private async resolveReceiverKeyboard(): Promise { + // A LIGHTSPEED slot can answer after waking its paired keyboard. + const lightspeed = this.device.productId === 0xc547; + const timeout = lightspeed ? RESPONSE_TIMEOUT_MS : 350; + const identity = async (feature: number, params: readonly number[]) => { + const read = () => this.rawRequest(feature, 0, params, timeout); + return read().catch(error => { + if (lightspeed && error instanceof Error && error.name === "TimeoutError") return read(); + throw error; + }); + }; for (const candidate of [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, LOGITECH_DIRECT_DEVICE_INDEX]) { this.deviceIndex = candidate; try { - const rootParams = await this.rawRequest(0, 0, [LOGITECH_FEATURE.deviceInformation >> 8, LOGITECH_FEATURE.deviceInformation & 0xff, 0x00], 350); + const rootParams = await identity(0, [LOGITECH_FEATURE.deviceInformation >> 8, LOGITECH_FEATURE.deviceInformation & 0xff, 0x00]); const root = decodeLogitechFeatureInfo(rootParams); if (!root) continue; - const deviceParams = await this.rawRequest(root.index, 0, [0x00, 0x00, 0x00], 350); + const deviceParams = await identity(root.index, [0x00, 0x00, 0x00]); const info = decodeLogitechDeviceInformation(deviceParams); - const productId = info?.modelIds.find((id) => LOGITECH_KEYBOARD_PRODUCTS.has(id)); + // This G915 advertises its Bluetooth ID first even on LIGHTSPEED. + const productId = lightspeed && info?.modelIds.includes(0x40b6) + ? 0x40b6 : info?.modelIds.find((id) => LOGITECH_KEYBOARD_PRODUCTS.has(id)); if (productId === undefined) continue; this.keyboardProductId = productId; this.featureIndexes.set(LOGITECH_FEATURE.deviceInformation, root.index); @@ -392,9 +431,19 @@ export class LogitechKeyboardHidClient { } private async readDeviceInformation(): Promise<{ device: LogitechDeviceInformation; firmware: string | null; serial: string | null }> { - const index = await this.getFeature(LOGITECH_FEATURE.deviceInformation); - if (!index) return { device: { entityCount: 0, unitId: "", transport: [], modelIds: [], extendedModelId: 0, serialNumber: false }, firmware: null, serial: null }; - const info = decodeLogitechDeviceInformation(await this.request(index, 0x00, [0x00, 0x00, 0x00])); + const readInfo = async () => { + const index = await this.getFeature(LOGITECH_FEATURE.deviceInformation); + const params = index ? await this.request(index, 0x00, [0x00, 0x00, 0x00]) : null; + return { index, params }; + }; + 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; + return readInfo(); + }); + if (!params) return { device: { entityCount: 0, unitId: "", transport: [], modelIds: [], extendedModelId: 0, serialNumber: false }, firmware: null, serial: null }; + const info = decodeLogitechDeviceInformation(params); if (!info) throw new Error("The Logitech keyboard returned an unreadable device-information block."); const firmware = await this.request(index, 0x01, [0x00, 0x00, 0x00]) .then((params) => decodeLogitechFirmwareInfo(params)?.version ?? null) @@ -650,12 +699,17 @@ export class LogitechKeyboardHidClient { // The G915 X can answer a short request with a long response. Try both // report types so capability reads survive a missing or slow HID interface. private async readRgbRegister(index: number, fn: number, params: readonly number[], bytes: number, matches = (_reply: Uint8Array) => true): Promise { + const session = this.session; const read = async (long: boolean): Promise => { const reply = await this.requestMode(index, fn, params, long); if (reply.length < bytes || !matches(reply)) throw new Error("The keyboard returned an unexpected LIGHTSYNC response."); return reply; }; - return read(false).catch(() => read(true)); + return read(false).catch(error => { + // A retry after close() would reopen the device. + if (session !== this.session) throw error; + return read(true); + }); } private async readRgbEffects(index: number, info: Uint8Array | null): Promise { @@ -674,6 +728,7 @@ export class LogitechKeyboardHidClient { index: effect, id: ((effectInfo[2] ?? 0) << 8) | (effectInfo[3] ?? 0), period: ((effectInfo[6] ?? 0) << 8) | (effectInfo[7] ?? 0), + capabilities: (effectInfo[4] << 8) | effectInfo[5], }); } if (effects.length) zones.push({ index: cluster, location, effects }); @@ -736,13 +791,15 @@ export class LogitechKeyboardHidClient { } private async setRgbPower(index: number, power: number): Promise { + const session = this.session; for (let attempt = 0; ; attempt++) { try { await this.requestMode(index, 8, [1, power, 0], true); return; } catch (error) { - if (attempt === 2) throw error; + if (attempt === 2 || session !== this.session) throw error; await new Promise(resolve => setTimeout(resolve, 100)); + if (session !== this.session) throw error; } } } @@ -931,7 +988,7 @@ export class LogitechKeyboardHidClient { mode: LogitechRgbMode, color?: { red: number; green: number; blue: number }, periodMs?: number, - options: { cluster?: number; target?: LogitechRgbTarget; intensity?: number } = {}, + options: { cluster?: number; target?: LogitechRgbTarget; intensity?: number; direction?: LogitechRgbWaveDirection } = {}, ): Promise { return this.serialized(async () => { const session = this.session; @@ -957,6 +1014,10 @@ export class LogitechKeyboardHidClient { return effect ? [{ zone, effect }] : []; }); if (!effects.length) throw new Error(`No Logitech RGB cluster advertises the ${effectMode} effect.`); + if (effectMode === "Wave" && options.direction !== undefined + && !effects.every(({ effect }) => logitechSupportsWaveDirection(effect, options.direction!))) { + throw new RangeError("The selected RGB clusters do not advertise that wave direction."); + } if (idle) await this.readRgbPowerConfig(index); const keyMode = idle ? null : this.rgbHost; const previousEffects = keyMode?.keyColors.size ? keyMode.activeEffects : null; @@ -985,7 +1046,7 @@ export class LogitechKeyboardHidClient { const defaultPeriod = effectMode === "Ripple" ? 50 : Math.min(Math.floor(65535 / unit), Math.max(1, Math.round(5000 / unit))) * unit; const period = periodMs ?? defaultPeriod; - const payload = [zone.index, effect.index, ...rgbEffectParameters(effect.id, rgb, period, intensity), flags, 0, 0, 0]; + const payload = [zone.index, effect.index, ...rgbEffectParameters(effect.id, rgb, period, intensity, options.direction), flags, 0, 0, 0]; await this.requestMode(index, 1, payload, true); if (idle) host?.idleEffects.set(zone.index, payload); else if (host) { @@ -1105,6 +1166,44 @@ export class LogitechKeyboardHidClient { }); } + /** Update a prepared volatile per-key frame without rereading capabilities. */ + updateZoneColors(colors: readonly (LogitechRgbColor & { zone: number })[], wake = true): Promise { + const frame = colors.map(({ zone, red, green, blue }) => ({ zone, red, green, blue })); + return this.serialized(async () => { + if (!frame.length) return; + const host = this.rgbHost; + if (!host || host.releasePending || host.keyIndex === null || frame.some(({ zone }) => !host.keyColors.has(zone))) { + throw new Error("Prepare those per-key lighting zones before sending live frames."); + } + const groups = new Map(); + for (const color of frame) { + const rgb = rgbChannels(color); + const packed = (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]; + const group = groups.get(packed) ?? { rgb, zones: [] }; + group.zones.push(color.zone); + groups.set(packed, group); + } + if (host.dimmed) { + if (!wake) return; + await this.wakeRgbForEdit(host); + } + const groupWrites = [...groups.values()].reduce((total, { zones }) => total + Math.ceil(zones.length / 13), 0); + if (groupWrites < Math.ceil(frame.length / 4)) { + for (const { rgb, zones } of groups.values()) { + for (let offset = 0; offset < zones.length; offset += 13) { + const chunk = zones.slice(offset, offset + 13); + const reply = await this.requestMode(host.keyIndex, 6, [...rgb, ...chunk], true); + if (reply[3] !== chunk[0]) throw new Error("The Logitech keyboard did not acknowledge the per-key colour frame."); + } + } + await this.requestMode(host.keyIndex, 7, [0, 0, 0, 0, 0, 0], true); + } else { + await this.writeZoneFrame(host.keyIndex, frame, false); + } + for (const { zone, ...color } of frame) host.keyColors.set(zone, color); + }); + } + private async readAnalog(): Promise { const index = await this.getFeature(LOGITECH_FEATURE.analogKeys); if (!index) return null; @@ -1152,10 +1251,184 @@ export class LogitechKeyboardHidClient { }); } + private isG915XTklLightspeed(): boolean { + return (this.keyboardProductId ?? this.device.productId) === 0x40b6 && this.receiver && this.longReports; + } + + private async onboardFilesystem() { + await this.open(); + const index = this.isG915XTklLightspeed() ? await this.getFeature(RGB_PROFILE_MANAGEMENT) : 0; + if (!index) throw new Error("Onboard profiles are unavailable on this Logitech connection."); + const { LogitechOnboardFilesystem } = await import("../../logitech/onboard.js"); + return new LogitechOnboardFilesystem((fn, params = []) => this.requestMode(index, fn, params, true)); + } + + readOnboardMemory(): Promise { + return this.serialized(async () => { + const state = await (await this.onboardFilesystem()).read(); + const animations = await this.readOnboardAnimations().catch(() => undefined); + return { ...state, animations }; + }); + } + + private async readOnboardAnimations(): Promise { + const dfu = await this.getFeature(0x00d0); + const rgb = await this.getFeature(LOGITECH_FEATURE.rgbEffects); + if (!dfu || !rgb) return undefined; + const { readLogitechAnimationSlot } = await import("../../logitech/onboard-animation.js"); + const request = (fn: number, params: readonly number[]) => this.requestMode(rgb, fn, params, true); + return [await readLogitechAnimationSlot(request, 0), await readLogitechAnimationSlot(request, 1)]; + } + + saveOnboardAnimation(slot: 0 | 1, expectedName: string | null, animation: LogitechAnimation): Promise { + return this.serialized(async () => { + await this.open(); + if (!this.isG915XTklLightspeed() || (slot !== 0 && slot !== 1)) throw new Error("Onboard animations are unavailable on this connection."); + const animations = await this.readOnboardAnimations(); + if (!animations || animations.find(item => item.slot === slot)?.name !== expectedName) { + throw new Error("The stored animation changed. Read the keyboard again before saving."); + } + const { encodeLogitechAnimation, uploadLogitechAnimation } = await import("../../logitech/onboard-animation.js"); + const uuid = globalThis.crypto.getRandomValues(new Uint8Array(16)); + uuid[6] = uuid[6]! & 0x0f | 0x40; + uuid[8] = uuid[8]! & 0x3f | 0x80; + const data = encodeLogitechAnimation(animation, uuid); + const index = await this.getFeature(0x00d0); + const request = (fn: number, params: readonly number[]) => this.rawRequest(index, fn, params, 5000, true); + await uploadLogitechAnimation(request, slot, data, () => new Promise(resolve => setTimeout(resolve, 2500))); + const confirmed = await this.readOnboardAnimations(); + if (!confirmed || confirmed.find(item => item.slot === slot)?.name !== animation.name.trim()) { + throw new Error("The keyboard acknowledged the upload but did not report the expected animation name."); + } + return confirmed; + }); + } + + activateOnboardProfile(slot: number): Promise> { + return this.serialized(async () => { + const fs = await this.onboardFilesystem(); + const rgb = await this.getFeature(LOGITECH_FEATURE.rgbEffects); + if (!rgb) throw new Error("The keyboard did not report its LIGHTSYNC controls."); + const readControl = () => this.readRgbRegister(rgb, 5, [0, 0, 0], 3); + const active = await fs.activate(slot, async () => { + if (this.rgbHost) await this.releaseRgbHost(); + // Profile mode and LIGHTSYNC ownership are independent. Ownership can + // survive a previous client and hide the effect in the selected slot. + const flags = await readControl(); + if (flags[1] & RGB_HOST_CONTROL) await this.setRgbControl(rgb, flags[1] & ~RGB_HOST_CONTROL, 0); + }); + if ((await readControl())[1] & RGB_HOST_CONTROL) { + throw new Error("Software still controls the keyboard lighting. Close G HUB and try activating the onboard profile again."); + } + return active; + }); + } + + leaveOnboardMemory(): Promise> { + return this.serialized(async () => (await this.onboardFilesystem()).leave()); + } + + saveOnboardProfile(slot: number, revision: number, changes: LogitechOnboardProfileChanges): Promise { + return this.serialized(async () => { + const fs = await this.onboardFilesystem(); + const requested = { keys: changes.lighting, ...changes.lightingByTarget }; + const effects: Partial> = {}; + if (Object.values(requested).some(Boolean)) { + const zones = (await this.readLightingZones())?.rgbZones; + for (const target of ["keys", "logo", "idleKeys", "idleLogo"] as const) { + const change = requested[target]; + if (!change) continue; + const { mode, color = { red: 255, green: 255, blue: 255 }, periodMs = mode === "Ripple" ? 50 : 3000 } = change; + const min = mode === "Ripple" ? 2 : 1; + const max = mode === "Ripple" ? 200 : 65535; + if (!Number.isInteger(periodMs) || periodMs < min || periodMs > max) throw new RangeError("Invalid onboard effect period."); + const location = target === "logo" || target === "idleLogo" ? 2 : 1; + const effect = zones?.find(zone => zone.location === location)?.effects.find(entry => logitechRgbMode(entry.id) === mode); + if (!effect || (mode === "Ripple" && target !== "keys")) throw new Error("The keyboard does not advertise the requested onboard lighting effect for that target."); + effects[target] = [effect.id, ...rgbEffectParameters(effect.id, color, periodMs, 100)]; + } + } + if (changes.animationSlot !== undefined) { + const animations = await this.readOnboardAnimations(); + if (!animations?.find(item => item.slot === changes.animationSlot)?.name) throw new Error("The selected onboard animation is empty."); + effects.keys = [0x0c, changes.animationSlot, 0, 0, 0, 0, 0, 0, 100, 0, 0]; + } + let binding: { index: number; usage: number | null; modifiers: number } | undefined; + if (changes.binding) { + const { sourceUsage, targetUsage, modifiers } = changes.binding; + const gameMode = await this.readGameModeRaw(); + const id = G915_X_TKL_GAME_MODE_KEYS.get(sourceUsage); + const index = id === undefined ? -1 : gameMode?.controls.indexOf(id) ?? -1; + if (index < 0 || !await this.getFeature(0x1b05)) throw new Error("The key cannot be assigned on this keyboard."); + binding = { index, usage: targetUsage, modifiers }; + } + let gameModeBitmap: Uint8Array | undefined; + if (changes.gameModeDisabledKeys) { + const gameMode = await this.readGameModeRaw(); + if (!gameMode) throw new Error("The keyboard did not report its Game Mode controls."); + gameModeBitmap = buildG915XTklGameModeBitmap(gameMode.controls, changes.gameModeDisabledKeys); + } + return fs.save(slot, revision, { ...changes, effects, gameModeBitmap, binding }); + }); + } + + private async readGameModeRaw(): Promise { + if (!this.isG915XTklLightspeed()) return null; + const index = await this.getFeature(LOGITECH_FEATURE.disableControls); + const list = await this.getFeature(LOGITECH_FEATURE.controlList); + if (!index || !list) return null; + const [flags] = await this.requestMode(index, 1, [], false); + if (flags === undefined) throw new Error("The Logitech keyboard did not report its Game Mode state."); + if (!this.gameModeKeys) { + const [count] = await this.requestMode(list, 0, [], false); + if (count !== GAME_MODE_CONTROL_COUNT) return null; + const controls: number[] = []; + for (let start = 0; start < count; start += GAME_MODE_CONTROLS_PER_PAGE) { + const page = await this.requestMode(list, 1, [start], true); + if (page.length !== GAME_MODE_CONTROLS_PER_PAGE * 2) throw new Error("Incomplete Logitech Game Mode control list."); + for (let offset = 0; offset < page.length; offset += 2) { + controls.push((page[offset]! << 8) | page[offset + 1]!); + } + } + if (!hasG915XTklGameModeControls(controls)) return null; + const layoutCode = await (async () => { + const layout = await this.getFeature(LOGITECH_FEATURE.keyboardLayout); + return layout ? (await this.requestMode(layout, 0, [], false))[0] ?? null : null; + })().catch(() => null); + this.gameModeKeys = { controls, layoutCode }; + } + return { active: Boolean(flags & 1), ...this.gameModeKeys }; + } + + setGameModeDisabledKeys(disabled: readonly number[]): Promise { + return this.serialized(async () => { + await this.open(); + const state = await this.readGameModeRaw(); + if (!state) throw new Error("Game Mode configuration is unavailable on this Logitech connection."); + const bitmap = buildG915XTklGameModeBitmap(state.controls, disabled); + const index = await this.getFeature(LOGITECH_FEATURE.disableControls); + await this.requestMode(index, 0, [...bitmap], true); + return state; + }); + } + + /** Name the keyboard this handle reaches without reading any of its settings. */ + identify(): Promise<{ productId: number; name: string } | null> { + return this.serialized(async () => { + await this.open(); + const productId = this.keyboardProductId ?? this.device.productId; + const product = LOGITECH_KEYBOARD_PRODUCTS.get(productId); + return product ? { productId, name: product.name } : null; + }); + } + readStatus({ refreshFeatures = false }: { refreshFeatures?: boolean } = {}): Promise { return this.serialized(async () => { await this.open(); - if (refreshFeatures) this.featureIndexes.clear(); + if (refreshFeatures) { + this.featureIndexes.clear(); + this.gameModeKeys = null; + } const { device, firmware, serial } = await this.readDeviceInformation(); if (this.rgbHost?.releasePending) await this.releaseRgbHost().catch(() => undefined); const battery = await this.readBattery().catch(() => null); @@ -1163,6 +1436,8 @@ export class LogitechKeyboardHidClient { const brightness = await this.readBrightness().catch(() => null); const analog = await this.readAnalog().catch(() => null); const lighting = await this.readLightingZones().catch(() => null); + const gameMode = await this.readGameModeRaw().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); if (!product) throw new Error("The Logitech device did not identify a catalogued keyboard."); @@ -1187,6 +1462,8 @@ export class LogitechKeyboardHidClient { analog, lighting, controls: null, + gameMode, + onboardMemory, wireless, verified: product.verified, }; diff --git a/src/logitech/game-mode.ts b/src/logitech/game-mode.ts new file mode 100644 index 0000000..4cae03e --- /dev/null +++ b/src/logitech/game-mode.ts @@ -0,0 +1,50 @@ +export interface LogitechGameModeState { + active: boolean; + /** Control IDs advertised by the keyboard. Zero is a reserved position. */ + controls: readonly number[]; + layoutCode: number | null; +} + +export const GAME_MODE_CONTROL_COUNT = 128; +export const GAME_MODE_CONTROLS_PER_PAGE = 8; + +// The G915 X TKL has five factory blocks, including the Windows and menu keys. +// Use control IDs so the bitmap follows the order reported by the keyboard. +export const G915_X_TKL_FACTORY_BLOCKS: readonly number[] = [0x004f, 0x018c, 0x0159, 0x0184, 0x018a]; + +/** HID keyboard usages to Logitech control IDs for the G915 X TKL. */ +export const G915_X_TKL_GAME_MODE_KEYS: ReadonlyMap = new Map([ + ...Array.from({ length: 26 }, (_, index): [number, number] => [0x04 + index, 0x0122 + index]), + ...Array.from({ length: 9 }, (_, index): [number, number] => [0x1e + index, 0x0143 + index]), + [0x27, 0x0142], [0x28, 0x0155], [0x29, 0x014c], [0x2a, 0x0156], [0x2b, 0x010c], [0x2c, 0x0161], + [0x2d, 0x0158], [0x2e, 0x0153], [0x2f, 0x015a], [0x30, 0x015b], [0x31, 0x011e], [0x32, 0x0169], + [0x33, 0x015c], [0x34, 0x015d], [0x35, 0x010b], [0x36, 0x0160], [0x37, 0x015f], [0x38, 0x015e], + [0x39, 0x010d], [0x3a, 0x00f6], [0x3b, 0x00ef], [0x3c, 0x00f0], [0x3d, 0x00f1], [0x3e, 0x00f2], + [0x3f, 0x00f3], [0x40, 0x00f4], [0x41, 0x00f5], [0x42, 0x014d], [0x43, 0x014e], [0x44, 0x014f], + [0x45, 0x0150], [0x46, 0x004c], [0x47, 0x004e], [0x48, 0x004d], [0x49, 0x0116], [0x4a, 0x0118], + [0x4b, 0x011a], [0x4c, 0x0117], [0x4d, 0x0119], [0x4e, 0x011b], [0x4f, 0x00eb], [0x50, 0x00ec], + [0x51, 0x0152], [0x52, 0x0151], [0x64, 0x016a], [0x65, 0x004f], + [0xe0, 0x010f], [0xe1, 0x010e], [0xe2, 0x018b], [0xe3, 0x018c], [0xe4, 0x0114], [0xe5, 0x0115], + [0xe6, 0x018d], +]); + +const G915_X_TKL_SELECTABLE_CONTROLS = new Set([...G915_X_TKL_GAME_MODE_KEYS.values(), 0x00e4, 0x00e5, 0x00e6, 0x00e7]); + +export function hasG915XTklGameModeControls(controls: readonly number[]): boolean { + return controls.length === GAME_MODE_CONTROL_COUNT && G915_X_TKL_FACTORY_BLOCKS.every(id => controls.includes(id)); +} + +export function buildG915XTklGameModeBitmap(controls: readonly number[], disabled: readonly number[]): Uint8Array { + if (!hasG915XTklGameModeControls(controls)) { + throw new Error("This G915 X TKL did not report the expected Game Mode controls."); + } + if (disabled.some(id => !G915_X_TKL_SELECTABLE_CONTROLS.has(id) || !controls.includes(id))) { + throw new RangeError("The selected Game Mode key is not available on this keyboard."); + } + const bitmap = new Uint8Array(GAME_MODE_CONTROL_COUNT / 8); + for (const id of [...G915_X_TKL_FACTORY_BLOCKS, ...disabled]) { + const position = controls.indexOf(id); + bitmap[position >> 3]! |= 1 << (position & 7); + } + return bitmap; +} diff --git a/src/logitech/index.ts b/src/logitech/index.ts index f953511..56a0ac6 100644 --- a/src/logitech/index.ts +++ b/src/logitech/index.ts @@ -1,4 +1,7 @@ export * from "./controls.js"; +export { G915_X_TKL_FACTORY_BLOCKS, G915_X_TKL_GAME_MODE_KEYS, type LogitechGameModeState } from "./game-mode.js"; +export type { LogitechAnimation, LogitechAnimationFrame, LogitechAnimationSlot } from "./onboard-animation.js"; +export type { LogitechOnboardBinding, LogitechOnboardEffect, LogitechOnboardLightingChange, LogitechOnboardLightingMode, LogitechOnboardLightingTarget, LogitechOnboardMemory, LogitechOnboardProfile, LogitechOnboardProfileChanges } from "./onboard.js"; /** * Logitech HID++ 2.0 keyboard codec. * @@ -30,6 +33,9 @@ export const LOGITECH_FEATURE = { unifiedBattery: 0x1004, reprogControls: 0x1b04, analogKeys: 0x1b08, + controlList: 0x1b10, + disableControls: 0x4523, + keyboardLayout: 0x4540, brightnessControl: 0x8040, colorLedEffects: 0x8070, rgbEffects: 0x8071, @@ -554,6 +560,7 @@ export interface LogitechRgbEffectInfo { index: number; id: number; period: number; + capabilities?: number; } export interface LogitechRgbZoneInfo { @@ -563,6 +570,14 @@ export interface LogitechRgbZoneInfo { } export type LogitechRgbMode = "Off" | "Static" | "Cycling" | "Wave" | "Breathing single" | "Ripple"; +export type LogitechRgbWaveDirection = 1 | 2 | 3 | 6 | 7 | 8; + +export function logitechSupportsWaveDirection(effect: LogitechRgbEffectInfo, direction: LogitechRgbWaveDirection): boolean { + if (effect.id !== 0x04 && effect.id !== 0x16) return false; + if (direction === 1) return true; + const mask = effect.capabilities ?? 0; + return (mask & 1) !== 0 && (mask & (1 << (direction + 4))) !== 0; +} const LOGITECH_RGB_EFFECT_IDS: Readonly> = { 0x00: "Off", @@ -629,6 +644,9 @@ export interface LogitechKeyboardState { analog: LogitechAnalogState | null; lighting: LogitechLightingState | null; controls: readonly import("./controls.js").LogitechControl[] | null; + /** Game Mode button state. The firmware does not return the disabled-key bitmap. */ + gameMode?: import("./game-mode.js").LogitechGameModeState | null; + onboardMemory?: boolean; wireless: boolean; verified: boolean; } diff --git a/src/logitech/onboard-animation.test.ts b/src/logitech/onboard-animation.test.ts new file mode 100644 index 0000000..64b7343 --- /dev/null +++ b/src/logitech/onboard-animation.test.ts @@ -0,0 +1,23 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { encodeLogitechAnimation, uploadLogitechAnimation } from "./onboard-animation.ts"; + +test("onboard animation creates a complete RGB-only transfer and verifies each acknowledgement", async () => { + const colors = [{ zone: 1, red: 255, green: 0, blue: 0 }]; + const data = encodeLogitechAnimation({ name: "Aurora", frameMs: 120, frames: [{ colors }] }, new Uint8Array(16)); + assert.deepEqual([...data.slice(0x4b, 0x50)], [0x1b, 1, 255, 0, 0]); + assert.deepEqual([...data.slice(-16)], [3, ...new Uint8Array(15)]); + let count = 0; + await uploadLogitechAnimation(async (fn, bytes) => { + if (fn === 4) { + assert.deepEqual(bytes.slice(0, 2), [4, 1]); + assert.equal(new TextDecoder().decode(Uint8Array.from(bytes.slice(2))), "RGB_V0000"); + return Uint8Array.of(0, 0, 0, 0, 1); + } + count++; + assert.equal(fn, count % 4); + assert.equal(bytes.length, 16); + return Uint8Array.of(0, 0, count >> 8, count & 255, count === data.length / 16 ? 2 : 1); + }, 1, data, async () => {}); + assert.equal(count, data.length / 16); +}); diff --git a/src/logitech/onboard-animation.ts b/src/logitech/onboard-animation.ts new file mode 100644 index 0000000..df80499 --- /dev/null +++ b/src/logitech/onboard-animation.ts @@ -0,0 +1,107 @@ +import type { LogitechRgbColor } from "./index.js"; + +export interface LogitechAnimationSlot { + slot: 0 | 1; + name: string | null; +} + +export interface LogitechAnimationFrame { + colors: readonly (LogitechRgbColor & { zone: number })[]; +} + +export interface LogitechAnimation { + name: string; + frames: readonly LogitechAnimationFrame[]; + frameMs: number; +} + +const HEADER = 0x4b; +const BODY = 12304; +const PACKET = 16; +const RECORD = 17; + +type Request = (fn: number, params: readonly number[]) => Promise; + +export async function readLogitechAnimationSlot(request: Request, slot: 0 | 1): Promise { + const name = new Uint8Array(33); + for (let part = 0; part < 3; part++) { + const reply = await request(0, [0xff, 0, 1, slot, part + 4]); + if (reply.length !== 16 || reply[0] !== 0xff || reply[2] !== 1) throw new Error("Invalid Logitech animation metadata."); + name.set(reply.subarray(5), 11 * part); + } + const end = name.findIndex(byte => byte === 0 || byte === 0xff); + const decoded = new TextDecoder().decode(end < 0 ? name : name.subarray(0, end)).trim(); + return { slot, name: decoded || null }; +} + +export function encodeLogitechAnimation(animation: LogitechAnimation, uuid: Uint8Array): Uint8Array { + const name = animation.name.trim(); + if (!/^[\x20-\x7e]{1,31}$/.test(name) || !Number.isInteger(animation.frameMs) || animation.frameMs < 20 || animation.frameMs > 5000 || + animation.frames.length < 1 || animation.frames.length > 64 || uuid.length !== 16) throw new RangeError("Invalid Logitech onboard animation."); + const data = new Uint8Array(BODY + PACKET).fill(0xff); + data.fill(0, 0, HEADER); + data[0] = 1; + data[7] = 0x30; + data.set(new TextEncoder().encode(name), 0x10); + data.set(uuid, 0x30); + const header = new DataView(data.buffer); + header.setUint16(0x40, animation.frames.length); + header.setUint16(0x46, animation.frames.length); + header.setUint16(0x48, animation.frameMs); + data[0x4a] = 100; + let offset = HEADER; + function record(op: number, fields: readonly number[]): void { + if (offset + RECORD > BODY) throw new RangeError("The animation is too large for the Logitech onboard slot."); + data.fill(0, offset, offset + RECORD); + data[offset] = op; + data.set(fields, offset + 1); + offset += RECORD; + } + let previous = new Map(); + animation.frames.forEach(({ colors }, index) => { + const current = new Map(); + const byColor = new Map(); + for (const { zone, red, green, blue } of colors) { + if (!Number.isInteger(zone) || zone < 1 || zone > 254 || current.has(zone) || + ![red, green, blue].every(value => Number.isInteger(value) && value >= 0 && value <= 255)) { + throw new RangeError("Invalid key color in the onboard animation."); + } + const color = (red << 16) | (green << 8) | blue; + current.set(zone, color); + if (previous.get(zone) === color) continue; + const group = byColor.get(color) ?? []; + group.push(zone); + byColor.set(color, group); + } + if (!current.size || [...previous.keys()].some(zone => !current.has(zone))) throw new RangeError("Every animation frame must contain the same keys."); + const separate: number[] = []; + for (const [color, zones] of byColor) { + const rgb = [color >>> 16, (color >>> 8) & 255, color & 255]; + if (zones.length < 4) { + for (const zone of zones) separate.push(zone, ...rgb); + } else { + for (let i = 0; i < zones.length; i += 13) record(0x6b, [...rgb, ...zones.slice(i, i + 13)]); + } + } + for (let i = 0; i < separate.length; i += 16) record(0x1b, separate.slice(i, i + 16)); + record(0x7b, [0, index >>> 8, index & 255, 0, 1]); + previous = current; + }); + data.fill(0, BODY); + data[BODY] = 3; + return data; +} + +export async function uploadLogitechAnimation(request: Request, slot: 0 | 1, data: Uint8Array, waitUntilReady: () => Promise): Promise { + const header = Array.from(new TextEncoder().encode("RGB_V0000")); + const opening = await request(4, [4, slot, ...header]); + if (opening[4] !== 1 && opening[4] !== 3) throw new Error("The keyboard refused the onboard animation upload."); + await waitUntilReady(); + const count = data.length / PACKET; + for (let packet = 1; packet <= count; packet++) { + const reply = await request(packet % 4, Array.from(data.subarray((packet - 1) * PACKET, packet * PACKET))); + if (((reply[2] ?? 0) << 8 | (reply[3] ?? 0)) !== packet || reply[4] !== (packet === count ? 2 : 1)) { + throw new Error(`The keyboard stopped the onboard animation upload at packet ${packet}.`); + } + } +} diff --git a/src/logitech/onboard.test.ts b/src/logitech/onboard.test.ts new file mode 100644 index 0000000..ff99f26 --- /dev/null +++ b/src/logitech/onboard.test.ts @@ -0,0 +1,163 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { LogitechOnboardFilesystem } from "./onboard.ts"; + +// The three factory-equivalent profile files, captured over LIGHTSPEED. +const rawProfile = Buffer.from("0101003c012cffffffffffffffffffffffffffffffffffffffffffffffff18ff008180aaff00006400000000000000000000000019ff008180aaff0000640000000000000000000000000300000000000000000000000044001808ffffffffffffffff", "hex"); +const rawDirectory = Buffer.from("b83806b203018101406331dc3109080281014063f502350e090381014063006734cc0aff", "hex"); + +function emulatedMemory() { + const sectors = new Map([[0, rawDirectory]]); + for (let slot = 1; slot <= 3; slot++) { + const data = Buffer.from(rawProfile); + data[0] = slot; + sectors.set(slot + 7, data); + } + let buffer: Buffer = Buffer.alloc(0); + let page = 0; + let mode = 0; + let active = 1; + const commits: number[] = []; + const faults = { badStagedSector: false, loseDirectoryReply: false, rejectSelection: false }; + const filesystem = new LogitechOnboardFilesystem(async (fn, params = []) => { + const data = Buffer.from(params); + switch (fn) { + case 0: return Buffer.from("0101008005807f7f0714ffffff200307", "hex"); + case 2: buffer = Buffer.alloc(data.readUInt16BE()); page = 0; break; + case 3: { + data.copy(buffer, page++ * 16); + const reply = Buffer.alloc(16); + reply.writeUInt16BE(page); + return reply; + } + case 6: { + const command = data[0] ?? 0; + if (command & 1) mode = (mode & ~1) | ((command >> 1) & 1); + if (command & 4) mode = (mode & ~2) | ((command >> 2) & 2); + return Uint8Array.of(mode, 0, active); + } + case 7: { + const sector = data[1]!; + const written = Buffer.from(buffer); + if (faults.badStagedSector && sector !== 0) written[10] ^= 128; + sectors.set(sector, written); + commits.push(sector); + if (faults.loseDirectoryReply && sector === 0) throw new Error("lost acknowledgement"); + break; + } + case 8: + buffer = Buffer.alloc(data.readUInt16BE(2)); + sectors.get(data[1]!)?.copy(buffer); + break; + case 9: + if (faults.rejectSelection) throw new Error("profile rejected"); + active = data[4]!; + break; + case 12: { + const reply = Buffer.alloc(16); + const offset = data.readUInt16BE(); + buffer.copy(reply, 0, offset, offset + 16); + return reply; + } + default: throw new Error(`unexpected function ${fn}`); + } + return new Uint8Array(16); + }); + return { filesystem, sectors, commits, faults, mode: () => mode }; +} + +test("saving onboard writes and verifies a new sector before replacing the directory entry", async () => { + const { filesystem, sectors, commits, faults, mode } = emulatedMemory(); + const before = await filesystem.read(); + faults.loseDirectoryReply = true; + const changed = await filesystem.save(3, before.profiles[2]!.revision, { name: "Noche ñ", dimAfterSeconds: 30 }); + assert.deepEqual(commits, [11, 0]); + assert.equal(changed.name, "Noche ñ"); + assert.equal(changed.dimAfterSeconds, 30); + const after = await filesystem.read(); + assert.deepEqual(after.profiles, [...before.profiles.slice(0, 2), changed]); + assert.deepEqual(sectors.get(11)?.subarray(30), sectors.get(10)?.subarray(30)); + assert.deepEqual(await filesystem.activate(3), { enabled: true, activeSlot: 3 }); + assert.equal(mode(), 3); + assert.deepEqual(await filesystem.leave(), { enabled: false, activeSlot: 3 }); +}); + +test("editing onboard effects enables independent zones only for the edited power state", async () => { + const { filesystem, sectors } = emulatedMemory(); + const initial = await filesystem.read(); + const profile = initial.profiles[2]!; + const staticCyan = [1, 0, 204, 255, 2, 0, 0, 0, 0, 0, 0]; + const dimmed = [1, 0, 25, 30, 2, 0, 0, 0, 0, 0, 0]; + const edited = await filesystem.save(3, profile.revision, { effects: { keys: staticCyan } }); + const active = sectors.get(11)!; + assert.equal(active[74], 2); + assert.deepEqual([...active.subarray(30, 34)], [1, 255, 0, 129]); + assert.deepEqual([...active.subarray(41, 52)], staticCyan); + assert.deepEqual(active.subarray(52, 74), rawProfile.subarray(52, 74)); + assert.deepEqual(edited.effects.keys.color, { red: 0, green: 204, blue: 255 }); + assert.equal(edited.effects.idleKeys.effectId, 0x19); + + const updated = await filesystem.save(3, edited.revision, { effects: { idleLogo: dimmed } }); + const idle = sectors.get(10)!; + assert.equal(idle[74], 0); + assert.deepEqual([...idle.subarray(52, 63)], dimmed); + assert.deepEqual(idle.subarray(30, 52), active.subarray(30, 52)); + assert.deepEqual([...idle.subarray(63, 67)], [1, 255, 0, 129]); + assert.deepEqual(updated.effects.idleLogo.color, { red: 0, green: 25, blue: 30 }); + assert.deepEqual((await filesystem.read()).profiles[2], updated); +}); + +test("the stored keys animation and idle wave use the primary records", async () => { + const { filesystem, sectors } = emulatedMemory(); + const profile = (await filesystem.read()).profiles[2]!; + const animation = [0x0c, 1, 0, 0, 0, 0, 0, 0, 100, 0, 0]; + const wave = [0x16, 0, 255, 0, 0, 0, 0, 11, 184, 100, 1]; + const off = new Array(11).fill(0); + const updated = await filesystem.save(3, profile.revision, { effects: { + keys: animation, logo: off, idleKeys: wave, idleLogo: off, + } }); + assert.deepEqual([...sectors.get(11)!.subarray(30, 74)], [...off, ...animation, ...off, ...wave]); + assert.equal(updated.effects.keys.animationSlot, 1); + assert.equal(updated.effects.logo.effectId, 0); + assert.equal(updated.effects.idleKeys.effectId, 0x16); + assert.equal(updated.effects.idleLogo.effectId, 0); +}); + +test("an invalid staged copy or a stale revision cannot replace the onboard directory", async () => { + const { filesystem, sectors, commits, faults } = emulatedMemory(); + const before = await filesystem.read(); + await assert.rejects(filesystem.save(3, 0, { name: "Noche" }), /changed/); + assert.deepEqual(commits, []); + faults.badStagedSector = true; + await assert.rejects(filesystem.save(3, before.profiles[2]!.revision, { name: "Noche" }), /staged/); + assert.deepEqual(commits, [11]); + assert.deepEqual(sectors.get(0), rawDirectory); + faults.rejectSelection = true; + await assert.rejects(filesystem.activate(3), /did not activate/); + assert.deepEqual(await filesystem.read(), before); +}); + +test("onboard remaps attach a checked base-layer file to only the selected profile", async () => { + const { filesystem, sectors, commits } = emulatedMemory(); + const initial = await filesystem.read(); + const mapped = await filesystem.save(3, initial.profiles[2]!.revision, { binding: { index: 11, usage: 5, modifiers: 3 } }); + assert.deepEqual(commits, [11, 12, 0]); + assert.deepEqual([...sectors.get(11)!], [0, 1, 11, 1, 0, 0x80, 0, 0, 0, 0x80, 2, 3, 5]); + assert.deepEqual(mapped.bindings, [{ index: 11, usage: 5, modifiers: 3 }]); + assert.deepEqual((await filesystem.read()).profiles, [...initial.profiles.slice(0, 2), mapped]); + const cleared = await filesystem.save(3, mapped.revision, { binding: { index: 11, usage: null, modifiers: 0 } }); + assert.deepEqual(cleared, initial.profiles[2]); + assert.equal(sectors.get(0)?.[4], 3); +}); + +test("an assignment that grows the onboard table beyond its limit leaves the saved profile intact", async () => { + const { filesystem, commits } = emulatedMemory(); + let profile = (await filesystem.read()).profiles[2]!; + for (let index = 0; index < 127; index++) { + profile = await filesystem.save(3, profile.revision, { binding: { index, usage: 5, modifiers: 0 } }); + } + const commitsBefore = commits.length; + await assert.rejects(filesystem.save(3, profile.revision, { binding: { index: 127, usage: 5, modifiers: 0 } }), /assignment table is too large/); + assert.equal(commits.length, commitsBefore); + assert.deepEqual((await filesystem.read()).profiles[2], profile); +}); diff --git a/src/logitech/onboard.ts b/src/logitech/onboard.ts new file mode 100644 index 0000000..24e1e84 --- /dev/null +++ b/src/logitech/onboard.ts @@ -0,0 +1,504 @@ +import type { LogitechAnimationSlot } from "./onboard-animation.js"; +import type { LogitechRgbColor, LogitechRgbMode } from "./index.js"; + +export type LogitechOnboardLightingMode = LogitechRgbMode; +export const LOGITECH_ONBOARD_LIGHTING_TARGETS = ["keys", "logo", "idleKeys", "idleLogo"] as const; +export type LogitechOnboardLightingTarget = (typeof LOGITECH_ONBOARD_LIGHTING_TARGETS)[number]; +export interface LogitechOnboardEffect { + effectId: number; + color: LogitechRgbColor | null; + periodMs: number | null; + animationSlot?: number; +} +export interface LogitechOnboardLightingChange { + mode: LogitechOnboardLightingMode; + color?: LogitechRgbColor; + periodMs?: number; +} + +export interface LogitechOnboardBinding { + index: number; + usage: number; + modifiers: number; +} + +export interface LogitechOnboardProfile { + slot: number; + name: string; + revision: number; + dimAfterSeconds: number | null; + offAfterSeconds: number | null; + effectId: number; + color: LogitechRgbColor | null; + periodMs: number | null; + effects: Readonly>; + bindings: readonly LogitechOnboardBinding[] | null; +} + +export interface LogitechOnboardMemory { + enabled: boolean; + activeSlot: number; + profiles: readonly LogitechOnboardProfile[]; + animations?: readonly LogitechAnimationSlot[]; +} + +export interface LogitechOnboardProfileChanges { + name?: string; + dimAfterSeconds?: number | null; + offAfterSeconds?: number | null; + lighting?: LogitechOnboardLightingChange; + lightingByTarget?: Partial>; + gameModeDisabledKeys?: readonly number[]; + binding?: { sourceUsage: number; targetUsage: number | null; modifiers: number }; + animationSlot?: 0 | 1; +} + +interface DirectoryEntry { + offset: number; + id: number; + feature: number; + kind: number; + size: number; + checksum: number; + sector: number; +} + +interface Directory { + bytes: Uint8Array; + entries: DirectoryEntry[]; +} + +type Request = (fn: number, params?: readonly number[]) => Promise; + +const DIRECTORY_SIZE = 0x400; +const SECTOR_SIZE = 0x80; +const LAST_USER_SECTOR = 0x7f; +const PROFILE_SIZE = 0x63; +const FEATURE = 0x8101; +const PROFILE_KIND = 1; +const NAME_START = 6; +const NAME_END = 30; +// In independent mode, flash stores logo first and primary keys second. +const EFFECT_OFFSETS: Record = { logo: 30, keys: 41, idleLogo: 52, idleKeys: 63 }; +const EFFECT_SIZE = 11; +const LIGHTING_FLAGS = 74; +const LIGHTING_STATES = [ + { logo: "logo", keys: "keys", combinedMask: 1 }, + { logo: "idleLogo", keys: "idleKeys", combinedMask: 2 }, +] as const; +const GAME_MODE_START = 75; +const BASE_BINDING_REFERENCE = 93; +const BINDING_FEATURE = 0x1b05; +const MAX_BINDING_TABLE_SIZE = 0x580; +const ONBOARD_MODE = 0x01; +const FIRMWARE_POWER = 0x02; +const AUTONOMOUS_MODE = ONBOARD_MODE | FIRMWARE_POWER; + +const view = (data: Uint8Array) => new DataView(data.buffer, data.byteOffset, data.byteLength); +const be16 = (n: number) => [n >>> 8, n & 255]; +const be32 = (n: number) => [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]; +const equal = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((byte, i) => byte === b[i]); + +function crc32(data: Uint8Array): number { + let crc = -1; + for (const byte of data) { + crc ^= byte; + for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); + } + return (~crc) >>> 0; +} + +function parseDirectory(bytes: Uint8Array): Directory { + const count = bytes[4] ?? 0; + const end = 5 + count * 10; + const fields = view(bytes); + if (end >= bytes.length || bytes[end] !== 0xff || fields.getUint32(0) !== crc32(bytes.subarray(4, end + 1))) { + throw new Error("The Logitech onboard directory failed its checksum."); + } + const entries: DirectoryEntry[] = []; + for (let offset = 5; offset < end; offset += 10) { + const kindAndSize = fields.getUint16(offset + 3); + entries.push({ + offset, id: bytes[offset]!, feature: fields.getUint16(offset + 1), kind: kindAndSize >> 14, + size: kindAndSize & 0x3fff, checksum: fields.getUint32(offset + 5), sector: bytes[offset + 9]!, + }); + } + return { bytes: bytes.slice(0, end + 1), entries }; +} + +function profileEntries(directory: Directory): DirectoryEntry[] { + const profiles = directory.entries.filter(entry => entry.feature === FEATURE && entry.kind === PROFILE_KIND); + if (profiles.length !== 3 || new Set(profiles.map(entry => entry.id)).size !== 3 || profiles.some(entry => + entry.offset !== 5 + (entry.id - 1) * 10 || entry.id < 1 || entry.id > 3 || entry.size !== PROFILE_SIZE || entry.sector < DIRECTORY_SIZE / SECTOR_SIZE || entry.sector > LAST_USER_SECTOR)) { + throw new Error("This G915 X TKL has an unsupported onboard profile directory."); + } + return profiles.sort((a, b) => a.id - b.id); +} + +function readEffect(bytes: Uint8Array, offset: number): LogitechOnboardEffect { + const effectId = bytes[offset]!; + const at = offset + 1; + const fields = view(bytes); + const periodMs = effectId === 0x0a ? fields.getUint16(at + 3) + : effectId === 0x15 || effectId === 0x16 || effectId === 0x17 ? fields.getUint16(at + 6) + : effectId === 3 ? fields.getUint16(at + 5) + : effectId === 4 ? (bytes[at + 9]! << 8) | bytes[at + 6]! : null; + const color = [1, 0x0a, 0x17].includes(effectId) + ? { red: bytes[at]!, green: bytes[at + 1]!, blue: bytes[at + 2]! } : null; + return { effectId, color, periodMs, ...(effectId === 0x0c ? { animationSlot: bytes[at] } : {}) }; +} + +function profileView(entry: DirectoryEntry, bytes: Uint8Array, bindings: readonly LogitechOnboardBinding[] | null): LogitechOnboardProfile { + const fields = view(bytes); + let name = ""; + for (let offset = NAME_START; offset < NAME_END; offset += 2) { + const char = fields.getUint16(offset); + if (char === 0 || char === 0xffff) break; + name += String.fromCharCode(char); + } + const dim = fields.getUint16(2), off = fields.getUint16(4); + const effects = {} as Record; + for (const { logo, keys, combinedMask } of LIGHTING_STATES) { + effects[logo] = readEffect(bytes, EFFECT_OFFSETS[logo]); + effects[keys] = bytes[LIGHTING_FLAGS]! & combinedMask ? effects[logo] : readEffect(bytes, EFFECT_OFFSETS[keys]); + } + return { + slot: entry.id, name, revision: entry.checksum, ...effects.keys, effects, bindings, + dimAfterSeconds: dim === 0xffff ? null : dim, offAfterSeconds: off === 0xffff ? null : off, + }; +} + +interface ProfileBytesChanges extends Pick { + effects?: Partial>; + gameModeBitmap?: Uint8Array; + binding?: { index: number; usage: number | null; modifiers: number }; +} + +function splitCombinedEffect(effect: Uint8Array, logo: boolean): Uint8Array { + const id = effect[0]!; + if (id === 0x18 || id === 0x19) { + // The factory two-colour preset is shared. Seed the untouched zone with + // its first colour when changing to independent effects. + const color = new Uint8Array(EFFECT_SIZE); + color.set([1, ...effect.subarray(1, 4), 2]); + return color; + } + return !logo || [0, 1, 0x0a, 0x15].includes(id) ? effect : new Uint8Array(EFFECT_SIZE); +} + +function editProfile(bytes: Uint8Array, changes: ProfileBytesChanges): Uint8Array { + const result = bytes.slice(); + const fields = view(result); + if (changes.name !== undefined) { + const name = changes.name.trim(); + if (name.length > (NAME_END - NAME_START) / 2 || /[\u0000-\u001f\ud800-\udfff\uffff]/u.test(name)) { + throw new RangeError("The onboard profile name must fit in 12 UTF-16 code units."); + } + result.fill(255, NAME_START, NAME_END); + for (let i = 0; i < name.length; i++) fields.setUint16(NAME_START + i * 2, name.charCodeAt(i)); + } + if (changes.dimAfterSeconds !== undefined || changes.offAfterSeconds !== undefined) { + const dim = changes.dimAfterSeconds === undefined ? fields.getUint16(2) : changes.dimAfterSeconds ?? 0xffff; + const off = changes.offAfterSeconds === undefined ? fields.getUint16(4) : changes.offAfterSeconds ?? 0xffff; + const valid = [changes.dimAfterSeconds, changes.offAfterSeconds].every(value => + value == null || (Number.isInteger(value) && value >= 1 && value < 0xffff)); + if (!valid || (dim !== 0xffff && off < dim)) { + throw new RangeError("The onboard inactivity times are invalid."); + } + fields.setUint16(2, dim); + fields.setUint16(4, off); + } + for (const { logo, keys, combinedMask } of LIGHTING_STATES) { + if (!changes.effects?.[logo] && !changes.effects?.[keys]) continue; + const combined = bytes[LIGHTING_FLAGS]! & combinedMask + ? bytes.subarray(EFFECT_OFFSETS[logo], EFFECT_OFFSETS[logo] + EFFECT_SIZE) + : null; + for (const target of [logo, keys]) { + const effect = changes.effects?.[target] ?? (combined && splitCombinedEffect(combined, target === logo)); + if (effect) { + if (effect.length !== EFFECT_SIZE) throw new RangeError("Invalid onboard effect size."); + result.set(effect, EFFECT_OFFSETS[target]); + } + } + result[LIGHTING_FLAGS] = result[LIGHTING_FLAGS]! & ~combinedMask; + } + if (changes.gameModeBitmap) result.set(changes.gameModeBitmap, GAME_MODE_START); + return result; +} + +function bindingGroups(bytes: Uint8Array): Map { + const groups = new Map(); + if (bytes.length < 2) throw new Error("Invalid Logitech assignment table."); + const count = view(bytes).getUint16(0); + let offset = 2; + for (let group = 0; group < count; group++) { + const index = bytes[offset]; + const rows = bytes[offset + 1]; + if (index === undefined || index >= 128 || !rows || groups.has(index)) throw new Error("Invalid Logitech assignment group."); + const end = offset + 2 + rows * 9; + if (end > bytes.length) throw new Error("Incomplete Logitech assignment group."); + groups.set(index, bytes.slice(offset, end)); + offset = end; + } + if (offset !== bytes.length) throw new Error("Unsupported Logitech assignment table."); + return groups; +} + +function simpleBindings(groups: ReadonlyMap): LogitechOnboardBinding[] { + return Array.from(groups.values()).flatMap(row => row.length === 11 && + row[2] === 0 && row[3] === 0x80 && row[4] === 0 && row[5] === 0 && row[6] === 0 && row[7] === 0x80 && row[8] === 2 + ? [{ index: row[0]!, usage: row[10]!, modifiers: row[9]! }] : []); +} + +function encodeGroups(groups: ReadonlyMap): Uint8Array { + const ordered = [...groups.entries()].sort(([a], [b]) => a - b); + return Uint8Array.from([...be16(ordered.length), ...ordered.flatMap(([, group]) => [...group])]); +} + +function findFreeSectors(inUse: Set, size: number): number { + const count = Math.ceil(size / SECTOR_SIZE); + for (let first = DIRECTORY_SIZE / SECTOR_SIZE; first + count <= LAST_USER_SECTOR + 1; first++) { + const block = Array.from({ length: count }, (_, index) => first + index); + if (block.every(sector => !inUse.has(sector))) { + block.forEach(sector => inUse.add(sector)); + return first; + } + } + throw new Error("The keyboard has no free onboard sectors for a verified copy."); +} + +function writeDirectoryEntry(directory: Uint8Array, entry: DirectoryEntry): void { + const fields = view(directory); + directory[entry.offset] = entry.id; + fields.setUint16(entry.offset + 1, entry.feature); + fields.setUint16(entry.offset + 3, (entry.kind << 14) | entry.size); + fields.setUint32(entry.offset + 5, entry.checksum); + directory[entry.offset + 9] = entry.sector; +} + +/** HID++ 0x8101, limited to the filesystem geometry verified on the LIGHTSPEED TKL. */ +export class LogitechOnboardFilesystem { + constructor(private readonly request: Request) {} + + private async readBuffer(length: number): Promise { + const bytes = new Uint8Array(length); + for (let offset = 0; offset < length; offset += 16) { + const page = await this.request(12, be16(offset)); + if (page.length !== 16) throw new Error("The Logitech onboard buffer returned an incomplete page."); + bytes.set(page.subarray(0, length - offset), offset); + } + return bytes; + } + + private async readSector(sector: number, size: number): Promise { + await this.request(8, [0, sector, ...be16(size)]); + return this.readBuffer(size); + } + + private async directory(): Promise { + await this.request(8, [0, 0, ...be16(DIRECTORY_SIZE)]); + const first = await this.request(12, [0, 0]); + const size = 6 + (first[4] ?? 0xff) * 10; + if (first.length !== 16 || size > DIRECTORY_SIZE) throw new Error("The Logitech onboard directory is invalid."); + const bytes = new Uint8Array(size); + bytes.set(first.subarray(0, size)); + for (let offset = 16; offset < size; offset += 16) { + const page = await this.request(12, be16(offset)); + if (page.length !== 16) throw new Error("The Logitech onboard directory returned an incomplete page."); + bytes.set(page.subarray(0, size - offset), offset); + } + return parseDirectory(bytes); + } + + private async readProfile(entry: DirectoryEntry): Promise { + const bytes = await this.readSector(entry.sector, entry.size); + if (bytes[0] !== entry.id || bytes[1] !== 1 || crc32(bytes) !== entry.checksum) { + throw new Error("A Logitech onboard profile failed verification."); + } + return bytes; + } + + private async baseBindings(directory: Directory, profile: Uint8Array): Promise<{ entry?: DirectoryEntry; groups: Map }> { + const file = profile[BASE_BINDING_REFERENCE + 1]; + if (file === 0xff) return { groups: new Map() }; + const entry = directory.entries.find(item => item.id === file && item.feature === BINDING_FEATURE && item.kind === 1); + if (profile[BASE_BINDING_REFERENCE] !== 0 || !entry || entry.size < 2 || entry.size > MAX_BINDING_TABLE_SIZE) { + throw new Error("The onboard key assignments use an unsupported file reference."); + } + const bytes = await this.readSector(entry.sector, entry.size); + if (crc32(bytes) !== entry.checksum) throw new Error("The onboard assignment table failed its checksum."); + return { entry, groups: bindingGroups(bytes) }; + } + + private async mode(): Promise<{ flags: number; activeSlot: number }> { + const state = await this.request(6); + if (state[0] === undefined || ![1, 2, 3].includes(state[2] ?? 0)) throw new Error("The keyboard did not report its onboard profile mode."); + return { flags: state[0] & AUTONOMOUS_MODE, activeSlot: state[2]! }; + } + + private async setMode(flags: number): Promise { + // Bits 0 and 2 enable writes of the mode and power management bits. + await this.request(6, [0x05 | ((flags & ONBOARD_MODE) << 1) | ((flags & FIRMWARE_POWER) << 2), 0, 0]); + } + + async read(): Promise { + const directory = await this.directory(); + const profiles: LogitechOnboardProfile[] = []; + for (const entry of profileEntries(directory)) { + const bytes = await this.readProfile(entry); + const bindings = await this.baseBindings(directory, bytes).then(({ groups }) => simpleBindings(groups), () => null); + profiles.push(profileView(entry, bytes, bindings)); + } + const { flags, activeSlot } = await this.mode(); + return { enabled: Boolean(flags & ONBOARD_MODE), activeSlot, profiles }; + } + + async activate(slot: number, releaseLighting?: () => Promise): Promise> { + const entry = profileEntries(await this.directory()).find(item => item.id === slot); + if (!entry) throw new RangeError("The requested Logitech onboard slot does not exist."); + await this.readProfile(entry); + await releaseLighting?.(); + const previous = await this.mode(); + let activationError: unknown; + try { + if (previous.flags !== AUTONOMOUS_MODE) await this.setMode(AUTONOMOUS_MODE); + await this.request(9, [0x81, 1, PROFILE_KIND, ...be16(slot), ...be16(entry.size), ...be32(entry.checksum)]); + } catch (error) { + activationError = error; + } + const confirmed = await this.mode().catch(() => null); + if (confirmed?.flags === AUTONOMOUS_MODE && confirmed.activeSlot === slot && (activationError === undefined || previous.activeSlot !== slot)) { + return { enabled: true, activeSlot: slot }; + } + if (confirmed && confirmed.flags !== previous.flags) await this.setMode(previous.flags); + throw new Error("The keyboard did not activate the selected onboard profile.", { cause: activationError }); + } + + async leave(): Promise> { + if ((await this.mode()).flags) await this.setMode(0); + const confirmed = await this.mode(); + if (confirmed.flags) throw new Error("The keyboard did not leave onboard memory mode."); + return { enabled: false, activeSlot: confirmed.activeSlot }; + } + + private async writeSector(sector: number, bytes: Uint8Array, checksum: number): Promise { + await this.request(2, be16(bytes.length)); + for (let offset = 0; offset < bytes.length; offset += 16) { + const reply = await this.request(3, [...bytes.subarray(offset, offset + 16)]); + if (reply.length < 2 || view(reply).getUint16(0) !== offset / 16 + 1) throw new Error("The Logitech onboard write returned an unexpected page number."); + } + await this.request(7, [0, sector, ...be16(bytes.length), ...be32(checksum)]); + } + + async save(slot: number, revision: number, changes: ProfileBytesChanges): Promise { + const caps = await this.request(0); + if (caps.length < 9 || view(caps).getUint16(0) !== 0x0101 || view(caps).getUint16(2) !== SECTOR_SIZE || + view(caps).getUint16(4) < DIRECTORY_SIZE || caps[7] !== LAST_USER_SECTOR || caps[8] !== 7) { + throw new Error("This keyboard has an unsupported onboard memory geometry."); + } + const original = await this.directory(); + const entry = profileEntries(original).find(item => item.id === slot); + if (!entry || entry.checksum !== revision) throw new Error("The onboard profile changed. Read the keyboard again before saving."); + const before = await this.readProfile(entry); + const updated = editProfile(before, changes); + const table = await this.baseBindings(original, before).catch(() => null); + if (changes.binding && !table) throw new Error("The current onboard assignments could not be read."); + if (equal(before, updated) && !changes.binding) return profileView(entry, before, table ? simpleBindings(table.groups) : null); + + const inUse = new Set(); + for (const file of original.entries) { + const end = file.sector + Math.max(1, Math.ceil(file.size / SECTOR_SIZE)); + if (file.sector < DIRECTORY_SIZE / SECTOR_SIZE || end > LAST_USER_SECTOR + 1) { + throw new Error("The Logitech onboard directory uses an unsupported sector range."); + } + for (let sector = file.sector; sector < end; sector++) { + if (inUse.has(sector)) throw new Error("The Logitech onboard directory has overlapping files."); + inUse.add(sector); + } + } + let directory = original.bytes.slice(); + if (changes.binding && table) { + const { index, usage, modifiers } = changes.binding; + if (!Number.isInteger(index) || index < 0 || index >= 128 || !Number.isInteger(modifiers) || modifiers < 0 || modifiers > 255 || + (usage !== null && (!Number.isInteger(usage) || usage < 4 || usage > 0xe7))) throw new RangeError("Invalid onboard key assignment."); + const existing = table.groups.get(index); + if (existing && simpleBindings(new Map([[index, existing]])).length !== 1) { + throw new Error("This key has a complex stored assignment. Edit it in G HUB before replacing it here."); + } + if (usage === null) table.groups.delete(index); + else table.groups.set(index, Uint8Array.of(index, 1, 0, 0x80, 0, 0, 0, 0x80, 2, modifiers, usage)); + if (usage !== null || existing) { + let shared = false; + if (table.entry) for (const other of profileEntries(original)) { + if (other.id === slot) continue; + const bytes = await this.readProfile(other); + shared ||= bytes[BASE_BINDING_REFERENCE] === 0 && bytes[BASE_BINDING_REFERENCE + 1] === table.entry.id; + } + if (table.groups.size === 0) { + updated.fill(0xff, BASE_BINDING_REFERENCE, BASE_BINDING_REFERENCE + 2); + if (table.entry && !shared) { + directory = Uint8Array.from([...directory.slice(0, table.entry.offset), ...directory.slice(table.entry.offset + 10)]); + directory[4]!--; + } + } else { + const bytes = encodeGroups(table.groups); + if (bytes.length > MAX_BINDING_TABLE_SIZE) throw new RangeError("The onboard assignment table is too large."); + const checksum = crc32(bytes); + const sector = findFreeSectors(inUse, bytes.length); + const reused = !shared ? table.entry : undefined; + let id = 4; + while (original.entries.some(item => item.id === id)) id++; + if (id > 127) throw new Error("The keyboard has no free assignment file ID."); + const offset = reused?.offset ?? directory.length - 1; + if (!reused) { + if (directory.length + 10 > DIRECTORY_SIZE) throw new Error("The Logitech onboard directory is full."); + directory = Uint8Array.from([...directory.slice(0, -1), ...new Uint8Array(10), 0xff]); + directory[4]!++; + } + await this.writeSector(sector, bytes, checksum); + if (!equal(bytes, await this.readSector(sector, bytes.length))) throw new Error("The staged Logitech assignment table failed verification."); + writeDirectoryEntry(directory, { offset, id, feature: BINDING_FEATURE, kind: 1, size: bytes.length, checksum, sector }); + updated.set([0, id], BASE_BINDING_REFERENCE); + } + } + } + if (equal(before, updated) && equal(directory, original.bytes)) return profileView(entry, before, table ? simpleBindings(table.groups) : null); + const spare = findFreeSectors(inUse, updated.length); + const checksum = crc32(updated); + await this.writeSector(spare, updated, checksum); + if (!equal(updated, await this.readSector(spare, entry.size))) throw new Error("The staged Logitech onboard profile failed verification."); + if (!equal(original.bytes, (await this.directory()).bytes)) throw new Error("The onboard directory changed during the save. Read the keyboard again."); + + const replacement = { ...entry, sector: spare, checksum }; + view(directory).setUint32(entry.offset + 5, checksum); + directory[entry.offset + 9] = spare; + const directoryChecksum = crc32(directory.subarray(4)); + view(directory).setUint32(0, directoryChecksum); + let writeError: unknown; + try { + await this.writeSector(0, directory, directoryChecksum); + } catch (error) { + writeError = error; + } + const committed = await this.directory().catch(() => null); + if (!committed) { + const error = new Error("The written Logitech onboard directory could not be verified.", { cause: writeError }); + await this.restoreDirectory(original, directory, error); + throw error; + } + if (!equal(committed.bytes, directory)) throw new Error("The keyboard did not retain the expected onboard directory.", { cause: writeError }); + return profileView(replacement, updated, table ? simpleBindings(table.groups) : null); + } + + private async restoreDirectory(original: Directory, attempted: Uint8Array, error: unknown): Promise { + try { + const current = await this.directory().catch(() => null); + if (current && equal(current.bytes, original.bytes)) return; + if (current && !equal(current.bytes, attempted)) throw new Error("Another process changed the onboard directory."); + await this.writeSector(0, original.bytes, view(original.bytes).getUint32(0)); + if (!equal((await this.directory()).bytes, original.bytes)) throw new Error("Original directory mismatch."); + } catch (restoreError) { + throw new Error("The Logitech onboard directory could not be restored. Reconnect and read the profiles before saving again.", { cause: new AggregateError([error, restoreError]) }); + } + } +} From a384ad1658b3cf285beafcaf99ee5c4c6a6fa872 Mon Sep 17 00:00:00 2001 From: Onyx Date: Thu, 3 Dec 2026 11:26:36 +0100 Subject: [PATCH 2/2] fix(logitech): reject duplicate live zones and animation frames that add keys --- src/drivers/logitech/hid.test.ts | 1 + src/drivers/logitech/hid.ts | 3 +++ src/logitech/onboard-animation.test.ts | 5 +++++ src/logitech/onboard-animation.ts | 2 +- 4 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/drivers/logitech/hid.test.ts b/src/drivers/logitech/hid.test.ts index b78b753..e4fb250 100644 --- a/src/drivers/logitech/hid.test.ts +++ b/src/drivers/logitech/hid.test.ts @@ -493,6 +493,7 @@ test("G915 X TKL claims host mode, encodes new effects, dims, turns off and repl await client.setZoneColors([key]); key.green = 255; await client.updateZoneColors([{ zone: 1, red: 0, green: 0, blue: 255 }]); + await assert.rejects(client.updateZoneColors([{ zone: 1, red: 255, green: 0, blue: 0 }, { zone: 1, red: 0, green: 0, blue: 255 }]), /Duplicate lighting zone 1/); const painted = device.writes.filter(write => write.featureIndex === 6 && write.functionId === 1).at(-1); assert.deepEqual(painted?.params.slice(0, 4), [1, 0, 0, 255]); await client.setRgbEffect("Static", { red: 0, green: 255, blue: 0 }); diff --git a/src/drivers/logitech/hid.ts b/src/drivers/logitech/hid.ts index a3edaaa..da4b4a9 100644 --- a/src/drivers/logitech/hid.ts +++ b/src/drivers/logitech/hid.ts @@ -1176,7 +1176,10 @@ export class LogitechKeyboardHidClient { throw new Error("Prepare those per-key lighting zones before sending live frames."); } const groups = new Map(); + const seen = new Set(); for (const color of frame) { + if (seen.has(color.zone)) throw new RangeError(`Duplicate lighting zone ${color.zone}.`); + seen.add(color.zone); const rgb = rgbChannels(color); const packed = (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]; const group = groups.get(packed) ?? { rgb, zones: [] }; diff --git a/src/logitech/onboard-animation.test.ts b/src/logitech/onboard-animation.test.ts index 64b7343..4bf18b0 100644 --- a/src/logitech/onboard-animation.test.ts +++ b/src/logitech/onboard-animation.test.ts @@ -21,3 +21,8 @@ test("onboard animation creates a complete RGB-only transfer and verifies each a }, 1, data, async () => {}); assert.equal(count, data.length / 16); }); + +test("onboard animation frames must all hold the same keys", () => { + const key = (zone: number) => ({ zone, red: 255, green: 0, blue: 0 }); + assert.throws(() => encodeLogitechAnimation({ name: "Grow", frameMs: 120, frames: [{ colors: [key(1)] }, { colors: [key(1), key(2)] }] }, new Uint8Array(16)), RangeError); +}); diff --git a/src/logitech/onboard-animation.ts b/src/logitech/onboard-animation.ts index df80499..36f32cd 100644 --- a/src/logitech/onboard-animation.ts +++ b/src/logitech/onboard-animation.ts @@ -73,7 +73,7 @@ export function encodeLogitechAnimation(animation: LogitechAnimation, uuid: Uint group.push(zone); byColor.set(color, group); } - if (!current.size || [...previous.keys()].some(zone => !current.has(zone))) throw new RangeError("Every animation frame must contain the same keys."); + if (!current.size || (previous.size > 0 && current.size !== previous.size) || [...previous.keys()].some(zone => !current.has(zone))) throw new RangeError("Every animation frame must contain the same keys."); const separate: number[] = []; for (const [color, zones] of byColor) { const rgb = [color >>> 16, (color >>> 8) & 255, color & 255];