@openmouse/protocol 0.53.1 → 0.54.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,1042 @@
1
+ import { REDRAGON_M719_PRO_BRIGHTNESS_PERCENTS, REDRAGON_M719_PRO_BUTTONS, REDRAGON_M719_PRO_BUTTON_ACTIONS, REDRAGON_M719_PRO_COMMAND, REDRAGON_M719_PRO_COMMAND_REPORT_ID, REDRAGON_M719_PRO_COMMAND_USAGE_PAGE, REDRAGON_M719_PRO_DPI_MAX, REDRAGON_M719_PRO_DPI_MIN, REDRAGON_M719_PRO_DPI_OPTIONS, REDRAGON_M719_PRO_DPI_STEP, REDRAGON_M719_PRO_EEPROM, REDRAGON_M719_PRO_MAX_CHUNK_LENGTH, REDRAGON_M719_PRO_MAX_DPI_STAGES, REDRAGON_M719_PRO_NOTIFY_REPORT_ID, REDRAGON_M719_PRO_NOTIFY_USAGE_PAGE, REDRAGON_M719_PRO_POLLING_RATES, REDRAGON_M719_PRO_PRODUCTS, REDRAGON_M719_PRO_RESPONSE_REPORT_ID, REDRAGON_M719_PRO_RGB_EFFECT, REDRAGON_M719_PRO_SPEED_LEVELS, REDRAGON_M719_PRO_VENDOR_ID, REDRAGON_M719_PRO_WIRED_PRODUCT_ID, REDRAGON_M719_PRO_WIRELESS_PRODUCT_ID, redragonM719ProDecodeBattery, redragonM719ProDecodeButtonAction, redragonM719ProDecodeConnectStatus, redragonM719ProDecodeDpiLedEffect, redragonM719ProDecodeDpiStage, redragonM719ProDecodeDpiStageColor, redragonM719ProDecodeDpiStageColors, redragonM719ProDecodeDpiStages, redragonM719ProDecodeHardwareNotification, redragonM719ProDecodePollingRate, redragonM719ProDecodeReadEeprom, redragonM719ProDecodeRgbLighting, redragonM719ProDecodeWriteEeprom, redragonM719ProEncodeButtonAction, redragonM719ProEncodeDpiLedEffect, redragonM719ProEncodeDpiStage, redragonM719ProEncodeDpiStageColor, redragonM719ProEncodeGetBattery, redragonM719ProEncodeGetConnectStatus, redragonM719ProEncodeHandshake, redragonM719ProEncodePollingRate, redragonM719ProEncodeReadEeprom, redragonM719ProEncodeRgbLighting, redragonM719ProEncodeTellDriverStatus, redragonM719ProEncodeWriteEeprom, redragonM719ProNearestDpi, redragonM719ProNormalizeReply, redragonM719ProPackScalar, redragonM719ProUnpackScalar, redragonM719ProVerifyDataChecksum, redragonM719ProVerifyHandshakeReply, redragonM719ProVerifyPacketChecksum, } from "@openmouse/protocol/redragon";
2
+ const DISPLAY_NAME = "Redragon M719RGB-PRO";
3
+ const COMMAND_TIMEOUT_MS = 900;
4
+ const WRITE_RETRY_LIMIT = 4;
5
+ const WRITE_SETTLE_DELAY_MS = 15;
6
+ const OFFLINE_NOTE = "The mouse is off or asleep. Wake it or switch it on to read and change its settings.";
7
+ const MAIN_LIGHTING_MODES = [
8
+ "Static",
9
+ "Breathing single",
10
+ "Neon",
11
+ "Off",
12
+ ];
13
+ const MAIN_COLOR_MODES = ["Static", "Breathing single"];
14
+ const MAIN_REACTIVE_MODES = ["Breathing single", "Neon"];
15
+ const DPI_INDICATOR_MODES = [
16
+ "Static",
17
+ "Breathing single",
18
+ "Off",
19
+ ];
20
+ /**
21
+ * Format an `{ r, g, b }` object into a lowercase `#rrggbb` hex colour string.
22
+ */
23
+ function rgbToHex({ r, g, b }) {
24
+ return `#${[r, g, b].map((channel) => (channel & 0xff).toString(16).padStart(2, "0")).join("")}`;
25
+ }
26
+ /**
27
+ * Parse a `#rrggbb` hex colour string into `{ r, g, b }` channels.
28
+ */
29
+ function hexToRgb(color) {
30
+ const match = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color.trim());
31
+ if (!match)
32
+ throw new Error(`Expected a #rrggbb colour, got "${color}".`);
33
+ return {
34
+ r: parseInt(match[1], 16),
35
+ g: parseInt(match[2], 16),
36
+ b: parseInt(match[3], 16),
37
+ };
38
+ }
39
+ /**
40
+ * Convert an EEPROM RGB effect code (`0x00`, `0x01`, `0x02`, `0x04`) into a UI `MouseLightingMode`.
41
+ */
42
+ function effectToMode(effect) {
43
+ switch (effect) {
44
+ case REDRAGON_M719_PRO_RGB_EFFECT.steady:
45
+ return "Static";
46
+ case REDRAGON_M719_PRO_RGB_EFFECT.breathing:
47
+ return "Breathing single";
48
+ case REDRAGON_M719_PRO_RGB_EFFECT.neon:
49
+ return "Neon";
50
+ default:
51
+ return "Off";
52
+ }
53
+ }
54
+ /**
55
+ * Convert a UI `MouseLightingMode` into the hardware RGB effect code for EEPROM `0x00a0`.
56
+ */
57
+ function modeToEffect(mode) {
58
+ switch (mode) {
59
+ case "Static":
60
+ return REDRAGON_M719_PRO_RGB_EFFECT.steady;
61
+ case "Breathing single":
62
+ return REDRAGON_M719_PRO_RGB_EFFECT.breathing;
63
+ case "Neon":
64
+ return REDRAGON_M719_PRO_RGB_EFFECT.neon;
65
+ case "Off":
66
+ return REDRAGON_M719_PRO_RGB_EFFECT.off;
67
+ default:
68
+ throw new Error(`Unsupported Redragon M719RGB-PRO lighting mode: ${String(mode)}.`);
69
+ }
70
+ }
71
+ /**
72
+ * Convert a DPI indicator LED mode byte (`0`, `1`, `2`) into a UI `MouseLightingMode`.
73
+ */
74
+ function dpiLedCodeToMode(code) {
75
+ if (code === 1)
76
+ return "Static";
77
+ if (code === 2)
78
+ return "Breathing single";
79
+ return "Off";
80
+ }
81
+ /**
82
+ * Convert a UI `MouseLightingMode` into a DPI indicator LED mode byte (`0`, `1`, `2`).
83
+ */
84
+ function modeToDpiLedCode(mode) {
85
+ switch (mode) {
86
+ case "Static":
87
+ return 1;
88
+ case "Breathing single":
89
+ return 2;
90
+ case "Off":
91
+ return 0;
92
+ default:
93
+ throw new Error(`Unsupported Redragon M719RGB-PRO DPI indicator mode: ${String(mode)}.`);
94
+ }
95
+ }
96
+ /**
97
+ * Recursively check whether any HID collection exposes a Feature Report with `reportId`.
98
+ */
99
+ function hasFeatureReport(collections, reportId) {
100
+ for (const collection of collections ?? []) {
101
+ if ((collection.featureReports ?? []).some((report) => report.reportId === reportId)) {
102
+ return true;
103
+ }
104
+ if (hasFeatureReport(collection.children, reportId))
105
+ return true;
106
+ }
107
+ return false;
108
+ }
109
+ /**
110
+ * Recursively check whether any HID collection exposes an Input Report with `reportId`.
111
+ */
112
+ function hasInputReport(collections, reportId) {
113
+ for (const collection of collections ?? []) {
114
+ if ((collection.inputReports ?? []).some((report) => report.reportId === reportId)) {
115
+ return true;
116
+ }
117
+ if (hasInputReport(collection.children, reportId))
118
+ return true;
119
+ }
120
+ return false;
121
+ }
122
+ /**
123
+ * Recursively check whether any HID collection matches `usagePage`.
124
+ */
125
+ function hasUsagePage(collections, usagePage) {
126
+ for (const collection of collections ?? []) {
127
+ if (collection.usagePage === usagePage)
128
+ return true;
129
+ if (hasUsagePage(collection.children, usagePage))
130
+ return true;
131
+ }
132
+ return false;
133
+ }
134
+ /**
135
+ * Check whether `device` exposes the Redragon M719RGB-PRO command collection
136
+ * (Feature Report `0x08` on Usage Page `0xff02`).
137
+ */
138
+ function hasCommandChannel(device) {
139
+ return hasFeatureReport(device.collections, REDRAGON_M719_PRO_COMMAND_REPORT_ID)
140
+ || hasUsagePage(device.collections, REDRAGON_M719_PRO_COMMAND_USAGE_PAGE);
141
+ }
142
+ /**
143
+ * Check whether `device` exposes the Redragon M719RGB-PRO response/notification
144
+ * collection (Input Report `0x09` on Usage Page `0xff01`).
145
+ */
146
+ function hasResponseChannel(device) {
147
+ return hasInputReport(device.collections, REDRAGON_M719_PRO_RESPONSE_REPORT_ID)
148
+ || hasUsagePage(device.collections, REDRAGON_M719_PRO_NOTIFY_USAGE_PAGE);
149
+ }
150
+ /**
151
+ * Sleep for `ms` milliseconds between multi-chunk or retried EEPROM writes.
152
+ */
153
+ function delay(ms) {
154
+ return new Promise((resolve) => setTimeout(resolve, ms));
155
+ }
156
+ /**
157
+ * WebHID driver client for the Redragon M719RGB-PRO (INVADER PRO) gaming mouse
158
+ * (`0x25a7:0xfa7e` 2.4 GHz wireless receiver and `0x25a7:0xfab0` wired USB).
159
+ */
160
+ export class RedragonM719ProHidClient {
161
+ device;
162
+ cmdDevice = null;
163
+ notifyDevice = null;
164
+ ambiguousPeers = false;
165
+ channelsResolved = false;
166
+ handshakeCompleted = false;
167
+ queue = Promise.resolve();
168
+ notificationListener = null;
169
+ lastRgbSpeed = 5;
170
+ lastRgbBrightness = 10;
171
+ lastRgbColor = { r: 0xff, g: 0x00, b: 0x00 };
172
+ waiter = null;
173
+ onInputReport = (event) => {
174
+ const raw = new Uint8Array(event.data.buffer.slice(event.data.byteOffset, event.data.byteOffset + event.data.byteLength));
175
+ const payload = redragonM719ProNormalizeReply(raw);
176
+ // Asynchronous hardware push notifications (physical DPI button or Profile Switch button).
177
+ if (event.reportId === REDRAGON_M719_PRO_NOTIFY_REPORT_ID
178
+ || (event.reportId === REDRAGON_M719_PRO_RESPONSE_REPORT_ID
179
+ && payload[0] === REDRAGON_M719_PRO_COMMAND.hardwareNotify)) {
180
+ const notification = redragonM719ProDecodeHardwareNotification(raw, event.reportId);
181
+ if (notification) {
182
+ this.notificationListener?.();
183
+ }
184
+ return;
185
+ }
186
+ if (event.reportId !== REDRAGON_M719_PRO_RESPONSE_REPORT_ID
187
+ && event.reportId !== REDRAGON_M719_PRO_COMMAND_REPORT_ID) {
188
+ return;
189
+ }
190
+ if (!redragonM719ProVerifyPacketChecksum(payload, event.reportId))
191
+ return;
192
+ const waiter = this.waiter;
193
+ if (!waiter || payload[0] !== waiter.command)
194
+ return;
195
+ if (waiter.address !== undefined
196
+ && ((((payload[2] ?? 0) << 8) | (payload[3] ?? 0)) & 0xffff) !== waiter.address) {
197
+ return;
198
+ }
199
+ clearTimeout(waiter.timer);
200
+ this.waiter = null;
201
+ waiter.resolve(payload);
202
+ };
203
+ /**
204
+ * Create a new Redragon M719RGB-PRO WebHID client bound to `device`.
205
+ */
206
+ constructor(device) {
207
+ this.device = device;
208
+ }
209
+ /**
210
+ * Return `true` when `device` is a Redragon M719RGB-PRO command or response HID collection.
211
+ */
212
+ static isSupported(device) {
213
+ if (device.vendorId !== REDRAGON_M719_PRO_VENDOR_ID)
214
+ return false;
215
+ if (!REDRAGON_M719_PRO_PRODUCTS.has(device.productId))
216
+ return false;
217
+ return hasCommandChannel(device) || hasResponseChannel(device);
218
+ }
219
+ /**
220
+ * Score how suitable `device` is as the primary handle for a Redragon M719RGB-PRO,
221
+ * preferring combined or command (`0xff02`) collections over notify-only (`0xff01`) siblings.
222
+ */
223
+ static supportScore(device) {
224
+ if (!this.isSupported(device))
225
+ return 0;
226
+ let score = 2;
227
+ if (hasCommandChannel(device))
228
+ score += 12;
229
+ if (hasResponseChannel(device))
230
+ score += 8;
231
+ if (device.productId === REDRAGON_M719_PRO_WIRED_PRODUCT_ID)
232
+ score += 2;
233
+ return score;
234
+ }
235
+ /**
236
+ * Return the human-readable model name (`"Redragon M719RGB-PRO"`).
237
+ */
238
+ displayName() {
239
+ return DISPLAY_NAME;
240
+ }
241
+ /**
242
+ * Return the canonical brand identifier (`"Redragon"`).
243
+ */
244
+ deviceBrand() {
245
+ return "Redragon";
246
+ }
247
+ /**
248
+ * Return `true` when connected via the `0x25a7:0xfa7e` 2.4 GHz wireless receiver.
249
+ */
250
+ isWireless() {
251
+ return this.device.productId === REDRAGON_M719_PRO_WIRELESS_PRODUCT_ID;
252
+ }
253
+ /**
254
+ * Return all discrete DPI steps supported by the PAW3325 hardware lookup table.
255
+ */
256
+ getDpiOptions() {
257
+ return [...REDRAGON_M719_PRO_DPI_OPTIONS];
258
+ }
259
+ /**
260
+ * Return the supported USB polling rates in Hz (`[125, 250, 500, 1000]`).
261
+ */
262
+ getSupportedPollingRates() {
263
+ return [...REDRAGON_M719_PRO_POLLING_RATES];
264
+ }
265
+ /**
266
+ * Bind command (`0xff02`, Feature Report 8) and response (`0xff01`, Input Report 9)
267
+ * collections whether the platform exposes them on one `HIDDevice` or across
268
+ * sibling `HIDDevice` entries in `navigator.hid.getDevices()`.
269
+ * Marks the pairing ambiguous if multiple distinct split devices match the missing channel.
270
+ */
271
+ bindPeers(devices) {
272
+ this.ambiguousPeers = false;
273
+ if (hasCommandChannel(this.device) && hasResponseChannel(this.device)) {
274
+ this.cmdDevice = this.device;
275
+ this.notifyDevice = this.device;
276
+ this.channelsResolved = true;
277
+ return;
278
+ }
279
+ const peers = devices.filter((candidate) => candidate.vendorId === this.device.vendorId
280
+ && candidate.productId === this.device.productId);
281
+ const pool = peers.length > 0 ? peers : [this.device];
282
+ const selectPeer = (predicate) => {
283
+ if (predicate(this.device))
284
+ return this.device;
285
+ let candidates = pool.filter(predicate);
286
+ if (candidates.length > 1 && this.device.productName) {
287
+ const sameName = candidates.filter((c) => c.productName === this.device.productName);
288
+ if (sameName.length > 0)
289
+ candidates = sameName;
290
+ }
291
+ if (candidates.length > 1) {
292
+ this.ambiguousPeers = true;
293
+ return null;
294
+ }
295
+ return candidates[0] ?? null;
296
+ };
297
+ this.cmdDevice = selectPeer(hasCommandChannel);
298
+ this.notifyDevice = selectPeer(hasResponseChannel);
299
+ this.channelsResolved = true;
300
+ }
301
+ /**
302
+ * Open the command and response HID collections and attach the input report listener.
303
+ */
304
+ async open() {
305
+ if (!RedragonM719ProHidClient.isSupported(this.device)) {
306
+ throw new Error("The Redragon M719RGB-PRO vendor configuration collection is not present on this HID interface.");
307
+ }
308
+ if (!this.channelsResolved) {
309
+ if (hasCommandChannel(this.device) && hasResponseChannel(this.device)) {
310
+ this.cmdDevice = this.device;
311
+ this.notifyDevice = this.device;
312
+ this.ambiguousPeers = false;
313
+ this.channelsResolved = true;
314
+ }
315
+ else {
316
+ const authorized = typeof navigator !== "undefined" && navigator.hid?.getDevices
317
+ ? await navigator.hid.getDevices().catch(() => [])
318
+ : [];
319
+ this.bindPeers(authorized);
320
+ }
321
+ }
322
+ if (this.ambiguousPeers) {
323
+ throw new Error("Multiple Redragon M719RGB-PRO split HID interfaces are authorized; cannot unambiguously pair command (0xff02) and response (0xff01) collections.");
324
+ }
325
+ const cmd = this.cmdDevice;
326
+ if (!cmd || !hasCommandChannel(cmd)) {
327
+ throw new Error("The Redragon M719RGB-PRO command collection (0xff02, feature report 8) is missing.");
328
+ }
329
+ const notify = this.notifyDevice;
330
+ if (!notify || !hasResponseChannel(notify)) {
331
+ throw new Error("The Redragon M719RGB-PRO response collection (0xff01, input report 9) is missing.");
332
+ }
333
+ if (!cmd.opened)
334
+ await cmd.open();
335
+ if (notify !== cmd && !notify.opened)
336
+ await notify.open();
337
+ notify.removeEventListener("inputreport", this.onInputReport);
338
+ notify.addEventListener("inputreport", this.onInputReport);
339
+ if (this.device !== notify) {
340
+ if (!this.device.opened)
341
+ await this.device.open();
342
+ this.device.removeEventListener("inputreport", this.onInputReport);
343
+ this.device.addEventListener("inputreport", this.onInputReport);
344
+ }
345
+ }
346
+ /**
347
+ * Abort any in-flight command waiter and close all bound HID interfaces in serialized order.
348
+ */
349
+ async close() {
350
+ this.failWaiter(new Error("The Redragon M719RGB-PRO device was closed."));
351
+ await this.serialized(async () => {
352
+ this.failWaiter(new Error("The Redragon M719RGB-PRO device was closed."));
353
+ this.notificationListener = null;
354
+ this.handshakeCompleted = false;
355
+ const devices = new Set([
356
+ this.device,
357
+ ...(this.cmdDevice ? [this.cmdDevice] : []),
358
+ ...(this.notifyDevice ? [this.notifyDevice] : []),
359
+ ]);
360
+ for (const dev of devices) {
361
+ dev.removeEventListener("inputreport", this.onInputReport);
362
+ if (dev.opened)
363
+ await dev.close().catch(() => undefined);
364
+ }
365
+ this.cmdDevice = null;
366
+ this.notifyDevice = null;
367
+ this.ambiguousPeers = false;
368
+ this.channelsResolved = false;
369
+ });
370
+ }
371
+ /**
372
+ * Subscribe to asynchronous hardware notifications (physical DPI stage or profile button changes).
373
+ */
374
+ async startNotifications(onChange) {
375
+ await this.open();
376
+ this.notificationListener = onChange ?? null;
377
+ return true;
378
+ }
379
+ /**
380
+ * Read the full mouse configuration, battery state, DPI stages, lighting zones, and button mappings.
381
+ */
382
+ async readStatus() {
383
+ return await this.serialized(async () => {
384
+ await this.open();
385
+ const wireless = this.isWireless();
386
+ if (wireless) {
387
+ const online = await this.checkOnline();
388
+ if (!online) {
389
+ return this.unreadyStatus(OFFLINE_NOTE);
390
+ }
391
+ }
392
+ await this.ensureHandshake();
393
+ let snapshot;
394
+ try {
395
+ snapshot = await this.readHardwareSnapshot();
396
+ }
397
+ catch (error) {
398
+ const message = error instanceof Error ? error.message : String(error);
399
+ return this.unreadyStatus(message);
400
+ }
401
+ const battery = await this.readBattery().catch(() => null);
402
+ let batteryPercent = null;
403
+ let batteryState = wireless ? "Unknown" : "Charging";
404
+ if (battery) {
405
+ batteryPercent = battery.percent;
406
+ if (wireless) {
407
+ batteryState = battery.charging
408
+ ? (battery.percent >= 100 ? "Full" : "Charging")
409
+ : "Discharging";
410
+ }
411
+ else {
412
+ batteryState = battery.percent >= 100 ? "Full" : "Charging";
413
+ }
414
+ }
415
+ const stageCount = snapshot.stageCount;
416
+ const activeStage = Math.min(snapshot.activeStage, stageCount - 1);
417
+ const visibleStages = snapshot.stages.slice(0, stageCount);
418
+ const visibleColors = snapshot.stageColors.slice(0, stageCount).map(rgbToHex);
419
+ const activeColorHex = visibleColors[activeStage] ?? rgbToHex(snapshot.stageColors[0]);
420
+ const mainLighting = this.buildMainLighting(snapshot.rgb);
421
+ const dpiIndicatorLighting = this.buildDpiIndicatorLighting(snapshot.dpiLedMode, activeColorHex);
422
+ return {
423
+ brand: "Redragon",
424
+ name: DISPLAY_NAME,
425
+ ui: {
426
+ family: "redragon",
427
+ defaultDisplayName: DISPLAY_NAME,
428
+ settingsReady: true,
429
+ valuesVerified: snapshot.dpiLedMode !== null,
430
+ hideUnsupportedPollingRates: true,
431
+ dpiStageEditor: {
432
+ maxStages: REDRAGON_M719_PRO_MAX_DPI_STAGES,
433
+ countEditable: true,
434
+ minDpi: REDRAGON_M719_PRO_DPI_MIN,
435
+ maxDpi: REDRAGON_M719_PRO_DPI_MAX,
436
+ stepDpi: REDRAGON_M719_PRO_DPI_STEP,
437
+ },
438
+ },
439
+ batteryPercent,
440
+ batteryState,
441
+ dpi: visibleStages[activeStage] ?? snapshot.stages[0] ?? 800,
442
+ dpiStages: visibleStages,
443
+ dpiStageColors: visibleColors,
444
+ activeDpiStage: activeStage,
445
+ pollingRateHz: snapshot.pollingHz,
446
+ supportedPollingRates: [...REDRAGON_M719_PRO_POLLING_RATES],
447
+ activeProfile: null,
448
+ buttonMappings: snapshot.buttonMappings,
449
+ buttonOptions: [...REDRAGON_M719_PRO_BUTTON_ACTIONS],
450
+ fixedButtons: snapshot.fixedButtons,
451
+ connectionType: wireless ? "Wireless" : "Wired",
452
+ connectionDetail: wireless ? "2.4 GHz receiver" : "USB",
453
+ liftOffDistance: null,
454
+ lighting: mainLighting,
455
+ lightingZones: [mainLighting, dpiIndicatorLighting],
456
+ firmware: [],
457
+ };
458
+ });
459
+ }
460
+ /**
461
+ * Write and verify the USB polling rate (`125`, `250`, `500`, or `1000` Hz) at EEPROM `0x0000`.
462
+ */
463
+ async setPollingRate(hz) {
464
+ const encoded = redragonM719ProEncodePollingRate(hz);
465
+ return await this.serialized(async () => {
466
+ await this.requireReady();
467
+ await this.writeEeprom(REDRAGON_M719_PRO_EEPROM.pollingRate, encoded);
468
+ const readBack = await this.readEeprom(REDRAGON_M719_PRO_EEPROM.pollingRate, 2);
469
+ if (readBack[0] !== encoded[0] || readBack[1] !== encoded[1]) {
470
+ const confirmed = redragonM719ProDecodePollingRate(readBack);
471
+ throw new Error(`The mouse kept ${confirmed} Hz instead of ${hz} Hz.`);
472
+ }
473
+ return hz;
474
+ });
475
+ }
476
+ /**
477
+ * Update the DPI value of the currently active DPI stage.
478
+ */
479
+ async setDpi(dpi) {
480
+ if (!Number.isFinite(dpi) || dpi < REDRAGON_M719_PRO_DPI_MIN || dpi > REDRAGON_M719_PRO_DPI_MAX) {
481
+ throw new RangeError(`Redragon M719RGB-PRO DPI must be between ${REDRAGON_M719_PRO_DPI_MIN} and ${REDRAGON_M719_PRO_DPI_MAX}.`);
482
+ }
483
+ const target = redragonM719ProNearestDpi(dpi);
484
+ return await this.serialized(async () => {
485
+ await this.requireReady();
486
+ const activeStage = await this.readActiveStageIndex();
487
+ return await this.writeStageDpi(activeStage, target);
488
+ });
489
+ }
490
+ /**
491
+ * Update the DPI value for a specific 0-based stage index (`0..4`).
492
+ */
493
+ async setDpiStageValue(stage, dpi) {
494
+ if (!Number.isInteger(stage) || stage < 0 || stage >= REDRAGON_M719_PRO_MAX_DPI_STAGES) {
495
+ throw new RangeError(`Redragon M719RGB-PRO DPI stage must be 0–${REDRAGON_M719_PRO_MAX_DPI_STAGES - 1}.`);
496
+ }
497
+ if (!Number.isFinite(dpi) || dpi < REDRAGON_M719_PRO_DPI_MIN || dpi > REDRAGON_M719_PRO_DPI_MAX) {
498
+ throw new RangeError(`Redragon M719RGB-PRO DPI must be between ${REDRAGON_M719_PRO_DPI_MIN} and ${REDRAGON_M719_PRO_DPI_MAX}.`);
499
+ }
500
+ const target = redragonM719ProNearestDpi(dpi);
501
+ return await this.serialized(async () => {
502
+ await this.requireReady();
503
+ return await this.writeStageDpi(stage, target);
504
+ });
505
+ }
506
+ /**
507
+ * Switch the active 0-based DPI stage index (`0..stageCount-1`) at EEPROM `0x0004`.
508
+ */
509
+ async setActiveDpiStage(stage) {
510
+ if (!Number.isInteger(stage) || stage < 0 || stage >= REDRAGON_M719_PRO_MAX_DPI_STAGES) {
511
+ throw new RangeError(`Redragon M719RGB-PRO active DPI stage must be 0–${REDRAGON_M719_PRO_MAX_DPI_STAGES - 1}.`);
512
+ }
513
+ return await this.serialized(async () => {
514
+ await this.requireReady();
515
+ const stageCount = await this.readStageCount();
516
+ if (stage >= stageCount) {
517
+ throw new RangeError(`Stage ${stage + 1} is disabled (only ${stageCount} stages active).`);
518
+ }
519
+ await this.writeEeprom(REDRAGON_M719_PRO_EEPROM.activeDpiStage, redragonM719ProPackScalar(stage));
520
+ const confirmed = await this.readActiveStageIndex();
521
+ if (confirmed !== stage) {
522
+ throw new Error(`The mouse kept DPI stage ${confirmed + 1} instead of ${stage + 1}.`);
523
+ }
524
+ return confirmed;
525
+ });
526
+ }
527
+ /**
528
+ * Set the number of enabled DPI stages (`1..5`) at EEPROM `0x0002`, clamping
529
+ * `activeDpiStage` first if the active stage index would exceed `count - 1`.
530
+ */
531
+ async setDpiStageCount(count) {
532
+ if (!Number.isInteger(count) || count < 1 || count > REDRAGON_M719_PRO_MAX_DPI_STAGES) {
533
+ throw new RangeError(`Redragon M719RGB-PRO supports 1–${REDRAGON_M719_PRO_MAX_DPI_STAGES} DPI stages.`);
534
+ }
535
+ return await this.serialized(async () => {
536
+ await this.requireReady();
537
+ const currentActive = await this.readActiveStageIndex();
538
+ if (currentActive >= count) {
539
+ const targetActive = count - 1;
540
+ await this.writeEeprom(REDRAGON_M719_PRO_EEPROM.activeDpiStage, redragonM719ProPackScalar(targetActive));
541
+ const confirmedActive = await this.readActiveStageIndex();
542
+ if (confirmedActive !== targetActive) {
543
+ throw new Error(`The mouse kept DPI stage ${confirmedActive + 1} instead of ${targetActive + 1}.`);
544
+ }
545
+ }
546
+ await this.writeEeprom(REDRAGON_M719_PRO_EEPROM.dpiStageCount, redragonM719ProPackScalar(count));
547
+ const confirmed = await this.readStageCount();
548
+ if (confirmed !== count) {
549
+ throw new Error(`The mouse kept ${confirmed} DPI stages instead of ${count}.`);
550
+ }
551
+ return confirmed;
552
+ });
553
+ }
554
+ /**
555
+ * Set the indicator RGB colour (`#rrggbb`) for a specific 0-based DPI stage (`0..4`).
556
+ */
557
+ async setDpiStageColor(stage, color) {
558
+ if (!Number.isInteger(stage) || stage < 0 || stage >= REDRAGON_M719_PRO_MAX_DPI_STAGES) {
559
+ throw new RangeError(`Redragon M719RGB-PRO DPI stage must be 0–${REDRAGON_M719_PRO_MAX_DPI_STAGES - 1}.`);
560
+ }
561
+ const rgb = hexToRgb(color);
562
+ const expectedHex = rgbToHex(rgb);
563
+ return await this.serialized(async () => {
564
+ await this.requireReady();
565
+ const address = REDRAGON_M719_PRO_EEPROM.dpiColors + stage * 4;
566
+ await this.writeEeprom(address, redragonM719ProEncodeDpiStageColor(rgb));
567
+ const readBack = await this.readEeprom(address, 4);
568
+ const confirmedHex = rgbToHex(redragonM719ProDecodeDpiStageColor(readBack));
569
+ if (confirmedHex !== expectedHex) {
570
+ throw new Error(`The mouse kept stage ${stage + 1} colour ${confirmedHex} instead of ${expectedHex}.`);
571
+ }
572
+ return confirmedHex;
573
+ });
574
+ }
575
+ /**
576
+ * Set the DPI indicator / logo LED mode (`0` Off, `1` Steady, `2` Breathing) at EEPROM `0x004c`.
577
+ */
578
+ async setDpiIndicatorMode(mode) {
579
+ if (mode !== 0 && mode !== 1 && mode !== 2) {
580
+ throw new RangeError(`Redragon M719RGB-PRO DPI indicator mode must be 0, 1, or 2.`);
581
+ }
582
+ return await this.serialized(async () => {
583
+ await this.requireReady();
584
+ const activeStage = await this.readActiveStageIndex();
585
+ await this.writeEeprom(REDRAGON_M719_PRO_EEPROM.dpiLedEffect, redragonM719ProEncodeDpiLedEffect(mode, activeStage));
586
+ const readBack = await this.readEeprom(REDRAGON_M719_PRO_EEPROM.dpiLedEffect, 2);
587
+ const confirmed = redragonM719ProDecodeDpiLedEffect(readBack);
588
+ if (confirmed !== mode) {
589
+ throw new Error(`The mouse kept DPI indicator mode ${confirmed} instead of ${mode}.`);
590
+ }
591
+ return confirmed;
592
+ });
593
+ }
594
+ /**
595
+ * Update either the main RGB zone (`"Mouse"`, EEPROM `0x00a0`) or the DPI indicator
596
+ * LED zone (`"DPI indicator"`, EEPROM `0x004c`).
597
+ */
598
+ async setLighting(lighting) {
599
+ if (lighting.zone === "DPI indicator") {
600
+ const code = modeToDpiLedCode(lighting.mode);
601
+ return await this.serialized(async () => {
602
+ await this.requireReady();
603
+ const activeStage = await this.readActiveStageIndex();
604
+ await this.writeEeprom(REDRAGON_M719_PRO_EEPROM.dpiLedEffect, redragonM719ProEncodeDpiLedEffect(code, activeStage));
605
+ const readBack = await this.readEeprom(REDRAGON_M719_PRO_EEPROM.dpiLedEffect, 2);
606
+ const confirmed = redragonM719ProDecodeDpiLedEffect(readBack);
607
+ if (confirmed !== code) {
608
+ throw new Error("The mouse did not confirm the requested DPI indicator effect.");
609
+ }
610
+ const stageColorRaw = await this.readEeprom(REDRAGON_M719_PRO_EEPROM.dpiColors + activeStage * 4, 4);
611
+ const activeStageColorHex = rgbToHex(redragonM719ProDecodeDpiStageColor(stageColorRaw));
612
+ return this.buildDpiIndicatorLighting(confirmed, activeStageColorHex);
613
+ });
614
+ }
615
+ if (lighting.zone && lighting.zone !== "Mouse") {
616
+ throw new Error(`Unknown Redragon M719RGB-PRO lighting zone: ${lighting.zone}.`);
617
+ }
618
+ const effect = modeToEffect(lighting.mode);
619
+ const explicitColor = lighting.color ? hexToRgb(lighting.color) : null;
620
+ return await this.serialized(async () => {
621
+ await this.requireReady();
622
+ const currentRaw = await this.readEeprom(REDRAGON_M719_PRO_EEPROM.rgbLighting, 7);
623
+ const current = redragonM719ProDecodeRgbLighting(currentRaw);
624
+ this.lastRgbColor = current.color;
625
+ if (current.effect !== REDRAGON_M719_PRO_RGB_EFFECT.off) {
626
+ this.lastRgbSpeed = current.speed;
627
+ this.lastRgbBrightness = current.brightness;
628
+ }
629
+ const color = explicitColor ?? this.lastRgbColor;
630
+ const speed = lighting.speed != null
631
+ ? Math.max(1, Math.min(10, Math.round(lighting.speed)))
632
+ : this.lastRgbSpeed;
633
+ const brightnessPercent = lighting.brightness != null
634
+ ? Math.max(10, Math.min(100, Math.round(lighting.brightness / 10) * 10))
635
+ : this.lastRgbBrightness * 10;
636
+ const brightnessLevel = Math.max(1, Math.min(10, Math.round(brightnessPercent / 10)));
637
+ this.lastRgbColor = color;
638
+ this.lastRgbSpeed = speed;
639
+ this.lastRgbBrightness = brightnessLevel;
640
+ const encoded = redragonM719ProEncodeRgbLighting({
641
+ effect,
642
+ color,
643
+ speed,
644
+ brightness: brightnessLevel,
645
+ });
646
+ await this.writeEeprom(REDRAGON_M719_PRO_EEPROM.rgbLighting, encoded);
647
+ const readBack = await this.readEeprom(REDRAGON_M719_PRO_EEPROM.rgbLighting, 7);
648
+ const confirmed = redragonM719ProDecodeRgbLighting(readBack);
649
+ if (confirmed.effect !== effect) {
650
+ throw new Error(`The mouse kept lighting mode ${effectToMode(confirmed.effect)} instead of ${lighting.mode}.`);
651
+ }
652
+ return this.buildMainLighting(confirmed);
653
+ });
654
+ }
655
+ /**
656
+ * Assign an action (direct click, DPI/profile control, multimedia key, or keyboard shortcut)
657
+ * to one of the 8 physical buttons, ensuring at least one button retains `"Left click"`.
658
+ */
659
+ async setButtonMapping(button, action) {
660
+ const entry = REDRAGON_M719_PRO_BUTTONS.find((candidate) => candidate.label === button);
661
+ if (!entry) {
662
+ throw new Error(`Unknown Redragon M719RGB-PRO button: ${button}.`);
663
+ }
664
+ const encoded = redragonM719ProEncodeButtonAction(action);
665
+ await this.serialized(async () => {
666
+ await this.requireReady();
667
+ const currentButtons = await this.readButtons();
668
+ const nextMappings = { ...currentButtons.buttonMappings, [button]: action };
669
+ if (!Object.values(nextMappings).includes("Left click")) {
670
+ throw new Error("Keep Left click on at least one button before reassigning this one.");
671
+ }
672
+ if (encoded.comboPayload) {
673
+ const comboAddress = REDRAGON_M719_PRO_EEPROM.comboBase + entry.slot * REDRAGON_M719_PRO_EEPROM.comboSlotStride;
674
+ await this.writeEeprom(comboAddress, encoded.comboPayload);
675
+ }
676
+ // The OEM driver writes the button matrix in 8-byte (2-slot) aligned chunks.
677
+ const pairBaseSlot = entry.slot & ~1;
678
+ const pairAddress = REDRAGON_M719_PRO_EEPROM.buttonMatrix + pairBaseSlot * 4;
679
+ const pairChunk = await this.readEeprom(pairAddress, 8);
680
+ const inPairOffset = (entry.slot & 1) * 4;
681
+ pairChunk.set(encoded.slotBytes, inPairOffset);
682
+ await this.writeEeprom(pairAddress, pairChunk);
683
+ if (encoded.comboPayload) {
684
+ const comboAddress = REDRAGON_M719_PRO_EEPROM.comboBase + entry.slot * REDRAGON_M719_PRO_EEPROM.comboSlotStride;
685
+ const comboBack = await this.readEeprom(comboAddress, encoded.comboPayload.length);
686
+ for (let i = 0; i < encoded.comboPayload.length; i += 1) {
687
+ if (comboBack[i] !== encoded.comboPayload[i]) {
688
+ throw new Error(`The mouse did not confirm the ${button} shortcut payload.`);
689
+ }
690
+ }
691
+ }
692
+ const confirmedChunk = await this.readEeprom(entry.offset, 4);
693
+ for (let i = 0; i < 4; i += 1) {
694
+ if (confirmedChunk[i] !== encoded.slotBytes[i]) {
695
+ throw new Error(`The mouse did not confirm the ${button} assignment.`);
696
+ }
697
+ }
698
+ });
699
+ }
700
+ // ── Internal Transport & EEPROM Helpers ──────────────────────────────────
701
+ /**
702
+ * Build a placeholder `MouseStatus` when the wireless mouse is asleep or an EEPROM read fails.
703
+ */
704
+ unreadyStatus(statusNote) {
705
+ const wireless = this.isWireless();
706
+ return {
707
+ brand: "Redragon",
708
+ name: DISPLAY_NAME,
709
+ ui: {
710
+ family: "redragon",
711
+ defaultDisplayName: DISPLAY_NAME,
712
+ settingsReady: false,
713
+ hideUnsupportedPollingRates: true,
714
+ statusNote,
715
+ },
716
+ batteryPercent: null,
717
+ batteryState: "Unknown",
718
+ dpi: 800,
719
+ pollingRateHz: 1000,
720
+ supportedPollingRates: [...REDRAGON_M719_PRO_POLLING_RATES],
721
+ activeProfile: null,
722
+ connectionType: wireless ? "Wireless" : "Wired",
723
+ connectionDetail: wireless ? "2.4 GHz receiver" : "USB",
724
+ liftOffDistance: null,
725
+ firmware: [],
726
+ };
727
+ }
728
+ /**
729
+ * Build the `"Mouse"` main RGB zone descriptor from a decoded 7-byte EEPROM record.
730
+ */
731
+ buildMainLighting(rgb) {
732
+ const mode = effectToMode(rgb.effect);
733
+ this.lastRgbColor = rgb.color;
734
+ if (rgb.effect !== REDRAGON_M719_PRO_RGB_EFFECT.off) {
735
+ this.lastRgbSpeed = rgb.speed;
736
+ this.lastRgbBrightness = rgb.brightness;
737
+ }
738
+ const shownSpeed = rgb.effect === REDRAGON_M719_PRO_RGB_EFFECT.off ? this.lastRgbSpeed : rgb.speed;
739
+ const shownBrightness = (rgb.effect === REDRAGON_M719_PRO_RGB_EFFECT.off ? this.lastRgbBrightness : rgb.brightness) * 10;
740
+ return {
741
+ zone: "Mouse",
742
+ modes: MAIN_LIGHTING_MODES,
743
+ mode,
744
+ color: rgbToHex(rgb.color),
745
+ color2: null,
746
+ colorModes: MAIN_COLOR_MODES,
747
+ dualColorModes: [],
748
+ reactiveModes: MAIN_REACTIVE_MODES,
749
+ speeds: [...REDRAGON_M719_PRO_SPEED_LEVELS],
750
+ speed: shownSpeed,
751
+ brightness: shownBrightness,
752
+ brightnessLevels: [...REDRAGON_M719_PRO_BRIGHTNESS_PERCENTS],
753
+ };
754
+ }
755
+ /**
756
+ * Build the `"DPI indicator"` zone descriptor using the active stage's colour.
757
+ */
758
+ buildDpiIndicatorLighting(modeCode, activeStageColorHex) {
759
+ return {
760
+ zone: "DPI indicator",
761
+ modes: DPI_INDICATOR_MODES,
762
+ mode: modeCode === null ? null : dpiLedCodeToMode(modeCode),
763
+ color: activeStageColorHex,
764
+ color2: null,
765
+ colorModes: [],
766
+ dualColorModes: [],
767
+ reactiveModes: [],
768
+ speeds: [],
769
+ speed: null,
770
+ };
771
+ }
772
+ /**
773
+ * Ensure the HID interfaces are open, the wireless mouse is awake, and the handshake has run.
774
+ */
775
+ async requireReady() {
776
+ await this.open();
777
+ if (this.isWireless()) {
778
+ const online = await this.checkOnline();
779
+ if (!online) {
780
+ throw new Error(OFFLINE_NOTE);
781
+ }
782
+ }
783
+ await this.ensureHandshake();
784
+ }
785
+ /**
786
+ * Query `GetConnectStatus` (`0x03`) to check whether the wireless mouse is awake.
787
+ */
788
+ async checkOnline() {
789
+ try {
790
+ const reply = await this.exchange(redragonM719ProEncodeGetConnectStatus());
791
+ return redragonM719ProDecodeConnectStatus(reply);
792
+ }
793
+ catch {
794
+ return false;
795
+ }
796
+ }
797
+ /**
798
+ * Perform the `Cmd 0x01` 4-byte challenge/response handshake and `Cmd 0x02` driver-status notice once per session.
799
+ */
800
+ async ensureHandshake() {
801
+ if (this.handshakeCompleted)
802
+ return;
803
+ const challenge = [0x17, 0x2a, 0x3d, 0x50];
804
+ try {
805
+ const reply = await this.exchange(redragonM719ProEncodeHandshake(challenge));
806
+ if (redragonM719ProVerifyHandshakeReply(challenge, reply)) {
807
+ await this.sendOnly(redragonM719ProEncodeTellDriverStatus(true)).catch(() => undefined);
808
+ }
809
+ }
810
+ catch {
811
+ // Some minimal receivers/mocks skip Cmd 0x01; EEPROM commands still validate directly.
812
+ }
813
+ this.handshakeCompleted = true;
814
+ }
815
+ /**
816
+ * Query `GetBattery` (`0x04`) and decode the current battery percentage and charging flag.
817
+ */
818
+ async readBattery() {
819
+ const reply = await this.exchange(redragonM719ProEncodeGetBattery());
820
+ return redragonM719ProDecodeBattery(reply);
821
+ }
822
+ /**
823
+ * Read the number of active DPI stages (`1..5`) from EEPROM `0x0002`.
824
+ */
825
+ async readStageCount() {
826
+ const raw = await this.readEeprom(REDRAGON_M719_PRO_EEPROM.dpiStageCount, 2);
827
+ const count = redragonM719ProUnpackScalar(raw);
828
+ if (count === null) {
829
+ throw new Error("The mouse returned a corrupt DPI stage count record.");
830
+ }
831
+ return Math.max(1, Math.min(REDRAGON_M719_PRO_MAX_DPI_STAGES, count));
832
+ }
833
+ /**
834
+ * Read the 0-based active DPI stage index (`0..4`) from EEPROM `0x0004`.
835
+ */
836
+ async readActiveStageIndex() {
837
+ const raw = await this.readEeprom(REDRAGON_M719_PRO_EEPROM.activeDpiStage, 2);
838
+ const scalar = redragonM719ProUnpackScalar(raw);
839
+ if (scalar === null) {
840
+ throw new Error("The mouse returned a corrupt active DPI stage record.");
841
+ }
842
+ const index = scalar & 0x0f;
843
+ return Math.max(0, Math.min(REDRAGON_M719_PRO_MAX_DPI_STAGES - 1, index));
844
+ }
845
+ /**
846
+ * Write a 4-byte PAW3325 DPI stage record and verify all 4 read-back bytes and checksum.
847
+ */
848
+ async writeStageDpi(stage, targetDpi) {
849
+ const address = REDRAGON_M719_PRO_EEPROM.dpiStages + stage * 4;
850
+ const encoded = redragonM719ProEncodeDpiStage(targetDpi);
851
+ await this.writeEeprom(address, encoded);
852
+ const readBack = await this.readEeprom(address, 4);
853
+ const confirmed = redragonM719ProDecodeDpiStage(readBack);
854
+ const exactMatch = redragonM719ProVerifyDataChecksum(readBack)
855
+ && readBack[0] === encoded[0]
856
+ && readBack[1] === encoded[1]
857
+ && readBack[2] === encoded[2]
858
+ && readBack[3] === encoded[3];
859
+ if (!exactMatch || confirmed !== targetDpi) {
860
+ throw new Error(`The mouse kept ${confirmed} DPI instead of ${targetDpi} DPI.`);
861
+ }
862
+ return confirmed;
863
+ }
864
+ /**
865
+ * Read all 8 physical button slots from the matrix at `0x0060` and any extended
866
+ * 32-byte combo payloads from `0x0100 + slot * 0x20`.
867
+ */
868
+ async readButtons() {
869
+ const chunk60 = await this.readEeprom(0x0060, 8);
870
+ const chunk68 = await this.readEeprom(0x0068, 8);
871
+ const chunk70 = await this.readEeprom(0x0070, 8);
872
+ const chunk80 = await this.readEeprom(0x0080, 8);
873
+ const chunk88 = await this.readEeprom(0x0088, 8);
874
+ const slotMap = new Map([
875
+ [0, chunk60.subarray(0, 4)],
876
+ [1, chunk60.subarray(4, 8)],
877
+ [2, chunk68.subarray(0, 4)],
878
+ [3, chunk68.subarray(4, 8)],
879
+ [4, chunk70.subarray(0, 4)],
880
+ [8, chunk80.subarray(0, 4)],
881
+ [10, chunk88.subarray(0, 4)],
882
+ [11, chunk88.subarray(4, 8)],
883
+ ]);
884
+ const buttonMappings = {};
885
+ const fixedButtons = [];
886
+ for (const button of REDRAGON_M719_PRO_BUTTONS) {
887
+ const slotBytes = slotMap.get(button.slot);
888
+ let comboBytes = null;
889
+ if (slotBytes[0] === 0x05) {
890
+ const comboAddress = REDRAGON_M719_PRO_EEPROM.comboBase + button.slot * REDRAGON_M719_PRO_EEPROM.comboSlotStride;
891
+ comboBytes = await this.readEeprom(comboAddress, REDRAGON_M719_PRO_EEPROM.comboSlotStride).catch(() => null);
892
+ }
893
+ const action = redragonM719ProDecodeButtonAction(slotBytes, comboBytes);
894
+ buttonMappings[button.label] = action;
895
+ if (!REDRAGON_M719_PRO_BUTTON_ACTIONS.includes(action)) {
896
+ fixedButtons.push(button.label);
897
+ }
898
+ }
899
+ return { buttonMappings, fixedButtons };
900
+ }
901
+ /**
902
+ * Read the full EEPROM configuration snapshot (polling rate, stages, stage colours,
903
+ * DPI indicator LED mode, button matrix, and main RGB lighting).
904
+ */
905
+ async readHardwareSnapshot() {
906
+ const pollingRaw = await this.readEeprom(REDRAGON_M719_PRO_EEPROM.pollingRate, 2);
907
+ const pollingHz = redragonM719ProDecodePollingRate(pollingRaw);
908
+ const stageCount = await this.readStageCount();
909
+ const activeStage = await this.readActiveStageIndex();
910
+ const stagesRaw = new Uint8Array(20);
911
+ stagesRaw.set(await this.readEeprom(0x000c, 8), 0);
912
+ stagesRaw.set(await this.readEeprom(0x0014, 8), 8);
913
+ stagesRaw.set(await this.readEeprom(0x001c, 4), 16);
914
+ const stages = redragonM719ProDecodeDpiStages(stagesRaw);
915
+ const colorsRaw = new Uint8Array(20);
916
+ colorsRaw.set(await this.readEeprom(0x002c, 8), 0);
917
+ colorsRaw.set(await this.readEeprom(0x0034, 8), 8);
918
+ colorsRaw.set(await this.readEeprom(0x003c, 4), 16);
919
+ const stageColors = redragonM719ProDecodeDpiStageColors(colorsRaw);
920
+ // A failed read stays unknown (null) instead of being decoded as a made-up mode.
921
+ const dpiLedRaw = await this.readEeprom(REDRAGON_M719_PRO_EEPROM.dpiLedEffect, 6).catch(() => null);
922
+ const dpiLedMode = dpiLedRaw ? redragonM719ProDecodeDpiLedEffect(dpiLedRaw) : null;
923
+ const { buttonMappings, fixedButtons } = await this.readButtons();
924
+ const rgbRaw = await this.readEeprom(REDRAGON_M719_PRO_EEPROM.rgbLighting, 7);
925
+ const rgb = redragonM719ProDecodeRgbLighting(rgbRaw);
926
+ return {
927
+ pollingHz,
928
+ stageCount,
929
+ activeStage,
930
+ stages,
931
+ stageColors,
932
+ dpiLedMode,
933
+ buttonMappings,
934
+ fixedButtons,
935
+ rgb,
936
+ };
937
+ }
938
+ /**
939
+ * Read `length` bytes from EEPROM starting at `address` in chunks of up to 10 bytes.
940
+ */
941
+ async readEeprom(address, length) {
942
+ const out = new Uint8Array(length);
943
+ for (let offset = 0; offset < length; offset += REDRAGON_M719_PRO_MAX_CHUNK_LENGTH) {
944
+ const chunkLen = Math.min(REDRAGON_M719_PRO_MAX_CHUNK_LENGTH, length - offset);
945
+ const currentAddr = address + offset;
946
+ const packet = redragonM719ProEncodeReadEeprom(currentAddr, chunkLen);
947
+ const reply = await this.exchange(packet);
948
+ const decoded = redragonM719ProDecodeReadEeprom(reply, currentAddr, chunkLen);
949
+ if (!decoded) {
950
+ throw new Error(`Redragon M719RGB-PRO rejected EEPROM read at 0x${currentAddr.toString(16).padStart(4, "0")}.`);
951
+ }
952
+ out.set(decoded, offset);
953
+ }
954
+ return out;
955
+ }
956
+ /**
957
+ * Write `data` to EEPROM starting at `address` in chunks of up to 10 bytes, retrying on MCU busy replies.
958
+ */
959
+ async writeEeprom(address, data) {
960
+ for (let offset = 0; offset < data.length; offset += REDRAGON_M719_PRO_MAX_CHUNK_LENGTH) {
961
+ const chunk = data.subarray(offset, Math.min(data.length, offset + REDRAGON_M719_PRO_MAX_CHUNK_LENGTH));
962
+ const currentAddr = address + offset;
963
+ const packet = redragonM719ProEncodeWriteEeprom(currentAddr, chunk);
964
+ let acked = false;
965
+ for (let attempt = 0; attempt < WRITE_RETRY_LIMIT; attempt += 1) {
966
+ const reply = await this.exchange(packet);
967
+ const status = redragonM719ProDecodeWriteEeprom(reply);
968
+ if (status === "ack") {
969
+ acked = true;
970
+ break;
971
+ }
972
+ if (status === "busy") {
973
+ await delay(WRITE_SETTLE_DELAY_MS * (attempt + 1));
974
+ continue;
975
+ }
976
+ break;
977
+ }
978
+ if (!acked) {
979
+ throw new Error(`Redragon M719RGB-PRO did not acknowledge EEPROM write at 0x${currentAddr.toString(16).padStart(4, "0")}.`);
980
+ }
981
+ if (this.isWireless() || offset + REDRAGON_M719_PRO_MAX_CHUNK_LENGTH < data.length) {
982
+ await delay(WRITE_SETTLE_DELAY_MS);
983
+ }
984
+ }
985
+ }
986
+ /**
987
+ * Send a 16-byte Feature Report `0x08` command without waiting for a response report.
988
+ */
989
+ async sendOnly(payload) {
990
+ const cmd = this.cmdDevice ?? this.device;
991
+ const copy = new Uint8Array(payload);
992
+ await cmd.sendFeatureReport(REDRAGON_M719_PRO_COMMAND_REPORT_ID, copy);
993
+ }
994
+ /**
995
+ * Send a 16-byte Feature Report `0x08` command and await its matching Input Report `0x09` response.
996
+ */
997
+ async exchange(payload) {
998
+ this.failWaiter(new Error("Superseded by another Redragon M719RGB-PRO request."));
999
+ const command = payload[0];
1000
+ const address = command === REDRAGON_M719_PRO_COMMAND.readEeprom || command === REDRAGON_M719_PRO_COMMAND.writeEeprom
1001
+ ? (((payload[2] ?? 0) << 8) | (payload[3] ?? 0)) & 0xffff
1002
+ : undefined;
1003
+ const cmd = this.cmdDevice ?? this.device;
1004
+ const promise = new Promise((resolve, reject) => {
1005
+ const timer = setTimeout(() => {
1006
+ if (this.waiter?.resolve === resolve)
1007
+ this.waiter = null;
1008
+ reject(new Error(`The Redragon M719RGB-PRO did not answer command 0x${command.toString(16).padStart(2, "0")}.`));
1009
+ }, COMMAND_TIMEOUT_MS);
1010
+ this.waiter = { command, address, resolve, reject, timer };
1011
+ });
1012
+ const copy = new Uint8Array(payload);
1013
+ try {
1014
+ await cmd.sendFeatureReport(REDRAGON_M719_PRO_COMMAND_REPORT_ID, copy);
1015
+ }
1016
+ catch (error) {
1017
+ const detail = error instanceof Error ? error.message : String(error);
1018
+ this.failWaiter(new Error(`Could not write Redragon M719RGB-PRO feature report 8 (${detail}).`));
1019
+ }
1020
+ return await promise;
1021
+ }
1022
+ /**
1023
+ * Reject and clear the current command waiter if one is active.
1024
+ */
1025
+ failWaiter(error) {
1026
+ const waiter = this.waiter;
1027
+ if (!waiter)
1028
+ return;
1029
+ clearTimeout(waiter.timer);
1030
+ this.waiter = null;
1031
+ waiter.reject(error);
1032
+ }
1033
+ /**
1034
+ * Enqueue an async operation on the client's serial execution promise chain.
1035
+ */
1036
+ serialized(action) {
1037
+ const next = this.queue.then(action, action);
1038
+ this.queue = next.then(() => undefined, () => undefined);
1039
+ return next;
1040
+ }
1041
+ }
1042
+ //# sourceMappingURL=m719-pro-hid.js.map