From 806aa1e76bfff9b7f7b909f426d9a1694cfaaa3d Mon Sep 17 00:00:00 2001 From: misakasakura Date: Mon, 30 Nov 2026 00:36:20 +0800 Subject: [PATCH 01/24] feat(asus): add ROG Harpe Ace Mini (0x1B63 / 0x1B65) Register 0x1B63 (wired) and 0x1B65 (Omni pair list); the receiver stays 0x1ACE. Reuse the Harpe Ace Aim Lab capabilities with a 42,000 DPI ceiling, 4 stages, X/Y DPI, DPI colours, 5 profiles, debounce, LOD, battery and the scroll-wheel zone. Declare the Battery lighting mode (0x06) and the lighting-sync capability consumed by the driver. Both PIDs are hardware-verified. --- src/asus/devices.ts | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/src/asus/devices.ts b/src/asus/devices.ts index 4cf7763b..61502a82 100644 --- a/src/asus/devices.ts +++ b/src/asus/devices.ts @@ -13,7 +13,8 @@ * * - G-Helper (seerge/g-helper, `app/Peripherals/Mouse/Models/*.cs`): product * ids, stage counts, DPI ranges and steps, profile counts, zones, and which - * settings each model exposes. + * settings each model exposes. The Harpe Ace Mini comes from + * `Models/HarpeAceMini.cs`. * - libratbag (`data/devices/asus-*.device`): cross-checks for the Strix * Impact III and Harpe Ace. * - OpenRGB (`AsusAuraMouseDevices.h`): lighting zones and effect order, and @@ -35,7 +36,7 @@ */ /** Effect names, spelled as the shared `MouseLightingMode` values. */ -export type AsusLightingEffect = "Static" | "Breathing single" | "Cycling" | "Spectrum" | "Reactive" | "Wave"; +export type AsusLightingEffect = "Static" | "Breathing single" | "Cycling" | "Spectrum" | "Reactive" | "Wave" | "Battery"; export interface AsusMouseModel { name: string; @@ -60,6 +61,8 @@ export interface AsusMouseModel { lightingModes: Readonly>>; /** Older firmware scales brightness 0-4, newer 0-100. */ brightnessMax: 4 | 100; + /** Firmware can hand the LEDs to Aura Sync / Windows Dynamic Lighting. */ + lightingSync?: boolean; /** Older firmware answers `12 03 00` with every zone in one reply. */ lightingAllZones?: boolean; verified: boolean; @@ -89,6 +92,13 @@ const MODERN_MODES = { Reactive: 0x04, } as const; +// Gear Link also offers a battery-level effect on the Harpe Ace Mini; captured +// on hardware as wire mode 0x06. +const HARPE_ACE_MINI_MODES = { + ...MODERN_MODES, + Battery: 0x06, +} as const; + const HARPE_ACE_AIM_LAB = { name: "ROG Harpe Ace Aim Lab Edition", dpiStages: 4, @@ -107,6 +117,14 @@ const HARPE_ACE_AIM_LAB = { verified: false, } as const; +const HARPE_ACE_MINI = { + ...HARPE_ACE_AIM_LAB, + name: "ROG Harpe Ace Mini", + maxDpi: 42_000, + lightingModes: HARPE_ACE_MINI_MODES, + lightingSync: true, +} as const; + const TUF_M5 = { name: "TUF Gaming M5", wireless: false, @@ -178,6 +196,16 @@ export const ASUS_MICE: ReadonlyMap = new Map Date: Mon, 30 Nov 2026 00:36:20 +0800 Subject: [PATCH 02/24] feat(asus): add Aura Sync lighting handoff Add setLightingSync() and assert 51 42 00 00 00/01 before every effect write so Aura Sync or Windows Dynamic Lighting cannot keep the stored effect off the LEDs. Only models that declare lightingSync send 51 42; older ASUS firmware keeps its previous command stream. Expose the selected owner through MouseLighting.sync. Firmware has no read-back, so it is session state. Cover the handoff, unsupported models and older models with tests. --- src/asus/index.ts | 9 ++++ src/drivers/asus/hid.test.ts | 70 +++++++++++++++++++++++- src/drivers/asus/hid.ts | 102 ++++++++++++++++++++++++----------- src/drivers/mouse-types.ts | 4 ++ 4 files changed, 153 insertions(+), 32 deletions(-) diff --git a/src/asus/index.ts b/src/asus/index.ts index 5767d88a..0a7e36f0 100644 --- a/src/asus/index.ts +++ b/src/asus/index.ts @@ -322,6 +322,15 @@ export function asusSetLightingRequest( return request(0x51, 0x28, zoneId(model, zone), 0x00, mode, brightness, red, green, blue, 0x00, 0x00, speed); } +/** + * `51 42` hands the LEDs to the onboard effect (0) or back to Aura Sync / + * Windows Dynamic Lighting (1). Gear Link sends the 0 form before `51 28`; + * without it the firmware stores the effect but the system keeps the LEDs. + */ +export function asusSetLightingSyncRequest(enabled: boolean): Uint8Array { + return request(0x51, 0x42, 0x00, 0x00, enabled ? 0x01 : 0x00); +} + export function asusSaveRequest(): Uint8Array { return request(0x50, 0x03); } diff --git a/src/drivers/asus/hid.test.ts b/src/drivers/asus/hid.test.ts index 2ba507c3..3dfa2164 100644 --- a/src/drivers/asus/hid.test.ts +++ b/src/drivers/asus/hid.test.ts @@ -245,6 +245,8 @@ class FakeAsusMouse { readonly model: AsusMouseModel; readonly sent: Uint8Array[] = []; asleep = false; + /** Answer the next N requests with FF AA, then behave normally. */ + sleepReplies = 0; /** Wire DPI values; `(value + 1) * step`. */ readonly dpi: number[]; readonly colors: number[][]; @@ -303,7 +305,8 @@ class FakeAsusMouse { reply(p: Uint8Array): Uint8Array { const r = new Uint8Array(ASUS_REPORT_SIZE); - if (this.asleep) { + if (this.asleep || this.sleepReplies > 0) { + this.sleepReplies = Math.max(0, this.sleepReplies - 1); r.set([0xff, 0xaa]); return r; } @@ -569,9 +572,74 @@ test("sends TUF Reactive as 0x03 on a 0-4 brightness scale", async () => { assert.equal(result.brightness, 50); }); +test("takes lighting control back before writing an effect", async () => { + const { fake, client } = connect(0x1b63); + const { lighting } = await client.readStatus(); + + await client.setLighting({ ...lighting!, mode: "Static", color: "#ff0000", brightness: 100 }); + + const sync = fake.sent.findIndex((frame) => frame[0] === 0x51 && frame[1] === 0x42); + const write = fake.sent.findIndex((frame) => frame[0] === 0x51 && frame[1] === 0x28); + assert.ok(sync >= 0, "expected a 51 42 control frame"); + assert.ok(sync < write, "control must come before the lighting write"); + assert.deepEqual([...fake.sent[sync].subarray(0, 5)], [0x51, 0x42, 0x00, 0x00, 0x00]); +}); + +test("Harpe Ace Mini exposes Gear Link's Battery mode", async () => { + const { fake, client } = connect(0x1b63); + const { lighting } = await client.readStatus(); + + assert.ok(lighting!.modes.includes("Battery")); + await client.setLighting({ ...lighting!, mode: "Battery", color: null, brightness: 100 }); + + assert.deepEqual(sentWith(fake, 0x51, 0x28)[0].slice(0, 6), [0x51, 0x28, 0x01, 0x00, 0x06, 0x64]); +}); + +test("hands lighting sync to the OS and back", async () => { + const { fake, client } = connect(0x1b63); + const { lighting } = await client.readStatus(); + + assert.equal(lighting!.sync, false); + assert.equal(await client.setLightingSync(true), true); + assert.equal((await client.readStatus()).lighting!.sync, true); + assert.deepEqual(sentWith(fake, 0x51, 0x42).at(-1)!.slice(0, 5), [0x51, 0x42, 0x00, 0x00, 0x01]); + + assert.equal(await client.setLightingSync(false), false); + assert.equal((await client.readStatus()).lighting!.sync, false); +}); + +test("models without a sync control reject setLightingSync", async () => { + const { client } = connect(0x1a94); + + await assert.rejects(client.setLightingSync(false), /no lighting sync/); +}); + +test("older models never send the sync control frame", async () => { + const { fake, client } = connect(0x1a94); + const { lighting } = await client.readStatus(); + + await client.setLighting({ ...lighting!, mode: "Static", color: "#00ff00", brightness: 50 }); + + assert.equal(sentWith(fake, 0x51, 0x42).length, 0); +}); + +test("the Omni-paired Mini is registered with lighting sync", () => { + assert.equal(ASUS_MICE.get(0x1b65)!.lightingSync, true); + assert.equal(ASUS_MICE.get(0x1b63)!.lightingSync, true); +}); + test("fails fast when the mouse answers FF AA", async () => { const { fake, client } = connect(0x1a94); fake.asleep = true; await assert.rejects(client.readStatus(), /asleep/); }); + +test("retries once when the first reply is FF AA", async () => { + const { fake, client } = connect(0x1a94); + fake.sleepReplies = 1; + + const status = await client.readStatus(); + + assert.equal(status.brand, "ASUS"); +}); diff --git a/src/drivers/asus/hid.ts b/src/drivers/asus/hid.ts index 923f3e08..0e0147f5 100644 --- a/src/drivers/asus/hid.ts +++ b/src/drivers/asus/hid.ts @@ -44,6 +44,7 @@ import { asusSetDpiRequest, asusSetLiftOffRequest, asusSetLightingRequest, + asusSetLightingSyncRequest, asusSetPollingRateRequest, asusSetProfileRequest, type AsusBattery, @@ -95,6 +96,12 @@ function wait(milliseconds: number): Promise { return new Promise((resolve) => setTimeout(resolve, milliseconds)); } +/** Delay before re-sending a command the firmware answered with `FF AA`. */ +const ASUS_WAKE_RETRY_MS = 40; + +/** `FF AA`: the mouse is asleep, out of range, or refused the request. */ +class AsusSleepError extends Error {} + function hexByte(value: number): string { return value.toString(16).padStart(2, "0"); } @@ -123,6 +130,10 @@ export class AsusHidClient { private booster = false; + /** False keeps the LEDs on the onboard effect; true hands them to Aura Sync. + * Firmware has no read-back, so this is session state only. */ + private lightingSync = false; + private queue: Promise = Promise.resolve(); constructor(device: HIDDevice) { @@ -197,47 +208,58 @@ export class AsusHidClient { private async exchange(request: Uint8Array, matchLength = 3, reportId = this.mouseReportId): Promise { return this.run(async () => { await this.open(); + try { + return await this.exchangeOnce(request, matchLength, reportId); + } catch (error) { + if (!(error instanceof AsusSleepError)) throw error; + // The first command after an idle spell is often applied by the firmware but + // answered with FF AA while the mouse wakes up. One retry absorbs that; a + // second FF AA is a real refusal. + await wait(ASUS_WAKE_RETRY_MS); + return this.exchangeOnce(request, matchLength, reportId); + } + }); + } - const payload = this.payload(request, reportId); + private exchangeOnce(request: Uint8Array, matchLength: number, reportId: number): Promise { + const payload = this.payload(request, reportId); - return new Promise((resolve, reject) => { - const cleanup = (): void => { - clearTimeout(timer); - this.device.removeEventListener("inputreport", listener); - }; + return new Promise((resolve, reject) => { + const cleanup = (): void => { + clearTimeout(timer); + this.device.removeEventListener("inputreport", listener); + }; - const listener = (event: HIDInputReportEvent): void => { - if (event.reportId !== reportId) return; + const listener = (event: HIDInputReportEvent): void => { + if (event.reportId !== reportId) return; - const data = copyDataView(event.data); - if (data.length < payload.byteLength) return; + const data = copyDataView(event.data); + if (data.length < payload.byteLength) return; - // `FF AA` is the firmware's reply while asleep, out of range, or refusing a request. - if (data[0] === 0xff && data[1] === 0xaa) { - cleanup(); - reject(new Error(`${this.label} is asleep or refused the request.`)); - return; - } + if (data[0] === 0xff && data[1] === 0xaa) { + cleanup(); + reject(new AsusSleepError(`${this.label} is asleep or refused the request.`)); + return; + } - for (let i = 0; i < matchLength; i++) { - if (data[i] !== request[i]) return; - } + for (let i = 0; i < matchLength; i++) { + if (data[i] !== request[i]) return; + } - cleanup(); - resolve(data.subarray(0, payload.byteLength)); - }; + cleanup(); + resolve(data.subarray(0, payload.byteLength)); + }; - const timer = setTimeout(() => { - this.device.removeEventListener("inputreport", listener); - reject(new Error(`${this.label} did not answer the HID request.`)); - }, RESPONSE_TIMEOUT_MS); + const timer = setTimeout(() => { + this.device.removeEventListener("inputreport", listener); + reject(new Error(`${this.label} did not answer the HID request.`)); + }, RESPONSE_TIMEOUT_MS); - this.device.addEventListener("inputreport", listener); + this.device.addEventListener("inputreport", listener); - this.device.sendReport(reportId, payload).catch((error: unknown) => { - cleanup(); - reject(error); - }); + this.device.sendReport(reportId, payload).catch((error: unknown) => { + cleanup(); + reject(error); }); }); } @@ -361,6 +383,7 @@ export class AsusHidClient { speed: null, brightness: Math.max(0, Math.min(100, Math.round((raw.brightness * 100) / brightnessMax))), brightnessLevels: BRIGHTNESS_LEVELS, + sync: this.model.lightingSync ? this.lightingSync : undefined, }; } @@ -481,6 +504,17 @@ export class AsusHidClient { return confirmed; } + /** Hands the LEDs to Aura Sync / Windows Dynamic Lighting (true) or back to the onboard effect (false). */ + async setLightingSync(enabled: boolean): Promise { + if (!this.model.lightingSync) { + throw new Error(`${this.model.name} has no lighting sync control.`); + } + + await this.exchange(asusSetLightingSyncRequest(enabled)); + this.lightingSync = enabled; + return enabled; + } + async setLighting(lighting: MouseLighting): Promise { const { model } = this; const zone = model.zones.indexOf(lighting.zone); @@ -512,6 +546,12 @@ export class AsusHidClient { speed = 0x64; } + // Only firmware with the sync control understands 51 42; older models + // would see it as an unknown command. + if (model.lightingSync) { + // With sync on the effect is still stored, but Aura Sync drives the LEDs. + await this.exchange(asusSetLightingSyncRequest(this.lightingSync)); + } await this.exchange(asusSetLightingRequest(model, zone, rawMode, brightness, red, green, blue, speed)); await this.save(); diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index b8bed1a5..cafc2a88 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -135,10 +135,14 @@ export interface MouseLighting { hardwareZoneId?: number; /** Lets the UI group individually painted cells into one physical surface. */ group?: string; + /** True when Aura Sync / Windows Dynamic Lighting owns the LEDs; undefined when unsupported. + * This is the app's selected owner, not a firmware read-back. */ + sync?: boolean; } export type MouseLightingMode = | "Off" + | "Battery" | "Static" | "Cycling" | "Wave" From 3b4982807f712f694ae0bc6d6f5a068b275317fd Mon Sep 17 00:00:00 2001 From: misakasakura Date: Mon, 30 Nov 2026 01:06:10 +0800 Subject: [PATCH 03/24] feat(asus): add angle tuning for the Harpe Ace Mini Read the signed -20..20 degree field from 12 04 00 and write 51 31 0B 00 , followed by the captured 50 03 save. Expose the control on the performance tab with the official range and hide the duplicate advanced row. Cover decode, encode, save order and unsupported models with tests. --- src/asus/devices.ts | 3 +++ src/asus/index.ts | 27 ++++++++++++++++++++++++- src/drivers/asus/hid.test.ts | 38 ++++++++++++++++++++++++++++++++++++ src/drivers/asus/hid.ts | 21 ++++++++++++++++++++ src/drivers/mouse-types.ts | 6 ++++++ 5 files changed, 94 insertions(+), 1 deletion(-) diff --git a/src/asus/devices.ts b/src/asus/devices.ts index 61502a82..cef02ce0 100644 --- a/src/asus/devices.ts +++ b/src/asus/devices.ts @@ -55,6 +55,8 @@ export interface AsusMouseModel { debounce: boolean; liftOff: boolean; battery: boolean; + /** Firmware exposes the -20..20 degree angle tuning field. */ + angleTuning?: boolean; /** Zone names in wire order. */ zones: readonly string[]; /** Wire byte for each effect the model offers, in display order. */ @@ -123,6 +125,7 @@ const HARPE_ACE_MINI = { maxDpi: 42_000, lightingModes: HARPE_ACE_MINI_MODES, lightingSync: true, + angleTuning: true, } as const; const TUF_M5 = { diff --git a/src/asus/index.ts b/src/asus/index.ts index 0a7e36f0..43e7bdf8 100644 --- a/src/asus/index.ts +++ b/src/asus/index.ts @@ -50,6 +50,8 @@ export interface AsusSettings { pollingRateHz: number; debounceMs: number | null; angleSnapping: boolean; + /** Degrees, -20..20; null when the model has no angle tuning field. */ + angleTuning?: number | null; } export interface AsusProfile { @@ -77,6 +79,8 @@ export type AsusRgb = readonly [number, number, number]; const FIELD_RATE = 0; const FIELD_DEBOUNCE = 1; const FIELD_SNAPPING = 2; +/** Signed int16 degrees, captured from Gear Link's performance page. */ +const FIELD_ANGLE = 3; /** Wire zone ids by position. A model lists only the zones it has, so its index is not the id. */ const ZONE_IDS: readonly string[] = ["Logo", "Scroll wheel", "Underglow"]; @@ -109,6 +113,11 @@ function readUint16LE(data: Uint8Array, offset: number): number { return data[offset] | (data[offset + 1] << 8); } +function readInt16LE(data: Uint8Array, offset: number): number { + const raw = readUint16LE(data, offset); + return raw & 0x8000 ? raw - 0x10000 : raw; +} + function decodeDpi(model: AsusMouseModel, value: number): number { return (value + 1) * model.dpiStep; } @@ -131,7 +140,13 @@ function requireStage(model: AsusMouseModel, stage: number): void { export function asusDecodeSettings(model: AsusMouseModel, data: Uint8Array, booster = false): AsusSettings { const rateOffset = settingOffset(model, FIELD_RATE); - requirePrefix(data, [0x12, 0x04, 0x00], "ASUS settings", settingOffset(model, FIELD_SNAPPING) + 1); + const angleOffset = settingOffset(model, FIELD_ANGLE); + requirePrefix( + data, + [0x12, 0x04, 0x00], + "ASUS settings", + model.angleTuning ? angleOffset + 2 : settingOffset(model, FIELD_SNAPPING) + 1, + ); // Newer firmware keeps a polling-booster value in the high nibble. G-Helper reads it only when the booster is on. const boosterRaw = booster ? data[rateOffset] >> 4 : 0; @@ -148,6 +163,7 @@ export function asusDecodeSettings(model: AsusMouseModel, data: Uint8Array, boos pollingRateHz, debounceMs: debounceRaw >= 0x02 && debounceRaw <= 0x07 ? debounceRaw * 4 + 4 : null, angleSnapping: data[settingOffset(model, FIELD_SNAPPING)] === 0x01, + ...(model.angleTuning ? { angleTuning: readInt16LE(data, angleOffset) } : {}), }; } @@ -287,6 +303,15 @@ export function asusSetAngleSnappingRequest(model: AsusMouseModel, enabled: bool return request(0x51, 0x31, settingField(model, FIELD_SNAPPING), 0x00, enabled ? 0x01 : 0x00); } +/** Gear Link writes signed int16 degrees (-20..20) and saves with 50 03. */ +export function asusSetAngleTuningRequest(degrees: number): Uint8Array { + if (!Number.isInteger(degrees) || degrees < -20 || degrees > 20) { + throw new Error("ASUS angle tuning must be an integer from -20 to 20 degrees."); + } + const raw = degrees < 0 ? degrees + 0x10000 : degrees; + return request(0x51, 0x31, 0x0b, 0x00, raw & 0xff, raw >> 8); +} + export function asusSetDebounceRequest(model: AsusMouseModel, milliseconds: number): Uint8Array { if (!ASUS_DEBOUNCE_MS.some((value) => value === milliseconds)) { throw new Error(`${model.name} debounce must be one of: ${ASUS_DEBOUNCE_MS.join(", ")} ms.`); diff --git a/src/drivers/asus/hid.test.ts b/src/drivers/asus/hid.test.ts index 3dfa2164..1f3f5174 100644 --- a/src/drivers/asus/hid.test.ts +++ b/src/drivers/asus/hid.test.ts @@ -28,6 +28,7 @@ import { asusSaveRequest, asusSetActiveDpiStageRequest, asusSetAngleSnappingRequest, + asusSetAngleTuningRequest, asusSetDebounceRequest, asusSetDpiRequest, asusSetLiftOffRequest, @@ -192,6 +193,21 @@ test("decodes the booster polling value only when the booster is on", () => { assert.equal(asusDecodeSettings(HARPE_ACE, packet("12 04 00 00 0 0 0 0 0 0 0 0 63 00")).pollingRateHz, 1000); }); +test("decodes the Mini angle tuning from the settings block", () => { + const mini = ASUS_MICE.get(0x1b63)!; + const negative = packet("12 04 00 00 ff ff ff ff ff ff ff ff 03 00 02 00 00 00 ec ff"); + const positive = packet("12 04 00 00 ff ff ff ff ff ff ff ff 03 00 02 00 00 00 14 00"); + + assert.equal(asusDecodeSettings(mini, negative).angleTuning, -20); + assert.equal(asusDecodeSettings(mini, positive).angleTuning, 20); +}); + +test("builds the captured angle tuning requests", () => { + assert.deepEqual([...asusSetAngleTuningRequest(-20).subarray(0, 6)], [0x51, 0x31, 0x0b, 0x00, 0xec, 0xff]); + assert.deepEqual([...asusSetAngleTuningRequest(20).subarray(0, 6)], [0x51, 0x31, 0x0b, 0x00, 0x14, 0x00]); + assert.throws(() => asusSetAngleTuningRequest(21), /-20 to 20/); +}); + test("decodes the receiver pair list and firmware", () => { const omni = (hex: string): Uint8Array => packet(hex).subarray(0, ASUS_OMNI_REPORT_SIZE); @@ -252,6 +268,8 @@ class FakeAsusMouse { readonly colors: number[][]; /** Rate index, debounce, angle snapping. */ readonly fields = [3, 7, 0]; + /** Signed degrees in the settings block. */ + angle = 0; profile = 0; stage = 1; readonly zones: number[][]; @@ -319,6 +337,7 @@ class FakeAsusMouse { // An X/Y model's plain block is left blank so only the X/Y read can supply DPI. if (!this.model.dpiXY) this.dpi.forEach((v, i) => r.set([v & 0xff, v >> 8], 4 + i * 2)); this.fields.forEach((v, n) => { r[4 + stages * 2 + n * 2] = v; }); + if (this.model.angleTuning) r.set([this.angle & 0xff, (this.angle >> 8) & 0xff], 4 + stages * 2 + 6); } else if (command === 0x1204 && p[2] === 0x02) { this.dpi.forEach((v, i) => r.set([v & 0xff, v >> 8, v & 0xff, v >> 8], 4 + i * 4)); } else if (command === 0x1204 && p[2] === 0x03) { @@ -336,6 +355,8 @@ class FakeAsusMouse { if (p[2] < stages) { this.dpi[p[2]] = p[4] | (p[5] << 8); if (this.model.dpiColors) this.colors[p[2]] = [p[6], p[7], p[8]]; + } else if (p[2] === 0x0b) { + this.angle = ((p[4] | (p[5] << 8)) << 16) >> 16; } else if (p[2] === 0x09) { this.stage = p[4]; } else { @@ -614,6 +635,23 @@ test("models without a sync control reject setLightingSync", async () => { await assert.rejects(client.setLightingSync(false), /no lighting sync/); }); +test("writes, saves and reads angle tuning", async () => { + const { fake, client } = connect(0x1b63); + + assert.equal(await client.setAngleTuning(-20), -20); + assert.deepEqual(sentWith(fake, 0x51, 0x31, 0x0b)[0].slice(0, 6), [0x51, 0x31, 0x0b, 0x00, 0xec, 0xff]); + + const writeIndex = fake.sent.findIndex((p) => p[0] === 0x51 && p[1] === 0x31 && p[2] === 0x0b); + const saveIndex = fake.sent.findIndex((p) => p[0] === 0x50 && p[1] === 0x03); + assert.ok(saveIndex > writeIndex, "expected a save after the angle write"); +}); + +test("models without angle tuning reject setAngleTuning", async () => { + const { client } = connect(0x1a94); + + await assert.rejects(client.setAngleTuning(0), /no angle tuning/); +}); + test("older models never send the sync control frame", async () => { const { fake, client } = connect(0x1a94); const { lighting } = await client.readStatus(); diff --git a/src/drivers/asus/hid.ts b/src/drivers/asus/hid.ts index 0e0147f5..ab8c7d17 100644 --- a/src/drivers/asus/hid.ts +++ b/src/drivers/asus/hid.ts @@ -40,6 +40,7 @@ import { asusSaveRequest, asusSetActiveDpiStageRequest, asusSetAngleSnappingRequest, + asusSetAngleTuningRequest, asusSetDebounceRequest, asusSetDpiRequest, asusSetLiftOffRequest, @@ -461,6 +462,22 @@ export class AsusHidClient { return enabled; } + async setAngleTuning(degrees: number): Promise { + if (!this.model.angleTuning) { + throw new Error(`The ${this.model.name} has no angle tuning setting.`); + } + + await this.exchange(asusSetAngleTuningRequest(degrees)); + await this.save(); + + const confirmed = (await this.readSettings()).angleTuning; + if (confirmed !== degrees) { + throw new Error(`${this.model.name} did not retain the angle tuning setting.`); + } + + return confirmed; + } + async setDebounceTime(milliseconds: number): Promise { if (!this.model.debounce) { throw new Error(`The ${this.model.name} has no debounce setting.`); @@ -613,6 +630,9 @@ export class AsusHidClient { hideSleepCard: true, hideMotionSync: true, hideRippleControl: true, + angleTuningRange: model.angleTuning ? { min: -20, max: 20 } : undefined, + angleTuningOnPerformance: model.angleTuning ? true : undefined, + hideAdvancedAngleTuning: model.angleTuning ? true : undefined, dpiStageEditor: { maxStages: model.dpiStages, countEditable: false, @@ -644,6 +664,7 @@ export class AsusHidClient { debounceMs: model.debounce ? settings.debounceMs : null, angleSnapping: settings.angleSnapping, + angleTuning: model.angleTuning ? settings.angleTuning : null, liftOffDistance, supportedLiftOffDistances: model.liftOff ? ["Low", "High"] : [], diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index cafc2a88..6a54818c 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -39,6 +39,12 @@ export interface MouseUiHints { hideSignalCard?: boolean; /** Hide auto-sleep when this protocol generation does not expose it. */ hideSleepCard?: boolean; + /** Allowed angle tuning range in degrees; defaults to -30..30 in the UI. */ + angleTuningRange?: { min: number; max: number }; + /** Render angle tuning on the performance tab instead of the advanced card. */ + angleTuningOnPerformance?: boolean; + /** Hide the advanced angle tuning row when it moved to performance. */ + hideAdvancedAngleTuning?: boolean; /** * Render the advanced settings section for a driver outside the brands that * open it by default. The section is the only place the signal, debounce, From 2a544a72523f16ebc63761d7485b782bc2f850ea Mon Sep 17 00:00:00 2001 From: misakasakura Date: Mon, 30 Nov 2026 02:18:32 +0800 Subject: [PATCH 04/24] feat(asus): add battery and power settings for the Harpe Ace Mini --- src/asus/devices.ts | 3 ++ src/asus/index.ts | 96 ++++++++++++++++++++++++++++++++++++ src/drivers/asus/hid.test.ts | 90 +++++++++++++++++++++++++++++++++ src/drivers/asus/hid.ts | 65 ++++++++++++++++++++++-- src/drivers/mouse-types.ts | 11 +++++ 5 files changed, 261 insertions(+), 4 deletions(-) diff --git a/src/asus/devices.ts b/src/asus/devices.ts index cef02ce0..a291e012 100644 --- a/src/asus/devices.ts +++ b/src/asus/devices.ts @@ -55,6 +55,8 @@ export interface AsusMouseModel { debounce: boolean; liftOff: boolean; battery: boolean; + /** Firmware exposes Gear Link's power page (`51 37`): sleep, warning, charge effect. */ + powerConfig?: boolean; /** Firmware exposes the -20..20 degree angle tuning field. */ angleTuning?: boolean; /** Zone names in wire order. */ @@ -125,6 +127,7 @@ const HARPE_ACE_MINI = { maxDpi: 42_000, lightingModes: HARPE_ACE_MINI_MODES, lightingSync: true, + powerConfig: true, angleTuning: true, } as const; diff --git a/src/asus/index.ts b/src/asus/index.ts index 43e7bdf8..61d93406 100644 --- a/src/asus/index.ts +++ b/src/asus/index.ts @@ -73,6 +73,36 @@ export interface AsusBattery { charging: boolean; } +/** Wire idle-time codes from Gear Link's power page, in minutes. */ +export const ASUS_SLEEP_MINUTES = [1, 2, 3, 5, 10] as const; + +/** `0xff` is Gear Link's "never". */ +const ASUS_SLEEP_NEVER = 0xff; + +/** Battery-warning lighting levels the power page offers; 0 turns it off. */ +export const ASUS_LOW_BATTERY_WARNINGS = [0, 10, 20, 30, 40, 50] as const; + +export interface AsusPowerInfo { + percent: number; + charging: boolean; + /** Pack voltage in millivolts. */ + voltageMv: number; + /** Idle minutes before sleep; null when the mouse never sleeps. */ + sleepMinutes: number | null; + lowBatteryWarning: number; + /** 0 for dry cells, 1 for rechargeable. Written back unchanged. */ + batteryType: number; + /** Keep the LEDs on once charging completes. */ + fullChargeEffect: boolean; +} + +export interface AsusPowerConfig { + sleepMinutes: number | null; + lowBatteryWarning: number; + batteryType: number; + fullChargeEffect: boolean; +} + export type AsusRgb = readonly [number, number, number]; /** Rate, debounce and angle snapping follow the DPI stages in the settings block. */ @@ -228,6 +258,32 @@ export function asusDecodeBattery(data: Uint8Array): AsusBattery { }; } +/** + * `12 07` also carries the power page's settings: idle time in byte 5, the + * warning level in byte 6, pack voltage in 7-8, and the charge effect in 11. + */ +export function asusDecodePowerInfo(data: Uint8Array): AsusPowerInfo { + requirePrefix(data, [0x12, 0x07], "ASUS power", 12); + + const sleepCode = data[5]; + const sleepMinutes = sleepCode === ASUS_SLEEP_NEVER + ? null + : ASUS_SLEEP_MINUTES[sleepCode]; + if (sleepMinutes === undefined) { + throw new Error(`Unknown ASUS sleep mode ${sleepCode}.`); + } + + return { + percent: data[4], + charging: data[9] === 1, + voltageMv: readUint16LE(data, 7), + sleepMinutes, + lowBatteryWarning: data[6], + batteryType: data[10], + fullChargeEffect: data[11] === 1, + }; +} + /* --------------------------------- * READ REQUESTS * --------------------------------- */ @@ -260,6 +316,11 @@ export function asusReadBatteryRequest(): Uint8Array { return request(0x12, 0x07); } +/** Same reply as the battery read; the power page decodes the extra fields. */ +export function asusReadPowerInfoRequest(): Uint8Array { + return asusReadBatteryRequest(); +} + /* --------------------------------- * WRITES * --------------------------------- */ @@ -356,6 +417,41 @@ export function asusSetLightingSyncRequest(enabled: boolean): Uint8Array { return request(0x51, 0x42, 0x00, 0x00, enabled ? 0x01 : 0x00); } +/** + * Gear Link's power page writes the whole configuration each time: + * `51 37 00 00 00 `. + */ +export function asusSetPowerConfigRequest(config: AsusPowerConfig): Uint8Array { + const sleepCode = config.sleepMinutes === null + ? ASUS_SLEEP_NEVER + : (ASUS_SLEEP_MINUTES as readonly number[]).indexOf(config.sleepMinutes); + if (sleepCode === -1) { + throw new Error( + `ASUS sleep time must be ${ASUS_SLEEP_MINUTES.join(", ")} minutes or null (never).`, + ); + } + + if (!(ASUS_LOW_BATTERY_WARNINGS as readonly number[]).includes(config.lowBatteryWarning)) { + throw new Error(`ASUS battery warning must be one of: ${ASUS_LOW_BATTERY_WARNINGS.join(", ")}%.`); + } + + if (config.batteryType !== 0 && config.batteryType !== 1) { + throw new Error("ASUS battery type must be 0 (dry cells) or 1 (rechargeable)."); + } + + return request( + 0x51, + 0x37, + 0x00, + 0x00, + sleepCode, + 0x00, + config.lowBatteryWarning, + config.batteryType, + config.fullChargeEffect ? 0x01 : 0x00, + ); +} + export function asusSaveRequest(): Uint8Array { return request(0x50, 0x03); } diff --git a/src/drivers/asus/hid.test.ts b/src/drivers/asus/hid.test.ts index 1f3f5174..b4fcdb4b 100644 --- a/src/drivers/asus/hid.test.ts +++ b/src/drivers/asus/hid.test.ts @@ -13,6 +13,7 @@ import { ASUS_VENDOR_ID, asusDecodeDpiXY, asusDecodeLighting, + asusDecodePowerInfo, asusDecodeProfile, asusDecodeSettings, asusOmniDecodeFirmware, @@ -34,6 +35,7 @@ import { asusSetLiftOffRequest, asusSetLightingRequest, asusSetPollingRateRequest, + asusSetPowerConfigRequest, asusSetProfileRequest, type AsusMouseModel, } from "../../asus/index.ts"; @@ -275,6 +277,12 @@ class FakeAsusMouse { readonly zones: number[][]; liftOff = 0; battery = 80; + /** Power-page block in the `12 07` reply. */ + sleepCode = 2; + warningPercent = 10; + batteryVoltageMv = 4100; + batteryType = 0; + fullChargeEffect = true; booster = false; private listeners = new Set<(event: HIDInputReportEvent) => void>(); @@ -351,6 +359,17 @@ class FakeAsusMouse { r[7] = this.liftOff; } else if (command === 0x1207) { r[4] = this.battery; + r[5] = this.sleepCode; + r[6] = this.warningPercent; + r.set([this.batteryVoltageMv & 0xff, this.batteryVoltageMv >> 8], 7); + r[9] = 0; + r[10] = this.batteryType; + r[11] = this.fullChargeEffect ? 1 : 0; + } else if (command === 0x5137) { + this.sleepCode = p[4]; + this.warningPercent = p[6]; + this.batteryType = p[7]; + this.fullChargeEffect = p[8] === 1; } else if (command === 0x5131) { if (p[2] < stages) { this.dpi[p[2]] = p[4] | (p[5] << 8); @@ -666,6 +685,77 @@ test("the Omni-paired Mini is registered with lighting sync", () => { assert.equal(ASUS_MICE.get(0x1b63)!.lightingSync, true); }); +test("decodes the power page block from 12 07", () => { + const reply = packet("12 07 00 00 64 04 1e 04 10 01 01 00"); + assert.deepEqual(asusDecodePowerInfo(reply), { + percent: 100, + charging: true, + voltageMv: 0x1004, + sleepMinutes: 10, + lowBatteryWarning: 30, + batteryType: 1, + fullChargeEffect: false, + }); + + reply[5] = 0xff; + assert.equal(asusDecodePowerInfo(reply).sleepMinutes, null); + reply[5] = 9; + assert.throws(() => asusDecodePowerInfo(reply), /Unknown ASUS sleep mode/); +}); + +test("builds the captured power configuration request", () => { + expectPrefix( + asusSetPowerConfigRequest({ sleepMinutes: 3, lowBatteryWarning: 20, batteryType: 0, fullChargeEffect: true }), + [0x51, 0x37, 0x00, 0x00, 0x02, 0x00, 0x14, 0x00, 0x01], + ); + expectPrefix( + asusSetPowerConfigRequest({ sleepMinutes: null, lowBatteryWarning: 0, batteryType: 1, fullChargeEffect: false }), + [0x51, 0x37, 0x00, 0x00, 0xff, 0x00, 0x00, 0x01, 0x00], + ); + assert.throws( + () => asusSetPowerConfigRequest({ sleepMinutes: 4, lowBatteryWarning: 10, batteryType: 0, fullChargeEffect: true }), + /sleep time/, + ); + assert.throws( + () => asusSetPowerConfigRequest({ sleepMinutes: 3, lowBatteryWarning: 15, batteryType: 0, fullChargeEffect: true }), + /battery warning/, + ); +}); + +test("writes, saves and reads the power configuration back", async () => { + const { fake, client } = connect(0x1b63); + + const confirmed = await client.setPowerConfig({ sleepMinutes: 5, lowBatteryWarning: 30, fullChargeEffect: false }); + assert.equal(confirmed.sleepMinutes, 5); + assert.equal(confirmed.lowBatteryWarning, 30); + assert.equal(confirmed.fullChargeEffect, false); + assert.equal(confirmed.batteryType, 0); + + assert.deepEqual(sentWith(fake, 0x51, 0x37)[0].slice(0, 9), [0x51, 0x37, 0x00, 0x00, 0x03, 0x00, 0x1e, 0x00, 0x00]); + const writeIndex = fake.sent.findIndex((p) => p[0] === 0x51 && p[1] === 0x37); + const saveIndex = fake.sent.findIndex((p) => p[0] === 0x50 && p[1] === 0x03); + assert.ok(saveIndex > writeIndex, "expected a save after the power write"); +}); + +test("the power page reports its current settings in the status", async () => { + const { client } = connect(0x1b63); + const status = await client.readStatus(); + + assert.equal(status.batteryPercent, 80); + assert.equal(status.batteryVoltageMv, 4100); + assert.equal(status.sleepTimeout, 180); + assert.equal(status.lowBatteryWarning, 10); + assert.equal(status.fullChargeEffect, true); + assert.deepEqual(status.ui?.powerSettings?.sleepMinutes, [1, 2, 3, 5, 10]); + assert.deepEqual(status.ui?.powerSettings?.lowBatteryWarnings, [0, 10, 20, 30, 40, 50]); +}); + +test("models without the power page reject setPowerConfig", async () => { + const { client } = connect(0x1a94); + + await assert.rejects(client.setPowerConfig({ fullChargeEffect: false }), /no power settings/); +}); + test("fails fast when the mouse answers FF AA", async () => { const { fake, client } = connect(0x1a94); fake.asleep = true; diff --git a/src/drivers/asus/hid.ts b/src/drivers/asus/hid.ts index ab8c7d17..9c6040ce 100644 --- a/src/drivers/asus/hid.ts +++ b/src/drivers/asus/hid.ts @@ -2,6 +2,7 @@ import type { AsusOmniDevice, AsusOmniInfo, MouseLighting, MouseLightingMode, Mo import { ASUS_DEBOUNCE_MS, + ASUS_LOW_BATTERY_WARNINGS, ASUS_MICE, ASUS_OMNI_KEYBOARDS, ASUS_OMNI_PRODUCT_ID, @@ -11,6 +12,7 @@ import { ASUS_POLLING_RATES, ASUS_REPORT_ID, ASUS_REPORT_SIZE, + ASUS_SLEEP_MINUTES, ASUS_USAGE, ASUS_USAGE_PAGE, ASUS_VENDOR_ID, @@ -24,13 +26,14 @@ import { asusOmniRebootRequest, asusOmniUnpairRequest, asusDecodeBattery, + asusDecodePowerInfo, asusDecodeDpiColors, asusDecodeDpiXY, asusDecodeLighting, asusDecodeLiftOffDistance, asusDecodeProfile, asusDecodeSettings, - asusReadBatteryRequest, + asusReadPowerInfoRequest, asusReadDpiColorsRequest, asusReadDpiXYRequest, asusReadLiftOffRequest, @@ -47,12 +50,14 @@ import { asusSetLightingRequest, asusSetLightingSyncRequest, asusSetPollingRateRequest, + asusSetPowerConfigRequest, asusSetProfileRequest, - type AsusBattery, type AsusLightingEffect, type AsusLiftOffDistance, type AsusMouseModel, type AsusOmniSlot, + type AsusPowerConfig, + type AsusPowerInfo, type AsusProfile, type AsusRawLightingZone, type AsusRgb, @@ -348,8 +353,16 @@ export class AsusHidClient { return asusDecodeLiftOffDistance(await this.exchange(asusReadLiftOffRequest(), 2)); } - private async readBattery(): Promise { - return asusDecodeBattery(await this.exchange(asusReadBatteryRequest(), 2)); + private async readBattery(): Promise<{ percent: number; charging: boolean; power: AsusPowerInfo | null }> { + const reply = await this.exchange(asusReadPowerInfoRequest(), 2); + return { + ...asusDecodeBattery(reply), + power: this.model.powerConfig ? asusDecodePowerInfo(reply) : null, + }; + } + + private async readPowerInfo(): Promise { + return asusDecodePowerInfo(await this.exchange(asusReadPowerInfoRequest(), 2)); } private async readLighting(): Promise { @@ -521,6 +534,38 @@ export class AsusHidClient { return confirmed; } + /** + * Writes Gear Link's power page. The firmware keeps one configuration block, + * so any field left out of `change` keeps the value the mouse reports now. + */ + async setPowerConfig(change: Partial): Promise { + if (!this.model.powerConfig) { + throw new Error(`The ${this.model.name} has no power settings.`); + } + + const current = await this.readPowerInfo(); + const config: AsusPowerConfig = { + sleepMinutes: change.sleepMinutes === undefined ? current.sleepMinutes : change.sleepMinutes, + lowBatteryWarning: change.lowBatteryWarning ?? current.lowBatteryWarning, + batteryType: change.batteryType ?? current.batteryType, + fullChargeEffect: change.fullChargeEffect ?? current.fullChargeEffect, + }; + + await this.exchange(asusSetPowerConfigRequest(config)); + await this.save(); + + const confirmed = await this.readPowerInfo(); + if ( + confirmed.sleepMinutes !== config.sleepMinutes || + confirmed.lowBatteryWarning !== config.lowBatteryWarning || + confirmed.fullChargeEffect !== config.fullChargeEffect + ) { + throw new Error(`${this.model.name} did not retain the power settings.`); + } + + return confirmed; + } + /** Hands the LEDs to Aura Sync / Windows Dynamic Lighting (true) or back to the onboard effect (false). */ async setLightingSync(enabled: boolean): Promise { if (!this.model.lightingSync) { @@ -612,9 +657,11 @@ export class AsusHidClient { const liftOffDistance = model.liftOff ? await this.readLiftOffDistance() : null; const lightingZones = await this.readLighting(); const battery = model.battery ? await this.readBattery() : null; + const power = battery?.power ?? null; // The battery read answers 0% while the mouse is asleep. const batteryPercent = battery && battery.percent > 0 ? battery.percent : null; + const sleepTimeout = power ? (power.sleepMinutes === null ? 0 : power.sleepMinutes * 60) : null; return { brand: "ASUS", @@ -630,6 +677,12 @@ export class AsusHidClient { hideSleepCard: true, hideMotionSync: true, hideRippleControl: true, + powerSettings: model.powerConfig + ? { + sleepMinutes: ASUS_SLEEP_MINUTES, + lowBatteryWarnings: ASUS_LOW_BATTERY_WARNINGS, + } + : undefined, angleTuningRange: model.angleTuning ? { min: -20, max: 20 } : undefined, angleTuningOnPerformance: model.angleTuning ? true : undefined, hideAdvancedAngleTuning: model.angleTuning ? true : undefined, @@ -647,7 +700,11 @@ export class AsusHidClient { }, batteryPercent, + batteryVoltageMv: power?.voltageMv ?? null, batteryState: battery?.charging ? "Charging" : batteryPercent !== null ? "Discharging" : "Unknown", + sleepTimeout, + lowBatteryWarning: power?.lowBatteryWarning ?? null, + fullChargeEffect: power?.fullChargeEffect ?? null, dpi: settings.dpiStages[profile.activeDpiStage], dpiStages: settings.dpiStages, diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index 6a54818c..ea15b1c6 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -58,6 +58,15 @@ export interface MouseUiHints { forceShowBattery?: boolean; /** Group the device's battery, DPI-indicator, and sleep controls on Overview. */ powerOverview?: boolean; + /** + * Gear Link-style power page controls: the battery warning levels and the + * sleep idle times (minutes) this firmware accepts. The presence of this + * object is what makes the power card render. + */ + powerSettings?: { + sleepMinutes: readonly number[]; + lowBatteryWarnings: readonly number[]; + }; /** * Extra sentence appended to the connected status line, for drivers whose * connection is deliberately limited (e.g. why settings are unavailable). @@ -538,6 +547,8 @@ export interface MouseStatus { angleTuning?: number | null; wheelAcceleration?: boolean | null; lowBatteryWarning?: number | null; + /** Keep the LEDs lit once the battery finishes charging. */ + fullChargeEffect?: boolean | null; remoteLedMode1?: number | null; remoteLedMode2?: number | null; dpiLedMode?: number | null; From 7654b85cf4fbd4f6234d52730b1fc0c51b2d3ea4 Mon Sep 17 00:00:00 2001 From: misakasakura Date: Mon, 30 Nov 2026 20:59:19 +0800 Subject: [PATCH 05/24] feat(asus): add manual surface calibration for the Harpe Ace Mini Send 51 35 01 00 ff, allow 30 s for the firmware to sample movement, and save only a sample whose seventh byte is 01. A failed fa sample is retried once, and a timed-out attempt drains late replies before the retry so the old frame cannot be read as the new sample. Write Low lift-off first and keep LOD controls with the calibration card, matching Gear Link. Surface calibration is write-only, so the app records the result locally. Cover request encoding, retry, late reply, timeout, save failure and unsupported models with tests. --- src/asus/devices.ts | 3 + src/asus/index.ts | 9 +++ src/drivers/asus/hid.test.ts | 114 ++++++++++++++++++++++++++++++++++- src/drivers/asus/hid.ts | 108 +++++++++++++++++++++++++++++++-- src/drivers/mouse-types.ts | 2 + 5 files changed, 227 insertions(+), 9 deletions(-) diff --git a/src/asus/devices.ts b/src/asus/devices.ts index a291e012..5f30d1d2 100644 --- a/src/asus/devices.ts +++ b/src/asus/devices.ts @@ -59,6 +59,8 @@ export interface AsusMouseModel { powerConfig?: boolean; /** Firmware exposes the -20..20 degree angle tuning field. */ angleTuning?: boolean; + /** Firmware exposes Gear Link's manual surface calibration (`51 35 01 00 ff`). */ + surfaceCalibration?: boolean; /** Zone names in wire order. */ zones: readonly string[]; /** Wire byte for each effect the model offers, in display order. */ @@ -129,6 +131,7 @@ const HARPE_ACE_MINI = { lightingSync: true, powerConfig: true, angleTuning: true, + surfaceCalibration: true, } as const; const TUF_M5 = { diff --git a/src/asus/index.ts b/src/asus/index.ts index 61d93406..02bee09c 100644 --- a/src/asus/index.ts +++ b/src/asus/index.ts @@ -386,6 +386,15 @@ export function asusSetLiftOffRequest(value: AsusLiftOffDistance): Uint8Array { return request(0x51, 0x35, 0xff, 0x00, 0xff, value === "High" ? 1 : 0); } +/** + * Starts Gear Link's manual surface calibration. The firmware samples movement + * and only answers `51 35 01 00 ff` once it has enough, so the caller must use a + * much longer response window than a normal settings read. + */ +export function asusStartSurfaceCalibrationRequest(): Uint8Array { + return request(0x51, 0x35, 0x01, 0x00, 0xff); +} + export function asusSetLightingRequest( model: AsusMouseModel, zone: number, diff --git a/src/drivers/asus/hid.test.ts b/src/drivers/asus/hid.test.ts index b4fcdb4b..6e551cdb 100644 --- a/src/drivers/asus/hid.test.ts +++ b/src/drivers/asus/hid.test.ts @@ -37,6 +37,7 @@ import { asusSetPollingRateRequest, asusSetPowerConfigRequest, asusSetProfileRequest, + asusStartSurfaceCalibrationRequest, type AsusMouseModel, } from "../../asus/index.ts"; import { AsusHidClient } from "./hid.ts"; @@ -93,6 +94,7 @@ test("builds the Gladius II requests confirmed on hardware", () => { [asusSetDebounceRequest(GLADIUS_II, 32), [0x51, 0x31, 0x03, 0x00, 0x07]], [asusSetLiftOffRequest("Low"), [0x51, 0x35, 0xff, 0x00, 0xff, 0x00]], [asusSetLiftOffRequest("High"), [0x51, 0x35, 0xff, 0x00, 0xff, 0x01]], + [asusStartSurfaceCalibrationRequest(), [0x51, 0x35, 0x01, 0x00, 0xff]], [asusSetLightingRequest(GLADIUS_II, 0, 0x00, 4, 0xff, 0x00, 0x00), [0x51, 0x28, 0x00, 0x00, 0x00, 0x04, 0xff]], [ asusSetLightingRequest(GLADIUS_II, 2, 0x01, 3, 0x12, 0x34, 0x56, 0x64), @@ -276,6 +278,14 @@ class FakeAsusMouse { stage = 1; readonly zones: number[][]; liftOff = 0; + /** Answer the next N calibration starts with the firmware's failed sample byte. */ + calibrationFailures = 0; + /** Delay the next N calibration-start replies, in timer-shim milliseconds. */ + readonly calibrationReplyDelays: number[] = []; + /** Leave the next N calibration starts unanswered so the driver times out. */ + calibrationSilences = 0; + /** Stop answering once a successful calibration sample has been sent. */ + sleepAfterCalibration = false; battery = 80; /** Power-page block in the `12 07` reply. */ sleepCode = 2; @@ -313,12 +323,20 @@ class FakeAsusMouse { async sendReport(_reportId: number, data: BufferSource): Promise { const request = new Uint8Array(data as ArrayBuffer); this.sent.push(request); + const isCalibrationStart = request[0] === 0x51 && request[1] === 0x35 && request[2] === 0x01; + if (isCalibrationStart && this.calibrationSilences > 0) { + this.calibrationSilences -= 1; + return; + } const reply = this.reply(request); - queueMicrotask(() => { + const dispatch = (): void => { for (const listener of this.listeners) { listener({ reportId: 0, data: new DataView(reply.buffer) } as HIDInputReportEvent); } - }); + }; + const delay = isCalibrationStart ? this.calibrationReplyDelays.shift() ?? 0 : 0; + if (delay > 0) setTimeout(dispatch, delay); + else queueMicrotask(dispatch); } private zoneId(index: number): number { @@ -388,7 +406,18 @@ class FakeAsusMouse { } else if (command === 0x5002) { this.profile = p[2]; } else if (command === 0x5135) { - this.liftOff = p[5]; + if (p[2] === 0x01) { + r.set(p.subarray(0, 5)); + if (this.calibrationFailures > 0) { + this.calibrationFailures -= 1; + r.set([0x00, 0xfa], 5); + } else { + r.set([0x00, 0x01, 0xb0, 0x00, 0x04], 5); + if (this.sleepAfterCalibration) this.asleep = true; + } + } else { + this.liftOff = p[5]; + } } return r; @@ -654,6 +683,85 @@ test("models without a sync control reject setLightingSync", async () => { await assert.rejects(client.setLightingSync(false), /no lighting sync/); }); +test("runs manual surface calibration and saves it", async () => { + const { fake, client } = connect(0x1b63); + const reply = await client.calibrateSurface(); + assert.deepEqual( + [...reply.subarray(0, 10)], + [0x51, 0x35, 0x01, 0x00, 0xff, 0x00, 0x01, 0xb0, 0x00, 0x04], + ); + assert.deepEqual([...fake.sent.at(-1)!.subarray(0, 2)], [0x50, 0x03]); + // Gear Link writes Low lift-off before the sample. + assert.equal(sentWith(fake, 0x51, 0x35, 0xff, 0x00, 0xff, 0x00).length, 1); +}); + +test("retries a failed surface sample and never saves it", async () => { + const { fake, client } = connect(0x1b63); + fake.calibrationFailures = 1; + + const reply = await client.calibrateSurface(); + + assert.deepEqual( + [...reply.subarray(0, 10)], + [0x51, 0x35, 0x01, 0x00, 0xff, 0x00, 0x01, 0xb0, 0x00, 0x04], + ); + assert.equal(sentWith(fake, 0x51, 0x35, 0x01).length, 2); + // One save for the Low lift-off, one for the successful sample. + assert.equal(sentWith(fake, 0x50, 0x03).length, 2); +}); + +test("rejects surface calibration after two failed samples without saving", async () => { + const { fake, client } = connect(0x1b63); + fake.calibrationFailures = 2; + + await assert.rejects(client.calibrateSurface(), /did not complete surface calibration/); + assert.equal(sentWith(fake, 0x51, 0x35, 0x01).length, 2); + // Only the Low lift-off save, never the failed sample. + assert.equal(sentWith(fake, 0x50, 0x03).length, 1); +}); + +test("drops a timed-out attempt's late reply before retrying calibration", async () => { + const { fake, client } = connect(0x1b63); + // The first attempt answers with the failed sample byte, but only after its + // timeout; the retry must not read that late frame as its own sample. + fake.calibrationFailures = 1; + fake.calibrationReplyDelays.push(1); + + const reply = await client.calibrateSurface(); + + assert.deepEqual( + [...reply.subarray(0, 7)], + [0x51, 0x35, 0x01, 0x00, 0xff, 0x00, 0x01], + ); + assert.equal(sentWith(fake, 0x51, 0x35, 0x01).length, 2); + // Low lift-off plus the saved sample, never the late failed frame. + assert.equal(sentWith(fake, 0x50, 0x03).length, 2); +}); + +test("times out a silent calibration and never saves the sample", async () => { + const { fake, client } = connect(0x1b63); + fake.calibrationSilences = 2; + + await assert.rejects(client.calibrateSurface(), /did not answer the HID request/); + assert.equal(sentWith(fake, 0x51, 0x35, 0x01).length, 2); + // Only the Low lift-off save. + assert.equal(sentWith(fake, 0x50, 0x03).length, 1); +}); + +test("reports a failed save after a good sample as a save failure", async () => { + const { fake, client } = connect(0x1b63); + fake.sleepAfterCalibration = true; + + await assert.rejects(client.calibrateSurface(), /sampled the surface but could not save/); + assert.equal(sentWith(fake, 0x51, 0x35, 0x01).length, 1); +}); + +test("models without surface calibration reject calibrateSurface", async () => { + const { client } = connect(0x1a92); + + await assert.rejects(client.calibrateSurface(), /no surface calibration/); +}); + test("writes, saves and reads angle tuning", async () => { const { fake, client } = connect(0x1b63); diff --git a/src/drivers/asus/hid.ts b/src/drivers/asus/hid.ts index 9c6040ce..7ad9c1ef 100644 --- a/src/drivers/asus/hid.ts +++ b/src/drivers/asus/hid.ts @@ -47,6 +47,7 @@ import { asusSetDebounceRequest, asusSetDpiRequest, asusSetLiftOffRequest, + asusStartSurfaceCalibrationRequest, asusSetLightingRequest, asusSetLightingSyncRequest, asusSetPollingRateRequest, @@ -68,6 +69,16 @@ const RESPONSE_TIMEOUT_MS = 1000; const UNPAIR_TIMEOUT_MS = 10_000; +/** Manual surface calibration only answers after the firmware has sampled enough movement. */ +const SURFACE_CALIBRATION_TIMEOUT_MS = 30_000; + +/** + * After a calibration attempt times out, wait this long for a late reply to + * arrive while nothing else is listening. Without it, a reply to the timed-out + * attempt can be picked up as the retry's sample and misread as a failure. + */ +const SURFACE_CALIBRATION_DRAIN_MS = 200; + const UNPAIR_POLL_MS = 500; const OMNI_NAME = "ROG Omni receiver"; @@ -108,6 +119,9 @@ const ASUS_WAKE_RETRY_MS = 40; /** `FF AA`: the mouse is asleep, out of range, or refused the request. */ class AsusSleepError extends Error {} +/** No reply arrived before the command's timeout. */ +class AsusTimeoutError extends Error {} + function hexByte(value: number): string { return value.toString(16).padStart(2, "0"); } @@ -211,23 +225,23 @@ export class AsusHidClient { } /** Sends `request` and resolves with the first reply echoing its first `matchLength` bytes. */ - private async exchange(request: Uint8Array, matchLength = 3, reportId = this.mouseReportId): Promise { + private async exchange(request: Uint8Array, matchLength = 3, reportId = this.mouseReportId, timeoutMs = RESPONSE_TIMEOUT_MS): Promise { return this.run(async () => { await this.open(); try { - return await this.exchangeOnce(request, matchLength, reportId); + return await this.exchangeOnce(request, matchLength, reportId, timeoutMs); } catch (error) { if (!(error instanceof AsusSleepError)) throw error; // The first command after an idle spell is often applied by the firmware but // answered with FF AA while the mouse wakes up. One retry absorbs that; a // second FF AA is a real refusal. await wait(ASUS_WAKE_RETRY_MS); - return this.exchangeOnce(request, matchLength, reportId); + return this.exchangeOnce(request, matchLength, reportId, timeoutMs); } }); } - private exchangeOnce(request: Uint8Array, matchLength: number, reportId: number): Promise { + private exchangeOnce(request: Uint8Array, matchLength: number, reportId: number, timeoutMs: number): Promise { const payload = this.payload(request, reportId); return new Promise((resolve, reject) => { @@ -258,8 +272,8 @@ export class AsusHidClient { const timer = setTimeout(() => { this.device.removeEventListener("inputreport", listener); - reject(new Error(`${this.label} did not answer the HID request.`)); - }, RESPONSE_TIMEOUT_MS); + reject(new AsusTimeoutError(`${this.label} did not answer the HID request.`)); + }, timeoutMs); this.device.addEventListener("inputreport", listener); @@ -512,6 +526,87 @@ export class AsusHidClient { return normalized; } + /** Resolves once no reply has arrived on `reportId` for `quietMs`. */ + private async drainInput(quietMs: number, reportId: number): Promise { + await this.run(async () => { + await this.open(); + await new Promise((resolve) => { + let timer: ReturnType | undefined; + const finish = (): void => { + if (timer !== undefined) clearTimeout(timer); + this.device.removeEventListener("inputreport", listener); + resolve(); + }; + const arm = (): void => { + if (timer !== undefined) clearTimeout(timer); + timer = setTimeout(finish, quietMs); + }; + const listener = (event: HIDInputReportEvent): void => { + if (event.reportId === reportId) arm(); + }; + this.device.addEventListener("inputreport", listener); + arm(); + }); + }); + } + + /** + * Gear Link's manual surface calibration. The firmware samples the surface + * while the user moves the mouse and only replies once it has enough data; + * `save()` then commits the result. At offset 6 (the seventh byte) the reply + * is `01` on a usable sample and `fa` when the firmware did not collect + * enough movement. Gear + * Link retries that once and never saves the failed sample, so this does the + * same instead of persisting a run the firmware rejected. + */ + async calibrateSurface(): Promise { + if (!this.model.surfaceCalibration) { + throw new Error(`The ${this.model.name} has no surface calibration.`); + } + + // Gear Link writes Low lift-off before every manual run, so start from the + // same sensor state instead of whatever LOD the user had selected. + if (this.model.liftOff) await this.setLiftOffDistance("Low"); + + // A timed-out attempt can still answer later; drain the channel before the + // retry so that frame is dropped instead of being read as the new sample. + let timedOut = false; + + for (let attempt = 0; attempt < 2; attempt += 1) { + if (timedOut) await this.drainInput(SURFACE_CALIBRATION_DRAIN_MS, this.mouseReportId); + timedOut = false; + + let response: Uint8Array; + try { + response = await this.exchange( + asusStartSurfaceCalibrationRequest(), + 5, + this.mouseReportId, + SURFACE_CALIBRATION_TIMEOUT_MS, + ); + } catch (error) { + if (error instanceof AsusTimeoutError && attempt === 0) { + timedOut = true; + continue; + } + throw error; + } + + if (response[6] === 0x01) { + try { + await this.save(); + } catch { + // The sample is good but the firmware never confirmed the save, so + // do not report this as a sampling failure. + throw new Error(`${this.model.name} sampled the surface but could not save the calibration.`); + } + return response; + } + } + + throw new Error(`${this.model.name} did not complete surface calibration. Keep moving the mouse and try again.`); + } + async setLiftOffDistance(value: "Low" | "Medium" | "High"): Promise { const { name } = this.model; @@ -677,6 +772,7 @@ export class AsusHidClient { hideSleepCard: true, hideMotionSync: true, hideRippleControl: true, + surfaceCalibration: model.surfaceCalibration ? true : undefined, powerSettings: model.powerConfig ? { sleepMinutes: ASUS_SLEEP_MINUTES, diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index ea15b1c6..83d52d11 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -21,6 +21,8 @@ export interface MouseUiHints { valuesVerified?: boolean; /** Hide the Low LOD option. */ hideLodLow?: boolean; + /** Firmware exposes Gear Link's manual surface calibration; the UI moves LOD into that card. */ + surfaceCalibration?: boolean; /** Disable LOD controls while gamingSurfaceMode is "Off". */ lodRequiresSurface?: boolean; /** Hide poll rates not listed in supportedPollingRates. */ From 4d18b0bfef57bce7d463d6985288e8b2914be5ec Mon Sep 17 00:00:00 2001 From: misakasakura Date: Mon, 30 Nov 2026 20:59:27 +0800 Subject: [PATCH 06/24] feat(asus): add button remapping for the Harpe Ace Mini Encode Gear Link's 51 21 00 00