From 44679cda2cc5cbf50b9d2671d370632cbee68b87 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 11 Nov 2026 18:09:07 -0700 Subject: [PATCH] config: add persistent flash-backed configuration with a HID command interface and CLI management --- Cargo.lock | 138 ++++++-- cli/src/main.rs | 629 +++++++++++++++++++++++++++++++-- firmware/Cargo.toml | 2 +- firmware/build.rs | 34 +- firmware/memory.x | 7 +- firmware/src/config.rs | 306 ++++++++++++++++ firmware/src/dac/ak4490.rs | 9 + firmware/src/dac/cs4398.rs | 5 + firmware/src/dac/noop.rs | 4 + firmware/src/dac/wm8904.rs | 5 + firmware/src/hid_config.rs | 455 ++++++++++++++++++++++++ firmware/src/main.rs | 163 ++++++--- firmware/src/traits.rs | 1 + shared/Cargo.toml | 6 +- shared/src/config/container.rs | 268 ++++++++++++++ shared/src/config/error.rs | 89 +++++ shared/src/config/mod.rs | 607 +++++++++++++++++++++++++++++++ shared/src/config/schema.rs | 198 +++++++++++ shared/src/config/tag.rs | 26 ++ shared/src/config/tlv.rs | 179 ++++++++++ shared/src/config/value.rs | 182 ++++++++++ shared/src/hardware.rs | 136 +++++++ shared/src/lib.rs | 182 ++++++++-- 23 files changed, 3483 insertions(+), 148 deletions(-) create mode 100644 firmware/src/config.rs create mode 100644 firmware/src/hid_config.rs create mode 100644 shared/src/config/container.rs create mode 100644 shared/src/config/error.rs create mode 100644 shared/src/config/mod.rs create mode 100644 shared/src/config/schema.rs create mode 100644 shared/src/config/tag.rs create mode 100644 shared/src/config/tlv.rs create mode 100644 shared/src/config/value.rs create mode 100644 shared/src/hardware.rs diff --git a/Cargo.lock b/Cargo.lock index d01f0bd..5b659fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -273,7 +273,7 @@ checksum = "c0cb6f3d4773a2107b94cbeccaa5b5f0b35a88389b5d522d13d659f64317b22d" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -359,7 +359,7 @@ checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -380,9 +380,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.11.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" dependencies = [ "find-msvc-tools", "shlex", @@ -441,7 +441,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -544,7 +544,7 @@ checksum = "05cf9e0f899304705b85fda7b178fc383f2529ec2479693248b600e530d2327a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -610,14 +610,38 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core 0.20.11", + "darling_macro 0.20.11", +] + [[package]] name = "darling" version = "0.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" dependencies = [ - "darling_core", - "darling_macro", + "darling_core 0.21.3", + "darling_macro 0.21.3", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", ] [[package]] @@ -634,13 +658,24 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core 0.20.11", + "quote", + "syn 2.0.119", +] + [[package]] name = "darling_macro" version = "0.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" dependencies = [ - "darling_core", + "darling_core 0.21.3", "quote", "syn 2.0.119", ] @@ -673,7 +708,7 @@ dependencies = [ "defmt-parser", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -713,7 +748,7 @@ version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bec2a42b511fc5efd9183f4f71c17885d627b17e7fd9a61a92089406caa4397e" dependencies = [ - "darling", + "darling 0.21.3", "proc-macro-crate", "proc-macro2", "quote", @@ -1007,6 +1042,18 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "heapless" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ba4bd83f9415b58b4ed8dc5714c76e626a105be4646c02630ad730ad3b5aa4" +dependencies = [ + "defmt 1.2.0", + "hash32 0.3.1", + "serde_core", + "stable_deref_trait", +] + [[package]] name = "heck" version = "0.5.0" @@ -1052,17 +1099,16 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "jiff" -version = "0.2.39" +version = "0.2.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ac703058abac89e5c39b0b879dce2b6b14a4ba36600c7e7e3d0c60a6883ef3c" +checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a" dependencies = [ - "defmt 1.2.0", "jiff-core", "jiff-static", "log", @@ -1073,19 +1119,18 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.2" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aee43309eb53bafb8c36d35d6e444769c8f8e6206a9fbf7546f5db9d7d4a0e93" +checksum = "ffe6854081f5ac0a3046a9b223729ccd7a20b1e0e8277e44dc0660eedf67dfe2" dependencies = [ - "defmt 1.2.0", "log", ] [[package]] name = "jiff-static" -version = "0.2.39" +version = "0.2.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dc32470c67eb7d0e9ccb74303fa925313dc04cecb1aa048beaa6f391e36a93d" +checksum = "4b4ff49b2887190c760b86207b55cdcaabbdecaf7a0660d68aa2ed6f652abf0a" dependencies = [ "jiff-core", "proc-macro2", @@ -1139,9 +1184,9 @@ dependencies = [ [[package]] name = "loom" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca" +checksum = "f1611ddbf89dc6ae42cfbd51fc207836140130257646eab8d6d2fb16577db2d2" dependencies = [ "cfg-if", "generator", @@ -1707,7 +1752,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1739,9 +1784,11 @@ dependencies = [ "bytemuck", "defmt 1.2.0", "deku", + "heapless 0.9.3", "num_enum", "serde", "usbd-hid", + "wary", ] [[package]] @@ -1768,9 +1815,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.4" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" [[package]] name = "smol" @@ -1861,9 +1908,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.9" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -1893,7 +1940,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1907,18 +1954,18 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.2+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" dependencies = [ "serde_core", ] [[package]] name = "toml_edit" -version = "0.25.18+spec-1.1.0" +version = "0.25.19+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ec6e78bd70db9420d8d212fa9dc97f116448a1ceff5d00eabb991d407e21396" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" dependencies = [ "indexmap", "toml_datetime", @@ -2049,7 +2096,7 @@ dependencies = [ "proc-macro2", "quote", "serde", - "syn 3.0.9", + "syn 3.0.10", "usbd-hid-descriptors", ] @@ -2106,6 +2153,29 @@ dependencies = [ "vcell", ] +[[package]] +name = "wary" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a416a0064ca6c13523354b9f26090ec9348ced3cbe5b915749c2351bfd2eaf7" +dependencies = [ + "serde", + "thiserror", + "wary_derive", +] + +[[package]] +name = "wary_derive" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42642dee10f1d8cce235f5e71139c8490545dce99d40ad34285c2383ee62645a" +dependencies = [ + "darling 0.20.11", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows" version = "0.61.3" diff --git a/cli/src/main.rs b/cli/src/main.rs index 99d5408..a19021e 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -6,18 +6,27 @@ use std::{ Arc, atomic::{AtomicBool, Ordering}, }, - time::Duration, + time::{Duration, Instant}, }; use async_hid::{ - AsyncHidRead, AsyncHidWrite, Device, DeviceReader, HidBackend, HidError, HidResult, + AsyncHidFeatureHandle, AsyncHidRead, Device, DeviceFeatureHandle, DeviceReader, HidBackend, + HidError, HidResult, }; use clap::{Parser, Subcommand, ValueEnum}; use deku::DekuContainerRead; use futures_lite::StreamExt; use shared::{ - AudioDeviceCommand, AudioTelemetrySnapshot, - hid::{AudioDeviceCommandReport, AudioTelemetryReport, USAGE_COMMAND, USAGE_TELEMETRY}, + AudioTelemetrySnapshot, + config::{ConfigBytes, ConfigSnapshot, ConfigTag, DeviceConfig, Tlv, TlvList, tags}, + hardware::HardwareInfo, + hid::{ + AudioTelemetryReport, USAGE_COMMAND, USAGE_TELEMETRY, + command::{ + COMMAND_PAYLOAD_LEN, COMMAND_REPORT_SIZE, CommandKind, HEADER_LEN, Header, + IN_PAYLOAD_LEN, IN_REPORT_SIZE, NackCode, ResponseKind, + }, + }, }; use smol_timeout::TimeoutExt; @@ -51,7 +60,38 @@ impl FromStr for UsbVidPid { } } -#[derive(Subcommand, Clone, Copy, Debug)] +#[derive(clap::Args, Clone, Debug)] +struct ConfigArgs { + /// Restore the built-in default configuration + #[arg( + long, + conflicts_with_all = ["vendor_id", "product_id", "manufacturer", "product", "serial"] + )] + reset: bool, + + /// USB vendor ID, in hex + #[arg(long, value_parser = parse_hex_u16)] + vendor_id: Option, + /// USB product ID, in hex + #[arg(long, value_parser = parse_hex_u16)] + product_id: Option, + /// USB manufacturer string + #[arg(long)] + manufacturer: Option, + /// USB product string + #[arg(long)] + product: Option, + /// USB serial string + #[arg(long)] + serial: Option, +} + +fn parse_hex_u16(value: &str) -> Result { + u16::from_str_radix(value.trim_start_matches("0x"), 16) + .map_err(|_| "expected a 16-bit hex value".to_string()) +} + +#[derive(Subcommand, Clone, Debug)] enum Command { /// Continuously print statistics from the connected device Monitor { @@ -70,6 +110,12 @@ enum Command { #[arg(short, long, default_value_t = false)] bootloader: bool, }, + /// Update configuration values + Config(ConfigArgs), + /// Show the device configuration + Show, + /// Show device hardware information + Hardware, } #[derive(Parser, Debug)] @@ -172,14 +218,56 @@ impl Drop for JsonEmitter { } } +fn usage_name(usage: u16) -> &'static str { + match usage { + USAGE_TELEMETRY => "telemetry", + USAGE_COMMAND => "command", + _ => "unknown", + } +} + /// The device exposes one vendor HID interface per usage; pick the one we need. -async fn find_device(vidpid: &UsbVidPid, usage_id: u16) -> HidResult { - Ok(HidBackend::default() +async fn try_find_device(vidpid: &UsbVidPid, usage_id: u16) -> HidResult> { + log::debug!( + "searching for {:04x}:{:04x} {} interface", + vidpid.vid, + vidpid.pid, + usage_name(usage_id) + ); + + let device = HidBackend::default() .enumerate() .await? .find(|d| d.product_id == vidpid.pid && d.vendor_id == vidpid.vid && d.usage_id == usage_id) - .await - .expect("GUAC device not found or not accessible (try as root?)")) + .await; + + if let Some(device) = &device { + log::info!( + "found {} interface: {:04x}:{:04x} {}", + usage_name(usage_id), + device.vendor_id, + device.product_id, + device.name + ); + } + + Ok(device) +} + +async fn find_device(vidpid: &UsbVidPid, usage_id: u16) -> HidResult { + try_find_device(vidpid, usage_id).await?.ok_or_else(|| { + log::error!( + "{:04x}:{:04x} {} interface not found", + vidpid.vid, + vidpid.pid, + usage_name(usage_id) + ); + HidError::Message( + "GUAC device not found or not accessible (try as root?)" + .to_string() + .into(), + ) + }) } async fn read_telemetry_report( @@ -196,7 +284,7 @@ async fn read_telemetry_report( match AudioTelemetryReport::from_bytes((buf, 0)) { Ok((_, r)) => Ok(r), Err(e) => { - eprintln!("Unable to parse report: {:?}", e); + log::error!("unable to parse telemetry report: {:?}", e); Err(HidError::Message("Unable to parse report".into())) } } @@ -212,11 +300,484 @@ async fn emit_telemetry_reports( let mut i = 0; while i < c && !stop.load(Ordering::Relaxed) { let Ok(r) = read_telemetry_report(&mut reader).await else { + log::warn!("telemetry stream ended"); break; }; writer.emit(&r.into()); i += count.map_or(0, |_| 1) } + + log::info!("telemetry complete"); +} + +async fn send_command( + handle: &mut DeviceFeatureHandle, + seq: u8, + kind: CommandKind, + payload: &[u8], +) -> HidResult<()> { + let total_len = payload.len(); + let mut offset = 0; + + log::info!( + "sending {:?} seq={} ({} payload bytes)", + kind, + seq, + total_len + ); + + loop { + let len = (total_len - offset).min(COMMAND_PAYLOAD_LEN); + // hidraw strips the leading report ID byte, which is 0 for an unnumbered report. + let mut report = [0u8; 1 + COMMAND_REPORT_SIZE]; + + Header { + kind: kind as u8, + seq, + total_len: total_len as u16, + offset: offset as u16, + len: len as u8, + } + .encode(&mut report[1..1 + HEADER_LEN]); + + report[1 + HEADER_LEN..1 + HEADER_LEN + len] + .copy_from_slice(&payload[offset..offset + len]); + + log::debug!( + "tx seq={} offset={}/{} len={}: {:02x?}", + seq, + offset, + total_len, + len, + &report[1..] + ); + + handle.write_feature_report(&report).await?; + offset += len; + + if offset >= total_len { + break; + } + } + + Ok(()) +} + +async fn read_header_report( + reader: &mut DeviceReader, +) -> HidResult<([u8; IN_REPORT_SIZE], Header)> { + let mut report = [0u8; IN_REPORT_SIZE]; + let len = reader + .read_input_report(&mut report) + .timeout(Duration::from_secs(2)) + .await + .ok_or_else(|| HidError::message("timed out waiting for device response"))??; + + let header = + Header::parse(&report[..len]).ok_or_else(|| HidError::message("invalid HID response"))?; + + log::debug!("rx {:?}: {:02x?}", header, &report[..len]); + + if HEADER_LEN + usize::from(header.len) > len { + log::error!( + "invalid response length: header {} in {} bytes", + header.len, + len + ); + return Err(HidError::message("invalid HID response length")); + } + + Ok((report, header)) +} + +fn nack_error(code: Option) -> HidError { + HidError::message(match code { + Some(code) => format!("device rejected command: {code:?}"), + None => "device rejected command".to_string(), + }) +} + +async fn wait_ack(reader: &mut DeviceReader, seq: u8) -> HidResult<()> { + log::debug!("waiting for ACK seq={}", seq); + + loop { + let (report, header) = read_header_report(reader).await?; + + if header.seq != seq { + log::debug!("ignoring stale response for seq={}", header.seq); + continue; + } + + match ResponseKind::try_from(header.kind) { + Ok(ResponseKind::Ack) => { + log::info!("acknowledged seq={}", seq); + return Ok(()); + } + Ok(ResponseKind::Nack) => { + let code = report + .get(HEADER_LEN) + .copied() + .and_then(|byte| NackCode::try_from(byte).ok()); + log::error!("nack seq={} code={:?}", seq, code); + return Err(nack_error(code)); + } + Ok(ResponseKind::Noop) => continue, + Ok(ResponseKind::ConfigData) | Ok(ResponseKind::Hardware) => { + log::error!("expected ACK seq={} but got data", seq); + return Err(HidError::message("unexpected data")); + } + Err(_) => { + log::error!("invalid response kind {}", header.kind); + return Err(HidError::message("invalid response kind")); + } + } + } +} + +async fn read_message( + reader: &mut DeviceReader, + seq: u8, + expected: ResponseKind, +) -> HidResult> { + let mut data = Vec::new(); + let mut total_len = None; + + loop { + let (report, header) = read_header_report(reader).await?; + + if header.seq != seq { + continue; + } + + match ResponseKind::try_from(header.kind) { + Ok(kind) if kind == expected => { + let offset = usize::from(header.offset); + let len = usize::from(header.len); + let total = usize::from(header.total_len); + + if len > IN_PAYLOAD_LEN || offset != data.len() || data.len() + len > total { + log::error!( + "invalid chunk: offset={} len={} total={} received={}", + offset, + len, + total, + data.len() + ); + return Err(HidError::message("invalid response chunk")); + } + + if let Some(existing) = total_len + && existing != total + { + log::error!("inconsistent response length: {} != {}", existing, total); + return Err(HidError::message("inconsistent response length")); + } + total_len = Some(total); + + log::debug!( + "rx chunk seq={} offset={}/{} len={}", + seq, + offset, + total, + len + ); + + data.extend_from_slice(&report[HEADER_LEN..HEADER_LEN + len]); + + if data.len() == total { + log::info!("received {} bytes seq={}", data.len(), seq); + return Ok(data); + } + } + Ok(ResponseKind::Nack) => { + let code = report + .get(HEADER_LEN) + .copied() + .and_then(|byte| NackCode::try_from(byte).ok()); + log::error!("nack seq={} code={:?}", seq, code); + return Err(nack_error(code)); + } + Ok(ResponseKind::Ack) | Ok(ResponseKind::Noop) => continue, + Ok(kind) => { + log::error!("unexpected response {:?}, wanted {:?}", kind, expected); + return Err(HidError::message("unexpected response")); + } + Err(_) => { + log::error!("invalid response kind {}", header.kind); + return Err(HidError::message("invalid response kind")); + } + } + } +} + +async fn read_config( + reader: &mut DeviceReader, + handle: &mut DeviceFeatureHandle, + seq: u8, +) -> HidResult { + send_command(handle, seq, CommandKind::ReadConfig, &[]).await?; + let data = read_message(reader, seq, ResponseKind::ConfigData).await?; + + let snapshot = ConfigSnapshot::parse(&data) + .map_err(|error| HidError::message(format!("invalid config: {error}")))?; + + log::info!( + "config from slot {} ({} tags)", + snapshot.active_slot, + snapshot.config.tlvs.len() + ); + log::debug!("config tlvs: {:?}", snapshot.config.tlvs); + + Ok(snapshot) +} + +async fn replace_tlv( + reader: &mut DeviceReader, + handle: &mut DeviceFeatureHandle, + seq: u8, + tag: ConfigTag, + value: &[u8], +) -> HidResult<()> { + let mut payload = Vec::with_capacity(2 + value.len()); + payload.extend_from_slice(&tag.0.to_le_bytes()); + payload.extend_from_slice(value); + + log::info!("setting {:?} ({} bytes)", tag, value.len()); + log::debug!("value for {:?}: {:02x?}", tag, value); + + send_command(handle, seq, CommandKind::ReplaceTlv, &payload).await?; + wait_ack(reader, seq).await +} + +async fn read_hardware( + reader: &mut DeviceReader, + handle: &mut DeviceFeatureHandle, +) -> HidResult { + send_command(handle, 0, CommandKind::Hardware, &[]) + .await + .map_err(|error| HidError::message(format!("hardware command write failed: {error}")))?; + let data = read_message(reader, 0, ResponseKind::Hardware) + .await + .map_err(|error| HidError::message(format!("hardware data failed: {error}")))?; + + let info = HardwareInfo::parse(&data) + .map_err(|error| HidError::message(format!("invalid hardware info: {error}")))?; + + log::debug!( + "hardware: uuid={:02x?} dac={:?} firmware={:?}", + &info.uuid[..], + info.dac.as_str(), + info.version.as_str() + ); + + Ok(info) +} + +/// Commands are written as feature reports over the control pipe; replies arrive on the interrupt +/// IN endpoint. +async fn open_command(dev: &Device) -> HidResult<(DeviceReader, DeviceFeatureHandle)> { + log::debug!("opening command interface"); + + Ok((dev.open_readable().await?, dev.open_feature_handle().await?)) +} + +fn tlv_u16(tlvs: &TlvList, tag: ConfigTag) -> Option { + let value = tlvs.find(tag)?.value.as_slice(); + (value.len() == 2).then(|| u16::from_le_bytes([value[0], value[1]])) +} + +fn print_hex(name: &str, tag: ConfigTag, value: &[u8]) { + print!("{name} (0x{:04x}):", tag.0); + + for byte in value { + print!(" {byte:02x}"); + } + + println!(); +} + +fn print_config(snapshot: &ConfigSnapshot) { + println!("Active slot: {}", snapshot.active_slot); + + for tlv in snapshot.config.tlvs.iter() { + let name = tlv.tag.name().unwrap_or("Unknown"); + let value = tlv.value.as_slice(); + + if tlv.tag == tags::VENDOR_ID || tlv.tag == tags::PRODUCT_ID { + match value { + [lo, hi] => println!( + "{name} (0x{:04x}): 0x{:04x}", + tlv.tag.0, + u16::from_le_bytes([*lo, *hi]) + ), + _ => print_hex(name, tlv.tag, value), + } + } else if tlv.tag == tags::MANUF_STRING + || tlv.tag == tags::PRODUCT_STRING + || tlv.tag == tags::SERIAL_STRING + { + match core::str::from_utf8(value) { + Ok(value) => println!("{name} (0x{:04x}): {value:?}", tlv.tag.0), + Err(_) => print_hex(name, tlv.tag, value), + } + } else { + print_hex(name, tlv.tag, value); + } + } +} + +async fn show_config(device: &UsbVidPid) -> HidResult<()> { + let dev = find_device(device, USAGE_COMMAND).await?; + let (mut reader, mut handle) = open_command(&dev).await?; + let snapshot = read_config(&mut reader, &mut handle, 0).await?; + + log::info!("printing configuration"); + print_config(&snapshot); + Ok(()) +} + +async fn show_hardware(device: &UsbVidPid) -> HidResult<()> { + let dev = find_device(device, USAGE_COMMAND).await?; + let (mut reader, mut handle) = open_command(&dev).await?; + let info = read_hardware(&mut reader, &mut handle).await?; + + log::info!("printing hardware info"); + print!("UUID: "); + for byte in info.uuid { + print!("{byte:02X}"); + } + println!(); + println!("DAC: {}", info.dac.as_str()); + println!("Firmware: {}", info.version.as_str()); + + Ok(()) +} + +async fn apply_config(device: &UsbVidPid, args: &ConfigArgs) -> HidResult<()> { + if args.reset { + return reset_config(device).await; + } + + let dev = find_device(device, USAGE_COMMAND).await?; + let (mut reader, mut handle) = open_command(&dev).await?; + + let current = read_config(&mut reader, &mut handle, 0).await?; + let mut expected = current.config.tlvs.clone(); + let mut replacements: Vec<(ConfigTag, Vec)> = Vec::new(); + + if let Some(value) = args.vendor_id { + replacements.push((tags::VENDOR_ID, value.to_le_bytes().to_vec())); + } + if let Some(value) = args.product_id { + replacements.push((tags::PRODUCT_ID, value.to_le_bytes().to_vec())); + } + if let Some(value) = &args.manufacturer { + replacements.push((tags::MANUF_STRING, value.as_bytes().to_vec())); + } + if let Some(value) = &args.product { + replacements.push((tags::PRODUCT_STRING, value.as_bytes().to_vec())); + } + if let Some(value) = &args.serial { + replacements.push((tags::SERIAL_STRING, value.as_bytes().to_vec())); + } + + for (tag, value) in &replacements { + let value = ConfigBytes::from_slice(value) + .map_err(|error| HidError::message(format!("invalid value for {tag:?}: {error}")))?; + expected + .upsert(Tlv { tag: *tag, value }) + .map_err(|error| HidError::message(format!("config too large: {error}")))?; + } + + DeviceConfig::from_tlvs(&expected) + .map_err(|error| HidError::message(format!("invalid configuration: {error}")))?; + + log::info!("applying {} change(s)", replacements.len()); + + let mut seq = 1u8; + for (tag, value) in &replacements { + replace_tlv(&mut reader, &mut handle, seq, *tag, value).await?; + seq = seq.wrapping_add(1); + } + + log::info!("committing configuration to flash"); + send_command(&mut handle, seq, CommandKind::CommitConfig, &[]).await?; + wait_ack(&mut reader, seq).await?; + + drop(reader); + drop(handle); + drop(dev); + + let expected_device = device_for(&expected)?; + let slot = await_config(expected_device, &expected).await?; + + println!("Configuration updated successfully (active slot {slot})."); + Ok(()) +} + +async fn reset_config(device: &UsbVidPid) -> HidResult<()> { + let dev = find_device(device, USAGE_COMMAND).await?; + let (mut reader, mut handle) = open_command(&dev).await?; + + let info = read_hardware(&mut reader, &mut handle).await?; + let defaults = DeviceConfig::with_defaults(DeviceConfig::serial_from_uuid(&info.uuid)) + .map_err(|error| HidError::message(format!("invalid default configuration: {error}")))?; + let expected = defaults + .to_tlvs() + .map_err(|error| HidError::message(format!("invalid default configuration: {error}")))?; + + log::info!("restoring default configuration"); + send_command(&mut handle, 0, CommandKind::ResetConfig, &[]).await?; + wait_ack(&mut reader, 0).await?; + + drop(reader); + drop(handle); + drop(dev); + + let expected_device = device_for(&expected)?; + let slot = await_config(expected_device, &expected).await?; + + println!("Configuration reset to defaults (active slot {slot})."); + Ok(()) +} + +fn device_for(tlvs: &TlvList) -> HidResult { + Ok(UsbVidPid { + vid: tlv_u16(tlvs, tags::VENDOR_ID) + .ok_or_else(|| HidError::message("missing vendor id"))?, + pid: tlv_u16(tlvs, tags::PRODUCT_ID) + .ok_or_else(|| HidError::message("missing product id"))?, + }) +} + +/// Waits for the device to come back with `expected_device` and report exactly `expected`. +async fn await_config(expected_device: UsbVidPid, expected: &TlvList) -> HidResult { + let deadline = Instant::now() + Duration::from_secs(10); + + log::info!( + "waiting for device to restart as {:04x}:{:04x}", + expected_device.vid, + expected_device.pid + ); + + loop { + if let Some(dev) = try_find_device(&expected_device, USAGE_COMMAND).await? + && let Ok((mut reader, mut handle)) = open_command(&dev).await + && let Ok(snapshot) = read_config(&mut reader, &mut handle, 0).await + && snapshot.config.tlvs == *expected + { + log::info!("configuration verified in slot {}", snapshot.active_slot); + return Ok(snapshot.active_slot); + } + + if Instant::now() >= deadline { + log::error!("configuration verification timed out"); + return Err(HidError::message("configuration verification failed")); + } + + log::debug!("device not ready yet, retrying"); + smol::Timer::after(Duration::from_millis(200)).await; + } } main! { @@ -226,6 +787,7 @@ async fn main() -> HidResult<()> { match &args.command { Some(Command::Monitor { format, count }) => { + log::info!("monitoring telemetry"); let dev = find_device(&args.device, USAGE_TELEMETRY).await?; let reader = dev.open_readable().await?; let writer: Box = match format { @@ -238,12 +800,13 @@ async fn main() -> HidResult<()> { let handler_stop = Arc::clone(&stop); if let Err(e) = ctrlc::set_handler(move || handler_stop.store(true, Ordering::Relaxed)) { - eprintln!("Unable to install Ctrl-C handler: {e}"); + log::warn!("unable to install Ctrl-C handler: {e}"); } emit_telemetry_reports(reader, writer, count, &stop).await } Some(Command::Status { format }) => { + log::info!("reading telemetry"); let dev = find_device(&args.device, USAGE_TELEMETRY).await?; let reader = dev.open_readable().await?; let writer: Box = match format { @@ -256,24 +819,38 @@ async fn main() -> HidResult<()> { } Some(Command::Reset { bootloader }) => { let dev = find_device(&args.device, USAGE_COMMAND).await?; - let mut dev_writer = dev.open_writeable().await?; - let cmd = if *bootloader { - print!("Rebooting into bootloader..."); - AudioDeviceCommand::Bootloader + let mut handle = dev.open_feature_handle().await?; + let kind = if *bootloader { + CommandKind::Bootloader } else { - print!("Rebooting..."); - AudioDeviceCommand::Reset + CommandKind::Reset }; - log::debug!("writing command: {:?}", &cmd); - let report: AudioDeviceCommandReport = cmd.into(); - log::debug!(" report: {:?}", &report); - // Our descriptor has no report IDs, so hidraw expects a leading 0x00 that it strips - let mut buf = [0u8; 1 + core::mem::size_of::()]; - buf[1..].copy_from_slice(&report.cmd); - match dev_writer.write_output_report(&buf).await { - Ok(_) => println!("write succeeded - reboot failed"), - Err(_) => println!("lost device - reboot successful"), + + if let Err(error) = send_command(&mut handle, 0, kind, &[]).await + && !matches!(error, HidError::Disconnected | HidError::NotConnected) + { + return Err(error); } + + if *bootloader { + log::info!("requested bootloader reboot"); + println!("Rebooting into bootloader..."); + } else { + log::info!("requested reboot"); + println!("Rebooting..."); + } + } + Some(Command::Config(config)) => { + log::info!("updating configuration"); + apply_config(&args.device, config).await?; + } + Some(Command::Show) => { + log::info!("reading configuration"); + show_config(&args.device).await?; + } + Some(Command::Hardware) => { + log::info!("reading hardware info"); + show_hardware(&args.device).await?; } None => {} } diff --git a/firmware/Cargo.toml b/firmware/Cargo.toml index 3fa0d6f..270ba98 100644 --- a/firmware/Cargo.toml +++ b/firmware/Cargo.toml @@ -4,7 +4,7 @@ version = "0.3.1" edition = "2024" [features] -default = ["nodac", "hid"] +default = ["evk", "hid"] ak4490 = [] cs4398 = [] nodac = [] diff --git a/firmware/build.rs b/firmware/build.rs index ffce9b8..fb286be 100644 --- a/firmware/build.rs +++ b/firmware/build.rs @@ -1,5 +1,33 @@ -// Find the actual path of memory.x and add it to link search, required for building in workspace +use std::{env, process::Command}; + +fn git_output(args: &[&str], dir: &str) -> Option { + let output = Command::new("git") + .args(["-C", dir]) + .args(args) + .output() + .ok()?; + + if !output.status.success() { + return None; + } + + let value = String::from_utf8_lossy(&output.stdout).trim().to_string(); + (!value.is_empty()).then_some(value) +} + +fn firmware_version(dir: &str) -> String { + git_output(&["describe", "--tags", "--exact-match", "HEAD"], dir) + .or_else(|| git_output(&["rev-parse", "--short=12", "HEAD"], dir)) + .unwrap_or_else(|| env::var("CARGO_PKG_VERSION").unwrap_or_else(|_| "unknown".to_string())) +} + fn main() { - let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); - println!("cargo:rustc-link-search={}", manifest_dir); + if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") { + println!("cargo:rustc-link-search={manifest_dir}"); + println!( + "cargo:rustc-env=GUAC_VERSION={}", + firmware_version(&manifest_dir) + ); + println!("cargo:rerun-if-changed=../.git/HEAD"); + } } diff --git a/firmware/memory.x b/firmware/memory.x index 5a68a5f..ceabcce 100644 --- a/firmware/memory.x +++ b/firmware/memory.x @@ -1,6 +1,7 @@ MEMORY { - FLASH : ORIGIN = 0x00000000, LENGTH = 512K + FLASH : ORIGIN = 0x00000000 , LENGTH = 512K - 32K + CONFIG : ORIGIN = 0x00000000 + 512K - 32K, LENGTH = 32K /* for use with standard link.x */ RAM : ORIGIN = 0x20000000, LENGTH = 192K @@ -19,3 +20,7 @@ MEMORY /* USB1 SRAM regin */ /* USB1_SRAM : ORIGIN = 0x40100000, LENGTH = 16K */ } +SECTIONS { + _config_start = ORIGIN(CONFIG); + _config_end = ORIGIN(CONFIG) + LENGTH(CONFIG); +} diff --git a/firmware/src/config.rs b/firmware/src/config.rs new file mode 100644 index 0000000..2c23fff --- /dev/null +++ b/firmware/src/config.rs @@ -0,0 +1,306 @@ +use lpc55_hal as hal; + +use hal::{FlashGordon, drivers::flash::GenericArray, raw as pac, traits::flash::WriteErase}; +use shared::config::{ + ConfigContainer, ConfigString, ConfigV1, ConfigVersion, DeviceConfig, TlvList, +}; + +use crate::{CONFIG_RESERVED, CONFIG_SLOT_COUNT, FLASH_PAGE_SIZE, SLOT_SIZE, config_base}; + +const SLOT_MAGIC: u32 = u32::from_le_bytes(*b"SLOT"); + +const FLASH_WORD_SIZE: usize = 16; +const READ_SINGLE_WORD: u32 = 0x3; +const READ_ECC_OFF: u32 = 1 << 2; +const COMMAND_TIMEOUT: u32 = 1_000_000; + +static mut CONFIG_BUF: [u8; SLOT_SIZE] = [0u8; SLOT_SIZE]; + +#[cfg(feature = "hid")] +pub struct ConfigState { + pub running: DeviceConfig, + pub active_slot: u8, +} + +#[cfg(feature = "hid")] +pub struct FlashState { + pub flash: FlashGordon, +} + +#[derive(Clone, Copy, defmt::Format)] +enum FlashError { + IllegalCommand, + Failed, + Timeout, +} + +fn halt() -> ! { + loop { + cortex_m::asm::wfi(); + } +} + +fn slot_page_address() -> usize { + config_base() +} + +fn slot_address(index: usize) -> usize { + config_base() + CONFIG_RESERVED + index * SLOT_SIZE +} + +fn config_buf() -> &'static mut [u8; SLOT_SIZE] { + // Safety: flash access is not reentrant and the buffer is only borrowed for one operation at a time. + unsafe { &mut *core::ptr::addr_of_mut!(CONFIG_BUF) } +} + +fn read_word( + flash: &pac::flash::RegisterBlock, + address: usize, +) -> Result<[u8; FLASH_WORD_SIZE], FlashError> { + flash.int_clr_status.write(|w| { + w.done() + .set_bit() + .ecc_err() + .set_bit() + .err() + .set_bit() + .fail() + .set_bit() + }); + flash + .starta + .write(|w| unsafe { w.starta().bits((address / FLASH_WORD_SIZE) as u32) }); + flash.dataw[0].write(|w| unsafe { w.bits(READ_ECC_OFF) }); + flash.cmd.write(|w| unsafe { w.bits(READ_SINGLE_WORD) }); + + let mut timeout = COMMAND_TIMEOUT; + + while flash.int_status.read().done().bit_is_clear() { + timeout -= 1; + + if timeout == 0 { + return Err(FlashError::Timeout); + } + } + + let status = flash.int_status.read(); + + if status.err().bit_is_set() { + return Err(FlashError::IllegalCommand); + } + + if status.fail().bit_is_set() { + return Err(FlashError::Failed); + } + + let mut word = [0u8; FLASH_WORD_SIZE]; + + for (chunk, register) in word.chunks_mut(4).zip(flash.dataw.iter()) { + chunk.copy_from_slice(®ister.read().bits().to_ne_bytes()); + } + + Ok(word) +} + +fn read_flash(address: usize, buf: &mut [u8]) -> Result<(), FlashError> { + // Safety: the flash controller registers are only ever accessed here and in the HAL, never concurrently. + let flash = unsafe { &*pac::FLASH::ptr() }; + + for (index, chunk) in buf.chunks_mut(FLASH_WORD_SIZE).enumerate() { + let word = read_word(flash, address + index * FLASH_WORD_SIZE)?; + chunk.copy_from_slice(&word[..chunk.len()]); + } + + Ok(()) +} + +fn read_active_slot() -> Option { + let mut page = [0u8; FLASH_PAGE_SIZE]; + read_flash(slot_page_address(), &mut page).ok()?; + + if u32::from_le_bytes([page[0], page[1], page[2], page[3]]) != SLOT_MAGIC { + return None; + } + + let slots = &page[4..8]; + let index = slots[0]; + + if slots.iter().any(|&slot| slot != index) || usize::from(index) >= CONFIG_SLOT_COUNT { + return None; + } + + Some(usize::from(index)) +} + +fn load_slot(index: usize) -> Option { + let buf = config_buf(); + + if let Err(error) = read_flash(slot_address(index), buf) { + defmt::error!("config: slot {} unreadable: {}", index, error); + return None; + } + + match ConfigContainer::parse(&buf[..]) { + Ok((container, _)) => match DeviceConfig::try_from(&container.config) { + Ok(config) => Some(config), + Err(error) => { + defmt::warn!("config: slot {} invalid: {}", index, error); + None + } + }, + Err(error) => { + defmt::debug!("config: slot {} skipped: {}", index, error); + None + } + } +} + +fn device_serial() -> Option> { + DeviceConfig::serial_from_uuid(&hal::uuid()) +} + +fn default_config() -> DeviceConfig { + match DeviceConfig::with_defaults(device_serial()) { + Ok(config) => config, + Err(_) => halt(), + } +} + +fn write_slot( + flash: &mut FlashGordon, + index: usize, + container: &ConfigContainer, +) -> Result<(), ()> { + let buf = config_buf(); + let len = container.encode(buf).map_err(|_| ())?; + let base = slot_address(index); + let pages = len.div_ceil(FLASH_PAGE_SIZE); + + for page in 0..pages { + let address = base + page * FLASH_PAGE_SIZE; + flash + .erase_page(address / FLASH_PAGE_SIZE) + .map_err(|_| ())?; + } + + for page in 0..pages { + let start = page * FLASH_PAGE_SIZE; + let end = (start + FLASH_PAGE_SIZE).min(len); + let mut page_buf = [0xffu8; FLASH_PAGE_SIZE]; + page_buf[..end - start].copy_from_slice(&buf[start..end]); + + flash + .write_native(base + start, GenericArray::from_slice(&page_buf)) + .map_err(|_| ())?; + } + + Ok(()) +} + +fn write_active_slot(flash: &mut FlashGordon, index: usize) -> Result<(), ()> { + let address = slot_page_address(); + let mut page = [0xffu8; FLASH_PAGE_SIZE]; + page[..4].copy_from_slice(&SLOT_MAGIC.to_le_bytes()); + page[4..8].fill(index as u8); + + flash + .erase_page(address / FLASH_PAGE_SIZE) + .map_err(|_| ())?; + flash + .write_native(address, GenericArray::from_slice(&page)) + .map_err(|_| ())?; + + Ok(()) +} + +fn slow_clock_for_flash() { + // Safety: the device resets after writing, so no peripheral depends on the core clock source. + let syscon = unsafe { &*pac::SYSCON::ptr() }; + + syscon.fmccr.modify(|_, w| w.flashtim().flashtim11()); + syscon.mainclksela.modify(|_, w| w.sel().enum_0x3()); + syscon.mainclkselb.modify(|_, w| w.sel().enum_0x0()); + syscon.ahbclkdiv.modify(|_, w| unsafe { w.div().bits(0) }); +} + +fn persist_and_reset( + flash: &mut FlashGordon, + slot: usize, + container: &ConfigContainer, +) -> Result<(), ()> { + defmt::info!("config: persisting to slot {}", slot); + + cortex_m::interrupt::free(|_| { + slow_clock_for_flash(); + + if write_slot(flash, slot, container).is_err() { + defmt::error!("config: slot write failed"); + return; + } + + if write_active_slot(flash, slot).is_err() { + defmt::error!("config: slot page write failed"); + return; + } + + cortex_m::peripheral::SCB::sys_reset(); + }); + + Err(()) +} + +fn create_default(flash: &mut FlashGordon) -> DeviceConfig { + let config = default_config(); + let Ok(tlvs) = config.to_tlvs() else { + return config; + }; + + defmt::info!("config: creating default"); + let container = ConfigContainer::new(ConfigVersion::V1(ConfigV1 { tlvs })); + + let _ = persist_and_reset(flash, 0, &container); + + config +} + +#[cfg(feature = "hid")] +fn commit_tlvs(state: &mut FlashState, config: &ConfigState, tlvs: TlvList) -> Result<(), ()> { + let next_slot = (usize::from(config.active_slot) + 1) % CONFIG_SLOT_COUNT; + let container = ConfigContainer::new(ConfigVersion::V1(ConfigV1 { tlvs })); + + persist_and_reset(&mut state.flash, next_slot, &container) +} + +#[cfg(feature = "hid")] +pub fn commit(state: &mut FlashState, config: &ConfigState) -> Result<(), ()> { + commit_tlvs(state, config, config.running.to_tlvs().map_err(|_| ())?) +} + +#[cfg(feature = "hid")] +pub fn commit_defaults(state: &mut FlashState, config: &ConfigState) -> Result<(), ()> { + commit_tlvs(state, config, default_config().to_tlvs().map_err(|_| ())?) +} + +pub fn load(flash: &mut FlashGordon) -> (DeviceConfig, u8) { + slow_clock_for_flash(); + + let active = read_active_slot(); + + if let Some(index) = active + && let Some(config) = load_slot(index) + { + return (config, index as u8); + } + + for index in (0..CONFIG_SLOT_COUNT).rev() { + if Some(index) == active { + continue; + } + + if let Some(config) = load_slot(index) { + return (config, index as u8); + } + } + + (create_default(flash), 0) +} diff --git a/firmware/src/dac/ak4490.rs b/firmware/src/dac/ak4490.rs index f97b95c..fe0a9a6 100644 --- a/firmware/src/dac/ak4490.rs +++ b/firmware/src/dac/ak4490.rs @@ -61,6 +61,11 @@ where volume: (0xff, 0xff), } } + + fn name(&self) -> &'static str { + "AK4490" + } + fn init(&mut self) { // bring out of reset self.pins.reset.set_high(); @@ -69,18 +74,22 @@ where self.write_reg(RegisterAddress::Control2, 0x22 | ((dfs & 0x3) << 3)); self.write_reg(RegisterAddress::Control4, (dfs & 0x4) >> 1); } + fn change_rate(&mut self, new_rate: u32) { let dfs = self.dfs_for_rate(new_rate); self.write_reg(RegisterAddress::Control2, 0x22 | ((dfs & 0x3) << 3)); self.write_reg(RegisterAddress::Control4, (dfs & 0x4) >> 1); } + fn set_volume(&mut self, left: u8, right: u8) { self.set_volume_impl(left, right); self.volume = (left, right); } + fn mute(&mut self) { self.set_volume_impl(0, 0); } + fn unmute(&mut self) { self.set_volume_impl(self.volume.0, self.volume.1); } diff --git a/firmware/src/dac/cs4398.rs b/firmware/src/dac/cs4398.rs index 01b13b8..f04e790 100644 --- a/firmware/src/dac/cs4398.rs +++ b/firmware/src/dac/cs4398.rs @@ -50,6 +50,11 @@ where fn new(i2c: T, pins: CodecPins) -> Self { Cs4398Dac { i2c, pins } } + + fn name(&self) -> &'static str { + "CS4398" + } + fn init(&mut self) { // reset self.pins.reset.set_low().ok(); diff --git a/firmware/src/dac/noop.rs b/firmware/src/dac/noop.rs index 9601176..16a2e70 100644 --- a/firmware/src/dac/noop.rs +++ b/firmware/src/dac/noop.rs @@ -7,6 +7,10 @@ pub struct NoopDac { __: PhantomData, } impl Dac for NoopDac { + fn name(&self) -> &'static str { + "None" + } + fn init(&mut self) {} fn change_rate(&mut self, _new_rate: u32) {} fn mute(&mut self) {} diff --git a/firmware/src/dac/wm8904.rs b/firmware/src/dac/wm8904.rs index c1cf7de..22f23a0 100644 --- a/firmware/src/dac/wm8904.rs +++ b/firmware/src/dac/wm8904.rs @@ -176,6 +176,11 @@ where mclk: MCLK, } } + + fn name(&self) -> &'static str { + "WM8904" + } + fn init(&mut self) { let mut buf = [0u8; 2]; match self.i2c.write_read(WM8904_I2C_ADDRESS, &[0], &mut buf) { diff --git a/firmware/src/hid_config.rs b/firmware/src/hid_config.rs new file mode 100644 index 0000000..cd865db --- /dev/null +++ b/firmware/src/hid_config.rs @@ -0,0 +1,455 @@ +use shared::{ + config::{ + ConfigBytes, ConfigError, ConfigSnapshot, ConfigTag, ConfigV1, DeviceConfig, MAX_VALUE_LEN, + Tlv, + }, + hardware::HardwareInfo, + hid::command::{ + COMMAND_REPORT_SIZE, CommandKind, HEADER_LEN, Header, IN_PAYLOAD_LEN, IN_REPORT_SIZE, + NackCode, ResponseKind, + }, +}; +use usb_device::{UsbError, bus::UsbBus}; +use usbd_hid::hid_class::HIDClass; + +use crate::config::{self, ConfigState, FlashState}; + +const MAX_COMMAND_LEN: usize = 128; +const REPLY_BUF_LEN: usize = 512; + +struct Reassembly { + kind: Option, + seq: u8, + total_len: usize, + received: usize, + buf: [u8; MAX_COMMAND_LEN], +} + +enum Action { + Nothing, + Apply(DeviceConfig), + Reset, + Bootloader, + Commit, + ResetDefaults, +} + +enum Pending { + Ack { seq: u8, action: Action }, + Nack { seq: u8, code: NackCode }, +} + +enum Push { + Sent, + Blocked, + Failed, +} + +/// A reply payload being segmented into IN reports. +struct Reply { + kind: ResponseKind, + seq: u8, + total_len: usize, + offset: usize, +} + +pub struct CommandState { + command: Reassembly, + pending: Option, + reply: Option, + reply_buf: [u8; REPLY_BUF_LEN], +} + +impl CommandState { + pub fn new() -> Self { + Self { + command: Reassembly { + kind: None, + seq: 0, + total_len: 0, + received: 0, + buf: [0; MAX_COMMAND_LEN], + }, + pending: None, + reply: None, + reply_buf: [0; REPLY_BUF_LEN], + } + } + + pub fn reset(&mut self) { + self.command.kind = None; + self.pending = None; + self.reply = None; + } + + fn nack(&mut self, seq: u8, code: NackCode) { + self.command.kind = None; + self.reply = None; + self.pending = Some(Pending::Nack { seq, code }); + } + + fn reply(&mut self, kind: ResponseKind, seq: u8, len: usize) { + self.reply = Some(Reply { + kind, + seq, + total_len: len, + offset: 0, + }); + } + + fn prepare( + &mut self, + kind: CommandKind, + seq: u8, + payload: &[u8], + config: &ConfigState, + hardware: &HardwareInfo, + ) { + match kind { + CommandKind::Noop => { + self.pending = Some(Pending::Ack { + seq, + action: Action::Nothing, + }); + } + CommandKind::Reset => { + self.pending = Some(Pending::Ack { + seq, + action: Action::Reset, + }); + } + CommandKind::Bootloader => { + self.pending = Some(Pending::Ack { + seq, + action: Action::Bootloader, + }); + } + CommandKind::ReadConfig => { + if !payload.is_empty() { + self.nack(seq, NackCode::InvalidPayload); + return; + } + + let Ok(tlvs) = config.running.to_tlvs() else { + self.nack(seq, NackCode::InvalidConfig); + return; + }; + + let snapshot = ConfigSnapshot { + active_slot: config.active_slot, + config: ConfigV1 { tlvs }, + }; + + match snapshot.encode(&mut self.reply_buf) { + Ok(len) => self.reply(ResponseKind::ConfigData, seq, len), + Err(error) => { + defmt::warn!("config snapshot encode failed: {}", error); + self.nack(seq, NackCode::ConfigTooLarge); + } + } + } + CommandKind::Hardware => { + if !payload.is_empty() { + self.nack(seq, NackCode::InvalidPayload); + return; + } + + match hardware.encode(&mut self.reply_buf) { + Ok(len) => self.reply(ResponseKind::Hardware, seq, len), + Err(error) => { + defmt::warn!("hardware encode failed: {}", error); + self.nack(seq, NackCode::ConfigTooLarge); + } + } + } + CommandKind::ReplaceTlv => { + if payload.len() < 2 { + self.nack(seq, NackCode::InvalidPayload); + return; + } + + let tag = ConfigTag(u16::from_le_bytes([payload[0], payload[1]])); + let Ok(value) = ConfigBytes::::from_slice(&payload[2..]) else { + self.nack(seq, NackCode::InvalidPayload); + return; + }; + + let mut staged = config.running.clone(); + match staged.replace_tlv(Tlv { tag, value }) { + Ok(()) => { + self.pending = Some(Pending::Ack { + seq, + action: Action::Apply(staged), + }); + } + Err(ConfigError::UnknownTag(_)) => self.nack(seq, NackCode::UnknownTag), + Err(_) => self.nack(seq, NackCode::InvalidConfig), + } + } + CommandKind::CommitConfig => { + if !payload.is_empty() { + self.nack(seq, NackCode::InvalidPayload); + return; + } + + self.pending = Some(Pending::Ack { + seq, + action: Action::Commit, + }); + } + CommandKind::ResetConfig => { + if !payload.is_empty() { + self.nack(seq, NackCode::InvalidPayload); + return; + } + + self.pending = Some(Pending::Ack { + seq, + action: Action::ResetDefaults, + }); + } + } + } + + fn flush( + &mut self, + hid: &HIDClass<'_, B>, + config: &mut ConfigState, + flash: &mut FlashState, + ) -> bool { + if let Some(pending) = self.pending.take() { + let pushed = match &pending { + Pending::Ack { seq, .. } => push_ack(hid, *seq), + Pending::Nack { seq, code } => push_nack(hid, *seq, *code), + }; + + match pushed { + Push::Blocked => { + self.pending = Some(pending); + return true; + } + Push::Failed => return true, + Push::Sent => {} + } + + if let Pending::Ack { action, .. } = pending { + match action { + Action::Nothing => {} + Action::Apply(staged) => config.running = staged, + Action::Reset => { + ack_delay(); + cortex_m::peripheral::SCB::sys_reset(); + } + Action::Bootloader => { + ack_delay(); + crate::boot_to_bootloader(); + } + Action::Commit => { + ack_delay(); + + if config::commit(flash, config).is_err() { + defmt::error!("config commit failed"); + } + } + Action::ResetDefaults => { + ack_delay(); + + if config::commit_defaults(flash, config).is_err() { + defmt::error!("config reset failed"); + } + } + } + } + + return true; + } + + if let Some(mut reply) = self.reply.take() { + let len = (reply.total_len - reply.offset).min(IN_PAYLOAD_LEN); + let mut report = [0u8; IN_REPORT_SIZE]; + + Header { + kind: reply.kind as u8, + seq: reply.seq, + total_len: reply.total_len as u16, + offset: reply.offset as u16, + len: len as u8, + } + .encode(&mut report[..HEADER_LEN]); + + let start = reply.offset; + report[HEADER_LEN..HEADER_LEN + len] + .copy_from_slice(&self.reply_buf[start..start + len]); + + match hid.push_raw_input(&report) { + Ok(_) => { + defmt::debug!( + "HID reply kind={:?} seq={} offset={} len={}/{}", + reply.kind, + reply.seq, + reply.offset, + len, + reply.total_len + ); + + reply.offset += len; + + if reply.offset < reply.total_len { + self.reply = Some(reply); + } + } + Err(UsbError::WouldBlock) => self.reply = Some(reply), + Err(error) => defmt::error!("HID reply push failed: {:?}", error), + } + + return true; + } + + false + } + + fn read( + &mut self, + hid: &mut HIDClass<'_, B>, + config: &ConfigState, + hardware: &HardwareInfo, + ) { + let mut raw = [0u8; IN_REPORT_SIZE]; + + let len = match hid.pull_raw_report(&mut raw) { + Ok(info) if info.report_id == 0 => info.len, + Ok(_) => return, + Err(UsbError::WouldBlock) => return, + Err(error) => { + defmt::error!("HID pull failed: {:?}", error); + return; + } + }; + + let len = len.min(COMMAND_REPORT_SIZE); + let report = &raw[..len]; + + let Some(header) = Header::parse(report) else { + return; + }; + + if HEADER_LEN + usize::from(header.len) > len + || usize::from(header.offset) + usize::from(header.len) > usize::from(header.total_len) + { + defmt::warn!("invalid HID command framing"); + self.nack(header.seq, NackCode::InvalidPayload); + return; + } + + let Ok(kind) = CommandKind::try_from(header.kind) else { + defmt::warn!("unknown HID command {}", header.kind); + self.nack(header.seq, NackCode::InvalidCommand); + return; + }; + + if header.offset == 0 { + self.command.kind = Some(kind); + self.command.seq = header.seq; + self.command.total_len = usize::from(header.total_len); + self.command.received = 0; + + if self.command.total_len > MAX_COMMAND_LEN { + defmt::warn!("HID command too large: {}", self.command.total_len); + self.nack(header.seq, NackCode::InvalidPayload); + return; + } + } + + if self.command.kind != Some(kind) + || self.command.seq != header.seq + || usize::from(header.offset) != self.command.received + { + defmt::warn!("out of sequence HID command chunk"); + self.nack(header.seq, NackCode::InvalidPayload); + return; + } + + let start = usize::from(header.offset); + let len = usize::from(header.len); + self.command.buf[start..start + len].copy_from_slice(&report[HEADER_LEN..HEADER_LEN + len]); + self.command.received += len; + + if self.command.received == self.command.total_len { + defmt::debug!( + "HID command kind={:?} seq={} len={}", + kind, + header.seq, + self.command.total_len + ); + + let mut payload = [0u8; MAX_COMMAND_LEN]; + let total_len = self.command.total_len; + payload[..total_len].copy_from_slice(&self.command.buf[..total_len]); + self.command.kind = None; + + if self.reply.take().is_some() { + defmt::warn!("dropping unsent reply"); + } + + self.prepare(kind, header.seq, &payload[..total_len], config, hardware); + } + } +} + +fn push_ack(hid: &HIDClass<'_, B>, seq: u8) -> Push { + let mut report = [0u8; IN_REPORT_SIZE]; + Header { + kind: ResponseKind::Ack as u8, + seq, + total_len: 0, + offset: 0, + len: 0, + } + .encode(&mut report[..HEADER_LEN]); + + match hid.push_raw_input(&report) { + Ok(_) => Push::Sent, + Err(UsbError::WouldBlock) => Push::Blocked, + Err(error) => { + defmt::error!("HID ACK failed: {:?}", error); + Push::Failed + } + } +} + +fn push_nack(hid: &HIDClass<'_, B>, seq: u8, code: NackCode) -> Push { + let mut report = [0u8; IN_REPORT_SIZE]; + Header { + kind: ResponseKind::Nack as u8, + seq, + total_len: 1, + offset: 0, + len: 1, + } + .encode(&mut report[..HEADER_LEN]); + report[HEADER_LEN] = code as u8; + + match hid.push_raw_input(&report) { + Ok(_) => Push::Sent, + Err(UsbError::WouldBlock) => Push::Blocked, + Err(error) => { + defmt::error!("HID NACK failed: {:?}", error); + Push::Failed + } + } +} + +fn ack_delay() { + cortex_m::asm::delay(5_000_000); +} + +pub fn poll( + hid: &mut HIDClass<'_, B>, + state: &mut CommandState, + config: &mut ConfigState, + flash: &mut FlashState, + hardware: &HardwareInfo, +) { + state.read(hid, config, hardware); + state.flush(hid, config, flash); +} diff --git a/firmware/src/main.rs b/firmware/src/main.rs index 0b21e8a..c84a454 100644 --- a/firmware/src/main.rs +++ b/firmware/src/main.rs @@ -24,6 +24,8 @@ use hal::typestates::pin::state::Gpio; use lpc55_hal as hal; use pac::interrupt; use static_cell::StaticCell; +#[cfg(feature = "hid")] +use usb_device::device::UsbDeviceState; use usb_device::{ bus::{self}, device::{StringDescriptors, UsbVidPid}, @@ -43,7 +45,13 @@ use crate::hw::led1; use crate::hw::led2; use crate::traits::Dac; use shared::AudioState; -use shared::hid::{AudioDeviceCommandReport, AudioTelemetryReport}; +#[cfg(feature = "hid")] +use shared::config::ConfigString; +#[cfg(feature = "hid")] +use shared::hardware::HardwareInfo; +use shared::hid::AudioTelemetryReport; +#[cfg(feature = "hid")] +use shared::hid::DeviceCommandReport; #[cfg(feature = "ak4490")] pub mod dac { @@ -66,7 +74,10 @@ pub mod dac { pub use self::wm8904::Wm8904Dac as DacImpl; } +mod config; mod dma; +#[cfg(feature = "hid")] +mod hid_config; mod hw; mod traits; @@ -106,7 +117,39 @@ const USB_FRAME_RATE: u32 = 8000; // microframe rate: 8000 for HS, 1000 for FS // const NODATA_TIMEOUT_FRAMES: usize = SAMPLE_RATE as usize / 100; // ~100ms const HID_INTERVAL_MS: u8 = 10; -const HID_CMD_INTERVAL_MS: u8 = 100; +const HID_CMD_INTERVAL_MS: u8 = 10; + +const FLASH_PAGE_SIZE: usize = 512; + +const CONFIG_LENGTH: usize = 32 * 1024; +const CONFIG_SLOT_COUNT: usize = 2; +// First page is reserved for slot selection, reserve two slots so remainder / 2 is aligned +const CONFIG_RESERVED: usize = 2 * FLASH_PAGE_SIZE; + +const SLOT_SIZE: usize = (CONFIG_LENGTH - CONFIG_RESERVED) / CONFIG_SLOT_COUNT; + +// Ensure config page alignment +const _: () = assert!( + CONFIG_RESERVED.is_multiple_of(FLASH_PAGE_SIZE), + "Reserved space must align to flash page size" +); +const _: () = assert!( + SLOT_SIZE.is_multiple_of(FLASH_PAGE_SIZE), + "Slot size must be a multiple of flash page size" +); +const _: () = assert!( + CONFIG_SLOT_COUNT.is_multiple_of(2), + "Slot count must be even" +); + +unsafe extern "C" { + #[link_name = "_config_start"] + static CONFIG_START: u8; +} + +pub fn config_base() -> usize { + core::ptr::addr_of!(CONFIG_START) as usize +} struct CodecPins { #[allow(dead_code)] @@ -842,6 +885,22 @@ fn main() -> ! { .system_frequency(96.MHz()) .configure(&mut anactrl, &mut pmc, &mut syscon) .unwrap(); + + // Flash controller commands require a core clock of at most 100 MHz, so the config is read + // before the system PLL takes the core to 150 MHz. + let flash = hal.flash.enabled(&mut syscon); + let mut flash = hal::FlashGordon::new(flash); + defmt::info!("config: loading"); + let (running_config, active_slot) = config::load(&mut flash); + defmt::info!( + "config: loaded slot={} vid={:04x} pid={:04x}", + active_slot, + running_config.usb_vendor_id, + running_config.usb_product_id + ); + #[cfg(not(feature = "hid"))] + let _ = active_slot; + hw::init_sys_pll1(); #[cfg(feature = "evk")] hw::init_audio_pll(); @@ -921,24 +980,46 @@ fn main() -> ! { #[cfg(feature = "hid")] let (mut hid, mut hid_cmd) = { let hid = HIDClass::new_ep_in(&usb_bus, AudioTelemetryReport::desc(), HID_INTERVAL_MS); - // Linux's usbhid refuses to bind an interface without an interrupt IN endpoint - // (no hidraw node), so the command interface needs one even though it is unused. - let hid_cmd = HIDClass::new( - &usb_bus, - AudioDeviceCommandReport::desc(), - HID_CMD_INTERVAL_MS, - ); + // Commands arrive as feature reports over the control pipe; Linux's usbhid needs an + // interrupt IN endpoint to bind the interface, and replies use it. + let hid_cmd = + HIDClass::new_ep_in(&usb_bus, DeviceCommandReport::desc(), HID_CMD_INTERVAL_MS); (hid, hid_cmd) }; - let mut usb_dev = usbd_uac2::builder(&usb_bus, UsbVidPid(0x1209, 0xcc1d)) - .strings(&[StringDescriptors::default() - .manufacturer("VE7XEN") - .product("Guac Tortilla")]) - .unwrap() - .max_packet_size_0(64) - .unwrap() - .build(); + #[cfg(feature = "hid")] + let hardware_info = HardwareInfo { + uuid: hal::uuid(), + dac: ConfigString::try_from(uac2.handler().dac.name()).unwrap_or_default(), + version: ConfigString::try_from(env!("GUAC_VERSION")).unwrap_or_default(), + }; + + #[cfg(feature = "hid")] + defmt::info!( + "hardware: uuid={=[u8]:02x} dac={=str} firmware={=str}", + &hardware_info.uuid[..], + hardware_info.dac.as_str(), + hardware_info.version.as_str() + ); + + let mut usb_dev = usbd_uac2::builder( + &usb_bus, + UsbVidPid(running_config.usb_vendor_id, running_config.usb_product_id), + ) + .strings(&[{ + let descriptors = StringDescriptors::default() + .manufacturer(running_config.usb_manufacturer.as_str()) + .product(running_config.usb_product.as_str()); + + match &running_config.usb_serial { + Some(serial) => descriptors.serial_number(serial.as_str()), + None => descriptors, + } + }]) + .unwrap() + .max_packet_size_0(64) + .unwrap() + .build(); // 1. Initialize the HID timer conditionally outside the closure #[cfg(feature = "hid")] @@ -952,6 +1033,16 @@ fn main() -> ! { timer }; + #[cfg(feature = "hid")] + let mut config_state = config::ConfigState { + running: running_config.clone(), + active_slot, + }; + #[cfg(feature = "hid")] + let mut flash_state = config::FlashState { flash }; + #[cfg(feature = "hid")] + let mut command_state = hid_config::CommandState::new(); + // 2. Single consolidated poll_all closure let mut poll_all = move || { // Poll active USB classes @@ -975,22 +1066,6 @@ fn main() -> ! { #[cfg(feature = "hid")] { - use deku::DekuContainerRead; - use shared::AudioDeviceCommand; - - fn handle_cmd(cmd: AudioDeviceCommand) { - use shared::AudioDeviceCommand; - - match cmd { - AudioDeviceCommand::Noop => {} - AudioDeviceCommand::Reset => { - cortex_m::interrupt::disable(); - cortex_m::peripheral::SCB::sys_reset(); - } - AudioDeviceCommand::Bootloader => boot_to_bootloader(), - } - } - if hid_update_timer.wait().is_ok() { let report = build_telemetry_report(&PERF, uac2.handler()); if let Err(e) = hid.push_input(&report) @@ -1001,19 +1076,17 @@ fn main() -> ! { // LPC55 CTIMER is not periodic; restart manually hid_update_timer.start(Microseconds::new(HID_INTERVAL_MS as u32 * 1000)); } - let mut cmd_report_buf = [0u8; core::mem::size_of::()]; - match hid_cmd.pull_raw_output(&mut cmd_report_buf) { - Ok(len) => { - if let Ok((_left, cmd)) = - AudioDeviceCommandReport::from_bytes((&cmd_report_buf[0..len], 0)) - && let Ok(cmd) = cmd.try_into() - { - handle_cmd(cmd) - } - } - Err(UsbError::WouldBlock) => {} - Err(e) => defmt::error!("Invalid report: {:?}", e), + if usb_dev.state() != UsbDeviceState::Configured { + command_state.reset(); } + + hid_config::poll( + &mut hid_cmd, + &mut command_state, + &mut config_state, + &mut flash_state, + &hardware_info, + ); } }; diff --git a/firmware/src/traits.rs b/firmware/src/traits.rs index 6616b9e..2a17461 100644 --- a/firmware/src/traits.rs +++ b/firmware/src/traits.rs @@ -1,6 +1,7 @@ use crate::CodecPins; pub trait Dac { fn new(i2c: T, pins: CodecPins) -> Self; + fn name(&self) -> &'static str; /// The DAC should start muted fn init(&mut self); fn change_rate(&mut self, new_rate: u32); diff --git a/shared/Cargo.toml b/shared/Cargo.toml index bfd5ab3..3deec5f 100644 --- a/shared/Cargo.toml +++ b/shared/Cargo.toml @@ -3,13 +3,15 @@ name = "shared" edition = "2024" [features] -std = ["deku/alloc"] -serde = ["dep:serde"] +std = ["deku/alloc", "heapless/alloc", "wary/std", "wary/alloc"] +serde = ["dep:serde", "heapless/serde"] [dependencies] bytemuck = { version = "1.25.0", features = ["derive"] } defmt = "1.1.1" deku = { version = "0.20.3", default-features = false } +heapless = { version = "0.9.3", features = ["defmt"] } num_enum = { version = "0.7.6", default-features = false } serde = { version = "1.0.228", optional = true, features = ["derive"] } usbd-hid = { version = "0.10.0" } +wary = { version = "0.3.2", default-features = false, features = ["derive"] } diff --git a/shared/src/config/container.rs b/shared/src/config/container.rs new file mode 100644 index 0000000..8b50b88 --- /dev/null +++ b/shared/src/config/container.rs @@ -0,0 +1,268 @@ +use super::schema::DeviceConfig; +use super::{ConfigError, Tlv, TlvList}; + +pub const MAGIC: [u8; 4] = *b"GUAC"; + +const HEADER_LEN: usize = 8; +const CRC_LEN: usize = 4; + +pub fn crc32(data: &[u8]) -> u32 { + let mut crc = 0xffff_ffffu32; + + for &byte in data { + crc ^= byte as u32; + for _ in 0..8 { + let mask = (crc & 1).wrapping_neg(); + crc = (crc >> 1) ^ (0xedb8_8320 & mask); + } + } + + !crc +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(transparent))] +pub struct ConfigV1 { + pub tlvs: TlvList, +} + +impl ConfigV1 { + pub fn encoded_len(&self) -> usize { + 2 + self.tlvs.encoded_len() + } + + pub fn parse(payload: &[u8]) -> Result { + if payload.len() < 2 { + return Err(ConfigError::Truncated { + needed: 2, + available: payload.len(), + }); + } + + let count = u16::from_le_bytes([payload[0], payload[1]]); + let mut tlvs = TlvList::new(); + let mut offset = 2; + + for _ in 0..count { + let (tlv, used) = Tlv::parse(&payload[offset..])?; + tlvs.push(tlv)?; + offset += used; + } + + if offset != payload.len() { + return Err(ConfigError::TrailingBytes(payload.len() - offset)); + } + + let config = Self { tlvs }; + config.validate()?; + Ok(config) + } + + pub fn validate(&self) -> Result<(), ConfigError> { + DeviceConfig::from_tlvs(&self.tlvs).map(|_| ()) + } + + pub fn encode(&self, out: &mut [u8]) -> Result { + self.validate()?; + + let needed = self.encoded_len(); + if out.len() < needed { + return Err(ConfigError::BufferTooSmall { + needed, + available: out.len(), + }); + } + + if self.tlvs.len() > u16::MAX as usize { + return Err(ConfigError::ConfigTooLarge(self.tlvs.len())); + } + + out[..2].copy_from_slice(&(self.tlvs.len() as u16).to_le_bytes()); + + let mut offset = 2; + for tlv in self.tlvs.iter() { + offset += tlv.encode(&mut out[offset..])?; + } + + Ok(offset) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum ConfigVersion { + V1(ConfigV1), +} + +impl ConfigVersion { + pub const fn version(&self) -> u16 { + match self { + Self::V1(_) => 1, + } + } + + pub fn encoded_len(&self) -> usize { + match self { + Self::V1(config) => config.encoded_len(), + } + } + + fn parse(version: u16, payload: &[u8]) -> Result { + match version { + 1 => ConfigV1::parse(payload).map(Self::V1), + version => Err(ConfigError::UnsupportedVersion(version)), + } + } + + pub fn validate(&self) -> Result<(), ConfigError> { + match self { + Self::V1(config) => config.validate(), + } + } + + fn encode(&self, out: &mut [u8]) -> Result { + match self { + Self::V1(config) => config.encode(out), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ConfigSnapshot { + pub active_slot: u8, + pub config: ConfigV1, +} + +impl ConfigSnapshot { + pub fn encoded_len(&self) -> usize { + 1 + self.config.encoded_len() + } + + pub fn parse(bytes: &[u8]) -> Result { + let Some((&active_slot, payload)) = bytes.split_first() else { + return Err(ConfigError::Truncated { + needed: 1, + available: 0, + }); + }; + + Ok(Self { + active_slot, + config: ConfigV1::parse(payload)?, + }) + } + + pub fn encode(&self, out: &mut [u8]) -> Result { + if out.is_empty() { + return Err(ConfigError::BufferTooSmall { + needed: self.encoded_len(), + available: 0, + }); + } + + out[0] = self.active_slot; + Ok(1 + self.config.encode(&mut out[1..])?) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(transparent))] +pub struct ConfigContainer { + pub config: ConfigVersion, +} + +impl ConfigContainer { + pub fn new(config: ConfigVersion) -> Self { + Self { config } + } + + pub const fn version(&self) -> u16 { + self.config.version() + } + + pub fn payload_len(&self) -> usize { + self.config.encoded_len() + } + + pub fn encoded_len(&self) -> usize { + HEADER_LEN + self.payload_len() + CRC_LEN + } + + pub fn parse(bytes: &[u8]) -> Result<(Self, usize), ConfigError> { + if bytes.len() < HEADER_LEN + CRC_LEN || bytes.iter().all(|&byte| byte == 0xff) { + return Err(ConfigError::NotPresent); + } + + if bytes[..4] != MAGIC { + return Err(ConfigError::BadMagic); + } + + let version = u16::from_le_bytes([bytes[4], bytes[5]]); + let payload_len = u16::from_le_bytes([bytes[6], bytes[7]]) as usize; + let total = HEADER_LEN + payload_len + CRC_LEN; + + if bytes.len() < total { + return Err(ConfigError::Truncated { + needed: total, + available: bytes.len(), + }); + } + + let crc_offset = HEADER_LEN + payload_len; + let expected = u32::from_le_bytes([ + bytes[crc_offset], + bytes[crc_offset + 1], + bytes[crc_offset + 2], + bytes[crc_offset + 3], + ]); + let actual = crc32(&bytes[..crc_offset]); + + if expected != actual { + return Err(ConfigError::CrcMismatch { expected, actual }); + } + + let config = ConfigVersion::parse(version, &bytes[HEADER_LEN..HEADER_LEN + payload_len])?; + + Ok((Self { config }, total)) + } + + pub fn encode(&self, out: &mut [u8]) -> Result { + self.config.validate()?; + + let payload_len = self.payload_len(); + let total = HEADER_LEN + payload_len + CRC_LEN; + + if out.len() < total { + return Err(ConfigError::BufferTooSmall { + needed: total, + available: out.len(), + }); + } + + if payload_len > u16::MAX as usize { + return Err(ConfigError::ConfigTooLarge(payload_len)); + } + + out[..4].copy_from_slice(&MAGIC); + out[4..6].copy_from_slice(&self.version().to_le_bytes()); + out[6..8].copy_from_slice(&(payload_len as u16).to_le_bytes()); + + let written = self + .config + .encode(&mut out[HEADER_LEN..HEADER_LEN + payload_len])?; + debug_assert_eq!(written, payload_len); + + let crc = crc32(&out[..HEADER_LEN + payload_len]); + out[HEADER_LEN + payload_len..total].copy_from_slice(&crc.to_le_bytes()); + + Ok(total) + } +} + +impl From for ConfigContainer { + fn from(config: ConfigVersion) -> Self { + Self::new(config) + } +} diff --git a/shared/src/config/error.rs b/shared/src/config/error.rs new file mode 100644 index 0000000..c922eb7 --- /dev/null +++ b/shared/src/config/error.rs @@ -0,0 +1,89 @@ +use super::ConfigTag; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, defmt::Format)] +pub enum ConfigError { + NotPresent, + BadMagic, + Truncated { + needed: usize, + available: usize, + }, + UnsupportedVersion(u16), + ValueTooLong { + len: usize, + max: usize, + }, + BadValueLength { + tag: ConfigTag, + expected: usize, + actual: usize, + }, + InvalidUtf8 { + tag: ConfigTag, + }, + Invalid { + errors: usize, + }, + UnknownTag(ConfigTag), + InvalidHardwareInfo, + TooManyTlvs, + TrailingBytes(usize), + CrcMismatch { + expected: u32, + actual: u32, + }, + Missing(ConfigTag), + BufferTooSmall { + needed: usize, + available: usize, + }, + ConfigTooLarge(usize), +} + +impl core::fmt::Display for ConfigError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::NotPresent => write!(f, "config not present"), + Self::BadMagic => write!(f, "bad config magic"), + Self::Truncated { needed, available } => { + write!(f, "config truncated: need {needed} bytes, have {available}") + } + Self::UnsupportedVersion(version) => { + write!(f, "unsupported config version {version}") + } + Self::ValueTooLong { len, max } => { + write!(f, "config value too long: {len} > {max}") + } + Self::BadValueLength { + tag, + expected, + actual, + } => write!( + f, + "bad value length for tag {:?}: expected {expected}, got {actual}", + tag + ), + Self::InvalidUtf8 { tag } => write!(f, "invalid UTF-8 for tag {tag:?}"), + Self::Invalid { errors } => { + write!(f, "config validation failed ({errors} errors)") + } + Self::UnknownTag(tag) => write!(f, "unknown config tag {tag:?}"), + Self::InvalidHardwareInfo => write!(f, "invalid hardware info"), + Self::TooManyTlvs => write!(f, "too many TLVs"), + Self::TrailingBytes(len) => write!(f, "trailing config bytes: {len}"), + Self::CrcMismatch { expected, actual } => { + write!( + f, + "CRC mismatch: expected {expected:#010x}, got {actual:#010x}" + ) + } + Self::Missing(tag) => write!(f, "missing config tag {tag:?}"), + Self::BufferTooSmall { needed, available } => { + write!(f, "buffer too small: need {needed}, have {available}") + } + Self::ConfigTooLarge(len) => write!(f, "config too large: {len}"), + } + } +} + +impl core::error::Error for ConfigError {} diff --git a/shared/src/config/mod.rs b/shared/src/config/mod.rs new file mode 100644 index 0000000..9e0bffc --- /dev/null +++ b/shared/src/config/mod.rs @@ -0,0 +1,607 @@ +mod container; +mod error; +mod schema; +mod tag; +mod tlv; +mod value; + +pub use container::{ConfigContainer, ConfigSnapshot, ConfigV1, ConfigVersion, MAGIC, crc32}; +pub use error::ConfigError; +pub use schema::DeviceConfig; +pub use tag::{ConfigTag, tags}; +pub use tlv::{ConfigKey, MAX_TLVS, Tlv, TlvList}; +pub use value::{ConfigBytes, ConfigString, ConfigValue, MAX_VALUE_LEN}; + +#[cfg(test)] +mod tests { + use super::schema::{ManufString, ProductId, ProductString, SerialString, VendorId}; + use super::*; + + const MANUF_STRING: &[u8] = b"VE7XEN"; + + fn bytes(value: &[u8]) -> ConfigBytes { + ConfigBytes::from_slice(value).unwrap() + } + + fn payload(tlvs: &[Tlv]) -> ([u8; 64], usize) { + let mut buf = [0u8; 64]; + buf[..2].copy_from_slice(&(tlvs.len() as u16).to_le_bytes()); + + let mut offset = 2; + for tlv in tlvs { + offset += tlv.encode(&mut buf[offset..]).unwrap(); + } + + (buf, offset) + } + + fn manuf_tlv() -> Tlv { + Tlv { + tag: tags::MANUF_STRING, + value: bytes(MANUF_STRING), + } + } + + fn v1_with_manuf() -> ConfigV1 { + let mut tlvs = TlvList::new(); + tlvs.push(manuf_tlv()).unwrap(); + ConfigV1 { tlvs } + } + + fn container_with_manuf() -> ConfigContainer { + ConfigContainer::new(ConfigVersion::V1(v1_with_manuf())) + } + + #[test] + fn tlv_wire_format_is_stable() { + let tlv = manuf_tlv(); + let mut buf = [0u8; 16]; + let len = tlv.encode(&mut buf).unwrap(); + + assert_eq!( + &buf[..len], + &[0x03, 0x00, 0x06, 0x00, b'V', b'E', b'7', b'X', b'E', b'N'] + ); + } + + #[test] + fn tlv_roundtrip() { + let tlv = manuf_tlv(); + let mut buf = [0u8; 16]; + let len = tlv.encode(&mut buf).unwrap(); + + let (decoded, consumed) = Tlv::parse(&buf[..len]).unwrap(); + + assert_eq!(decoded, tlv); + assert_eq!(consumed, len); + } + + #[test] + fn config_v1_roundtrip() { + let config = v1_with_manuf(); + let mut buf = [0u8; 32]; + let len = config.encode(&mut buf).unwrap(); + + assert_eq!(&buf[..2], &[0x01, 0x00]); + + let decoded = ConfigV1::parse(&buf[..len]).unwrap(); + + assert_eq!(decoded, config); + assert_eq!(len, config.encoded_len()); + } + + #[test] + fn empty_config_roundtrip() { + let config = ConfigV1::default(); + let mut buf = [0u8; 4]; + let len = config.encode(&mut buf).unwrap(); + + assert_eq!(&buf[..len], &[0x00, 0x00]); + assert_eq!(ConfigV1::parse(&buf[..len]).unwrap(), config); + } + + #[test] + fn config_container_roundtrip() { + let container = container_with_manuf(); + let mut buf = [0u8; 64]; + let len = container.encode(&mut buf).unwrap(); + + let (decoded, consumed) = ConfigContainer::parse(&buf[..len]).unwrap(); + + assert_eq!(decoded, container); + assert_eq!(consumed, len); + assert_eq!(len, container.encoded_len()); + } + + #[test] + fn config_container_wire_format_is_stable() { + let container = container_with_manuf(); + let mut buf = [0u8; 64]; + let len = container.encode(&mut buf).unwrap(); + + assert_eq!( + &buf[..len], + &[ + 0x47, 0x55, 0x41, 0x43, // magic + 0x01, 0x00, // version + 0x0c, 0x00, // payload length + 0x01, 0x00, // tlv count + 0x03, 0x00, 0x06, 0x00, b'V', b'E', b'7', b'X', b'E', b'N', // tlv + 0x22, 0x95, 0x37, 0x8b, // crc32 + ] + ); + } + + #[test] + fn config_container_ignores_trailing_slot_bytes() { + let container = container_with_manuf(); + let mut buf = [0xffu8; 64]; + let len = container.encode(&mut buf).unwrap(); + + let (decoded, consumed) = ConfigContainer::parse(&buf).unwrap(); + + assert_eq!(decoded, container); + assert_eq!(consumed, len); + } + + #[test] + fn config_container_rejects_erased_slot() { + assert_eq!( + ConfigContainer::parse(&[0xff; 32]).unwrap_err(), + ConfigError::NotPresent + ); + } + + #[test] + fn config_container_rejects_bad_magic() { + assert_eq!( + ConfigContainer::parse(&[0x00; 32]).unwrap_err(), + ConfigError::BadMagic + ); + } + + #[test] + fn config_container_rejects_bad_crc() { + let container = container_with_manuf(); + let mut buf = [0u8; 64]; + let len = container.encode(&mut buf).unwrap(); + buf[10] ^= 0xff; + + assert!(matches!( + ConfigContainer::parse(&buf[..len]), + Err(ConfigError::CrcMismatch { .. }) + )); + } + + #[test] + fn config_container_rejects_unsupported_version() { + let container = container_with_manuf(); + let mut buf = [0u8; 64]; + let len = container.encode(&mut buf).unwrap(); + let payload_len = u16::from_le_bytes([buf[6], buf[7]]) as usize; + + buf[4..6].copy_from_slice(&2u16.to_le_bytes()); + let crc = crc32(&buf[..8 + payload_len]); + buf[8 + payload_len..len].copy_from_slice(&crc.to_le_bytes()); + + assert_eq!( + ConfigContainer::parse(&buf[..len]).unwrap_err(), + ConfigError::UnsupportedVersion(2) + ); + } + + #[test] + fn config_container_rejects_truncated_payload() { + let container = container_with_manuf(); + let mut buf = [0u8; 64]; + let len = container.encode(&mut buf).unwrap(); + + assert_eq!( + ConfigContainer::parse(&buf[..len - 1]).unwrap_err(), + ConfigError::Truncated { + needed: len, + available: len - 1, + } + ); + } + + #[test] + fn config_v1_rejects_too_many_tlvs() { + let mut payload = [0u8; 2 + (MAX_TLVS + 1) * 4]; + payload[..2].copy_from_slice(&((MAX_TLVS + 1) as u16).to_le_bytes()); + + for offset in (2..payload.len()).step_by(4) { + payload[offset..offset + 4].copy_from_slice(&[0x99, 0x99, 0x00, 0x00]); + } + + assert_eq!( + ConfigV1::parse(&payload).unwrap_err(), + ConfigError::TooManyTlvs + ); + } + + #[test] + fn config_v1_rejects_trailing_bytes() { + let config = v1_with_manuf(); + let mut buf = [0u8; 16]; + let len = config.encode(&mut buf).unwrap(); + buf[len] = 0x00; + + assert_eq!( + ConfigV1::parse(&buf[..=len]).unwrap_err(), + ConfigError::TrailingBytes(1) + ); + } + + #[test] + fn tlv_rejects_oversized_value() { + assert_eq!( + Tlv::parse(&[0x03, 0x00, 0x41, 0x00]).unwrap_err(), + ConfigError::ValueTooLong { + len: 65, + max: MAX_VALUE_LEN, + } + ); + } + + #[test] + fn tlv_rejects_truncated_value() { + assert_eq!( + Tlv::parse(&[0x03, 0x00, 0x06, 0x00, b'V']).unwrap_err(), + ConfigError::Truncated { + needed: 10, + available: 5, + } + ); + } + + #[test] + fn unknown_tag_roundtrips() { + let mut tlvs = TlvList::new(); + tlvs.push(Tlv { + tag: ConfigTag(0x9999), + value: bytes(b"raw"), + }) + .unwrap(); + + let container = ConfigContainer::new(ConfigVersion::V1(ConfigV1 { tlvs })); + let mut buf = [0u8; 64]; + let len = container.encode(&mut buf).unwrap(); + let (decoded, _) = ConfigContainer::parse(&buf[..len]).unwrap(); + + assert_eq!(decoded, container); + } + + #[test] + fn config_container_rejects_small_buffer() { + let container = container_with_manuf(); + let mut buf = [0u8; 4]; + + assert_eq!( + container.encode(&mut buf).unwrap_err(), + ConfigError::BufferTooSmall { + needed: 24, + available: 4, + } + ); + } + + #[test] + fn typed_value_roundtrip() { + let mut tlvs = TlvList::new(); + tlvs.set::(0x1209).unwrap(); + tlvs.set::(ConfigString::<32>::try_from("VE7XEN").unwrap()) + .unwrap(); + + assert_eq!(tlvs.get::().unwrap(), Some(0x1209)); + assert_eq!( + tlvs.get::().unwrap(), + Some(ConfigString::<32>::try_from("VE7XEN").unwrap()) + ); + } + + #[test] + fn typed_value_uses_little_endian() { + let mut tlvs = TlvList::new(); + tlvs.set::(0x1209).unwrap(); + + assert_eq!( + tlvs.find(tags::VENDOR_ID).unwrap().value.as_slice(), + &[0x09, 0x12] + ); + } + + #[test] + fn typed_value_rejects_bad_length() { + let mut tlvs = TlvList::new(); + tlvs.push(Tlv { + tag: tags::VENDOR_ID, + value: bytes(&[1, 2, 3]), + }) + .unwrap(); + + assert_eq!( + tlvs.get::().unwrap_err(), + ConfigError::BadValueLength { + tag: tags::VENDOR_ID, + expected: 2, + actual: 3, + } + ); + } + + #[test] + fn string_value_rejects_invalid_utf8() { + let mut tlvs = TlvList::new(); + tlvs.push(Tlv { + tag: tags::MANUF_STRING, + value: bytes(&[0xff]), + }) + .unwrap(); + + assert_eq!( + tlvs.get::().unwrap_err(), + ConfigError::InvalidUtf8 { + tag: tags::MANUF_STRING, + } + ); + } + + #[test] + fn string_value_rejects_too_long() { + assert_eq!( + ConfigString::<4>::try_from("hello").unwrap_err(), + ConfigError::ValueTooLong { len: 5, max: 4 } + ); + } + + #[test] + fn duplicate_tags_first_match_wins() { + let mut tlvs = TlvList::new(); + tlvs.push(Tlv { + tag: tags::VENDOR_ID, + value: bytes(&0x1111u16.to_le_bytes()), + }) + .unwrap(); + tlvs.push(Tlv { + tag: tags::VENDOR_ID, + value: bytes(&0x2222u16.to_le_bytes()), + }) + .unwrap(); + + assert_eq!(tlvs.get::().unwrap(), Some(0x1111)); + } + + #[test] + fn set_replaces_existing_tag() { + let mut tlvs = TlvList::new(); + tlvs.set::(0x1111).unwrap(); + tlvs.set::(0x2222).unwrap(); + + assert_eq!(tlvs.len(), 1); + assert_eq!(tlvs.get::().unwrap(), Some(0x2222)); + } + + #[test] + fn missing_key_returns_none() { + assert_eq!(TlvList::new().get::().unwrap(), None); + } + + #[test] + fn config_v1_rejects_zero_vendor_id() { + let (buf, len) = payload(&[Tlv { + tag: tags::VENDOR_ID, + value: bytes(&0u16.to_le_bytes()), + }]); + + assert_eq!( + ConfigV1::parse(&buf[..len]).unwrap_err(), + ConfigError::Invalid { errors: 1 } + ); + } + + #[test] + fn config_v1_rejects_bad_known_value_length() { + let (buf, len) = payload(&[Tlv { + tag: tags::VENDOR_ID, + value: bytes(&[1, 2, 3]), + }]); + + assert_eq!( + ConfigV1::parse(&buf[..len]).unwrap_err(), + ConfigError::BadValueLength { + tag: tags::VENDOR_ID, + expected: 2, + actual: 3, + } + ); + } + + #[test] + fn config_v1_rejects_invalid_known_utf8() { + let (buf, len) = payload(&[Tlv { + tag: tags::MANUF_STRING, + value: bytes(&[0xff]), + }]); + + assert_eq!( + ConfigV1::parse(&buf[..len]).unwrap_err(), + ConfigError::InvalidUtf8 { + tag: tags::MANUF_STRING, + } + ); + } + + #[test] + fn config_v1_rejects_empty_serial() { + let (buf, len) = payload(&[Tlv { + tag: tags::SERIAL_STRING, + value: bytes(&[]), + }]); + + assert_eq!( + ConfigV1::parse(&buf[..len]).unwrap_err(), + ConfigError::Invalid { errors: 1 } + ); + } + + #[test] + fn config_v1_counts_validation_errors() { + let (buf, len) = payload(&[ + Tlv { + tag: tags::VENDOR_ID, + value: bytes(&0u16.to_le_bytes()), + }, + Tlv { + tag: tags::PRODUCT_ID, + value: bytes(&0u16.to_le_bytes()), + }, + ]); + + assert_eq!( + ConfigV1::parse(&buf[..len]).unwrap_err(), + ConfigError::Invalid { errors: 2 } + ); + } + + #[test] + fn config_v1_rejects_empty_manufacturer() { + let (buf, len) = payload(&[Tlv { + tag: tags::MANUF_STRING, + value: bytes(&[]), + }]); + + assert_eq!( + ConfigV1::parse(&buf[..len]).unwrap_err(), + ConfigError::Invalid { errors: 1 } + ); + } + + #[test] + fn encode_rejects_invalid_config() { + let mut tlvs = TlvList::new(); + tlvs.push(Tlv { + tag: tags::VENDOR_ID, + value: bytes(&0u16.to_le_bytes()), + }) + .unwrap(); + + let mut buf = [0u8; 64]; + + assert_eq!( + ConfigV1 { tlvs }.encode(&mut buf).unwrap_err(), + ConfigError::Invalid { errors: 1 } + ); + } + + #[test] + fn device_config_defaults() { + let config = DeviceConfig::with_defaults(None).unwrap(); + + assert_eq!(config.usb_vendor_id, 0x1209); + assert_eq!(config.usb_product_id, 0xcc1d); + assert_eq!(config.usb_manufacturer.as_str(), "VE7XEN"); + assert_eq!(config.usb_product.as_str(), "Guac Tortilla"); + assert!(config.usb_serial.is_none()); + } + + #[test] + fn device_config_from_tlvs() { + let mut tlvs = TlvList::new(); + tlvs.set::(0x1234).unwrap(); + tlvs.set::(0x5678).unwrap(); + tlvs.set::(ConfigString::try_from("Maker").unwrap()) + .unwrap(); + tlvs.set::(ConfigString::try_from("Widget").unwrap()) + .unwrap(); + tlvs.set::(ConfigString::try_from("SN123").unwrap()) + .unwrap(); + + let config = DeviceConfig::from_tlvs(&tlvs).unwrap(); + + assert_eq!(config.usb_vendor_id, 0x1234); + assert_eq!(config.usb_product_id, 0x5678); + assert_eq!(config.usb_manufacturer.as_str(), "Maker"); + assert_eq!(config.usb_product.as_str(), "Widget"); + assert_eq!(config.usb_serial.as_ref().unwrap().as_str(), "SN123"); + assert_eq!( + DeviceConfig::from_tlvs(&config.to_tlvs().unwrap()).unwrap(), + config + ); + } + + #[test] + fn device_config_with_serial_defaults() { + let serial = ConfigString::<32>::try_from("0123456789ABCDEF0123456789ABCDEF").unwrap(); + let config = DeviceConfig::with_defaults(Some(serial.clone())).unwrap(); + + assert_eq!(config.usb_vendor_id, 0x1209); + assert_eq!(config.usb_manufacturer.as_str(), "VE7XEN"); + assert_eq!(config.usb_serial, Some(serial)); + } + + #[test] + fn config_snapshot_roundtrip() { + let snapshot = ConfigSnapshot { + active_slot: 1, + config: v1_with_manuf(), + }; + let mut buf = [0u8; 64]; + let len = snapshot.encode(&mut buf).unwrap(); + + assert_eq!(len, snapshot.encoded_len()); + assert_eq!(ConfigSnapshot::parse(&buf[..len]).unwrap(), snapshot); + } + + #[test] + fn replace_tlv_updates_config() { + let mut config = DeviceConfig::with_defaults(None).unwrap(); + + config + .replace_tlv(Tlv { + tag: tags::VENDOR_ID, + value: bytes(&0x1234u16.to_le_bytes()), + }) + .unwrap(); + assert_eq!(config.usb_vendor_id, 0x1234); + + config + .replace_tlv(Tlv { + tag: tags::SERIAL_STRING, + value: bytes(b"SN123"), + }) + .unwrap(); + assert_eq!(config.usb_serial.as_ref().unwrap().as_str(), "SN123"); + + assert_eq!( + config + .replace_tlv(Tlv { + tag: ConfigTag(0x9999), + value: bytes(b"x"), + }) + .unwrap_err(), + ConfigError::UnknownTag(ConfigTag(0x9999)) + ); + + assert_eq!( + config + .replace_tlv(Tlv { + tag: tags::VENDOR_ID, + value: bytes(&0u16.to_le_bytes()), + }) + .unwrap_err(), + ConfigError::Invalid { errors: 1 } + ); + } + + #[test] + fn crc32_known_vector() { + assert_eq!(crc32(b"123456789"), 0xcbf4_3926); + } + + #[test] + fn tag_name() { + assert_eq!(tags::VENDOR_ID.name(), Some("VendorId")); + assert_eq!(ConfigTag(0x9999).name(), None); + } +} diff --git a/shared/src/config/schema.rs b/shared/src/config/schema.rs new file mode 100644 index 0000000..2b39f54 --- /dev/null +++ b/shared/src/config/schema.rs @@ -0,0 +1,198 @@ +use wary::Validate; + +use super::{ + ConfigError, ConfigKey, ConfigString, ConfigTag, ConfigV1, ConfigVersion, Tlv, TlvList, tags, +}; + +#[derive(Clone, Debug, PartialEq, Eq, wary::Wary)] +pub struct DeviceConfig { + #[validate(range(1..))] + pub usb_vendor_id: u16, + + #[validate(range(1..))] + pub usb_product_id: u16, + + #[validate(dive)] + pub usb_manufacturer: ConfigString<32>, + + #[validate(dive)] + pub usb_product: ConfigString<64>, + + #[validate(dive)] + pub usb_serial: Option>, +} + +impl DeviceConfig { + pub fn from_tlvs(tlvs: &TlvList) -> Result { + let config = Self { + usb_vendor_id: resolve::(tlvs)?, + usb_product_id: resolve::(tlvs)?, + usb_manufacturer: resolve::(tlvs)?, + usb_product: resolve::(tlvs)?, + usb_serial: tlvs.get::()?, + }; + + config + .validate(&()) + .map_err(|report| ConfigError::Invalid { + errors: report.len(), + })?; + + Ok(config) + } + + pub fn with_defaults(usb_serial: Option>) -> Result { + let mut config = Self::from_tlvs(&TlvList::new())?; + config.usb_serial = usb_serial; + + config + .validate(&()) + .map_err(|report| ConfigError::Invalid { + errors: report.len(), + })?; + + Ok(config) + } + + /// Serial used for the default configuration, rendered as upper case hex. + pub fn serial_from_uuid(uuid: &[u8; 16]) -> Option> { + const HEX: &[u8; 16] = b"0123456789ABCDEF"; + + let mut serial = [0u8; 32]; + + for (index, &byte) in uuid.iter().enumerate() { + serial[index * 2] = HEX[usize::from(byte >> 4)]; + serial[index * 2 + 1] = HEX[usize::from(byte & 0x0f)]; + } + + let serial = core::str::from_utf8(&serial).ok()?; + ConfigString::try_from(serial).ok() + } + + pub fn replace_tlv(&mut self, tlv: Tlv) -> Result<(), ConfigError> { + if tlv.tag.name().is_none() { + return Err(ConfigError::UnknownTag(tlv.tag)); + } + + let mut tlvs = self.to_tlvs()?; + tlvs.upsert(tlv)?; + *self = Self::from_tlvs(&tlvs)?; + Ok(()) + } + + pub fn to_tlvs(&self) -> Result { + let mut tlvs = TlvList::new(); + tlvs.set::(self.usb_vendor_id)?; + tlvs.set::(self.usb_product_id)?; + tlvs.set::(self.usb_manufacturer.clone())?; + tlvs.set::(self.usb_product.clone())?; + + if let Some(serial) = &self.usb_serial { + tlvs.set::(serial.clone())?; + } + + Ok(tlvs) + } +} + +impl TryFrom<&ConfigVersion> for DeviceConfig { + type Error = ConfigError; + + fn try_from(value: &ConfigVersion) -> Result { + match value { + ConfigVersion::V1(config) => Self::try_from(config), + } + } +} + +impl TryFrom<&ConfigV1> for DeviceConfig { + type Error = ConfigError; + + fn try_from(value: &ConfigV1) -> Result { + Self::from_tlvs(&value.tlvs) + } +} + +fn resolve(tlvs: &TlvList) -> Result { + tlvs.get::()? + .or_else(K::default_value) + .ok_or(ConfigError::Missing(K::TAG)) +} + +pub(crate) struct VendorId; +impl ConfigKey for VendorId { + const TAG: ConfigTag = tags::VENDOR_ID; + type Value = u16; + + fn default_value() -> Option { + Some(0x1209) + } +} + +pub(crate) struct ProductId; +impl ConfigKey for ProductId { + const TAG: ConfigTag = tags::PRODUCT_ID; + type Value = u16; + + fn default_value() -> Option { + Some(0xcc1d) + } +} + +pub(crate) struct ManufString; +impl ConfigKey for ManufString { + const TAG: ConfigTag = tags::MANUF_STRING; + type Value = ConfigString<32>; + + fn default_value() -> Option { + Some(ConfigString::try_from("VE7XEN").unwrap_or_default()) + } +} + +pub(crate) struct ProductString; +impl ConfigKey for ProductString { + const TAG: ConfigTag = tags::PRODUCT_STRING; + type Value = ConfigString<64>; + + fn default_value() -> Option { + Some(ConfigString::try_from("Guac Tortilla").unwrap_or_default()) + } +} + +pub(crate) struct SerialString; +impl ConfigKey for SerialString { + const TAG: ConfigTag = tags::SERIAL_STRING; + type Value = ConfigString<32>; + + fn default_value() -> Option { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn serial_from_uuid_is_uppercase_hex() { + let uuid = [ + 0x35, 0x60, 0x14, 0xf7, 0x7b, 0x65, 0xb4, 0x5d, 0x9d, 0xbf, 0x81, 0x11, 0xc5, 0xc4, + 0x29, 0xa5, + ]; + + assert_eq!( + DeviceConfig::serial_from_uuid(&uuid).unwrap().as_str(), + "356014F77B65B45D9DBF8111C5C429A5" + ); + } + + #[test] + fn defaults_are_valid() { + let config = DeviceConfig::with_defaults(None).unwrap(); + + assert_eq!(config.usb_vendor_id, 0x1209); + assert_eq!(config.usb_product_id, 0xcc1d); + assert!(config.usb_serial.is_none()); + assert_eq!(config.to_tlvs().unwrap().len(), 4); + } +} diff --git a/shared/src/config/tag.rs b/shared/src/config/tag.rs new file mode 100644 index 0000000..33aa4af --- /dev/null +++ b/shared/src/config/tag.rs @@ -0,0 +1,26 @@ +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, defmt::Format)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct ConfigTag(pub u16); + +pub mod tags { + use super::ConfigTag; + + pub const VENDOR_ID: ConfigTag = ConfigTag(0x0001); + pub const PRODUCT_ID: ConfigTag = ConfigTag(0x0002); + pub const MANUF_STRING: ConfigTag = ConfigTag(0x0003); + pub const PRODUCT_STRING: ConfigTag = ConfigTag(0x0004); + pub const SERIAL_STRING: ConfigTag = ConfigTag(0x0005); +} + +impl ConfigTag { + pub const fn name(self) -> Option<&'static str> { + match self.0 { + 0x0001 => Some("VendorId"), + 0x0002 => Some("ProductId"), + 0x0003 => Some("ManufString"), + 0x0004 => Some("ProductString"), + 0x0005 => Some("SerialString"), + _ => None, + } + } +} diff --git a/shared/src/config/tlv.rs b/shared/src/config/tlv.rs new file mode 100644 index 0000000..d4c6db6 --- /dev/null +++ b/shared/src/config/tlv.rs @@ -0,0 +1,179 @@ +use super::{ConfigBytes, ConfigError, ConfigTag, ConfigValue, MAX_VALUE_LEN}; + +pub const MAX_TLVS: usize = 64; + +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Tlv { + pub tag: ConfigTag, + pub value: ConfigBytes, +} + +impl Tlv { + pub fn encoded_len(&self) -> usize { + 4 + self.value.len() + } + + pub fn parse(bytes: &[u8]) -> Result<(Self, usize), ConfigError> { + if bytes.len() < 4 { + return Err(ConfigError::Truncated { + needed: 4, + available: bytes.len(), + }); + } + + let tag = ConfigTag(u16::from_le_bytes([bytes[0], bytes[1]])); + let len = u16::from_le_bytes([bytes[2], bytes[3]]) as usize; + + if len > MAX_VALUE_LEN { + return Err(ConfigError::ValueTooLong { + len, + max: MAX_VALUE_LEN, + }); + } + + let needed = 4 + len; + if bytes.len() < needed { + return Err(ConfigError::Truncated { + needed, + available: bytes.len(), + }); + } + + let value = ConfigBytes::from_slice(&bytes[4..needed])?; + + Ok((Self { tag, value }, needed)) + } + + pub fn encode(&self, out: &mut [u8]) -> Result { + let needed = self.encoded_len(); + if out.len() < needed { + return Err(ConfigError::BufferTooSmall { + needed, + available: out.len(), + }); + } + + out[..2].copy_from_slice(&self.tag.0.to_le_bytes()); + out[2..4].copy_from_slice(&(self.value.len() as u16).to_le_bytes()); + out[4..needed].copy_from_slice(self.value.as_slice()); + + Ok(needed) + } +} + +pub trait ConfigKey { + const TAG: ConfigTag; + type Value: ConfigValue; + + fn default_value() -> Option; +} + +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(transparent))] +pub struct TlvList { + items: heapless::Vec, +} + +impl TlvList { + pub const fn new() -> Self { + Self { + items: heapless::Vec::new(), + } + } + + pub fn as_slice(&self) -> &[Tlv] { + self.items.as_slice() + } + + pub fn iter(&self) -> core::slice::Iter<'_, Tlv> { + self.items.iter() + } + + pub fn len(&self) -> usize { + self.items.len() + } + + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } + + pub fn push(&mut self, tlv: Tlv) -> Result<(), ConfigError> { + self.items.push(tlv).map_err(|_| ConfigError::TooManyTlvs) + } + + pub fn find(&self, tag: ConfigTag) -> Option<&Tlv> { + self.items.iter().find(|tlv| tlv.tag == tag) + } + + pub fn get(&self) -> Result, ConfigError> { + self.find(K::TAG) + .map(|tlv| K::Value::decode(K::TAG, tlv.value.as_slice())) + .transpose() + } + + pub fn set(&mut self, value: K::Value) -> Result<(), ConfigError> { + let mut bytes = ConfigBytes::new(); + value.encode(&mut bytes)?; + self.upsert(Tlv { + tag: K::TAG, + value: bytes, + }) + } + + pub fn upsert(&mut self, tlv: Tlv) -> Result<(), ConfigError> { + if let Some(existing) = self + .items + .iter_mut() + .find(|existing| existing.tag == tlv.tag) + { + existing.value = tlv.value; + Ok(()) + } else { + self.push(tlv) + } + } + + pub fn remove(&mut self, tag: ConfigTag) -> bool { + if let Some(index) = self.items.iter().position(|tlv| tlv.tag == tag) { + self.items.remove(index); + true + } else { + false + } + } + + pub fn encoded_len(&self) -> usize { + self.items.iter().map(Tlv::encoded_len).sum() + } +} + +impl Default for TlvList { + fn default() -> Self { + Self::new() + } +} + +impl AsRef<[Tlv]> for TlvList { + fn as_ref(&self) -> &[Tlv] { + self.as_slice() + } +} + +impl core::ops::Deref for TlvList { + type Target = [Tlv]; + + fn deref(&self) -> &Self::Target { + self.as_slice() + } +} + +impl<'a> IntoIterator for &'a TlvList { + type Item = &'a Tlv; + type IntoIter = core::slice::Iter<'a, Tlv>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} diff --git a/shared/src/config/value.rs b/shared/src/config/value.rs new file mode 100644 index 0000000..a18a976 --- /dev/null +++ b/shared/src/config/value.rs @@ -0,0 +1,182 @@ +use super::{ConfigError, ConfigTag}; + +pub const MAX_VALUE_LEN: usize = 64; + +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct ConfigBytes(heapless::Vec); + +impl ConfigBytes { + pub const fn new() -> Self { + Self(heapless::Vec::new()) + } + + pub fn from_slice(bytes: &[u8]) -> Result { + heapless::Vec::from_slice(bytes) + .map(Self) + .map_err(|_| ConfigError::ValueTooLong { + len: bytes.len(), + max: N, + }) + } + + pub fn as_slice(&self) -> &[u8] { + self.0.as_slice() + } + + pub fn len(&self) -> usize { + self.0.len() + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn extend_from_slice(&mut self, bytes: &[u8]) -> Result<(), ConfigError> { + self.0 + .extend_from_slice(bytes) + .map_err(|_| ConfigError::ValueTooLong { + len: self.0.len() + bytes.len(), + max: N, + }) + } +} + +impl Default for ConfigBytes { + fn default() -> Self { + Self::new() + } +} + +impl AsRef<[u8]> for ConfigBytes { + fn as_ref(&self) -> &[u8] { + self.as_slice() + } +} + +impl core::ops::Deref for ConfigBytes { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + self.as_slice() + } +} + +impl TryFrom<&[u8]> for ConfigBytes { + type Error = ConfigError; + + fn try_from(value: &[u8]) -> Result { + Self::from_slice(value) + } +} + +pub trait ConfigValue: Sized { + fn decode(tag: ConfigTag, bytes: &[u8]) -> Result; + fn encode(&self, out: &mut ConfigBytes) -> Result<(), ConfigError>; +} + +impl ConfigValue for ConfigBytes { + fn decode(_tag: ConfigTag, bytes: &[u8]) -> Result { + Self::from_slice(bytes) + } + + fn encode(&self, out: &mut ConfigBytes) -> Result<(), ConfigError> { + out.extend_from_slice(self.as_slice()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, wary::Wary)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[wary(transparent)] +pub struct ConfigString( + #[validate(length(code_units, 1..=126))] heapless::String, +); + +impl ConfigString { + pub const fn new() -> Self { + Self(heapless::String::new()) + } + + pub fn as_str(&self) -> &str { + self.0.as_str() + } + + pub fn as_bytes(&self) -> &[u8] { + self.0.as_str().as_bytes() + } + + pub fn len(&self) -> usize { + self.0.len() + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +impl Default for ConfigString { + fn default() -> Self { + Self::new() + } +} + +impl AsRef for ConfigString { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl core::ops::Deref for ConfigString { + type Target = str; + + fn deref(&self) -> &Self::Target { + self.as_str() + } +} + +impl core::fmt::Display for ConfigString { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(self.as_str()) + } +} + +impl TryFrom<&str> for ConfigString { + type Error = ConfigError; + + fn try_from(value: &str) -> Result { + heapless::String::try_from(value) + .map(Self) + .map_err(|_| ConfigError::ValueTooLong { + len: value.len(), + max: N, + }) + } +} + +impl ConfigValue for ConfigString { + fn decode(tag: ConfigTag, bytes: &[u8]) -> Result { + let value = core::str::from_utf8(bytes).map_err(|_| ConfigError::InvalidUtf8 { tag })?; + + Self::try_from(value) + } + + fn encode(&self, out: &mut ConfigBytes) -> Result<(), ConfigError> { + out.extend_from_slice(self.as_bytes()) + } +} + +impl ConfigValue for u16 { + fn decode(tag: ConfigTag, bytes: &[u8]) -> Result { + let bytes: [u8; 2] = bytes.try_into().map_err(|_| ConfigError::BadValueLength { + tag, + expected: 2, + actual: bytes.len(), + })?; + + Ok(Self::from_le_bytes(bytes)) + } + + fn encode(&self, out: &mut ConfigBytes) -> Result<(), ConfigError> { + out.extend_from_slice(&self.to_le_bytes()) + } +} diff --git a/shared/src/hardware.rs b/shared/src/hardware.rs new file mode 100644 index 0000000..ea67262 --- /dev/null +++ b/shared/src/hardware.rs @@ -0,0 +1,136 @@ +use crate::config::{ConfigError, ConfigString}; + +pub const UUID_LEN: usize = 16; +pub const MAX_DAC_NAME_LEN: usize = 32; +pub const MAX_VERSION_LEN: usize = 128; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HardwareInfo { + pub uuid: [u8; UUID_LEN], + pub dac: ConfigString, + pub version: ConfigString, +} + +impl HardwareInfo { + pub fn encoded_len(&self) -> usize { + UUID_LEN + 1 + self.dac.len() + 1 + self.version.len() + } + + pub fn encode(&self, out: &mut [u8]) -> Result { + let dac = self.dac.as_bytes(); + let version = self.version.as_bytes(); + let needed = self.encoded_len(); + + if out.len() < needed { + return Err(ConfigError::BufferTooSmall { + needed, + available: out.len(), + }); + } + + out[..UUID_LEN].copy_from_slice(&self.uuid); + + let mut offset = UUID_LEN; + out[offset] = dac.len() as u8; + offset += 1; + out[offset..offset + dac.len()].copy_from_slice(dac); + offset += dac.len(); + + out[offset] = version.len() as u8; + offset += 1; + out[offset..offset + version.len()].copy_from_slice(version); + + Ok(needed) + } + + pub fn parse(bytes: &[u8]) -> Result { + let mut offset = UUID_LEN; + + if bytes.len() < offset + 1 { + return Err(ConfigError::Truncated { + needed: offset + 1, + available: bytes.len(), + }); + } + + let uuid = bytes[..UUID_LEN] + .try_into() + .map_err(|_| ConfigError::InvalidHardwareInfo)?; + + let dac_len = usize::from(bytes[offset]); + offset += 1; + + if bytes.len() < offset + dac_len + 1 { + return Err(ConfigError::Truncated { + needed: offset + dac_len + 1, + available: bytes.len(), + }); + } + + let dac = core::str::from_utf8(&bytes[offset..offset + dac_len]) + .map_err(|_| ConfigError::InvalidHardwareInfo)?; + let dac = ConfigString::try_from(dac).map_err(|_| ConfigError::InvalidHardwareInfo)?; + offset += dac_len; + + let version_len = usize::from(bytes[offset]); + offset += 1; + + if bytes.len() < offset + version_len { + return Err(ConfigError::Truncated { + needed: offset + version_len, + available: bytes.len(), + }); + } + + let version = core::str::from_utf8(&bytes[offset..offset + version_len]) + .map_err(|_| ConfigError::InvalidHardwareInfo)?; + let version = + ConfigString::try_from(version).map_err(|_| ConfigError::InvalidHardwareInfo)?; + offset += version_len; + + if offset != bytes.len() { + return Err(ConfigError::TrailingBytes(bytes.len() - offset)); + } + + Ok(Self { uuid, dac, version }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn roundtrip() { + let info = HardwareInfo { + uuid: [ + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, + 0xee, 0xff, + ], + dac: ConfigString::try_from("AK4490").unwrap(), + version: ConfigString::try_from("v1.2.3").unwrap(), + }; + let mut buf = [0u8; 128]; + let len = info.encode(&mut buf).unwrap(); + + assert_eq!(len, info.encoded_len()); + assert_eq!(HardwareInfo::parse(&buf[..len]).unwrap(), info); + } + + #[test] + fn rejects_trailing_bytes() { + let info = HardwareInfo { + uuid: [0; UUID_LEN], + dac: ConfigString::try_from("DAC").unwrap(), + version: ConfigString::try_from("abc").unwrap(), + }; + let mut buf = [0u8; 128]; + let len = info.encode(&mut buf).unwrap(); + buf[len] = 0; + + assert_eq!( + HardwareInfo::parse(&buf[..=len]).unwrap_err(), + ConfigError::TrailingBytes(1) + ); + } +} diff --git a/shared/src/lib.rs b/shared/src/lib.rs index 5a0453e..60d4e04 100644 --- a/shared/src/lib.rs +++ b/shared/src/lib.rs @@ -1,9 +1,9 @@ #![no_std] +pub mod config; +pub mod hardware; + use bytemuck::NoUninit; -use deku::DekuRead; -#[cfg(feature = "std")] -use deku::DekuWrite; use num_enum::TryFromPrimitive; #[cfg(feature = "serde")] @@ -102,26 +102,11 @@ pub struct AudioTelemetrySnapshot { pub fb_rate_estimate: f32, } -// Writing is host-side only (needs deku's `alloc`, enabled by the `std` feature) -#[derive(Debug, DekuRead, Clone)] -#[cfg_attr(feature = "std", derive(DekuWrite))] -#[deku(id_type = "u8")] -pub enum AudioDeviceCommand { - #[deku(id = 0)] - Noop, - #[deku(id = 1)] - Reset, - #[deku(id = 2)] - Bootloader, -} - pub mod hid { - use deku::{DekuContainerRead, DekuError, DekuRead}; - #[cfg(feature = "std")] - use deku::{DekuContainerWrite, DekuWrite}; + use deku::DekuRead; use usbd_hid::descriptor::generator_prelude::*; - use crate::{AudioDeviceCommand, AudioState, AudioTelemetrySnapshot}; + use crate::{AudioState, AudioTelemetrySnapshot}; /// HID usage IDs identifying each vendor interface. `gen_hid_descriptor` only accepts /// literals, so the descriptors below repeat these values; keep them in sync. @@ -170,30 +155,155 @@ pub mod hid { } } - #[derive(DekuRead)] - #[cfg_attr(feature = "std", derive(DekuWrite))] - #[deku(endian = "little")] #[gen_hid_descriptor((collection = APPLICATION, usage_page = VENDOR_DEFINED_START, usage = 0x02, ) = { - cmd=output; + cmd=feature; + resp=input; })] #[repr(C, packed)] - pub struct AudioDeviceCommandReport { - pub cmd: [u8; 32], + pub struct DeviceCommandReport { + pub cmd: [u8; 63], + pub resp: [u8; 64], } - impl TryFrom for AudioDeviceCommand { - type Error = DekuError; - fn try_from(value: AudioDeviceCommandReport) -> Result { - Ok(AudioDeviceCommand::from_bytes((value.cmd.as_slice(), 0))?.1) + #[cfg(test)] + mod tests { + use super::*; + use usbd_hid::descriptor::SerializedDescriptor; + + #[test] + fn command_descriptor_has_bidirectional_reports() { + let descriptor = DeviceCommandReport::desc(); + + assert_eq!( + descriptor, + &[ + 0x06, 0x00, 0xff, 0x09, 0x02, 0xa1, 0x01, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, + 0x08, 0x95, 0x3f, 0xb1, 0x02, 0x95, 0x40, 0x81, 0x02, 0xc0, + ][..] + ); } } - #[cfg(feature = "std")] - impl From for AudioDeviceCommandReport { - fn from(value: AudioDeviceCommand) -> Self { - let mut buf = [0u8; core::mem::size_of::()]; - value.to_slice(&mut buf).unwrap(); - Self { cmd: buf } + pub mod command { + use num_enum::TryFromPrimitive; + + pub const COMMAND_REPORT_SIZE: usize = 63; + pub const IN_REPORT_SIZE: usize = 64; + pub const HEADER_LEN: usize = 7; + pub const COMMAND_PAYLOAD_LEN: usize = COMMAND_REPORT_SIZE - HEADER_LEN; + pub const IN_PAYLOAD_LEN: usize = IN_REPORT_SIZE - HEADER_LEN; + + #[repr(u8)] + #[derive(Clone, Copy, Debug, PartialEq, Eq, TryFromPrimitive, defmt::Format)] + pub enum CommandKind { + Noop = 0, + Reset = 1, + Bootloader = 2, + ReadConfig = 3, + ReplaceTlv = 4, + CommitConfig = 5, + Hardware = 6, + ResetConfig = 7, + } + + #[repr(u8)] + #[derive(Clone, Copy, Debug, PartialEq, Eq, TryFromPrimitive, defmt::Format)] + pub enum ResponseKind { + Ack = 0, + Nack = 1, + ConfigData = 2, + Noop = 3, + Hardware = 4, + } + + #[repr(u8)] + #[derive(Clone, Copy, Debug, PartialEq, Eq, TryFromPrimitive, defmt::Format)] + pub enum NackCode { + InvalidCommand = 0, + InvalidPayload = 1, + UnknownTag = 2, + InvalidConfig = 3, + FlashWriteFailed = 4, + Busy = 5, + ConfigTooLarge = 6, + } + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct Header { + pub kind: u8, + pub seq: u8, + pub total_len: u16, + pub offset: u16, + pub len: u8, + } + + impl Header { + pub fn encode(self, out: &mut [u8]) { + out[0] = self.kind; + out[1] = self.seq; + out[2..4].copy_from_slice(&self.total_len.to_le_bytes()); + out[4..6].copy_from_slice(&self.offset.to_le_bytes()); + out[6] = self.len; + } + + pub fn parse(bytes: &[u8]) -> Option { + if bytes.len() < HEADER_LEN { + return None; + } + + Some(Self { + kind: bytes[0], + seq: bytes[1], + total_len: u16::from_le_bytes([bytes[2], bytes[3]]), + offset: u16::from_le_bytes([bytes[4], bytes[5]]), + len: bytes[6], + }) + } + + pub fn is_complete(self) -> bool { + usize::from(self.offset) + usize::from(self.len) == usize::from(self.total_len) + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn legacy_reset_report_is_a_zero_length_header() { + let mut report = [0u8; COMMAND_REPORT_SIZE]; + report[0] = CommandKind::Reset as u8; + + let header = Header::parse(&report).unwrap(); + + assert_eq!(header.kind, CommandKind::Reset as u8); + assert_eq!(header.total_len, 0); + assert!(header.is_complete()); + } + + #[test] + fn header_roundtrip() { + let header = Header { + kind: CommandKind::ReplaceTlv as u8, + seq: 7, + total_len: 66, + offset: 25, + len: 25, + }; + + let mut buf = [0u8; HEADER_LEN]; + header.encode(&mut buf); + + assert_eq!(Header::parse(&buf), Some(header)); + assert!(!header.is_complete()); + + let header = Header { + offset: 41, + ..header + }; + + assert!(header.is_complete()); + } } } }