diff --git a/docs/mchose-protocol.md b/docs/mchose-protocol.md index fc77740f..056b7d7f 100644 --- a/docs/mchose-protocol.md +++ b/docs/mchose-protocol.md @@ -222,6 +222,7 @@ used directly when the mouse is on a cable: | A7 V2 Ultra | `0x4019` | 42000 | 0.7 mm, 1 mm, 2 mm | | A7 V2 Ultra+ | `0x4021` | 42000 | 0.7 mm, 1 mm, 2 mm | | L7 Pro+ | `0x4015` | 26000 | 1 mm, 2 mm (indices 1 and 2) | +| L7 Ultra | `0x00b1` | 42000 | 0.7 mm, 1 mm, 2 mm | MCHOSE's own firmware-version table cross-checks this: the Ultra reports `5.44.2.4` and the Ultra+ `5.46.2.4`. The test hardware reported `5.46.2.4`. @@ -261,7 +262,28 @@ Observed on an 8K receiver (macOS, `node-hid`): byte-identical config. Because other MCHOSE product lines share `0x5253`, the picker filter and the -driver match it only together with these two PIDs. +driver match it only together with these known PIDs. + +## L7 Ultra + +Firmware 5.14.5.0 uses wired ID `5253:00b1` and an 8K receiver at `5253:1020`. +The feature report bodies are 20 bytes for `0x11` and 64 bytes for `0x12`. +The receiver can answer `0x06` with zeros before reporting the mouse's ID +and battery. Its connection flag is bit 3 of battery payload byte 8. An +unidentified `5253:1020` receiver keeps trying identity, battery and config +on later reads. A connected `0x03` reply that explicitly names the L7 Ultra +can also complete discovery when battery telemetry is unavailable. + +Once identified, the L7 Ultra keeps its model through empty replies. Battery +(`0x06`) and config (`0x67`) stay retryable on later reads so the mouse can +recover after sleep. Identified legacy models retain empty-response suppression. + +The 63-byte `0x67` payload stores the X table at offsets 4–15, the enabled +stage count at offset 16, and the Y table at offsets 51–62. The L7 Ultra +uses `0x40` to apply both DPI tables, the stage count and the active indices. +The packet carries the reserved byte at config offset 3 and the observed +`diff` value of `0xff`. Post-cleanup physical testing was reported successful. +The L7 Pro+ retains the previously hardware-tested `0x57` write path. ## L7 Pro+ diff --git a/src/drivers/mchose/hid.test.ts b/src/drivers/mchose/hid.test.ts index d4af1c00..b26cf699 100644 --- a/src/drivers/mchose/hid.test.ts +++ b/src/drivers/mchose/hid.test.ts @@ -91,7 +91,10 @@ function fakeDevice(overrides?: Partial) { profile: 0, sleepEnabled: 0, mouseProductId: 0x4021, + batteryPayload: null as number[] | null, + identityPayload: IDENTITY, emptyShortReplies: [] as number[], + emptyConfigReplies: false, buttonNames: {} as Record, unansweredButtonNames: [] as number[], }; @@ -150,10 +153,20 @@ function fakeDevice(overrides?: Partial) { if (command === MCHOSE_COMMAND.writeConfig) { // The write layout is the read layout with the command byte in front. state.writes.push(tokens); - state.config = tokens.slice(1, 1 + CONFIG.length); + state.config = tokens.slice(1, 1 + state.config.length); pendingLong = MCHOSE_COMMAND.writeConfig; return; } + if (command === MCHOSE_COMMAND.writeDpi) { + state.writes.push(tokens); + state.config[1] = (state.config[1]! & 0xf0) | tokens[1]!; + state.config[2] = (state.config[2]! & 0xf0) | tokens[2]!; + state.config.splice(4, 12, ...tokens.slice(4, 16)); + state.config[16] = tokens[16]!; + state.config.splice(51, 12, ...tokens.slice(18, 30)); + pendingLong = command; + return; + } if (command === MCHOSE_COMMAND.setButton) { // A standalone command: it touches one button's four bytes and nothing // else, which is what the hardware was observed to do. @@ -173,10 +186,10 @@ function fakeDevice(overrides?: Partial) { if (state.emptyShortReplies.includes(pendingShort)) { return wireReply(id, pendingShort, new Array(MCHOSE_SHORT_TOKENS - 1).fill(0)); } - const payload = pendingShort === MCHOSE_COMMAND.identity ? IDENTITY + const payload = pendingShort === MCHOSE_COMMAND.identity ? state.identityPayload : pendingShort === MCHOSE_COMMAND.version ? VERSION : pendingShort === MCHOSE_COMMAND.battery - ? [...BATTERY.slice(0, 2), state.mouseProductId & 0xff, (state.mouseProductId >> 8) & 0xff, ...BATTERY.slice(4)] + ? state.batteryPayload ?? [...BATTERY.slice(0, 2), state.mouseProductId & 0xff, (state.mouseProductId >> 8) & 0xff, ...BATTERY.slice(4)] : []; return wireReply(id, pendingShort, payload); } @@ -191,7 +204,8 @@ function fakeDevice(overrides?: Partial) { const name = state.buttonNames[pendingButton] ?? ""; return wireReply(id, pendingLong, [pendingButton, name.length, ...[...name].map((c) => c.charCodeAt(0))]); } - return wireReply(id, MCHOSE_COMMAND.config, state.config); + const config = state.emptyConfigReplies ? new Array(MCHOSE_LONG_TOKENS - 1).fill(0) : state.config; + return wireReply(id, MCHOSE_COMMAND.config, config); }, ...overrides, } as unknown as HIDDevice; @@ -199,7 +213,183 @@ function fakeDevice(overrides?: Partial) { return { device, state }; } +/** Synthetic L7 Ultra configuration using observed DPI tables: one enabled stage, six stored X/Y stages. */ +function l7UltraDevice(wired = false) { + const fake = fakeDevice({ + vendorId: 0x5253, + productId: wired ? 0x00b1 : 0x1020, + productName: "", + } as Partial); + fake.state.batteryPayload = [0x53, 0x52, 0xb1, 0x00, 0x0e, 0x05, 0x05, 0x00, 0x09, 0x64, 0x00]; + fake.state.config = [...CONFIG, ...new Array(63 - CONFIG.length).fill(0)]; + fake.state.config[1] = 0x50; + fake.state.config[2] = 0x40; + const stages = [4000, 40000, 2000, 3200, 6400, 42000]; + stages.forEach((value, stage) => { + fake.state.config[4 + stage * 2] = value & 0xff; + fake.state.config[5 + stage * 2] = value >> 8; + fake.state.config[51 + stage * 2] = value & 0xff; + fake.state.config[52 + stage * 2] = value >> 8; + }); + fake.state.config[16] = 1; + fake.state.config[17] = 0xc0; + fake.state.config[18] = 0; + fake.state.config[19] = 5; + return fake; +} + describe("MchoseHidClient", () => { + it("reads L7 Ultra on both links and sends X/Y writes through the Bridge", async () => { + for (const wired of [false, true]) { + const { device, state } = l7UltraDevice(wired); + const send = device.sendFeatureReport; + const read = device.receiveFeatureReport; + device.collections[0]!.featureReports = [{ reportId: MCHOSE_SHORT_REPORT_ID, items: [{ reportCount: 20, reportSize: 8 }] }] as HIDReportInfo[]; + device.sendFeatureReport = async (id, body) => { + if (id === MCHOSE_SHORT_REPORT_ID) assert.equal(body.byteLength, 20); + return send(id, body); + }; + device.receiveFeatureReport = async (id) => { + const reply = await read(id); + return new DataView(reply.buffer, reply.byteOffset + 1, reply.byteLength - 1); + }; + const client = new MchoseHidClient(device); + assert.equal(MchoseHidClient.isSupported(device), true); + const status = await client.readStatus(); + assert.equal(status.name, "MCHOSE L7 Ultra"); + assert.equal(status.connectionType, wired ? "Wired" : "Wireless"); + assert.equal(status.batteryPercent, 100); + assert.deepEqual(status.dpiStages, [4000]); + assert.deepEqual(status.dpiStagesY, [4000]); + assert.deepEqual(status.dpiStoredStages, [4000, 40000, 2000, 3200, 6400, 42000]); + assert.equal(typeof client.setDpiStageAxes, "function"); + await client.setDpiStageAxes!(0, 1600, 2400); + assert.equal(state.writes.at(-1)?.[0], MCHOSE_COMMAND.writeDpi); + const after = await client.readStatus(); + assert.deepEqual(after.dpiStages, [1600]); + assert.deepEqual(after.dpiStagesY, [2400]); + assert.deepEqual(after.dpiStoredStagesY?.slice(1), status.dpiStoredStagesY?.slice(1)); + } + }); + + it("recovers L7 Ultra battery and config after a sleeping receiver poll", async () => { + const { device, state } = l7UltraDevice(); + const client = new MchoseHidClient(device); + assert.equal((await client.readStatus()).supportsSeparateDpiAxes, true); + + const send = device.sendFeatureReport; + device.sendFeatureReport = async (id, body) => { + const bytes = body instanceof Uint8Array ? body : new Uint8Array(body as ArrayBuffer); + if (id === MCHOSE_SHORT_REPORT_ID && bytes[0] === (~MCHOSE_COMMAND.identity & 0xff)) { + throw new Error("Cannot send identity request"); + } + return send(id, body); + }; + state.emptyShortReplies = [MCHOSE_COMMAND.battery]; + state.emptyConfigReplies = true; + const status = await client.readStatus(); + assert.equal(status.name, "MCHOSE L7 Ultra"); + assert.equal(status.batteryPercent, null); + assert.equal(status.supportsSeparateDpiAxes, true); + assert.equal(status.dpiStages, undefined); + await assert.rejects(() => client.setDpiStageValue(0, 2400), /did not return its configuration/); + + device.sendFeatureReport = send; + state.emptyShortReplies = []; + state.emptyConfigReplies = false; + const awake = await client.readStatus(); + assert.equal(awake.batteryPercent, 100); + assert.deepEqual(awake.dpiStagesY, [4000]); + await client.setDpiStageValue(0, 2400); + assert.equal(state.writes.at(-1)?.[0], MCHOSE_COMMAND.writeDpi); + assert.equal(state.config[51], 0x60); + }); + + it("discovers an L7 Ultra after an unnamed receiver's initial poll is empty", async () => { + for (const usingBattery of [true, false]) { + const { device, state } = l7UltraDevice(); + const client = new MchoseHidClient(device); + state.emptyShortReplies = [MCHOSE_COMMAND.identity, MCHOSE_COMMAND.battery]; + state.emptyConfigReplies = true; + const unidentified = await client.readStatus(); + assert.equal(unidentified.name, "MCHOSE"); + assert.equal(unidentified.supportsSeparateDpiAxes, false); + assert.equal(unidentified.dpiStages, undefined); + + state.emptyShortReplies = usingBattery ? [] : [MCHOSE_COMMAND.battery]; + if (!usingBattery) state.identityPayload = [1, 0x53, 0x52, 0xb1, 0x00, 1, 0]; + state.emptyConfigReplies = false; + const identified = await client.readStatus(); + assert.equal(identified.name, "MCHOSE L7 Ultra"); + assert.equal(identified.batteryPercent, usingBattery ? 100 : null); + assert.deepEqual(identified.dpiStagesY, [4000]); + } + }); + + it("enables stored L7 stages and keeps both active indices in range when shrinking", async () => { + const { device, state } = l7UltraDevice(); + const client = new MchoseHidClient(device); + await client.readStatus(); + await client.setDpiStageCount(6); + assert.equal(state.writes.at(-1)?.[0], MCHOSE_COMMAND.writeDpi); + assert.deepEqual((await client.readStatus()).dpiStages, [4000, 40000, 2000, 3200, 6400, 42000]); + await client.setActiveDpiStage(5); + // Exercise the inactive link too, not just the wireless setter above. + state.config[1] = (state.config[1]! & 0xf0) | 4; + await client.setDpiStageCount(1); + const status = await client.readStatus(); + assert.deepEqual(status.dpiStages, [4000]); + assert.equal(status.activeDpiStage, 0); + assert.equal(state.config[1]! & 0x0f, 0); + assert.equal(state.config[2]! & 0x0f, 0); + assert.deepEqual(status.dpiStoredStages, [4000, 40000, 2000, 3200, 6400, 42000]); + }); + + it("rejects DPI writes on an unidentified shared receiver until discovery", async () => { + const { device, state } = l7UltraDevice(); + const client = new MchoseHidClient(device); + await assert.rejects(() => client.setDpiStageValue(0, 2400), /Identify the mouse/); + await assert.rejects(() => client.setDpi(2400), /Identify the mouse/); + await assert.rejects(() => client.setDpiStageCount(2), /Identify the mouse/); + await assert.rejects(() => client.setActiveDpiStage(0), /Identify the mouse/); + assert.equal(state.writes.length, 0); + await client.readStatus(); + await client.setDpiStageValue(0, 2400); + assert.equal(state.writes.at(-1)?.[0], MCHOSE_COMMAND.writeDpi); + }); + + it("keeps the name fallback for an unlisted battery PID", async () => { + const { device, state } = fakeDevice({ + vendorId: 0x5253, productId: 0x1020, productName: "MCHOSE A7 V2 Ultra+", + } as Partial); + state.mouseProductId = 0x7fff; + const client = new MchoseHidClient(device); + const status = await client.readStatus(); + assert.equal(status.name, "MCHOSE A7 V2 Ultra+"); + assert.ok(status.supportedPollingRates?.includes(1000)); + await client.setPollingRate(1000); + assert.equal(state.writes.at(-1)?.[0], MCHOSE_COMMAND.writeConfig); + }); + + it("sizes short setter reports for L7 Ultra and retains the legacy fallback", async () => { + for (const ultra of [true, false]) { + const { device } = ultra ? l7UltraDevice() : fakeDevice(); + if (ultra) { + device.collections[0]!.featureReports = [{ reportId: MCHOSE_SHORT_REPORT_ID, items: [{ reportCount: 20, reportSize: 8 }] }] as HIDReportInfo[]; + } + const send = device.sendFeatureReport; + device.sendFeatureReport = async (id, body) => { + if (id === MCHOSE_SHORT_REPORT_ID) assert.equal(body.byteLength, ultra ? 20 : 64); + return send(id, body); + }; + const client = new MchoseHidClient(device); + await client.readStatus(); + await client.setMotionSync(true); + await client.setSleepTimeout(120); + await client.setProfile(3); + } + }); + it("matches an MCHOSE device exposing the 0xff01 config collection", () => { assert.equal(MchoseHidClient.isSupported(fakeDevice().device), true); }); @@ -229,8 +419,9 @@ describe("MchoseHidClient", () => { assert.equal(status.ui?.dpiStageEditor?.maxDpi, 42000); }); - it("stops polling commands the 0x5253 receiver only ever answers empty", async () => { - const { device } = a7UltraDevice(); + it("suppresses repeatedly empty identity, battery and version replies for a named legacy receiver", async () => { + const { device, state } = a7UltraDevice(); + state.emptyShortReplies.push(MCHOSE_COMMAND.identity); const counts = countCommands(device); const client = new MchoseHidClient(device); await client.readStatus(); @@ -238,12 +429,33 @@ describe("MchoseHidClient", () => { counts.clear(); const status = await client.readStatus(); + assert.equal(counts.get(MCHOSE_COMMAND.identity), undefined); assert.equal(counts.get(MCHOSE_COMMAND.battery), undefined); assert.equal(counts.get(MCHOSE_COMMAND.version), undefined); assert.ok(counts.get(MCHOSE_COMMAND.config), "config is still read"); assert.equal(status.pollingRateHz, 2000); }); + it("suppresses empty polls once battery has identified L7 Pro+ on an unnamed receiver", async () => { + const { device, state } = l7UltraDevice(); + state.batteryPayload = [0x37, 0x38, 0x15, 0x40, ...BATTERY.slice(4)]; + const counts = countCommands(device); + const client = new MchoseHidClient(device); + assert.equal((await client.readStatus()).name, "MCHOSE L7 Pro+"); + assert.equal(client.setDpiStageAxes, undefined); + await client.setDpiStageValue(0, 2400); + assert.equal(state.writes.at(-1)?.[0], MCHOSE_COMMAND.writeConfig); + + state.emptyShortReplies = [MCHOSE_COMMAND.identity, MCHOSE_COMMAND.battery]; + state.emptyConfigReplies = true; + await client.readStatus(); + counts.clear(); + assert.equal((await client.readStatus()).name, "MCHOSE L7 Pro+"); + assert.equal(counts.get(MCHOSE_COMMAND.identity), undefined); + assert.equal(counts.get(MCHOSE_COMMAND.battery), undefined); + assert.equal(counts.get(MCHOSE_COMMAND.config), undefined); + }); + it("keeps polling empty replies in full on a 0x3837 receiver", async () => { const { device, state } = fakeDevice(); state.emptyShortReplies = [MCHOSE_COMMAND.battery]; diff --git a/src/drivers/mchose/hid.ts b/src/drivers/mchose/hid.ts index e24a7a6c..29d9c7ff 100644 --- a/src/drivers/mchose/hid.ts +++ b/src/drivers/mchose/hid.ts @@ -3,6 +3,8 @@ import { MCHOSE_CONFIG_USAGE, MCHOSE_CONFIG_USAGE_PAGE, MCHOSE_DPI_STAGES, + MCHOSE_L7_ULTRA_PRODUCT_ID, + MCHOSE_LINK_PRODUCT_IDS, MCHOSE_LONG_REPORT_ID, MCHOSE_LONG_TOKENS, MCHOSE_PRODUCTS, @@ -21,9 +23,11 @@ import { mchoseDecodeVersion, mchoseEncodeCommand, mchoseEncodeConfigWrite, + mchoseEncodeDpiWrite, mchoseEncodeSetProfile, mchoseEncodeSleep, mchoseEncodePerformance, + type MchoseDpiEdit, type MchoseProcessing, mchoseLiftOffLabels, mchoseDecodeButtons, @@ -74,9 +78,8 @@ const PERFORMANCE_SETTLE_MS = 2000; const PERFORMANCE_ATTEMPTS = 3; /** A button write is a standalone command and applies quickly. */ const BUTTON_SETTLE_MS = 900; -/** Bytes of the 0x67 reply that carry fields; past this is stale scratch. */ +/** Legacy 0x67 fields end at byte 20; only L7 Ultra verifies the Y table. */ const CONFIG_MEANINGFUL_BYTES = 20; -const BATTERY_MEANINGFUL_BYTES = 11; const DPI_MIN = 50; const DPI_STEP = 50; @@ -87,11 +90,57 @@ export class MchoseHidClient { readonly device: HIDDevice; private queue: Promise = Promise.resolve(); - private cachedProduct: ReturnType = null; + private cachedProduct: ReturnType; + private receiverProductId: number | null = null; private readonly unansweredCommands = new Set(); + private get isL7Ultra(): boolean { + return this.cachedProduct?.productId === MCHOSE_L7_ULTRA_PRODUCT_ID; + } + + private get isSharedRealtekReceiver(): boolean { + return this.device.vendorId === VENDOR_ID.mchoseRealtek + && this.device.productId === MCHOSE_LINK_PRODUCT_IDS.receiver8k; + } + + private get isUnidentifiedRealtekReceiver(): boolean { + return this.isSharedRealtekReceiver + && this.receiverProductId === null + && this.cachedProduct === null; + } + + private commandBody(tokens: readonly number[], tokenCount: number): Uint8Array { + const body = mchoseEncodeCommand(tokens, tokenCount); + if (tokenCount !== MCHOSE_SHORT_TOKENS) return body; + const reportBytes = (collection: HIDCollectionInfo): number | null => { + const report = collection.featureReports?.find((item) => item.reportId === MCHOSE_SHORT_REPORT_ID); + if (report) { + const bits = report.items.reduce((sum, item) => sum + item.reportSize * item.reportCount, 0); + return Math.ceil(bits / 8); + } + for (const child of collection.children) { + const size = reportBytes(child); + if (size !== null) return size; + } + return null; + }; + const declared = this.device.collections.map(reportBytes).find((bytes) => bytes !== null); + const product = this.cachedProduct ?? (this.receiverProductId === null + ? mchoseFindProduct(null, this.device.productName) : null); + const length = declared === MCHOSE_SHORT_TOKENS || ((declared == null || declared === 0) && product?.productId === MCHOSE_L7_ULTRA_PRODUCT_ID) + ? MCHOSE_SHORT_TOKENS : MCHOSE_LONG_TOKENS; + return length === MCHOSE_SHORT_TOKENS ? body.slice(0, length) : body; + } + + private enqueue(run: () => Promise): Promise { + const next = this.queue.then(run, run); + this.queue = next.catch(() => undefined); + return next; + } + constructor(device: HIDDevice) { this.device = device; + this.cachedProduct = mchoseFindProduct(device.productId); } static isSupported(device: HIDDevice): boolean { @@ -155,53 +204,69 @@ export class MchoseHidClient { * reads as a valid one — which is exactly how a config read can hand back a * battery reply. */ - private request( + private async requestNow( reportId: number, command: number, tokenCount: number, accept: (payload: Uint8Array) => boolean, extraTokens: readonly number[] = [], + stableLength?: (payload: Uint8Array) => number, ): Promise { const key = [reportId, command, ...extraTokens].join(":"); - const run = async (): Promise => { - if (this.unansweredCommands.has(key)) return null; - const body = mchoseEncodeCommand([command, ...extraTokens], tokenCount); - let previous: Uint8Array | null = null; - let onlyEmptyEchoes = true; - for (let attempt = 0; attempt < POLL_ATTEMPTS; attempt += 1) { - await this.device.sendFeatureReport(reportId, body); - await delay(POLL_DELAY_MS); - let raw: DataView; - try { - raw = await this.device.receiveFeatureReport(reportId); - } catch { - onlyEmptyEchoes = false; - continue; - } - const reply = mchoseDecodeReply(new Uint8Array(raw.buffer)); - const empty = reply?.command === command - && reply.payload.subarray(0, tokenCount - 1).every((byte) => byte === 0); - if (!empty) onlyEmptyEchoes = false; - if (!reply || reply.command !== command) continue; - if (!accept(reply.payload)) continue; - if (previous && reply.payload.every((byte, index) => byte === previous![index])) { - return reply.payload; - } - previous = Uint8Array.from(reply.payload); + const discovering = this.isUnidentifiedRealtekReceiver; + // Unknown receivers can be waiting for their first mouse reply. An L7 + // Ultra can also leave battery and config empty while the mouse sleeps. + const retryEmpty = (discovering || this.isL7Ultra) + && (command === MCHOSE_COMMAND.battery || command === MCHOSE_COMMAND.config + || (discovering && command === MCHOSE_COMMAND.identity)); + const suppressEmpty = this.device.vendorId === VENDOR_ID.mchoseRealtek && !retryEmpty; + if (suppressEmpty && this.unansweredCommands.has(key)) return null; + const body = this.commandBody([command, ...extraTokens], tokenCount); + let previous: Uint8Array | null = null; + let onlyEmptyEchoes = true; + for (let attempt = 0; attempt < POLL_ATTEMPTS; attempt += 1) { + await this.device.sendFeatureReport(reportId, body); + await delay(POLL_DELAY_MS); + let raw: DataView; + try { + raw = await this.device.receiveFeatureReport(reportId); + } catch { + onlyEmptyEchoes = false; + continue; } - // The A7 Ultra's 0x5253 receiver acknowledges some commands with an - // empty payload every time. Once it has done so for a whole poll, skip - // that command for the rest of the session instead of polling it again. - // The 0x3837 receivers answer empty while waiting on the RF link, so - // they keep the full poll every time. - if (onlyEmptyEchoes && this.device.vendorId === VENDOR_ID.mchoseRealtek) { - this.unansweredCommands.add(key); + const bytes = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength); + // WebHID includes the report ID. The native Bridge adapter removes it + // before constructing its DataView, so accept that framing as well. + const framed = bytes[0] === reportId ? bytes : Uint8Array.of(reportId, ...bytes); + const reply = mchoseDecodeReply(framed); + const empty = reply?.command === command + && reply.payload.subarray(0, tokenCount - 1).every((byte) => byte === 0); + if (!empty) onlyEmptyEchoes = false; + if (!reply || reply.command !== command || !accept(reply.payload)) continue; + const length = stableLength?.(reply.payload) ?? reply.payload.length; + if (length < 1 || reply.payload.length < length) continue; + const meaningful = reply.payload.subarray(0, length); + if (command === MCHOSE_COMMAND.battery && mchoseDecodeBattery(reply.payload)?.productId === MCHOSE_L7_ULTRA_PRODUCT_ID) return reply.payload; + if (previous && previous.length === length && meaningful.every((byte, index) => byte === previous![index])) { + return reply.payload; } - return null; - }; - const next = this.queue.then(run, run); - this.queue = next.catch(() => undefined); - return next; + previous = Uint8Array.from(meaningful); + } + if (onlyEmptyEchoes && suppressEmpty) { + this.unansweredCommands.add(key); + } + return null; + } + + private request( + reportId: number, + command: number, + tokenCount: number, + accept: (payload: Uint8Array) => boolean, + extraTokens: readonly number[] = [], + stableLength?: (payload: Uint8Array) => number, + ): Promise { + return this.enqueue(() => this.requestNow(reportId, command, tokenCount, accept, extraTokens, stableLength)); } private nonZero(length: number) { @@ -217,11 +282,17 @@ export class MchoseHidClient { } private readConfigPayload(): Promise { - return this.request( + return this.enqueue(() => this.readConfigPayloadNow()); + } + + private readConfigPayloadNow(): Promise { + return this.requestNow( MCHOSE_LONG_REPORT_ID, MCHOSE_COMMAND.config, MCHOSE_LONG_TOKENS, MchoseHidClient.looksLikeConfig, + [], + this.isL7Ultra ? () => 63 : undefined, ); } @@ -231,26 +302,50 @@ export class MchoseHidClient { * and macros are preserved rather than zeroed by a partial write. */ private async updateConfig( - changes: Parameters[1], + changes: NonNullable[1]> | ((current: MchoseConfig) => MchoseDpiEdit), ): Promise { - await this.open(); - const before = await this.readConfigPayload(); - if (!before) throw new Error("The mouse did not return its configuration."); - - const tokens = mchoseEncodeConfigWrite(before, changes); - const body = mchoseEncodeCommand(tokens, MCHOSE_LONG_TOKENS); - const send = async (): Promise => { - await this.device.sendFeatureReport(MCHOSE_LONG_REPORT_ID, body); + return this.enqueue(async () => { + await this.open(); + const dpiEdit = typeof changes === "function"; + if (dpiEdit && this.isSharedRealtekReceiver && this.cachedProduct === null) { + // Preserve the name fallback for known legacy receivers, but never + // guess the DPI write layout for an unidentified shared receiver. + if (this.receiverProductId === null) { + this.cachedProduct = mchoseFindProduct(null, this.device.productName); + } + if (this.cachedProduct === null) { + throw new Error("Identify the mouse with readStatus() before changing DPI."); + } + } + const layout = this.isL7Ultra ? "l7-ultra" : "legacy"; + const before = await this.readConfigPayloadNow(); + if (!before) throw new Error("The mouse did not return its configuration."); + const current = mchoseDecodeConfig(before, layout); + if (!current) throw new Error("The mouse did not return its configuration."); + const edit = dpiEdit ? changes(current) : changes; + const extended = dpiEdit && this.isL7Ultra; + const tokens = extended ? mchoseEncodeDpiWrite(before, edit) : mchoseEncodeConfigWrite(before, edit); + await this.device.sendFeatureReport(MCHOSE_LONG_REPORT_ID, mchoseEncodeCommand(tokens, MCHOSE_LONG_TOKENS)); await delay(WRITE_SETTLE_MS); - }; - const queued = this.queue.then(send, send); - this.queue = queued.catch(() => undefined); - await queued; - const after = await this.readConfigPayload(); - const decoded = after ? mchoseDecodeConfig(after) : null; - if (!decoded) throw new Error("The mouse did not confirm the new configuration."); - return decoded; + for (let attempt = 0; attempt < (extended ? 5 : 1); attempt += 1) { + const after = await this.readConfigPayloadNow(); + const config = after && mchoseDecodeConfig(after, layout); + if (config && (!extended || this.confirmsDpiWrite(config, tokens))) return config; + if (extended && attempt < 4) await delay(80 * (attempt + 1)); + } + throw new Error("The mouse did not confirm the requested configuration change."); + }); + } + + private confirmsDpiWrite(config: MchoseConfig, tokens: number[]): boolean { + const matchesTable = (table: number[] | undefined, offset: number) => + table?.every((dpi, stage) => dpi === (tokens[offset + stage * 2]! | (tokens[offset + stage * 2 + 1]! << 8))); + return config.wiredDpiIndex === tokens[1] + && config.wirelessDpiIndex === tokens[2] + && config.stageCount === tokens[16] + && matchesTable(config.dpiStages, 4) === true + && matchesTable(config.dpiStagesY, 18) === true; } private linkRates(product: ReturnType): readonly number[] { @@ -264,32 +359,57 @@ export class MchoseHidClient { async readStatus(): Promise { await this.open(); - // Identity and version answer from the receiver itself and are reliable; - // battery and config travel over the RF link, so a partial read degrades - // rather than breaking the connect flow. - const identity = mchoseDecodeIdentity( - (await this.request(MCHOSE_SHORT_REPORT_ID, MCHOSE_COMMAND.identity, MCHOSE_SHORT_TOKENS, this.nonZero(7))) ?? new Uint8Array(), - ); - const version = mchoseDecodeVersion( - (await this.request(MCHOSE_SHORT_REPORT_ID, MCHOSE_COMMAND.version, MCHOSE_SHORT_TOKENS, this.nonZero(2))) ?? new Uint8Array(), - ); - - let battery: MchoseBattery | null = null; - const batteryPayload = await this.request( - MCHOSE_SHORT_REPORT_ID, MCHOSE_COMMAND.battery, MCHOSE_SHORT_TOKENS, - this.nonZero(BATTERY_MEANINGFUL_BYTES), - ); - if (batteryPayload) battery = mchoseDecodeBattery(batteryPayload); - - const configPayload = await this.readConfigPayload(); - const config = configPayload ? mchoseDecodeConfig(configPayload) : null; - - const product = mchoseFindProduct(battery?.productId ?? null, this.device.productName); - this.cachedProduct = product; const wired = this.isWired(); + // Keep model selection and its config read together so writes cannot + // see a partially refreshed receiver identity. + const { identity, version, battery, product, configPayload } = await this.enqueue(async () => { + if (!wired && this.receiverProductId === null && this.cachedProduct === null) { + this.cachedProduct = mchoseFindProduct(null, this.device.productName); + } + const identityPayload = await this.requestNow( + MCHOSE_SHORT_REPORT_ID, MCHOSE_COMMAND.identity, MCHOSE_SHORT_TOKENS, this.nonZero(7), [], () => 7, + ).catch(() => null); + const identity = identityPayload ? mchoseDecodeIdentity(identityPayload) : null; + const versionPayload = await this.requestNow( + MCHOSE_SHORT_REPORT_ID, MCHOSE_COMMAND.version, MCHOSE_SHORT_TOKENS, + (payload) => mchoseDecodeVersion(payload) !== null, [], (payload) => 1 + (payload[0] ?? 0), + ).catch(() => null); + const version = versionPayload ? mchoseDecodeVersion(versionPayload) : null; + const batteryPayload = await this.requestNow( + MCHOSE_SHORT_REPORT_ID, MCHOSE_COMMAND.battery, MCHOSE_SHORT_TOKENS, + (payload) => { + const battery = mchoseDecodeBattery(payload); + return battery !== null && battery.productId !== 0 && battery.batteryPercent <= 100 + && (battery.vendorId === VENDOR_ID.mchose || battery.vendorId === VENDOR_ID.mchoseRealtek); + }, + ).catch(() => null); + const battery: MchoseBattery | null = batteryPayload ? mchoseDecodeBattery(batteryPayload) : null; + + if (!wired) { + // 0x03 usually names the receiver. It can identify an L7 Ultra + // during discovery if it explicitly reports the linked mouse ID. + const linkedL7Ultra = this.isUnidentifiedRealtekReceiver && identity?.bonded && identity.connected + && identity.vendorId === VENDOR_ID.mchoseRealtek && identity.productId === MCHOSE_L7_ULTRA_PRODUCT_ID; + const newProductId = battery?.productId ?? (linkedL7Ultra ? MCHOSE_L7_ULTRA_PRODUCT_ID : undefined); + if (newProductId !== undefined && newProductId !== this.receiverProductId) { + this.receiverProductId = newProductId; + this.cachedProduct = mchoseFindProduct(newProductId, this.device.productName); + } + } + const product = this.cachedProduct; + const configPayload = await this.readConfigPayloadNow(); + return { identity, version, battery, product, configPayload }; + }); + const config = configPayload + ? mchoseDecodeConfig(configPayload, product?.productId === MCHOSE_L7_ULTRA_PRODUCT_ID ? "l7-ultra" : "legacy") + : null; const stageIndex = config ? (wired ? config.wiredDpiIndex : config.wirelessDpiIndex) : 0; const rateIndex = config ? (wired ? config.wiredRateIndex : config.wirelessRateIndex) : -1; const stages = config?.dpiStages ?? []; + const enabledCount = config && config.stageCount >= 1 && config.stageCount <= MCHOSE_DPI_STAGES + ? config.stageCount : 0; + const separateAxes = product?.productId === MCHOSE_L7_ULTRA_PRODUCT_ID; + const yStages = separateAxes ? config?.dpiStagesY : undefined; const rates = this.linkRates(product); const liftOffSteps = product?.liftOffDistances.length ?? 3; const liftOffBase = product?.liftOffIndexBase ?? 0; @@ -298,16 +418,22 @@ export class MchoseHidClient { const profileNames = config ? await this.readProfileNames() : null; const firmware: string[] = []; - if (version) firmware.push(`Receiver ${version}`); + if (version) firmware.push(`${wired && separateAxes ? "Mouse" : "Receiver"} ${version}`); + const visibleBattery = battery && (!separateAxes || wired || battery.connected) ? battery : null; return { brand: "MCHOSE", name: product ? `MCHOSE ${product.name}` : this.displayName(), - batteryPercent: battery?.batteryPercent ?? null, - batteryState: battery?.charging ? "Charging" : battery ? "Discharging" : "Unknown", + batteryPercent: visibleBattery?.batteryPercent ?? null, + batteryState: visibleBattery?.charging ? "Charging" : visibleBattery ? "Discharging" : "Unknown", dpi: stages[stageIndex] ?? 0, - dpiStages: stages.length ? stages : undefined, - activeDpiStage: stages.length ? stageIndex : undefined, + dpiY: yStages?.[stageIndex], + supportsSeparateDpiAxes: separateAxes, + dpiStages: separateAxes ? (enabledCount ? stages.slice(0, enabledCount) : undefined) : (stages.length ? stages : undefined), + dpiStagesY: yStages && enabledCount ? yStages.slice(0, enabledCount) : undefined, + dpiStoredStages: yStages ? stages : undefined, + dpiStoredStagesY: yStages, + activeDpiStage: separateAxes && stageIndex >= enabledCount ? undefined : (stages.length ? stageIndex : undefined), pollingRateHz: rates[rateIndex] ?? 0, supportedPollingRates: rates.length ? [...rates] : undefined, // The wire index is 0-based; the shell shows profiles counting from one. @@ -317,7 +443,7 @@ export class MchoseHidClient { debounceMs: config?.keyDebounce ?? null, sleepTimeout: config ? config.sleep * 60 : null, connectionType: wired ? "Wired" : "Wireless", - connectionDetail: identity && !identity.connected + connectionDetail: !(wired && separateAxes) && identity && !identity.connected ? "Receiver connected, mouse not linked" : undefined, liftOffDistance: config ? (mchoseLiftOffLabels(liftOffSteps)[config.liftOffIndex - liftOffBase] ?? null) : null, @@ -359,7 +485,9 @@ export class MchoseHidClient { /** Called for every connected client; the stage editor drives DPI here. */ getDpiOptions(): number[] { - return []; + if (!this.isL7Ultra) return []; + const max = this.cachedProduct!.dpiMax; + return Array.from({ length: Math.floor((max - DPI_MIN) / DPI_STEP) + 1 }, (_, index) => DPI_MIN + index * DPI_STEP); } // ── setters ────────────────────────────────────────────────────────────── @@ -379,27 +507,43 @@ export class MchoseHidClient { throw new Error(`DPI stage must be 0-${MCHOSE_DPI_STAGES - 1}.`); } const key = this.isWired() ? "wiredDpiIndex" : "wirelessDpiIndex"; - const after = await this.updateConfig({ [key]: stage }); + const after = await this.updateConfig((current) => { + if (this.isL7Ultra && stage >= current.stageCount) throw new RangeError("DPI stage is not enabled."); + return { [key]: stage }; + }); const applied = this.isWired() ? after.wiredDpiIndex : after.wirelessDpiIndex; if (applied !== stage) throw new Error("The mouse did not accept the new DPI stage."); } - async setDpiStageValue(stage: number, dpi: number): Promise { - if (!Number.isInteger(stage) || stage < 0 || stage >= MCHOSE_DPI_STAGES) { - throw new Error(`DPI stage must be 0-${MCHOSE_DPI_STAGES - 1}.`); - } - const max = this.cachedProduct?.dpiMax ?? 26000; - if (dpi < DPI_MIN || dpi > max) throw new Error(`DPI must be between ${DPI_MIN} and ${max}.`); - const rounded = Math.round(dpi / DPI_STEP) * DPI_STEP; - - const before = await this.readConfigPayload(); - const current = before ? mchoseDecodeConfig(before) : null; - if (!current) throw new Error("The mouse did not return its configuration."); - const stages = [...current.dpiStages]; - stages[stage] = rounded; - - const after = await this.updateConfig({ dpiStages: stages }); - if (after.dpiStages[stage] !== rounded) { + setDpiStageValue(stage: number, dpi: number): Promise { + return this.setStageDpi(stage, dpi); + } + + get setDpiStageAxes(): ((stage: number, x: number, y: number) => Promise) | undefined { + // Older consumers detect axis support by checking for a callable setter. + return this.isL7Ultra ? (stage, x, y) => this.setStageDpi(stage, x, y) : undefined; + } + + private async setStageDpi(stage: number | null, x: number, y?: number): Promise { + const after = await this.updateConfig((current) => { + if (y !== undefined && !this.isL7Ultra) throw new Error("Separate DPI axes are not verified for this model."); + stage ??= this.isWired() ? current.wiredDpiIndex : current.wirelessDpiIndex; + if (!Number.isInteger(stage) || stage < 0 || stage >= MCHOSE_DPI_STAGES) { + throw new RangeError(`DPI stage must be 0-${MCHOSE_DPI_STAGES - 1}.`); + } + if (this.isL7Ultra && stage >= current.stageCount) throw new RangeError("DPI stage is not enabled."); + const max = this.cachedProduct?.dpiMax ?? 26000; + for (const dpi of [x, y ?? x]) { + if (!Number.isFinite(dpi) || dpi < DPI_MIN || dpi > max) throw new RangeError(`DPI must be between ${DPI_MIN} and ${max}.`); + } + const dpiStages = [...current.dpiStages]; + dpiStages[stage] = Math.round(x / DPI_STEP) * DPI_STEP; + if (!this.isL7Ultra) return { dpiStages }; + const dpiStagesY = [...current.dpiStagesY!]; + dpiStagesY[stage] = Math.round((y ?? x) / DPI_STEP) * DPI_STEP; + return { dpiStages, dpiStagesY }; + }); + if (after.dpiStages[stage!] !== Math.round(x / DPI_STEP) * DPI_STEP) { throw new Error("The mouse did not accept the new DPI value."); } } @@ -418,7 +562,7 @@ export class MchoseHidClient { throw new Error(`Profile must be 1-${MCHOSE_PROFILE_COUNT}.`); } await this.open(); - const body = mchoseEncodeCommand(mchoseEncodeSetProfile(profile - 1), MCHOSE_SHORT_TOKENS); + const body = this.commandBody(mchoseEncodeSetProfile(profile - 1), MCHOSE_SHORT_TOKENS); const send = async (): Promise => { await this.device.sendFeatureReport(MCHOSE_SHORT_REPORT_ID, body); await delay(PROFILE_SETTLE_MS); @@ -446,7 +590,7 @@ export class MchoseHidClient { applied: (config: MchoseConfig) => boolean, ): Promise { await this.open(); - const body = mchoseEncodeCommand( + const body = this.commandBody( mchoseEncodePerformance(liftOffIndex, changes), MCHOSE_SHORT_TOKENS, ); @@ -561,7 +705,11 @@ export class MchoseHidClient { if (!Number.isInteger(count) || count < 1 || count > MCHOSE_DPI_STAGES) { throw new Error(`DPI stage count must be 1-${MCHOSE_DPI_STAGES}.`); } - const after = await this.updateConfig({ stageCount: count }); + const after = await this.updateConfig((current) => ({ + stageCount: count, + ...(this.isL7Ultra && current.wiredDpiIndex >= count ? { wiredDpiIndex: count - 1 } : {}), + ...(this.isL7Ultra && current.wirelessDpiIndex >= count ? { wirelessDpiIndex: count - 1 } : {}), + })); if (after.stageCount !== count) { throw new Error("The mouse did not accept the new DPI stage count."); } @@ -662,7 +810,7 @@ export class MchoseHidClient { async setSleepTimeout(seconds: number): Promise { const minutes = Math.round(Math.max(0, seconds) / 60); await this.open(); - const body = mchoseEncodeCommand(mchoseEncodeSleep(minutes), MCHOSE_SHORT_TOKENS); + const body = this.commandBody(mchoseEncodeSleep(minutes), MCHOSE_SHORT_TOKENS); const send = async (): Promise => { await this.device.sendFeatureReport(MCHOSE_SHORT_REPORT_ID, body); await delay(SLEEP_SETTLE_MS); @@ -689,13 +837,7 @@ export class MchoseHidClient { } /** Sets the DPI of whichever stage the live connection is using. */ - async setDpi(dpi: number): Promise { - const payload = await this.readConfigPayload(); - const current = payload ? mchoseDecodeConfig(payload) : null; - if (!current) throw new Error("The mouse did not return its configuration."); - await this.setDpiStageValue( - this.isWired() ? current.wiredDpiIndex : current.wirelessDpiIndex, - dpi, - ); + setDpi(dpi: number): Promise { + return this.setStageDpi(null, dpi); } } diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index 3319860f..6060456e 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -458,6 +458,9 @@ export interface MouseStatus { motionSync?: boolean | null; /** On-device DPI stages, where supported (Teevolution, Ninjutso, …). */ dpiStages?: number[]; + /** Full stored table when fewer stages are enabled; inactive values survive count changes. */ + dpiStoredStages?: number[]; + dpiStoredStagesY?: number[]; /** Per-stage Y DPI on devices that support independently stored axes. */ dpiStagesY?: number[]; /** RGB colour for each DPI stage, as lowercase #rrggbb. */ diff --git a/src/mchose/index.test.ts b/src/mchose/index.test.ts index d0373765..a82ab7d7 100644 --- a/src/mchose/index.test.ts +++ b/src/mchose/index.test.ts @@ -12,6 +12,7 @@ import { mchoseDecodeVersion, mchoseEncodeCommand, mchoseEncodeConfigWrite, + mchoseEncodeDpiWrite, mchoseFindProduct, mchoseDecodeProfileName, mchosePackLinkByte, @@ -60,6 +61,23 @@ test("long commands invert all 64 tokens", () => { assert.equal(body[63], 0xff); }); +test("long DPI command carries independent Y values and rejects inactive indices", () => { + const before = Uint8Array.from([...CONFIG, ...new Array(63 - CONFIG.length).fill(0)]); + const y = [2400, 800, 1600, 3200, 6400, 42000]; + assert.equal(mchoseDecodeConfig(before)?.dpiStagesY, undefined, "legacy payloads do not advertise Y DPI"); + assert.deepEqual(mchoseDecodeConfig(before, "l7-ultra")?.dpiStagesY, [0, 0, 0, 0, 0, 0]); + assert.equal(mchoseDecodeConfig(before.subarray(0, 62), "l7-ultra"), null); + const command = mchoseEncodeDpiWrite(before, { dpiStagesY: y }); + assert.equal(command[17], 0xff, "M HUB uses the same diff byte for both axis modes"); + assert.deepEqual(command.slice(18, 22), [0x60, 0x09, 0x20, 0x03]); + assert.throws(() => mchoseEncodeDpiWrite(before, { wiredDpiIndex: 1 }), /must be enabled/); + assert.throws(() => mchoseEncodeDpiWrite(before.subarray(0, 62)), /requires 63/); + const sparse = [...y]; + delete sparse[1]; + assert.throws(() => mchoseEncodeDpiWrite(before, { dpiStages: sparse }), /six uint16/); + assert.throws(() => mchoseEncodeDpiWrite(before, { dpiStagesY: sparse }), /six uint16/); +}); + test("a reply is un-inverted behind its report-id byte", () => { // [reportId, ~cmd, ~payload…] const raw = new Uint8Array([MCHOSE_LONG_REPORT_ID, 0x98, 0xff, 0xcf]); @@ -350,3 +368,11 @@ test("profile names decode as UTF-8 and translate the Chinese factory names", () assert.equal(mchoseDecodeProfileName(reply(0, [...new TextEncoder().encode("配置")])), "配置"); assert.equal(mchoseDecodeProfileName(reply(0, [])), null); }); + +test("legacy config writes still accept a short payload and a partial X table", () => { + const before = CONFIG.subarray(0, 20); + const tokens = mchoseEncodeConfigWrite(before, { dpiStages: [2400] }); + const expected = [MCHOSE_COMMAND.writeConfig, ...before]; + expected.splice(5, 2, 0x60, 0x09); + assert.deepEqual(tokens, expected); +}); diff --git a/src/mchose/index.ts b/src/mchose/index.ts index adb4899d..b0f7fbcb 100644 --- a/src/mchose/index.ts +++ b/src/mchose/index.ts @@ -24,10 +24,11 @@ export const MCHOSE_VENDOR_ID = 0x3837; * MCHOSE's older id, manufacturer string "RealTek", still used by L7 and some * A7 units with the same configuration channel. Other MCHOSE product lines sit * under it too, so it is only ever matched together with these PIDs: the 8K - * receiver and the A7 Ultra's cable link. + * receiver and the known A7 Ultra and L7 Ultra cable links. */ export const MCHOSE_REALTEK_VENDOR_ID = 0x5253; -export const MCHOSE_REALTEK_PRODUCT_IDS: readonly number[] = [0x1020, 0x1011]; +export const MCHOSE_L7_ULTRA_PRODUCT_ID = 0x00b1; +export const MCHOSE_REALTEK_PRODUCT_IDS: readonly number[] = [0x1020, 0x1011, MCHOSE_L7_ULTRA_PRODUCT_ID]; /** Vendor configuration collection. */ export const MCHOSE_CONFIG_USAGE_PAGE = 0xff01; @@ -53,6 +54,8 @@ export const MCHOSE_COMMAND = { config: 0x67, /** Writes the same blob back, one command byte in front of the same layout. */ writeConfig: 0x57, + /** Applies DPI indices, stage count and both axis tables. */ + writeDpi: 0x40, /** Switches the active onboard profile; takes a single 0-based index. */ setProfile: 0x58, /** Reassigns one button: `[buttonIndex, reserved, type, value u24 BE]`. */ @@ -348,14 +351,15 @@ export interface MchoseBattery { export function mchoseDecodeBattery(payload: Uint8Array): MchoseBattery | null { if (payload.length < 11) return null; - // Bit fields are packed most-significant first: 3 bits mode, 1 bit status. + // The L7 Ultra uses the low nibble; older receivers use the high nibble. const flags = payload[8] ?? 0; + const l7Ultra = u16(payload, 2) === MCHOSE_L7_ULTRA_PRODUCT_ID; return { vendorId: u16(payload, 0), productId: u16(payload, 2), firmwareVersion: u16(payload, 4) | (u16(payload, 6) << 16), - connectMode: (flags >> 5) & 0x07, - connected: ((flags >> 4) & 0x01) !== 0, + connectMode: l7Ultra ? flags & 0x07 : (flags >> 5) & 0x07, + connected: l7Ultra ? (flags & 0x08) !== 0 : (flags & 0x10) !== 0, batteryPercent: payload[9] ?? 0, charging: (payload[10] ?? 0) !== 0, }; @@ -375,6 +379,8 @@ export interface MchoseConfig { wiredRateIndex: number; /** Six DPI stages, little-endian uint16 each. */ dpiStages: number[]; + /** Six stored Y-axis DPI stages, including inactive stages. */ + dpiStagesY?: number[]; stageCount: number; sensor: number; /** Lift-off step, decoded out of the low bits of `sensor`. */ @@ -405,13 +411,16 @@ export interface MchoseConfig { * matches the vendor's write schema; its read schema has both the byte order * and the nibble order backwards. Do not "correct" this to match the latter. */ -export function mchoseDecodeConfig(payload: Uint8Array): MchoseConfig | null { +export function mchoseDecodeConfig(payload: Uint8Array, layout: "legacy" | "l7-ultra" = "legacy"): MchoseConfig | null { if (payload.length < 4 + MCHOSE_DPI_STAGES * 2) return null; + if (layout === "l7-ultra" && payload.length < 63) return null; const wired = payload[1] ?? 0; const wireless = payload[2] ?? 0; const dpiStages: number[] = []; + const dpiStagesY: number[] | undefined = layout === "l7-ultra" ? [] : undefined; for (let stage = 0; stage < MCHOSE_DPI_STAGES; stage += 1) { dpiStages.push(u16(payload, 4 + stage * 2)); + dpiStagesY?.push(u16(payload, 51 + stage * 2)); } return { profileIndex: payload[0] ?? 0, @@ -420,6 +429,7 @@ export function mchoseDecodeConfig(payload: Uint8Array): MchoseConfig | null { wiredDpiIndex: wired & 0x0f, wiredRateIndex: (wired >> 4) & 0x0f, dpiStages, + ...(dpiStagesY ? { dpiStagesY } : {}), stageCount: payload[16] ?? 0, sensor: payload[17] ?? 0, liftOffIndex: mchoseDecodeLiftOffIndex(payload[17] ?? 0), @@ -480,6 +490,44 @@ export function mchoseEncodeConfigWrite( return out; } +/** Fields sent by the L7 Ultra DPI command. */ +export interface MchoseDpiEdit { + wiredDpiIndex?: number; + wirelessDpiIndex?: number; + dpiStages?: readonly number[]; + dpiStagesY?: readonly number[]; + stageCount?: number; +} + +/** Build the L7 Ultra's `0x40` command, preserving unedited stages and link indices. */ +export function mchoseEncodeDpiWrite(readPayload: Uint8Array, changes: MchoseDpiEdit = {}): number[] { + const config = mchoseDecodeConfig(readPayload, "l7-ultra"); + if (!config?.dpiStagesY) throw new RangeError("MCHOSE extended DPI write requires 63 configuration bytes."); + const wired = changes.wiredDpiIndex ?? config.wiredDpiIndex; + const wireless = changes.wirelessDpiIndex ?? config.wirelessDpiIndex; + const count = changes.stageCount ?? config.stageCount; + if (!Number.isInteger(count) || count < 1 || count > MCHOSE_DPI_STAGES + || [wired, wireless].some((index) => !Number.isInteger(index) || index < 0 || index >= count)) { + throw new RangeError("MCHOSE active DPI stage must be enabled."); + } + const axes = [changes.dpiStages ?? config.dpiStages, changes.dpiStagesY ?? config.dpiStagesY]; + const [x, y] = axes.map((table) => { + if (table.length !== MCHOSE_DPI_STAGES) { + throw new RangeError("MCHOSE DPI tables must contain six uint16 values."); + } + const bytes: number[] = []; + for (let stage = 0; stage < MCHOSE_DPI_STAGES; stage += 1) { + const value = table[stage]; + if (value === undefined || !Number.isInteger(value) || value < 0 || value > 0xffff) { + throw new RangeError("MCHOSE DPI tables must contain six uint16 values."); + } + bytes.push(value & 0xff, value >> 8); + } + return bytes; + }); + return [MCHOSE_COMMAND.writeDpi, wired, wireless, readPayload[3]!, ...x!, count, 0xff, ...y!]; +} + // ── model catalog ────────────────────────────────────────────────────────── /** @@ -519,6 +567,7 @@ export const MCHOSE_PRODUCTS: readonly MchoseProduct[] = [ { name: "L7 Pro", productId: 0x00b0, dpiMax: 26000, liftOffDistances: [1, 2], maxPollingRate: 8000 }, // Firmware 5.32.5.0 reports 1 mm and 2 mm as lift-off indices 1 and 2. { name: "L7 Pro+", productId: 0x4015, dpiMax: 26000, liftOffDistances: [1, 2], liftOffIndexBase: 1, maxPollingRate: 8000 }, + { name: "L7 Ultra", productId: MCHOSE_L7_ULTRA_PRODUCT_ID, dpiMax: 42000, liftOffDistances: [0.7, 1, 2], maxPollingRate: 8000 }, ]; /** Rate lists the firmware exposes, keyed by the model's maximum rate. */