@openmouse/protocol 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +1 -0
  2. package/dist/drivers/keychron/mouse-4k-hid.d.ts +5 -1
  3. package/dist/drivers/keychron/mouse-4k-hid.d.ts.map +1 -1
  4. package/dist/drivers/keychron/mouse-4k-hid.js +8 -3
  5. package/dist/drivers/keychron/mouse-4k-hid.js.map +1 -1
  6. package/dist/drivers/keychron/mouse-8k-nordic-hid.d.ts +145 -0
  7. package/dist/drivers/keychron/mouse-8k-nordic-hid.d.ts.map +1 -0
  8. package/dist/drivers/keychron/mouse-8k-nordic-hid.js +639 -0
  9. package/dist/drivers/keychron/mouse-8k-nordic-hid.js.map +1 -0
  10. package/dist/drivers/ksnake/hid.d.ts +43 -10
  11. package/dist/drivers/ksnake/hid.d.ts.map +1 -1
  12. package/dist/drivers/ksnake/hid.js +223 -48
  13. package/dist/drivers/ksnake/hid.js.map +1 -1
  14. package/dist/drivers/mouse-types.d.ts +4 -2
  15. package/dist/drivers/mouse-types.d.ts.map +1 -1
  16. package/dist/drivers/pulsar/pulsar-xs1-hid.d.ts.map +1 -1
  17. package/dist/drivers/pulsar/pulsar-xs1-hid.js +4 -1
  18. package/dist/drivers/pulsar/pulsar-xs1-hid.js.map +1 -1
  19. package/dist/drivers/rapoo/hid.d.ts +72 -0
  20. package/dist/drivers/rapoo/hid.d.ts.map +1 -0
  21. package/dist/drivers/rapoo/hid.js +389 -0
  22. package/dist/drivers/rapoo/hid.js.map +1 -0
  23. package/dist/drivers/redragon/hid.d.ts +56 -5
  24. package/dist/drivers/redragon/hid.d.ts.map +1 -1
  25. package/dist/drivers/redragon/hid.js +309 -1
  26. package/dist/drivers/redragon/hid.js.map +1 -1
  27. package/dist/drivers/registry.d.ts +3 -1
  28. package/dist/drivers/registry.d.ts.map +1 -1
  29. package/dist/drivers/registry.js +10 -0
  30. package/dist/drivers/registry.js.map +1 -1
  31. package/dist/drivers/vendors.d.ts +2 -0
  32. package/dist/drivers/vendors.d.ts.map +1 -1
  33. package/dist/drivers/vendors.js +11 -0
  34. package/dist/drivers/vendors.js.map +1 -1
  35. package/dist/index.d.ts +1 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +1 -0
  38. package/dist/index.js.map +1 -1
  39. package/dist/keychron/index.d.ts +19 -0
  40. package/dist/keychron/index.d.ts.map +1 -1
  41. package/dist/keychron/index.js +21 -0
  42. package/dist/keychron/index.js.map +1 -1
  43. package/dist/ksnake/index.d.ts +88 -15
  44. package/dist/ksnake/index.d.ts.map +1 -1
  45. package/dist/ksnake/index.js +323 -26
  46. package/dist/ksnake/index.js.map +1 -1
  47. package/dist/pulsar/index.d.ts.map +1 -1
  48. package/dist/pulsar/index.js +1 -1
  49. package/dist/pulsar/index.js.map +1 -1
  50. package/dist/rapoo/index.d.ts +278 -0
  51. package/dist/rapoo/index.d.ts.map +1 -0
  52. package/dist/rapoo/index.js +363 -0
  53. package/dist/rapoo/index.js.map +1 -0
  54. package/dist/redragon/index.d.ts +122 -0
  55. package/dist/redragon/index.d.ts.map +1 -1
  56. package/dist/redragon/index.js +322 -0
  57. package/dist/redragon/index.js.map +1 -1
  58. package/package.json +5 -1
