From b8b03dcded0e6329a6b3a7583419f80d73c6ab74 Mon Sep 17 00:00:00 2001 From: Fredrik Storm Date: Tue, 10 Nov 2026 21:51:05 +0100 Subject: [PATCH] feat(settings): add sleep and accessory controls - Add settings get/set commands with verified writes and dry-run support - Document the mechanical firmware protocol and CLI usage --- README.md | 2 + docs/reverse-engineering.md | 28 +++++ docs/usage.md | 40 ++++++++ src/app.rs | 8 +- src/cli.rs | 75 ++++++++++++++ src/main.rs | 1 + src/nuphy_protocol.rs | 59 +++++++++++ src/settings_cmd.rs | 197 ++++++++++++++++++++++++++++++++++++ 8 files changed, 409 insertions(+), 1 deletion(-) create mode 100644 src/settings_cmd.rs diff --git a/README.md b/README.md index 90b9236..062d657 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ - Set main/backlight, side-light, and decorative RGB effects. - Read, remap, back up, and restore keymaps, including declarative TOML configuration. +- Read and set automatic sleep, both sleep timers, and the knob/button accessory switch. - List HID devices and send raw reports for reverse engineering. ## Installation @@ -30,6 +31,7 @@ nuphyctl list nuphyctl rgb set --hex ff8800 --brightness 35 nuphyctl keymap info nuphyctl keymap dump --changed +nuphyctl settings get --accessory ``` Use `nuphyctl --help` or `nuphyctl --help` to explore the CLI. diff --git a/docs/reverse-engineering.md b/docs/reverse-engineering.md index 3f28189..8148982 100644 --- a/docs/reverse-engineering.md +++ b/docs/reverse-engineering.md @@ -142,6 +142,34 @@ Keycodes are QMK-style: `nuphyctl keymap keycodes` prints the full catalogue. +## Keyboard settings protocol (implemented) + +Recovered from NuPhy IO's `main.ba072d08.js` and settings chunk +`829.01203ccb.chunk.js` at on 2026-11-10. +These are data commands using the same session-key framing as keymap operations, +not the legacy lighting subcommand format. This path is for mechanical firmware; +HE models use a different configuration block. + +| cmd | name | address | length | data | +| --- | --- | --- | --- | --- | +| `0xf3` | GetSleepInfo | 0 | 4 | enable, Level 1 minutes, Level 2 minutes, reserved | +| `0xf5` | SetSleepCfg | 0 | 1 or 4 | same fields | +| `0xfb` | GetAppDefine | 168 | 1 | accessory: knob=0, button/key=1 | +| `0xfc` | SetAppDefine | 168 | 1 | accessory: knob=0, button/key=1 | + +The web app writes one byte for the sleep toggle. For timer changes it reads four +bytes, updates byte 1 or 2, and writes all four back. The CLI reads and preserves the +four-byte block when updating any sleep setting. No extra apply command is used. +The settings UI limits both timers to 5–127 minutes. The accessory offset applies +to boards exposing the swappable control, including the Air75 V3. + +Live read on the connected Air75 V3 returned sleep bytes `01 06 18 00` and accessory +`00`: auto-sleep on, Level 1 6 minutes, Level 2 24 minutes, knob. Changed-value writes +still need hardware validation; read-back verification is implemented for writes. + +The Keyboard Layout selector calls the web app's local preference setter and reloads +the page. It sends no HID command and is not a firmware setting. + ## 1) Capture packets in Chrome Open in Chrome, then open DevTools Console and paste: diff --git a/docs/usage.md b/docs/usage.md index 635a80b..a6868e9 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -25,6 +25,46 @@ Show help for a subcommand: cargo run -- rgb set --help ``` +## Keyboard settings + +Read sleep settings, optionally including the accessory switch: + +```bash +cargo run -- settings get +cargo run -- settings get --accessory --json +``` + +Update one or more settings: + +```bash +cargo run -- settings set --auto-sleep on --level1-minutes 6 --level2-minutes 24 +cargo run -- settings set --auto-sleep off +cargo run -- settings set --accessory knob +cargo run -- settings set --accessory button +cargo run -- settings set --level1-minutes 10 --dry-run +``` + +Both timers accept **5–127 minutes**, matching NuPhy IO. Level 1 turns off lighting; +Level 2 disables lighting and communication and requires Level 1 sleep first. +Disabling auto-sleep preserves both timers. Changing a timer preserves the sleep +toggle, the other timer, and the reserved configuration byte. + +Writes are read back and verified; unchanged values are skipped. `--dry-run` +reads the keyboard and prints the proposed values without writing. `--json` is +available for both commands. All device selectors (such as `--path`) work here too. +If an update to several settings fails partway through, earlier writes may have +succeeded; use `settings get` to inspect the device before retrying. + +These commands use the NuPhy IO **mechanical keyboard protocol**, read successfully +on an Air75 V3. HE models use a different configuration format and are not supported +by these commands. Use accessory options only for boards with a swappable knob/button; +`settings get` reads that model-dependent setting only when `--accessory` is passed. +Hardware writes have not yet been validated with changed values. + +The web app's **Keyboard Layout** selector (for example US-ANSI-WIN) changes its +virtual keyboard labels only. It does not change firmware or the operating system's +layout, so there is no corresponding device setting in this CLI. + ## Lighting examples Set a static backlight color (`#RRGGBB` or `RRGGBB`): diff --git a/src/app.rs b/src/app.rs index ccc950b..bac3591 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,7 +1,7 @@ use crate::cli::{ Cli, Command, DeviceSelector, KeymapSubcommand, RawSubcommand, RgbColorMode, RgbDecorativeSetArgs, RgbDirection, RgbEffect, RgbSetArgs, RgbSideEffect, RgbSideSetArgs, - RgbSubcommand, + RgbSubcommand, SettingsSubcommand, }; use crate::color::{RgbColor, parse_hex_bytes}; use crate::hid_transport::{ @@ -75,6 +75,10 @@ pub fn run(cli: Cli, api: &HidApi) -> Result<()> { Command::Raw(raw) => match raw.action { RawSubcommand::Send(args) => run_raw_send(api, &args.device, args.report_id, &args.hex), }, + Command::Settings(settings) => match settings.action { + SettingsSubcommand::Get(args) => crate::settings_cmd::run_get(api, &args), + SettingsSubcommand::Set(args) => crate::settings_cmd::run_set(api, &args), + }, } } @@ -375,6 +379,8 @@ fn parse_effect_color( fn print_commands() { const COMMANDS: &[&str] = &[ "list", + "settings get", + "settings set", "rgb set", "rgb side", "rgb decorative", diff --git a/src/cli.rs b/src/cli.rs index 9ad3805..143e3d1 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -18,6 +18,8 @@ pub enum Command { Rgb(RgbCommand), /// Keymap commands (read, remap, back up and restore keys) Keymap(KeymapCommand), + /// Keyboard sleep and accessory settings (NuPhy IO mechanical protocol) + Settings(SettingsCommand), /// Send a raw HID output report Raw(RawCommand), } @@ -44,6 +46,79 @@ pub struct DeviceSelector { pub usage: Option, } +#[derive(Args, Debug)] +pub struct SettingsCommand { + #[command(subcommand)] + pub action: SettingsSubcommand, +} + +#[derive(Subcommand, Debug)] +pub enum SettingsSubcommand { + /// Read sleep settings; optionally include the model-dependent accessory switch + Get(SettingsGetArgs), + /// Update only the specified settings, then read back and verify + Set(SettingsSetArgs), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] +pub enum Accessory { + Knob, + #[value(alias = "key")] + Button, +} + +impl Accessory { + pub const fn protocol_value(self) -> u8 { + match self { + Self::Knob => 0, + Self::Button => 1, + } + } +} + +#[derive(Args, Debug)] +pub struct SettingsGetArgs { + /// Also read the accessory switch (for boards with a swappable knob/button) + #[arg(long)] + pub accessory: bool, + #[arg(long)] + pub json: bool, + #[command(flatten)] + pub device: DeviceSelector, +} + +#[derive(Args, Debug)] +#[group(required = true, multiple = true, args = ["auto_sleep", "level1_minutes", "level2_minutes", "accessory"])] +pub struct SettingsSetArgs { + /// Enable or disable automatic keyboard sleep (on/off) + #[arg(long, value_parser = parse_on_off)] + pub auto_sleep: Option, + /// Idle time for Level 1 sleep (lights off), in minutes + #[arg(long, value_parser = clap::value_parser!(u8).range(5..=127))] + pub level1_minutes: Option, + /// Level 2 sleep timer (lights and communication off), in minutes + #[arg(long, value_parser = clap::value_parser!(u8).range(5..=127))] + pub level2_minutes: Option, + /// Installed accessory on boards with a swappable knob/button + #[arg(long, value_enum)] + pub accessory: Option, + /// Show proposed settings without writing + #[arg(long)] + pub dry_run: bool, + #[arg(long)] + pub json: bool, + #[command(flatten)] + pub device: DeviceSelector, +} + +fn parse_on_off(input: &str) -> Result { + match input { + "on" | "true" => Ok(true), + "off" | "false" => Ok(false), + _ => Err("expected on or off".into()), + } +} + #[derive(Subcommand, Debug)] pub enum RgbSubcommand { /// Set backlight effect and color using #RRGGBB or RRGGBB diff --git a/src/main.rs b/src/main.rs index d301dd9..91852fe 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ mod keycodes; mod keymap; mod keymap_cmd; mod nuphy_protocol; +mod settings_cmd; use anyhow::{Context, Result}; use clap::Parser; diff --git a/src/nuphy_protocol.rs b/src/nuphy_protocol.rs index c97a0ad..5555236 100644 --- a/src/nuphy_protocol.rs +++ b/src/nuphy_protocol.rs @@ -18,6 +18,11 @@ const CMD_GET_DEFAULT_KEYS: u8 = 0xb1; const CMD_GET_USE_KEYS: u8 = 0xb2; const CMD_SET_USE_KEYS: u8 = 0xb3; const CMD_RESTORE_USE_LAYERS: u8 = 0xb4; +const CMD_GET_SLEEP_INFO: u8 = 0xf3; +const CMD_SET_SLEEP_CFG: u8 = 0xf5; +const CMD_GET_APP_DEFINE: u8 = 0xfb; +const CMD_SET_APP_DEFINE: u8 = 0xfc; +const ACCESSORY_OFFSET: u16 = 168; const DATA_INFO_LEN: u8 = 8; const DATA_COMMAND_ATTEMPTS: usize = 3; @@ -86,6 +91,38 @@ impl<'a> KeyboardProtocol<'a> { self.session_key } + /// NuPhy IO mechanical firmware: enable, shallow minutes, deep minutes, + /// and a reserved byte. Preserve the reserved byte when updating timers. + pub fn read_sleep_settings(&self) -> Result<[u8; 4]> { + let data = self + .data_command(CMD_GET_SLEEP_INFO, 0, 4, &[]) + .context("GetSleepInfo failed; this firmware may not support sleep settings")?; + Ok(data + .try_into() + .expect("data_command returns requested length")) + } + + pub fn write_sleep_settings(&self, data: &[u8; 4]) -> Result<()> { + self.data_command(CMD_SET_SLEEP_CFG, 0, 4, data) + .context("SetSleepCfg failed")?; + Ok(()) + } + + pub fn read_accessory(&self) -> Result { + let data = self + .data_command(CMD_GET_APP_DEFINE, ACCESSORY_OFFSET, 1, &[]) + .context( + "cannot read accessory switch; use only on boards with a swappable knob/button", + )?; + Ok(data[0]) + } + + pub fn write_accessory(&self, value: u8) -> Result<()> { + self.data_command(CMD_SET_APP_DEFINE, ACCESSORY_OFFSET, 1, &[value]) + .context("failed to write accessory switch")?; + Ok(()) + } + pub fn set_main_light(&self, settings: MainLightSettings) -> Result<()> { let effect_id = settings.effect.protocol_id(); let light_payload = build_main_light_payload( @@ -599,6 +636,28 @@ mod tests { ); } + #[test] + fn settings_packets_match_nuphy_io_data_commands() { + let key = SessionKey(0x5a); + for (cmd, addr, len, payload) in [ + (CMD_GET_SLEEP_INFO, 0, 4, vec![]), + (CMD_SET_SLEEP_CFG, 0, 4, vec![1, 6, 24, 0xa5]), + (CMD_GET_APP_DEFINE, ACCESSORY_OFFSET, 1, vec![]), + (CMD_SET_APP_DEFINE, ACCESSORY_OFFSET, 1, vec![1]), + ] { + let packet = build_data_packet(cmd, addr, len, &payload, key).unwrap(); + assert_eq!(packet[1], cmd); + assert_eq!(decode_data_header(&packet, key), (len, addr)); + assert_eq!(packet[7] ^ key.value(), 0); + assert_eq!(packet[3], calc_checksum(&packet)); + for (i, byte) in payload.iter().enumerate() { + assert_eq!(packet[8 + i] ^ key.value(), *byte); + } + let response = reply(cmd, len, addr, &payload, key.value()); + assert!(parse_data_response(&response, cmd, addr, len, key).is_ok()); + } + } + fn reply(cmd: u8, len: u8, addr: u16, data: &[u8], key: u8) -> Report { let mut r = [0u8; REPORT_LEN]; r[0] = 0xaa; diff --git a/src/settings_cmd.rs b/src/settings_cmd.rs new file mode 100644 index 0000000..4e0afcd --- /dev/null +++ b/src/settings_cmd.rs @@ -0,0 +1,197 @@ +//! Sleep settings use the NuPhy IO mechanical protocol, not the HE config block. +use crate::cli::{SettingsGetArgs, SettingsSetArgs}; +use crate::hid_transport::{clear_input_reports, open_selected_device}; +use crate::nuphy_protocol::KeyboardProtocol; +use anyhow::{Context, Result, bail}; +use hidapi::HidApi; +use serde_json::{Value, json}; + +pub fn run_get(api: &HidApi, args: &SettingsGetArgs) -> Result<()> { + let dev = open_selected_device(api, &args.device)?; + clear_input_reports(&dev)?; + let protocol = KeyboardProtocol::new(&dev)?; + let sleep = protocol.read_sleep_settings()?; + let accessory = args + .accessory + .then(|| protocol.read_accessory()) + .transpose()?; + print_settings(Some(sleep), accessory, args.json, None); + Ok(()) +} + +pub fn run_set(api: &HidApi, args: &SettingsSetArgs) -> Result<()> { + let dev = open_selected_device(api, &args.device)?; + clear_input_reports(&dev)?; + let protocol = KeyboardProtocol::new(&dev)?; + let changes_sleep = + args.auto_sleep.is_some() || args.level1_minutes.is_some() || args.level2_minutes.is_some(); + // Read everything needed before performing any writes. + let before_sleep = changes_sleep + .then(|| protocol.read_sleep_settings()) + .transpose()?; + let desired_sleep = before_sleep.map(|current| update_sleep(current, args)); + let before_accessory = args + .accessory + .map(|_| protocol.read_accessory()) + .transpose()?; + let desired_accessory = args.accessory.map(|value| value.protocol_value()); + + if !args.dry_run { + if let Some(desired) = desired_sleep { + if Some(desired) != before_sleep { + protocol.write_sleep_settings(&desired)?; + } + let actual = protocol + .read_sleep_settings() + .context("sleep settings may have been written, but read-back failed")?; + if actual != desired { + bail!("sleep settings verification failed: expected {desired:?}, got {actual:?}"); + } + } + if let Some(desired) = desired_accessory { + if Some(desired) != before_accessory { + protocol.write_accessory(desired)?; + } + let actual = protocol + .read_accessory() + .context("accessory setting may have been written, but read-back failed")?; + if actual != desired { + bail!("accessory verification failed: expected {desired}, got {actual}"); + } + } + } + print_settings( + desired_sleep, + desired_accessory, + args.json, + Some(args.dry_run), + ); + Ok(()) +} + +fn update_sleep(mut current: [u8; 4], args: &SettingsSetArgs) -> [u8; 4] { + if let Some(enabled) = args.auto_sleep { + current[0] = u8::from(enabled); + } + if let Some(minutes) = args.level1_minutes { + current[1] = minutes; + } + if let Some(minutes) = args.level2_minutes { + current[2] = minutes; + } + current +} + +fn print_settings( + sleep: Option<[u8; 4]>, + accessory: Option, + json_output: bool, + dry_run: Option, +) { + let mut output = json!({}); + if let Some(data) = sleep { + output["auto_sleep"] = json!(data[0] != 0); + output["level1_minutes"] = json!(data[1]); + output["level2_minutes"] = json!(data[2]); + } + if let Some(value) = accessory { + output["accessory"] = match value { + 0 => json!("knob"), + 1 => json!("button"), + _ => json!(format!("unknown ({value})")), + }; + } + if let Some(dry_run) = dry_run { + output["dry_run"] = json!(dry_run); + } + if json_output { + println!("{output}"); + } else { + if dry_run == Some(true) { + println!("Proposed settings (no writes):"); + } + for (key, value) in output.as_object().expect("settings object") { + if key == "dry_run" { + continue; + } + let text = match value { + Value::String(text) => text.clone(), + other => other.to_string(), + }; + println!("{key}: {text}"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cli::{Cli, Command, SettingsSubcommand}; + use clap::Parser; + + fn set_args(flags: &[&str]) -> SettingsSetArgs { + let mut argv = vec!["nuphyctl", "settings", "set"]; + argv.extend_from_slice(flags); + let Command::Settings(command) = Cli::try_parse_from(argv).unwrap().command else { + panic!() + }; + let SettingsSubcommand::Set(args) = command.action else { + panic!() + }; + args + } + + #[test] + fn updates_preserve_unrequested_fields_and_reserved_byte() { + let current = [1, 6, 24, 0xa5]; + assert_eq!( + update_sleep(current, &set_args(&["--level1-minutes", "10"])), + [1, 10, 24, 0xa5] + ); + assert_eq!( + update_sleep(current, &set_args(&["--auto-sleep", "off"])), + [0, 6, 24, 0xa5] + ); + assert_eq!( + update_sleep( + current, + &set_args(&["--level2-minutes", "127", "--auto-sleep", "on"]) + ), + [1, 6, 127, 0xa5] + ); + } + + #[test] + fn rejects_invalid_or_empty_updates() { + for flags in [ + vec![], + vec!["--json"], + vec!["--dry-run"], + vec!["--level1-minutes", "4"], + vec!["--level2-minutes", "128"], + vec!["--auto-sleep", "maybe"], + vec!["--accessory", "slider"], + ] { + let mut argv = vec!["nuphyctl", "settings", "set"]; + argv.extend(flags); + assert!(Cli::try_parse_from(argv).is_err()); + } + for minutes in ["5", "127"] { + set_args(&["--level1-minutes", minutes, "--level2-minutes", minutes]); + } + assert_eq!( + set_args(&["--accessory", "knob"]) + .accessory + .unwrap() + .protocol_value(), + 0 + ); + assert_eq!( + set_args(&["--accessory", "button"]) + .accessory + .unwrap() + .protocol_value(), + 1 + ); + } +}