@openmouse/protocol 0.21.0 → 0.22.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.
@@ -0,0 +1,754 @@
1
+ import { KEYCHRON_8K_NORDIC_PRODUCT_IDS, KEYCHRON_M6_COMMAND_REPORT_ID as COMMAND_REPORT_ID, KEYCHRON_M6_SETTINGS_REPORT_ID as SETTINGS_REPORT_ID, KEYCHRON_M6_STATUS_COMMAND as STATUS_COMMAND, KEYCHRON_M6_STATUS_PACKET_LENGTH as PACKET_LENGTH, KEYCHRON_M6_USAGE as USAGE, KEYCHRON_M6_USAGE_PAGE as USAGE_PAGE, KEYCHRON_RECEIVERS, KEYCHRON_VENDOR_ID, } from "@openmouse/protocol/keychron";
2
+ import { KEYCHRON_DEBOUNCE_MAX_MS as DEBOUNCE_MAX_MS, KEYCHRON_DEFAULT_DPI as DEFAULT_DPI, KEYCHRON_DPI_STAGE_COUNT as DPI_STAGE_COUNT, KEYCHRON_DPI_STEP as DEFAULT_DPI_STEP, KEYCHRON_POLLING_RATES as POLLING_RATES, KEYCHRON_SET, KEYCHRON_SLEEP_MINUTES as SLEEP_MINUTES, KEYCHRON_STANDARD_LOD as STANDARD_LOD, keychronActiveGear, keychronActiveStage, keychronButtonOptions, keychronButtons, keychronDecodeButton, keychronDecodeConnectedMouse, keychronDecodeSettings, keychronEncodeAngle, keychronEncodeButton, keychronEncodeDebounce, keychronEncodeDpi, keychronEncodeLighting, keychronEncodeSensor, keychronLauncherFirmware, keychronLauncherMouse, keychronLighting, keychronLiftOff, keychronLiftOffStops, readU16, writeU16, } from "./launcher-mouse.js";
3
+ const QUERY_TIMEOUT_MS = 1200;
4
+ const SETTINGS_PACKET_LENGTH = 20;
5
+ const ACK = 0xe4;
6
+ /** Launcher's angle slider; the byte is signed and Launcher reads anything past +90 as negative. */
7
+ const ANGLE_LIMIT = 90;
8
+ const PROFILE_MAX = 5;
9
+ const POLLING_GEARS = 6;
10
+ /** From this protocol version the feature flags sit in the 0x02 answer instead of the status report. */
11
+ const FLAGS_IN_VERSION_REPLY = 6;
12
+ /** Commands on the 63-byte 0xb3 report (answers arrive on 0xb4). */
13
+ const CMD = {
14
+ firmware: KEYCHRON_SET.firmware,
15
+ status: STATUS_COMMAND,
16
+ writeXy: 0x48,
17
+ readXy: 0x49,
18
+ writeButton: KEYCHRON_SET.writeButton,
19
+ readButton: KEYCHRON_SET.readButton,
20
+ };
21
+ /** Commands on the 20-byte 0xb5 report (answers arrive on 0xb6). */
22
+ const SET = {
23
+ version: 0x02,
24
+ receiverState: KEYCHRON_SET.receiverState,
25
+ sleep: 0x0a,
26
+ profile: 0x0e,
27
+ lightingAnswer: 0x21,
28
+ readLighting: 0x23,
29
+ writeLighting: 0x24,
30
+ polling: KEYCHRON_SET.polling,
31
+ writePollingSets: 0x4a,
32
+ readPollingSets: 0x4b,
33
+ };
34
+ /**
35
+ * Keychron Launcher's "8k" mouse protocol on the 0xffc1 collection (63-byte
36
+ * 0xb3/0xb4 reads, 20-byte 0xb5/0xb6 writes), which the M6 and most other
37
+ * Keychron mice speak. Not the VIA raw-HID protocol the Nape Pro speaks.
38
+ * Decoded from Launcher (main.be11320b2a72b61b.js, webpack module 20706);
39
+ * the M6 (firmware 1.0.3, USB and Link-KM) confirmed every field it reads and
40
+ * every write except angle tuning, buttons, lighting and the flagged paths.
41
+ *
42
+ * Status report (0x06) layout:
43
+ * [1] active onboard profile, zero-based; [50] profile count
44
+ * [2..4] per connection (USB, 2.4 GHz, Bluetooth): DPI stage in the low
45
+ * nibble, polling gear in the high nibble
46
+ * [5..14] five DPI slots, little-endian 16-bit
47
+ * [15] bits 0-1 lift-off code, bit 2 ripple control, bit 3 angle
48
+ * snapping, bit 4 motion sync, bit 6 reversed scroll
49
+ * [16] DPI stages in use (1-5); unused tail slots keep stale values
50
+ * [17] debounce in ms; [18] sleep timeout in minutes
51
+ * [19] battery percent, bit 7 = charging
52
+ * [26] [53] [60] feature flags before protocol 6 (from 6, 0x02 bytes 11-13 and 15)
53
+ * [40..41] DPI ceiling; [42] DPI step (when flagged)
54
+ * [43..48] polling gears as indexes into POLLING_RATES; [49] gears in use
55
+ * [52] bit 0 20K FPS; [55] sensor angle, signed
56
+ * [61] lift-off level in the low nibble, level count in the high nibble
57
+ * Settings writes are acknowledged with [0xe4, code, command]; code 0 is
58
+ * success and 7 means the command is not supported on this connection.
59
+ * The 0x40 write packet is the DPI part of this layout shifted one byte down
60
+ * (stage at [1..3], slots at [4..13], stage count at [14]).
61
+ */
62
+ export class Keychron8kHidClient {
63
+ device;
64
+ openedListener = false;
65
+ identity = null;
66
+ model;
67
+ /** Floor, ceiling and step from the last status report, for getDpiOptions(). */
68
+ dpiLimits = null;
69
+ responseWaiter = null;
70
+ onInputReport = (event) => {
71
+ if (!this.responseWaiter)
72
+ return;
73
+ const bytes = new Uint8Array(event.data.buffer.slice(event.data.byteOffset, event.data.byteOffset + event.data.byteLength));
74
+ if (!this.responseWaiter.match(bytes))
75
+ return;
76
+ const waiter = this.responseWaiter;
77
+ this.responseWaiter = null;
78
+ waiter.resolve(bytes);
79
+ };
80
+ constructor(device) {
81
+ this.device = device;
82
+ }
83
+ /** Launcher treats any Keychron device with this collection as an "8k" mouse, so this does too. */
84
+ static isSupported(device) {
85
+ // The G3 Air and its Ultra-Link receivers speak the 8K Nordic protocol
86
+ // instead, and their own driver claims them by product ID. A G3 Air can
87
+ // still expose a 0xffc1 collection, so exclude those IDs here or the
88
+ // collection match would shadow the Nordic driver.
89
+ if (KEYCHRON_8K_NORDIC_PRODUCT_IDS.includes(device.productId))
90
+ return false;
91
+ return device.vendorId === KEYCHRON_VENDOR_ID
92
+ && device.collections.some((collection) => collection.usagePage === USAGE_PAGE
93
+ && collection.usage === USAGE
94
+ && collection.outputReports.some((report) => report.reportId === COMMAND_REPORT_ID)
95
+ && collection.inputReports.some((report) => report.reportId === COMMAND_REPORT_ID + 1));
96
+ }
97
+ async open() {
98
+ if (!this.device.opened)
99
+ await this.device.open();
100
+ if (!this.openedListener) {
101
+ this.device.addEventListener("inputreport", this.onInputReport);
102
+ this.openedListener = true;
103
+ }
104
+ }
105
+ async close() {
106
+ if (this.openedListener) {
107
+ this.device.removeEventListener("inputreport", this.onInputReport);
108
+ this.openedListener = false;
109
+ }
110
+ this.responseWaiter?.reject(new Error(`The ${this.label} was closed.`));
111
+ this.responseWaiter = null;
112
+ if (this.device.opened)
113
+ await this.device.close();
114
+ }
115
+ getDpiOptions() {
116
+ const { min, max, step } = this.dpiLimits ?? this.modelDpiLimits(null);
117
+ return Array.from({ length: Math.floor((max - min) / step) + 1 }, (_, index) => min + index * step);
118
+ }
119
+ getSleepOptions() {
120
+ return SLEEP_MINUTES.map((minutes) => minutes * 60);
121
+ }
122
+ getDebounceOptions() {
123
+ return Array.from({ length: DEBOUNCE_MAX_MS + 1 }, (_, ms) => ms);
124
+ }
125
+ canDisableSleep = false;
126
+ /** Falls back to the name alone when the mouse does not answer, e.g. asleep behind its receiver. */
127
+ async readStatus() {
128
+ await this.open();
129
+ const identity = await this.readIdentity();
130
+ const model = await this.readModel(identity);
131
+ let status;
132
+ let dpi;
133
+ let polling;
134
+ try {
135
+ status = await this.readSettings();
136
+ dpi = await this.readDpi(status, identity);
137
+ polling = await this.readPolling(status, identity);
138
+ }
139
+ catch {
140
+ return this.unreachableStatus(identity);
141
+ }
142
+ const buttons = await this.readButtons().catch(() => null);
143
+ const light = model?.light ? await this.readLight().catch(() => null) : null;
144
+ const pollingRateHz = POLLING_RATES[polling.table[polling.level] ?? 2] ?? 1000;
145
+ const liftOff = this.liftOffChoices(status);
146
+ const lod = keychronLiftOff(liftOff.choices, liftOff.kind === "level" ? status.lodLevel : status.lod);
147
+ const { min, max, step } = this.modelDpiLimits(status);
148
+ const sensorOptions = !model?.noSensorOptions;
149
+ const name = this.label;
150
+ return {
151
+ brand: "Keychron",
152
+ name,
153
+ ui: {
154
+ family: "keychron-8k",
155
+ defaultDisplayName: name,
156
+ hideUnsupportedPollingRates: true,
157
+ forceShowBattery: true,
158
+ ...(lod.note ? { statusNote: lod.note } : {}),
159
+ ...(sensorOptions ? {} : { hideProcessingCard: true }),
160
+ dpiStageEditor: {
161
+ maxStages: DPI_STAGE_COUNT,
162
+ countEditable: true,
163
+ minDpi: min,
164
+ maxDpi: max,
165
+ stepDpi: step,
166
+ },
167
+ },
168
+ batteryPercent: status.batteryPercent <= 100 ? status.batteryPercent : null,
169
+ batteryState: status.charging ? "Charging" : "Discharging",
170
+ dpi: dpi.stages[dpi.activeStage] ?? dpi.stages[0] ?? 800,
171
+ dpiStages: dpi.stages.slice(0, dpi.stageCount),
172
+ activeDpiStage: dpi.activeStage,
173
+ pollingRateHz,
174
+ supportedPollingRates: this.supportedRates(status, polling),
175
+ activeProfile: status.profileCount > 1 ? status.profile + 1 : null,
176
+ profileCount: status.profileCount > 1 ? status.profileCount : undefined,
177
+ connectionType: identity.workMode === 0 ? "Wired" : "Wireless",
178
+ connectionDetail: this.connectionDetail(identity),
179
+ liftOffDistance: lod.liftOffDistance,
180
+ ...(lod.supportedLiftOffDistances ? { supportedLiftOffDistances: lod.supportedLiftOffDistances } : {}),
181
+ ...(lod.liftOffScale ? { liftOffScale: lod.liftOffScale } : {}),
182
+ ...(sensorOptions ? {
183
+ motionSync: status.motionSync,
184
+ angleSnapping: status.angleSnapping,
185
+ rippleControl: status.rippleControl,
186
+ } : {}),
187
+ ...(status.features.fps20k ? { performanceMode: status.maxSpeed } : {}),
188
+ angleTuning: status.features.angle ? status.angle : undefined,
189
+ debounceMs: status.debounceMs,
190
+ sleepTimeout: status.sleepMinutes > 0 && status.sleepMinutes < 0xff ? status.sleepMinutes * 60 : null,
191
+ ...(buttons ? {
192
+ buttonMappings: Object.fromEntries(buttons.map(({ button, action }) => [button.name, action])),
193
+ buttonOptions: keychronButtonOptions("8k"),
194
+ } : {}),
195
+ ...(light && model?.light ? { lighting: keychronLighting(light, model.light) } : {}),
196
+ firmware: [identity.firmware ?? "Firmware unavailable"],
197
+ };
198
+ }
199
+ async setDpi(dpi) {
200
+ const current = await this.readDpi(await this.readSettings(), await this.readIdentity());
201
+ return await this.setDpiStageValue(current.activeStage, dpi);
202
+ }
203
+ async setDpiStageValue(stage, dpi) {
204
+ const status = await this.readSettings();
205
+ this.requireDpi(dpi, status);
206
+ const identity = await this.readIdentity();
207
+ const current = await this.readDpi(status, identity);
208
+ this.requireStage(stage, current.stageCount);
209
+ const stages = current.stages.map((value, index) => (index === stage ? dpi : value));
210
+ const confirmed = (await this.writeDpi(current, { ...current, stages }, identity)).stages[stage];
211
+ if (confirmed !== dpi) {
212
+ throw new Error(`The ${this.label} kept ${confirmed} DPI on stage ${stage + 1} instead of ${dpi} DPI.`);
213
+ }
214
+ return confirmed;
215
+ }
216
+ async setActiveDpiStage(stage) {
217
+ const identity = await this.readIdentity();
218
+ const current = await this.readDpi(await this.readSettings(), identity);
219
+ this.requireStage(stage, current.stageCount);
220
+ const confirmed = (await this.writeDpi(current, { ...current, activeStage: stage }, identity)).activeStage;
221
+ if (confirmed !== stage)
222
+ throw new Error(`The ${this.label} kept DPI stage ${confirmed + 1}.`);
223
+ return confirmed;
224
+ }
225
+ async setDpiStageCount(count) {
226
+ if (!Number.isInteger(count) || count < 1 || count > DPI_STAGE_COUNT) {
227
+ throw new Error(`The ${this.label} holds between 1 and ${DPI_STAGE_COUNT} DPI stages.`);
228
+ }
229
+ const identity = await this.readIdentity();
230
+ const current = await this.readDpi(await this.readSettings(), identity);
231
+ // All five hardware slots keep their DPI; the count only decides how many
232
+ // the DPI button cycles through. The active stage rides along on the same
233
+ // packet, so shrinking past it would write a stage the mouse cannot hold.
234
+ const activeStage = Math.min(current.activeStage, count - 1);
235
+ const confirmed = (await this.writeDpi(current, { ...current, stageCount: count, activeStage }, identity)).stageCount;
236
+ if (confirmed !== count) {
237
+ throw new Error(`The ${this.label} kept ${confirmed} DPI stages instead of ${count}.`);
238
+ }
239
+ return confirmed;
240
+ }
241
+ /**
242
+ * Picks the gear that already holds the rate. Firmware that flags editable
243
+ * gears gets the rate written into the active gear instead, when the model
244
+ * offers it.
245
+ */
246
+ async setPollingRate(rateHz) {
247
+ const identity = await this.readIdentity();
248
+ const status = await this.readSettings();
249
+ const polling = await this.readPolling(status, identity);
250
+ const rate = POLLING_RATES.indexOf(rateHz);
251
+ const gear = polling.table.slice(0, polling.count).indexOf(rate);
252
+ let next;
253
+ if (rate >= 0 && gear >= 0)
254
+ next = { ...polling, level: gear };
255
+ else if (rate >= 0 && status.features.pollingGears && this.supportedRates(status, polling).includes(rateHz)) {
256
+ next = { ...polling, table: polling.table.map((value, index) => (index === polling.level ? rate : value)) };
257
+ }
258
+ else {
259
+ throw new Error(`The ${this.label} does not support ${rateHz} Hz on this connection.`);
260
+ }
261
+ await this.writeSettings(this.pollingPacket(polling, next));
262
+ const confirmed = await this.readPolling(await this.readSettings(), identity);
263
+ const actual = POLLING_RATES[confirmed.table[confirmed.level] ?? 2] ?? 1000;
264
+ if (actual !== rateHz)
265
+ throw new Error(`The ${this.label} kept ${actual} Hz instead of ${rateHz} Hz.`);
266
+ return actual;
267
+ }
268
+ async setLiftOffDistance(lod) {
269
+ const status = await this.readSettings();
270
+ const liftOff = this.liftOffChoices(status);
271
+ const code = liftOff.choices.length <= 3
272
+ ? keychronLiftOffStops(liftOff.choices).find(([name]) => name === lod)?.[1]
273
+ : undefined;
274
+ if (code === undefined)
275
+ throw new Error(`The ${this.label} has no ${lod} lift-off distance.`);
276
+ await this.writeLiftOff(status, liftOff.kind, code);
277
+ return lod;
278
+ }
279
+ /** Lift-off on models with more than three heights; the code is the level Launcher's config lists. */
280
+ async setLiftOffScale(code) {
281
+ const status = await this.readSettings();
282
+ const liftOff = this.liftOffChoices(status);
283
+ if (!liftOff.choices.some(([value]) => value === code))
284
+ throw new Error(`The ${this.label} has no lift-off level ${code}.`);
285
+ await this.writeLiftOff(status, liftOff.kind, code);
286
+ return code;
287
+ }
288
+ async setMotionSync(enabled) {
289
+ return this.writeSensorFlag("motionSync", enabled);
290
+ }
291
+ async setAngleSnapping(enabled) {
292
+ return this.writeSensorFlag("angleSnapping", enabled);
293
+ }
294
+ async setRippleControl(enabled) {
295
+ return this.writeSensorFlag("rippleControl", enabled);
296
+ }
297
+ /** Launcher's "20K FPS" switch, on firmware that flags it. */
298
+ async setPerformanceMode(enabled) {
299
+ if (!(await this.readSettings()).features.fps20k)
300
+ throw new Error(`The ${this.label} has no 20K FPS mode.`);
301
+ return this.writeSensorFlag("maxSpeed", enabled);
302
+ }
303
+ async setAngleTuning(degrees) {
304
+ if (!Number.isInteger(degrees) || Math.abs(degrees) > ANGLE_LIMIT) {
305
+ throw new Error(`The ${this.label} angle must be a whole number between -${ANGLE_LIMIT} and ${ANGLE_LIMIT} degrees.`);
306
+ }
307
+ if (!(await this.readSettings()).features.angle) {
308
+ throw new Error(`This ${this.label} firmware does not support angle tuning.`);
309
+ }
310
+ await this.writeSettings(keychronEncodeAngle(degrees));
311
+ const confirmed = (await this.readSettings()).angle;
312
+ if (confirmed !== degrees)
313
+ throw new Error(`The ${this.label} kept a ${confirmed}° sensor angle instead of ${degrees}°.`);
314
+ return confirmed;
315
+ }
316
+ async setDebounceTime(debounceMs) {
317
+ if (!Number.isInteger(debounceMs) || debounceMs < 0 || debounceMs > DEBOUNCE_MAX_MS) {
318
+ throw new Error(`The ${this.label} debounce must be between 0 and ${DEBOUNCE_MAX_MS} ms.`);
319
+ }
320
+ await this.open();
321
+ await this.writeSettings(keychronEncodeDebounce(debounceMs));
322
+ const confirmed = (await this.readSettings()).debounceMs;
323
+ if (confirmed !== debounceMs)
324
+ throw new Error(`The ${this.label} kept ${confirmed} ms debounce instead of ${debounceMs} ms.`);
325
+ return confirmed;
326
+ }
327
+ async setSleepTimeout(seconds) {
328
+ const minutes = Math.round(seconds / 60);
329
+ if (!SLEEP_MINUTES.includes(minutes)) {
330
+ throw new Error(`The ${this.label} sleep timeout must be one of ${SLEEP_MINUTES.join(", ")} minutes.`);
331
+ }
332
+ await this.open();
333
+ const packet = new Uint8Array(SETTINGS_PACKET_LENGTH);
334
+ packet[0] = SET.sleep;
335
+ packet[1] = 1;
336
+ packet[2] = minutes;
337
+ await this.writeSettings(packet);
338
+ const confirmed = (await this.readSettings()).sleepMinutes;
339
+ if (confirmed !== minutes)
340
+ throw new Error(`The ${this.label} kept a ${confirmed} minute sleep timeout instead of ${minutes}.`);
341
+ return confirmed * 60;
342
+ }
343
+ /** Switch the onboard profile (1-based, as the panel numbers them). */
344
+ async setProfile(profile) {
345
+ const status = await this.readSettings();
346
+ if (!Number.isInteger(profile) || profile < 1 || profile > Math.min(status.profileCount, PROFILE_MAX)) {
347
+ throw new Error(`The ${this.label} profile must be between 1 and ${status.profileCount}.`);
348
+ }
349
+ const packet = new Uint8Array(SETTINGS_PACKET_LENGTH);
350
+ packet[0] = SET.profile;
351
+ packet[1] = profile - 1;
352
+ await this.writeSettings(packet);
353
+ const confirmed = (await this.readSettings()).profile + 1;
354
+ if (confirmed !== profile)
355
+ throw new Error(`The ${this.label} kept profile ${confirmed}.`);
356
+ return confirmed;
357
+ }
358
+ /** 0x52 on the 63-byte report: [1] button index, [3] type, then the type's data. */
359
+ async setButtonMapping(button, action) {
360
+ await this.readModel(await this.readIdentity());
361
+ const buttons = keychronButtons(this.model ?? undefined);
362
+ const slot = buttons.find((entry) => entry.name === button);
363
+ if (!slot)
364
+ throw new Error(`The ${this.label} has no "${button}" button.`);
365
+ const code = keychronEncodeButton(action, "8k");
366
+ if (!code)
367
+ throw new Error(`Unknown button action "${action}".`);
368
+ const expected = action === "Default" ? slot.defaultAction : action;
369
+ const after = (await this.readButtons()).map((entry) => (entry.button.index === slot.index ? expected : entry.action));
370
+ if (!after.includes("Left Click"))
371
+ throw new Error("Keep at least one button as Left Click.");
372
+ const packet = new Uint8Array(PACKET_LENGTH);
373
+ packet[0] = CMD.writeButton;
374
+ packet[1] = slot.index;
375
+ packet.set(code, 3);
376
+ const reply = await this.query(COMMAND_REPORT_ID, PACKET_LENGTH, Array.from(packet), (bytes) => bytes[0] === ACK && bytes[2] === CMD.writeButton);
377
+ if (reply[1] !== 0)
378
+ throw new Error(`The ${this.label} rejected the ${button} button (code ${reply[1]}).`);
379
+ const confirmed = await this.readButton(slot);
380
+ if (confirmed !== expected)
381
+ throw new Error(`The ${this.label} kept ${confirmed} on ${button} instead of ${action}.`);
382
+ }
383
+ async setLighting(lighting) {
384
+ await this.readModel(await this.readIdentity());
385
+ const offered = this.model?.light;
386
+ if (!offered)
387
+ throw new Error(`The ${this.label} has no lighting.`);
388
+ const light = keychronEncodeLighting(lighting, offered);
389
+ const packet = new Uint8Array(SETTINGS_PACKET_LENGTH);
390
+ packet[0] = SET.writeLighting;
391
+ packet.set([light.mode, light.brightness, light.speed, ...light.rgb], 1);
392
+ await this.writeSettings(packet);
393
+ const confirmed = keychronLighting(await this.readLight(), offered);
394
+ if (confirmed.mode !== lighting.mode)
395
+ throw new Error(`The ${this.label} kept its ${confirmed.mode ?? "previous"} lighting.`);
396
+ return confirmed;
397
+ }
398
+ get label() {
399
+ return this.model?.name ?? "Keychron mouse";
400
+ }
401
+ async writeSensorFlag(flag, enabled) {
402
+ const confirmed = await this.writeSensor({ ...(await this.readSettings()), [flag]: enabled });
403
+ if (confirmed[flag] !== enabled)
404
+ throw new Error(`The ${this.label} kept ${flag} ${confirmed[flag] ? "on" : "off"}.`);
405
+ return confirmed[flag];
406
+ }
407
+ /**
408
+ * The 0x42 packet carries every sensor option at once, so resend the
409
+ * current state with the requested change applied. Lift-off goes in the
410
+ * code or the level byte, whichever the firmware uses, with the other one
411
+ * 0 the way Launcher sends it.
412
+ */
413
+ async writeSensor(next) {
414
+ const levelMode = this.liftOffChoices(next).kind === "level";
415
+ await this.writeSettings(keychronEncodeSensor({
416
+ ...next,
417
+ lod: levelMode ? 0 : next.lod,
418
+ lodLevel: levelMode ? next.lodLevel : 0,
419
+ }));
420
+ return await this.readSettings();
421
+ }
422
+ async writeLiftOff(status, kind, code) {
423
+ const confirmed = await this.writeSensor(kind === "level" ? { ...status, lodLevel: code } : { ...status, lod: code });
424
+ const actual = kind === "level" ? confirmed.lodLevel : confirmed.lod;
425
+ if (actual !== code)
426
+ throw new Error(`The ${this.label} kept lift-off ${kind} ${actual}.`);
427
+ }
428
+ /**
429
+ * The 2-bit codes, or on firmware that flags lift-off levels the level byte,
430
+ * which Launcher fills from the same config list sorted by index and cut to
431
+ * the count the mouse reports.
432
+ */
433
+ liftOffChoices(status) {
434
+ const model = this.model;
435
+ const codes = model ? model.lod ?? [] : STANDARD_LOD;
436
+ if (!status.features.lodLevel)
437
+ return { kind: "code", choices: codes };
438
+ const levels = [...(model?.lodLevels?.length ? model.lodLevels : codes)].sort((a, b) => a[0] - b[0]);
439
+ return { kind: "level", choices: status.lodCount > 0 ? levels.slice(0, status.lodCount) : levels };
440
+ }
441
+ /** The model's rates when the gears can be rewritten, otherwise the rates the gears hold. */
442
+ supportedRates(status, polling) {
443
+ const model = this.model;
444
+ const rates = status.features.pollingGears && model
445
+ ? POLLING_RATES.filter((rate) => rate <= model.maxPollingHz)
446
+ : polling.table.slice(0, polling.count).map((value) => POLLING_RATES[value]).filter((rate) => rate !== undefined);
447
+ const unique = [...new Set(rates)].sort((a, b) => a - b);
448
+ return unique.length ? unique : [POLLING_RATES[polling.table[polling.level] ?? 2] ?? 1000];
449
+ }
450
+ connectionDetail(identity) {
451
+ if (identity.workMode === 2)
452
+ return "Bluetooth";
453
+ if (identity.workMode === 0)
454
+ return "Wired USB";
455
+ const receiver = KEYCHRON_RECEIVERS.get(this.device.productId);
456
+ return receiver ? `2.4 GHz (${receiver})` : "2.4 GHz receiver";
457
+ }
458
+ unreachableStatus(identity) {
459
+ const name = this.label;
460
+ return {
461
+ brand: "Keychron",
462
+ name,
463
+ ui: {
464
+ family: "keychron-8k",
465
+ defaultDisplayName: name,
466
+ settingsReady: false,
467
+ statusNote: identity.workMode === 1
468
+ ? "The mouse did not answer through the receiver. Wake it and reconnect."
469
+ : "The mouse did not answer its settings reads. Reconnect it and try again.",
470
+ },
471
+ batteryPercent: null,
472
+ batteryState: "Unknown",
473
+ dpi: 0,
474
+ pollingRateHz: 0,
475
+ activeProfile: null,
476
+ connectionType: identity.workMode === 0 ? "Wired" : "Wireless",
477
+ liftOffDistance: null,
478
+ firmware: identity.firmware ? [identity.firmware] : [],
479
+ };
480
+ }
481
+ requireDpi(dpi, status) {
482
+ const { min, max, step } = this.modelDpiLimits(status);
483
+ if (!Number.isInteger(dpi) || dpi < min || dpi > max || dpi % step !== 0) {
484
+ throw new Error(`The ${this.label} DPI must be a multiple of ${step} between ${min} and ${max}.`);
485
+ }
486
+ }
487
+ requireStage(stage, stageCount) {
488
+ if (!Number.isInteger(stage) || stage < 0 || stage >= stageCount) {
489
+ throw new Error(`DPI stage must be between 1 and ${stageCount}.`);
490
+ }
491
+ }
492
+ /** The model's floor, and the mouse's own ceiling and step when it flags them. */
493
+ modelDpiLimits(status) {
494
+ const [min, max] = this.model?.dpi ?? DEFAULT_DPI;
495
+ return {
496
+ min,
497
+ max: status?.features.dpiLimits && status.dpiMax > min ? status.dpiMax : max,
498
+ step: status?.features.dpiLimits && status.dpiStep > 0 ? status.dpiStep : DEFAULT_DPI_STEP,
499
+ };
500
+ }
501
+ async readSettings() {
502
+ await this.open();
503
+ const identity = await this.readIdentity();
504
+ await this.readModel(identity);
505
+ const status = this.parseStatus(await this.queryStatus(), identity);
506
+ this.dpiLimits = this.modelDpiLimits(status);
507
+ return status;
508
+ }
509
+ /**
510
+ * Firmware string (0x04 on 0xb3) and connection mode (0x02 on 0xb5) never
511
+ * change while connected, so they are read once. Either failing leaves the
512
+ * mouse usable: the mode falls back to what the product ID implies.
513
+ */
514
+ async readIdentity() {
515
+ if (this.identity)
516
+ return this.identity;
517
+ await this.open();
518
+ const fallbackMode = KEYCHRON_RECEIVERS.has(this.device.productId) ? 1 : 0;
519
+ const version = await this.querySettings(SET.version, [fallbackMode]).catch(() => null);
520
+ const workMode = version ? (version[9] ?? fallbackMode) & 0x07 : fallbackMode;
521
+ const firmware = await this.query(COMMAND_REPORT_ID, PACKET_LENGTH, [CMD.firmware, workMode], (bytes) => bytes[0] === CMD.firmware)
522
+ .then((bytes) => keychronLauncherFirmware(bytes) ?? (version ? decodeFirmwareNibbles(version) : null))
523
+ .catch(() => (version ? decodeFirmwareNibbles(version) : null));
524
+ this.identity = {
525
+ firmware,
526
+ workMode,
527
+ version: version ? readU16(version, 1) : 0,
528
+ productId: version ? readU16(version, 5) : null,
529
+ flags: version ? [version[11] ?? 0, version[12] ?? 0, version[13] ?? 0, version[15] ?? 0] : [0, 0, 0, 0],
530
+ };
531
+ return this.identity;
532
+ }
533
+ /**
534
+ * The model table row: by USB product ID, then by the ID in the 0x02
535
+ * answer, then, behind a receiver, by the connected mouse in its 0x03 list.
536
+ */
537
+ async readModel(identity) {
538
+ if (this.model !== undefined)
539
+ return this.model;
540
+ let model = keychronLauncherMouse(this.device.productId) ?? keychronLauncherMouse(identity.productId);
541
+ if (!model && identity.workMode === 1) {
542
+ const list = await this.querySettings(SET.receiverState, []).catch(() => null);
543
+ model = keychronLauncherMouse(list ? keychronDecodeConnectedMouse(list) : null);
544
+ }
545
+ this.model = model ?? null;
546
+ return this.model;
547
+ }
548
+ parseStatus(bytes, identity) {
549
+ if (bytes.length < 51 || bytes[0] !== STATUS_COMMAND) {
550
+ throw new Error(`The ${this.label} returned an invalid status report.`);
551
+ }
552
+ const flags = identity.version >= FLAGS_IN_VERSION_REPLY
553
+ ? identity.flags
554
+ : [bytes[26] ?? 0, bytes[53] ?? 0, bytes[60] ?? 0, 0];
555
+ const angle = bytes[55] ?? 0;
556
+ return {
557
+ ...keychronDecodeSettings(bytes),
558
+ profileCount: Math.min(bytes[50] ?? 0, PROFILE_MAX),
559
+ pollingTable: Array.from(bytes.slice(43, 43 + POLLING_GEARS)),
560
+ pollingCount: Math.min(bytes[49] || POLLING_GEARS, POLLING_GEARS),
561
+ dpiMax: readU16(bytes, 40),
562
+ dpiStep: bytes[42] ?? 0,
563
+ maxSpeed: ((bytes[52] ?? 0) & 0x01) !== 0,
564
+ angle: angle > ANGLE_LIMIT ? angle - 256 : angle,
565
+ lodLevel: (bytes[61] ?? 0) & 0x0f,
566
+ lodCount: (bytes[61] ?? 0) >> 4,
567
+ sleepMinutes: bytes[18] ?? 0,
568
+ batteryPercent: (bytes[19] ?? 0) & 0x7f,
569
+ charging: ((bytes[19] ?? 0) & 0x80) !== 0,
570
+ features: decodeFeatures(flags[0] ?? 0, flags[1] ?? 0, flags[2] ?? 0, flags[3] ?? 0),
571
+ };
572
+ }
573
+ /** Stages from the status report, or from 0x49 on firmware that keeps X and Y apart. */
574
+ async readDpi(status, identity) {
575
+ if (!status.features.separateDpi) {
576
+ return {
577
+ activeStage: keychronActiveStage(status, identity.workMode),
578
+ stages: status.dpiStages,
579
+ stageCount: status.stageCount,
580
+ xy: null,
581
+ };
582
+ }
583
+ const bytes = await this.query(COMMAND_REPORT_ID, PACKET_LENGTH, [CMD.readXy], (reply) => reply[0] === CMD.readXy);
584
+ const stageCount = Math.min(bytes[4] || DPI_STAGE_COUNT, DPI_STAGE_COUNT);
585
+ const levels = bytes[1 + Math.min(identity.workMode, 2)] ?? 0;
586
+ return {
587
+ activeStage: Math.min(levels & 0x0f, stageCount - 1),
588
+ stages: Array.from({ length: DPI_STAGE_COUNT }, (_, stage) => readU16(bytes, 5 + stage * 2)),
589
+ stageCount,
590
+ xy: {
591
+ y: Array.from({ length: DPI_STAGE_COUNT }, (_, stage) => readU16(bytes, 21 + stage * 2)),
592
+ // Protocol 6 packs the per-stage flags into one byte; older firmware gives each a byte.
593
+ enable: identity.version >= FLAGS_IN_VERSION_REPLY
594
+ ? Array.from({ length: 8 }, (_, bit) => ((bytes[37] ?? 0) >> bit) & 1)
595
+ : Array.from(bytes.slice(37, 45)),
596
+ },
597
+ };
598
+ }
599
+ /**
600
+ * 0x40, or 0x48 when X and Y are kept apart. The panel edits one axis, so
601
+ * a changed stage gets X = Y; the other stages keep their pairs.
602
+ */
603
+ async writeDpi(current, next, identity) {
604
+ if (!current.xy) {
605
+ await this.writeSettings(keychronEncodeDpi(next.activeStage, next.stages, next.stageCount));
606
+ return await this.readDpi(await this.readSettings(), identity);
607
+ }
608
+ const { y, enable } = current.xy;
609
+ const v6 = identity.version >= FLAGS_IN_VERSION_REPLY;
610
+ const packet = new Uint8Array(PACKET_LENGTH);
611
+ packet[0] = CMD.writeXy;
612
+ // Before protocol 6 each connection byte also carries the Y stage in its high nibble.
613
+ packet.fill(v6 ? next.activeStage : (next.activeStage << 4) | next.activeStage, 1, 4);
614
+ packet[4] = next.stageCount;
615
+ next.stages.forEach((x, stage) => {
616
+ writeU16(packet, 5 + stage * 2, x);
617
+ writeU16(packet, 21 + stage * 2, x === current.stages[stage] ? y[stage] ?? x : x);
618
+ });
619
+ if (v6)
620
+ packet[37] = enable.reduce((mask, bit, index) => mask | ((bit & 1) << index), 0);
621
+ else
622
+ packet.set(enable.slice(0, 8), 37);
623
+ const reply = await this.query(COMMAND_REPORT_ID, PACKET_LENGTH, Array.from(packet), (bytes) => bytes[0] === ACK && bytes[2] === CMD.writeXy);
624
+ if (reply[1] !== 0)
625
+ throw new Error(`The ${this.label} rejected command 0x48 (code ${reply[1]}).`);
626
+ return await this.readDpi(await this.readSettings(), identity);
627
+ }
628
+ /** The gear set of this connection: the status table, or 0x4b's USB and 2.4 GHz sets. */
629
+ async readPolling(status, identity) {
630
+ if (!status.features.separatePolling) {
631
+ return {
632
+ level: keychronActiveGear(status, identity.workMode),
633
+ count: status.pollingCount,
634
+ table: status.pollingTable,
635
+ sets: null,
636
+ set: 0,
637
+ };
638
+ }
639
+ const bytes = await this.querySettings(SET.readPollingSets, []);
640
+ const sets = [0, 1].map((set) => ({
641
+ level: bytes[1 + set] ?? 0,
642
+ count: Math.min(bytes[3 + set] || POLLING_GEARS, POLLING_GEARS),
643
+ table: Array.from(bytes.slice(5 + set * POLLING_GEARS, 5 + (set + 1) * POLLING_GEARS)),
644
+ }));
645
+ const set = identity.workMode === 1 ? 1 : 0;
646
+ return { ...sets[set], sets, set };
647
+ }
648
+ /** 0x41 carries this connection's gears; 0x4a carries both sets. */
649
+ pollingPacket(polling, next) {
650
+ const packet = new Uint8Array(SETTINGS_PACKET_LENGTH);
651
+ if (!polling.sets) {
652
+ packet[0] = SET.polling;
653
+ packet[1] = next.level;
654
+ packet[2] = next.level;
655
+ packet.set(next.table.slice(0, next.count), 3);
656
+ packet[9] = next.count;
657
+ return packet;
658
+ }
659
+ packet[0] = SET.writePollingSets;
660
+ polling.sets.map((set, index) => (index === polling.set ? next : set)).forEach((set, index) => {
661
+ packet[1 + index] = set.level;
662
+ packet[3 + index] = set.count;
663
+ packet.set(set.table.slice(0, POLLING_GEARS), 5 + index * POLLING_GEARS);
664
+ });
665
+ return packet;
666
+ }
667
+ async readButtons() {
668
+ const buttons = keychronButtons(this.model ?? undefined);
669
+ if (!buttons.length)
670
+ throw new Error(`OpenMouse does not know the ${this.label} buttons.`);
671
+ const result = [];
672
+ for (const button of buttons)
673
+ result.push({ button, action: await this.readButton(button) });
674
+ return result;
675
+ }
676
+ /** 0x62 answers [0x62, index, 0, type, data...]. */
677
+ async readButton(button) {
678
+ const bytes = await this.query(COMMAND_REPORT_ID, PACKET_LENGTH, [CMD.readButton, button.index], (reply) => reply[0] === CMD.readButton && reply[1] === button.index);
679
+ return keychronDecodeButton(bytes, "8k") ?? button.defaultAction;
680
+ }
681
+ /** 0x23 answers on 0x21: mode, brightness, speed, then RGB. */
682
+ async readLight() {
683
+ const bytes = await this.query(SETTINGS_REPORT_ID, SETTINGS_PACKET_LENGTH, [SET.readLighting], (reply) => reply[0] === SET.lightingAnswer);
684
+ return { mode: bytes[1] ?? 0, brightness: bytes[2] ?? 0, speed: bytes[3] ?? 0, rgb: [bytes[4] ?? 0, bytes[5] ?? 0, bytes[6] ?? 0] };
685
+ }
686
+ async queryStatus() {
687
+ return await this.query(COMMAND_REPORT_ID, PACKET_LENGTH, [STATUS_COMMAND], (bytes) => bytes[0] === STATUS_COMMAND);
688
+ }
689
+ async querySettings(command, args) {
690
+ return await this.query(SETTINGS_REPORT_ID, SETTINGS_PACKET_LENGTH, [command, ...args], (bytes) => bytes[0] === command);
691
+ }
692
+ async writeSettings(packet) {
693
+ const command = packet[0] ?? 0;
694
+ const reply = await this.query(SETTINGS_REPORT_ID, SETTINGS_PACKET_LENGTH, Array.from(packet), (bytes) => bytes[0] === command || (bytes[0] === ACK && bytes[2] === command));
695
+ if (reply[0] === ACK && reply[1] !== 0) {
696
+ throw new Error(`The ${this.label} rejected command 0x${command.toString(16)} (code ${reply[1]}).`);
697
+ }
698
+ }
699
+ async query(reportId, length, payload, match) {
700
+ if (this.responseWaiter)
701
+ throw new Error(`Another ${this.label} request is already in progress.`);
702
+ const packet = new Uint8Array(length);
703
+ packet.set(payload.slice(0, length));
704
+ let timeout;
705
+ let rejectResponse = null;
706
+ const response = new Promise((resolve, reject) => {
707
+ rejectResponse = reject;
708
+ timeout = setTimeout(() => {
709
+ this.responseWaiter = null;
710
+ reject(new Error(`The ${this.label} did not answer command 0x${packet[0]?.toString(16)}.`));
711
+ }, QUERY_TIMEOUT_MS);
712
+ this.responseWaiter = {
713
+ match,
714
+ resolve: (bytes) => {
715
+ clearTimeout(timeout);
716
+ resolve(bytes);
717
+ },
718
+ reject: (reason) => {
719
+ clearTimeout(timeout);
720
+ reject(reason);
721
+ },
722
+ };
723
+ });
724
+ void response.catch(() => undefined);
725
+ try {
726
+ await this.device.sendReport(reportId, packet.buffer);
727
+ }
728
+ catch (error) {
729
+ this.responseWaiter = null;
730
+ clearTimeout(timeout);
731
+ const detail = error instanceof Error ? error.message : String(error);
732
+ rejectResponse?.(new Error(`Chrome could not write the ${this.label} HID report. ${detail}`));
733
+ }
734
+ return await response;
735
+ }
736
+ }
737
+ function decodeFeatures(feature1, feature2, feature3, feature4) {
738
+ return {
739
+ dpiLimits: (feature1 & 0x08) !== 0,
740
+ pollingGears: (feature1 & 0x10) !== 0,
741
+ fps20k: (feature1 & 0x80) !== 0,
742
+ angle: (feature2 & 0x04) !== 0,
743
+ separateDpi: (feature3 & 0x01) !== 0,
744
+ separatePolling: (feature3 & 0x02) !== 0,
745
+ lodLevel: (feature4 & 0x10) !== 0,
746
+ };
747
+ }
748
+ /** 0x02 answer: major at [8], minor and patch in the nibbles of [7]. */
749
+ function decodeFirmwareNibbles(bytes) {
750
+ if (bytes.length < 9)
751
+ return null;
752
+ return `v${bytes[8]}.${(bytes[7] ?? 0) >> 4}.${(bytes[7] ?? 0) & 0x0f}`;
753
+ }
754
+ //# sourceMappingURL=mouse-8k-hid.js.map