From e0992297524e544b4e9cbe71449a9f4e80357c64 Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 20 Nov 2026 19:01:26 +0100 Subject: [PATCH] feat(attackshark): native X3 support from the Linux reference protocol The X3 (1d57:fa60 receiver) was named but read-only. Its settings channel (usage page 0x000B) is only reachable natively, so this adds the protocol documented by enthonyaraujo/attacksharkx3-linux (MIT) behind the receiver model id that names the X3. - compx/x3-config: pure codec for reports 0x0C, 0x04, 0x05, 0x06, 0x08 and the 0x09 macro chunks, checksums, defaults and the battery decode - attackshark driver: X3 path gated on model id 0x4d and the X3 product ids, full settings kept per product id (the mouse has no read-back) and the whole burst sent on every change, paced 500 ms on the receiver and 15 ms wired - client methods for DPI stages and colours, polling, lift-off, ripple, angle snap, motion sync, sleep, deep sleep, debounce, button remapping and macros - docs/attackshark-x3-testing.md with the hardware test steps R1, X11, X6 and M600 Pro behaviour is unchanged. Unverified on real hardware. --- docs/attackshark-x11-testing.md | 5 +- docs/attackshark-x3-testing.md | 99 ++++++++ src/compx/x3-config.test.ts | 171 +++++++++++++ src/compx/x3-config.ts | 363 ++++++++++++++++++++++++++++ src/drivers/attackshark/hid.test.ts | 1 + src/drivers/attackshark/hid.ts | 317 +++++++++++++++++++++++- src/drivers/attackshark/x3.test.ts | 348 ++++++++++++++++++++++++++ 7 files changed, 1301 insertions(+), 3 deletions(-) create mode 100644 docs/attackshark-x3-testing.md create mode 100644 src/compx/x3-config.test.ts create mode 100644 src/compx/x3-config.ts create mode 100644 src/drivers/attackshark/x3.test.ts diff --git a/docs/attackshark-x11-testing.md b/docs/attackshark-x11-testing.md index 31d84cc6..92db48de 100644 --- a/docs/attackshark-x11-testing.md +++ b/docs/attackshark-x11-testing.md @@ -44,8 +44,9 @@ listed only the Delux M600 Pro (`0x20`), so a genuine X11 stayed failure in #161. #174 adds `0x55`: same receiver, protocol and rebuilt transport as the verified M600 Pro, resolving to the receiver's documented 56-byte DPI frame (`x11UsesShortDpiReport` returns the long form for -`0xfa60`). Models whose frame shape is not established (R1 `0x10`, X3 -`0x4d`/`0x4e`, X6 `0x85`) stay read-only. +`0xfa60`). Models whose frame shape is not established (R1 `0x10`, X3 Max `0x4e`, +X3 Pro `0x01`, X6 `0x85`) stay read-only. The X3 (`0x4d`) has its own +protocol, see `docs/attackshark-x3-testing.md`. ## Observed facts diff --git a/docs/attackshark-x3-testing.md b/docs/attackshark-x3-testing.md new file mode 100644 index 00000000..4d880b72 --- /dev/null +++ b/docs/attackshark-x3-testing.md @@ -0,0 +1,99 @@ +# Attack Shark X3 testing notes + +Native X3 support (2.4 GHz receiver `1d57:fa60`, wired `1d57:fa61`). The +protocol is taken from the MIT licensed repo enthonyaraujo/attacksharkx3-linux, +read only. **No part of it has been run against our own X3 hardware yet.** +Settings are HID feature reports on the config collection (usage page `0x000B`, +interface MI_02), which browsers cannot reach, so this runs through OpenMouse +Bridge or the desktop app. + +## Identity + +| Path | VID:PID | Config collection | Battery collection | +|---|---|---|---| +| Receiver | `1d57:fa60` | usage page `0x000B`, MI_02 | usage page `0x000A`, input report `0x03` | +| Wired | `1d57:fa61` | same | same | + +The X3 path is gated on the receiver message naming model id `0x4d` +(`03 40 01 `) plus the X3 product ids. Any other model id keeps +today's behaviour. + +## Reports (all feature reports, report id first) + +| Id | Length | Content | +|---|---|---| +| `0x0C` | 10 | commit lead `0C 0A 01 FE 01 FE 00 00 00 00` | +| `0x04` | 56 | LOD, ripple, stage mask, angle snap, motion sync, 8 DPI slots (raw = dpi/50 - 1), active stage, 8 RGB colours, checksum at 50..51 | +| `0x05` | 15 | deep sleep, sleep (half minutes), debounce (2 ms units), checksum at 11..12 | +| `0x06` | 9 | polling code and complement | +| `0x08` | 59 | 18 button slots of 3 bytes, checksum at 57..58 | +| `0x09` | 64, 64, 12 | macro upload chunks, slot 2, checksum over the 128 byte block from offset 0 | + +The X3 has no read-back. The library keeps the full settings per product id and +every change sends the whole burst in the order `0C, 04, 05, 06, 08`. The UI +therefore shows defaults until the first write, and the first write overwrites +settings changed elsewhere (this matches the reference). + +## Pacing + +500 ms after every report of a burst on the receiver, 15 ms on wired, as in the +reference, which saw polling changes ignored on the receiver at 15 ms. A burst +takes about 2.5 s on the receiver. The wired 15 ms value was not validated, and +the reference's own analysis of the vendor app suggests it may use 500 ms on +wired too. Macro chunks use 15 ms on both. + +## Buttons, macros, profiles + +- Remappable: Left, Right, Middle, Forward (slot 6), Back (slot 7). Actions: + clicks, Forward/Backward, double click, fire, scroll, DPI cycle/+/-, Easy Aim, + media, My Computer, Browser Home, Off, Macro, and keyboard shortcuts typed as + `Ctrl+Shift+Alt+Win+` (A-Z, 0-9, F1-F12, Enter, Esc, Backspace, Tab, Space). +- Slots 3, 4, 5 and 8 (factory `0D`, `3C`, `0F`, `3C`) are never touched; their + physical buttons are unknown. At least one slot must stay Left Click. +- Macros: key press and release events, up to 50, slot 2 only. + `uploadMacro({events})`, then `setButtonMapping(button, "Macro")`. The + protocol has no delays, mouse-button events or repeat modes. +- Profiles: not supported. The protocol has one profile (byte `0x01`) and no + select report. + +## Battery + +Battery is derived from the reference (`03 10 [raw] 01 09` on usage page +`0x000A`, voltage = raw/16, reference lithium curve, charging = flag bit 1) and +is not yet confirmed on our hardware. + +## Model id question: 0x4d versus 0x10 + +The `DeviceId` table names `0x4d` as X3, but the battery packet starts +`03 10`, the same shape as an R1 message (`0x10`). Once `0x4d` has been learned +the library routes `03 10 xx 01 09` to the X3 battery parser. Before that, such +a packet still reads as an R1. If a real X3 never sends a `0x4d` message, the +X3 path never activates. Wired `fa61` receives no receiver messages, so it can +not be named `0x4d` and stays read-only until the maintainer picks an +identification source. + +## Unknowns + +Wired identification, factory `0x3C` slots, byte 49 `0x01` and trailing zeros of +`0x04`, power byte 8 `0xFF`, whether a commit is needed after a macro upload, +LOD naming (Low = 1 mm, High = 2 mm), battery scale and charging bit. + +## Steps for a tester with a real X3 (through Bridge) + +1. Plug in the receiver, open OpenMouse through Bridge, export the diagnostic + and confirm the collections include `0x000B` and `0x000A`, and the device is + named Attack Shark X3 (model id `0x4d`). If it is named R1 or unnamed, stop + and report the receiver message bytes. +2. Change polling to 500, 250, 125 and 1000, waiting about 3 s each, and check + with a polling-rate tool (evhz) that it applies. +3. Change DPI stage values, active stage, stage count and colours; confirm the + cursor speed and LED colour follow. +4. Toggle lift-off, ripple, angle snapping and motion sync; set sleep and + debounce. Confirm a polling change afterwards did not reset them. +5. Remap Forward to `Ctrl+X`, Back to DPI Cycle, Middle to Play/Pause; verify + each, and that Left cannot be set to Off. +6. Upload a macro (7 taps of key `0x06`), bind it with `Macro` and press the + button. Report whether it plays or needs a follow-up commit. +7. Watch the battery value for a while, then plug in charging, and report the + raw bytes of `03 10 xx 01 09` against a known charge level. +8. If you own a wired `fa61` unit, report what the diagnostic shows. diff --git a/src/compx/x3-config.test.ts b/src/compx/x3-config.test.ts new file mode 100644 index 00000000..a2ed64ee --- /dev/null +++ b/src/compx/x3-config.test.ts @@ -0,0 +1,171 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + buildX3Burst, + buildX3Buttons, + buildX3Commit, + buildX3MacroChunks, + buildX3Polling, + buildX3Power, + buildX3Sensor, + defaultX3Settings, + parseX3Battery, + x3DpiToRaw, + x3EnabledMask, + x3KeyboardAction, + x3MacroAction, + x3RawToDpi, + X3_MOD, +} from "./x3-config.ts"; + +const hex = (s: string) => Uint8Array.from(s.split(" ").map((b) => parseInt(b, 16))); +const h = (u: Uint8Array) => [...u].map((b) => b.toString(16).padStart(2, "0").toUpperCase()).join(" "); + +test("commit", () => { + assert.equal(h(buildX3Commit()), "0C 0A 01 FE 01 FE 00 00 00 00"); +}); + +test("default sensor golden", () => { + assert.equal( + h(buildX3Sensor(defaultX3Settings())), + "04 38 01 01 00 3F 00 00 0F 1F 2F 3F 63 07 00 00 00 00 00 00 00 02 00 00 01 FF 00 00 00 FF 00 00 00 FF FF FF 00 00 FF FF FF 00 FF FF 40 00 FF FF FF 01 0E 7D 00 00 00 00", + ); +}); + +test("default power golden", () => { + assert.equal(h(buildX3Power(defaultX3Settings())), "05 0F 01 00 13 E8 00 00 FF 0A 02 02 06 00 00"); +}); + +test("polling goldens", () => { + assert.equal(h(buildX3Polling(1000)), "06 09 01 01 FE 00 00 00 00"); + assert.equal(h(buildX3Polling(500)), "06 09 01 02 FD 00 00 00 00"); + assert.equal(h(buildX3Polling(250)), "06 09 01 04 FB 00 00 00 00"); + assert.equal(h(buildX3Polling(125)), "06 09 01 08 F7 00 00 00 00"); + assert.throws(() => buildX3Polling(100 as 125)); +}); + +const DEFAULT_BUTTONS = + "08 3B 01 02 00 00 03 00 00 04 00 00 0D 00 00 3C 00 00 0F 00 00 06 00 00 05 00 00 3C 00 00 01 00 00 01 00 00 01 00 00 01 00 00 01 00 00 01 00 00 01 00 00 0A 00 00 09 00 00 00 C2"; + +test("default buttons golden", () => { + assert.equal(h(buildX3Buttons(defaultX3Settings().buttons)), DEFAULT_BUTTONS); +}); + +test("forward = Ctrl+X golden", () => { + const s = defaultX3Settings(); + s.buttons[6] = x3KeyboardAction(X3_MOD.ctrl, 0x1b); + assert.equal( + h(buildX3Buttons(s.buttons)), + "08 3B 01 02 00 00 03 00 00 04 00 00 0D 00 00 3C 00 00 0F 00 00 11 01 1B 05 00 00 3C 00 00 01 00 00 01 00 00 01 00 00 01 00 00 01 00 00 01 00 00 01 00 00 0A 00 00 09 00 00 00 E9", + ); +}); + +test("buttons need a left click and 18 slots", () => { + const s = defaultX3Settings(); + s.buttons[0] = [0x01, 0, 0]; + assert.throws(() => buildX3Buttons(s.buttons)); + assert.throws(() => buildX3Buttons(s.buttons.slice(1))); + assert.deepEqual([...x3MacroAction(2)], [0x12, 0, 2]); +}); + +test("burst order and lengths", () => { + const b = buildX3Burst(defaultX3Settings()); + assert.deepEqual(b.map((r) => r[0]), [0x0c, 0x04, 0x05, 0x06, 0x08]); + assert.deepEqual(b.map((r) => r.length), [10, 56, 15, 9, 59]); +}); + +test("macro golden", () => { + const events = Array.from({ length: 7 }, () => [ + { usage: 6, down: true }, + { usage: 6, down: false }, + ]).flat(); + const [c0, c1, c2] = buildX3MacroChunks(events, 2); + assert.deepEqual([c0.length, c1.length, c2.length], [64, 64, 12]); + assert.deepEqual([...c0.subarray(0, 4)], [9, 0x40, 8, 0]); + assert.deepEqual([...c1.subarray(0, 4)], [9, 0x40, 8, 1]); + assert.deepEqual([...c2.subarray(0, 4)], [9, 0x0c, 8, 2]); + const block = new Uint8Array(128); + block.set(c0.subarray(4), 0); + block.set(c1.subarray(4), 60); + block.set(c2.subarray(4), 120); + assert.deepEqual([...block.subarray(0, 5)], [2, 0, 0, 0, 1]); + assert.equal(block[25], 14); + assert.deepEqual([...block.subarray(26, 30)], [1, 6, 0x81, 6]); + assert.deepEqual([...block.subarray(126)], [0x03, 0xf3]); + assert.throws(() => buildX3MacroChunks(events, 0)); + assert.throws(() => buildX3MacroChunks(Array(51).fill({ usage: 4, down: true }))); +}); + +test("dpi conversion", () => { + assert.equal(x3DpiToRaw(800), 15); + assert.equal(x3DpiToRaw(26000), 0x207); + for (let d = 50; d <= 26000; d += 50) assert.equal(x3RawToDpi(x3DpiToRaw(d)), d); + for (const bad of [0, 49, 75, 26050, 800.5]) assert.throws(() => x3DpiToRaw(bad)); +}); + +test("sensor active stage, mask, validation", () => { + const s = defaultX3Settings(); + s.dpiStages = [800, 1600, 12850]; + s.activeStage = 4; + assert.equal(x3EnabledMask(s), 0x07); + const r = buildX3Sensor(s); + assert.equal(r[5], 0x07); + assert.equal(r[24], 2); + assert.equal(r[18], 1); + assert.equal(r[10], 0xff & (12850 / 50 - 1)); + s.enabledMask = 0x05; + assert.equal(buildX3Sensor(s)[5], 0x05); + s.dpiStages = []; + assert.throws(() => buildX3Sensor(s)); +}); + +test("power validation", () => { + const p = defaultX3Settings(); + assert.throws(() => buildX3Power({ ...p, sleepMinutes: 0 })); + assert.throws(() => buildX3Power({ ...p, sleepMinutes: 31 })); + assert.throws(() => buildX3Power({ ...p, deepSleepMinutes: 0 })); + assert.throws(() => buildX3Power({ ...p, deepSleepMinutes: 61 })); + assert.throws(() => buildX3Power({ ...p, debounceMs: 1 })); + assert.throws(() => buildX3Power({ ...p, debounceMs: 52 })); + assert.equal(buildX3Power({ ...p, sleepMinutes: 0.5 })[9], 1); + assert.equal(buildX3Power({ ...p, sleepMinutes: 30, debounceMs: 50 })[10], 25); +}); + +test("checksum unchanged bytes verify", () => { + const r = buildX3Sensor(defaultX3Settings()); + let s = 0; + for (let i = 3; i <= 49; i++) s += r[i]; + assert.equal((r[50] << 8) | r[51], s); + assert.deepEqual(hex("0E 7D"), r.subarray(50, 52)); +}); + +test("battery sample and curve", () => { + const b = parseX3Battery(hex("03 10 40 01 09"))!; + assert.equal(b.voltage, 4); + assert.equal(b.percent, 77); + assert.equal(b.charging, false); + assert.equal(parseX3Battery(hex("03 10 40 02 09"))!.charging, true); + const want: Record = { 0x36: 0, 0x37: 1, 0x38: 3, 0x39: 6, 0x3a: 13, 0x3b: 21, 0x3c: 33, 0x3d: 46, 0x3e: 59, 0x3f: 68, 0x41: 87, 0x42: 94, 0x43: 100, 0xff: 100 }; + for (const [raw, pct] of Object.entries(want)) { + const got = parseX3Battery(Uint8Array.of(3, 0x10, Number(raw), 1, 9))!.percent; + assert.ok(Math.abs(got - pct) <= 1, `raw ${raw}: ${got} vs ${pct}`); + } + assert.equal(parseX3Battery(hex("03 10 40 01")), null); + assert.equal(parseX3Battery(hex("04 10 40 01 09")), null); + assert.equal(parseX3Battery(hex("03 11 40 01 09")), null); +}); + +test("X3 action labels round trip and match the reference codes", async () => { + const { x3ActionLabel, x3ParseActionLabel } = await import("./x3-config.ts"); + assert.deepEqual([...x3ParseActionLabel("Ctrl+X")!], [0x11, 0x01, 0x1b]); + assert.deepEqual([...x3ParseActionLabel("Ctrl+Shift+Alt+Win+F12")!], [0x11, 0x0f, 0x45]); + assert.deepEqual([...x3ParseActionLabel("Mute")!], [0x1a, 0, 0]); + assert.deepEqual([...x3ParseActionLabel("Macro", 2)!], [0x12, 0, 2]); + for (const l of ["Ctrl+X", "Alt+Tab", "Win+0", "Space", "DPI-", "Volume Up", "Macro", "Browser Home"]) { + assert.equal(x3ActionLabel(x3ParseActionLabel(l)!), l); + } + assert.equal(x3ParseActionLabel("Ctrl+Ctrl+X"), null); + assert.equal(x3ParseActionLabel("Bogus"), null); + assert.equal(x3ActionLabel([0x3c, 0, 0]), null); +}); diff --git a/src/compx/x3-config.ts b/src/compx/x3-config.ts new file mode 100644 index 00000000..27bd43ba --- /dev/null +++ b/src/compx/x3-config.ts @@ -0,0 +1,363 @@ + +export const X3_REPORT = { commit: 0x0c, sensor: 0x04, power: 0x05, polling: 0x06, buttons: 0x08, macro: 0x09 } as const; +export const X3_DPI_MIN = 50; +export const X3_DPI_MAX = 26000; +export const X3_DPI_STEP = 50; +export const X3_MAX_STAGES = 8; +export const X3_BUTTON_SLOTS = 18; +export const X3_MACRO_MAX_EVENTS = 50; +export const X3_RECEIVER_GAP_MS = 500; +export const X3_WIRED_GAP_MS = 15; +export const X3_MACRO_GAP_MS = 15; + +export type X3Rgb = readonly [number, number, number]; +export type X3Slot = readonly [number, number, number]; +export type X3PollingHz = 125 | 250 | 500 | 1000; + +export interface X3MacroEvent { + usage: number; + down: boolean; +} + +export interface X3Settings { + dpiStages: number[]; + enabledMask?: number; + activeStage: number; + stageColors: X3Rgb[]; + lod: 0 | 1; + ripple: boolean; + angleSnap: boolean; + motionSync: boolean; + pollingHz: X3PollingHz; + sleepMinutes: number; + deepSleepMinutes: number; + debounceMs: number; + buttons: X3Slot[]; +} + +export const X3_DEFAULT_COLORS: readonly X3Rgb[] = [ + [255, 0, 0], + [0, 255, 0], + [0, 0, 255], + [255, 255, 0], + [0, 255, 255], + [255, 0, 255], + [255, 64, 0], + [255, 255, 255], +]; + +export const X3_FACTORY_BUTTONS: readonly X3Slot[] = [ + [0x02, 0, 0], + [0x03, 0, 0], + [0x04, 0, 0], + [0x0d, 0, 0], + [0x3c, 0, 0], + [0x0f, 0, 0], + [0x06, 0, 0], + [0x05, 0, 0], + [0x3c, 0, 0], + [0x01, 0, 0], + [0x01, 0, 0], + [0x01, 0, 0], + [0x01, 0, 0], + [0x01, 0, 0], + [0x01, 0, 0], + [0x01, 0, 0], + [0x0a, 0, 0], + [0x09, 0, 0], +]; + +export function defaultX3Settings(): X3Settings { + return { + dpiStages: [800, 1600, 2400, 3200, 5000, 26000], + activeStage: 0, + stageColors: X3_DEFAULT_COLORS.map((c) => [...c] as unknown as X3Rgb), + lod: 1, + ripple: false, + angleSnap: false, + motionSync: false, + pollingHz: 1000, + sleepMinutes: 5, + deepSleepMinutes: 30, + debounceMs: 4, + buttons: X3_FACTORY_BUTTONS.map((s) => [...s] as unknown as X3Slot), + }; +} + +function sum(data: Uint8Array, from: number, to: number): number { + let s = 0; + for (let i = from; i <= to; i++) s += data[i]; + return s & 0xffff; +} + +function putBe16(data: Uint8Array, offset: number, value: number): void { + data[offset] = (value >> 8) & 0xff; + data[offset + 1] = value & 0xff; +} + +function header(id: number, length: number): Uint8Array { + const out = new Uint8Array(length); + out[0] = id; + out[1] = length; + out[2] = 0x01; + return out; +} + +export function x3DpiToRaw(dpi: number): number { + if (!Number.isInteger(dpi) || dpi < X3_DPI_MIN || dpi > X3_DPI_MAX || dpi % X3_DPI_STEP !== 0) { + throw new RangeError(`X3 DPI must be ${X3_DPI_MIN}..${X3_DPI_MAX} in steps of ${X3_DPI_STEP}, got ${dpi}`); + } + return dpi / X3_DPI_STEP - 1; +} + +export function x3RawToDpi(raw: number): number { + return (raw + 1) * X3_DPI_STEP; +} + +export function x3EnabledMask(s: Pick): number { + return s.enabledMask ?? (1 << Math.min(s.dpiStages.length, X3_MAX_STAGES)) - 1; +} + +export function buildX3Commit(): Uint8Array { + const out = new Uint8Array(10); + out.set([0x0c, 0x0a, 0x01, 0xfe, 0x01, 0xfe]); + return out; +} + +export function buildX3Sensor(s: X3Settings): Uint8Array { + const count = s.dpiStages.length; + if (count < 1) throw new RangeError("X3 needs at least one DPI stage"); + const out = header(X3_REPORT.sensor, 56); + out[3] = s.lod ? 1 : 0; + out[4] = s.ripple ? 1 : 0; + out[5] = x3EnabledMask(s) & 0xff; + out[6] = s.angleSnap ? 1 : 0; + out[7] = s.motionSync ? 1 : 0; + s.dpiStages.slice(0, X3_MAX_STAGES).forEach((dpi, i) => { + const raw = x3DpiToRaw(dpi); + out[8 + i] = raw & 0xff; + out[16 + i] = raw >> 8; + }); + out[24] = (s.activeStage % count) + 1; + s.stageColors.slice(0, X3_MAX_STAGES).forEach((c, i) => { + for (let k = 0; k < 3; k++) { + if (!Number.isInteger(c[k]) || c[k] < 0 || c[k] > 255) throw new RangeError("X3 colour channel must be 0..255"); + out[25 + 3 * i + k] = c[k]; + } + }); + out[49] = 0x01; + putBe16(out, 50, sum(out, 3, 49)); + return out; +} + +export function buildX3Power(s: Pick): Uint8Array { + const sleepRaw = Math.round(s.sleepMinutes * 2); + if (sleepRaw < 1 || sleepRaw > 60) throw new RangeError("X3 sleep must be 0.5..30 minutes"); + const deep = s.deepSleepMinutes; + if (!Number.isInteger(deep) || deep < 1 || deep > 60) throw new RangeError("X3 deep sleep must be 1..60 minutes"); + const debounceRaw = Math.trunc(s.debounceMs / 2); + if (debounceRaw < 1 || debounceRaw > 25) throw new RangeError("X3 debounce must be 2..51 ms"); + const out = header(X3_REPORT.power, 15); + out[3] = 0; + out[4] = (deep & 0xf0) | 0x03; + out[5] = ((deep & 0x0f) << 4) | 0x08; + out[8] = 0xff; + out[9] = sleepRaw; + out[10] = debounceRaw; + putBe16(out, 11, sum(out, 3, 10)); + return out; +} + +const POLLING_CODES: Record = { 1000: 0x01, 500: 0x02, 250: 0x04, 125: 0x08 }; + +export function buildX3Polling(hz: X3PollingHz): Uint8Array { + const code = POLLING_CODES[hz]; + if (code === undefined) throw new RangeError(`X3 polling rate must be 125, 250, 500 or 1000, got ${hz}`); + const out = header(X3_REPORT.polling, 9); + out[3] = code; + out[4] = 0xff - code; + return out; +} + +export function buildX3Buttons(buttons: readonly X3Slot[]): Uint8Array { + if (buttons.length !== X3_BUTTON_SLOTS) throw new RangeError(`X3 needs ${X3_BUTTON_SLOTS} button slots`); + if (!buttons.some((b) => b[0] === 0x02)) throw new RangeError("X3 needs at least one slot set to Left click"); + const out = header(X3_REPORT.buttons, 59); + buttons.forEach((b, i) => out.set(b, 3 + 3 * i)); + putBe16(out, 57, sum(out, 3, 56)); + return out; +} + +export function buildX3Burst(s: X3Settings): Uint8Array[] { + return [buildX3Commit(), buildX3Sensor(s), buildX3Power(s), buildX3Polling(s.pollingHz), buildX3Buttons(s.buttons)]; +} + +export const X3_ACTION = { + off: 0x01, + left: 0x02, + right: 0x03, + middle: 0x04, + backward: 0x05, + forward: 0x06, + doubleClick: 0x07, + fire: 0x08, + scrollUp: 0x09, + scrollDown: 0x0a, + dpiCycle: 0x0d, + dpiUp: 0x0e, + dpiDown: 0x0f, + easyAim: 0x10, + mediaPlayer: 0x15, + nextTrack: 0x17, + playPause: 0x18, + mute: 0x1a, + volumeUp: 0x1b, + myComputer: 0x23, + browserHome: 0x25, +} as const; + +export const X3_MOD = { ctrl: 0x01, shift: 0x02, alt: 0x04, win: 0x08 } as const; + +export function x3SimpleAction(code: number): X3Slot { + return [code, 0, 0]; +} + +export function x3KeyboardAction(modifiers: number, hidKey: number): X3Slot { + if (!Number.isInteger(modifiers) || modifiers < 0 || modifiers > 0x0f) throw new RangeError("X3 modifiers must be 0..15"); + if (!Number.isInteger(hidKey) || hidKey < 0 || hidKey > 0xff) throw new RangeError("X3 HID key must be 0..255"); + return [0x11, modifiers, hidKey]; +} + +export function x3MacroAction(slot: number): X3Slot { + if (!Number.isInteger(slot) || slot < 1 || slot > 0xff) throw new RangeError("X3 macro slot must be 1..255"); + return [0x12, 0, slot]; +} + +export function buildX3MacroChunks(events: readonly X3MacroEvent[], slot = 2): Uint8Array[] { + if (!Number.isInteger(slot) || slot < 1 || slot > 0xff) throw new RangeError("X3 macro slot must be 1..255"); + if (events.length > X3_MACRO_MAX_EVENTS) throw new RangeError(`X3 macro holds at most ${X3_MACRO_MAX_EVENTS} events`); + const block = new Uint8Array(128); + block[0] = slot; + block[4] = 0x01; + block[25] = events.length; + events.forEach((e, i) => { + if (!Number.isInteger(e.usage) || e.usage < 0 || e.usage > 0x7f) throw new RangeError("X3 macro usage must be 0..127"); + block[26 + 2 * i] = e.down ? 0x01 : 0x81; + block[27 + 2 * i] = e.usage; + }); + putBe16(block, 126, sum(block, 0, 125)); + const chunk = (length: number, index: number, from: number, to: number) => { + const out = new Uint8Array(length); + out.set([0x09, length, 0x08, index]); + out.set(block.subarray(from, to), 4); + return out; + }; + return [chunk(64, 0, 0, 60), chunk(64, 1, 60, 120), chunk(12, 2, 120, 128)]; +} + +export interface X3Battery { + rawByte: number; + voltage: number; + percent: number; + charging: boolean; +} + +const f = Math.fround; + +export function x3VoltageToPercent(voltage: number): number { + const v = f(voltage); + const seg = (lo: number, span: number, base: number, gain: number): number => + base + Math.trunc(f(f(f(v - f(lo)) / f(span)) * f(gain))); + if (v >= f(4.18)) return 100; + if (v >= f(4.08)) return seg(4.08, 0.1, 90, 10); + if (v >= f(3.98)) return seg(3.98, 0.1, 75, 15); + if (v >= f(3.88)) return seg(3.88, 0.1, 60, 15); + if (v >= f(3.78)) return seg(3.78, 0.1, 40, 20); + if (v >= f(3.68)) return seg(3.68, 0.1, 20, 20); + if (v >= f(3.55)) return seg(3.55, 0.13, 5, 15); + if (v >= f(3.4)) return seg(3.4, 0.15, 0, 5); + return 0; +} + +export function parseX3Battery(data: Uint8Array): X3Battery | null { + if (data.length < 5 || data[0] !== 0x03 || data[1] !== 0x10) return null; + const voltage = f(data[2] / 16); + return { rawByte: data[2], voltage, percent: x3VoltageToPercent(voltage), charging: (data[3] & 0x02) !== 0 }; +} + +export const X3_BUTTON_SLOT: Readonly> = { Left: 0, Right: 1, Middle: 2, Forward: 6, Back: 7 }; +export const X3_MACRO_LABEL = "Macro"; + +const NAMED_ACTIONS: ReadonlyArray = [ + ["Off", X3_ACTION.off], + ["Left Click", X3_ACTION.left], + ["Right Click", X3_ACTION.right], + ["Middle Click", X3_ACTION.middle], + ["Backward", X3_ACTION.backward], + ["Forward", X3_ACTION.forward], + ["Double Click", X3_ACTION.doubleClick], + ["Fire Button", X3_ACTION.fire], + ["Scroll Up", X3_ACTION.scrollUp], + ["Scroll Down", X3_ACTION.scrollDown], + ["DPI Cycle", X3_ACTION.dpiCycle], + ["DPI+", X3_ACTION.dpiUp], + ["DPI-", X3_ACTION.dpiDown], + ["Easy Aim", X3_ACTION.easyAim], + ["Media Player", X3_ACTION.mediaPlayer], + ["Next Track", X3_ACTION.nextTrack], + ["Play/Pause", X3_ACTION.playPause], + ["Mute", X3_ACTION.mute], + ["Volume Up", X3_ACTION.volumeUp], + ["My Computer", X3_ACTION.myComputer], + ["Browser Home", X3_ACTION.browserHome], +]; + +export const X3_BUTTON_OPTIONS: readonly string[] = [...NAMED_ACTIONS.map(([l]) => l), X3_MACRO_LABEL]; + +const MODS: ReadonlyArray = [["Ctrl", 1], ["Shift", 2], ["Alt", 4], ["Win", 8]]; +const NAMED_KEYS: ReadonlyArray = [ + ["Enter", 0x28], ["Esc", 0x29], ["Backspace", 0x2a], ["Tab", 0x2b], ["Space", 0x2c], +]; + +function keyCode(name: string): number | undefined { + if (/^[A-Z]$/.test(name)) return 0x04 + name.charCodeAt(0) - 65; + if (/^[1-9]$/.test(name)) return 0x1e + Number(name) - 1; + if (name === "0") return 0x27; + const f = /^F(\d{1,2})$/.exec(name); + if (f && Number(f[1]) >= 1 && Number(f[1]) <= 12) return 0x3a + Number(f[1]) - 1; + return NAMED_KEYS.find(([n]) => n === name)?.[1]; +} + +function keyName(code: number): string | undefined { + if (code >= 0x04 && code <= 0x1d) return String.fromCharCode(65 + code - 4); + if (code >= 0x1e && code <= 0x26) return String(code - 0x1d); + if (code === 0x27) return "0"; + if (code >= 0x3a && code <= 0x45) return `F${code - 0x39}`; + return NAMED_KEYS.find(([, c]) => c === code)?.[0]; +} + +export function x3ParseActionLabel(label: string, macroSlot = 2): X3Slot | null { + if (label === X3_MACRO_LABEL) return x3MacroAction(macroSlot); + const named = NAMED_ACTIONS.find(([l]) => l === label); + if (named) return x3SimpleAction(named[1]); + const parts = label.split("+"); + const last = parts.pop()!; + let mods = 0; + for (const p of parts) { + const m = MODS.find(([n]) => n === p); + if (!m || mods & m[1]) return null; + mods |= m[1]; + } + const key = keyCode(last); + return key === undefined ? null : x3KeyboardAction(mods, key); +} + +export function x3ActionLabel(slot: X3Slot): string | null { + if (slot[0] === 0x12) return X3_MACRO_LABEL; + if (slot[0] === 0x11) { + const key = keyName(slot[2]); + if (key === undefined || slot[1] > 0x0f) return null; + return [...MODS.filter(([, b]) => slot[1] & b).map(([n]) => n), key].join("+"); + } + return NAMED_ACTIONS.find(([, c]) => c === slot[0])?.[0] ?? null; +} diff --git a/src/drivers/attackshark/hid.test.ts b/src/drivers/attackshark/hid.test.ts index ea8399d2..fe0dc130 100644 --- a/src/drivers/attackshark/hid.test.ts +++ b/src/drivers/attackshark/hid.test.ts @@ -374,6 +374,7 @@ test("the receiver's model id names the mouse, never the PID", async () => { test("the declared DPI report length picks the 56-byte receiver form", async () => { resetAttackSharkX11DpiState(); + resetAttackSharkX11RuntimeState(); const { unit, sent } = linuxX11Receiver(55); const client = new AttackSharkHidClient(unit, { batteryWaitMs: 0 }); assert.equal(await client.setDpi(1600), 1600); diff --git a/src/drivers/attackshark/hid.ts b/src/drivers/attackshark/hid.ts index eba01aca..e3cfbdb3 100644 --- a/src/drivers/attackshark/hid.ts +++ b/src/drivers/attackshark/hid.ts @@ -16,6 +16,28 @@ import { X11_DPI_STEP, X11_DPI_VALUES, } from "../../compx/x11-dpi.ts"; +import { + buildX3Burst, + buildX3MacroChunks, + defaultX3Settings, + X3_BUTTON_OPTIONS, + X3_BUTTON_SLOT, + X3_FACTORY_BUTTONS, + X3_MACRO_GAP_MS, + x3ActionLabel, + x3ParseActionLabel, + type X3MacroEvent, + parseX3Battery, + X3_DPI_MAX, + X3_DPI_MIN, + X3_DPI_STEP, + X3_MAX_STAGES, + X3_RECEIVER_GAP_MS, + X3_WIRED_GAP_MS, + type X3PollingHz, + type X3Rgb, + type X3Settings, +} from "../../compx/x3-config.ts"; // Attack Shark mice ship from multiple OEMs with different VIDs and protocols: // @@ -339,8 +361,37 @@ const x11LastReceiverWriteAt = new Map(); export function resetAttackSharkX11RuntimeState(): void { x11RuntimeStates.clear(); x11LastReceiverWriteAt.clear(); + x3States.clear(); +} + +const X3_MODEL_ID = 0x4d; +const X3_PIDS: ReadonlySet = new Set([0xfa60, 0xfa61]); +const X3_POLLING_RATES: X3PollingHz[] = [125, 250, 500, 1000]; +const X3_SLEEP_STEP_S = 30; +const X3_LOD = ["Low", "High"] as const; + +interface X3State { + settings: X3Settings; + battery: { percent: number; voltageMv: number; charging: boolean } | null; +} + +const x3States = new Map(); + +function x3StateFor(productId: number): X3State { + let state = x3States.get(productId); + if (!state) { + state = { settings: defaultX3Settings(), battery: null }; + x3States.set(productId, state); + } + return state; +} + +export function resetAttackSharkX3State(): void { + x3States.clear(); } +const rgbToHex = (c: X3Rgb): string => `#${c.map((v) => v.toString(16).padStart(2, "0")).join("")}`; + /** * If the granted devices include an X11-family unit that no driver could * claim, explain why instead of letting the generic "not a control @@ -464,7 +515,13 @@ export class AttackSharkHidClient { private batteryPercent: number | null = null; private listening = false; - constructor(device: HIDDevice, options: { batteryWaitMs?: number; receiverWriteGapMs?: number } = {}) { + private readonly x3BurstGapMs: number | undefined; + + constructor( + device: HIDDevice, + options: { batteryWaitMs?: number; receiverWriteGapMs?: number; x3BurstGapMs?: number } = {}, + ) { + this.x3BurstGapMs = options.x3BurstGapMs; this.device = device; this.family = detectFamily(device); this.batteryWaitMs = options.batteryWaitMs ?? X11_BATTERY_WAIT_MS; @@ -507,6 +564,15 @@ export class AttackSharkHidClient { && X11_DPI_PIDS.has(this.device.productId); } + private get x3Active(): boolean { + return this.family === "1d57-x11" + && X3_PIDS.has(this.device.productId) + && this.receiverModelId === X3_MODEL_ID + && (this.nativeConfig + || x11ConfigReportBytes(this.device) !== null + || x11RebuiltConfigCollection(this.device)); + } + static isSupported(device: HIDDevice): boolean { return detectFamily(device) !== null; } @@ -527,6 +593,22 @@ export class AttackSharkHidClient { packet[0] = event.reportId; packet.set(data, 1); } + if (packet[0] === BATTERY_REPORT_ID && packet[1] === 0x10 && this.x3Active) { + const battery = parseX3Battery(packet); + if (battery) { + const entry = { percent: battery.percent, voltageMv: Math.round(battery.voltage * 1000), charging: battery.charging }; + x3StateFor(this.device.productId).battery = entry; + if (this.lastStatus) { + this.lastStatus = { + ...this.lastStatus, + batteryPercent: entry.percent, + batteryVoltageMv: entry.voltageMv, + batteryState: entry.charging ? "Charging" : "Discharging", + }; + } + } + return; + } if (packet[0] === BATTERY_REPORT_ID && X11_RECEIVER_MODELS.has(packet[1])) { x11RuntimeFor(this.device.productId).modelId = packet[1]; } @@ -604,6 +686,7 @@ export class AttackSharkHidClient { } getSupportedPollingRates(): number[] { + if (this.x3Active) return [...X3_POLLING_RATES]; if (this.family === "1d57") return POLLING_RATES_1D57.map(([, hz]) => hz); if (this.family === "25a7") return [...POLLING_CODES_25A7.keys()]; // Native transport: the X11 exposes the same 0x06 polling command the @@ -616,6 +699,9 @@ export class AttackSharkHidClient { // 25a7 devices expose up to 8 DPI slots per profile. // The actual values are read dynamically in readStatus(); we return a // standard set of supported DPI steps so the UI can offer them. + if (this.x3Active) { + return Array.from({ length: (X3_DPI_MAX - X3_DPI_MIN) / X3_DPI_STEP + 1 }, (_, i) => X3_DPI_MIN + i * X3_DPI_STEP); + } if (this.family === "25a7") { return [400, 800, 1200, 1600, 2400, 3200, 6400, 12000, 26000]; } @@ -627,6 +713,7 @@ export class AttackSharkHidClient { async readStatus(): Promise { await this.open(); + if (this.x3Active) return this.readX3Status(); let pollingRateHz = 0; let dpi = 0; @@ -730,6 +817,13 @@ export class AttackSharkHidClient { } async setPollingRate(pollingRateHz: number): Promise { + if (this.x3Active) { + if (!X3_POLLING_RATES.includes(pollingRateHz as X3PollingHz)) { + throw new Error(`This mouse does not support ${pollingRateHz} Hz.`); + } + await this.applyX3((s) => { s.pollingHz = pollingRateHz as X3PollingHz; }); + return pollingRateHz; + } if (this.family === "1d57-x11") { if (!this.x11ConfigReachable) { throw new Error( @@ -862,6 +956,7 @@ export class AttackSharkHidClient { /** Sets the active stage's DPI, preserving the other five. */ async setDpi(dpi: number, _dpiY?: number): Promise { + if (this.x3Active) return this.setDpiStageValue(x3StateFor(this.device.productId).settings.activeStage, dpi); this.requireX11Dpi(); const state = x11DpiStateFor(this.device.productId); const value = nearestX11Dpi(dpi); @@ -873,6 +968,13 @@ export class AttackSharkHidClient { /** Edits one stage's DPI. `stage` is 0-based, matching the shared UI contract. */ async setDpiStageValue(stage: number, dpi: number): Promise { + if (this.x3Active) { + await this.applyX3((s) => { + this.requireX3Stage(s, stage); + s.dpiStages[stage] = dpi; + }); + return dpi; + } this.requireX11Dpi(); if (!Number.isInteger(stage) || stage < 0 || stage >= X11_DPI_STAGE_COUNT) { throw new RangeError(`This mouse has no DPI stage ${stage + 1}.`); @@ -887,6 +989,13 @@ export class AttackSharkHidClient { /** Selects the active stage. `stage` is 0-based, matching the shared UI contract. */ async setActiveDpiStage(stage: number): Promise { + if (this.x3Active) { + await this.applyX3((s) => { + this.requireX3Stage(s, stage); + s.activeStage = stage; + }); + return stage; + } this.requireX11Dpi(); if (!Number.isInteger(stage) || stage < 0 || stage >= X11_DPI_STAGE_COUNT) { throw new RangeError(`This mouse has no DPI stage ${stage + 1}.`); @@ -905,6 +1014,10 @@ export class AttackSharkHidClient { } async setAngleSnapping(enabled: boolean): Promise { + if (this.x3Active) { + await this.applyX3((s) => { s.angleSnap = enabled; }); + return enabled; + } this.requireX11Dpi(); x11DpiStateFor(this.device.productId).angleSnap = enabled; await this.writeX11Dpi(); @@ -913,6 +1026,10 @@ export class AttackSharkHidClient { } async setRippleControl(enabled: boolean): Promise { + if (this.x3Active) { + await this.applyX3((s) => { s.ripple = enabled; }); + return enabled; + } this.requireX11Dpi(); x11DpiStateFor(this.device.productId).rippleControl = enabled; await this.writeX11Dpi(); @@ -920,6 +1037,204 @@ export class AttackSharkHidClient { return enabled; } + private requireX3(): void { + if (!this.x3Active) throw new Error("This setting is only available on the Attack Shark X3."); + } + + private requireX3Stage(s: X3Settings, stage: number): void { + if (!Number.isInteger(stage) || stage < 0 || stage >= s.dpiStages.length) { + throw new RangeError(`This mouse has no DPI stage ${stage + 1}.`); + } + } + + private async applyX3(change: (settings: X3Settings) => void): Promise { + const state = x3StateFor(this.device.productId); + const next = structuredClone(state.settings); + change(next); + const burst = buildX3Burst(next); + const gap = this.x3BurstGapMs ?? (this.isWireless() ? X3_RECEIVER_GAP_MS : X3_WIRED_GAP_MS); + await this.run(async () => { + for (const report of burst) { + const payload = new Uint8Array(report.length - 1); + payload.set(report.subarray(1)); + await this.device.sendFeatureReport(report[0], payload); + await this.delay(gap); + } + }); + state.settings = next; + if (this.lastStatus) this.lastStatus = { ...this.lastStatus, ...this.x3Fields(next) }; + } + + private x3Fields(s: X3Settings): Partial { + const count = Math.min(s.dpiStages.length, X3_MAX_STAGES); + return { + dpi: s.dpiStages[s.activeStage] ?? 0, + dpiStages: [...s.dpiStages], + dpiStageColors: s.stageColors.slice(0, count).map(rgbToHex), + activeDpiStage: s.activeStage, + pollingRateHz: s.pollingHz, + liftOffDistance: X3_LOD[s.lod], + rippleControl: s.ripple, + angleSnapping: s.angleSnap, + motionSync: s.motionSync, + sleepTimeout: s.sleepMinutes * 60, + debounceMs: s.debounceMs, + ...this.x3Buttons(s), + }; + } + + private x3Buttons(s: X3Settings): Partial { + const buttonMappings: Record = {}; + const fixedButtons: string[] = []; + for (const [name, slot] of Object.entries(X3_BUTTON_SLOT)) { + const label = x3ActionLabel(s.buttons[slot]); + buttonMappings[name] = label ?? "Custom (read-only)"; + if (!label) fixedButtons.push(name); + } + return { buttonMappings, buttonOptions: [...X3_BUTTON_OPTIONS], fixedButtons }; + } + + private readX3Status(): MouseStatus { + const state = x3StateFor(this.device.productId); + const battery = state.battery; + return this.lastStatus = { + brand: this.deviceBrand(), + name: this.displayName(), + ui: { + family: "attackshark", + settingsReady: true, + hideUnsupportedPollingRates: true, + hideProcessingCard: false, + showAdvancedSection: true, + forceShowBattery: this.isWireless(), + dpiStageEditor: { + maxStages: X3_MAX_STAGES, + countEditable: true, + minDpi: X3_DPI_MIN, + maxDpi: X3_DPI_MAX, + stepDpi: X3_DPI_STEP, + }, + }, + batteryPercent: battery?.percent ?? null, + batteryVoltageMv: battery?.voltageMv ?? null, + batteryState: battery ? (battery.charging ? "Charging" : "Discharging") : "Unknown", + ...this.x3Fields(state.settings), + supportedPollingRates: [...X3_POLLING_RATES], + supportedLiftOffDistances: [...X3_LOD], + activeProfile: null, + connectionType: this.isWireless() ? "Wireless" : "Wired", + firmware: [], + } as MouseStatus; + } + + getButtonOptions(): string[] { + return [...X3_BUTTON_OPTIONS]; + } + + async setButtonMapping(button: string, action: string): Promise { + this.requireX3(); + const index = X3_BUTTON_SLOT[button]; + if (index === undefined) throw new RangeError(`Unknown X3 button: ${button}`); + const slot = x3ParseActionLabel(action); + if (!slot) throw new RangeError(`${action} is not an X3 button action.`); + await this.applyX3((s) => { s.buttons[index] = slot; }); + } + + async resetButtonMappings(): Promise { + this.requireX3(); + await this.applyX3((s) => { s.buttons = X3_FACTORY_BUTTONS.map((b) => [...b] as unknown as X3Settings["buttons"][number]); }); + } + + async uploadMacro(macro: { slot?: number; events: readonly X3MacroEvent[] }): Promise { + this.requireX3(); + const chunks = buildX3MacroChunks(macro.events, macro.slot ?? 2); + await this.run(async () => { + for (const chunk of chunks) { + await this.device.sendFeatureReport(chunk[0], chunk.slice(1)); + await this.delay(this.x3BurstGapMs ?? X3_MACRO_GAP_MS); + } + }); + } + + async setDpiStageCount(count: number): Promise { + this.requireX3(); + await this.applyX3((s) => { + if (!Number.isInteger(count) || count < 1 || count > X3_MAX_STAGES) { + throw new RangeError(`This mouse has 1 to ${X3_MAX_STAGES} DPI stages.`); + } + const last = s.dpiStages[s.dpiStages.length - 1] ?? 800; + s.dpiStages = Array.from({ length: count }, (_, i) => s.dpiStages[i] ?? last); + s.activeStage = Math.min(s.activeStage, count - 1); + }); + return count; + } + + async setDpiStageColor(stage: number, color: string): Promise { + this.requireX3(); + const match = /^#([0-9a-f]{6})$/i.exec(color); + if (!match) throw new TypeError("DPI stage colour must be #rrggbb."); + const rgb = [0, 2, 4].map((i) => parseInt(match[1].slice(i, i + 2), 16)) as unknown as X3Rgb; + await this.applyX3((s) => { + this.requireX3Stage(s, stage); + s.stageColors[stage] = rgb; + }); + return color.toLowerCase(); + } + + getSleepOptions(): number[] { + return Array.from({ length: 60 }, (_, i) => (i + 1) * X3_SLEEP_STEP_S); + } + + async setSleepTimeout(seconds: number): Promise { + this.requireX3(); + if (!Number.isInteger(seconds) || seconds % X3_SLEEP_STEP_S !== 0) { + throw new RangeError("Sleep time must be a multiple of 30 seconds."); + } + await this.applyX3((s) => { s.sleepMinutes = seconds / 60; }); + return seconds; + } + + async setDeepSleepTimeout(minutes: number): Promise { + this.requireX3(); + await this.applyX3((s) => { s.deepSleepMinutes = minutes; }); + return minutes; + } + + getDeepSleepTimeout(): number { + return x3StateFor(this.device.productId).settings.deepSleepMinutes; + } + + getDebounceMaxMs(): number { + return 50; + } + + getDebounceOptions(): number[] { + return Array.from({ length: 25 }, (_, i) => (i + 1) * 2); + } + + async setDebounceTime(ms: number): Promise { + this.requireX3(); + if (!Number.isInteger(ms) || ms < 2 || ms > 50 || ms % 2 !== 0) { + throw new RangeError("Debounce time must be an even 2 to 50 ms."); + } + await this.applyX3((s) => { s.debounceMs = ms; }); + return ms; + } + + async setLiftOffDistance(lod: "Low" | "High"): Promise { + this.requireX3(); + const index = X3_LOD.indexOf(lod); + if (index < 0) throw new RangeError("Lift-off distance must be Low (1 mm) or High (2 mm)."); + await this.applyX3((s) => { s.lod = index as 0 | 1; }); + return lod; + } + + async setMotionSync(enabled: boolean): Promise { + this.requireX3(); + await this.applyX3((s) => { s.motionSync = enabled; }); + return enabled; + } + // ── 0x25a7 low-level ────────────────────────────────────────────────── /** diff --git a/src/drivers/attackshark/x3.test.ts b/src/drivers/attackshark/x3.test.ts new file mode 100644 index 00000000..d8cde3e5 --- /dev/null +++ b/src/drivers/attackshark/x3.test.ts @@ -0,0 +1,348 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { AttackSharkHidClient, resetAttackSharkX11DpiState, resetAttackSharkX11RuntimeState } from "./hid.ts"; +import { buildX11DpiReport, X11_DPI_DEFAULT_ACTIVE, X11_DPI_DEFAULT_STAGES } from "../../compx/x11-dpi.ts"; +import { buildX3Burst, defaultX3Settings } from "../../compx/x3-config.ts"; + +type Sent = { reportId: number; data: number[] }; +type Listener = (event: { reportId: number; data: DataView }) => void; + +function fakeDevice(productId: number, collections: unknown[] = [], failAt = -1) { + const sent: Sent[] = []; + let listener: Listener | undefined; + let attempts = 0; + const unit = { + vendorId: 0x1d57, + productId, + productName: "2.4G Wireless Device", + collections, + opened: false, + open() { (this as { opened: boolean }).opened = true; return Promise.resolve(); }, + close() { return Promise.resolve(); }, + sendFeatureReport(reportId: number, data: BufferSource) { + attempts++; + sent.push({ reportId, data: [...new Uint8Array(data as ArrayBuffer)] }); + return attempts - 1 === failAt ? Promise.reject(new Error("write failed")) : Promise.resolve(); + }, + receiveFeatureReport() { return Promise.reject(new Error("no read-back")); }, + addEventListener(_type: string, l: Listener) { listener = l; }, + removeEventListener() { listener = undefined; }, + } as unknown as HIDDevice; + const push = (bytes: number[]) => listener?.({ reportId: 0, data: new DataView(new Uint8Array(bytes).buffer) }); + return { unit, sent, push }; +} + +const rebuilt = (usagePage: number) => ({ + usagePage, + usage: 0, + type: 1, + children: [], + inputReports: [], + outputReports: [], + featureReports: [], +}); + +const BRIDGE_COLLECTIONS = [rebuilt(0x0c), rebuilt(0x0a), rebuilt(0x0b)]; + +const fresh = () => { + resetAttackSharkX11DpiState(); + resetAttackSharkX11RuntimeState(); +}; + +async function namedX3(productId = 0xfa60, failAt = -1, collections: unknown[] = []) { + const device = fakeDevice(productId, collections, failAt); + const client = new AttackSharkHidClient(device.unit, { batteryWaitMs: 0, x3BurstGapMs: 0 }); + await client.open(); + device.push([0x03, 0x4d, 0x50, 0x00, 0x06]); + return { ...device, client }; +} + +const IDS = [0x0c, 0x04, 0x05, 0x06, 0x08]; +const PAYLOAD_LENGTHS = [9, 55, 14, 8, 58]; + +test("X3 burst is complete and in wire order after a single setting change", async () => { + fresh(); + const { client, sent } = await namedX3(); + assert.equal(await client.setPollingRate(500), 500); + assert.deepEqual(sent.map((s) => s.reportId), IDS); + assert.deepEqual(sent.map((s) => s.data.length), PAYLOAD_LENGTHS); + assert.deepEqual(sent[0].data, [0x0a, 0x01, 0xfe, 0x01, 0xfe, 0, 0, 0, 0]); + assert.deepEqual(sent[3].data, [0x09, 0x01, 0x02, 0xfd, 0, 0, 0, 0]); + const expected = buildX3Burst({ ...defaultX3Settings(), pollingHz: 500 }); + sent.forEach((s, i) => assert.deepEqual(s.data, [...expected[i].subarray(1)])); +}); + +test("X3 settings persist between changes and every change resends the full state", async () => { + fresh(); + const { client, sent } = await namedX3(); + await client.setDpiStageValue(1, 1000); + await client.setActiveDpiStage(2); + sent.length = 0; + await client.setPollingRate(250); + assert.deepEqual(sent.map((s) => s.reportId), IDS); + const sensor = sent[1].data; + assert.equal(sensor[8], 19); + assert.equal(sensor[24 - 1], 3); + const status = await client.readStatus(); + assert.deepEqual(status.dpiStages, [800, 1000, 2400, 3200, 5000, 26000]); + assert.equal(status.activeDpiStage, 2); + assert.equal(status.dpi, 2400); + assert.equal(status.pollingRateHz, 250); +}); + +test("X3 setters cover lift-off, ripple, snapping, motion sync, sleep, deep sleep, debounce, stages", async () => { + fresh(); + const { client, sent } = await namedX3(); + await client.setLiftOffDistance("Low"); + await client.setRippleControl(true); + await client.setAngleSnapping(true); + await client.setMotionSync(true); + await client.setSleepTimeout(90); + await client.setDeepSleepTimeout(45); + await client.setDebounceTime(10); + await client.setDpiStageCount(4); + await client.setDpiStageColor(0, "#102030"); + const status = await client.readStatus(); + assert.equal(status.liftOffDistance, "Low"); + assert.equal(status.rippleControl, true); + assert.equal(status.angleSnapping, true); + assert.equal(status.motionSync, true); + assert.equal(status.sleepTimeout, 90); + assert.equal(status.debounceMs, 10); + assert.equal(client.getDeepSleepTimeout(), 45); + assert.equal(status.dpiStages?.length, 4); + assert.equal(status.dpiStageColors?.[0], "#102030"); + assert.equal(status.ui?.settingsReady, true); + assert.equal(status.ui?.dpiStageEditor?.countEditable, true); + assert.deepEqual(status.supportedPollingRates, [125, 250, 500, 1000]); + const last = sent.slice(-5); + assert.deepEqual(last.map((s) => s.reportId), IDS); + assert.equal(last[1].data[5 - 1], 0x0f); + assert.equal(last[2].data[4 - 1], 0x23); + assert.equal(last[2].data[5 - 1], 0xd8); + assert.equal(last[2].data[9 - 1], 3); + assert.equal(last[2].data[10 - 1], 5); +}); + +test("X3 rejects invalid values before anything is sent", async () => { + fresh(); + const { client, sent } = await namedX3(); + await assert.rejects(() => client.setDpiStageValue(0, 125)); + await assert.rejects(() => client.setDpiStageValue(9, 800), /no DPI stage/); + await assert.rejects(() => client.setPollingRate(2000)); + await assert.rejects(() => client.setDebounceTime(5)); + await assert.rejects(() => client.setSleepTimeout(45)); + await assert.rejects(() => client.setDeepSleepTimeout(0)); + await assert.rejects(() => client.setDpiStageCount(9)); + await assert.rejects(() => client.setDpiStageColor(0, "red")); + await assert.rejects(() => client.setLiftOffDistance("Medium" as "Low")); + assert.deepEqual(sent, []); +}); + +test("X3 waits 500 ms after every report on the receiver and 15 ms on wired", async () => { + for (const [productId, gap] of [[0xfa60, 500], [0xfa61, 15]] as const) { + fresh(); + const device = fakeDevice(productId); + const client = new AttackSharkHidClient(device.unit, { batteryWaitMs: 0 }); + await client.open(); + device.push([0x03, 0x4d, 0x50, 0x00, 0x06]); + const waits: number[] = []; + const realSetTimeout = globalThis.setTimeout; + globalThis.setTimeout = ((fn: () => void, ms?: number, ...rest: unknown[]) => { + waits.push(ms ?? 0); + return realSetTimeout(fn, 0, ...rest); + }) as typeof setTimeout; + try { + await client.setPollingRate(125); + } finally { + globalThis.setTimeout = realSetTimeout; + } + assert.deepEqual(waits, [gap, gap, gap, gap, gap]); + assert.equal(device.sent.length, 5); + } +}); + +test("X3 state is kept per product id", async () => { + fresh(); + const receiver = await namedX3(0xfa60); + const wired = await namedX3(0xfa61); + await receiver.client.setPollingRate(125); + assert.equal((await wired.client.readStatus()).pollingRateHz, 1000); + assert.equal((await receiver.client.readStatus()).pollingRateHz, 125); + assert.equal((await wired.client.readStatus()).connectionType, "Wired"); +}); + +test("a failed X3 burst stops, reports the error and keeps the saved state", async () => { + fresh(); + const { client, sent } = await namedX3(0xfa60, 3); + await assert.rejects(() => client.setPollingRate(500), /write failed/); + assert.deepEqual(sent.map((s) => s.reportId), [0x0c, 0x04, 0x05, 0x06]); + assert.equal((await client.readStatus()).pollingRateHz, 1000); +}); + +test("X3 battery packet 03 10 raw 01 09 is parsed once the X3 is named, not read as an R1", async () => { + fresh(); + const { client, push } = await namedX3(); + assert.equal((await client.readStatus()).batteryPercent, null); + push([0x03, 0x10, 0x40, 0x01, 0x09]); + let status = await client.readStatus(); + assert.equal(status.name, "Attack Shark X3"); + assert.equal(status.batteryPercent, 77); + assert.equal(status.batteryVoltageMv, 4000); + assert.equal(status.batteryState, "Discharging"); + push([0x03, 0x10, 0x40, 0x03, 0x09]); + status = await client.readStatus(); + assert.equal(status.batteryState, "Charging"); + assert.equal(status.name, "Attack Shark X3"); + assert.equal(await client.setPollingRate(500), 500); +}); + +test("X3 works through a Bridge rebuilt config collection", async () => { + fresh(); + const { client, sent } = await namedX3(0xfa60, -1, BRIDGE_COLLECTIONS); + await client.setMotionSync(true); + assert.deepEqual(sent.map((s) => s.reportId), IDS); +}); + +test("the X3 path stays off until the receiver names model 0x4d", async () => { + fresh(); + const device = fakeDevice(0xfa60, BRIDGE_COLLECTIONS); + const client = new AttackSharkHidClient(device.unit, { batteryWaitMs: 0, x3BurstGapMs: 0 }); + await client.open(); + await assert.rejects(() => client.setMotionSync(true), /only available on the Attack Shark X3/); + await assert.rejects(() => client.setDpiStageCount(3), /only available/); + assert.deepEqual(device.sent, []); + assert.equal((await client.readStatus()).ui?.settingsReady, false); +}); + +test("a mouse reporting an unknown model id never writes through the X3 path", async () => { + for (const id of [0x21, 0x4e, 0x01, 0x07]) { + fresh(); + const device = fakeDevice(0xfa60); + const client = new AttackSharkHidClient(device.unit, { batteryWaitMs: 0, x3BurstGapMs: 0 }); + await client.open(); + device.push([0x03, id, 0x50, 0x00, 0x06]); + await assert.rejects(() => client.setMotionSync(true)); + await assert.rejects(() => client.setDebounceTime(10)); + await assert.rejects(() => client.setSleepTimeout(60)); + await assert.rejects(() => client.setLiftOffDistance("Low")); + assert.ok(device.sent.every((s) => s.reportId !== 0x0c && s.reportId !== 0x05 && s.reportId !== 0x08)); + } + fresh(); + const device = fakeDevice(0xfa60); + const client = new AttackSharkHidClient(device.unit, { batteryWaitMs: 0, x3BurstGapMs: 0 }); + await client.open(); + await assert.rejects(() => client.setMotionSync(true)); + assert.deepEqual(device.sent, []); +}); + +async function named(id: number) { + const device = fakeDevice(0xfa60); + const client = new AttackSharkHidClient(device.unit, { batteryWaitMs: 0, x3BurstGapMs: 0 }); + await client.open(); + device.push([0x03, id, 0x50, 0x00, 0x06]); + return { ...device, client }; +} + +test("other models keep their exact single-report writes", async () => { + for (const id of [0x10, 0x55, 0x85]) { + fresh(); + const { client, sent } = await named(id); + assert.equal(await client.setPollingRate(500), 500); + assert.deepEqual(sent, [{ reportId: 0x06, data: [0x09, 0x01, 0x02, 0xfd, 0, 0, 0, 0] }]); + } + fresh(); + const x11 = await named(0x55); + await x11.client.setDpi(1600); + const expected = buildX11DpiReport({ + stages: [...X11_DPI_DEFAULT_STAGES].map((v, i) => (i === X11_DPI_DEFAULT_ACTIVE - 1 ? 1600 : v)), + activeStage: X11_DPI_DEFAULT_ACTIVE, + angleSnap: false, + rippleControl: true, + wired: false, + }); + assert.equal(x11.sent.length, 1); + assert.equal(x11.sent[0].reportId, 0x04); + assert.deepEqual(x11.sent[0].data, [...expected.subarray(1)]); + assert.equal(x11.client.getDpiOptions().at(-1), 22000); +}); + +test("M600 Pro keeps its 51-byte DPI write through the Bridge shape", async () => { + fresh(); + const device = fakeDevice(0xfa60, BRIDGE_COLLECTIONS); + const client = new AttackSharkHidClient(device.unit, { batteryWaitMs: 0, receiverWriteGapMs: 0, x3BurstGapMs: 0 }); + await client.open(); + device.push([0x03, 0x20, 0x40, 0x01, 0x4c]); + assert.equal(await client.setDpi(400), 400); + assert.equal(device.sent.length, 1); + assert.equal(device.sent[0].reportId, 0x04); + assert.equal(device.sent[0].data.length, 51); +}); + +test("an R1 battery packet before any X3 is named still reads as an R1", async () => { + fresh(); + const { client } = await named(0x10); + const status = await client.readStatus(); + assert.equal(status.name, "Attack Shark R1"); + assert.equal(status.ui?.family, "attackshark"); + assert.equal(client.getSupportedPollingRates().length, 4); +}); + +test("X3 button remap sends the full burst with keys, media, DPI and macro slots in place", async () => { + fresh(); + const { client, sent } = await namedX3(); + await client.setButtonMapping("Forward", "Ctrl+X"); + assert.deepEqual(sent.map((s) => s.reportId), IDS); + assert.deepEqual(sent[4].data.slice(21 - 1, 24 - 1), [0x11, 0x01, 0x1b]); + assert.deepEqual(sent[4].data.slice(-2), [0x00, 0xe9]); + await client.setButtonMapping("Back", "DPI Cycle"); + await client.setButtonMapping("Middle", "Play/Pause"); + await client.setButtonMapping("Right", "Macro"); + const status = await client.readStatus(); + assert.deepEqual(status.buttonMappings, { + Left: "Left Click", Right: "Macro", Middle: "Play/Pause", Forward: "Ctrl+X", Back: "DPI Cycle", + }); + assert.ok(status.buttonOptions?.includes("Macro")); + const last = sent.slice(-5)[4].data; + assert.deepEqual(last.slice(5, 8), [0x12, 0x00, 0x02]); + assert.deepEqual(last.slice(12 - 1, 15 - 1), [0x0d, 0, 0]); +}); + +test("X3 button remap rejects bad input and the no-left-click state before sending", async () => { + fresh(); + const { client, sent } = await namedX3(); + await assert.rejects(client.setButtonMapping("Nope", "Mute"), /Unknown X3 button/); + await assert.rejects(client.setButtonMapping("Left", "Ctrl+Ctrl+X"), /not an X3 button action/); + await assert.rejects(client.setButtonMapping("Left", "Off"), /Left click/); + assert.equal(sent.length, 0); + await client.setButtonMapping("Right", "Left Click"); + await client.setButtonMapping("Left", "Off"); + assert.equal(sent.length, 10); + await client.resetButtonMappings(); + assert.equal((await client.readStatus()).buttonMappings?.Left, "Left Click"); +}); + +test("X3 macro upload sends three chunks, no commit lead, and keeps button state", async () => { + fresh(); + const { client, sent } = await namedX3(); + const events = Array.from({ length: 7 }, () => [{ usage: 6, down: true }, { usage: 6, down: false }]).flat(); + await client.uploadMacro({ events }); + assert.deepEqual(sent.map((s) => s.reportId), [0x09, 0x09, 0x09]); + assert.deepEqual(sent.map((s) => s.data.length), [63, 63, 11]); + assert.deepEqual(sent.map((s) => s.data.slice(0, 3)), [[0x40, 0x08, 0], [0x40, 0x08, 1], [0x0c, 0x08, 2]]); + assert.deepEqual(sent[2].data.slice(-2), [0x03, 0xf3]); + await assert.rejects(client.uploadMacro({ events: Array(51).fill({ usage: 4, down: true }) }), /at most 50/); + await assert.rejects(client.uploadMacro({ slot: 0, events }), /slot/); + assert.equal(sent.length, 3); +}); + +test("X3 button and macro methods are refused when the X3 is not named", async () => { + fresh(); + const device = fakeDevice(0xfa60); + const client = new AttackSharkHidClient(device.unit, { batteryWaitMs: 0, x3BurstGapMs: 0 }); + await client.open(); + await assert.rejects(client.setButtonMapping("Left", "Mute"), /only available on the Attack Shark X3/); + await assert.rejects(client.uploadMacro({ events: [] }), /only available on the Attack Shark X3/); + assert.equal(device.sent.length, 0); +});