@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,1071 @@
1
+ /**
2
+ * Redragon M719RGB-PRO (INVADER PRO) protocol codec.
3
+ *
4
+ * The M719RGB-PRO enumerates under CompX / Areson's vendor ID (0x25a7) rather
5
+ * than Holtek (0x04d9) or SinoWealth (0x258a):
6
+ * - 0x25a7:0xfa7e — 2.4 GHz wireless receiver
7
+ * - 0x25a7:0xfab0 — wired USB cable
8
+ *
9
+ * Transport:
10
+ * - Commands are sent as 16-byte payloads on Feature Report ID 0x08
11
+ * (Usage Page 0xff02, Usage 0x0002; 17 bytes on the wire including Report ID).
12
+ * - Responses and asynchronous hardware notifications arrive on Input Report
13
+ * ID 0x09 (Usage Page 0xff01, Usage 0x0001; 16-byte payload).
14
+ * - Every 17-byte packet sums to 0x55 modulo 256:
15
+ * payload[15] = (0x55 - ((0x08 + sum(payload[0..14])) & 0xff)) & 0xff
16
+ * - Every EEPROM record also ends with a trailing data checksum byte so the
17
+ * record sums to 0x55 modulo 256.
18
+ *
19
+ * Sensor: PixArt PAW3325 (200–5,000 DPI in 100-DPI steps via non-linear hardware
20
+ * code table with hiByte = 0x00; 5,200–10,000 DPI in 200-DPI steps via
21
+ * hiByte = 0x01 and half-DPI code lookup).
22
+ */
23
+ // ── USB Identity & HID Collections ─────────────────────────────────────────
24
+ export const REDRAGON_M719_PRO_VENDOR_ID = 0x25a7;
25
+ export const REDRAGON_M719_PRO_WIRELESS_PRODUCT_ID = 0xfa7e;
26
+ export const REDRAGON_M719_PRO_WIRED_PRODUCT_ID = 0xfab0;
27
+ export const REDRAGON_M719_PRO_RECEIVER_PRODUCT_ID = REDRAGON_M719_PRO_WIRELESS_PRODUCT_ID;
28
+ export const REDRAGON_M719_PRO_COMMAND_USAGE_PAGE = 0xff02;
29
+ export const REDRAGON_M719_PRO_COMMAND_USAGE = 0x0002;
30
+ export const REDRAGON_M719_PRO_NOTIFY_USAGE_PAGE = 0xff01;
31
+ export const REDRAGON_M719_PRO_NOTIFY_USAGE = 0x0001;
32
+ export const REDRAGON_M719_PRO_COMMAND_REPORT_ID = 0x08;
33
+ export const REDRAGON_M719_PRO_RESPONSE_REPORT_ID = 0x09;
34
+ export const REDRAGON_M719_PRO_NOTIFY_REPORT_ID = 0x0a;
35
+ /** WebHID report payload length (excluding the 1-byte report ID). */
36
+ export const REDRAGON_M719_PRO_PACKET_LENGTH = 16;
37
+ /** Maximum EEPROM payload bytes carried in a single read/write frame. */
38
+ export const REDRAGON_M719_PRO_MAX_CHUNK_LENGTH = 10;
39
+ /** Modulo-256 sum target used for both packet frames and EEPROM records. */
40
+ export const REDRAGON_M719_PRO_CHECKSUM_TARGET = 0x55;
41
+ export const REDRAGON_M719_PRO_PRODUCTS = new Map([
42
+ [REDRAGON_M719_PRO_WIRELESS_PRODUCT_ID, {
43
+ name: "M719RGB-PRO",
44
+ productId: REDRAGON_M719_PRO_WIRELESS_PRODUCT_ID,
45
+ connection: "Wireless",
46
+ sensor: "PAW3325",
47
+ maxDpi: 10000,
48
+ maxPollingRate: 1000,
49
+ dpiSteps: 5,
50
+ buttons: 8,
51
+ verified: true,
52
+ }],
53
+ [REDRAGON_M719_PRO_WIRED_PRODUCT_ID, {
54
+ name: "M719RGB-PRO",
55
+ productId: REDRAGON_M719_PRO_WIRED_PRODUCT_ID,
56
+ connection: "Wired",
57
+ sensor: "PAW3325",
58
+ maxDpi: 10000,
59
+ maxPollingRate: 1000,
60
+ dpiSteps: 5,
61
+ buttons: 8,
62
+ verified: true,
63
+ }],
64
+ ]);
65
+ export const REDRAGON_M719_PRO_PRODUCT_IDS = [...REDRAGON_M719_PRO_PRODUCTS.keys()];
66
+ // ── Command Opcodes & EEPROM Layout ────────────────────────────────────────
67
+ export const REDRAGON_M719_PRO_COMMAND = {
68
+ handshake: 0x01,
69
+ tellDriverStatus: 0x02,
70
+ getConnectStatus: 0x03,
71
+ getBattery: 0x04,
72
+ writeEeprom: 0x07,
73
+ readEeprom: 0x08,
74
+ commit: 0x09,
75
+ hardwareNotify: 0x0a,
76
+ };
77
+ export const REDRAGON_M719_PRO_EEPROM = {
78
+ /** 2 bytes: [rateCode, 0x55 - rateCode]. */
79
+ pollingRate: 0x0000,
80
+ /** 2 bytes: [stageCount, 0x55 - stageCount] (1..5). */
81
+ dpiStageCount: 0x0002,
82
+ /** 2 bytes: [activeStageIndex, 0x55 - activeStageIndex] (0..4). */
83
+ activeDpiStage: 0x0004,
84
+ /** 20 bytes: 5 stages × 4 bytes [xCode, yCode, hiByte, chk]. */
85
+ dpiStages: 0x000c,
86
+ /** 20 bytes: 5 stages × 4 bytes [r, g, b, chk]. */
87
+ dpiColors: 0x002c,
88
+ /** 2 or 6 bytes: DPI indicator / logo LED mode block. */
89
+ dpiLedEffect: 0x004c,
90
+ /** 64 bytes: 16 slots × 4 bytes [b0, b1, b2, chk]. */
91
+ buttonMatrix: 0x0060,
92
+ /** 7 bytes: [hwEffect, r, g, b, hwSpeed, hwBrightness, chk]. */
93
+ rgbLighting: 0x00a0,
94
+ /** Base address for extended multimedia / key-combo payloads (0x20 bytes per slot). */
95
+ comboBase: 0x0100,
96
+ /** Stride per hardware button slot in the extended combo area. */
97
+ comboSlotStride: 0x0020,
98
+ /** Base address for onboard macro blocks (0x0180 bytes per slot). */
99
+ macroBase: 0x0300,
100
+ /** Stride per macro slot. */
101
+ macroSlotStride: 0x0180,
102
+ };
103
+ export const REDRAGON_M719_PRO_POLLING_RATES = [125, 250, 500, 1000];
104
+ export const REDRAGON_M719_PRO_MAX_DPI_STAGES = 5;
105
+ export const REDRAGON_M719_PRO_DPI_MIN = 200;
106
+ export const REDRAGON_M719_PRO_DPI_MAX = 10000;
107
+ export const REDRAGON_M719_PRO_DPI_STEP = 100;
108
+ export const REDRAGON_M719_PRO_DEFAULT_STAGES = [800, 1600, 2400, 3200, 4800];
109
+ export const REDRAGON_M719_PRO_DEFAULT_STAGE_COLORS = [
110
+ { r: 0xff, g: 0x00, b: 0x00 },
111
+ { r: 0x00, g: 0x00, b: 0xff },
112
+ { r: 0x00, g: 0xff, b: 0x00 },
113
+ { r: 0xff, g: 0x00, b: 0xff },
114
+ { r: 0xff, g: 0xff, b: 0x00 },
115
+ ];
116
+ // ── Checksum & Packet Framing ──────────────────────────────────────────────
117
+ /**
118
+ * Compute the trailing checksum byte so `[...bytes, checksum]` sums to `0x55` mod 256.
119
+ */
120
+ export function redragonM719ProDataChecksum(bytes) {
121
+ let sum = 0;
122
+ for (let i = 0; i < bytes.length; i += 1) {
123
+ sum = (sum + (bytes[i] ?? 0)) & 0xff;
124
+ }
125
+ return (REDRAGON_M719_PRO_CHECKSUM_TARGET - sum) & 0xff;
126
+ }
127
+ /**
128
+ * Validate that a buffer with its trailing checksum byte sums to `0x55` mod 256.
129
+ */
130
+ export function redragonM719ProVerifyDataChecksum(bytes) {
131
+ if (bytes.length < 2)
132
+ return false;
133
+ let sum = 0;
134
+ for (let i = 0; i < bytes.length; i += 1) {
135
+ sum = (sum + (bytes[i] ?? 0)) & 0xff;
136
+ }
137
+ return sum === REDRAGON_M719_PRO_CHECKSUM_TARGET;
138
+ }
139
+ /**
140
+ * Compute byte 15 of a 16-byte WebHID payload sent with report ID `0x08`
141
+ * (or report ID `0x09` on replies) so `(reportId + sum(payload[0..15])) & 0xff === 0x55`.
142
+ */
143
+ export function redragonM719ProPacketChecksum(payload, reportId = REDRAGON_M719_PRO_COMMAND_REPORT_ID) {
144
+ let sum = reportId & 0xff;
145
+ const limit = Math.min(payload.length, REDRAGON_M719_PRO_PACKET_LENGTH - 1);
146
+ for (let i = 0; i < limit; i += 1) {
147
+ sum = (sum + (payload[i] ?? 0)) & 0xff;
148
+ }
149
+ return (REDRAGON_M719_PRO_CHECKSUM_TARGET - sum) & 0xff;
150
+ }
151
+ /**
152
+ * Verify that a 16-byte WebHID payload (or 17-byte raw report frame) carries a
153
+ * valid trailing packet checksum byte so `(reportId + sum(payload[0..15])) & 0xff === 0x55`.
154
+ */
155
+ export function redragonM719ProVerifyPacketChecksum(rawPayload, reportId = REDRAGON_M719_PRO_RESPONSE_REPORT_ID) {
156
+ let effectiveReportId = reportId;
157
+ let payload = rawPayload;
158
+ if (rawPayload.length === REDRAGON_M719_PRO_PACKET_LENGTH + 1
159
+ && (rawPayload[0] === REDRAGON_M719_PRO_RESPONSE_REPORT_ID
160
+ || rawPayload[0] === REDRAGON_M719_PRO_COMMAND_REPORT_ID
161
+ || rawPayload[0] === REDRAGON_M719_PRO_NOTIFY_REPORT_ID)) {
162
+ effectiveReportId = rawPayload[0];
163
+ payload = rawPayload.subarray(1);
164
+ }
165
+ if (payload.length < REDRAGON_M719_PRO_PACKET_LENGTH)
166
+ return false;
167
+ return payload[15] === redragonM719ProPacketChecksum(payload, effectiveReportId);
168
+ }
169
+ /**
170
+ * Pack a 2-byte scalar record `[value, (0x55 - value) & 0xff]`.
171
+ */
172
+ export function redragonM719ProPackScalar(value) {
173
+ const b = value & 0xff;
174
+ return new Uint8Array([b, (REDRAGON_M719_PRO_CHECKSUM_TARGET - b) & 0xff]);
175
+ }
176
+ /**
177
+ * Unpack a 2-byte scalar record `[value, checksum]`, returning `null` if corrupt.
178
+ */
179
+ export function redragonM719ProUnpackScalar(bytes) {
180
+ if (bytes.length < 2)
181
+ return null;
182
+ const value = (bytes[0] ?? 0) & 0xff;
183
+ const chk = (bytes[1] ?? 0) & 0xff;
184
+ if (((value + chk) & 0xff) !== REDRAGON_M719_PRO_CHECKSUM_TARGET)
185
+ return null;
186
+ return value;
187
+ }
188
+ /**
189
+ * Build a 16-byte WebHID Feature Report 0x08 payload.
190
+ */
191
+ export function redragonM719ProEncodeCommand(command, options = {}) {
192
+ const payload = new Uint8Array(REDRAGON_M719_PRO_PACKET_LENGTH);
193
+ const address = options.address ?? 0;
194
+ const data = options.data ?? [];
195
+ if (data.length > REDRAGON_M719_PRO_MAX_CHUNK_LENGTH) {
196
+ throw new RangeError(`Redragon M719RGB-PRO packet carries at most ${REDRAGON_M719_PRO_MAX_CHUNK_LENGTH} data bytes, got ${data.length}.`);
197
+ }
198
+ payload[0] = command & 0xff;
199
+ payload[1] = (options.subCommand ?? 0) & 0xff;
200
+ payload[2] = (address >> 8) & 0xff;
201
+ payload[3] = address & 0xff;
202
+ payload[4] = (options.length ?? data.length) & 0xff;
203
+ for (let i = 0; i < data.length; i += 1) {
204
+ payload[5 + i] = (data[i] ?? 0) & 0xff;
205
+ }
206
+ payload[15] = redragonM719ProPacketChecksum(payload, REDRAGON_M719_PRO_COMMAND_REPORT_ID);
207
+ return payload;
208
+ }
209
+ /**
210
+ * Normalize an incoming input report buffer into a 16-byte payload
211
+ * (stripping a leading report ID `0x08`, `0x09`, or `0x0a` when a 17-byte raw
212
+ * wire frame is passed).
213
+ */
214
+ export function redragonM719ProNormalizeReply(raw) {
215
+ if (raw.length === REDRAGON_M719_PRO_PACKET_LENGTH + 1
216
+ && (raw[0] === REDRAGON_M719_PRO_RESPONSE_REPORT_ID
217
+ || raw[0] === REDRAGON_M719_PRO_COMMAND_REPORT_ID
218
+ || raw[0] === REDRAGON_M719_PRO_NOTIFY_REPORT_ID)) {
219
+ return raw.subarray(1);
220
+ }
221
+ return raw;
222
+ }
223
+ // ── Handshake, Link, Battery, EEPROM & Notification Commands ───────────────
224
+ const HANDSHAKE_SECRET_KEY = [0x05, 0x00, 0x00, 0x00];
225
+ /**
226
+ * Compute the 4-byte expected response for a 4-byte handshake challenge (`Cmd 0x01`).
227
+ * Verified from OEM `FUN_00442600` (`k = [0x05, 0x00, 0x00, 0x00]`).
228
+ */
229
+ export function redragonM719ProComputeHandshakeResponse(challenge) {
230
+ const [r0, r1, r2, r3] = challenge;
231
+ return [
232
+ (HANDSHAKE_SECRET_KEY[0] + r1 + r0) & 0xff,
233
+ (HANDSHAKE_SECRET_KEY[1] + r2 + ((r1 << 1) & 0xff)) & 0xff,
234
+ (HANDSHAKE_SECRET_KEY[2] + r3 + ((r2 * 3) & 0xff)) & 0xff,
235
+ (HANDSHAKE_SECRET_KEY[3] + r0 + ((r3 << 2) & 0xff)) & 0xff,
236
+ ];
237
+ }
238
+ /**
239
+ * Encode a `Handshake` (`0x01`) command packet with a 4-byte challenge.
240
+ */
241
+ export function redragonM719ProEncodeHandshake(challenge) {
242
+ return redragonM719ProEncodeCommand(REDRAGON_M719_PRO_COMMAND.handshake, {
243
+ data: challenge,
244
+ });
245
+ }
246
+ /**
247
+ * Verify the device's reply to a `Handshake` (`0x01`) challenge against the
248
+ * expected 4-byte response derived from `challenge`.
249
+ */
250
+ export function redragonM719ProVerifyHandshakeReply(challenge, rawReply) {
251
+ const reply = redragonM719ProNormalizeReply(rawReply);
252
+ if (reply.length < 9 || reply[0] !== REDRAGON_M719_PRO_COMMAND.handshake || reply[1] !== 0x00) {
253
+ return false;
254
+ }
255
+ const expected = redragonM719ProComputeHandshakeResponse(challenge);
256
+ return reply[5] === expected[0]
257
+ && reply[6] === expected[1]
258
+ && reply[7] === expected[2]
259
+ && reply[8] === expected[3];
260
+ }
261
+ /**
262
+ * Encode a `TellDriverStatus` (`0x02`) command packet notifying the mouse
263
+ * whether the host driver is active (`online = true`).
264
+ */
265
+ export function redragonM719ProEncodeTellDriverStatus(online = true) {
266
+ return redragonM719ProEncodeCommand(REDRAGON_M719_PRO_COMMAND.tellDriverStatus, {
267
+ data: [online ? 0x01 : 0x00],
268
+ });
269
+ }
270
+ /**
271
+ * Encode a `GetConnectStatus` (`0x03`) command packet querying whether the
272
+ * wireless mouse is awake and linked to the 2.4 GHz receiver.
273
+ */
274
+ export function redragonM719ProEncodeGetConnectStatus() {
275
+ return redragonM719ProEncodeCommand(REDRAGON_M719_PRO_COMMAND.getConnectStatus);
276
+ }
277
+ /**
278
+ * Decode a `GetConnectStatus` (`0x03`) reply.
279
+ * In the 16-byte payload, `reply[4]` is the parameter length (`0x01`) and
280
+ * `reply[5]` is the online flag (`0x01` = online, `0x00` = offline). Some
281
+ * firmware revisions place the flag directly in `reply[4]` with `reply[5] == 0`.
282
+ */
283
+ export function redragonM719ProDecodeConnectStatus(rawReply) {
284
+ const reply = redragonM719ProNormalizeReply(rawReply);
285
+ if (reply.length < 6 || reply[0] !== REDRAGON_M719_PRO_COMMAND.getConnectStatus || reply[1] !== 0x00) {
286
+ return false;
287
+ }
288
+ if (reply[4] === 0x01) {
289
+ return (reply[5] ?? 0) !== 0;
290
+ }
291
+ return (reply[5] ?? 0) !== 0 || (reply[4] ?? 0) !== 0;
292
+ }
293
+ /**
294
+ * Encode a `GetBattery` (`0x04`) command packet querying the current battery
295
+ * level and charging flag.
296
+ */
297
+ export function redragonM719ProEncodeGetBattery() {
298
+ return redragonM719ProEncodeCommand(REDRAGON_M719_PRO_COMMAND.getBattery);
299
+ }
300
+ /**
301
+ * Decode a `GetBattery` (`0x04`) reply.
302
+ * Verified from OEM `FUN_00409d00`:
303
+ * - `reply[5]` carries the battery level (`0..100` directly in 2-byte replies where
304
+ * `reply[4]` is `0x02` or `0x00`, or `0..10` in 10% steps when `reply[3] === 0x0a`
305
+ * or `reply[4] === 0x01`; bit 7 may also flag charging).
306
+ * - `reply[6]` is the charging flag (`0x01` = charging, `0x00` = discharging).
307
+ */
308
+ export function redragonM719ProDecodeBattery(rawReply) {
309
+ const reply = redragonM719ProNormalizeReply(rawReply);
310
+ if (reply.length < 7 || reply[0] !== REDRAGON_M719_PRO_COMMAND.getBattery || reply[1] !== 0x00) {
311
+ return null;
312
+ }
313
+ const paramLen = reply[4] ?? 0;
314
+ const rawByte = reply[5] ?? 0;
315
+ const chargeByte = reply[6] ?? 0;
316
+ const rawLevel = rawByte & 0x7f;
317
+ if (rawLevel === 0 && chargeByte === 0 && paramLen === 0) {
318
+ return null;
319
+ }
320
+ const charging = chargeByte !== 0 || (rawByte & 0x80) !== 0;
321
+ const isTenStep = reply[3] === 0x0a || paramLen === 0x01;
322
+ const percent = isTenStep && rawLevel <= 10
323
+ ? Math.max(0, Math.min(100, rawLevel * 10))
324
+ : Math.max(0, Math.min(100, rawLevel));
325
+ return { percent, charging, rawLevel };
326
+ }
327
+ /**
328
+ * Encode a `ReadEeprom` (`0x08`) command packet for `1..10` bytes at `address`.
329
+ */
330
+ export function redragonM719ProEncodeReadEeprom(address, length) {
331
+ if (!Number.isInteger(length) || length < 1 || length > REDRAGON_M719_PRO_MAX_CHUNK_LENGTH) {
332
+ throw new RangeError(`EEPROM read length must be 1–${REDRAGON_M719_PRO_MAX_CHUNK_LENGTH}, got ${length}.`);
333
+ }
334
+ return redragonM719ProEncodeCommand(REDRAGON_M719_PRO_COMMAND.readEeprom, {
335
+ address,
336
+ length,
337
+ });
338
+ }
339
+ /**
340
+ * Decode and validate a `ReadEeprom` (`0x08`) reply, checking the echoed
341
+ * 16-bit EEPROM address (`reply[2..3]`) and declared data length (`reply[4]`).
342
+ */
343
+ export function redragonM719ProDecodeReadEeprom(rawReply, expectedAddress, expectedLength) {
344
+ const reply = redragonM719ProNormalizeReply(rawReply);
345
+ if (reply.length < 5 + expectedLength)
346
+ return null;
347
+ if (reply[0] !== REDRAGON_M719_PRO_COMMAND.readEeprom || reply[1] !== 0x00)
348
+ return null;
349
+ const addrHi = (expectedAddress >> 8) & 0xff;
350
+ const addrLo = expectedAddress & 0xff;
351
+ if (reply[2] !== addrHi || reply[3] !== addrLo)
352
+ return null;
353
+ if ((reply[4] ?? 0) < expectedLength)
354
+ return null;
355
+ return Uint8Array.from(reply.subarray(5, 5 + expectedLength));
356
+ }
357
+ /**
358
+ * Encode a `WriteEeprom` (`0x07`) command packet for `1..10` bytes at `address`.
359
+ */
360
+ export function redragonM719ProEncodeWriteEeprom(address, data) {
361
+ if (data.length < 1 || data.length > REDRAGON_M719_PRO_MAX_CHUNK_LENGTH) {
362
+ throw new RangeError(`EEPROM write length must be 1–${REDRAGON_M719_PRO_MAX_CHUNK_LENGTH}, got ${data.length}.`);
363
+ }
364
+ return redragonM719ProEncodeCommand(REDRAGON_M719_PRO_COMMAND.writeEeprom, {
365
+ address,
366
+ data,
367
+ });
368
+ }
369
+ /**
370
+ * Decode the status byte (`reply[1]`) of a `WriteEeprom` (`0x07`) response into
371
+ * `"ack"` (`0x00`), `"busy"` (`0x01`), or `"error"`.
372
+ */
373
+ export function redragonM719ProDecodeWriteEeprom(rawReply) {
374
+ const reply = redragonM719ProNormalizeReply(rawReply);
375
+ if (reply.length < 2 || reply[0] !== REDRAGON_M719_PRO_COMMAND.writeEeprom)
376
+ return "error";
377
+ if (reply[1] === 0x00)
378
+ return "ack";
379
+ if (reply[1] === 0x01)
380
+ return "busy";
381
+ return "error";
382
+ }
383
+ /**
384
+ * Decode an asynchronous MCU notification (`Cmd 0x0a` on Report `0x09` or `0x0a`).
385
+ * Verified from OEM `FUN_004428e0`:
386
+ * - Bit 0 (`0x01`) of flags byte (`payload[5]`): DPI stage changed to `payload[6] & 0x0f` (0..4)
387
+ * - Bit 1 (`0x02`) of flags byte (`payload[5]`): Profile changed to `(payload[7] & 0x0f) + 1` (1..5)
388
+ */
389
+ export function redragonM719ProDecodeHardwareNotification(rawReport, reportId = REDRAGON_M719_PRO_RESPONSE_REPORT_ID) {
390
+ let payload = rawReport;
391
+ if (payload.length === REDRAGON_M719_PRO_PACKET_LENGTH + 1
392
+ && (payload[0] === REDRAGON_M719_PRO_RESPONSE_REPORT_ID || payload[0] === REDRAGON_M719_PRO_NOTIFY_REPORT_ID)) {
393
+ reportId = payload[0];
394
+ payload = payload.subarray(1);
395
+ }
396
+ let flags = 0;
397
+ let dpiRaw = 0;
398
+ let profileRaw = 0;
399
+ if (reportId === REDRAGON_M719_PRO_RESPONSE_REPORT_ID && payload[0] === REDRAGON_M719_PRO_COMMAND.hardwareNotify) {
400
+ if (payload.length < 8)
401
+ return null;
402
+ flags = payload[5] ?? 0;
403
+ dpiRaw = payload[6] ?? 0;
404
+ profileRaw = payload[7] ?? 0;
405
+ }
406
+ else if (reportId === REDRAGON_M719_PRO_NOTIFY_REPORT_ID) {
407
+ if (payload.length < 7)
408
+ return null;
409
+ flags = payload[4] ?? 0;
410
+ dpiRaw = payload[5] ?? 0;
411
+ profileRaw = payload[6] ?? 0;
412
+ }
413
+ else {
414
+ return null;
415
+ }
416
+ if ((flags & 0x03) === 0)
417
+ return null;
418
+ const result = {};
419
+ if ((flags & 0x01) !== 0) {
420
+ result.activeDpiStage = Math.min(REDRAGON_M719_PRO_MAX_DPI_STAGES - 1, dpiRaw & 0x0f);
421
+ }
422
+ if ((flags & 0x02) !== 0) {
423
+ result.activeProfile = Math.min(5, (profileRaw & 0x0f) + 1);
424
+ }
425
+ return result;
426
+ }
427
+ // ── Polling Rate Codec (EEPROM 0x0000) ─────────────────────────────────────
428
+ const POLLING_RATE_TO_CODE = new Map([
429
+ [1000, 0x01],
430
+ [500, 0x02],
431
+ [250, 0x04],
432
+ [125, 0x08],
433
+ ]);
434
+ const CODE_TO_POLLING_RATE = new Map([
435
+ [0x01, 1000],
436
+ [0x02, 500],
437
+ [0x04, 250],
438
+ [0x08, 125],
439
+ ]);
440
+ /**
441
+ * Encode a polling rate in Hz (`125`, `250`, `500`, or `1000`) into its 2-byte
442
+ * EEPROM scalar record at `0x0000`.
443
+ */
444
+ export function redragonM719ProEncodePollingRate(hz) {
445
+ const code = POLLING_RATE_TO_CODE.get(hz);
446
+ if (code === undefined) {
447
+ throw new RangeError(`Unsupported Redragon M719RGB-PRO polling rate: ${hz} Hz.`);
448
+ }
449
+ return redragonM719ProPackScalar(code);
450
+ }
451
+ /**
452
+ * Decode a 2-byte polling-rate record from EEPROM `0x0000` into Hz.
453
+ */
454
+ export function redragonM719ProDecodePollingRate(bytes) {
455
+ const code = bytes[0] ?? 0x01;
456
+ return CODE_TO_POLLING_RATE.get(code) ?? 1000;
457
+ }
458
+ // ── PAW3325 Sensor DPI Codec (EEPROM 0x000C) ───────────────────────────────
459
+ /**
460
+ * Authentic PAW3325 DPI lookup table extracted from `Cfg.ini` / `FUN_0040b910`:
461
+ * 49 entries covering 200 to 5,000 DPI in 100-DPI increments.
462
+ * Above 5,000 DPI (up to 10,000 DPI in 200-DPI increments), `hiByte = 0x01`
463
+ * and the hardware code is looked up for `dpi / 2`.
464
+ */
465
+ export const REDRAGON_M719_PRO_PAW3325_DPI_TABLE = [
466
+ 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100,
467
+ 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100,
468
+ 2200, 2300, 2400, 2500, 2600, 2700, 2800, 2900, 3000, 3100,
469
+ 3200, 3300, 3400, 3500, 3600, 3700, 3800, 3900, 4000, 4100,
470
+ 4200, 4300, 4400, 4500, 4600, 4700, 4800, 4900, 5000,
471
+ ];
472
+ export const REDRAGON_M719_PRO_PAW3325_CODE_TABLE = [
473
+ 0x04, 0x06, 0x08, 0x0b, 0x0d, 0x0f, 0x12, 0x14, 0x16, 0x19,
474
+ 0x1b, 0x1d, 0x20, 0x22, 0x24, 0x27, 0x29, 0x2b, 0x2e, 0x30,
475
+ 0x32, 0x34, 0x37, 0x39, 0x3b, 0x3e, 0x40, 0x42, 0x45, 0x47,
476
+ 0x49, 0x4c, 0x4e, 0x50, 0x53, 0x55, 0x57, 0x5a, 0x5c, 0x5e,
477
+ 0x61, 0x63, 0x65, 0x68, 0x6a, 0x6c, 0x6f, 0x71, 0x73,
478
+ ];
479
+ /**
480
+ * Every distinct DPI value the PAW3325 hardware table can represent:
481
+ * 200–5,000 DPI in 100-DPI steps, then 5,200–10,000 DPI in 200-DPI steps.
482
+ */
483
+ export const REDRAGON_M719_PRO_DPI_OPTIONS = [
484
+ ...REDRAGON_M719_PRO_PAW3325_DPI_TABLE,
485
+ ...REDRAGON_M719_PRO_PAW3325_DPI_TABLE.filter((dpi) => dpi >= 2600).map((dpi) => dpi * 2),
486
+ ];
487
+ /**
488
+ * Snap an arbitrary DPI number to the nearest supported PAW3325 hardware step.
489
+ */
490
+ export function redragonM719ProNearestDpi(dpi) {
491
+ const clamped = Math.max(REDRAGON_M719_PRO_DPI_MIN, Math.min(REDRAGON_M719_PRO_DPI_MAX, Math.round(dpi)));
492
+ let best = REDRAGON_M719_PRO_DPI_OPTIONS[0];
493
+ let minDiff = Math.abs(clamped - best);
494
+ for (const candidate of REDRAGON_M719_PRO_DPI_OPTIONS) {
495
+ const diff = Math.abs(clamped - candidate);
496
+ if (diff < minDiff) {
497
+ minDiff = diff;
498
+ best = candidate;
499
+ }
500
+ }
501
+ return best;
502
+ }
503
+ /**
504
+ * Encode a DPI value into the 4-byte PAW3325 EEPROM stage record
505
+ * `[xCode, yCode, hiByte, checksum]`.
506
+ */
507
+ export function redragonM719ProEncodeDpiStage(dpi) {
508
+ if (!Number.isFinite(dpi) || dpi < REDRAGON_M719_PRO_DPI_MIN || dpi > REDRAGON_M719_PRO_DPI_MAX) {
509
+ throw new RangeError(`Redragon M719RGB-PRO DPI must be between ${REDRAGON_M719_PRO_DPI_MIN} and ${REDRAGON_M719_PRO_DPI_MAX}, got ${dpi}.`);
510
+ }
511
+ const snapped = redragonM719ProNearestDpi(dpi);
512
+ const hiRange = snapped > 5000;
513
+ const effectiveDpi = hiRange ? Math.round(snapped / 2) : snapped;
514
+ let bestIndex = 0;
515
+ let minDiff = Number.MAX_SAFE_INTEGER;
516
+ for (let i = 0; i < REDRAGON_M719_PRO_PAW3325_DPI_TABLE.length; i += 1) {
517
+ const tableDpi = REDRAGON_M719_PRO_PAW3325_DPI_TABLE[i];
518
+ const diff = Math.abs(effectiveDpi - tableDpi);
519
+ if (diff < minDiff) {
520
+ minDiff = diff;
521
+ bestIndex = i;
522
+ }
523
+ }
524
+ const code = REDRAGON_M719_PRO_PAW3325_CODE_TABLE[bestIndex];
525
+ const hiByte = hiRange ? 0x01 : 0x00;
526
+ const chk = (REDRAGON_M719_PRO_CHECKSUM_TARGET - ((code + code + hiByte) & 0xff)) & 0xff;
527
+ return new Uint8Array([code, code, hiByte, chk]);
528
+ }
529
+ /**
530
+ * Decode a 4-byte PAW3325 EEPROM stage record `[xCode, yCode, hiByte, checksum]`.
531
+ */
532
+ export function redragonM719ProDecodeDpiStage(bytes) {
533
+ const code = bytes[0] ?? 0x12;
534
+ const hiRange = (bytes[2] ?? 0) !== 0;
535
+ let bestIndex = 0;
536
+ let minDiff = 0xff;
537
+ for (let i = 0; i < REDRAGON_M719_PRO_PAW3325_CODE_TABLE.length; i += 1) {
538
+ const tableCode = REDRAGON_M719_PRO_PAW3325_CODE_TABLE[i];
539
+ const diff = Math.abs(code - tableCode);
540
+ if (diff < minDiff) {
541
+ minDiff = diff;
542
+ bestIndex = i;
543
+ }
544
+ }
545
+ const baseDpi = REDRAGON_M719_PRO_PAW3325_DPI_TABLE[bestIndex] ?? 800;
546
+ return hiRange ? baseDpi * 2 : baseDpi;
547
+ }
548
+ /**
549
+ * Encode all 5 DPI stages into the 20-byte block at `0x000c`.
550
+ */
551
+ export function redragonM719ProEncodeDpiStages(stages) {
552
+ const block = new Uint8Array(REDRAGON_M719_PRO_MAX_DPI_STAGES * 4);
553
+ for (let i = 0; i < REDRAGON_M719_PRO_MAX_DPI_STAGES; i += 1) {
554
+ const dpi = stages[i] ?? REDRAGON_M719_PRO_DEFAULT_STAGES[i] ?? 800;
555
+ block.set(redragonM719ProEncodeDpiStage(dpi), i * 4);
556
+ }
557
+ return block;
558
+ }
559
+ /**
560
+ * Decode the 20-byte DPI stage block at `0x000c` into 5 DPI values.
561
+ */
562
+ export function redragonM719ProDecodeDpiStages(bytes) {
563
+ const stages = [];
564
+ for (let i = 0; i < REDRAGON_M719_PRO_MAX_DPI_STAGES; i += 1) {
565
+ const offset = i * 4;
566
+ if (offset + 4 <= bytes.length) {
567
+ stages.push(redragonM719ProDecodeDpiStage(bytes.subarray(offset, offset + 4)));
568
+ }
569
+ else {
570
+ stages.push(REDRAGON_M719_PRO_DEFAULT_STAGES[i]);
571
+ }
572
+ }
573
+ return stages;
574
+ }
575
+ // ── DPI Stage Colors & DPI Indicator LED Codec (EEPROM 0x002C & 0x004C) ────
576
+ /**
577
+ * Encode a single DPI stage's RGB colour into a 4-byte EEPROM record `[r, g, b, checksum]`.
578
+ */
579
+ export function redragonM719ProEncodeDpiStageColor(color) {
580
+ const r = color.r & 0xff;
581
+ const g = color.g & 0xff;
582
+ const b = color.b & 0xff;
583
+ const chk = (REDRAGON_M719_PRO_CHECKSUM_TARGET - ((r + g + b) & 0xff)) & 0xff;
584
+ return new Uint8Array([r, g, b, chk]);
585
+ }
586
+ /**
587
+ * Decode a 4-byte DPI stage colour record `[r, g, b, checksum]` into RGB channels.
588
+ */
589
+ export function redragonM719ProDecodeDpiStageColor(bytes) {
590
+ return {
591
+ r: (bytes[0] ?? 0xff) & 0xff,
592
+ g: (bytes[1] ?? 0x00) & 0xff,
593
+ b: (bytes[2] ?? 0x00) & 0xff,
594
+ };
595
+ }
596
+ /**
597
+ * Encode all 5 DPI stage RGB colours into the 20-byte block at EEPROM `0x002c`.
598
+ */
599
+ export function redragonM719ProEncodeDpiStageColors(colors) {
600
+ const block = new Uint8Array(REDRAGON_M719_PRO_MAX_DPI_STAGES * 4);
601
+ for (let i = 0; i < REDRAGON_M719_PRO_MAX_DPI_STAGES; i += 1) {
602
+ const color = colors[i] ?? REDRAGON_M719_PRO_DEFAULT_STAGE_COLORS[i];
603
+ block.set(redragonM719ProEncodeDpiStageColor(color), i * 4);
604
+ }
605
+ return block;
606
+ }
607
+ /**
608
+ * Decode the 20-byte DPI stage colour block at EEPROM `0x002c` into 5 RGB objects.
609
+ */
610
+ export function redragonM719ProDecodeDpiStageColors(bytes) {
611
+ const colors = [];
612
+ for (let i = 0; i < REDRAGON_M719_PRO_MAX_DPI_STAGES; i += 1) {
613
+ const offset = i * 4;
614
+ if (offset + 3 <= bytes.length) {
615
+ colors.push(redragonM719ProDecodeDpiStageColor(bytes.subarray(offset, offset + 4)));
616
+ }
617
+ else {
618
+ colors.push({ ...REDRAGON_M719_PRO_DEFAULT_STAGE_COLORS[i] });
619
+ }
620
+ }
621
+ return colors;
622
+ }
623
+ /**
624
+ * DPI indicator / logo LED mode values at EEPROM `0x004c`:
625
+ * - `0` (`0x00`): Off
626
+ * - `1` (`0x01`): Steady
627
+ * - `2` (`0x02`): Respiration (Breathing)
628
+ */
629
+ export const REDRAGON_M719_PRO_DPI_LED_MODES = [0, 1, 2];
630
+ /**
631
+ * Encode the DPI indicator LED block at `0x004c`.
632
+ * Verified from OEM `FUN_0040b350` (`dec1.c` lines 1995–2042):
633
+ * - Off (`0`): `[0x00, 0x55]`
634
+ * - Steady (`1`) / Breathing (`2`): `[mode, 0x55 - mode, 0xff, 0x56, activeStage, 0x55 - activeStage]`
635
+ */
636
+ export function redragonM719ProEncodeDpiLedEffect(mode, activeStage = 0) {
637
+ if (mode === 0) {
638
+ return new Uint8Array([0x00, 0x55]);
639
+ }
640
+ const eff = mode & 0xff;
641
+ const stageIdx = Math.max(0, Math.min(REDRAGON_M719_PRO_MAX_DPI_STAGES - 1, activeStage)) & 0xff;
642
+ return new Uint8Array([
643
+ eff,
644
+ (REDRAGON_M719_PRO_CHECKSUM_TARGET - eff) & 0xff,
645
+ 0xff,
646
+ (REDRAGON_M719_PRO_CHECKSUM_TARGET - 0xff) & 0xff,
647
+ stageIdx,
648
+ (REDRAGON_M719_PRO_CHECKSUM_TARGET - stageIdx) & 0xff,
649
+ ]);
650
+ }
651
+ /**
652
+ * Decode the DPI indicator LED mode byte from EEPROM `0x004c` into `0` (Off),
653
+ * `1` (Steady), or `2` (Breathing).
654
+ */
655
+ export function redragonM719ProDecodeDpiLedEffect(bytes) {
656
+ const raw = bytes[0] ?? 0;
657
+ if (raw === 1 || raw === 2)
658
+ return raw;
659
+ return 0;
660
+ }
661
+ // ── Main RGB Lighting Codec (EEPROM 0x00A0) ────────────────────────────────
662
+ export const REDRAGON_M719_PRO_RGB_EFFECT = {
663
+ neon: 0x00,
664
+ breathing: 0x01,
665
+ steady: 0x02,
666
+ off: 0x04,
667
+ };
668
+ /** Speed lookup table (levels 1..10) for Steady / Breathing modes (`DAT_00462fc8`). */
669
+ export const REDRAGON_M719_PRO_SPEED_LUT = [
670
+ 0xff, 0xe6, 0xd2, 0xbe, 0xaa, 0x96, 0x82, 0x6e, 0x46, 0x28,
671
+ ];
672
+ /** Speed lookup table (levels 1..10) for Neon mode (`DAT_00462fd4`). */
673
+ export const REDRAGON_M719_PRO_NEON_SPEED_LUT = [
674
+ 0x2d, 0x28, 0x23, 0x1e, 0x19, 0x13, 0x0f, 0x0a, 0x05, 0x03,
675
+ ];
676
+ /** Brightness lookup table (levels 1..10 -> 10%..100%) (`DAT_00462fe0`). */
677
+ export const REDRAGON_M719_PRO_BRIGHTNESS_LUT = [
678
+ 0x19, 0x32, 0x4b, 0x64, 0x7d, 0x96, 0xaf, 0xc8, 0xe1, 0xff,
679
+ ];
680
+ export const REDRAGON_M719_PRO_SPEED_LEVELS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
681
+ export const REDRAGON_M719_PRO_BRIGHTNESS_PERCENTS = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
682
+ /**
683
+ * Find the 1-based level (`1..10`) in a hardware lookup table closest to `rawByte`.
684
+ */
685
+ function reverseLut(lut, rawByte) {
686
+ let bestIndex = 0;
687
+ let minDiff = 0xff;
688
+ for (let i = 0; i < lut.length; i += 1) {
689
+ const diff = Math.abs(rawByte - lut[i]);
690
+ if (diff < minDiff) {
691
+ minDiff = diff;
692
+ bestIndex = i;
693
+ }
694
+ }
695
+ return bestIndex + 1;
696
+ }
697
+ /**
698
+ * Encode the 7-byte main RGB lighting block at EEPROM `0x00a0`:
699
+ * `[hwEffect, r, g, b, hwSpeed, hwBrightness, checksum]`.
700
+ */
701
+ export function redragonM719ProEncodeRgbLighting(config) {
702
+ const effect = config.effect;
703
+ const r = config.color.r & 0xff;
704
+ const g = config.color.g & 0xff;
705
+ const b = config.color.b & 0xff;
706
+ const speedLevel = Math.max(1, Math.min(10, Math.round(config.speed)));
707
+ const brightnessLevel = Math.max(1, Math.min(10, Math.round(config.brightness)));
708
+ let hwSpeed = 0x00;
709
+ let hwBrightness = 0x00;
710
+ if (effect !== REDRAGON_M719_PRO_RGB_EFFECT.off) {
711
+ hwSpeed = effect === REDRAGON_M719_PRO_RGB_EFFECT.neon
712
+ ? REDRAGON_M719_PRO_NEON_SPEED_LUT[speedLevel - 1]
713
+ : REDRAGON_M719_PRO_SPEED_LUT[speedLevel - 1];
714
+ hwBrightness = REDRAGON_M719_PRO_BRIGHTNESS_LUT[brightnessLevel - 1];
715
+ }
716
+ const bytes = [effect, r, g, b, hwSpeed, hwBrightness];
717
+ return new Uint8Array([...bytes, redragonM719ProDataChecksum(bytes)]);
718
+ }
719
+ /**
720
+ * Decode the 7-byte main RGB lighting block from EEPROM `0x00a0`.
721
+ */
722
+ export function redragonM719ProDecodeRgbLighting(bytes) {
723
+ const rawEffect = bytes[0] ?? REDRAGON_M719_PRO_RGB_EFFECT.steady;
724
+ const effect = rawEffect === REDRAGON_M719_PRO_RGB_EFFECT.neon
725
+ || rawEffect === REDRAGON_M719_PRO_RGB_EFFECT.breathing
726
+ || rawEffect === REDRAGON_M719_PRO_RGB_EFFECT.steady
727
+ || rawEffect === REDRAGON_M719_PRO_RGB_EFFECT.off
728
+ ? rawEffect
729
+ : REDRAGON_M719_PRO_RGB_EFFECT.off;
730
+ const color = {
731
+ r: (bytes[1] ?? 0xff) & 0xff,
732
+ g: (bytes[2] ?? 0x00) & 0xff,
733
+ b: (bytes[3] ?? 0x00) & 0xff,
734
+ };
735
+ const spdByte = bytes[4] ?? 0x96;
736
+ const briByte = bytes[5] ?? 0xff;
737
+ const speed = spdByte === 0
738
+ ? 5
739
+ : effect === REDRAGON_M719_PRO_RGB_EFFECT.neon
740
+ ? reverseLut(REDRAGON_M719_PRO_NEON_SPEED_LUT, spdByte)
741
+ : reverseLut(REDRAGON_M719_PRO_SPEED_LUT, spdByte);
742
+ const brightness = briByte === 0 ? 10 : reverseLut(REDRAGON_M719_PRO_BRIGHTNESS_LUT, briByte);
743
+ return { effect, color, speed, brightness };
744
+ }
745
+ // ── Button Matrix & Extended Multimedia / Key Combo Codec ──────────────────
746
+ /**
747
+ * Physical buttons on the Redragon M719RGB-PRO and their hardware slot indices
748
+ * in the 16-slot matrix at `0x0060..0x009f` (`slotOffset = 0x0060 + slot * 4`).
749
+ *
750
+ * Verified from OEM `pro.dct` (`+0x23C MatrixInx+1`) and Wireshark captures:
751
+ * - Button 1 (Left): slot 0 (`0x0060`)
752
+ * - Button 2 (Right): slot 1 (`0x0064`)
753
+ * - Button 3 (Middle / Wheel click): slot 2 (`0x0068`)
754
+ * - Button 4 (Forward): slot 4 (`0x0070`)
755
+ * - Button 5 (Back): slot 3 (`0x006c`)
756
+ * - Button 6 (Fire): slot 8 (`0x0080`)
757
+ * - Button 7 (DPI up): slot 10 (`0x0088`)
758
+ * - Button 8 (DPI down): slot 11 (`0x008c`)
759
+ * (Slot 6 at `0x0078` is the physical bottom Profile Switch button `[0x09, 0x00, 0x00, 0x4c]`.)
760
+ */
761
+ export const REDRAGON_M719_PRO_BUTTONS = [
762
+ { label: "Left (1)", slot: 0, offset: 0x0060 },
763
+ { label: "Right (2)", slot: 1, offset: 0x0064 },
764
+ { label: "Wheel click (3)", slot: 2, offset: 0x0068 },
765
+ { label: "Forward (4)", slot: 4, offset: 0x0070 },
766
+ { label: "Back (5)", slot: 3, offset: 0x006c },
767
+ { label: "Fire (6)", slot: 8, offset: 0x0080 },
768
+ { label: "DPI up (7)", slot: 10, offset: 0x0088 },
769
+ { label: "DPI down (8)", slot: 11, offset: 0x008c },
770
+ ];
771
+ /** Direct 4-byte matrix actions (`[b0, b1, b2]`). */
772
+ const DIRECT_BUTTON_ACTIONS = [
773
+ ["Left click", [0x01, 0x01, 0x00]],
774
+ ["Right click", [0x01, 0x02, 0x00]],
775
+ ["Middle click", [0x01, 0x04, 0x00]],
776
+ ["Back", [0x01, 0x08, 0x00]],
777
+ ["Forward", [0x01, 0x10, 0x00]],
778
+ ["Three click", [0x04, 0x32, 0x03]],
779
+ ["DPI cycle", [0x02, 0x01, 0x00]],
780
+ ["DPI up", [0x02, 0x02, 0x00]],
781
+ ["DPI down", [0x02, 0x03, 0x00]],
782
+ ["Polling rate switch", [0x07, 0x00, 0x00]],
783
+ ["RGB on/off", [0x08, 0x00, 0x00]],
784
+ ["Profile switch", [0x09, 0x00, 0x00]],
785
+ ["Disabled", [0x00, 0x00, 0x00]],
786
+ ];
787
+ /** Multimedia actions stored as `[0x05, 0x00, 0x00, 0x50]` + consumer usage at `0x0100 + slot * 0x20`. */
788
+ const MULTIMEDIA_ACTIONS = [
789
+ ["Media player", 0x0183],
790
+ ["Play/Pause", 0x00cd],
791
+ ["Next track", 0x00b5],
792
+ ["Previous track", 0x00b6],
793
+ ["Stop", 0x00b7],
794
+ ["Mute", 0x00e2],
795
+ ["Volume up", 0x00e9],
796
+ ["Volume down", 0x00ea],
797
+ ["Email", 0x018a],
798
+ ["Calculator", 0x0192],
799
+ ["My computer", 0x0194],
800
+ ["Web home", 0x0223],
801
+ ["Web search", 0x0221],
802
+ ["Web forward", 0x0225],
803
+ ["Web back", 0x0224],
804
+ ["Web stop", 0x0226],
805
+ ["Web refresh", 0x0227],
806
+ ["Web favorites", 0x022a],
807
+ ];
808
+ /** Common keyboard shortcuts stored as `[0x05, 0x00, 0x00, 0x50]` + key events at `0x0100 + slot * 0x20`. */
809
+ const SHORTCUT_ACTIONS = [
810
+ // [label, modifierMask (1=Ctrl, 2=Shift, 4=Alt, 8=Win), hidKeyUsage]
811
+ ["Copy (Ctrl+C)", 0x01, 0x06],
812
+ ["Paste (Ctrl+V)", 0x01, 0x19],
813
+ ["Cut (Ctrl+X)", 0x01, 0x1b],
814
+ ["Undo (Ctrl+Z)", 0x01, 0x1d],
815
+ ["Select all (Ctrl+A)", 0x01, 0x04],
816
+ ["Find (Ctrl+F)", 0x01, 0x09],
817
+ ["New (Ctrl+N)", 0x01, 0x11],
818
+ ["Print (Ctrl+P)", 0x01, 0x13],
819
+ ["Save (Ctrl+S)", 0x01, 0x16],
820
+ ["Close window (Alt+F4)", 0x04, 0x3d],
821
+ ["Show desktop (Win+D)", 0x08, 0x07],
822
+ ["Explorer (Win+E)", 0x08, 0x08],
823
+ ["Run (Win+R)", 0x08, 0x15],
824
+ ["Lock PC (Win+L)", 0x08, 0x0f],
825
+ ["Task Manager (Ctrl+Shift+Esc)", 0x03, 0x29],
826
+ ];
827
+ const KEY_USAGES = [
828
+ ...Array.from({ length: 26 }, (_, i) => [String.fromCharCode(65 + i), 0x04 + i]),
829
+ ...Array.from({ length: 9 }, (_, i) => [String(i + 1), 0x1e + i]),
830
+ ["0", 0x27],
831
+ ["Enter", 0x28],
832
+ ["Esc", 0x29],
833
+ ["Backspace", 0x2a],
834
+ ["Tab", 0x2b],
835
+ ["Space", 0x2c],
836
+ ["-", 0x2d],
837
+ ["=", 0x2e],
838
+ ...Array.from({ length: 12 }, (_, i) => [`F${i + 1}`, 0x3a + i]),
839
+ ["Insert", 0x49],
840
+ ["Home", 0x4a],
841
+ ["Page Up", 0x4b],
842
+ ["Delete", 0x4c],
843
+ ["End", 0x4d],
844
+ ["Page Down", 0x4e],
845
+ ["Right arrow", 0x4f],
846
+ ["Left arrow", 0x50],
847
+ ["Down arrow", 0x51],
848
+ ["Up arrow", 0x52],
849
+ ];
850
+ const KEY_BY_NAME = new Map(KEY_USAGES.map(([name, usage]) => [name.toLowerCase(), usage]));
851
+ const KEY_BY_USAGE = new Map(KEY_USAGES.map(([name, usage]) => [usage, name]));
852
+ const DIRECT_BY_LABEL = new Map(DIRECT_BUTTON_ACTIONS);
853
+ const MULTIMEDIA_BY_LABEL = new Map(MULTIMEDIA_ACTIONS);
854
+ const MULTIMEDIA_BY_CODE = new Map(MULTIMEDIA_ACTIONS.map(([label, code]) => [code, label]));
855
+ const SHORTCUT_BY_LABEL = new Map(SHORTCUT_ACTIONS.map(([label, mods, key]) => [label, [mods, key]]));
856
+ export const REDRAGON_M719_PRO_BUTTON_ACTIONS = [
857
+ ...DIRECT_BUTTON_ACTIONS.map(([label]) => label),
858
+ ...MULTIMEDIA_ACTIONS.map(([label]) => label),
859
+ ...SHORTCUT_ACTIONS.map(([label]) => label),
860
+ ...KEY_USAGES.map(([name]) => `Key ${name}`),
861
+ ];
862
+ /**
863
+ * Encode a 16-bit HID Consumer usage into the 10-byte EEPROM block at `0x0100 + slot * 0x20`.
864
+ * Format: `[0x02, 0x82, lo, hi, 0x42, lo, hi, chk, 0x00, 0x00]`.
865
+ */
866
+ export function redragonM719ProEncodeMultimediaPayload(consumerCode) {
867
+ const lo = consumerCode & 0xff;
868
+ const hi = (consumerCode >> 8) & 0xff;
869
+ const body = [0x02, 0x82, lo, hi, 0x42, lo, hi];
870
+ const buf = new Uint8Array(10);
871
+ buf.set(body, 0);
872
+ buf[7] = redragonM719ProDataChecksum(body);
873
+ return buf;
874
+ }
875
+ /**
876
+ * Encode a modifier mask (`0x01` Ctrl, `0x02` Shift, `0x04` Alt, `0x08` Win) and
877
+ * HID keyboard usage into the EEPROM block at `0x0100 + slot * 0x20` (capped at
878
+ * the 32-byte `comboSlotStride`).
879
+ * Verified from OEM `FUN_0040af50` (`dec2.c` lines 3466–3521).
880
+ */
881
+ export function redragonM719ProEncodeKeyComboPayload(modifierMask, hidKey) {
882
+ const events = [];
883
+ for (const bit of [0x01, 0x02, 0x04, 0x08]) {
884
+ if ((modifierMask & bit) !== 0) {
885
+ events.push([0x80, bit, 0x00]);
886
+ }
887
+ }
888
+ if (hidKey !== 0) {
889
+ events.push([0x81, hidKey & 0xff, 0x00]);
890
+ }
891
+ for (const bit of [0x01, 0x02, 0x04, 0x08]) {
892
+ if ((modifierMask & bit) !== 0) {
893
+ events.push([0x40, bit, 0x00]);
894
+ }
895
+ }
896
+ if (hidKey !== 0) {
897
+ events.push([0x41, hidKey & 0xff, 0x00]);
898
+ }
899
+ const rawLen = 1 + events.length * 3 + 1;
900
+ const totalLen = Math.min(REDRAGON_M719_PRO_EEPROM.comboSlotStride, Math.max(1, Math.ceil(rawLen / REDRAGON_M719_PRO_MAX_CHUNK_LENGTH)) * REDRAGON_M719_PRO_MAX_CHUNK_LENGTH);
901
+ const buf = new Uint8Array(totalLen);
902
+ buf[0] = events.length & 0xff;
903
+ let idx = 1;
904
+ for (const [e0, e1, e2] of events) {
905
+ buf[idx] = e0;
906
+ buf[idx + 1] = e1;
907
+ buf[idx + 2] = e2;
908
+ idx += 3;
909
+ }
910
+ buf[idx] = redragonM719ProDataChecksum(buf.subarray(0, idx));
911
+ return buf;
912
+ }
913
+ /**
914
+ * Parse a generic `"Key <name>"`, `"Keys <Mod+...+Key>"`, or `"Combo:<Mod+...+Key>"`
915
+ * action label into a `[modifierMask, hidKeyUsage]` pair.
916
+ */
917
+ function parseGenericKeyAction(action) {
918
+ if (action.startsWith("Key ")) {
919
+ const keyName = action.slice(4).trim().toLowerCase();
920
+ const usage = KEY_BY_NAME.get(keyName);
921
+ return usage !== undefined ? [0, usage] : null;
922
+ }
923
+ const body = action.startsWith("Keys ")
924
+ ? action.slice(5).trim()
925
+ : action.startsWith("Combo:")
926
+ ? action.slice(6).trim()
927
+ : null;
928
+ if (!body)
929
+ return null;
930
+ const parts = body.split("+").map((part) => part.trim()).filter(Boolean);
931
+ if (parts.length === 0)
932
+ return null;
933
+ let mask = 0;
934
+ let keyUsage = 0;
935
+ for (const part of parts) {
936
+ const lower = part.toLowerCase();
937
+ if (lower === "ctrl" || lower === "control")
938
+ mask |= 0x01;
939
+ else if (lower === "shift")
940
+ mask |= 0x02;
941
+ else if (lower === "alt")
942
+ mask |= 0x04;
943
+ else if (lower === "win" || lower === "meta" || lower === "gui")
944
+ mask |= 0x08;
945
+ else {
946
+ const usage = KEY_BY_NAME.get(lower);
947
+ if (usage === undefined || keyUsage !== 0)
948
+ return null;
949
+ keyUsage = usage;
950
+ }
951
+ }
952
+ if (mask === 0 && keyUsage === 0)
953
+ return null;
954
+ return [mask, keyUsage];
955
+ }
956
+ /**
957
+ * Encode a human-readable button action into its 4-byte matrix slot record and
958
+ * optional extended payload for `0x0100 + slot * 0x20`.
959
+ */
960
+ export function redragonM719ProEncodeButtonAction(action) {
961
+ const direct = DIRECT_BY_LABEL.get(action);
962
+ if (direct) {
963
+ const [b0, b1, b2] = direct;
964
+ return {
965
+ slotBytes: new Uint8Array([b0, b1, b2, redragonM719ProDataChecksum(direct)]),
966
+ };
967
+ }
968
+ const consumerCode = MULTIMEDIA_BY_LABEL.get(action);
969
+ if (consumerCode !== undefined) {
970
+ const slotTriplet = [0x05, 0x00, 0x00];
971
+ return {
972
+ slotBytes: new Uint8Array([...slotTriplet, redragonM719ProDataChecksum(slotTriplet)]),
973
+ comboPayload: redragonM719ProEncodeMultimediaPayload(consumerCode),
974
+ };
975
+ }
976
+ const shortcut = SHORTCUT_BY_LABEL.get(action) ?? parseGenericKeyAction(action);
977
+ if (shortcut) {
978
+ const [modifierMask, hidKey] = shortcut;
979
+ const slotTriplet = [0x05, 0x00, 0x00];
980
+ return {
981
+ slotBytes: new Uint8Array([...slotTriplet, redragonM719ProDataChecksum(slotTriplet)]),
982
+ comboPayload: redragonM719ProEncodeKeyComboPayload(modifierMask, hidKey),
983
+ };
984
+ }
985
+ throw new Error(`Unsupported Redragon M719RGB-PRO button action: ${action}`);
986
+ }
987
+ /**
988
+ * Decode an extended payload from `0x0100 + slot * 0x20` when a button slot has `b0 === 0x05`.
989
+ */
990
+ export function redragonM719ProDecodeComboPayload(comboBytes) {
991
+ if (comboBytes.length < 4)
992
+ return null;
993
+ const kind = comboBytes[1] ?? 0;
994
+ if (kind === 0x82 || kind === 0x83) {
995
+ const code = ((comboBytes[2] ?? 0) & 0xff) | (((comboBytes[3] ?? 0) & 0xff) << 8);
996
+ return MULTIMEDIA_BY_CODE.get(code) ?? `Consumer (0x${code.toString(16).toUpperCase().padStart(4, "0")})`;
997
+ }
998
+ if (kind === 0x80 || kind === 0x81) {
999
+ let modifierMask = 0;
1000
+ let keyUsage = 0;
1001
+ for (let i = 1; i + 2 < comboBytes.length; i += 3) {
1002
+ const evType = comboBytes[i] ?? 0;
1003
+ const evCode = comboBytes[i + 1] ?? 0;
1004
+ if (evType === 0x80) {
1005
+ modifierMask |= evCode & 0x0f;
1006
+ }
1007
+ else if (evType === 0x81) {
1008
+ keyUsage = evCode & 0xff;
1009
+ }
1010
+ else {
1011
+ break;
1012
+ }
1013
+ }
1014
+ for (const [label, mask, usage] of SHORTCUT_ACTIONS) {
1015
+ if (mask === modifierMask && usage === keyUsage)
1016
+ return label;
1017
+ }
1018
+ const keyName = KEY_BY_USAGE.get(keyUsage);
1019
+ if (modifierMask === 0 && keyName) {
1020
+ return `Key ${keyName}`;
1021
+ }
1022
+ const parts = [];
1023
+ if ((modifierMask & 0x01) !== 0)
1024
+ parts.push("Ctrl");
1025
+ if ((modifierMask & 0x02) !== 0)
1026
+ parts.push("Shift");
1027
+ if ((modifierMask & 0x04) !== 0)
1028
+ parts.push("Alt");
1029
+ if ((modifierMask & 0x08) !== 0)
1030
+ parts.push("Win");
1031
+ if (keyName)
1032
+ parts.push(keyName);
1033
+ else if (keyUsage !== 0)
1034
+ parts.push(`0x${keyUsage.toString(16).toUpperCase().padStart(2, "0")}`);
1035
+ if (parts.length > 0)
1036
+ return `Keys ${parts.join("+")}`;
1037
+ }
1038
+ return null;
1039
+ }
1040
+ /**
1041
+ * Decode a 4-byte button slot record `[b0, b1, b2, chk]` (with an optional
1042
+ * extended payload from `0x0100 + slot * 0x20` when `b0 === 0x05`).
1043
+ */
1044
+ export function redragonM719ProDecodeButtonAction(slotBytes, comboBytes) {
1045
+ const b0 = (slotBytes[0] ?? 0) & 0xff;
1046
+ const b1 = (slotBytes[1] ?? 0) & 0xff;
1047
+ const b2 = (slotBytes[2] ?? 0) & 0xff;
1048
+ if (b0 === 0x05) {
1049
+ if (comboBytes) {
1050
+ const decoded = redragonM719ProDecodeComboPayload(comboBytes);
1051
+ if (decoded)
1052
+ return decoded;
1053
+ }
1054
+ return "Multimedia / Key combination";
1055
+ }
1056
+ if (b0 === 0x06) {
1057
+ return `Macro ${b1 + 1}`;
1058
+ }
1059
+ for (const [label, [d0, d1, d2]] of DIRECT_BUTTON_ACTIONS) {
1060
+ if (b0 === d0 && b1 === d1 && b2 === d2)
1061
+ return label;
1062
+ }
1063
+ if (b0 === 0x04) {
1064
+ return "Three click";
1065
+ }
1066
+ const hex = [b0, b1, b2, (slotBytes[3] ?? 0) & 0xff]
1067
+ .map((byte) => byte.toString(16).padStart(2, "0"))
1068
+ .join(" ");
1069
+ return `Custom (${hex})`;
1070
+ }
1071
+ //# sourceMappingURL=m719-pro.js.map