Skip to content

Architecture

Keymotion is one Windows program. Rust does all the work: it finds keyboards, builds every packet, talks to the hardware and runs the background features. The React interface only shows things and collects the user’s choices. Tauri 2 hosts that interface in WebView2 and connects it to Rust.

app/src React + TypeScript pages, editors, previews
│ invoke() and events, with types generated by ts-rs
app/src-tauri Tauri 2 shell commands, the device actor, background tasks, tray, updater
│
kb-core shared logic detection, the protocol driver, color, read-back
├── kb-protocol packets and the safety guard (no I/O)
├── kb-devices model files and matching (no I/O)
└── kb-transport HID and Bluetooth LE access (moves bytes)
kb-winsys Windows readings processor, graphics, audio, running programs
kb-cli (kb) developer tool on the same crates

The Cargo workspace is crates/* plus app/src-tauri. The workspace denies unsafe code; only kb-winsys allows it.

Crate Role
kb-protocol Pure packet encoding and decoding for the SONiX command family the AK980 PRO speaks: command headers, lighting, per-key tables, keymaps, macros, screen images, the clock. It holds the command allowlist and guard, which every packet passes before it is sent. No I/O, so every packet is unit-tested.
kb-devices Keyboard model files (TOML in models/, embedded at compile time) and matching: which model and connection mode an HID collection belongs to. No I/O.
kb-transport Raw device access. hid enumerates HID collections and exchanges feature, output and input reports through hidapi. ble reads the battery over Bluetooth LE through WinRT and has no write function. It moves bytes and knows nothing about protocols.
kb-core Logic shared by the app and kb: detection (detect), HID descriptor shape checks (shape), the command-channel driver with its sessions, echoes, checksums and screen upload (sonix), color calibration (color), read-back interpretation (readback), programs that conflict with the keyboard (conflicts), the clock, keymap rules and screen import.
kb-winsys Readings from Windows for the system gauges and reminders: processor, graphics and memory load, speaker volume, microphone mute, idle time, running programs. Also the Windows version, per-user data protection for calendar addresses, the startup entry and the notification identity. The only crate that calls Win32 and COM directly, behind small safe types.
kb-cli The kb developer tool: lists keyboards, reads descriptors and colors, streams live frames, and runs measured write commands behind --yes.

app/src-tauri builds the keymotion executable. It is deliberately thin: it wires Tauri commands and events to the crates.

  • Commands. lib.rs defines every #[tauri::command]. A command converts its input from the interface’s types, hands the work on, and returns a result or an English error string. The interface maps those errors to its own messages (app/src/lib/errors.ts).
  • The device actor (device.rs) is the only code that talks to keyboards. One thread owns the HID subsystem. Requests arrive on a channel and run one at a time, so two protocol sessions can never interleave. Between requests it re-enumerates devices every 2 seconds, re-sends the current live frame every 50 ms, reads the keys’ colors every 250 ms while the interface shows its mirror, and sets the keyboard’s clock when it connects (at most once a day). It keeps the app’s own record of the keymap and macros, because the keyboard cannot report them.
  • Background tasks, each with its own handle, started in setup: the live screen worker (live.rs), what Windows reports as playing (now_playing.rs), the focus timer (pomodoro.rs), the system gauges (gauges.rs), the calendar (calendar.rs, ics.rs), reminders (reminders.rs) and updates (updates.rs). They hand light layers to the device actor and screen cards to the live worker.
  • The tray (tray.rs). Closing the window can hide it, and the app goes on in the notification area, because the focus timer, reminders, calendar cards, live screen and gauges only work while it runs. The menu shows the keyboard and offers the focus timer, reminders, gauges, profiles and Quit. A profile chosen there opens the window to confirm it, since every write to permanent memory needs the user’s yes.
  • The updater (updates.rs, tauri-plugin-updater). The release workflow publishes latest.json with each GitHub release; the updater checks the download against the public key in tauri.conf.json. If the user allows it, the app looks once a day; nothing installs until the user chooses to, and installing waits for a write to the keyboard to finish.
  • Storage. Settings are versioned JSON files in %APPDATA%\dev.keymotion (settings.rs); a damaged file is kept aside and reported once. The screen library (screen_lib.rs) is the only copy of uploaded pictures, because the keyboard cannot give them back. Logs go to %LOCALAPPDATA%\dev.keymotion\logs, one file a day.
  • One instance. tauri-plugin-single-instance brings the open window forward instead of starting a second copy, which would send commands at the same time. A second start with Windows (--hidden) stays quiet, and the GitHub copy hands over to an installed Microsoft Store copy (handoff.rs; Microsoft Store package).

app/src is React 19 and TypeScript, built with Vite and styled with Tailwind CSS.

  • pages/ has one component per sidebar page, components/ the shared pieces.
  • lib/ holds each feature’s logic and state (zustand stores), lib/ipc.ts every call to the backend, and lib/i18n.ts every text in Turkish and English.
  • The interface holds no keyboard logic. It prepares data, for example the screen image in the keyboard’s format (lib/screen.ts), but the backend validates everything again: the interface is not trusted with the keyboard’s format.
  • Tauri runs commands concurrently, so two quick calls can arrive in the wrong order. Commands that change state go through one serial queue in lib/ipc.ts.

The types the interface and the backend exchange are declared once, in Rust, in app/src-tauri/src/dto.rs:

#[derive(Debug, Clone, Serialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export)]
pub struct UiEnvironment {
pub app_version: String,
pub mica: bool,
pub os_build: u32,
}

cargo test exports them with ts-rs to app/src/bindings/*.ts (.cargo/config.toml sets TS_RS_EXPORT_DIR), and the interface imports them:

import type { UiEnvironment } from "../bindings/UiEnvironment";

The same test run writes the browser mock’s data from Rust: the effect catalogue, the keymap catalogue and each model’s geometry (lighting-catalog.json, keymap-catalog.json, geometry-<model>.json). Never edit app/src/bindings by hand. Commit it after cargo test; CI fails when it is out of date.

For interface work without the app or a keyboard, run pnpm --dir app dev and open http://127.0.0.1:1420/ in a browser. Outside Tauri, each function in lib/ipc.ts returns stand-in data instead of calling the backend; lib/screen.ts, live.ts, pomodoro.ts, calendar.ts, reminders.ts and gauges.ts have their own. Switches in the address:

Switch What it does
?mock=usb, bluetooth, dongle, none The connection to pretend. Default: bluetooth.
?fw=1.07 A firmware version nobody has tested, to see the confirmation before a write.
?unsupported A keyboard the app doesn’t support yet, with Request support.
?reset=keymap,macros The notice about settings files that went back to their defaults.
?failPart=lighting A profile part that fails to load.
?crash The note about a problem last time.
?update=available, none, offline, norelease The update check’s answer.

window.dispatchEvent(new Event("mock-close-requested")) stands in for the window’s close button.

The mock exists in development only. Every mock branch is guarded by import.meta.env.DEV, which Vite replaces with false in a production build, so the mock and its switches are not in the installed app; there, a call outside Tauri fails with a clear error. The mock never talks to a keyboard: check every change in the real app as well.

Saving a lighting effect, step by step:

  1. On the Lighting page the user presses Save to keyboard. applyEffect in lib/ipc.ts wraps the call in flashWrite, which asks the user if the firmware is untested, and queues it on the serial queue as invoke("apply_effect", { request }).

  2. The apply_effect command in lib.rs turns the EffectRequest into EffectSettings and passes it to the device actor on a blocking thread.

  3. The device actor announces a write to permanent memory (flash-write), applies the user’s color calibration, and runs the write gate: one keyboard on the cable, no conflicting program, a tested firmware version or the user’s confirmation. It opens the command channel if needed, checking the collection’s descriptor shape first.

  4. kb_core::sonix::SonixFf13::apply_effect asks kb_protocol::sonix::lighting_data to validate and encode the effect, then runs the session: open, announce one data packet, send it, commit and compare the keyboard’s checksum, apply.

  5. Every packet passes kb_protocol::sonix::guard, gets report ID 0 in front, and goes out through kb_transport::hid::HidChannel::send_feature as a 65-byte HID feature report. Echoes come back with get_feature, which retries when Windows reports a stalled request.

  6. The result returns along the same path. The interface shows Saved to the keyboard, and flash-write reports that the write ended.

Other paths use the same layers. A preview sends set_live_frame; the actor keeps the frame and sends it as a RAM-only live frame every 50 ms, with the focus timer’s or the gauges’ light layer underneath. A screen upload starts as an image the interface prepared; screen_add validates it again, and screen_upload sends it page by page on the screen channel, with progress events. Live cards from the focus timer, the calendar, reminders and the song that is playing go through the live worker, which waits for the cable and the daily upload limit.

Each layer works on its own, so a mistake in one is caught by the next.

Layer Where What it does
Command allowlist kb_protocol::sonix::guard, Op A command header must start with 04 and carry an opcode on the list. Anything else is refused, including commands the firmware accepts but nobody here has measured.
Blocked bootloader guard, guard_screen_page, kb_transport::ble Firmware-update and in-system-programming sequences are refused at the start of any packet, on both channels. The encoders adjust user data (a color, a key entry) so it can never start like one. The Bluetooth module has no write function. Only collections that match a model file are ever opened.
Shape checks kb_core::shape, device::open_checked When a channel opens, its report descriptor (read from Windows, nothing sent) must have the expected layout: 64-byte feature and output reports without report IDs for commands, a 4096-byte output report for the screen. Keyboards with the same IDs but another command family fail here, and nothing is sent to them.
Size and value limits kb-protocol, kb_core::screen_import Packets are at most 64 bytes and screen pages exactly 4096. An upload has at most 140 frames and 2,215 pages. LED and key indices, brightness, speed, direction, macro size and clock fields are range-checked before encoding. Imported files have size, frame and memory limits.
Delivery checks kb_core::sonix The keyboard’s byte sum in the commit echo is compared with what was sent; on a mismatch the write fails and is not applied. The clock’s data echo is compared byte for byte. Every screen page waits for its acknowledgement. A live frame, once started, is always completed.
Write gate device::write_block No writes to permanent memory with more than one keyboard on the cable, while a known program talks to the keyboard (the official driver, SignalRGB, OpenRGB, kb), or on a firmware version not in the model’s tested list until the user confirms it for this session.
One writer the device actor, the serial queue, single instance Requests run one at a time on one thread, so sessions never interleave.
Daily screen upload limit live.rs Every upload erases flash, so the live screen runs on a token bucket: Low 8 a day (3 in a row), Balanced 24 (6), High 48 (8). Uploads the user starts by hand count too but are never blocked; the debt is capped so the live screen is not locked out for long. An upload that never reached the keyboard is given back.
Writes in progress flash-write, kb-winsys While permanent memory is written, closing the app waits and Windows is told why shutting down now is a bad idea.