From 453481f34c254f1043d21f39acbcc637555348f8 Mon Sep 17 00:00:00 2001 From: Snowy-Fluffy Date: Thu, 3 Dec 2026 22:28:55 +0000 Subject: [PATCH 1/8] feat(mchose): support the Ace 68 V2 III on the glw protocol - Catalogue the Ace 68 V2 III (0x3837:0x3024) under MCHOSE's second vendor id. It answers the same 55/AA command set on the same usage-0001:0000 collection; its bootloader (0x3025) is not claimed. - Add its model entry: the Air's 68-key drawing and lighting bytes, no light box. - Read on hardware (firmware 116, Linux hidraw): identity, profile table, function config, lighting, key travel, keymap and key colours; the layout resolved from the keyboard's default keymap matches the static Ace 68 table. A lighting write and a per-key colour write were confirmed by read-back and restored byte-for-byte. - Polling rates, actuation writes, keymaps, macros and calibration are not exercised on this model, so it stays catalogued as unverified. --- README.md | 10 +++++++++- docs/mchose-support.md | 26 ++++++++++++++++++++++++-- src/drivers/mchose/hid.test.ts | 19 +++++++++++++++++++ src/mchose/models.ts | 15 ++++++++++++++- src/mchose/products.ts | 5 ++++- src/mchose/protocol.test.ts | 2 ++ 6 files changed, 72 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 4b8c221..5a6fd52 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ filters, the driver registry, and shared status types live under | ATK (Hall-effect and RS series) | `@openmouse/keyboard-protocol/atk` | | Glorious (stock firmware) | `@openmouse/keyboard-protocol/glorious` | | VIA (QMK/VIA firmware, any vendor) | `@openmouse/keyboard-protocol/via` | -| MCHOSE (Ace 68 Air, Mix 87 III) | `@openmouse/keyboard-protocol/mchose` | +| MCHOSE (Ace 68 Air, Ace 68 V2 III, Mix 87 III) | `@openmouse/keyboard-protocol/mchose` | The VIA driver matches the raw-HID collection (`0xFF60:0x61`) on any board and covers keymaps, keycode names, encoders, macros and custom-menu lighting. Layout @@ -146,6 +146,14 @@ confirmed by read-back. It was tested on an Air III with firmware 116; the ledger lists exactly which reads and writes were exercised on hardware. The Air II (`0x2120`) is catalogued from the same bundle and is untested. +The Ace 68 V2 III (`0x3837:0x3024`, firmware 116) is the same `glw` command set +under MCHOSE's other vendor id, with the Air's 68-key layout and lighting bytes +but no light box. Through the driver its identity, profile table, function +config, lighting, key travel, keymap and key colours were read on hardware, and +a lighting and a per-key colour write were confirmed by read-back and restored. +It is catalogued as unverified until the rest is exercised. The bootloader +enumerates as `0x3837:0x3025` and is not claimed. + The Mix 87 III (`0x3837:0x300D`) is the same `glw` command set under MCHOSE's other vendor id; its identity, profile table, function config, key travel, profile names and default keymap were read on firmware 1.22, and its 90-key diff --git a/docs/mchose-support.md b/docs/mchose-support.md index d717021..ebe1ba9 100644 --- a/docs/mchose-support.md +++ b/docs/mchose-support.md @@ -5,17 +5,20 @@ configurator (`https://www.mchose.com.cn/cizhou/CZ_SHARED_DATA/`, `main.7d734adfcc65efb81c4d.js`, fetched 2026-10-31), which calls this command set the `glw` family, and checked against an **Ace 68 Air III** (`0x41E4:0x2132`, firmware 116, controller `GL8KH-PRO`) and a **Mix 87 III** -(`0x3837:0x300D`, firmware 1.22, controller `GL8KH-PRO`) over USB on Windows. +(`0x3837:0x300D`, firmware 1.22, controller `GL8KH-PRO`) over USB on Windows, and +an **Ace 68 V2 III** (`0x3837:0x3024`, firmware 116) over USB on Linux (hidraw). Most MCHOSE `0x3837` boards speak a different protocol (`qhw`, report id `0x4D`) and are not covered. The Mix 87 III is the exception: it answers the -same `glw` frames on the same usage-`0x0001:0x0000` collection. +same `glw` frames on the same usage-`0x0001:0x0000` collection, and so does the +Ace 68 V2 III. | Model | Vendor:product | Status | | --- | --- | --- | | Ace 68 Air III | `0x41E4:0x2132` | Verified on hardware (firmware 116); "Hardware checks" lists what was exercised | | Ace 68 Air II | `0x41E4:0x2120` | Same layout, keymap and command set in the vendor bundle; not tested | | Mix 87 III | `0x3837:0x300D` | Identity, profile table, function config, key travel, profile names and default keymap read on firmware 1.22; writes not exercised | +| Ace 68 V2 III | `0x3837:0x3024` | Identity, profile table, function config, lighting, key travel, keymap and key colours read on firmware 116; a lighting and a key-colour write confirmed and restored; the rest not exercised | ## Transport @@ -147,6 +150,11 @@ key with a deeper factory actuation, 2.50 mm, and sits in slot 46). `mchoseLayoutFromDefaults` resolves the slots from the connected keyboard; `MCHOSE_ACE68_LAYOUT` is the same table read from an Air III on firmware 116. +The Ace 68 V2 III uses the same 68-key drawing and slot numbers as the Air: all +68 keys resolved from its own default keymap (firmware 116) match +`MCHOSE_ACE68_LAYOUT` slot for slot. It has no light box, so its model lists no +side effects. + The Mix 87 III uses the vendor's 90-key drawing (87 keys plus the G1/RT/Light function keys). Its default keymap on firmware 1.22 places every ordinary key; the three function keys are `0xF0` actions the usage join cannot name, so the @@ -259,3 +267,17 @@ change written, read back and then restored: Not exercised: how advanced keys and macros behave when typed, the Air II, wireless models. + +On the Ace 68 V2 III (`0x3837:0x3024`, firmware 116), through +`MchoseKeyboardHidClient` over `/dev/hidraw` on Linux: + +- Info, profile table, function config, lighting, key travel, keymap and key + colour reads decode; the layout resolved from the default keymap matches the + static Ace 68 table. +- Backlight brightness written and read back, and one per-key colour written + straight after that settings write and again 2.5 s later, each confirmed by + read-back; then both restored, byte-identical to a dump taken first. + +Not exercised: polling rate (the supported list is copied from the Air), +actuation and rapid-trigger writes, keymaps, macros, advanced keys, calibration +and factory reset on this model. diff --git a/src/drivers/mchose/hid.test.ts b/src/drivers/mchose/hid.test.ts index fdaa39d..16f7ccd 100644 --- a/src/drivers/mchose/hid.test.ts +++ b/src/drivers/mchose/hid.test.ts @@ -144,6 +144,25 @@ test("recognises the Mix 87 III on MCHOSE's other vendor id", async () => { assert.ok(!MchoseKeyboardHidClient.isSupported(other.hid), "another product on the Mix vendor id is not a Mix 87"); }); +test("recognises the Ace 68 V2 III on MCHOSE's other vendor id", async () => { + const fake = new FakeMchoseKeyboard(); + fake.vendorId = 0x3837; + fake.productId = 0x3024; + assert.ok(MchoseKeyboardHidClient.isSupported(fake.hid)); + assert.equal(deviceBrand(createSupportedClient(fake.hid)!), "MCHOSE"); + assert.ok(MCHOSE_HID_FILTERS.some((filter) => + filter.vendorId === 0x3837 && filter.productId === 0x3024 && filter.usagePage === 1 && filter.usage === 0)); + const status = await new MchoseKeyboardHidClient(fake.hid).readStatus(); + assert.equal(status.name, "Ace 68 V2 III"); + assert.equal(status.mchose?.layout?.length, 68); + assert.equal(status.mchose?.layout?.find((key) => key.label === "E")?.index, 0); + // The bootloader enumerates as 0x3025 and is not a configuration interface. + const boot = new FakeMchoseKeyboard(); + boot.vendorId = 0x3837; + boot.productId = 0x3025; + assert.ok(!MchoseKeyboardHidClient.isSupported(boot.hid)); +}); + test("readStatus reads identity, the active profile, performance and key travel", async () => { const fake = new FakeMchoseKeyboard(); const status = await new MchoseKeyboardHidClient(fake.hid).readStatus(); diff --git a/src/mchose/models.ts b/src/mchose/models.ts index 503c647..fd76208 100644 --- a/src/mchose/models.ts +++ b/src/mchose/models.ts @@ -37,7 +37,20 @@ const MIX87_III: MchoseModel = { fullTravel: 341, }; -const MODELS: Readonly> = { 0x2132: ACE68_AIR, 0x2120: ACE68_AIR, 0x300d: MIX87_III }; +/** The Ace 68 V2 III: the Air's 68-key drawing and lighting bytes, but no light box. */ +const ACE68_V2_III: MchoseModel = { + layout: MCHOSE_ACE68_LAYOUT, + effects: { main: MCHOSE_ACE68_EFFECTS, side: null }, + switches: MCHOSE_ACE68_SWITCHES, + fullTravel: 341, +}; + +const MODELS: Readonly> = { + 0x2132: ACE68_AIR, + 0x2120: ACE68_AIR, + 0x300d: MIX87_III, + 0x3024: ACE68_V2_III, +}; /** The model details for a product id from `MCHOSE_PRODUCTS`. */ export function mchoseModel(productId: number): MchoseModel | undefined { diff --git a/src/mchose/products.ts b/src/mchose/products.ts index e94663d..6202920 100644 --- a/src/mchose/products.ts +++ b/src/mchose/products.ts @@ -1,6 +1,6 @@ /** MCHOSE magnetic keyboards this package knows, and the collection their configuration uses. */ export const MCHOSE_KEYBOARD_VENDOR_ID = 0x41e4; -/** The M HUB boards that enumerate under MCHOSE's other USB vendor id. */ +/** The M HUB boards that enumerate under MCHOSE's other USB vendor id (Mix 87 III, Ace 68 V2 III). */ export const MCHOSE_MIX87_VENDOR_ID = 0x3837; export const MCHOSE_CONFIG_USAGE_PAGE = 0x0001; export const MCHOSE_CONFIG_USAGE = 0x0000; @@ -23,6 +23,9 @@ export const MCHOSE_PRODUCTS: readonly MchoseProduct[] = [ // M HUB ARM board on the same 55/AA command set (command 0x03 answers // firmware 1.22 on hardware); the vendor bundle calls it Mix 87 III. { vendorId: MCHOSE_MIX87_VENDOR_ID, name: "Mix 87 III", productId: 0x300d, pollingRatesHz: [1000, 2000, 4000, 8000], verified: false }, + // Same 55/AA command set, layout and lighting bytes as the Ace 68 Air, with + // no light box; the vendor bundle calls it Ace 68 V2 (usage-0001:0000 collection). + { vendorId: MCHOSE_MIX87_VENDOR_ID, name: "Ace 68 V2 III", productId: 0x3024, pollingRatesHz: [1000, 2000, 4000, 8000], verified: false }, ]; export const MCHOSE_PRODUCT_IDS: readonly number[] = /* @__PURE__ */ MCHOSE_PRODUCTS.map((entry) => entry.productId); diff --git a/src/mchose/protocol.test.ts b/src/mchose/protocol.test.ts index 021793b..04c89a1 100644 --- a/src/mchose/protocol.test.ts +++ b/src/mchose/protocol.test.ts @@ -172,6 +172,8 @@ test("the catalog and layout cover the Ace 68 Air", () => { assert.equal(mchoseProduct(0x41e4, 0x2132)?.verified, true); assert.equal(mchoseProduct(0x41e4, 0x2120)?.verified, false); assert.equal(mchoseProduct(0x3837, 0x2132), undefined); + assert.equal(mchoseProduct(0x3837, 0x3024)?.name, "Ace 68 V2 III"); + assert.equal(mchoseProduct(0x3837, 0x3024)?.verified, false); assert.equal(MCHOSE_ACE68_LAYOUT.length, 68); const indexes = MCHOSE_ACE68_LAYOUT.map((key) => key.index); assert.equal(new Set(indexes).size, 68, "every key has its own slot"); From 640f10190a3b83faaea6b99ca3e4d3dd6737b4a1 Mon Sep 17 00:00:00 2001 From: Snowy-Fluffy Date: Thu, 3 Dec 2026 23:45:55 +0000 Subject: [PATCH 2/8] feat(mchose): write key mode 2 (Quick Trigger with the Rapid trigger switch) - Add `keyMode` (0-2) to the key travel update, named after the M HUB trigger page. Mode 2 is how an Ace 68 V2 III ships, and the existing `rapidTrigger` boolean could only write 0 or 1. - Document the three modes and which dead zone the page calls Top and Bottom. Both were read from the frames the page wrote while its switches were changed on an Ace 68 V2 III, which was then restored byte for byte. --- docs/mchose-support.md | 9 ++++++++- src/mchose/codec.ts | 14 +++++++++++++- src/mchose/protocol.test.ts | 5 +++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/docs/mchose-support.md b/docs/mchose-support.md index ebe1ba9..daa204f 100644 --- a/docs/mchose-support.md +++ b/docs/mchose-support.md @@ -119,7 +119,7 @@ read, then compare all 64 bytes on read-back. | Byte | Field | | --- | --- | | 0 | High nibble `0xA` on every captured key (kept as read), low nibble switch type | -| 1 | Low nibble key mode (0 normal, 1 rapid trigger), high nibble priority | +| 1 | Low nibble key mode, high nibble priority | | 2, 3 bit 0 | Actuation, 9 bits, stored minus one | | 3 bits 3-4 / 1-2 | Press / release rapid-trigger precision | | 4, 5 bit 0 | Rapid-trigger press, 9 bits, stored minus one | @@ -127,6 +127,13 @@ read, then compare all 64 bytes on read-back. | 6, 7 bit 0 | Rapid-trigger release, 9 bits, stored minus one | | 7 bits 1-7 | Release dead zone | +Key mode, from the M HUB trigger page on an Ace 68 V2 III (each switch was +turned on a key and the frames it wrote were read): 0 is a fixed actuation point +(Quick Trigger off), 1 is Quick Trigger (RT) with the page's "Rapid trigger" +switch off, and 2 is Quick Trigger with that switch on, which is how the +keyboard ships. In the page's "Key Deadzone" the Top value is the press dead +zone (byte 5) and Bottom is the release dead zone (byte 7). + Units, from the vendor app's conversions: - Actuation and dead zones are 0.01 mm. The app allows actuation from diff --git a/src/mchose/codec.ts b/src/mchose/codec.ts index a3d1fbf..81ba540 100644 --- a/src/mchose/codec.ts +++ b/src/mchose/codec.ts @@ -490,7 +490,12 @@ export function mchoseDisplayProfileName(name: string | null): string | null { } /** Key mode values the vendor app writes; the firmware may hold others. */ -export const MCHOSE_KEY_MODE = { normal: 0, rapidTrigger: 1 } as const; +/** + * Key modes, named as the M HUB trigger page shows them: 0 is a fixed + * actuation point, 1 is "Quick Trigger (RT)", and 2 is Quick Trigger with the + * page's "Rapid trigger" switch on (the factory setting on the Ace 68 V2 III). + */ +export const MCHOSE_KEY_MODE = { normal: 0, rapidTrigger: 1, rapidTriggerSwitch: 2 } as const; /** * One 8-byte key-travel record. Distances are the firmware's own steps: @@ -601,7 +606,10 @@ export function mchoseMmToSteps(mm: number, stepMm = MCHOSE_TRAVEL_STEP_MM): num export interface MchoseKeyTravelUpdate { index: number; actuation?: number; + /** Quick Trigger on (mode 1) or off (mode 0); `keyMode` wins when both are given. */ rapidTrigger?: boolean; + /** The key mode itself, 0-2 (see `MCHOSE_KEY_MODE`). */ + keyMode?: number; rapidTriggerPress?: number; rapidTriggerRelease?: number; pressDeadzone?: number; @@ -718,6 +726,10 @@ export function applyMchoseKeyTravelUpdate(key: MchoseKeyTravel, update: MchoseK next.actuation = update.actuation; } if (update.rapidTrigger !== undefined) next.keyMode = update.rapidTrigger ? MCHOSE_KEY_MODE.rapidTrigger : MCHOSE_KEY_MODE.normal; + if (update.keyMode !== undefined) { + if (!Number.isInteger(update.keyMode) || update.keyMode < 0 || update.keyMode > MCHOSE_KEY_MODE.rapidTriggerSwitch) throw new RangeError("Key mode must be 0-2."); + next.keyMode = update.keyMode; + } if (update.rapidTriggerPress !== undefined) { assertRange(update.rapidTriggerPress, mchoseRapidTriggerStep(next.pressPrecision), "Rapid-trigger press"); next.rapidTriggerPress = update.rapidTriggerPress; diff --git a/src/mchose/protocol.test.ts b/src/mchose/protocol.test.ts index 04c89a1..b45e657 100644 --- a/src/mchose/protocol.test.ts +++ b/src/mchose/protocol.test.ts @@ -130,6 +130,11 @@ test("key edits are range-checked against the vendor app's limits", () => { assert.throws(() => applyMchoseKeyTravelUpdate(key, { index: 0, actuation: 9 }), RangeError); assert.throws(() => applyMchoseKeyTravelUpdate(key, { index: 0, actuation: 341 }), RangeError); assert.throws(() => applyMchoseKeyTravelUpdate(key, { index: 0, rapidTriggerPress: 1 }), RangeError); + // The three key modes the M HUB trigger page writes. + for (const keyMode of [0, 1, 2]) assert.equal(applyMchoseKeyTravelUpdate(key, { index: 0, keyMode }).keyMode, keyMode); + assert.equal(applyMchoseKeyTravelUpdate(key, { index: 0, rapidTrigger: false, keyMode: 2 }).keyMode, 2, "keyMode wins"); + assert.throws(() => applyMchoseKeyTravelUpdate(key, { index: 0, keyMode: 3 }), RangeError); + assert.throws(() => applyMchoseKeyTravelUpdate(key, { index: 0, keyMode: 1.5 }), RangeError); assert.throws(() => applyMchoseKeyTravelUpdate(key, { index: 0, releaseDeadzone: 51 }), RangeError); const fine = { ...key, pressPrecision: 2 }; assert.equal(applyMchoseKeyTravelUpdate(fine, { index: 0, rapidTriggerPress: 500 }).rapidTriggerPress, 500); From 785ddfa8240bf461e60c14bb4a53b0f39fe9dc67 Mon Sep 17 00:00:00 2001 From: Snowy-Fluffy Date: Thu, 3 Dec 2026 23:53:44 +0000 Subject: [PATCH 3/8] feat(mchose): keep every profile's name list alike - Write a renamed profile's name list to all four profile custom areas, as the M HUB page does (it was seen writing the same list at 336, 1360, 2384 and 3408 when a profile was renamed); the driver wrote only profile 0's copy. - Read each copy back before reporting the rename. --- src/drivers/mchose/hid.test.ts | 4 +++- src/drivers/mchose/hid.ts | 15 ++++++++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/drivers/mchose/hid.test.ts b/src/drivers/mchose/hid.test.ts index 16f7ccd..eabe815 100644 --- a/src/drivers/mchose/hid.test.ts +++ b/src/drivers/mchose/hid.test.ts @@ -303,7 +303,9 @@ test("advanced-key slots, colours, names and calibration", async () => { assert.deepEqual(colors[3], { r: 1, g: 2, b: 3 }); const names = await client.setProfileName(2, "Aim"); assert.equal(names[2], "Aim"); - assert.deepEqual(fake.writes(MCHOSE_COMMAND.setCustomData).map((frame) => frame[4]), [56], "only the frames the JSON needs"); + assert.deepEqual(fake.writes(MCHOSE_COMMAND.setCustomData).map((frame) => frame[4]), [56, 56, 56, 56], "only the frames the JSON needs, once per profile's copy"); + const copies = [0, 1, 2, 3].map((slot) => fake.custom.slice(1024 * slot + 336, 1024 * slot + 336 + 56).join(",")); + assert.ok(copies.every((copy) => copy === copies[0]), "every profile holds the same list"); await client.calibrate("start"); await client.calibrate("end"); assert.deepEqual(fake.calibration, [MCHOSE_COMMAND.startCalibration, MCHOSE_COMMAND.endCalibration]); diff --git a/src/drivers/mchose/hid.ts b/src/drivers/mchose/hid.ts index 1c457f1..7e8be70 100644 --- a/src/drivers/mchose/hid.ts +++ b/src/drivers/mchose/hid.ts @@ -7,6 +7,7 @@ import { MCHOSE_FUNC_CONFIG_SIZE, MCHOSE_INFO_SIZE, MCHOSE_KEY_TRAVEL_SIZE, + MCHOSE_CUSTOM_AREA_SIZE, MCHOSE_PROFILE_COUNT, MCHOSE_REPORT_ID, applyMchoseKeyTravelUpdate, @@ -510,7 +511,7 @@ export class MchoseKeyboardHidClient { return this.serialized(async () => decodeMchoseProfileNames(await this.readNameBytes())); } - /** Rename one profile; the other names are written back as read. */ + /** Rename one profile; the other names are written back as read, in every profile's copy of the list. */ setProfileName(profile: number, name: string): Promise<(string | null)[]> { return this.serialized(async () => { MchoseKeyboardHidClient.assertProfile(profile); @@ -520,10 +521,14 @@ export class MchoseKeyboardHidClient { const padded = encodeMchoseJson(names, MCHOSE_PROFILE_NAMES_SIZE); const length = Math.min(MCHOSE_PROFILE_NAMES_SIZE, MCHOSE_MAX_CHUNK * Math.ceil((padded.indexOf(0xff) + 1) / MCHOSE_MAX_CHUNK)); const next = padded.slice(0, length); - await this.write(mchoseWriteFrames(MCHOSE_COMMAND.setCustomData, MCHOSE_PROFILE_NAMES_OFFSET, next)); - const confirmed = await this.readNameBytes(); - if (next.some((byte, index) => byte !== confirmed[index])) throw new Error("The MCHOSE keyboard did not retain the profile name."); - return decodeMchoseProfileNames(confirmed); + // The vendor app keeps the same list in every profile's custom area, so the copies stay alike. + for (let slot = 0; slot < MCHOSE_PROFILE_COUNT; slot += 1) { + const offset = MCHOSE_CUSTOM_AREA_SIZE * slot + MCHOSE_PROFILE_NAMES_OFFSET; + await this.write(mchoseWriteFrames(MCHOSE_COMMAND.setCustomData, offset, next)); + const copy = await this.read(MCHOSE_COMMAND.getCustomData, offset, next.length); + if (next.some((byte, index) => byte !== copy[index])) throw new Error("The MCHOSE keyboard did not retain the profile name."); + } + return decodeMchoseProfileNames(await this.readNameBytes()); }); } From 83a8cc2d91bdd6fc4f9ca0d8c9d8af58061f7762 Mon Sep 17 00:00:00 2001 From: Snowy-Fluffy Date: Fri, 4 Dec 2026 00:13:08 +0000 Subject: [PATCH 4/8] feat(mchose): add and remove profiles - createProfile copies a profile (settings, lighting, per-key colours, travel, the four keymap layers, advanced keys and the custom area) into the first free slot under a new name, checks every block by reading it back (writing it again after a pause if it differs), and lists the profile in the table last, so the keyboard never shows a half-written one. - deleteProfile takes a profile off the table and clears its name. The active and the last profile cannot be removed. - The table edits follow what the M HUB page writes, seen on an Ace 68 V2 III while a profile was deleted and another created: the freed slot moves behind the used ones, the active position follows its profile, and three profiles is the most. --- src/drivers/mchose/hid.test.ts | 42 ++++++++++++ src/drivers/mchose/hid.ts | 116 +++++++++++++++++++++++++++++---- src/mchose/codec.ts | 45 +++++++++++++ src/mchose/protocol.test.ts | 21 ++++++ 4 files changed, 210 insertions(+), 14 deletions(-) diff --git a/src/drivers/mchose/hid.test.ts b/src/drivers/mchose/hid.test.ts index eabe815..a44acc2 100644 --- a/src/drivers/mchose/hid.test.ts +++ b/src/drivers/mchose/hid.test.ts @@ -382,3 +382,45 @@ test("closing while the device is still opening leaves it closed", async () => { fake.open = async () => { fake.opened = true; }; assert.ok((await client.readBase()).profileCount > 0, "a later open starts a new session"); }); + +test("a profile is added as a copy and removed again, in the order the page writes", async () => { + const fake = new FakeMchoseKeyboard(); + fake.base = [0, 2, 0, 2, 1, 3, 0xaa, 0xbb, ...new Array(48).fill(0xa2)]; + // Give profile 0 recognisable data in every block that is copied. + fake.config[0]![20] = 9; + fake.config[0]![1] = 0x50 | 0x01; // the Windows Fn layer is showing + fake.colors.splice(0, 3, 1, 2, 3); + fake.travel[0]!.splice(8, 8, 0xa1, 0x02, 0x4a, 0x00, 0x4a, 0x1e, 0x4a, 0x1e); + fake.keymap.splice(3, 3, 0x10, 0x00, 0x14); + fake.keymap.splice(512 * 3 + 6, 3, 0x10, 0x00, 0x15); + fake.dks.splice(0, 2, 7, 8); + fake.modTap.splice(0, 2, 5, 6); + fake.toggle.splice(0, 2, 3, 4); + fake.custom.splice(700, 2, 0x41, 0x42); + const client = new MchoseKeyboardHidClient(fake.hid); + + const created = await client.createProfile(0, "Copy"); + assert.deepEqual([created.activeProfile, created.profileCount], [1, 3], "slot 1 is the first free one and becomes active"); + assert.equal(fake.config[1]![20], 9, "settings are copied"); + assert.equal(fake.config[1]![1] & 0x0f, 4, "the layer nibble follows the slot and the copy starts on its base layer"); + assert.deepEqual(fake.colors.slice(512, 515), [1, 2, 3]); + assert.deepEqual(fake.travel[1]!.slice(8, 16), fake.travel[0]!.slice(8, 16)); + assert.deepEqual(fake.keymap.slice(2048 + 3, 2048 + 6), [0x10, 0x00, 0x14], "layer 0 of the new slot"); + assert.deepEqual(fake.keymap.slice(2048 + 512 * 3 + 6, 2048 + 512 * 3 + 9), [0x10, 0x00, 0x15], "layer 3 of the new slot"); + assert.deepEqual([fake.dks[768], fake.modTap[256], fake.toggle[128]], [7, 5, 3]); + assert.deepEqual(fake.custom.slice(1024 + 700, 1024 + 702), [0x41, 0x42]); + assert.equal((await client.readProfileNames())[1], "Copy"); + // The profile table is written last. + const order = fake.sent.filter((frame) => frame[0] === 0x55).map((frame) => frame[1]); + assert.equal(order.lastIndexOf(MCHOSE_COMMAND.setBase) > order.lastIndexOf(MCHOSE_COMMAND.setKeyTravel), true); + await assert.rejects(client.createProfile(0, "Fourth"), RangeError, "three is the most"); + await assert.rejects(client.createProfile(0, ""), RangeError); + await assert.rejects(client.createProfile(0, "x".repeat(16)), RangeError); + + // Removing a profile other than the active one. + await assert.rejects(client.deleteProfile(1), RangeError, "the active profile stays"); + await client.setActiveProfile(0); + const left = await client.deleteProfile(2); + assert.deepEqual([left.activeProfile, left.profileCount, [...left.order]], [0, 2, [0, 1, 2, 3]]); + assert.equal((await client.readProfileNames())[2], null, "its name is cleared"); +}); diff --git a/src/drivers/mchose/hid.ts b/src/drivers/mchose/hid.ts index 7e8be70..34f44a5 100644 --- a/src/drivers/mchose/hid.ts +++ b/src/drivers/mchose/hid.ts @@ -18,6 +18,8 @@ import { decodeMchoseReply, encodeMchoseKeyTravel, mchoseBaseWithActiveProfile, + mchoseBaseWithNewProfile, + mchoseBaseWithoutProfile, mchoseChangedWriteFrames, mchoseConfigWithPollingRate, mchoseConfigWithWinLock, @@ -71,6 +73,7 @@ import { mchoseLayoutFromDefaults, mchoseModel, mchoseMacroRegionLength, + MCHOSE_KEYMAP_LAYER_SIZE, MCHOSE_LAYER_COUNT, type MchoseAction, type MchoseAdvancedKeys, @@ -89,6 +92,10 @@ const RESET_WAIT_MS = 5000; const REPLY_RETRIES = 2; /** Quiet time after a timeout, so a late reply arrives while nothing waits for it and is dropped. */ const SETTLE_MS = 200; +/** Pause before a profile block that read back wrong is written again. */ +const PROFILE_COPY_RETRY_MS = 2500; +/** Longest profile name the vendor page accepts. */ +const MCHOSE_PROFILE_NAME_LENGTH = 15; /** MCHOSE magnetic keyboards (Ace 68 Air) on their vendor collection (usage page 0x0001, usage 0). */ export class MchoseKeyboardHidClient { @@ -513,22 +520,103 @@ export class MchoseKeyboardHidClient { /** Rename one profile; the other names are written back as read, in every profile's copy of the list. */ setProfileName(profile: number, name: string): Promise<(string | null)[]> { + return this.serialized(() => this.writeProfileName(profile, name)); + } + + private async writeProfileName(profile: number, name: string): Promise<(string | null)[]> { + MchoseKeyboardHidClient.assertProfile(profile); + const names = decodeMchoseProfileNames(await this.readNameBytes()).map((entry) => entry ?? ""); + names[profile] = name; + // Like the vendor app, send only the 56-byte frames the JSON and its first 0xFF pad need. + const padded = encodeMchoseJson(names, MCHOSE_PROFILE_NAMES_SIZE); + const length = Math.min(MCHOSE_PROFILE_NAMES_SIZE, MCHOSE_MAX_CHUNK * Math.ceil((padded.indexOf(0xff) + 1) / MCHOSE_MAX_CHUNK)); + const next = padded.slice(0, length); + // The vendor app keeps the same list in every profile's custom area, so the copies stay alike. + for (let slot = 0; slot < MCHOSE_PROFILE_COUNT; slot += 1) { + const offset = MCHOSE_CUSTOM_AREA_SIZE * slot + MCHOSE_PROFILE_NAMES_OFFSET; + await this.write(mchoseWriteFrames(MCHOSE_COMMAND.setCustomData, offset, next)); + const copy = await this.read(MCHOSE_COMMAND.getCustomData, offset, next.length); + if (next.some((byte, index) => byte !== copy[index])) throw new Error("The MCHOSE keyboard did not retain the profile name."); + } + return decodeMchoseProfileNames(await this.readNameBytes()); + } + + /** + * Writes a block and reads it back. A key-table write made soon after a + * settings write can come out garbled, so a block that differs is written + * again after a pause, up to three times. + */ + private async writeChecked(write: MchoseCommand, read: MchoseCommand, offset: number, data: readonly number[]): Promise { + for (let attempt = 0; ; attempt += 1) { + await this.write(mchoseWriteFrames(write, offset, data)); + const back = await this.read(read, offset, data.length); + if (data.every((byte, index) => byte === back[index])) return; + if (attempt >= 2) throw new Error("The MCHOSE keyboard did not retain a profile block."); + await new Promise((resolve) => setTimeout(resolve, PROFILE_COPY_RETRY_MS)); + } + } + + /** + * Add a profile that starts as a copy of `from` (settings, lighting, per-key + * colours, travel, all four keymap layers, advanced keys and the custom + * area), under `name`. The new profile's data is written before the profile + * table lists it, so the keyboard never shows a half-written one. + */ + createProfile(from: number, name: string, activate = true): Promise { return this.serialized(async () => { - MchoseKeyboardHidClient.assertProfile(profile); - const names = decodeMchoseProfileNames(await this.readNameBytes()).map((entry) => entry ?? ""); - names[profile] = name; - // Like the vendor app, send only the 56-byte frames the JSON and its first 0xFF pad need. - const padded = encodeMchoseJson(names, MCHOSE_PROFILE_NAMES_SIZE); - const length = Math.min(MCHOSE_PROFILE_NAMES_SIZE, MCHOSE_MAX_CHUNK * Math.ceil((padded.indexOf(0xff) + 1) / MCHOSE_MAX_CHUNK)); - const next = padded.slice(0, length); - // The vendor app keeps the same list in every profile's custom area, so the copies stay alike. - for (let slot = 0; slot < MCHOSE_PROFILE_COUNT; slot += 1) { - const offset = MCHOSE_CUSTOM_AREA_SIZE * slot + MCHOSE_PROFILE_NAMES_OFFSET; - await this.write(mchoseWriteFrames(MCHOSE_COMMAND.setCustomData, offset, next)); - const copy = await this.read(MCHOSE_COMMAND.getCustomData, offset, next.length); - if (next.some((byte, index) => byte !== copy[index])) throw new Error("The MCHOSE keyboard did not retain the profile name."); + MchoseKeyboardHidClient.assertProfile(from); + if (typeof name !== "string" || name.trim() === "" || [...name].length > MCHOSE_PROFILE_NAME_LENGTH) { + throw new RangeError(`A profile name must be 1-${MCHOSE_PROFILE_NAME_LENGTH} characters.`); + } + const baseBytes = await this.readBaseBytes(); + const source = decodeMchoseBase(baseBytes); + if (!source || source.order.indexOf(from) < 0 || source.order.indexOf(from) >= source.profileCount) { + throw new RangeError(`Profile ${from + 1} is not one of this keyboard's enabled profiles.`); + } + const { bytes: table, slot } = mchoseBaseWithNewProfile(baseBytes, activate); + const config = Array.from(await this.readFuncConfig(from)); + // The low nibble of byte 1 holds the profile's layer: four per profile, two more for Mac. + config[1] = (config[1]! & 0xf0) | ((4 * slot + (((config[1]! & 0x0f) % 4) >= 2 ? 2 : 0)) & 0x0f); + await this.writeChecked(MCHOSE_COMMAND.setFuncConfig, MCHOSE_COMMAND.getFuncConfig, MCHOSE_FUNC_CONFIG_SIZE * slot, config); + const copies: [MchoseCommand, MchoseCommand, number, number][] = [ + [MCHOSE_COMMAND.setKeyColors, MCHOSE_COMMAND.getKeyColors, MCHOSE_LIGHT_PROFILE_SIZE, MCHOSE_LIGHT_PROFILE_SIZE], + [MCHOSE_COMMAND.setKeyTravel, MCHOSE_COMMAND.getKeyTravel, MCHOSE_KEY_TRAVEL_SIZE, MCHOSE_KEY_TRAVEL_SIZE], + ...Array.from({ length: MCHOSE_LAYER_COUNT }, (_, layer): [MchoseCommand, MchoseCommand, number, number] => + [MCHOSE_COMMAND.setKeymap, MCHOSE_COMMAND.getKeymap, mchoseKeymapOffset(from, layer), mchoseKeymapOffset(slot, layer)]), + ...(Object.values(MCHOSE_ADVANCED_TABLE) as { read: number; write: number; stride: number }[]) + .map((spec): [MchoseCommand, MchoseCommand, number, number] => [spec.write as MchoseCommand, spec.read as MchoseCommand, spec.stride, spec.stride]), + [MCHOSE_COMMAND.setCustomData, MCHOSE_COMMAND.getCustomData, MCHOSE_CUSTOM_AREA_SIZE, MCHOSE_CUSTOM_AREA_SIZE], + ]; + for (const [write, read, fromOffset, toOffset] of copies) { + // Per-profile blocks sit at `size * profile`; keymap layers carry their own offsets. + const isKeymap = write === MCHOSE_COMMAND.setKeymap; + const source = isKeymap ? fromOffset : fromOffset * from; + const target = isKeymap ? toOffset : toOffset * slot; + const size = isKeymap ? MCHOSE_KEYMAP_LAYER_SIZE : fromOffset; + await this.writeChecked(write, read, target, Array.from(await this.read(read, source, size))); } - return decodeMchoseProfileNames(await this.readNameBytes()); + await this.writeProfileName(slot, name.trim()); + await this.write(mchoseWriteFrames(MCHOSE_COMMAND.setBase, 0, table)); + const confirmed = await this.readBaseValue(); + if (confirmed.profileCount !== source.profileCount + 1) throw new Error("The MCHOSE keyboard did not add the profile."); + return confirmed; + }); + } + + /** + * Take a profile off the keyboard's list and clear its name. Its stored data + * stays in the slot until a new profile is written over it. The active + * profile and the last one cannot be removed. + */ + deleteProfile(profile: number): Promise { + return this.serialized(async () => { + MchoseKeyboardHidClient.assertProfile(profile); + const next = mchoseBaseWithoutProfile(await this.readBaseBytes(), profile); + await this.write(mchoseWriteFrames(MCHOSE_COMMAND.setBase, 0, next)); + const confirmed = await this.readBaseValue(); + if (confirmed.order.slice(0, confirmed.profileCount).includes(profile)) throw new Error("The MCHOSE keyboard did not remove the profile."); + await this.writeProfileName(profile, ""); + return confirmed; }); } diff --git a/src/mchose/codec.ts b/src/mchose/codec.ts index 81ba540..eea3714 100644 --- a/src/mchose/codec.ts +++ b/src/mchose/codec.ts @@ -256,6 +256,51 @@ export function mchoseBaseWithActiveProfile(data: Uint8Array, profile: number): return next; } +/** Most profiles the M HUB page lets a keyboard hold ("3/3" in its profile list). */ +export const MCHOSE_MAX_PROFILES = 3; + +/** + * `data` with the next free profile slot added to the list and, unless told + * otherwise, made the active one. The slot is the first of the entries after + * the used ones in the order list, as the vendor page picks it. + */ +export function mchoseBaseWithNewProfile(data: Uint8Array, activate = true): { bytes: number[]; slot: number } { + const base = decodeMchoseBase(data); + if (!base) throw new Error("The MCHOSE keyboard reported an unreadable profile table."); + if (base.profileCount >= MCHOSE_MAX_PROFILES) throw new RangeError(`The keyboard already holds ${MCHOSE_MAX_PROFILES} profiles.`); + const slot = base.order[base.profileCount]; + if (slot === undefined) throw new RangeError("The profile table has no free slot."); + const bytes = Array.from(data); + bytes[1] = base.profileCount + 1; + if (activate) bytes[0] = base.profileCount; + return { bytes, slot }; +} + +/** + * `data` with `profile` taken out of the list. The profiles that remain keep + * their order, the freed slot goes first among the unused ones, and the active + * position follows its profile (the vendor page writes the table this way: + * `[0, 2, 1, 3]` with 3 profiles becomes `[0, 1, 2, 3]` with 2 when slot 2 + * goes). The active profile and the last profile cannot be removed. + */ +export function mchoseBaseWithoutProfile(data: Uint8Array, profile: number): number[] { + const base = decodeMchoseBase(data); + if (!base) throw new Error("The MCHOSE keyboard reported an unreadable profile table."); + const position = base.order.indexOf(profile); + if (!Number.isInteger(profile) || position < 0 || position >= base.profileCount) { + throw new RangeError(`Profile ${profile + 1} is not one of this keyboard's ${base.profileCount} enabled profiles.`); + } + if (base.profileCount <= 1) throw new RangeError("The last profile cannot be removed."); + if (profile === base.activeProfile) throw new RangeError("The active profile cannot be removed; switch to another one first."); + const kept = base.order.slice(0, base.profileCount).filter((slot) => slot !== profile); + const order = [...kept, profile, ...base.order.slice(base.profileCount)]; + const bytes = Array.from(data); + bytes[0] = kept.indexOf(base.activeProfile); + bytes[1] = base.profileCount - 1; + order.forEach((slot, index) => { bytes[2 + index] = slot; }); + return bytes; +} + /** Wire value of the polling-rate nibble -> Hz, from the vendor app's options. */ export const MCHOSE_POLLING_RATES: Readonly> = { 0: 16000, diff --git a/src/mchose/protocol.test.ts b/src/mchose/protocol.test.ts index b45e657..6cb99db 100644 --- a/src/mchose/protocol.test.ts +++ b/src/mchose/protocol.test.ts @@ -203,3 +203,24 @@ test("every MCHOSE product has its model details", async () => { assert.ok(model.layout.length > 0 && model.effects.main.length > 0 && model.switches.length > 0 && model.fullTravel > 0, product.name); } }); + +test("the profile table is edited the way the M HUB page writes it", async () => { + const { mchoseBaseWithNewProfile, mchoseBaseWithoutProfile, decodeMchoseBase } = await import("./index.ts"); + const table = (position: number, count: number, order: number[]) => Uint8Array.from([position, count, ...order, 0xaa, 0xbb, ...new Array(48).fill(0xa2)]); + const head = (bytes: ArrayLike) => Array.from(bytes).slice(0, 6); + // Seen on an Ace 68 V2 III: removing the last of three profiles (slot 1) changed only the count. + assert.deepEqual(head(mchoseBaseWithoutProfile(table(0, 3, [0, 2, 1, 3]), 1)), [0, 2, 0, 2, 1, 3]); + // Removing slot 2 while slot 1 was active: the freed slot moves behind the used ones and the position follows slot 1. + assert.deepEqual(head(mchoseBaseWithoutProfile(table(2, 3, [0, 2, 1, 3]), 2)), [1, 2, 0, 1, 2, 3]); + // Adding a profile takes the first free slot, counts it and makes it active. + const added = mchoseBaseWithNewProfile(table(0, 2, [0, 2, 1, 3])); + assert.equal(added.slot, 1); + assert.deepEqual(head(added.bytes), [2, 3, 0, 2, 1, 3]); + assert.deepEqual(head(mchoseBaseWithNewProfile(table(0, 2, [0, 2, 1, 3]), false).bytes), [0, 3, 0, 2, 1, 3]); + assert.equal(decodeMchoseBase(Uint8Array.from(added.bytes))?.activeProfile, 1); + // What cannot be done. + assert.throws(() => mchoseBaseWithoutProfile(table(0, 3, [0, 2, 1, 3]), 0), RangeError, "the active profile stays"); + assert.throws(() => mchoseBaseWithoutProfile(table(0, 1, [0, 1, 2, 3]), 0), RangeError, "the last profile stays"); + assert.throws(() => mchoseBaseWithoutProfile(table(0, 2, [0, 1, 2, 3]), 3), RangeError, "an unused slot is not a profile"); + assert.throws(() => mchoseBaseWithNewProfile(table(0, 3, [0, 1, 2, 3])), RangeError, "three is the most"); +}); From 885ae897702bca97b6f9fc80adf65fe5137fb3d3 Mon Sep 17 00:00:00 2001 From: Snowy-Fluffy Date: Fri, 4 Dec 2026 00:27:02 +0000 Subject: [PATCH 5/8] feat(mchose): export and import a profile's contents --- src/drivers/mchose/hid.test.ts | 23 +++++++++++ src/drivers/mchose/hid.ts | 70 ++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) diff --git a/src/drivers/mchose/hid.test.ts b/src/drivers/mchose/hid.test.ts index a44acc2..445404b 100644 --- a/src/drivers/mchose/hid.test.ts +++ b/src/drivers/mchose/hid.test.ts @@ -424,3 +424,26 @@ test("a profile is added as a copy and removed again, in the order the page writ assert.deepEqual([left.activeProfile, left.profileCount, [...left.order]], [0, 2, [0, 1, 2, 3]]); assert.equal((await client.readProfileNames())[2], null, "its name is cleared"); }); + +test("a profile is exported and imported into another profile, keeping that profile's own layer", async () => { + const fake = new FakeMchoseKeyboard(); + fake.base = [0, 2, 0, 2, 1, 3, 0xaa, 0xbb, ...new Array(48).fill(0xa2)]; + fake.config[0]![20] = 9; + fake.config[1]![1] = 0x50 | 0x04; + fake.colors.splice(0, 3, 1, 2, 3); + fake.keymap.splice(3, 3, 0x10, 0x00, 0x14); + fake.dks.splice(0, 2, 7, 8); + fake.modTap.splice(0, 2, 5, 6); + fake.toggle.splice(0, 2, 3, 4); + const client = new MchoseKeyboardHidClient(fake.hid); + const snapshot = await client.exportProfile(0); + // A saved file goes through JSON. + await client.importProfile(1, JSON.parse(JSON.stringify(snapshot))); + assert.equal(fake.config[1]![20], 9); + assert.equal(fake.config[1]![1] & 0x0f, 4, "profile 1 keeps its own layer"); + assert.deepEqual(fake.colors.slice(512, 515), [1, 2, 3]); + assert.deepEqual(fake.keymap.slice(2048 + 3, 2048 + 6), [0x10, 0x00, 0x14]); + assert.deepEqual([fake.dks[768], fake.modTap[256], fake.toggle[128]], [7, 5, 3]); + await assert.rejects(client.importProfile(1, { ...snapshot, format: "other" }), RangeError); + await assert.rejects(client.importProfile(1, { ...snapshot, travel: "zz" }), RangeError); +}); diff --git a/src/drivers/mchose/hid.ts b/src/drivers/mchose/hid.ts index 34f44a5..3c19ab2 100644 --- a/src/drivers/mchose/hid.ts +++ b/src/drivers/mchose/hid.ts @@ -98,6 +98,20 @@ const PROFILE_COPY_RETRY_MS = 2500; const MCHOSE_PROFILE_NAME_LENGTH = 15; /** MCHOSE magnetic keyboards (Ace 68 Air) on their vendor collection (usage page 0x0001, usage 0). */ +/** Marks a file made by `exportProfile`. */ +export const MCHOSE_PROFILE_FORMAT = "openmouse-mchose-profile-1"; + +export interface MchoseProfileSnapshot { + format: string; + config: string; + colours: string; + travel: string; + keymap: string[]; + dks: string; + modTap: string; + toggle: string; +} + export class MchoseKeyboardHidClient { readonly device: HIDDevice; private queue: Promise = Promise.resolve(); @@ -603,6 +617,62 @@ export class MchoseKeyboardHidClient { }); } + /** + * Everything a profile holds apart from its name, as hex strings: settings, + * lighting, per-key colours, travel, the four keymap layers and the advanced + * keys. Macros are shared by all profiles and are not part of it. + */ + exportProfile(profile: number): Promise { + return this.serialized(async () => { + MchoseKeyboardHidClient.assertProfile(profile); + const hex = (bytes: ArrayLike) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); + const block = async (command: MchoseCommand, offset: number, size: number) => hex(await this.read(command, offset, size)); + return { + format: MCHOSE_PROFILE_FORMAT, + config: hex(await this.readFuncConfig(profile)), + colours: await block(MCHOSE_COMMAND.getKeyColors, MCHOSE_LIGHT_PROFILE_SIZE * profile, MCHOSE_LIGHT_PROFILE_SIZE), + travel: await block(MCHOSE_COMMAND.getKeyTravel, MCHOSE_KEY_TRAVEL_SIZE * profile, MCHOSE_KEY_TRAVEL_SIZE), + keymap: await Promise.all(Array.from({ length: MCHOSE_LAYER_COUNT }, (_, layer) => + block(MCHOSE_COMMAND.getKeymap, mchoseKeymapOffset(profile, layer), MCHOSE_KEYMAP_LAYER_SIZE))), + dks: await block(MCHOSE_COMMAND.getDks, MCHOSE_ADVANCED_TABLE.dks.stride * profile, MCHOSE_ADVANCED_TABLE.dks.stride), + modTap: await block(MCHOSE_COMMAND.getModTap, MCHOSE_ADVANCED_TABLE.modTap.stride * profile, MCHOSE_ADVANCED_TABLE.modTap.stride), + toggle: await block(MCHOSE_COMMAND.getToggle, MCHOSE_ADVANCED_TABLE.toggle.stride * profile, MCHOSE_ADVANCED_TABLE.toggle.stride), + }; + }); + } + + /** + * Replace the contents of an existing profile with an exported snapshot. + * The profile keeps its name, and its own layer number in the settings. + */ + importProfile(profile: number, snapshot: MchoseProfileSnapshot): Promise { + return this.serialized(async () => { + MchoseKeyboardHidClient.assertProfile(profile); + const bytes = (text: string, size: number): number[] => { + if (typeof text !== "string" || !/^([0-9a-f]{2})*$/i.test(text) || text.length !== size * 2) throw new RangeError("That profile file is damaged."); + return Array.from({ length: size }, (_, i) => Number.parseInt(text.slice(2 * i, 2 * i + 2), 16)); + }; + if (!snapshot || snapshot.format !== MCHOSE_PROFILE_FORMAT || !Array.isArray(snapshot.keymap) || snapshot.keymap.length !== MCHOSE_LAYER_COUNT) { + throw new RangeError("That is not a profile saved by this app."); + } + const config = bytes(snapshot.config, MCHOSE_FUNC_CONFIG_SIZE); + const own = Array.from(await this.readFuncConfig(profile)); + config[1] = (config[1]! & 0xf0) | (own[1]! & 0x0f); + const blocks: [MchoseCommand, MchoseCommand, number, number[]][] = [ + [MCHOSE_COMMAND.setKeyColors, MCHOSE_COMMAND.getKeyColors, MCHOSE_LIGHT_PROFILE_SIZE * profile, bytes(snapshot.colours, MCHOSE_LIGHT_PROFILE_SIZE)], + [MCHOSE_COMMAND.setKeyTravel, MCHOSE_COMMAND.getKeyTravel, MCHOSE_KEY_TRAVEL_SIZE * profile, bytes(snapshot.travel, MCHOSE_KEY_TRAVEL_SIZE)], + ...snapshot.keymap.map((layer, index): [MchoseCommand, MchoseCommand, number, number[]] => + [MCHOSE_COMMAND.setKeymap, MCHOSE_COMMAND.getKeymap, mchoseKeymapOffset(profile, index), bytes(layer, MCHOSE_KEYMAP_LAYER_SIZE)]), + ...(["dks", "modTap", "toggle"] as const).map((table): [MchoseCommand, MchoseCommand, number, number[]] => { + const spec = MCHOSE_ADVANCED_TABLE[table]; + return [spec.write as MchoseCommand, spec.read as MchoseCommand, spec.stride * profile, bytes(snapshot[table], spec.stride)]; + }), + ]; + await this.writeChecked(MCHOSE_COMMAND.setFuncConfig, MCHOSE_COMMAND.getFuncConfig, MCHOSE_FUNC_CONFIG_SIZE * profile, config); + for (const [write, read, offset, data] of blocks) await this.writeChecked(write, read, offset, data); + }); + } + /** * Take a profile off the keyboard's list and clear its name. Its stored data * stays in the slot until a new profile is written over it. The active From 3c4fdb159e434abe67addd6903ac862d36c9a5dd Mon Sep 17 00:00:00 2001 From: Snowy-Fluffy Date: Fri, 4 Dec 2026 00:28:11 +0000 Subject: [PATCH 6/8] fix(mchose): read profile layers one request at a time --- src/drivers/mchose/hid.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/drivers/mchose/hid.ts b/src/drivers/mchose/hid.ts index 3c19ab2..6557aa9 100644 --- a/src/drivers/mchose/hid.ts +++ b/src/drivers/mchose/hid.ts @@ -632,8 +632,14 @@ export class MchoseKeyboardHidClient { config: hex(await this.readFuncConfig(profile)), colours: await block(MCHOSE_COMMAND.getKeyColors, MCHOSE_LIGHT_PROFILE_SIZE * profile, MCHOSE_LIGHT_PROFILE_SIZE), travel: await block(MCHOSE_COMMAND.getKeyTravel, MCHOSE_KEY_TRAVEL_SIZE * profile, MCHOSE_KEY_TRAVEL_SIZE), - keymap: await Promise.all(Array.from({ length: MCHOSE_LAYER_COUNT }, (_, layer) => - block(MCHOSE_COMMAND.getKeymap, mchoseKeymapOffset(profile, layer), MCHOSE_KEYMAP_LAYER_SIZE))), + keymap: await (async () => { + // One request at a time: the keyboard answers a single command at once. + const layers: string[] = []; + for (let layer = 0; layer < MCHOSE_LAYER_COUNT; layer += 1) { + layers.push(await block(MCHOSE_COMMAND.getKeymap, mchoseKeymapOffset(profile, layer), MCHOSE_KEYMAP_LAYER_SIZE)); + } + return layers; + })(), dks: await block(MCHOSE_COMMAND.getDks, MCHOSE_ADVANCED_TABLE.dks.stride * profile, MCHOSE_ADVANCED_TABLE.dks.stride), modTap: await block(MCHOSE_COMMAND.getModTap, MCHOSE_ADVANCED_TABLE.modTap.stride * profile, MCHOSE_ADVANCED_TABLE.modTap.stride), toggle: await block(MCHOSE_COMMAND.getToggle, MCHOSE_ADVANCED_TABLE.toggle.stride * profile, MCHOSE_ADVANCED_TABLE.toggle.stride), From 20ea6a4498ed9ce83b4ba4aa084924f4c094397b Mon Sep 17 00:00:00 2001 From: Snowy-Fluffy Date: Fri, 4 Dec 2026 00:43:23 +0000 Subject: [PATCH 7/8] docs(mchose): describe profile management --- docs/mchose-support.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/mchose-support.md b/docs/mchose-support.md index daa204f..5faf559 100644 --- a/docs/mchose-support.md +++ b/docs/mchose-support.md @@ -220,6 +220,20 @@ The delay follows the step; under 5 ms is written as 4, meaning none. Writing the first frame takes a flash erase (180 ms measured); the driver resends a frame that gets no answer, twice at most, as the vendor app does. +### Profiles on the keyboard + +`createProfile(from, name, activate)` adds a profile as a copy of another: its +data goes into the first free slot, then the name, and the profile table last, +so the keyboard never lists a half-written profile (three at most). +`deleteProfile(profile)` takes a profile off the table and clears its name; the +active and the last profile stay. `factoryReset(profile | "all")` is the vendor +app's restore (the keyboard reboots). `exportProfile` and `importProfile` move a +profile's settings, lighting, colours, travel, keymap layers and advanced keys +as hex strings (format `openmouse-mchose-profile-1`, not the vendor's JSON); +the target keeps its own name and layer number, and macros are not included. +Table writes made soon after a settings write can come out garbled, so every +block is read back and rewritten after a pause if it differs. + ### Lighting In the function config: backlight effect, brightness (0-100), `4 - speed`, From 8aac623fb92bb66495088dad4fb121f54a8601f1 Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 4 Dec 2026 19:37:26 +0100 Subject: [PATCH 8/8] fix(mchose): review findings on profile management - A new profile is named from profile 0's name list, read before the copy can overwrite it - An import checks every keymap layer before the first write - Removing a profile refuses a table without a valid order list instead of rebuilding it from a guess --- src/drivers/mchose/hid.test.ts | 25 ++++++++++++++++++++++++- src/drivers/mchose/hid.ts | 12 +++++++----- src/mchose/codec.ts | 7 +++++-- src/mchose/protocol.test.ts | 1 + 4 files changed, 37 insertions(+), 8 deletions(-) diff --git a/src/drivers/mchose/hid.test.ts b/src/drivers/mchose/hid.test.ts index 445404b..befbf86 100644 --- a/src/drivers/mchose/hid.test.ts +++ b/src/drivers/mchose/hid.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { MCHOSE_COMMAND, mchoseChecksum } from "../../mchose/index.ts"; +import { MCHOSE_COMMAND, MCHOSE_CUSTOM_AREA_SIZE, MCHOSE_PROFILE_NAMES_OFFSET, MCHOSE_PROFILE_NAMES_SIZE, encodeMchoseJson, mchoseChecksum } from "../../mchose/index.ts"; import { MchoseKeyboardHidClient } from "./hid.ts"; import { createSupportedClient, deviceBrand } from "../registry.ts"; import { MCHOSE_HID_FILTERS, SUPPORTED_HID_FILTERS, VENDOR_ID } from "../vendors.ts"; @@ -447,3 +447,26 @@ test("a profile is exported and imported into another profile, keeping that prof await assert.rejects(client.importProfile(1, { ...snapshot, format: "other" }), RangeError); await assert.rejects(client.importProfile(1, { ...snapshot, travel: "zz" }), RangeError); }); + +test("a new profile keeps the other names from profile 0's list, not from the copied profile's", async () => { + const fake = new FakeMchoseKeyboard(); + fake.base = [0, 1, 2, 0, 1, 3, 0xaa, 0xbb, ...new Array(48).fill(0xa2)]; + const names = (list: string[], slot: number) => + fake.custom.splice(MCHOSE_CUSTOM_AREA_SIZE * slot + MCHOSE_PROFILE_NAMES_OFFSET, MCHOSE_PROFILE_NAMES_SIZE, ...encodeMchoseJson(list, MCHOSE_PROFILE_NAMES_SIZE)); + names(["", "", "Game", ""], 0); + names(["", "", "Old", ""], 2); + const client = new MchoseKeyboardHidClient(fake.hid); + + await client.createProfile(2, "New"); + assert.deepEqual((await client.readProfileNames()).slice(0, 3), ["New", null, "Game"]); +}); + +test("an import with a missing keymap layer is refused before anything is written", async () => { + const fake = new FakeMchoseKeyboard(); + fake.base = [0, 2, 0, 2, 1, 3, 0xaa, 0xbb, ...new Array(48).fill(0xa2)]; + const client = new MchoseKeyboardHidClient(fake.hid); + const snapshot = await client.exportProfile(0); + const sent = fake.sent.length; + await assert.rejects(client.importProfile(1, { ...snapshot, keymap: new Array(4) }), RangeError); + assert.equal(fake.sent.slice(sent).filter((frame) => frame[0] === 0x55 && frame[1] !== MCHOSE_COMMAND.getFuncConfig).length, 0); +}); diff --git a/src/drivers/mchose/hid.ts b/src/drivers/mchose/hid.ts index 6557aa9..590dd76 100644 --- a/src/drivers/mchose/hid.ts +++ b/src/drivers/mchose/hid.ts @@ -537,9 +537,9 @@ export class MchoseKeyboardHidClient { return this.serialized(() => this.writeProfileName(profile, name)); } - private async writeProfileName(profile: number, name: string): Promise<(string | null)[]> { + private async writeProfileName(profile: number, name: string, current?: (string | null)[]): Promise<(string | null)[]> { MchoseKeyboardHidClient.assertProfile(profile); - const names = decodeMchoseProfileNames(await this.readNameBytes()).map((entry) => entry ?? ""); + const names = (current ?? decodeMchoseProfileNames(await this.readNameBytes())).map((entry) => entry ?? ""); names[profile] = name; // Like the vendor app, send only the 56-byte frames the JSON and its first 0xFF pad need. const padded = encodeMchoseJson(names, MCHOSE_PROFILE_NAMES_SIZE); @@ -588,6 +588,7 @@ export class MchoseKeyboardHidClient { throw new RangeError(`Profile ${from + 1} is not one of this keyboard's enabled profiles.`); } const { bytes: table, slot } = mchoseBaseWithNewProfile(baseBytes, activate); + const names = decodeMchoseProfileNames(await this.readNameBytes()); const config = Array.from(await this.readFuncConfig(from)); // The low nibble of byte 1 holds the profile's layer: four per profile, two more for Mac. config[1] = (config[1]! & 0xf0) | ((4 * slot + (((config[1]! & 0x0f) % 4) >= 2 ? 2 : 0)) & 0x0f); @@ -609,7 +610,7 @@ export class MchoseKeyboardHidClient { const size = isKeymap ? MCHOSE_KEYMAP_LAYER_SIZE : fromOffset; await this.writeChecked(write, read, target, Array.from(await this.read(read, source, size))); } - await this.writeProfileName(slot, name.trim()); + await this.writeProfileName(slot, name.trim(), names); await this.write(mchoseWriteFrames(MCHOSE_COMMAND.setBase, 0, table)); const confirmed = await this.readBaseValue(); if (confirmed.profileCount !== source.profileCount + 1) throw new Error("The MCHOSE keyboard did not add the profile."); @@ -662,13 +663,14 @@ export class MchoseKeyboardHidClient { throw new RangeError("That is not a profile saved by this app."); } const config = bytes(snapshot.config, MCHOSE_FUNC_CONFIG_SIZE); + const layers = Array.from(snapshot.keymap, (layer) => bytes(layer, MCHOSE_KEYMAP_LAYER_SIZE)); const own = Array.from(await this.readFuncConfig(profile)); config[1] = (config[1]! & 0xf0) | (own[1]! & 0x0f); const blocks: [MchoseCommand, MchoseCommand, number, number[]][] = [ [MCHOSE_COMMAND.setKeyColors, MCHOSE_COMMAND.getKeyColors, MCHOSE_LIGHT_PROFILE_SIZE * profile, bytes(snapshot.colours, MCHOSE_LIGHT_PROFILE_SIZE)], [MCHOSE_COMMAND.setKeyTravel, MCHOSE_COMMAND.getKeyTravel, MCHOSE_KEY_TRAVEL_SIZE * profile, bytes(snapshot.travel, MCHOSE_KEY_TRAVEL_SIZE)], - ...snapshot.keymap.map((layer, index): [MchoseCommand, MchoseCommand, number, number[]] => - [MCHOSE_COMMAND.setKeymap, MCHOSE_COMMAND.getKeymap, mchoseKeymapOffset(profile, index), bytes(layer, MCHOSE_KEYMAP_LAYER_SIZE)]), + ...layers.map((layer, index): [MchoseCommand, MchoseCommand, number, number[]] => + [MCHOSE_COMMAND.setKeymap, MCHOSE_COMMAND.getKeymap, mchoseKeymapOffset(profile, index), layer]), ...(["dks", "modTap", "toggle"] as const).map((table): [MchoseCommand, MchoseCommand, number, number[]] => { const spec = MCHOSE_ADVANCED_TABLE[table]; return [spec.write as MchoseCommand, spec.read as MchoseCommand, spec.stride * profile, bytes(snapshot[table], spec.stride)]; diff --git a/src/mchose/codec.ts b/src/mchose/codec.ts index eea3714..81327e8 100644 --- a/src/mchose/codec.ts +++ b/src/mchose/codec.ts @@ -281,11 +281,14 @@ export function mchoseBaseWithNewProfile(data: Uint8Array, activate = true): { b * their order, the freed slot goes first among the unused ones, and the active * position follows its profile (the vendor page writes the table this way: * `[0, 2, 1, 3]` with 3 profiles becomes `[0, 1, 2, 3]` with 2 when slot 2 - * goes). The active profile and the last profile cannot be removed. + * goes). The active profile and the last profile cannot be removed, and a + * table without a valid order list is refused rather than rebuilt from a guess. */ export function mchoseBaseWithoutProfile(data: Uint8Array, profile: number): number[] { const base = decodeMchoseBase(data); - if (!base) throw new Error("The MCHOSE keyboard reported an unreadable profile table."); + if (!base || base.profileCount !== data[1] || base.order.some((slot, index) => slot !== data[2 + index])) { + throw new Error("The MCHOSE keyboard reported an unreadable profile table."); + } const position = base.order.indexOf(profile); if (!Number.isInteger(profile) || position < 0 || position >= base.profileCount) { throw new RangeError(`Profile ${profile + 1} is not one of this keyboard's ${base.profileCount} enabled profiles.`); diff --git a/src/mchose/protocol.test.ts b/src/mchose/protocol.test.ts index 6cb99db..e31c7a4 100644 --- a/src/mchose/protocol.test.ts +++ b/src/mchose/protocol.test.ts @@ -223,4 +223,5 @@ test("the profile table is edited the way the M HUB page writes it", async () => assert.throws(() => mchoseBaseWithoutProfile(table(0, 1, [0, 1, 2, 3]), 0), RangeError, "the last profile stays"); assert.throws(() => mchoseBaseWithoutProfile(table(0, 2, [0, 1, 2, 3]), 3), RangeError, "an unused slot is not a profile"); assert.throws(() => mchoseBaseWithNewProfile(table(0, 3, [0, 1, 2, 3])), RangeError, "three is the most"); + assert.throws(() => mchoseBaseWithoutProfile(table(0, 3, [0, 0, 1, 2]), 1), /unreadable/, "a guessed table is not rebuilt"); });