@openmouse/protocol 0.50.0 → 0.51.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 (106) hide show
  1. package/README.md +1 -0
  2. package/dist/amkette/index.d.ts +2 -0
  3. package/dist/amkette/index.d.ts.map +1 -0
  4. package/dist/amkette/index.js +2 -0
  5. package/dist/amkette/index.js.map +1 -0
  6. package/dist/amkette/xs.d.ts +63 -0
  7. package/dist/amkette/xs.d.ts.map +1 -0
  8. package/dist/amkette/xs.js +79 -0
  9. package/dist/amkette/xs.js.map +1 -0
  10. package/dist/corsair/bragi.d.ts +70 -12
  11. package/dist/corsair/bragi.d.ts.map +1 -1
  12. package/dist/corsair/bragi.js +85 -16
  13. package/dist/corsair/bragi.js.map +1 -1
  14. package/dist/drivers/amkette/xs-hid.d.ts +142 -0
  15. package/dist/drivers/amkette/xs-hid.d.ts.map +1 -0
  16. package/dist/drivers/amkette/xs-hid.js +683 -0
  17. package/dist/drivers/amkette/xs-hid.js.map +1 -0
  18. package/dist/drivers/corsair/bragi-hid.d.ts +17 -12
  19. package/dist/drivers/corsair/bragi-hid.d.ts.map +1 -1
  20. package/dist/drivers/corsair/bragi-hid.js +35 -15
  21. package/dist/drivers/corsair/bragi-hid.js.map +1 -1
  22. package/dist/drivers/gwolves/products.d.ts.map +1 -1
  23. package/dist/drivers/gwolves/products.js +3 -0
  24. package/dist/drivers/gwolves/products.js.map +1 -1
  25. package/dist/drivers/incott/hid.d.ts +5 -0
  26. package/dist/drivers/incott/hid.d.ts.map +1 -1
  27. package/dist/drivers/incott/hid.js +18 -7
  28. package/dist/drivers/incott/hid.js.map +1 -1
  29. package/dist/drivers/lamzu/hid.d.ts +4 -0
  30. package/dist/drivers/lamzu/hid.d.ts.map +1 -1
  31. package/dist/drivers/lamzu/hid.js +41 -2
  32. package/dist/drivers/lamzu/hid.js.map +1 -1
  33. package/dist/drivers/lamzu-atlantis/hid.d.ts.map +1 -1
  34. package/dist/drivers/lamzu-atlantis/hid.js +2 -3
  35. package/dist/drivers/lamzu-atlantis/hid.js.map +1 -1
  36. package/dist/drivers/logitech/hidpp.d.ts +2 -0
  37. package/dist/drivers/logitech/hidpp.d.ts.map +1 -1
  38. package/dist/drivers/logitech/hidpp.js +28 -13
  39. package/dist/drivers/logitech/hidpp.js.map +1 -1
  40. package/dist/drivers/mchose/hid.d.ts +9 -0
  41. package/dist/drivers/mchose/hid.d.ts.map +1 -1
  42. package/dist/drivers/mchose/hid.js +36 -5
  43. package/dist/drivers/mchose/hid.js.map +1 -1
  44. package/dist/drivers/mouse-types.d.ts +1 -1
  45. package/dist/drivers/mouse-types.d.ts.map +1 -1
  46. package/dist/drivers/ninjutso/hid.d.ts +1 -0
  47. package/dist/drivers/ninjutso/hid.d.ts.map +1 -1
  48. package/dist/drivers/ninjutso/hid.js +18 -11
  49. package/dist/drivers/ninjutso/hid.js.map +1 -1
  50. package/dist/drivers/pulsar/pulsar-hid.js +1 -1
  51. package/dist/drivers/pulsar/pulsar-hid.js.map +1 -1
  52. package/dist/drivers/registry.d.ts +2 -1
  53. package/dist/drivers/registry.d.ts.map +1 -1
  54. package/dist/drivers/registry.js +6 -0
  55. package/dist/drivers/registry.js.map +1 -1
  56. package/dist/drivers/ryunix/kyu-pro-mx1-hid.d.ts.map +1 -1
  57. package/dist/drivers/ryunix/kyu-pro-mx1-hid.js +4 -1
  58. package/dist/drivers/ryunix/kyu-pro-mx1-hid.js.map +1 -1
  59. package/dist/drivers/scyrox/hid.d.ts +5 -0
  60. package/dist/drivers/scyrox/hid.d.ts.map +1 -1
  61. package/dist/drivers/scyrox/hid.js +5 -0
  62. package/dist/drivers/scyrox/hid.js.map +1 -1
  63. package/dist/drivers/vendors.d.ts +7 -2
  64. package/dist/drivers/vendors.d.ts.map +1 -1
  65. package/dist/drivers/vendors.js +35 -9
  66. package/dist/drivers/vendors.js.map +1 -1
  67. package/dist/incott/index.d.ts +33 -8
  68. package/dist/incott/index.d.ts.map +1 -1
  69. package/dist/incott/index.js +44 -11
  70. package/dist/incott/index.js.map +1 -1
  71. package/dist/index.d.ts +1 -0
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +1 -0
  74. package/dist/index.js.map +1 -1
  75. package/dist/lamzu/atlantis.d.ts +18 -9
  76. package/dist/lamzu/atlantis.d.ts.map +1 -1
  77. package/dist/lamzu/atlantis.js +21 -6
  78. package/dist/lamzu/atlantis.js.map +1 -1
  79. package/dist/lamzu/index.d.ts +8 -5
  80. package/dist/lamzu/index.d.ts.map +1 -1
  81. package/dist/lamzu/index.js +10 -5
  82. package/dist/lamzu/index.js.map +1 -1
  83. package/dist/mchose/index.d.ts +14 -0
  84. package/dist/mchose/index.d.ts.map +1 -1
  85. package/dist/mchose/index.js +25 -2
  86. package/dist/mchose/index.js.map +1 -1
  87. package/dist/ninjutso/index.d.ts.map +1 -1
  88. package/dist/ninjutso/index.js +5 -2
  89. package/dist/ninjutso/index.js.map +1 -1
  90. package/dist/ryunix/index.d.ts +1 -0
  91. package/dist/ryunix/index.d.ts.map +1 -1
  92. package/dist/ryunix/index.js +1 -0
  93. package/dist/ryunix/index.js.map +1 -1
  94. package/dist/ryunix/kyu-pro-mx1.d.ts +10 -1
  95. package/dist/ryunix/kyu-pro-mx1.d.ts.map +1 -1
  96. package/dist/ryunix/kyu-pro-mx1.js +10 -12
  97. package/dist/ryunix/kyu-pro-mx1.js.map +1 -1
  98. package/dist/ryunix/protocol.d.ts +204 -0
  99. package/dist/ryunix/protocol.d.ts.map +1 -0
  100. package/dist/ryunix/protocol.js +366 -0
  101. package/dist/ryunix/protocol.js.map +1 -0
  102. package/dist/scyrox/index.d.ts +5 -0
  103. package/dist/scyrox/index.d.ts.map +1 -1
  104. package/dist/scyrox/index.js +37 -1
  105. package/dist/scyrox/index.js.map +1 -1
  106. package/package.json +6 -1
