@openmouse/protocol 0.40.1 → 0.41.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 (42) hide show
  1. package/README.md +6 -1
  2. package/dist/drivers/finalmouse/hid.d.ts +7 -0
  3. package/dist/drivers/finalmouse/hid.d.ts.map +1 -1
  4. package/dist/drivers/finalmouse/hid.js +21 -3
  5. package/dist/drivers/finalmouse/hid.js.map +1 -1
  6. package/dist/drivers/lamzu/hid.d.ts +29 -1
  7. package/dist/drivers/lamzu/hid.d.ts.map +1 -1
  8. package/dist/drivers/lamzu/hid.js +426 -78
  9. package/dist/drivers/lamzu/hid.js.map +1 -1
  10. package/dist/drivers/mouse-types.d.ts +2 -0
  11. package/dist/drivers/mouse-types.d.ts.map +1 -1
  12. package/dist/drivers/vendors.d.ts.map +1 -1
  13. package/dist/drivers/vendors.js +8 -0
  14. package/dist/drivers/vendors.js.map +1 -1
  15. package/dist/drivers/wallhack/mouse-hid.d.ts +15 -0
  16. package/dist/drivers/wallhack/mouse-hid.d.ts.map +1 -1
  17. package/dist/drivers/wallhack/mouse-hid.js +32 -11
  18. package/dist/drivers/wallhack/mouse-hid.js.map +1 -1
  19. package/dist/lamzu/index.d.ts +3 -0
  20. package/dist/lamzu/index.d.ts.map +1 -1
  21. package/dist/lamzu/index.js +3 -0
  22. package/dist/lamzu/index.js.map +1 -1
  23. package/dist/lamzu/lunafury-buttons.d.ts +44 -0
  24. package/dist/lamzu/lunafury-buttons.d.ts.map +1 -0
  25. package/dist/lamzu/lunafury-buttons.js +96 -0
  26. package/dist/lamzu/lunafury-buttons.js.map +1 -0
  27. package/dist/lamzu/lunafury-onboard.d.ts +102 -0
  28. package/dist/lamzu/lunafury-onboard.d.ts.map +1 -0
  29. package/dist/lamzu/lunafury-onboard.js +118 -0
  30. package/dist/lamzu/lunafury-onboard.js.map +1 -0
  31. package/dist/lamzu/lunafury-power.d.ts +39 -0
  32. package/dist/lamzu/lunafury-power.d.ts.map +1 -0
  33. package/dist/lamzu/lunafury-power.js +61 -0
  34. package/dist/lamzu/lunafury-power.js.map +1 -0
  35. package/dist/lamzu/lunafury.d.ts +9 -0
  36. package/dist/lamzu/lunafury.d.ts.map +1 -1
  37. package/dist/lamzu/lunafury.js.map +1 -1
  38. package/dist/wallhack/index.d.ts +44 -5
  39. package/dist/wallhack/index.d.ts.map +1 -1
  40. package/dist/wallhack/index.js +61 -6
  41. package/dist/wallhack/index.js.map +1 -1
  42. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { COMPX_HEADER_LENGTH as HEADER_LENGTH, COMPX_PACKET_LENGTH as PACKET_LENGTH, COMPX_REPORT_ID as REPORT_ID, COMPX_STATUS as STATUS, compaxDecodeDpiStages, compaxDecodeFirmware, compaxDecodeLiftOff, compaxDecodePollingRate, compaxDecodeSleep, compaxEncodeRequest, LAMZU_POLLING_RATES as POLLING_RATES, LAMZU_VENDOR_IDS, lamzuProduct, LUNAFURY_READ, LUNAFURY_WRITE, lunafuryDecodeAngle, lunafuryDecodeLightning, lunafuryDecodeButtonDebounce, lunafuryDecodeWheelGuard, MAGNETIC_CALIBRATION_ERRORS, MAGNETIC_CALIBRATION_STATE, MAGNETIC_CALIBRATION_STEPS, MAGNETIC_RAPID_TRIGGER_MAX_MS, MAGNETIC_RELEASE_FOLLOWS, MAGNETIC_SWITCH, MAGNETIC_TRAVEL_MAX, magneticCalibrationPrompt, magneticDecodeCalibration, magneticDecodeEid, magneticDecodeFault, magneticDecodeRapidTrigger, magneticDecodeSwitchTypes, magneticDecodeTravel, magneticRead, magneticWrite, } from "@openmouse/protocol/lamzu";
1
+ import { COMPX_HEADER_LENGTH as HEADER_LENGTH, COMPX_PACKET_LENGTH as PACKET_LENGTH, COMPX_REPORT_ID as REPORT_ID, COMPX_STATUS as STATUS, compaxDecodeDpiStages, compaxDecodeFirmware, compaxDecodeLiftOff, compaxDecodePollingRate, compaxDecodeSleep, compaxEncodeRequest, LAMZU_POLLING_RATES as POLLING_RATES, LAMZU_VENDOR_IDS, lamzuProduct, LUNAFURY_READ, LUNAFURY_WRITE, lunafuryDecodeAngle, lunafuryDecodeLightning, lunafuryDecodeButtonDebounce, lunafuryDecodeWheelGuard, LUNAFURY_ONBOARD_READ, LUNAFURY_ONBOARD_WRITE, LUNAFURY_DPI_DEFAULTS, lunafuryDecodeButtonRate, lunafuryDecodeSeparateAxes, lunafuryDecodeDpiStages, lunafuryDecodeDpiStorage, lunafuryWriteDpiStorage, lunafuryValidateDpi, lunafuryWriteDpiStages, LUNAFURY_BUTTON_IDS, LUNAFURY_BUTTON_ACTIONS, lunafuryButtonActionWritable, lunafuryDecodeButton, lunafuryDecodeButtonAction, lunafuryIsMappedButton, lunafuryReadButton, lunafuryWriteButton, LUNAFURY_SLEEP_OPTIONS, lunafuryEncodeSleep, lunafuryDecodeSleep, lunafuryReceiverLightTarget, lunafuryReadReceiverLight, lunafuryWriteReceiverLight, lunafuryDecodeReceiverLight, lunafuryReadBottomButton, lunafuryWriteBottomButton, lunafuryDecodeBottomButton, MAGNETIC_CALIBRATION_ERRORS, MAGNETIC_CALIBRATION_STATE, MAGNETIC_CALIBRATION_STEPS, MAGNETIC_RAPID_TRIGGER_MAX_MS, MAGNETIC_RELEASE_FOLLOWS, MAGNETIC_SWITCH, MAGNETIC_TRAVEL_MAX, magneticCalibrationPrompt, magneticDecodeCalibration, magneticDecodeEid, magneticDecodeFault, magneticDecodeRapidTrigger, magneticDecodeSwitchTypes, magneticDecodeTravel, magneticRead, magneticWrite, } from "@openmouse/protocol/lamzu";
2
2
  const SLEEP_SECONDS = [10, 30, 60, 300, 600, 1800];
