From 8f7fc57d0914a5d22199f726eddd7530b3962f15 Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 09:02:03 -0700 Subject: [PATCH 01/21] feat(razer): button remapping on the Viper Mini via class 0x02 under 0x1f --- src/drivers/razer/viper-mini-hid.test.ts | 142 ++++++++++++++++++++++- src/drivers/razer/viper-mini-hid.ts | 86 ++++++++++++++ 2 files changed, 227 insertions(+), 1 deletion(-) diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index 91db0a64..5a37056c 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -1,9 +1,24 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { RAZER_READ, encodeRazerRequest, razerSetDpiCommand, razerSetExtendedEffectCommand, razerSetLegacyPollingCommand } from "@openmouse/protocol/razer"; +// The client schedules its inter-exchange delay through `window`, which node +// does not provide. The global carries the same `setTimeout`. +Object.assign(globalThis, { window: globalThis }); + +import { + RAZER_PACKET_LENGTH, + RAZER_STATUS, + RAZER_READ, + encodeRazerRequest, + razerChecksum, + razerReadButtonMappingCommand, + razerSetDpiCommand, + razerSetExtendedEffectCommand, + razerSetLegacyPollingCommand, +} from "@openmouse/protocol/razer"; import { VIPER_MINI_DPI_READ, + VIPER_MINI_KEYMAP_TRANSACTION_ID, VIPER_MINI_PRODUCT_ID, VIPER_MINI_TRANSACTION_ID, RazerViperMiniHidClient, @@ -79,3 +94,128 @@ test("Viper Mini accepts only its own PID on a single Generic Desktop Mouse coll assert.equal(RazerViperMiniHidClient.isSupported(wrongPid), false); assert.equal(RazerViperMiniHidClient.isSupported(extraCollection), false); }); + +function replyPacket(commandClass: number, commandId: number, dataSize: number, args: number[], status: number): Uint8Array { + const packet = new Uint8Array(RAZER_PACKET_LENGTH); + packet[0] = status; + packet[1] = VIPER_MINI_TRANSACTION_ID; + packet[5] = dataSize; + packet[6] = commandClass; + packet[7] = commandId; + packet.set(args, 8); + packet[88] = razerChecksum(packet); + return packet; +} + +/** + * A mouse that answers what `readStatus` asks for, plus class `0x02`: each + * control's stored action is read back and a write replaces it, the way the real + * firmware stores whatever the write carried. `ignoreButtonWrites` models a unit + * that acknowledges a write and keeps the old action — the case read-back + * confirmation exists to catch. + */ +function fakeViperMini(options: { ignoreButtonWrites?: boolean } = {}) { + const sent: Uint8Array[] = []; + let pending = new Uint8Array(RAZER_PACKET_LENGTH); + const actions = new Map([ + [0x01, [0x01, 0x01, 0x01]], + [0x02, [0x01, 0x01, 0x02]], + [0x04, [0x01, 0x01, 0x04]], + [0x05, [0x01, 0x01, 0x05]], + ]); + const device = { + vendorId: 0x1532, + productId: VIPER_MINI_PRODUCT_ID, + productName: "Razer Viper Mini", + opened: true, + collections: [{ usagePage: 0x01, usage: 0x02, children: [], featureReports: [], inputReports: [], outputReports: [] }], + open: async () => {}, + close: async () => {}, + sendFeatureReport: async (_reportId: number, data: Uint8Array) => { + sent.push(data); + const commandClass = data[6]; + const commandId = data[7]; + if (commandClass === 0x00 && commandId === 0x81) { + pending = replyPacket(commandClass, commandId, data[5], [0x01, 0x03], RAZER_STATUS.ok); + return; + } + if (commandClass === 0x00 && commandId === 0x82) { + pending = replyPacket(commandClass, commandId, data[5], [], RAZER_STATUS.unsupported); + return; + } + if (commandClass === 0x04 && commandId === 0x85) { + pending = replyPacket(commandClass, commandId, data[5], [data[8], 0x04, 0xb0, 0x04, 0xb0, 0x00, 0x00], RAZER_STATUS.ok); + return; + } + if (commandClass === 0x00 && commandId === 0x85) { + pending = replyPacket(commandClass, commandId, data[5], [8], RAZER_STATUS.ok); + return; + } + const control = data[9]; + const read = commandClass === 0x02 && commandId === 0x8c; + const write = commandClass === 0x02 && commandId === 0x0c; + if (read || write) { + if (write && !options.ignoreButtonWrites) { + actions.set(control, [data[11], data[12], data[13]]); + } + const action = actions.get(control) ?? [0x00, 0x00, 0x00]; + 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)), + } as unknown as HIDDevice; + return { client: new RazerViperMiniHidClient(device), sent, actions }; +} + +test("Viper Mini keymap commands answer on 0x1f, not the legacy default", () => { + // Confirmed on hardware: class 0x02 is the one group on this firmware that + // does not reply under the client's 0xFF id. + const packet = encodeRazerRequest(razerReadButtonMappingCommand("mouse4"), VIPER_MINI_KEYMAP_TRANSACTION_ID); + + assert.equal(VIPER_MINI_KEYMAP_TRANSACTION_ID, 0x1f); + assert.notEqual(VIPER_MINI_KEYMAP_TRANSACTION_ID, VIPER_MINI_TRANSACTION_ID); + assert.equal(packet[1], 0x1f); + assert.equal(packet[6], 0x02); + assert.equal(packet[7], 0x8c); + assert.deepEqual([...packet.slice(8, 11)], [0x01, 0x04, 0x00]); +}); + +test("Viper Mini reports the four remappable controls in its status", async () => { + const { client } = fakeViperMini(); + + const status = await client.readStatus(); + + assert.deepEqual(status.razerButtonMappings, { + leftClick: "Left Click", + rightClick: "Right Click", + mouse4: "Mouse Button 4", + mouse5: "Mouse Button 5", + }); +}); + +test("Viper Mini writes a mapping on 0x1f and confirms it by read-back", async () => { + const { client, sent, actions } = fakeViperMini(); + + 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.equal((await client.readStatus()).razerButtonMappings?.mouse4, "Right Click"); +}); + +test("Viper Mini refuses a mapping the mouse did not keep", async () => { + // The firmware stores bytes without validating them, so a write can report + // success and leave the button dead. Only the read-back catches that. + const { client } = fakeViperMini({ ignoreButtonWrites: true }); + + await assert.rejects(() => client.setButtonMapping("mouse5", "Disabled"), /Mouse Button 5 instead of Disabled/); +}); + +test("Viper Mini cannot reassign Left Click, matching the shared restriction", async () => { + const { client } = fakeViperMini(); + + await assert.rejects(() => client.setButtonMapping("leftClick", "Right Click"), /fixed on the Standard layer/); +}); + diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index bf6e6e8c..2dd93d1b 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -2,9 +2,12 @@ import type { MouseLighting, MouseStatus } from "../mouse-types.ts"; import { VENDOR_ID } from "../vendors.ts"; import { openRazerDevice } from "./hid-open.ts"; import { + RAZER_BUTTON_CONTROLS, + RAZER_BUTTON_CONTROL_LABEL, RAZER_READ, RAZER_REPORT_ID, RAZER_STATUS, + RAZER_TRANSACTION_ID_1F, RAZER_TRANSACTION_ID_3F, RazerProtocolError, decodeDpi, @@ -13,9 +16,14 @@ import { decodeRazerResponse, decodeSerial, encodeRazerRequest, + razerDecodeButtonMapping, + razerReadButtonMappingCommand, + razerSetButtonMappingCommand, razerSetDpiCommand, razerSetExtendedEffectCommand, razerSetLegacyPollingCommand, + type RazerButtonControl, + type RazerButtonMapping, type RazerCommand, type RazerExtendedEffect, type RazerReactiveSpeed, @@ -29,6 +37,20 @@ export const VIPER_MINI_PRODUCT_ID = 0x008a; */ export const VIPER_MINI_TRANSACTION_ID = 0xff; +/** + * Class `0x02` is the exception to this model's legacy ids: its button-mapping + * commands only answer on `0x1f`, the id the Viper V3 Pro family uses. + * + * Verified on a Viper Mini on firmware v1.3. Reading the back button answered + * `01 01 04` (mouse button 4) under `0x1f`, and writing `0c 01 01` (Hypershift) + * to the DPI button plus keyboard actions to the side buttons under the same id + * changed what the hardware physically sent — confirmed with `wev`, not by + * read-back alone. Unlike the V3 Pro, whose class `0x02` write silently no-ops + * on `0x1f` and needs `RAZER_BUTTON_TRANSACTION_ID`, this firmware persists the + * write on `0x1f`, which is what this client sends every command with. + */ +export const VIPER_MINI_KEYMAP_TRANSACTION_ID = RAZER_TRANSACTION_ID_1F; + // Openrazer reads DPI with the no-store byte and writes with the storage byte. export const VIPER_MINI_DPI_READ: RazerCommand = { commandClass: 0x04, @@ -117,6 +139,14 @@ export class RazerViperMiniHidClient { */ private lighting: MouseLighting | null = null; + /** + * Button mappings as last read or written. Read once per connection rather + * than on every status poll, the same way the Viper V3 Pro client caches + * them, and refreshed from each write it confirms. + */ + private buttonMappings: Record | null = null; + private buttonMappingsKnown = false; + readonly device: HIDDevice; constructor(device: HIDDevice) { @@ -173,6 +203,7 @@ export class RazerViperMiniHidClient { const serial = await this.once("serial", () => this.request(RAZER_READ.serial).catch(() => null)); const dpi = decodeDpi(await this.request(VIPER_MINI_DPI_READ)); const pollingRateHz = decodeLegacyPollingRate(await this.request(RAZER_READ.pollingRate)); + const buttonMappings = await this.currentButtonMappings(); return { brand: "Razer", name: this.displayName(), @@ -199,6 +230,7 @@ export class RazerViperMiniHidClient { connectionType: "Wired", connectionDetail: "Wired USB", unitId: serial ? decodeSerial(serial) : null, + razerButtonMappings: buttonMappings ?? undefined, liftOffDistance: null, supportedLiftOffDistances: [], lighting: this.lightingFromCache(), @@ -233,6 +265,60 @@ export class RazerViperMiniHidClient { return confirmed; } + /** + * Every shipped control's current mapping, keyed by control name. Null when + * the class refuses every read, so the Buttons card is hidden outright rather + * than rendered empty. + * + * The DPI button is a fifth remappable slot on this model (id `0x60`), but it + * ships as a keyboard action (`02 02 00 73`, F24) and nothing this driver can + * send targets it, so it is left alone rather than half-supported: reading it + * would report an encoding the panel cannot name, and writing it would mean + * inventing a mapping vocabulary no other model shares. + */ + async readButtonMappings(): Promise | null> { + const mappings: Record = {}; + await Promise.all( + RAZER_BUTTON_CONTROLS.map(async (control) => { + const reply = await this.request(razerReadButtonMappingCommand(control), VIPER_MINI_KEYMAP_TRANSACTION_ID).catch(() => null); + const mapping = reply ? razerDecodeButtonMapping(reply) : null; + if (mapping) mappings[control] = mapping; + }), + ); + return Object.keys(mappings).length > 0 ? mappings : null; + } + + /** Probes once, then trusts what `setButtonMapping` leaves behind. */ + private async currentButtonMappings(): Promise | null> { + if (!this.buttonMappingsKnown) { + this.buttonMappings = await this.readButtonMappings(); + this.buttonMappingsKnown = true; + } + return this.buttonMappings; + } + + /** + * 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 { + // 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. + 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); + if (confirmed !== mapping) { + throw new Error( + `The mouse kept ${confirmed ?? "an unrecognised mapping"} for ${RAZER_BUTTON_CONTROL_LABEL[control]} instead of ${mapping}.`, + ); + } + this.buttonMappings = { ...this.buttonMappings, [control]: confirmed }; + this.buttonMappingsKnown = true; + return confirmed; + } + /** * Writes a lighting zone. The effect commands have no read back, so unlike * DPI and polling there is nothing to confirm against; the value written is From a1d2a953e12945f73eefdadbf7a702e9741c2d0b Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 09:19:54 -0700 Subject: [PATCH 02/21] fix(razer): retry a Viper Mini exchange answered by a stale reply --- src/drivers/razer/viper-mini-hid.test.ts | 25 ++++++++++++-- src/drivers/razer/viper-mini-hid.ts | 42 ++++++++++++++++++++++-- 2 files changed, 62 insertions(+), 5 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index 5a37056c..aa5f9125 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -95,7 +95,7 @@ test("Viper Mini accepts only its own PID on a single Generic Desktop Mouse coll assert.equal(RazerViperMiniHidClient.isSupported(extraCollection), false); }); -function replyPacket(commandClass: number, commandId: number, dataSize: number, args: number[], status: number): Uint8Array { +function replyPacket(commandClass: number, commandId: number, dataSize: number, args: number[], status: number): Uint8Array { const packet = new Uint8Array(RAZER_PACKET_LENGTH); packet[0] = status; packet[1] = VIPER_MINI_TRANSACTION_ID; @@ -114,9 +114,10 @@ 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 } = {}) { +function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: number } = {}) { const sent: Uint8Array[] = []; let pending = new Uint8Array(RAZER_PACKET_LENGTH); + let staleLeft = options.staleReplies ?? 0; const actions = new Map([ [0x01, [0x01, 0x01, 0x01]], [0x02, [0x01, 0x01, 0x02]], @@ -135,6 +136,13 @@ function fakeViperMini(options: { ignoreButtonWrites?: boolean } = {}) { sent.push(data); const commandClass = data[6]; const commandId = data[7]; + // The firmware can still hold the answer to an exchange the caller gave + // up on; the first read then returns that instead of its own reply. + if (staleLeft > 0) { + staleLeft -= 1; + pending = replyPacket(0x05, 0x81, 0x02, [0x01, 0x01], RAZER_STATUS.ok); + return; + } if (commandClass === 0x00 && commandId === 0x81) { pending = replyPacket(commandClass, commandId, data[5], [0x01, 0x03], RAZER_STATUS.ok); return; @@ -219,3 +227,16 @@ test("Viper Mini cannot reassign Left Click, matching the shared restriction", a await assert.rejects(() => client.setButtonMapping("leftClick", "Right Click"), /fixed on the Standard layer/); }); +test("Viper Mini resends after a reply left over from an earlier exchange", async () => { + // Reproduced on hardware: a polling-rate write was answered with a `0x05`/ + // `0x81` profile reply the app had already given up on, which failed a write + // that had landed. A stale reply on a read costs one more send, nothing else. + const { client, sent } = fakeViperMini({ staleReplies: 1 }); + + const status = await client.readStatus(); + + assert.deepEqual(status.firmware, ["Mouse 1.3"]); + assert.equal(status.pollingRateHz, 125); + assert.equal(sent.filter((packet) => packet[6] === 0x00 && packet[7] === 0x81).length, 2); +}); + diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index 2dd93d1b..c76641da 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -16,6 +16,7 @@ import { decodeRazerResponse, decodeSerial, encodeRazerRequest, + isRazerGetter, razerDecodeButtonMapping, razerReadButtonMappingCommand, razerSetButtonMappingCommand, @@ -65,6 +66,9 @@ const DPI_MIN = 100; const DPI_MAX = 8500; const RESPONSE_DELAY_MS = 100; 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; const VIPER_MINI_LIGHTING_ZONE = "Logo"; @@ -381,20 +385,52 @@ export class RazerViperMiniHidClient { return await run; } + /** + * One send, then reads until the reply for that command arrives. + * + * A stale reply is retried by sending again rather than thrown: this firmware + * leaves the answer to an earlier, timed-out exchange in the buffer, and a + * read that arrives after it belongs to the next command. Observed on a Viper + * Mini where a polling-rate write was answered with a `0x05`/`0x81` profile + * reply left over from a read the app had already given up on, reporting + * "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): Promise { await this.open(); - await this.device.sendFeatureReport(RAZER_REPORT_ID, encodeRazerRequest(command, transactionId)); + const request = encodeRazerRequest(command, transactionId); + for (let attempt = 0; attempt < SEND_ATTEMPTS; attempt += 1) { + await this.device.sendFeatureReport(RAZER_REPORT_ID, request); + const reply = await this.awaitReply(command); + if (reply) return reply; + } + throw new Error("The mouse kept answering an earlier command — replug it and try again."); + } + + /** + * Reads up to the response budget for one send. Returns null when the reply + * 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); const reply = this.copyDataView(await this.device.receiveFeatureReport(RAZER_REPORT_ID)); try { return decodeRazerResponse(reply, command); } catch (error) { - if (error instanceof RazerProtocolError && error.status === RAZER_STATUS.busy) continue; + if (!(error instanceof RazerProtocolError)) throw error; + if (error.status === RAZER_STATUS.busy) continue; + // A bad checksum or length carries no status, so it is transport + // corruption rather than an answer the mouse decided on. + if (error.status === null) return null; + // Repeating a getter is free. A setter is not: re-sending it could + // apply the write twice, so it confirms through a later read instead. + if (error.stale && isRazerGetter(command)) return null; throw error; } } - throw new Error("The mouse stayed busy — it may be asleep or out of range."); + return null; } private copyDataView(view: DataView): Uint8Array { From fad5972746dd8fa7ae73b70efd4d63e3955bfd4f Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 09:57:26 -0700 Subject: [PATCH 03/21] feat(razer): keyboard-key button mappings, verified on the Viper Mini --- src/drivers/razer/protocol.test.ts | 37 ++++++++ src/drivers/razer/viper-mini-hid.test.ts | 31 ++++++- src/drivers/razer/viper-mini-hid.ts | 39 +++++++- src/razer/codec.ts | 113 +++++++++++++++++++++++ 4 files changed, 217 insertions(+), 3 deletions(-) diff --git a/src/drivers/razer/protocol.test.ts b/src/drivers/razer/protocol.test.ts index d0a9de72..a624fef3 100644 --- a/src/drivers/razer/protocol.test.ts +++ b/src/drivers/razer/protocol.test.ts @@ -49,10 +49,13 @@ import { RAZER_TOGGLE_CONTROLS, RAZER_TOGGLE_CONTROL_INFO, razerDecodeButtonMapping, + razerDecodeKeyboardMapping, + razerKeyLabel, razerDecodeToggleControl, razerReadButtonMappingCommand, razerReadToggleControlCommand, razerSetButtonMappingCommand, + razerSetKeyboardMappingCommand, razerSetToggleControlCommand, RAZER_BACKLIGHT_BRIGHTNESS_READ, RAZER_LED, @@ -938,3 +941,37 @@ test("every whole brightness percentage survives the 0-255 round trip", () => { assert.equal(decodeBacklightBrightness(Uint8Array.of(0x01, 0x05, level)), percent); } }); + +test("a keyboard-mapping write matches the encoding the Viper Mini stored", () => { + // Confirmed on hardware: F13 (usage 0x68) written to the back button on the + // Hypershift layer and pressed — a real F13 arrived in `wev`. + const packet = encodeRazerRequest(razerSetKeyboardMappingCommand("mouse4", { mods: 0x00, usage: 0x68 })); + + assert.equal(packet[5], 0x0a); + assert.equal(packet[6], 0x02); + assert.equal(packet[7], 0x0c); + assert.deepEqual([...packet.slice(8, 18)], [0x01, 0x04, 0x00, 0x02, 0x02, 0x00, 0x68, 0x00, 0x00, 0x00]); +}); + +test("a keyboard mapping decodes back to the key it was written as", () => { + // The reply echoes the three request args, so the action starts at index 3. + const reply = new Uint8Array([0x01, 0x04, 0x00, 0x02, 0x02, 0x01, 0x68, 0x00, 0x00, 0x00]); + + assert.deepEqual(razerDecodeKeyboardMapping(reply), { mods: 0x01, usage: 0x68 }); + // The mouse-action decoder still refuses the type, which is what lets a + // caller tell the two apart instead of showing one as the other. + assert.equal(razerDecodeButtonMapping(reply), null); + assert.equal(razerKeyLabel({ mods: 0x01, usage: 0x68 }), "Ctrl+F13"); +}); + +test("key labels name what they can and hex what they cannot", () => { + assert.equal(razerKeyLabel({ mods: 0x00, usage: 0x04 }), "A"); + assert.equal(razerKeyLabel({ mods: 0x03, usage: 0x3a }), "Ctrl+Shift+F1"); + assert.equal(razerKeyLabel({ mods: 0x00, usage: 0x73 }), "F24"); + assert.equal(razerKeyLabel({ mods: 0x00, usage: 0x59 }), "Numpad 1"); + assert.equal(razerKeyLabel({ mods: 0x00, usage: 0x7f }), "0x7f"); +}); + +test("Left Click cannot take a keyboard key either", () => { + assert.throws(() => razerSetKeyboardMappingCommand("leftClick", { mods: 0x00, usage: 0x68 }), RazerProtocolError); +}); diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index aa5f9125..b4759939 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -164,7 +164,11 @@ function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: n const write = commandClass === 0x02 && commandId === 0x0c; if (read || write) { if (write && !options.ignoreButtonWrites) { - actions.set(control, [data[11], data[12], data[13]]); + // 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 + ? [data[11], data[12], data[13], data[14]] + : [data[11], data[12], data[13]]); } const action = actions.get(control) ?? [0x00, 0x00, 0x00]; pending = replyPacket(commandClass, commandId, data[5], [data[8], control, data[10], ...action], RAZER_STATUS.ok); @@ -240,3 +244,28 @@ test("Viper Mini resends after a reply left over from an earlier exchange", asyn assert.equal(sent.filter((packet) => packet[6] === 0x00 && packet[7] === 0x81).length, 2); }); +test("Viper Mini assigns a keyboard key and confirms it by read-back", async () => { + // Verified on hardware: F13 (usage 0x68) on the back button, pressed and seen + // as a real F13 in `wev`. The payload is the mouse-action layout with the + // keyboard type and a four-byte action. + const { client, sent } = fakeViperMini(); + + assert.equal(await client.setKeyboardMapping("mouse4", { mods: 0x00, usage: 0x68 }), "F13"); + assert.deepEqual([...sent.at(-2)!.slice(8, 18)], [0x01, 0x04, 0x00, 0x02, 0x02, 0x00, 0x68, 0x00, 0x00, 0x00]); + assert.equal(sent.at(-2)![1], 0x1f); + assert.equal((await client.readStatus()).razerButtonMappings?.mouse4, "F13"); +}); + +test("Viper Mini reports a key already stored on the mouse instead of dropping the control", async () => { + // The mouse's own DPI button ships as `02 02 00 73` (F24); a control decoded + // 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]); + + const status = await client.readStatus(); + + assert.equal(status.razerButtonMappings?.mouse5, "Ctrl+F13"); + assert.equal(status.razerButtonMappings?.mouse4, "Mouse Button 4"); +}); + diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index c76641da..19433ff5 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -18,8 +18,11 @@ import { encodeRazerRequest, isRazerGetter, razerDecodeButtonMapping, + razerDecodeKeyboardMapping, + razerKeyLabel, razerReadButtonMappingCommand, razerSetButtonMappingCommand, + razerSetKeyboardMappingCommand, razerSetDpiCommand, razerSetExtendedEffectCommand, razerSetLegacyPollingCommand, @@ -27,6 +30,7 @@ import { type RazerButtonMapping, type RazerCommand, type RazerExtendedEffect, + type RazerKeyAction, type RazerReactiveSpeed, } from "@openmouse/protocol/razer"; @@ -285,8 +289,17 @@ export class RazerViperMiniHidClient { await Promise.all( RAZER_BUTTON_CONTROLS.map(async (control) => { const reply = await this.request(razerReadButtonMappingCommand(control), VIPER_MINI_KEYMAP_TRANSACTION_ID).catch(() => null); - const mapping = reply ? razerDecodeButtonMapping(reply) : null; - if (mapping) mappings[control] = mapping; + if (!reply) return; + const mapping = razerDecodeButtonMapping(reply); + if (mapping) { + mappings[control] = mapping; + return; + } + // 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); }), ); return Object.keys(mappings).length > 0 ? mappings : null; @@ -323,6 +336,28 @@ export class RazerViperMiniHidClient { return confirmed; } + /** + * Assigns a keyboard key to a control and confirms it by read-back, the same + * way `setButtonMapping` does — the firmware stores any bytes it is handed, so + * only a read that shows the key back proves the assignment took. + * + * Returns the label the panel shows for the assignment (`Ctrl+F13`). + */ + async setKeyboardMapping(control: RazerButtonControl, key: RazerKeyAction): Promise { + 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); + 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}.`, + ); + } + this.buttonMappings = { ...this.buttonMappings, [control]: label }; + this.buttonMappingsKnown = true; + return label; + } + /** * Writes a lighting zone. The effect commands have no read back, so unlike * DPI and polling there is nothing to confirm against; the value written is diff --git a/src/razer/codec.ts b/src/razer/codec.ts index d39c90f6..e2671b64 100644 --- a/src/razer/codec.ts +++ b/src/razer/codec.ts @@ -969,6 +969,119 @@ export function razerSetButtonMappingCommand(control: RazerButtonControl, mappin }; } +/** + * A keyboard key a button sends instead of a mouse action. + * + * Verified on a Viper Mini (firmware v1.3) rather than inferred: its DPI button + * ships as `02 02 00 73` (F24), and writing the same shape to the side buttons + * on the Hypershift layer produced real F13/F14 key events, confirmed with + * `wev` and surviving a replug. The write layout mirrors the mouse actions — + * `[profile, control, layer, 0x02, 0x02, mods, usage]` — with the length byte + * counting the two bytes after it. + * + * `mods` is the same modifier bitfield the rest of the driver's keyboard + * payloads use; `usage` is a HID keyboard usage (0x04 = a, 0x68 = F13). + */ +export interface RazerKeyAction { + mods: number; + usage: number; +} + +export const RAZER_KEY_MODIFIERS: Readonly> = { + ctrl: 0x01, + shift: 0x02, + alt: 0x04, + meta: 0x08, +}; + +const RAZER_KEY_NAMES: Readonly> = (() => { + const names: Record = {}; + for (let i = 0; i < 26; i += 1) names[0x04 + i] = String.fromCharCode(65 + i); + for (let i = 0; i < 10; i += 1) names[0x1e + i] = String((i + 1) % 10); + for (let i = 0; i < 12; i += 1) names[0x3a + i] = `F${i + 1}`; + for (let i = 0; i < 12; i += 1) names[0x68 + i] = `F${i + 13}`; + return Object.assign(names, { + 0x28: "Enter", + 0x29: "Esc", + 0x2a: "Backspace", + 0x2b: "Tab", + 0x2c: "Space", + 0x2d: "Minus", + 0x2e: "Equals", + 0x2f: "[", + 0x30: "]", + 0x31: "\\", + 0x33: ";", + 0x34: "'", + 0x35: "`", + 0x36: ",", + 0x37: ".", + 0x38: "/", + 0x39: "Caps Lock", + 0x46: "Print Screen", + 0x47: "Scroll Lock", + 0x48: "Pause", + 0x49: "Insert", + 0x4a: "Home", + 0x4b: "Page Up", + 0x4c: "Delete", + 0x4d: "End", + 0x4e: "Page Down", + 0x4f: "Right", + 0x50: "Left", + 0x51: "Down", + 0x52: "Up", + 0x53: "Num Lock", + 0x54: "Numpad /", + 0x55: "Numpad *", + 0x56: "Numpad -", + 0x57: "Numpad +", + 0x58: "Numpad Enter", + 0x62: "Numpad 0", + 0x63: "Numpad .", + }); +})(); + +/** + * How a key reads in the panel, e.g. `Ctrl+Shift+F13`. Used as the mapping + * label so a button carrying a key is not mistaken for one the driver cannot + * name, which is what a `null` decode would look like. + */ +export function razerKeyLabel(key: RazerKeyAction): string { + const parts: string[] = []; + if (key.mods & RAZER_KEY_MODIFIERS.ctrl!) parts.push("Ctrl"); + if (key.mods & RAZER_KEY_MODIFIERS.shift!) parts.push("Shift"); + if (key.mods & RAZER_KEY_MODIFIERS.alt!) parts.push("Alt"); + if (key.mods & RAZER_KEY_MODIFIERS.meta!) parts.push("Meta"); + const name = RAZER_KEY_NAMES[key.usage] ?? `0x${key.usage.toString(16).padStart(2, "0")}`; + parts.push(key.usage >= 0x59 && key.usage <= 0x61 ? `Numpad ${key.usage - 0x59 + 1}` : name); + return parts.join("+"); +} + +export function razerSetKeyboardMappingCommand(control: RazerButtonControl, key: RazerKeyAction): 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.`, + ); + } + return { + ...RAZER_WRITE.buttonMapping, + args: [0x01, RAZER_BUTTON_CONTROL_INDEX[control], 0x00, 0x02, 0x02, key.mods, key.usage, 0x00, 0x00, 0x00], + }; +} + +/** + * The keyboard action in a button-mapping reply, or null when the reply is not + * a keyboard action. `razerDecodeButtonMapping` deliberately returns null for + * this type; callers that can carry keys read them through this instead. + */ +export function razerDecodeKeyboardMapping(args: Uint8Array): RazerKeyAction | null { + if (args[3] !== 0x02) return null; + // The reply echoes the three request args, so the action starts at index 3: + // type, length, modifier, usage. + return { mods: args[5] ?? 0, usage: args[6] ?? 0 }; +} + /** * Scroll Up, Scroll Down and the bottom sensitivity button, each restricted * to exactly two states: their own factory action, or Disabled. Unlike From 694b1763ca0c684b4db23d2588aad24609eea884 Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 10:06:46 -0700 Subject: [PATCH 04/21] fix(razer): treat a lost write ack on the Viper Mini as unconfirmed, not failed --- src/drivers/razer/viper-mini-hid.test.ts | 22 +++++++++++++++++++++- src/drivers/razer/viper-mini-hid.ts | 19 ++++++++++++++++--- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index b4759939..7fa77840 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -114,10 +114,11 @@ 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 } = {}) { +function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: number; staleWriteAcks?: number } = {}) { const sent: Uint8Array[] = []; let pending = new Uint8Array(RAZER_PACKET_LENGTH); let staleLeft = options.staleReplies ?? 0; + let staleAcks = options.staleWriteAcks ?? 0; const actions = new Map([ [0x01, [0x01, 0x01, 0x01]], [0x02, [0x01, 0x01, 0x02]], @@ -171,6 +172,14 @@ function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: n : [data[11], data[12], data[13]]); } const action = actions.get(control) ?? [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. + if (write && staleAcks > 0) { + staleAcks -= 1; + pending = replyPacket(0x05, 0x81, 0x02, [0x01, 0x01], RAZER_STATUS.ok); + return; + } pending = replyPacket(commandClass, commandId, data[5], [data[8], control, data[10], ...action], RAZER_STATUS.ok); return; } @@ -269,3 +278,14 @@ test("Viper Mini reports a key already stored on the mouse instead of dropping t assert.equal(status.razerButtonMappings?.mouse4, "Mouse Button 4"); }); + +test("Viper Mini keeps a write whose acknowledgement was lost", async () => { + // The reporter hit this as "Class 0x02 command 0x0c was answered by a + // different command" on a binding that had actually stored. The ack is never + // what proves a write here — the read-back is — so it must not fail the write, + // and the write must not be sent twice. + const { client, sent } = fakeViperMini({ staleWriteAcks: 1 }); + + assert.equal(await client.setButtonMapping("mouse4", "Right Click"), "Right Click"); + assert.equal(sent.filter((packet) => packet[6] === 0x02 && packet[7] === 0x0c).length, 1); +}); diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index 19433ff5..a8d915f0 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -434,10 +434,20 @@ export class RazerViperMiniHidClient { private async exchange(command: RazerCommand, transactionId: number): Promise { await this.open(); const request = encodeRazerRequest(command, transactionId); - for (let attempt = 0; attempt < SEND_ATTEMPTS; attempt += 1) { + const getter = isRazerGetter(command); + // A getter can be asked again for free; a setter cannot, because a second + // send could apply the write twice. + 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); 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 + // never what proves it. Reporting the lost ack here is what turned a + // stored button mapping into "Class 0x02 command 0x0c was answered by a + // different command". + if (!getter) return new Uint8Array(0); } throw new Error("The mouse kept answering an earlier command — replug it and try again."); } @@ -460,8 +470,11 @@ export class RazerViperMiniHidClient { // corruption rather than an answer the mouse decided on. if (error.status === null) return null; // Repeating a getter is free. A setter is not: re-sending it could - // apply the write twice, so it confirms through a later read instead. - if (error.stale && isRazerGetter(command)) return null; + // apply the write twice, so it keeps reading for its own ack instead. + if (error.stale) { + if (isRazerGetter(command)) return null; + continue; + } throw error; } } From 1def63b18edc0783316c74af14190ec578a76a4e Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 10:27:36 -0700 Subject: [PATCH 05/21] feat(razer): the Viper Mini's bottom button is a remappable control --- src/drivers/mouse-types.ts | 6 ++++ src/drivers/razer/viper-mini-hid.test.ts | 15 +++++++++ src/drivers/razer/viper-mini-hid.ts | 21 +++++++------ src/razer/codec.ts | 39 +++++++++++++++++++++--- 4 files changed, 66 insertions(+), 15 deletions(-) diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index 97cd3b17..1d517627 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -495,6 +495,12 @@ export interface MouseStatus { * omitted rather than guessed at. */ razerButtonMappings?: Record; + /** + * The mappings this model's firmware has been checked with, in display order. + * Falls back to `RAZER_BUTTON_MAPPINGS` when absent; the Viper Mini adds + * Hypershift because that write was verified on it. + */ + razerButtonOptions?: string[]; /** 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/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index 7fa77840..19a7bbb7 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -124,6 +124,8 @@ function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: n [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]], ]); const device = { vendorId: 0x1532, @@ -213,7 +215,20 @@ 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", }); + assert.ok(status.razerButtonOptions?.includes("Hypershift")); + assert.deepEqual(status.razerButtonOptions?.slice(0, 5), ["Left Click", "Right Click", "Mouse Button 4", "Mouse Button 5", "Disabled"]); +}); + +test("Viper Mini turns its bottom button into the Hypershift modifier", async () => { + // The reporter's original ask, and the write verified on hardware: `0c 01 01` + // on index 0x60 makes the button a layer modifier. + const { client, sent } = fakeViperMini(); + + assert.equal(await client.setButtonMapping("dpiButton", "Hypershift"), "Hypershift"); + assert.deepEqual([...sent.at(-2)!.slice(8, 18)], [0x01, 0x60, 0x00, 0x0c, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00]); + assert.equal((await client.readStatus()).razerButtonMappings?.dpiButton, "Hypershift"); }); test("Viper Mini writes a mapping on 0x1f and confirms it by read-back", async () => { diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index a8d915f0..04ff693b 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -2,8 +2,9 @@ import type { MouseLighting, MouseStatus } from "../mouse-types.ts"; import { VENDOR_ID } from "../vendors.ts"; import { openRazerDevice } from "./hid-open.ts"; import { - RAZER_BUTTON_CONTROLS, RAZER_BUTTON_CONTROL_LABEL, + VIPER_MINI_BUTTON_CONTROLS, + VIPER_MINI_BUTTON_MAPPINGS, RAZER_READ, RAZER_REPORT_ID, RAZER_STATUS, @@ -239,6 +240,8 @@ export class RazerViperMiniHidClient { connectionDetail: "Wired USB", unitId: serial ? decodeSerial(serial) : null, razerButtonMappings: buttonMappings ?? undefined, + // Hypershift is included here and only here — see VIPER_MINI_BUTTON_MAPPINGS. + razerButtonOptions: [...VIPER_MINI_BUTTON_MAPPINGS], liftOffDistance: null, supportedLiftOffDistances: [], lighting: this.lightingFromCache(), @@ -274,20 +277,18 @@ export class RazerViperMiniHidClient { } /** - * Every shipped control's current mapping, keyed by control name. Null when - * the class refuses every read, so the Buttons card is hidden outright rather - * than rendered empty. + * Every control's current mapping, keyed by control name. Null when the class + * refuses every read, so the Buttons card is hidden outright rather than + * rendered empty. * - * The DPI button is a fifth remappable slot on this model (id `0x60`), but it - * ships as a keyboard action (`02 02 00 73`, F24) and nothing this driver can - * send targets it, so it is left alone rather than half-supported: reading it - * would report an encoding the panel cannot name, and writing it would mean - * inventing a mapping vocabulary no other model shares. + * The bottom button is included: this firmware keeps a keyboard action in it + * (`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> { const mappings: Record = {}; await Promise.all( - RAZER_BUTTON_CONTROLS.map(async (control) => { + VIPER_MINI_BUTTON_CONTROLS.map(async (control) => { const reply = await this.request(razerReadButtonMappingCommand(control), VIPER_MINI_KEYMAP_TRANSACTION_ID).catch(() => null); if (!reply) return; const mapping = razerDecodeButtonMapping(reply); diff --git a/src/razer/codec.ts b/src/razer/codec.ts index e2671b64..ccbedacc 100644 --- a/src/razer/codec.ts +++ b/src/razer/codec.ts @@ -884,29 +884,51 @@ export function decodeExtendedPollingRate(args: Uint8Array): number { * driver's own write to it has only been physically checked against the wrong * action, and Hypershift's read does not honour a requested layer at all. */ -export type RazerButtonControl = "leftClick" | "rightClick" | "mouse4" | "mouse5"; +export type RazerButtonControl = "leftClick" | "rightClick" | "mouse4" | "mouse5" | "dpiButton"; export const RAZER_BUTTON_CONTROLS: readonly RazerButtonControl[] = ["leftClick", "rightClick", "mouse4", "mouse5"]; +/** + * The Viper Mini's bottom button is the same slot as the V3 Pro's toggle + * `sensitivityButton` (index `0x60`), but this firmware stores a plain + * keyboard action in it (`02 02 00 73`, F24) rather than `06 01 06`. That makes + * it an ordinary cross-assignable control here instead of a two-state toggle, + * so it is read and written through the button path — under its own name so no + * model ever shows two rows for one slot. + */ +export const VIPER_MINI_BUTTON_CONTROLS: readonly RazerButtonControl[] = [...RAZER_BUTTON_CONTROLS, "dpiButton"]; + const RAZER_BUTTON_CONTROL_INDEX: Record = { leftClick: 0x01, rightClick: 0x02, mouse4: 0x04, mouse5: 0x05, + dpiButton: 0x60, }; /** Every mapping the panel can offer: each control's own action, plus Disabled. */ export const RAZER_BUTTON_MAPPINGS = ["Left Click", "Right Click", "Mouse Button 4", "Mouse Button 5", "Disabled"] as const; -export type RazerButtonMapping = (typeof RAZER_BUTTON_MAPPINGS)[number]; +export type RazerButtonMapping = (typeof RAZER_BUTTON_MAPPINGS)[number] | "Hypershift"; + +/** + * The Viper Mini's option list. Hypershift is offered here because this + * firmware was checked with it: `0c 01 01` on the bottom button made it the + * layer modifier, confirmed by the other buttons changing what they send while + * it was held. The other shipped models have never been tried with it, so it + * stays out of `RAZER_BUTTON_MAPPINGS` and only this client advertises it. + */ +export const VIPER_MINI_BUTTON_MAPPINGS: readonly RazerButtonMapping[] = [...RAZER_BUTTON_MAPPINGS, "Hypershift"]; // Each control's own label doubles as the mapping that plays its native // action, so the type carries that: "leftClick"'s label is also a valid -// RazerButtonMapping, not just display text. -export const RAZER_BUTTON_CONTROL_LABEL: Record = { +// RazerButtonMapping, not just display text. `dpiButton` is display-only — its +// factory action is a keyboard key, not one of the five mouse mappings. +export const RAZER_BUTTON_CONTROL_LABEL: Record = { leftClick: "Left Click", rightClick: "Right Click", mouse4: "Mouse Button 4", mouse5: "Mouse Button 5", + dpiButton: "DPI Button", }; const RAZER_MAPPING_CONTROL: Partial> = Object.fromEntries( @@ -922,6 +944,8 @@ const RAZER_MAPPING_CONTROL: Partial RAZER_BUTTON_CONTROL_INDEX[candidate] === value); - return control ? RAZER_BUTTON_CONTROL_LABEL[control] : null; + // Only the four cross-assignable controls are searched, and each of those + // labels is a real mapping, so the widening to `string` for `dpiButton`'s + // sake is safe to narrow back here. + return control ? (RAZER_BUTTON_CONTROL_LABEL[control] as RazerButtonMapping) : null; } /** Only the Standard layer is trusted for reads — see `RAZER_READ.buttonMapping`. */ From 2e0936d03741a207e5c0bef28c631be8ab95adb8 Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 10:40:41 -0700 Subject: [PATCH 06/21] feat(razer): middle click as a target and the wheel press as a control on the Viper Mini --- src/drivers/razer/viper-mini-hid.test.ts | 15 ++++- src/razer/codec.ts | 76 +++++++++++++++++------- 2 files changed, 68 insertions(+), 23 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index 19a7bbb7..ab826a64 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -121,6 +121,7 @@ function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: n let staleAcks = options.staleWriteAcks ?? 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]], @@ -212,13 +213,25 @@ test("Viper Mini reports the four remappable controls in its status", async () = assert.deepEqual(status.razerButtonMappings, { leftClick: "Left Click", + scrollClick: "Middle Click", rightClick: "Right Click", mouse4: "Mouse Button 4", mouse5: "Mouse Button 5", dpiButton: "F24", }); assert.ok(status.razerButtonOptions?.includes("Hypershift")); - assert.deepEqual(status.razerButtonOptions?.slice(0, 5), ["Left Click", "Right Click", "Mouse Button 4", "Mouse Button 5", "Disabled"]); + assert.ok(status.razerButtonOptions?.includes("Middle Click")); + assert.deepEqual(status.razerButtonOptions?.slice(0, 2), ["Left Click", "Middle Click"]); +}); + +test("Viper Mini assigns a middle click to another button", async () => { + // `01 01 03` is the wheel press's own action, read off the device; assigning + // it elsewhere is the same cross-assignment already confirmed for 1/2/4/5. + const { client, sent } = fakeViperMini(); + + assert.equal(await client.setButtonMapping("dpiButton", "Middle Click"), "Middle Click"); + assert.deepEqual([...sent.at(-2)!.slice(8, 18)], [0x01, 0x60, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00]); + assert.equal((await client.readStatus()).razerButtonMappings?.dpiButton, "Middle Click"); }); test("Viper Mini turns its bottom button into the Hypershift modifier", async () => { diff --git a/src/razer/codec.ts b/src/razer/codec.ts index ccbedacc..bd2869eb 100644 --- a/src/razer/codec.ts +++ b/src/razer/codec.ts @@ -884,22 +884,32 @@ export function decodeExtendedPollingRate(args: Uint8Array): number { * driver's own write to it has only been physically checked against the wrong * action, and Hypershift's read does not honour a requested layer at all. */ -export type RazerButtonControl = "leftClick" | "rightClick" | "mouse4" | "mouse5" | "dpiButton"; +export type RazerButtonControl = "leftClick" | "scrollClick" | "rightClick" | "mouse4" | "mouse5" | "dpiButton"; export const RAZER_BUTTON_CONTROLS: readonly RazerButtonControl[] = ["leftClick", "rightClick", "mouse4", "mouse5"]; /** - * The Viper Mini's bottom button is the same slot as the V3 Pro's toggle - * `sensitivityButton` (index `0x60`), but this firmware stores a plain - * keyboard action in it (`02 02 00 73`, F24) rather than `06 01 06`. That makes - * it an ordinary cross-assignable control here instead of a two-state toggle, - * so it is read and written through the button path — under its own name so no - * model ever shows two rows for one slot. + * The Viper Mini's whole button set, in the order the panel shows it. + * + * Two of these are model-specific. `scrollClick` (`0x03`) is the wheel press: + * the index is known everywhere, but this driver's own write to it on the V3 + * Pro was only ever physically checked against the wrong action, so it is not + * in the shared list. `dpiButton` (`0x60`) is the V3 Pro's two-state + * `sensitivityButton`, where this firmware instead keeps a plain keyboard + * action (`02 02 00 73`, F24) — an ordinary cross-assignable control here. */ -export const VIPER_MINI_BUTTON_CONTROLS: readonly RazerButtonControl[] = [...RAZER_BUTTON_CONTROLS, "dpiButton"]; +export const VIPER_MINI_BUTTON_CONTROLS: readonly RazerButtonControl[] = [ + "leftClick", + "scrollClick", + "rightClick", + "mouse4", + "mouse5", + "dpiButton", +]; const RAZER_BUTTON_CONTROL_INDEX: Record = { leftClick: 0x01, + scrollClick: 0x03, rightClick: 0x02, mouse4: 0x04, mouse5: 0x05, @@ -908,31 +918,55 @@ const RAZER_BUTTON_CONTROL_INDEX: Record = { /** Every mapping the panel can offer: each control's own action, plus Disabled. */ export const RAZER_BUTTON_MAPPINGS = ["Left Click", "Right Click", "Mouse Button 4", "Mouse Button 5", "Disabled"] as const; -export type RazerButtonMapping = (typeof RAZER_BUTTON_MAPPINGS)[number] | "Hypershift"; +export type RazerButtonMapping = (typeof RAZER_BUTTON_MAPPINGS)[number] | "Middle Click" | "Hypershift"; /** - * The Viper Mini's option list. Hypershift is offered here because this - * firmware was checked with it: `0c 01 01` on the bottom button made it the - * layer modifier, confirmed by the other buttons changing what they send while - * it was held. The other shipped models have never been tried with it, so it - * stays out of `RAZER_BUTTON_MAPPINGS` and only this client advertises it. + * The Viper Mini's option list. Two entries are here and nowhere else: + * + * - `Middle Click` (`01 01 03`) — the mouse's own wheel-press action, so the + * encoding is read straight off the device even though no other control has + * been assigned it yet. + * - `Hypershift` (`0c 01 01`) — checked on this firmware: the bottom button + * became the layer modifier and the other buttons changed what they send + * while it was held. */ -export const VIPER_MINI_BUTTON_MAPPINGS: readonly RazerButtonMapping[] = [...RAZER_BUTTON_MAPPINGS, "Hypershift"]; +export const VIPER_MINI_BUTTON_MAPPINGS: readonly RazerButtonMapping[] = [ + "Left Click", + "Middle Click", + "Right Click", + "Mouse Button 4", + "Mouse Button 5", + "Hypershift", + "Disabled", +]; // Each control's own label doubles as the mapping that plays its native // action, so the type carries that: "leftClick"'s label is also a valid // RazerButtonMapping, not just display text. `dpiButton` is display-only — its -// factory action is a keyboard key, not one of the five mouse mappings. +// factory action is a keyboard key, not one of the mouse mappings. export const RAZER_BUTTON_CONTROL_LABEL: Record = { leftClick: "Left Click", + scrollClick: "Middle Click", rightClick: "Right Click", mouse4: "Mouse Button 4", mouse5: "Mouse Button 5", dpiButton: "DPI Button", }; +/** + * Control index -> the mapping that replays it. `dpiButton` is absent because + * its factory action is a keyboard key, and a key is not one of the mappings. + */ +const RAZER_CONTROL_MAPPING_LABEL: Partial> = { + leftClick: "Left Click", + scrollClick: "Middle Click", + rightClick: "Right Click", + mouse4: "Mouse Button 4", + mouse5: "Mouse Button 5", +}; + const RAZER_MAPPING_CONTROL: Partial> = Object.fromEntries( - RAZER_BUTTON_CONTROLS.map((control) => [RAZER_BUTTON_CONTROL_LABEL[control], control]), + Object.entries(RAZER_CONTROL_MAPPING_LABEL).map(([control, label]) => [label, control]), ); /** @@ -964,11 +998,9 @@ export function razerDecodeButtonMapping(args: Uint8Array): RazerButtonMapping | if (type === 0x00) return "Disabled"; if (type === 0x0c && len === 0x01 && value === 0x01) return "Hypershift"; if (type !== 0x01) return null; - const control = RAZER_BUTTON_CONTROLS.find((candidate) => RAZER_BUTTON_CONTROL_INDEX[candidate] === value); - // Only the four cross-assignable controls are searched, and each of those - // labels is a real mapping, so the widening to `string` for `dpiButton`'s - // sake is safe to narrow back here. - return control ? (RAZER_BUTTON_CONTROL_LABEL[control] as RazerButtonMapping) : null; + const entry = (Object.entries(RAZER_CONTROL_MAPPING_LABEL) as Array<[RazerButtonControl, RazerButtonMapping]>) + .find(([control]) => RAZER_BUTTON_CONTROL_INDEX[control] === value); + return entry ? entry[1] : null; } /** Only the Standard layer is trusted for reads — see `RAZER_READ.buttonMapping`. */ From 880d151d828519a0b64f0e2acda9c709fbd0d727 Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 4 Dec 2026 19:14:59 +0100 Subject: [PATCH 07/21] fix(razer): review findings on the Viper Mini button mapping - A mapping reply is accepted only when it echoes the control that was asked for - A write before the first status read no longer hides the other controls, and a probe with a failed read is retried later - close() forgets the cached mappings - A lighting write whose acknowledgement never arrives is reported, since lighting has no read-back --- src/drivers/razer/viper-mini-hid.test.ts | 48 +++++++++++++++++++++++- src/drivers/razer/viper-mini-hid.ts | 47 ++++++++++++++++------- 2 files changed, 80 insertions(+), 15 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index ab826a64..1efa5d5d 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -114,11 +114,12 @@ 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 } = {}) { +function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: number; staleWriteAcks?: number; wrongControlReplies?: 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]], @@ -183,6 +184,11 @@ function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: n pending = replyPacket(0x05, 0x81, 0x02, [0x01, 0x01], RAZER_STATUS.ok); 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; + } pending = replyPacket(commandClass, commandId, data[5], [data[8], control, data[10], ...action], RAZER_STATUS.ok); return; } @@ -317,3 +323,43 @@ test("Viper Mini keeps a write whose acknowledgement was lost", async () => { assert.equal(await client.setButtonMapping("mouse4", "Right Click"), "Right Click"); assert.equal(sent.filter((packet) => packet[6] === 0x02 && packet[7] === 0x0c).length, 1); }); + +const ALL_DEFAULT_MAPPINGS = { + leftClick: "Left Click", + scrollClick: "Middle Click", + rightClick: "Right Click", + mouse4: "Mouse Button 4", + mouse5: "Mouse Button 5", + dpiButton: "F24", +}; + +test("Viper Mini ignores a mapping reply that echoes another control", async () => { + const { client } = fakeViperMini({ wrongControlReplies: 1 }); + + assert.deepEqual(await client.readButtonMappings(), ALL_DEFAULT_MAPPINGS); +}); + +test("Viper Mini still reports every control after a write before the first status read", async () => { + const { client } = fakeViperMini(); + + await client.setButtonMapping("mouse4", "Right Click"); + assert.deepEqual((await client.readStatus()).razerButtonMappings, { ...ALL_DEFAULT_MAPPINGS, mouse4: "Right Click" }); +}); + +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]); + await client.close(); + assert.equal((await client.readStatus()).razerButtonMappings?.mouse4, "Right Click"); +}); + +test("Viper Mini reports a lighting write the mouse never acknowledged", async () => { + const { client } = fakeViperMini({ staleReplies: 1 }); + + await assert.rejects( + () => client.setLighting({ zone: "Logo", mode: "Static", color: "#00ff00", color2: null, speed: null } as never), + /did not confirm/, + ); +}); diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index 04ff693b..d48b3d1e 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -179,6 +179,8 @@ export class RazerViperMiniHidClient { async close(): Promise { this.staticReads.clear(); + this.buttonMappings = null; + this.buttonMappingsKnown = false; if (this.device.opened) await this.device.close(); } @@ -286,10 +288,18 @@ export class RazerViperMiniHidClient { * it behaves like any other cross-assignable control here. */ async readButtonMappings(): Promise | null> { + return (await this.probeButtonMappings()).mappings; + } + + private async probeButtonMappings(): Promise<{ mappings: Record | null; complete: boolean }> { 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(() => null); + 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) { @@ -303,14 +313,15 @@ export class RazerViperMiniHidClient { if (key) mappings[control] = razerKeyLabel(key); }), ); - return Object.keys(mappings).length > 0 ? mappings : null; + return { mappings: Object.keys(mappings).length > 0 ? mappings : null, complete }; } /** Probes once, then trusts what `setButtonMapping` leaves behind. */ private async currentButtonMappings(): Promise | null> { if (!this.buttonMappingsKnown) { - this.buttonMappings = await this.readButtonMappings(); - this.buttonMappingsKnown = true; + const { mappings, complete } = await this.probeButtonMappings(); + this.buttonMappings = mappings; + this.buttonMappingsKnown = complete; } return this.buttonMappings; } @@ -332,8 +343,7 @@ export class RazerViperMiniHidClient { `The mouse kept ${confirmed ?? "an unrecognised mapping"} for ${RAZER_BUTTON_CONTROL_LABEL[control]} instead of ${mapping}.`, ); } - this.buttonMappings = { ...this.buttonMappings, [control]: confirmed }; - this.buttonMappingsKnown = true; + if (this.buttonMappingsKnown) this.buttonMappings = { ...this.buttonMappings, [control]: confirmed }; return confirmed; } @@ -354,8 +364,7 @@ export class RazerViperMiniHidClient { `The mouse kept ${confirmed ? razerKeyLabel(confirmed) : "a mouse action"} for ${RAZER_BUTTON_CONTROL_LABEL[control]} instead of ${label}.`, ); } - this.buttonMappings = { ...this.buttonMappings, [control]: label }; - this.buttonMappingsKnown = true; + if (this.buttonMappingsKnown) this.buttonMappings = { ...this.buttonMappings, [control]: label }; return label; } @@ -378,7 +387,7 @@ export class RazerViperMiniHidClient { if (lighting.color !== null) options.color = lighting.color; if (lighting.color2 !== null) options.color2 = lighting.color2; if (lighting.speed !== null) options.speed = lighting.speed as RazerReactiveSpeed; - await this.request(razerSetExtendedEffectCommand(effect, options), VIPER_MINI_EFFECT_TRANSACTION_ID); + await this.request(razerSetExtendedEffectCommand(effect, options), VIPER_MINI_EFFECT_TRANSACTION_ID, true); this.lighting = { ...lighting }; return this.lighting; } @@ -412,10 +421,11 @@ export class RazerViperMiniHidClient { private async request( command: RazerCommand, transactionId: number = VIPER_MINI_TRANSACTION_ID, + requireAck = false, ): Promise { const run = this.queue.then( - () => this.exchange(command, transactionId), - () => this.exchange(command, transactionId), + () => this.exchange(command, transactionId, requireAck), + () => this.exchange(command, transactionId, requireAck), ); this.queue = run.catch(() => undefined); return await run; @@ -432,7 +442,7 @@ 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): Promise { + private async exchange(command: RazerCommand, transactionId: number, requireAck: boolean): Promise { await this.open(); const request = encodeRazerRequest(command, transactionId); const getter = isRazerGetter(command); @@ -448,7 +458,10 @@ export class RazerViperMiniHidClient { // never what proves it. Reporting the lost ack here is what turned a // stored button mapping into "Class 0x02 command 0x0c was answered by a // different command". - if (!getter) return new Uint8Array(0); + if (!getter) { + if (requireAck) throw new Error("The mouse did not confirm the change. Try again."); + return new Uint8Array(0); + } } throw new Error("The mouse kept answering an earlier command — replug it and try again."); } @@ -463,7 +476,9 @@ export class RazerViperMiniHidClient { await this.delay(RESPONSE_DELAY_MS); const reply = this.copyDataView(await this.device.receiveFeatureReport(RAZER_REPORT_ID)); try { - return decodeRazerResponse(reply, command); + const args = decodeRazerResponse(reply, command); + if (this.isMappingRead(command) && command.args?.some((byte, i) => args[i] !== byte)) return null; + return args; } catch (error) { if (!(error instanceof RazerProtocolError)) throw error; if (error.status === RAZER_STATUS.busy) continue; @@ -482,6 +497,10 @@ export class RazerViperMiniHidClient { return null; } + private isMappingRead(command: RazerCommand): boolean { + return command.commandClass === RAZER_READ.buttonMapping.commandClass && command.commandId === RAZER_READ.buttonMapping.commandId; + } + private copyDataView(view: DataView): Uint8Array { return new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength)); } From c43926323c1f8db357a5c213c30104c1b52793c7 Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 4 Dec 2026 19:26:46 +0100 Subject: [PATCH 08/21] fix(razer): re-read the Viper Mini mappings after an unconfirmed write --- src/drivers/razer/viper-mini-hid.test.ts | 9 +++++++++ src/drivers/razer/viper-mini-hid.ts | 14 ++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index 1efa5d5d..692b236e 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -363,3 +363,12 @@ test("Viper Mini reports a lighting write the mouse never acknowledged", async ( /did not confirm/, ); }); + +test("Viper Mini reads the mappings again when a write's read-back is refused", async () => { + const { client, actions } = fakeViperMini({ ignoreButtonWrites: true }); + + await client.readStatus(); + await assert.rejects(() => client.setButtonMapping("mouse4", "Right Click")); + actions.set(0x04, [0x01, 0x01, 0x02]); + assert.equal((await client.readStatus()).razerButtonMappings?.mouse4, "Right Click"); +}); diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index d48b3d1e..0b471be3 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -335,6 +335,8 @@ export class RazerViperMiniHidClient { async setButtonMapping(control: RazerButtonControl, mapping: RazerButtonMapping): 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); @@ -343,7 +345,10 @@ export class RazerViperMiniHidClient { `The mouse kept ${confirmed ?? "an unrecognised mapping"} for ${RAZER_BUTTON_CONTROL_LABEL[control]} instead of ${mapping}.`, ); } - if (this.buttonMappingsKnown) this.buttonMappings = { ...this.buttonMappings, [control]: confirmed }; + if (known) { + this.buttonMappings = { ...this.buttonMappings, [control]: confirmed }; + this.buttonMappingsKnown = true; + } return confirmed; } @@ -355,6 +360,8 @@ 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); @@ -364,7 +371,10 @@ export class RazerViperMiniHidClient { `The mouse kept ${confirmed ? razerKeyLabel(confirmed) : "a mouse action"} for ${RAZER_BUTTON_CONTROL_LABEL[control]} instead of ${label}.`, ); } - if (this.buttonMappingsKnown) this.buttonMappings = { ...this.buttonMappings, [control]: label }; + if (known) { + this.buttonMappings = { ...this.buttonMappings, [control]: label }; + this.buttonMappingsKnown = true; + } return label; } From 383ba36add0aa13b8dfb7bc282e77b24a75034a8 Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 13:37:33 -0700 Subject: [PATCH 09/21] feat(razer): read and write the Viper Mini's Hypershift layer --- src/drivers/mouse-types.ts | 6 +++ src/drivers/razer/viper-mini-hid.test.ts | 52 ++++++++++++++++------ src/drivers/razer/viper-mini-hid.ts | 55 ++++++++++++++++++------ src/razer/codec.ts | 24 ++++++++--- 4 files changed, 103 insertions(+), 34 deletions(-) diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index 3319860f..4ee45c3b 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -503,6 +503,12 @@ export interface MouseStatus { * Hypershift because that write was verified on it. */ razerButtonOptions?: string[]; + /** + * The Hypershift layer's own assignments, same shape as + * `razerButtonMappings`. Absent when the firmware does not answer for that + * layer, in which case the layer has nothing to show and nothing to edit. + */ + razerHypershiftMappings?: Record; /** 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/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index 692b236e..c8ea1200 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -120,14 +120,18 @@ function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: n 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]], + // 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]], // The real mouse's bottom button ships as F24, not as a mouse action. - [0x60, [0x02, 0x02, 0x00, 0x73]], + ["0:96", [0x02, 0x02, 0x00, 0x73]], + // Hypershift layer starts empty on a factory mouse. + ["1:4", [0x00, 0x00, 0x00]], + ["1:5", [0x00, 0x00, 0x00]], ]); const device = { vendorId: 0x1532, @@ -165,17 +169,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. @@ -186,7 +191,7 @@ function fakeViperMini(options: { ignoreButtonWrites?: boolean; staleReplies?: n } if (read && wrongControls > 0) { wrongControls -= 1; - pending = replyPacket(commandClass, commandId, data[5], [data[8], 0x05, data[10], ...actions.get(0x05)!], RAZER_STATUS.ok); + pending = replyPacket(commandClass, commandId, data[5], [data[8], 0x05, data[10], ...(actions.get(`${data[10]}:5`) ?? [0x00, 0x00, 0x00])], RAZER_STATUS.ok); return; } pending = replyPacket(commandClass, commandId, data[5], [data[8], control, data[10], ...action], RAZER_STATUS.ok); @@ -256,7 +261,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 +309,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(); @@ -350,7 +355,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 +374,25 @@ 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 an empty Hypershift layer rather than hiding it", async () => { + const { client } = fakeViperMini(); + + const status = await client.readStatus(); + + assert.equal(status.razerHypershiftMappings?.mouse4, "Disabled"); + assert.equal(status.razerButtonMappings?.mouse4, "Mouse Button 4"); +}); diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index 0b471be3..91c712d0 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -3,6 +3,8 @@ 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, @@ -215,6 +217,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 = await this.readHypershiftMappings().catch(() => null); return { brand: "Razer", name: this.displayName(), @@ -242,6 +245,7 @@ export class RazerViperMiniHidClient { connectionDetail: "Wired USB", unitId: serial ? decodeSerial(serial) : null, razerButtonMappings: buttonMappings ?? undefined, + razerHypershiftMappings: hypershiftMappings ?? undefined, // Hypershift is included here and only here — see VIPER_MINI_BUTTON_MAPPINGS. razerButtonOptions: [...VIPER_MINI_BUTTON_MAPPINGS], liftOffDistance: null, @@ -287,16 +291,16 @@ 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; } - private async probeButtonMappings(): Promise<{ mappings: Record | null; complete: boolean }> { + private async probeButtonMappings(layer: number): Promise<{ mappings: Record | null; complete: boolean }> { 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) => { + const reply = await this.request(razerReadButtonMappingCommand(control, layer), VIPER_MINI_KEYMAP_TRANSACTION_ID).catch((error: unknown) => { if (!(error instanceof RazerProtocolError && error.status === RAZER_STATUS.unsupported)) complete = false; return null; }); @@ -316,36 +320,55 @@ export class RazerViperMiniHidClient { return { mappings: Object.keys(mappings).length > 0 ? mappings : null, complete }; } - /** Probes once, then trusts what `setButtonMapping` leaves behind. */ + /** + * 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(); + const { mappings, complete } = await this.probeButtonMappings(RAZER_STANDARD_LAYER); this.buttonMappings = mappings; this.buttonMappingsKnown = complete; } return this.buttonMappings; } + /** + * The Hypershift layer's own assignments, or null when the firmware does not + * answer for it. Read separately from the Standard layer because a binding + * only does something on this layer if the layer holds an action of its own. + */ + async readHypershiftMappings(): Promise | null> { + return await this.readButtonMappings(RAZER_HYPERSHIFT_LAYER); + } + /** * 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); + await this.request(razerSetButtonMappingCommand(control, mapping, layer), VIPER_MINI_KEYMAP_TRANSACTION_ID); + const reply = await this.request(razerReadButtonMappingCommand(control, layer), VIPER_MINI_KEYMAP_TRANSACTION_ID); const confirmed = razerDecodeButtonMapping(reply); 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; } @@ -359,11 +382,15 @@ export class RazerViperMiniHidClient { * * Returns the label the panel shows for the assignment (`Ctrl+F13`). */ - async setKeyboardMapping(control: RazerButtonControl, key: RazerKeyAction): Promise { + async setKeyboardMapping( + control: RazerButtonControl, + key: RazerKeyAction, + layer: number = RAZER_STANDARD_LAYER, + ): 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); + await this.request(razerSetKeyboardMappingCommand(control, key, layer), VIPER_MINI_KEYMAP_TRANSACTION_ID); + const reply = await this.request(razerReadButtonMappingCommand(control, layer), VIPER_MINI_KEYMAP_TRANSACTION_ID); const confirmed = razerDecodeKeyboardMapping(reply); const label = razerKeyLabel(key); if (!confirmed || confirmed.mods !== key.mods || confirmed.usage !== key.usage) { @@ -371,7 +398,7 @@ export class RazerViperMiniHidClient { `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; } diff --git a/src/razer/codec.ts b/src/razer/codec.ts index bd2869eb..5246703f 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"]; /** @@ -1004,8 +1008,8 @@ export function razerDecodeButtonMapping(args: Uint8Array): RazerButtonMapping | } /** 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 +1021,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 +1034,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 +1127,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,7 +1139,7 @@ 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], }; } From 3ca167f717cc20fdcc07e6870a786de23885cbd1 Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 13:50:43 -0700 Subject: [PATCH 10/21] fix(razer): probe the Viper Mini's controls one at a time so none go missing --- src/drivers/razer/viper-mini-hid.test.ts | 27 +++++++++++- src/drivers/razer/viper-mini-hid.ts | 54 +++++++++++++++++------- 2 files changed, 65 insertions(+), 16 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index c8ea1200..309798a1 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -114,12 +114,20 @@ 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; + // 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]], @@ -189,6 +197,11 @@ 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(`${data[10]}:5`) ?? [0x00, 0x00, 0x00])], RAZER_STATUS.ok); @@ -396,3 +409,15 @@ test("Viper Mini reports an empty Hypershift layer rather than hiding it", async assert.equal(status.razerHypershiftMappings?.mouse4, "Disabled"); assert.equal(status.razerButtonMappings?.mouse4, "Mouse Button 4"); }); + +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); +}); diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index 91c712d0..f56ba197 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -76,6 +76,8 @@ 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; const VIPER_MINI_LIGHTING_ZONE = "Logo"; @@ -295,31 +297,53 @@ export class RazerViperMiniHidClient { return (await this.probeButtonMappings(layer)).mappings; } + /** + * 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 }> { const mappings: Record = {}; let complete = true; - await Promise.all( - VIPER_MINI_BUTTON_CONTROLS.map(async (control) => { - const reply = await this.request(razerReadButtonMappingCommand(control, layer), 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); + const key = reply ? razerDecodeKeyboardMapping(reply) : null; if (key) mappings[control] = razerKeyLabel(key); - }), - ); + else complete = false; + } + await this.delay(PROBE_GAP_MS); + } return { mappings: Object.keys(mappings).length > 0 ? mappings : null, complete }; } + /** + * 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]; + for (let attempt = 0; attempt < 2; attempt += 1) { + const reply = await this.request(command, VIPER_MINI_KEYMAP_TRANSACTION_ID).catch(() => null); + if (reply && (expected === undefined || reply[1] === expected)) return reply; + } + return null; + } + /** * Probes once, then trusts what `setButtonMapping` leaves behind. * From 04b8468e1db6e6dd8385b72d2c55dfdb22793e1d Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 14:02:03 -0700 Subject: [PATCH 11/21] fix(razer): keep reading a control's own reply instead of dropping it --- src/drivers/razer/viper-mini-hid.test.ts | 12 +++++-- src/drivers/razer/viper-mini-hid.ts | 41 +++++++++++++++++------- 2 files changed, 39 insertions(+), 14 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index 309798a1..5807dba7 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -126,6 +126,9 @@ function fakeViperMini(options: { let staleLeft = options.staleReplies ?? 0; let staleAcks = options.staleWriteAcks ?? 0; let wrongControls = options.wrongControlReplies ?? 0; + // 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. @@ -204,15 +207,18 @@ function fakeViperMini(options: { } if (read && wrongControls > 0) { wrongControls -= 1; - pending = replyPacket(commandClass, commandId, data[5], [data[8], 0x05, data[10], ...(actions.get(`${data[10]}:5`) ?? [0x00, 0x00, 0x00])], 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 }; } diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index f56ba197..fa95536e 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -337,11 +337,15 @@ export class RazerViperMiniHidClient { private async readControlMapping(control: RazerButtonControl, layer: number): Promise { const command = razerReadButtonMappingCommand(control, layer); const expected = command.args?.[1]; - for (let attempt = 0; attempt < 2; attempt += 1) { - const reply = await this.request(command, VIPER_MINI_KEYMAP_TRANSACTION_ID).catch(() => null); - if (reply && (expected === undefined || reply[1] === expected)) return reply; - } - return null; + // 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. + return await this.request( + command, + VIPER_MINI_KEYMAP_TRANSACTION_ID, + false, + expected === undefined ? undefined : (packet) => packet[9] === expected, + ).catch(() => null); } /** @@ -483,10 +487,12 @@ 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, ): Promise { const run = this.queue.then( - () => this.exchange(command, transactionId, requireAck), - () => this.exchange(command, transactionId, requireAck), + () => this.exchange(command, transactionId, requireAck, accept), + () => this.exchange(command, transactionId, requireAck, accept), ); this.queue = run.catch(() => undefined); return await run; @@ -503,7 +509,12 @@ 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, + ): Promise { await this.open(); const request = encodeRazerRequest(command, transactionId); const getter = isRazerGetter(command); @@ -512,7 +523,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); 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 @@ -532,13 +543,21 @@ 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 { + private async awaitReply( + command: RazerCommand, + accept?: (packet: Uint8Array) => boolean, + ): Promise { for (let attempt = 0; attempt < RESPONSE_ATTEMPTS; attempt += 1) { await this.delay(RESPONSE_DELAY_MS); const reply = this.copyDataView(await this.device.receiveFeatureReport(RAZER_REPORT_ID)); try { const args = decodeRazerResponse(reply, command); - if (this.isMappingRead(command) && command.args?.some((byte, i) => args[i] !== byte)) return null; + // The class answers for every control, so a reply addressed to this + // command can still be the previous control's answer. Keep reading the + // same send — ours is queued behind it — instead of dropping the reply + // and leaving that control out of the map. + if (accept && !accept(reply)) continue; + if (this.isMappingRead(command) && command.args?.some((byte, i) => args[i] !== byte)) continue; return args; } catch (error) { if (!(error instanceof RazerProtocolError)) throw error; From 3cc67f103194bb4ba443a46b486c0c18fc4317ae Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 14:09:20 -0700 Subject: [PATCH 12/21] perf(razer): read the Viper Mini's keymap at the speed it actually answers --- src/drivers/razer/viper-mini-hid.ts | 61 ++++++++++++++++++++++------- 1 file changed, 47 insertions(+), 14 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index fa95536e..6471667c 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -78,6 +78,13 @@ const RESPONSE_ATTEMPTS = 6; const SEND_ATTEMPTS = 3; // Let the mouse finish one class `0x02` read before asking the next. const PROBE_GAP_MS = 20; +// Keymap reads answer in a few milliseconds, so waiting the shared 100 ms and +// giving up after six tries is what made a status read take seconds. +const KEYMAP_POLL_MS = 25; +const KEYMAP_ATTEMPTS = 14; +// 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"; @@ -159,6 +166,8 @@ export class RazerViperMiniHidClient { */ private buttonMappings: Record | null = null; private buttonMappingsKnown = false; + private hypershiftMappings: Record | null = null; + private hypershiftKnown = false; readonly device: HIDDevice; @@ -185,6 +194,8 @@ export class RazerViperMiniHidClient { this.staticReads.clear(); this.buttonMappings = null; this.buttonMappingsKnown = false; + this.hypershiftMappings = null; + this.hypershiftKnown = false; if (this.device.opened) await this.device.close(); } @@ -340,12 +351,18 @@ export class RazerViperMiniHidClient { // 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. - return await this.request( + const accept = expected === undefined ? undefined : (packet: Uint8Array) => packet[9] === expected; + const fast = await this.request( command, VIPER_MINI_KEYMAP_TRANSACTION_ID, false, - expected === undefined ? undefined : (packet) => packet[9] === expected, + 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); } /** @@ -356,10 +373,13 @@ export class RazerViperMiniHidClient { * caching the second case would hide a row for the rest of the session. */ private async currentButtonMappings(): Promise | null> { + // A probe now costs a few hundred milliseconds at most, so an incomplete + // one is retried on the next status read rather than cached with rows + // missing. A complete probe is kept for the session. if (!this.buttonMappingsKnown) { const { mappings, complete } = await this.probeButtonMappings(RAZER_STANDARD_LAYER); - this.buttonMappings = mappings; - this.buttonMappingsKnown = complete; + this.buttonMappings = mappings ?? this.buttonMappings; + this.buttonMappingsKnown = complete || Object.keys(mappings ?? {}).length >= VIPER_MINI_BUTTON_CONTROLS.length; } return this.buttonMappings; } @@ -370,7 +390,13 @@ export class RazerViperMiniHidClient { * only does something on this layer if the layer holds an action of its own. */ async readHypershiftMappings(): Promise | null> { - return await this.readButtonMappings(RAZER_HYPERSHIFT_LAYER); + // Read once and kept, like the Standard layer: six more reads on every + // status refresh is what made the panel feel slow. + if (!this.hypershiftKnown) { + this.hypershiftMappings = await this.readButtonMappings(RAZER_HYPERSHIFT_LAYER); + this.hypershiftKnown = this.hypershiftMappings !== null; + } + return this.hypershiftMappings; } /** @@ -389,8 +415,9 @@ export class RazerViperMiniHidClient { const known = this.buttonMappingsKnown; this.buttonMappingsKnown = false; await this.request(razerSetButtonMappingCommand(control, mapping, layer), VIPER_MINI_KEYMAP_TRANSACTION_ID); - const reply = await this.request(razerReadButtonMappingCommand(control, layer), VIPER_MINI_KEYMAP_TRANSACTION_ID); - const confirmed = razerDecodeButtonMapping(reply); + 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}.`, @@ -400,6 +427,7 @@ export class RazerViperMiniHidClient { this.buttonMappings = { ...this.buttonMappings, [control]: confirmed }; this.buttonMappingsKnown = true; } + if (layer === RAZER_HYPERSHIFT_LAYER) this.hypershiftKnown = false; return confirmed; } @@ -418,8 +446,9 @@ export class RazerViperMiniHidClient { const known = this.buttonMappingsKnown; this.buttonMappingsKnown = false; await this.request(razerSetKeyboardMappingCommand(control, key, layer), VIPER_MINI_KEYMAP_TRANSACTION_ID); - const reply = await this.request(razerReadButtonMappingCommand(control, layer), VIPER_MINI_KEYMAP_TRANSACTION_ID); - const confirmed = razerDecodeKeyboardMapping(reply); + 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( @@ -430,6 +459,7 @@ export class RazerViperMiniHidClient { this.buttonMappings = { ...this.buttonMappings, [control]: label }; this.buttonMappingsKnown = true; } + if (layer === RAZER_HYPERSHIFT_LAYER) this.hypershiftKnown = false; return label; } @@ -489,10 +519,11 @@ export class RazerViperMiniHidClient { 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, accept), - () => this.exchange(command, transactionId, requireAck, accept), + () => this.exchange(command, transactionId, requireAck, accept, timing), + () => this.exchange(command, transactionId, requireAck, accept, timing), ); this.queue = run.catch(() => undefined); return await run; @@ -514,6 +545,7 @@ export class RazerViperMiniHidClient { 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); @@ -523,7 +555,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, accept); + 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 @@ -546,9 +578,10 @@ export class RazerViperMiniHidClient { 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 < RESPONSE_ATTEMPTS; attempt += 1) { - await this.delay(RESPONSE_DELAY_MS); + 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); From 47313a25a331eafee7deb4ae8194021a621e96bc Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 14:27:54 -0700 Subject: [PATCH 13/21] fix(razer): fill missing controls a couple at a time instead of re-probing --- src/drivers/razer/viper-mini-hid.ts | 30 ++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index 6471667c..2ea576b9 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -78,10 +78,14 @@ const RESPONSE_ATTEMPTS = 6; const SEND_ATTEMPTS = 3; // Let the mouse finish one class `0x02` read before asking the next. const PROBE_GAP_MS = 20; -// Keymap reads answer in a few milliseconds, so waiting the shared 100 ms and -// giving up after six tries is what made a status read take seconds. -const KEYMAP_POLL_MS = 25; -const KEYMAP_ATTEMPTS = 14; +// 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; @@ -373,13 +377,25 @@ export class RazerViperMiniHidClient { * caching the second case would hide a row for the rest of the session. */ private async currentButtonMappings(): Promise | null> { - // A probe now costs a few hundred milliseconds at most, so an incomplete - // one is retried on the next status read rather than cached with rows - // missing. A complete probe is kept for the session. if (!this.buttonMappingsKnown) { 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; } From d3fea07d6a16fe92d6b213a66beeeb7bf3829a2e Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 14:38:40 -0700 Subject: [PATCH 14/21] fix(razer): only one Viper Mini probe at a time --- src/drivers/razer/viper-mini-hid.test.ts | 12 +++++++++ src/drivers/razer/viper-mini-hid.ts | 32 ++++++++++++++++++++---- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index 5807dba7..e0339de0 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -427,3 +427,15 @@ test("Viper Mini re-probes the controls a read missed", async () => { 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); +}); diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index 2ea576b9..3f7a1b86 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -172,6 +172,13 @@ export class RazerViperMiniHidClient { private buttonMappingsKnown = false; private hypershiftMappings: Record | null = null; private hypershiftKnown = false; + /** + * 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; @@ -342,6 +349,17 @@ export class RazerViperMiniHidClient { return { mappings: Object.keys(mappings).length > 0 ? mappings : null, complete }; } + /** 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. * @@ -378,9 +396,11 @@ export class RazerViperMiniHidClient { */ private async currentButtonMappings(): Promise | null> { if (!this.buttonMappingsKnown) { - 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; + 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. @@ -409,8 +429,10 @@ export class RazerViperMiniHidClient { // Read once and kept, like the Standard layer: six more reads on every // status refresh is what made the panel feel slow. if (!this.hypershiftKnown) { - this.hypershiftMappings = await this.readButtonMappings(RAZER_HYPERSHIFT_LAYER); - this.hypershiftKnown = this.hypershiftMappings !== null; + await this.probeOnce(async () => { + this.hypershiftMappings = await this.readButtonMappings(RAZER_HYPERSHIFT_LAYER); + this.hypershiftKnown = this.hypershiftMappings !== null; + }); } return this.hypershiftMappings; } From 481d06779c5be278a5b17ca902ba8c038c11ccbe Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 14:46:01 -0700 Subject: [PATCH 15/21] fix(razer): re-send instead of re-polling when the Viper Mini answers another control --- src/drivers/razer/viper-mini-hid.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index 3f7a1b86..fc38dc71 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -624,11 +624,12 @@ export class RazerViperMiniHidClient { 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. Keep reading the - // same send — ours is queued behind it — instead of dropping the reply - // and leaving that control out of the map. - if (accept && !accept(reply)) continue; - if (this.isMappingRead(command) && command.args?.some((byte, i) => args[i] !== byte)) continue; + // 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) { if (!(error instanceof RazerProtocolError)) throw error; From beb53354c52f9f6b7b23c97c15d4222dbb51003d Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 14:52:56 -0700 Subject: [PATCH 16/21] fix(razer): name the bottom button's factory DPI action on the Viper Mini --- src/drivers/razer/viper-mini-hid.test.ts | 28 ++++++++++++++++++++---- src/drivers/razer/viper-mini-hid.ts | 12 ++++++++-- src/razer/codec.ts | 18 +++++++++++++++ 3 files changed, 52 insertions(+), 6 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index e0339de0..6ec7995e 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -138,8 +138,8 @@ function fakeViperMini(options: { ["0:2", [0x01, 0x01, 0x02]], ["0:4", [0x01, 0x01, 0x04]], ["0:5", [0x01, 0x01, 0x05]], - // The real mouse's bottom button ships as F24, not as a mouse action. - ["0:96", [0x02, 0x02, 0x00, 0x73]], + // 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]], @@ -247,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 Cycle Up", }); assert.ok(status.razerButtonOptions?.includes("Hypershift")); assert.ok(status.razerButtonOptions?.includes("Middle Click")); @@ -354,7 +354,7 @@ const ALL_DEFAULT_MAPPINGS = { rightClick: "Right Click", mouse4: "Mouse Button 4", mouse5: "Mouse Button 5", - dpiButton: "F24", + dpiButton: "DPI Cycle Up", }; test("Viper Mini ignores a mapping reply that echoes another control", async () => { @@ -439,3 +439,23 @@ test("Viper Mini reports every control when status is read twice at once", async 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 Cycle Up"); +}); + +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 fc38dc71..5e7b0ee2 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -21,6 +21,7 @@ import { encodeRazerRequest, isRazerGetter, razerDecodeButtonMapping, + razerDecodeDpiAction, razerDecodeKeyboardMapping, razerKeyLabel, razerReadButtonMappingCommand, @@ -341,8 +342,15 @@ export class RazerViperMiniHidClient { // decoder reports as unknown. Reading it here keeps the row in the // panel instead of silently dropping the control from the card. const key = reply ? razerDecodeKeyboardMapping(reply) : null; - if (key) mappings[control] = razerKeyLabel(key); - else complete = false; + 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); } diff --git a/src/razer/codec.ts b/src/razer/codec.ts index 5246703f..e58a3edc 100644 --- a/src/razer/codec.ts +++ b/src/razer/codec.ts @@ -1143,6 +1143,24 @@ export function razerSetKeyboardMappingCommand( }; } +/** + * 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", + 0x06: "DPI Cycle Up", + 0x07: "DPI Cycle Down", +}; + +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 From f34080636563aa1bafbeeb6aab7bd49c16e9bce7 Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 15:06:54 -0700 Subject: [PATCH 17/21] fix(razer): call the wraparound DPI steps what they are --- src/drivers/razer/viper-mini-hid.test.ts | 6 +++--- src/razer/codec.ts | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index 6ec7995e..1a439c40 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -247,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: "DPI Cycle Up", + dpiButton: "DPI Up Wrap", }); assert.ok(status.razerButtonOptions?.includes("Hypershift")); assert.ok(status.razerButtonOptions?.includes("Middle Click")); @@ -354,7 +354,7 @@ const ALL_DEFAULT_MAPPINGS = { rightClick: "Right Click", mouse4: "Mouse Button 4", mouse5: "Mouse Button 5", - dpiButton: "DPI Cycle Up", + dpiButton: "DPI Up Wrap", }; test("Viper Mini ignores a mapping reply that echoes another control", async () => { @@ -448,7 +448,7 @@ test("Viper Mini names the bottom button's factory DPI action", async () => { const status = await client.readStatus(); - assert.equal(status.razerButtonMappings?.dpiButton, "DPI Cycle Up"); + assert.equal(status.razerButtonMappings?.dpiButton, "DPI Up Wrap"); }); test("Viper Mini still reports a keyboard key left on the bottom button", async () => { diff --git a/src/razer/codec.ts b/src/razer/codec.ts index e58a3edc..95ac51cc 100644 --- a/src/razer/codec.ts +++ b/src/razer/codec.ts @@ -1152,8 +1152,10 @@ export function razerSetKeyboardMappingCommand( const RAZER_DPI_ACTION_LABELS: Readonly> = { 0x01: "DPI Up", 0x02: "DPI Down", - 0x06: "DPI Cycle Up", - 0x07: "DPI Cycle 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 { From bb0f4763a7f2baa952a2ed171eb15f9c16eb8f35 Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 15:29:22 -0700 Subject: [PATCH 18/21] feat(razer): read the Viper Mini keymap in one table read --- src/drivers/razer/protocol.test.ts | 43 +++++++++++++++++++++ src/drivers/razer/viper-mini-hid.ts | 32 ++++++++++++++++ src/razer/codec.ts | 59 +++++++++++++++++++++++++++++ 3 files changed, 134 insertions(+) diff --git a/src/drivers/razer/protocol.test.ts b/src/drivers/razer/protocol.test.ts index a624fef3..4c9c2f07 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,45 @@ 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); + + 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 an unknown shape", () => { + const bytes = 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(bytes, 0x01, 0x00); + assert.equal(table?.get(0x02), "F13"); + assert.equal(table?.get(0x03), "F14"); + + // A record whose third byte does not repeat the control is not this layout. + const broken = Uint8Array.from([0x01,0x04,0x00, 0x01,0x01,0,0,0,0, 0x02,0x01,0x07,0x02,0,0,0,0, 0xc1]); + assert.equal(razerDecodeKeymapTable(broken, 0x01, 0x00), null); +}); diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index 5e7b0ee2..f5f94980 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -9,6 +9,7 @@ import { VIPER_MINI_BUTTON_MAPPINGS, RAZER_READ, RAZER_REPORT_ID, + RAZER_STORAGE, RAZER_STATUS, RAZER_TRANSACTION_ID_1F, RAZER_TRANSACTION_ID_3F, @@ -24,7 +25,10 @@ import { razerDecodeDpiAction, razerDecodeKeyboardMapping, razerKeyLabel, + razerButtonControlIndex, + razerDecodeKeymapTable, razerReadButtonMappingCommand, + razerReadKeymapTableCommand, razerSetButtonMappingCommand, razerSetKeyboardMappingCommand, razerSetDpiCommand, @@ -320,6 +324,21 @@ export class RazerViperMiniHidClient { 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; + } + /** * Reads every control one at a time, with a short gap between them. * @@ -330,6 +349,19 @@ export class RazerViperMiniHidClient { * 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; for (const control of VIPER_MINI_BUTTON_CONTROLS) { diff --git a/src/razer/codec.ts b/src/razer/codec.ts index 95ac51cc..8357be8f 100644 --- a/src/razer/codec.ts +++ b/src/razer/codec.ts @@ -911,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, @@ -1007,6 +1012,60 @@ 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] }; +} + +export function razerDecodeKeymapTable( + args: Uint8Array, + profile: number = RAZER_STORAGE, + layer: number = RAZER_STANDARD_LAYER, +): Map | null { + const TABLE_START = 9; + const RECORD_LENGTH = 8; + if (args.length < TABLE_START + RECORD_LENGTH) return null; + const table = new Map(); + for (let at = TABLE_START; at + RECORD_LENGTH <= args.length - 1; at += RECORD_LENGTH) { + const control = args[at]!; + const type = args[at + 1]!; + const echo = args[at + 2]!; + if (echo !== control) return null; + const a = args[at + 3]!; + const b = args[at + 4]!; + const action = new Uint8Array(8); + action[0] = profile; + action[1] = control; + action[2] = layer; + action[3] = type; + action[4] = type === 0x02 ? 0x02 : type === 0x0c ? 0x01 : 0x01; + action[5] = a; + action[6] = b; + const mapping = razerDecodeButtonMapping(action); + const key = mapping ? null : razerDecodeKeyboardMapping(action); + const label = mapping ?? (key ? razerKeyLabel(key) : razerDecodeDpiAction(action)); + if (label) table.set(control, label); + } + return table.size > 0 ? table : null; +} + /** Only the Standard layer is trusted for reads — see `RAZER_READ.buttonMapping`. */ export function razerReadButtonMappingCommand(control: RazerButtonControl, layer: number = RAZER_STANDARD_LAYER): RazerCommand { return { ...RAZER_READ.buttonMapping, args: [0x01, RAZER_BUTTON_CONTROL_INDEX[control], layer] }; From 9dc87d1197ccec56a2474be7766631281d4bb993 Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 15:40:05 -0700 Subject: [PATCH 19/21] fix(razer): anchor the keymap table where this driver's own request puts it --- src/drivers/razer/protocol.test.ts | 45 ++++++++++++++++++++++++------ src/razer/codec.ts | 35 +++++++++++++++-------- 2 files changed, 60 insertions(+), 20 deletions(-) diff --git a/src/drivers/razer/protocol.test.ts b/src/drivers/razer/protocol.test.ts index 4c9c2f07..7d2b11da 100644 --- a/src/drivers/razer/protocol.test.ts +++ b/src/drivers/razer/protocol.test.ts @@ -992,7 +992,7 @@ test("the keymap table decodes a captured Viper Mini reply", () => { 0xa2, ]); - const table = razerDecodeKeymapTable(bytes, 0x01, 0x00); + const table = razerDecodeKeymapTable(bytes, 0x01, 0x00, 9); assert.ok(table); assert.equal(table.get(0x02), "Right Click"); @@ -1002,19 +1002,48 @@ test("the keymap table decodes a captured Viper Mini reply", () => { assert.equal(table.get(0x60), "Hypershift"); }); -test("the keymap table carries keyboard keys and refuses an unknown shape", () => { - const bytes = Uint8Array.from([ +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(bytes, 0x01, 0x00); + const table = razerDecodeKeymapTable(keys, 0x01, 0x00, 9); assert.equal(table?.get(0x02), "F13"); assert.equal(table?.get(0x03), "F14"); - // A record whose third byte does not repeat the control is not this layout. - const broken = Uint8Array.from([0x01,0x04,0x00, 0x01,0x01,0,0,0,0, 0x02,0x01,0x07,0x02,0,0,0,0, 0xc1]); - assert.equal(razerDecodeKeymapTable(broken, 0x01, 0x00), null); + // 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/razer/codec.ts b/src/razer/codec.ts index 8357be8f..af893083 100644 --- a/src/razer/codec.ts +++ b/src/razer/codec.ts @@ -1034,36 +1034,47 @@ export function razerReadKeymapTableCommand( 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 TABLE_START = 9; const RECORD_LENGTH = 8; - if (args.length < TABLE_START + RECORD_LENGTH) return null; + if (args.length < tableStart + RECORD_LENGTH) return null; const table = new Map(); - for (let at = TABLE_START; at + RECORD_LENGTH <= args.length - 1; at += RECORD_LENGTH) { + 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]!; - const echo = args[at + 2]!; - if (echo !== control) return null; - const a = args[at + 3]!; - const b = args[at + 4]!; + 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 : type === 0x0c ? 0x01 : 0x01; - action[5] = a; - action[6] = b; + 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.set(control, label); + if (label && !table.has(control)) table.set(control, label); + seen += 1; } - return table.size > 0 ? table : null; + return seen >= 2 && table.size > 0 ? table : null; } /** Only the Standard layer is trusted for reads — see `RAZER_READ.buttonMapping`. */ From 01cde9494e5b76be2875948e30156328a5fc59af Mon Sep 17 00:00:00 2001 From: OpenMouse Bot Date: Fri, 4 Dec 2026 15:56:40 -0700 Subject: [PATCH 20/21] fix(razer): never present a Hypershift read as the layer's contents --- src/drivers/mouse-types.ts | 10 +++++--- src/drivers/razer/viper-mini-hid.test.ts | 16 +++++++++---- src/drivers/razer/viper-mini-hid.ts | 29 +++++++++++++----------- 3 files changed, 35 insertions(+), 20 deletions(-) diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index 4ee45c3b..6fcd7bd0 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -504,11 +504,15 @@ export interface MouseStatus { */ razerButtonOptions?: string[]; /** - * The Hypershift layer's own assignments, same shape as - * `razerButtonMappings`. Absent when the firmware does not answer for that - * layer, in which case the layer has nothing to show and nothing to edit. + * 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/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index 1a439c40..5635a84b 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -407,13 +407,21 @@ test("Viper Mini writes and reads the Hypershift layer separately", async () => assert.equal((await client.readStatus()).razerHypershiftMappings?.mouse4, "Middle Click"); }); -test("Viper Mini reports an empty Hypershift layer rather than hiding it", async () => { +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 status = await client.readStatus(); + const untouched = await client.readStatus(); + assert.equal(untouched.razerHypershiftMappings, undefined); + assert.equal(untouched.razerHypershiftWritable, true); - assert.equal(status.razerHypershiftMappings?.mouse4, "Disabled"); - assert.equal(status.razerButtonMappings?.mouse4, "Mouse Button 4"); + 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 re-probes the controls a read missed", async () => { diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index f5f94980..8545859a 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -176,7 +176,6 @@ export class RazerViperMiniHidClient { private buttonMappings: Record | null = null; private buttonMappingsKnown = false; private hypershiftMappings: Record | null = null; - private hypershiftKnown = false; /** * 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 — @@ -211,7 +210,6 @@ export class RazerViperMiniHidClient { this.buttonMappings = null; this.buttonMappingsKnown = false; this.hypershiftMappings = null; - this.hypershiftKnown = false; if (this.device.opened) await this.device.close(); } @@ -246,7 +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 = await this.readHypershiftMappings().catch(() => null); + const hypershiftMappings = this.hypershiftMappings; return { brand: "Razer", name: this.displayName(), @@ -275,6 +273,7 @@ export class RazerViperMiniHidClient { 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, @@ -465,15 +464,15 @@ export class RazerViperMiniHidClient { * answer for it. Read separately from the Standard layer because a binding * only does something on this layer if the layer holds an action of its own. */ + /** + * 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> { - // Read once and kept, like the Standard layer: six more reads on every - // status refresh is what made the panel feel slow. - if (!this.hypershiftKnown) { - await this.probeOnce(async () => { - this.hypershiftMappings = await this.readButtonMappings(RAZER_HYPERSHIFT_LAYER); - this.hypershiftKnown = this.hypershiftMappings !== null; - }); - } return this.hypershiftMappings; } @@ -505,7 +504,9 @@ export class RazerViperMiniHidClient { this.buttonMappings = { ...this.buttonMappings, [control]: confirmed }; this.buttonMappingsKnown = true; } - if (layer === RAZER_HYPERSHIFT_LAYER) this.hypershiftKnown = false; + if (layer === RAZER_HYPERSHIFT_LAYER) { + this.hypershiftMappings = { ...this.hypershiftMappings, [control]: confirmed }; + } return confirmed; } @@ -537,7 +538,9 @@ export class RazerViperMiniHidClient { this.buttonMappings = { ...this.buttonMappings, [control]: label }; this.buttonMappingsKnown = true; } - if (layer === RAZER_HYPERSHIFT_LAYER) this.hypershiftKnown = false; + if (layer === RAZER_HYPERSHIFT_LAYER) { + this.hypershiftMappings = { ...this.hypershiftMappings, [control]: label }; + } return label; } From df4b791afb6fbc5177a6c12e549130af55d143f2 Mon Sep 17 00:00:00 2001 From: Onyx Date: Sat, 5 Dec 2026 20:46:58 +0100 Subject: [PATCH 21/21] fix(razer): a Hypershift write keeps the Standard mapping cache The firmware answers a class 0x02 read with whichever layer was written last, so dropping the Standard cache after a Hypershift write made the next refresh read Hypershift values into the Standard card. Only a Standard write clears it now. A Hypershift write drops that control's remembered entry first, so a write that fails its read-back no longer leaves the old action on show. --- src/drivers/razer/viper-mini-hid.test.ts | 14 ++++++++++++++ src/drivers/razer/viper-mini-hid.ts | 22 +++++++++++++--------- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/src/drivers/razer/viper-mini-hid.test.ts b/src/drivers/razer/viper-mini-hid.test.ts index 5635a84b..2c8265e5 100644 --- a/src/drivers/razer/viper-mini-hid.test.ts +++ b/src/drivers/razer/viper-mini-hid.test.ts @@ -424,6 +424,20 @@ test("Viper Mini reports only what it wrote to the Hypershift layer", async () = 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. diff --git a/src/drivers/razer/viper-mini-hid.ts b/src/drivers/razer/viper-mini-hid.ts index 8545859a..9ce36a9a 100644 --- a/src/drivers/razer/viper-mini-hid.ts +++ b/src/drivers/razer/viper-mini-hid.ts @@ -459,11 +459,6 @@ export class RazerViperMiniHidClient { return this.buttonMappings; } - /** - * The Hypershift layer's own assignments, or null when the firmware does not - * answer for it. Read separately from the Standard layer because a binding - * only does something on this layer if the layer holds an action of its own. - */ /** * What this session has written to the Hypershift layer — never a read. * @@ -476,6 +471,17 @@ export class RazerViperMiniHidClient { 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 @@ -489,8 +495,7 @@ export class RazerViperMiniHidClient { ): 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; + 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); @@ -522,8 +527,7 @@ export class RazerViperMiniHidClient { key: RazerKeyAction, layer: number = RAZER_STANDARD_LAYER, ): Promise { - const known = this.buttonMappingsKnown; - this.buttonMappingsKnown = false; + 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);