diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index 90e31cc7..f4fe5551 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -508,6 +508,16 @@ export interface MouseStatus { * Hypershift because that write was verified on it. */ razerButtonOptions?: string[]; + /** + * What this session has written to the Hypershift layer, keyed like + * `razerButtonMappings`. It is deliberately not a read: this firmware answers + * a class `0x02` read with whichever layer was written last, ignoring the + * layer argument, so a "read" of Hypershift returns the Standard value. Only + * a value written here is known. + */ + razerHypershiftMappings?: Record; + /** True when the driver accepts writes to the Hypershift layer. */ + razerHypershiftWritable?: boolean; /** Keychron Nape Pro user layer currently running on the device (1–8). * Matches firmware get/set. Undefined when the layer commands were not answered. */ diff --git a/src/drivers/razer/protocol.test.ts b/src/drivers/razer/protocol.test.ts index a624fef3..7d2b11da 100644 --- a/src/drivers/razer/protocol.test.ts +++ b/src/drivers/razer/protocol.test.ts @@ -49,6 +49,7 @@ import { RAZER_TOGGLE_CONTROLS, RAZER_TOGGLE_CONTROL_INFO, razerDecodeButtonMapping, + razerDecodeKeymapTable, razerDecodeKeyboardMapping, razerKeyLabel, razerDecodeToggleControl, @@ -975,3 +976,74 @@ test("key labels name what they can and hex what they cannot", () => { test("Left Click cannot take a keyboard key either", () => { assert.throws(() => razerSetKeyboardMappingCommand("leftClick", { mods: 0x00, usage: 0x68 }), RazerProtocolError); }); + +test("the keymap table decodes a captured Viper Mini reply", () => { + // Captured after every slot was set to a distinct action, then re-read after + // only `back` changed — one byte moved, which is what fixed the record shape. + const bytes = Uint8Array.from([ + 0x01,0x04,0x00, 0x01,0x01,0x00,0x00,0x00,0x00, + 0x02,0x01,0x02,0x02,0x00,0x00,0x00,0x00, + 0x03,0x01,0x03,0x03,0x00,0x00,0x00,0x00, + 0x04,0x01,0x04,0x04,0x00,0x00,0x00,0x00, + 0x05,0x01,0x05,0x05,0x00,0x00,0x00,0x00, + 0x60,0x0c,0x60,0x01,0x00,0x00,0x00,0x00, + 0x09,0x01,0x09,0x09,0x00,0x00,0x00,0x00, + 0x0a,0x01,0x0a,0x0a,0x00,0x00,0x00,0x00, + 0xa2, + ]); + + const table = razerDecodeKeymapTable(bytes, 0x01, 0x00, 9); + + assert.ok(table); + assert.equal(table.get(0x02), "Right Click"); + assert.equal(table.get(0x03), "Middle Click"); + assert.equal(table.get(0x04), "Mouse Button 4"); + assert.equal(table.get(0x05), "Mouse Button 5"); + assert.equal(table.get(0x60), "Hypershift"); +}); + +test("the keymap table carries keyboard keys and refuses records it cannot place", () => { + const keys = Uint8Array.from([ + 0x01,0x04,0x00, 0x01,0x01,0x00,0x00,0x00,0x00, + 0x02,0x02,0x02,0x00,0x68,0x00,0x00,0x00, + 0x03,0x02,0x03,0x00,0x69,0x00,0x00,0x00, + 0xc1, + ]); + const table = razerDecodeKeymapTable(keys, 0x01, 0x00, 9); + assert.equal(table?.get(0x02), "F13"); + assert.equal(table?.get(0x03), "F14"); + + // Controls that are not on this mouse mean this is not its keymap table. + const foreign = Uint8Array.from([ + 0x01,0x04,0x00, 0x01,0x01,0x00,0x00,0x00,0x00, + 0x77,0x01,0x77,0x02,0x00,0x00,0x00,0x00, + 0x78,0x01,0x78,0x02,0x00,0x00,0x00,0x00, + 0x79,0x01,0x79,0x02,0x00,0x00,0x00,0x00, + 0xc1, + ]); + assert.equal(razerDecodeKeymapTable(foreign, 0x01, 0x00, 9), null); +}); + +test("the keymap table decodes the reply the panel actually receives", () => { + // Captured from the panel's own request: the preamble is eleven bytes here + // versus nine for a probe with different arguments, and the third field of + // each record is a constant rather than the control. + const bytes = Uint8Array.from([ + 0x01,0x00,0x00, 0x01,0x01,0x01,0x01, 0x00,0x00,0x00,0x00, + 0x02,0x01,0x01,0x02,0x00,0x00,0x00,0x00, + 0x03,0x01,0x01,0x03,0x00,0x00,0x00,0x00, + 0x04,0x01,0x01,0x04,0x00,0x00,0x00,0x00, + 0x05,0x01,0x01,0x05,0x00,0x00,0x00,0x00, + 0x60,0x0c,0x01,0x01,0x00,0x00,0x00,0x00, + 0x09,0x01,0x01,0x09,0x00,0x00,0x00,0x00, + 0x0a,0x01,0x01,0x0a,0x00,0x00,0x00,0x00, + 0x00,0x00, + ]); + + const table = razerDecodeKeymapTable(bytes, 0x01, 0x00); + + assert.ok(table); + assert.equal(table.get(0x02), "Right Click"); + assert.equal(table.get(0x04), "Mouse Button 4"); + assert.equal(table.get(0x60), "Hypershift"); +}); diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index 692b236e..2c8265e5 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -114,20 +114,35 @@ function replyPacket(commandClass: number, commandId: number, dataSize: number, * that acknowledges a write and keeps the old action — the case read-back * confirmation exists to catch. */ -function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: number; staleWriteAcks?: number; wrongControlReplies?: number } = {}) { +function fakeViperMini(options: { + ignoreButtonWrites?: boolean; + staleReplies?: number; + staleWriteAcks?: number; + wrongControlReplies?: number; + droppedReads?: number; +} = {}) { const sent: Uint8Array[] = []; let pending = new Uint8Array(RAZER_PACKET_LENGTH); let staleLeft = options.staleReplies ?? 0; let staleAcks = options.staleWriteAcks ?? 0; let wrongControls = options.wrongControlReplies ?? 0; - const actions = new Map([ - [0x01, [0x01, 0x01, 0x01]], - [0x03, [0x01, 0x01, 0x03]], - [0x02, [0x01, 0x01, 0x02]], - [0x04, [0x01, 0x01, 0x04]], - [0x05, [0x01, 0x01, 0x05]], - // The real mouse's bottom button ships as F24, not as a mouse action. - [0x60, [0x02, 0x02, 0x00, 0x73]], + // A reply the mouse is still holding from an earlier exchange: it comes out + // of the buffer first, then the answer to the command just sent. + let stalePending: Uint8Array | null = null; + // Reads answered with "unsupported", the way a busy mouse drops a request. + let droppedReads = options.droppedReads ?? 0; + // Keyed by layer and control: the two layers store independent actions. + const actions = new Map([ + ["0:1", [0x01, 0x01, 0x01]], + ["0:3", [0x01, 0x01, 0x03]], + ["0:2", [0x01, 0x01, 0x02]], + ["0:4", [0x01, 0x01, 0x04]], + ["0:5", [0x01, 0x01, 0x05]], + // A factory bottom button steps the sensitivity, not a mouse action. + ["0:96", [0x06, 0x01, 0x06]], + // Hypershift layer starts empty on a factory mouse. + ["1:4", [0x00, 0x00, 0x00]], + ["1:5", [0x00, 0x00, 0x00]], ]); const device = { vendorId: 0x1532, @@ -165,17 +180,18 @@ function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: n return; } const control = data[9]; + const slot = `${data[10]}:${data[9]}`; const read = commandClass === 0x02 && commandId === 0x8c; const write = commandClass === 0x02 && commandId === 0x0c; if (read || write) { if (write && !options.ignoreButtonWrites) { // A mouse action is three bytes, a keyboard key is four (type, len, // mods, usage) — the reply echoes whichever the write carried. - actions.set(control, data[11] === 0x02 + actions.set(slot, data[11] === 0x02 ? [data[11], data[12], data[13], data[14]] : [data[11], data[12], data[13]]); } - const action = actions.get(control) ?? [0x00, 0x00, 0x00]; + const action = actions.get(slot) ?? [0x00, 0x00, 0x00]; // A write the mouse applied but acknowledged with an older reply, which // is what the reporter's log showed as "answered by a different // command" on a write that had in fact stored. @@ -184,17 +200,25 @@ function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: n pending = replyPacket(0x05, 0x81, 0x02, [0x01, 0x01], RAZER_STATUS.ok); return; } + if (read && droppedReads > 0) { + droppedReads -= 1; + pending = replyPacket(commandClass, commandId, data[5], [], RAZER_STATUS.unsupported); + return; + } if (read && wrongControls > 0) { wrongControls -= 1; - pending = replyPacket(commandClass, commandId, data[5], [data[8], 0x05, data[10], ...actions.get(0x05)!], RAZER_STATUS.ok); - return; + stalePending = replyPacket(commandClass, commandId, data[5], [data[8], 0x05, data[10], ...(actions.get(`${data[10]}:5`) ?? [0x00, 0x00, 0x00])], RAZER_STATUS.ok); } pending = replyPacket(commandClass, commandId, data[5], [data[8], control, data[10], ...action], RAZER_STATUS.ok); return; } pending = replyPacket(commandClass, commandId, data[5], [], RAZER_STATUS.unsupported); }, - receiveFeatureReport: async () => new DataView(pending.buffer.slice(0)), + receiveFeatureReport: async () => { + const out = stalePending ?? pending; + stalePending = null; + return new DataView(out.buffer.slice(0)); + }, } as unknown as HIDDevice; return { client: new RazerViperMiniHidClient(device), sent, actions }; } @@ -223,7 +247,7 @@ test("Viper Mini reports the four remappable controls in its status", async () = rightClick: "Right Click", mouse4: "Mouse Button 4", mouse5: "Mouse Button 5", - dpiButton: "F24", + dpiButton: "DPI Up Wrap", }); assert.ok(status.razerButtonOptions?.includes("Hypershift")); assert.ok(status.razerButtonOptions?.includes("Middle Click")); @@ -256,7 +280,7 @@ test("Viper Mini writes a mapping on 0x1f and confirms it by read-back", async ( assert.equal(await client.setButtonMapping("mouse4", "Right Click"), "Right Click"); assert.deepEqual([...sent.at(-2)!.slice(8, 18)], [0x01, 0x04, 0x00, 0x01, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00]); assert.equal(sent.at(-2)![1], 0x1f); - assert.deepEqual(actions.get(0x04), [0x01, 0x01, 0x02]); + assert.deepEqual(actions.get("0:4"), [0x01, 0x01, 0x02]); assert.equal((await client.readStatus()).razerButtonMappings?.mouse4, "Right Click"); }); @@ -304,7 +328,7 @@ test("Viper Mini reports a key already stored on the mouse instead of dropping t // as a mouse action returns null, so without the keyboard read the row would // vanish from the card. const { client, actions } = fakeViperMini(); - actions.set(0x05, [0x02, 0x02, 0x01, 0x68]); + actions.set("0:5", [0x02, 0x02, 0x01, 0x68]); const status = await client.readStatus(); @@ -330,7 +354,7 @@ const ALL_DEFAULT_MAPPINGS = { rightClick: "Right Click", mouse4: "Mouse Button 4", mouse5: "Mouse Button 5", - dpiButton: "F24", + dpiButton: "DPI Up Wrap", }; test("Viper Mini ignores a mapping reply that echoes another control", async () => { @@ -350,7 +374,7 @@ test("Viper Mini reads the mappings again after it is closed", async () => { const { client, actions } = fakeViperMini(); await client.readStatus(); - actions.set(0x04, [0x01, 0x01, 0x02]); + actions.set("0:4", [0x01, 0x01, 0x02]); await client.close(); assert.equal((await client.readStatus()).razerButtonMappings?.mouse4, "Right Click"); }); @@ -369,6 +393,91 @@ test("Viper Mini reads the mappings again when a write's read-back is refused", await client.readStatus(); await assert.rejects(() => client.setButtonMapping("mouse4", "Right Click")); - actions.set(0x04, [0x01, 0x01, 0x02]); + actions.set("0:4", [0x01, 0x01, 0x02]); assert.equal((await client.readStatus()).razerButtonMappings?.mouse4, "Right Click"); }); + +test("Viper Mini writes and reads the Hypershift layer separately", async () => { + // The layer byte is the third argument: 0 Standard, 1 Hypershift. A binding + // on Hypershift only does something if that layer holds its own action. + const { client, sent } = fakeViperMini(); + + assert.equal(await client.setButtonMapping("mouse4", "Middle Click", 1), "Middle Click"); + assert.deepEqual([...sent.at(-2)!.slice(8, 18)], [0x01, 0x04, 0x01, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00]); + assert.equal((await client.readStatus()).razerHypershiftMappings?.mouse4, "Middle Click"); +}); + +test("Viper Mini reports only what it wrote to the Hypershift layer", async () => { + // The class `0x02` read ignores the layer argument and answers with whichever + // layer was written last, so a read must never be presented as the Hypershift + // layer's contents. + const { client } = fakeViperMini(); + + const untouched = await client.readStatus(); + assert.equal(untouched.razerHypershiftMappings, undefined); + assert.equal(untouched.razerHypershiftWritable, true); + + await client.setButtonMapping("mouse4", "Middle Click", 1); + const written = await client.readStatus(); + assert.equal(written.razerHypershiftMappings?.mouse4, "Middle Click"); + assert.equal(written.razerHypershiftMappings?.mouse5, undefined); + assert.equal(written.razerButtonMappings?.mouse4, "Mouse Button 4"); +}); + +test("Viper Mini keeps the Standard cache through a Hypershift write", async () => { + const { client, sent } = fakeViperMini(); + + await client.readStatus(); + await client.setButtonMapping("mouse4", "Middle Click", 1); + const before = sent.length; + const status = await client.readStatus(); + + const keymapReads = sent.slice(before).filter((packet) => packet[6] === 0x02); + assert.equal(keymapReads.length, 0); + assert.equal(status.razerButtonMappings?.mouse4, "Mouse Button 4"); + assert.equal(status.razerHypershiftMappings?.mouse4, "Middle Click"); +}); + +test("Viper Mini re-probes the controls a read missed", async () => { + // The card showed two rows on hardware because three reads were dropped and + // the short map was cached. An incomplete probe must not be cached. + const { client } = fakeViperMini({ droppedReads: 3 }); + + const first = await client.readStatus(); + assert.ok(Object.keys(first.razerButtonMappings ?? {}).length < 6); + + const second = await client.readStatus(); + assert.deepEqual(second.razerButtonMappings, ALL_DEFAULT_MAPPINGS); +}); + +test("Viper Mini reports every control when status is read twice at once", async () => { + // Two status reads used to interleave their probes and answer each other's + // reads, leaving one layer with the first few controls and the other with the + // rest. Only one probe may run at a time. + const { client } = fakeViperMini(); + + const [first, second] = await Promise.all([client.readStatus(), client.readStatus()]); + + assert.deepEqual(first.razerButtonMappings, ALL_DEFAULT_MAPPINGS); + assert.deepEqual(second.razerButtonMappings, ALL_DEFAULT_MAPPINGS); +}); + +test("Viper Mini names the bottom button's factory DPI action", async () => { + // A mouse nobody has remapped reads its bottom button as a DPI step, which is + // a type the mouse-action decoder reports as unknown. Without this the row + // would vanish on exactly the mice that have never been touched. + const { client } = fakeViperMini(); + + const status = await client.readStatus(); + + assert.equal(status.razerButtonMappings?.dpiButton, "DPI Up Wrap"); +}); + +test("Viper Mini still reports a keyboard key left on the bottom button", async () => { + const { client, actions } = fakeViperMini(); + actions.set("0:96", [0x02, 0x02, 0x00, 0x73]); + + const status = await client.readStatus(); + + assert.equal(status.razerButtonMappings?.dpiButton, "F24"); +}); diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index 0b471be3..9ce36a9a 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -3,10 +3,13 @@ import { VENDOR_ID } from "../vendors.ts"; import { openRazerDevice } from "./hid-open.ts"; import { RAZER_BUTTON_CONTROL_LABEL, + RAZER_HYPERSHIFT_LAYER, + RAZER_STANDARD_LAYER, VIPER_MINI_BUTTON_CONTROLS, VIPER_MINI_BUTTON_MAPPINGS, RAZER_READ, RAZER_REPORT_ID, + RAZER_STORAGE, RAZER_STATUS, RAZER_TRANSACTION_ID_1F, RAZER_TRANSACTION_ID_3F, @@ -19,9 +22,13 @@ import { encodeRazerRequest, isRazerGetter, razerDecodeButtonMapping, + razerDecodeDpiAction, razerDecodeKeyboardMapping, razerKeyLabel, + razerButtonControlIndex, + razerDecodeKeymapTable, razerReadButtonMappingCommand, + razerReadKeymapTableCommand, razerSetButtonMappingCommand, razerSetKeyboardMappingCommand, razerSetDpiCommand, @@ -74,6 +81,19 @@ const RESPONSE_ATTEMPTS = 6; // A stale reply has to be read out of the buffer before the right one arrives, // so each exchange gets this many sends before it gives up. const SEND_ATTEMPTS = 3; +// Let the mouse finish one class `0x02` read before asking the next. +const PROBE_GAP_MS = 20; +// Keymap reads are polled on the shared cadence: the mouse needs the same +// settle between feature reports here as everywhere else, and asking faster +// gets its previous answer back instead of the new one. +const KEYMAP_POLL_MS = RESPONSE_DELAY_MS; +const KEYMAP_ATTEMPTS = RESPONSE_ATTEMPTS; +// Controls left unresolved by a probe are retried a couple at a time on later +// status reads, so a stubborn one cannot stall every refresh. +const PROBE_RETRY_LIMIT = 2; +// A write lands in flash before the next read reflects it; reading instantly +// answers with the old action and reads as a refused change. +const KEYMAP_SETTLE_MS = 60; const VIPER_MINI_LIGHTING_ZONE = "Logo"; @@ -155,6 +175,14 @@ export class RazerViperMiniHidClient { */ private buttonMappings: Record | null = null; private buttonMappingsKnown = false; + private hypershiftMappings: Record | null = null; + /** + * One probe at a time. The panel can ask for status while a previous read is + * still in flight, and two interleaved probes answer each other's reads — + * which is how one layer ends up holding the first few controls and the other + * the rest. + */ + private probing: Promise | null = null; readonly device: HIDDevice; @@ -181,6 +209,7 @@ export class RazerViperMiniHidClient { this.staticReads.clear(); this.buttonMappings = null; this.buttonMappingsKnown = false; + this.hypershiftMappings = null; if (this.device.opened) await this.device.close(); } @@ -215,6 +244,7 @@ export class RazerViperMiniHidClient { const dpi = decodeDpi(await this.request(VIPER_MINI_DPI_READ)); const pollingRateHz = decodeLegacyPollingRate(await this.request(RAZER_READ.pollingRate)); const buttonMappings = await this.currentButtonMappings(); + const hypershiftMappings = this.hypershiftMappings; return { brand: "Razer", name: this.displayName(), @@ -242,6 +272,8 @@ export class RazerViperMiniHidClient { connectionDetail: "Wired USB", unitId: serial ? decodeSerial(serial) : null, razerButtonMappings: buttonMappings ?? undefined, + razerHypershiftMappings: hypershiftMappings ?? undefined, + razerHypershiftWritable: true, // Hypershift is included here and only here — see VIPER_MINI_BUTTON_MAPPINGS. razerButtonOptions: [...VIPER_MINI_BUTTON_MAPPINGS], liftOffDistance: null, @@ -287,68 +319,199 @@ export class RazerViperMiniHidClient { * (`02 02 00 73`, F24) rather than the sensitivity toggle the V3 Pro uses, so * it behaves like any other cross-assignable control here. */ - async readButtonMappings(): Promise | null> { - return (await this.probeButtonMappings()).mappings; + async readButtonMappings(layer: number = RAZER_STANDARD_LAYER): Promise | null> { + return (await this.probeButtonMappings(layer)).mappings; + } + + /** + * The whole keymap for one layer in a single reply, or null when the model + * does not answer `0x8e` or answers a shape this driver does not recognise. + */ + private async readKeymapTable(layer: number): Promise | null> { + const reply = await this.request( + razerReadKeymapTableCommand(RAZER_STORAGE, layer), + VIPER_MINI_KEYMAP_TRANSACTION_ID, + false, + // The reply echoes profile, an unused byte and the layer. + (packet) => packet[8] === RAZER_STORAGE && packet[10] === layer, + ).catch(() => null); + return reply ? razerDecodeKeymapTable(reply, RAZER_STORAGE, layer) : null; } - private async probeButtonMappings(): Promise<{ mappings: Record | null; complete: boolean }> { + /** + * Reads every control one at a time, with a short gap between them. + * + * Firing them together lost rows on hardware: the mouse needs a moment + * between feature reports, and the reads that lost that race came back as + * another control's reply. `complete` stays false when any control did not + * resolve, which makes the next status read probe again instead of caching a + * map that is missing buttons. + */ + private async probeButtonMappings(layer: number): Promise<{ mappings: Record | null; complete: boolean }> { + // One read of the whole table when the firmware offers it; twelve one at a + // time only as a fallback, since that is what makes the card slow to fill. + const table = await this.readKeymapTable(layer); + if (table) { + const mappings: Record = {}; + let complete = true; + for (const control of VIPER_MINI_BUTTON_CONTROLS) { + const label = table.get(razerButtonControlIndex(control)); + if (label) mappings[control] = label; + else complete = false; + } + if (complete || Object.keys(mappings).length > 0) return { mappings, complete }; + } const mappings: Record = {}; let complete = true; - await Promise.all( - VIPER_MINI_BUTTON_CONTROLS.map(async (control) => { - const reply = await this.request(razerReadButtonMappingCommand(control), VIPER_MINI_KEYMAP_TRANSACTION_ID).catch((error: unknown) => { - if (!(error instanceof RazerProtocolError && error.status === RAZER_STATUS.unsupported)) complete = false; - return null; - }); - if (!reply) return; - const mapping = razerDecodeButtonMapping(reply); - if (mapping) { - mappings[control] = mapping; - return; - } + for (const control of VIPER_MINI_BUTTON_CONTROLS) { + const reply = await this.readControlMapping(control, layer); + const mapping = reply ? razerDecodeButtonMapping(reply) : null; + if (mapping) { + mappings[control] = mapping; + } else { // A key assignment encodes as type 0x02, which the mouse-action // decoder reports as unknown. Reading it here keeps the row in the // panel instead of silently dropping the control from the card. - const key = razerDecodeKeyboardMapping(reply); - if (key) mappings[control] = razerKeyLabel(key); - }), - ); + const key = reply ? razerDecodeKeyboardMapping(reply) : null; + if (key) { + mappings[control] = razerKeyLabel(key); + } else { + // The bottom button's factory job is a DPI step, not a key — that is + // why it reads as an unfamiliar type on a mouse nobody has remapped. + const dpi = reply ? razerDecodeDpiAction(reply) : null; + if (dpi) mappings[control] = dpi; + else complete = false; + } + } + await this.delay(PROBE_GAP_MS); + } return { mappings: Object.keys(mappings).length > 0 ? mappings : null, complete }; } - /** Probes once, then trusts what `setButtonMapping` leaves behind. */ + /** Runs a probe, or waits for the one already running instead of starting a + * second that would answer its own reads. */ + private async probeOnce(probe: () => Promise): Promise { + if (!this.probing) { + this.probing = probe().finally(() => { + this.probing = null; + }); + } + await this.probing; + } + + /** + * One control's reply, retried once. + * + * A reply is only accepted when it echoes the control that was asked for: the + * class answers whatever it is still holding, so a stale packet decodes as + * some other button's action and would otherwise be filed under the wrong row. + */ + private async readControlMapping(control: RazerButtonControl, layer: number): Promise { + const command = razerReadButtonMappingCommand(control, layer); + const expected = command.args?.[1]; + // The reply's second argument echoes the control that was asked for. Reads + // are not re-sent while the mouse is still emptying its buffer — one send, + // and every reply before ours is discarded. + const accept = expected === undefined ? undefined : (packet: Uint8Array) => packet[9] === expected; + const fast = await this.request( + command, + VIPER_MINI_KEYMAP_TRANSACTION_ID, + false, + accept, + { delay: KEYMAP_POLL_MS, attempts: KEYMAP_ATTEMPTS }, + ).catch(() => null); + if (fast) return fast; + // Second chance on the slower budget: right after a write the mouse can be + // slower than the fast window, and giving up there reads as a timeout. + return await this.request(command, VIPER_MINI_KEYMAP_TRANSACTION_ID, false, accept).catch(() => null); + } + + /** + * Probes once, then trusts what `setButtonMapping` leaves behind. + * + * A short map is read again before it is cached: a control whose action is + * genuinely unknown decodes to nothing, but so does one whose read failed, and + * caching the second case would hide a row for the rest of the session. + */ private async currentButtonMappings(): Promise | null> { if (!this.buttonMappingsKnown) { - const { mappings, complete } = await this.probeButtonMappings(); - this.buttonMappings = mappings; - this.buttonMappingsKnown = complete; + await this.probeOnce(async () => { + const { mappings, complete } = await this.probeButtonMappings(RAZER_STANDARD_LAYER); + this.buttonMappings = mappings ?? this.buttonMappings; + this.buttonMappingsKnown = complete || Object.keys(mappings ?? {}).length >= VIPER_MINI_BUTTON_CONTROLS.length; + }); + return this.buttonMappings; + } + // Nothing missing: nothing to do. + const missing = VIPER_MINI_BUTTON_CONTROLS.filter((control) => this.buttonMappings?.[control] === undefined); + if (missing.length === 0) return this.buttonMappings; + // Fill in a couple of the gaps per refresh. Reading the whole map again on + // every status poll is what made the panel crawl while one control stubbornly + // failed to answer. + for (const control of missing.slice(0, PROBE_RETRY_LIMIT)) { + const reply = await this.readControlMapping(control, RAZER_STANDARD_LAYER); + if (!reply) continue; + const mapping = razerDecodeButtonMapping(reply); + const key = mapping ? null : razerDecodeKeyboardMapping(reply); + if (mapping) this.buttonMappings = { ...this.buttonMappings, [control]: mapping }; + else if (key) this.buttonMappings = { ...this.buttonMappings, [control]: razerKeyLabel(key) }; } return this.buttonMappings; } + /** + * What this session has written to the Hypershift layer — never a read. + * + * The class `0x02` read ignores the layer argument and answers with whichever + * layer was written last, so a read of Hypershift returns the Standard value + * and would misrepresent the layer as untouched. Only writes are known, and + * the behaviour itself (holding the modifier) is the proof. + */ + async readHypershiftMappings(): Promise | null> { + return this.hypershiftMappings; + } + + private forgetBeforeWrite(control: RazerButtonControl, layer: number): boolean { + const known = this.buttonMappingsKnown; + if (layer === RAZER_STANDARD_LAYER) { + this.buttonMappingsKnown = false; + } else if (this.hypershiftMappings) { + const { [control]: _dropped, ...rest } = this.hypershiftMappings; + this.hypershiftMappings = Object.keys(rest).length > 0 ? rest : null; + } + return known; + } + /** * Sets one control's mapping and confirms it by reading the same control back. * The confirmation is the point: on this firmware a write is stored whatever * it contains, so a status-only check would happily ship a mapping the buttons * do not follow. */ - async setButtonMapping(control: RazerButtonControl, mapping: RazerButtonMapping): Promise { + async setButtonMapping( + control: RazerButtonControl, + mapping: RazerButtonMapping, + layer: number = RAZER_STANDARD_LAYER, + ): Promise { // The command object carries the V3 Pro's transaction id, but this client // passes its own to every exchange and that one wins on the wire. - const known = this.buttonMappingsKnown; - this.buttonMappingsKnown = false; - await this.request(razerSetButtonMappingCommand(control, mapping), VIPER_MINI_KEYMAP_TRANSACTION_ID); - const reply = await this.request(razerReadButtonMappingCommand(control), VIPER_MINI_KEYMAP_TRANSACTION_ID); - const confirmed = razerDecodeButtonMapping(reply); + const known = this.forgetBeforeWrite(control, layer); + await this.request(razerSetButtonMappingCommand(control, mapping, layer), VIPER_MINI_KEYMAP_TRANSACTION_ID); + await this.delay(KEYMAP_SETTLE_MS); + const reply = await this.readControlMapping(control, layer); + const confirmed = reply ? razerDecodeButtonMapping(reply) : null; if (confirmed !== mapping) { throw new Error( `The mouse kept ${confirmed ?? "an unrecognised mapping"} for ${RAZER_BUTTON_CONTROL_LABEL[control]} instead of ${mapping}.`, ); } - if (known) { + if (known && layer === RAZER_STANDARD_LAYER) { this.buttonMappings = { ...this.buttonMappings, [control]: confirmed }; this.buttonMappingsKnown = true; } + if (layer === RAZER_HYPERSHIFT_LAYER) { + this.hypershiftMappings = { ...this.hypershiftMappings, [control]: confirmed }; + } return confirmed; } @@ -359,22 +522,29 @@ export class RazerViperMiniHidClient { * * Returns the label the panel shows for the assignment (`Ctrl+F13`). */ - async setKeyboardMapping(control: RazerButtonControl, key: RazerKeyAction): Promise { - const known = this.buttonMappingsKnown; - this.buttonMappingsKnown = false; - await this.request(razerSetKeyboardMappingCommand(control, key), VIPER_MINI_KEYMAP_TRANSACTION_ID); - const reply = await this.request(razerReadButtonMappingCommand(control), VIPER_MINI_KEYMAP_TRANSACTION_ID); - const confirmed = razerDecodeKeyboardMapping(reply); + async setKeyboardMapping( + control: RazerButtonControl, + key: RazerKeyAction, + layer: number = RAZER_STANDARD_LAYER, + ): Promise { + const known = this.forgetBeforeWrite(control, layer); + await this.request(razerSetKeyboardMappingCommand(control, key, layer), VIPER_MINI_KEYMAP_TRANSACTION_ID); + await this.delay(KEYMAP_SETTLE_MS); + const reply = await this.readControlMapping(control, layer); + const confirmed = reply ? razerDecodeKeyboardMapping(reply) : null; const label = razerKeyLabel(key); if (!confirmed || confirmed.mods !== key.mods || confirmed.usage !== key.usage) { throw new Error( `The mouse kept ${confirmed ? razerKeyLabel(confirmed) : "a mouse action"} for ${RAZER_BUTTON_CONTROL_LABEL[control]} instead of ${label}.`, ); } - if (known) { + if (known && layer === RAZER_STANDARD_LAYER) { this.buttonMappings = { ...this.buttonMappings, [control]: label }; this.buttonMappingsKnown = true; } + if (layer === RAZER_HYPERSHIFT_LAYER) { + this.hypershiftMappings = { ...this.hypershiftMappings, [control]: label }; + } return label; } @@ -432,10 +602,13 @@ export class RazerViperMiniHidClient { command: RazerCommand, transactionId: number = VIPER_MINI_TRANSACTION_ID, requireAck = false, + /** Rejects a reply that answers this command but not the thing asked for. */ + accept?: (packet: Uint8Array) => boolean, + timing: { delay: number; attempts: number } = { delay: RESPONSE_DELAY_MS, attempts: RESPONSE_ATTEMPTS }, ): Promise { const run = this.queue.then( - () => this.exchange(command, transactionId, requireAck), - () => this.exchange(command, transactionId, requireAck), + () => this.exchange(command, transactionId, requireAck, accept, timing), + () => this.exchange(command, transactionId, requireAck, accept, timing), ); this.queue = run.catch(() => undefined); return await run; @@ -452,7 +625,13 @@ export class RazerViperMiniHidClient { * "Class 0x00 command 0x05 was answered by a different command" and failing a * write that had in fact landed. */ - private async exchange(command: RazerCommand, transactionId: number, requireAck: boolean): Promise { + private async exchange( + command: RazerCommand, + transactionId: number, + requireAck: boolean, + accept?: (packet: Uint8Array) => boolean, + timing: { delay: number; attempts: number } = { delay: RESPONSE_DELAY_MS, attempts: RESPONSE_ATTEMPTS }, + ): Promise { await this.open(); const request = encodeRazerRequest(command, transactionId); const getter = isRazerGetter(command); @@ -461,7 +640,7 @@ export class RazerViperMiniHidClient { const sends = getter ? SEND_ATTEMPTS : 1; for (let attempt = 0; attempt < sends; attempt += 1) { await this.device.sendFeatureReport(RAZER_REPORT_ID, request); - const reply = await this.awaitReply(command); + const reply = await this.awaitReply(command, accept, timing); if (reply) return reply; // A lost acknowledgement is not a failed write: every setter on this // client confirms through a read of its own afterwards, so the ack is @@ -481,12 +660,22 @@ export class RazerViperMiniHidClient { * was corrupt, belonged to an earlier exchange, or the budget ran out on busy * statuses — all cases where the caller should send again rather than fail. */ - private async awaitReply(command: RazerCommand): Promise { - for (let attempt = 0; attempt < RESPONSE_ATTEMPTS; attempt += 1) { - await this.delay(RESPONSE_DELAY_MS); + private async awaitReply( + command: RazerCommand, + accept?: (packet: Uint8Array) => boolean, + timing: { delay: number; attempts: number } = { delay: RESPONSE_DELAY_MS, attempts: RESPONSE_ATTEMPTS }, + ): Promise { + for (let attempt = 0; attempt < timing.attempts; attempt += 1) { + await this.delay(timing.delay); const reply = this.copyDataView(await this.device.receiveFeatureReport(RAZER_REPORT_ID)); try { const args = decodeRazerResponse(reply, command); + // The class answers for every control, so a reply addressed to this + // command can still be the previous control's answer. Polling again + // only returns that same packet, so hand back null and let the caller + // send again — the re-send is what makes the mouse flush its queue and + // answer the command we actually asked. + if (accept && !accept(reply)) return null; if (this.isMappingRead(command) && command.args?.some((byte, i) => args[i] !== byte)) return null; return args; } catch (error) { diff --git a/src/razer/codec.ts b/src/razer/codec.ts index bd2869eb..af893083 100644 --- a/src/razer/codec.ts +++ b/src/razer/codec.ts @@ -886,6 +886,10 @@ export function decodeExtendedPollingRate(args: Uint8Array): number { */ export type RazerButtonControl = "leftClick" | "scrollClick" | "rightClick" | "mouse4" | "mouse5" | "dpiButton"; +/** Layer argument of the class `0x02` commands: 0 is Standard, 1 is Hypershift. */ +export const RAZER_STANDARD_LAYER = 0x00; +export const RAZER_HYPERSHIFT_LAYER = 0x01; + export const RAZER_BUTTON_CONTROLS: readonly RazerButtonControl[] = ["leftClick", "rightClick", "mouse4", "mouse5"]; /** @@ -907,6 +911,11 @@ export const VIPER_MINI_BUTTON_CONTROLS: readonly RazerButtonControl[] = [ "dpiButton", ]; +/** The index a control occupies in the class `0x02` commands and the table. */ +export function razerButtonControlIndex(control: RazerButtonControl): number { + return RAZER_BUTTON_CONTROL_INDEX[control]; +} + const RAZER_BUTTON_CONTROL_INDEX: Record = { leftClick: 0x01, scrollClick: 0x03, @@ -1003,9 +1012,74 @@ export function razerDecodeButtonMapping(args: Uint8Array): RazerButtonMapping | return entry ? entry[1] : null; } +/** + * Class `0x02`/`0x8e` answers with one profile's whole keymap in a single reply: + * the three request arguments, six header bytes, one 8-byte record per control, + * and a trailer. Records are `[control, type, control, a, b, 0, 0, 0]` — the + * third byte repeats the control, which is what tells a reader this is the + * layout it thinks it is. + * + * Captured on a Viper Mini with every slot set to a distinct, known action, then + * re-read after a single slot changed; only that record's `a` byte moved. Types: + * `0x00` disabled, `0x01` mouse button (value in `a`), `0x02` keyboard key (mod + * in `a`, usage in `b`), `0x0c` Hypershift (value in `a`, length implied). + * + * Null when the reply does not match that shape, so a caller can fall back to + * reading each control on its own rather than misreading a table. + */ +export function razerReadKeymapTableCommand( + profile: number = RAZER_STORAGE, + layer: number = RAZER_STANDARD_LAYER, +): RazerCommand { + return { commandClass: 0x02, commandId: 0x8e, dataSize: 0x50, args: [profile, 0x00, layer] }; +} + +const KEYMAP_CONTROL_IDS: ReadonlySet = new Set([0x01, 0x02, 0x03, 0x04, 0x05, 0x60, 0x09, 0x0a]); + +/** + * How far into the reply the records start, for the arguments this driver sends + * (`[profile, 0x00, layer]`). The preamble carries the echoed arguments plus + * padding the firmware sizes from those arguments, so it is not the same offset + * a different request gets — hence a parameter rather than a constant. + */ +export const RAZER_KEYMAP_TABLE_START = 11; + +export function razerDecodeKeymapTable( + args: Uint8Array, + profile: number = RAZER_STORAGE, + layer: number = RAZER_STANDARD_LAYER, + tableStart: number = RAZER_KEYMAP_TABLE_START, +): Map | null { + const RECORD_LENGTH = 8; + if (args.length < tableStart + RECORD_LENGTH) return null; + const table = new Map(); + let seen = 0; + for (let at = tableStart; at + RECORD_LENGTH <= args.length - 1; at += RECORD_LENGTH) { + const control = args[at]!; + const type = args[at + 1]!; + if (control === 0x00 && type === 0x00) break; // padding + if (!KEYMAP_CONTROL_IDS.has(control)) return null; + if (type !== 0x00 && type !== 0x01 && type !== 0x02 && type !== 0x06 && type !== 0x0c) return null; + const action = new Uint8Array(8); + action[0] = profile; + action[1] = control; + action[2] = layer; + action[3] = type; + action[4] = type === 0x02 ? 0x02 : 0x01; + action[5] = args[at + 3]!; + action[6] = args[at + 4]!; + const mapping = razerDecodeButtonMapping(action); + const key = mapping ? null : razerDecodeKeyboardMapping(action); + const label = mapping ?? (key ? razerKeyLabel(key) : razerDecodeDpiAction(action)); + if (label && !table.has(control)) table.set(control, label); + seen += 1; + } + return seen >= 2 && table.size > 0 ? table : null; +} + /** Only the Standard layer is trusted for reads — see `RAZER_READ.buttonMapping`. */ -export function razerReadButtonMappingCommand(control: RazerButtonControl): RazerCommand { - return { ...RAZER_READ.buttonMapping, args: [0x01, RAZER_BUTTON_CONTROL_INDEX[control], 0x00] }; +export function razerReadButtonMappingCommand(control: RazerButtonControl, layer: number = RAZER_STANDARD_LAYER): RazerCommand { + return { ...RAZER_READ.buttonMapping, args: [0x01, RAZER_BUTTON_CONTROL_INDEX[control], layer] }; } /** @@ -1017,7 +1091,11 @@ export function razerReadButtonMappingCommand(control: RazerButtonControl): Raze */ export const RAZER_LOCKED_BUTTON_CONTROL: RazerButtonControl = "leftClick"; -export function razerSetButtonMappingCommand(control: RazerButtonControl, mapping: RazerButtonMapping): RazerCommand { +export function razerSetButtonMappingCommand( + control: RazerButtonControl, + mapping: RazerButtonMapping, + layer: number = RAZER_STANDARD_LAYER, +): RazerCommand { if (control === RAZER_LOCKED_BUTTON_CONTROL && mapping !== RAZER_BUTTON_CONTROL_LABEL[RAZER_LOCKED_BUTTON_CONTROL]) { throw new RazerProtocolError( `${RAZER_BUTTON_CONTROL_LABEL[RAZER_LOCKED_BUTTON_CONTROL]} is fixed on the Standard layer and cannot be reassigned or disabled.`, @@ -1026,7 +1104,7 @@ export function razerSetButtonMappingCommand(control: RazerButtonControl, mappin const [type, len, value] = razerEncodeButtonMapping(mapping); return { ...RAZER_WRITE.buttonMapping, - args: [0x01, RAZER_BUTTON_CONTROL_INDEX[control], 0x00, type, len, value, 0x00, 0x00, 0x00, 0x00], + args: [0x01, RAZER_BUTTON_CONTROL_INDEX[control], layer, type, len, value, 0x00, 0x00, 0x00, 0x00], }; } @@ -1119,7 +1197,11 @@ export function razerKeyLabel(key: RazerKeyAction): string { return parts.join("+"); } -export function razerSetKeyboardMappingCommand(control: RazerButtonControl, key: RazerKeyAction): RazerCommand { +export function razerSetKeyboardMappingCommand( + control: RazerButtonControl, + key: RazerKeyAction, + layer: number = RAZER_STANDARD_LAYER, +): RazerCommand { if (control === RAZER_LOCKED_BUTTON_CONTROL) { throw new RazerProtocolError( `${RAZER_BUTTON_CONTROL_LABEL[RAZER_LOCKED_BUTTON_CONTROL]} is fixed on the Standard layer and cannot be reassigned or disabled.`, @@ -1127,10 +1209,30 @@ export function razerSetKeyboardMappingCommand(control: RazerButtonControl, key: } return { ...RAZER_WRITE.buttonMapping, - args: [0x01, RAZER_BUTTON_CONTROL_INDEX[control], 0x00, 0x02, 0x02, key.mods, key.usage, 0x00, 0x00, 0x00], + args: [0x01, RAZER_BUTTON_CONTROL_INDEX[control], layer, 0x02, 0x02, key.mods, key.usage, 0x00, 0x00, 0x00], }; } +/** + * DPI actions, type `0x06`: the bottom button's factory job on most of these + * mice is to step or cycle the sensitivity, not to send a key. Sub-operation + * ids are the ones the class `0x04` commands use (`01` up, `02` down, `06` + * cycle up with wraparound, `07` cycle down). + */ +const RAZER_DPI_ACTION_LABELS: Readonly> = { + 0x01: "DPI Up", + 0x02: "DPI Down", + // `06` is the wraparound step — the Viper Mini's factory job for its bottom + // button — and `07` its downward twin. + 0x06: "DPI Up Wrap", + 0x07: "DPI Down Wrap", +}; + +export function razerDecodeDpiAction(args: Uint8Array): string | null { + if (args[3] !== 0x06) return null; + return RAZER_DPI_ACTION_LABELS[args[5] ?? -1] ?? null; +} + /** * The keyboard action in a button-mapping reply, or null when the reply is not * a keyboard action. `razerDecodeButtonMapping` deliberately returns null for