@@ -0,0 +1,683 @@
1
+ import { decodeKyuProMx1Telemetry, RYUNIX_BRIGHTNESS_LEVELS, RYUNIX_BUTTON_ACTIONS, RYUNIX_BUTTON_FACTORY_CODES, RYUNIX_BUTTON_POSITIONS, RYUNIX_BUTTON_SLOTS, RYUNIX_COMMAND_REPORT_ID, RYUNIX_CONFIG_REPORT_ID, RYUNIX_DEFAULT_DPI_COLORS, RYUNIX_DPI_MAX_STAGES, RYUNIX_DPI_MIN, RYUNIX_DPI_STEP, RYUNIX_LIFT_OFF_MM, RYUNIX_LIGHTING_SCHEMES, RYUNIX_SLEEP_MAX_MINUTES, RYUNIX_SLEEP_MIN_MINUTES, RYUNIX_SPEED_LEVELS, RYUNIX_USAGE, RYUNIX_USAGE_PAGE, RYUNIX_VENDOR_ID, RYUNIX_WIRELESS_PRODUCT_ID, ryunixAckOk, ryunixButtonActionName, ryunixClampDpi, ryunixDefaultDpiStages, ryunixNextSequence, ryunixParseColor, ryunixSensor, ryunixSetButtonsFrames, ryunixSetDpiColorsFrame, ryunixSetDpiFrame, ryunixSetLiftOffFrame, ryunixSetLightingFrame, ryunixSetPollingRateFrame, ryunixSetPowerFrame, ryunixSetSensorOptionsFrame, ryunixSupportedPollingRates, } from "@openmouse/protocol/ryunix";
2
+ import { AMKETTE_XS_BLUETOOTH_PRODUCT_ID, AMKETTE_XS_FALLBACK_NAME, AMKETTE_XS_PRODUCT_IDS, AMKETTE_XS_USAGE, amketteBluetoothSlot, amketteIsReceiverName, amketteXsModel, } from "@openmouse/protocol/amkette";
3
+ const COMMAND_ATTEMPTS = 3;
4
+ /**
5
+ * Waits before each acknowledgement read of one attempt (cumulative 60, 150, 300
6
+ * and 600 ms). Over the 2.4 GHz receiver the acknowledgement was seen reading 0
7
+ * at 60 ms and 1 by 150 ms, so one early read would re-send a command that had
8
+ * landed.
9
+ */
10
+ const ACK_POLL_DELAYS_MS = [60, 90, 150, 300];
11
+ const DPI_AXIS_GAP_MS = 200;
12
+ /** How long a status read waits for the report it asked for. */
13
+ const STATUS_WAIT_MS = 300;
14
+ /** Fresh-status polls after a write; the mouse reports on request, not on change. */
15
+ const CONFIRM_POLLS = 4;
16
+ const CONFIRM_POLL_MS = 400;
17
+ /** Brightness levels 1-4 as the percentages shown in the UI. */
18
+ const BRIGHTNESS_PERCENT = [25, 50, 75, 100];
19
+ /**
20
+ * The XS Flow 2 Speed's three effects (scheme 1). Other schemes are not offered:
21
+ * the XS Natural Plus has none (scheme 4), and the XS Flow Plus's seven
22
+ * (scheme 3) have not been mapped or checked, so it keeps this subset.
23
+ */
24
+ const BASIC_EFFECT_CODES = RYUNIX_LIGHTING_SCHEMES[1];
25
+ const LIGHTING_MODE_NAMES = {
26
+ 0: "Off",
27
+ 2: "Breathing single",
28
+ 3: "Static",
29
+ };
30
+ const LIFT_OFF_LEVEL_MM = { Low: 1, High: 2 };
31
+ /** What the vendor app assumes before anything is written; the mouse cannot confirm them. */
32
+ const VENDOR_DEFAULTS = {
33
+ liftOffMm: 2,
34
+ sleepMinutes: 1,
35
+ angleSnapping: false,
36
+ motionSync: true,
37
+ rippleControl: false,
38
+ };
39
+ const claimsByProduct = new Map();
40
+ /** Handles WebHID has reported disconnected; their state can pass to a replugged mouse. */
41
+ const disconnected = new WeakSet();
42
+ let watchedHid = null;
43
+ function watchDisconnects() {
44
+ const hid = globalThis.navigator?.hid;
45
+ if (!hid || hid === watchedHid)
46
+ return;
47
+ watchedHid = hid;
48
+ hid.addEventListener("disconnect", (event) => disconnected.add(event.device));
49
+ }
50
+ /**
51
+ * The state for this handle. WebHID hands a replugged mouse over as a new
52
+ * HIDDevice, so a new handle takes over the state of a same-product handle that
53
+ * has disconnected, keeping the session's DPI table across the replug. Any
54
+ * other new handle starts fresh: two identical mice connected together, or
55
+ * switched between, never share settings. Two that are both unplugged and
56
+ * replugged may swap, since nothing tells them apart.
57
+ */
58
+ function stateFor(device) {
59
+ watchDisconnects();
60
+ let claims = claimsByProduct.get(device.productId);
61
+ if (!claims)
62
+ claimsByProduct.set(device.productId, claims = []);
63
+ let claim = claims.find((entry) => entry.device === device)
64
+ ?? claims.find((entry) => disconnected.has(entry.device));
65
+ if (claim) {
66
+ claim.device = device;
67
+ }
68
+ else {
69
+ claim = {
70
+ device,
71
+ state: {
72
+ dpiStages: null,
73
+ dpiColors: [...RYUNIX_DEFAULT_DPI_COLORS],
74
+ liftOffMm: null,
75
+ sleepMinutes: null,
76
+ angleSnapping: null,
77
+ motionSync: null,
78
+ rippleControl: null,
79
+ buttons: new Array(RYUNIX_BUTTON_POSITIONS).fill(null),
80
+ brightness: 4,
81
+ speed: 3,
82
+ },
83
+ };
84
+ claims.push(claim);
85
+ }
86
+ return claim.state;
87
+ }
88
+ /**
89
+ * One command queue per handle, shared by every client on it: write-only state
90
+ * is per handle, and the acknowledgement carries no sequence number, so two
91
+ * clients' commands must not interleave.
92
+ */
93
+ const queues = new WeakMap();
94
+ /** Forget what this session wrote, e.g. between tests. */
95
+ export function resetAmketteXsWriteState(productId) {
96
+ if (productId === undefined)
97
+ claimsByProduct.clear();
98
+ else
99
+ claimsByProduct.delete(productId);
100
+ }
101
+ function hasCollection(collections, usage, featureReport) {
102
+ return collections.some((collection) => collection.usagePage === RYUNIX_USAGE_PAGE
103
+ && collection.usage === usage
104
+ && (featureReport === undefined || collection.featureReports.some((report) => report.reportId === featureReport))
105
+ || hasCollection(collection.children, usage, featureReport));
106
+ }
107
+ /** True when the product string names an Amkette XS model; never inferred from IDs. */
108
+ export function isAmketteDevice(device) {
109
+ return amketteXsModel(device.productName) !== null;
110
+ }
111
+ /** 0 discharging, 1 charging; a wired mouse at 100% sends 2, read as full. */
112
+ function batteryState(telemetry) {
113
+ if (!telemetry)
114
+ return "Unknown";
115
+ switch (telemetry.batteryStatusCode) {
116
+ case 0: return "Discharging";
117
+ case 1: return "Charging";
118
+ case 2: return telemetry.batteryPercent === 100 ? "Full" : "Unknown";
119
+ default: return "Unknown";
120
+ }
121
+ }
122
+ function delay(ms) {
123
+ return new Promise((resolve) => setTimeout(resolve, ms));
124
+ }
125
+ function bytesOf(view) {
126
+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
127
+ }
128
+ /**
129
+ * The Amkette XS firmware on 0x04F3, which shares its IDs and wire protocol with
130
+ * the Ryunix Kyu Pro MX1 (see `docs/amkette-xs-flow-testing.md`). It is told
131
+ * apart by its configuration collection on usage 0x00, seen on all three paths
132
+ * of an XS Flow 2 Speed; the Kyu Pro MX1 (usage 0xC7) keeps its own read-only
133
+ * driver.
134
+ */
135
+ export class AmketteXsHidClient {
136
+ device;
137
+ telemetry = null;
138
+ /** Counts decoded status reports, so a read can wait for one it asked for. */
139
+ telemetryCount = 0;
140
+ /** `open()` has asked for a report that no status read has waited for yet. */
141
+ openRequestPending = false;
142
+ listening = false;
143
+ sequence = 0;
144
+ telemetryWaiters = [];
145
+ onChange = null;
146
+ constructor(device) {
147
+ this.device = device;
148
+ }
149
+ static isSupported(device) {
150
+ return device.vendorId === RYUNIX_VENDOR_ID
151
+ && AMKETTE_XS_PRODUCT_IDS.has(device.productId)
152
+ && hasCollection(device.collections, AMKETTE_XS_USAGE, RYUNIX_CONFIG_REPORT_ID)
153
+ && !hasCollection(device.collections, RYUNIX_USAGE);
154
+ }
155
+ onInputReport = (event) => {
156
+ const bytes = new Uint8Array(event.data.buffer, event.data.byteOffset, event.data.byteLength);
157
+ const telemetry = decodeKyuProMx1Telemetry(bytes, event.reportId);
158
+ if (!telemetry)
159
+ return;
160
+ this.telemetry = telemetry;
161
+ this.telemetryCount += 1;
162
+ const waiters = this.telemetryWaiters;
163
+ this.telemetryWaiters = [];
164
+ for (const wake of waiters)
165
+ wake();
166
+ this.onChange?.();
167
+ };
168
+ async open() {
169
+ if (!AmketteXsHidClient.isSupported(this.device)) {
170
+ throw new Error("The mouse's configuration collection is unavailable.");
171
+ }
172
+ if (!this.device.opened)
173
+ await this.device.open();
174
+ if (!this.listening) {
175
+ this.device.addEventListener("inputreport", this.onInputReport);
176
+ this.listening = true;
177
+ this.openRequestPending = true;
178
+ await this.requestTelemetry();
179
+ }
180
+ }
181
+ /**
182
+ * Runs after the commands already queued, so a pending write finishes all its
183
+ * frames rather than reopening the mouse once it is closed.
184
+ */
185
+ close() {
186
+ return this.enqueue(async () => {
187
+ if (this.listening) {
188
+ this.device.removeEventListener("inputreport", this.onInputReport);
189
+ this.listening = false;
190
+ }
191
+ this.telemetry = null;
192
+ this.openRequestPending = false;
193
+ this.onChange = null;
194
+ if (this.device.opened)
195
+ await this.device.close();
196
+ });
197
+ }
198
+ /**
199
+ * The mouse sends status only when asked (feature report 0x05), not when it
200
+ * changes, so there is nothing to subscribe to: callers keep polling
201
+ * `readStatus`, which asks for a fresh report each time. The callback still
202
+ * fires on any report that does arrive.
203
+ */
204
+ async startNotifications(onChange) {
205
+ await this.open();
206
+ this.onChange = onChange ?? null;
207
+ return false;
208
+ }
209
+ /**
210
+ * Always Amkette: the driver is chosen by the usage-0x00 collection, which has
211
+ * only been seen on an Amkette mouse, so the brand follows the same evidence.
212
+ * The product name only refines the model.
213
+ */
214
+ deviceBrand() {
215
+ return "Amkette";
216
+ }
217
+ displayName() {
218
+ const model = amketteXsModel(this.device.productName);
219
+ if (model)
220
+ return model.name;
221
+ // A receiver's generic string names the dongle, not the mouse, so it is not shown.
222
+ const name = this.device.productName?.trim();
223
+ return name && !amketteIsReceiverName(name) ? name : AMKETTE_XS_FALLBACK_NAME;
224
+ }
225
+ isBluetooth() {
226
+ return this.device.productId === AMKETTE_XS_BLUETOOTH_PRODUCT_ID;
227
+ }
228
+ isWireless() {
229
+ return this.device.productId === RYUNIX_WIRELESS_PRODUCT_ID || this.isBluetooth();
230
+ }
231
+ /** Bluetooth shows its slot when the advertised name carries one. */
232
+ connectionDetail() {
233
+ if (this.isBluetooth()) {
234
+ const slot = amketteBluetoothSlot(this.device.productName);
235
+ return slot === null ? "Bluetooth" : `Bluetooth, slot ${slot}`;
236
+ }
237
+ return this.isWireless() ? "2.4 GHz receiver" : "USB";
238
+ }
239
+ getDpiOptions() {
240
+ return [];
241
+ }
242
+ /** Auto-sleep choices in seconds: whole minutes from 1 to 15. */
243
+ getSleepOptions() {
244
+ const options = [];
245
+ for (let minutes = RYUNIX_SLEEP_MIN_MINUTES; minutes <= RYUNIX_SLEEP_MAX_MINUTES; minutes++)
246
+ options.push(minutes * 60);
247
+ return options;
248
+ }
249
+ getSupportedPollingRates() {
250
+ return ryunixSupportedPollingRates(this.telemetry?.maxPollingCode ?? null);
251
+ }
252
+ /** Effects the detected model offers; an unidentified mouse gets the basic set. */
253
+ lightingEffects() {
254
+ return amketteXsModel(this.device.productName)?.lightingScheme === 4 ? [] : BASIC_EFFECT_CODES;
255
+ }
256
+ /** Reading feature report 0x05 makes the mouse emit an input report 0x04. */
257
+ async requestTelemetry() {
258
+ try {
259
+ await this.device.receiveFeatureReport(RYUNIX_CONFIG_REPORT_ID);
260
+ }
261
+ catch {
262
+ // A failed read leaves the last report in place; the next read asks again.
263
+ }
264
+ }
265
+ waitForTelemetry(accept, timeoutMs) {
266
+ return new Promise((resolve) => {
267
+ let settled = false;
268
+ const finish = (value) => {
269
+ if (settled)
270
+ return;
271
+ settled = true;
272
+ this.telemetryWaiters = this.telemetryWaiters.filter((waiter) => waiter !== check);
273
+ clearTimeout(timer);
274
+ resolve(value);
275
+ };
276
+ const check = () => {
277
+ if (settled)
278
+ return;
279
+ if (this.telemetry && accept(this.telemetry))
280
+ finish(this.telemetry);
281
+ else
282
+ this.telemetryWaiters.push(check);
283
+ };
284
+ const timer = setTimeout(() => finish(null), timeoutMs);
285
+ check();
286
+ });
287
+ }
288
+ /**
289
+ * Ask for a status report and wait briefly for it, keeping the last one if
290
+ * none comes. Right after `open()` the report it asked for is awaited instead
291
+ * of asking again.
292
+ */
293
+ async refreshTelemetry() {
294
+ if (this.openRequestPending) {
295
+ this.openRequestPending = false;
296
+ await this.waitForTelemetry(() => this.telemetryCount > 0, STATUS_WAIT_MS);
297
+ return;
298
+ }
299
+ const before = this.telemetryCount;
300
+ await this.requestTelemetry();
301
+ await this.waitForTelemetry(() => this.telemetryCount > before, STATUS_WAIT_MS);
302
+ }
303
+ /**
304
+ * The mouse only sends status when asked, so a write is judged against a
305
+ * report requested after it. Returns the matching report, or null if none of
306
+ * the polls matched.
307
+ */
308
+ async confirmByTelemetry(accept) {
309
+ for (let poll = 0; poll < CONFIRM_POLLS; poll++) {
310
+ const before = this.telemetryCount;
311
+ await this.requestTelemetry();
312
+ const match = await this.waitForTelemetry((telemetry) => this.telemetryCount > before && accept(telemetry), CONFIRM_POLL_MS);
313
+ if (match)
314
+ return match;
315
+ }
316
+ return null;
317
+ }
318
+ enqueue(action) {
319
+ const run = (queues.get(this.device) ?? Promise.resolve()).then(action);
320
+ queues.set(this.device, run.catch(() => undefined));
321
+ return run;
322
+ }
323
+ nextSequence() {
324
+ this.sequence = ryunixNextSequence(this.sequence);
325
+ return this.sequence;
326
+ }
327
+ /** Send one frame on report 0x06 and require the mouse to acknowledge it. */
328
+ async sendFrame(frame) {
329
+ let lastError = null;
330
+ for (let attempt = 0; attempt < COMMAND_ATTEMPTS; attempt++) {
331
+ await delay(100 + attempt * 50);
332
+ try {
333
+ await this.device.sendFeatureReport(RYUNIX_COMMAND_REPORT_ID, new Uint8Array(frame));
334
+ for (const wait of ACK_POLL_DELAYS_MS) {
335
+ await delay(wait);
336
+ const ack = await this.device.receiveFeatureReport(RYUNIX_COMMAND_REPORT_ID);
337
+ if (ryunixAckOk(bytesOf(ack)))
338
+ return;
339
+ }
340
+ lastError = new Error("The mouse did not acknowledge the command.");
341
+ }
342
+ catch (error) {
343
+ lastError = error;
344
+ }
345
+ }
346
+ throw lastError instanceof Error ? lastError : new Error("The mouse did not acknowledge the command.");
347
+ }
348
+ /**
349
+ * Send frames and, when `accept` is given, judge the write against fresh
350
+ * status, all inside the command queue so another setter's frames cannot land
351
+ * between the write and its confirmation. Throws when a report requested
352
+ * after the write shows a value other than the one written; with no fresh
353
+ * report, the write is judged by its acknowledgement alone.
354
+ */
355
+ send(build, confirm) {
356
+ return this.enqueue(() => this.transmit(build, confirm));
357
+ }
358
+ /**
359
+ * `send` without the queue, for setters that read and update write-only state
360
+ * inside their own queued transaction, so concurrent setters build on each
361
+ * other's writes rather than on the state before either.
362
+ */
363
+ async transmit(build, confirm) {
364
+ await this.open();
365
+ const frames = build(() => this.nextSequence());
366
+ for (const [index, frame] of (Array.isArray(frames) ? frames : [frames]).entries()) {
367
+ if (index > 0)
368
+ await delay(DPI_AXIS_GAP_MS);
369
+ await this.sendFrame(frame);
370
+ }
371
+ if (!confirm)
372
+ return;
373
+ const before = this.telemetryCount;
374
+ const confirmed = await this.confirmByTelemetry(confirm.accept);
375
+ if (!confirmed && this.telemetryCount > before && this.telemetry && !confirm.accept(this.telemetry)) {
376
+ throw new Error(confirm.mismatch(this.telemetry));
377
+ }
378
+ }
379
+ /**
380
+ * DPI values are encoded per sensor (50 or 100 counts per step), so a write
381
+ * waits for the mouse to report which sensor it has rather than assume one.
382
+ */
383
+ requireSensor() {
384
+ const sensorType = this.telemetry?.sensorType ?? null;
385
+ if (sensorType === null) {
386
+ throw new Error("The mouse has not reported its sensor yet, so DPI cannot be written safely.");
387
+ }
388
+ return ryunixSensor(sensorType);
389
+ }
390
+ /** The vendor app seeds a table the first time, since the mouse never reports one. */
391
+ tableFor(state) {
392
+ return state.dpiStages ? [...state.dpiStages] : ryunixDefaultDpiStages(ryunixSensor(this.telemetry?.sensorType ?? null));
393
+ }
394
+ /**
395
+ * Opens the mouse and, until it has reported, waits for the report that names
396
+ * its sensor, which DPI values depend on. Runs inside a queued transaction.
397
+ */
398
+ async awaitSensorReport() {
399
+ await this.open();
400
+ if (!this.telemetry)
401
+ await this.refreshTelemetry();
402
+ }
403
+ /** Runs inside a queued transaction. */
404
+ async writeDpiTable(stages, activeStage, confirm) {
405
+ const sensor = this.requireSensor();
406
+ const state = stateFor(this.device);
407
+ const table = { stages, activeStage };
408
+ await this.transmit((sequence) => [
409
+ ryunixSetDpiFrame(sequence(), table, sensor, "x"),
410
+ ryunixSetDpiFrame(sequence(), table, sensor, "y"),
411
+ ryunixSetDpiColorsFrame(sequence(), state.dpiColors),
412
+ ], confirm);
413
+ state.dpiStages = [...stages];
414
+ }
415
+ activeStage(count) {
416
+ const reported = this.telemetry?.dpiStage ?? 0;
417
+ return reported < count ? reported : 0;
418
+ }
419
+ readStatus() {
420
+ return this.enqueue(async () => {
421
+ await this.open();
422
+ await this.refreshTelemetry();
423
+ return this.buildStatus();
424
+ });
425
+ }
426
+ buildStatus() {
427
+ const telemetry = this.telemetry;
428
+ const state = stateFor(this.device);
429
+ const sensor = ryunixSensor(telemetry?.sensorType ?? null);
430
+ const wireless = this.isWireless();
431
+ // Until a table is written the mouse's own stages are unknown; the vendor's
432
+ // defaults are shown so the editor has rows, and the note below says so.
433
+ const stages = this.tableFor(state);
434
+ const activeStage = this.activeStage(stages.length);
435
+ const effects = this.lightingEffects();
436
+ const mode = telemetry ? LIGHTING_MODE_NAMES[telemetry.ledModeCode] ?? null : null;
437
+ const lighting = telemetry && effects.length > 0 ? {
438
+ zone: "Mouse",
439
+ modes: effects.map((code) => LIGHTING_MODE_NAMES[code]),
440
+ mode,
441
+ // No effect has its own colour: Breathe takes the active DPI stage's colour.
442
+ color: null,
443
+ color2: null,
444
+ colorModes: [],
445
+ dualColorModes: [],
446
+ reactiveModes: ["Breathing single"],
447
+ speeds: [...RYUNIX_SPEED_LEVELS],
448
+ speed: state.speed,
449
+ brightness: BRIGHTNESS_PERCENT[state.brightness - 1] ?? 100,
450
+ brightnessLevels: [...BRIGHTNESS_PERCENT],
451
+ } : undefined;
452
+ const buttonMappings = {};
453
+ for (const [index, slot] of RYUNIX_BUTTON_SLOTS.entries()) {
454
+ const code = state.buttons[index];
455
+ buttonMappings[slot.name] = (code ? ryunixButtonActionName(code) : null) ?? slot.factory;
456
+ }
457
+ const liftOffMm = state.liftOffMm ?? VENDOR_DEFAULTS.liftOffMm;
458
+ const liftOff = Object.entries(LIFT_OFF_LEVEL_MM).find(([, mm]) => mm === liftOffMm)?.[0] ?? null;
459
+ return {
460
+ brand: this.deviceBrand(),
461
+ name: this.displayName(),
462
+ ui: {
463
+ family: "amkette-xs",
464
+ settingsReady: true,
465
+ // Polling and the active stage are read, but DPI values never are.
466
+ valuesVerified: false,
467
+ hideUnsupportedPollingRates: true,
468
+ hideSignalCard: true,
469
+ forceShowBattery: true,
470
+ showAdvancedSection: true,
471
+ defaultDisplayName: AMKETTE_XS_FALLBACK_NAME,
472
+ statusNote: "This mouse reports battery, active DPI stage, polling rate and lighting mode. DPI values, lift-off, sleep, processing options and buttons cannot be read back: they show what OpenMouse last wrote, and the vendor app's defaults until then. Choosing a stage or changing a DPI value writes the whole stage table as shown here, replacing stages stored on the mouse by another tool.",
473
+ dpiStageEditor: {
474
+ maxStages: RYUNIX_DPI_MAX_STAGES,
475
+ countEditable: true,
476
+ minDpi: RYUNIX_DPI_MIN,
477
+ maxDpi: sensor.maxDpi,
478
+ stepDpi: RYUNIX_DPI_STEP,
479
+ },
480
+ },
481
+ batteryPercent: telemetry?.batteryPercent ?? null,
482
+ batteryState: batteryState(telemetry),
483
+ dpi: stages[activeStage] ?? 0,
484
+ dpiStages: [...stages],
485
+ activeDpiStage: activeStage,
486
+ dpiStageColors: state.dpiColors.slice(0, stages.length),
487
+ pollingRateHz: telemetry?.pollingRateHz ?? 0,
488
+ supportedPollingRates: this.getSupportedPollingRates(),
489
+ activeProfile: null,
490
+ connectionType: wireless ? "Wireless" : "Wired",
491
+ connectionDetail: this.connectionDetail(),
492
+ liftOffDistance: liftOff,
493
+ supportedLiftOffDistances: ["Low", "High"],
494
+ sleepTimeout: (state.sleepMinutes ?? VENDOR_DEFAULTS.sleepMinutes) * 60,
495
+ angleSnapping: state.angleSnapping ?? VENDOR_DEFAULTS.angleSnapping,
496
+ motionSync: state.motionSync ?? VENDOR_DEFAULTS.motionSync,
497
+ rippleControl: state.rippleControl ?? VENDOR_DEFAULTS.rippleControl,
498
+ buttonMappings,
499
+ buttonOptions: [...RYUNIX_BUTTON_ACTIONS.keys()],
500
+ ...(lighting ? { lighting } : {}),
501
+ firmware: [],
502
+ };
503
+ }
504
+ async setPollingRate(pollingRateHz) {
505
+ if (!this.getSupportedPollingRates().includes(pollingRateHz)) {
506
+ throw new Error(`This mouse does not offer ${pollingRateHz} Hz.`);
507
+ }
508
+ await this.send((sequence) => ryunixSetPollingRateFrame(sequence(), pollingRateHz), {
509
+ accept: (value) => value.pollingRateHz === pollingRateHz,
510
+ mismatch: (value) => `The mouse still reports ${value.pollingRateHz} Hz after the change.`,
511
+ });
512
+ return pollingRateHz;
513
+ }
514
+ setDpi(dpi) {
515
+ return this.enqueue(async () => {
516
+ await this.awaitSensorReport();
517
+ const stages = this.tableFor(stateFor(this.device));
518
+ return this.writeStageValue(stages, this.activeStage(stages.length), dpi);
519
+ });
520
+ }
521
+ setDpiStageValue(stage, dpi) {
522
+ return this.enqueue(async () => {
523
+ await this.awaitSensorReport();
524
+ return this.writeStageValue(this.tableFor(stateFor(this.device)), stage, dpi);
525
+ });
526
+ }
527
+ /** Runs inside a queued transaction. */
528
+ async writeStageValue(stages, stage, dpi) {
529
+ if (!Number.isInteger(stage) || stage < 0 || stage >= stages.length) {
530
+ throw new RangeError(`Invalid DPI stage ${stage + 1}.`);
531
+ }
532
+ const value = ryunixClampDpi(dpi, this.requireSensor());
533
+ stages[stage] = value;
534
+ await this.writeDpiTable(stages, this.activeStage(stages.length));
535
+ return value;
536
+ }
537
+ /**
538
+ * The mouse selects a stage only through a full table write, so this writes
539
+ * the table OpenMouse shows (the vendor's defaults until something else has
540
+ * been written this session) with the chosen stage active, as Amkette's own
541
+ * configurator does on every stage click. Stages stored on the mouse by
542
+ * another tool are replaced by the shown values.
543
+ */
544
+ setActiveDpiStage(stage) {
545
+ return this.enqueue(async () => {
546
+ await this.awaitSensorReport();
547
+ const stages = this.tableFor(stateFor(this.device));
548
+ if (!Number.isInteger(stage) || stage < 0 || stage >= stages.length) {
549
+ throw new RangeError(`Invalid DPI stage ${stage + 1}.`);
550
+ }
551
+ await this.writeDpiTable(stages, stage, {
552
+ accept: (value) => value.dpiStage === stage,
553
+ mismatch: (value) => `The mouse still reports DPI stage ${value.dpiStage + 1} after the change.`,
554
+ });
555
+ return stage;
556
+ });
557
+ }
558
+ async setDpiStageCount(count) {
559
+ if (!Number.isInteger(count) || count < 1 || count > RYUNIX_DPI_MAX_STAGES) {
560
+ throw new RangeError(`A DPI table needs 1 to ${RYUNIX_DPI_MAX_STAGES} stages.`);
561
+ }
562
+ return this.enqueue(async () => {
563
+ await this.awaitSensorReport();
564
+ const sensor = this.requireSensor();
565
+ const current = this.tableFor(stateFor(this.device));
566
+ const stages = ryunixDefaultDpiStages(sensor, RYUNIX_DPI_MAX_STAGES)
567
+ .map((fallback, index) => current[index] ?? fallback)
568
+ .slice(0, count);
569
+ await this.writeDpiTable(stages, this.activeStage(stages.length));
570
+ return count;
571
+ });
572
+ }
573
+ async setDpiStageColor(index, color) {
574
+ ryunixParseColor(color);
575
+ if (!Number.isInteger(index) || index < 0 || index >= RYUNIX_DPI_MAX_STAGES) {
576
+ throw new RangeError(`Invalid DPI stage ${index + 1}.`);
577
+ }
578
+ return this.enqueue(async () => {
579
+ const state = stateFor(this.device);
580
+ const colors = [...state.dpiColors];
581
+ colors[index] = color.toLowerCase();
582
+ await this.transmit((sequence) => ryunixSetDpiColorsFrame(sequence(), colors));
583
+ state.dpiColors = colors;
584
+ return colors[index];
585
+ });
586
+ }
587
+ async setLiftOffDistance(level) {
588
+ const millimetres = LIFT_OFF_LEVEL_MM[level];
589
+ if (millimetres === undefined || !RYUNIX_LIFT_OFF_MM.includes(millimetres)) {
590
+ throw new Error(`This mouse offers Low and High lift-off, not ${level}.`);
591
+ }
592
+ await this.send((sequence) => ryunixSetLiftOffFrame(sequence(), millimetres));
593
+ stateFor(this.device).liftOffMm = millimetres;
594
+ return level;
595
+ }
596
+ /** Auto sleep in seconds; the mouse stores whole minutes from 1 to 15. */
597
+ async setSleepTimeout(seconds) {
598
+ const minutes = Math.min(RYUNIX_SLEEP_MAX_MINUTES, Math.max(RYUNIX_SLEEP_MIN_MINUTES, Math.round(seconds / 60)));
599
+ // The vendor app also sends its wake-on-move and light-on-move defaults.
600
+ await this.send((sequence) => ryunixSetPowerFrame(sequence(), {
601
+ sleepMinutes: minutes,
602
+ wakeOnMove: true,
603
+ lightOnMove: false,
604
+ }));
605
+ stateFor(this.device).sleepMinutes = minutes;
606
+ return minutes * 60;
607
+ }
608
+ writeSensorOptions(patch) {
609
+ return this.enqueue(async () => {
610
+ const state = stateFor(this.device);
611
+ // The mouse cannot report these, so unwritten ones take the vendor app's defaults.
612
+ const next = {
613
+ angleSnapping: patch.angleSnapping ?? state.angleSnapping ?? VENDOR_DEFAULTS.angleSnapping,
614
+ motionSync: patch.motionSync ?? state.motionSync ?? VENDOR_DEFAULTS.motionSync,
615
+ rippleControl: patch.rippleControl ?? state.rippleControl ?? VENDOR_DEFAULTS.rippleControl,
616
+ };
617
+ await this.transmit((sequence) => ryunixSetSensorOptionsFrame(sequence(), next));
618
+ Object.assign(state, next);
619
+ });
620
+ }
621
+ async setAngleSnapping(enabled) {
622
+ await this.writeSensorOptions({ angleSnapping: enabled });
623
+ return enabled;
624
+ }
625
+ async setMotionSync(enabled) {
626
+ await this.writeSensorOptions({ motionSync: enabled });
627
+ return enabled;
628
+ }
629
+ async setRippleControl(enabled) {
630
+ await this.writeSensorOptions({ rippleControl: enabled });
631
+ return enabled;
632
+ }
633
+ async setLighting(lighting) {
634
+ const effect = this.lightingEffects().find((code) => LIGHTING_MODE_NAMES[code] === lighting.mode);
635
+ if (effect === undefined || !lighting.mode) {
636
+ throw new Error(`This mouse does not offer the ${lighting.mode ?? "selected"} lighting effect.`);
637
+ }
638
+ const mode = lighting.mode;
639
+ return this.enqueue(async () => {
640
+ const state = stateFor(this.device);
641
+ const level = lighting.brightness == null
642
+ ? state.brightness
643
+ : RYUNIX_BRIGHTNESS_LEVELS[BRIGHTNESS_PERCENT.indexOf(lighting.brightness)];
644
+ if (level === undefined)
645
+ throw new Error(`Brightness ${lighting.brightness}% is not available.`);
646
+ const speed = lighting.speed ?? state.speed;
647
+ if (!RYUNIX_SPEED_LEVELS.includes(speed)) {
648
+ throw new Error(`Lighting speed ${speed} is not available.`);
649
+ }
650
+ await this.transmit((sequence) => ryunixSetLightingFrame(sequence(), { effect, brightness: level, speed }), {
651
+ accept: (value) => value.ledModeCode === effect,
652
+ mismatch: () => "The mouse still reports its previous lighting effect after the change.",
653
+ });
654
+ state.brightness = level;
655
+ state.speed = speed;
656
+ return mode;
657
+ });
658
+ }
659
+ /**
660
+ * `button` is the slot name from `buttonMappings`; `action` one of
661
+ * `buttonOptions`. Every write carries all ten positions; positions not
662
+ * changed in this session are written as the vendor app's default layout, as
663
+ * the vendor app does, rather than 0xFF, whose meaning here is unknown.
664
+ */
665
+ async setButtonMapping(button, action) {
666
+ const index = RYUNIX_BUTTON_SLOTS.findIndex((slot) => slot.name === button);
667
+ if (index < 0)
668
+ throw new Error(`Unknown button "${button}".`);
669
+ const code = RYUNIX_BUTTON_ACTIONS.get(action);
670
+ if (!code)
671
+ throw new Error(`Unknown button action "${action}".`);
672
+ return this.enqueue(async () => {
673
+ const state = stateFor(this.device);
674
+ const changed = [...state.buttons];
675
+ changed[index] = code;
676
+ const positions = RYUNIX_BUTTON_FACTORY_CODES.map((factory, position) => changed[position] ?? factory);
677
+ await this.transmit((sequence) => ryunixSetButtonsFrames([sequence(), sequence()], positions));
678
+ state.buttons = changed;
679
+ return action;
680
+ });
681
+ }
682
+ }
683
+ //# sourceMappingURL=xs-hid.js.map