3
3
  const RESPONSE_ATTEMPTS = 12;
4
4
  const RESPONSE_DELAY_MS = 30;
@@ -70,6 +70,7 @@ export class LamzuHidClient {
70
70
  notifier = null;
71
71
  notifyListener = null;
72
72
  activeProfile = 1;
73
+ onboardQueue = Promise.resolve();
73
74
  device;
74
75
  constructor(device) {
75
76
  this.device = device;
@@ -155,6 +156,8 @@ export class LamzuHidClient {
155
156
  return this.profile()?.maxDpiStages ?? 6;
156
157
  }
157
158
  getSleepOptions() {
159
+ if (this.deviceBrand() === "LunaFury")
160
+ return LUNAFURY_SLEEP_OPTIONS;
158
161
  return this.profile()?.sleepOptions ?? SLEEP_SECONDS;
159
162
  }
160
163
  getDebounceMaxMs() {
@@ -179,6 +182,11 @@ export class LamzuHidClient {
179
182
  return /receiver|dongle/i.test(this.device.productName || "");
180
183
  }
181
184
  async readStatus(live = false) {
185
+ // A status read must not interleave a bank switch or repopulate its old cache.
186
+ return this.deviceBrand() === "LunaFury"
187
+ ? this.onboardOperation(() => this.readStatusNow(live)) : this.readStatusNow(live);
188
+ }
189
+ async readStatusNow(live = false) {
182
190
  await this.open();
183
191
  if (live && this.lastStatus)
184
192
  return await this.readLiveStatus(this.lastStatus);
@@ -194,15 +202,21 @@ export class LamzuHidClient {
194
202
  const activeProfileReply = await this.request(READ.activeProfile).catch(() => null);
195
203
  const profile = activeProfileReply ? Math.max(1, activeProfileReply[0]) : 1;
196
204
  this.activeProfile = profile;
197
- const sleepTimeout = await this.request(PROFILE_READ.sleepTimeout(profile)).catch(() => null);
205
+ const luna = this.deviceBrand() === "LunaFury";
206
+ const sleepTimeout = await (luna ? this.readLunaFury(PROFILE_READ.sleepTimeout(profile))
207
+ : this.request(PROFILE_READ.sleepTimeout(profile))).catch(() => null);
198
208
  const debounce = await this.request(PROFILE_READ.debounce(profile)).catch(() => null);
199
- const stages = this.decodeDpiStages(await this.request(PROFILE_READ.dpiStages(profile, this.maxDpiStages())));
200
- const activeStage = this.stageIndex((await this.request(PROFILE_READ.activeStage(profile)))[1], stages.length);
209
+ const { raw: dpiRaw, stages } = await this.readDpiTable(profile);
210
+ const activeStage = luna
211
+ ? await this.readLunaFuryStage(profile, stages.length)
212
+ : this.stageIndex((await this.request(PROFILE_READ.activeStage(profile)))[1], stages.length);
201
213
  const pollingRate = await this.request(PROFILE_READ.pollingRate(profile));
202
214
  const liftOffDistance = await this.request(PROFILE_READ.liftOffDistance(profile));
203
- const separateAxes = this.profile()?.separateDpiAxes === false
215
+ const separateAxesUnsupported = this.profile()?.separateDpiAxes === false;
216
+ const separateAxes = separateAxesUnsupported
204
217
  ? null
205
- : await this.request(PROFILE_READ.separateAxes(profile)).catch(() => null);
218
+ : await (luna ? this.readLunaFury(LUNAFURY_ONBOARD_READ.separateAxes(profile))
219
+ : this.request(PROFILE_READ.separateAxes(profile))).catch(() => null);
206
220
  const angleSnapping = await this.request(PROFILE_READ.angleSnapping(profile)).catch(() => null);
207
221
  const motionSync = await this.request(PROFILE_READ.motionSync(profile)).catch(() => null);
208
222
  const competitiveMode = await this.request(PROFILE_READ.competitiveMode(profile)).catch(() => null);
@@ -215,6 +229,7 @@ export class LamzuHidClient {
215
229
  : null;
216
230
  const lunafury = this.deviceBrand() === "LunaFury"
217
231
  ? await this.readLunaFurySettings(profile) : undefined;
232
+ const buttons = luna ? await this.readLunaFuryButtons(profile) : undefined;
218
233
  const stage = stages[activeStage];
219
234
  if (!stage)
220
235
  throw new Error("The mouse did not report any DPI stages.");
@@ -227,21 +242,29 @@ export class LamzuHidClient {
227
242
  family: this.profile()?.uiFamily ?? "lamzu",
228
243
  hideUnsupportedPollingRates: true,
229
244
  forceShowBattery: true,
245
+ ...(luna ? { dpiStageEditor: { maxStages: this.maxDpiStages(), countEditable: true,
246
+ minDpi: 50, maxDpi: this.maxDpi(), stepDpi: DPI_STEP } } : {}),
230
247
  },
231
248
  batteryPercent: battery[1] <= 100 ? battery[1] : null,
232
249
  batteryState: battery[0] === 1 ? "Charging" : "Discharging",
233
250
  dpi: stage.x,
234
251
  dpiY: stage.y,
235
- supportsSeparateDpiAxes: separateAxes ? separateAxes[1] === 1 : false,
252
+ supportsSeparateDpiAxes: luna
253
+ ? (separateAxesUnsupported ? false
254
+ : separateAxes === null ? undefined : lunafuryDecodeSeparateAxes(separateAxes) !== undefined)
255
+ : separateAxes ? separateAxes[1] === 1 : false,
256
+ ...(luna ? { dpiStages: stages.map((item) => item.x), dpiStagesY: stages.map((item) => item.y), activeDpiStage: activeStage } : {}),
236
257
  pollingRateHz: this.decodePollingRate(pollingRate[1]),
237
258
  supportedPollingRates: this.getSupportedPollingRates(),
238
259
  activeProfile: activeProfileReply ? activeProfileReply[0] : null,
260
+ ...(luna && activeProfileReply && activeProfileReply[0] >= 1 && activeProfileReply[0] <= 3 ? { profileCount: 3 } : {}),
239
261
  angleSnapping: angleSnapping ? angleSnapping[1] === 1 : null,
240
262
  motionSync: motionSync ? motionSync[1] === 1 : null,
241
263
  performanceMode: competitiveMode ? competitiveMode[1] === 1 : null,
242
264
  hyperMode: hyperMode ? hyperMode[1] === 1 : null,
243
265
  rippleControl: rippleControl ? rippleControl[1] === 1 : null,
244
- ...(lunafury ? { lunafury: lunafury.settings, angleTuning: lunafury.angle } : {}),
266
+ ...(lunafury ? { lunafury: { ...lunafury.settings, dpiStorage: lunafuryDecodeDpiStorage(dpiRaw, this.maxDpiStages()) }, angleTuning: lunafury.angle } : {}),
267
+ ...buttons,
245
268
  dongleLedEnabled: dongleLed ? dongleLed[1] === 1 : null,
246
269
  connectionType: wireless ? "Wireless" : "Wired",
247
270
  connectionDetail: wireless ? "2.4 GHz receiver" : "Wired USB",
@@ -254,10 +277,22 @@ export class LamzuHidClient {
254
277
  };
255
278
  }
256
279
  async readLiveStatus(previous) {
280
+ let dpi = {};
281
+ if (this.deviceBrand() === "LunaFury") {
282
+ const profile = await this.currentProfile();
283
+ if (profile !== previous.activeProfile)
284
+ return this.readStatusNow();
285
+ const { raw, stages } = await this.readDpiTable(profile);
286
+ const active = await this.readLunaFuryStage(profile, stages.length);
287
+ dpi = { dpiStages: stages.map((stage) => stage.x), dpiStagesY: stages.map((stage) => stage.y),
288
+ activeDpiStage: active, dpi: stages[active].x, dpiY: stages[active].y,
289
+ lunafury: { ...previous.lunafury, dpiStorage: lunafuryDecodeDpiStorage(raw, this.maxDpiStages()) } };
290
+ }
257
291
  const battery = await this.request(READ.battery);
258
292
  const pollingRate = await this.request(PROFILE_READ.pollingRate(this.activeProfile));
259
293
  return this.lastStatus = {
260
294
  ...previous,
295
+ ...dpi,
261
296
  batteryPercent: battery[1] <= 100 ? battery[1] : null,
262
297
  batteryState: battery[0] === 1 ? "Charging" : "Discharging",
263
298
  pollingRateHz: this.decodePollingRate(pollingRate[1]),
@@ -286,78 +321,345 @@ export class LamzuHidClient {
286
321
  const middleDebounceMs = lunafuryDecodeButtonDebounce(await optional(LUNAFURY_READ.buttonDebounce(profile, "middle")), "middle");
287
322
  const wheelGuard = lunafuryDecodeWheelGuard(await optional(LUNAFURY_READ.wheelGuard(profile)));
288
323
  const angle = lunafuryDecodeAngle(await optional(LUNAFURY_READ.angle(profile)));
289
- return { settings: { lightningMode, leftDebounceMs, rightDebounceMs, middleDebounceMs, wheelGuard }, angle };
324
+ const buttonPollingRateHz = lunafuryDecodeButtonRate(await optional(LUNAFURY_ONBOARD_READ.buttonRate(profile)));
325
+ const separateDpiAxes = lunafuryDecodeSeparateAxes(await optional(LUNAFURY_ONBOARD_READ.separateAxes(profile)));
326
+ const receiverLightMode = lunafuryReceiverLightTarget(this.device.productId) !== undefined
327
+ ? lunafuryDecodeReceiverLight(await this.readReceiverLight(2).catch(() => null)) : undefined;
328
+ const bottomButtonMode = lunafuryDecodeBottomButton(await this.readLunaFuryBottomButton(profile, 2).catch(() => null), profile);
329
+ return { settings: { lightningMode, leftDebounceMs, rightDebounceMs, middleDebounceMs, wheelGuard,
330
+ ...(bottomButtonMode !== undefined ? { bottomButtonMode } : {}),
331
+ ...(receiverLightMode !== undefined ? { receiverLightMode } : {}),
332
+ ...(buttonPollingRateHz !== undefined ? { buttonPollingRateHz, supportedButtonPollingRates: this.getLunaFuryButtonPollingRates() } : {}),
333
+ ...(separateDpiAxes !== undefined ? { separateDpiAxes } : {}),
334
+ }, angle };
335
+ }
336
+ readLunaFuryBottomButton(profile, attempts) {
337
+ return this.request({ ...lunafuryReadBottomButton(profile), attempts,
338
+ matchesReply: (reply) => reply[0] === profile && reply[1] === 0x14 && reply[2] === 0 });
339
+ }
340
+ async setLunaFuryBottomButtonMode(mode) {
341
+ this.requireLunaFury();
342
+ lunafuryWriteBottomButton(1, mode); // Validate before sending any request.
343
+ return this.onboardOperation(async () => {
344
+ const profile = await this.currentProfile();
345
+ const previous = lunafuryDecodeBottomButton(await this.readLunaFuryBottomButton(profile), profile);
346
+ if (previous === undefined)
347
+ throw new Error("The bottom-button binding is unsupported or unknown.");
348
+ await this.request(lunafuryWriteBottomButton(profile, mode));
349
+ const confirmed = lunafuryDecodeBottomButton(await this.readLunaFuryBottomButton(profile), profile);
350
+ if (confirmed !== mode)
351
+ throw new Error("The mouse did not confirm the bottom-button mode.");
352
+ this.patchLunaFury({ bottomButtonMode: confirmed });
353
+ return confirmed;
354
+ });
355
+ }
356
+ getLunaFuryButtonPollingRates() {
357
+ this.requireLunaFury();
358
+ return this.device.productId === 0x0032 ? [1000] : [1000, 2000, 4000, 8000];
359
+ }
360
+ async readLunaFuryButton(profile, button, attempts) {
361
+ const spec = lunafuryReadButton(profile, button);
362
+ const payload = await this.request({ ...spec, attempts,
363
+ matchesReply: (reply) => reply[0] === profile && reply[1] === spec.args[1] && reply[2] === 0 });
364
+ return lunafuryDecodeButton(payload, profile, button);
365
+ }
366
+ async readLunaFuryButtons(profile) {
367
+ const buttonMappings = {};
368
+ const fixedButtons = ["Left"];
369
+ for (const button of Object.keys(LUNAFURY_BUTTON_IDS)) {
370
+ const binding = await this.readLunaFuryButton(profile, button, 2).catch(() => null);
371
+ if (!binding)
372
+ continue; // An unsupported remapping read must not hide basic settings.
373
+ const action = lunafuryDecodeButtonAction(binding);
374
+ buttonMappings[button] = action;
375
+ if (button !== "Left" && !lunafuryButtonActionWritable(action))
376
+ fixedButtons.push(button);
377
+ }
378
+ return Object.keys(buttonMappings).length
379
+ ? { buttonMappings, fixedButtons, buttonOptions: [...LUNAFURY_BUTTON_ACTIONS] } : {};
380
+ }
381
+ async setButtonMapping(button, action) {
382
+ this.requireLunaFury();
383
+ if (!lunafuryIsMappedButton(button) || button === "Left")
384
+ throw new Error("This LunaFury button is protected.");
385
+ // Validate before issuing even a read. Macro/unknown commands never become writes.
386
+ lunafuryWriteButton(1, button, action);
387
+ return this.onboardOperation(async () => {
388
+ const profile = await this.currentProfile();
389
+ const previous = await this.readLunaFuryButton(profile, button);
390
+ if (!lunafuryButtonActionWritable(lunafuryDecodeButtonAction(previous))) {
391
+ throw new Error("Existing macros and unknown assignments are read-only.");
392
+ }
393
+ await this.request(lunafuryWriteButton(profile, button, action));
394
+ const confirmed = lunafuryDecodeButtonAction(await this.readLunaFuryButton(profile, button));
395
+ if (confirmed !== action)
396
+ throw new Error("The mouse did not confirm the button assignment.");
397
+ if (this.lastStatus?.buttonMappings)
398
+ this.patch({ buttonMappings: { ...this.lastStatus.buttonMappings, [button]: confirmed } });
399
+ return confirmed;
400
+ });
401
+ }
402
+ async setLunaFuryButtonPollingRate(hertz) {
403
+ this.requireLunaFury();
404
+ if (!this.getLunaFuryButtonPollingRates().includes(hertz))
405
+ throw new Error(`This mouse does not support ${hertz} Hz button polling.`);
406
+ return this.onboardOperation(async () => {
407
+ const profile = await this.currentProfile();
408
+ await this.request(LUNAFURY_ONBOARD_WRITE.buttonRate(profile, hertz));
409
+ const confirmed = lunafuryDecodeButtonRate(await this.readLunaFury(LUNAFURY_ONBOARD_READ.buttonRate(profile)));
410
+ if (confirmed !== hertz)
411
+ throw new Error("The mouse did not confirm the button polling rate.");
412
+ this.patchLunaFury({ buttonPollingRateHz: confirmed });
413
+ return confirmed;
414
+ });
415
+ }
416
+ /** Serialize multi-report edits so a profile switch cannot split an edit. */
417
+ onboardOperation(operation) {
418
+ const run = this.onboardQueue.then(operation, operation);
419
+ this.onboardQueue = run.catch(() => { this.lastStatus = null; });
420
+ return run;
421
+ }
422
+ /** Older shared setters join LunaFury's queue without changing other brands. */
423
+ profileOperation(operation) {
424
+ const run = async () => operation(await this.currentProfile());
425
+ return this.deviceBrand() === "LunaFury" ? this.onboardOperation(run) : run();
426
+ }
427
+ async readDpiTable(profile) {
428
+ const luna = this.deviceBrand() === "LunaFury";
429
+ const raw = luna ? await this.readLunaFury({ ...LUNAFURY_ONBOARD_READ.dpiStages(profile, this.maxDpiStages()), full: true })
430
+ : await this.request(PROFILE_READ.dpiStages(profile, this.maxDpiStages()));
431
+ return { raw, stages: luna ? lunafuryDecodeDpiStages(raw, this.maxDpiStages()) : this.decodeDpiStages(raw) };
432
+ }
433
+ async readLunaFuryStage(profile, count) {
434
+ const reply = await this.readLunaFury(LUNAFURY_ONBOARD_READ.activeStage(profile));
435
+ if (reply.length < 2 || reply[1] < 1 || reply[1] > count)
436
+ throw new Error("The mouse reported an invalid active DPI stage.");
437
+ return reply[1] - 1;
438
+ }
439
+ patchDpiTable(stages, active, raw) {
440
+ this.patch({ dpiStages: stages.map((stage) => stage.x), dpiStagesY: stages.map((stage) => stage.y),
441
+ activeDpiStage: active, dpi: stages[active].x, dpiY: stages[active].y });
442
+ this.patchLunaFury({ dpiStorage: lunafuryDecodeDpiStorage(raw, this.maxDpiStages()) });
443
+ }
444
+ async writeLunaFuryDpiTable(profile, raw, stages, active) {
445
+ await this.request(lunafuryWriteDpiStages(profile, stages, raw, this.maxDpiStages()));
446
+ const { raw: confirmedRaw, stages: confirmed } = await this.readDpiTable(profile);
447
+ if (JSON.stringify(confirmed) !== JSON.stringify(stages))
448
+ throw new Error("The mouse did not confirm the complete DPI table.");
449
+ if (await this.readLunaFuryStage(profile, confirmed.length) !== active)
450
+ throw new Error("The mouse did not keep the active DPI stage.");
451
+ this.patchDpiTable(confirmed, active, confirmedRaw);
452
+ }
453
+ /** Restore enabled count and dormant slots in one bank-scoped transaction. */
454
+ async setLunaFuryDpiStorage(storage) {
455
+ this.requireLunaFury();
456
+ const saved = structuredClone(storage);
457
+ return this.onboardOperation(async () => {
458
+ const profile = await this.currentProfile();
459
+ if (saved.profile !== profile)
460
+ throw new Error("DPI backup belongs to another onboard profile.");
461
+ const { raw, stages } = await this.readDpiTable(profile);
462
+ const write = lunafuryWriteDpiStorage(saved, raw, this.maxDpiStages());
463
+ let active = await this.readLunaFuryStage(profile, stages.length);
464
+ if (active >= saved.count) {
465
+ active = saved.count - 1;
466
+ await this.request(LUNAFURY_ONBOARD_WRITE.activeStage(profile, active, stages.length));
467
+ if (await this.readLunaFuryStage(profile, stages.length) !== active)
468
+ throw new Error("The mouse did not confirm the active DPI stage.");
469
+ }
470
+ await this.request(write);
471
+ const { raw: confirmedRaw, stages: confirmed } = await this.readDpiTable(profile);
472
+ const stored = lunafuryDecodeDpiStorage(confirmedRaw, this.maxDpiStages());
473
+ if (!stored || stored.count !== saved.count || stored.stages.some((stage, index) => stage.x !== saved.stages[index].x || stage.y !== saved.stages[index].y)
474
+ || raw.slice(2 + this.maxDpiStages() * 4, 26).some((byte, index) => byte !== confirmedRaw[2 + this.maxDpiStages() * 4 + index])) {
475
+ throw new Error("The mouse did not confirm the complete stored DPI table.");
476
+ }
477
+ if (await this.readLunaFuryStage(profile, confirmed.length) !== active)
478
+ throw new Error("The mouse did not keep the active DPI stage.");
479
+ this.patchDpiTable(confirmed, active, confirmedRaw);
480
+ return saved.count;
481
+ });
482
+ }
483
+ async setProfile(profile) {
484
+ this.requireLunaFury();
485
+ const write = LUNAFURY_ONBOARD_WRITE.profile(profile);
486
+ return this.onboardOperation(async () => {
487
+ await this.request(write);
488
+ const confirmed = (await this.request(LUNAFURY_ONBOARD_READ.profile()))[0];
489
+ if (confirmed !== profile)
490
+ throw new Error("The mouse did not confirm the onboard profile.");
491
+ this.activeProfile = profile;
492
+ this.lastStatus = null; // DPI, flags, latencies and rates all belong to the newly selected bank.
493
+ return confirmed;
494
+ });
495
+ }
496
+ async setActiveDpiStage(stage) {
497
+ this.requireLunaFury();
498
+ if (!Number.isInteger(stage) || stage < 0 || stage >= this.maxDpiStages())
499
+ throw new Error("Invalid DPI stage index.");
500
+ return this.onboardOperation(async () => {
501
+ const profile = await this.currentProfile();
502
+ const { raw, stages } = await this.readDpiTable(profile);
503
+ await this.request(LUNAFURY_ONBOARD_WRITE.activeStage(profile, stage, stages.length));
504
+ if (await this.readLunaFuryStage(profile, stages.length) !== stage)
505
+ throw new Error("The mouse did not confirm the active DPI stage.");
506
+ this.patchDpiTable(stages, stage, raw);
507
+ return stage;
508
+ });
509
+ }
510
+ async setDpiStageCount(count) {
511
+ this.requireLunaFury();
512
+ if (!Number.isInteger(count) || count < 1 || count > this.maxDpiStages())
513
+ throw new Error("Invalid DPI stage count.");
514
+ return this.onboardOperation(async () => {
515
+ const profile = await this.currentProfile();
516
+ const { raw, stages } = await this.readDpiTable(profile);
517
+ if (!lunafuryDecodeDpiStorage(raw, this.maxDpiStages()))
518
+ throw new Error("Cannot change stage count without complete stored DPI data.");
519
+ let active = await this.readLunaFuryStage(profile, stages.length);
520
+ if (active >= count) {
521
+ active = count - 1;
522
+ await this.request(LUNAFURY_ONBOARD_WRITE.activeStage(profile, active, stages.length));
523
+ if (await this.readLunaFuryStage(profile, stages.length) !== active)
524
+ throw new Error("The mouse did not confirm the active DPI stage.");
525
+ }
526
+ const next = stages.slice(0, count);
527
+ while (next.length < count) {
528
+ const offset = 2 + next.length * 4;
529
+ const x = (raw[offset] << 8) | raw[offset + 1];
530
+ const y = (raw[offset + 2] << 8) | raw[offset + 3];
531
+ const valid = (value) => value >= 50 && value <= this.maxDpi() && value % DPI_STEP === 0;
532
+ const fallback = LUNAFURY_DPI_DEFAULTS[next.length];
533
+ next.push(valid(x) && valid(y) ? { x, y } : { x: fallback, y: fallback });
534
+ }
535
+ await this.writeLunaFuryDpiTable(profile, raw, next, active);
536
+ return count;
537
+ });
538
+ }
539
+ async setDpiStageValue(stage, dpi) {
540
+ return this.setLunaFuryStageAxes(stage, dpi);
541
+ }
542
+ async setLunaFuryDpiStageAxes(stage, dpi, dpiY) {
543
+ return this.setLunaFuryStageAxes(stage, dpi, dpiY);
544
+ }
545
+ async setLunaFuryStageAxes(stage, dpi, dpiY) {
546
+ this.requireLunaFury();
547
+ lunafuryValidateDpi(dpi);
548
+ if (dpiY !== undefined)
549
+ lunafuryValidateDpi(dpiY);
550
+ if (stage !== undefined && (!Number.isInteger(stage) || stage < 0 || stage >= this.maxDpiStages()))
551
+ throw new Error("Invalid DPI stage index.");
552
+ return this.onboardOperation(async () => {
553
+ const profile = await this.currentProfile();
554
+ const { raw, stages } = await this.readDpiTable(profile);
555
+ const active = await this.readLunaFuryStage(profile, stages.length);
556
+ const index = stage ?? active;
557
+ if (!stages[index])
558
+ throw new Error("This DPI stage is not enabled.");
559
+ const separate = dpiY === undefined ? lunafuryDecodeSeparateAxes(await this.readLunaFury(LUNAFURY_ONBOARD_READ.separateAxes(profile)).catch(() => null)) : undefined;
560
+ // Axis lock controls sensor behaviour, not whether the Y value is
561
+ // stored. Explicit X/Y writes also restore dormant Y values in Games.
562
+ stages[index] = { x: dpi, y: dpiY ?? (separate === false ? dpi : stages[index].y) };
563
+ await this.writeLunaFuryDpiTable(profile, raw, stages, active);
564
+ return dpi;
565
+ });
566
+ }
567
+ async setLunaFurySeparateDpiAxes(enabled) {
568
+ this.requireLunaFury();
569
+ LUNAFURY_ONBOARD_WRITE.separateAxes(1, enabled);
570
+ return this.onboardOperation(async () => {
571
+ const profile = await this.currentProfile();
572
+ await this.request(LUNAFURY_ONBOARD_WRITE.separateAxes(profile, enabled));
573
+ const confirmed = lunafuryDecodeSeparateAxes(await this.readLunaFury(LUNAFURY_ONBOARD_READ.separateAxes(profile)));
574
+ if (confirmed !== enabled)
575
+ throw new Error("The mouse did not confirm the DPI axis mode.");
576
+ this.patchLunaFury({ separateDpiAxes: enabled });
577
+ return enabled;
578
+ });
290
579
  }
291
580
  patchLunaFury(changes) {
292
581
  this.patch({ lunafury: { ...this.lastStatus?.lunafury, ...changes } });
293
582
  }
294
583
  async setAngleTuning(degrees) {
295
584
  this.requireLunaFury();
296
- const profile = await this.currentProfile();
297
- await this.request(LUNAFURY_WRITE.angle(profile, degrees));
298
- const confirmed = lunafuryDecodeAngle(await this.readLunaFury(LUNAFURY_READ.angle(profile)));
299
- if (confirmed !== degrees)
300
- throw new Error(`The mouse did not confirm the ${degrees}° sensor angle.`);
301
- this.patch({ angleTuning: confirmed });
302
- return confirmed;
585
+ LUNAFURY_WRITE.angle(1, degrees);
586
+ return this.profileOperation(async (profile) => {
587
+ await this.request(LUNAFURY_WRITE.angle(profile, degrees));
588
+ const confirmed = lunafuryDecodeAngle(await this.readLunaFury(LUNAFURY_READ.angle(profile)));
589
+ if (confirmed !== degrees)
590
+ throw new Error(`The mouse did not confirm the ${degrees}° sensor angle.`);
591
+ this.patch({ angleTuning: confirmed });
592
+ return confirmed;
593
+ });
303
594
  }
304
595
  async setLunaFuryLightningMode(mode) {
305
596
  this.requireLunaFury();
306
- const profile = await this.currentProfile();
307
- await this.request(LUNAFURY_WRITE.lightning(profile, mode));
308
- const confirmed = lunafuryDecodeLightning(await this.readLunaFury(LUNAFURY_READ.lightning(profile)));
309
- if (confirmed !== mode)
310
- throw new Error("The mouse did not confirm the Lightning Trigger mode.");
311
- this.patchLunaFury({ lightningMode: confirmed });
312
- return confirmed;
597
+ LUNAFURY_WRITE.lightning(1, mode);
598
+ return this.profileOperation(async (profile) => {
599
+ await this.request(LUNAFURY_WRITE.lightning(profile, mode));
600
+ const confirmed = lunafuryDecodeLightning(await this.readLunaFury(LUNAFURY_READ.lightning(profile)));
601
+ if (confirmed !== mode)
602
+ throw new Error("The mouse did not confirm the Lightning Trigger mode.");
603
+ this.patchLunaFury({ lightningMode: confirmed });
604
+ return confirmed;
605
+ });
313
606
  }
314
607
  async setLunaFuryButtonDebounce(button, milliseconds) {
315
608
  this.requireLunaFury();
316
- const profile = await this.currentProfile();
317
- await this.request(LUNAFURY_WRITE.buttonDebounce(profile, button, milliseconds));
318
- const confirmed = lunafuryDecodeButtonDebounce(await this.readLunaFury(LUNAFURY_READ.buttonDebounce(profile, button)), button);
319
- if (confirmed !== milliseconds)
320
- throw new Error(`The mouse did not confirm ${milliseconds} ms latency for the ${button} button.`);
321
- this.patchLunaFury({ [`${button}DebounceMs`]: confirmed });
322
- return confirmed;
609
+ LUNAFURY_WRITE.buttonDebounce(1, button, milliseconds);
610
+ return this.profileOperation(async (profile) => {
611
+ await this.request(LUNAFURY_WRITE.buttonDebounce(profile, button, milliseconds));
612
+ const confirmed = lunafuryDecodeButtonDebounce(await this.readLunaFury(LUNAFURY_READ.buttonDebounce(profile, button)), button);
613
+ if (confirmed !== milliseconds)
614
+ throw new Error(`The mouse did not confirm ${milliseconds} ms latency for the ${button} button.`);
615
+ this.patchLunaFury({ [`${button}DebounceMs`]: confirmed });
616
+ return confirmed;
617
+ });
323
618
  }
324
619
  async setLunaFuryWheelGuard(guard) {
325
620
  this.requireLunaFury();
326
- const profile = await this.currentProfile();
327
- await this.request(LUNAFURY_WRITE.wheelGuard(profile, guard));
328
- const confirmed = lunafuryDecodeWheelGuard(await this.readLunaFury(LUNAFURY_READ.wheelGuard(profile)));
329
- if (!confirmed || confirmed.enabled !== guard.enabled || confirmed.windowMs !== guard.windowMs) {
330
- throw new Error("The mouse did not confirm the wheel guard settings.");
331
- }
332
- this.patchLunaFury({ wheelGuard: confirmed });
333
- return confirmed;
621
+ LUNAFURY_WRITE.wheelGuard(1, guard);
622
+ const wanted = { ...guard };
623
+ return this.profileOperation(async (profile) => {
624
+ await this.request(LUNAFURY_WRITE.wheelGuard(profile, wanted));
625
+ const confirmed = lunafuryDecodeWheelGuard(await this.readLunaFury(LUNAFURY_READ.wheelGuard(profile)));
626
+ if (!confirmed || confirmed.enabled !== wanted.enabled || confirmed.windowMs !== wanted.windowMs) {
627
+ throw new Error("The mouse did not confirm the wheel guard settings.");
628
+ }
629
+ this.patchLunaFury({ wheelGuard: confirmed });
630
+ return confirmed;
631
+ });
334
632
  }
335
633
  async setPollingRate(pollingRateHz) {
336
634
  const encoded = POLLING_RATES.find(([, hertz]) => hertz === pollingRateHz);
337
635
  if (!encoded || !this.getSupportedPollingRates().includes(pollingRateHz)) {
338
636
  throw new Error(`This mouse does not support ${pollingRateHz} Hz.`);
339
637
  }
340
- const profile = await this.currentProfile();
341
- await this.write(PAGE.profile, WRITE.pollingRate, profile, [encoded[0]]);
342
- const confirmed = this.decodePollingRate((await this.request(PROFILE_READ.pollingRate(profile)))[1]);
343
- if (confirmed !== pollingRateHz) {
344
- throw new Error(`The mouse kept ${confirmed} Hz instead of ${pollingRateHz} Hz.`);
345
- }
346
- this.patch({ pollingRateHz: confirmed });
347
- return confirmed;
638
+ return this.profileOperation(async (profile) => {
639
+ await this.write(PAGE.profile, WRITE.pollingRate, profile, [encoded[0]]);
640
+ const reply = await (this.deviceBrand() === "LunaFury" ? this.readLunaFury(PROFILE_READ.pollingRate(profile)) : this.request(PROFILE_READ.pollingRate(profile)));
641
+ const confirmed = this.decodePollingRate(reply[1]);
642
+ if (confirmed !== pollingRateHz) {
643
+ throw new Error(`The mouse kept ${confirmed} Hz instead of ${pollingRateHz} Hz.`);
644
+ }
645
+ this.patch({ pollingRateHz: confirmed });
646
+ return confirmed;
647
+ });
348
648
  }
349
649
  async setLiftOffDistance(value) {
350
650
  const encoded = LIFT_OFF_DISTANCES.find(([, name]) => name === value);
351
651
  if (!encoded)
352
652
  throw new Error(`This mouse does not support a ${value.toLowerCase()} lift-off distance.`);
353
- const profile = await this.currentProfile();
354
- await this.write(PAGE.profile, WRITE.liftOffDistance, profile, [encoded[0]]);
355
- const confirmed = this.decodeLiftOffDistance((await this.request(PROFILE_READ.liftOffDistance(profile)))[1]);
356
- if (confirmed !== value) {
357
- throw new Error(`The mouse kept a ${String(confirmed).toLowerCase()} lift-off distance instead of ${value.toLowerCase()}.`);
358
- }
359
- this.patch({ liftOffDistance: confirmed });
360
- return confirmed;
653
+ return this.profileOperation(async (profile) => {
654
+ await this.write(PAGE.profile, WRITE.liftOffDistance, profile, [encoded[0]]);
655
+ const reply = await (this.deviceBrand() === "LunaFury" ? this.readLunaFury(PROFILE_READ.liftOffDistance(profile)) : this.request(PROFILE_READ.liftOffDistance(profile)));
656
+ const confirmed = this.decodeLiftOffDistance(reply[1]);
657
+ if (confirmed !== value) {
658
+ throw new Error(`The mouse kept a ${String(confirmed).toLowerCase()} lift-off distance instead of ${value.toLowerCase()}.`);
659
+ }
660
+ this.patch({ liftOffDistance: confirmed });
661
+ return confirmed;
662
+ });
361
663
  }
362
664
  async setAngleSnapping(enabled) {
363
665
  return await this.setFlag(WRITE.angleSnapping, PROFILE_READ.angleSnapping, enabled, "angleSnapping", "angle snapping");
@@ -379,40 +681,57 @@ export class LamzuHidClient {
379
681
  async setDongleLed(enabled) {
380
682
  if (!this.profile()?.dongleLed)
381
683
  throw new Error("This receiver has no LED control.");
382
- const profile = await this.currentProfile();
383
- await this.request({
384
- target: TARGET.dongle, page: PAGE.dongle, command: WRITE.dongleLed, length: 0x02, args: [profile, enabled ? 1 : 0],
684
+ return this.profileOperation(async (profile) => {
685
+ await this.request({
686
+ target: TARGET.dongle, page: PAGE.dongle, command: WRITE.dongleLed, length: 0x02, args: [profile, enabled ? 1 : 0],
687
+ });
688
+ const confirmed = (await this.request(PROFILE_READ.dongleLed(profile)))[1] === 1;
689
+ if (confirmed !== enabled)
690
+ throw new Error(`The receiver left its LED ${confirmed ? "on" : "off"}.`);
691
+ this.patch({ dongleLedEnabled: confirmed });
692
+ return confirmed;
385
693
  });
386
- const confirmed = (await this.request(PROFILE_READ.dongleLed(profile)))[1] === 1;
387
- if (confirmed !== enabled)
388
- throw new Error(`The receiver left its LED ${confirmed ? "on" : "off"}.`);
389
- this.patch({ dongleLedEnabled: confirmed });
390
- return confirmed;
391
694
  }
392
695
  async setFlag(command, read, enabled, field, label) {
393
- const profile = await this.currentProfile();
394
- await this.write(PAGE.profile, command, profile, [enabled ? 1 : 0]);
395
- const confirmed = (await this.request(read(profile)))[1] === 1;
396
- if (confirmed !== enabled) {
397
- throw new Error(`The mouse left ${label} ${confirmed ? "on" : "off"}.`);
398
- }
399
- this.patch({ [field]: confirmed });
400
- return confirmed;
696
+ return this.profileOperation(async (profile) => {
697
+ await this.write(PAGE.profile, command, profile, [enabled ? 1 : 0]);
698
+ const reply = await (this.deviceBrand() === "LunaFury" ? this.readLunaFury(read(profile)) : this.request(read(profile)));
699
+ const confirmed = reply[1] === 1;
700
+ if (confirmed !== enabled) {
701
+ throw new Error(`The mouse left ${label} ${confirmed ? "on" : "off"}.`);
702
+ }
703
+ this.patch({ [field]: confirmed });
704
+ return confirmed;
705
+ });
401
706
  }
402
707
  async setDebounceTime(milliseconds) {
403
708
  if (!Number.isInteger(milliseconds) || milliseconds < 0 || milliseconds > DEBOUNCE_MAX_MS) {
404
709
  throw new Error(`Debounce must be a whole number of milliseconds between 0 and ${DEBOUNCE_MAX_MS}.`);
405
710
  }
406
- const profile = await this.currentProfile();
407
- await this.write(PAGE.device, WRITE.debounce, profile, [milliseconds]);
408
- const confirmed = (await this.request(PROFILE_READ.debounce(profile)))[1];
409
- if (confirmed !== milliseconds) {
410
- throw new Error(`The mouse kept ${confirmed} ms of debounce instead of ${milliseconds} ms.`);
411
- }
412
- this.patch({ debounceMs: confirmed });
413
- return confirmed;
711
+ return this.profileOperation(async (profile) => {
712
+ await this.write(PAGE.device, WRITE.debounce, profile, [milliseconds]);
713
+ const reply = await (this.deviceBrand() === "LunaFury" ? this.readLunaFury(PROFILE_READ.debounce(profile)) : this.request(PROFILE_READ.debounce(profile)));
714
+ const confirmed = reply[1];
715
+ if (confirmed !== milliseconds) {
716
+ throw new Error(`The mouse kept ${confirmed} ms of debounce instead of ${milliseconds} ms.`);
717
+ }
718
+ this.patch({ debounceMs: confirmed });
719
+ return confirmed;
720
+ });
414
721
  }
415
722
  async setSleepTimeout(seconds) {
723
+ if (this.deviceBrand() === "LunaFury") {
724
+ const encoded = lunafuryEncodeSleep(seconds);
725
+ return this.onboardOperation(async () => {
726
+ const profile = await this.currentProfile();
727
+ await this.write(PAGE.device, WRITE.sleepTimeout, profile, [encoded >> 8, encoded & 0xff]);
728
+ const confirmed = lunafuryDecodeSleep(await this.readLunaFury(PROFILE_READ.sleepTimeout(profile)));
729
+ if (confirmed !== seconds)
730
+ throw new Error("The mouse did not confirm the sleep timeout.");
731
+ this.patch({ sleepTimeout: confirmed });
732
+ return confirmed;
733
+ });
734
+ }
416
735
  if (!Number.isInteger(seconds) || seconds < 1 || seconds > SLEEP_MAX_SECONDS) {
417
736
  throw new Error(`The sleep timeout must be a whole number of seconds between 1 and ${SLEEP_MAX_SECONDS}.`);
418
737
  }
@@ -427,6 +746,8 @@ export class LamzuHidClient {
427
746
  return confirmed;
428
747
  }
429
748
  async setDpi(dpi, dpiY = dpi) {
749
+ if (this.deviceBrand() === "LunaFury")
750
+ return this.setLunaFuryStageAxes(undefined, dpi, dpiY);
430
751
  const ceiling = this.maxDpi();
431
752
  for (const value of [dpi, dpiY]) {
432
753
  if (!Number.isInteger(value) || value < DPI_STEP || value > ceiling || value % DPI_STEP !== 0) {
@@ -579,6 +900,11 @@ export class LamzuHidClient {
579
900
  }
580
901
  async currentProfile() {
581
902
  const reply = await this.request(READ.activeProfile);
903
+ if (this.deviceBrand() === "LunaFury" && (reply.length < 1 || reply[0] < 1 || reply[0] > 3)) {
904
+ throw new Error("The mouse did not report a valid LunaFury profile.");
905
+ }
906
+ if (this.deviceBrand() === "LunaFury" && this.lastStatus && this.lastStatus.activeProfile !== reply[0])
907
+ this.lastStatus = null;
582
908
  this.activeProfile = Math.max(1, reply[0]);
583
909
  return this.activeProfile;
584
910
  }
@@ -637,8 +963,30 @@ export class LamzuHidClient {
637
963
  return compaxDecodeLiftOff(value);
638
964
  }
639
965
  decodeSleepTimeout(payload) {
966
+ if (this.deviceBrand() === "LunaFury")
967
+ return lunafuryDecodeSleep(payload);
640
968
  return compaxDecodeSleep(payload, SLEEP_DISABLED_MIN);
641
969
  }
970
+ readReceiverLight(attempts) {
971
+ return this.request({ ...lunafuryReadReceiverLight(this.device.productId), attempts,
972
+ matchesReply: (payload) => payload.length >= 3 && payload[0] === 1 });
973
+ }
974
+ async setLunaFuryReceiverLightMode(mode) {
975
+ this.requireLunaFury();
976
+ const spec = lunafuryWriteReceiverLight(this.device.productId, mode);
977
+ return this.onboardOperation(async () => {
978
+ // Read before writing: unsupported firmware must not receive a light write.
979
+ if (lunafuryDecodeReceiverLight(await this.readReceiverLight()) === undefined) {
980
+ throw new Error("The receiver did not report a supported light mode.");
981
+ }
982
+ await this.request(spec);
983
+ const confirmed = lunafuryDecodeReceiverLight(await this.readReceiverLight());
984
+ if (confirmed !== mode)
985
+ throw new Error("The receiver did not confirm the light mode.");
986
+ this.patchLunaFury({ receiverLightMode: confirmed });
987
+ return confirmed;
988
+ });
989
+ }
642
990
  decodeFirmware(label, payload) {
643
991
  return compaxDecodeFirmware(label, payload);
644
992
  }