// MCHOSE keyboards: the backlight (effect, brightness, speed, direction, colour // and a colour for every key), each key's actuation and rapid trigger, and the // keyboard's settings, all for the active profile. Every change is read back by the driver before // it is reported as made, and settings live on the keyboard at once. // // Only the main backlight is edited. A light box (side zone) is carried through // untouched. Settings are edited in place and live on the keyboard at once. import { MCHOSE_LIGHT_OFF, MCHOSE_MAX_PROFILES, MCHOSE_SPEED_MAX, MCHOSE_ACTION_TYPE, MCHOSE_MEDIA_NAMES, MCHOSE_MODIFIER, MCHOSE_MOUSE_NAMES, MCHOSE_SPECIAL_NAMES, MCHOSE_SYSTEM_NAMES, MCHOSE_USAGE_NAMES, mchoseActionFromValue, mchoseActionLabel, mchoseActionValue, mchoseDisplayProfileName, mchoseKeyAction, mchoseLayoutFromDefaults, mchoseMmToSteps, mchoseModel, mchoseProduct, mchoseRapidTriggerStep, mchoseStepsToMm, type MchoseAction, type MchoseKeyTravel, type MchoseMacro, type MchoseKeyTravelUpdate, type MchoseLighting, type MchoseSettings, } from "@openmouse/keyboard-protocol/mchose"; import { MACRO_MODES, VIRTUAL_MOD_TAP, VIRTUAL_TOGGLE, advancedCategories, describeSlot, formatMacro, calibrationControl, calibrationStatus, freeUnusedSlots, loadProfileFile, saveProfileFile, savedProfileControls, runCalibration, PAIRS, PAIR_OPTIONS, readPairs, setPair, parseMacro, setSlotKey, detachPair, } from "./keyboard-mchose-advanced"; export const MCHOSE_FEATURES = { actuation: true, remap: true, lighting: true }; /** * What an effect's direction switch does, from sampling the live colours of an * Ace 68 V2 III: the first name is the keyboard's value 0, the second its * value 1. The spin has no direction that reads clearly from the colours * alone, so it is only called forward and reverse. */ const DIRECTIONS: Record = { 6: ["Left to right", "Right to left"], 7: ["Top to bottom", "Bottom to top"], 8: ["Outward", "Inward"], 10: ["Forward", "Reverse"], }; /** "Constant on", the effect a board returns to when it is switched on without a remembered one. */ const DEFAULT_EFFECT = 3; /** The effect before the backlight was switched off, so switching it on again restores it. */ const beforeOff = new Map(); const byte = (value: unknown): value is number => Number.isInteger(value) && (value as number) >= 0 && (value as number) <= 255; async function load(client: any) { const model = mchoseModel(client.device.productId); if (!model) throw new Error("This MCHOSE keyboard has no lighting description."); const { activeProfile } = await client.readBase(); const lighting: MchoseLighting = await client.readLighting(activeProfile); return { profile: activeProfile as number, lighting, model, memory: `${client.device.productId}:${activeProfile}` }; } function describe(lighting: MchoseLighting, effects: readonly { value: number; name: string; speed: boolean; direction: boolean; color: boolean }[], memory: string) { const { main } = lighting; const on = main.effect !== MCHOSE_LIGHT_OFF; if (on) beforeOff.set(memory, main.effect); return { on, effect: on ? main.effect : beforeOff.get(memory) ?? DEFAULT_EFFECT, brightness: main.brightness, speed: main.speed, speedMax: MCHOSE_SPEED_MAX, direction: main.direction, rainbow: main.rainbow, rgb: [main.color.r, main.color.g, main.color.b], effects: effects.map((e) => ({ value: e.value, name: e.name, speed: e.speed, direction: e.direction, colour: e.color, directions: e.direction ? DIRECTIONS[e.value] ?? ["Forward", "Reverse"] : null, })), }; } async function readLights(client: any) { const { lighting, model, memory } = await load(client); return describe(lighting, model.effects.main, memory); } async function setLights(client: any, wanted: any) { const { profile, lighting, model, memory } = await load(client); const known = model.effects.main.some((effect) => effect.value === wanted.effect); const rgb: unknown[] = Array.isArray(wanted.rgb) ? wanted.rgb : []; if (!known || typeof wanted.on !== "boolean" || typeof wanted.rainbow !== "boolean" || !Number.isInteger(wanted.brightness) || wanted.brightness < 0 || wanted.brightness > 100 || !Number.isInteger(wanted.speed) || wanted.speed < 0 || wanted.speed > MCHOSE_SPEED_MAX || ![0, 1].includes(wanted.direction) || rgb.length !== 3 || !rgb.every(byte)) { throw new RangeError("That lighting value is out of range."); } const [r, g, b] = rgb as number[]; const main = { ...lighting.main, effect: wanted.on ? wanted.effect : MCHOSE_LIGHT_OFF, brightness: wanted.brightness, speed: wanted.speed, direction: wanted.direction, rainbow: wanted.rainbow, color: { r, g, b }, }; // The driver writes only what changed and compares the whole config on read-back. const confirmed: MchoseLighting = await client.setLighting(profile, { ...lighting, main }); return describe(confirmed, model.effects.main, memory); } /** The effect that shows the per-key colours. */ const CUSTOM_EFFECT = 0; /** * Every key with where it sits and its own colour, in the shape the keyboard * pages draw. `col` is the key's slot in the colour table, which is what a * colour is written to. */ async function readKeyColours(client: any) { const { profile, model } = await load(client); // The keyboard's own default keymap places each key, as the vendor app does. const layout = mchoseLayoutFromDefaults(await client.readDefaultKeymap(0), model.layout); const colours: { r: number; g: number; b: number }[] = await client.readKeyColors(profile); return { layer: 0, layers: 1, width: Math.max(...layout.map((key) => key.x + key.width)), keys: layout.map((key) => { const c = colours[key.index] ?? { r: 0, g: 0, b: 0 }; return { row: key.row, col: key.index, x: key.x, y: key.row, w: key.width, label: key.label, colour: [c.r, c.g, c.b] }; }), categories: [], }; } /** Paints keys one colour. The Custom effect is the one that shows them, so it is switched to. */ async function setKeyColours(client: any, args: any) { const rgb: unknown[] = Array.isArray(args.rgb) ? args.rgb : []; const slots: unknown[] = Array.isArray(args.keys) ? args.keys : []; if (rgb.length !== 3 || !rgb.every(byte) || slots.length === 0 || !slots.every((slot) => Number.isInteger(slot) && (slot as number) >= 0 && (slot as number) < 128)) { throw new RangeError("Those keys or that colour can't be set."); } const { profile, lighting, model, memory } = await load(client); const [r, g, b] = rgb as number[]; const written: { r: number; g: number; b: number }[] = await client.setKeyColors( profile, (slots as number[]).map((index) => ({ index, color: { r, g, b } })), ); let shown = lighting; if (lighting.main.effect !== CUSTOM_EFFECT) { shown = await client.setLighting(profile, { ...lighting, main: { ...lighting.main, effect: CUSTOM_EFFECT } }); } return { keys: (slots as number[]).map((col) => ({ col, colour: [written[col].r, written[col].g, written[col].b] })), lights: describe(shown, model.effects.main, memory), }; } // --- Actuation and rapid trigger ------------------------------------------- /** The numbers the actuation page edits, in millimetres, with the keyboard's limits. */ const FIELDS = [ { id: "travel", name: "Actuation point", hint: "How far a key goes down before it registers.", min: 0.1, max: 3.4 }, { id: "rtPress", name: "Rapid trigger: press", hint: "How far back down it registers again.", min: 0.02, max: 3.4 }, { id: "rtRelease", name: "Rapid trigger: release", hint: "How far up it lets go.", min: 0.02, max: 3.4 }, { id: "deadPress", name: "Top dead zone", hint: "Travel at the top that does not count, so a light touch can't register.", min: 0, max: 0.5 }, { id: "deadRelease", name: "Bottom dead zone", hint: "Travel at the bottom that does not count, so a key held down can't be missed.", min: 0, max: 0.5 }, ] as const; /** The key modes, as the vendor's trigger page names them (see MCHOSE_KEY_MODE in the driver). */ const MODES = [ { value: 0, label: "Off" }, { value: 1, label: "Quick trigger" }, { value: 2, label: "Quick + rapid trigger" }, ] as const; /** A key's settings in millimetres, by the names the page uses. */ function travelMm(record: MchoseKeyTravel) { const press = mchoseRapidTriggerStep(record.pressPrecision).stepMm; const release = mchoseRapidTriggerStep(record.releasePrecision).stepMm; return { travel: mchoseStepsToMm(record.actuation), rtPress: mchoseStepsToMm(record.rapidTriggerPress, press), rtRelease: mchoseStepsToMm(record.rapidTriggerRelease, release), deadPress: mchoseStepsToMm(record.pressDeadzone), deadRelease: mchoseStepsToMm(record.releaseDeadzone), mode: record.keyMode, }; } /** The layers of a profile, in the order the keyboard stores them. */ const LAYERS = ["Windows", "Windows Fn", "Mac", "Mac Fn"]; /** Functions that are safe to put on a key; the factory reset function is left out on purpose. */ const SPECIAL_HIDDEN = new Set([0x0800]); /** What a key can be set to, grouped as the vendor's key mapping page groups them. */ function categories() { const entry = (action: MchoseAction, label: string) => ({ code: mchoseActionValue(action), label }); const key = (usage: number) => entry(mchoseKeyAction(usage), MCHOSE_USAGE_NAMES[usage]); const named = (names: Readonly>, make: (code: number) => MchoseAction) => Object.entries(names).map(([code, label]) => entry(make(Number(code)), label)); const modifiers: [number, string][] = [ [MCHOSE_MODIFIER.leftCtrl, "Ctrl"], [MCHOSE_MODIFIER.leftShift, "Shift"], [MCHOSE_MODIFIER.leftAlt, "Alt"], [MCHOSE_MODIFIER.leftWin, "Win"], [MCHOSE_MODIFIER.rightCtrl, "Right Ctrl"], [MCHOSE_MODIFIER.rightShift, "Right Shift"], [MCHOSE_MODIFIER.rightAlt, "Right Alt"], [MCHOSE_MODIFIER.rightWin, "Right Win"], ]; return [ { name: "Keys", keys: [entry({ type: MCHOSE_ACTION_TYPE.key, code1: 0, code2: 0 }, "Disabled"), ...Object.keys(MCHOSE_USAGE_NAMES).map((usage) => key(Number(usage)))] }, { name: "Modifiers", keys: modifiers.map(([mask, label]) => entry({ type: MCHOSE_ACTION_TYPE.key, code1: mask, code2: 0 }, label)) }, { name: "Mouse", keys: [ ...named(MCHOSE_MOUSE_NAMES, (mask) => ({ type: MCHOSE_ACTION_TYPE.mouse, code1: mask, code2: 0 })), entry({ type: MCHOSE_ACTION_TYPE.wheel, code1: 0, code2: 1 }, "Wheel up"), entry({ type: MCHOSE_ACTION_TYPE.wheel, code1: 0, code2: 0xff }, "Wheel down"), ] }, { name: "Media", keys: named(MCHOSE_MEDIA_NAMES, (usage) => ({ type: MCHOSE_ACTION_TYPE.media, code1: usage & 0xff, code2: usage >> 8 })) }, { name: "System", keys: named(MCHOSE_SYSTEM_NAMES, (code) => ({ type: MCHOSE_ACTION_TYPE.system, code1: code, code2: 0 })) }, { name: "Keyboard", keys: Object.entries(MCHOSE_SPECIAL_NAMES) .filter(([code]) => !SPECIAL_HIDDEN.has(Number(code))) .map(([code, label]) => entry({ type: MCHOSE_ACTION_TYPE.special, code1: Number(code) >> 8, code2: Number(code) & 0xff }, label)) }, ...advancedCategories(), ]; } /** Every key with where it sits, what it does on `layer`, and its actuation settings. */ async function readKeys(client: any, layerArg?: unknown) { const layer = Number.isInteger(layerArg) && (layerArg as number) >= 0 && (layerArg as number) < LAYERS.length ? (layerArg as number) : 0; const { profile, model } = await load(client); const layout = mchoseLayoutFromDefaults(await client.readDefaultKeymap(0), model.layout); const travel: MchoseKeyTravel[] = await client.readKeyTravel(profile); const now: MchoseAction[] = await client.readKeymap(profile, layer); const factory: MchoseAction[] = await client.readDefaultKeymap(layer); const tables = await client.readAdvancedKeys(profile); const name = (action: MchoseAction) => describeSlot(action, tables) ?? mchoseActionLabel(action) ?? "?"; return { layer, layers: LAYERS.length, layerNames: LAYERS, width: Math.max(...layout.map((key) => key.x + key.width)), // Changes are in the keyboard's profile as soon as they are made. stored: true, fields: FIELDS, modes: MODES, categories: categories(), keys: layout.map((key) => ({ row: key.row, col: key.index, x: key.x, y: key.row, w: key.width, code: mchoseActionValue(now[key.index]), label: name(now[key.index]), standard: mchoseActionValue(factory[key.index]), standardLabel: name(factory[key.index]), actuation: travelMm(travel[key.index]), })), }; } /** Puts an action on a key of one layer; the driver reads the layer back. */ async function setKey(client: any, args: any) { const { layer, col, code } = args; if (![layer, col, code].every(Number.isInteger) || layer < 0 || layer >= LAYERS.length || col < 0 || col >= 128 || code < 0 || code > 0xffffff) { throw new RangeError("That key can't be assigned."); } const action = mchoseActionFromValue(code); if (action.type === VIRTUAL_TOGGLE || action.type === VIRTUAL_MOD_TAP) { const { profile } = await load(client); // A mod-tap key keeps doing what it did when it is tapped; a key already using a slot falls back to its factory action. const now: MchoseAction[] = await client.readKeymap(profile, layer); const plain = (a: MchoseAction) => a.type !== MCHOSE_ACTION_TYPE.toggle && a.type !== MCHOSE_ACTION_TYPE.modTap && a.type !== MCHOSE_ACTION_TYPE.dks && ![0x92, 0x93, 0x94, 0x95].includes(a.type); const tap = plain(now[col]) ? now[col] : (await client.readDefaultKeymap(layer))[col]; await detachPair(client, profile, layer, col, now[col]); const written = await setSlotKey(client, profile, layer, col, action, tap); const tables = await client.readAdvancedKeys(profile); return { row: args.row ?? 0, col, code: mchoseActionValue(written), label: describeSlot(written, tables) ?? mchoseActionLabel(written) ?? "?" }; } const known = action.type === MCHOSE_ACTION_TYPE.key || mchoseActionLabel(action) !== null; if (!known) throw new RangeError("That action is not one this keyboard offers."); const { profile } = await load(client); await detachPair(client, profile, layer, col, (await client.readKeymap(profile, layer))[col]); const written: MchoseAction[] = await client.setKeymap(profile, layer, [{ index: col, action }]); // A key that used a toggle or mod-tap slot has just left it. await freeUnusedSlots(client, profile); return { row: args.row ?? 0, col, code: mchoseActionValue(written[col]), label: mchoseActionLabel(written[col]) ?? "?" }; } /** Changes the given fields on each key, keeping the rest as the keyboard has them. */ async function setActuation(client: any, args: any) { const keys: unknown[] = Array.isArray(args.keys) ? args.keys : []; const patch: Record = args.patch ?? {}; const known = new Set([...FIELDS.map((f) => f.id), "mode"]); if (keys.length === 0 || Object.keys(patch).length === 0 || Object.keys(patch).some((name) => !known.has(name) || !Number.isFinite(patch[name])) || !keys.every((key) => Array.isArray(key) && Number.isInteger(key[1]) && key[1] >= 0 && key[1] < 128)) { throw new RangeError("Those keys or values can't be set."); } for (const field of FIELDS) { const value = patch[field.id]; if (value !== undefined && (value < field.min - 1e-9 || value > field.max + 1e-9)) throw new RangeError(`${field.name} must be ${field.min} to ${field.max} mm.`); } if (patch.mode !== undefined && !MODES.some((mode) => mode.value === patch.mode)) throw new RangeError("That trigger mode does not exist."); const { profile } = await load(client); const before: MchoseKeyTravel[] = await client.readKeyTravel(profile); for (const [field, precision] of [["rtPress", "pressPrecision"], ["rtRelease", "releasePrecision"]] as const) { if (patch[field] === undefined) continue; const most = Math.min(...(keys as [number, number][]).map(([, index]) => { const step = mchoseRapidTriggerStep(before[index][precision]); return step.max * step.stepMm; })); if (patch[field] > most + 1e-9) throw new RangeError(`Rapid trigger on these keys goes up to ${most} mm.`); } const updates: MchoseKeyTravelUpdate[] = (keys as [number, number][]).map(([, index]) => { const record = before[index]; const update: MchoseKeyTravelUpdate = { index }; // Distances are written in the key's own steps; its precision is kept. if (patch.travel !== undefined) update.actuation = mchoseMmToSteps(patch.travel); if (patch.rtPress !== undefined) update.rapidTriggerPress = mchoseMmToSteps(patch.rtPress, mchoseRapidTriggerStep(record.pressPrecision).stepMm); if (patch.rtRelease !== undefined) update.rapidTriggerRelease = mchoseMmToSteps(patch.rtRelease, mchoseRapidTriggerStep(record.releasePrecision).stepMm); if (patch.deadPress !== undefined) update.pressDeadzone = mchoseMmToSteps(patch.deadPress); if (patch.deadRelease !== undefined) update.releaseDeadzone = mchoseMmToSteps(patch.deadRelease); if (patch.mode !== undefined) update.keyMode = patch.mode; return update; }); // The driver checks every value against the vendor's limits and reads the whole table back. const now: MchoseKeyTravel[] = await client.setKeyTravel(profile, updates); // An older driver ignores a key mode it does not know and would report success. if (patch.mode !== undefined && updates.some(({ index }) => now[index].keyMode !== patch.mode)) { throw new Error("This version of the keyboard library can't set that trigger mode."); } return updates.map(({ index }, i) => ({ row: (keys as [number, number][])[i][0], col: index, actuation: travelMm(now[index]) })); } // --- Settings -------------------------------------------------------------- const PREFIX = "mchose.kb."; export const isMchoseKeyboardControl = (action: string) => action.startsWith(`control:${PREFIX}`); const toggle = (id: string, label: string, current: boolean, description?: string) => ({ id: PREFIX + id, label, kind: "toggle", current, description }); const choice = (id: string, label: string, current: number, options: { value: number; label: string }[], description?: string) => ({ id: PREFIX + id, label, kind: "choice", current, options, description }); /** Settings that are one field of the keyboard's settings block. */ const SETTINGS: Record = { scan: { field: "scanRateRaw", type: "number", max: 3 }, debounce: { field: "debounce", type: "boolean" }, stability: { field: "bottomRapidTrigger", type: "boolean" }, check: { field: "travelCheck", type: "boolean" }, berserk: { field: "tachyonMode", type: "boolean" }, rtsmart: { field: "rtSmart", type: "number", max: 15 }, lockwin: { field: "lockWin", type: "boolean" }, lockalttab: { field: "lockAltTab", type: "boolean" }, lockaltf4: { field: "lockAltF4", type: "boolean" }, mac: { field: "macMode", type: "boolean" }, sleep: { field: "sleepEnabled", type: "boolean" }, sleeptime: { field: "sleepTime", type: "number", max: 255 }, }; /** The name to show: the user's own, or "Profile N" where the vendor app left a code. */ const profileName = (name: string | null | undefined, index: number): string => mchoseDisplayProfileName(name ?? null) ?? `Profile ${index + 1}`; /** Longest profile name the vendor app accepts. */ const NAME_LENGTH = 15; const text = (id: string, label: string, current: string, description?: string) => ({ id: PREFIX + id, label, kind: "text", current, description }); /** Sleep delays offered, in the keyboard's 30-second steps; the current one is always among them. */ const SLEEP_MINUTES = [1, 2, 5, 10, 30, 60]; export async function mchoseSections(client: any) { const { activeProfile, profileCount, order } = await client.readBase(); const product = mchoseProduct(client.device.vendorId, client.device.productId); const [settings, performance, names]: [MchoseSettings, any, (string | null)[]] = await Promise.all([ client.readSettings(activeProfile), client.readPerformance(activeProfile), client.readProfileNames().catch(() => []), ]); const macros: MchoseMacro[] = await client.readMacros().catch(() => []); // Every macro in use, then one empty slot to start the next. const used = macros.map((m, i) => (m.steps.length > 0 ? i : -1)).filter((i) => i >= 0); const shown = [...used, ...(used.length < macros.length ? [macros.findIndex((m) => m.steps.length === 0)] : [])].filter((i) => i >= 0); const macroControls = shown.flatMap((i) => [ text(`macro.${i}`, `Macro ${i + 1}`, formatMacro(macros[i].steps), i === shown[shown.length - 1] && macros[i].steps.length === 0 ? "Keys by name: +Ctrl presses, -Ctrl releases, A taps, a number waits that many ms. Example: +Ctrl C -Ctrl 50 Enter. Empty removes the macro." : "Empty removes the macro."), choice(`macromode.${i}`, `Macro ${i + 1} plays`, macros[i].mode, MACRO_MODES.some((m) => m.value === macros[i].mode) ? MACRO_MODES : [...MACRO_MODES, { value: macros[i].mode, label: "Custom" }]), ]); const pairs = await readPairs(client, activeProfile); const saved = savedProfileControls(); const rates = new Set(product?.pollingRatesHz ?? []); if (performance.pollingHz) rates.add(performance.pollingHz); const sleeps = new Set([...SLEEP_MINUTES.map((m) => m * 2), settings.sleepTime]); const others = (order as number[]).slice(0, profileCount) .filter((slot) => slot !== activeProfile) .map((slot) => ({ value: slot, label: profileName(names[slot], slot) })); return [ { title: "Profile", controls: [ choice("profile", "Active profile", activeProfile, (order as number[]).slice(0, profileCount).map((slot) => ({ value: slot, label: profileName(names[slot], slot) })), "Each profile keeps its own lighting, actuation and settings."), text("name", "Profile name", profileName(names[activeProfile], activeProfile), `Up to ${NAME_LENGTH} characters.`), ...(profileCount < MCHOSE_MAX_PROFILES ? [ text("newprofile", "New profile", "", `Type a name to add a copy of the active profile (up to ${MCHOSE_MAX_PROFILES} on the keyboard).`), ] : []), ...(others.length > 0 ? [ choice("deleteprofile", "Delete profile", -1, [{ value: -1, label: "Choose…" }, ...others], "Removes another profile from the keyboard. The active profile stays."), choice("resetprofile", "Reset profile", -1, [{ value: -1, label: "Choose…" }, ...others], "Sets another profile back to the factory settings. The keyboard restarts."), ] : []), ] }, { title: "Opposing keys", controls: PAIRS.map((pair) => choice(`pair.${pair.id}`, pair.label, pairs[pair.id], PAIR_OPTIONS, "SOCD decides what happens when both keys are held; rapid snap releases the first the moment the second goes down.")) }, ...(saved.length ? [{ title: "Saved profiles", controls: saved }] : []), { title: "Calibration", controls: [await calibrationControl(client, activeProfile)] }, { title: "Macros", controls: macroControls }, { title: "Performance", controls: [ choice("polling", "Polling rate", performance.pollingHz ?? 0, [...rates].sort((a, b) => a - b).map((hz) => ({ value: hz, label: `${hz} Hz` }))), choice("scan", "Key scan rate", settings.scanRateRaw, [0, 1, 2, 3].map((n) => ({ value: n, label: `${[1, 2, 4, 8][n]} kHz` })), "How often the keyboard checks its keys."), toggle("debounce", "Debounce optimisation", settings.debounce), toggle("stability", "Stability mode", settings.bottomRapidTrigger), toggle("check", "Travel self-check", settings.travelCheck), ] }, { title: "Rapid trigger", controls: [ choice("rtsmart", "Smart rapid trigger", settings.rtSmart, Array.from({ length: 16 }, (_, n) => ({ value: n, label: n === 0 ? "Off" : String(n) }))), toggle("berserk", "Berserk mode", settings.tachyonMode, "Allows the smallest rapid-trigger distances."), ] }, { title: "Locks", controls: [ toggle("lockwin", "Lock the Windows key", settings.lockWin), toggle("lockalttab", "Lock Alt+Tab", settings.lockAltTab), toggle("lockaltf4", "Lock Alt+F4", settings.lockAltF4), toggle("mac", "Mac layout", settings.macMode, "Uses the Mac layer; turning it on also releases the Windows key lock."), ] }, { title: "Power", controls: [ toggle("sleep", "Sleep when idle", settings.sleepEnabled), choice("sleeptime", "Sleep after", settings.sleepTime, [...sleeps].sort((a, b) => a - b).map((steps) => ({ value: steps, label: steps % 2 === 0 ? `${steps / 2} min` : `${steps * 30} s` }))), ] }, ]; } /** Writes one setting; the driver reads it back before this returns. */ export async function writeMchoseKeyboard(client: any, action: string, value: unknown): Promise<"rebooted" | void> { const id = action.slice(`control:${PREFIX}`.length); const { activeProfile } = await client.readBase(); if (id === "profile") { if (!Number.isInteger(value)) throw new RangeError("Pick a profile."); await client.setActiveProfile(value); return; } if (id === "name") { const name = typeof value === "string" ? value.trim() : ""; if (name === "" || [...name].length > NAME_LENGTH) throw new RangeError(`Use a name of 1 to ${NAME_LENGTH} characters.`); await client.setProfileName(activeProfile, name); return; } if (id === "newprofile") { const name = typeof value === "string" ? value.trim() : ""; if (name === "" || [...name].length > NAME_LENGTH) throw new RangeError(`Use a name of 1 to ${NAME_LENGTH} characters.`); await client.createProfile(activeProfile, name, false); return; } if (id === "deleteprofile" || id === "resetprofile") { if (value === -1) return; if (!Number.isInteger(value)) throw new RangeError("Pick a profile."); // Only other profiles: the one in use is never touched from here. if (value === activeProfile) throw new RangeError("The active profile can't be removed or reset here."); if (id === "deleteprofile") await client.deleteProfile(value); else await client.factoryReset(value); return id === "resetprofile" ? "rebooted" : undefined; } if (id === "saveprofile") { await saveProfileFile(client, activeProfile, value); return; } if (id === "loadprofile") { await loadProfileFile(client, activeProfile, value); return; } if (id === "calibrate") { if (!Number.isInteger(value)) throw new RangeError("Pick what to do."); if (value === -1) return; await runCalibration(client, activeProfile, value as number); return; } const pairId = /^pair\.(.+)$/.exec(id); if (pairId) { if (!Number.isInteger(value)) throw new RangeError("Pick how the pair behaves."); await setPair(client, activeProfile, pairId[1], value as number); return; } const macroId = /^macro(mode)?\.(\d+)$/.exec(id); if (macroId) { const index = Number(macroId[2]); if (index < 0 || index >= 16) throw new RangeError("That macro does not exist."); const macros: MchoseMacro[] = await client.readMacros(); if (macroId[1]) { if (!Number.isInteger(value) || (value as number) < 0 || (value as number) > 255) throw new RangeError("Pick how the macro plays."); macros[index] = { ...macros[index], mode: value as number }; } else { macros[index] = { mode: macros[index].mode, steps: parseMacro(typeof value === "string" ? value : "") }; } await client.setMacros(macros); return; } if (id === "polling") { if (!Number.isInteger(value)) throw new RangeError("Pick a polling rate."); await client.setPollingRate(activeProfile, value); return; } const setting = SETTINGS[id]; if (!setting) throw new Error("Unknown MCHOSE keyboard control."); const valid = setting.type === "boolean" ? typeof value === "boolean" : Number.isInteger(value) && (value as number) >= 0 && (value as number) <= (setting.max ?? 255); if (!valid) throw new RangeError("That setting value is out of range."); const current: MchoseSettings = await client.readSettings(activeProfile); await client.setSettings(activeProfile, { ...current, [setting.field]: value }); } export async function mchoseOp(client: any, op: string, args: any): Promise { switch (op) { case "lighting": return readLights(client); case "setLighting": return setLights(client, args); case "keys": return readKeys(client, args?.layer); case "setKey": return setKey(client, args); case "setActuation": return setActuation(client, args); // Every change is already on the keyboard. case "save": return true; case "calibrationStatus": return calibrationStatus(); case "keyColours": return readKeyColours(client); case "setKeyColours": return setKeyColours(client, args); default: throw new Error(`Unknown keyboard operation ${op}`); } }