import type { MouseLighting, MouseLightingMode, MouseStatus } from "../mouse-types.ts"; import { AngryMiaoHidClient, type AngryMiaoLightingChange, type AngryMiaoSettingsChange } from "./hid.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; return this.enqueue(async () => { await this.open(); const replyNow = options.reply === false ? null : this.useFeature ? null : this.waitForInput(command, deviceId); 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, deviceId); 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, deviceId: number): Promise { const budget = deviceId >= AM35_REMOTE_DEVICE ? REMOTE_REPLY_TIMEOUT_MS : REPLY_TIMEOUT_MS; const attempts = Math.max(deviceId >= AM35_REMOTE_DEVICE ? 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)); if (chunk.length === 0 || chunk.every((b) => b === 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) { 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, deviceId: number): 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) 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)}.`)); }, deviceId >= AM35_REMOTE_DEVICE ? REMOTE_REPLY_TIMEOUT_MS : REPLY_TIMEOUT_MS); this.device.addEventListener("inputreport", onReport); }); } /** * Through the receiver, the vendor app asks for its mode and link type and lists its devices; any device * there means the mouse answers on 0x80. False when the receiver holds no mouse. */ private async connectReceiver(): Promise { if (!this.isReceiver || this.remoteDevice !== null) return true; if (!this.useFeature) return false; 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 battery: Awaited> | null = null; 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()); battery = linked ? await optional(async () => am35DecodeBattery(await this.send(AM35_CMD.GET_BATTERY))) : null; if (!battery) { this.remoteDevice = null; return this.receiverOnlyStatus(); } } else { battery = await optional(async () => am35DecodeBattery(await this.send(AM35_CMD.GET_BATTERY))); } // The DPI read has to work: it proves the transport. const dpi = await this.getDpi(); 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; } }