@@ -0,0 +1,639 @@
1
+ import { KEYCHRON_4K_USAGE as USAGE, KEYCHRON_4K_USAGE_PAGE as USAGE_PAGE, KEYCHRON_8K_NORDIC_MICE as MICE, KEYCHRON_8K_NORDIC_PRODUCT_IDS as PRODUCT_IDS, KEYCHRON_VENDOR_ID, LEMOKEY_VENDOR_ID, } from "@openmouse/protocol/keychron";
2
+ import { orbitalFinishPacket } from "@openmouse/protocol/orbital";
3
+ const PACKET_LENGTH = 64;
4
+ const QUERY_TIMEOUT_MS = 1000;
5
+ /** Launcher's receiver queue resends an unanswered command three times; wired it sends once. */
6
+ const RECEIVER_RESENDS = 3;
7
+ const DPI_STAGE_COUNT = 5;
8
+ /** The G3 Air config (launcher.keychron.com/static/device/875876471/json/v3.json) says 100-30000; Launcher steps by 50. */
9
+ const DPI_MIN = 100;
10
+ const DPI_MAX = 30_000;
11
+ const DPI_STEP = 50;
12
+ /** Launcher's POLLING_RATE_VALUE_SCALE. Gear table bytes are an index into it plus one, with 0 for 125 Hz. */
13
+ const POLLING_RATES = [125, 500, 1000, 2000, 4000, 8000];
14
+ const POLLING_GEARS = 6;
15
+ /** Sensor byte 11, per the G3 Air config: 0 = 0.7 mm, 1 = 1 mm, 2 = 2 mm. */
16
+ const LOD_BY_LEVEL = { Low: 0, Medium: 1, High: 2 };
17
+ /** Launcher's angle slider; the byte is signed. */
18
+ const ANGLE_LIMIT = 90;
19
+ const DEBOUNCE_MAX_MS = 20;
20
+ /** Launcher takes 1-240 minutes and stores seconds. These are the M6 driver's choices. */
21
+ const SLEEP_MINUTES = [1, 3, 5, 10, 15, 30, 60, 120, 240];
22
+ const SLEEP_MAX_MINUTES = 240;
23
+ const PROFILE_COUNT = 5;
24
+ /** From this firmware the system block holds a second polling gear set for 2.4 GHz. */
25
+ const SEPARATE_RATES_FIRMWARE = [1, 6, 0];
26
+ /** Bytes 0, 2 and 3 of each command; byte 2 is 0x80 | payload length. */
27
+ const CMD = {
28
+ version: [0x00, 0x81, 0x00],
29
+ status: [0x01, 0x81, 0x01],
30
+ profile: [0x02, 0x82, 0x02],
31
+ readButtons: [0x03, 0x81, 0x01],
32
+ writeButton: [0x03, 0x85, 0x04],
33
+ readSensor: [0x04, 0x81, 0x01],
34
+ writeSensor: [0x04, 0xbc, 0x02],
35
+ readSystem: [0x04, 0x83, 0x03],
36
+ /** 24-byte payload; 32 bytes (0xa0) once the 2.4 GHz gear set exists. */
37
+ writeSystem: [0x04, 0x98, 0x04],
38
+ save: [0x0a, 0x81, 0x01],
39
+ };
40
+ /** Physical buttons by their index in the 0x03 table (the G3 Air config's key list). */
41
+ const BUTTONS = [
42
+ { name: "Left", index: 0 },
43
+ { name: "Right", index: 1 },
44
+ { name: "Middle", index: 2 },
45
+ { name: "Back", index: 4 },
46
+ { name: "Forward", index: 3 },
47
+ ];
48
+ /**
49
+ * Four-byte button codes from the key enums Launcher's 8k_nordic commands use
50
+ * (its 4K set, webpack module 45710): mouse buttons are 01 00 f0-f4 00, the
51
+ * same table the GearHub driver confirmed on hardware.
52
+ */
53
+ const BUTTON_ACTIONS = [
54
+ ["Left Click", [0x01, 0x00, 0xf0, 0x00]],
55
+ ["Right Click", [0x01, 0x00, 0xf1, 0x00]],
56
+ ["Middle Click", [0x01, 0x00, 0xf2, 0x00]],
57
+ ["Back", [0x01, 0x00, 0xf3, 0x00]],
58
+ ["Forward", [0x01, 0x00, 0xf4, 0x00]],
59
+ ["DPI Loop", [0x07, 0x00, 0x03, 0x00]],
60
+ ["DPI +", [0x07, 0x00, 0x01, 0x00]],
61
+ ["DPI -", [0x07, 0x00, 0x02, 0x00]],
62
+ ["Disabled", [0x00, 0x00, 0x00, 0x00]],
63
+ ];
64
+ const MACRO_CODE = 0x09;
65
+ /**
66
+ * Keychron Launcher's "8k_nordic" mouse protocol (Keychron G3 Air), decoded
67
+ * from Launcher (main.be11320b2a72b61b.js, webpack module 20706) and not yet
68
+ * confirmed on hardware. It shares the 4K family's collection and framing:
69
+ * 64-byte report 0, byte 63 = 0xa1 - sum, 0x40 on byte 0 to route through
70
+ * the receiver (echoed on the reply). The settings are Orbital's DMS v2
71
+ * blocks, with Keychron's polling gear table added to the system block.
72
+ * Every offset below is a packet offset; reads and writes share them.
73
+ *
74
+ * Sensor block (read 04/81/01, write 04/bc/02):
75
+ * [4..10] angle snapping, ripple, motion sync, full speed, 20K FPS, lift-down, glass (0/1)
76
+ * [11] lift-off code; [12] sensor angle, signed
77
+ * [13] active stage; [14] enabled-stage mask (1, 3, 7, 15, 31)
78
+ * [15..34] five stages of X then Y DPI, little-endian 16-bit
79
+ * [43..57] five stage colours, RGB
80
+ * System block (read 04/83/03, write 04/98/04 or 04/a0/04):
81
+ * [4..5] sleep in seconds; [6..7] Bluetooth sleep; both little-endian
82
+ * [8] active polling gear; [9] debounce in ms
83
+ * [10..19] quick response, wake sources, wheel reverse, key modes, RF power, BLE slot
84
+ * [20] enabled-gear mask; [21..26] gear table
85
+ * [28..35] the same three fields for 2.4 GHz, from firmware 1.6.0
86
+ * Status (01/81/01): [4] link, [6..9] vendor and product ID, [10] charge
87
+ * state (3 counts as none), [11] battery percent, [12] profile. Sent to the
88
+ * receiver unrouted, it answers itself with the paired mouse's IDs, which is
89
+ * how Launcher tells this protocol from the 4K one.
90
+ * Version (00/81/00): [9] major, [8] minor and patch nibbles.
91
+ * Buttons: 03/81/01 returns a 4-byte code per index at [4 + 4i]; 03/85/04
92
+ * writes one ([4] index, [5..8] code). Writes are followed by a save
93
+ * (0a/81/01), as Launcher does; a profile switch (02/82/02) is not.
94
+ */
95
+ export class Keychron8kNordicHidClient {
96
+ device;
97
+ /** Anything that is not a known wired mouse is one of the Ultra-Link 8K receivers. */
98
+ receiver;
99
+ listening = false;
100
+ name = null;
101
+ identity = null;
102
+ waiter = null;
103
+ onInputReport = (event) => {
104
+ if (!this.waiter)
105
+ return;
106
+ const bytes = new Uint8Array(event.data.buffer.slice(event.data.byteOffset, event.data.byteOffset + event.data.byteLength));
107
+ if (!this.waiter.match(bytes))
108
+ return;
109
+ const waiter = this.waiter;
110
+ this.waiter = null;
111
+ waiter.resolve(bytes);
112
+ };
113
+ constructor(device) {
114
+ this.device = device;
115
+ this.receiver = !MICE.some((mouse) => mouse.productId === device.productId);
116
+ }
117
+ static isSupported(device) {
118
+ return device.vendorId === KEYCHRON_VENDOR_ID
119
+ && PRODUCT_IDS.includes(device.productId)
120
+ && device.collections.some((collection) => collection.usagePage === USAGE_PAGE && collection.usage === USAGE);
121
+ }
122
+ async open() {
123
+ if (!this.device.opened)
124
+ await this.device.open();
125
+ if (!this.listening) {
126
+ this.device.addEventListener("inputreport", this.onInputReport);
127
+ this.listening = true;
128
+ }
129
+ }
130
+ async close() {
131
+ if (this.listening) {
132
+ this.device.removeEventListener("inputreport", this.onInputReport);
133
+ this.listening = false;
134
+ }
135
+ this.waiter?.reject(new Error(`The ${this.label} was closed.`));
136
+ this.waiter = null;
137
+ if (this.device.opened)
138
+ await this.device.close();
139
+ }
140
+ getDpiOptions() {
141
+ return Array.from({ length: (DPI_MAX - DPI_MIN) / DPI_STEP + 1 }, (_, index) => DPI_MIN + index * DPI_STEP);
142
+ }
143
+ getDebounceOptions() {
144
+ return Array.from({ length: DEBOUNCE_MAX_MS + 1 }, (_, ms) => ms);
145
+ }
146
+ getSleepOptions() {
147
+ return SLEEP_MINUTES.map((minutes) => minutes * 60);
148
+ }
149
+ /** Falls back to the name alone when the mouse does not answer, e.g. asleep behind its receiver. */
150
+ async readStatus() {
151
+ const name = await this.readName();
152
+ let identity;
153
+ let sensor;
154
+ let system;
155
+ let power;
156
+ try {
157
+ identity = await this.readIdentity();
158
+ sensor = await this.readSensor();
159
+ system = await this.readSystem();
160
+ power = await this.readPower();
161
+ }
162
+ catch {
163
+ return this.unreachableStatus(name);
164
+ }
165
+ const buttons = await this.readButtons().catch(() => null);
166
+ const gears = system.gears[this.gearSet(identity)];
167
+ const pollingRateHz = POLLING_RATES[gears.rates[gears.level] ?? -1] ?? 1000;
168
+ const liftOffDistance = Object.keys(LOD_BY_LEVEL)
169
+ .find((level) => LOD_BY_LEVEL[level] === sensor.lod) ?? null;
170
+ return {
171
+ brand: "Keychron",
172
+ name,
173
+ ui: {
174
+ family: "keychron-8k-nordic",
175
+ defaultDisplayName: name,
176
+ hideUnsupportedPollingRates: true,
177
+ forceShowBattery: true,
178
+ statusNote: "Lift-off: Low is 0.7 mm, Medium is 1 mm, High is 2 mm.",
179
+ dpiStageEditor: {
180
+ maxStages: DPI_STAGE_COUNT,
181
+ countEditable: true,
182
+ minDpi: DPI_MIN,
183
+ maxDpi: DPI_MAX,
184
+ stepDpi: DPI_STEP,
185
+ },
186
+ },
187
+ batteryPercent: power.percent <= 100 ? power.percent : null,
188
+ batteryState: power.state === 2 ? "Full" : power.state === 1 ? "Charging" : "Discharging",
189
+ dpi: sensor.stages[sensor.activeStage]?.[0] ?? 800,
190
+ dpiStages: sensor.stages.slice(0, sensor.stageCount).map(([x]) => x),
191
+ activeDpiStage: sensor.activeStage,
192
+ pollingRateHz,
193
+ supportedPollingRates: [...POLLING_RATES],
194
+ activeProfile: power.profile + 1,
195
+ profileCount: PROFILE_COUNT,
196
+ connectionType: this.receiver ? "Wireless" : "Wired",
197
+ connectionDetail: this.receiver ? "2.4 GHz (Keychron Ultra-Link 8K)" : "Wired USB",
198
+ liftOffDistance,
199
+ supportedLiftOffDistances: Object.keys(LOD_BY_LEVEL),
200
+ motionSync: sensor.motionSync,
201
+ angleSnapping: sensor.angleSnapping,
202
+ rippleControl: sensor.rippleControl,
203
+ performanceMode: sensor.maxSpeed,
204
+ angleTuning: sensor.angle,
205
+ debounceMs: system.debounceMs,
206
+ sleepTimeout: system.sleepSeconds > 0 ? system.sleepSeconds : null,
207
+ ...(buttons ? {
208
+ buttonMappings: Object.fromEntries(BUTTONS.map(({ name: button, index }) => [button, keychronNordicButtonLabel(buttons[index])])),
209
+ buttonOptions: BUTTON_ACTIONS.map(([label]) => label),
210
+ } : {}),
211
+ firmware: [identity.firmware],
212
+ };
213
+ }
214
+ async setDpi(dpi) {
215
+ this.requireDpi(dpi);
216
+ return this.setDpiStageValue((await this.readSensor()).activeStage, dpi);
217
+ }
218
+ async setDpiStageValue(stage, dpi) {
219
+ this.requireDpi(dpi);
220
+ const sensor = await this.readSensor();
221
+ this.requireStage(stage, sensor.stageCount);
222
+ // The panel edits one axis, so the stage gets X = Y; other stages keep their pairs.
223
+ const stages = sensor.stages.map((pair, index) => (index === stage ? [dpi, dpi] : pair));
224
+ const [x, y] = (await this.writeSensor({ ...sensor, stages })).stages[stage] ?? [];
225
+ if (x !== dpi || y !== dpi)
226
+ throw new Error(`The ${this.label} kept ${x} DPI on stage ${stage + 1} instead of ${dpi} DPI.`);
227
+ return dpi;
228
+ }
229
+ async setActiveDpiStage(stage) {
230
+ const sensor = await this.readSensor();
231
+ this.requireStage(stage, sensor.stageCount);
232
+ const confirmed = (await this.writeSensor({ ...sensor, activeStage: stage })).activeStage;
233
+ if (confirmed !== stage)
234
+ throw new Error(`The ${this.label} kept DPI stage ${confirmed + 1}.`);
235
+ return confirmed;
236
+ }
237
+ async setDpiStageCount(count) {
238
+ if (!Number.isInteger(count) || count < 1 || count > DPI_STAGE_COUNT) {
239
+ throw new Error(`The ${this.label} holds between 1 and ${DPI_STAGE_COUNT} DPI stages.`);
240
+ }
241
+ const sensor = await this.readSensor();
242
+ const activeStage = Math.min(sensor.activeStage, count - 1);
243
+ const confirmed = (await this.writeSensor({ ...sensor, stageCount: count, activeStage })).stageCount;
244
+ if (confirmed !== count)
245
+ throw new Error(`The ${this.label} kept ${confirmed} DPI stages instead of ${count}.`);
246
+ return confirmed;
247
+ }
248
+ /**
249
+ * Picks the gear that already holds the rate, or puts the rate in the
250
+ * active gear, which is what Launcher's own assistant does.
251
+ */
252
+ async setPollingRate(rateHz) {
253
+ const rate = POLLING_RATES.indexOf(rateHz);
254
+ if (rate < 0)
255
+ throw new Error(`The ${this.label} does not support ${rateHz} Hz.`);
256
+ const identity = await this.readIdentity();
257
+ const system = await this.readSystem();
258
+ const set = this.gearSet(identity);
259
+ const gears = system.gears[set];
260
+ const gear = gears.rates.slice(0, gears.count).indexOf(rate);
261
+ const next = gear >= 0
262
+ ? { ...gears, level: gear }
263
+ : { ...gears, rates: gears.rates.map((value, index) => (index === gears.level ? rate : value)) };
264
+ const updated = { ...system, gears: set === 0 ? [next, system.gears[1]] : [system.gears[0], next] };
265
+ const confirmed = (await this.writeSystem(updated)).gears[set];
266
+ const actual = POLLING_RATES[confirmed.rates[confirmed.level] ?? -1];
267
+ if (actual !== rateHz)
268
+ throw new Error(`The ${this.label} kept ${actual ?? "an unknown rate"} Hz instead of ${rateHz} Hz.`);
269
+ return actual;
270
+ }
271
+ async setLiftOffDistance(lod) {
272
+ const code = LOD_BY_LEVEL[lod];
273
+ if (code === undefined)
274
+ throw new Error(`The ${this.label} has no ${lod} lift-off distance.`);
275
+ const confirmed = (await this.writeSensor({ ...(await this.readSensor()), lod: code })).lod;
276
+ if (confirmed !== code)
277
+ throw new Error(`The ${this.label} kept lift-off code ${confirmed}.`);
278
+ return lod;
279
+ }
280
+ async setMotionSync(enabled) {
281
+ return this.writeFlag("motionSync", enabled);
282
+ }
283
+ async setAngleSnapping(enabled) {
284
+ return this.writeFlag("angleSnapping", enabled);
285
+ }
286
+ async setRippleControl(enabled) {
287
+ return this.writeFlag("rippleControl", enabled);
288
+ }
289
+ async setPerformanceMode(enabled) {
290
+ return this.writeFlag("maxSpeed", enabled);
291
+ }
292
+ async setAngleTuning(degrees) {
293
+ if (!Number.isInteger(degrees) || Math.abs(degrees) > ANGLE_LIMIT) {
294
+ throw new Error(`The ${this.label} angle must be a whole number between -${ANGLE_LIMIT} and ${ANGLE_LIMIT} degrees.`);
295
+ }
296
+ const confirmed = (await this.writeSensor({ ...(await this.readSensor()), angle: degrees })).angle;
297
+ if (confirmed !== degrees)
298
+ throw new Error(`The ${this.label} kept a ${confirmed}° sensor angle instead of ${degrees}°.`);
299
+ return confirmed;
300
+ }
301
+ async setDebounceTime(debounceMs) {
302
+ if (!Number.isInteger(debounceMs) || debounceMs < 0 || debounceMs > DEBOUNCE_MAX_MS) {
303
+ throw new Error(`The ${this.label} debounce must be between 0 and ${DEBOUNCE_MAX_MS} ms.`);
304
+ }
305
+ const confirmed = (await this.writeSystem({ ...(await this.readSystem()), debounceMs })).debounceMs;
306
+ if (confirmed !== debounceMs)
307
+ throw new Error(`The ${this.label} kept ${confirmed} ms debounce instead of ${debounceMs} ms.`);
308
+ return confirmed;
309
+ }
310
+ /** Launcher writes the same timeout to the 2.4 GHz and Bluetooth fields. */
311
+ async setSleepTimeout(seconds) {
312
+ const minutes = seconds / 60;
313
+ if (!Number.isInteger(minutes) || minutes < 1 || minutes > SLEEP_MAX_MINUTES) {
314
+ throw new Error(`The ${this.label} sleeps after 1 to ${SLEEP_MAX_MINUTES} whole minutes.`);
315
+ }
316
+ const system = await this.readSystem();
317
+ const confirmed = (await this.writeSystem({ ...system, sleepSeconds: seconds, bleSleepSeconds: seconds })).sleepSeconds;
318
+ if (confirmed !== seconds)
319
+ throw new Error(`The ${this.label} kept a ${confirmed} s sleep timeout instead of ${seconds} s.`);
320
+ return confirmed;
321
+ }
322
+ /** Switch the onboard profile (1-based, as the panel numbers them). */
323
+ async setProfile(profile) {
324
+ if (!Number.isInteger(profile) || profile < 1 || profile > PROFILE_COUNT) {
325
+ throw new Error(`The ${this.label} profile must be between 1 and ${PROFILE_COUNT}.`);
326
+ }
327
+ await this.readIdentity();
328
+ const packet = commandPacket(CMD.profile);
329
+ packet[4] = profile - 1;
330
+ await this.request(packet, replyTo(CMD.profile));
331
+ // The ack can arrive before the switch lands, so wait for the status report to show it.
332
+ let current = -1;
333
+ for (let attempt = 0; attempt < 3; attempt += 1) {
334
+ current = (await this.readPower()).profile;
335
+ if (current === profile - 1)
336
+ return profile;
337
+ await new Promise((resolve) => setTimeout(resolve, 150));
338
+ }
339
+ throw new Error(`The ${this.label} stayed on profile ${current + 1}.`);
340
+ }
341
+ async setButtonMapping(button, action) {
342
+ const slot = BUTTONS.find((entry) => entry.name === button);
343
+ if (!slot)
344
+ throw new Error(`The ${this.label} has no "${button}" button.`);
345
+ const code = BUTTON_ACTIONS.find(([label]) => label === action)?.[1];
346
+ if (!code)
347
+ throw new Error(`Unknown button action "${action}".`);
348
+ const codes = await this.readButtons();
349
+ if (keychronNordicButtonLabel(codes[slot.index]) === action)
350
+ return;
351
+ codes[slot.index] = [...code];
352
+ if (!BUTTONS.some(({ index }) => keychronNordicButtonLabel(codes[index]) === "Left Click")) {
353
+ throw new Error("Keep at least one button as Left Click.");
354
+ }
355
+ const packet = commandPacket(CMD.writeButton);
356
+ packet[4] = slot.index;
357
+ packet.set(code, 5);
358
+ await this.request(packet, replyTo(CMD.writeButton));
359
+ await this.save();
360
+ const confirmed = keychronNordicButtonLabel((await this.readButtons())[slot.index]);
361
+ if (confirmed !== action)
362
+ throw new Error(`The ${this.label} kept ${confirmed} on ${button} instead of ${action}.`);
363
+ }
364
+ get label() {
365
+ return this.name ?? "Keychron mouse";
366
+ }
367
+ /** Which gear set this connection uses: 2.4 GHz has its own from firmware 1.6.0. */
368
+ gearSet(identity) {
369
+ return this.receiver && identity.separateRates ? 1 : 0;
370
+ }
371
+ unreachableStatus(name) {
372
+ return {
373
+ brand: "Keychron",
374
+ name,
375
+ ui: {
376
+ family: "keychron-8k-nordic",
377
+ defaultDisplayName: name,
378
+ settingsReady: false,
379
+ statusNote: this.receiver
380
+ ? "The mouse did not answer through the receiver. Wake it and reconnect."
381
+ : "The mouse did not answer its settings reads. Reconnect it and try again.",
382
+ },
383
+ batteryPercent: null,
384
+ batteryState: "Unknown",
385
+ dpi: 0,
386
+ pollingRateHz: 0,
387
+ activeProfile: null,
388
+ connectionType: this.receiver ? "Wireless" : "Wired",
389
+ liftOffDistance: null,
390
+ firmware: this.identity ? [this.identity.firmware] : [],
391
+ };
392
+ }
393
+ async writeFlag(flag, enabled) {
394
+ const confirmed = (await this.writeSensor({ ...(await this.readSensor()), [flag]: enabled }))[flag];
395
+ if (confirmed !== enabled)
396
+ throw new Error(`The ${this.label} kept ${flag} ${confirmed ? "on" : "off"}.`);
397
+ return confirmed;
398
+ }
399
+ async writeSensor(next) {
400
+ await this.request(keychronNordicEncodeSensor(next), replyTo(CMD.writeSensor));
401
+ await this.save();
402
+ return await this.readSensor();
403
+ }
404
+ async writeSystem(next) {
405
+ const identity = await this.readIdentity();
406
+ await this.request(keychronNordicEncodeSystem(next, identity.separateRates), replyTo(CMD.writeSystem));
407
+ await this.save();
408
+ return await this.readSystem();
409
+ }
410
+ async save() {
411
+ await this.request(commandPacket(CMD.save), (bytes) => ((bytes[0] ?? 0) & 0xbf) === CMD.save[0]);
412
+ }
413
+ requireDpi(dpi) {
414
+ if (!Number.isInteger(dpi) || dpi < DPI_MIN || dpi > DPI_MAX || dpi % DPI_STEP !== 0) {
415
+ throw new Error(`The ${this.label} DPI must be a multiple of ${DPI_STEP} between ${DPI_MIN} and ${DPI_MAX}.`);
416
+ }
417
+ }
418
+ requireStage(stage, stageCount) {
419
+ if (!Number.isInteger(stage) || stage < 0 || stage >= stageCount) {
420
+ throw new Error(`DPI stage must be between 1 and ${stageCount}.`);
421
+ }
422
+ }
423
+ /**
424
+ * Read once per connection. A receiver answers this handshake itself, so
425
+ * it goes out unrouted; bytes 6-7 must carry Keychron's or Lemokey's vendor
426
+ * ID (Launcher's test for this protocol) and bytes 8-9 name the paired mouse.
427
+ * Every read and write passes through here first, so a receiver on another
428
+ * protocol is refused before anything is written.
429
+ */
430
+ async readName() {
431
+ await this.open();
432
+ if (this.name)
433
+ return this.name;
434
+ let productId = this.device.productId;
435
+ if (this.receiver) {
436
+ // Strict match: a routed status report from the mouse (0x41) must not stand in for the receiver's answer.
437
+ const handshake = await this.request(commandPacket(CMD.status), (bytes) => bytes[0] === CMD.status[0] && bytes[3] === CMD.status[2], false);
438
+ const vendorId = readU16(handshake, 6);
439
+ if (vendorId !== KEYCHRON_VENDOR_ID && vendorId !== LEMOKEY_VENDOR_ID) {
440
+ throw new Error("This Keychron receiver did not report a paired 8K Nordic mouse.");
441
+ }
442
+ productId = readU16(handshake, 8);
443
+ }
444
+ this.name = MICE.find((mouse) => mouse.productId === productId)?.name ?? "Keychron 8K mouse";
445
+ return this.name;
446
+ }
447
+ /** The mouse's firmware (routed), which decides the system block layout. */
448
+ async readIdentity() {
449
+ await this.readName();
450
+ if (this.identity)
451
+ return this.identity;
452
+ const reply = await this.request(commandPacket(CMD.version), replyTo(CMD.version));
453
+ const version = [reply[9] ?? 0, (reply[8] ?? 0) >> 4, (reply[8] ?? 0) & 0x0f];
454
+ const newer = version.findIndex((part, index) => part !== SEPARATE_RATES_FIRMWARE[index]);
455
+ this.identity = {
456
+ firmware: `v${version.join(".")}`,
457
+ separateRates: newer < 0 || version[newer] > SEPARATE_RATES_FIRMWARE[newer],
458
+ };
459
+ return this.identity;
460
+ }
461
+ async readSensor() {
462
+ await this.readName();
463
+ return keychronNordicDecodeSensor(await this.request(commandPacket(CMD.readSensor), replyTo(CMD.readSensor)));
464
+ }
465
+ async readSystem() {
466
+ await this.readName();
467
+ return keychronNordicDecodeSystem(await this.request(commandPacket(CMD.readSystem), replyTo(CMD.readSystem)));
468
+ }
469
+ async readPower() {
470
+ await this.readName();
471
+ const bytes = await this.request(commandPacket(CMD.status), replyTo(CMD.status));
472
+ const state = bytes[10] ?? 0;
473
+ return {
474
+ state: state === 3 ? 0 : state,
475
+ percent: bytes[11] ?? 0,
476
+ profile: Math.min(bytes[12] ?? 0, PROFILE_COUNT - 1),
477
+ };
478
+ }
479
+ /** Four-byte codes for every table index up to the last button. */
480
+ async readButtons() {
481
+ await this.readName();
482
+ const bytes = await this.request(commandPacket(CMD.readButtons), replyTo(CMD.readButtons));
483
+ const last = Math.max(...BUTTONS.map(({ index }) => index));
484
+ return Array.from({ length: last + 1 }, (_, index) => Array.from(bytes.slice(4 + index * 4, 8 + index * 4)));
485
+ }
486
+ /** Routes through the receiver unless told not to, fills in the checksum, and resends like Launcher's queue. */
487
+ async request(packet, match, route = true) {
488
+ const routed = this.receiver && route;
489
+ const finished = new Uint8Array(orbitalFinishPacket(packet, routed));
490
+ for (let resends = routed ? RECEIVER_RESENDS : 0;; resends -= 1) {
491
+ const reply = await this.exchange(finished, match);
492
+ if (reply)
493
+ return reply;
494
+ if (resends === 0) {
495
+ throw new Error(routed
496
+ ? `The ${this.label} did not answer through the receiver. Wake the mouse and try again.`
497
+ : `The ${this.label} did not answer command 0x${packet[0]?.toString(16)}.`);
498
+ }
499
+ }
500
+ }
501
+ /** One send; resolves null when no matching reply arrives in time. */
502
+ async exchange(packet, match) {
503
+ if (this.waiter)
504
+ throw new Error(`Another ${this.label} request is already in progress.`);
505
+ return await new Promise((resolve, reject) => {
506
+ const timeout = setTimeout(() => {
507
+ this.waiter = null;
508
+ resolve(null);
509
+ }, QUERY_TIMEOUT_MS);
510
+ this.waiter = {
511
+ match,
512
+ resolve: (bytes) => {
513
+ clearTimeout(timeout);
514
+ resolve(bytes);
515
+ },
516
+ reject: (reason) => {
517
+ clearTimeout(timeout);
518
+ reject(reason);
519
+ },
520
+ };
521
+ this.device.sendReport(0, packet).catch((error) => {
522
+ this.waiter?.reject(new Error(`Chrome could not write the ${this.label} HID report. ${error instanceof Error ? error.message : String(error)}`));
523
+ this.waiter = null;
524
+ });
525
+ });
526
+ }
527
+ }
528
+ export function keychronNordicDecodeSensor(bytes) {
529
+ const stageCount = Math.min(countBits(bytes[14] ?? 0) || DPI_STAGE_COUNT, DPI_STAGE_COUNT);
530
+ const angle = bytes[12] ?? 0;
531
+ return {
532
+ angleSnapping: Boolean(bytes[4]),
533
+ rippleControl: Boolean(bytes[5]),
534
+ motionSync: Boolean(bytes[6]),
535
+ maxSpeed: Boolean(bytes[8]),
536
+ reserved: [bytes[7] ?? 0, bytes[9] ?? 0, bytes[10] ?? 0],
537
+ lod: bytes[11] ?? 0,
538
+ // Launcher reads anything above its +90 limit as negative.
539
+ angle: angle > ANGLE_LIMIT ? angle - 256 : angle,
540
+ activeStage: Math.min(bytes[13] ?? 0, stageCount - 1),
541
+ stageCount,
542
+ stages: Array.from({ length: DPI_STAGE_COUNT }, (_, stage) => [
543
+ readU16(bytes, 15 + stage * 4),
544
+ readU16(bytes, 17 + stage * 4),
545
+ ]),
546
+ colors: Array.from(bytes.slice(43, 58)),
547
+ };
548
+ }
549
+ /** The sensor block exactly as Launcher builds it: every field it knows, zeros elsewhere. */
550
+ export function keychronNordicEncodeSensor(sensor) {
551
+ const packet = commandPacket(CMD.writeSensor);
552
+ packet[4] = Number(sensor.angleSnapping);
553
+ packet[5] = Number(sensor.rippleControl);
554
+ packet[6] = Number(sensor.motionSync);
555
+ packet[7] = sensor.reserved[0];
556
+ packet[8] = Number(sensor.maxSpeed);
557
+ packet[9] = sensor.reserved[1];
558
+ packet[10] = sensor.reserved[2];
559
+ packet[11] = sensor.lod;
560
+ packet[12] = sensor.angle & 0xff;
561
+ packet[13] = sensor.activeStage;
562
+ packet[14] = (1 << sensor.stageCount) - 1;
563
+ sensor.stages.forEach(([x, y], stage) => {
564
+ writeU16(packet, 15 + stage * 4, x);
565
+ writeU16(packet, 17 + stage * 4, y);
566
+ });
567
+ packet.set(sensor.colors.slice(0, 15), 43);
568
+ return packet;
569
+ }
570
+ export function keychronNordicDecodeSystem(bytes) {
571
+ const gears = (levelAt, maskAt, tableAt) => {
572
+ const count = Math.min(countBits(bytes[maskAt] ?? 0) || POLLING_GEARS, POLLING_GEARS);
573
+ return {
574
+ level: Math.min(bytes[levelAt] ?? 0, count - 1),
575
+ count,
576
+ // Stored as rate index + 1; 0 (and the unused 1) mean 125 Hz.
577
+ rates: Array.from(bytes.slice(tableAt, tableAt + POLLING_GEARS), (raw) => (raw > 0 ? raw - 1 : 0)),
578
+ };
579
+ };
580
+ return {
581
+ sleepSeconds: readU16(bytes, 4),
582
+ bleSleepSeconds: readU16(bytes, 6),
583
+ debounceMs: bytes[9] ?? 0,
584
+ reserved: Array.from(bytes.slice(10, 20)),
585
+ gears: [gears(8, 20, 21), gears(28, 29, 30)],
586
+ };
587
+ }
588
+ /** Launcher sends the 2.4 GHz gear set only to firmware that has one. */
589
+ export function keychronNordicEncodeSystem(system, separateRates) {
590
+ const packet = commandPacket(CMD.writeSystem);
591
+ if (separateRates)
592
+ packet[2] = 0x80 | 32;
593
+ writeU16(packet, 4, system.sleepSeconds);
594
+ writeU16(packet, 6, system.bleSleepSeconds);
595
+ packet[9] = system.debounceMs;
596
+ packet.set(system.reserved.slice(0, 10), 10);
597
+ const writeGears = (gears, levelAt, maskAt, tableAt) => {
598
+ packet[levelAt] = gears.level;
599
+ packet[maskAt] = (1 << gears.count) - 1;
600
+ gears.rates.forEach((rate, gear) => {
601
+ packet[tableAt + gear] = rate > 0 ? rate + 1 : 0;
602
+ });
603
+ };
604
+ writeGears(system.gears[0], 8, 20, 21);
605
+ if (separateRates)
606
+ writeGears(system.gears[1], 28, 29, 30);
607
+ return packet;
608
+ }
609
+ /** "Macro" and "Custom" cover codes the remapper cannot offer (macros, keys, media). */
610
+ export function keychronNordicButtonLabel(code) {
611
+ if (code[0] === MACRO_CODE)
612
+ return "Macro";
613
+ return BUTTON_ACTIONS.find(([, bytes]) => bytes.every((byte, index) => byte === code[index]))?.[0] ?? "Custom";
614
+ }
615
+ function commandPacket(command) {
616
+ const packet = new Uint8Array(PACKET_LENGTH);
617
+ packet[0] = command[0];
618
+ packet[2] = command[1];
619
+ packet[3] = command[2];
620
+ return packet;
621
+ }
622
+ /** Replies echo bytes 0 and 3; the receiver adds 0x40 to byte 0. */
623
+ function replyTo(command) {
624
+ return (bytes) => ((bytes[0] ?? 0) & 0xbf) === command[0] && bytes[3] === command[2];
625
+ }
626
+ function countBits(value) {
627
+ let count = 0;
628
+ for (let rest = value; rest; rest >>= 1)
629
+ count += rest & 1;
630
+ return count;
631
+ }
632
+ function readU16(bytes, offset) {
633
+ return (bytes[offset] ?? 0) | ((bytes[offset + 1] ?? 0) << 8);
634
+ }
635
+ function writeU16(bytes, offset, value) {
636
+ bytes[offset] = value & 0xff;
637
+ bytes[offset + 1] = (value >> 8) & 0xff;
638
+ }
639
+ //# sourceMappingURL=mouse-8k-nordic-hid.js.map