diff --git a/README.md b/README.md index 3943fc49..8a59f125 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ checklist. | SteelSeries Rival 3 (Gen 1) | `@openmouse/protocol/steelseries` | | Teevolution | `@openmouse/protocol/teevolution` | | VGN | `@openmouse/protocol/vgn` | +| VAXEE / ZYGEN | `@openmouse/protocol/vaxee` | | WALLHACK | `@openmouse/protocol/wallhack` | | WLMouse | `@openmouse/protocol/wlmouse` | | Wooting | `@openmouse/protocol/wooting` | diff --git a/docs/vaxee-testing.md b/docs/vaxee-testing.md index e4a6a6e5..64c5f045 100644 --- a/docs/vaxee-testing.md +++ b/docs/vaxee-testing.md @@ -2,8 +2,44 @@ Source: the public [VAXEE Control Center](https://vcc.vaxee.cn/index.php), version 3.6, specifically its `api/api_core.js`, `api/api.js`, and `api/paramter.js` modules. The global site has the same page but currently serves a browser challenge to automated requests. The code in this repository is an independent implementation of the commands exposed by those modules. -The site advertises USB VID `3057`, the `FF05:0001` control collection, feature report `0E`, and the product IDs in `src/vaxee/index.ts`. Requests are 63 data bytes after the report ID. The panel sends a request, waits 100 ms, then reads feature report `0E`. Reply data begins at byte 5. The battery value is in 5% steps, which the panel multiplies by five. +The site advertises USB VID `3057`, the `FF05:0001` control collection, feature report `0E`, and the product IDs in `src/vaxee/index.ts`. Requests are 63 data bytes after the report ID. The panel sends a request, waits 100 ms, then reads feature report `0E`. On Windows the WebHID `DataView` includes the report ID at byte 0, so payload data begins at byte 5; implementations must also tolerate platforms that strip the prefix. Read replies carry `A5 01 ` and write acknowledgements carry `A5 03 01 01 ...`. The battery value is in 5% steps, which the panel multiplies by five. -OpenMouse currently exposes the active DPI stage, polling rate, battery, and lift-off distance. DPI, polling, and LOD writes are followed by a read-back. The driver limits DPI writes to the common 100–26,000 range in steps of 50 and limits the polling choices to rates the current wired or receiver path can safely use. VAXEE's newer 3954 models expose additional DPI and 8 kHz options, while the Control Center also supports tracking modes, trajectory, click latency, profiles, and key remapping. Those need model-specific verification before they are exposed here. +A receiver can answer the previous request when another application is polling the same collection. The Control Center retries a failed read; the driver does the same with a short pause before resending. -No model or connection path has been exercised on physical hardware yet. To validate one, record the mouse and receiver USB IDs, firmware versions, control-collection descriptor, and sanitized replies for commands `01`, `02`, `04`, `07`, `09`, `0A`, `0B`, and `10`. Test read-back after each setting change and note which writes persist after reconnection. The receiver may report a mouse PID distinct from its own USB PID. Avoid sharing device serial numbers or raw captures with personal data. +OpenMouse exposes all four DPI stages, the active stage, polling rate, battery, and lift-off distance. DPI stage values, the active stage, polling, and LOD writes are followed by a read-back. The driver limits DPI writes to the common 100–26,000 range in steps of 50 and limits the polling choices to rates the current wired or receiver path can safely use. VAXEE's newer 3954 models expose additional DPI and 8 kHz options, while the Control Center also supports tracking modes, trajectory, click latency, profiles, and key remapping. Those need model-specific verification before they are exposed here. + +No model or connection path had been exercised on physical hardware when the driver was added. To validate one, record the mouse and receiver USB IDs, firmware versions, control-collection descriptor, and sanitized replies for commands `01`, `02`, `04`, `07`, `09`, `0A`, `0B`, and `10`. Test read-back after each setting change and note which writes persist after reconnection. The receiver may report a mouse PID distinct from its own USB PID. Avoid sharing device serial numbers or raw captures with personal data. + +## Hardware verification + +A VAXEE E1 Wireless (mouse PID `0x1010`) behind the VXD02 4K receiver +(`3057:2001`, product string `VAXEE 4K Wireless 1.0`) was tested on Windows +WebHID. The official Control Center and the driver both report four enabled +stages: 400 / 800 / 800 / 3,200 DPI, with stage 3 active at 800 DPI and +1,000 Hz polling. The mouse reported firmware `0x0059`, low LOD, tracking mode +1, and a battery level of 7 steps (35%) while discharging. + +Measured replies (report ID included): + +```text +mouse PID 0E A5 0A 01 02 10 10 +DPI stage 0E A5 02 01 01 03 +DPI enabled 0E A5 03 01 04 01 01 01 01 +DPI stage 1 0E A5 04 01 03 01 90 01 (400 DPI) +DPI stage 2 0E A5 04 01 03 02 20 03 (800 DPI) +DPI stage 3 0E A5 04 01 03 03 20 03 (800 DPI) +DPI stage 4 0E A5 04 01 03 04 80 0C (3,200 DPI) +polling 0E A5 07 01 01 02 +LOD 0E A5 09 01 01 01 +battery 0E A5 0B 01 01 07 +charging 0E A5 10 01 01 00 +firmware 0E A5 01 01 02 59 00 +``` + +A stage write is acknowledged with `0E A5 04 03 01 01` and read back as +`0E A5 04 01 03 `. When the edited stage is the +active one, the driver selects that stage again with a `0x02` write so the +firmware applies the new DPI to the sensor; the Control Center does the same. +Stage 3 was written to 800 DPI and read back as +`0E A5 04 01 03 03 20 03`; polling and LOD writes were also acknowledged and +read back. Persistence across a power cycle has not been tested. diff --git a/src/drivers/vaxee/hid.test.ts b/src/drivers/vaxee/hid.test.ts index 56586f40..e86231eb 100644 --- a/src/drivers/vaxee/hid.test.ts +++ b/src/drivers/vaxee/hid.test.ts @@ -3,11 +3,15 @@ import test from "node:test"; import { VaxeeHidClient } from "./hid.ts"; import { VAXEE_COMMAND, VAXEE_REPORT_ID } from "@openmouse/protocol/vaxee"; -function device(productId = 0x2002, options: { ignoreWrites?: boolean; standardMode?: boolean } = {}) { - let dpi = 800; +function device(productId = 0x2002, options: { ignoreWrites?: boolean; standardMode?: boolean; mousePid?: number; batterySteps?: number; dpiStages?: number[]; activeStage?: number; staleDpiStageOnce?: number } = {}) { let rateCode = 2; let lod = 1; + const targetPid = options.mousePid ?? 0x1011; + const batterySteps = options.batterySteps ?? 13; + const dpiStages = [...(options.dpiStages ?? [800, 800, 800, 800])]; + let activeStage = options.activeStage ?? 0; let pending: Uint8Array | null = null; + let staleDpiStage = options.staleDpiStageOnce ?? null; const writes: Uint8Array[] = []; const hid = { vendorId: 0x3057, @@ -25,7 +29,11 @@ function device(productId = 0x2002, options: { ignoreWrites?: boolean; standardM pending = new Uint8Array(buffer as ArrayBuffer); writes.push(pending); if (pending[2] === 2 && !options.ignoreWrites) { - if (pending[1] === VAXEE_COMMAND.dpiValue) dpi = pending[5]! | (pending[6]! << 8); + if (pending[1] === VAXEE_COMMAND.dpiStage) activeStage = pending[4]! - 1; + if (pending[1] === VAXEE_COMMAND.dpiValue) { + const stage = pending[4]! - 1; + dpiStages[stage] = pending[5]! | (pending[6]! << 8); + } if (pending[1] === VAXEE_COMMAND.polling) rateCode = pending[4]!; if (pending[1] === VAXEE_COMMAND.lod) lod = pending[4]!; } @@ -34,17 +42,27 @@ function device(productId = 0x2002, options: { ignoreWrites?: boolean; standardM assert.equal(reportId, VAXEE_REPORT_ID); assert.ok(pending); const command = pending[1]!; - const reply = new Uint8Array(63); - const data = command === VAXEE_COMMAND.mousePid ? [0x11, 0x10] - : command === VAXEE_COMMAND.dpiStage ? [1] - : command === VAXEE_COMMAND.dpiValue ? [1, dpi & 255, dpi >> 8] + const reply = new Uint8Array(64); + const requestedStage = pending[4]!; + const stageDpi = dpiStages[requestedStage - 1] ?? 800; + const data = command === VAXEE_COMMAND.mousePid ? [targetPid & 0xff, targetPid >> 8] + : command === VAXEE_COMMAND.dpiStage ? [activeStage + 1] + : command === VAXEE_COMMAND.dpiEnabled ? [1, 1, 1, 1] + : command === VAXEE_COMMAND.dpiValue ? [requestedStage, stageDpi & 255, stageDpi >> 8] : command === VAXEE_COMMAND.polling ? [rateCode] : command === VAXEE_COMMAND.tracking ? [options.standardMode ? 0 : 1] : command === VAXEE_COMMAND.lod ? [lod] - : command === VAXEE_COMMAND.battery ? [13] + : command === VAXEE_COMMAND.battery ? [batterySteps] : command === VAXEE_COMMAND.charging ? [0] : command === VAXEE_COMMAND.firmware ? [1, 2] : [1]; - reply.set([0xa5, command, 3, 1, data.length, ...data]); + if (command === VAXEE_COMMAND.dpiValue && requestedStage === staleDpiStage) { + staleDpiStage = null; + data[0] = requestedStage - 1; + } + // Windows WebHID keeps the report ID at byte 0. Read replies carry type + // 0x01 followed by the payload length; write acks carry 0x03 0x01 0x01. + if (pending[2] === 1) reply.set([0x0e, 0xa5, command, 1, data.length, ...data]); + else reply.set([0x0e, 0xa5, command, 3, 1, 1]); return new DataView(reply.buffer); }, } as unknown as HIDDevice; @@ -81,3 +99,92 @@ test("VAXEE status decodes battery steps and writes verify against read-back", a await assert.rejects(() => client.setDpi(1651), RangeError); await assert.rejects(() => client.setPollingRate(125), RangeError); }); + +test("VAXEE retries a reply that answers another command", async () => { + const { hid } = device(); + const receive = hid.receiveFeatureReport.bind(hid); + let first = true; + hid.receiveFeatureReport = async (reportId: number) => { + if (first) { + first = false; + const reply = new Uint8Array(64); + reply.set([0x0e, 0xa5, VAXEE_COMMAND.polling, 1, 1, 2]); + return new DataView(reply.buffer); + } + return receive(reportId); + }; + const status = await new VaxeeHidClient(hid).readStatus(); + assert.equal(first, false); + assert.equal(status.name, "VAXEE NP-01S V2 Wireless"); + assert.equal(status.dpi, 800); +}); + +test("VAXEE retries a DPI reply that answers the previous stage", async () => { + const { hid } = device(0x2001, { + mousePid: 0x1010, + dpiStages: [400, 800, 1600, 3200], activeStage: 2, + staleDpiStageOnce: 2, + }); + const status = await new VaxeeHidClient(hid).readStatus(); + assert.deepEqual(status.dpiStages, [400, 800, 1600, 3200]); + assert.equal(status.dpi, 1600); + assert.equal(status.activeDpiStage, 2); +}); + +test("VAXEE retries a stale DPI read-back after a stage write", async () => { + const { hid } = device(0x2001, { + mousePid: 0x1010, + dpiStages: [400, 800, 1600, 3200], activeStage: 2, + staleDpiStageOnce: 3, + }); + const client = new VaxeeHidClient(hid); + assert.equal(await client.setDpiStageValue(2, 2000), 2000); +}); + +test("VAXEE reselects the active stage after a DPI write", async () => { + const { hid, writes } = device(0x2001, { + mousePid: 0x1010, + dpiStages: [400, 800, 1600, 3200], activeStage: 2, + }); + const client = new VaxeeHidClient(hid); + writes.length = 0; + await client.setDpiStageValue(1, 900); + assert.equal(writes.some((report) => report[1] === VAXEE_COMMAND.dpiStage && report[2] === 2), false); + writes.length = 0; + await client.setDpiStageValue(2, 2000); + assert.ok(writes.some((report) => report[1] === VAXEE_COMMAND.dpiStage && report[2] === 2 && report[4] === 3)); + assert.equal((await client.readStatus()).dpi, 2000); +}); + +test("VAXEE exposes the four DPI stages and writes them", async () => { + const { hid } = device(0x2001, { + mousePid: 0x1010, batterySteps: 7, + dpiStages: [400, 800, 800, 3200], activeStage: 2, + }); + const client = new VaxeeHidClient(hid); + const status = await client.readStatus(); + assert.equal(status.name, "VAXEE E1 Wireless"); + assert.equal(status.batteryPercent, 35); + assert.equal(status.batteryState, "Discharging"); + assert.equal(status.connectionType, "Wireless"); + assert.equal(status.connectionDetail, "2.4 GHz receiver"); + assert.deepEqual(status.supportedPollingRates, [500, 1000, 2000, 4000]); + assert.deepEqual(status.dpiStages, [400, 800, 800, 3200]); + assert.equal(status.activeDpiStage, 2); + assert.equal(status.dpi, 800); + assert.deepEqual(status.ui?.dpiStageEditor, { + maxStages: 4, countEditable: false, minDpi: 100, maxDpi: 26000, stepDpi: 50, + }); + + assert.equal(await client.setDpiStageValue(0, 1600), 1600); + assert.equal(await client.setActiveDpiStage(0), 0); + const afterStageWrite = await client.readStatus(); + assert.deepEqual(afterStageWrite.dpiStages, [1600, 800, 800, 3200]); + assert.equal(afterStageWrite.activeDpiStage, 0); + assert.equal(afterStageWrite.dpi, 1600); + + assert.equal(await client.setDpi(1200), 1200); + assert.equal((await client.readStatus()).dpi, 1200); + await assert.rejects(() => client.setDpiStageValue(4, 800), /between 0 and 3/); + await assert.rejects(() => client.setActiveDpiStage(-1), /between 0 and 3/); +}); diff --git a/src/drivers/vaxee/hid.ts b/src/drivers/vaxee/hid.ts index 4e077070..8db123dc 100644 --- a/src/drivers/vaxee/hid.ts +++ b/src/drivers/vaxee/hid.ts @@ -1,12 +1,27 @@ import type { MouseStatus } from "../mouse-types.ts"; import { - VAXEE_COMMAND, VAXEE_MOUSE_NAMES, VAXEE_PRODUCT_IDS, VAXEE_RECEIVER_IDS, + VAXEE_COMMAND, VAXEE_DPI_MAX, VAXEE_DPI_MIN, VAXEE_DPI_STAGE_COUNT, VAXEE_DPI_STEP, + VAXEE_MOUSE_NAMES, VAXEE_PRODUCT_IDS, VAXEE_RECEIVER_IDS, VAXEE_REPORT_ID, VAXEE_USAGE, VAXEE_USAGE_PAGE, VAXEE_VENDOR_ID, - vaxeeDpi, vaxeePollingCode, vaxeePollingRate, vaxeeReply, vaxeeRequest, + vaxeePollingCode, vaxeePollingRate, vaxeeReplyData, vaxeeRequest, } from "@openmouse/protocol/vaxee"; const PRODUCT_IDS = new Set(VAXEE_PRODUCT_IDS); const PAUSE_MS = 100; // Vendor panel waits 100 ms between send and receive. +const READ_ATTEMPTS = 3; // The receiver can answer the previous request when another app is polling. +const RETRY_MS = 150; + +function assertDpi(dpi: number): void { + if (!Number.isInteger(dpi) || dpi < VAXEE_DPI_MIN || dpi > VAXEE_DPI_MAX || dpi % VAXEE_DPI_STEP !== 0) { + throw new RangeError(`VAXEE DPI must be ${VAXEE_DPI_MIN}–${VAXEE_DPI_MAX.toLocaleString("en-US")} in steps of ${VAXEE_DPI_STEP}.`); + } +} + +function assertStage(stage: number): void { + if (!Number.isInteger(stage) || stage < 0 || stage >= VAXEE_DPI_STAGE_COUNT) { + throw new RangeError(`VAXEE DPI stage must be between 0 and ${VAXEE_DPI_STAGE_COUNT - 1}.`); + } +} function hasControlCollection(collections: readonly HIDCollectionInfo[]): boolean { return collections.some((collection) => @@ -33,7 +48,10 @@ export class VaxeeHidClient { getDpiOptions(): number[] { // The Control Center uses one-DPI steps on the 3954 generation, but the // current model may be behind a receiver. A 50-DPI grid is common to both. - return Array.from({ length: 519 }, (_, index) => 100 + index * 50); + return Array.from( + { length: (VAXEE_DPI_MAX - VAXEE_DPI_MIN) / VAXEE_DPI_STEP + 1 }, + (_, index) => VAXEE_DPI_MIN + index * VAXEE_DPI_STEP, + ); } getSupportedPollingRates(): number[] { @@ -53,24 +71,36 @@ export class VaxeeHidClient { async readStatus(): Promise { return this.run(async () => { const receiver = VAXEE_RECEIVER_IDS.has(this.device.productId); - const modelReply = await this.exchange(VAXEE_COMMAND.mousePid, 2, [], 2); - const mousePid = modelReply[5]! | (modelReply[6]! << 8); - const stage = (await this.exchange(VAXEE_COMMAND.dpiStage, 1, [], 1))[5]!; - if (stage < 1 || stage > 4) throw new Error(`Invalid VAXEE DPI stage ${stage}.`); - const dpi = vaxeeDpi(await this.exchange(VAXEE_COMMAND.dpiValue, 3, [stage], 3)); - const pollingRateHz = vaxeePollingRate((await this.exchange(VAXEE_COMMAND.polling, 1, [], 1))[5]!); - const lodCode = (await this.exchange(VAXEE_COMMAND.lod, 1, [], 1))[5]!; + const model = await this.exchange(VAXEE_COMMAND.mousePid, 2, [], 2); + const mousePid = model[0]! | (model[1]! << 8); + const activeStage = (await this.exchange(VAXEE_COMMAND.dpiStage, 1, [], 1))[0]!; + if (activeStage < 1 || activeStage > VAXEE_DPI_STAGE_COUNT) { + throw new Error(`Invalid VAXEE DPI stage ${activeStage}.`); + } + const dpiStages: number[] = []; + for (let stage = 1; stage <= VAXEE_DPI_STAGE_COUNT; stage += 1) { + const reply = await this.exchange(VAXEE_COMMAND.dpiValue, 3, [stage], 3, (data) => { + if (data[0] !== stage) throw new Error(`Invalid VAXEE DPI stage ${data[0]}.`); + }); + dpiStages.push(reply[1]! | (reply[2]! << 8)); + } + const activeDpiStage = activeStage - 1; + const dpi = dpiStages[activeDpiStage]!; + const pollingRateHz = vaxeePollingRate((await this.exchange(VAXEE_COMMAND.polling, 1, [], 1))[0]!); + const lodCode = (await this.exchange(VAXEE_COMMAND.lod, 1, [], 1))[0]!; if (lodCode !== 1 && lodCode !== 2) throw new Error(`Invalid VAXEE LOD code ${lodCode}.`); - const batterySteps = (await this.exchange(VAXEE_COMMAND.battery, 1, [], 1))[5]!; - const charging = (await this.exchange(VAXEE_COMMAND.charging, 1, [], 1))[5]!; + const batterySteps = (await this.exchange(VAXEE_COMMAND.battery, 1, [], 1))[0]!; + const charging = (await this.exchange(VAXEE_COMMAND.charging, 1, [], 1))[0]!; const firmware = await this.exchange(VAXEE_COMMAND.firmware, 2, [], 2); - const firmwareString = (firmware[5]! | (firmware[6]! << 8)).toString(16); + const firmwareString = (firmware[0]! | (firmware[1]! << 8)).toString(16); return { brand: "VAXEE", name: VAXEE_MOUSE_NAMES[mousePid] ? `VAXEE ${VAXEE_MOUSE_NAMES[mousePid]}` : this.device.productName || "VAXEE mouse", batteryPercent: batterySteps <= 20 ? batterySteps * 5 : null, batteryState: charging ? "Charging" : "Discharging", dpi, + dpiStages, + activeDpiStage, pollingRateHz, supportedPollingRates: this.getSupportedPollingRates(), activeProfile: null, @@ -86,22 +116,40 @@ export class VaxeeHidClient { hideSignalCard: true, hideSleepCard: true, defaultDisplayName: "VAXEE mouse", + dpiStageEditor: { + maxStages: VAXEE_DPI_STAGE_COUNT, + countEditable: false, + minDpi: VAXEE_DPI_MIN, + maxDpi: VAXEE_DPI_MAX, + stepDpi: VAXEE_DPI_STEP, + }, }, }; }); } async setDpi(dpi: number): Promise { - if (!Number.isInteger(dpi) || dpi < 100 || dpi > 26000 || dpi % 50 !== 0) { - throw new RangeError("VAXEE DPI must be 100–26,000 in steps of 50."); - } + assertDpi(dpi); return this.run(async () => { - const stage = (await this.exchange(VAXEE_COMMAND.dpiStage, 1, [], 1))[5]!; - if (stage < 1 || stage > 4) throw new Error(`Invalid VAXEE DPI stage ${stage}.`); - await this.exchange(VAXEE_COMMAND.dpiValue, 3, [stage, dpi & 255, dpi >> 8], 1, true); - const confirmed = vaxeeDpi(await this.exchange(VAXEE_COMMAND.dpiValue, 3, [stage], 3)); - if (confirmed !== dpi) throw new Error("VAXEE DPI write did not persist."); - return confirmed; + const stage = (await this.exchange(VAXEE_COMMAND.dpiStage, 1, [], 1))[0]!; + if (stage < 1 || stage > VAXEE_DPI_STAGE_COUNT) throw new Error(`Invalid VAXEE DPI stage ${stage}.`); + return this.writeDpiStage(stage - 1, dpi); + }); + } + + async setDpiStageValue(stage: number, dpi: number): Promise { + assertStage(stage); + assertDpi(dpi); + return this.run(() => this.writeDpiStage(stage, dpi)); + } + + async setActiveDpiStage(stage: number): Promise { + assertStage(stage); + return this.run(async () => { + await this.write(VAXEE_COMMAND.dpiStage, 1, [stage + 1]); + const confirmed = (await this.exchange(VAXEE_COMMAND.dpiStage, 1, [], 1))[0]!; + if (confirmed !== stage + 1) throw new Error("VAXEE DPI stage write did not persist."); + return stage; }); } @@ -110,15 +158,15 @@ export class VaxeeHidClient { return this.run(async () => { if (rate > 1000) { const newer = this.device.productId === 0x2002; - const tracking = (await this.exchange(VAXEE_COMMAND.tracking, newer ? 2 : 1, [], 1))[5]!; + const tracking = (await this.exchange(VAXEE_COMMAND.tracking, newer ? 2 : 1, [], 1))[0]!; if (newer ? tracking > 1 : tracking < 1 || tracking > 4) { throw new Error(`Unknown VAXEE tracking mode ${tracking}.`); } const standard = newer ? tracking === 0 : tracking === 2 || tracking === 4; if (standard) throw new Error("VAXEE standard mode is limited to 1,000 Hz."); } - await this.exchange(VAXEE_COMMAND.polling, 1, [vaxeePollingCode(rate)], 1, true); - const confirmed = vaxeePollingRate((await this.exchange(VAXEE_COMMAND.polling, 1, [], 1))[5]!); + await this.write(VAXEE_COMMAND.polling, 1, [vaxeePollingCode(rate)]); + const confirmed = vaxeePollingRate((await this.exchange(VAXEE_COMMAND.polling, 1, [], 1))[0]!); if (confirmed !== rate) throw new Error("VAXEE polling-rate write did not persist."); return confirmed; }); @@ -128,18 +176,66 @@ export class VaxeeHidClient { if (value !== "Low" && value !== "High") throw new RangeError("VAXEE supports Low or High LOD."); return this.run(async () => { const code = value === "Low" ? 1 : 2; - await this.exchange(VAXEE_COMMAND.lod, 1, [code], 1, true); - const confirmed = (await this.exchange(VAXEE_COMMAND.lod, 1, [], 1))[5]!; + await this.write(VAXEE_COMMAND.lod, 1, [code]); + const confirmed = (await this.exchange(VAXEE_COMMAND.lod, 1, [], 1))[0]!; if (confirmed !== code) throw new Error("VAXEE LOD write did not persist."); return value; }); } - private async exchange(command: number, length: number, values: number[], responseLength: number, write = false): Promise { + private async writeDpiStage(stage: number, dpi: number): Promise { + await this.write(VAXEE_COMMAND.dpiValue, 3, [stage + 1, dpi & 255, dpi >> 8]); + // The firmware applies a new value to the sensor only when the active + // stage is selected again. The Control Center does the same. + const active = (await this.exchange(VAXEE_COMMAND.dpiStage, 1, [], 1))[0]!; + if (active === stage + 1) { + await this.write(VAXEE_COMMAND.dpiStage, 1, [stage + 1]); + } + const reply = await this.exchange(VAXEE_COMMAND.dpiValue, 3, [stage + 1], 3, (data) => { + if (data[0] !== stage + 1) throw new Error(`Invalid VAXEE DPI stage ${data[0]}.`); + }); + const confirmed = reply[1]! | (reply[2]! << 8); + if (confirmed !== dpi) throw new Error("VAXEE DPI write did not persist."); + return confirmed; + } + + private async exchange( + command: number, + length: number, + values: number[], + responseLength: number, + validate?: (data: Uint8Array) => void, + ): Promise { await this.open(); - await this.device.sendFeatureReport(VAXEE_REPORT_ID, new Uint8Array(vaxeeRequest(command, length, values, write)).buffer); + let lastError: unknown; + for (let attempt = 0; attempt < READ_ATTEMPTS; attempt += 1) { + await this.device.sendFeatureReport(VAXEE_REPORT_ID, new Uint8Array(vaxeeRequest(command, length, values)).buffer); + await new Promise((resolve) => setTimeout(resolve, PAUSE_MS)); + try { + const data = vaxeeReplyData(await this.device.receiveFeatureReport(VAXEE_REPORT_ID), command, responseLength); + validate?.(data); + return data; + } catch (error) { + lastError = error; + if (attempt + 1 < READ_ATTEMPTS) { + await new Promise((resolve) => setTimeout(resolve, RETRY_MS)); + } + } + } + throw lastError; + } + + private async write(command: number, length: number, values: number[]): Promise { + await this.open(); + await this.device.sendFeatureReport(VAXEE_REPORT_ID, new Uint8Array(vaxeeRequest(command, length, values, true)).buffer); await new Promise((resolve) => setTimeout(resolve, PAUSE_MS)); - return vaxeeReply(await this.device.receiveFeatureReport(VAXEE_REPORT_ID), command, responseLength); + try { + // Setters verify through the read-back below; some firmware revisions + // do not answer a write with a feature report. + await this.device.receiveFeatureReport(VAXEE_REPORT_ID); + } catch { + // A missing acknowledgement is not fatal when the read-back succeeds. + } } private async run(action: () => Promise): Promise { diff --git a/src/vaxee/index.test.ts b/src/vaxee/index.test.ts index 0fec229c..82516415 100644 --- a/src/vaxee/index.test.ts +++ b/src/vaxee/index.test.ts @@ -1,20 +1,37 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { VAXEE_COMMAND, VAXEE_REPORT_SIZE, vaxeeDpi, vaxeePollingCode, vaxeePollingRate, vaxeeReply, vaxeeRequest } from "./index.ts"; +import { VAXEE_COMMAND, VAXEE_REPORT_SIZE, vaxeeDpi, vaxeePollingCode, vaxeePollingRate, vaxeeReply, vaxeeReplyData, vaxeeRequest } from "./index.ts"; -test("VAXEE DPI request and reply use the Control Center byte positions", () => { +test("VAXEE decodes read replies with the Windows report-ID prefix", () => { const request = vaxeeRequest(VAXEE_COMMAND.dpiValue, 3, [2, 0x88, 0x13], true); assert.equal(request.length, VAXEE_REPORT_SIZE); assert.deepEqual([...request.slice(0, 7)], [0xa5, 4, 2, 3, 2, 0x88, 0x13]); - const response = new Uint8Array(VAXEE_REPORT_SIZE); - response.set([0xa5, 4, 3, 1, 3, 2, 0x88, 0x13]); - assert.equal(vaxeeDpi(vaxeeReply(response, VAXEE_COMMAND.dpiValue, 3)), 5000); + + // Captured from an E1 Wireless on the VXD02 4K receiver: + // report ID 0x0e, magic 0xa5, command 0x04, read 0x01, length 0x03, + // then stage, DPI low, DPI high. + const response = new Uint8Array([0x0e, 0xa5, 4, 1, 3, 2, 0x88, 0x13]); + assert.equal(vaxeeDpi(response), 5000); + assert.deepEqual([...vaxeeReplyData(response, VAXEE_COMMAND.dpiValue, 3)], [2, 0x88, 0x13]); +}); + +test("VAXEE accepts read replies when the platform strips the report ID", () => { + const response = new Uint8Array([0xa5, 4, 1, 3, 2, 0x88, 0x13]); + assert.equal(vaxeeDpi(response), 5000); +}); + +test("VAXEE accepts write acknowledgements and rejects them as read data", () => { + const ack = new Uint8Array([0x0e, 0xa5, 4, 3, 1, 1]); + assert.doesNotThrow(() => vaxeeReply(ack, 4, 0)); + assert.throws(() => vaxeeReplyData(ack, 4, 0), /did not return a read reply/); }); test("VAXEE rejects truncated, mismatched, and invalid reports", () => { - const reply = new Uint8Array([0xa5, 4, 3, 1, 1, 2]); - assert.throws(() => vaxeeReply(reply, 4, 3)); - assert.throws(() => vaxeeReply(reply, 7, 1)); + const truncated = new Uint8Array([0x0e, 0xa5, 4, 1, 3, 2]); + assert.throws(() => vaxeeReply(truncated, 4, 3), /Truncated/); + assert.throws(() => vaxeeReply(new Uint8Array([0xa5, 7, 1, 1, 1, 0]), 4, 1)); + assert.throws(() => vaxeeReply(new Uint8Array([0xa5, 4, 2, 1, 1, 0]), 4, 1)); + assert.throws(() => vaxeeReply(new Uint8Array([0xa5, 4, 3]), 4, 0), /Truncated/); assert.throws(() => vaxeeRequest(4, 1, [256])); assert.equal(vaxeePollingRate(vaxeePollingCode(4000)), 4000); assert.throws(() => vaxeePollingCode(125)); diff --git a/src/vaxee/index.ts b/src/vaxee/index.ts index 9d7e2583..43a601bc 100644 --- a/src/vaxee/index.ts +++ b/src/vaxee/index.ts @@ -5,6 +5,12 @@ export const VAXEE_USAGE = 0x01; export const VAXEE_REPORT_ID = 0x0e; export const VAXEE_REPORT_SIZE = 63; +/** Four DPI stages, each 100–26,000 in 50-DPI steps. */ +export const VAXEE_DPI_STAGE_COUNT = 4; +export const VAXEE_DPI_MIN = 100; +export const VAXEE_DPI_MAX = 26000; +export const VAXEE_DPI_STEP = 50; + /** USB product IDs advertised by the official VAXEE Control Center. */ export const VAXEE_PRODUCT_IDS = [ 0x1001, 0x1002, 0x1003, 0x1004, 0x1005, 0x1006, 0x1007, 0x1008, @@ -44,21 +50,61 @@ export function vaxeeRequest(command: number, length: number, values: readonly n return bytes; } -export function vaxeeReply(source: DataView | Uint8Array, command: number, minimumDataLength: number): Uint8Array { - const bytes = source instanceof Uint8Array +function vaxeeBytes(source: DataView | Uint8Array): Uint8Array { + return source instanceof Uint8Array ? source : new Uint8Array(source.buffer, source.byteOffset, source.byteLength); - // The response has a five-byte envelope; data starts at offset 5. - if (bytes.length < 5 + minimumDataLength || bytes[0] !== 0xa5 || bytes[1] !== command || bytes[2] !== 3 || bytes[3] !== 1) { +} + +/** + * WebHID on Windows returns the report ID as the first byte of a feature + * report. Other platforms may omit it, so both layouts are accepted. + */ +function vaxeeReplyOffset(bytes: Uint8Array): number { + return bytes[0] === VAXEE_REPORT_ID ? 1 : 0; +} + +/** + * Validates a VAXEE feature-report reply. + * + * Read replies carry `A5 01 `. + * Write acknowledgements carry `A5 03 01 01 ...`; the written + * value is verified with a separate read-back. + */ +export function vaxeeReply(source: DataView | Uint8Array, command: number, minimumDataLength: number): Uint8Array { + const bytes = vaxeeBytes(source); + const offset = vaxeeReplyOffset(bytes); + if (bytes[offset] !== 0xa5 || bytes[offset + 1] !== command) { + throw new Error(`Invalid VAXEE reply for command 0x${command.toString(16)}.`); + } + const type = bytes[offset + 2]; + if (type === 0x01) { + const length = bytes[offset + 3] ?? 0; + if (length < minimumDataLength || bytes.length < offset + 4 + length) { + throw new Error("Truncated VAXEE reply payload."); + } + } else if (type === 0x03) { + if (bytes.length < offset + 5) throw new Error("Truncated VAXEE reply payload."); + } else { throw new Error(`Invalid VAXEE reply for command 0x${command.toString(16)}.`); } - if (bytes[4]! < minimumDataLength) throw new Error("Truncated VAXEE reply payload."); return bytes; } +/** Returns the payload of a read reply, excluding the report ID and envelope. */ +export function vaxeeReplyData(source: DataView | Uint8Array, command: number, minimumDataLength: number): Uint8Array { + const bytes = vaxeeReply(source, command, minimumDataLength); + const offset = vaxeeReplyOffset(bytes); + if (bytes[offset + 2] !== 0x01) { + throw new Error(`VAXEE command 0x${command.toString(16)} did not return a read reply.`); + } + const length = bytes[offset + 3]!; + return bytes.subarray(offset + 4, offset + 4 + length); +} + export function vaxeeDpi(reply: Uint8Array): number { - vaxeeReply(reply, VAXEE_COMMAND.dpiValue, 3); - return reply[6]! | (reply[7]! << 8); + const data = vaxeeReplyData(reply, VAXEE_COMMAND.dpiValue, 3); + return data[1]! | (data[2]! << 8); } export function vaxeePollingRate(code: number): number {