diff --git a/docs/angry-miao-infinity.md b/docs/angry-miao-infinity-100.md similarity index 96% rename from docs/angry-miao-infinity.md rename to docs/angry-miao-infinity-100.md index 277fd00f..d28992ac 100644 --- a/docs/angry-miao-infinity.md +++ b/docs/angry-miao-infinity-100.md @@ -4,9 +4,12 @@ The Angry Miao Infinity .100 (model AM30) is a wireless mouse. It is sold as "AM Infinity", and the vendor app calls it "AM Infinity .100". Yichip makes its chip and owns vendor ID 0x3151, so the mouse speaks the Yichip protocol. -- `AngryMiaoHidClient` (`src/drivers/angry-miao/hid.ts`) and its codec - (`src/angry-miao/`) handle everything for this mouse: sending reports, - passing commands through the receiver, and the settings layout. +- `AngryMiaoAm30HidClient` (`src/drivers/angry-miao/am30-hid.ts`) and its codec + (`src/angry-miao/am30.ts`) handle everything that goes over the wire for this + mouse: sending reports, passing commands through the receiver, and the + settings layout. The setters and their checks are shared with the + [Infinity .97 and .100R2](angry-miao-infinity-97-100R2.md) through + `AngryMiaoHidClient` (`src/drivers/angry-miao/hid.ts`). - Other brands use the same product IDs. The driver claims a device only when the product ID and the product name both say Angry Miao. - The driver reads the device ID with `8F` during each status read that reaches diff --git a/docs/angry-miao-infinity-97-100R2.md b/docs/angry-miao-infinity-97-100R2.md new file mode 100644 index 00000000..43093d40 --- /dev/null +++ b/docs/angry-miao-infinity-97-100R2.md @@ -0,0 +1,148 @@ +# Angry Miao Infinity .97 and .100R2 + +The Angry Miao Infinity .97 (model AM35) and Infinity .100R2 (model AM30R2) are +wireless mice built on MediaTek's Airoha chips (vendor ID 0x0E8D). They speak +Airoha's RACE command protocol, not the Yichip protocol of the +[Infinity .100](angry-miao-infinity-100.md). + +Original contributor does not have the necessary hardward to test. The drivers copy what the vendor +configurator at ammaster.angrymiao.com sends, from its bundle +`index-9145eff3.js`. The supported list marks both models "Test Needed" until +owners confirm them with OpenMouse's Hardware test. + +Until then the drivers only read. A status read reports every setting, and the +Hardware test records the readings, but OpenMouse shows no editor and every +setter refuses before it sends a change. The write path below is in place and +tested against a fake mouse; turning it on is a one-line change in +`AngryMiaoAm35HidClient` (`writable`) once an owner's report confirms the reads. + +- `AngryMiaoAm35HidClient` (`src/drivers/angry-miao/am35-hid.ts`) drives the + .97. `AngryMiaoAm30R2HidClient` drives the .100R2 and differs only in its + button numbers. +- The codec is `src/angry-miao/am35.ts`. The settings the three Infinity models + share (rates, debounce steps, lift-off levels, sleep presets, button actions) + live in `src/angry-miao/shared.ts`. +- `AngryMiaoHidClient` (`src/drivers/angry-miao/hid.ts`) holds the setters, + their checks and the one-step-at-a-time rule for all three models. Each + protocol client supplies only its reads and writes. + +## Identification + +| Model | Mouse | 2.4 GHz receiver | +| --- | --- | --- | +| Infinity .97 | 0E8D:0880, 35A1:0035 | 0E8D:0703 | +| Infinity .100R2 | 0E8D:0881 | 0E8D:0704 | + +The vendor app treats 0E8D:0880 and 35A1:0035 as a receiver when the product +name contains "dongle", "receiver" or "2.4". The drivers do the same. + +A driver claims a device when its vendor and product ID match and the interface +carries feature report 0x14, or output report 0x06 with input report 0x07. The +picker asks for the IDs alone, as the vendor app does. + +## Framing + +A RACE frame is `05 5A `. The length +counts the command and the payload. A reply has the same shape, and most reply +payloads start with a status byte, where 0 means done. + +One HID report carries ` `, zero padded to at +least 61 bytes. A chunk holds up to 59 frame bytes, so a longer frame, such as +the DPI table reply, spans several reports. + +- The drivers write to feature report 0x14 and poll it for the reply. They + wait up to 1.2 s, or 3 s through the receiver, as the vendor app does. +- Without report 0x14, they write output report 0x06 and wait for input report + 0x07. +- A firmware-version reply of just `00` only acknowledges the request. The + drivers wait for the next one. + +## Receiver + +Device ID 0 is the device the browser opened: the mouse on the cable, the +receiver on 2.4 GHz. Before it talks to the mouse through the +receiver, the driver sends the vendor app's opening sequence to the receiver +itself: + +1. `2C83` with `12 00` (receiver mode). +2. `2CB2` with `06` (link type). The vendor app sends this write on every + connect. +3. `2C94` and `2C96` (device and paired lists). + +When either list holds a device, the mouse answers on device ID 0x80. Without +feature report 0x14 the vendor app skips this sequence and sends mouse commands +to device 0, and the drivers do the same. The DPI read decides whether the mouse +answered; the battery read is optional. When the lists are empty or the DPI read +fails, OpenMouse shows the receiver alone. Until the receiver has been set up +this way, the driver refuses any mouse command, so nothing meant for the mouse +reaches the receiver by mistake. + +The link type write is the one command a read-only driver still sends, because +the vendor app sends it before it lists the receiver's devices. + +## Settings + +Each change goes out as the vendor app sends it, then the driver reads the +setting back. A change the mouse does not keep shows an error. + +| Setting | Read | Write | Payload | +| --- | --- | --- | --- | +| Report rate | `3011` | `3010` | Hz as LE16 | +| Debounce | `30E9` | `30E8` | raw cable, 2.4 GHz and Bluetooth bytes for the rate | +| Lift-off | `30CD` | `30CC` | 0 low, 1 medium, 2 high | +| Motion sync | `30D3` | `30D2` | 0 or 1 | +| Angle snapping | `30D5` | `30D4` | 0 or 1 | +| Ripple control | `30D7` | `30D6` | 0 or 1 | +| Blast Mode | `30DF` | `30DE` | 0 or 1 | +| Sleep | `3013` | `3012` | see below | +| DPI stage | `30C5` | `30C4` | stage, X LE16, Y LE16 | +| DPI stage count | `30C5` | `30C6` | count, then `30C7` with the active stage | +| Active DPI stage | `30C5` | `30C7` | stage | +| Button | `30C3` | `30C2` | key, action type, parameters | +| Mouse light | stored data `600A` | `30B3` | on, effect, speed; no reply on report 0x14 | +| Receiver light | `300E` | `300D` | on, effect, three hues with saturation, speed + 80, brightness; no reply | + +- A rate change rewrites debounce for the same step, because the raw bytes + differ per rate. These are the .100's tables. +- Sleep holds the 2.4 GHz timer, then the Bluetooth one. Each is three LE16 + parts that add up to the seconds, followed by two zero bytes. A fixed tail + `3C 00 1E 00 3C 00 1E 00` ends the payload. "Never" is 65535. OpenMouse + changes the 2.4 GHz timer and keeps the Bluetooth one. +- After editing the active DPI stage, the vendor app selects it again with + `30C7`. The drivers do the same. +- Button action types, with their parameters: + - 1 to 5: left, right, middle, forward and back. + - 12 and 13: scroll up and down. + - 11 with `00`, `01` or `03`: DPI up, down and cycle. + - 6 with a consumer usage LE16: media keys. + - 0: disabled. + + Left stays a left click, as on the .100. +- The .100R2 sends its buttons as `F0` to `F6` where the .97 uses 1 to 7. + The vendor app names its buttons 6 and 7 "custom key 1" and "custom key 2" + and restores them to scroll up and down. + +## What stays read-only + +The vendor app writes some settings into the mouse's stored data (`0A0D`), +not into a setting. The drivers never send that command, so these stay +read-only: + +- the mouse light's effect, speed and colour (OpenMouse can turn it on and off) +- the DPI stage colours + +The drivers also leave out profile switching, macros, rotation angle, DPI quick +switch, pairing and firmware update. + +`am35Frame` refuses every command outside the table above, so the drivers +cannot send factory reset, firmware update, pairing or reboot by mistake. + +## Automated tests + +- `src/angry-miao/am35.test.ts` checks the framing against the vendor app's own + example, every encoder and decoder, and the refused commands. +- `src/drivers/angry-miao/am35-hid.test.ts` runs both clients against a fake + mouse. It checks that a status read sends only reads, that the read-only + default refuses every setter, that no mouse command reaches an unlinked + receiver, every write and its read-back, the receiver's opening sequence, the + .100R2 button numbers and the output 0x06 fallback. diff --git a/docs/diagrams/angry-miao-relay-dark.svg b/docs/diagrams/angry-miao-relay-dark.svg index e382f505..8052079f 100644 --- a/docs/diagrams/angry-miao-relay-dark.svg +++ b/docs/diagrams/angry-miao-relay-dark.svg @@ -47,7 +47,7 @@ HOST OpenMouse driver -AngryMiaoHidClient +AngryMiaoAm30HidClient diff --git a/docs/diagrams/angry-miao-relay.svg b/docs/diagrams/angry-miao-relay.svg index a18adcfc..3f085eba 100644 --- a/docs/diagrams/angry-miao-relay.svg +++ b/docs/diagrams/angry-miao-relay.svg @@ -47,7 +47,7 @@ HOST OpenMouse driver -AngryMiaoHidClient +AngryMiaoAm30HidClient diff --git a/src/angry-miao/am30.ts b/src/angry-miao/am30.ts new file mode 100644 index 00000000..1a233fb2 --- /dev/null +++ b/src/angry-miao/am30.ts @@ -0,0 +1,362 @@ +/** + * Angry Miao Infinity .100 mouse (model AM30) on the Yichip (VID 0x3151) block + * protocol. This codec owns everything the Angry Miao driver + * (`src/drivers/angry-miao/`) sends; it does not share constants with the + * other Yichip brands, so their changes cannot move this mouse. + * + * Sources: replies read over the USB cable and the vendor configurator + * (ammaster.angrymiao.com, model page am30). See + * docs/angry-miao-infinity-100.md. + */ + +import { + ANGRY_MIAO_DEBOUNCE_GEARS_MS, + ANGRY_MIAO_DEBOUNCE_RAW, + ANGRY_MIAO_LIFT_OFF_LEVELS, + ANGRY_MIAO_RATES, + ANGRY_MIAO_SLEEP_OPTIONS, + angryMiaoDebounceGear, + angryMiaoDebounceRaw, + type AngryMiaoLiftOff, + type AngryMiaoModel, +} from "./shared.ts"; + +/** Yichip's vendor id. Other brands ship on it, so it never identifies this mouse alone. */ +export const ANGRY_MIAO_VENDOR_ID = 0x3151; +/** Product names: cable "Angry Miao Infinity", receiver "AM INFINITY 8K MOUSE", Bluetooth "AM INFINITY BT MOUSE". */ +export const ANGRY_MIAO_PRODUCT_NAME = /angry\s*miao|\bAM\s+INFINITY\b/i; +/** One unnumbered 64-byte feature report on usage page 0xFFFF, usage 0x02. */ +export const AM30_REPORT_ID = 0; +export const AM30_REPORT_SIZE = 64; +export const AM30_USAGE_PAGE = 0xffff; +export const AM30_USAGE = 0x02; + +/** Bluetooth: the same commands go out and come back as report 6 on 0xFF55:0x0202, after a `55` byte. */ +export const AM30_BT_USAGE_PAGE = 0xff55; +export const AM30_BT_USAGE = 0x0202; +export const AM30_BT_REPORT_ID = 6; +export const AM30_BT_REPORT_SIZE = 65; +export const AM30_BT_ENVELOPE = 0x55; +/** `77` asks for the battery (byte 1, percent); a reply of `88` means the mouse is asleep. */ +export const AM30_BT_BATTERY = 0x77; +export const AM30_BT_SLEEPING = 0x88; + +export function am30BluetoothPacket(encoded: Uint8Array): Uint8Array { + const packet = new Uint8Array(AM30_BT_REPORT_SIZE); + packet[0] = AM30_BT_ENVELOPE; + packet.set(encoded.subarray(0, AM30_BT_REPORT_SIZE - 1), 1); + return packet; +} + +/** Mouse commands. Blocks are read whole and written back whole. */ +export const AM30_CMD = { + GET_FIRMWARE: 0x80, + GET_DEVICE_ID: 0x8f, + GET_OPTIONS: 0xd3, + SET_OPTIONS: 0x53, + GET_DPI: 0xd4, + SET_DPI: 0x54, + GET_KEYMATRIX: 0xd0, + SET_KEYMATRIX: 0x50, +} as const; + +/** Receiver relay commands. Raw: no checksum. */ +export const AM30_RELAY = { + SELECT_TARGET: 0xf6, + GET_STATUS: 0xf7, + NOTICE_READ: 0xfc, + SET_LENGTH: 0xfe, +} as const; +export const AM30_TARGET_MOUSE = 0x05; +/** `F6 00` releases the receiver after a relay fails, as the vendor app does. */ +export const AM30_TARGET_NONE = 0x00; +/** The vendor app tries a relayed command this many times, 100 ms apart. */ +export const AM30_RELAY_ATTEMPTS = 3; +/** The vendor app sends `FE 40` before every relayed command. */ +export const AM30_RELAY_LENGTH = 0x40; + +/** Pad to 9 bytes; byte 7 is 255 minus the sum of bytes 0-6. */ +export function am30EncodeCommand(bytes: readonly number[]): Uint8Array { + const out = new Uint8Array(Math.max(9, bytes.length)); + out.set(bytes); + let sum = 0; + for (let i = 0; i < 7; i++) sum = (sum + out[i]) & 0xff; + out[7] = (255 - sum) & 0xff; + return out; +} + +/** Options block (`D3` / `53`) byte offsets. */ +export const AM30_OPT0_REPORT_RATE = 9; +export const AM30_OPT0_DEBOUNCE = 10; +export const AM30_OPT0_FLAGS = 12; +export const AM30_OPT0_SLEEP_BT = 40; +export const AM30_OPT0_SLEEP_24G = 44; +export const AM30_OPT0_LIFT_OFF = 52; +export const AM30_OPT0_ANGLE_SNAP = 53; + +/** Report rate byte: a code, not an index. */ +export const AM30_RATE_ENCODE: Readonly> = { + 125: 8, 250: 4, 500: 2, 1000: 1, 2000: 132, 4000: 130, 8000: 129, +}; +export const AM30_RATE_DECODE: Readonly> = Object.fromEntries( + Object.entries(AM30_RATE_ENCODE).map(([hz, code]) => [code, Number(hz)]), +); +export const AM30_RATES = ANGRY_MIAO_RATES; + +/** Lift-off byte 52: 0, 1, 2. */ +export const AM30_LIFT_OFF_LEVELS = ANGRY_MIAO_LIFT_OFF_LEVELS; +export type Am30LiftOff = AngryMiaoLiftOff; + +/** DPI block (`D4` / `54`): byte 2 active stage, byte 3 count, then X, Y and RGB per stage. */ +export const AM30_MAX_DPI_STAGES = 8; +export const AM30_DPI_X_OFFSET = 8; +export const AM30_DPI_Y_OFFSET = 24; +export const AM30_DPI_RGB_OFFSET = 40; + +/** OPTIONPARAM0 debounce bytes for the 2.4 GHz and Bluetooth links. */ +export const AM30_OPT0_DEBOUNCE_24G = 61; +export const AM30_OPT0_DEBOUNCE_BT = 62; +/** Ripple control on is byte 12 = 1 (captured from the vendor app). */ +export const AM30_OPT0_FLAG_RIPPLE = 1 << 0; +/** Motion sync, 1 = on. */ +export const AM30_OPT0_MOTION_SYNC = 63; +/** Mouse light: on/off switch and two RGB slots, which the vendor panel sets to one colour. */ +export const AM30_OPT0_LIGHT_COLOR = 54; +export const AM30_OPT0_LIGHT_COLOR_2 = 57; +export const AM30_OPT0_LIGHT = 60; +/** LE16 standby value meaning "never". */ +export const AM30_SLEEP_NEVER = 0xffff; + +export const AM30_SLEEP_OPTIONS = ANGRY_MIAO_SLEEP_OPTIONS; +export const AM30_DEBOUNCE_GEARS_MS = ANGRY_MIAO_DEBOUNCE_GEARS_MS; +export const AM30_DEBOUNCE_RAW = ANGRY_MIAO_DEBOUNCE_RAW; +export const am30DebounceGear = angryMiaoDebounceGear; +export const am30DebounceRaw = angryMiaoDebounceRaw; + +/** Battery read: byte 1 = charge state, byte 2 = percent valid, byte 3 = percent. */ +export const AM30_GET_BATTERY = 0xd6; +/** Blast Mode (sensor at its top frame rate): read byte 1, write `62 <0|1>`. */ +export const AM30_GET_BLAST_MODE = 0xe2; +export const AM30_SET_BLAST_MODE = 0x62; + +/** Onboard profiles: read `85` byte 1 (active, 0-based), switch with `05 `. */ +export const AM30_GET_PROFILE = 0x85; +export const AM30_SET_PROFILE = 0x05; +export const AM30_PROFILE_COUNT = 2; + +/** USB firmware read (`AD`): bytes 1-2, LE16. The SoC version is the shared `80` read. */ +export const AM30_GET_USB_VERSION = 0xad; + +const hexCode = (code: number) => `0x${code.toString(16).padStart(4, "0")}`; + +/** + * Raw firmware codes. The vendor app's names for them (SoC 0x0318 = 1.1.1, + * package 1.6) come from a table on its server, so they are not repeated here. + */ +export function am30FirmwareLabels(usbCode: number | null, socCode: number | null): string[] { + return [ + ...(socCode === null ? [] : [`Mouse SoC ${hexCode(socCode)}`]), + ...(usbCode === null ? [] : [`Mouse USB ${hexCode(usbCode)}`]), + ]; +} + +/** Receiver firmware reads, sent to the receiver itself. The vendor app reads these instead of `AD` on 2.4 GHz. */ +export const AM30_RECEIVER_GET_USB_VERSION = 0xf0; +export const AM30_RECEIVER_GET_RF_VERSION = 0xfb; +export const AM30_RECEIVER_GET_LED_VERSION = 0xae; + +/** `F0` and `AE` hold LE16 codes at bytes 1-2; `FB` does not echo and holds the RF code in byte 3. */ +export function am30ReceiverFirmwareLabels( + usb: Uint8Array | null, + rf: Uint8Array | null, + led: Uint8Array | null, +): string[] { + const le16 = (reply: Uint8Array) => reply[1] | (reply[2] << 8); + return [ + ...(usb ? [`Receiver USB ${hexCode(le16(usb))}`] : []), + ...(rf ? [`Receiver RF 0x${rf[3].toString(16).padStart(2, "0")}`] : []), + ...(led ? [`Receiver LED ${hexCode(le16(led))}`] : []), + ]; +} + +export type Am30ChargeState = "Discharging" | "Charging" | "Full" | "Unknown"; + +/** Receiver status (`F7`) byte 4: 0 while the mouse is linked. */ +export const AM30_STATUS_MOUSE_OFFLINE = 4; + +/** Receiver status (`F7`) byte 10: the spare battery in the dock, 1-100; 0 = none. */ +export const AM30_STATUS_SPARE_BATTERY = 10; + +/** As the vendor app reads it: 100 is full, below that the dock is charging it. */ +export function am30DecodeSpareBattery(status: Uint8Array): { percent: number; state: "Charging" | "Full" } | null { + const percent = status[AM30_STATUS_SPARE_BATTERY]; + if (!percent || percent > 100) return null; + return { percent, state: percent === 100 ? "Full" : "Charging" }; +} + +/** Byte 1 is 0 on battery, 1 charging, 2 full, as the vendor app reads it. */ +export function am30DecodeBattery(reply: Uint8Array): { percent: number | null; state: Am30ChargeState } { + const percent = reply[2] !== 0 && reply[3] <= 100 ? reply[3] : null; + const state = (["Discharging", "Charging", "Full"] as const)[reply[1]] ?? "Unknown"; + return { percent, state }; +} + +/** + * Receiver light, sent to the receiver itself (never relayed). Read `88` / + * write `08`: effect, speed, brightness, colour option, R, G, B. Read `87` / + * write `07`: on/off. + */ +export const AM30_RECEIVER_GET_LIGHT = 0x88; +export const AM30_RECEIVER_SET_LIGHT = 0x08; +export const AM30_RECEIVER_GET_LIGHT_SWITCH = 0x87; +export const AM30_RECEIVER_SET_LIGHT_SWITCH = 0x07; +/** Effects 1..8: always on, breathing, neon, light wave, marquee, ring, buffer, chase. */ +export const AM30_RECEIVER_EFFECT_COUNT = 8; +export const AM30_RECEIVER_SPEEDS: readonly number[] = [1, 2, 3, 4, 5]; +export const AM30_RECEIVER_BRIGHTNESS: readonly number[] = [0, 25, 50, 75, 100]; +/** Colour option 7 = custom RGB; 0..6 pick these presets. */ +const RECEIVER_CUSTOM_COLOR = 7; +const RECEIVER_PRESETS = ["#ff0000", "#ff8800", "#ffff00", "#00ff00", "#00ffff", "#0000ff", "#8800ff"]; + +export interface Am30ReceiverLight { + enabled: boolean; + /** 1..8, see `AM30_RECEIVER_EFFECT_COUNT`. */ + effect: number; + /** The vendor slider, 1..5; the wire stores 4..0. */ + speed: number; + /** Percent in 25 % steps; the wire stores 0..4. */ + brightness: number; + color: string; +} + +const hex = (bytes: ArrayLike) => + `#${Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")}`; + +export function am30DecodeReceiverLight(light: Uint8Array, power: Uint8Array): Am30ReceiverLight { + return { + enabled: power[1] === 1, + effect: Math.max(1, Math.min(AM30_RECEIVER_EFFECT_COUNT, light[1])), + speed: 5 - Math.min(4, light[2]), + brightness: Math.min(4, light[3]) * 25, + color: RECEIVER_PRESETS[light[4]] ?? hex(light.subarray(5, 8)), + }; +} + +/** The 64-byte `08` write. Its checksum is in byte 8, after the seven fields. */ +export function am30EncodeReceiverLight(light: Omit): Uint8Array { + const { effect, speed, brightness, color } = light; + if (!Number.isInteger(effect) || effect < 1 || effect > AM30_RECEIVER_EFFECT_COUNT) { + throw new Error(`Receiver light effect must be 1..${AM30_RECEIVER_EFFECT_COUNT}.`); + } + if (!AM30_RECEIVER_SPEEDS.includes(speed)) throw new Error("Receiver light speed must be 1..5."); + if (!AM30_RECEIVER_BRIGHTNESS.includes(brightness)) throw new Error("Receiver light brightness must be 0..100 in 25 % steps."); + const match = /^#?([0-9a-f]{6})$/i.exec(color); + if (!match) throw new Error(`Invalid receiver light colour: ${color}.`); + const rgb = parseInt(match[1], 16); + // The vendor app writes speed 0 for always on. + const fields = [ + AM30_RECEIVER_SET_LIGHT, effect, effect === 1 ? 0 : 5 - speed, brightness / 25, + RECEIVER_CUSTOM_COLOR, (rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff, + ]; + const out = new Uint8Array(64); + out.set(fields); + out[8] = (255 - (fields.reduce((sum, b) => sum + b, 0) & 0xff)) & 0xff; + return out; +} + +/** + * Key matrix actions from the vendor app (`D0` / `50`), label to 4-byte value. + * Scroll Up/Down are the factory values of slots 14 and 15. + */ +export const AM30_BUTTON_ACTIONS: ReadonlyArray = [ + ["Left Click", [0x01, 0, 0xf0, 0]], + ["Right Click", [0x01, 0, 0xf1, 0]], + ["Middle Click", [0x01, 0, 0xf2, 0]], + ["Back", [0x01, 0, 0xf3, 0]], + ["Forward", [0x01, 0, 0xf4, 0]], + ["Scroll Up", [0x01, 0, 0xf5, 0x01]], + ["Scroll Down", [0x01, 0, 0xf5, 0xff]], + ["DPI Loop", [0x14, 0, 0x00, 0]], + ["DPI +", [0x14, 0, 0x01, 0]], + ["DPI -", [0x14, 0, 0x02, 0]], + ["Volume Up", [0x03, 0, 0xe9, 0]], + ["Volume Down", [0x03, 0, 0xea, 0]], + ["Mute", [0x03, 0, 0xe2, 0]], + ["Play/Pause", [0x03, 0, 0xcd, 0]], + ["Disabled", [0, 0, 0, 0]], +]; + +/** Action label for a 4-byte slot; "Custom" for keys, combinations and macros. */ +export function am30DecodeButtonAction(bytes: ArrayLike): string { + const match = AM30_BUTTON_ACTIONS.find(([, value]) => value.every((b, i) => b === bytes[i])); + return match?.[0] ?? "Custom"; +} + +export function am30EncodeButtonAction(label: string): readonly [number, number, number, number] | null { + return AM30_BUTTON_ACTIONS.find(([l]) => l === label)?.[1] ?? null; +} + +/** Factory assignments, from the first cable read of the key matrix. */ +export const AM30_DEFAULT_BUTTON_MAPPINGS: Readonly> = { + Left: "Left Click", + Right: "Right Click", + Middle: "Middle Click", + Back: "Back", + Forward: "Forward", + "Scroll Up": "Scroll Up", + "Scroll Down": "Scroll Down", +}; + +/** A Yichip-protocol Angry Miao model, keyed by its `8F` device id. Button slots are key matrix slots. */ +export interface AngryMiaoProfile extends AngryMiaoModel { + deviceId: number; + sensor: string; +} + +/** + * Device id 2222 (0x08AE) and firmware bytes 0x0318 were read over the USB + * cable (0x3151:0x402A). PAW3950 and 50-30000 DPI are from the retail listing + * and the AM30 manual; the top stage reads back 30000. + */ +export const ANGRY_MIAO_INFINITY_PROFILE: AngryMiaoProfile = { + deviceId: 2222, + brand: "Angry Miao", + model: "Infinity .100", + sensor: "PixArt PAW3950", + maxPollingHz: 8000, + minDpi: 50, + maxDpi: 30000, + dpiStep: 50, + maxDpiStages: AM30_MAX_DPI_STAGES, + defaultButtonMappings: AM30_DEFAULT_BUTTON_MAPPINGS, + // Slot 3 is Forward and slot 4 is Back on this mouse. Slot 5 reads DPI Loop, + // but the mouse has no DPI button, so it is not offered. Slots 12 and 13 + // hold a second wheel pair the vendor app does not show. + buttons: [ + { name: "Left", slot: 0 }, + { name: "Right", slot: 1 }, + { name: "Middle", slot: 2 }, + { name: "Back", slot: 4 }, + { name: "Forward", slot: 3 }, + { name: "Scroll Up", slot: 14 }, + { name: "Scroll Down", slot: 15 }, + ], +}; + +export const ANGRY_MIAO_PROFILES: ReadonlyMap = new Map([ + [ANGRY_MIAO_INFINITY_PROFILE.deviceId, ANGRY_MIAO_INFINITY_PROFILE], +]); + +export interface AngryMiaoTransport { + transport: "direct" | "dongle" | "bluetooth"; + /** The settings collection on this link. */ + usagePage: number; + usage: number; +} + +/** Transport by product id. The receiver relays every mouse command; Bluetooth wraps them in report 6. */ +export const ANGRY_MIAO_PRODUCTS: ReadonlyMap = new Map([ + [0x402a, { transport: "direct", usagePage: AM30_USAGE_PAGE, usage: AM30_USAGE }], + [0x5007, { transport: "dongle", usagePage: AM30_USAGE_PAGE, usage: AM30_USAGE }], + [0x402c, { transport: "bluetooth", usagePage: AM30_BT_USAGE_PAGE, usage: AM30_BT_USAGE }], +]); diff --git a/src/angry-miao/am35.test.ts b/src/angry-miao/am35.test.ts new file mode 100644 index 00000000..aecd2f03 --- /dev/null +++ b/src/angry-miao/am35.test.ts @@ -0,0 +1,146 @@ +import assert from "node:assert/strict"; +import { it } from "node:test"; +import { + AM30R2_KEY_OFFSET, + AM35_CMD, + AM35_NV_DPI_COLOR, + am35ColorFromHue, + am35DecodeBattery, + am35DecodeButtonAction, + am35DecodeDpi, + am35DecodeFpsMode, + am35DecodeNvData, + am35DecodeReceiverLight, + am35DecodeSleep, + am35DecodeStoredColor, + am35DecodeVersion, + am35EncodeButtonAction, + am35EncodeDpiStage, + am35EncodeNvRead, + am35EncodeReceiverLight, + am35EncodeReportRate, + am35EncodeSleep, + am35Frame, + am35HueFromColor, + am35IsReceiver, + am35ParseFrames, + am35Product, + am35ReportChunk, + am35Reports, + ANGRY_MIAO_BUTTON_ACTION_LABELS, + AM35_BUTTON_ACTIONS, +} from "./index.ts"; + +const hex = (bytes: ArrayLike) => Buffer.from(Array.from(bytes)).toString("hex"); + +it("frames a RACE command as the vendor app does", () => { + // The vendor's own example: set the report rate to 1000 Hz. + assert.equal(hex(am35Frame(AM35_CMD.SET_REPORT_RATE, am35EncodeReportRate(1000))), "055a04001030e803"); + // The firmware version read carries one zero byte; a report is [frame length, device id, frame], padded to 61. + const [report] = am35Reports(0, am35Frame(AM35_CMD.GET_VERSION, [0])); + assert.equal(report.length, 61); + assert.equal(hex(report.subarray(0, 9)), "0700055a0300071c00"); + assert.ok(report.subarray(9).every((b) => b === 0)); +}); + +it("refuses every command it does not implement", () => { + // Factory reset, firmware start, clear bonding, reboot and stored-colour writes. + for (const command of [0x30ce, 0x1c08, 0x306b, 0x1101, 0x0a0d, 0x30c0]) { + assert.throws(() => am35Frame(command), /not one this driver sends/, `0x${command.toString(16)}`); + } +}); + +it("splits a long frame into 59-byte chunks and finds frames in a reply", () => { + const frame = am35Frame(AM35_CMD.GET_DPI, new Array(60).fill(1)); + const reports = am35Reports(0x80, frame); + assert.deepEqual(reports.map((r) => [r[0], r[1]]), [[59, 0x80], [7, 0x80]]); + const two = [...am35Frame(AM35_CMD.GET_LOD), ...am35Frame(AM35_CMD.GET_REPORT_RATE)]; + assert.deepEqual(am35ParseFrames(two).map((f) => f.command), [AM35_CMD.GET_LOD, AM35_CMD.GET_REPORT_RATE]); + // A browser that keeps the report id in front of a 62-byte read. + const withId = [0x14, 3, 0, 9, 8, 7, ...new Array(56).fill(0)]; + assert.deepEqual(am35ReportChunk(0x14, withId), [9, 8, 7]); + assert.deepEqual(am35ReportChunk(0x14, withId.slice(1)), [9, 8, 7]); +}); + +it("routes the .97 and .100R2 ids as the vendor app does", () => { + const either = am35Product(0x0e8d, 0x0880)!; + assert.equal(either.family, "am35"); + assert.equal(am35IsReceiver(either, "AM Infinity .97"), false); + assert.equal(am35IsReceiver(either, "AM INFINITY 2.4G Dongle"), true); + assert.equal(am35IsReceiver(am35Product(0x0e8d, 0x0703)!, "anything"), true); + assert.equal(am35Product(0x0e8d, 0x0881)?.family, "am30r2"); + assert.equal(am35IsReceiver(am35Product(0x0e8d, 0x0704)!, undefined), true); + assert.equal(am35Product(0x35a1, 0x0035)?.family, "am35"); + assert.equal(am35Product(0x0e8d, 0x0882), undefined); +}); + +it("encodes sleep as three parts per link plus the vendor's fixed tail", () => { + assert.deepEqual( + am35EncodeSleep(30, 600), + [10, 0, 10, 0, 10, 0, 0, 0, 200, 0, 200, 0, 200, 0, 0, 0, 60, 0, 30, 0, 60, 0, 30, 0], + ); + // Never is 65535, split 21845 three ways. + assert.deepEqual(am35EncodeSleep(0, 15).slice(0, 6), [0x55, 0x55, 0x55, 0x55, 0x55, 0x55]); + assert.deepEqual(am35DecodeSleep([0, ...am35EncodeSleep(0, 600)]), { seconds24g: 0, secondsBt: 600 }); + assert.deepEqual(am35DecodeSleep(am35EncodeSleep(61, 3600)), { seconds24g: 61, secondsBt: 3600 }); + assert.deepEqual(am35DecodeSleep(am35EncodeSleep(768, 600)), { seconds24g: 768, secondsBt: 600 }); +}); + +it("decodes the DPI table with its eight slots and colours", () => { + const xs = [400, 800, 1600, 3200, 6400, 12800, 800, 800]; + const payload = [0, 6, 2, ...xs.flatMap((x) => [x & 0xff, x >> 8]), ...xs.flatMap((x) => [x & 0xff, x >> 8]), + ...xs.flatMap(() => [0xff, 0x00, 0x00])]; + const table = am35DecodeDpi(payload); + assert.equal(table.count, 6); + assert.equal(table.activeIndex, 2); + assert.equal(table.stages.length, 8); + assert.deepEqual(table.stages[3], { x: 3200, y: 3200, color: "#ff0000" }); + assert.deepEqual(am35EncodeDpiStage(2, 1600, 800), [2, 0x40, 0x06, 0x20, 0x03]); +}); + +it("treats a DPI reply too short for its X and Y fields as no stages", () => { + assert.equal(am35DecodeDpi([0, 1, 0]).count, 0); + assert.equal(am35DecodeDpi([0, 1, 0, 0x20, 0x03]).count, 0); + const one = am35DecodeDpi([0, 1, 0, 0x20, 0x03, 0x40, 0x06]); + assert.equal(one.count, 1); + assert.deepEqual(one.stages, [{ x: 800, y: 1600, color: null }]); +}); + +it("decodes battery, Blast Mode and version replies", () => { + assert.deepEqual(am35DecodeBattery([0, 1, 86, 0, 0, 0, 0]), { percent: 86, charging: true }); + assert.deepEqual(am35DecodeBattery([1, 0, 86]), { percent: null, charging: false }); + assert.equal(am35DecodeFpsMode([0, 1]), true); + assert.equal(am35DecodeFpsMode([1]), true); + assert.equal(am35DecodeVersion([0, ...Buffer.from("AM35 v1.0.12")]), "v1.0.12"); + assert.equal(am35DecodeVersion([0]), null); +}); + +it("reads stored data only from the address it asked for", () => { + assert.deepEqual(am35EncodeNvRead(AM35_NV_DPI_COLOR + 1), [0x22, 0x62, 0xe8, 0x03]); + const record = [0, 0x22, 0x62, 7, 0, 1, 2, 3, 4, 0x12, 0x34, 0x56]; + assert.equal(am35DecodeStoredColor(am35DecodeNvData(record, AM35_NV_DPI_COLOR + 1)!), "#123456"); + assert.equal(am35DecodeNvData(record, AM35_NV_DPI_COLOR), null); +}); + +it("maps every OpenMouse button action both ways", () => { + assert.deepEqual(AM35_BUTTON_ACTIONS.map(([label]) => label), ANGRY_MIAO_BUTTON_ACTION_LABELS); + for (const label of ANGRY_MIAO_BUTTON_ACTION_LABELS) { + const command = am35EncodeButtonAction(4, label)!; + assert.deepEqual(am35DecodeButtonAction([0, ...command]), { keyId: 4, action: label }); + } + assert.deepEqual(am35EncodeButtonAction(2, "Volume Up"), [2, 6, 0xe9, 0, 0, 0]); + assert.equal(am35DecodeButtonAction([0, 3, 8, ...new Array(18).fill(0)])?.action, "Custom", "a macro"); + assert.equal(AM30R2_KEY_OFFSET + 1, 0xf0); + assert.equal(AM30R2_KEY_OFFSET + 7, 0xf6); +}); + +it("round-trips the receiver light on the vendor's hue wheel", () => { + assert.equal(am35HueFromColor("#ff0000"), 0); + assert.equal(am35HueFromColor("#00ff00"), 510); + assert.equal(am35HueFromColor("#0000ff"), 1020); + assert.equal(am35ColorFromHue(765), "#00ffff"); + const light = { enabled: true, effect: 2, hues: [510, 0, 1020] as [number, number, number], saturations: [96, 100, 50] as [number, number, number], speed: 10, brightness: 240 }; + const bytes = am35EncodeReceiverLight(light); + assert.deepEqual(bytes, [1, 2, 0x01, 0xfe, 96, 0, 0, 100, 0x03, 0xfc, 50, 90, 240]); + assert.deepEqual(am35DecodeReceiverLight(bytes), light); +}); diff --git a/src/angry-miao/am35.ts b/src/angry-miao/am35.ts new file mode 100644 index 00000000..f61af88e --- /dev/null +++ b/src/angry-miao/am35.ts @@ -0,0 +1,470 @@ +/** + * Angry Miao Infinity .97 (AM35) and .100R2 (AM30R2) on Airoha's RACE command + * protocol (vendor id 0x0E8D, MediaTek). Every byte layout here follows the + * vendor configurator (ammaster.angrymiao.com, bundle `index-9145eff3.js`), + * which runs the .100R2 through its .97 driver and only renumbers the buttons. + * Nothing here has been checked against a real mouse yet. See + * docs/angry-miao-infinity-97-100R2.md. + */ + +import { + ANGRY_MIAO_BRAND, + type AngryMiaoLiftOff, + ANGRY_MIAO_LIFT_OFF_LEVELS, + type AngryMiaoModel, +} from "./shared.ts"; + +export const AM35_VENDOR_ID = 0x0e8d; +/** The vendor app also routes 35A1:0035 to the .97. */ +export const AM35_ALT_VENDOR_ID = 0x35a1; + +export type Am35Family = "am35" | "am30r2"; + +export interface Am35Product { + family: Am35Family; + /** "either": a receiver when the product name says so, as the vendor app decides. */ + role: "mouse" | "receiver" | "either"; +} + +const key = (vendorId: number, productId: number) => `${vendorId}:${productId}`; + +const PRODUCTS = new Map([ + [key(AM35_VENDOR_ID, 0x0880), { family: "am35", role: "either" }], + [key(AM35_ALT_VENDOR_ID, 0x0035), { family: "am35", role: "either" }], + [key(AM35_VENDOR_ID, 0x0703), { family: "am35", role: "receiver" }], + [key(AM35_VENDOR_ID, 0x0881), { family: "am30r2", role: "mouse" }], + [key(AM35_VENDOR_ID, 0x0704), { family: "am30r2", role: "receiver" }], +]); + +/** Every vendor and product id the vendor app routes to the .97 driver, for the picker. */ +export const AM35_PRODUCT_IDS: ReadonlyArray<{ vendorId: number; productId: number; family: Am35Family }> = + [...PRODUCTS].map(([id, { family }]) => { + const [vendorId, productId] = id.split(":").map(Number); + return { vendorId, productId, family }; + }); + +export function am35Product(vendorId: number, productId: number): Am35Product | undefined { + return PRODUCTS.get(key(vendorId, productId)); +} + +/** The vendor app's receiver test for ids that can be either. */ +export const AM35_RECEIVER_NAME = /dongle|receiver|2\.4/i; + +export function am35IsReceiver(product: Am35Product, productName: string | undefined): boolean { + return product.role === "receiver" || (product.role === "either" && AM35_RECEIVER_NAME.test(productName ?? "")); +} + +/** Feature report 0x14 carries commands and replies; the vendor app's fallback is output 0x06 and input 0x07. */ +export const AM35_FEATURE_REPORT = 0x14; +export const AM35_OUTPUT_REPORT = 0x06; +export const AM35_INPUT_REPORT = 0x07; +/** Reports are padded to at least 61 bytes: frame length, device id, then up to 59 frame bytes. */ +export const AM35_REPORT_SIZE = 61; +export const AM35_CHUNK_SIZE = 59; + +/** Device id 0 is whatever is plugged in; through the receiver the mouse answers on 0x80 once paired. */ +export const AM35_LOCAL_DEVICE = 0x00; +export const AM35_REMOTE_DEVICE = 0x80; + +export const AM35_RACE_COMMAND = 0x05; +export const AM35_RACE_MAGIC = 0x5a; + +/** The commands this driver sends. Anything else (reset, firmware update, pairing) is refused. */ +export const AM35_CMD = { + GET_DONGLE_MODE: 0x2c83, + SET_DONGLE_LINK_TYPE: 0x2cb2, + GET_DONGLE_DEVICE_LIST: 0x2c94, + GET_DONGLE_PAIRED_LIST: 0x2c96, + SET_DONGLE_LIGHT: 0x300d, + GET_DONGLE_LIGHT: 0x300e, + GET_DONGLE_BATTERY: 0x300f, + SET_REPORT_RATE: 0x3010, + GET_REPORT_RATE: 0x3011, + SET_SLEEP_TIME: 0x3012, + GET_SLEEP_TIME: 0x3013, + SET_LIGHT_SETTINGS: 0x30b3, + SET_KEY_REMAP: 0x30c2, + GET_KEY_REMAP: 0x30c3, + SET_DPI: 0x30c4, + GET_DPI: 0x30c5, + SET_DPI_LOOP_RANGE: 0x30c6, + SET_CURRENT_DPI_STAGE: 0x30c7, + SET_LOD: 0x30cc, + GET_LOD: 0x30cd, + GET_BATTERY: 0x30cf, + SET_MOTION_SYNC: 0x30d2, + GET_MOTION_SYNC: 0x30d3, + SET_ANGLE_SNAPPING: 0x30d4, + GET_ANGLE_SNAPPING: 0x30d5, + SET_RIPPLE_CONTROL: 0x30d6, + GET_RIPPLE_CONTROL: 0x30d7, + SET_FPS_MODE: 0x30de, + GET_FPS_MODE: 0x30df, + SET_SW_DEBOUNCE: 0x30e8, + GET_SW_DEBOUNCE: 0x30e9, + READ_NV_DATA: 0x0a0c, + GET_VERSION: 0x1c07, +} as const; + +const ALLOWED = new Set(Object.values(AM35_CMD)); + +/** `[0x05, 0x5A, length LE16, command LE16, payload]`; the length counts the command and the payload. */ +export function am35Frame(command: number, payload: readonly number[] = []): number[] { + if (!ALLOWED.has(command)) throw new Error(`RACE command 0x${command.toString(16)} is not one this driver sends.`); + const length = payload.length + 2; + return [AM35_RACE_COMMAND, AM35_RACE_MAGIC, length & 0xff, length >> 8, command & 0xff, command >> 8, ...payload.map((b) => b & 0xff)]; +} + +/** One report per 59-byte chunk: `[chunk length, device id, chunk]`, zero padded. */ +export function am35Reports(deviceId: number, frame: readonly number[], size = AM35_REPORT_SIZE): Uint8Array[] { + const chunks: number[][] = []; + for (let i = 0; i < frame.length; i += AM35_CHUNK_SIZE) chunks.push(frame.slice(i, i + AM35_CHUNK_SIZE)); + return chunks.map((chunk) => { + const report = new Uint8Array(Math.max(size, AM35_REPORT_SIZE)); + report[0] = chunk.length; + report[1] = deviceId; + report.set(chunk, 2); + return report; + }); +} + +export interface Am35Reply { + command: number; + /** Bytes after the command id; most replies start with a status byte, 0 = done. */ + payload: number[]; +} + +/** One complete frame at the start of `bytes`, or null. */ +export function am35ParseFrame(bytes: ArrayLike): Am35Reply | null { + if (bytes.length < 6 || (bytes[0] !== 0x05 && bytes[0] !== 0x15)) return null; + const total = (bytes[2] | (bytes[3] << 8)) + 4; + if (bytes.length < total) return null; + return { command: bytes[4] | (bytes[5] << 8), payload: Array.from(bytes).slice(6, total) }; +} + +/** Every complete frame in a row, as the vendor app reads a report that holds several. */ +export function am35ParseFrames(bytes: ArrayLike): Am35Reply[] { + const frames: Am35Reply[] = []; + let rest = Array.from(bytes); + for (let frame = am35ParseFrame(rest); frame; frame = am35ParseFrame(rest)) { + frames.push(frame); + rest = rest.slice(frame.payload.length + 6); + } + return frames; +} + +/** A report's frame bytes: drops a leading report id the browser may keep, then reads `[length, device id, chunk]`. */ +export function am35ReportChunk(reportId: number, data: ArrayLike): number[] { + const bytes = Array.from(data); + const body = bytes.length >= 62 && bytes[0] === reportId ? bytes.slice(1) : bytes; + return body.slice(2, 2 + (body[0] ?? 0)); +} + +/** A firmware-version reply of just `00` only acknowledges the request; the version follows. */ +export function am35IsVersionAck(reply: Am35Reply): boolean { + return reply.command === AM35_CMD.GET_VERSION && reply.payload.length === 1 && reply.payload[0] === 0; +} + +/** The receiver asks for mode 18, then link type 6, before it relays to the mouse (the vendor app's order). */ +export const AM35_DONGLE_MODE_QUERY = [18, 0]; +export const AM35_DONGLE_LINK_TYPE = [6]; + +/** Receiver device and paired lists: 10-byte records of address (7), device id, group and role. */ +export function am35DecodeDeviceList(payload: readonly number[]): Array<{ deviceId: number }> { + if (payload.length < 1 || payload[0] !== 0) return []; + const devices: Array<{ deviceId: number }> = []; + for (let at = 1; at + 9 < payload.length; at += 10) devices.push({ deviceId: payload[at + 7] ?? 0 }); + return devices; +} + +const le16 = (bytes: readonly number[], at: number) => (bytes[at] ?? 0) | ((bytes[at + 1] ?? 0) << 8); +const u16 = (value: number) => [value & 0xff, (value >> 8) & 0xff]; + +// ── Settings ────────────────────────────────────────────────────────────── + +/** Hz as LE16, not a code. */ +export const am35EncodeReportRate = (hz: number) => u16(hz); +export const am35DecodeReportRate = (payload: readonly number[]) => (payload.length < 3 || payload[0] !== 0 ? 0 : le16(payload, 1)); + +/** Raw software debounce for the cable, 2.4 GHz and Bluetooth, from the shared per-rate tables. */ +export const am35EncodeDebounce = (raw: { usb: number; rf: number; bt: number }) => [raw.usb, raw.rf, raw.bt]; +export const am35DecodeDebounce = (payload: readonly number[]) => ({ usb: payload[1] ?? 0, rf: payload[2] ?? 0, bt: payload[3] ?? 0 }); + +export const am35EncodeLiftOff = (level: AngryMiaoLiftOff) => [ANGRY_MIAO_LIFT_OFF_LEVELS.indexOf(level)]; +export const am35DecodeLiftOff = (payload: readonly number[]): AngryMiaoLiftOff => + ANGRY_MIAO_LIFT_OFF_LEVELS[payload[1] ?? 0] ?? ANGRY_MIAO_LIFT_OFF_LEVELS[0]; + +/** Motion sync, angle snapping and ripple control: byte 1 after the status. */ +export const am35DecodeFlag = (payload: readonly number[]) => (payload[1] ?? 0) !== 0; +/** Blast Mode replies may come with or without the status byte. */ +export const am35DecodeFpsMode = (payload: readonly number[]) => + (payload.length >= 2 && payload[0] === 0 ? payload[1] : payload[0]) !== 0; + +/** The vendor app's "never". */ +export const AM35_SLEEP_NEVER = 0xffff; + +function splitSleep(seconds: number): number[] { + const third = Math.floor(seconds / 3); + return [third, third, seconds - third * 2].flatMap(u16); +} + +/** 2.4 GHz then Bluetooth, each as three LE16 parts that add up, then the vendor's fixed tail. 0 = never. */ +export function am35EncodeSleep(seconds24g: number, secondsBt: number): number[] { + const raw = (s: number) => (s === 0 ? AM35_SLEEP_NEVER : Math.max(0, Math.min(0xffff, Math.trunc(s)))); + return [...splitSleep(raw(seconds24g)), 0, 0, ...splitSleep(raw(secondsBt)), 0, 0, 60, 0, 30, 0, 60, 0, 30, 0]; +} + +/** Seconds per link, 0 = never; the reply may or may not lead with a status byte. */ +export function am35DecodeSleep(payload: readonly number[]): { seconds24g: number; secondsBt: number } { + if (payload.length < 14) return { seconds24g: 0, secondsBt: 0 }; + const at = payload.length % 2; + const sum = (from: number) => le16(payload, from) + le16(payload, from + 2) + le16(payload, from + 4); + const seconds = (raw: number) => (raw === AM35_SLEEP_NEVER ? 0 : raw); + return { seconds24g: seconds(sum(at)), secondsBt: seconds(sum(at + 8)) }; +} + +export interface Am35DpiTable { + count: number; + activeIndex: number; + stages: Array<{ x: number; y: number; color: string | null }>; +} + +/** Byte 1 count, byte 2 active stage, then every X, every Y and, when present, an RGB per stage. */ +export function am35DecodeDpi(payload: readonly number[]): Am35DpiTable { + const count = payload[1] ?? 0; + const slots = count > 0 && count <= 8 && payload.length >= 3 + 8 * 4 ? 8 : count; + // Unlike the vendor app, a reply too short for its X and Y fields has no stages rather than zero DPI. + if (payload.length < 3 + slots * 4) return { count: 0, activeIndex: 0, stages: [] }; + const yAt = 3 + slots * 2; + const rgbAt = yAt + slots * 2; + const hasRgb = payload.length >= rgbAt + slots * 3; + const stages = Array.from({ length: slots }, (_, i) => ({ + x: le16(payload, 3 + i * 2), + y: le16(payload, yAt + i * 2), + color: hasRgb ? hex(payload.slice(rgbAt + i * 3, rgbAt + i * 3 + 3)) : null, + })); + return { count, activeIndex: payload[2] ?? 0, stages }; +} + +/** One stage's X and Y; the vendor app leaves the colour out of this write. */ +export const am35EncodeDpiStage = (index: number, x: number, y: number) => [index, ...u16(x), ...u16(y)]; + +export interface Am35Battery { + percent: number | null; + charging: boolean; +} + +/** As the vendor app reads it: byte 1 charging, the percent at byte 2 (or LE16 at 1-2 on a short reply). */ +export function am35DecodeBattery(payload: readonly number[]): Am35Battery { + if (payload.length < 3 || payload[0] !== 0) return { percent: null, charging: false }; + const valid = (value: number) => value >= 0 && value <= 100; + const percent = payload.length >= 7 && valid(payload[2]) ? payload[2] : valid(le16(payload, 1)) ? le16(payload, 1) : null; + return { percent, charging: payload.length >= 5 && payload[1] !== 0 }; +} + +/** Text after the status byte, e.g. "v1.2.3". */ +export function am35DecodeVersion(payload: readonly number[]): string | null { + const text = String.fromCharCode(...payload.filter((b) => b >= 32 && b <= 126)); + return text.match(/v?\d+\.\d+\.\d+/i)?.[0] ?? null; +} + +// ── Stored data ─────────────────────────────────────────────────────────── + +/** Stored-data addresses the vendor app reads; this driver never writes them. */ +export const AM35_NV_LIGHT_SETTINGS = 0x600a; +export const AM35_NV_LIGHT_COLOR = 0x6200; +export const AM35_NV_DPI_COLOR = 0x6221; +export const AM35_NV_READ_LENGTH = 1000; + +export const am35EncodeNvRead = (address: number) => [...u16(address), ...u16(AM35_NV_READ_LENGTH)]; + +/** `[status, address LE16, length LE16, data]`; null for another address or a failed read. */ +export function am35DecodeNvData(payload: readonly number[], address: number): number[] | null { + if (payload.length < 6 || payload[0] !== 0 || le16(payload, 1) !== address) return null; + const length = le16(payload, 3); + const data = payload.slice(5); + return length > 0 ? data.slice(0, length) : data; +} + +export type Am35MouseEffect = "Solid" | "Breathing" | "Neon"; + +export function am35DecodeMouseLight(data: readonly number[]): { enabled: boolean; effect: Am35MouseEffect; speed: number } | null { + if (data.length < 3) return null; + return { enabled: data[0] !== 0, effect: data[1] === 1 ? "Breathing" : data[1] === 2 ? "Neon" : "Solid", speed: data[2] }; +} + +export const am35EncodeMouseLight = (light: { enabled: boolean; effect: Am35MouseEffect; speed: number }) => + [light.enabled ? 1 : 0, light.effect === "Solid" ? 0 : light.effect === "Breathing" ? 1 : 2, Math.max(1, Math.min(10, Math.round(light.speed)))]; + +/** The mouse light colour and each DPI stage colour sit at bytes 4-6 of their record. */ +export const am35DecodeStoredColor = (data: readonly number[]) => (data.length < 7 ? null : hex(data.slice(4, 7))); + +// ── Receiver light ──────────────────────────────────────────────────────── + +/** The vendor's colour wheel: hue 0..1530, six 255-step ramps. */ +const HUE_MAX = 1530; + +export function am35HueFromColor(color: string): number { + const [r, g, b] = rgb(color).map((v) => v / 255); + const max = Math.max(r, g, b); + const span = max - Math.min(r, g, b); + let hue = 0; + if (span !== 0) { + hue = max === r ? ((g - b) / span) % 6 : max === g ? (b - r) / span + 2 : (r - g) / span + 4; + hue *= 60; + if (hue < 0) hue += 360; + } + return Math.max(0, Math.min(HUE_MAX, Math.round((((hue % 360) + 360) % 360) / 360 * HUE_MAX))); +} + +export function am35ColorFromHue(hue: number): string { + const t = Math.round(hue); + if (!Number.isFinite(hue) || t < 0 || t > HUE_MAX) return "#ffffff"; + const [r, g, b] = t <= 255 ? [255, t, 0] + : t <= 510 ? [510 - t, 255, 0] + : t <= 765 ? [0, 255, t - 510] + : t <= 1020 ? [0, 1020 - t, 255] + : t <= 1275 ? [t - 1020, 0, 255] + : [255, 0, 1530 - t]; + return hex([r, g, b]); +} + +export interface Am35ReceiverLight { + enabled: boolean; + /** 1..7: solid, breathing, flow, mosaic, aurora, night city, arc. */ + effect: number; + /** Three hues (big-endian) with a saturation percent each. */ + hues: [number, number, number]; + saturations: [number, number, number]; + /** 1..20. */ + speed: number; + /** 1..255. */ + brightness: number; +} + +/** No status byte: the reply starts at the on/off byte. */ +export function am35DecodeReceiverLight(payload: readonly number[]): Am35ReceiverLight | null { + if (payload.length < 13) return null; + const hue = (at: number) => (payload[at] << 8) | payload[at + 1]; + return { + enabled: payload[0] !== 0, + effect: payload[1] >= 1 && payload[1] <= 7 ? payload[1] : 1, + hues: [hue(2), hue(5), hue(8)], + saturations: [Math.max(1, payload[4]), Math.max(1, payload[7]), Math.max(1, payload[10])], + speed: Math.max(1, Math.abs(payload[11] - 80)), + brightness: Math.max(1, payload[12]), + }; +} + +export function am35EncodeReceiverLight(light: Am35ReceiverLight): number[] { + const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, Math.round(v))); + const hue = (i: number) => [(light.hues[i] >> 8) & 0xff, light.hues[i] & 0xff, clamp(light.saturations[i], 1, 100)]; + return [ + light.enabled ? 1 : 0, + light.effect >= 1 && light.effect <= 7 ? light.effect : 1, + ...hue(0), ...hue(1), ...hue(2), + clamp(light.speed, 1, 20) + 80, + clamp(light.brightness, 1, 255), + ]; +} + +// ── Buttons ─────────────────────────────────────────────────────────────── + +/** OpenMouse's action labels as the vendor app writes them: action type, then its parameters. */ +export const AM35_BUTTON_ACTIONS: ReadonlyArray = [ + ["Left Click", 1, []], + ["Right Click", 2, []], + ["Middle Click", 3, []], + ["Back", 5, []], + ["Forward", 4, []], + ["Scroll Up", 12, []], + ["Scroll Down", 13, []], + ["DPI Loop", 11, [3, 0, 0]], + ["DPI +", 11, [0, 0, 0]], + ["DPI -", 11, [1, 0, 0]], + ["Volume Up", 6, [0xe9, 0, 0, 0]], + ["Volume Down", 6, [0xea, 0, 0, 0]], + ["Mute", 6, [0xe2, 0, 0, 0]], + ["Play/Pause", 6, [0xcd, 0, 0, 0]], + ["Disabled", 0, []], +]; + +export function am35EncodeButtonAction(keyId: number, label: string): number[] | null { + const entry = AM35_BUTTON_ACTIONS.find(([l]) => l === label); + return entry ? [keyId, entry[1], ...entry[2]] : null; +} + +/** `[status, key, type, params]`. Keys, macros and rapid fire read as "Custom". */ +export function am35DecodeButtonAction(payload: readonly number[]): { keyId: number; action: string } | null { + if (payload.length < 3 || payload[0] !== 0) return null; + const [, keyId, type] = payload; + const params = payload.slice(3); + const match = AM35_BUTTON_ACTIONS.find(([, t, p]) => { + if (t !== type) return false; + if (type === 11) return params[0] === p[0]; + if (type === 6) return le16(params, 0) === le16(p, 0); + return true; + }); + return { keyId, action: match?.[0] ?? "Custom" }; +} + +/** The .100R2 numbers its buttons 0xF0-0xF6 where the .97 uses 1-7; only the key commands carry them. */ +export const AM30R2_KEY_OFFSET = 0xef; + +// ── Models ──────────────────────────────────────────────────────────────── + +const AM35_BUTTONS = [ + { name: "Left", slot: 1 }, + { name: "Right", slot: 2 }, + { name: "Middle", slot: 3 }, + { name: "Forward", slot: 4 }, + { name: "Back", slot: 5 }, +] as const; + +/** From the vendor app: 8 stages of 50-30000 DPI in 50 DPI steps, 125 Hz to 8 kHz. It names no sensor. */ +export const ANGRY_MIAO_INFINITY_97_MODEL: AngryMiaoModel = { + brand: ANGRY_MIAO_BRAND, + model: "Infinity .97", + maxPollingHz: 8000, + minDpi: 50, + maxDpi: 30000, + dpiStep: 50, + maxDpiStages: 8, + buttons: [...AM35_BUTTONS, { name: "Scroll Up", slot: 6 }, { name: "Scroll Down", slot: 7 }], + defaultButtonMappings: { + Left: "Left Click", + Right: "Right Click", + Middle: "Middle Click", + Forward: "Forward", + Back: "Back", + "Scroll Up": "Scroll Up", + "Scroll Down": "Scroll Down", + }, +}; + +/** The vendor app names buttons 6 and 7 "custom key 1/2" here, and restores them to scroll up and down. */ +export const ANGRY_MIAO_INFINITY_100R2_MODEL: AngryMiaoModel = { + ...ANGRY_MIAO_INFINITY_97_MODEL, + model: "Infinity .100R2", + buttons: [...AM35_BUTTONS, { name: "Custom 1", slot: 6 }, { name: "Custom 2", slot: 7 }], + defaultButtonMappings: { + Left: "Left Click", + Right: "Right Click", + Middle: "Middle Click", + Forward: "Forward", + Back: "Back", + "Custom 1": "Scroll Up", + "Custom 2": "Scroll Down", + }, +}; + +function rgb(color: string): [number, number, number] { + const match = /^#?([0-9a-f]{6})$/i.exec(color); + if (!match) throw new Error(`Invalid colour: ${color}.`); + const value = parseInt(match[1], 16); + return [(value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff]; +} + +function hex(bytes: readonly number[]): string { + return `#${bytes.map((b) => (b ?? 0).toString(16).padStart(2, "0")).join("")}`; +} diff --git a/src/angry-miao/index.ts b/src/angry-miao/index.ts index a153a3c0..49d2184d 100644 --- a/src/angry-miao/index.ts +++ b/src/angry-miao/index.ts @@ -1,391 +1,8 @@ /** - * Angry Miao Infinity .100 mouse (model AM30) on the Yichip (VID 0x3151) block - * protocol. This codec owns everything the Angry Miao driver - * (`src/drivers/angry-miao/`) sends; it does not share constants with the - * other Yichip brands, so their changes cannot move this mouse. - * - * Sources: replies read over the USB cable and the vendor configurator - * (ammaster.angrymiao.com, model page am30). See - * docs/angry-miao-infinity.md. + * Angry Miao mice. `shared.ts` holds what every model has in common; each + * wire protocol has its own codec: `am30.ts` for the Infinity .100 (Yichip), + * `am35.ts` for the Infinity .97 and .100R2 (Airoha RACE). */ - -/** Yichip's vendor id. Other brands ship on it, so it never identifies this mouse alone. */ -export const ANGRY_MIAO_VENDOR_ID = 0x3151; -/** Product names: cable "Angry Miao Infinity", receiver "AM INFINITY 8K MOUSE", Bluetooth "AM INFINITY BT MOUSE". */ -export const ANGRY_MIAO_PRODUCT_NAME = /angry\s*miao|\bAM\s+INFINITY\b/i; -/** One unnumbered 64-byte feature report on usage page 0xFFFF, usage 0x02. */ -export const AM30_REPORT_ID = 0; -export const AM30_REPORT_SIZE = 64; -export const AM30_USAGE_PAGE = 0xffff; -export const AM30_USAGE = 0x02; - -/** Bluetooth: the same commands go out and come back as report 6 on 0xFF55:0x0202, after a `55` byte. */ -export const AM30_BT_USAGE_PAGE = 0xff55; -export const AM30_BT_USAGE = 0x0202; -export const AM30_BT_REPORT_ID = 6; -export const AM30_BT_REPORT_SIZE = 65; -export const AM30_BT_ENVELOPE = 0x55; -/** `77` asks for the battery (byte 1, percent); a reply of `88` means the mouse is asleep. */ -export const AM30_BT_BATTERY = 0x77; -export const AM30_BT_SLEEPING = 0x88; - -export function am30BluetoothPacket(encoded: Uint8Array): Uint8Array { - const packet = new Uint8Array(AM30_BT_REPORT_SIZE); - packet[0] = AM30_BT_ENVELOPE; - packet.set(encoded.subarray(0, AM30_BT_REPORT_SIZE - 1), 1); - return packet; -} - -/** Mouse commands. Blocks are read whole and written back whole. */ -export const AM30_CMD = { - GET_FIRMWARE: 0x80, - GET_DEVICE_ID: 0x8f, - GET_OPTIONS: 0xd3, - SET_OPTIONS: 0x53, - GET_DPI: 0xd4, - SET_DPI: 0x54, - GET_KEYMATRIX: 0xd0, - SET_KEYMATRIX: 0x50, -} as const; - -/** Receiver relay commands. Raw: no checksum. */ -export const AM30_RELAY = { - SELECT_TARGET: 0xf6, - GET_STATUS: 0xf7, - NOTICE_READ: 0xfc, - SET_LENGTH: 0xfe, -} as const; -export const AM30_TARGET_MOUSE = 0x05; -/** `F6 00` releases the receiver after a relay fails, as the vendor app does. */ -export const AM30_TARGET_NONE = 0x00; -/** The vendor app tries a relayed command this many times, 100 ms apart. */ -export const AM30_RELAY_ATTEMPTS = 3; -/** The vendor app sends `FE 40` before every relayed command. */ -export const AM30_RELAY_LENGTH = 0x40; - -/** Pad to 9 bytes; byte 7 is 255 minus the sum of bytes 0-6. */ -export function am30EncodeCommand(bytes: readonly number[]): Uint8Array { - const out = new Uint8Array(Math.max(9, bytes.length)); - out.set(bytes); - let sum = 0; - for (let i = 0; i < 7; i++) sum = (sum + out[i]) & 0xff; - out[7] = (255 - sum) & 0xff; - return out; -} - -/** Options block (`D3` / `53`) byte offsets. */ -export const AM30_OPT0_REPORT_RATE = 9; -export const AM30_OPT0_DEBOUNCE = 10; -export const AM30_OPT0_FLAGS = 12; -export const AM30_OPT0_SLEEP_BT = 40; -export const AM30_OPT0_SLEEP_24G = 44; -export const AM30_OPT0_LIFT_OFF = 52; -export const AM30_OPT0_ANGLE_SNAP = 53; - -/** Report rate byte: a code, not an index. */ -export const AM30_RATE_ENCODE: Readonly> = { - 125: 8, 250: 4, 500: 2, 1000: 1, 2000: 132, 4000: 130, 8000: 129, -}; -export const AM30_RATE_DECODE: Readonly> = Object.fromEntries( - Object.entries(AM30_RATE_ENCODE).map(([hz, code]) => [code, Number(hz)]), -); -export const AM30_RATES: readonly number[] = Object.keys(AM30_RATE_ENCODE).map(Number).sort((a, b) => a - b); - -/** Lift-off byte 52: 0, 1, 2. */ -export const AM30_LIFT_OFF_LEVELS = ["Low", "Medium", "High"] as const; -export type Am30LiftOff = (typeof AM30_LIFT_OFF_LEVELS)[number]; - -/** DPI block (`D4` / `54`): byte 2 active stage, byte 3 count, then X, Y and RGB per stage. */ -export const AM30_MAX_DPI_STAGES = 8; -export const AM30_DPI_X_OFFSET = 8; -export const AM30_DPI_Y_OFFSET = 24; -export const AM30_DPI_RGB_OFFSET = 40; - -/** OPTIONPARAM0 debounce bytes for the 2.4 GHz and Bluetooth links. */ -export const AM30_OPT0_DEBOUNCE_24G = 61; -export const AM30_OPT0_DEBOUNCE_BT = 62; -/** Ripple control on is byte 12 = 1 (captured from the vendor app). */ -export const AM30_OPT0_FLAG_RIPPLE = 1 << 0; -/** Motion sync, 1 = on. */ -export const AM30_OPT0_MOTION_SYNC = 63; -/** Mouse light: on/off switch and two RGB slots, which the vendor panel sets to one colour. */ -export const AM30_OPT0_LIGHT_COLOR = 54; -export const AM30_OPT0_LIGHT_COLOR_2 = 57; -export const AM30_OPT0_LIGHT = 60; -/** LE16 standby value meaning "never". */ -export const AM30_SLEEP_NEVER = 0xffff; - -/** Standby stops in seconds, 0 = never (the vendor presets). */ -export const AM30_SLEEP_OPTIONS: readonly number[] = [0, 15, 30, 60, 600, 1800, 3600]; - -/** The vendor app's one debounce slider, by gear index (30..0 ms). */ -export const AM30_DEBOUNCE_GEARS_MS: readonly number[] = [30, 25, 20, 15, 10, 5, 0]; - -const LOW_RATE_DEBOUNCE = [10, 8, 6, 4, 3, 2, 0] as const; - -/** USB and 2.4 GHz raw debounce by gear, per report rate. Bluetooth always uses the 1000 Hz list. */ -export const AM30_DEBOUNCE_RAW: Readonly> = { - 125: LOW_RATE_DEBOUNCE, - 250: LOW_RATE_DEBOUNCE, - 500: LOW_RATE_DEBOUNCE, - 1000: LOW_RATE_DEBOUNCE, - 2000: [20, 16, 12, 8, 4, 2, 0], - 4000: [39, 31, 23, 15, 7, 3, 0], - 8000: [79, 63, 47, 31, 15, 7, 0], -}; - -function debounceRawList(rateHz: number | undefined): readonly number[] { - return (rateHz !== undefined && AM30_DEBOUNCE_RAW[rateHz]) || LOW_RATE_DEBOUNCE; -} - -/** Gear index for a raw USB debounce byte: exact match, else the nearest. */ -export function am30DebounceGear(rateHz: number | undefined, raw: number): number { - const list = debounceRawList(rateHz); - const exact = list.indexOf(raw); - if (exact >= 0) return exact; - const nearest = Math.min(...list.map((value) => Math.abs(value - raw))); - return list.findIndex((value) => Math.abs(value - raw) === nearest); -} - -/** Raw bytes for one gear at a report rate: USB, 2.4 GHz and Bluetooth. */ -export function am30DebounceRaw( - rateHz: number | undefined, - gear: number, -): { usb: number; rf: number; bt: number } { - const list = debounceRawList(rateHz); - return { usb: list[gear], rf: list[gear], bt: LOW_RATE_DEBOUNCE[gear] }; -} - -/** Battery read: byte 1 = charge state, byte 2 = percent valid, byte 3 = percent. */ -export const AM30_GET_BATTERY = 0xd6; -/** Blast Mode (sensor at its top frame rate): read byte 1, write `62 <0|1>`. */ -export const AM30_GET_BLAST_MODE = 0xe2; -export const AM30_SET_BLAST_MODE = 0x62; - -/** Onboard profiles: read `85` byte 1 (active, 0-based), switch with `05 `. */ -export const AM30_GET_PROFILE = 0x85; -export const AM30_SET_PROFILE = 0x05; -export const AM30_PROFILE_COUNT = 2; - -/** USB firmware read (`AD`): bytes 1-2, LE16. The SoC version is the shared `80` read. */ -export const AM30_GET_USB_VERSION = 0xad; - -const hexCode = (code: number) => `0x${code.toString(16).padStart(4, "0")}`; - -/** - * Raw firmware codes. The vendor app's names for them (SoC 0x0318 = 1.1.1, - * package 1.6) come from a table on its server, so they are not repeated here. - */ -export function am30FirmwareLabels(usbCode: number | null, socCode: number | null): string[] { - return [ - ...(socCode === null ? [] : [`Mouse SoC ${hexCode(socCode)}`]), - ...(usbCode === null ? [] : [`Mouse USB ${hexCode(usbCode)}`]), - ]; -} - -/** Receiver firmware reads, sent to the receiver itself. The vendor app reads these instead of `AD` on 2.4 GHz. */ -export const AM30_RECEIVER_GET_USB_VERSION = 0xf0; -export const AM30_RECEIVER_GET_RF_VERSION = 0xfb; -export const AM30_RECEIVER_GET_LED_VERSION = 0xae; - -/** `F0` and `AE` hold LE16 codes at bytes 1-2; `FB` does not echo and holds the RF code in byte 3. */ -export function am30ReceiverFirmwareLabels( - usb: Uint8Array | null, - rf: Uint8Array | null, - led: Uint8Array | null, -): string[] { - const le16 = (reply: Uint8Array) => reply[1] | (reply[2] << 8); - return [ - ...(usb ? [`Receiver USB ${hexCode(le16(usb))}`] : []), - ...(rf ? [`Receiver RF 0x${rf[3].toString(16).padStart(2, "0")}`] : []), - ...(led ? [`Receiver LED ${hexCode(le16(led))}`] : []), - ]; -} - -export type Am30ChargeState = "Discharging" | "Charging" | "Full" | "Unknown"; - -/** Receiver status (`F7`) byte 4: 0 while the mouse is linked. */ -export const AM30_STATUS_MOUSE_OFFLINE = 4; - -/** Receiver status (`F7`) byte 10: the spare battery in the dock, 1-100; 0 = none. */ -export const AM30_STATUS_SPARE_BATTERY = 10; - -/** As the vendor app reads it: 100 is full, below that the dock is charging it. */ -export function am30DecodeSpareBattery(status: Uint8Array): { percent: number; state: "Charging" | "Full" } | null { - const percent = status[AM30_STATUS_SPARE_BATTERY]; - if (!percent || percent > 100) return null; - return { percent, state: percent === 100 ? "Full" : "Charging" }; -} - -/** Byte 1 is 0 on battery, 1 charging, 2 full, as the vendor app reads it. */ -export function am30DecodeBattery(reply: Uint8Array): { percent: number | null; state: Am30ChargeState } { - const percent = reply[2] !== 0 && reply[3] <= 100 ? reply[3] : null; - const state = (["Discharging", "Charging", "Full"] as const)[reply[1]] ?? "Unknown"; - return { percent, state }; -} - -/** - * Receiver light, sent to the receiver itself (never relayed). Read `88` / - * write `08`: effect, speed, brightness, colour option, R, G, B. Read `87` / - * write `07`: on/off. - */ -export const AM30_RECEIVER_GET_LIGHT = 0x88; -export const AM30_RECEIVER_SET_LIGHT = 0x08; -export const AM30_RECEIVER_GET_LIGHT_SWITCH = 0x87; -export const AM30_RECEIVER_SET_LIGHT_SWITCH = 0x07; -/** Effects 1..8: always on, breathing, neon, light wave, marquee, ring, buffer, chase. */ -export const AM30_RECEIVER_EFFECT_COUNT = 8; -export const AM30_RECEIVER_SPEEDS: readonly number[] = [1, 2, 3, 4, 5]; -export const AM30_RECEIVER_BRIGHTNESS: readonly number[] = [0, 25, 50, 75, 100]; -/** Colour option 7 = custom RGB; 0..6 pick these presets. */ -const RECEIVER_CUSTOM_COLOR = 7; -const RECEIVER_PRESETS = ["#ff0000", "#ff8800", "#ffff00", "#00ff00", "#00ffff", "#0000ff", "#8800ff"]; - -export interface Am30ReceiverLight { - enabled: boolean; - /** 1..8, see `AM30_RECEIVER_EFFECT_COUNT`. */ - effect: number; - /** The vendor slider, 1..5; the wire stores 4..0. */ - speed: number; - /** Percent in 25 % steps; the wire stores 0..4. */ - brightness: number; - color: string; -} - -const hex = (bytes: ArrayLike) => - `#${Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")}`; - -export function am30DecodeReceiverLight(light: Uint8Array, power: Uint8Array): Am30ReceiverLight { - return { - enabled: power[1] === 1, - effect: Math.max(1, Math.min(AM30_RECEIVER_EFFECT_COUNT, light[1])), - speed: 5 - Math.min(4, light[2]), - brightness: Math.min(4, light[3]) * 25, - color: RECEIVER_PRESETS[light[4]] ?? hex(light.subarray(5, 8)), - }; -} - -/** The 64-byte `08` write. Its checksum is in byte 8, after the seven fields. */ -export function am30EncodeReceiverLight(light: Omit): Uint8Array { - const { effect, speed, brightness, color } = light; - if (!Number.isInteger(effect) || effect < 1 || effect > AM30_RECEIVER_EFFECT_COUNT) { - throw new Error(`Receiver light effect must be 1..${AM30_RECEIVER_EFFECT_COUNT}.`); - } - if (!AM30_RECEIVER_SPEEDS.includes(speed)) throw new Error("Receiver light speed must be 1..5."); - if (!AM30_RECEIVER_BRIGHTNESS.includes(brightness)) throw new Error("Receiver light brightness must be 0..100 in 25 % steps."); - const match = /^#?([0-9a-f]{6})$/i.exec(color); - if (!match) throw new Error(`Invalid receiver light colour: ${color}.`); - const rgb = parseInt(match[1], 16); - // The vendor app writes speed 0 for always on. - const fields = [ - AM30_RECEIVER_SET_LIGHT, effect, effect === 1 ? 0 : 5 - speed, brightness / 25, - RECEIVER_CUSTOM_COLOR, (rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff, - ]; - const out = new Uint8Array(64); - out.set(fields); - out[8] = (255 - (fields.reduce((sum, b) => sum + b, 0) & 0xff)) & 0xff; - return out; -} - -/** - * Key matrix actions from the vendor app (`D0` / `50`), label to 4-byte value. - * Scroll Up/Down are the factory values of slots 14 and 15. - */ -export const AM30_BUTTON_ACTIONS: ReadonlyArray = [ - ["Left Click", [0x01, 0, 0xf0, 0]], - ["Right Click", [0x01, 0, 0xf1, 0]], - ["Middle Click", [0x01, 0, 0xf2, 0]], - ["Back", [0x01, 0, 0xf3, 0]], - ["Forward", [0x01, 0, 0xf4, 0]], - ["Scroll Up", [0x01, 0, 0xf5, 0x01]], - ["Scroll Down", [0x01, 0, 0xf5, 0xff]], - ["DPI Loop", [0x14, 0, 0x00, 0]], - ["DPI +", [0x14, 0, 0x01, 0]], - ["DPI -", [0x14, 0, 0x02, 0]], - ["Volume Up", [0x03, 0, 0xe9, 0]], - ["Volume Down", [0x03, 0, 0xea, 0]], - ["Mute", [0x03, 0, 0xe2, 0]], - ["Play/Pause", [0x03, 0, 0xcd, 0]], - ["Disabled", [0, 0, 0, 0]], -]; - -/** Action label for a 4-byte slot; "Custom" for keys, combinations and macros. */ -export function am30DecodeButtonAction(bytes: ArrayLike): string { - const match = AM30_BUTTON_ACTIONS.find(([, value]) => value.every((b, i) => b === bytes[i])); - return match?.[0] ?? "Custom"; -} - -export function am30EncodeButtonAction(label: string): readonly [number, number, number, number] | null { - return AM30_BUTTON_ACTIONS.find(([l]) => l === label)?.[1] ?? null; -} - -/** Factory assignments, from the first cable read of the key matrix. */ -export const AM30_DEFAULT_BUTTON_MAPPINGS: Readonly> = { - Left: "Left Click", - Right: "Right Click", - Middle: "Middle Click", - Back: "Back", - Forward: "Forward", - "Scroll Up": "Scroll Up", - "Scroll Down": "Scroll Down", -}; - -/** A Yichip-protocol Angry Miao model, keyed by its `8F` device id. */ -export interface AngryMiaoProfile { - deviceId: number; - brand: "Angry Miao"; - model: string; - sensor: string; - maxPollingHz: number; - minDpi: number; - maxDpi: number; - dpiStep: number; - /** Key matrix slot per physical button. */ - buttons: ReadonlyArray<{ name: string; slot: number }>; -} - -/** - * Device id 2222 (0x08AE) and firmware bytes 0x0318 were read over the USB - * cable (0x3151:0x402A). PAW3950 and 50-30000 DPI are from the retail listing - * and the AM30 manual; the top stage reads back 30000. - */ -export const ANGRY_MIAO_INFINITY_PROFILE: AngryMiaoProfile = { - deviceId: 2222, - brand: "Angry Miao", - model: "Infinity .100", - sensor: "PixArt PAW3950", - maxPollingHz: 8000, - minDpi: 50, - maxDpi: 30000, - dpiStep: 50, - // Slot 3 is Forward and slot 4 is Back on this mouse. Slot 5 reads DPI Loop, - // but the mouse has no DPI button, so it is not offered. Slots 12 and 13 - // hold a second wheel pair the vendor app does not show. - buttons: [ - { name: "Left", slot: 0 }, - { name: "Right", slot: 1 }, - { name: "Middle", slot: 2 }, - { name: "Back", slot: 4 }, - { name: "Forward", slot: 3 }, - { name: "Scroll Up", slot: 14 }, - { name: "Scroll Down", slot: 15 }, - ], -}; - -export const ANGRY_MIAO_PROFILES: ReadonlyMap = new Map([ - [ANGRY_MIAO_INFINITY_PROFILE.deviceId, ANGRY_MIAO_INFINITY_PROFILE], -]); - -export interface AngryMiaoTransport { - transport: "direct" | "dongle" | "bluetooth"; - /** The settings collection on this link. */ - usagePage: number; - usage: number; -} - -/** Transport by product id. The receiver relays every mouse command; Bluetooth wraps them in report 6. */ -export const ANGRY_MIAO_PRODUCTS: ReadonlyMap = new Map([ - [0x402a, { transport: "direct", usagePage: AM30_USAGE_PAGE, usage: AM30_USAGE }], - [0x5007, { transport: "dongle", usagePage: AM30_USAGE_PAGE, usage: AM30_USAGE }], - [0x402c, { transport: "bluetooth", usagePage: AM30_BT_USAGE_PAGE, usage: AM30_BT_USAGE }], -]); +export * from "./shared.ts"; +export * from "./am30.ts"; +export * from "./am35.ts"; diff --git a/src/angry-miao/shared.test.ts b/src/angry-miao/shared.test.ts new file mode 100644 index 00000000..07a77f5d --- /dev/null +++ b/src/angry-miao/shared.test.ts @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import { it } from "node:test"; +import { + AM30_BUTTON_ACTIONS, + AM30_DEBOUNCE_GEARS_MS, + AM30_RATES, + AM30_SLEEP_OPTIONS, + ANGRY_MIAO_BUTTON_ACTION_LABELS, + ANGRY_MIAO_DEBOUNCE_GEARS_MS, + ANGRY_MIAO_RATES, + ANGRY_MIAO_SLEEP_OPTIONS, + angryMiaoDebounceGear, + angryMiaoDebounceRaw, +} from "./index.ts"; + +it("offers the .100's options from the shared catalog", () => { + assert.equal(AM30_RATES, ANGRY_MIAO_RATES); + assert.equal(AM30_DEBOUNCE_GEARS_MS, ANGRY_MIAO_DEBOUNCE_GEARS_MS); + assert.equal(AM30_SLEEP_OPTIONS, ANGRY_MIAO_SLEEP_OPTIONS); + assert.deepEqual(AM30_BUTTON_ACTIONS.map(([label]) => label), ANGRY_MIAO_BUTTON_ACTION_LABELS); +}); + +it("keeps the debounce step across rates with the vendor's per-rate tables", () => { + // 20 ms is gear 2: raw 6 at 1000 Hz, 47 at 8000 Hz; Bluetooth always uses the 1000 Hz list. + assert.equal(angryMiaoDebounceGear(1000, 6), 2); + assert.deepEqual(angryMiaoDebounceRaw(8000, 2), { usb: 47, rf: 47, bt: 6 }); + assert.equal(angryMiaoDebounceGear(8000, 46), 2, "an unlisted raw byte maps to the nearest gear"); +}); diff --git a/src/angry-miao/shared.ts b/src/angry-miao/shared.ts new file mode 100644 index 00000000..9bc86ac1 --- /dev/null +++ b/src/angry-miao/shared.ts @@ -0,0 +1,90 @@ +/** + * What every Angry Miao mouse has in common, whatever its wire protocol: the + * vendor app (ammaster.angrymiao.com) offers the same options on the .100 + * (Yichip, `am30.ts`) and the .97 and .100R2 (Airoha RACE, `am35.ts`). + */ + +export const ANGRY_MIAO_BRAND = "Angry Miao"; + +export const ANGRY_MIAO_RATES: readonly number[] = [125, 250, 500, 1000, 2000, 4000, 8000]; + +export const ANGRY_MIAO_LIFT_OFF_LEVELS = ["Low", "Medium", "High"] as const; +export type AngryMiaoLiftOff = (typeof ANGRY_MIAO_LIFT_OFF_LEVELS)[number]; + +/** Standby stops in seconds, 0 = never (the vendor presets). */ +export const ANGRY_MIAO_SLEEP_OPTIONS: readonly number[] = [0, 15, 30, 60, 600, 1800, 3600]; + +/** The vendor app's one debounce slider, by gear index (30..0 ms). */ +export const ANGRY_MIAO_DEBOUNCE_GEARS_MS: readonly number[] = [30, 25, 20, 15, 10, 5, 0]; + +const LOW_RATE_DEBOUNCE = [10, 8, 6, 4, 3, 2, 0] as const; + +/** USB and 2.4 GHz raw debounce by gear, per report rate. Bluetooth always uses the 1000 Hz list. */ +export const ANGRY_MIAO_DEBOUNCE_RAW: Readonly> = { + 125: LOW_RATE_DEBOUNCE, + 250: LOW_RATE_DEBOUNCE, + 500: LOW_RATE_DEBOUNCE, + 1000: LOW_RATE_DEBOUNCE, + 2000: [20, 16, 12, 8, 4, 2, 0], + 4000: [39, 31, 23, 15, 7, 3, 0], + 8000: [79, 63, 47, 31, 15, 7, 0], +}; + +function debounceRawList(rateHz: number | undefined): readonly number[] { + return (rateHz !== undefined && ANGRY_MIAO_DEBOUNCE_RAW[rateHz]) || LOW_RATE_DEBOUNCE; +} + +/** Gear index for a raw USB debounce byte: exact match, else the nearest. */ +export function angryMiaoDebounceGear(rateHz: number | undefined, raw: number): number { + const list = debounceRawList(rateHz); + const exact = list.indexOf(raw); + if (exact >= 0) return exact; + const nearest = Math.min(...list.map((value) => Math.abs(value - raw))); + return list.findIndex((value) => Math.abs(value - raw) === nearest); +} + +/** Raw bytes for one gear at a report rate: USB, 2.4 GHz and Bluetooth. */ +export function angryMiaoDebounceRaw( + rateHz: number | undefined, + gear: number, +): { usb: number; rf: number; bt: number } { + const list = debounceRawList(rateHz); + return { usb: list[gear], rf: list[gear], bt: LOW_RATE_DEBOUNCE[gear] }; +} + +/** Button actions OpenMouse offers, in display order. Each protocol encodes them its own way. */ +export const ANGRY_MIAO_BUTTON_ACTION_LABELS: readonly string[] = [ + "Left Click", + "Right Click", + "Middle Click", + "Back", + "Forward", + "Scroll Up", + "Scroll Down", + "DPI Loop", + "DPI +", + "DPI -", + "Volume Up", + "Volume Down", + "Mute", + "Play/Pause", + "Disabled", +]; + +/** One model's fixed facts, whatever its protocol. */ +export interface AngryMiaoModel { + brand: "Angry Miao"; + model: string; + /** Left out where no source names it. */ + sensor?: string; + maxPollingHz: number; + minDpi: number; + maxDpi: number; + dpiStep: number; + /** DPI stages the mouse holds. */ + maxDpiStages: number; + /** Physical buttons; `slot` is the protocol's own button index. */ + buttons: ReadonlyArray<{ name: string; slot: number }>; + /** Factory action per button name. */ + defaultButtonMappings: Readonly>; +} diff --git a/src/drivers/angry-miao/hid.test.ts b/src/drivers/angry-miao/am30-hid.test.ts similarity index 94% rename from src/drivers/angry-miao/hid.test.ts rename to src/drivers/angry-miao/am30-hid.test.ts index 0e591761..dd792d82 100644 --- a/src/drivers/angry-miao/hid.test.ts +++ b/src/drivers/angry-miao/am30-hid.test.ts @@ -12,7 +12,7 @@ import { AM30_OPT0_SLEEP_24G as OPT0_SLEEP_24G, } from "@openmouse/protocol/angry-miao"; import { DEVICE_DRIVERS } from "../registry.ts"; -import { AngryMiaoHidClient } from "./hid.ts"; +import { AngryMiaoAm30HidClient } from "./am30-hid.ts"; /** Every registered driver that would take this device. */ const claimants = (device: HIDDevice) => DEVICE_DRIVERS.filter((driver) => driver.supports(device)).map((driver) => driver.brand); @@ -140,12 +140,12 @@ function holdWrites(device: HIDDevice, held: { dpi?: number[]; option0?: number[ }; } -describe("AngryMiaoHidClient", () => { +describe("AngryMiaoAm30HidClient", () => { it("reads and writes over Bluetooth in report 6, as captured", async () => { const { device, sent } = fakeBluetooth(); - assert.equal(AngryMiaoHidClient.isSupported(device), true); + assert.equal(AngryMiaoAm30HidClient.isSupported(device), true); assert.deepEqual(claimants(device), ["Angry Miao"], "the AJ179 PRO driver shares 0x402C"); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); const status = await client.readStatus(); assert.equal(status.name, "Angry Miao Infinity .100"); assert.deepEqual([status.connectionType, status.connectionDetail], ["Wireless", "Bluetooth"]); @@ -167,16 +167,16 @@ describe("AngryMiaoHidClient", () => { it("claims its cable and receiver by product id and name; the registry keeps the shared driver and Fantech off them", () => { for (const ids of [WIRED, RECEIVER]) { const { device } = fakeDevice({ ids }); - assert.equal(AngryMiaoHidClient.isSupported(device), true); + assert.equal(AngryMiaoAm30HidClient.isSupported(device), true); assert.deepEqual(claimants(device), ["Angry Miao"]); } - assert.equal(AngryMiaoHidClient.isSupported(fakeDevice({ ids: { vendorId: 0x3151, productId: 0x402d } }).device), false); + assert.equal(AngryMiaoAm30HidClient.isSupported(fakeDevice({ ids: { vendorId: 0x3151, productId: 0x402d } }).device), false); // linux-hardware.org lists an AJAZZ receiver on 3151:5007. for (const productName of ["AJAZZ 2.4G 8K", ""]) { - assert.equal(AngryMiaoHidClient.isSupported(fakeDevice({ ids: RECEIVER, productName }).device), false, productName); + assert.equal(AngryMiaoAm30HidClient.isSupported(fakeDevice({ ids: RECEIVER, productName }).device), false, productName); } - assert.equal(new AngryMiaoHidClient(fakeDevice({ ids: WIRED }).device).transport, "direct"); - assert.equal(new AngryMiaoHidClient(fakeDevice({ ids: RECEIVER }).device).transport, "dongle"); + assert.equal(new AngryMiaoAm30HidClient(fakeDevice({ ids: WIRED }).device).transport, "direct"); + assert.equal(new AngryMiaoAm30HidClient(fakeDevice({ ids: RECEIVER }).device).transport, "dongle"); }); it("identifies the Infinity by cable from captured replies", async () => { @@ -196,7 +196,7 @@ describe("AngryMiaoHidClient", () => { // USB firmware read on the cable: 0x0101. [0xad]: [0xad, 0x01, 0x01, 0, 0, 0, 0, 0x52], } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); assert.equal(await client.getDeviceId(), 2222); const status = await client.readStatus(); @@ -258,7 +258,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_OPTIONPARAM0]: option0, [CMD.GET_KEYMATRIX]: bytes("keyMatrix"), } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); await client.readStatus(); const lastWrite = () => sent.filter((report) => report[0] === CMD.SET_OPTIONPARAM0).at(-1)!; // The mouse keeps each write, so a change is measured against the block it held just before. @@ -323,7 +323,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_OPTIONPARAM0]: option0, [CMD.GET_KEYMATRIX]: bytes(vendor.reads.keyMatrix), } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); await client.readStatus(); const steps: Array<[string, () => Promise]> = [ ["polling rate 1000 -> 8000 Hz", () => client.setPollingRate(8000)], @@ -355,7 +355,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_OPTIONPARAM0]: bytes("option0"), [CMD.GET_KEYMATRIX]: keyMatrix, } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); const status = await client.readStatus(); assert.deepEqual(status.buttonOptions, [ "Left Click", "Right Click", "Middle Click", "Back", "Forward", "Scroll Up", "Scroll Down", @@ -396,7 +396,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_DPI]: bytes("dpi"), [CMD.GET_OPTIONPARAM0]: bytes("option0"), } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); await client.readStatus(); const before = sent.length; assert.equal(await client.setDpi(1700), 1700); @@ -415,7 +415,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_DPI]: dpi, [CMD.GET_OPTIONPARAM0]: bytes("option0"), } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); await client.readStatus(); // The status read gets eight stages, then another D4 sees two before the status read finishes. const fake = device as unknown as { sendFeatureReport: (id: number, data: Uint8Array) => Promise }; @@ -441,7 +441,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_DPI]: dpi, [CMD.GET_OPTIONPARAM0]: bytes("option0"), } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); await client.readStatus(); const lastDpiWrite = () => sent.filter((report) => report[0] === CMD.SET_DPI).at(-1)!; @@ -490,7 +490,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_KEYMATRIX]: bytes("keyMatrix"), [0x85]: profileReply, } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); const status = await client.readStatus(); assert.equal(status.profileCount, 2); assert.equal(status.activeProfile, 2, "85 byte 1 = 1 is the second profile"); @@ -537,7 +537,7 @@ describe("AngryMiaoHidClient", () => { } return send(id, data); }; - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); await client.readStatus(); assert.equal(await client.setProfile(2), 2); assert.equal((await client.readStatus()).activeProfile, 2); @@ -557,7 +557,7 @@ describe("AngryMiaoHidClient", () => { // An empty reply reads as 64 zeros, which the driver treats as unanswered. [0x85]: [], } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); const status = await client.readStatus(); assert.equal(status.activeProfile, null); assert.equal(status.profileCount, undefined); @@ -580,7 +580,7 @@ describe("AngryMiaoHidClient", () => { const idle = [0x01, 0, 0x59, 1, 0, 1, 2, 0, 0, 1]; const spare = async (byte10: number) => { const { device } = fakeDevice({ ids: RECEIVER, replies, status: [...idle, byte10] }); - return (await new AngryMiaoHidClient(device).readStatus()).spareBattery; + return (await new AngryMiaoAm30HidClient(device).readStatus()).spareBattery; }; assert.deepEqual(await spare(0x5a), { percent: 90, state: "Charging" }); assert.deepEqual(await spare(0x64), { percent: 100, state: "Full" }); @@ -589,14 +589,14 @@ describe("AngryMiaoHidClient", () => { const onHardware = async (status: number[]) => { const { device } = fakeDevice({ ids: RECEIVER, replies, status }); - return (await new AngryMiaoHidClient(device).readStatus()).spareBattery; + return (await new AngryMiaoAm30HidClient(device).readStatus()).spareBattery; }; assert.deepEqual(await onHardware(bytes(dongle.status.replyReady)), { percent: 99, state: "Charging" }); const removed = capture("receiver-spare-removed.json"); assert.equal(await onHardware(bytes(removed.status.replyReady)), undefined, "spare taken out of the dock"); const { device } = fakeDevice({ ids: WIRED, replies }); - assert.equal((await new AngryMiaoHidClient(device).readStatus()).spareBattery, undefined, "the cable has no receiver"); + assert.equal((await new AngryMiaoAm30HidClient(device).readStatus()).spareBattery, undefined, "the cable has no receiver"); }); it("reads never-sleep and an off-table debounce byte", async () => { @@ -610,7 +610,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], [CMD.GET_OPTIONPARAM0]: option0, } }); - const status = await new AngryMiaoHidClient(device).readStatus(); + const status = await new AngryMiaoAm30HidClient(device).readStatus(); assert.equal(status.sleepTimeout, 0); assert.equal(status.pollingRateHz, 8000); assert.equal(status.debounceMs, 10, "raw 16 at 8000 Hz is nearest to 15, the 10 ms stop"); @@ -634,7 +634,7 @@ describe("AngryMiaoHidClient", () => { [0xe2]: bytes(dongle.relayed.fpsMode), }, }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); const status = await client.readStatus(); assert.equal(status.name, "Angry Miao Infinity .100"); assert.equal(status.connectionDetail, "2.4 GHz"); @@ -682,7 +682,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], [CMD.GET_OPTIONPARAM0]: [...Buffer.from(reads.replies.option0, "hex")], } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); const status = await client.readStatus(); assert.equal(status.ui?.settingsReady, false); assert.equal(status.ui?.receiverOnly, undefined, "the mouse answered; only its id is unknown"); @@ -706,7 +706,7 @@ describe("AngryMiaoHidClient", () => { [0x85]: profile, } }); holdWrites(device, { dpi, option0, profile }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); await client.readStatus(); // Two DPI table edits started together both stay on the mouse. @@ -736,7 +736,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], [CMD.GET_OPTIONPARAM0]: [...Buffer.from(reads.replies.option0, "hex")], } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); await client.readStatus(); // The next status read finds another model, and a change starts before that read finishes. usbVersion.splice(1, 2, 1893 & 0xff, 1893 >> 8); @@ -752,7 +752,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], [CMD.GET_OPTIONPARAM0]: [...Buffer.from(reads.replies.option0, "hex")], } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); await client.readStatus(); await assert.rejects(client.setMotionSync(true), /did not keep the change: options byte 63/); const heads = sent.map((report) => report[0]); @@ -774,7 +774,7 @@ describe("AngryMiaoHidClient", () => { if (data[0] === CMD.SET_OPTIONPARAM0) option0.splice(8, 56, ...data.subarray(8)); return send(id, data); }; - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); assert.equal((await client.readStatus()).liftOffDistance, "Medium"); // Neither call waits for the other, as when two controls change at once. await Promise.all([client.setLiftOffDistance("Low"), client.setMotionSync(true)]); @@ -789,7 +789,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], [CMD.GET_OPTIONPARAM0]: [...Buffer.from(reads.replies.option0, "hex")], } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); await client.readStatus(); // A background poll starts, then the user changes a setting before it finishes. const poll = client.readStatus(); @@ -803,7 +803,7 @@ describe("AngryMiaoHidClient", () => { const { device, sent } = fakeDevice({ ids: WIRED, replies: { [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); const busy = client.command([CMD.GET_DPI]); const request = [0x85]; const queued = client.command(request); @@ -814,7 +814,7 @@ describe("AngryMiaoHidClient", () => { it("retries an unanswered relayed command three times, then releases the receiver", async () => { const { device, sent } = fakeDevice({ ids: RECEIVER }); - await assert.rejects(new AngryMiaoHidClient(device).command([0xd6]), /not answered/); + await assert.rejects(new AngryMiaoAm30HidClient(device).command([0xd6]), /not answered/); assert.equal(sent.filter((report) => report[0] === 0xd6).length, 3); assert.deepEqual([...sent.at(-1)!.subarray(0, 2)], [0xf6, 0x00], "F6 00 after the last try"); }); @@ -826,7 +826,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_OPTIONPARAM0]: bytes(dongle.relayed.option0), [CMD.GET_DPI]: bytes(dongle.relayed.dpi), } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); await client.readStatus(); const fake = device as unknown as { sendFeatureReport: (id: number, data: Uint8Array) => Promise }; const send = fake.sendFeatureReport; @@ -856,7 +856,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_OPTIONPARAM0]: bytes(dongle.relayed.option0), [CMD.GET_DPI]: bytes(dongle.relayed.dpi), } }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); const receiverLabels = (firmware: string[]) => firmware.filter((label) => label.startsWith("Receiver")); assert.deepEqual(receiverLabels((await client.readStatus()).firmware), ["Receiver USB 0x0008", "Receiver LED 0x0109"]); @@ -885,7 +885,7 @@ describe("AngryMiaoHidClient", () => { [CMD.GET_FIRMWARE]: [CMD.GET_FIRMWARE, 0x18, 0x03], }; const { device, sent } = fakeDevice({ ids: RECEIVER, receiverReplies, replies }); - const client = new AngryMiaoHidClient(device); + const client = new AngryMiaoAm30HidClient(device); const status = await client.readStatus(); assert.deepEqual(status.firmware, [ "Mouse SoC 0x0318", "Receiver USB 0x0008", "Receiver RF 0xf0", "Receiver LED 0x0109", "PixArt PAW3950", @@ -897,7 +897,7 @@ describe("AngryMiaoHidClient", () => { // F7 byte 4 = 1: the mouse is asleep, off, or on another link; byte 10 is a spare at 90 %. const offline = fakeDevice({ ids: RECEIVER, receiverReplies, replies, status: [0, 0, 0, 1, 1, 1, 2, 0, 0, 1, 0x5a] }); - const alone = await new AngryMiaoHidClient(offline.device).readStatus(); + const alone = await new AngryMiaoAm30HidClient(offline.device).readStatus(); assert.equal(alone.ui?.settingsReady, false); assert.equal(alone.ui?.receiverOnly, true); assert.equal(alone.name, "Angry Miao Receiver"); diff --git a/src/drivers/angry-miao/am30-hid.ts b/src/drivers/angry-miao/am30-hid.ts new file mode 100644 index 00000000..99974919 --- /dev/null +++ b/src/drivers/angry-miao/am30-hid.ts @@ -0,0 +1,878 @@ +import type { MouseLighting, MouseLightingMode, MouseStatus } from "../mouse-types.ts"; +import { AngryMiaoHidClient, type AngryMiaoLightingChange, type AngryMiaoSettingsChange } from "./base.ts"; +import { + AM30_BUTTON_ACTIONS, + AM30_CMD, + AM30_DPI_RGB_OFFSET, + AM30_DPI_X_OFFSET, + AM30_DPI_Y_OFFSET, + AM30_LIFT_OFF_LEVELS, + AM30_MAX_DPI_STAGES, + AM30_OPT0_ANGLE_SNAP, + AM30_OPT0_DEBOUNCE, + AM30_OPT0_FLAGS, + AM30_OPT0_LIFT_OFF, + AM30_OPT0_REPORT_RATE, + AM30_OPT0_SLEEP_24G, + AM30_RATE_DECODE, + AM30_RATE_ENCODE, + AM30_RELAY, + AM30_RELAY_ATTEMPTS, + AM30_RELAY_LENGTH, + AM30_REPORT_ID, + AM30_REPORT_SIZE, + AM30_TARGET_MOUSE, + AM30_TARGET_NONE, + AM30_BT_BATTERY, + AM30_BT_ENVELOPE, + AM30_BT_REPORT_ID, + AM30_BT_REPORT_SIZE, + AM30_BT_SLEEPING, + AM30_OPT0_SLEEP_BT, + am30BluetoothPacket, + ANGRY_MIAO_PRODUCT_NAME, + am30EncodeCommand, + ANGRY_MIAO_VENDOR_ID, + type AngryMiaoModel, + type AngryMiaoProfile, + type AngryMiaoTransport, + AM30_DEBOUNCE_GEARS_MS, + AM30_DEFAULT_BUTTON_MAPPINGS, + AM30_GET_BATTERY, + AM30_GET_BLAST_MODE, + AM30_GET_PROFILE, + AM30_GET_USB_VERSION, + AM30_OPT0_DEBOUNCE_24G, + AM30_OPT0_DEBOUNCE_BT, + AM30_OPT0_FLAG_RIPPLE, + AM30_OPT0_LIGHT, + AM30_OPT0_LIGHT_COLOR, + AM30_OPT0_LIGHT_COLOR_2, + AM30_OPT0_MOTION_SYNC, + AM30_PROFILE_COUNT, + AM30_RECEIVER_BRIGHTNESS, + AM30_RECEIVER_GET_LED_VERSION, + AM30_RECEIVER_GET_LIGHT, + AM30_RECEIVER_GET_LIGHT_SWITCH, + AM30_RECEIVER_GET_RF_VERSION, + AM30_RECEIVER_GET_USB_VERSION, + AM30_RECEIVER_SET_LIGHT_SWITCH, + AM30_RECEIVER_SPEEDS, + AM30_SET_BLAST_MODE, + AM30_SET_PROFILE, + AM30_SLEEP_NEVER, + AM30_STATUS_MOUSE_OFFLINE, + am30DebounceGear, + am30DebounceRaw, + am30DecodeBattery, + am30DecodeButtonAction, + am30DecodeReceiverLight, + am30DecodeSpareBattery, + am30EncodeButtonAction, + am30EncodeReceiverLight, + am30FirmwareLabels, + am30ReceiverFirmwareLabels, + ANGRY_MIAO_INFINITY_PROFILE, + ANGRY_MIAO_PRODUCTS, + ANGRY_MIAO_PROFILES, +} from "@openmouse/protocol/angry-miao"; + +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +interface Am30DpiStage { + x: number; + y: number; + rgb: number; +} + +/** Receiver light effects 1..8 in the vendor's order (always on, breathing, neon, light wave, ...). */ +const RECEIVER_EFFECTS: readonly MouseLightingMode[] = [ + "Static", "Breathing single", "Neon", "Wave", "Marquee", "Ring", "Buffer", "Chase", +]; + +/** + * Angry Miao Infinity .100 (AM30) on the Yichip protocol. This client owns its + * whole stack: feature-report I/O, the receiver relay, the settings layout + * (`@openmouse/protocol/angry-miao`), the battery, motion sync, Blast Mode and + * both lights. Nothing is inherited from the other Yichip brands' driver; the + * settings OpenMouse offers come from the shared Angry Miao base. + */ +export class AngryMiaoAm30HidClient extends AngryMiaoHidClient { + currentProfile = 0; + + private readonly transportEntry: AngryMiaoTransport | undefined; + /** False until `85` answers, so button mappings never go to a guessed profile. */ + private profileConfirmed = false; + /** The model for the last `8F` device id, or null when it is not one we know. */ + private resolvedProfile: AngryMiaoProfile | null = null; + /** Last Blast Mode write; on SoC firmware 1.1.1 `E2` does not reflect it. */ + private blastMode: boolean | null = null; + /** `80` reply from the last status read. */ + private firmwareCode: number | null = null; + /** Receiver version replies, kept once each answers, so a later status read retries only the missing ones. */ + private receiverFirmware: { usb: Uint8Array | null; rf: Uint8Array | null; led: Uint8Array | null } = { + usb: null, rf: null, led: null, + }; + /** `8F` device id from the last status read; writes need a known one. */ + private deviceId: number | null = null; + + constructor(device: HIDDevice) { + super(device); + this.transportEntry = ANGRY_MIAO_PRODUCTS.get(device.productId); + } + + static isSupported(device: HIDDevice): boolean { + const entry = ANGRY_MIAO_PRODUCTS.get(device.productId); + if (device.vendorId !== ANGRY_MIAO_VENDOR_ID || !entry) return false; + // Other brands reuse these product ids, so the name has to be Angry Miao's too. + if (!ANGRY_MIAO_PRODUCT_NAME.test(device.productName ?? "")) return false; + const hasControl = (collections: readonly HIDCollectionInfo[]): boolean => + collections.some((c) => (c.usagePage === entry.usagePage && c.usage === entry.usage) || hasControl(c.children ?? [])); + return hasControl(device.collections); + } + + get transport(): "dongle" | "direct" | "bluetooth" { + return this.transportEntry?.transport ?? "direct"; + } + + private get profile(): AngryMiaoProfile { + return this.resolvedProfile ?? ANGRY_MIAO_INFINITY_PROFILE; + } + + protected get model(): AngryMiaoModel { + return this.profile; + } + + // ── Feature-report I/O and the receiver relay ───────────────────────────── + + private async rawSend(bytes: readonly number[] | Uint8Array): Promise { + const buf = new Uint8Array(AM30_REPORT_SIZE); + buf.set(bytes instanceof Uint8Array ? bytes.subarray(0, AM30_REPORT_SIZE) : bytes.slice(0, AM30_REPORT_SIZE)); + await this.device.sendFeatureReport(AM30_REPORT_ID, buf); + } + + private async rawRead(): Promise { + const view = await this.device.receiveFeatureReport(AM30_REPORT_ID); + return new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength)); + } + + /** `F7`: byte 0 = 1 when a reply is ready, byte 5 = 1 when the receiver takes a command. */ + private async pollStatus(): Promise { + await this.rawSend([AM30_RELAY.GET_STATUS]); + await delay(10); + return this.rawRead(); + } + + private async waitReady(byte: 0 | 5): Promise { + for (let attempt = 0; attempt < 8; attempt++) { + await delay(100); + if ((await this.pollStatus())[byte] === 1) return true; + } + return false; + } + + /** The vendor app selects the mouse and sends `FE 40` before every relayed command. */ + private async prepareRelay(): Promise { + await this.rawSend([AM30_RELAY.SELECT_TARGET, AM30_TARGET_MOUSE]); + await delay(50); + if (!(await this.waitReady(5))) throw new Error("The 2.4 GHz receiver never became ready to send."); + await this.rawSend([AM30_RELAY.SET_LENGTH, AM30_RELAY_LENGTH]); + await delay(10); + } + + /** A reply of 64 zeros means the command was not answered; most replies echo the command id. */ + private verifyReply(resp: Uint8Array, cmd: number, echoes: boolean): Uint8Array { + const id = `0x${cmd.toString(16)}`; + if (resp.length < AM30_REPORT_SIZE) throw new Error(`Command ${id} returned ${resp.length} bytes, expected ${AM30_REPORT_SIZE}.`); + if (resp.every((byte) => byte === 0)) throw new Error(`Command ${id} was not answered (all-zero response).`); + if (echoes && resp[0] !== cmd) throw new Error(`Command ${id} answered with id 0x${resp[0].toString(16)}.`); + return resp; + } + + /** Retries a relayed exchange, then sends `F6 00` so a failed relay does not leave the receiver stuck. */ + private async relay(exchange: () => Promise): Promise { + let failure: unknown; + for (let attempt = 0; attempt < AM30_RELAY_ATTEMPTS; attempt++) { + if (attempt > 0) await delay(100); + try { + return await exchange(); + } catch (error) { + failure = error; + } + } + await this.rawSend([AM30_RELAY.SELECT_TARGET, AM30_TARGET_NONE]).catch(() => undefined); + throw failure; + } + + /** One mouse command and its reply, relayed on 2.4 GHz. */ + async command(bytes: readonly number[], opts: { echoes?: boolean } = {}): Promise { + // Copied now, so a caller that reuses its array cannot change a command still waiting in the queue. + const request = [...bytes]; + const echoes = opts.echoes ?? true; + return this.enqueue(() => this.exchange(request, echoes)); + } + + /** The body of `command`. Call it only from a task that already holds the queue. */ + private async exchange(bytes: readonly number[], echoes: boolean): Promise { + const encoded = am30EncodeCommand(bytes); + await this.open(); + if (this.transport === "bluetooth") return this.exchangeBluetooth(encoded, bytes[0], echoes); + if (this.transport === "direct") { + await this.rawSend(encoded); + await delay(10); + return this.verifyReply(await this.rawRead(), bytes[0], echoes); + } + return this.relay(async () => { + await this.prepareRelay(); + await this.rawSend(encoded); + if (!(await this.waitReady(0))) throw new Error("The 2.4 GHz receiver never became ready to read."); + await this.rawSend([AM30_RELAY.NOTICE_READ]); + await delay(10); + return this.verifyReply(await this.rawRead(), bytes[0], echoes); + }); + } + + /** Product ids and names are shared, so only a device id we have tested may be written to. */ + private async sendWrite(cmd: Uint8Array): Promise { + this.assertModelVerified(); + return this.enqueue(() => this.transmit(cmd)); + } + + /** The body of `sendWrite`. Call it only from a task that already holds the queue. */ + private async transmit(cmd: Uint8Array): Promise { + const encoded = am30EncodeCommand([...cmd]); + await this.open(); + if (this.transport === "bluetooth") { + await this.device.sendReport(AM30_BT_REPORT_ID, am30BluetoothPacket(encoded)); + await delay(60); + return; + } + if (this.transport === "direct") { + await this.rawSend(encoded); + await delay(10); + return; + } + // A retry only happens before the write is sent: `prepareRelay` is the step that can fail. + await this.relay(() => this.prepareRelay()); + try { + await this.rawSend(encoded); + } catch (error) { + // No retry, because the receiver may already hold the write. Release it so it does not stay on the mouse. + await this.rawSend([AM30_RELAY.SELECT_TARGET, AM30_TARGET_NONE]).catch(() => undefined); + throw error; + } + await delay(50); + } + + private assertModelVerified(): void { + if (!this.modelVerified) { + throw new Error(`Device id ${this.deviceId ?? "unknown"} is not a verified Angry Miao model; settings are read-only.`); + } + } + + private get modelVerified(): boolean { + return this.deviceId !== null && ANGRY_MIAO_PROFILES.has(this.deviceId); + } + + /** Bluetooth replies arrive as input report 6; null from `decode` skips an unrelated report. */ + private requestBluetooth(request: Uint8Array, decode: (packet: Uint8Array) => T | null): Promise { + return new Promise((resolve, reject) => { + const cleanup = () => { + clearTimeout(timer); + this.device.removeEventListener("inputreport", onReport); + }; + const onReport = (event: HIDInputReportEvent) => { + if (event.reportId !== AM30_BT_REPORT_ID) return; + const packet = new Uint8Array(event.data.buffer, event.data.byteOffset, event.data.byteLength); + if (packet.length !== AM30_BT_REPORT_SIZE) return; + try { + const result = decode(packet); + if (result === null) return; + cleanup(); + resolve(result); + } catch (error) { + cleanup(); + reject(error); + } + }; + const timer = setTimeout(() => { + cleanup(); + reject(new Error("The mouse did not answer over Bluetooth. Move it and try again.")); + }, 2000); + this.device.addEventListener("inputreport", onReport); + this.device.sendReport(AM30_BT_REPORT_ID, request).catch((error) => { + cleanup(); + reject(error); + }); + }); + } + + private exchangeBluetooth(encoded: Uint8Array, cmd: number, echoes: boolean): Promise { + return this.requestBluetooth(am30BluetoothPacket(encoded), (packet) => { + if (packet[0] !== AM30_BT_ENVELOPE) return null; + const reply = packet.slice(1); + if (echoes && reply[0] !== cmd) return null; + return this.verifyReply(reply, cmd, echoes); + }); + } + + /** `77`: battery percent in byte 1. The mouse answers `88` while asleep. */ + private bluetoothBattery(): Promise { + return this.enqueue(async () => { + await this.open(); + const request = new Uint8Array(AM30_BT_REPORT_SIZE); + request[0] = AM30_BT_BATTERY; + return this.requestBluetooth(request, (packet) => { + if (packet[0] === AM30_BT_SLEEPING) throw new Error("The mouse is asleep."); + if (packet[0] !== AM30_BT_BATTERY) return null; + if (packet[1] > 100) throw new Error("The mouse returned an invalid battery percentage."); + return packet[1]; + }); + }); + } + + // ── Reads ───────────────────────────────────────────────────────────────── + + /** `8F` bytes 1-4, LE32. */ + async getDeviceId(): Promise { + const resp = await this.command([AM30_CMD.GET_DEVICE_ID]); + return (resp[1] | (resp[2] << 8) | (resp[3] << 16) | (resp[4] << 24)) >>> 0; + } + + async getFirmwareVersion(): Promise { + const resp = await this.command([AM30_CMD.GET_FIRMWARE]); + this.firmwareCode = (resp[2] << 8) | resp[1]; + return this.firmwareCode; + } + + async getOptionParam0(): Promise { + return this.command([AM30_CMD.GET_OPTIONS]); + } + + async getReportRate(): Promise { + const code = (await this.getOptionParam0())[AM30_OPT0_REPORT_RATE]; + const hz = AM30_RATE_DECODE[code]; + if (hz === undefined) throw new Error(`Unknown report-rate code ${code}.`); + return hz; + } + + /** 14 slots x 4 bytes with no echo byte. Read late in a status read, so it retries once. */ + async getKeyMatrix(profile = 0): Promise { + const read = async () => { + const reply = await this.command([AM30_CMD.GET_KEYMATRIX, profile], { echoes: false }); + // A lost relay reply can leave an echoed command buffered; actions never start at 0x80 or above. + if (reply[0] >= 0x80) throw new Error("The mouse returned a stale command instead of button mappings."); + return reply; + }; + try { + return await read(); + } catch { + return await read(); + } + } + + /** + * Read-modify-write of the whole options block; bytes not overridden are written back as read. + * Call it only from inside `exclusive`, so another change cannot land between the read and the write. + */ + private async patchOptions( + overrides: Record number)>, + ): Promise { + this.assertModelVerified(); + const current = await this.getOptionParam0(); + const block = new Uint8Array(AM30_REPORT_SIZE); + block.set(current.subarray(8, AM30_REPORT_SIZE), 8); + block[0] = AM30_CMD.SET_OPTIONS; + for (const [offset, value] of Object.entries(overrides)) { + const i = Number(offset); + block[i] = (typeof value === "function" ? value(current[i], current) : value) & 0xff; + } + await this.sendWrite(block); + // Read the block back, as the maintainer asked: the mouse reports every byte this setter changed. + const kept = await this.getOptionParam0(); + const lost = Object.keys(overrides).map(Number).find((i) => kept[i] !== block[i]); + if (lost !== undefined) { + throw new Error(`The mouse did not keep the change: options byte ${lost} reads ${kept[lost]}, not ${block[lost]}.`); + } + } + + // ── Settings ────────────────────────────────────────────────────────────── + + private buttonSlots() { + return this.profile.buttons; + } + + /** Active onboard profile, 0-based, or null when `85` is not answered. */ + private async readProfile(): Promise { + const active = (await this.command([AM30_GET_PROFILE]))[1]; + return active < AM30_PROFILE_COUNT ? active : null; + } + + /** 1-based. The vendor app confirms with `85`, then always turns Blast Mode off. */ + setProfile(profile: number): Promise { + return this.exclusive(() => this.switchProfile(profile)); + } + + private async switchProfile(profile: number): Promise { + if (!Number.isInteger(profile) || profile < 1 || profile > AM30_PROFILE_COUNT) { + throw new Error(`The Angry Miao Infinity .100 has onboard profiles 1 to ${AM30_PROFILE_COUNT}.`); + } + // Unknown from here on: the mouse may switch even if the send or every confirmation fails. + this.profileConfirmed = false; + await this.sendWrite(Uint8Array.from([AM30_SET_PROFILE, profile - 1, AM30_PROFILE_COUNT])); + let active: number | null = null; + for (let attempt = 0; attempt < 3 && active !== profile - 1; attempt++) { + if (attempt > 0) await delay(100); + // One unanswered read does not mean the switch failed, so the remaining attempts still run. + try { active = await this.readProfile(); } catch { active = null; } + } + if (active !== profile - 1) { + this.profileConfirmed = active !== null; + if (active !== null) this.currentProfile = active; + throw new Error(active === null + ? `The mouse did not confirm the switch to profile ${profile}. Read the status again.` + : `The mouse stayed on profile ${active + 1}.`); + } + this.currentProfile = active; + this.profileConfirmed = true; + await this.writeBlastMode(false); + return profile; + } + + /** `50` and `D0` name a profile, so the mappings stay read-only until `85` confirms the active one. */ + private confirmedProfile(): number { + if (!this.profileConfirmed) { + throw new Error("The active profile is unknown, so button mappings are read-only. Read the status again."); + } + return this.currentProfile; + } + + getButtonOptions(): string[] { + return AM30_BUTTON_ACTIONS.map(([label]) => label); + } + + /** The vendor app locks Left to Left Click so the mouse always keeps a primary click. */ + protected writeButtonMapping(button: string, action: string): Promise { + return this.writeButton(this.confirmedProfile(), button, action); + } + + private async writeButton(profile: number, button: string, action: string): Promise { + const target = this.buttonSlots().find((b) => b.name === button); + if (!target) throw new Error(`Unknown button "${button}".`); + const value = am30EncodeButtonAction(button === "Left" ? "Left Click" : action); + if (!value) throw new Error(`Unsupported button action "${action}".`); + const cmd = new Uint8Array(AM30_REPORT_SIZE); + cmd.set([AM30_CMD.SET_KEYMATRIX, profile, target.slot]); + cmd.set(value, 8); + await this.sendWrite(cmd); + } + + /** The confirmed profile's mappings; the base's reset compares them with the factory ones. */ + protected async readButtonMappings(): Promise> { + const matrix = await this.getKeyMatrix(this.confirmedProfile()); + return Object.fromEntries(this.buttonSlots().map(({ name, slot }) => [ + name, am30DecodeButtonAction(matrix.subarray(slot * 4, slot * 4 + 4)), + ])); + } + + /** All eight stage slots; stages past the count keep their values for when it grows again. */ + async getDpi(): Promise<{ stages: Am30DpiStage[]; activeIndex: number; count: number }> { + // No profile byte: `D4` answers for the active profile, as the vendor app reads it. + const resp = await this.command([AM30_CMD.GET_DPI]); + const count = Math.min(resp[3], AM30_MAX_DPI_STAGES); + if (count === 0) throw new Error("The Angry Miao Infinity .100 reported no DPI stages."); + const stages: Am30DpiStage[] = []; + for (let i = 0; i < AM30_MAX_DPI_STAGES; i++) { + const rgb = AM30_DPI_RGB_OFFSET + i * 3; + stages.push({ + x: resp[AM30_DPI_X_OFFSET + i * 2] | (resp[AM30_DPI_X_OFFSET + 1 + i * 2] << 8), + y: resp[AM30_DPI_Y_OFFSET + i * 2] | (resp[AM30_DPI_Y_OFFSET + 1 + i * 2] << 8), + rgb: (resp[rgb] << 16) | (resp[rgb + 1] << 8) | resp[rgb + 2], + }); + } + return { stages, activeIndex: Math.min(resp[2], count - 1), count }; + } + + /** `54`: the whole eight-stage table with the active stage and the count. */ + private async writeStageTable(stages: Am30DpiStage[], active: number, count: number): Promise { + const cmd = new Uint8Array(AM30_REPORT_SIZE); + cmd.set([AM30_CMD.SET_DPI, 0, active, count]); + stages.forEach((stage, i) => { + cmd.set([stage.x & 0xff, stage.x >> 8], AM30_DPI_X_OFFSET + i * 2); + cmd.set([stage.y & 0xff, stage.y >> 8], AM30_DPI_Y_OFFSET + i * 2); + cmd.set([(stage.rgb >> 16) & 0xff, (stage.rgb >> 8) & 0xff, stage.rgb & 0xff], AM30_DPI_RGB_OFFSET + i * 3); + }); + await this.sendWrite(cmd); + } + + /** Reads the table, edits one stage and writes it back; out-of-range `index` means the active stage. */ + protected async writeDpiStage(x: number, y: number, index: number): Promise { + // `D4` runs once, so an out-of-range stage targets the active stage of the table it returns. + const { stages, activeIndex, count } = await this.getDpi(); + const target = index >= 0 && index < count ? index : activeIndex; + stages[target] = { ...stages[target], x, y }; + await this.writeStageTable(stages, activeIndex, count); + } + + setDpiStageColor(index: number, color: string): Promise { + return this.exclusive(async () => { + const match = /^#?([0-9a-f]{6})$/i.exec(color); + if (!match) throw new Error(`Invalid DPI stage colour "${color}".`); + const rgb = parseInt(match[1], 16); + const { stages, activeIndex, count } = await this.getDpi(); + const target = index >= 0 && index < count ? index : activeIndex; + stages[target] = { ...stages[target], rgb }; + await this.writeStageTable(stages, activeIndex, count); + return `#${match[1].toLowerCase()}`; + }); + } + + protected async writeActiveDpiStage(index: number): Promise { + const { stages, count } = await this.getDpi(); + const target = Math.max(0, Math.min(index, count - 1)); + await this.writeStageTable(stages, target, count); + return target; + } + + /** The active stage clamps to the last one kept. */ + protected async writeDpiStageCount(count: number): Promise { + const { stages, activeIndex } = await this.getDpi(); + // The vendor app fills a slot it does not hold with 800 DPI, red. + const filled = stages.map((stage) => (stage.x === 0 ? { x: 800, y: 800, rgb: 0xff0000 } : stage)); + await this.writeStageTable(filled, Math.min(activeIndex, count - 1), count); + return count; + } + + /** Every change is one patch of the options block, read back by `patchOptions`. */ + protected async applySettings(change: AngryMiaoSettingsChange): Promise { + const overrides: Record number)> = {}; + const { reportRateHz, debounceGear } = change; + if (reportRateHz !== undefined || debounceGear !== undefined) { + // Raw debounce bytes are per rate, so a rate change rewrites them for the step the block holds. + const raw = (block: Uint8Array) => { + const currentRate = AM30_RATE_DECODE[block[AM30_OPT0_REPORT_RATE]]; + return am30DebounceRaw( + reportRateHz ?? currentRate, + debounceGear ?? am30DebounceGear(currentRate, block[AM30_OPT0_DEBOUNCE]), + ); + }; + if (reportRateHz !== undefined) overrides[AM30_OPT0_REPORT_RATE] = AM30_RATE_ENCODE[reportRateHz]; + overrides[AM30_OPT0_DEBOUNCE] = (_, block) => raw(block).usb; + overrides[AM30_OPT0_DEBOUNCE_24G] = (_, block) => raw(block).rf; + overrides[AM30_OPT0_DEBOUNCE_BT] = (_, block) => raw(block).bt; + } + if (change.liftOff !== undefined) overrides[AM30_OPT0_LIFT_OFF] = AM30_LIFT_OFF_LEVELS.indexOf(change.liftOff); + if (change.angleSnapping !== undefined) overrides[AM30_OPT0_ANGLE_SNAP] = change.angleSnapping ? 1 : 0; + if (change.rippleControl !== undefined) { + const on = change.rippleControl; + overrides[AM30_OPT0_FLAGS] = (current) => on ? current | AM30_OPT0_FLAG_RIPPLE : current & ~AM30_OPT0_FLAG_RIPPLE; + } + if (change.motionSync !== undefined) overrides[AM30_OPT0_MOTION_SYNC] = change.motionSync ? 1 : 0; + if (change.sleepSeconds !== undefined) { + // The vendor app edits each link's timer on its own, so only the current link's is written. + const raw = change.sleepSeconds === 0 ? AM30_SLEEP_NEVER : change.sleepSeconds; + overrides[this.sleepOffset] = raw & 0xff; + overrides[this.sleepOffset + 1] = (raw >> 8) & 0xff; + } + await this.patchOptions(overrides); + } + + private get sleepOffset(): number { + return this.transport === "bluetooth" ? AM30_OPT0_SLEEP_BT : AM30_OPT0_SLEEP_24G; + } + + protected async writeBlastMode(enabled: boolean): Promise { + await this.sendWrite(Uint8Array.from([AM30_SET_BLAST_MODE, enabled ? 1 : 0])); + this.blastMode = enabled; + return enabled; + } + + private mouseLight(opt0: Uint8Array): MouseLighting { + const rgb = opt0.subarray(AM30_OPT0_LIGHT_COLOR, AM30_OPT0_LIGHT_COLOR + 3); + return { + zone: "Mouse", + modes: ["Off", "Static"], + mode: opt0[AM30_OPT0_LIGHT] ? "Static" : "Off", + color: `#${Array.from(rgb, (b) => b.toString(16).padStart(2, "0")).join("")}`, + color2: null, + colorModes: ["Static"], + dualColorModes: [], + reactiveModes: [], + speeds: [], + speed: null, + }; + } + + /** The vendor's mouse light panel writes its one colour into both RGB slots. */ + setLighting(lighting: AngryMiaoLightingChange): Promise { + return this.exclusive(() => this.writeLighting(lighting)); + } + + private async writeLighting(lighting: AngryMiaoLightingChange): Promise { + if (lighting.zone === "Receiver") return this.setReceiverLight(lighting); + if (lighting.mode !== "Off" && lighting.mode !== "Static") { + throw new Error(`Unsupported lighting mode: ${lighting.mode}.`); + } + const overrides: Record = { [AM30_OPT0_LIGHT]: lighting.mode === "Static" ? 1 : 0 }; + if (lighting.mode === "Static" && lighting.color) { + const match = /^#?([0-9a-f]{6})$/i.exec(lighting.color); + if (!match) throw new Error(`Invalid lighting colour: ${lighting.color}.`); + const value = parseInt(match[1], 16); + [(value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff].forEach((byte, i) => { + overrides[AM30_OPT0_LIGHT_COLOR + i] = byte; + overrides[AM30_OPT0_LIGHT_COLOR_2 + i] = byte; + }); + } + await this.patchOptions(overrides); + return this.mouseLight(await this.getOptionParam0()); + } + + /** Commands for the receiver itself: straight to it, never relayed to the mouse. */ + private receiverCommand(packet: Uint8Array, expectReply: boolean, echoes = true): Promise { + return this.enqueue(async () => { + await this.open(); + await this.rawSend(packet); + await delay(10); + return expectReply ? this.verifyReply(await this.rawRead(), packet[0], echoes) : null; + }); + } + + /** Raw `F7` status reply, which carries no checksum and no echo byte. */ + private readReceiverStatus(): Promise { + return this.enqueue(async () => { + await this.open(); + await this.rawSend([AM30_RELAY.GET_STATUS]); + await delay(10); + return this.rawRead(); + }); + } + + /** The vendor app's order: USB, a 500 ms pause, RF, LED. */ + private async readReceiverFirmware(): Promise { + const known = this.receiverFirmware; + const read = async (command: number, echoes = true) => { + try { return await this.receiverCommand(am30EncodeCommand([command]), true, echoes); } catch { return null; } + }; + // A failed read never replaces a version that is already known. + if (!known.usb) { + known.usb = await read(AM30_RECEIVER_GET_USB_VERSION) ?? known.usb; + if (!known.rf) await delay(500); + } + if (!known.rf) known.rf = await read(AM30_RECEIVER_GET_RF_VERSION, false) ?? known.rf; + if (!known.led) known.led = await read(AM30_RECEIVER_GET_LED_VERSION) ?? known.led; + return am30ReceiverFirmwareLabels(known.usb, known.rf, known.led); + } + + /** The receiver answers on its own while the mouse sleeps, is off, or is on another link. */ + private async receiverOnlyStatus(receiverStatus: Uint8Array): Promise { + let receiverLight: MouseLighting | undefined; + try { receiverLight = await this.readReceiverLight(); } catch { /* Optional: the zone stays hidden. */ } + const firmware = await this.readReceiverFirmware(); + const spareBattery = am30DecodeSpareBattery(receiverStatus); + const { brand } = ANGRY_MIAO_INFINITY_PROFILE; + // No mouse answers, so the receiver gets its own name instead of the mouse's. + const name = `${brand} Receiver`; + return { + brand, + name, + ui: { + family: "angry-miao", + settingsReady: false, + receiverOnly: true, + defaultDisplayName: name, + hideAdvancedLighting: true, + separateLightingZones: true, + statusNote: "The receiver is connected, but the mouse is not answering. Wake it, or switch it to 2.4 GHz.", + }, + batteryPercent: null, + batteryState: "Unknown", + dpi: 0, + pollingRateHz: 0, + activeProfile: null, + liftOffDistance: null, + connectionType: "Wireless", + connectionDetail: "2.4 GHz", + firmware, + ...(spareBattery ? { spareBattery } : {}), + ...(receiverLight ? { lightingZones: [receiverLight] } : {}), + }; + } + + private async readReceiverLight(): Promise { + const light = await this.receiverCommand(am30EncodeCommand([AM30_RECEIVER_GET_LIGHT]), true); + const power = await this.receiverCommand(am30EncodeCommand([AM30_RECEIVER_GET_LIGHT_SWITCH]), true); + const decoded = am30DecodeReceiverLight(light!, power!); + return { + zone: "Receiver", + modes: ["Off", ...RECEIVER_EFFECTS], + mode: decoded.enabled ? RECEIVER_EFFECTS[decoded.effect - 1] : "Off", + color: decoded.color, + color2: null, + // The vendor panel hides the colour for neon and the speed for always on. + colorModes: RECEIVER_EFFECTS.filter((mode) => mode !== "Neon"), + dualColorModes: [], + reactiveModes: RECEIVER_EFFECTS.filter((mode) => mode !== "Static"), + speeds: [...AM30_RECEIVER_SPEEDS], + speed: decoded.speed, + brightness: decoded.brightness, + brightnessLevels: [...AM30_RECEIVER_BRIGHTNESS], + }; + } + + private async setReceiverLight( + lighting: Pick & Partial>, + ): Promise { + if (this.transport !== "dongle") throw new Error("The receiver light needs the 2.4 GHz receiver."); + if (lighting.mode !== "Off") { + const effect = lighting.mode ? RECEIVER_EFFECTS.indexOf(lighting.mode) + 1 : 0; + if (effect < 1) throw new Error(`Unsupported receiver light effect: ${lighting.mode}.`); + await this.receiverCommand(am30EncodeReceiverLight({ + effect, + speed: lighting.speed ?? 1, + brightness: lighting.brightness ?? 100, + color: lighting.color ?? "#ffffff", + }), false); + await delay(30); + } + await this.receiverCommand(am30EncodeCommand([AM30_RECEIVER_SET_LIGHT_SWITCH, lighting.mode === "Off" ? 0 : 1]), false); + return this.readReceiverLight(); + } + + readStatus(): Promise { + return this.exclusive(() => this.readStatusNow()); + } + + private async readStatusNow(): Promise { + await this.open(); + this.firmwareCode = null; + // The last verified id stays until `8F` answers again, so a write made during this read still goes out. + let receiverStatus: Uint8Array | null = null; + if (this.transport === "dongle") { + receiverStatus = await this.readReceiverStatus(); + if (receiverStatus[AM30_STATUS_MOUSE_OFFLINE] !== 0) { + // The mouse is absent, so nothing it reported earlier holds any more. + this.deviceId = null; + this.resolvedProfile = null; + this.profileConfirmed = false; + return this.receiverOnlyStatus(receiverStatus); + } + } + // Read first: `D0` and `50` take the profile index. + let profile: number | null = null; + try { profile = await this.readProfile(); } catch { /* Optional: the profile selector stays hidden. */ } + this.profileConfirmed = profile !== null; + if (profile !== null) this.currentProfile = profile; + let deviceId: number | null = null; + try { deviceId = await this.getDeviceId(); } catch { /* Unknown: settings stay read-only. */ } + this.deviceId = deviceId; + this.resolvedProfile = this.deviceId === null ? null : ANGRY_MIAO_PROFILES.get(this.deviceId) ?? null; + const model = this.profile; + const name = this.resolvedProfile + ? `${model.brand} ${model.model}` + : this.device.productName?.trim() || "Angry Miao mouse"; + + // The DPI read has to work: it proves the relay and checksum path. + const dpi = await this.getDpi(); + const active = dpi.stages[dpi.activeIndex] ?? dpi.stages[0]; + const [opt0Result, matrixResult] = await Promise.allSettled([ + this.getOptionParam0(), + // Without a confirmed profile the mappings stay hidden rather than show a guessed profile's. + profile !== null ? this.getKeyMatrix(profile) : Promise.resolve(null), + this.getFirmwareVersion(), + ]); + const opt0 = opt0Result.status === "fulfilled" ? opt0Result.value : null; + // Only this read's own `D0` reply, never another call's. + const matrix = matrixResult.status === "fulfilled" ? matrixResult.value : null; + const buttonMappings = matrix && Object.fromEntries(this.buttonSlots().map(({ name, slot }) => [ + name, am30DecodeButtonAction(matrix.subarray(slot * 4, slot * 4 + 4)), + ])); + const { count } = dpi; + + // F7 byte 2 mirrors the mouse battery through the receiver; D6 reads it from the mouse itself. + let battery: ReturnType = { percent: null, state: "Unknown" }; + try { battery = am30DecodeBattery(await this.command([AM30_GET_BATTERY])); } catch { /* Optional. */ } + if (battery.percent === null && this.transport === "bluetooth") { + try { battery = { percent: await this.bluetoothBattery(), state: "Unknown" }; } catch { /* Optional. */ } + } + let turboMode: boolean | undefined; + try { + turboMode = this.blastMode ?? (await this.command([AM30_GET_BLAST_MODE]))[1] === 1; + } catch { /* Optional: the switch stays hidden. */ } + let usbCode: number | null = null; + // The vendor app reads `AD` on the cable only; through the receiver it reads 0. + if (this.transport === "direct") { + try { + const reply = await this.command([AM30_GET_USB_VERSION]); + usbCode = reply[1] | (reply[2] << 8); + } catch { /* Optional: the package version needs it. */ } + } + const firmware = am30FirmwareLabels(usbCode, this.firmwareCode || null); + let receiverLight: MouseLighting | undefined; + let spareBattery: ReturnType = null; + if (this.transport === "dongle") { + try { receiverLight = await this.readReceiverLight(); } catch { /* Optional: the zone stays hidden. */ } + firmware.push(...await this.readReceiverFirmware()); + if (receiverStatus) spareBattery = am30DecodeSpareBattery(receiverStatus); + } + const mouseLight = opt0 ? this.mouseLight(opt0) : undefined; + const rawSleep = opt0 ? opt0[this.sleepOffset] | (opt0[this.sleepOffset + 1] << 8) : null; + const wireless = this.transport !== "direct"; + + return { + brand: model.brand, + name, + ui: { + family: "angry-miao", + settingsReady: this.modelVerified, + defaultDisplayName: name, + hideAdvancedLighting: true, + separateLightingZones: true, + dpiStageEditor: { + maxStages: AM30_MAX_DPI_STAGES, + minDpi: model.minDpi, + maxDpi: model.maxDpi, + stepDpi: model.dpiStep, + countEditable: true, + }, + ...(this.modelVerified ? {} : { + statusNote: `This mouse reports device id ${this.deviceId ?? "unknown"}, which OpenMouse has not verified, so its settings are read-only.`, + }), + }, + dpi: active.x, + dpiY: active.y, + supportsSeparateDpiAxes: true, + dpiStages: dpi.stages.slice(0, count).map((stage) => stage.x), + dpiStageColors: dpi.stages.slice(0, count).map((stage) => `#${stage.rgb.toString(16).padStart(6, "0")}`), + activeDpiStage: dpi.activeIndex, + pollingRateHz: (opt0 && AM30_RATE_DECODE[opt0[AM30_OPT0_REPORT_RATE]]) || 1000, + supportedPollingRates: this.supportedPollingRates, + connectionType: wireless ? "Wireless" : "Wired", + connectionDetail: { bluetooth: "Bluetooth", dongle: "2.4 GHz", direct: "USB" }[this.transport], + liftOffDistance: opt0 ? AM30_LIFT_OFF_LEVELS[opt0[AM30_OPT0_LIFT_OFF]] ?? AM30_LIFT_OFF_LEVELS[0] : null, + angleSnapping: opt0 ? opt0[AM30_OPT0_ANGLE_SNAP] !== 0 : null, + debounceMs: null, + rippleControl: null, + sleepTimeout: rawSleep === AM30_SLEEP_NEVER ? 0 : rawSleep, + activeProfile: profile === null ? null : profile + 1, + ...(profile !== null ? { profileCount: AM30_PROFILE_COUNT } : {}), + firmware: [...firmware, model.sensor], + batteryPercent: battery.percent, + batteryState: battery.state, + ...(spareBattery ? { spareBattery } : {}), + ...(opt0 ? { + debounceMs: AM30_DEBOUNCE_GEARS_MS[am30DebounceGear(AM30_RATE_DECODE[opt0[AM30_OPT0_REPORT_RATE]], opt0[AM30_OPT0_DEBOUNCE])], + rippleControl: (opt0[AM30_OPT0_FLAGS] & AM30_OPT0_FLAG_RIPPLE) !== 0, + motionSync: opt0[AM30_OPT0_MOTION_SYNC] === 1, + lighting: mouseLight, + } : {}), + ...(receiverLight ? { lightingZones: [...(mouseLight ? [mouseLight] : []), receiverLight] } : {}), + ...(turboMode !== undefined ? { turboMode } : {}), + ...(buttonMappings ? { + buttonMappings, + buttonOptions: this.getButtonOptions(), + defaultButtonMappings: { ...AM30_DEFAULT_BUTTON_MAPPINGS }, + fixedButtons: ["Left"], + } : {}), + }; + } +} diff --git a/src/drivers/angry-miao/am35-hid.test.ts b/src/drivers/angry-miao/am35-hid.test.ts new file mode 100644 index 00000000..233407c1 --- /dev/null +++ b/src/drivers/angry-miao/am35-hid.test.ts @@ -0,0 +1,426 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { AM35_CMD, am35EncodeSleep, am35ParseFrame } from "@openmouse/protocol/angry-miao"; +import { DEVICE_DRIVERS } from "../registry.ts"; +import { AngryMiaoAm30R2HidClient, AngryMiaoAm35HidClient } from "./am35-hid.ts"; + +const claimants = (device: HIDDevice) => DEVICE_DRIVERS.filter((driver) => driver.supports(device)).map((driver) => driver.brand); + +/** The write path as it runs once an owner has confirmed the mouse. */ +class Writable97 extends AngryMiaoAm35HidClient { + protected override readonly writable = true; +} +class WritableR2 extends AngryMiaoAm30R2HidClient { + protected override readonly writable = true; +} + +const READS = new Set([ + AM35_CMD.GET_REPORT_RATE, AM35_CMD.GET_SW_DEBOUNCE, AM35_CMD.GET_LOD, AM35_CMD.GET_MOTION_SYNC, AM35_CMD.GET_ANGLE_SNAPPING, + AM35_CMD.GET_RIPPLE_CONTROL, AM35_CMD.GET_SLEEP_TIME, AM35_CMD.GET_FPS_MODE, AM35_CMD.GET_DPI, AM35_CMD.GET_BATTERY, + AM35_CMD.GET_KEY_REMAP, AM35_CMD.READ_NV_DATA, AM35_CMD.GET_DONGLE_LIGHT, AM35_CMD.GET_VERSION, AM35_CMD.GET_DONGLE_MODE, + AM35_CMD.GET_DONGLE_DEVICE_LIST, AM35_CMD.GET_DONGLE_PAIRED_LIST, +]); +/** Writes the vendor app sends without waiting for a reply. */ +const NO_REPLY = new Set([AM35_CMD.SET_LIGHT_SETTINGS, AM35_CMD.SET_DONGLE_LIGHT]); + +const le = (v: number) => [v & 0xff, v >> 8]; + +interface Sent { command: number; deviceId: number; payload: number[] } + +/** + * A mouse that keeps what it is told and answers RACE as the vendor app reads it: on feature report 0x14 + * (or, with `documented`, output 0x06 and input 0x07), splitting long replies over several reports. + */ +function fakeMouse(options: { + ids?: { vendorId: number; productId: number }; + productName?: string; + documented?: boolean; + paired?: boolean; + /** Commands the mouse acknowledges but does not apply. */ + ignores?: number[]; + /** Commands the mouse never answers. */ + silent?: number[]; + /** RGB per DPI slot; red by default. */ + rgb?: number[][]; + prefix?: number; +} = {}) { + const ids = options.ids ?? { vendorId: 0x0e8d, productId: 0x0880 }; + const state = { + rate: 1000, + debounce: [6, 6, 6], + lod: 1, + flags: { [AM35_CMD.GET_MOTION_SYNC]: 1, [AM35_CMD.GET_ANGLE_SNAPPING]: 0, [AM35_CMD.GET_RIPPLE_CONTROL]: 0 } as Record, + sleep: am35EncodeSleep(30, 600), + fps: 1, + dpi: { count: 6, active: 2, xs: [400, 800, 1600, 3200, 6400, 12800, 800, 800], ys: [400, 800, 1600, 3200, 6400, 12800, 800, 800] }, + keys: new Map(), + light: [1, 0, 6], + receiverLight: [0, 1, 0x01, 0xfe, 96, 0, 0, 100, 0, 0, 100, 90, 240], + }; + const keyBase = ids.productId === 0x0881 || ids.productId === 0x0704 ? 0xef : 0; + for (let k = 1; k <= 7; k++) state.keys.set(k + keyBase, [k === 6 ? 12 : k === 7 ? 13 : k]); + const sent: Sent[] = []; + const pending: number[][] = []; + const listeners = new Set<(event: unknown) => void>(); + let partial: number[] = []; + + const reply = (command: number, payload: number[]) => { + const frame = [options.prefix ?? 0x05, 0x5b, ...le(payload.length + 2), ...le(command), ...payload]; + for (let i = 0; i < frame.length; i += 59) { + const chunk = frame.slice(i, i + 59); + pending.push([chunk.length, 0, ...chunk, ...new Array(59 - chunk.length).fill(0)]); + } + }; + + const handle = (command: number, deviceId: number, payload: number[]) => { + sent.push({ command, deviceId, payload }); + if (options.silent?.includes(command)) return; + if (options.ignores?.includes(command)) return reply(command, [0]); + switch (command) { + case AM35_CMD.GET_REPORT_RATE: return reply(command, [0, ...le(state.rate)]); + case AM35_CMD.SET_REPORT_RATE: state.rate = payload[0] | (payload[1] << 8); return reply(command, [0]); + case AM35_CMD.GET_SW_DEBOUNCE: return reply(command, [0, ...state.debounce]); + case AM35_CMD.SET_SW_DEBOUNCE: state.debounce = payload.slice(0, 3); return reply(command, [0]); + case AM35_CMD.GET_LOD: return reply(command, [0, state.lod]); + case AM35_CMD.SET_LOD: state.lod = payload[0]; return reply(command, [0]); + case AM35_CMD.GET_MOTION_SYNC: case AM35_CMD.GET_ANGLE_SNAPPING: case AM35_CMD.GET_RIPPLE_CONTROL: + return reply(command, [0, state.flags[command]]); + case AM35_CMD.SET_MOTION_SYNC: case AM35_CMD.SET_ANGLE_SNAPPING: case AM35_CMD.SET_RIPPLE_CONTROL: + state.flags[command + 1] = payload[0]; + return reply(command, [0]); + case AM35_CMD.GET_SLEEP_TIME: return reply(command, [0, ...state.sleep]); + case AM35_CMD.SET_SLEEP_TIME: state.sleep = payload; return reply(command, [0]); + case AM35_CMD.GET_FPS_MODE: return reply(command, [0, state.fps]); + case AM35_CMD.SET_FPS_MODE: state.fps = payload[0]; return reply(command, [0]); + case AM35_CMD.GET_DPI: { + const { count, active, xs, ys } = state.dpi; + return reply(command, [0, count, active, ...xs.flatMap(le), ...ys.flatMap(le), ...xs.flatMap((_, i) => options.rgb?.[i] ?? [0xff, 0, 0])]); + } + case AM35_CMD.SET_DPI: { + state.dpi.xs[payload[0]] = payload[1] | (payload[2] << 8); + state.dpi.ys[payload[0]] = payload[3] | (payload[4] << 8); + return reply(command, [0]); + } + case AM35_CMD.SET_DPI_LOOP_RANGE: state.dpi.count = payload[0]; return reply(command, [0]); + case AM35_CMD.SET_CURRENT_DPI_STAGE: state.dpi.active = payload[0]; return reply(command, [0]); + case AM35_CMD.GET_BATTERY: return reply(command, [0, 0, 86, 0, 1, 0, 0]); + case AM35_CMD.GET_KEY_REMAP: return reply(command, [0, payload[0], ...(state.keys.get(payload[0]) ?? [0])]); + case AM35_CMD.SET_KEY_REMAP: state.keys.set(payload[0], payload.slice(1)); return reply(command, [0]); + case AM35_CMD.READ_NV_DATA: { + const address = payload[0] | (payload[1] << 8); + if (address === 0x600a) return reply(command, [0, ...le(address), 3, 0, ...state.light]); + if (address === 0x6200) return reply(command, [0, ...le(address), 7, 0, 0, 0, 0, 0, 0x00, 0xff, 0x00]); + return reply(command, [1]); + } + case AM35_CMD.SET_LIGHT_SETTINGS: state.light = payload; return options.documented ? reply(command, [0]) : undefined; + case AM35_CMD.GET_DONGLE_LIGHT: return reply(command, state.receiverLight); + case AM35_CMD.SET_DONGLE_LIGHT: state.receiverLight = payload; return; + case AM35_CMD.GET_VERSION: + reply(command, [0]); + return reply(command, [0, ...Buffer.from("v1.0.12")]); + case AM35_CMD.GET_DONGLE_MODE: return reply(command, [0, 18, 0, 1]); + case AM35_CMD.SET_DONGLE_LINK_TYPE: return reply(command, [0, 6]); + case AM35_CMD.GET_DONGLE_DEVICE_LIST: case AM35_CMD.GET_DONGLE_PAIRED_LIST: + return reply(command, options.paired === false ? [0] : [0, 1, 2, 3, 4, 5, 6, 7, 0x80, 0, 1]); + default: return reply(command, [1]); + } + }; + + const receive = (data: Uint8Array) => { + partial.push(...data.subarray(2, 2 + data[0])); + const frame = am35ParseFrame(partial); + if (!frame) return; + partial = []; + handle(frame.command, data[1], frame.payload); + }; + + const report = (id: number) => ({ reportId: id, items: [{ reportSize: 8, reportCount: 61 }] }); + const device = { + ...ids, + productName: options.productName ?? "AM Infinity .97", + opened: true, + collections: [{ + usagePage: 0xff00, + usage: 1, + featureReports: options.documented ? [] : [report(0x14)], + outputReports: options.documented ? [report(0x06)] : [], + inputReports: options.documented ? [report(0x07)] : [], + children: [], + }], + open: async () => {}, + close: async () => {}, + addEventListener: (_type: string, listener: (event: unknown) => void) => listeners.add(listener), + removeEventListener: (_type: string, listener: (event: unknown) => void) => listeners.delete(listener), + sendFeatureReport: options.documented ? undefined : async (id: number, data: Uint8Array) => { + assert.equal(id, 0x14); + assert.equal(data.length, 61); + receive(data); + }, + receiveFeatureReport: async () => new DataView(Uint8Array.from(pending.shift() ?? new Array(61).fill(0)).buffer), + sendReport: async (id: number, data: Uint8Array) => { + assert.equal(id, 0x06); + receive(data); + queueMicrotask(() => { + while (pending.length) { + const data = new DataView(Uint8Array.from(pending.shift()!).buffer); + listeners.forEach((listener) => listener({ reportId: 0x07, data })); + } + }); + }, + }; + return { device: device as unknown as HIDDevice, sent, state }; +} + +const writes = (sent: Sent[]) => sent.filter(({ command }) => !READS.has(command)); + +describe("AngryMiaoAm35HidClient", () => { + it("claims the .97 and .100R2 ids only on an interface with the RACE reports", () => { + const nine7 = fakeMouse().device; + assert.equal(AngryMiaoAm35HidClient.isSupported(nine7), true); + assert.equal(AngryMiaoAm30R2HidClient.isSupported(nine7), false); + assert.deepEqual(claimants(nine7), ["Angry Miao"]); + const r2 = fakeMouse({ ids: { vendorId: 0x0e8d, productId: 0x0881 } }).device; + assert.equal(AngryMiaoAm30R2HidClient.isSupported(r2), true); + assert.equal(AngryMiaoAm35HidClient.isSupported(r2), false); + assert.deepEqual(claimants(r2), ["Angry Miao"]); + assert.equal(AngryMiaoAm35HidClient.isSupported(fakeMouse({ documented: true }).device), true); + const bare = { ...fakeMouse().device, collections: [{ usagePage: 0xff00, usage: 1, featureReports: [{ reportId: 0x05 }], children: [] }] }; + assert.deepEqual(claimants(bare as unknown as HIDDevice), []); + assert.deepEqual(claimants({ ...fakeMouse().device, vendorId: 0x0e8d, productId: 0x0882 } as unknown as HIDDevice), []); + }); + + it("reads every setting on the cable and writes nothing doing it", async () => { + const { device, sent } = fakeMouse(); + const status = await new Writable97(device).readStatus(); + assert.equal(status.name, "Angry Miao Infinity .97"); + assert.equal(status.ui?.settingsReady, true); + assert.equal(status.connectionDetail, "USB"); + assert.deepEqual(status.dpiStages, [400, 800, 1600, 3200, 6400, 12800]); + assert.equal(status.dpi, 1600); + assert.equal(status.activeDpiStage, 2); + assert.equal(status.dpiStageColors?.[0], "#ff0000"); + assert.equal(status.pollingRateHz, 1000); + assert.equal(status.debounceMs, 20); + assert.equal(status.liftOffDistance, "Medium"); + assert.equal(status.motionSync, true); + assert.equal(status.angleSnapping, false); + assert.equal(status.sleepTimeout, 30); + assert.equal(status.turboMode, true); + assert.equal(status.batteryPercent, 86); + assert.deepEqual(status.firmware, ["Mouse firmware v1.0.12"]); + assert.equal(status.lighting?.mode, "Static"); + assert.equal(status.lighting?.color, "#00ff00"); + assert.deepEqual(status.buttonMappings, { + Left: "Left Click", Right: "Right Click", Middle: "Middle Click", Forward: "Forward", Back: "Back", + "Scroll Up": "Scroll Up", "Scroll Down": "Scroll Down", + }); + assert.deepEqual(writes(sent), [], "a status read sends only reads"); + assert.ok(sent.every(({ deviceId }) => deviceId === 0)); + }); + + it("only reads until an owner confirms the mouse: no editors, and every setter refuses", async () => { + const { device, sent } = fakeMouse(); + const client = new AngryMiaoAm35HidClient(device); + const status = await client.readStatus(); + assert.equal(status.ui?.settingsReady, false); + assert.equal(status.ui?.valuesVerified, true, "Hardware test still reports the readings"); + assert.equal(status.ui?.pollingReadOnly, true); + assert.equal(status.ui?.dpiStageEditor, undefined); + assert.deepEqual(status.dpiStages, [400, 800, 1600, 3200, 6400, 12800]); + assert.equal(status.pollingRateHz, 1000); + assert.equal(status.liftOffDistance, "Medium"); + assert.equal(status.buttonMappings?.Back, "Back"); + for (const key of ["lighting", "lightingZones", "turboMode", "buttonOptions"] as const) assert.equal(status[key], undefined, key); + const refused = /only reads the Angry Miao Infinity \.97/; + await assert.rejects(client.setPollingRate(2000), refused); + await assert.rejects(client.setDpi(800), refused); + await assert.rejects(client.setButtonMapping("Back", "Mute"), refused); + await assert.rejects(client.setLighting({ mode: "Off", color: null }), refused); + await assert.rejects(client.setTurboMode(false), refused); + assert.deepEqual(writes(sent), []); + }); + + it("keeps the debounce step when the rate changes, as the vendor app does", async () => { + const { device, sent, state } = fakeMouse(); + await new Writable97(device).setPollingRate(8000); + assert.deepEqual(writes(sent).map(({ command, payload }) => [command, payload]), [ + [AM35_CMD.SET_REPORT_RATE, [0x40, 0x1f]], + // 20 ms is raw 47 at 8000 Hz; Bluetooth keeps the 1000 Hz value. + [AM35_CMD.SET_SW_DEBOUNCE, [47, 47, 6]], + ]); + assert.equal(state.rate, 8000); + }); + + it("reads every write back and reports a change the mouse did not keep", async () => { + const client = new Writable97(fakeMouse({ ignores: [AM35_CMD.SET_LOD] }).device); + await assert.rejects(client.setLiftOffDistance("High"), /did not keep the change: lift-off reads "Medium", not "High"/); + const { device, state } = fakeMouse(); + const ok = new Writable97(device); + assert.equal(await ok.setDebounceTime(5), 5); + assert.deepEqual(state.debounce, [2, 2, 2]); + assert.equal(await ok.setSleepTimeout(0), 0); + assert.deepEqual(state.sleep, am35EncodeSleep(0, 600), "Bluetooth keeps its own timer"); + assert.equal(await ok.setTurboMode(false), false); + assert.equal(state.fps, 0); + }); + + it("edits DPI stages with the vendor app's commands", async () => { + const { device, sent, state } = fakeMouse(); + const client = new Writable97(device); + await client.setDpiStageValue(2, 1650); + await client.setDpiStageValue(0, 450); + await client.setDpiStageCount(2); + assert.deepEqual(writes(sent).map(({ command, payload }) => [command, payload]), [ + [AM35_CMD.SET_DPI, [2, ...le(1650), ...le(1650)]], + // Stage 3 is the active one, so it is selected again. + [AM35_CMD.SET_CURRENT_DPI_STAGE, [2]], + [AM35_CMD.SET_DPI, [0, ...le(450), ...le(450)]], + [AM35_CMD.SET_DPI_LOOP_RANGE, [2]], + [AM35_CMD.SET_CURRENT_DPI_STAGE, [1]], + ]); + assert.equal(state.dpi.count, 2); + await assert.rejects(client.setDpiStageCount(9), /holds 1 to 8 DPI stages/); + await assert.rejects(client.setDpi(1625), /50 DPI steps/); + }); + + it("maps buttons by the .97's key ids and keeps Left a left click", async () => { + const { device, sent } = fakeMouse(); + const client = new Writable97(device); + await client.setButtonMapping("Back", "DPI +"); + await client.setButtonMapping("Left", "Mute"); + assert.deepEqual(writes(sent).map(({ payload }) => payload), [[5, 11, 0, 0, 0], [1, 1]]); + await client.resetButtonMappings(); + assert.deepEqual(writes(sent).at(-1)?.payload, [5, 5], "only Back differed from its factory action"); + }); + + it("numbers the .100R2's buttons 0xF0-0xF6 and names its two custom keys", async () => { + const { device, sent } = fakeMouse({ ids: { vendorId: 0x0e8d, productId: 0x0881 }, productName: "AM INFINITY .100R2" }); + const client = new WritableR2(device); + const status = await client.readStatus(); + assert.equal(status.name, "Angry Miao Infinity .100R2"); + assert.equal(status.buttonMappings?.["Custom 1"], "Scroll Up"); + assert.deepEqual(sent.filter(({ command }) => command === AM35_CMD.GET_KEY_REMAP).map(({ payload }) => payload[0]), + [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6]); + await client.setButtonMapping("Back", "Mute"); + assert.deepEqual(writes(sent).at(-1)?.payload, [0xf4, 6, 0xe2, 0, 0, 0]); + }); + + it("asks the receiver for its paired mouse, then talks to the mouse as device 0x80", async () => { + const { device, sent } = fakeMouse({ ids: { vendorId: 0x0e8d, productId: 0x0703 }, productName: "AM INFINITY 2.4G Dongle" }); + const status = await new Writable97(device).readStatus(); + assert.equal(status.connectionDetail, "2.4 GHz"); + assert.deepEqual(sent.slice(0, 5).map(({ command, deviceId, payload }) => [command, deviceId, payload]), [ + [AM35_CMD.GET_DONGLE_MODE, 0, [18, 0]], + [AM35_CMD.SET_DONGLE_LINK_TYPE, 0, [6]], + [AM35_CMD.GET_DONGLE_DEVICE_LIST, 0, []], + [AM35_CMD.GET_DONGLE_PAIRED_LIST, 0, []], + [AM35_CMD.GET_DPI, 0x80, []], + ]); + const local = new Set([AM35_CMD.GET_DONGLE_LIGHT, AM35_CMD.GET_VERSION]); + assert.ok(sent.slice(4).every(({ command, deviceId }) => deviceId === (local.has(command) ? 0 : 0x80))); + assert.deepEqual(writes(sent).map(({ command }) => command), [AM35_CMD.SET_DONGLE_LINK_TYPE], "the vendor app's link type is the only write"); + assert.equal(status.lightingZones?.at(-1)?.zone, "Receiver"); + assert.equal(status.lightingZones?.at(-1)?.color, "#00ff00"); + assert.deepEqual(status.firmware, ["Receiver firmware v1.0.12"]); + }); + + it("shows the receiver alone when it holds no mouse", async () => { + const { device } = fakeMouse({ ids: { vendorId: 0x0e8d, productId: 0x0703 }, paired: false }); + const status = await new AngryMiaoAm35HidClient(device).readStatus(); + assert.equal(status.ui?.receiverOnly, true); + assert.equal(status.ui?.settingsReady, false); + }); + + it("counts the mouse as linked when it answers the DPI read, even without a battery reply", async () => { + const { device } = fakeMouse({ ids: { vendorId: 0x0e8d, productId: 0x0703 }, silent: [AM35_CMD.GET_BATTERY] }); + const status = await new AngryMiaoAm35HidClient(device).readStatus(); + assert.equal(status.ui?.receiverOnly, undefined); + assert.equal(status.dpi, 1600); + assert.equal(status.batteryPercent, null); + }); + + it("talks to the mouse as device 0 through a receiver without report 0x14, as the vendor app does", async () => { + const { device, sent } = fakeMouse({ ids: { vendorId: 0x0e8d, productId: 0x0703 }, documented: true }); + const status = await new AngryMiaoAm35HidClient(device).readStatus(); + assert.equal(status.ui?.receiverOnly, undefined); + assert.equal(status.connectionDetail, "2.4 GHz"); + assert.equal(status.dpi, 1600); + assert.ok(sent.every(({ deviceId }) => deviceId === 0)); + assert.ok(!sent.some(({ command }) => command === AM35_CMD.GET_DONGLE_MODE), "no opening sequence"); + }); + + it("keeps a zero-filled continuation report of a long reply", async () => { + const black = [0, 0, 0]; + const red = [0xff, 0, 0]; + const { device } = fakeMouse({ rgb: [red, red, red, red, red, red, black, black] }); + const status = await new AngryMiaoAm35HidClient(device).readStatus(); + assert.equal(status.dpi, 1600); + assert.deepEqual(status.dpiStages, [400, 800, 1600, 3200, 6400, 12800]); + }); + + it("sends no mouse command through the receiver until it has found the mouse", async () => { + const linked = fakeMouse({ ids: { vendorId: 0x0e8d, productId: 0x0703 } }); + await assert.rejects(new Writable97(linked.device).setPollingRate(2000), /not linked through the receiver/); + assert.deepEqual(linked.sent, [], "nothing reached the receiver as device 0"); + const alone = fakeMouse({ ids: { vendorId: 0x0e8d, productId: 0x0703 }, paired: false }); + const client = new Writable97(alone.device); + assert.equal((await client.readStatus()).ui?.receiverOnly, true); + const before = alone.sent.length; + await assert.rejects(client.setPollingRate(2000), /not linked through the receiver/); + assert.equal(alone.sent.length, before); + }); + + it("turns the lights on and off without touching their stored patterns", async () => { + const { device, sent, state } = fakeMouse({ ids: { vendorId: 0x0e8d, productId: 0x0703 } }); + const client = new Writable97(device); + await client.readStatus(); + const mouse = await client.setLighting({ mode: "Off", color: null }); + assert.equal(mouse.mode, "Off"); + assert.deepEqual(state.light, [0, 0, 6]); + await assert.rejects(client.setLighting({ mode: "Breathing single", color: null }), /only turn this light on or off/); + const receiver = await client.setLighting({ zone: "Receiver", mode: "Breathing single", color: "#0000ff" }); + assert.equal(receiver.mode, "Breathing single"); + assert.equal(receiver.color, "#0000ff"); + assert.deepEqual(state.receiverLight.slice(0, 5), [1, 2, 0x03, 0xfc, 96]); + const lightWrites = sent.filter(({ command }) => command === AM35_CMD.SET_LIGHT_SETTINGS || command === AM35_CMD.SET_DONGLE_LIGHT); + assert.deepEqual(lightWrites.map(({ command, deviceId }) => [command, deviceId]), [ + [AM35_CMD.SET_LIGHT_SETTINGS, 0x80], + [AM35_CMD.SET_DONGLE_LIGHT, 0], + ]); + }); + + it("falls back to output 0x06 and input 0x07 when the interface has no report 0x14", async () => { + const { device, sent } = fakeMouse({ documented: true }); + const client = new Writable97(device); + const status = await client.readStatus(); + assert.equal(status.dpi, 1600); + await client.setMotionSync(false); + assert.deepEqual(writes(sent).map(({ command, payload }) => [command, payload]), [[AM35_CMD.SET_MOTION_SYNC, [0]]]); + }); + + it("joins a long reply that starts with 0x15 on both transports", async () => { + for (const documented of [false, true]) { + const status = await new Writable97(fakeMouse({ documented, prefix: 0x15 }).device).readStatus(); + assert.deepEqual(status.dpiStages, [400, 800, 1600, 3200, 6400, 12800]); + } + }); + + it("leaves no reply wait behind when a report cannot be sent", async () => { + const { device } = fakeMouse({ documented: true }); + device.sendReport = async () => { + throw new Error("unplugged"); + }; + const unhandled: unknown[] = []; + const record = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", record); + try { + await assert.rejects(new AngryMiaoAm35HidClient(device).getDpi(), /unplugged/); + await new Promise((resolve) => setTimeout(resolve, 3500)); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); + } finally { + process.off("unhandledRejection", record); + } + assert.deepEqual(unhandled, []); + }); +}); diff --git a/src/drivers/angry-miao/am35-hid.ts b/src/drivers/angry-miao/am35-hid.ts new file mode 100644 index 00000000..13c89caa --- /dev/null +++ b/src/drivers/angry-miao/am35-hid.ts @@ -0,0 +1,704 @@ +import type { MouseLighting, MouseLightingMode, MouseStatus } from "../mouse-types.ts"; +import { AngryMiaoHidClient, type AngryMiaoLightingChange, type AngryMiaoSettingsChange } from "./base.ts"; +import { + AM30R2_KEY_OFFSET, + AM35_CMD, + AM35_DONGLE_LINK_TYPE, + AM35_DONGLE_MODE_QUERY, + AM35_FEATURE_REPORT, + AM35_INPUT_REPORT, + AM35_LOCAL_DEVICE, + AM35_NV_DPI_COLOR, + AM35_NV_LIGHT_COLOR, + AM35_NV_LIGHT_SETTINGS, + AM35_OUTPUT_REPORT, + AM35_REMOTE_DEVICE, + AM35_REPORT_SIZE, + type Am35DpiTable, + type Am35MouseEffect, + type Am35Product, + type Am35Reply, + type Am35ReceiverLight, + ANGRY_MIAO_DEBOUNCE_GEARS_MS, + ANGRY_MIAO_INFINITY_100R2_MODEL, + ANGRY_MIAO_INFINITY_97_MODEL, + type AngryMiaoModel, + am35ColorFromHue, + am35DecodeBattery, + am35DecodeButtonAction, + am35DecodeDebounce, + am35DecodeDeviceList, + am35DecodeDpi, + am35DecodeFlag, + am35DecodeFpsMode, + am35DecodeLiftOff, + am35DecodeMouseLight, + am35DecodeNvData, + am35DecodeReceiverLight, + am35DecodeReportRate, + am35DecodeSleep, + am35DecodeStoredColor, + am35DecodeVersion, + am35EncodeButtonAction, + am35EncodeDebounce, + am35EncodeDpiStage, + am35EncodeLiftOff, + am35EncodeMouseLight, + am35EncodeNvRead, + am35EncodeReceiverLight, + am35EncodeReportRate, + am35EncodeSleep, + am35Frame, + am35HueFromColor, + am35IsReceiver, + am35IsVersionAck, + am35ParseFrame, + am35ParseFrames, + am35Product, + am35ReportChunk, + am35Reports, + angryMiaoDebounceGear, + angryMiaoDebounceRaw, +} from "@openmouse/protocol/angry-miao"; + +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** The vendor app's reply wait: 1.2 s, or 3 s through the receiver; empty reads are retried every 20 ms. */ +const REPLY_TIMEOUT_MS = 1200; +const REMOTE_REPLY_TIMEOUT_MS = 3000; +const EMPTY_READ_DELAY_MS = 20; +const BUSY_READ_DELAY_MS = 80; + +const MOUSE_EFFECT_MODE: Record = { + Solid: "Static", + Breathing: "Breathing single", + Neon: "Neon", +}; + +/** Receiver light effects 1 and 2; the vendor's others (flow, mosaic, aurora, night city, arc) have no OpenMouse name. */ +const RECEIVER_MODES: readonly MouseLightingMode[] = ["Static", "Breathing single"]; + +/** Commands that change a setting. The receiver link type is left out: the vendor app sends it to connect. */ +const SETTING_WRITES: ReadonlySet = new Set( + Object.entries(AM35_CMD).filter(([name]) => name.startsWith("SET_") && name !== "SET_DONGLE_LINK_TYPE").map(([, command]) => command), +); + +/** Without writes, report the readings but no editor that would offer a change. */ +function readOnlyStatus(status: MouseStatus): MouseStatus { + const { lighting, lightingZones, turboMode, buttonOptions, defaultButtonMappings, fixedButtons, ...readings } = status; + const { dpiStageEditor, ...ui } = status.ui ?? {}; + return { + ...readings, + ui: { + ...ui, + settingsReady: false, + valuesVerified: !ui.receiverOnly, + pollingReadOnly: true, + ...(ui.receiverOnly ? {} : { + statusNote: "OpenMouse reads this mouse but does not change it yet. Run Hardware test and share the report so settings can be turned on.", + }), + }, + }; +} + +interface SendOptions { + /** Defaults to the mouse: through the receiver that is its paired device id. */ + device?: number; + /** False for writes the vendor app sends without waiting for a reply. */ + reply?: boolean; + /** False for replies that do not lead with a status byte. */ + status?: boolean; +} + +function hasReport(collections: readonly HIDCollectionInfo[], kind: "featureReports" | "inputReports" | "outputReports", id: number): boolean { + return collections.some((c) => (c[kind] ?? []).some((r) => r.reportId === id) || hasReport(c.children ?? [], kind, id)); +} + +function reportBytes(collections: readonly HIDCollectionInfo[], kind: "featureReports" | "outputReports", id: number): number | null { + for (const c of collections) { + const report = (c[kind] ?? []).find((r) => r.reportId === id); + if (report) { + const bits = (report.items ?? []).reduce((sum, item) => sum + (item.reportSize ?? 0) * (item.reportCount ?? 0), 0); + return bits > 0 ? Math.ceil(bits / 8) : null; + } + const nested = reportBytes(c.children ?? [], kind, id); + if (nested !== null) return nested; + } + return null; +} + +/** + * Angry Miao Infinity .97 (AM35) on Airoha's RACE protocol, following the + * vendor configurator byte for byte. Every write is read back. The codec + * refuses any command outside the ones used here, so reset, firmware update, + * pairing and stored-data writes cannot be sent. Untested on hardware. + */ +export class AngryMiaoAm35HidClient extends AngryMiaoHidClient { + /** Off until an owner confirms the reads with Hardware test; the writes follow the vendor app but are untested. */ + protected readonly writable: boolean = false; + protected readonly product: Am35Product; + readonly isReceiver: boolean; + /** The mouse's device id behind the receiver, once the receiver has listed it. */ + private remoteDevice: number | null = null; + + constructor(device: HIDDevice) { + super(device); + this.product = am35Product(device.vendorId, device.productId) ?? { family: "am35", role: "mouse" }; + this.isReceiver = am35IsReceiver(this.product, device.productName); + } + + /** The vendor app's ids, on an interface that carries the RACE reports. */ + static isSupported(device: HIDDevice): boolean { + const product = am35Product(device.vendorId, device.productId); + if (!product || product.family !== this.family) return false; + const collections = device.collections ?? []; + return hasReport(collections, "featureReports", AM35_FEATURE_REPORT) + || (hasReport(collections, "outputReports", AM35_OUTPUT_REPORT) && hasReport(collections, "inputReports", AM35_INPUT_REPORT)); + } + + protected static family: Am35Product["family"] = "am35"; + + protected get model(): AngryMiaoModel { + return ANGRY_MIAO_INFINITY_97_MODEL; + } + + /** The key id a button's slot goes out as. */ + protected wireKey(slot: number): number { + return slot; + } + + // ── RACE I/O ────────────────────────────────────────────────────────────── + + /** Feature report 0x14 is the vendor app's default; output 0x06 with input 0x07 its fallback. */ + private get useFeature(): boolean { + return typeof this.device.sendFeatureReport === "function" + && hasReport(this.device.collections ?? [], "featureReports", AM35_FEATURE_REPORT); + } + + private get reportSize(): number { + const declared = this.useFeature + ? reportBytes(this.device.collections ?? [], "featureReports", AM35_FEATURE_REPORT) + : reportBytes(this.device.collections ?? [], "outputReports", AM35_OUTPUT_REPORT); + return Math.max(declared ?? 0, AM35_REPORT_SIZE); + } + + /** One command and, unless told otherwise, its reply payload. */ + private send(command: number, payload: readonly number[] = [], options: SendOptions = {}): Promise { + const { brand, model } = this.model; + if (!this.writable && SETTING_WRITES.has(command)) { + return Promise.reject(new Error(`OpenMouse only reads the ${brand} ${model} until an owner confirms it with Hardware test.`)); + } + // Through the receiver, device 0 is the receiver itself: a mouse command there would change or read the wrong device. + if (this.isReceiver && options.device === undefined && this.remoteDevice === null) { + return Promise.reject(new Error(`The ${brand} ${model} is not linked through the receiver; read its status first.`)); + } + const frame = am35Frame(command, payload); + const deviceId = options.device ?? this.remoteDevice ?? AM35_LOCAL_DEVICE; + const remote = deviceId >= AM35_REMOTE_DEVICE || (this.isReceiver && options.device === undefined); + return this.enqueue(async () => { + await this.open(); + const replyNow = options.reply === false ? null : this.useFeature ? null : this.waitForInput(command, remote); + const reports = am35Reports(deviceId, frame, this.reportSize); + try { + for (const [i, report] of reports.entries()) { + if (i > 0) await delay(1); + if (this.useFeature) await this.device.sendFeatureReport(AM35_FEATURE_REPORT, report); + else await this.device.sendReport(AM35_OUTPUT_REPORT, report); + } + } catch (error) { + replyNow?.catch(() => undefined); + throw error; + } + if (options.reply === false) return []; + const reply = replyNow ? await replyNow : await this.pollFeature(command, remote); + if (options.status !== false && reply.payload[0] !== 0) { + throw new Error(`The mouse refused RACE command 0x${command.toString(16)} (status ${reply.payload[0] ?? "none"}).`); + } + return reply.payload; + }); + } + + /** The vendor app's read loop: poll report 0x14, joining a frame that spans several reports. */ + private async pollFeature(command: number, remote: boolean): Promise { + const budget = remote ? REMOTE_REPLY_TIMEOUT_MS : REPLY_TIMEOUT_MS; + const attempts = Math.max(remote ? 48 : 8, Math.ceil(budget / EMPTY_READ_DELAY_MS) + 2); + const start = performance.now(); + let partial: number[] = []; + for (let attempt = 0; attempt < attempts && performance.now() - start < budget; attempt++) { + let data: DataView; + try { + data = await this.device.receiveFeatureReport(AM35_FEATURE_REPORT); + } catch (error) { + if (!this.device.opened || !/Failed to (?:receive|read) (?:the |a )?feature report/i.test(String(error))) throw error; + await delay(EMPTY_READ_DELAY_MS); + continue; + } + const chunk = am35ReportChunk(AM35_FEATURE_REPORT, new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); + // Only a declared length of 0 is an empty read; a zero-filled continuation is frame data. + if (chunk.length === 0) { + await delay(EMPTY_READ_DELAY_MS); + continue; + } + const frames = am35ParseFrames(chunk); + const match = frames.find((f) => f.command === command && !am35IsVersionAck(f)); + if (match) return match; + if (partial.length > 0 || chunk[0] === 0x05 || chunk[0] === 0x15) { + partial.push(...chunk); + const joined = am35ParseFrame(partial); + if (joined) { + partial = []; + if (joined.command === command && !am35IsVersionAck(joined)) return joined; + } + } + await delay(partial.length > 0 || frames.length > 0 ? 1 : BUSY_READ_DELAY_MS); + } + throw new Error(`The mouse did not answer RACE command 0x${command.toString(16)}.`); + } + + /** Output 0x06 replies come back as input report 0x07; a long one, such as the DPI table, spans several. */ + private waitForInput(command: number, remote: boolean): Promise { + return new Promise((resolve, reject) => { + let partial: number[] = []; + const cleanup = () => { + clearTimeout(timer); + this.device.removeEventListener("inputreport", onReport); + }; + const done = (reply: Am35Reply) => { + cleanup(); + resolve(reply); + }; + const onReport = (event: HIDInputReportEvent) => { + if (event.reportId !== AM35_INPUT_REPORT) return; + const chunk = am35ReportChunk(AM35_INPUT_REPORT, new Uint8Array(event.data.buffer, event.data.byteOffset, event.data.byteLength)); + const match = am35ParseFrames(chunk).find((f) => f.command === command && !am35IsVersionAck(f)); + if (match) return done(match); + if (partial.length === 0 && chunk[0] !== 0x05 && chunk[0] !== 0x15) return; + partial.push(...chunk); + const joined = am35ParseFrame(partial); + if (!joined) return; + partial = []; + if (joined.command === command && !am35IsVersionAck(joined)) done(joined); + }; + const timer = setTimeout(() => { + cleanup(); + reject(new Error(`The mouse did not answer RACE command 0x${command.toString(16)}.`)); + }, remote ? REMOTE_REPLY_TIMEOUT_MS : REPLY_TIMEOUT_MS); + this.device.addEventListener("inputreport", onReport); + }); + } + + /** + * Through the receiver on report 0x14, the vendor app asks for its mode and link type and lists its devices; + * any device there means the mouse answers on 0x80. Without report 0x14 it skips this and talks to device 0. + * False when the receiver holds no mouse. + */ + private async connectReceiver(): Promise { + if (!this.isReceiver || this.remoteDevice !== null) return true; + if (!this.useFeature) { + this.remoteDevice = AM35_LOCAL_DEVICE; + return true; + } + const local = { device: AM35_LOCAL_DEVICE }; + await this.send(AM35_CMD.GET_DONGLE_MODE, AM35_DONGLE_MODE_QUERY, local); + await this.send(AM35_CMD.SET_DONGLE_LINK_TYPE, AM35_DONGLE_LINK_TYPE, local); + const listed = am35DecodeDeviceList(await this.send(AM35_CMD.GET_DONGLE_DEVICE_LIST, [], local)); + const paired = am35DecodeDeviceList(await this.send(AM35_CMD.GET_DONGLE_PAIRED_LIST, [], local)); + if (![...listed, ...paired].some((d) => d.deviceId > 0)) return false; + this.remoteDevice = AM35_REMOTE_DEVICE; + return true; + } + + /** Sets, then reads back and compares. */ + private async write( + what: string, + set: () => Promise, + read: () => Promise, + expected: T, + same: (a: T, b: T) => boolean = (a, b) => a === b, + ): Promise { + await set(); + const kept = await read(); + if (!same(kept, expected)) { + throw new Error(`The mouse did not keep the change: ${what} reads ${JSON.stringify(kept)}, not ${JSON.stringify(expected)}.`); + } + } + + // ── Reads ───────────────────────────────────────────────────────────────── + + private async readRate(): Promise { + return am35DecodeReportRate(await this.send(AM35_CMD.GET_REPORT_RATE)); + } + + private async readDebounce() { + return am35DecodeDebounce(await this.send(AM35_CMD.GET_SW_DEBOUNCE)); + } + + private async readFlag(command: number): Promise { + return am35DecodeFlag(await this.send(command)); + } + + private async readSleep() { + return am35DecodeSleep(await this.send(AM35_CMD.GET_SLEEP_TIME, [], { status: false })); + } + + private async readBlastMode(): Promise { + return am35DecodeFpsMode(await this.send(AM35_CMD.GET_FPS_MODE, [], { status: false })); + } + + async getDpi(): Promise { + const table = am35DecodeDpi(await this.send(AM35_CMD.GET_DPI)); + if (table.count === 0) throw new Error(`The ${this.model.brand} ${this.model.model} reported no DPI stages.`); + return table; + } + + private async readNv(address: number): Promise { + return am35DecodeNvData(await this.send(AM35_CMD.READ_NV_DATA, am35EncodeNvRead(address)), address); + } + + private async readMouseLight() { + const data = await this.readNv(AM35_NV_LIGHT_SETTINGS); + const light = data && am35DecodeMouseLight(data); + if (!light) throw new Error("The mouse light settings could not be read."); + return light; + } + + private async readReceiverLight(): Promise { + const light = am35DecodeReceiverLight(await this.send(AM35_CMD.GET_DONGLE_LIGHT, [], { device: AM35_LOCAL_DEVICE, status: false })); + if (!light) throw new Error("The receiver light could not be read."); + return light; + } + + /** The connected device's own firmware: the mouse on the cable, the receiver through it. Three tries, as the vendor app does. */ + private async readVersion(): Promise { + for (let attempt = 0; attempt < 3; attempt++) { + if (attempt > 0) await delay(80); + try { + const version = am35DecodeVersion(await this.send(AM35_CMD.GET_VERSION, [0], { device: AM35_LOCAL_DEVICE, status: false })); + if (version) return version; + } catch { /* Optional: tried again. */ } + } + return null; + } + + private async readButton(slot: number): Promise { + const reply = am35DecodeButtonAction(await this.send(AM35_CMD.GET_KEY_REMAP, [this.wireKey(slot)])); + if (!reply || reply.keyId !== this.wireKey(slot)) throw new Error(`Button ${slot} answered for another key.`); + return reply.action; + } + + protected async readButtonMappings(): Promise> { + const mappings: Record = {}; + for (const { name, slot } of this.model.buttons) mappings[name] = await this.readButton(slot); + return mappings; + } + + // ── Writes ──────────────────────────────────────────────────────────────── + + /** One command per setting, in the vendor app's order; each is read back. */ + protected async applySettings(change: AngryMiaoSettingsChange): Promise { + if (change.reportRateHz !== undefined || change.debounceGear !== undefined) { + const rate = await this.readRate(); + const current = await this.readDebounce(); + const newRate = change.reportRateHz ?? rate; + const gear = change.debounceGear ?? angryMiaoDebounceGear(rate, current.usb); + if (change.reportRateHz !== undefined) { + await this.write("the report rate", () => this.send(AM35_CMD.SET_REPORT_RATE, am35EncodeReportRate(newRate)), () => this.readRate(), newRate); + } + // Raw debounce is per rate, so a rate change rewrites it for the same step. + const raw = angryMiaoDebounceRaw(newRate, gear); + await this.write("debounce", () => this.send(AM35_CMD.SET_SW_DEBOUNCE, am35EncodeDebounce(raw)), () => this.readDebounce(), raw, + (a, b) => a.usb === b.usb && a.rf === b.rf && a.bt === b.bt); + } + if (change.liftOff !== undefined) { + await this.write("lift-off", () => this.send(AM35_CMD.SET_LOD, am35EncodeLiftOff(change.liftOff!)), + async () => am35DecodeLiftOff(await this.send(AM35_CMD.GET_LOD)), change.liftOff); + } + const flags: Array<[boolean | undefined, number, number, string]> = [ + [change.motionSync, AM35_CMD.SET_MOTION_SYNC, AM35_CMD.GET_MOTION_SYNC, "motion sync"], + [change.angleSnapping, AM35_CMD.SET_ANGLE_SNAPPING, AM35_CMD.GET_ANGLE_SNAPPING, "angle snapping"], + [change.rippleControl, AM35_CMD.SET_RIPPLE_CONTROL, AM35_CMD.GET_RIPPLE_CONTROL, "ripple control"], + ]; + for (const [value, set, get, what] of flags) { + if (value !== undefined) await this.write(what, () => this.send(set, [value ? 1 : 0]), () => this.readFlag(get), value); + } + if (change.sleepSeconds !== undefined) { + // OpenMouse shows one timer: the 2.4 GHz one, as on the .100. Bluetooth keeps its own. + const { secondsBt } = await this.readSleep(); + const seconds = change.sleepSeconds; + await this.write("the sleep timer", () => this.send(AM35_CMD.SET_SLEEP_TIME, am35EncodeSleep(seconds, secondsBt)), + async () => (await this.readSleep()).seconds24g, seconds); + } + } + + protected async writeBlastMode(enabled: boolean): Promise { + await this.write("Blast Mode", () => this.send(AM35_CMD.SET_FPS_MODE, [enabled ? 1 : 0]), () => this.readBlastMode(), enabled); + return enabled; + } + + /** The vendor app re-selects the active stage after editing it. */ + protected async writeDpiStage(x: number, y: number, index: number): Promise { + const { count, activeIndex } = await this.getDpi(); + const target = index >= 0 && index < count ? index : activeIndex; + await this.send(AM35_CMD.SET_DPI, am35EncodeDpiStage(target, x, y)); + if (target === activeIndex) await this.send(AM35_CMD.SET_CURRENT_DPI_STAGE, [target]); + const kept = (await this.getDpi()).stages[target]; + if (kept?.x !== x || kept?.y !== y) { + throw new Error(`The mouse did not keep the change: stage ${target + 1} reads ${kept?.x}x${kept?.y}, not ${x}x${y}.`); + } + } + + protected async writeActiveDpiStage(index: number): Promise { + const { count } = await this.getDpi(); + const target = Math.max(0, Math.min(index, count - 1)); + await this.write("the active DPI stage", () => this.send(AM35_CMD.SET_CURRENT_DPI_STAGE, [target]), + async () => (await this.getDpi()).activeIndex, target); + return target; + } + + /** As the vendor app does: set the count, then re-select the active stage, kept within the new count. */ + protected async writeDpiStageCount(count: number): Promise { + const { activeIndex } = await this.getDpi(); + await this.send(AM35_CMD.SET_DPI_LOOP_RANGE, [count]); + await this.send(AM35_CMD.SET_CURRENT_DPI_STAGE, [Math.min(activeIndex, count - 1)]); + const kept = (await this.getDpi()).count; + if (kept !== count) throw new Error(`The mouse did not keep the change: it reports ${kept} DPI stages, not ${count}.`); + return count; + } + + /** Left stays Left Click, as on the .100. */ + protected async writeButtonMapping(button: string, action: string): Promise { + const target = this.model.buttons.find((b) => b.name === button); + if (!target) throw new Error(`Unknown button "${button}".`); + const label = button === "Left" ? "Left Click" : action; + const command = am35EncodeButtonAction(this.wireKey(target.slot), label); + if (!command) throw new Error(`Unsupported button action "${action}".`); + await this.write(`button ${button}`, () => this.send(AM35_CMD.SET_KEY_REMAP, command), () => this.readButton(target.slot), label); + } + + setLighting(lighting: AngryMiaoLightingChange): Promise { + return this.exclusive(() => (lighting.zone === "Receiver" ? this.writeReceiverLight(lighting) : this.writeMouseLight(lighting))); + } + + /** + * On and off only. A new effect, speed or colour makes the vendor app rewrite a stored light pattern, + * which this driver does not send. + */ + private async writeMouseLight(lighting: AngryMiaoLightingChange): Promise { + const current = await this.readMouseLight(); + const enabled = lighting.mode !== "Off"; + if (enabled && lighting.mode !== MOUSE_EFFECT_MODE[current.effect]) { + throw new Error("OpenMouse can only turn this light on or off; change its effect in the Angry Miao app."); + } + // The vendor app skips this reply on report 0x14 only. + await this.write("the mouse light", () => this.send(AM35_CMD.SET_LIGHT_SETTINGS, am35EncodeMouseLight({ ...current, enabled }), { reply: !this.useFeature }), + async () => (await this.readMouseLight()).enabled, enabled); + return this.mouseLighting({ ...current, enabled }, await this.readMouseColor()); + } + + private async writeReceiverLight(lighting: AngryMiaoLightingChange): Promise { + if (!this.isReceiver) throw new Error("The receiver light needs the 2.4 GHz receiver."); + const current = await this.readReceiverLight(); + const enabled = lighting.mode !== "Off"; + const effect = lighting.mode === "Breathing single" ? 2 : lighting.mode === "Static" ? 1 : current.effect; + if (enabled && !RECEIVER_MODES.includes(lighting.mode!)) throw new Error(`Unsupported receiver light effect: ${lighting.mode}.`); + const hue = lighting.color ? am35HueFromColor(lighting.color) : current.hues[0]; + const next: Am35ReceiverLight = { ...current, enabled, effect, hues: [hue, current.hues[1], current.hues[2]] }; + // Sent to the receiver itself, without a reply, as the vendor app does. + await this.write("the receiver light", () => this.send(AM35_CMD.SET_DONGLE_LIGHT, am35EncodeReceiverLight(next), { device: AM35_LOCAL_DEVICE, reply: false }), + () => this.readReceiverLight(), next, (a, b) => a.enabled === b.enabled && a.effect === b.effect && a.hues[0] === b.hues[0]); + return this.receiverLighting(next); + } + + // ── Status ──────────────────────────────────────────────────────────────── + + private async readMouseColor(): Promise { + try { + const data = await this.readNv(AM35_NV_LIGHT_COLOR); + return data && am35DecodeStoredColor(data); + } catch { + return null; + } + } + + private mouseLighting(light: { enabled: boolean; effect: Am35MouseEffect }, color: string | null): MouseLighting { + const effect = MOUSE_EFFECT_MODE[light.effect]; + return { + zone: "Mouse", + modes: ["Off", effect], + mode: light.enabled ? effect : "Off", + color, + color2: null, + colorModes: [], + dualColorModes: [], + reactiveModes: [], + speeds: [], + speed: null, + }; + } + + private receiverLighting(light: Am35ReceiverLight): MouseLighting { + const effect = light.effect === 1 ? "Static" : light.effect === 2 ? "Breathing single" : null; + return { + zone: "Receiver", + modes: ["Off", ...RECEIVER_MODES], + mode: light.enabled ? effect : "Off", + color: am35ColorFromHue(light.hues[0]), + color2: null, + colorModes: [...RECEIVER_MODES], + dualColorModes: [], + reactiveModes: [], + speeds: [], + speed: null, + }; + } + + /** DPI colours come with the table when the mouse sends them, else from stored data. */ + private async stageColors(table: Am35DpiTable): Promise { + const colors: string[] = []; + for (let i = 0; i < table.count; i++) { + const color = table.stages[i]?.color ?? await this.readNv(AM35_NV_DPI_COLOR + i).then((d) => d && am35DecodeStoredColor(d), () => null); + if (!color) return null; + colors.push(color); + } + return colors; + } + + async readStatus(): Promise { + const status = await this.exclusive(() => this.readStatusNow()); + return this.writable ? status : readOnlyStatus(status); + } + + private async readStatusNow(): Promise { + await this.open(); + const optional = async (read: () => Promise): Promise => { + try { return await read(); } catch { return null; } + }; + let dpi: Am35DpiTable; + if (this.isReceiver) { + // The mouse may be asleep, off or on another link; the receiver still answers for itself. + const linked = await optional(() => this.connectReceiver()); + const table = linked ? await optional(() => this.getDpi()) : null; + if (!table) { + this.remoteDevice = null; + return this.receiverOnlyStatus(); + } + dpi = table; + } else { + // The DPI read has to work: it proves the transport. + dpi = await this.getDpi(); + } + const battery = await optional(async () => am35DecodeBattery(await this.send(AM35_CMD.GET_BATTERY))); + const rate = await optional(() => this.readRate()); + const debounce = await optional(() => this.readDebounce()); + const liftOff = await optional(async () => am35DecodeLiftOff(await this.send(AM35_CMD.GET_LOD))); + const motionSync = await optional(() => this.readFlag(AM35_CMD.GET_MOTION_SYNC)); + const angleSnapping = await optional(() => this.readFlag(AM35_CMD.GET_ANGLE_SNAPPING)); + const rippleControl = await optional(() => this.readFlag(AM35_CMD.GET_RIPPLE_CONTROL)); + const sleep = await optional(() => this.readSleep()); + const blastMode = await optional(() => this.readBlastMode()); + const mouseLight = await optional(() => this.readMouseLight()); + const mouseColor = mouseLight ? await this.readMouseColor() : null; + const colors = await this.stageColors(dpi); + const buttonMappings = await optional(() => this.readButtonMappings()); + const receiverLight = this.isReceiver ? await optional(() => this.readReceiverLight()) : null; + const version = await this.readVersion(); + + const model = this.model; + const name = `${model.brand} ${model.model}`; + const active = dpi.stages[Math.min(dpi.activeIndex, dpi.count - 1)] ?? dpi.stages[0]; + const lighting = mouseLight ? this.mouseLighting(mouseLight, mouseColor) : undefined; + const receiverLighting = receiverLight ? this.receiverLighting(receiverLight) : undefined; + return { + brand: model.brand, + name, + ui: { + family: "angry-miao", + settingsReady: true, + defaultDisplayName: name, + hideAdvancedLighting: true, + separateLightingZones: true, + dpiStageEditor: { + maxStages: model.maxDpiStages, + minDpi: model.minDpi, + maxDpi: model.maxDpi, + stepDpi: model.dpiStep, + countEditable: true, + }, + statusNote: "OpenMouse follows the Angry Miao app for this mouse but has not been tested on one yet. If a setting misbehaves, run Hardware test and share the log.", + }, + dpi: active?.x ?? 0, + dpiY: active?.y ?? 0, + supportsSeparateDpiAxes: true, + dpiStages: dpi.stages.slice(0, dpi.count).map((stage) => stage.x), + ...(colors ? { dpiStageColors: colors } : {}), + activeDpiStage: Math.min(dpi.activeIndex, dpi.count - 1), + pollingRateHz: rate || 1000, + supportedPollingRates: this.supportedPollingRates, + connectionType: this.isReceiver ? "Wireless" : "Wired", + connectionDetail: this.isReceiver ? "2.4 GHz" : "USB", + liftOffDistance: liftOff, + angleSnapping, + debounceMs: debounce ? ANGRY_MIAO_DEBOUNCE_GEARS_MS[angryMiaoDebounceGear(rate || 1000, debounce.usb)] : null, + rippleControl, + ...(motionSync !== null ? { motionSync } : {}), + sleepTimeout: sleep ? sleep.seconds24g : null, + activeProfile: null, + firmware: version ? [`${this.isReceiver ? "Receiver" : "Mouse"} firmware ${version}`] : [], + batteryPercent: battery?.percent ?? null, + batteryState: battery?.percent == null ? "Unknown" : battery.charging ? "Charging" : "Discharging", + ...(lighting ? { lighting } : {}), + ...(receiverLighting ? { lightingZones: [...(lighting ? [lighting] : []), receiverLighting] } : {}), + ...(blastMode !== null ? { turboMode: blastMode } : {}), + ...(buttonMappings ? { + buttonMappings, + buttonOptions: this.getButtonOptions(), + defaultButtonMappings: { ...model.defaultButtonMappings }, + fixedButtons: ["Left"], + } : {}), + }; + } + + /** The receiver answers on its own while the mouse sleeps, is off, or is on another link. */ + private async receiverOnlyStatus(): Promise { + let receiverLight: Am35ReceiverLight | null = null; + try { receiverLight = await this.readReceiverLight(); } catch { /* Optional: the zone stays hidden. */ } + const version = await this.readVersion(); + const name = `${this.model.brand} Receiver`; + return { + brand: this.model.brand, + name, + ui: { + family: "angry-miao", + settingsReady: false, + receiverOnly: true, + defaultDisplayName: name, + hideAdvancedLighting: true, + separateLightingZones: true, + statusNote: "The receiver is connected, but the mouse is not answering. Wake it, or switch it to 2.4 GHz.", + }, + batteryPercent: null, + batteryState: "Unknown", + dpi: 0, + pollingRateHz: 0, + activeProfile: null, + liftOffDistance: null, + connectionType: "Wireless", + connectionDetail: "2.4 GHz", + firmware: version ? [`Receiver firmware ${version}`] : [], + ...(receiverLight ? { lightingZones: [this.receiverLighting(receiverLight)] } : {}), + }; + } +} + +/** Angry Miao Infinity .100R2: the .97's protocol with buttons numbered 0xF0-0xF6, as the vendor app sends them. */ +export class AngryMiaoAm30R2HidClient extends AngryMiaoAm35HidClient { + protected static family: Am35Product["family"] = "am30r2"; + + protected get model(): AngryMiaoModel { + return ANGRY_MIAO_INFINITY_100R2_MODEL; + } + + protected wireKey(slot: number): number { + return slot + AM30R2_KEY_OFFSET; + } +} diff --git a/src/drivers/angry-miao/base.ts b/src/drivers/angry-miao/base.ts new file mode 100644 index 00000000..62d3a2dc --- /dev/null +++ b/src/drivers/angry-miao/base.ts @@ -0,0 +1,224 @@ +import type { MouseLighting, MouseStatus } from "../mouse-types.ts"; +import { + ANGRY_MIAO_BUTTON_ACTION_LABELS, + ANGRY_MIAO_DEBOUNCE_GEARS_MS, + ANGRY_MIAO_LIFT_OFF_LEVELS, + ANGRY_MIAO_RATES, + ANGRY_MIAO_SLEEP_OPTIONS, + type AngryMiaoLiftOff, + type AngryMiaoModel, +} from "@openmouse/protocol/angry-miao"; + +/** A change to the settings every Angry Miao mouse stores. Absent fields stay as the mouse has them. */ +export interface AngryMiaoSettingsChange { + /** When only the rate changes, the mouse keeps its debounce step, as the vendor app does. */ + reportRateHz?: number; + debounceGear?: number; + liftOff?: AngryMiaoLiftOff; + angleSnapping?: boolean; + rippleControl?: boolean; + motionSync?: boolean; + /** Seconds on the current link's timer; 0 = never. */ + sleepSeconds?: number; +} + +export type AngryMiaoLightingChange = + Pick & Partial>; + +/** + * What every Angry Miao client does the same way, whatever its wire protocol: + * the settings OpenMouse offers, their validation, and one change at a time. + * Each protocol subclass reads and writes the mouse through the hooks below. + */ +export abstract class AngryMiaoHidClient { + device: HIDDevice; + + /** Reports go out one at a time. */ + private queue: Promise = Promise.resolve(); + /** Setting changes and status reads, one whole step at a time (see `exclusive`). */ + private settingsQueue: Promise = Promise.resolve(); + + constructor(device: HIDDevice) { + this.device = device; + } + + /** The connected model; drives the option lists and validation. */ + protected abstract get model(): AngryMiaoModel; + + abstract readStatus(): Promise; + abstract setLighting(lighting: AngryMiaoLightingChange): Promise; + + /** Writes the change and reads it back; throws when the mouse does not keep it. Called inside `exclusive`. */ + protected abstract applySettings(change: AngryMiaoSettingsChange): Promise; + protected abstract writeBlastMode(enabled: boolean): Promise; + /** An out-of-range `index` means the active stage. */ + protected abstract writeDpiStage(x: number, y: number, index: number): Promise; + /** Returns the stage the mouse ends on. */ + protected abstract writeActiveDpiStage(index: number): Promise; + protected abstract writeDpiStageCount(count: number): Promise; + protected abstract writeButtonMapping(button: string, action: string): Promise; + protected abstract readButtonMappings(): Promise>; + + get supportedPollingRates(): number[] { + return ANGRY_MIAO_RATES.filter((hz) => hz <= this.model.maxPollingHz); + } + + /** Every writable DPI step; the app validates typed stage values against it. */ + getDpiOptions(): number[] { + const { minDpi, maxDpi, dpiStep } = this.model; + return Array.from({ length: Math.floor((maxDpi - minDpi) / dpiStep) + 1 }, (_, i) => minDpi + i * dpiStep); + } + + async open(): Promise { + if (!this.device.opened) await this.device.open(); + } + + async close(): Promise { + if (this.device.opened) await this.device.close(); + } + + protected enqueue(task: () => Promise): Promise { + const run = this.queue.then(task, task); + this.queue = run.catch(() => undefined); + return run; + } + + /** + * Runs a whole setting change or status read before the next one starts, as the 8BitDo driver does. + * Reads, edits and writes inside it still go through `enqueue` one report at a time. Nothing else can + * change the device id or the profile mid-step, so a step checks them once, at its start. + */ + protected exclusive(operation: () => Promise): Promise { + const run = this.settingsQueue.then(operation, operation); + this.settingsQueue = run.catch(() => undefined); + return run; + } + + // ── Settings ────────────────────────────────────────────────────────────── + + async setReportRate(hz: number): Promise { + if (!this.supportedPollingRates.includes(hz)) { + throw new Error(`Unsupported rate ${hz} Hz. Supported: ${this.supportedPollingRates.join(", ")}`); + } + await this.exclusive(() => this.applySettings({ reportRateHz: hz })); + return hz; + } + + async setPollingRate(rate: number): Promise { + return this.setReportRate(rate); + } + + async setLiftOffDistance(level: AngryMiaoLiftOff): Promise { + if (!ANGRY_MIAO_LIFT_OFF_LEVELS.includes(level)) throw new Error(`Lift-off level "${level}" is not available on this model.`); + await this.exclusive(() => this.applySettings({ liftOff: level })); + return level; + } + + async setAngleSnapping(enabled: boolean): Promise { + await this.exclusive(() => this.applySettings({ angleSnapping: enabled })); + return enabled; + } + + getDebounceMaxMs(): number { + return Math.max(...ANGRY_MIAO_DEBOUNCE_GEARS_MS); + } + + getDebounceOptions(): number[] { + return [...ANGRY_MIAO_DEBOUNCE_GEARS_MS].sort((a, b) => a - b); + } + + /** One slider sets every link, as in the vendor app. */ + async setDebounceTime(ms: number): Promise { + const distance = ANGRY_MIAO_DEBOUNCE_GEARS_MS.map((label) => Math.abs(label - ms)); + const gear = distance.indexOf(Math.min(...distance)); + await this.exclusive(() => this.applySettings({ debounceGear: gear })); + return ANGRY_MIAO_DEBOUNCE_GEARS_MS[gear]; + } + + getSleepOptions(): number[] { + return [...ANGRY_MIAO_SLEEP_OPTIONS]; + } + + async setSleepTimeout(seconds: number): Promise { + const s = Math.max(0, Math.min(0xffff, Math.round(seconds))); + await this.exclusive(() => this.applySettings({ sleepSeconds: s })); + return s; + } + + async setRippleControl(enabled: boolean): Promise { + await this.exclusive(() => this.applySettings({ rippleControl: enabled })); + return enabled; + } + + async setMotionSync(enabled: boolean): Promise { + await this.exclusive(() => this.applySettings({ motionSync: enabled })); + return enabled; + } + + /** Angry Miao's "Blast Mode". */ + setTurboMode(enabled: boolean): Promise { + return this.exclusive(() => this.writeBlastMode(enabled)); + } + + // ── DPI ─────────────────────────────────────────────────────────────────── + + setDpiForStage(x: number, y: number, index: number): Promise { + return this.exclusive(() => this.writeStageDpi(x, y, index)); + } + + /** The stage editor's shared entry point; one value sets both axes. */ + setDpiStageValue(stage: number, dpi: number): Promise { + return this.exclusive(() => this.writeStageDpi(dpi, dpi, stage)); + } + + async setDpi(dpi: number, dpiY = dpi): Promise { + await this.exclusive(() => this.writeStageDpi(dpi, dpiY, -1)); + return dpi; + } + + setActiveDpiStage(index: number): Promise { + return this.exclusive(() => this.writeActiveDpiStage(index)); + } + + /** The DPI button cycles through the first `count` stages. */ + setDpiStageCount(count: number): Promise { + return this.exclusive(async () => { + const { brand, model, maxDpiStages } = this.model; + if (!Number.isInteger(count) || count < 1 || count > maxDpiStages) { + throw new Error(`The ${brand} ${model} holds 1 to ${maxDpiStages} DPI stages.`); + } + return this.writeDpiStageCount(count); + }); + } + + private async writeStageDpi(x: number, y: number, index: number): Promise { + const { minDpi, maxDpi, dpiStep } = this.model; + if (![x, y].every((v) => Number.isInteger(v) && v >= minDpi && v <= maxDpi && (v - minDpi) % dpiStep === 0)) { + throw new Error(`DPI must be ${minDpi}..${maxDpi} in ${dpiStep} DPI steps.`); + } + await this.writeDpiStage(x, y, index); + return x; + } + + // ── Buttons ─────────────────────────────────────────────────────────────── + + getButtonOptions(): string[] { + return [...ANGRY_MIAO_BUTTON_ACTION_LABELS]; + } + + /** The vendor app keeps a primary click on Left. */ + setButtonMapping(button: string, action: string): Promise { + return this.exclusive(() => this.writeButtonMapping(button, action)); + } + + /** Rewrites each button that differs from its factory action, as the vendor's restore does. */ + resetButtonMappings(): Promise { + return this.exclusive(async () => { + const current = await this.readButtonMappings(); + for (const { name } of this.model.buttons) { + const action = this.model.defaultButtonMappings[name]; + if (action !== undefined && current[name] !== action) await this.writeButtonMapping(name, action); + } + }); + } +} diff --git a/src/drivers/angry-miao/hid.ts b/src/drivers/angry-miao/hid.ts index 0e09b713..9170653d 100644 --- a/src/drivers/angry-miao/hid.ts +++ b/src/drivers/angry-miao/hid.ts @@ -1,1010 +1,2 @@ -import type { MouseLighting, MouseLightingMode, MouseStatus } from "../mouse-types.ts"; -import { - AM30_BUTTON_ACTIONS, - AM30_CMD, - AM30_DPI_RGB_OFFSET, - AM30_DPI_X_OFFSET, - AM30_DPI_Y_OFFSET, - AM30_LIFT_OFF_LEVELS, - AM30_MAX_DPI_STAGES, - AM30_OPT0_ANGLE_SNAP, - AM30_OPT0_DEBOUNCE, - AM30_OPT0_FLAGS, - AM30_OPT0_LIFT_OFF, - AM30_OPT0_REPORT_RATE, - AM30_OPT0_SLEEP_24G, - AM30_RATE_DECODE, - AM30_RATE_ENCODE, - AM30_RATES, - AM30_RELAY, - AM30_RELAY_ATTEMPTS, - AM30_RELAY_LENGTH, - AM30_REPORT_ID, - AM30_REPORT_SIZE, - AM30_TARGET_MOUSE, - AM30_TARGET_NONE, - AM30_BT_BATTERY, - AM30_BT_ENVELOPE, - AM30_BT_REPORT_ID, - AM30_BT_REPORT_SIZE, - AM30_BT_SLEEPING, - AM30_OPT0_SLEEP_BT, - am30BluetoothPacket, - ANGRY_MIAO_PRODUCT_NAME, - am30EncodeCommand, - ANGRY_MIAO_VENDOR_ID, - type Am30LiftOff, - type AngryMiaoProfile, - type AngryMiaoTransport, - AM30_DEBOUNCE_GEARS_MS, - AM30_DEFAULT_BUTTON_MAPPINGS, - AM30_GET_BATTERY, - AM30_GET_BLAST_MODE, - AM30_GET_PROFILE, - AM30_GET_USB_VERSION, - AM30_OPT0_DEBOUNCE_24G, - AM30_OPT0_DEBOUNCE_BT, - AM30_OPT0_FLAG_RIPPLE, - AM30_OPT0_LIGHT, - AM30_OPT0_LIGHT_COLOR, - AM30_OPT0_LIGHT_COLOR_2, - AM30_OPT0_MOTION_SYNC, - AM30_PROFILE_COUNT, - AM30_RECEIVER_BRIGHTNESS, - AM30_RECEIVER_GET_LED_VERSION, - AM30_RECEIVER_GET_LIGHT, - AM30_RECEIVER_GET_LIGHT_SWITCH, - AM30_RECEIVER_GET_RF_VERSION, - AM30_RECEIVER_GET_USB_VERSION, - AM30_RECEIVER_SET_LIGHT_SWITCH, - AM30_RECEIVER_SPEEDS, - AM30_SET_BLAST_MODE, - AM30_SET_PROFILE, - AM30_SLEEP_NEVER, - AM30_SLEEP_OPTIONS, - AM30_STATUS_MOUSE_OFFLINE, - am30DebounceGear, - am30DebounceRaw, - am30DecodeBattery, - am30DecodeButtonAction, - am30DecodeReceiverLight, - am30DecodeSpareBattery, - am30EncodeButtonAction, - am30EncodeReceiverLight, - am30FirmwareLabels, - am30ReceiverFirmwareLabels, - ANGRY_MIAO_INFINITY_PROFILE, - ANGRY_MIAO_PRODUCTS, - ANGRY_MIAO_PROFILES, -} from "@openmouse/protocol/angry-miao"; - -const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); - -interface Am30DpiStage { - x: number; - y: number; - rgb: number; -} - -/** Receiver light effects 1..8 in the vendor's order (always on, breathing, neon, light wave, ...). */ -const RECEIVER_EFFECTS: readonly MouseLightingMode[] = [ - "Static", "Breathing single", "Neon", "Wave", "Marquee", "Ring", "Buffer", "Chase", -]; - -/** - * Angry Miao Infinity .100 (AM30) on the Yichip protocol. This client owns its - * whole stack: feature-report I/O, the receiver relay, the settings layout - * (`@openmouse/protocol/angry-miao`), the battery, motion sync, Blast Mode and - * both lights. Nothing is inherited from the other Yichip brands' driver. - */ -export class AngryMiaoHidClient { - device: HIDDevice; - currentProfile = 0; - - private readonly transportEntry: AngryMiaoTransport | undefined; - /** False until `85` answers, so button mappings never go to a guessed profile. */ - private profileConfirmed = false; - /** The model for the last `8F` device id, or null when it is not one we know. */ - private resolvedProfile: AngryMiaoProfile | null = null; - /** The relay is stateful, so exchanges run one at a time. */ - private queue: Promise = Promise.resolve(); - /** Setting changes and status reads, one whole step at a time (see `exclusive`). */ - private settingsQueue: Promise = Promise.resolve(); - /** Last Blast Mode write; on SoC firmware 1.1.1 `E2` does not reflect it. */ - private blastMode: boolean | null = null; - /** `80` reply from the last status read. */ - private firmwareCode: number | null = null; - /** Receiver version replies, kept once each answers, so a later status read retries only the missing ones. */ - private receiverFirmware: { usb: Uint8Array | null; rf: Uint8Array | null; led: Uint8Array | null } = { - usb: null, rf: null, led: null, - }; - /** `8F` device id from the last status read; writes need a known one. */ - private deviceId: number | null = null; - - constructor(device: HIDDevice) { - this.device = device; - this.transportEntry = ANGRY_MIAO_PRODUCTS.get(device.productId); - } - - static isSupported(device: HIDDevice): boolean { - const entry = ANGRY_MIAO_PRODUCTS.get(device.productId); - if (device.vendorId !== ANGRY_MIAO_VENDOR_ID || !entry) return false; - // Other brands reuse these product ids, so the name has to be Angry Miao's too. - if (!ANGRY_MIAO_PRODUCT_NAME.test(device.productName ?? "")) return false; - const hasControl = (collections: readonly HIDCollectionInfo[]): boolean => - collections.some((c) => (c.usagePage === entry.usagePage && c.usage === entry.usage) || hasControl(c.children ?? [])); - return hasControl(device.collections); - } - - get transport(): "dongle" | "direct" | "bluetooth" { - return this.transportEntry?.transport ?? "direct"; - } - - private get profile(): AngryMiaoProfile { - return this.resolvedProfile ?? ANGRY_MIAO_INFINITY_PROFILE; - } - - get supportedPollingRates(): number[] { - return AM30_RATES.filter((hz) => hz <= this.profile.maxPollingHz); - } - - /** Every writable DPI step; the app validates typed stage values against it. */ - getDpiOptions(): number[] { - const { minDpi, maxDpi, dpiStep } = this.profile; - return Array.from({ length: Math.floor((maxDpi - minDpi) / dpiStep) + 1 }, (_, i) => minDpi + i * dpiStep); - } - - async open(): Promise { - if (!this.device.opened) await this.device.open(); - } - - async close(): Promise { - if (this.device.opened) await this.device.close(); - } - - // ── Feature-report I/O and the receiver relay ───────────────────────────── - - private enqueue(task: () => Promise): Promise { - const run = this.queue.then(task, task); - this.queue = run.catch(() => undefined); - return run; - } - - /** - * Runs a whole setting change or status read before the next one starts, as the 8BitDo driver does. - * Reads, edits and writes inside it still go through `enqueue` one report at a time. Nothing else can - * change the device id or the profile mid-step, so a step checks them once, at its start. - */ - private exclusive(operation: () => Promise): Promise { - const run = this.settingsQueue.then(operation, operation); - this.settingsQueue = run.catch(() => undefined); - return run; - } - - private async rawSend(bytes: readonly number[] | Uint8Array): Promise { - const buf = new Uint8Array(AM30_REPORT_SIZE); - buf.set(bytes instanceof Uint8Array ? bytes.subarray(0, AM30_REPORT_SIZE) : bytes.slice(0, AM30_REPORT_SIZE)); - await this.device.sendFeatureReport(AM30_REPORT_ID, buf); - } - - private async rawRead(): Promise { - const view = await this.device.receiveFeatureReport(AM30_REPORT_ID); - return new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength)); - } - - /** `F7`: byte 0 = 1 when a reply is ready, byte 5 = 1 when the receiver takes a command. */ - private async pollStatus(): Promise { - await this.rawSend([AM30_RELAY.GET_STATUS]); - await delay(10); - return this.rawRead(); - } - - private async waitReady(byte: 0 | 5): Promise { - for (let attempt = 0; attempt < 8; attempt++) { - await delay(100); - if ((await this.pollStatus())[byte] === 1) return true; - } - return false; - } - - /** The vendor app selects the mouse and sends `FE 40` before every relayed command. */ - private async prepareRelay(): Promise { - await this.rawSend([AM30_RELAY.SELECT_TARGET, AM30_TARGET_MOUSE]); - await delay(50); - if (!(await this.waitReady(5))) throw new Error("The 2.4 GHz receiver never became ready to send."); - await this.rawSend([AM30_RELAY.SET_LENGTH, AM30_RELAY_LENGTH]); - await delay(10); - } - - /** A reply of 64 zeros means the command was not answered; most replies echo the command id. */ - private verifyReply(resp: Uint8Array, cmd: number, echoes: boolean): Uint8Array { - const id = `0x${cmd.toString(16)}`; - if (resp.length < AM30_REPORT_SIZE) throw new Error(`Command ${id} returned ${resp.length} bytes, expected ${AM30_REPORT_SIZE}.`); - if (resp.every((byte) => byte === 0)) throw new Error(`Command ${id} was not answered (all-zero response).`); - if (echoes && resp[0] !== cmd) throw new Error(`Command ${id} answered with id 0x${resp[0].toString(16)}.`); - return resp; - } - - /** Retries a relayed exchange, then sends `F6 00` so a failed relay does not leave the receiver stuck. */ - private async relay(exchange: () => Promise): Promise { - let failure: unknown; - for (let attempt = 0; attempt < AM30_RELAY_ATTEMPTS; attempt++) { - if (attempt > 0) await delay(100); - try { - return await exchange(); - } catch (error) { - failure = error; - } - } - await this.rawSend([AM30_RELAY.SELECT_TARGET, AM30_TARGET_NONE]).catch(() => undefined); - throw failure; - } - - /** One mouse command and its reply, relayed on 2.4 GHz. */ - async command(bytes: readonly number[], opts: { echoes?: boolean } = {}): Promise { - // Copied now, so a caller that reuses its array cannot change a command still waiting in the queue. - const request = [...bytes]; - const echoes = opts.echoes ?? true; - return this.enqueue(() => this.exchange(request, echoes)); - } - - /** The body of `command`. Call it only from a task that already holds the queue. */ - private async exchange(bytes: readonly number[], echoes: boolean): Promise { - const encoded = am30EncodeCommand(bytes); - await this.open(); - if (this.transport === "bluetooth") return this.exchangeBluetooth(encoded, bytes[0], echoes); - if (this.transport === "direct") { - await this.rawSend(encoded); - await delay(10); - return this.verifyReply(await this.rawRead(), bytes[0], echoes); - } - return this.relay(async () => { - await this.prepareRelay(); - await this.rawSend(encoded); - if (!(await this.waitReady(0))) throw new Error("The 2.4 GHz receiver never became ready to read."); - await this.rawSend([AM30_RELAY.NOTICE_READ]); - await delay(10); - return this.verifyReply(await this.rawRead(), bytes[0], echoes); - }); - } - - /** Product ids and names are shared, so only a device id we have tested may be written to. */ - private async sendWrite(cmd: Uint8Array): Promise { - this.assertModelVerified(); - return this.enqueue(() => this.transmit(cmd)); - } - - /** The body of `sendWrite`. Call it only from a task that already holds the queue. */ - private async transmit(cmd: Uint8Array): Promise { - const encoded = am30EncodeCommand([...cmd]); - await this.open(); - if (this.transport === "bluetooth") { - await this.device.sendReport(AM30_BT_REPORT_ID, am30BluetoothPacket(encoded)); - await delay(60); - return; - } - if (this.transport === "direct") { - await this.rawSend(encoded); - await delay(10); - return; - } - // A retry only happens before the write is sent: `prepareRelay` is the step that can fail. - await this.relay(() => this.prepareRelay()); - try { - await this.rawSend(encoded); - } catch (error) { - // No retry, because the receiver may already hold the write. Release it so it does not stay on the mouse. - await this.rawSend([AM30_RELAY.SELECT_TARGET, AM30_TARGET_NONE]).catch(() => undefined); - throw error; - } - await delay(50); - } - - private assertModelVerified(): void { - if (!this.modelVerified) { - throw new Error(`Device id ${this.deviceId ?? "unknown"} is not a verified Angry Miao model; settings are read-only.`); - } - } - - private get modelVerified(): boolean { - return this.deviceId !== null && ANGRY_MIAO_PROFILES.has(this.deviceId); - } - - /** Bluetooth replies arrive as input report 6; null from `decode` skips an unrelated report. */ - private requestBluetooth(request: Uint8Array, decode: (packet: Uint8Array) => T | null): Promise { - return new Promise((resolve, reject) => { - const cleanup = () => { - clearTimeout(timer); - this.device.removeEventListener("inputreport", onReport); - }; - const onReport = (event: HIDInputReportEvent) => { - if (event.reportId !== AM30_BT_REPORT_ID) return; - const packet = new Uint8Array(event.data.buffer, event.data.byteOffset, event.data.byteLength); - if (packet.length !== AM30_BT_REPORT_SIZE) return; - try { - const result = decode(packet); - if (result === null) return; - cleanup(); - resolve(result); - } catch (error) { - cleanup(); - reject(error); - } - }; - const timer = setTimeout(() => { - cleanup(); - reject(new Error("The mouse did not answer over Bluetooth. Move it and try again.")); - }, 2000); - this.device.addEventListener("inputreport", onReport); - this.device.sendReport(AM30_BT_REPORT_ID, request).catch((error) => { - cleanup(); - reject(error); - }); - }); - } - - private exchangeBluetooth(encoded: Uint8Array, cmd: number, echoes: boolean): Promise { - return this.requestBluetooth(am30BluetoothPacket(encoded), (packet) => { - if (packet[0] !== AM30_BT_ENVELOPE) return null; - const reply = packet.slice(1); - if (echoes && reply[0] !== cmd) return null; - return this.verifyReply(reply, cmd, echoes); - }); - } - - /** `77`: battery percent in byte 1. The mouse answers `88` while asleep. */ - private bluetoothBattery(): Promise { - return this.enqueue(async () => { - await this.open(); - const request = new Uint8Array(AM30_BT_REPORT_SIZE); - request[0] = AM30_BT_BATTERY; - return this.requestBluetooth(request, (packet) => { - if (packet[0] === AM30_BT_SLEEPING) throw new Error("The mouse is asleep."); - if (packet[0] !== AM30_BT_BATTERY) return null; - if (packet[1] > 100) throw new Error("The mouse returned an invalid battery percentage."); - return packet[1]; - }); - }); - } - - // ── Reads ───────────────────────────────────────────────────────────────── - - /** `8F` bytes 1-4, LE32. */ - async getDeviceId(): Promise { - const resp = await this.command([AM30_CMD.GET_DEVICE_ID]); - return (resp[1] | (resp[2] << 8) | (resp[3] << 16) | (resp[4] << 24)) >>> 0; - } - - async getFirmwareVersion(): Promise { - const resp = await this.command([AM30_CMD.GET_FIRMWARE]); - this.firmwareCode = (resp[2] << 8) | resp[1]; - return this.firmwareCode; - } - - async getOptionParam0(): Promise { - return this.command([AM30_CMD.GET_OPTIONS]); - } - - async getReportRate(): Promise { - const code = (await this.getOptionParam0())[AM30_OPT0_REPORT_RATE]; - const hz = AM30_RATE_DECODE[code]; - if (hz === undefined) throw new Error(`Unknown report-rate code ${code}.`); - return hz; - } - - /** 14 slots x 4 bytes with no echo byte. Read late in a status read, so it retries once. */ - async getKeyMatrix(profile = 0): Promise { - const read = async () => { - const reply = await this.command([AM30_CMD.GET_KEYMATRIX, profile], { echoes: false }); - // A lost relay reply can leave an echoed command buffered; actions never start at 0x80 or above. - if (reply[0] >= 0x80) throw new Error("The mouse returned a stale command instead of button mappings."); - return reply; - }; - try { - return await read(); - } catch { - return await read(); - } - } - - /** - * Read-modify-write of the whole options block; bytes not overridden are written back as read. - * The read and the write run as one exclusive step, so another change cannot land between them. - */ - private patchOptionParam0( - overrides: Record number)>, - ): Promise { - return this.exclusive(() => this.patchOptions(overrides)); - } - - /** The body of `patchOptionParam0`. Call it only from inside `exclusive`. */ - private async patchOptions( - overrides: Record number)>, - ): Promise { - this.assertModelVerified(); - const current = await this.getOptionParam0(); - const block = new Uint8Array(AM30_REPORT_SIZE); - block.set(current.subarray(8, AM30_REPORT_SIZE), 8); - block[0] = AM30_CMD.SET_OPTIONS; - for (const [offset, value] of Object.entries(overrides)) { - const i = Number(offset); - block[i] = (typeof value === "function" ? value(current[i], current) : value) & 0xff; - } - await this.sendWrite(block); - // Read the block back, as the maintainer asked: the mouse reports every byte this setter changed. - const kept = await this.getOptionParam0(); - const lost = Object.keys(overrides).map(Number).find((i) => kept[i] !== block[i]); - if (lost !== undefined) { - throw new Error(`The mouse did not keep the change: options byte ${lost} reads ${kept[lost]}, not ${block[lost]}.`); - } - } - - // ── Settings ────────────────────────────────────────────────────────────── - - private buttonSlots() { - return this.profile.buttons; - } - - /** Active onboard profile, 0-based, or null when `85` is not answered. */ - private async readProfile(): Promise { - const active = (await this.command([AM30_GET_PROFILE]))[1]; - return active < AM30_PROFILE_COUNT ? active : null; - } - - /** 1-based. The vendor app confirms with `85`, then always turns Blast Mode off. */ - setProfile(profile: number): Promise { - return this.exclusive(() => this.switchProfile(profile)); - } - - private async switchProfile(profile: number): Promise { - if (!Number.isInteger(profile) || profile < 1 || profile > AM30_PROFILE_COUNT) { - throw new Error(`The Angry Miao Infinity .100 has onboard profiles 1 to ${AM30_PROFILE_COUNT}.`); - } - // Unknown from here on: the mouse may switch even if the send or every confirmation fails. - this.profileConfirmed = false; - await this.sendWrite(Uint8Array.from([AM30_SET_PROFILE, profile - 1, AM30_PROFILE_COUNT])); - let active: number | null = null; - for (let attempt = 0; attempt < 3 && active !== profile - 1; attempt++) { - if (attempt > 0) await delay(100); - // One unanswered read does not mean the switch failed, so the remaining attempts still run. - try { active = await this.readProfile(); } catch { active = null; } - } - if (active !== profile - 1) { - this.profileConfirmed = active !== null; - if (active !== null) this.currentProfile = active; - throw new Error(active === null - ? `The mouse did not confirm the switch to profile ${profile}. Read the status again.` - : `The mouse stayed on profile ${active + 1}.`); - } - this.currentProfile = active; - this.profileConfirmed = true; - await this.writeBlastMode(false); - return profile; - } - - /** `50` and `D0` name a profile, so the mappings stay read-only until `85` confirms the active one. */ - private confirmedProfile(): number { - if (!this.profileConfirmed) { - throw new Error("The active profile is unknown, so button mappings are read-only. Read the status again."); - } - return this.currentProfile; - } - - getButtonOptions(): string[] { - return AM30_BUTTON_ACTIONS.map(([label]) => label); - } - - /** The vendor app locks Left to Left Click so the mouse always keeps a primary click. */ - setButtonMapping(button: string, action: string): Promise { - return this.exclusive(() => this.writeButton(this.confirmedProfile(), button, action)); - } - - private async writeButton(profile: number, button: string, action: string): Promise { - const target = this.buttonSlots().find((b) => b.name === button); - if (!target) throw new Error(`Unknown button "${button}".`); - const value = am30EncodeButtonAction(button === "Left" ? "Left Click" : action); - if (!value) throw new Error(`Unsupported button action "${action}".`); - const cmd = new Uint8Array(AM30_REPORT_SIZE); - cmd.set([AM30_CMD.SET_KEYMATRIX, profile, target.slot]); - cmd.set(value, 8); - await this.sendWrite(cmd); - } - - /** Rewrites each button that differs from its factory action, as the vendor's restore does. */ - resetButtonMappings(): Promise { - return this.exclusive(async () => { - // The comparison and every write use the one profile read here. - const profile = this.confirmedProfile(); - const matrix = await this.getKeyMatrix(profile); - for (const { name, slot } of this.buttonSlots()) { - const action = AM30_DEFAULT_BUTTON_MAPPINGS[name]; - if (am30DecodeButtonAction(matrix.subarray(slot * 4, slot * 4 + 4)) !== action) { - await this.writeButton(profile, name, action); - } - } - }); - } - - /** All eight stage slots; stages past the count keep their values for when it grows again. */ - async getDpi(): Promise<{ stages: Am30DpiStage[]; activeIndex: number; count: number }> { - // No profile byte: `D4` answers for the active profile, as the vendor app reads it. - const resp = await this.command([AM30_CMD.GET_DPI]); - const count = Math.min(resp[3], AM30_MAX_DPI_STAGES); - if (count === 0) throw new Error("The Angry Miao Infinity .100 reported no DPI stages."); - const stages: Am30DpiStage[] = []; - for (let i = 0; i < AM30_MAX_DPI_STAGES; i++) { - const rgb = AM30_DPI_RGB_OFFSET + i * 3; - stages.push({ - x: resp[AM30_DPI_X_OFFSET + i * 2] | (resp[AM30_DPI_X_OFFSET + 1 + i * 2] << 8), - y: resp[AM30_DPI_Y_OFFSET + i * 2] | (resp[AM30_DPI_Y_OFFSET + 1 + i * 2] << 8), - rgb: (resp[rgb] << 16) | (resp[rgb + 1] << 8) | resp[rgb + 2], - }); - } - return { stages, activeIndex: Math.min(resp[2], count - 1), count }; - } - - /** `54`: the whole eight-stage table with the active stage and the count. */ - private async writeStageTable(stages: Am30DpiStage[], active: number, count: number): Promise { - const cmd = new Uint8Array(AM30_REPORT_SIZE); - cmd.set([AM30_CMD.SET_DPI, 0, active, count]); - stages.forEach((stage, i) => { - cmd.set([stage.x & 0xff, stage.x >> 8], AM30_DPI_X_OFFSET + i * 2); - cmd.set([stage.y & 0xff, stage.y >> 8], AM30_DPI_Y_OFFSET + i * 2); - cmd.set([(stage.rgb >> 16) & 0xff, (stage.rgb >> 8) & 0xff, stage.rgb & 0xff], AM30_DPI_RGB_OFFSET + i * 3); - }); - await this.sendWrite(cmd); - } - - setDpiForStage(x: number, y: number, index: number): Promise { - return this.exclusive(() => this.writeStageDpi(x, y, index)); - } - - /** Reads the table, edits one stage and writes it back; out-of-range `index` means the active stage. */ - private async writeStageDpi(x: number, y: number, index: number): Promise { - const { minDpi, maxDpi, dpiStep } = this.profile; - if (![x, y].every((v) => Number.isInteger(v) && v >= minDpi && v <= maxDpi && (v - minDpi) % dpiStep === 0)) { - throw new Error(`DPI must be ${minDpi}..${maxDpi} in ${dpiStep} DPI steps.`); - } - const { stages, activeIndex, count } = await this.getDpi(); - const target = index >= 0 && index < count ? index : activeIndex; - stages[target] = { ...stages[target], x, y }; - await this.writeStageTable(stages, activeIndex, count); - return x; - } - - /** The stage editor's shared entry point; one value sets both axes. */ - setDpiStageValue(stage: number, dpi: number): Promise { - return this.exclusive(() => this.writeStageDpi(dpi, dpi, stage)); - } - - async setDpi(dpi: number, dpiY = dpi): Promise { - // An out-of-range stage targets the active stage of the table `writeStageDpi` reads, so `D4` runs once. - await this.exclusive(() => this.writeStageDpi(dpi, dpiY, -1)); - return dpi; - } - - setDpiStageColor(index: number, color: string): Promise { - return this.exclusive(async () => { - const match = /^#?([0-9a-f]{6})$/i.exec(color); - if (!match) throw new Error(`Invalid DPI stage colour "${color}".`); - const rgb = parseInt(match[1], 16); - const { stages, activeIndex, count } = await this.getDpi(); - const target = index >= 0 && index < count ? index : activeIndex; - stages[target] = { ...stages[target], rgb }; - await this.writeStageTable(stages, activeIndex, count); - return `#${match[1].toLowerCase()}`; - }); - } - - setActiveDpiStage(index: number): Promise { - return this.exclusive(async () => { - const { stages, count } = await this.getDpi(); - const target = Math.max(0, Math.min(index, count - 1)); - await this.writeStageTable(stages, target, count); - return target; - }); - } - - /** The DPI button cycles through the first `count` stages; the active stage clamps to the last. */ - setDpiStageCount(count: number): Promise { - return this.exclusive(async () => { - if (!Number.isInteger(count) || count < 1 || count > AM30_MAX_DPI_STAGES) { - throw new Error(`The Angry Miao Infinity .100 holds 1 to ${AM30_MAX_DPI_STAGES} DPI stages.`); - } - const { stages, activeIndex } = await this.getDpi(); - // The vendor app fills a slot it does not hold with 800 DPI, red. - const filled = stages.map((stage) => (stage.x === 0 ? { x: 800, y: 800, rgb: 0xff0000 } : stage)); - await this.writeStageTable(filled, Math.min(activeIndex, count - 1), count); - return count; - }); - } - - async setReportRate(hz: number): Promise { - const code = AM30_RATE_ENCODE[hz]; - if (code === undefined || !this.supportedPollingRates.includes(hz)) { - throw new Error(`Unsupported rate ${hz} Hz. Supported: ${this.supportedPollingRates.join(", ")}`); - } - // Keep the debounce stop, as the vendor app does: its raw bytes are per rate. - const raw = (block: Uint8Array) => am30DebounceRaw( - hz, - am30DebounceGear(AM30_RATE_DECODE[block[AM30_OPT0_REPORT_RATE]], block[AM30_OPT0_DEBOUNCE]), - ); - await this.patchOptionParam0({ - [AM30_OPT0_REPORT_RATE]: code, - [AM30_OPT0_DEBOUNCE]: (_, block) => raw(block).usb, - [AM30_OPT0_DEBOUNCE_24G]: (_, block) => raw(block).rf, - [AM30_OPT0_DEBOUNCE_BT]: (_, block) => raw(block).bt, - }); - return hz; - } - - async setPollingRate(rate: number): Promise { - return this.setReportRate(rate); - } - - async setLiftOffDistance(level: Am30LiftOff): Promise { - const index = AM30_LIFT_OFF_LEVELS.indexOf(level); - if (index < 0) throw new Error(`Lift-off level "${level}" is not available on this model.`); - await this.patchOptionParam0({ [AM30_OPT0_LIFT_OFF]: index }); - return level; - } - - async setAngleSnapping(enabled: boolean): Promise { - await this.patchOptionParam0({ [AM30_OPT0_ANGLE_SNAP]: enabled ? 1 : 0 }); - return enabled; - } - - getDebounceMaxMs(): number { - return Math.max(...AM30_DEBOUNCE_GEARS_MS); - } - - getDebounceOptions(): number[] { - return [...AM30_DEBOUNCE_GEARS_MS].sort((a, b) => a - b); - } - - /** One slider sets all three links, as in the vendor app. */ - async setDebounceTime(ms: number): Promise { - const distance = AM30_DEBOUNCE_GEARS_MS.map((label) => Math.abs(label - ms)); - const gear = distance.indexOf(Math.min(...distance)); - const raw = (block: Uint8Array) => am30DebounceRaw(AM30_RATE_DECODE[block[AM30_OPT0_REPORT_RATE]], gear); - await this.patchOptionParam0({ - [AM30_OPT0_DEBOUNCE]: (_, block) => raw(block).usb, - [AM30_OPT0_DEBOUNCE_24G]: (_, block) => raw(block).rf, - [AM30_OPT0_DEBOUNCE_BT]: (_, block) => raw(block).bt, - }); - return AM30_DEBOUNCE_GEARS_MS[gear]; - } - - getSleepOptions(): number[] { - return [...AM30_SLEEP_OPTIONS]; - } - - /** The vendor app edits each link's timer on its own, so only the current link's is written. */ - async setSleepTimeout(seconds: number): Promise { - const s = Math.max(0, Math.min(0xffff, Math.round(seconds))); - const raw = s === 0 ? AM30_SLEEP_NEVER : s; - const offset = this.sleepOffset; - await this.patchOptionParam0({ [offset]: raw & 0xff, [offset + 1]: (raw >> 8) & 0xff }); - return s; - } - - private get sleepOffset(): number { - return this.transport === "bluetooth" ? AM30_OPT0_SLEEP_BT : AM30_OPT0_SLEEP_24G; - } - - async setRippleControl(enabled: boolean): Promise { - await this.patchOptionParam0({ - [AM30_OPT0_FLAGS]: (current) => enabled ? current | AM30_OPT0_FLAG_RIPPLE : current & ~AM30_OPT0_FLAG_RIPPLE, - }); - return enabled; - } - - async setMotionSync(enabled: boolean): Promise { - await this.patchOptionParam0({ [AM30_OPT0_MOTION_SYNC]: enabled ? 1 : 0 }); - return enabled; - } - - /** Angry Miao's "Blast Mode". */ - setTurboMode(enabled: boolean): Promise { - return this.exclusive(() => this.writeBlastMode(enabled)); - } - - private async writeBlastMode(enabled: boolean): Promise { - await this.sendWrite(Uint8Array.from([AM30_SET_BLAST_MODE, enabled ? 1 : 0])); - this.blastMode = enabled; - return enabled; - } - - private mouseLight(opt0: Uint8Array): MouseLighting { - const rgb = opt0.subarray(AM30_OPT0_LIGHT_COLOR, AM30_OPT0_LIGHT_COLOR + 3); - return { - zone: "Mouse", - modes: ["Off", "Static"], - mode: opt0[AM30_OPT0_LIGHT] ? "Static" : "Off", - color: `#${Array.from(rgb, (b) => b.toString(16).padStart(2, "0")).join("")}`, - color2: null, - colorModes: ["Static"], - dualColorModes: [], - reactiveModes: [], - speeds: [], - speed: null, - }; - } - - /** The vendor's mouse light panel writes its one colour into both RGB slots. */ - setLighting( - lighting: Pick & Partial>, - ): Promise { - return this.exclusive(() => this.writeLighting(lighting)); - } - - private async writeLighting( - lighting: Pick & Partial>, - ): Promise { - if (lighting.zone === "Receiver") return this.setReceiverLight(lighting); - if (lighting.mode !== "Off" && lighting.mode !== "Static") { - throw new Error(`Unsupported lighting mode: ${lighting.mode}.`); - } - const overrides: Record = { [AM30_OPT0_LIGHT]: lighting.mode === "Static" ? 1 : 0 }; - if (lighting.mode === "Static" && lighting.color) { - const match = /^#?([0-9a-f]{6})$/i.exec(lighting.color); - if (!match) throw new Error(`Invalid lighting colour: ${lighting.color}.`); - const value = parseInt(match[1], 16); - [(value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff].forEach((byte, i) => { - overrides[AM30_OPT0_LIGHT_COLOR + i] = byte; - overrides[AM30_OPT0_LIGHT_COLOR_2 + i] = byte; - }); - } - await this.patchOptions(overrides); - return this.mouseLight(await this.getOptionParam0()); - } - - /** Commands for the receiver itself: straight to it, never relayed to the mouse. */ - private receiverCommand(packet: Uint8Array, expectReply: boolean, echoes = true): Promise { - return this.enqueue(async () => { - await this.open(); - await this.rawSend(packet); - await delay(10); - return expectReply ? this.verifyReply(await this.rawRead(), packet[0], echoes) : null; - }); - } - - /** Raw `F7` status reply, which carries no checksum and no echo byte. */ - private readReceiverStatus(): Promise { - return this.enqueue(async () => { - await this.open(); - await this.rawSend([AM30_RELAY.GET_STATUS]); - await delay(10); - return this.rawRead(); - }); - } - - /** The vendor app's order: USB, a 500 ms pause, RF, LED. */ - private async readReceiverFirmware(): Promise { - const known = this.receiverFirmware; - const read = async (command: number, echoes = true) => { - try { return await this.receiverCommand(am30EncodeCommand([command]), true, echoes); } catch { return null; } - }; - // A failed read never replaces a version that is already known. - if (!known.usb) { - known.usb = await read(AM30_RECEIVER_GET_USB_VERSION) ?? known.usb; - if (!known.rf) await delay(500); - } - if (!known.rf) known.rf = await read(AM30_RECEIVER_GET_RF_VERSION, false) ?? known.rf; - if (!known.led) known.led = await read(AM30_RECEIVER_GET_LED_VERSION) ?? known.led; - return am30ReceiverFirmwareLabels(known.usb, known.rf, known.led); - } - - /** The receiver answers on its own while the mouse sleeps, is off, or is on another link. */ - private async receiverOnlyStatus(receiverStatus: Uint8Array): Promise { - let receiverLight: MouseLighting | undefined; - try { receiverLight = await this.readReceiverLight(); } catch { /* Optional: the zone stays hidden. */ } - const firmware = await this.readReceiverFirmware(); - const spareBattery = am30DecodeSpareBattery(receiverStatus); - const { brand } = ANGRY_MIAO_INFINITY_PROFILE; - // No mouse answers, so the receiver gets its own name instead of the mouse's. - const name = `${brand} Receiver`; - return { - brand, - name, - ui: { - family: "angry-miao", - settingsReady: false, - receiverOnly: true, - defaultDisplayName: name, - hideAdvancedLighting: true, - separateLightingZones: true, - statusNote: "The receiver is connected, but the mouse is not answering. Wake it, or switch it to 2.4 GHz.", - }, - batteryPercent: null, - batteryState: "Unknown", - dpi: 0, - pollingRateHz: 0, - activeProfile: null, - liftOffDistance: null, - connectionType: "Wireless", - connectionDetail: "2.4 GHz", - firmware, - ...(spareBattery ? { spareBattery } : {}), - ...(receiverLight ? { lightingZones: [receiverLight] } : {}), - }; - } - - private async readReceiverLight(): Promise { - const light = await this.receiverCommand(am30EncodeCommand([AM30_RECEIVER_GET_LIGHT]), true); - const power = await this.receiverCommand(am30EncodeCommand([AM30_RECEIVER_GET_LIGHT_SWITCH]), true); - const decoded = am30DecodeReceiverLight(light!, power!); - return { - zone: "Receiver", - modes: ["Off", ...RECEIVER_EFFECTS], - mode: decoded.enabled ? RECEIVER_EFFECTS[decoded.effect - 1] : "Off", - color: decoded.color, - color2: null, - // The vendor panel hides the colour for neon and the speed for always on. - colorModes: RECEIVER_EFFECTS.filter((mode) => mode !== "Neon"), - dualColorModes: [], - reactiveModes: RECEIVER_EFFECTS.filter((mode) => mode !== "Static"), - speeds: [...AM30_RECEIVER_SPEEDS], - speed: decoded.speed, - brightness: decoded.brightness, - brightnessLevels: [...AM30_RECEIVER_BRIGHTNESS], - }; - } - - private async setReceiverLight( - lighting: Pick & Partial>, - ): Promise { - if (this.transport !== "dongle") throw new Error("The receiver light needs the 2.4 GHz receiver."); - if (lighting.mode !== "Off") { - const effect = lighting.mode ? RECEIVER_EFFECTS.indexOf(lighting.mode) + 1 : 0; - if (effect < 1) throw new Error(`Unsupported receiver light effect: ${lighting.mode}.`); - await this.receiverCommand(am30EncodeReceiverLight({ - effect, - speed: lighting.speed ?? 1, - brightness: lighting.brightness ?? 100, - color: lighting.color ?? "#ffffff", - }), false); - await delay(30); - } - await this.receiverCommand(am30EncodeCommand([AM30_RECEIVER_SET_LIGHT_SWITCH, lighting.mode === "Off" ? 0 : 1]), false); - return this.readReceiverLight(); - } - - readStatus(): Promise { - return this.exclusive(() => this.readStatusNow()); - } - - private async readStatusNow(): Promise { - await this.open(); - this.firmwareCode = null; - // The last verified id stays until `8F` answers again, so a write made during this read still goes out. - let receiverStatus: Uint8Array | null = null; - if (this.transport === "dongle") { - receiverStatus = await this.readReceiverStatus(); - if (receiverStatus[AM30_STATUS_MOUSE_OFFLINE] !== 0) { - // The mouse is absent, so nothing it reported earlier holds any more. - this.deviceId = null; - this.resolvedProfile = null; - this.profileConfirmed = false; - return this.receiverOnlyStatus(receiverStatus); - } - } - // Read first: `D0` and `50` take the profile index. - let profile: number | null = null; - try { profile = await this.readProfile(); } catch { /* Optional: the profile selector stays hidden. */ } - this.profileConfirmed = profile !== null; - if (profile !== null) this.currentProfile = profile; - let deviceId: number | null = null; - try { deviceId = await this.getDeviceId(); } catch { /* Unknown: settings stay read-only. */ } - this.deviceId = deviceId; - this.resolvedProfile = this.deviceId === null ? null : ANGRY_MIAO_PROFILES.get(this.deviceId) ?? null; - const model = this.profile; - const name = this.resolvedProfile - ? `${model.brand} ${model.model}` - : this.device.productName?.trim() || "Angry Miao mouse"; - - // The DPI read has to work: it proves the relay and checksum path. - const dpi = await this.getDpi(); - const active = dpi.stages[dpi.activeIndex] ?? dpi.stages[0]; - const [opt0Result, matrixResult] = await Promise.allSettled([ - this.getOptionParam0(), - // Without a confirmed profile the mappings stay hidden rather than show a guessed profile's. - profile !== null ? this.getKeyMatrix(profile) : Promise.resolve(null), - this.getFirmwareVersion(), - ]); - const opt0 = opt0Result.status === "fulfilled" ? opt0Result.value : null; - // Only this read's own `D0` reply, never another call's. - const matrix = matrixResult.status === "fulfilled" ? matrixResult.value : null; - const buttonMappings = matrix && Object.fromEntries(this.buttonSlots().map(({ name, slot }) => [ - name, am30DecodeButtonAction(matrix.subarray(slot * 4, slot * 4 + 4)), - ])); - const { count } = dpi; - - // F7 byte 2 mirrors the mouse battery through the receiver; D6 reads it from the mouse itself. - let battery: ReturnType = { percent: null, state: "Unknown" }; - try { battery = am30DecodeBattery(await this.command([AM30_GET_BATTERY])); } catch { /* Optional. */ } - if (battery.percent === null && this.transport === "bluetooth") { - try { battery = { percent: await this.bluetoothBattery(), state: "Unknown" }; } catch { /* Optional. */ } - } - let turboMode: boolean | undefined; - try { - turboMode = this.blastMode ?? (await this.command([AM30_GET_BLAST_MODE]))[1] === 1; - } catch { /* Optional: the switch stays hidden. */ } - let usbCode: number | null = null; - // The vendor app reads `AD` on the cable only; through the receiver it reads 0. - if (this.transport === "direct") { - try { - const reply = await this.command([AM30_GET_USB_VERSION]); - usbCode = reply[1] | (reply[2] << 8); - } catch { /* Optional: the package version needs it. */ } - } - const firmware = am30FirmwareLabels(usbCode, this.firmwareCode || null); - let receiverLight: MouseLighting | undefined; - let spareBattery: ReturnType = null; - if (this.transport === "dongle") { - try { receiverLight = await this.readReceiverLight(); } catch { /* Optional: the zone stays hidden. */ } - firmware.push(...await this.readReceiverFirmware()); - if (receiverStatus) spareBattery = am30DecodeSpareBattery(receiverStatus); - } - const mouseLight = opt0 ? this.mouseLight(opt0) : undefined; - const rawSleep = opt0 ? opt0[this.sleepOffset] | (opt0[this.sleepOffset + 1] << 8) : null; - const wireless = this.transport !== "direct"; - - return { - brand: model.brand, - name, - ui: { - family: "angry-miao", - settingsReady: this.modelVerified, - defaultDisplayName: name, - hideAdvancedLighting: true, - separateLightingZones: true, - dpiStageEditor: { - maxStages: AM30_MAX_DPI_STAGES, - minDpi: model.minDpi, - maxDpi: model.maxDpi, - stepDpi: model.dpiStep, - countEditable: true, - }, - ...(this.modelVerified ? {} : { - statusNote: `This mouse reports device id ${this.deviceId ?? "unknown"}, which OpenMouse has not verified, so its settings are read-only.`, - }), - }, - dpi: active.x, - dpiY: active.y, - supportsSeparateDpiAxes: true, - dpiStages: dpi.stages.slice(0, count).map((stage) => stage.x), - dpiStageColors: dpi.stages.slice(0, count).map((stage) => `#${stage.rgb.toString(16).padStart(6, "0")}`), - activeDpiStage: dpi.activeIndex, - pollingRateHz: (opt0 && AM30_RATE_DECODE[opt0[AM30_OPT0_REPORT_RATE]]) || 1000, - supportedPollingRates: this.supportedPollingRates, - connectionType: wireless ? "Wireless" : "Wired", - connectionDetail: { bluetooth: "Bluetooth", dongle: "2.4 GHz", direct: "USB" }[this.transport], - liftOffDistance: opt0 ? AM30_LIFT_OFF_LEVELS[opt0[AM30_OPT0_LIFT_OFF]] ?? AM30_LIFT_OFF_LEVELS[0] : null, - angleSnapping: opt0 ? opt0[AM30_OPT0_ANGLE_SNAP] !== 0 : null, - debounceMs: null, - rippleControl: null, - sleepTimeout: rawSleep === AM30_SLEEP_NEVER ? 0 : rawSleep, - activeProfile: profile === null ? null : profile + 1, - ...(profile !== null ? { profileCount: AM30_PROFILE_COUNT } : {}), - firmware: [...firmware, model.sensor], - batteryPercent: battery.percent, - batteryState: battery.state, - ...(spareBattery ? { spareBattery } : {}), - ...(opt0 ? { - debounceMs: AM30_DEBOUNCE_GEARS_MS[am30DebounceGear(AM30_RATE_DECODE[opt0[AM30_OPT0_REPORT_RATE]], opt0[AM30_OPT0_DEBOUNCE])], - rippleControl: (opt0[AM30_OPT0_FLAGS] & AM30_OPT0_FLAG_RIPPLE) !== 0, - motionSync: opt0[AM30_OPT0_MOTION_SYNC] === 1, - lighting: mouseLight, - } : {}), - ...(receiverLight ? { lightingZones: [...(mouseLight ? [mouseLight] : []), receiverLight] } : {}), - ...(turboMode !== undefined ? { turboMode } : {}), - ...(buttonMappings ? { - buttonMappings, - buttonOptions: this.getButtonOptions(), - defaultButtonMappings: { ...AM30_DEFAULT_BUTTON_MAPPINGS }, - fixedButtons: ["Left"], - } : {}), - }; - } -} +export { AngryMiaoAm30HidClient as AngryMiaoHidClient } from "./am30-hid.ts"; +export type { AngryMiaoLightingChange, AngryMiaoSettingsChange } from "./base.ts"; diff --git a/src/drivers/registry.ts b/src/drivers/registry.ts index 7c54fd60..7ecebe89 100644 --- a/src/drivers/registry.ts +++ b/src/drivers/registry.ts @@ -9,7 +9,8 @@ import { EggOp1HidClient } from "./endgame/egg-op1-hid.ts"; import { EggOtHidClient } from "./endgame/egg-ot-hid.ts"; import { FantechHidClient } from "./fantech/hid.ts"; import { GearHubHidClient } from "./gearhub/hid.ts"; -import { AngryMiaoHidClient } from "./angry-miao/hid.ts"; +import { AngryMiaoAm30HidClient } from "./angry-miao/am30-hid.ts"; +import { AngryMiaoAm30R2HidClient, AngryMiaoAm35HidClient } from "./angry-miao/am35-hid.ts"; import { eggWeCreate, eggWeIsSupported, eggWeSupportScore, isEggWeClient, type EggWeHidClient } from "./endgame/egg-we-control.ts"; import { FinalmouseHidClient } from "./finalmouse/hid.ts"; import { Keychron1kHidClient } from "./keychron/mouse-1k-hid.ts"; @@ -118,7 +119,7 @@ import { XiaomiHidClient } from "./xiaomi/hid.ts"; import { A4techHidClient } from "./a4tech/a4tech-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 | AttackSharkCompxHidClient | 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 | UtechsmartVenusHidClient | RedragonM690ProHidClient | RedragonM719ProHidClient | IncottHidClient | HyperXHidClient | MchoseV3HidClient | AsusHidClient | KyuProMx1Client | AmketteXsHidClient | DeluxHidClient | BytechHidClient | RapooHidClient | FaterHidClient | CoolerMasterHidClient | AjazzHidClient | AjazzAj200pHidClient | AjazzAk820HidClient | ScyroxHidClient | ZaopinHidClient | HitscanHidClient | RoccatHidClient | ThermaltakeHidClient | RedgearX13HidClient | AulaSc380ProHidClient | AulaSc590ProHidClient | InstantA825HidClient | XiaomiHidClient | LeobogGm3HidClient | Sinowealth520HidClient | KmartHidClient | EightBitDoHidClient | A4techHidClient | AngryMiaoHidClient; +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 | AttackSharkCompxHidClient | 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 | UtechsmartVenusHidClient | RedragonM690ProHidClient | RedragonM719ProHidClient | IncottHidClient | HyperXHidClient | MchoseV3HidClient | AsusHidClient | KyuProMx1Client | AmketteXsHidClient | DeluxHidClient | BytechHidClient | RapooHidClient | FaterHidClient | CoolerMasterHidClient | AjazzHidClient | AjazzAj200pHidClient | AjazzAk820HidClient | ScyroxHidClient | ZaopinHidClient | HitscanHidClient | RoccatHidClient | ThermaltakeHidClient | RedgearX13HidClient | AulaSc380ProHidClient | AulaSc590ProHidClient | InstantA825HidClient | XiaomiHidClient | LeobogGm3HidClient | Sinowealth520HidClient | KmartHidClient | EightBitDoHidClient | A4techHidClient | AngryMiaoAm30HidClient | AngryMiaoAm35HidClient | AngryMiaoAm30R2HidClient; export interface DeviceDriver { brand: string; supports(device: HIDDevice): boolean; @@ -218,9 +219,11 @@ export const DEVICE_DRIVERS: readonly DeviceDriver[] = [ // registry label is the M5 Pro's brand (the fallback identity). // Angry Miao reuses Yichip product ids (cable, receiver and the AJ179 PRO's // Bluetooth id); its own driver claims them by name, so these two step aside. - { brand: "Lingbao", supports: (device) => GearHubHidClient.isSupported(device) && !AngryMiaoHidClient.isSupported(device), create: (device) => new GearHubHidClient(device), score: () => 7 }, - { brand: "Angry Miao", supports: (device) => AngryMiaoHidClient.isSupported(device), create: (device) => new AngryMiaoHidClient(device), score: () => 7 }, - { brand: "Fantech", supports: (device) => FantechHidClient.isSupported(device) && !AngryMiaoHidClient.isSupported(device), create: (device) => new FantechHidClient(device), score: () => 5 }, + { brand: "Lingbao", supports: (device) => GearHubHidClient.isSupported(device) && !AngryMiaoAm30HidClient.isSupported(device), create: (device) => new GearHubHidClient(device), score: () => 7 }, + { brand: "Angry Miao", supports: (device) => AngryMiaoAm30HidClient.isSupported(device), create: (device) => new AngryMiaoAm30HidClient(device), score: () => 7 }, + { brand: "Angry Miao", supports: (device) => AngryMiaoAm35HidClient.isSupported(device), create: (device) => new AngryMiaoAm35HidClient(device), score: () => 7 }, + { brand: "Angry Miao", supports: (device) => AngryMiaoAm30R2HidClient.isSupported(device), create: (device) => new AngryMiaoAm30R2HidClient(device), score: () => 7 }, + { brand: "Fantech", supports: (device) => FantechHidClient.isSupported(device) && !AngryMiaoAm30HidClient.isSupported(device), create: (device) => new FantechHidClient(device), score: () => 5 }, { brand: "Wooting", supports: (device) => WootingHidClient.isSupported(device), create: (device) => new WootingHidClient(device), score: () => 6 }, { brand: "WALLHACK", supports: (device) => WallhackMouseHidClient.isSupported(device), create: (device) => new WallhackMouseHidClient(device), score: () => 8 }, { brand: "WALLHACK", supports: (device) => WallhackKeyboardHidClient.isSupported(device), create: (device) => new WallhackKeyboardHidClient(device), score: () => 8 }, diff --git a/src/drivers/vendors.ts b/src/drivers/vendors.ts index 847cbc7b..8c01c704 100644 --- a/src/drivers/vendors.ts +++ b/src/drivers/vendors.ts @@ -38,7 +38,13 @@ import { GEARHUB_PRODUCTS, GEARHUB_VENDOR_ID, } from "@openmouse/protocol/gearhub"; -import { ANGRY_MIAO_PRODUCTS, ANGRY_MIAO_VENDOR_ID } from "@openmouse/protocol/angry-miao"; +import { + AM35_ALT_VENDOR_ID, + AM35_PRODUCT_IDS, + AM35_VENDOR_ID, + ANGRY_MIAO_PRODUCTS, + ANGRY_MIAO_VENDOR_ID, +} from "@openmouse/protocol/angry-miao"; import { GWOLVES_PRODUCTS } from "./gwolves/products.ts"; import { LAMZU_INCA_PRODUCTS, LAMZU_INCA_VENDOR_ID } from "@openmouse/protocol/lamzu"; import { @@ -280,6 +286,9 @@ export const VENDOR_ID = { incott: INCOTT_VENDOR_ID, hyperxKingston: HYPERX_VENDOR_ID_KINGSTON, hyperxHp: HYPERX_VENDOR_ID_HP, + // Angry Miao Infinity .97 and .100R2 (MediaTek); the vendor app also routes 35A1:0035 to the .97. + angryMiaoMediatek: AM35_VENDOR_ID, + angryMiaoAlt: AM35_ALT_VENDOR_ID, hitscan: HITSCAN_VENDOR_ID, roccat: ROCCAT_VENDOR_ID, thermaltake: THERMALTAKE_VENDOR_ID, @@ -932,6 +941,11 @@ export const ANGRY_MIAO_HID_FILTERS: HIDDeviceFilter[] = [...ANGRY_MIAO_PRODUCTS ([productId, { usagePage, usage }]) => ({ vendorId: ANGRY_MIAO_VENDOR_ID, productId, usagePage, usage }), ); +/** The .97 and .100R2 by id alone, as the vendor app asks for them; the drivers check the reports. */ +export const ANGRY_MIAO_AM35_HID_FILTERS: HIDDeviceFilter[] = AM35_PRODUCT_IDS.map( + ({ vendorId, productId }) => ({ vendorId, productId }), +); + // Corsair NXP-family mice answer on the interface whose collection is usage // page 0xffc2, usage 4 (64-byte feature reports on id 0). MI_00 also carries // an 0xffc2 collection (usage 3) that never answers, so the usage is required @@ -1200,6 +1214,7 @@ export const SUPPORTED_HID_FILTERS: HIDDeviceFilter[] = [ ...LOGITECH_BLUETOOTH_FILTERS, ...GEARHUB_HID_FILTERS, ...ANGRY_MIAO_HID_FILTERS, + ...ANGRY_MIAO_AM35_HID_FILTERS, // Fantech mice use vendor usage page 0xFFFF, usage 0x02 for configuration. { vendorId: VENDOR_ID.fantech, usagePage: 0xffff, usage: 0x02 }, ...WALLHACK_HID_FILTERS,