From f055f4b39f9bd1743b4e49ddb664a8bcc7a77ad5 Mon Sep 17 00:00:00 2001 From: snekxs <26660858+snekxs@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:16:17 -0600 Subject: [PATCH 1/2] feat(keychron): add G6 HE and TurboLink receiver controls --- docs/keychron-g6-he.md | 145 +++++++++++++++ src/drivers/keychron/mouse-8k-hid.test.ts | 114 ++++++++++++ src/drivers/keychron/mouse-8k-hid.ts | 210 +++++++++++++++++++++- src/drivers/keychron/receiver-hid.test.ts | 73 ++++++++ src/drivers/keychron/receiver-hid.ts | 80 +++++++++ src/drivers/mouse-types.ts | 25 +++ src/keychron/index.ts | 1 + src/keychron/receiver-keys.ts | 51 ++++++ 8 files changed, 697 insertions(+), 2 deletions(-) create mode 100644 docs/keychron-g6-he.md create mode 100644 src/drivers/keychron/receiver-hid.test.ts create mode 100644 src/drivers/keychron/receiver-hid.ts create mode 100644 src/keychron/receiver-keys.ts diff --git a/docs/keychron-g6-he.md b/docs/keychron-g6-he.md new file mode 100644 index 00000000..1164ef92 --- /dev/null +++ b/docs/keychron-g6-he.md @@ -0,0 +1,145 @@ +# Keychron G6 HE Launcher controls + +Inspected on 2026-11-17 with REA against https://launcher.keychron.com/#/mouse/he. +The live page redirected to `#/not-connect` without a paired device. Commands +below come from the shipped JavaScript, not a capture from a physical G6 HE. + +## Source identity + +| Launcher artifact | SHA-256 | +| --- | --- | +| `main.9597847ee340b1c7.js` | `c0d660c60eb74c4f50c2db1440d9a602f2b2c74d09198bbca64fa051de75089b` | +| `common.f59398e631a24e1c.js` | `fb507c912c5e40abfc1f4c8fe1f4777326ed22ef468c74629629575354a0485b` | +| `810.819eff90b9bbaedb.js` | `e8a66cc2d614705dd77362709e7be3045103991fdc6eefaa6a8631c50be3fddd` | +| `690.e82e62fccdf1e18c.js` | `50bbd52d229ce998c9fd9b1bc54e9dd6c785b5d833cf9f973b73f566af027979` | +| `static/device/875876486/json/v3.json` | `05504e9ba070c2b19242f9ce830125dd91dbe2f5c23b939b6e942b6a09ed5883` | + +REA main-bundle graph: `ev_52f2b265461d9dcbd5afc642668e9543717fc2825c9da7b7d3d71b72b6f6feed`. +Focused HE UI/scale graph: `ev_ff8f74baea0a43cc1484b349ea78c635d320d1de32f4947f1198a364f2050333`. +Both have bounded, incomplete static semantic coverage; unresolved relationships +are not evidence of absent features. No vendor bootstrap code was evaluated by +the static analysis. + +The session's REA evidence was exported to +`C:/Users/snekxs/AppData/Local/Temp/openmouse-keychron-rea-evidence.json`. +Vendor bundles and screenshots remain outside the source repository. + +## HE records + +Command report `0xb3`, response `0xb4`, 63-byte payload. `0x65` reads; +`0x55` writes and returns `[0xe4, status, 0x55]`. Payload byte 1 is the record +count. Records start at byte 2 and have a stride of 22. Physical index 0 is +left, 2 is right. Do not use UI button index 1 as the wire index for right. + +| Record offset | Meaning | +| --- | --- | +| 0 | Physical button index | +| 1–2 | Dead bands | +| 3–4 | Percent points | +| 5–8 | Press/release scale points, two little-endian uint16s | +| 9 | Percent value | +| 10–11 | Current travel scale, little-endian uint16 | +| 12 | Low nibble: 1 optical, 2 magnetic. High nibble: rapid trigger enable | +| 13–16 | Rapid press/release distances, two little-endian uint16s | +| 17–21 | Read-only ADC/optical state | + +The G6 JSON has no scale override. Launcher's common module defaults to +12 actuation levels with raw values `[10,15,...,65]`. Rapid trigger has an +off level at 0, then raw values `[5,10,...,55]`; both rapid distances are set +together. Rapid distance cannot exceed `65 - actuation`. Changing actuation +sets the ordinary release point to `max(5, actuation - 10)` and clamps rapid +trigger to the remaining travel. Values are scale levels, not millimetres. + +Feature byte 2 bits 3/5/6 advertise ALL/optical/magnetic respectively. Only +ALL exposes the optical/magnetic selector. These are status byte 53 before +protocol version 6, version-response byte 12 from version 6 onward. + +Launcher polls HE every 50 ms while its view is visible. OpenMouse likewise +polls only while subscribed, skips hidden documents and busy requests, and +serializes requests with writes. Travel is normalized to percent of 65 for +the shared interface. The G6 chart converts that back to actuation levels 0–12, +so the threshold and trace share the same scale. The time axis redraws on browser +animation frames, independently of the 50 ms device query interval. Travel beyond +the configured threshold is shaded in the current theme accent. Charts show received samples over three seconds; +stale/failed data clears rather than inventing zero travel. The chart does +not claim to count firmware click events or reproduce Launcher's derived +rapid-trigger click/hold simulation. + +Independent/shared editing is a UI choice. The firmware stores separate left +and right records. Writes preserve both records' other configuration fields +and verify configuration readback, excluding live input fields. + +## Other controls + +| Control | Protocol / implementation | +| --- | --- | +| Lift-off 0.7–1.7 mm | Existing model table and level-byte sensor writer | +| Ripple, angle snap, motion sync | Existing `0x42` sensor writer | +| Scroll direction | Status byte 15 bit 6, `0x42` byte 6: 1 forward, 2 reverse; preserves other sensor options | +| Debounce / sleep | Existing driver; sleep is stored in minutes | +| Left click lock | Local remapping guard, as in Launcher; no firmware command | +| System mouse settings | OS settings URI, Windows/macOS only | +| Pairing shortcut | Feature byte 2 bit 1. `0x0b,2` reads mask/time; `0x0b,1,mask,time` writes. One to three buttons; preserve hold time | +| Dynamic DPI | Feature byte 4 bit 5. `0x4f,profile` reads; `0x4e` writes without waiting for an ACK, followed by readback | +| Factory reset | Restore debounce to 8 ms, then `0x0f,0xff` on settings report `0xb5`; wait three seconds as Launcher does | + +Dynamic DPI payload: profile at 1, enabled bit at 2, mode at 3, count at 5; +points at 6 with stride 4: uint16 speed (IPS), gain byte, reserved byte. +UI gain is gain/16, max 3.5; speed max 200 IPS. Modes are custom, classic, +natural and jump, with the three preset point tables recovered from chunk 690. +Pairing and dynamic controls are exposed only after a successful feature-gated +device read. The current G6 descriptor alone does not prove firmware advertises +Dynamic DPI. + +## Validation + +Protocol tests exercise feature gating, left/right record preservation, +readback failure, travel limits, real sample decoding, polling cleanup and +request serialization, scroll preservation, pairing constraints and dynamic +DPI read/write validation. Browser preview exercises the shared/independent +controls and optical disabling in Emerald and Arabic RTL/NieR, plus the dynamic +editor in Light. Preview data is simulated and is explicitly labelled as such. + +Physical wired and receiver operation, persistence across power cycles, OS URI +handling and factory reset still require hardware validation. Do not interpret +mock protocol or browser-preview success as physical-device confirmation. + +## TurboLink controls on the mouse page + +The connected Windows device was enumerated read-only as `3434:d05a`. +Its descriptor declares four receiver buttons, independently of the mouse: +polling cycle (0), lighting cycle (1), optical/magnetic toggle (2), DPI cycle (3). +REA's receiver UI graph is +`ev_700de899e9a81e76d3102f1e71fe29a733b6e330d527b19963ab17b82d708df8`. + +Launcher module 98004 uses 63-byte command reports `0xb3`: `0x31,index` reads +one receiver assignment; `0x30,index,0,type,data...` writes it. Success is +`e4,0,30`. This is separate from the mouse's `0x62`/`0x52` commands. Receiver +lighting uses settings report `0xb5`: `0x20,0` reads, with mode/brightness/speed +at reply offsets 4/5/6 and RGB at 7–9. `0x24,0,mode,brightness,speed,r,g,b` +writes, followed by readback. The second byte is the receiver lighting target, +not the mouse's lighting mode. Extra receiver actions include lighting cycling +and custom function `15,3,target,action` for optical/magnetic control, where +target is 204 (both), 0 (left), or 2 (right), and action is 0/1/2 (toggle/optical/magnetic). + +OpenMouse exposes this as `MouseStatus.keychronReceiver` inside the paired +mouse's page. It does not create a second device entry. Receiver reads and writes +share the mouse client's request queue to prevent live travel queries colliding +with configuration. Receiver button writes verify only the receiver's records. +Receiver lighting does not change the mouse's lighting state. Tests cover those +separate commands and nesting; physical settings writes have not been performed. + +Receiver keyboard actions use function type 2, followed by the modifier mask +and USB keyboard usages. These are distinct from function type 8 shortcut +presets. Module 98004's `keyboard` method constructs this record; chunk 808's +editor was retained in REA evidence +`ev_e044b4061bbfe04da69c3b167051dd50910b8ced13528e8017e7124753fe2a54`. +Readback preserves keyboard combinations rather than treating them as unknown. + +The examined TurboLink receiver class (`Oe` in module 98022) reads firmware, +button assignments and lighting. Its monitor handles lighting event 0xe1. +Module 98004 contains no dock-battery query or percentage decoder, and the +receiver class does not expose a spare-battery field. This establishes no +Launcher readout in this examined code path; it does not rule out an +undocumented firmware command. OpenMouse therefore does not substitute the +mouse's battery percentage for the battery charging in the dock. diff --git a/src/drivers/keychron/mouse-8k-hid.test.ts b/src/drivers/keychron/mouse-8k-hid.test.ts index f81079ff..15df07f5 100644 --- a/src/drivers/keychron/mouse-8k-hid.test.ts +++ b/src/drivers/keychron/mouse-8k-hid.test.ts @@ -17,6 +17,15 @@ class FakeKeychronMouse { opened = false; readonly sent: Array<{ reportId: number; packet: Uint8Array }> = []; private listeners = new Map void>(); + heRecords = [0, 2].map(index => { + const r = new Uint8Array(22); r[0] = index; r.set([2, 3, 25, 30], 1); + r[5] = 25; r[7] = 15; r[10] = 40; r[12] = 0x12; r[13] = 5; r[15] = 5; + return r; + }); + failHeWrite = false; + pairMask = 9; + receiverButtons = new Map(); + dynamic = { profile: 1, enabled: true, mode: 0, points: [{ speed: 0, gain: 16 }, { speed: 200, gain: 56 }] }; workMode = 0; /** Protocol version in the 0x02 answer; from 6 the feature flags move there. */ version = 5; @@ -74,6 +83,29 @@ class FakeKeychronMouse { async sendReport(reportId: number, data: ArrayBuffer): Promise { const packet = new Uint8Array(data); this.sent.push({ reportId, packet }); + if (reportId === 0xb3 && packet[0] === 0x31) { + const reply = new Uint8Array(63); reply.set([0x31, packet[1]!, 0]); reply.set(this.receiverButtons.get(packet[1]!) ?? [0], 3); this.emit(0xb4, reply); return; + } + if (reportId === 0xb3 && packet[0] === 0x30) { + this.receiverButtons.set(packet[1]!, Array.from(packet.slice(3))); this.emit(0xb4, new Uint8Array([ACK, 0, 0x30])); return; + } + if (reportId === 0xb3 && packet[0] === 0x4f) { + const r = new Uint8Array(63); r.set([0x4f, packet[1]!, +this.dynamic.enabled, this.dynamic.mode, 0, this.dynamic.points.length]); + this.dynamic.points.forEach((p, i) => { r[6 + i * 4] = p.speed & 255; r[7 + i * 4] = p.speed >> 8; r[8 + i * 4] = p.gain; }); + this.emit(0xb4, r); return; + } + if (reportId === 0xb3 && packet[0] === 0x4e) { + this.dynamic = { profile: packet[1]!, enabled: !!packet[2], mode: packet[3]!, points: Array.from({ length: packet[5]! }, (_, i) => ({ speed: packet[6 + 4 * i]! | packet[7 + 4 * i]! << 8, gain: packet[8 + 4 * i]! })) }; return; + } + if (reportId === 0xb3 && packet[0] === 0x65) { + const reply = new Uint8Array(63); reply.set([0x65, 2]); + this.heRecords.forEach((r, i) => reply.set(r, 2 + i * 22)); + this.emit(0xb4, reply); return; + } + if (reportId === 0xb3 && packet[0] === 0x55) { + if (!this.failHeWrite) this.heRecords = [packet.slice(2, 24), packet.slice(24, 46)]; + this.emit(0xb4, new Uint8Array([ACK, 0, 0x55])); return; + } if (reportId === 0xb3) return this.command(packet); if (reportId !== 0xb5) return; if (this.rejectNext) { @@ -82,6 +114,11 @@ class FakeKeychronMouse { return; } switch (packet[0]) { + case 0x0b: { + if (packet[1] === 1) this.pairMask = packet[2]!; + this.emit(0xb6, packet[1] === 1 ? new Uint8Array([ACK, 0, 0x0b]) : new Uint8Array([0x0b, 2, this.pairMask, 4])); return; + } + case 0x0f: this.emit(0xb6, new Uint8Array([ACK, 0, 0x0f])); return; case 0x02: { const reply = new Uint8Array(20); reply.set([0x02, this.version, 0, 0x34, 0x34, this.reportedProductId & 0xff, this.reportedProductId >> 8, 0x03, 0x01, this.workMode]); @@ -100,6 +137,7 @@ class FakeKeychronMouse { this.emit(0xb6, reply); return; } + case 0x20: this.emit(0xb6, new Uint8Array([0x20, 0, 0, 0, this.light.mode, this.light.brightness, this.light.speed, ...this.light.rgb])); return; case 0x23: this.emit(0xb6, new Uint8Array([0x21, this.light.mode, this.light.brightness, this.light.speed, ...this.light.rgb])); return; @@ -717,3 +755,79 @@ test("shortcut presets remap like Launcher and polling keys follow feature1 bit assert.equal(status.buttonMappings?.["Tilt Left"], "Copy (Ctrl+C)"); assert.equal(status.buttonMappings?.["Tilt Right"], "Polling +"); }); + +test("HE capability flags expose actual button records only on supported firmware", async () => { + const fake = new FakeKeychronMouse(), hid = client(fake); + assert.equal((await hid.readStatus()).magneticButtons, undefined); + fake.version = 6; fake.features[1] = 8; + await hid.close(); + const status = await client(fake).readStatus(); + assert.equal(status.magneticButtons?.buttons[0]?.triggerPoint, 4); + assert.equal(status.magneticButtons?.buttons[1]?.switchType, "magnetic"); + assert.equal(status.magneticButtons?.canChooseSwitchType, true); await hid.close(); +}); +test("HE writes preserve the other button and reserved settings and verify readback", async () => { + const fake = new FakeKeychronMouse(), hid = client(fake); await hid.open(); + const other = fake.heRecords[1]!.slice(0, 17); + await hid.setMagneticTriggerPoint(0, 6); + assert.equal(fake.heRecords[0]![5], 35); assert.equal(fake.heRecords[0]![7], 25); + assert.deepEqual(fake.heRecords[1]!.slice(0, 17), other); + assert.deepEqual(Array.from(fake.heRecords[0]!.slice(1, 5)), [2,3,25,30]); + await hid.setMagneticRapidTrigger(1, true, 3); + assert.equal(fake.heRecords[1]![13], 15); assert.equal(fake.heRecords[1]![15], 15); + await hid.setMagneticSwitchTypes(["optical", "magnetic"]); + assert.equal(fake.heRecords[0]![12], 0x11); + await hid.setMagneticTriggerPoint(0, 12); assert.equal(fake.heRecords[0]![12], 1); + await assert.rejects(() => hid.setMagneticRapidTrigger(0, true, 1), /remaining/); + fake.failHeWrite = true; await assert.rejects(() => hid.setMagneticTriggerPoint(1, 2), /did not keep/); + await hid.close(); +}); +test("scroll reversal preserves sensor flags and lift off", async () => { + const fake = new FakeKeychronMouse(), hid = client(fake); await hid.open(); + await hid.setScrollDirection("Reverse"); + assert.equal(fake.scrollReversed, true); assert.equal(fake.motion, true); assert.equal(fake.lod, 1); + assert.equal((await hid.readStatus()).scrollDirection, "Reverse"); await hid.close(); +}); + +test("pairing shortcut and dynamic DPI are capability-gated and round-trip", async () => { + const fake = new FakeKeychronMouse(); fake.version = 6; fake.features[1] = 2; fake.features[3] = 32; + const hid = client(fake); const status = await hid.readStatus(); + assert.deepEqual(status.keychronMouse?.pairing, { mask: 9, holdTime: 4 }); + assert.deepEqual(status.keychronMouse?.dynamicDpi, fake.dynamic); + await hid.setKeychronPairingShortcut({ mask: 3, holdTime: 99 }); + assert.equal(fake.pairMask, 3); assert.equal(lastSent(fake, 0x0b)![1], 2); + await assert.rejects(() => hid.setKeychronPairingShortcut({ mask: 31, holdTime: 4 }), /three/); + const next = { ...fake.dynamic, points: [{ speed: 0, gain: 8 }, { speed: 100, gain: 32 }] }; + await hid.setKeychronDynamicDpi(next); assert.deepEqual(fake.dynamic, next); + await assert.rejects(() => hid.setKeychronDynamicDpi({ ...next, profile: 0 }), /profile changed/); + await assert.rejects(() => hid.setKeychronDynamicDpi({ ...next, points: [{ speed: 10, gain: 8 }, { speed: 5, gain: 20 }] }), /Invalid/); + await hid.close(); +}); +test("live travel uses device samples, serializes writes and stops after unsubscribe", async (t) => { + t.mock.timers.enable({ apis: ["setInterval"] }); + const fake = new FakeKeychronMouse(), hid = client(fake); await hid.open(); + const samples: Array<[number, number]> = []; + const stop = hid.onButtonDepth((left, right) => samples.push([left, right])); + t.mock.timers.tick(50); + await Promise.all([hid.setMagneticTriggerPoint(0, 4), hid.setScrollDirection("Reverse")]); + assert.deepEqual(samples, [[40 / 65 * 100, 40 / 65 * 100]]); + stop(); + const before = fake.sent.length; + t.mock.timers.tick(200); + assert.equal(fake.sent.length, before); + await hid.close(); + assert.equal(fake.opened, false); +}); + +test("TurboLink controls stay nested in the G6 mouse status and use their own button commands", async () => { + const fake = new FakeKeychronMouse(); fake.productId = 0xd05a; fake.reportedProductId = 0xd086; fake.workMode = 1; + const hid = client(fake), status = await hid.readStatus(); + assert.equal(status.name, "Keychron G6 HE 8K"); + assert.equal(status.keychronReceiver?.name, "Keychron TurboLink 8K"); + assert.equal(status.keychronReceiver?.buttonMappings.Polling, "Polling Loop"); + assert.equal(status.keychronReceiver?.lighting.zone, "Receiver"); + await hid.setKeychronReceiverButton({ button: "Switch type", action: "Magnetic (both)" }); + assert.deepEqual(fake.receiverButtons.get(2)?.slice(0, 4), [15, 3, 204, 2]); + assert.equal(fake.buttons.size, 0); + await hid.close(); +}); diff --git a/src/drivers/keychron/mouse-8k-hid.ts b/src/drivers/keychron/mouse-8k-hid.ts index c0705f99..0d846d4e 100644 --- a/src/drivers/keychron/mouse-8k-hid.ts +++ b/src/drivers/keychron/mouse-8k-hid.ts @@ -1,4 +1,5 @@ -import type { MouseLighting, MouseStatus } from "../mouse-types.ts"; +import type { KeychronDynamicDpi, MagneticButtonsStatus, MouseLighting, MouseStatus } from "../mouse-types.ts"; +import { isKeychronConfigurableReceiver, KeychronReceiverControls } from "./receiver-hid.ts"; import { KEYCHRON_8K_NORDIC_PRODUCT_IDS, KEYCHRON_M6_COMMAND_REPORT_ID as COMMAND_REPORT_ID, @@ -90,6 +91,10 @@ type Features = { /** The 20K FPS switch. */ fps20k: boolean; angle: boolean; + triggerSense: boolean; + switchChoice: boolean; + pairing: boolean; + dynamicDpi: boolean; /** Separate X/Y DPI through 0x48/0x49. */ separateDpi: boolean; /** USB and 2.4 GHz polling tables through 0x4a/0x4b. */ @@ -196,6 +201,19 @@ export class Keychron8kHidClient { this.device = device; } + private receiverControls(): KeychronReceiverControls { + if (!isKeychronConfigurableReceiver(this.device)) throw new Error("No configurable Keychron receiver is connected."); + return new KeychronReceiverControls(this.query.bind(this), this.sendWithoutReply.bind(this)); + } + + async setKeychronReceiverButton(value: { button: string; action: string }): Promise { + await this.receiverControls().setButtonMapping(value.button, value.action); + } + + async setKeychronReceiverLighting(value: MouseLighting): Promise { + return await this.receiverControls().setLighting(value); + } + /** Launcher treats any Keychron device with this collection as an "8k" mouse, so this does too. */ static isSupported(device: HIDDevice): boolean { // The G3 Air and its Ultra-Link receivers speak the 8K Nordic protocol @@ -220,6 +238,9 @@ export class Keychron8kHidClient { } async close(): Promise { + if (this.depthTimer) clearInterval(this.depthTimer); + this.depthTimer = null; + this.depthListeners.clear(); if (this.openedListener) { this.device.removeEventListener("inputreport", this.onInputReport); this.openedListener = false; @@ -260,6 +281,11 @@ export class Keychron8kHidClient { return this.unreachableStatus(identity); } const buttons = await this.readButtons().catch(() => null); + const receiver = isKeychronConfigurableReceiver(this.device) + ? await this.receiverControls().readStatus().catch(() => null) : null; + const pairing = status.features.pairing ? await this.readPairingShortcut().catch(() => null) : null; + const dynamicDpi = status.features.dynamicDpi ? await this.readDynamicDpi(status.profile).catch(() => null) : null; + const magnetic = status.features.triggerSense ? await this.readMagneticStatus(status.features.switchChoice).catch(() => null) : null; const light = model?.light ? await this.readLight().catch(() => null) : null; const pollingRateHz = POLLING_RATES[polling.table[polling.level] ?? 2] ?? 1000; const liftOff = this.liftOffChoices(status); @@ -271,8 +297,13 @@ export class Keychron8kHidClient { return { brand: "Keychron", name, + ...(receiver ? { keychronReceiver: receiver } : {}), + keychronMouse: { pairing, dynamicDpi, factoryReset: true }, + scrollDirection: status.scrollReversed ? "Reverse" : "Forward", + ...(magnetic ? { magneticButtons: magnetic } : {}), ui: { family: "keychron-8k", + receiverControls: isKeychronConfigurableReceiver(this.device), defaultDisplayName: name, hideUnsupportedPollingRates: true, forceShowBattery: true, @@ -318,6 +349,148 @@ export class Keychron8kHidClient { }; } + private depthTimer: ReturnType | null = null; + private depthListeners = new Set<(left: number, right: number) => void>(); + private magneticWrite = false; + + /** Launcher polls 0x65 every 50 ms only while its travel view is visible. */ + onButtonDepth(listener: (left: number, right: number) => void): () => void { + this.depthListeners.add(listener); + if (!this.depthTimer) this.depthTimer = setInterval(() => { + if (this.queryPending || this.magneticWrite || (typeof document !== "undefined" && document.hidden)) return; + void this.readHeRecords().then((records) => { + for (const notify of this.depthListeners) notify(readU16(records[0]!, 10) / 65 * 100, readU16(records[1]!, 10) / 65 * 100); + }).catch(() => { for (const notify of this.depthListeners) notify(NaN, NaN); }); + }, 50); + return () => { + this.depthListeners.delete(listener); + if (!this.depthListeners.size && this.depthTimer) { clearInterval(this.depthTimer); this.depthTimer = null; } + }; + } + + private async readHeRecords(): Promise { + const reply = await this.query(COMMAND_REPORT_ID, PACKET_LENGTH, [0x65], bytes => bytes[0] === 0x65); + if (reply[1] !== 2 || reply.length < 46) throw new Error("Invalid magnetic button report."); + const records = [reply.slice(2, 24), reply.slice(24, 46)]; + const ordered = [records.find(r => r[0] === 0), records.find(r => r[0] === 2)]; + if (!ordered[0] || !ordered[1]) throw new Error("Missing magnetic button record."); + return ordered as Uint8Array[]; + } + + private async readMagneticStatus(choice: boolean): Promise { + const records = await this.readHeRecords(); + return { + buttons: records.map(r => ({ + switchType: (r[12]! & 15) === 1 ? "optical" : (r[12]! & 15) === 2 ? "magnetic" : null, + triggerPoint: heTravelLevel(readU16(r, 5)), + rapidTriggerEnabled: (r[12]! >> 4) <= 1 ? (r[12]! >> 4) === 1 : null, + rapidTrigger: readU16(r, 13) >= 5 && readU16(r, 13) <= 55 && readU16(r, 13) % 5 === 0 ? readU16(r, 13) / 5 : null, + })), + triggerPointRange: { min: 1, max: 12 }, rapidTriggerRange: { min: 1, max: 11 }, + rapidTriggerUnit: "level", rapidTriggerSwitch: true, canChooseSwitchType: choice, + calibration: null, liveDepth: true, + }; + } + + private async editHe(edit: (records: Uint8Array[]) => void): Promise { + this.magneticWrite = true; + try { + const records = await this.readHeRecords(); + edit(records); + const packet = new Uint8Array(PACKET_LENGTH); + packet.set([0x55, 2]); + records.forEach((r, i) => { + // Launcher writes configuration only; ADC and optical input bytes are read-only. + packet.set(r.slice(0, 17), 2 + 22 * i); + }); + const reply = await this.query(COMMAND_REPORT_ID, PACKET_LENGTH, Array.from(packet), bytes => bytes[0] === ACK && bytes[2] === 0x55); + if (reply[1] !== 0) throw new Error("The mouse rejected magnetic button settings."); + const confirmed = await this.readHeRecords(); + if (confirmed.some((r, i) => r.slice(0, 9).some((v, j) => v !== records[i]![j]) || r.slice(12, 17).some((v, j) => v !== records[i]![12 + j]))) { + throw new Error("The mouse did not keep the magnetic button settings."); + } + return confirmed; + } finally { this.magneticWrite = false; } + } + + async setMagneticTriggerPoint(button: 0 | 1, point: number): Promise { + if (!Number.isInteger(point) || point < 1 || point > 12) throw new Error("Actuation must be level 1 to 12."); + await this.editHe(records => { + const r = records[button]!; const travel = 10 + (point - 1) * 5; + writeU16(r, 5, travel); writeU16(r, 7, Math.max(5, travel - 10)); + const rapid = Math.min(readU16(r, 13), 65 - travel); + r[12] = (r[12]! & 15) | (rapid > 0 && (r[12]! >> 4) === 1 ? 16 : 0); + writeU16(r, 13, rapid || 1); writeU16(r, 15, rapid || 1); + }); + return point; + } + + async setMagneticRapidTrigger(button: 0 | 1, enabled: boolean, level: number): Promise<{ enabled: boolean; level: number }> { + if (!Number.isInteger(level) || level < 1 || level > 11) throw new Error("Rapid trigger must be level 1 to 11."); + await this.editHe(records => { + const r = records[button]!; + if (enabled && level * 5 > 65 - readU16(r, 5)) throw new Error("Rapid trigger exceeds the remaining button travel."); + r[12] = (r[12]! & 15) | (enabled ? 16 : 0); + writeU16(r, 13, level * 5); writeU16(r, 15, level * 5); + }); + return { enabled, level }; + } + + async setMagneticSwitchTypes(types: readonly ["magnetic" | "optical", "magnetic" | "optical"]): Promise { + await this.editHe(records => records.forEach((r, i) => { r[12] = (r[12]! & 240) | (types[i] === "optical" ? 1 : 2); })); + } + + async setScrollDirection(direction: NonNullable): Promise { + if (direction !== "Forward" && direction !== "Reverse") throw new Error("Invalid scroll direction."); + const confirmed = await this.writeSensor({ ...(await this.readSettings()), scrollReversed: direction === "Reverse" }); + if (confirmed.scrollReversed !== (direction === "Reverse")) throw new Error("The mouse did not keep the scroll direction."); + return direction; + } + + private async readPairingShortcut(): Promise<{ mask: number; holdTime: number }> { + const r = await this.querySettings(0x0b, [2]); + if (r.length < 4 || (r[2]! & 0xe0)) throw new Error("Invalid pairing shortcut."); + return { mask: r[2] || 9, holdTime: r[3]! }; + } + + async setKeychronPairingShortcut(value: { mask: number; holdTime: number }): Promise { + const count = value.mask.toString(2).replaceAll("0", "").length; + if (!Number.isInteger(value.mask) || value.mask < 1 || value.mask > 31 || count > 3 + || !Number.isInteger(value.holdTime) || value.holdTime < 0 || value.holdTime > 255) throw new Error("Choose one to three pairing buttons."); + const current = await this.readPairingShortcut(); + const p = new Uint8Array(20); p.set([0x0b, 1, value.mask, current.holdTime]); + await this.writeSettings(p); + if ((await this.readPairingShortcut()).mask !== value.mask) throw new Error("The mouse did not keep the pairing shortcut."); + } + + private async readDynamicDpi(profile: number): Promise { + const r = await this.query(COMMAND_REPORT_ID, PACKET_LENGTH, [0x4f, profile], b => b[0] === 0x4f && b[1] === profile); + const count = r[5]!; + if (!count || count > 14 || r.length < 6 + count * 4 || r[3]! > 3) throw new Error("Invalid dynamic DPI report."); + return { profile, enabled: !!(r[2]! & 1), mode: r[3]!, points: Array.from({ length: count }, (_, i) => ({ speed: readU16(r, 6 + 4 * i), gain: r[8 + 4 * i]! })) }; + } + + async setKeychronDynamicDpi(value: KeychronDynamicDpi): Promise { + const status = await this.readSettings(); + if (!status.features.dynamicDpi || value.profile !== status.profile) throw new Error("The active dynamic DPI profile changed. Refresh first."); + if (!Number.isInteger(value.mode) || value.mode < 0 || value.mode > 3 || !value.points.length || value.points.length > 14 + || value.points.some((p, i) => !Number.isInteger(p.speed) || p.speed < 0 || p.speed > 200 + || !Number.isInteger(p.gain) || p.gain < 0 || p.gain > 56 || (i > 0 && p.speed <= value.points[i - 1]!.speed))) throw new Error("Invalid dynamic DPI curve."); + const packet = new Uint8Array(PACKET_LENGTH); packet.set([0x4e, value.profile, +value.enabled, value.mode, 0, value.points.length]); + value.points.forEach((p, i) => { writeU16(packet, 6 + 4 * i, p.speed); packet[8 + 4 * i] = p.gain; }); + // Launcher does not wait for an ACK for 0x4e. Serialize the send, then verify with 0x4f. + await this.sendWithoutReply(COMMAND_REPORT_ID, packet); + const confirmed = await this.readDynamicDpi(value.profile); + if (JSON.stringify(confirmed) !== JSON.stringify(value)) throw new Error("The mouse did not keep the dynamic DPI settings."); + } + + async resetKeychronMouse(): Promise { + await this.setDebounceTime(8); + const packet = new Uint8Array(20); packet.set([0x0f, 0xff]); + await this.writeSettings(packet); + await new Promise(resolve => setTimeout(resolve, 3000)); + } + async setDpi(dpi: number): Promise { const current = await this.readDpi(await this.readSettings(), await this.readIdentity()); return await this.setDpiStageValue(current.activeStage, dpi); @@ -840,12 +1013,37 @@ export class Keychron8kHidClient { } } - private async query( + private queryTail: Promise = Promise.resolve(); + private queryPending = 0; + + protected async sendWithoutReply(reportId: number, packet: Uint8Array): Promise { + const previous = this.queryTail; + let release!: () => void; + this.queryPending++; + this.queryTail = new Promise(resolve => { release = resolve; }); + try { + await previous; + if (!this.device.opened) throw new Error("The mouse was disconnected."); + await this.device.sendReport(reportId, packet.buffer as ArrayBuffer); + } finally { this.queryPending--; release(); } + } + + protected async query(reportId: number, length: number, payload: number[], match: (bytes: Uint8Array) => boolean): Promise { + this.queryPending++; + const previous = this.queryTail; + let release!: () => void; + this.queryTail = new Promise(resolve => { release = resolve; }); + try { await previous; return await this.executeQuery(reportId, length, payload, match); } + finally { this.queryPending--; release(); } + } + + private async executeQuery( reportId: number, length: number, payload: number[], match: (bytes: Uint8Array) => boolean, ): Promise { + if (!this.device.opened) throw new Error("The mouse was disconnected."); if (this.responseWaiter) throw new Error(`Another ${this.label} request is already in progress.`); const packet = new Uint8Array(length); packet.set(payload.slice(0, length)); @@ -890,6 +1088,10 @@ function decodeFeatures(feature1: number, feature2: number, feature3: number, fe pollingGears: (feature1 & 0x10) !== 0, fps20k: (feature1 & 0x80) !== 0, angle: (feature2 & 0x04) !== 0, + triggerSense: (feature2 & 0x68) !== 0, + switchChoice: (feature2 & 0x08) !== 0, + pairing: (feature2 & 0x02) !== 0, + dynamicDpi: (feature4 & 0x20) !== 0, separateDpi: (feature3 & 0x01) !== 0, separatePolling: (feature3 & 0x02) !== 0, lodLevel: (feature4 & 0x10) !== 0, @@ -901,3 +1103,7 @@ function decodeFirmwareNibbles(bytes: Uint8Array): string | null { if (bytes.length < 9) return null; return `v${bytes[8]}.${(bytes[7] ?? 0) >> 4}.${(bytes[7] ?? 0) & 0x0f}`; } + +function heTravelLevel(raw: number): number | null { + return raw >= 10 && raw <= 65 && (raw - 10) % 5 === 0 ? 1 + (raw - 10) / 5 : null; +} diff --git a/src/drivers/keychron/receiver-hid.test.ts b/src/drivers/keychron/receiver-hid.test.ts new file mode 100644 index 00000000..5692d115 --- /dev/null +++ b/src/drivers/keychron/receiver-hid.test.ts @@ -0,0 +1,73 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { isKeychronConfigurableReceiver, KeychronReceiverControls } from "./receiver-hid.ts"; + +function receiver() { + const requests: Array<{ report: number; bytes: number[] }> = []; + const buttons = new Map(); + let light = [1, 255, 153, 10, 20, 30]; + let keepWrite = true; + const client = new KeychronReceiverControls(async (report, length, bytes, match) => { + requests.push({ report, bytes }); + const reply = new Uint8Array(length); + if (bytes[0] === 2) reply.set([2, 6, 0, 0x34, 0x34, 0x5a, 0xd0, 0x23, 1]); + else if (bytes[0] === 0x31) { reply.set([0x31, bytes[1]!, 0]); reply.set(buttons.get(bytes[1]!) ?? [0], 3); } + else if (bytes[0] === 0x30) { + if (keepWrite) buttons.set(bytes[1]!, bytes.slice(3)); + reply.set([0xe4, 0, 0x30]); + } else if (bytes[0] === 0x20) { reply.set([0x20, 0, 0, 0, ...light]); } + else throw new Error("Unexpected receiver request"); + assert.equal(match(reply), true); + return reply; + }, async (report, bytes) => { + requests.push({ report, bytes: Array.from(bytes) }); + assert.equal(report, 0xb5); assert.deepEqual(Array.from(bytes.slice(0, 2)), [0x24, 0]); + if (keepWrite) light = Array.from(bytes.slice(2, 8)); + }); + return { client, requests, buttons, rejectReadback: () => { keepWrite = false; } }; +} + +test("only the described TurboLink receiver exposes its own configuration", () => { + assert.equal(isKeychronConfigurableReceiver({ vendorId: 0x3434, productId: 0xd05a } as HIDDevice), true); + assert.equal(isKeychronConfigurableReceiver({ vendorId: 0x3434, productId: 0xd086 } as HIDDevice), false); + assert.equal(isKeychronConfigurableReceiver({ vendorId: 0x3434, productId: 0xd028 } as HIDDevice), false); +}); + +test("receiver buttons use 0x30/0x31, preserve unknown assignments, and verify readback", async () => { + const { client, requests, buttons, rejectReadback } = receiver(); + const state = await client.readStatus(); + assert.equal(Object.keys(state.buttonMappings).length, 4); + assert.equal(state.firmware, "v1.2.3"); + await client.setButtonMapping("Switch type", "Magnetic (both)"); + assert.deepEqual(buttons.get(2)?.slice(0, 4), [15, 3, 204, 2]); + await client.setButtonMapping("Polling", "DPI Loop"); + assert.equal((await client.readStatus()).buttonMappings.Polling, "DPI Loop"); + assert.equal(requests.some(r => r.bytes[0] === 0x52 || r.bytes[0] === 0x62 || r.bytes[0] === 0x65), false); + buttons.set(1, [14, 99]); + assert.equal((await client.readStatus()).buttonMappings.Lighting, "Custom"); + rejectReadback(); + await assert.rejects(() => client.setButtonMapping("Polling", "Disabled"), /did not keep/); +}); + +test("receiver lighting writes its target byte and verifies its separate read format", async () => { + const { client, requests, rejectReadback } = receiver(); + const lighting = (await client.readStatus()).lighting; + const next = { ...lighting, brightness: 50, speed: 2, color: "#20a080" }; + assert.deepEqual(await client.setLighting(next), next); + const write = requests.find(r => r.bytes[0] === 0x24)!; + assert.deepEqual(write.bytes.slice(0, 8), [0x24, 0, 1, 128, 102, 32, 160, 128]); + rejectReadback(); + await assert.rejects(() => client.setLighting({ ...next, brightness: 100 }), /did not keep/); +}); + +test("receiver key combinations use keyboard records and retain modifiers on readback", async () => { + const { client, buttons, rejectReadback } = receiver(); + await client.setButtonMapping("Polling", "Keyboard: Ctrl+Shift+A"); + assert.deepEqual(buttons.get(0)?.slice(0, 4), [2, 3, 4, 0]); + assert.equal((await client.readStatus()).buttonMappings.Polling, "Keyboard: Ctrl+Shift+A"); + await client.setButtonMapping("Lighting", "Keyboard: Win+F12"); + assert.deepEqual(buttons.get(1)?.slice(0, 3), [2, 8, 69]); + await assert.rejects(() => client.setButtonMapping("Polling", "Keyboard: Ctrl+Unknown"), /Unknown/); + rejectReadback(); + await assert.rejects(() => client.setButtonMapping("Polling", "Keyboard: Alt+Tab"), /did not keep/); +}); diff --git a/src/drivers/keychron/receiver-hid.ts b/src/drivers/keychron/receiver-hid.ts new file mode 100644 index 00000000..760ff5d5 --- /dev/null +++ b/src/drivers/keychron/receiver-hid.ts @@ -0,0 +1,80 @@ +import type { KeychronReceiverStatus, MouseLighting } from "../mouse-types.ts"; +import { encodeReceiverKeys, decodeReceiverKeys } from "../../keychron/receiver-keys.ts"; +import { keychronButtonOptions, keychronDecodeButton, keychronEncodeButton, keychronEncodeLighting, keychronLighting } from "./launcher-mouse.ts"; + +const BUTTONS = [ + { name: "Polling", index: 0, action: "Polling Loop" }, + { name: "Lighting", index: 1, action: "Lighting mode cycle" }, + { name: "Switch type", index: 2, action: "Toggle optical / magnetic" }, + { name: "DPI", index: 3, action: "DPI Loop" }, +]; +const EXTRA: ReadonlyArray = [ + ["Lighting mode cycle", [6, 1]], ["Lighting speed cycle", [6, 2]], ["Lighting colour cycle", [6, 3]], + ["Lighting brightness +", [6, 4]], ["Lighting brightness -", [6, 5]], + ...([204, 0, 2] as const).flatMap((target, i) => ([ + [`Toggle optical / magnetic${i ? i === 1 ? " (left)" : " (right)" : ""}`, [15, 3, target, 0]], + [`Optical${i ? i === 1 ? " (left)" : " (right)" : " (both)"}`, [15, 3, target, 1]], + [`Magnetic${i ? i === 1 ? " (left)" : " (right)" : " (both)"}`, [15, 3, target, 2]], + ] as const)), +]; + + +export function isKeychronConfigurableReceiver(device: HIDDevice): boolean { + return device.vendorId === 0x3434 && device.productId === 0xd05a; +} + +type Query = (reportId: number, length: number, payload: number[], match: (bytes: Uint8Array) => boolean) => Promise; +type Send = (reportId: number, packet: Uint8Array) => Promise; + +/** Receiver controls share the mouse's transport queue, but use bridge_config commands. */ +export class KeychronReceiverControls { + constructor(private readonly query: Query, private readonly sendWithoutReply: Send) {} + + async readStatus(): Promise { + const version = await this.query(0xb5, 20, [2, 0], b => b[0] === 2); + if (version.length < 9) throw new Error("Incomplete receiver identity."); + const buttonMappings: Record = {}; + for (const button of BUTTONS) buttonMappings[button.name] = await this.readReceiverButton(button.index, button.action); + return { + name: "Keychron TurboLink 8K", + buttonMappings, + buttonOptions: [...keychronButtonOptions("8k", true), ...EXTRA.map(([label]) => label)], + lighting: await this.readReceiverLighting(), + firmware: 'v' + version[8] + '.' + (version[7] >> 4) + '.' + (version[7] & 15), + }; + } + + private async readReceiverButton(index: number, fallback: string): Promise { + const reply = await this.query(0xb3, 63, [0x31, index], b => b[0] === 0x31 && b[1] === index); + if (reply.length < 4) throw new Error("Incomplete receiver button record."); + const special = EXTRA.find(([, bytes]) => bytes.every((byte, i) => reply[3 + i] === byte)); + return special?.[0] ?? decodeReceiverKeys(reply) ?? keychronDecodeButton(reply, "8k") ?? fallback; + } + + async setButtonMapping(button: string, action: string): Promise { + const target = BUTTONS.find(b => b.name === button); + const bytes = EXTRA.find(([label]) => label === action)?.[1] ?? encodeReceiverKeys(action) ?? keychronEncodeButton(action, "8k"); + if (!target || !bytes) throw new Error("Unknown receiver button assignment."); + const packet = new Uint8Array(63); packet.set([0x30, target.index, 0]); packet.set(bytes, 3); + const ack = await this.query(0xb3, 63, Array.from(packet), b => b[0] === 0xe4 && b[2] === 0x30); + if (ack[1] !== 0) throw new Error("The receiver rejected the button assignment."); + const expected = action === "Default" ? target.action : action; + if (await this.readReceiverButton(target.index, target.action) !== expected) throw new Error("The receiver did not keep the button assignment."); + } + + private async readReceiverLighting(): Promise { + const r = await this.query(0xb5, 20, [0x20, 0], b => b[0] === 0x20 && b[1] === 0); + if (r.length < 10) throw new Error("Incomplete receiver lighting report."); + return { ...keychronLighting({ mode: r[4]!, brightness: r[5]!, speed: r[6]!, rgb: [r[7]!, r[8]!, r[9]!] }, [1, 2, 3]), zone: "Receiver" }; + } + + async setLighting(lighting: MouseLighting): Promise { + const next = keychronEncodeLighting(lighting, [1, 2, 3]); + const packet = new Uint8Array(20); packet.set([0x24, 0, next.mode, next.brightness, next.speed, ...next.rgb]); + await this.sendWithoutReply(0xb5, packet); + const confirmed = await this.readReceiverLighting(); + if (confirmed.mode !== lighting.mode || confirmed.brightness !== lighting.brightness || confirmed.speed !== lighting.speed + || confirmed.color?.toLowerCase() !== lighting.color?.toLowerCase()) throw new Error("The receiver did not keep the lighting settings."); + return confirmed; + } +} diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index 78bb6c0f..b5e8e2bb 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -6,6 +6,8 @@ import type { AtkDeviceFeatures } from "./atk/device-catalog.generated.js"; export interface MouseUiHints { + /** This connection is carried by a receiver with its own configurable controls. */ + receiverControls?: boolean; /** Stable driver id, e.g. "egg-we". */ family?: string; /** When false, core settings grid stays hidden. Default true. */ @@ -207,7 +209,30 @@ export interface MagneticCalibrationProgress { steps: number; } +export interface KeychronDynamicDpi { + profile: number; + enabled: boolean; + mode: number; + points: Array<{ speed: number; gain: number }>; +} + +export interface KeychronReceiverStatus { + name: string; + firmware: string; + buttonMappings: Record; + buttonOptions: string[]; + lighting: MouseLighting; +} + export interface MouseStatus { + /** Controls for the configurable receiver carrying this mouse's wireless link. */ + keychronReceiver?: KeychronReceiverStatus; + /** Optional Launcher 8K features, populated only after successful device reads. */ + keychronMouse?: { + pairing: { mask: number; holdTime: number } | null; + dynamicDpi: KeychronDynamicDpi | null; + factoryReset: boolean; + }; brand: "RAWM" | "Motospeed" | "Logitech" | "Pulsar" | "Endgame Gear" | "WLMouse" | "G-Wolves" | "Lamzu" | "CRDRAKO" | "Attack Shark" | "LunaFury" | "Vancer" | "Orbital" | "Razer" | "Teevolution" | "ATK" | "VXE" | "VGN" | "VAXEE" | "Finalmouse" | "Keychron" | "moddoMOUSE" | "Ninjutso" | "Zaunkoenig" | "Fantech" | "Wooting" | "WALLHACK" | "SteelSeries" | "Glorious" | "MCHOSE" | "K-snake" | "Noir Gear" | "Lingbao" | "GearHub" | "AJAZZ" | "Corsair" | "Microsoft" | "Dareu" | "Redragon" | "Incott" | "HyperX" | "ASUS" | "Ryunix" | "Amkette" | "Delux" | "GravaStar" | "IPI" | "Rapoo" | "Fater" | "Cooler Master" | "AJAZZ" | "Scyrox" | "Hitscan" | "ROCCAT" | "Thermaltake" | "Redgear" | "AULA"; name: string; /** Optional LunaFury controls, populated only after successful device reads. */ diff --git a/src/keychron/index.ts b/src/keychron/index.ts index 073b98eb..5070b240 100644 --- a/src/keychron/index.ts +++ b/src/keychron/index.ts @@ -556,3 +556,4 @@ export function keychronDecodeKeycodeReply(response: Uint8Array): number { return ((response[4] ?? 0) << 8) | (response[5] ?? 0); } +export { KEYCHRON_RECEIVER_KEYS, KEYCHRON_RECEIVER_MODIFIERS } from "./receiver-keys.ts"; diff --git a/src/keychron/receiver-keys.ts b/src/keychron/receiver-keys.ts new file mode 100644 index 00000000..e89cdc84 --- /dev/null +++ b/src/keychron/receiver-keys.ts @@ -0,0 +1,51 @@ +/** USB keyboard usages offered by Launcher's receiver keyboard editor. */ +export const KEYCHRON_RECEIVER_KEYS: ReadonlyArray = [ + ...Array.from({ length: 26 }, (_, i) => [String.fromCharCode(65 + i), 4 + i] as const), + ...Array.from({ length: 9 }, (_, i) => [String(i + 1), 30 + i] as const), + ["0", 39], ["Enter", 40], ["Escape", 41], ["Backspace", 42], ["Tab", 43], ["Space", 44], + ["Minus", 45], ["Equal", 46], ["BracketLeft", 47], ["BracketRight", 48], ["Backslash", 49], + ["Semicolon", 51], ["Quote", 52], ["Backquote", 53], ["Comma", 54], ["Period", 55], ["Slash", 56], + ["CapsLock", 57], ...Array.from({ length: 12 }, (_, i) => [`F${i + 1}`, 58 + i] as const), + ["PrintScreen", 70], ["ScrollLock", 71], ["Pause", 72], ["Insert", 73], ["Home", 74], + ["PageUp", 75], ["Delete", 76], ["End", 77], ["PageDown", 78], + ["ArrowRight", 79], ["ArrowLeft", 80], ["ArrowDown", 81], ["ArrowUp", 82], + ["NumLock", 83], ["NumpadDivide", 84], ["NumpadMultiply", 85], ["NumpadSubtract", 86], + ["NumpadAdd", 87], ["NumpadEnter", 88], + ...Array.from({ length: 9 }, (_, i) => [`Numpad${i + 1}`, 89 + i] as const), + ["Numpad0", 98], ["NumpadDecimal", 99], + ...Array.from({ length: 7 }, (_, i) => [`F${i + 13}`, 104 + i] as const), + ["ControlLeft", 224], ["ShiftLeft", 225], ["AltLeft", 226], ["MetaLeft", 227], + ["ControlRight", 228], ["ShiftRight", 229], ["AltRight", 230], ["MetaRight", 231], +]; +export const KEYCHRON_RECEIVER_MODIFIERS = ["Ctrl", "Shift", "Alt", "Win", "RightCtrl", "RightShift", "RightAlt", "RightWin"] as const; + +/** Receiver EFunKey.Keyboard (2): modifier bitmask followed by USB usages. */ +export function encodeReceiverKeys(action: string): number[] | null { + if (!action.startsWith("Keyboard: ")) return null; + const parts = action.slice(10).split("+"); + let modifiers = 0; + const keys: number[] = []; + for (const part of parts) { + const bit = KEYCHRON_RECEIVER_MODIFIERS.indexOf(part as typeof KEYCHRON_RECEIVER_MODIFIERS[number]); + if (bit >= 0) { if (modifiers & (1 << bit)) return null; modifiers |= 1 << bit; } + else { + const key = KEYCHRON_RECEIVER_KEYS.find(([name]) => name === part); + if (!key || keys.includes(key[1])) return null; + keys.push(key[1]); + } + } + return keys.length > 0 && keys.length <= 6 ? [2, modifiers, ...keys] : null; +} + +export function decodeReceiverKeys(bytes: Uint8Array): string | null { + if (bytes[3] !== 2 || bytes.length < 6) return null; + const parts: string[] = KEYCHRON_RECEIVER_MODIFIERS.filter((_, bit) => (bytes[4]! & (1 << bit)) !== 0); + let count = 0; + for (const usage of bytes.slice(5)) { + if (usage === 0) break; + const key = KEYCHRON_RECEIVER_KEYS.find(([, code]) => code === usage); + if (!key || ++count > 6) return null; + parts.push(key[0]); + } + return count ? `Keyboard: ${parts.join("+")}` : null; +} From 8f54fd8c119e75bf5955681216d52549aa02ecf6 Mon Sep 17 00:00:00 2001 From: snekxs <26660858+snekxs@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:28:50 -0600 Subject: [PATCH 2/2] fix(keychron): serialize HE edits and normalize readback checks --- src/drivers/keychron/mouse-8k-hid.test.ts | 37 +++++++++++++++++++++++ src/drivers/keychron/mouse-8k-hid.ts | 15 +++++++-- src/drivers/keychron/receiver-hid.test.ts | 15 +++++++++ src/drivers/keychron/receiver-hid.ts | 8 +++-- 4 files changed, 70 insertions(+), 5 deletions(-) diff --git a/src/drivers/keychron/mouse-8k-hid.test.ts b/src/drivers/keychron/mouse-8k-hid.test.ts index 15df07f5..583025b9 100644 --- a/src/drivers/keychron/mouse-8k-hid.test.ts +++ b/src/drivers/keychron/mouse-8k-hid.test.ts @@ -23,6 +23,7 @@ class FakeKeychronMouse { return r; }); failHeWrite = false; + failDynamicWrite = false; pairMask = 9; receiverButtons = new Map(); dynamic = { profile: 1, enabled: true, mode: 0, points: [{ speed: 0, gain: 16 }, { speed: 200, gain: 56 }] }; @@ -95,6 +96,7 @@ class FakeKeychronMouse { this.emit(0xb4, r); return; } if (reportId === 0xb3 && packet[0] === 0x4e) { + if (this.failDynamicWrite) return; this.dynamic = { profile: packet[1]!, enabled: !!packet[2], mode: packet[3]!, points: Array.from({ length: packet[5]! }, (_, i) => ({ speed: packet[6 + 4 * i]! | packet[7 + 4 * i]! << 8, gain: packet[8 + 4 * i]! })) }; return; } if (reportId === 0xb3 && packet[0] === 0x65) { @@ -789,6 +791,41 @@ test("scroll reversal preserves sensor flags and lift off", async () => { assert.equal((await hid.readStatus()).scrollDirection, "Reverse"); await hid.close(); }); +test("concurrent HE edits retain both buttons and the edit queue recovers after failure", async () => { + const fake = new FakeKeychronMouse(), hid = client(fake); await hid.open(); + await Promise.all([hid.setMagneticTriggerPoint(0, 6), hid.setMagneticTriggerPoint(1, 8)]); + assert.equal(fake.heRecords[0]![5], 35); + assert.equal(fake.heRecords[1]![5], 45); + const results = await Promise.allSettled([ + hid.setMagneticRapidTrigger(0, true, 11), hid.setMagneticTriggerPoint(1, 5), + ]); + assert.equal(results[0]!.status, "rejected"); + assert.equal(results[1]!.status, "fulfilled"); + assert.equal(fake.heRecords[1]![5], 30); + fake.failHeWrite = true; + await assert.rejects(hid.setMagneticTriggerPoint(0, 7), /did not keep/); + fake.failHeWrite = false; + await hid.setMagneticTriggerPoint(0, 8); + assert.equal(fake.heRecords[0]![5], 45); + await hid.close(); +}); + +test("Dynamic DPI accepts reordered properties but rejects changed scalars and point values", async () => { + const fake = new FakeKeychronMouse(); fake.version = 6; fake.features[3] = 32; + const hid = client(fake); await hid.open(); + const next = { enabled: true, points: [{ gain: 8, speed: 0 }, { gain: 32, speed: 100 }], mode: 0, profile: 1 }; + await hid.setKeychronDynamicDpi(next); + assert.deepEqual(fake.dynamic, next); + fake.failDynamicWrite = true; + for (const value of [ + { ...next, enabled: false }, { ...next, mode: 1 }, + { ...next, points: [{ speed: 0, gain: 9 }, { speed: 100, gain: 32 }] }, + { ...next, points: [{ speed: 0, gain: 8 }, { speed: 101, gain: 32 }] }, + { ...next, points: [{ speed: 0, gain: 8 }] }, + ]) await assert.rejects(hid.setKeychronDynamicDpi(value), /did not keep/); + await hid.close(); +}); + test("pairing shortcut and dynamic DPI are capability-gated and round-trip", async () => { const fake = new FakeKeychronMouse(); fake.version = 6; fake.features[1] = 2; fake.features[3] = 32; const hid = client(fake); const status = await hid.readStatus(); diff --git a/src/drivers/keychron/mouse-8k-hid.ts b/src/drivers/keychron/mouse-8k-hid.ts index 0d846d4e..b38deea1 100644 --- a/src/drivers/keychron/mouse-8k-hid.ts +++ b/src/drivers/keychron/mouse-8k-hid.ts @@ -352,6 +352,7 @@ export class Keychron8kHidClient { private depthTimer: ReturnType | null = null; private depthListeners = new Set<(left: number, right: number) => void>(); private magneticWrite = false; + private heEditTail: Promise = Promise.resolve(); /** Launcher polls 0x65 every 50 ms only while its travel view is visible. */ onButtonDepth(listener: (left: number, right: number) => void): () => void { @@ -392,7 +393,13 @@ export class Keychron8kHidClient { }; } - private async editHe(edit: (records: Uint8Array[]) => void): Promise { + private editHe(edit: (records: Uint8Array[]) => void): Promise { + const result = this.heEditTail.then(() => this.performHeEdit(edit)); + this.heEditTail = result.catch(() => {}); + return result; + } + + private async performHeEdit(edit: (records: Uint8Array[]) => void): Promise { this.magneticWrite = true; try { const records = await this.readHeRecords(); @@ -481,7 +488,11 @@ export class Keychron8kHidClient { // Launcher does not wait for an ACK for 0x4e. Serialize the send, then verify with 0x4f. await this.sendWithoutReply(COMMAND_REPORT_ID, packet); const confirmed = await this.readDynamicDpi(value.profile); - if (JSON.stringify(confirmed) !== JSON.stringify(value)) throw new Error("The mouse did not keep the dynamic DPI settings."); + if (confirmed.profile !== value.profile || confirmed.enabled !== value.enabled || confirmed.mode !== value.mode + || confirmed.points.length !== value.points.length || confirmed.points.some((point, i) => + point.speed !== value.points[i]!.speed || point.gain !== value.points[i]!.gain)) { + throw new Error("The mouse did not keep the dynamic DPI settings."); + } } async resetKeychronMouse(): Promise { diff --git a/src/drivers/keychron/receiver-hid.test.ts b/src/drivers/keychron/receiver-hid.test.ts index 5692d115..fe992a91 100644 --- a/src/drivers/keychron/receiver-hid.test.ts +++ b/src/drivers/keychron/receiver-hid.test.ts @@ -65,9 +65,24 @@ test("receiver key combinations use keyboard records and retain modifiers on rea await client.setButtonMapping("Polling", "Keyboard: Ctrl+Shift+A"); assert.deepEqual(buttons.get(0)?.slice(0, 4), [2, 3, 4, 0]); assert.equal((await client.readStatus()).buttonMappings.Polling, "Keyboard: Ctrl+Shift+A"); + await client.setButtonMapping("Polling", "Keyboard: Shift+Ctrl+A"); + assert.equal((await client.readStatus()).buttonMappings.Polling, "Keyboard: Ctrl+Shift+A"); await client.setButtonMapping("Lighting", "Keyboard: Win+F12"); assert.deepEqual(buttons.get(1)?.slice(0, 3), [2, 8, 69]); await assert.rejects(() => client.setButtonMapping("Polling", "Keyboard: Ctrl+Unknown"), /Unknown/); rejectReadback(); await assert.rejects(() => client.setButtonMapping("Polling", "Keyboard: Alt+Tab"), /did not keep/); }); + +test("receiver lighting verifies the encoded defaults and still rejects a retained old value", async () => { + const { client, rejectReadback } = receiver(); + const lighting = (await client.readStatus()).lighting; + const confirmed = await client.setLighting({ ...lighting, brightness: undefined, speed: null, color: null }); + assert.equal(confirmed.brightness, 100); + assert.equal(confirmed.speed, 5); + assert.equal(confirmed.color, "#ffffff"); + const uppercase = await client.setLighting({ ...confirmed, color: "#ABCDEF" }); + assert.equal(uppercase.color, "#abcdef"); + rejectReadback(); + await assert.rejects(client.setLighting({ ...uppercase, brightness: 25 }), /did not keep/); +}); diff --git a/src/drivers/keychron/receiver-hid.ts b/src/drivers/keychron/receiver-hid.ts index 760ff5d5..e9494012 100644 --- a/src/drivers/keychron/receiver-hid.ts +++ b/src/drivers/keychron/receiver-hid.ts @@ -58,7 +58,8 @@ export class KeychronReceiverControls { const packet = new Uint8Array(63); packet.set([0x30, target.index, 0]); packet.set(bytes, 3); const ack = await this.query(0xb3, 63, Array.from(packet), b => b[0] === 0xe4 && b[2] === 0x30); if (ack[1] !== 0) throw new Error("The receiver rejected the button assignment."); - const expected = action === "Default" ? target.action : action; + const expected = action === "Default" ? target.action + : bytes[0] === 2 ? decodeReceiverKeys(Uint8Array.from([0, 0, 0, ...bytes])) : action; if (await this.readReceiverButton(target.index, target.action) !== expected) throw new Error("The receiver did not keep the button assignment."); } @@ -73,8 +74,9 @@ export class KeychronReceiverControls { const packet = new Uint8Array(20); packet.set([0x24, 0, next.mode, next.brightness, next.speed, ...next.rgb]); await this.sendWithoutReply(0xb5, packet); const confirmed = await this.readReceiverLighting(); - if (confirmed.mode !== lighting.mode || confirmed.brightness !== lighting.brightness || confirmed.speed !== lighting.speed - || confirmed.color?.toLowerCase() !== lighting.color?.toLowerCase()) throw new Error("The receiver did not keep the lighting settings."); + const expected = keychronLighting(next, [1, 2, 3]); + if (confirmed.mode !== expected.mode || confirmed.brightness !== expected.brightness || confirmed.speed !== expected.speed + || confirmed.color !== expected.color) throw new Error("The receiver did not keep the lighting settings."); return confirmed; } }