5 Commits
Author SHA1 Message Date
ktims 8917696367 bootloader: enter ISP from a boot request honoured before peripheral setup
Build and Release Firmware / firmware (ak4490) (push) Successful in 18s
Build and Release Firmware / firmware (cs4398) (push) Successful in 17s
Build and Release Firmware / firmware (evk) (push) Successful in 17s
Build and Release Firmware / cli (aarch64-unknown-linux-musl) (push) Successful in 1m0s
Build and Release Firmware / cli (universal2-apple-darwin) (push) Successful in 51s
Build and Release Firmware / cli (x86_64-pc-windows-gnu) (push) Successful in 1m5s
Build and Release Firmware / cli (x86_64-unknown-linux-musl) (push) Successful in 57s
Build and Release Firmware / release (push) Successful in 7s
2026-11-11 21:57:39 -07:00
ktims cc92b55df4 build: build for apple
Build and Release Firmware / firmware (ak4490) (push) Successful in 17s
Build and Release Firmware / firmware (cs4398) (push) Successful in 16s
Build and Release Firmware / firmware (evk) (push) Successful in 15s
Build and Release Firmware / cli (aarch64-unknown-linux-musl) (push) Successful in 1m58s
Build and Release Firmware / cli (universal2-apple-darwin) (push) Successful in 1m16s
Build and Release Firmware / cli (x86_64-pc-windows-gnu) (push) Successful in 1m26s
Build and Release Firmware / cli (x86_64-unknown-linux-musl) (push) Successful in 1m14s
Build and Release Firmware / release (push) Successful in 7s
2026-11-11 18:57:25 -07:00
ktims 27c8fa6a32 fix git version extraction 2026-11-11 18:16:51 -07:00
ktims 44679cda2c config: add persistent flash-backed configuration with a HID command interface and CLI management
Build and Release Firmware / firmware (ak4490) (push) Successful in 50s
Build and Release Firmware / firmware (cs4398) (push) Successful in 44s
Build and Release Firmware / firmware (evk) (push) Successful in 43s
Build and Release Firmware / cli (aarch64-unknown-linux-musl) (push) Successful in 1m8s
Build and Release Firmware / cli (x86_64-pc-windows-gnu) (push) Successful in 1m32s
Build and Release Firmware / cli (x86_64-unknown-linux-musl) (push) Successful in 1m6s
Build and Release Firmware / release (push) Successful in 7s
2026-11-11 18:09:07 -07:00
ktims 7b49f116d4 cli: add more options, refactor, switch to smol runtime 2026-11-05 17:04:37 -07:00
29 changed files with 4410 additions and 487 deletions

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
FROM ghcr.io/rust-cross/cargo-zigbuild:latest
# The base image may resolve its toolchain through $HOME, which the runner does not preserve for
# action containers, so pin it to a fixed path. entrypoint.sh re-exports this because the runner
# injects the workflow environment into action containers as well.
ENV RUSTUP_HOME=/usr/local/rustup
RUN if ! rustup default >/dev/null 2>&1; then \
rustup toolchain install stable --profile minimal --no-self-update; \
rustup default stable; \
fi
# The image ships the toolchain, zig, a macOS SDK and cargo-zigbuild, but not the bits the build and
# packaging scripts need.
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates zip zstd \
&& rm -rf /var/lib/apt/lists/*
# Install every target up front so building needs no network access. `universal2-apple-darwin` is
# not a rustc target: cargo-zigbuild builds both architectures and merges them.
RUN rustup target install \
aarch64-unknown-linux-musl \
x86_64-unknown-linux-musl \
x86_64-pc-windows-gnu \
aarch64-apple-darwin \
x86_64-apple-darwin
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
+13
View File
@@ -0,0 +1,13 @@
name: Build guac CLI
description: Cross-compile the guac CLI with cargo-zigbuild and package the artifact
inputs:
target:
description: Rust target triple, or universal2-apple-darwin
required: true
runs:
using: docker
image: Dockerfile
args:
- ${{ inputs.target }}
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
set -eu
target="$1"
cd "${GITHUB_WORKSPACE:-$(pwd)}"
# The runner overrides env vars from the workflow for action containers, so re-assert the
# toolchain path the image installed to, and keep the registry in the workspace for caching.
export RUSTUP_HOME=/usr/local/rustup
export CARGO_HOME="${PWD}/.cargo-cache"
bin=guac-cli
case "$target" in
*windows*) bin=guac-cli.exe ;;
esac
(cd cli && cargo zigbuild --release --target "$target")
artifact="target/${target}/release/${bin}"
if [ ! -f "$artifact" ]; then
artifact="cli/${artifact}"
fi
mkdir -p dist
zip -j "dist/guac-cli-${target}.zip" "$artifact"
+23 -50
View File
@@ -5,13 +5,6 @@ on:
tags:
- "v*"
env:
TARGET: thumbv8m.main-none-eabihf
# The catthehacker image installs rust here and only symlinks ~/.rustup and ~/.cargo to it.
# actions/cache archives the symlink, not its contents, so point at the real paths.
RUSTUP_HOME: /usr/share/rust/.rustup
CARGO_HOME: /usr/share/rust/.cargo
jobs:
firmware:
runs-on: ubuntu-latest
@@ -21,8 +14,15 @@ jobs:
fail-fast: true
matrix:
variant: [cs4398, ak4490, evk]
# Job-scoped on purpose: the runner also injects workflow env into action containers, where it
# would override the cli image's own toolchain paths.
env:
FEATURES: ${{ matrix.variant }},hid
TARGET: thumbv8m.main-none-eabihf
# The catthehacker image installs rust here and only symlinks ~/.rustup and ~/.cargo to it.
# actions/cache archives the symlink, not its contents, so point at the real paths.
RUSTUP_HOME: /usr/share/rust/.rustup
CARGO_HOME: /usr/share/rust/.cargo
steps:
- name: Checkout repository
uses: actions/checkout@v4
@@ -69,66 +69,39 @@ jobs:
cli:
runs-on: ubuntu-latest
container:
image: catthehacker/ubuntu:rust-latest
strategy:
fail-fast: true
fail-fast: false
matrix:
target:
- aarch64-unknown-linux-musl
- x86_64-pc-windows-gnu
- x86_64-unknown-linux-musl
- universal2-apple-darwin
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Cache rustup
# Building and packaging both happen in .gitea/actions/cli-build, whose image the runner
# builds from its Dockerfile and keeps in the Docker layer cache. That image carries the
# toolchain, zig, the macOS SDK and every target, so none of that is installed per job.
- name: Cache cargo registry
uses: actions/cache@v4
with:
path: ${{ env.RUSTUP_HOME }}
key: rustup-cli-${{ matrix.target }}-${{ runner.os }}
path: .cargo-cache
key: cli-registry-${{ hashFiles('**/Cargo.lock') }}
restore-keys: cli-registry-
- name: Install Rust Toolchain
run: rustup target install ${{ matrix.target }}
- name: Cache cargo
uses: Swatinem/rust-cache@v2
with:
shared-key: cli-${{ matrix.target }}
- name: Cache zigbuild install
- name: Cache build artifacts
uses: actions/cache@v4
with:
path: /opt/zigvenv
key: zigbuild-venv-${{ runner.os }}
# compiled libc/compiler-rt are per target, so these stay keyed on it
- name: Cache zig build artifacts
uses: actions/cache@v4
with:
path: |
~/.cache/zig
~/.cache/cargo-zigbuild
key: zigbuild-cache-${{ matrix.target }}-${{ runner.os }}
- name: Install cargo-zigbuild Toolchain
run: |
# venv keeps cargo-zigbuild and ziglang in one relocatable-by-path directory we can cache
[ -d /opt/zigvenv ] || python3 -m venv /opt/zigvenv
/opt/zigvenv/bin/pip install cargo-zigbuild
echo /opt/zigvenv/bin >> "$GITHUB_PATH"
path: target
key: cli-target-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}
restore-keys: cli-target-${{ matrix.target }}-
- name: Build cli (${{ matrix.target }})
working-directory: cli
run: cargo zigbuild --release --target ${{ matrix.target }}
- name: Package
run: |
bin=cli
[[ "${{ matrix.target }}" == *windows* ]] && bin=cli.exe
mkdir -p dist
zip -j "dist/guac-cli-${{ matrix.target }}.zip" "target/${{ matrix.target }}/release/$bin"
shell: bash
uses: ./.gitea/actions/cli-build
with:
target: ${{ matrix.target }}
- name: Upload artifact
uses: actions/upload-artifact@v3
+1 -1
View File
@@ -3,7 +3,7 @@ repos:
hooks:
- id: cargo-check-host
name: Cargo check (host)
entry: cargo check -p cli -p shared
entry: cargo check -p guac-cli -p shared
pass_filenames: false
types: [file, rust]
language: system
Generated
+639 -285
View File
File diff suppressed because it is too large. Load diff
+7 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "cli"
version = "0.3.0"
name = "guac-cli"
version = "0.3.2"
edition = "2024"
[dependencies]
@@ -8,8 +8,12 @@ async-hid = "0.5.1"
clap = { version = "4.6.1", features = ["derive"] }
colog = "1.4.0"
csv = "1.4.0"
ctrlc = "3.5.2"
deku = "0.20.3"
futures-lite = "2.6.1"
log = { version = "0.4.29", features = ["std"] }
pollster = { version = "0.4.0", features = ["macro"] }
serde_json = "1.0.154"
shared = { path = "../shared", features = ["serde", "std"] }
smol = "2.0.2"
smol-macros = "0.1.1"
smol-timeout = "0.6.1"
+781 -55
View File
@@ -1,53 +1,153 @@
use std::io;
use smol_macros::main;
use std::{
io,
str::FromStr,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::{Duration, Instant},
};
use async_hid::{AsyncHidRead, AsyncHidWrite, Device, HidBackend, HidResult};
use async_hid::{
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;
#[derive(Clone, Copy, Debug, ValueEnum)]
enum Format {
Debug,
Csv,
Json,
}
#[derive(Subcommand, Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug)]
struct UsbVidPid {
vid: u16,
pid: u16,
}
impl FromStr for UsbVidPid {
type Err = clap::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let invalid = || {
clap::Error::raw(
clap::error::ErrorKind::ValueValidation,
"Format of USB device ID is `12ab:cd34` (vendor:product, hex)",
)
};
let (vid, pid) = s.split_once(':').ok_or_else(invalid)?;
Ok(Self {
vid: u16::from_str_radix(vid, 16).map_err(|_| invalid())?,
pid: u16::from_str_radix(pid, 16).map_err(|_| invalid())?,
})
}
}
#[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<u16>,
/// USB product ID, in hex
#[arg(long, value_parser = parse_hex_u16)]
product_id: Option<u16>,
/// USB manufacturer string
#[arg(long)]
manufacturer: Option<String>,
/// USB product string
#[arg(long)]
product: Option<String>,
/// USB serial string
#[arg(long)]
serial: Option<String>,
}
fn parse_hex_u16(value: &str) -> Result<u16, String> {
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 {
Monitor,
/// Continuously print statistics from the connected device
Monitor {
#[arg(short, long, default_value = "debug")]
format: Format,
#[arg(short, long, default_value = None)]
count: Option<usize>,
},
/// Print the current state of the connected device
Status {
#[arg(short, long, default_value = "debug")]
format: Format,
},
/// Reset the connected device or boot to bootloader for firmware upgrade
Reset {
#[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)]
#[command(version, about)]
#[command(
version,
about = "Interact with GUAC UAC2 devices",
arg_required_else_help = true
)]
struct Args {
#[arg(short, long, default_value = "debug")]
format: Format,
#[arg(short, long, default_value = "1209:cc1d")]
/// USB device ID to operate on, format `1209:cc1d` (vendor:product, hex)
device: UsbVidPid,
#[command(subcommand)]
command: Option<Command>,
}
trait StateEmitter<W: io::Write> {
fn from_writer(writer: W) -> Self
where
Self: Sized;
trait StateEmitter {
fn emit(&mut self, r: &AudioTelemetrySnapshot);
fn close(&mut self) {}
}
struct DebugEmitter<T: io::Write> {
writer: T,
}
impl<W: io::Write> StateEmitter<W> for DebugEmitter<W> {
fn from_writer(writer: W) -> Self {
impl<W: io::Write> DebugEmitter<W> {
fn new(writer: W) -> Self {
Self { writer }
}
}
impl<W: io::Write> StateEmitter for DebugEmitter<W> {
fn emit(&mut self, r: &AudioTelemetrySnapshot) {
writeln!(self.writer, "{r:?}").ok();
}
@@ -57,12 +157,15 @@ struct CsvEmitter<W: io::Write> {
csv: csv::Writer<W>,
}
impl<W: io::Write> StateEmitter<W> for CsvEmitter<W> {
fn from_writer(writer: W) -> Self {
impl<W: io::Write> CsvEmitter<W> {
fn new(writer: W) -> Self {
Self {
csv: csv::Writer::from_writer(writer),
}
}
}
impl<W: io::Write> StateEmitter for CsvEmitter<W> {
fn emit(&mut self, r: &AudioTelemetrySnapshot) {
if let Err(e) = self.csv.serialize(r) {
eprintln!("Serialization error: {e:?}");
@@ -72,63 +175,686 @@ impl<W: io::Write> StateEmitter<W> for CsvEmitter<W> {
}
}
/// The device exposes one vendor HID interface per usage; pick the one we need.
async fn find_device(usage_id: u16) -> HidResult<Device> {
Ok(HidBackend::default()
.enumerate()
.await?
.find(|d| d.product_id == 0xcc1d && d.vendor_id == 0x1209 && d.usage_id == usage_id)
.await
.expect("GUAC device not found or not accessible (try as root?)"))
struct JsonEmitter<W: io::Write> {
writer: W,
first: bool,
}
impl<W: io::Write> JsonEmitter<W> {
fn new(mut writer: W) -> Self {
if let Err(e) = write!(writer, "[") {
eprintln!("Write error: {e:?}")
}
Self {
writer,
first: true,
}
}
}
#[pollster::main]
impl<W: io::Write> StateEmitter for JsonEmitter<W> {
fn emit(&mut self, r: &AudioTelemetrySnapshot) {
if !self.first
&& let Err(e) = write!(&mut self.writer, ",")
{
eprintln!("Write error: {e:?}")
} else {
self.first = false
}
if let Err(e) = serde_json::to_writer(&mut self.writer, r) {
eprintln!("Serialization error: {e:?}")
}
self.writer.flush().ok();
}
fn close(&mut self) {
if let Err(e) = write!(&mut self.writer, "]") {
eprintln!("Write error: {e:?}")
}
}
}
impl<W: io::Write> Drop for JsonEmitter<W> {
fn drop(&mut self) {
self.close()
}
}
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 try_find_device(vidpid: &UsbVidPid, usage_id: u16) -> HidResult<Option<Device>> {
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;
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<Device> {
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(
reader: &mut DeviceReader,
) -> Result<AudioTelemetryReport, HidError> {
let mut buf = [0u8; core::mem::size_of::<AudioTelemetryReport>()];
let r = reader
.read_input_report(&mut buf)
.timeout(Duration::from_secs(1))
.await
.ok_or(HidError::Other("Timeout".into()))??;
log::debug!("read {}: {:?}", r, &buf[..r]);
let buf = &buf[..r];
match AudioTelemetryReport::from_bytes((buf, 0)) {
Ok((_, r)) => Ok(r),
Err(e) => {
log::error!("unable to parse telemetry report: {:?}", e);
Err(HidError::Message("Unable to parse report".into()))
}
}
}
async fn emit_telemetry_reports(
mut reader: DeviceReader,
mut writer: Box<dyn StateEmitter>,
count: &Option<usize>,
stop: &AtomicBool,
) {
let c = count.unwrap_or(1);
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<NackCode>) -> 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<Vec<u8>> {
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<ConfigSnapshot> {
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<HardwareInfo> {
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<u16> {
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<u8>)> = 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<UsbVidPid> {
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<u8> {
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! {
async fn main() -> HidResult<()> {
colog::init();
let args = Args::parse();
match &args.command {
Some(Command::Monitor) => {
let dev = find_device(USAGE_TELEMETRY).await?;
let mut reader = dev.open_readable().await?;
let mut writer: Box<dyn StateEmitter<_>> = match args.format {
Format::Debug => Box::new(DebugEmitter::from_writer(io::stdout())),
Format::Csv => Box::new(CsvEmitter::from_writer(io::stdout())),
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<dyn StateEmitter> = match format {
Format::Debug => Box::new(DebugEmitter::new(io::stdout())),
Format::Csv => Box::new(CsvEmitter::new(io::stdout())),
Format::Json => Box::new(JsonEmitter::new(io::stdout())),
};
let mut buf = [0u8; core::mem::size_of::<AudioTelemetryReport>()];
while let Ok(r) = reader.read_input_report(&mut buf).await {
log::debug!("read {}: {:?}", r, &buf[..r]);
let buf = &buf[..r];
match AudioTelemetryReport::from_bytes((buf, 0)) {
Ok((_, r)) => writer.emit(&r.into()),
Err(e) => eprintln!("Unable to parse report: {:?}", e),
let stop = Arc::new(AtomicBool::new(false));
let handler_stop = Arc::clone(&stop);
if let Err(e) = ctrlc::set_handler(move || handler_stop.store(true, Ordering::Relaxed))
{
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<dyn StateEmitter> = match format {
Format::Debug => Box::new(DebugEmitter::new(io::stdout())),
Format::Csv => Box::new(CsvEmitter::new(io::stdout())),
Format::Json => Box::new(JsonEmitter::new(io::stdout())),
};
emit_telemetry_reports(reader, writer, &Some(1), &AtomicBool::new(false)).await
}
Some(Command::Reset { bootloader }) => {
let dev = find_device(USAGE_COMMAND).await?;
let mut dev_writer = dev.open_writeable().await?;
let cmd = if *bootloader {
print!("Rebooting into bootloader...");
AudioDeviceCommand::Bootloader
let dev = find_device(&args.device, USAGE_COMMAND).await?;
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::<AudioDeviceCommandReport>()];
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 => {}
}
Ok(())
}
}
+2 -2
View File
@@ -1,10 +1,10 @@
[package]
name = "guac"
version = "0.3.0"
version = "0.3.2"
edition = "2024"
[features]
default = ["nodac", "hid"]
default = ["evk", "hid"]
ak4490 = []
cs4398 = []
nodac = []
+48 -3
View File
@@ -1,5 +1,50 @@
// Find the actual path of memory.x and add it to link search, required for building in workspace
use std::{env, path::Path, process::Command};
/// Paths that change when `HEAD`, a branch, or a tag moves. `HEAD` itself is only rewritten on
/// checkout, so commits are tracked through the reflog and the ref directories.
const GIT_WATCH: [&str; 5] = [
"../.git/HEAD",
"../.git/logs/HEAD",
"../.git/refs/heads",
"../.git/refs/tags",
"../.git/packed-refs",
];
fn git_output(args: &[&str], dir: &str) -> Option<String> {
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)
);
for path in GIT_WATCH {
let path = Path::new(&manifest_dir).join(path);
if path.exists() {
println!("cargo:rerun-if-changed={}", path.display());
}
}
}
}
+6 -1
View File
@@ -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);
}
+373
View File
@@ -0,0 +1,373 @@
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
}
// The spare page in the reserved area, used to carry a boot request across a reset.
const BOOT_REQUEST_MAGIC: u32 = u32::from_le_bytes(*b"BOOT");
fn boot_request_address() -> usize {
config_base() + FLASH_PAGE_SIZE
}
/// Writes a boot request and resets. The next boot hands over to the ROM before configuring
/// anything, which is the only way it gets a chip that is still in its reset state.
#[cfg(feature = "hid")]
pub fn request_bootloader(state: &mut FlashState) -> Result<(), ()> {
defmt::info!("config: requesting bootloader");
cortex_m::interrupt::free(|_| {
slow_clock_for_flash();
let address = boot_request_address();
let mut page = [0xffu8; FLASH_PAGE_SIZE];
page[..4].copy_from_slice(&BOOT_REQUEST_MAGIC.to_le_bytes());
if state.flash.erase_page(address / FLASH_PAGE_SIZE).is_err() {
defmt::error!("config: boot request erase failed");
return Err(());
}
if state
.flash
.write_native(address, GenericArray::from_slice(&page))
.is_err()
{
defmt::error!("config: boot request write failed");
return Err(());
}
Ok(())
})?;
// Let the probe client drain RTT before the reset tears it down.
cortex_m::asm::delay(15_000_000);
cortex_m::peripheral::SCB::sys_reset()
}
/// Consumes a pending boot request, clearing it first so a hand-off that fails to enter ISP cannot
/// cause a boot loop.
pub fn take_bootloader_request(flash: &mut FlashGordon) -> bool {
slow_clock_for_flash();
let address = boot_request_address();
let mut word = [0u8; FLASH_WORD_SIZE];
if read_flash(address, &mut word).is_err() {
return false;
}
if u32::from_le_bytes([word[0], word[1], word[2], word[3]]) != BOOT_REQUEST_MAGIC {
return false;
}
if flash.erase_page(address / FLASH_PAGE_SIZE).is_err() {
defmt::error!("config: boot request clear failed");
}
defmt::info!("config: boot request found");
true
}
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(&register.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<usize> {
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<DeviceConfig> {
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<ConfigString<32>> {
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)
}
+9
View File
@@ -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);
}
+5
View File
@@ -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();
+4
View File
@@ -7,6 +7,10 @@ pub struct NoopDac<T> {
__: PhantomData<T>,
}
impl<T> Dac<T> for NoopDac<T> {
fn name(&self) -> &'static str {
"None"
}
fn init(&mut self) {}
fn change_rate(&mut self, _new_rate: u32) {}
fn mute(&mut self) {}
+5
View File
@@ -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) {
+458
View File
@@ -0,0 +1,458 @@
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<CommandKind>,
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<Pending>,
reply: Option<Reply>,
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::<MAX_VALUE_LEN>::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<B: UsbBus>(
&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();
if config::request_bootloader(flash).is_err() {
defmt::error!("boot request failed, staying in the application");
}
}
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<B: UsbBus>(
&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<B: UsbBus>(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<B: UsbBus>(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<B: UsbBus>(
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);
}
+143 -49
View File
@@ -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)]
@@ -175,17 +218,32 @@ static PERF: PerfCounters = PerfCounters {
// fb: AtomicI32::new(0),
};
fn boot_to_bootloader() -> ! {
cortex_m::interrupt::disable();
fn boot_to_isp() -> ! {
// Hand the ROM a chip that is still in its reset state, with the ISP pin held low. Peripheral
// resets are left alone: holding them asserted stops the ROM's own USB from coming up.
let mut syscon = unsafe { hal::Syscon::steal() };
let mut iocon = unsafe { hal::Iocon::steal() }.enabled(&mut syscon);
let mut gpio = unsafe { hal::Gpio::steal() }.enabled(&mut syscon);
let _isp = unsafe { pins::Pio0_5::steal() }
.into_gpio_pin(&mut iocon, &mut gpio)
.into_output_low();
unsafe {
(*pac::IOCON::ptr())
.pio0_5
.modify(|_, w| w.mode().pull_down())
};
// And the boot error counter, in case the pin is not the input the ROM acts on.
unsafe {
let pmc = &*pac::PMC::ptr();
// https://community.nxp.com/t5/LPC-Microcontrollers/Configure-LPC55-to-enter-re-invoke-ROM-Bootloader-from/m-p/966990?profile.language=en
// If you write the following register, it will be set to boot from the ROM:
// PMC->AOREG1 |= (0x0A << 16); //Set to boot from ROM
// NVIC_SystemReset(); //Reset‍‍
pmc.aoreg1.modify(|r, w| w.bits(r.bits() | (0x0a << 16)));
pmc.aoreg1.modify(|r, w| w.bits(r.bits() | (0xa << 16)));
}
cortex_m::peripheral::SCB::sys_reset()
cortex_m::interrupt::disable();
defmt::info!("bootloader: entering ROM from the reset state");
cortex_m::asm::delay(15_000_000);
unsafe { cortex_m::asm::bootload(0x0300_0000 as *const u32) }
}
fn build_telemetry_report<D: Dac<I>, I>(
@@ -795,6 +853,14 @@ fn main() -> ! {
debug!("start");
// A boot request is honoured before any peripheral or clock is configured beyond what reading
// flash requires, so the ROM is entered with the chip still in its reset state.
let mut flash = hal::FlashGordon::new(hal.flash.enabled(&mut syscon));
if config::take_bootloader_request(&mut flash) {
boot_to_isp();
}
debug!("iocon");
let usb0_vbus_pin = pins::Pio0_22::take()
.unwrap()
@@ -842,6 +908,20 @@ 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.
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,20 +1001,42 @@ 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")])
#[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()
@@ -952,6 +1054,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 +1087,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 +1097,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::<AudioDeviceCommandReport>()];
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,
);
}
};
+1
View File
@@ -1,6 +1,7 @@
use crate::CodecPins;
pub trait Dac<T> {
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);
+4 -2
View File
@@ -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"] }
+268
View File
@@ -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<Self, ConfigError> {
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<usize, ConfigError> {
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<Self, ConfigError> {
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<usize, ConfigError> {
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<Self, ConfigError> {
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<usize, ConfigError> {
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<usize, ConfigError> {
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<ConfigVersion> for ConfigContainer {
fn from(config: ConfigVersion) -> Self {
Self::new(config)
}
}
+89
View File
@@ -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 {}
+607
View File
@@ -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<MAX_VALUE_LEN> {
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::<VendorId>(0x1209).unwrap();
tlvs.set::<ManufString>(ConfigString::<32>::try_from("VE7XEN").unwrap())
.unwrap();
assert_eq!(tlvs.get::<VendorId>().unwrap(), Some(0x1209));
assert_eq!(
tlvs.get::<ManufString>().unwrap(),
Some(ConfigString::<32>::try_from("VE7XEN").unwrap())
);
}
#[test]
fn typed_value_uses_little_endian() {
let mut tlvs = TlvList::new();
tlvs.set::<VendorId>(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::<VendorId>().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::<ManufString>().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::<VendorId>().unwrap(), Some(0x1111));
}
#[test]
fn set_replaces_existing_tag() {
let mut tlvs = TlvList::new();
tlvs.set::<VendorId>(0x1111).unwrap();
tlvs.set::<VendorId>(0x2222).unwrap();
assert_eq!(tlvs.len(), 1);
assert_eq!(tlvs.get::<VendorId>().unwrap(), Some(0x2222));
}
#[test]
fn missing_key_returns_none() {
assert_eq!(TlvList::new().get::<VendorId>().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::<VendorId>(0x1234).unwrap();
tlvs.set::<ProductId>(0x5678).unwrap();
tlvs.set::<ManufString>(ConfigString::try_from("Maker").unwrap())
.unwrap();
tlvs.set::<ProductString>(ConfigString::try_from("Widget").unwrap())
.unwrap();
tlvs.set::<SerialString>(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);
}
}
+198
View File
@@ -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<ConfigString<32>>,
}
impl DeviceConfig {
pub fn from_tlvs(tlvs: &TlvList) -> Result<Self, ConfigError> {
let config = Self {
usb_vendor_id: resolve::<VendorId>(tlvs)?,
usb_product_id: resolve::<ProductId>(tlvs)?,
usb_manufacturer: resolve::<ManufString>(tlvs)?,
usb_product: resolve::<ProductString>(tlvs)?,
usb_serial: tlvs.get::<SerialString>()?,
};
config
.validate(&())
.map_err(|report| ConfigError::Invalid {
errors: report.len(),
})?;
Ok(config)
}
pub fn with_defaults(usb_serial: Option<ConfigString<32>>) -> Result<Self, ConfigError> {
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<ConfigString<32>> {
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<TlvList, ConfigError> {
let mut tlvs = TlvList::new();
tlvs.set::<VendorId>(self.usb_vendor_id)?;
tlvs.set::<ProductId>(self.usb_product_id)?;
tlvs.set::<ManufString>(self.usb_manufacturer.clone())?;
tlvs.set::<ProductString>(self.usb_product.clone())?;
if let Some(serial) = &self.usb_serial {
tlvs.set::<SerialString>(serial.clone())?;
}
Ok(tlvs)
}
}
impl TryFrom<&ConfigVersion> for DeviceConfig {
type Error = ConfigError;
fn try_from(value: &ConfigVersion) -> Result<Self, Self::Error> {
match value {
ConfigVersion::V1(config) => Self::try_from(config),
}
}
}
impl TryFrom<&ConfigV1> for DeviceConfig {
type Error = ConfigError;
fn try_from(value: &ConfigV1) -> Result<Self, Self::Error> {
Self::from_tlvs(&value.tlvs)
}
}
fn resolve<K: ConfigKey>(tlvs: &TlvList) -> Result<K::Value, ConfigError> {
tlvs.get::<K>()?
.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<Self::Value> {
Some(0x1209)
}
}
pub(crate) struct ProductId;
impl ConfigKey for ProductId {
const TAG: ConfigTag = tags::PRODUCT_ID;
type Value = u16;
fn default_value() -> Option<Self::Value> {
Some(0xcc1d)
}
}
pub(crate) struct ManufString;
impl ConfigKey for ManufString {
const TAG: ConfigTag = tags::MANUF_STRING;
type Value = ConfigString<32>;
fn default_value() -> Option<Self::Value> {
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<Self::Value> {
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<Self::Value> {
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);
}
}
+26
View File
@@ -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,
}
}
}
+179
View File
@@ -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<MAX_VALUE_LEN>,
}
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<usize, ConfigError> {
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<Self::Value>;
}
#[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<Tlv, MAX_TLVS>,
}
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<K: ConfigKey>(&self) -> Result<Option<K::Value>, ConfigError> {
self.find(K::TAG)
.map(|tlv| K::Value::decode(K::TAG, tlv.value.as_slice()))
.transpose()
}
pub fn set<K: ConfigKey>(&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()
}
}
+182
View File
@@ -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<const N: usize = MAX_VALUE_LEN>(heapless::Vec<u8, N>);
impl<const N: usize> ConfigBytes<N> {
pub const fn new() -> Self {
Self(heapless::Vec::new())
}
pub fn from_slice(bytes: &[u8]) -> Result<Self, ConfigError> {
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<const N: usize> Default for ConfigBytes<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> AsRef<[u8]> for ConfigBytes<N> {
fn as_ref(&self) -> &[u8] {
self.as_slice()
}
}
impl<const N: usize> core::ops::Deref for ConfigBytes<N> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl<const N: usize> TryFrom<&[u8]> for ConfigBytes<N> {
type Error = ConfigError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
Self::from_slice(value)
}
}
pub trait ConfigValue: Sized {
fn decode(tag: ConfigTag, bytes: &[u8]) -> Result<Self, ConfigError>;
fn encode(&self, out: &mut ConfigBytes<MAX_VALUE_LEN>) -> Result<(), ConfigError>;
}
impl<const N: usize> ConfigValue for ConfigBytes<N> {
fn decode(_tag: ConfigTag, bytes: &[u8]) -> Result<Self, ConfigError> {
Self::from_slice(bytes)
}
fn encode(&self, out: &mut ConfigBytes<MAX_VALUE_LEN>) -> 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<const N: usize>(
#[validate(length(code_units, 1..=126))] heapless::String<N>,
);
impl<const N: usize> ConfigString<N> {
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<const N: usize> Default for ConfigString<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> AsRef<str> for ConfigString<N> {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl<const N: usize> core::ops::Deref for ConfigString<N> {
type Target = str;
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl<const N: usize> core::fmt::Display for ConfigString<N> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
impl<const N: usize> TryFrom<&str> for ConfigString<N> {
type Error = ConfigError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
heapless::String::try_from(value)
.map(Self)
.map_err(|_| ConfigError::ValueTooLong {
len: value.len(),
max: N,
})
}
}
impl<const N: usize> ConfigValue for ConfigString<N> {
fn decode(tag: ConfigTag, bytes: &[u8]) -> Result<Self, ConfigError> {
let value = core::str::from_utf8(bytes).map_err(|_| ConfigError::InvalidUtf8 { tag })?;
Self::try_from(value)
}
fn encode(&self, out: &mut ConfigBytes<MAX_VALUE_LEN>) -> Result<(), ConfigError> {
out.extend_from_slice(self.as_bytes())
}
}
impl ConfigValue for u16 {
fn decode(tag: ConfigTag, bytes: &[u8]) -> Result<Self, ConfigError> {
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<MAX_VALUE_LEN>) -> Result<(), ConfigError> {
out.extend_from_slice(&self.to_le_bytes())
}
}
+136
View File
@@ -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<MAX_DAC_NAME_LEN>,
pub version: ConfigString<MAX_VERSION_LEN>,
}
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<usize, ConfigError> {
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<Self, ConfigError> {
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)
);
}
}
+146 -36
View File
@@ -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<AudioDeviceCommandReport> for AudioDeviceCommand {
type Error = DekuError;
fn try_from(value: AudioDeviceCommandReport) -> Result<Self, Self::Error> {
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<AudioDeviceCommand> for AudioDeviceCommandReport {
fn from(value: AudioDeviceCommand) -> Self {
let mut buf = [0u8; core::mem::size_of::<Self>()];
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<Self> {
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());
}
}
}
}