diff --git a/package.json b/package.json index a360811..5890ed6 100644 --- a/package.json +++ b/package.json @@ -257,6 +257,10 @@ "./roccat": { "types": "./dist/roccat/index.d.ts", "import": "./dist/roccat/index.js" + }, + "./xiaomi": { + "types": "./dist/xiaomi/index.d.ts", + "import": "./dist/xiaomi/index.js" } }, "scripts": { diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index 78bb6c0..8f05d38 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -208,7 +208,7 @@ export interface MagneticCalibrationProgress { } export interface MouseStatus { - brand: "RAWM" | "Motospeed" | "Logitech" | "Pulsar" | "Endgame Gear" | "WLMouse" | "G-Wolves" | "Lamzu" | "CRDRAKO" | "Attack Shark" | "LunaFury" | "Vancer" | "Orbital" | "Razer" | "Teevolution" | "ATK" | "VXE" | "VGN" | "VAXEE" | "Finalmouse" | "Keychron" | "moddoMOUSE" | "Ninjutso" | "Zaunkoenig" | "Fantech" | "Wooting" | "WALLHACK" | "SteelSeries" | "Glorious" | "MCHOSE" | "K-snake" | "Noir Gear" | "Lingbao" | "GearHub" | "AJAZZ" | "Corsair" | "Microsoft" | "Dareu" | "Redragon" | "Incott" | "HyperX" | "ASUS" | "Ryunix" | "Amkette" | "Delux" | "GravaStar" | "IPI" | "Rapoo" | "Fater" | "Cooler Master" | "AJAZZ" | "Scyrox" | "Hitscan" | "ROCCAT" | "Thermaltake" | "Redgear" | "AULA"; + brand: "RAWM" | "Motospeed" | "Logitech" | "Pulsar" | "Endgame Gear" | "WLMouse" | "G-Wolves" | "Lamzu" | "CRDRAKO" | "Attack Shark" | "LunaFury" | "Vancer" | "Orbital" | "Razer" | "Teevolution" | "ATK" | "VXE" | "VGN" | "VAXEE" | "Finalmouse" | "Keychron" | "moddoMOUSE" | "Ninjutso" | "Zaunkoenig" | "Fantech" | "Wooting" | "WALLHACK" | "SteelSeries" | "Glorious" | "MCHOSE" | "K-snake" | "Noir Gear" | "Lingbao" | "GearHub" | "AJAZZ" | "Corsair" | "Microsoft" | "Dareu" | "Redragon" | "Incott" | "HyperX" | "ASUS" | "Ryunix" | "Amkette" | "Delux" | "GravaStar" | "IPI" | "Rapoo" | "Fater" | "Cooler Master" | "AJAZZ" | "Scyrox" | "Hitscan" | "ROCCAT" | "Thermaltake" | "Redgear" | "AULA" | "Xiaomi"; name: string; /** Optional LunaFury controls, populated only after successful device reads. */ lunafury?: import("../lamzu/lunafury.js").LunaFurySettings; diff --git a/src/drivers/registry.ts b/src/drivers/registry.ts index a245b65..7af142d 100644 --- a/src/drivers/registry.ts +++ b/src/drivers/registry.ts @@ -104,9 +104,10 @@ import { AjazzAk820HidClient } from "./ajazz/ak820-hid.ts"; import { RoccatHidClient } from "./roccat/hid.ts"; import { HitscanHidClient } from "./hitscan/hid.ts"; import { HitscanXviHidClient } from "./hitscan/xvi-hid.ts"; +import { XiaomiHidClient } from "./xiaomi/hid.ts"; export type PulsarClient = PulsarHidClient | PulsarProHidClient | PulsarXs1HidClient; -export type SupportedClient = RawmHidClient | MotospeedHidClient | LogitechHidppClient | PulsarClient | EggOp1HidClient | EggOtHidClient | EggWeHidClient | FinalmouseHidClient | WLMouseHidClient | WLMouseBeastX4kHidClient | LamzuHidClient | LamzuAtlantisHidClient | OrbitalHidClient | RazerHidClient | RazerViperHidClient | RazerViperMiniHidClient | RazerViperV4ProHidClient | RazerCobraHidClient | TeevolutionHidClient | AtkHidClient | AtkBitmouseHidClient | VgnF2HidClient | VaxeeHidClient | Keychron8kHidClient | Keychron1kHidClient | Keychron4kHidClient | Keychron8kNordicHidClient | KeychronNapeHidClient | ModdoHidClient | NinjutsoHidClient | ZaunkoenigHidClient | CorsairHidClient | CorsairBragiHidClient | AttackSharkHidClient | FantechHidClient | GearHubHidClient | WootingHidClient | WallhackMouseHidClient | WallhackKeyboardHidClient | GWolvesHidClient | GWolvesXviHidClient | GWolvesXviNewHidClient | SteelSeriesRival3HidClient | SteelSeriesAerox3HidClient | SteelSeriesAerox3WirelessHidClient | SteelSeriesRival3WirelessHidClient | SteelSeriesAerox5HidClient | SteelSeriesAerox5WirelessHidClient | SteelSeriesRival650HidClient | SteelSeriesAerox9WirelessHidClient | SteelSeriesRival310HidClient | SteelSeriesPrimePlusHidClient | SteelSeriesPrimeMiniWirelessHidClient | SteelSeriesSenseiTenHidClient | SteelSeriesSenseiRivalProHidClient | SteelSeriesSensei310HidClient | SteelSeriesPrimeMiniHidClient | SteelSeriesRival5HidClient | SteelSeriesRival3Gen2HidClient | SteelSeriesRival3WirelessV2HidClient | SteelSeriesAerox3WirelessGen2HidClient | SteelSeriesRival600HidClient | SteelSeriesRival100HidClient | SteelSeriesRival110HidClient | SteelSeriesRival300HidClient | SteelSeriesSenseiRawHidClient | GloriousHidClient | GloriousClassicHidClient | GloriousCore2HidClient | GloriousSinowealthHidClient | MchoseHidClient | MchoseDockHidClient | MchoseA5ProMaxHidClient | KsnakeHidClient | MicrosoftHidClient | DareuHidClient | RedragonHidClient | RedragonM690ProHidClient | RedragonM719ProHidClient | IncottHidClient | HyperXHidClient | MchoseV3HidClient | AsusHidClient | KyuProMx1Client | AmketteXsHidClient | DeluxHidClient | BytechHidClient | RapooHidClient | FaterHidClient | CoolerMasterHidClient | AjazzHidClient | AjazzAj200pHidClient | AjazzAk820HidClient | ScyroxHidClient | HitscanHidClient | RoccatHidClient | ThermaltakeHidClient | RedgearX13HidClient | AulaSc380ProHidClient; +export type SupportedClient = RawmHidClient | MotospeedHidClient | LogitechHidppClient | PulsarClient | EggOp1HidClient | EggOtHidClient | EggWeHidClient | FinalmouseHidClient | WLMouseHidClient | WLMouseBeastX4kHidClient | LamzuHidClient | LamzuAtlantisHidClient | OrbitalHidClient | RazerHidClient | RazerViperHidClient | RazerViperMiniHidClient | RazerViperV4ProHidClient | RazerCobraHidClient | TeevolutionHidClient | AtkHidClient | AtkBitmouseHidClient | VgnF2HidClient | VaxeeHidClient | Keychron8kHidClient | Keychron1kHidClient | Keychron4kHidClient | Keychron8kNordicHidClient | KeychronNapeHidClient | ModdoHidClient | NinjutsoHidClient | ZaunkoenigHidClient | CorsairHidClient | CorsairBragiHidClient | AttackSharkHidClient | FantechHidClient | GearHubHidClient | WootingHidClient | WallhackMouseHidClient | WallhackKeyboardHidClient | GWolvesHidClient | GWolvesXviHidClient | GWolvesXviNewHidClient | SteelSeriesRival3HidClient | SteelSeriesAerox3HidClient | SteelSeriesAerox3WirelessHidClient | SteelSeriesRival3WirelessHidClient | SteelSeriesAerox5HidClient | SteelSeriesAerox5WirelessHidClient | SteelSeriesRival650HidClient | SteelSeriesAerox9WirelessHidClient | SteelSeriesRival310HidClient | SteelSeriesPrimePlusHidClient | SteelSeriesPrimeMiniWirelessHidClient | SteelSeriesSenseiTenHidClient | SteelSeriesSenseiRivalProHidClient | SteelSeriesSensei310HidClient | SteelSeriesPrimeMiniHidClient | SteelSeriesRival5HidClient | SteelSeriesRival3Gen2HidClient | SteelSeriesRival3WirelessV2HidClient | SteelSeriesAerox3WirelessGen2HidClient | SteelSeriesRival600HidClient | SteelSeriesRival100HidClient | SteelSeriesRival110HidClient | SteelSeriesRival300HidClient | SteelSeriesSenseiRawHidClient | GloriousHidClient | GloriousClassicHidClient | GloriousCore2HidClient | GloriousSinowealthHidClient | MchoseHidClient | MchoseDockHidClient | MchoseA5ProMaxHidClient | KsnakeHidClient | MicrosoftHidClient | DareuHidClient | RedragonHidClient | RedragonM690ProHidClient | RedragonM719ProHidClient | IncottHidClient | HyperXHidClient | MchoseV3HidClient | AsusHidClient | KyuProMx1Client | AmketteXsHidClient | DeluxHidClient | BytechHidClient | RapooHidClient | FaterHidClient | CoolerMasterHidClient | AjazzHidClient | AjazzAj200pHidClient | AjazzAk820HidClient | ScyroxHidClient | HitscanHidClient | RoccatHidClient | ThermaltakeHidClient | RedgearX13HidClient | AulaSc380ProHidClient | XiaomiHidClient; export interface DeviceDriver { brand: string; supports(device: HIDDevice): boolean; @@ -266,6 +267,10 @@ export const DEVICE_DRIVERS: readonly DeviceDriver[] = [ // Windows hides the config collection; the mouse interface still switches // profiles, and the keyboard interface alone is status only. { brand: "Thermaltake", supports: (device) => ThermaltakeHidClient.isSupported(device), create: (device) => new ThermaltakeHidClient(device), score: (device) => THERMALTAKE_CHANNEL_SCORE[thermaltakeChannel(device) ?? "none"] }, + // Xiaomi owns vendor id 0x2717, which no other driver claims. No HID + // descriptor has been captured, so the driver selects its collection by + // shape (any collection with both input and output reports). + { brand: "Xiaomi", supports: (device) => XiaomiHidClient.isSupported(device), create: (device) => new XiaomiHidClient(device), score: () => 7 }, ]; const THERMALTAKE_CHANNEL_SCORE = { config: 7, short: 5, none: 2 } as const; diff --git a/src/drivers/vendors.ts b/src/drivers/vendors.ts index a2a9e36..7f3f143 100644 --- a/src/drivers/vendors.ts +++ b/src/drivers/vendors.ts @@ -254,6 +254,7 @@ export const VENDOR_ID = { hitscan: HITSCAN_VENDOR_ID, roccat: ROCCAT_VENDOR_ID, thermaltake: THERMALTAKE_VENDOR_ID, + xiaomi: 0x2717, } as const; /** @@ -977,6 +978,17 @@ export const VAXEE_HID_FILTERS: HIDDeviceFilter[] = VAXEE_PRODUCT_IDS.map((produ vendorId: VAXEE_VENDOR_ID, productId, usagePage: VAXEE_USAGE_PAGE, usage: VAXEE_USAGE, })); +/** + * Xiaomi Mi Gaming Mouse, wired (0x5009) and wireless (0x500b). No HID + * descriptor has been captured, so the usage page is unknown; the driver + * selects its collection by shape (any collection with input and output + * reports). + */ +export const XIAOMI_HID_FILTERS: HIDDeviceFilter[] = [0x5009, 0x500b].map((productId) => ({ + vendorId: VENDOR_ID.xiaomi, + productId, +})); + export const SUPPORTED_HID_FILTERS: HIDDeviceFilter[] = [ { vendorId: SC380_PRO_VENDOR_ID, @@ -1130,4 +1142,5 @@ export const SUPPORTED_HID_FILTERS: HIDDeviceFilter[] = [ // 64-byte feature report 0 for control.hitscan.com). ...[...new Set([...HITSCAN_PRODUCTS.keys(), ...HITSCAN_XVI_PRODUCTS.keys()])] .map((productId) => ({ vendorId: VENDOR_ID.hitscan, productId })), + ...XIAOMI_HID_FILTERS, ]; diff --git a/src/drivers/xiaomi/hid.test.ts b/src/drivers/xiaomi/hid.test.ts new file mode 100644 index 0000000..486bc1e --- /dev/null +++ b/src/drivers/xiaomi/hid.test.ts @@ -0,0 +1,403 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { XiaomiHidClient } from "./hid.ts"; +import { + XIAOMI_BUTTON_ACTIONS, + XIAOMI_BUTTON_NAMES, + XIAOMI_KEY_COMBOS, + XIAOMI_MACRO_PACKET_SIZE, + XIAOMI_MACRO_REPORT_DATA_SIZE, + XIAOMI_MACRO_REPORT_ID, + XIAOMI_PACKET_SIZE, + XIAOMI_REPORT_DATA_SIZE, + XIAOMI_REPORT_ID, + xiaomiDecodeDpi, + xiaomiDecodeLighting, + xiaomiDecodePolling, + type XiaomiMacroEvent, +} from "@openmouse/protocol/xiaomi"; + +/** Builds a 32-byte reply echoing the header and command byte. */ +function reply(...bytes: number[]): Uint8Array { + const data = new Uint8Array(XIAOMI_PACKET_SIZE); + data.set(bytes); + return data; +} + +/** Builds a 64-byte macro-channel reply. */ +function macroReply(...bytes: number[]): Uint8Array { + const data = new Uint8Array(XIAOMI_MACRO_PACKET_SIZE); + data.set(bytes); + return data; +} + +class FakeDevice implements HIDDevice { + vendorId = 0x2717; + productId = 0x5009; + productName = "Mi Gaming Mouse"; + opened = false; + collections: HIDCollectionInfo[] = [{ + usagePage: 0xff00, + usage: 2, + children: [], + featureReports: [], + inputReports: [{ reportId: XIAOMI_REPORT_ID, items: [{ reportSize: 8, reportCount: XIAOMI_REPORT_DATA_SIZE }] }], + outputReports: [{ reportId: XIAOMI_REPORT_ID, items: [{ reportSize: 8, reportCount: XIAOMI_REPORT_DATA_SIZE }] }], + }]; + listeners = new Set<(event: HIDInputReportEvent) => void>(); + sent: Uint8Array[] = []; + /** Canned replies keyed by the command byte (request[1]). */ + replies = new Map(); + /** Canned binding-read replies keyed by button index (all reads share command 0xb0). */ + bindingReplies = new Map(); + /** Canned macro-channel read replies keyed by the requested offset. */ + macroReplies = new Map(); + respond = true; + async open() { this.opened = true; } + async close() { this.opened = false; } + addEventListener(_type: "inputreport", listener: (event: HIDInputReportEvent) => void) { this.listeners.add(listener); } + removeEventListener(_type: "inputreport", listener: (event: HIDInputReportEvent) => void) { this.listeners.delete(listener); } + emit(payload: Uint8Array) { + // payload is the hidraw layout (32 or 64 bytes); WebHID delivers the + // data bytes without the report-ID byte. + const reportId = payload[0]!; + const data = payload.subarray(1); + const event = { device: this, reportId, data: new DataView(data.buffer, data.byteOffset, data.byteLength) } as HIDInputReportEvent; + for (const listener of this.listeners) listener(event); + } + async sendReport(reportId: number, data: BufferSource) { + const request = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); + if (reportId === XIAOMI_REPORT_ID) { + assert.equal(request.length, XIAOMI_REPORT_DATA_SIZE); + this.sent.push(request.slice()); + if (request[0] === 0xc1) { + // DPI write: update the read-back state so verification sees the new value. + this.replies.set(0xc2, [0x4d, 0xc2, 0, request[1]!, request[2]!, request[3]!, request[4]!, request[5]!, request[6]!]); + } + if (!this.respond) return; + if (request[0] === 0xb0) { + // Binding reads share command 0xb0; the button index is request[1]. + const canned = this.bindingReplies.get(request[1]!); + if (canned) this.emit(reply(...canned)); + return; + } + const canned = this.replies.get(request[0]!); + if (canned) this.emit(reply(...canned)); + return; + } + assert.equal(reportId, XIAOMI_MACRO_REPORT_ID); + assert.equal(request.length, XIAOMI_MACRO_REPORT_DATA_SIZE); + this.sent.push(request.slice()); + if (request[0] !== 0xf0) return; // macro writes (0xf1) are fire-and-forget + if (!this.respond) return; + // Data payload (report ID stripped): [0xf0, 0x0d, chunk, 0, 0, off_hi, off_lo, ...] + const offset = (request[5]! << 8) | request[6]!; + const canned = this.macroReplies.get(offset); + if (canned) this.emit(macroReply(...canned)); + } + async sendFeatureReport(): Promise { throw new Error("Feature transport must not be used."); } + async receiveFeatureReport(): Promise { throw new Error("Feature transport must not be used."); } +} + +function device(vendorId = 0x2717, productId = 0x5009): FakeDevice { + const fake = new FakeDevice(); + fake.vendorId = vendorId; + fake.productId = productId; + return fake; +} + +test("Xiaomi identity accepts both PIDs only with an input/output collection", () => { + for (const productId of [0x5009, 0x500b]) { + assert.equal(XiaomiHidClient.isSupported(device(0x2717, productId)), true); + } + assert.equal(XiaomiHidClient.isSupported(device(0x2717, 0x500c)), false); + assert.equal(XiaomiHidClient.isSupported(device(0x1234, 0x5009)), false); + const bare = device(); + bare.collections[0]!.outputReports = []; + assert.equal(XiaomiHidClient.isSupported(bare), false); +}); + +test("readStatus reports battery, DPI, polling and both lighting zones", async () => { + const fake = device(); + fake.replies.set(0x90, [0x4d, 0x90, 0x90, 87]); + fake.replies.set(0xc2, [0x4d, 0xc2, 0, 2, 16, 32, 48, 96, 1]); + fake.replies.set(0xc4, [0x4d, 0xc4, 0, 1]); + fake.replies.set(0xa0, [0x4d, 0xa0, 0, 0, 1, 4, 0, 0, 0, 255, 0]); + for (const [button, combo] of factoryBindings()) fake.bindingReplies.set(button, bindingReply(combo)); + const client = new XiaomiHidClient(fake); + const status = await client.readStatus(); + assert.equal(status.brand, "Xiaomi"); + assert.equal(status.batteryPercent, 87); + assert.equal(status.dpi, 800); + assert.deepEqual(status.dpiStages, [100, 800, 1600, 2400, 4800]); + assert.equal(status.activeDpiStage, 1); + assert.equal(status.pollingRateHz, 1000); + assert.deepEqual(status.supportedPollingRates, [125, 250, 500, 1000]); + assert.equal(status.lightingZones.length, 2); + assert.equal(status.lightingZones[0]!.zone, "TAIL"); + assert.equal(status.lightingZones[0]!.mode, "Static"); + assert.equal(status.lightingZones[0]!.color, "#00ff00"); + assert.equal(status.lightingZones[1]!.zone, "WHEEL"); + assert.deepEqual(status.lightingZones[1]!.modes, ["Off", "Static"]); +}); + +test("readStatus exposes the 8 button mappings and the 20 preset options", async () => { + const fake = device(); + fake.replies.set(0x90, [0x4d, 0x90, 0x90, 87]); + fake.replies.set(0xc2, [0x4d, 0xc2, 0, 2, 16, 32, 48, 96, 1]); + fake.replies.set(0xc4, [0x4d, 0xc4, 0, 1]); + fake.replies.set(0xa0, [0x4d, 0xa0, 0, 0, 1, 4, 0, 0, 0, 255, 0]); + for (const [button, combo] of factoryBindings()) fake.bindingReplies.set(button, bindingReply(combo)); + const client = new XiaomiHidClient(fake); + const status = await client.readStatus(); + assert.deepEqual(Object.keys(status.buttonMappings!), XIAOMI_BUTTON_NAMES); + assert.deepEqual(status.buttonMappings, { + Left: "Left-click", + Right: "Right-click", + Scroll: "Middle-click", + M5: "Move forward", + M4: "Move back", + "Rise DPI": "Rise DPI", + "Lower DPI": "Lower DPI", + Aiming: "Turn DPI", + }); + assert.deepEqual(status.buttonOptions, XIAOMI_BUTTON_ACTIONS.map((action) => action.label)); + assert.equal(status.buttonOptions!.length, 20); + // One binding read per button, in order. + const reads = fake.sent.filter((frame) => frame[0] === 0xb0); + assert.equal(reads.length, 8); + assert.deepEqual(reads.map((frame) => frame[1]), [0, 1, 2, 3, 4, 5, 6, 7]); +}); + +test("readStatus labels custom combos and macros instead of presets", async () => { + const fake = device(); + fake.replies.set(0x90, [0x4d, 0x90, 0x90, 87]); + fake.replies.set(0xc2, [0x4d, 0xc2, 0, 2, 16, 32, 48, 96, 1]); + fake.replies.set(0xc4, [0x4d, 0xc4, 0, 1]); + fake.replies.set(0xa0, [0x4d, 0xa0, 0, 0, 1, 4, 0, 0, 0, 255, 0]); + for (const [button, combo] of factoryBindings()) fake.bindingReplies.set(button, bindingReply(combo)); + // M5 (3): custom combo Ctrl+Shift+N; M4 (4): no-delay macro of 3 events (12 bytes). + fake.bindingReplies.set(3, [0x4d, 0xb0, 0, 0, 0x01, 0x00, 0x03, 0x11]); + fake.bindingReplies.set(4, [0x4d, 0xb0, 0, 0, 0x02, 0x00, 0x00, 12]); + const client = new XiaomiHidClient(fake); + const status = await client.readStatus(); + assert.equal(status.buttonMappings!["M5"], "Custom (Ctrl+Shift+N)"); + assert.equal(status.buttonMappings!["M4"], "Macro (3 events)"); + // Preset bindings are untouched. + assert.equal(status.buttonMappings!["Left"], "Left-click"); +}); + +test("setButtonMapping writes the preset combo for the named button", async () => { + const fake = device(); + const client = new XiaomiHidClient(fake); + await client.setButtonMapping("M5", "Ctrl+C"); + const write = fake.sent.find((frame) => frame[0] === 0xb1); + assert.ok(write, "a binding write must be sent"); + // M5 is button 3; Ctrl+C is combo 0x0109. + assert.equal(write![1], 3); + assert.equal(write![2], 0x01); + assert.equal(write![3], 0x09); + assert.equal(write![4], 0); + assert.equal(write![5], 0); +}); + +test("setButtonMapping rejects unknown buttons and actions", async () => { + const fake = device(); + const client = new XiaomiHidClient(fake); + await assert.rejects(() => client.setButtonMapping("M9", "Ctrl+C"), /Unknown .* button: M9/); + await assert.rejects(() => client.setButtonMapping("M5", "Ctrl+D"), /Unknown .* button action: Ctrl\+D/); + assert.equal(fake.sent.length, 0); +}); + +test("setDpi writes the full level table and verifies by read-back", async () => { + const fake = device(); + fake.replies.set(0xc2, [0x4d, 0xc2, 0, 2, 16, 32, 48, 96, 1]); + const client = new XiaomiHidClient(fake); + const dpi = await client.setDpi(1200); + assert.equal(dpi, 1200); + const write = fake.sent.find((frame) => frame[0] === 0xc1); + assert.ok(write, "a DPI write must be sent"); + // 1200/50 = 24 at the active level (index 1). + assert.equal(write![1], 2); + assert.equal(write![2], 24); + assert.equal(write![6], 1); +}); + +test("setPollingRate rejects unsupported rates and verifies by read-back", async () => { + const fake = device(); + fake.replies.set(0xc4, [0x4d, 0xc4, 0, 4]); + const client = new XiaomiHidClient(fake); + await assert.rejects(() => client.setPollingRate(750), /not supported/); + const rate = await client.setPollingRate(250); + assert.equal(rate, 250); + const write = fake.sent.find((frame) => frame[0] === 0xc3); + assert.ok(write, "a polling write must be sent"); + assert.equal(write![1], 4); +}); + +test("setLighting writes the wire effect and reads the zone back", async () => { + const fake = device(); + // Read-back echoes the written wire effect: Spectrum is logical 6 → wire 7. + fake.replies.set(0xa0, [0x4d, 0xa0, 0, 0, 7, 3, 0, 0, 255, 0, 0]); + const client = new XiaomiHidClient(fake); + const zone = await client.setLighting({ zone: "TAIL", mode: "Spectrum", color: "#ff0000", speed: 3 }); + assert.equal(zone.mode, "Spectrum"); + assert.equal(zone.color, "#ff0000"); + const write = fake.sent.find((frame) => frame[0] === 0xa1); + assert.ok(write, "a lighting write must be sent"); + // Spectrum is logical effect 6 → wire 7. + assert.equal(write![2], 7); + assert.equal(write![3], 3); + assert.equal(write![6], 255); +}); + +test("setLighting rejects an effect the wheel zone does not support", async () => { + const fake = device(); + const client = new XiaomiHidClient(fake); + await assert.rejects( + () => client.setLighting({ zone: "WHEEL", mode: "Spectrum", color: "#ff0000", speed: 3 }), + /not supported for the wheel zone/, + ); +}); + +test("a read that never answers times out", async () => { + const fake = device(); + fake.respond = false; + const client = new XiaomiHidClient(fake); + await assert.rejects(() => client.readStatus(), /did not answer/); +}); + +test("decoders agree with the driver on the wire layout", () => { + const lighting = xiaomiDecodeLighting(reply(0x4d, 0xa0, 0, 0, 6, 3, 0, 0, 255, 0, 0)); + assert.equal(lighting.effect, 5); + const dpi = xiaomiDecodeDpi(reply(0x4d, 0xc2, 0, 2, 16, 32, 48, 96, 1)); + assert.equal(dpi.levels[1], 800); + assert.equal(xiaomiDecodePolling(reply(0x4d, 0xc4, 0, 1)), 1000); +}); + +/** Builds a binding read reply carrying `combo`. The real device does not + * echo the button index in byte 2 (always 0x00). */ +function bindingReply(combo: number): number[] { + return [0x4d, 0xb0, 0, 0, (combo >> 8) & 0xff, combo & 0xff, 0, 0]; +} + +/** Factory-default bindings as reported by the reference app. */ +function factoryBindings(): Map { + return new Map([ + [0, XIAOMI_KEY_COMBOS.LEFT_CLICK], + [1, XIAOMI_KEY_COMBOS.RIGHT_CLICK], + [2, XIAOMI_KEY_COMBOS.MIDDLE_CLICK], + [3, XIAOMI_KEY_COMBOS.MOVE_FORWARD], + [4, XIAOMI_KEY_COMBOS.MOVE_BACK], + [5, XIAOMI_KEY_COMBOS.RISE_DPI], + [6, XIAOMI_KEY_COMBOS.LOWER_DPI], + [7, XIAOMI_KEY_COMBOS.TURN_DPI], + ]); +} + +/** Builds a 64-byte macro read reply carrying `events` (4 bytes each). */ +function macroChunkReply(events: readonly XiaomiMacroEvent[]): number[] { + const bytes = [0x57, 0xf0, 0x0d, events.length * 4, 0, 0, 0, 0]; + for (const event of events) bytes.push(event.key, event.state, (event.delayMs >> 8) & 0xff, event.delayMs & 0xff); + return bytes; +} + +test("readBinding decodes a custom key combo from the control channel", async () => { + const fake = device(); + fake.bindingReplies.set(2, [0x4d, 0xb0, 0, 0, 0x01, 0x00, 0x02, 0x11]); + const client = new XiaomiHidClient(fake); + const binding = await client.readBinding(2); + assert.equal(binding.mode, XIAOMI_KEY_COMBOS.CUSTOM_KEY_COMBO); + assert.equal(binding.modifiers, 0x02); + assert.equal(binding.key, 0x11); + const read = fake.sent.find((frame) => frame[0] === 0xb0); + assert.ok(read, "a binding read must be sent"); + assert.equal(read![1], 2); +}); + +test("setBinding writes the combo on the control channel", async () => { + const fake = device(); + const client = new XiaomiHidClient(fake); + await client.setBinding(3, XIAOMI_KEY_COMBOS.CUSTOM_KEY_COMBO, 0x04, 0x2a); + const write = fake.sent.find((frame) => frame[0] === 0xb1); + assert.ok(write, "a binding write must be sent"); + assert.equal(write![1], 3); + assert.equal(write![2], 0x01); + assert.equal(write![3], 0x00); + assert.equal(write![4], 0x04); + assert.equal(write![5], 0x2a); +}); + +test("readMacro streams the macro body in chunks until the size is reached", async () => { + const fake = device(); + // Button 4 is bound to a no-delay macro of 21 events (84 event bytes). + fake.bindingReplies.set(4, [0x4d, 0xb0, 0, 0, 0x02, 0x00, 0x00, 84]); + const first: XiaomiMacroEvent[] = []; + for (let i = 0; i < 14; i++) first.push({ key: i, state: i % 2, delayMs: 0 }); + const second: XiaomiMacroEvent[] = []; + for (let i = 14; i < 21; i++) second.push({ key: i, state: i % 2, delayMs: 10 }); + fake.macroReplies.set(0, macroChunkReply(first)); + fake.macroReplies.set(56, macroChunkReply(second)); + const client = new XiaomiHidClient(fake); + const events = await client.readMacro(4); + assert.equal(events.length, 21); + assert.deepEqual(events[0], { key: 0, state: 0, delayMs: 0 }); + assert.deepEqual(events[14], { key: 14, state: 0, delayMs: 10 }); + assert.deepEqual(events[20], { key: 20, state: 0, delayMs: 10 }); + const reads = fake.sent.filter((frame) => frame[0] === 0xf0); + assert.equal(reads.length, 2); + // Data payload: [0xf0, 0x0d, chunkSize, 0, 0, off_hi, off_lo, ...]. + // First request: 56 event bytes at offset 0; second: the remaining 28 at offset 56. + assert.equal(reads[0]![2], 56); + assert.equal(reads[0]![5], 0); + assert.equal(reads[0]![6], 0); + assert.equal(reads[1]![2], 28); + assert.equal(reads[1]![5], 0); + assert.equal(reads[1]![6], 56); +}); + +test("readMacro stops early when the device signals the end of the macro", async () => { + const fake = device(); + fake.bindingReplies.set(4, [0x4d, 0xb0, 0, 0, 0x02, 0x01, 0x00, 84]); + const events: XiaomiMacroEvent[] = []; + for (let i = 0; i < 7; i++) events.push({ key: i, state: 1, delayMs: 5 }); + fake.macroReplies.set(0, macroChunkReply(events)); + // The offset accumulates by the *requested* diff (56), so the second read + // goes to offset 56. packetSize 0 (< 8) marks the end of the macro. + fake.macroReplies.set(56, [0x57, 0xf0, 0x0d, 0, 0, 0, 0, 0]); + const client = new XiaomiHidClient(fake); + const read = await client.readMacro(4); + assert.equal(read.length, 7); + assert.deepEqual(read[0], { key: 0, state: 1, delayMs: 5 }); +}); + +test("setMacro writes the binding first, then streams the macro packets", async () => { + const fake = device(); + const client = new XiaomiHidClient(fake); + const events: XiaomiMacroEvent[] = []; + for (let i = 0; i < 21; i++) events.push({ key: i, state: i % 2, delayMs: i * 10 }); + await client.setMacro(5, XIAOMI_KEY_COMBOS.MACROS_WITH_DELAY, events); + const binding = fake.sent.find((frame) => frame[0] === 0xb1); + assert.ok(binding, "the binding write must be sent"); + assert.equal(binding![1], 5); + assert.equal(binding![2], 0x02); + assert.equal(binding![3], 0x01); + // 21 events × 4 bytes = 84 event bytes. + assert.equal(binding![4], 0); + assert.equal(binding![5], 84); + const packets = fake.sent.filter((frame) => frame[0] === 0xf1); + assert.equal(packets.length, 2); + // Data payload: [0xf1, 0x0d, pktSize, 0, 0, off_hi, off_lo, ...events]. + // Packet 1: 14 events (56 bytes) at offset 0. + assert.equal(packets[0]![2], 56); + assert.equal(packets[0]![5], 0); + assert.equal(packets[0]![6], 0); + assert.equal(packets[0]![7], 0); // first event key + assert.equal(packets[0]![8], 0); // first event state + // Packet 2: the remaining 7 events (28 bytes) at offset 56. + assert.equal(packets[1]![2], 28); + assert.equal(packets[1]![5], 0); + assert.equal(packets[1]![6], 56); + assert.equal(packets[1]![7], 14); // first event key of the second packet + assert.equal(packets[1]![31], 20); // last event key (event 6, byte 7) +}); diff --git a/src/drivers/xiaomi/hid.ts b/src/drivers/xiaomi/hid.ts new file mode 100644 index 0000000..9f35ec0 --- /dev/null +++ b/src/drivers/xiaomi/hid.ts @@ -0,0 +1,399 @@ +import type { MouseLighting, MouseLightingMode, MouseStatus } from "../mouse-types.js"; +import type { XiaomiBinding, XiaomiLightingDevice, XiaomiMacroEvent } from "@openmouse/protocol/xiaomi"; +import { + XIAOMI_BUTTON_ACTIONS, + XIAOMI_BUTTON_NAMES, + XIAOMI_DEVICES, + XIAOMI_EFFECTS_BY_DEVICE, + XIAOMI_KEY_COMBOS, + XIAOMI_LIGHTING_DEVICES, + XIAOMI_MACRO_EVENT_SIZE, + XIAOMI_MACRO_MAX_EVENT_BYTES, + XIAOMI_MACRO_PACKET_SIZE, + XIAOMI_MACRO_REPORT_DATA_SIZE, + XIAOMI_MACRO_REPORT_ID, + XIAOMI_PACKET_SIZE, + XIAOMI_POLLING_RATES, + XIAOMI_PRODUCT_IDS, + XIAOMI_REPORT_DATA_SIZE, + XIAOMI_REPORT_ID, + XIAOMI_SPEEDS, + XIAOMI_VENDOR_ID, + xiaomiBindingLabel, + xiaomiDecodeBattery, + xiaomiDecodeBinding, + xiaomiDecodeDpi, + xiaomiDecodeLighting, + xiaomiDecodeMacroChunk, + xiaomiDecodePolling, + xiaomiHexColorToRgb, + xiaomiMacroPackets, + xiaomiReadBatteryRequest, + xiaomiReadBindingRequest, + xiaomiReadDpiRequest, + xiaomiReadLightingRequest, + xiaomiReadMacroRequest, + xiaomiReadPollingRequest, + xiaomiRgbToHexColor, + xiaomiWriteBindingRequest, + xiaomiWriteDpiRequest, + xiaomiWriteLightingRequest, + xiaomiWriteMacroRequest, + xiaomiWritePollingRequest, +} from "@openmouse/protocol/xiaomi"; + +const RESPONSE_TIMEOUT_MS = 1_500; + +/** Logical effect → shared lighting-mode label. */ +const EFFECT_MODES: Record = { + 0: "Off", + 1: "Static", + 2: "Breathing single", + 3: "Single Flash", + 5: "Cycling", + 6: "Spectrum", +}; + +/** Shared lighting-mode label → logical effect. */ +const MODE_EFFECTS: Record = Object.fromEntries( + Object.entries(EFFECT_MODES).map(([effect, mode]) => [mode, Number(effect)]), +); + +/** Factory defaults, used to fill a level the firmware reports empty (0). */ +const DEFAULT_DPI_LEVELS = [100, 800, 1600, 2400, 4800]; + +/** A HID report channel: its report ID and the hidraw packet/data sizes. */ +interface XiaomiChannel { + reportId: number; + packetSize: number; + dataSize: number; +} + +/** Control channel: 32-byte hidraw reports headed by 0x4d. */ +const CONTROL_CHANNEL: XiaomiChannel = { + reportId: XIAOMI_REPORT_ID, + packetSize: XIAOMI_PACKET_SIZE, + dataSize: XIAOMI_REPORT_DATA_SIZE, +}; + +/** Macro channel: 64-byte hidraw reports headed by 0x57. */ +const MACRO_CHANNEL: XiaomiChannel = { + reportId: XIAOMI_MACRO_REPORT_ID, + packetSize: XIAOMI_MACRO_PACKET_SIZE, + dataSize: XIAOMI_MACRO_REPORT_DATA_SIZE, +}; + +function copyDataView(view: DataView): Uint8Array { + return new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength)); +} + +/** + * No HID descriptor has been captured for this mouse, so the control channel + * is selected by shape: any collection that can both send and receive reports. + */ +function hasControlCollection(collections: readonly HIDCollectionInfo[]): boolean { + return collections.some( + (collection) => + (collection.inputReports.length > 0 && collection.outputReports.length > 0) || + hasControlCollection(collection.children), + ); +} + +function sanitizeDpiLevel(level: number, index: number): number { + if (Number.isInteger(level) && level >= 50 && level <= 7200 && level % 50 === 0) return level; + return DEFAULT_DPI_LEVELS[index]; +} + +export class XiaomiHidClient { + readonly device: HIDDevice; + + private queue: Promise = Promise.resolve(); + + constructor(device: HIDDevice) { + this.device = device; + } + + static isSupported(device: HIDDevice): boolean { + if (device.vendorId !== XIAOMI_VENDOR_ID || !XIAOMI_PRODUCT_IDS.has(device.productId)) return false; + return hasControlCollection(device.collections); + } + + private get definition() { + return XIAOMI_DEVICES.get(this.device.productId)!; + } + + private get label(): string { + return this.definition.name; + } + + async open(): Promise { + if (!this.device.opened) await this.device.open(); + } + + async close(): Promise { + if (this.device.opened) await this.device.close(); + } + + getDpiOptions(): number[] { + const values: number[] = []; + for (let dpi = 50; dpi <= 7200; dpi += 50) values.push(dpi); + return values; + } + + getSupportedPollingRates(): number[] { + return [...XIAOMI_POLLING_RATES].sort((a, b) => a - b); + } + + private async run(task: () => Promise): Promise { + const started = this.queue.then(task, task); + this.queue = started.catch(() => undefined); + return started; + } + + /** + * Strips the leading report-ID byte from the hidraw request, leaving the + * data bytes WebHID's `sendReport` expects. + */ + private payload(channel: XiaomiChannel, request: Uint8Array): ArrayBuffer { + const buffer = new ArrayBuffer(channel.dataSize); + new Uint8Array(buffer).set(request.subarray(1, channel.packetSize)); + return buffer; + } + + /** + * Sends a write command. The firmware does not answer writes (the reference + * app never reads after them), so the caller must read back to verify. + */ + private async write(channel: XiaomiChannel, request: Uint8Array): Promise { + return this.run(async () => { + await this.open(); + await this.device.sendReport(channel.reportId, this.payload(channel, request)); + }); + } + + /** Sends `request` and resolves with the first reply echoing its header and command byte. */ + private async exchange(channel: XiaomiChannel, request: Uint8Array): Promise { + return this.run(async () => { + await this.open(); + const payload = this.payload(channel, request); + return new Promise((resolve, reject) => { + const cleanup = (): void => { + clearTimeout(timer); + this.device.removeEventListener("inputreport", listener); + }; + + const listener = (event: HIDInputReportEvent): void => { + if (event.reportId !== channel.reportId) return; + const data = copyDataView(event.data); + if (data.length < 2) return; + // WebHID delivers the data bytes without the report-ID byte; the + // decoders expect the hidraw layout, so prepend the report ID. + const report = new Uint8Array(channel.packetSize); + report[0] = channel.reportId; + report.set(data.subarray(0, channel.dataSize), 1); + if (report[0] !== request[0] || report[1] !== request[1]) return; + cleanup(); + resolve(report); + }; + + const timer = setTimeout(() => { + this.device.removeEventListener("inputreport", listener); + reject(new Error(`${this.label} did not answer the HID request.`)); + }, RESPONSE_TIMEOUT_MS); + + this.device.addEventListener("inputreport", listener); + + this.device.sendReport(channel.reportId, payload).catch((error: unknown) => { + cleanup(); + reject(error); + }); + }); + }); + } + + private async readLightingZones(): Promise { + const zones: MouseLighting[] = []; + for (const [zone, zoneId] of Object.entries(XIAOMI_LIGHTING_DEVICES) as [string, number][]) { + const raw = xiaomiDecodeLighting(await this.exchange(CONTROL_CHANNEL, xiaomiReadLightingRequest(zoneId))); + zones.push(this.lightingStatus(zone, raw)); + } + return zones; + } + + private lightingStatus( + zone: string, + raw: { effect: number; speed: number; color: [number, number, number] }, + ): MouseLighting { + const modes = XIAOMI_EFFECTS_BY_DEVICE[zone as XiaomiLightingDevice].map((effect) => EFFECT_MODES[effect]); + return { + zone, + modes, + mode: EFFECT_MODES[raw.effect] ?? "Static", + color: xiaomiRgbToHexColor(raw.color), + color2: null, + colorModes: modes.filter((mode) => mode !== "Off"), + dualColorModes: [], + reactiveModes: [], + speeds: [...XIAOMI_SPEEDS], + speed: raw.speed, + }; + } + + async readLighting(): Promise { + return this.readLightingZones(); + } + + async setLighting(lighting: MouseLighting): Promise { + const zoneId = (Object.entries(XIAOMI_LIGHTING_DEVICES) as [string, number][]) + .find(([name]) => name === lighting.zone)?.[1]; + if (zoneId === undefined) throw new Error(`Unknown ${this.label} lighting zone: ${lighting.zone}`); + if (!lighting.mode) throw new Error("Choose an RGB effect first."); + const effect = MODE_EFFECTS[lighting.mode]; + if (effect === undefined) throw new Error(`Unsupported ${this.label} lighting mode: ${lighting.mode}`); + const [red, green, blue] = xiaomiHexColorToRgb(lighting.color ?? "#00ff00"); + const speed = lighting.speed ?? 4; + await this.write(CONTROL_CHANNEL, xiaomiWriteLightingRequest(zoneId, effect, speed, [red, green, blue])); + return (await this.readLightingZones())[zoneId]; + } + + async readStatus(): Promise { + const definition = this.definition; + const battery = xiaomiDecodeBattery(await this.exchange(CONTROL_CHANNEL, xiaomiReadBatteryRequest())); + const dpi = xiaomiDecodeDpi(await this.exchange(CONTROL_CHANNEL, xiaomiReadDpiRequest())); + const pollingRateHz = xiaomiDecodePolling(await this.exchange(CONTROL_CHANNEL, xiaomiReadPollingRequest())); + const lightingZones = await this.readLightingZones(); + const wireless = definition.wireless; + const buttonMappings: Record = {}; + for (const [button, name] of XIAOMI_BUTTON_NAMES.entries()) { + const binding = await this.readBinding(button); + buttonMappings[name] = xiaomiBindingLabel(binding) ?? "Unknown"; + } + + return { + brand: "Xiaomi", + name: definition.name, + ui: { + family: "xiaomi", + settingsReady: definition.verified, + valuesVerified: definition.verified, + hideUnsupportedPollingRates: true, + forceShowBattery: true, + defaultDisplayName: definition.name, + statusNote: definition.verified + ? `${definition.name} hardware controls are enabled.` + : `${definition.name} wireless support has not been tested on real hardware yet. Every change is read back from the mouse.`, + }, + batteryPercent: battery, + batteryState: wireless ? "Discharging" : "Charging", + dpi: dpi.levels[dpi.active], + dpiStages: dpi.levels, + activeDpiStage: dpi.active, + pollingRateHz, + supportedPollingRates: this.getSupportedPollingRates(), + activeProfile: null, + connectionType: wireless ? "Wireless" : "Wired", + connectionDetail: wireless ? "2.4 GHz receiver" : "Wired USB", + liftOffDistance: null, + lighting: lightingZones[0], + lightingZones, + firmware: [], + buttonMappings, + buttonOptions: XIAOMI_BUTTON_ACTIONS.map((action) => action.label), + }; + } + + async setDpi(dpi: number): Promise { + const current = xiaomiDecodeDpi(await this.exchange(CONTROL_CHANNEL, xiaomiReadDpiRequest())); + const levels = current.levels.map((level, index) => sanitizeDpiLevel(level, index)); + levels[current.active] = dpi; + await this.write(CONTROL_CHANNEL, xiaomiWriteDpiRequest(levels, current.active)); + const confirmed = xiaomiDecodeDpi(await this.exchange(CONTROL_CHANNEL, xiaomiReadDpiRequest())); + if (confirmed.levels[confirmed.active] !== dpi) { + throw new Error(`${this.label} kept ${confirmed.levels[confirmed.active]} DPI instead of ${dpi} DPI.`); + } + return confirmed.levels[confirmed.active]; + } + + async setPollingRate(rate: number): Promise { + if (!this.getSupportedPollingRates().includes(rate)) { + throw new Error(`${rate} Hz is not supported by the ${this.label}.`); + } + await this.write(CONTROL_CHANNEL, xiaomiWritePollingRequest(rate)); + const confirmed = xiaomiDecodePolling(await this.exchange(CONTROL_CHANNEL, xiaomiReadPollingRequest())); + if (confirmed !== rate) { + throw new Error(`${this.label} kept ${confirmed} Hz instead of ${rate} Hz.`); + } + return confirmed; + } + + /** Reads the current binding (key combo or macro) of a button. */ + async readBinding(button: number): Promise { + const report = await this.exchange(CONTROL_CHANNEL, xiaomiReadBindingRequest(button)); + return xiaomiDecodeBinding(report); + } + + /** + * Binds a button to a key combo. `combo` is one of `XIAOMI_KEY_COMBOS` + * (e.g. `CUSTOM_KEY_COMBO`); `modifiers` and `key` are only meaningful for + * the custom-key combo. + */ + async setBinding(button: number, combo: number, modifiers = 0, key = 0): Promise { + await this.write(CONTROL_CHANNEL, xiaomiWriteBindingRequest(button, combo, modifiers, key)); + } + + /** + * Maps a button (by display name) to one of the preset actions in + * `buttonOptions`. Custom combos and macros are not selectable here: they + * appear in `buttonMappings` and are overwritten when a preset is chosen. + */ + async setButtonMapping(button: string, actionLabel: string): Promise { + const buttonIndex = XIAOMI_BUTTON_NAMES.indexOf(button as (typeof XIAOMI_BUTTON_NAMES)[number]); + if (buttonIndex === -1) throw new Error(`Unknown ${this.label} button: ${button}`); + const action = XIAOMI_BUTTON_ACTIONS.find((candidate) => candidate.label === actionLabel); + if (!action) throw new Error(`Unknown ${this.label} button action: ${actionLabel}`); + await this.setBinding(buttonIndex, action.combo); + } + + /** + * Reads the macro bound to a button. Throws if the button is not bound to a + * macro. The macro body lives on the 64-byte macro channel (report ID 0x57), + * read in chunks of up to 14 events. + */ + async readMacro(button: number): Promise { + const binding = await this.readBinding(button); + if (binding.mode !== XIAOMI_KEY_COMBOS.MACROS_NO_DELAY && binding.mode !== XIAOMI_KEY_COMBOS.MACROS_WITH_DELAY) { + throw new Error(`Button ${button} is not bound to a macro (mode 0x${binding.mode.toString(16)}).`); + } + const events: XiaomiMacroEvent[] = []; + let offset = 0; + for (;;) { + const remaining = (binding.macroSize ?? 0) - events.length * XIAOMI_MACRO_EVENT_SIZE; + if (remaining <= 0) break; + const chunkSize = Math.min(remaining, XIAOMI_MACRO_MAX_EVENT_BYTES); + const report = await this.exchange(MACRO_CHANNEL, xiaomiReadMacroRequest(offset, chunkSize)); + const chunk = xiaomiDecodeMacroChunk(report); + events.push(...chunk.events); + if (chunk.packetSize < XIAOMI_MACRO_EVENT_SIZE) break; // end of macro + offset += chunkSize; + } + return events; + } + + /** + * Writes a macro to a button. `mode` must be `MACROS_NO_DELAY` or + * `MACROS_WITH_DELAY`. The binding is written on the control channel first, + * then the macro body is streamed in 64-byte packets on the macro channel. + */ + async setMacro(button: number, mode: number, events: readonly XiaomiMacroEvent[]): Promise { + if (mode !== XIAOMI_KEY_COMBOS.MACROS_NO_DELAY && mode !== XIAOMI_KEY_COMBOS.MACROS_WITH_DELAY) { + throw new Error(`Unsupported macro mode 0x${mode.toString(16)}.`); + } + const size = events.length * XIAOMI_MACRO_EVENT_SIZE; + await this.write(CONTROL_CHANNEL, xiaomiWriteBindingRequest(button, mode, (size >> 8) & 0xff, size & 0xff)); + let offset = 0; + for (const chunk of xiaomiMacroPackets(events)) { + await this.write(MACRO_CHANNEL, xiaomiWriteMacroRequest(offset, chunk)); + offset += chunk.length * XIAOMI_MACRO_EVENT_SIZE; + } + } +} diff --git a/src/index.ts b/src/index.ts index ce0629f..adf17a4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -48,3 +48,4 @@ export * as ajazz from "./ajazz/index.js"; export * as scyrox from "./scyrox/index.js"; export * as roccat from "./roccat/index.js"; export * as ajazzAj200p from "./ajazz/aj200p.js"; +export * as xiaomi from "./xiaomi/index.js"; diff --git a/src/xiaomi/index.test.ts b/src/xiaomi/index.test.ts new file mode 100644 index 0000000..f29ae33 --- /dev/null +++ b/src/xiaomi/index.test.ts @@ -0,0 +1,282 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + XIAOMI_DPI_LEVELS, + XIAOMI_DPI_MAX, + XIAOMI_DPI_MIN, + XIAOMI_DPI_STEP, + XIAOMI_EFFECTS, + XIAOMI_EFFECTS_BY_DEVICE, + XIAOMI_HEADER, + XIAOMI_KEY_COMBOS, + XIAOMI_MACRO_EVENT_SIZE, + XIAOMI_MACRO_HEADER_LENGTH, + XIAOMI_MACRO_MAX_EVENTS_PER_PACKET, + XIAOMI_MACRO_PACKET_SIZE, + XIAOMI_MACRO_REPORT_ID, + XIAOMI_PACKET_SIZE, + XIAOMI_POLLING_RATES, + XIAOMI_PRODUCT_IDS, + XIAOMI_SPEEDS, + xiaomiDecodeBattery, + xiaomiDecodeBinding, + xiaomiDecodeDpi, + xiaomiDecodeLighting, + xiaomiDecodeMacroChunk, + xiaomiDecodePolling, + xiaomiDpiFromWire, + xiaomiDpiToWire, + xiaomiEffectFromWire, + xiaomiEffectToWire, + xiaomiHexColorToRgb, + xiaomiMacroPackets, + xiaomiPollingRateFromWire, + xiaomiPollingRateToWire, + xiaomiReadBatteryRequest, + xiaomiReadBindingRequest, + xiaomiReadDpiRequest, + xiaomiReadLightingRequest, + xiaomiReadMacroRequest, + xiaomiReadPollingRequest, + xiaomiRgbToHexColor, + xiaomiWriteBindingRequest, + xiaomiWriteDpiRequest, + xiaomiWriteLightingRequest, + xiaomiWriteMacroRequest, + xiaomiWritePollingRequest, +} from "./index.js"; + +function reply(...bytes: number[]): Uint8Array { + const data = new Uint8Array(XIAOMI_PACKET_SIZE); + data.set(bytes); + return data; +} + +function macroReply(...bytes: number[]): Uint8Array { + const data = new Uint8Array(XIAOMI_MACRO_PACKET_SIZE); + data.set(bytes); + return data; +} + +test("device table covers the wired and wireless PIDs", () => { + assert.deepEqual([...XIAOMI_PRODUCT_IDS], [0x5009, 0x500b]); +}); + +test("effect wire mapping skips the firmware gap", () => { + for (const effect of XIAOMI_EFFECTS) { + assert.equal(xiaomiEffectFromWire(xiaomiEffectToWire(effect)), effect); + } + assert.equal(xiaomiEffectToWire(3), 3); + assert.equal(xiaomiEffectToWire(5), 6); + assert.equal(xiaomiEffectToWire(6), 7); + assert.equal(xiaomiEffectFromWire(6), 5); + assert.equal(xiaomiEffectFromWire(7), 6); +}); + +test("polling wire mapping is a power of two in wire order", () => { + assert.deepEqual(XIAOMI_POLLING_RATES, [1000, 500, 250, 125]); + assert.equal(xiaomiPollingRateToWire(1000), 0x01); + assert.equal(xiaomiPollingRateToWire(500), 0x02); + assert.equal(xiaomiPollingRateToWire(250), 0x04); + assert.equal(xiaomiPollingRateToWire(125), 0x08); + assert.equal(xiaomiPollingRateFromWire(0x04), 250); + assert.throws(() => xiaomiPollingRateToWire(750), RangeError); + assert.throws(() => xiaomiPollingRateFromWire(0x03), Error); + assert.throws(() => xiaomiPollingRateFromWire(0x10), Error); +}); + +test("DPI wire mapping divides by the step and validates the range", () => { + assert.equal(XIAOMI_DPI_MIN, 50); + assert.equal(XIAOMI_DPI_MAX, 7200); + assert.equal(XIAOMI_DPI_STEP, 50); + assert.equal(xiaomiDpiToWire(100), 2); + assert.equal(xiaomiDpiToWire(7200), 144); + assert.equal(xiaomiDpiFromWire(2), 100); + assert.throws(() => xiaomiDpiToWire(49), RangeError); + assert.throws(() => xiaomiDpiToWire(7250), RangeError); + assert.throws(() => xiaomiDpiToWire(101), RangeError); + assert.throws(() => xiaomiDpiToWire(100.5), RangeError); +}); + +test("color helpers round-trip", () => { + assert.deepEqual(xiaomiHexColorToRgb("#00ff80"), [0x00, 0xff, 0x80]); + assert.deepEqual(xiaomiHexColorToRgb("00ff80"), [0x00, 0xff, 0x80]); + assert.equal(xiaomiRgbToHexColor([0x00, 0xff, 0x80]), "#00ff80"); + assert.throws(() => xiaomiHexColorToRgb("#00ff8"), RangeError); + assert.throws(() => xiaomiHexColorToRgb("nope"), RangeError); +}); + +test("read requests are 32-byte reports headed by 0x4D", () => { + const lighting = xiaomiReadLightingRequest(0); + assert.equal(lighting.length, XIAOMI_PACKET_SIZE); + assert.deepEqual([...lighting.slice(0, 3)], [XIAOMI_HEADER, 0xa0, 0]); + assert.deepEqual([...xiaomiReadLightingRequest(1).slice(0, 3)], [XIAOMI_HEADER, 0xa0, 1]); + assert.throws(() => xiaomiReadLightingRequest(2), RangeError); + + assert.deepEqual([...xiaomiReadBatteryRequest().slice(0, 2)], [XIAOMI_HEADER, 0x90]); + assert.deepEqual([...xiaomiReadPollingRequest().slice(0, 2)], [XIAOMI_HEADER, 0xc4]); + assert.deepEqual([...xiaomiReadDpiRequest().slice(0, 2)], [XIAOMI_HEADER, 0xc2]); + assert.deepEqual([...xiaomiReadBindingRequest(3).slice(0, 3)], [XIAOMI_HEADER, 0xb0, 3]); + assert.throws(() => xiaomiReadBindingRequest(8), RangeError); +}); + +test("lighting write encodes effect, speed and RGB", () => { + const frame = xiaomiWriteLightingRequest(0, 1, 4, [0x00, 0xff, 0x80]); + assert.equal(frame.length, XIAOMI_PACKET_SIZE); + assert.deepEqual([...frame.slice(0, 10)], [XIAOMI_HEADER, 0xa1, 0, 1, 4, 0x08, 0x08, 0x00, 0xff, 0x80]); + + // Logical effect 5 maps to wire value 6. + assert.equal(xiaomiWriteLightingRequest(0, 5, 1, [1, 2, 3])[3], 6); + + // The wheel zone only accepts Off and Static. + assert.deepEqual(XIAOMI_EFFECTS_BY_DEVICE.WHEEL, [0, 1]); + assert.throws(() => xiaomiWriteLightingRequest(1, 2, 4, [0, 0, 0]), RangeError); + assert.throws(() => xiaomiWriteLightingRequest(0, 4, 4, [0, 0, 0]), RangeError); + assert.throws(() => xiaomiWriteLightingRequest(0, 1, 0, [0, 0, 0]), RangeError); + assert.throws(() => xiaomiWriteLightingRequest(0, 1, 9, [0, 0, 0]), RangeError); + assert.throws(() => xiaomiWriteLightingRequest(2, 1, 4, [0, 0, 0]), RangeError); +}); + +test("polling write encodes the rate as a power of two", () => { + assert.equal(xiaomiWritePollingRequest(1000)[2], 0x01); + assert.equal(xiaomiWritePollingRequest(125)[2], 0x08); + assert.throws(() => xiaomiWritePollingRequest(100), RangeError); +}); + +test("DPI write packs five levels, the active level and the trailer", () => { + const frame = xiaomiWriteDpiRequest([100, 800, 1600, 2400, 4800], 2); + assert.deepEqual([...frame.slice(0, 10)], [XIAOMI_HEADER, 0xc1, 2, 16, 32, 48, 96, 2, 0x00, 0x05]); + assert.throws(() => xiaomiWriteDpiRequest([100, 800, 1600, 2400], 2), RangeError); + assert.throws(() => xiaomiWriteDpiRequest([100, 800, 1600, 2400, 4800], 5), RangeError); + assert.throws(() => xiaomiWriteDpiRequest([100, 800, 1600, 2400, 4800], -1), RangeError); +}); + +test("binding write packs the combo big-endian with modifiers and key", () => { + const frame = xiaomiWriteBindingRequest(3, XIAOMI_KEY_COMBOS.CUSTOM_KEY_COMBO, 0x01, 0x04); + assert.deepEqual([...frame.slice(0, 7)], [XIAOMI_HEADER, 0xb1, 3, 0x01, 0x00, 0x01, 0x04]); + assert.throws(() => xiaomiWriteBindingRequest(8, 1, 0, 0), RangeError); + assert.throws(() => xiaomiWriteBindingRequest(3, 0x10000, 0, 0), RangeError); +}); + +test("lighting decode reads effect, speed and RGB", () => { + const data = reply(XIAOMI_HEADER, 0xa0, 0, 0, 6, 4, 0, 0, 0x00, 0xff, 0x80); + assert.deepEqual(xiaomiDecodeLighting(data), { effect: 5, speed: 4, color: [0x00, 0xff, 0x80] }); + assert.throws(() => xiaomiDecodeLighting(reply(XIAOMI_HEADER, 0xa1, 0, 0, 6, 4, 0, 0, 0, 0, 0)), Error); + assert.throws(() => xiaomiDecodeLighting(new Uint8Array([XIAOMI_HEADER, 0xa0])), Error); +}); + +test("battery decode reads the percentage", () => { + assert.equal(xiaomiDecodeBattery(reply(XIAOMI_HEADER, 0x90, 0, 87)), 87); + assert.throws(() => xiaomiDecodeBattery(reply(XIAOMI_HEADER, 0x91, 0, 87)), Error); +}); + +test("polling decode maps the wire byte back to Hz", () => { + assert.equal(xiaomiDecodePolling(reply(XIAOMI_HEADER, 0xc4, 0, 0x02)), 500); + assert.throws(() => xiaomiDecodePolling(reply(XIAOMI_HEADER, 0xc4, 0, 0x03)), Error); +}); + +test("DPI decode reads five levels and clamps the active level", () => { + const data = reply(XIAOMI_HEADER, 0xc2, 0, 2, 16, 32, 48, 96, 2); + assert.deepEqual(xiaomiDecodeDpi(data), { levels: [100, 800, 1600, 2400, 4800], active: 2 }); + const clamped = reply(XIAOMI_HEADER, 0xc2, 0, 2, 16, 32, 48, 96, 9); + assert.equal(xiaomiDecodeDpi(clamped).active, XIAOMI_DPI_LEVELS - 1); + assert.throws(() => xiaomiDecodeDpi(new Uint8Array([XIAOMI_HEADER, 0xc2, 0, 2, 16, 32, 48])), Error); +}); + +test("binding decode handles direct combos, custom combos and macros", () => { + // The real device does not echo the button index in byte 2 (always 0x00). + const direct = reply(XIAOMI_HEADER, 0xb0, 0, 0, 0x01, 0x03, 0, 0); + assert.deepEqual(xiaomiDecodeBinding(direct), { mode: XIAOMI_KEY_COMBOS.CTRL_TAB }); + + const custom = reply(XIAOMI_HEADER, 0xb0, 0, 0, 0x01, 0x00, 0x01, 0x04); + assert.deepEqual(xiaomiDecodeBinding(custom), { + mode: XIAOMI_KEY_COMBOS.CUSTOM_KEY_COMBO, + modifiers: 0x01, + key: 0x04, + }); + + const macro = reply(XIAOMI_HEADER, 0xb0, 0, 0, 0x02, 0x01, 0x00, 0x10); + assert.deepEqual(xiaomiDecodeBinding(macro), { + mode: XIAOMI_KEY_COMBOS.MACROS_WITH_DELAY, + macroSize: 0x10, + }); +}); + +test("speeds are 1 through 8", () => { + assert.deepEqual(XIAOMI_SPEEDS, [1, 2, 3, 4, 5, 6, 7, 8]); +}); + +test("macro channel constants match the 64-byte hidraw layout", () => { + assert.equal(XIAOMI_MACRO_REPORT_ID, 0x57); + assert.equal(XIAOMI_MACRO_PACKET_SIZE, 64); + assert.equal(XIAOMI_MACRO_HEADER_LENGTH, 8); + assert.equal(XIAOMI_MACRO_EVENT_SIZE, 4); + assert.equal(XIAOMI_MACRO_MAX_EVENTS_PER_PACKET, 14); +}); + +test("macro read request is a 64-byte 0x57 0xf0 0x0d report with offset and chunk", () => { + const frame = xiaomiReadMacroRequest(0x0102, 56); + assert.equal(frame.length, XIAOMI_MACRO_PACKET_SIZE); + assert.deepEqual([...frame.slice(0, 8)], [0x57, 0xf0, 0x0d, 56, 0x00, 0x00, 0x01, 0x02]); + assert.deepEqual([...frame.slice(8, 12)], [0, 0, 0, 0]); + + const first = xiaomiReadMacroRequest(0, 4); + assert.deepEqual([...first.slice(0, 8)], [0x57, 0xf0, 0x0d, 4, 0x00, 0x00, 0x00, 0x00]); + + assert.throws(() => xiaomiReadMacroRequest(-1, 4), RangeError); + assert.throws(() => xiaomiReadMacroRequest(0x10000, 4), RangeError); + assert.throws(() => xiaomiReadMacroRequest(0, 57), RangeError); + assert.throws(() => xiaomiReadMacroRequest(0, -1), RangeError); +}); + +test("macro write request packs events as [key, state, delay_hi, delay_lo]", () => { + const events = [ + { key: 0x04, state: 0 as const, delayMs: 0 }, + { key: 0x04, state: 1 as const, delayMs: 0x0102 }, + ]; + const frame = xiaomiWriteMacroRequest(0x0008, events); + assert.equal(frame.length, XIAOMI_MACRO_PACKET_SIZE); + assert.deepEqual([...frame.slice(0, 8)], [0x57, 0xf1, 0x0d, 8, 0x00, 0x00, 0x00, 0x08]); + assert.deepEqual([...frame.slice(8, 16)], [0x04, 0x00, 0x00, 0x00, 0x04, 0x01, 0x01, 0x02]); + assert.deepEqual([...frame.slice(16, 20)], [0, 0, 0, 0]); + + assert.throws(() => xiaomiWriteMacroRequest(0, [{ key: 0x100, state: 0, delayMs: 0 }]), RangeError); + assert.throws(() => xiaomiWriteMacroRequest(0, [{ key: 0x04, state: 2, delayMs: 0 }]), RangeError); + assert.throws(() => xiaomiWriteMacroRequest(0, [{ key: 0x04, state: 0, delayMs: 0x10000 }]), RangeError); + assert.throws(() => xiaomiWriteMacroRequest(0x10000, []), RangeError); + assert.throws( + () => xiaomiWriteMacroRequest(0, Array.from({ length: 15 }, () => ({ key: 0x04, state: 0 as const, delayMs: 0 }))), + RangeError, + ); +}); + +test("macro chunk decode reads the event bytes and stops at the header length", () => { + const data = macroReply(0x57, 0xf0, 0x0d, 8, 0, 0, 0, 0, 0x04, 0x00, 0x00, 0x00, 0x04, 0x01, 0x01, 0x02); + assert.deepEqual(xiaomiDecodeMacroChunk(data), { + packetSize: 8, + events: [ + { key: 0x04, state: 0, delayMs: 0 }, + { key: 0x04, state: 1, delayMs: 0x0102 }, + ], + }); + + const end = macroReply(0x57, 0xf0, 0x0d, 0, 0, 0, 0, 0); + assert.deepEqual(xiaomiDecodeMacroChunk(end), { packetSize: 0, events: [] }); + + assert.throws(() => xiaomiDecodeMacroChunk(macroReply(0x57, 0xf1, 0x0d, 8)), Error); + assert.throws(() => xiaomiDecodeMacroChunk(new Uint8Array([0x57, 0xf0, 0x0d, 8])), Error); +}); + +test("macro packets chunk events into groups of 14", () => { + const events = Array.from({ length: 30 }, (_, i) => ({ key: 0x04, state: (i % 2) as 0 | 1, delayMs: 0 })); + const packets = xiaomiMacroPackets(events); + assert.equal(packets.length, 3); + assert.equal(packets[0].length, 14); + assert.equal(packets[1].length, 14); + assert.equal(packets[2].length, 2); + assert.deepEqual(packets[2][0], { key: 0x04, state: 0, delayMs: 0 }); + + assert.deepEqual(xiaomiMacroPackets([]), []); + assert.equal(xiaomiMacroPackets([{ key: 1, state: 0, delayMs: 0 }])[0].length, 1); +}); diff --git a/src/xiaomi/index.ts b/src/xiaomi/index.ts new file mode 100644 index 0000000..d725bbe --- /dev/null +++ b/src/xiaomi/index.ts @@ -0,0 +1,716 @@ +/* + * Xiaomi Mi Gaming Mouse configuration protocol. + * + * The command layout is reverse-engineered from the third-party Qt app + * JUGGERNAUT13/XIAOMI_MI_GAMING_MOUSE_APP (mainwindow.cpp / mainwindow.h), + * which the protocol contributor tested on hardware. Every command and reply + * is a 32-byte report headed by 0x4D followed by the command byte; the device + * answers with an input report that echoes the header and command byte. + */ + +export const XIAOMI_VENDOR_ID = 0x2717; +/** + * First byte of every 32-byte hidraw report. It is also the HID report ID + * of the vendor control channel, so it doubles as `XIAOMI_REPORT_ID`. + */ +export const XIAOMI_HEADER = 0x4d; +/** + * Size of the raw hidraw buffer: 1 report-ID byte + 31 data bytes. + * The codec builds and parses this 32-byte layout; the WebHID driver + * strips the leading report-ID byte before calling `sendReport`. + */ +export const XIAOMI_PACKET_SIZE = 32; +/** + * HID report ID of the vendor control channel (vendor page 0xFF00, + * usage 2, 31-byte reports). The Qt app writes it as the first byte of + * its 32-byte hidraw buffer; WebHID passes it as `sendReport`'s first + * argument instead. + */ +export const XIAOMI_REPORT_ID = XIAOMI_HEADER; +/** Data size of one control report, excluding the report-ID byte. */ +export const XIAOMI_REPORT_DATA_SIZE = XIAOMI_PACKET_SIZE - 1; + +export interface XiaomiDeviceDefinition { + name: string; + wireless: boolean; + verified: boolean; +} + +/** + * Product IDs of the Mi Gaming Mouse. The wired PID is verified on hardware; + * the wireless PID is reported by the reference app as "NOT WORKING IN + * WIRELESS MODE, BUT COMMANDS EXEC SUCCESSFULLY", so it is unverified. + */ +export const XIAOMI_DEVICES: ReadonlyMap = new Map([ + [0x5009, { name: "Mi Gaming Mouse", wireless: false, verified: true }], + [0x500b, { name: "Mi Gaming Mouse", wireless: true, verified: false }], +]); + +export const XIAOMI_PRODUCT_IDS: ReadonlySet = new Set(XIAOMI_DEVICES.keys()); + +/* --------------------------------- + * Lighting + * --------------------------------- */ + +/** Wire zone ids. */ +export const XIAOMI_LIGHTING_DEVICES = { TAIL: 0, WHEEL: 1 } as const; +export type XiaomiLightingDevice = keyof typeof XIAOMI_LIGHTING_DEVICES; + +/** + * Logical effect values. 4 is a gap in the firmware's enum; the wire value is + * `effect + (effect > 3 ? 1 : 0)`, so the wire gaps are 4 and 5. + */ +export const XIAOMI_EFFECTS = [0, 1, 2, 3, 5, 6] as const; +export type XiaomiEffect = (typeof XIAOMI_EFFECTS)[number]; + +/** Effects each zone accepts. The wheel only supports Off and Static. */ +export const XIAOMI_EFFECTS_BY_DEVICE: Record = { + TAIL: [0, 1, 2, 3, 5, 6], + WHEEL: [0, 1], +}; + +/** Blink speed, 1 (slowest) to 8 (fastest). */ +export const XIAOMI_SPEEDS = [1, 2, 3, 4, 5, 6, 7, 8] as const; + +export function xiaomiEffectToWire(effect: number): number { + return effect + (effect > 3 ? 1 : 0); +} + +export function xiaomiEffectFromWire(wire: number): number { + return wire - (wire > 3 ? 1 : 0); +} + +/* --------------------------------- + * Polling rate + * --------------------------------- */ + +/** + * Supported rates in wire order: index `i` is encoded on the wire as the byte + * `1 << i`. Display order is the reverse (ascending). + */ +export const XIAOMI_POLLING_RATES = [1000, 500, 250, 125] as const; + +export function xiaomiPollingRateToWire(hz: number): number { + const index = (XIAOMI_POLLING_RATES as readonly number[]).indexOf(hz); + if (index < 0) throw new RangeError(`Xiaomi polling rate ${hz} Hz is not supported.`); + return 1 << index; +} + +export function xiaomiPollingRateFromWire(byte: number): number { + const index = Math.log2(byte); + if (!Number.isInteger(index) || index < 0 || index >= XIAOMI_POLLING_RATES.length) { + throw new Error(`Unknown Xiaomi polling value 0x${byte.toString(16).padStart(2, "0")}.`); + } + return XIAOMI_POLLING_RATES[index]; +} + +/* --------------------------------- + * DPI + * --------------------------------- */ + +export const XIAOMI_DPI_STEP = 50; +export const XIAOMI_DPI_LEVELS = 5; +export const XIAOMI_DPI_MIN = 50; +export const XIAOMI_DPI_MAX = 7200; + +export function xiaomiDpiToWire(dpi: number): number { + if (!Number.isInteger(dpi) || dpi < XIAOMI_DPI_MIN || dpi > XIAOMI_DPI_MAX || dpi % XIAOMI_DPI_STEP !== 0) { + throw new RangeError(`Xiaomi DPI ${dpi} must be ${XIAOMI_DPI_MIN}-${XIAOMI_DPI_MAX} in steps of ${XIAOMI_DPI_STEP}.`); + } + return dpi / XIAOMI_DPI_STEP; +} + +export function xiaomiDpiFromWire(byte: number): number { + return byte * XIAOMI_DPI_STEP; +} + +/* --------------------------------- + * Button binding + * --------------------------------- */ + +/** Wire button ids. Left and right click are not bindable in the reference app but the firmware allows it. */ +export const XIAOMI_BUTTONS = { + LEFT: 0, + RIGHT: 1, + SCROLL: 2, + M5: 3, + M4: 4, + RISE_DPI: 5, + LOWER_DPI: 6, + AIMING: 7, +} as const; + +/** + * Binding modes. Values 0x0001-0x0008 and 0x0101-0x010c are direct key + * combos; 0x0100 is a custom combo (modifier + key); 0x0200/0x0201 are macros + * (with and without per-event delay). + */ +export const XIAOMI_KEY_COMBOS = { + LEFT_CLICK: 0x0001, + RIGHT_CLICK: 0x0002, + MIDDLE_CLICK: 0x0003, + MOVE_BACK: 0x0004, + MOVE_FORWARD: 0x0005, + RISE_DPI: 0x0006, + LOWER_DPI: 0x0007, + TURN_DPI: 0x0008, + ALT_F4: 0x0101, + WIN_D: 0x0102, + CTRL_TAB: 0x0103, + CTRL_SHIFT_TAB: 0x0104, + CTRL_X: 0x0105, + CTRL_V: 0x0106, + CTRL_Z: 0x0107, + CTRL_Y: 0x0108, + CTRL_C: 0x0109, + VOLUME_UP: 0x010a, + VOLUME_DOWN: 0x010b, + SILENT_MODE: 0x010c, + CUSTOM_KEY_COMBO: 0x0100, + MACROS_NO_DELAY: 0x0200, + MACROS_WITH_DELAY: 0x0201, +} as const; + +/** Modifier bitmask for custom key combos. */ +export const XIAOMI_KEY_MODIFIERS = { + LEFT_CTRL: 0x01, + LEFT_SHIFT: 0x02, + LEFT_ALT: 0x04, + LEFT_WIN: 0x08, + RIGHT_CTRL: 0x10, + RIGHT_SHIFT: 0x20, + RIGHT_ALT: 0x40, + RIGHT_WIN: 0x80, +} as const; + +/** HID keyboard usage codes for custom key combos. */ +export const XIAOMI_KEY_CODES = { + CTRL_BREAK: 0x03, + A: 0x04, + B: 0x05, + C: 0x06, + D: 0x07, + E: 0x08, + F: 0x09, + G: 0x0a, + H: 0x0b, + I: 0x0c, + J: 0x0d, + K: 0x0e, + L: 0x0f, + M: 0x10, + N: 0x11, + O: 0x12, + P: 0x13, + Q: 0x14, + R: 0x15, + S: 0x16, + T: 0x17, + U: 0x18, + V: 0x19, + W: 0x1a, + X: 0x1b, + Y: 0x1c, + Z: 0x1d, + ONE: 0x1e, + TWO: 0x1f, + THREE: 0x20, + FOUR: 0x21, + FIVE: 0x22, + SIX: 0x23, + SEVEN: 0x24, + EIGHT: 0x25, + NINE: 0x26, + ZERO: 0x27, + ENTER: 0x28, + ESCAPE: 0x29, + BACKSPACE: 0x2a, + TAB: 0x2b, + SPACE: 0x2c, + SUB: 0x2d, + EQUAL: 0x2e, + SQR_BRKT_OPEN: 0x2f, + SQR_BRKT_CLOSE: 0x30, + BACKSLASH: 0x31, + SEMICOLON: 0x33, + APOSTROPHE: 0x34, + BACKTICK: 0x35, + COMMA: 0x36, + DOT: 0x37, + SLASH: 0x38, + CAPS_LOCK: 0x39, + F1: 0x3a, + F2: 0x3b, + F3: 0x3c, + F4: 0x3d, + F5: 0x3e, + F6: 0x3f, + F7: 0x40, + F8: 0x41, + F9: 0x42, + F10: 0x43, + F11: 0x44, + F12: 0x45, + PRINT_SCREEN: 0x46, + SCROLL_LOCK: 0x47, + PAUSE: 0x48, + INSERT: 0x49, + HOME: 0x4a, + PAGE_UP: 0x4b, + DELETE: 0x4c, + END: 0x4d, + PAGE_DOWN: 0x4e, + RIGHT_ARROW: 0x4f, + LEFT_ARROW: 0x50, + DOWN_ARROW: 0x51, + UP_ARROW: 0x52, + NUM_LOCK: 0x53, + NUMPAD_DIV: 0x54, + NUMPAD_MULT: 0x55, + NUMPAD_SUB: 0x56, + NUMPAD_ADD: 0x57, + NUMPAD_ENTER: 0x58, + NUMPAD_1: 0x59, + NUMPAD_2: 0x5a, + NUMPAD_3: 0x5b, + NUMPAD_4: 0x5c, + NUMPAD_5: 0x5d, + NUMPAD_6: 0x5e, + NUMPAD_7: 0x5f, + NUMPAD_8: 0x60, + NUMPAD_9: 0x61, + NUMPAD_0: 0x62, + NUMPAD_DOT: 0x63, + LESS: 0x64, + APPS_MENU: 0x65, + LEFT_CTRL: 0xe0, + LEFT_SHIFT: 0xe1, + LEFT_ALT: 0xe2, + LEFT_WIN: 0xe3, + RIGHT_CTRL: 0xe4, + RIGHT_SHIFT: 0xe5, + RIGHT_ALT: 0xe6, + RIGHT_WIN: 0xe7, +} as const; + +/** Display names of the bindable buttons, indexed by wire button id. */ +export const XIAOMI_BUTTON_NAMES = [ + "Left", + "Right", + "Scroll", + "M5", + "M4", + "Rise DPI", + "Lower DPI", + "Aiming", +] as const; + +/** + * The preset key combos a button can be mapped to, in display order. Custom + * combos and macros are not presets: they are shown via + * {@link xiaomiBindingLabel} and cannot be selected from the list. + */ +export const XIAOMI_BUTTON_ACTIONS: ReadonlyArray<{ label: string; combo: number }> = [ + { label: "Left-click", combo: XIAOMI_KEY_COMBOS.LEFT_CLICK }, + { label: "Right-click", combo: XIAOMI_KEY_COMBOS.RIGHT_CLICK }, + { label: "Middle-click", combo: XIAOMI_KEY_COMBOS.MIDDLE_CLICK }, + { label: "Move back", combo: XIAOMI_KEY_COMBOS.MOVE_BACK }, + { label: "Move forward", combo: XIAOMI_KEY_COMBOS.MOVE_FORWARD }, + { label: "Rise DPI", combo: XIAOMI_KEY_COMBOS.RISE_DPI }, + { label: "Lower DPI", combo: XIAOMI_KEY_COMBOS.LOWER_DPI }, + { label: "Turn DPI", combo: XIAOMI_KEY_COMBOS.TURN_DPI }, + { label: "Alt+F4", combo: XIAOMI_KEY_COMBOS.ALT_F4 }, + { label: "Win+D", combo: XIAOMI_KEY_COMBOS.WIN_D }, + { label: "Ctrl+Tab", combo: XIAOMI_KEY_COMBOS.CTRL_TAB }, + { label: "Ctrl+Shift+Tab", combo: XIAOMI_KEY_COMBOS.CTRL_SHIFT_TAB }, + { label: "Ctrl+X", combo: XIAOMI_KEY_COMBOS.CTRL_X }, + { label: "Ctrl+V", combo: XIAOMI_KEY_COMBOS.CTRL_V }, + { label: "Ctrl+Z", combo: XIAOMI_KEY_COMBOS.CTRL_Z }, + { label: "Ctrl+Y", combo: XIAOMI_KEY_COMBOS.CTRL_Y }, + { label: "Ctrl+C", combo: XIAOMI_KEY_COMBOS.CTRL_C }, + { label: "Volume up", combo: XIAOMI_KEY_COMBOS.VOLUME_UP }, + { label: "Volume down", combo: XIAOMI_KEY_COMBOS.VOLUME_DOWN }, + { label: "Silent mode", combo: XIAOMI_KEY_COMBOS.SILENT_MODE }, +]; + +const XIAOMI_MODIFIER_NAMES: ReadonlyArray<{ bit: number; name: string }> = [ + { bit: XIAOMI_KEY_MODIFIERS.LEFT_CTRL, name: "Ctrl" }, + { bit: XIAOMI_KEY_MODIFIERS.LEFT_SHIFT, name: "Shift" }, + { bit: XIAOMI_KEY_MODIFIERS.LEFT_ALT, name: "Alt" }, + { bit: XIAOMI_KEY_MODIFIERS.LEFT_WIN, name: "Win" }, + { bit: XIAOMI_KEY_MODIFIERS.RIGHT_CTRL, name: "R-Ctrl" }, + { bit: XIAOMI_KEY_MODIFIERS.RIGHT_SHIFT, name: "R-Shift" }, + { bit: XIAOMI_KEY_MODIFIERS.RIGHT_ALT, name: "R-Alt" }, + { bit: XIAOMI_KEY_MODIFIERS.RIGHT_WIN, name: "R-Win" }, +]; + +const XIAOMI_KEY_CODE_NAMES: Record = Object.fromEntries( + Object.entries(XIAOMI_KEY_CODES).map(([name, code]) => [code, name.replace(/_/g, " ")]), +); + +/** + * Human-readable label for a binding: the preset label for direct key combos, + * `Custom (…)` for a custom combo, `Macro (N events)` for macros. Returns + * `undefined` for unknown modes so callers can fall back to "Unknown". + */ +export function xiaomiBindingLabel(binding: XiaomiBinding): string | undefined { + const preset = XIAOMI_BUTTON_ACTIONS.find((action) => action.combo === binding.mode); + if (preset) return preset.label; + if (binding.mode === XIAOMI_KEY_COMBOS.CUSTOM_KEY_COMBO) { + const parts: string[] = []; + for (const { bit, name } of XIAOMI_MODIFIER_NAMES) { + if ((binding.modifiers ?? 0) & bit) parts.push(name); + } + const key = XIAOMI_KEY_CODE_NAMES[binding.key ?? 0]; + parts.push(key ?? `0x${(binding.key ?? 0).toString(16)}`); + return `Custom (${parts.join("+")})`; + } + if (binding.mode === XIAOMI_KEY_COMBOS.MACROS_NO_DELAY || binding.mode === XIAOMI_KEY_COMBOS.MACROS_WITH_DELAY) { + return `Macro (${Math.round((binding.macroSize ?? 0) / XIAOMI_MACRO_EVENT_SIZE)} events)`; + } + return undefined; +} + +export interface XiaomiBinding { + /** Binding mode (a key combo, 0x0100 custom, or 0x0200/0x0201 macro). */ + mode: number; + /** Macro size in bytes, present for macro modes. */ + macroSize?: number; + /** Modifier bitmask, present for the custom-combo mode. */ + modifiers?: number; + /** HID keyboard usage, present for the custom-combo mode. */ + key?: number; +} + +/* --------------------------------- + * Macro + * --------------------------------- */ + +/** + * HID report ID of the macro channel. The Qt app writes it as the first byte + * of its 64-byte hidraw buffer; WebHID passes it as `sendReport`'s first + * argument instead. + */ +export const XIAOMI_MACRO_REPORT_ID = 0x57; +/** Size of the raw hidraw macro buffer: 1 report-ID byte + 63 data bytes. */ +export const XIAOMI_MACRO_PACKET_SIZE = 64; +/** Data size of one macro report, excluding the report-ID byte. */ +export const XIAOMI_MACRO_REPORT_DATA_SIZE = XIAOMI_MACRO_PACKET_SIZE - 1; +/** Fixed header length of a macro packet (bytes 0-7). */ +export const XIAOMI_MACRO_HEADER_LENGTH = 8; +/** Size of one macro event on the wire: [key, state, delay_hi, delay_lo]. */ +export const XIAOMI_MACRO_EVENT_SIZE = 4; +/** Max event bytes per macro packet: 64 - 8 = 56. */ +export const XIAOMI_MACRO_MAX_EVENT_BYTES = XIAOMI_MACRO_PACKET_SIZE - XIAOMI_MACRO_HEADER_LENGTH; +/** Max events per macro packet: 56 / 4 = 14. */ +export const XIAOMI_MACRO_MAX_EVENTS_PER_PACKET = XIAOMI_MACRO_MAX_EVENT_BYTES / XIAOMI_MACRO_EVENT_SIZE; + +/** + * A single macro event. `state` is 0 (pressed) or 1 (released). `delayMs` is + * the delay before this event, meaningful only for the with-delay macro mode + * and always 0 for the first event. + */ +export interface XiaomiMacroEvent { + key: number; + state: 0 | 1; + delayMs: number; +} + +/** Decoded macro chunk: the event-byte count and the events it carries. */ +export interface XiaomiMacroChunk { + /** Number of event bytes in this packet (byte 3 of the reply). */ + packetSize: number; + events: XiaomiMacroEvent[]; +} + +/** + * Split a macro into packets of at most {@link XIAOMI_MACRO_MAX_EVENTS_PER_PACKET} + * events, in order. The driver writes one packet per chunk. + */ +export function xiaomiMacroPackets(events: readonly XiaomiMacroEvent[]): XiaomiMacroEvent[][] { + const packets: XiaomiMacroEvent[][] = []; + for (let i = 0; i < events.length; i += XIAOMI_MACRO_MAX_EVENTS_PER_PACKET) { + packets.push(events.slice(i, i + XIAOMI_MACRO_MAX_EVENTS_PER_PACKET)); + } + return packets; +} + +/* --------------------------------- + * Helpers + * --------------------------------- */ + +function request(...bytes: number[]): Uint8Array { + const data = new Uint8Array(XIAOMI_PACKET_SIZE); + data.set(bytes); + return data; +} + +function macroRequest(...bytes: number[]): Uint8Array { + const data = new Uint8Array(XIAOMI_MACRO_PACKET_SIZE); + data.set(bytes); + return data; +} + +function requirePrefix(data: Uint8Array, expected: readonly number[], name: string, minLength: number): void { + if (data.length < minLength) { + throw new Error(`${name} reply is too short.`); + } + + expected.forEach((byte, i) => { + if (data[i] !== byte) { + throw new Error(`${name} reply has unexpected byte ${i}: 0x${data[i].toString(16).padStart(2, "0")}.`); + } + }); +} + +function lightingZone(device: number): XiaomiLightingDevice { + if (device === XIAOMI_LIGHTING_DEVICES.TAIL) return "TAIL"; + if (device === XIAOMI_LIGHTING_DEVICES.WHEEL) return "WHEEL"; + throw new RangeError("Xiaomi lighting device must be 0 (tail) or 1 (wheel)."); +} + +export function xiaomiHexColorToRgb(color: string): [number, number, number] { + const match = /^#?([0-9a-f]{6})$/i.exec(color.trim()); + if (!match) throw new RangeError(`Xiaomi color must be "#rrggbb", got "${color}".`); + const value = parseInt(match[1], 16); + return [(value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff]; +} + +export function xiaomiRgbToHexColor(rgb: readonly [number, number, number]): string { + const hex = (n: number) => n.toString(16).padStart(2, "0"); + return `#${hex(rgb[0])}${hex(rgb[1])}${hex(rgb[2])}`; +} + +/* --------------------------------- + * READ REQUESTS + * --------------------------------- */ + +export function xiaomiReadLightingRequest(device: number): Uint8Array { + lightingZone(device); + return request(XIAOMI_HEADER, 0xa0, device); +} + +export function xiaomiReadBatteryRequest(): Uint8Array { + return request(XIAOMI_HEADER, 0x90); +} + +export function xiaomiReadPollingRequest(): Uint8Array { + return request(XIAOMI_HEADER, 0xc4); +} + +export function xiaomiReadDpiRequest(): Uint8Array { + return request(XIAOMI_HEADER, 0xc2); +} + +export function xiaomiReadBindingRequest(button: number): Uint8Array { + if (!Number.isInteger(button) || button < 0 || button > 7) { + throw new RangeError("Xiaomi button must be 0-7."); + } + return request(XIAOMI_HEADER, 0xb0, button); +} + +/* --------------------------------- + * WRITES + * --------------------------------- */ + +export function xiaomiWriteLightingRequest( + device: number, + effect: number, + speed: number, + rgb: readonly [number, number, number], +): Uint8Array { + const zone = lightingZone(device); + if (!XIAOMI_EFFECTS_BY_DEVICE[zone].includes(effect as XiaomiEffect)) { + throw new RangeError(`Xiaomi effect ${effect} is not supported for the ${zone.toLowerCase()} zone.`); + } + if (!XIAOMI_SPEEDS.includes(speed as (typeof XIAOMI_SPEEDS)[number])) { + throw new RangeError("Xiaomi lighting speed must be 1-8."); + } + return request(XIAOMI_HEADER, 0xa1, device, xiaomiEffectToWire(effect), speed, 0x08, 0x08, rgb[0], rgb[1], rgb[2]); +} + +export function xiaomiWritePollingRequest(hz: number): Uint8Array { + return request(XIAOMI_HEADER, 0xc3, xiaomiPollingRateToWire(hz)); +} + +export function xiaomiWriteDpiRequest(levels: readonly number[], active: number): Uint8Array { + if (levels.length !== XIAOMI_DPI_LEVELS) { + throw new RangeError(`Xiaomi DPI needs exactly ${XIAOMI_DPI_LEVELS} levels.`); + } + if (!Number.isInteger(active) || active < 0 || active >= XIAOMI_DPI_LEVELS) { + throw new RangeError(`Xiaomi active DPI level must be 0-${XIAOMI_DPI_LEVELS - 1}.`); + } + const bytes = [XIAOMI_HEADER, 0xc1]; + for (const level of levels) bytes.push(xiaomiDpiToWire(level)); + bytes.push(active, 0x00, 0x05); + return request(...bytes); +} + +export function xiaomiWriteBindingRequest(button: number, combo: number, modifiers: number, key: number): Uint8Array { + if (!Number.isInteger(button) || button < 0 || button > 7) { + throw new RangeError("Xiaomi button must be 0-7."); + } + if (!Number.isInteger(combo) || combo < 0 || combo > 0xffff) { + throw new RangeError("Xiaomi binding combo must fit in 16 bits."); + } + return request(XIAOMI_HEADER, 0xb1, button, combo >> 8, combo & 0xff, modifiers, key); +} + +/* --------------------------------- + * READ DECODERS + * --------------------------------- */ + +export interface XiaomiLighting { + effect: number; + speed: number; + color: [number, number, number]; +} + +export function xiaomiDecodeLighting(data: Uint8Array): XiaomiLighting { + requirePrefix(data, [XIAOMI_HEADER, 0xa0], "Xiaomi lighting", 11); + return { + effect: xiaomiEffectFromWire(data[4]), + speed: data[5], + color: [data[8], data[9], data[10]], + }; +} + +export function xiaomiDecodeBattery(data: Uint8Array): number { + requirePrefix(data, [XIAOMI_HEADER, 0x90], "Xiaomi battery", 4); + return data[3]; +} + +export function xiaomiDecodePolling(data: Uint8Array): number { + requirePrefix(data, [XIAOMI_HEADER, 0xc4], "Xiaomi polling", 4); + return xiaomiPollingRateFromWire(data[3]); +} + +export interface XiaomiDpi { + levels: number[]; + active: number; +} + +export function xiaomiDecodeDpi(data: Uint8Array): XiaomiDpi { + requirePrefix(data, [XIAOMI_HEADER, 0xc2], "Xiaomi DPI", 9); + const levels = Array.from({ length: XIAOMI_DPI_LEVELS }, (_, i) => xiaomiDpiFromWire(data[3 + i])); + let active = data[8]; + if (active > XIAOMI_DPI_LEVELS - 1) active = XIAOMI_DPI_LEVELS - 1; + return { levels, active }; +} + +export function xiaomiDecodeBinding(data: Uint8Array): XiaomiBinding { + // The device does not echo the button index in byte 2 (it stays 0x00), so + // only the header and command are validated; the reply is correlated with + // the request by the driver's request/response exchange. + requirePrefix(data, [XIAOMI_HEADER, 0xb0], "Xiaomi binding", 8); + const mode = (data[4] << 8) | data[5]; + const result: XiaomiBinding = { mode }; + if (mode === XIAOMI_KEY_COMBOS.MACROS_NO_DELAY || mode === XIAOMI_KEY_COMBOS.MACROS_WITH_DELAY) { + const size = (data[6] << 8) | data[7]; + result.macroSize = size >= 0x8000 ? size - 0x10000 : size; + } else if (mode === XIAOMI_KEY_COMBOS.CUSTOM_KEY_COMBO) { + result.modifiers = data[6]; + result.key = data[7]; + } + return result; +} + +/* --------------------------------- + * Macro + * --------------------------------- */ + +/** + * Build a macro read request (0x57 0xf0 0x0d). `offset` is the cumulative + * event-byte offset to resume from; `chunkSize` is the number of event bytes + * to request (max {@link XIAOMI_MACRO_MAX_EVENT_BYTES}). The device replies + * with a 64-byte packet whose byte 3 is the number of event bytes returned. + */ +export function xiaomiReadMacroRequest(offset: number, chunkSize: number): Uint8Array { + if (!Number.isInteger(offset) || offset < 0 || offset > 0xffff) { + throw new RangeError("Xiaomi macro offset must be a 16-bit integer"); + } + if (!Number.isInteger(chunkSize) || chunkSize < 0 || chunkSize > XIAOMI_MACRO_MAX_EVENT_BYTES) { + throw new RangeError(`Xiaomi macro chunk size must be 0..${XIAOMI_MACRO_MAX_EVENT_BYTES}`); + } + return macroRequest( + XIAOMI_MACRO_REPORT_ID, + 0xf0, + 0x0d, + chunkSize, + 0x00, + 0x00, + (offset >> 8) & 0xff, + offset & 0xff, + ); +} + +/** + * Build a macro write packet (0x57 0xf1 0x0d). `offset` is the cumulative + * event-byte offset of this packet; `events` holds at most + * {@link XIAOMI_MACRO_MAX_EVENTS_PER_PACKET} events. Each event is encoded as + * [key, state, delay_hi, delay_lo]. The device does not reply. + */ +export function xiaomiWriteMacroRequest(offset: number, events: readonly XiaomiMacroEvent[]): Uint8Array { + if (!Number.isInteger(offset) || offset < 0 || offset > 0xffff) { + throw new RangeError("Xiaomi macro offset must be a 16-bit integer"); + } + if (events.length > XIAOMI_MACRO_MAX_EVENTS_PER_PACKET) { + throw new RangeError(`A Xiaomi macro packet holds at most ${XIAOMI_MACRO_MAX_EVENTS_PER_PACKET} events`); + } + const data = macroRequest( + XIAOMI_MACRO_REPORT_ID, + 0xf1, + 0x0d, + events.length * XIAOMI_MACRO_EVENT_SIZE, + 0x00, + 0x00, + (offset >> 8) & 0xff, + offset & 0xff, + ); + events.forEach((event, i) => { + const pos = XIAOMI_MACRO_HEADER_LENGTH + i * XIAOMI_MACRO_EVENT_SIZE; + if (!Number.isInteger(event.key) || event.key < 0 || event.key > 0xff) { + throw new RangeError("Xiaomi macro key must be a byte"); + } + if (event.state !== 0 && event.state !== 1) { + throw new RangeError("Xiaomi macro state must be 0 (pressed) or 1 (released)"); + } + if (!Number.isInteger(event.delayMs) || event.delayMs < 0 || event.delayMs > 0xffff) { + throw new RangeError("Xiaomi macro delay must be a 16-bit integer"); + } + data[pos] = event.key; + data[pos + 1] = event.state; + data[pos + 2] = (event.delayMs >> 8) & 0xff; + data[pos + 3] = event.delayMs & 0xff; + }); + return data; +} + +/** + * Decode a macro read reply. Byte 3 is the number of event bytes in the + * packet; events start at byte 8. A `packetSize` below the header length + * signals the end of the macro. + */ +export function xiaomiDecodeMacroChunk(data: Uint8Array): XiaomiMacroChunk { + if (data.length < XIAOMI_MACRO_PACKET_SIZE) { + throw new Error(`Xiaomi macro reply must be ${XIAOMI_MACRO_PACKET_SIZE} bytes, got ${data.length}`); + } + if (data[0] !== XIAOMI_MACRO_REPORT_ID || data[1] !== 0xf0 || data[2] !== 0x0d) { + throw new Error("Xiaomi macro reply has an unexpected header"); + } + const packetSize = data[3]; + if (packetSize < XIAOMI_MACRO_HEADER_LENGTH) { + return { packetSize, events: [] }; + } + const count = Math.min(packetSize / XIAOMI_MACRO_EVENT_SIZE, XIAOMI_MACRO_MAX_EVENTS_PER_PACKET); + const events: XiaomiMacroEvent[] = []; + for (let i = 0; i < count; i++) { + const pos = XIAOMI_MACRO_HEADER_LENGTH + i * XIAOMI_MACRO_EVENT_SIZE; + events.push({ + key: data[pos], + state: data[pos + 1] === 1 ? 1 : 0, + delayMs: (data[pos + 2] << 8) | data[pos + 3], + }); + } + return { packetSize, events }; +} diff --git a/tsconfig.json b/tsconfig.json index 42402b8..8b0e39f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -55,7 +55,8 @@ "@openmouse/protocol/thermaltake": ["./src/thermaltake/index.ts"], "@openmouse/protocol/coolermaster": ["./src/coolermaster/index.ts"], "@openmouse/protocol/ajazz": ["./src/ajazz/index.ts"], - "@openmouse/protocol/hitscan": ["./src/hitscan/index.ts"] + "@openmouse/protocol/hitscan": ["./src/hitscan/index.ts"], + "@openmouse/protocol/xiaomi": ["./src/xiaomi/index.ts"] } }, "include": ["src/**/*"],