Compare commits

1 Commits
Author SHA1 Message Date
ktims 1e87561b37 add gitea workflow
Build and Release Firmware / build-and-release (push) Successful in 1m35s
2026-08-26 15:20:09 -07:00
29 changed files with 657 additions and 4755 deletions

No files matched your search

+45 -144
View File
@@ -7,159 +7,60 @@ on:
env: env:
TARGET: thumbv8m.main-none-eabihf 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: jobs:
firmware: build-and-release:
runs-on: ubuntu-latest
container:
image: catthehacker/ubuntu:rust-latest
strategy:
fail-fast: true
matrix:
variant: [cs4398, ak4490, evk]
env:
FEATURES: ${{ matrix.variant }},hid
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Cache rustup
uses: actions/cache@v4
with:
path: ${{ env.RUSTUP_HOME }}
key: rustup-firmware-${{ env.TARGET }}-${{ runner.os }}
- name: Install Rust Toolchain
run: |
rustup target install ${{ env.TARGET }}
rustup component add llvm-tools
- name: Cache cargo
uses: Swatinem/rust-cache@v2
with:
shared-key: firmware-${{ matrix.variant }}
- name: Install cargo-binutils
run: cargo binstall -y --locked cargo-binutils
- name: Build firmware (${{ matrix.variant }})
working-directory: firmware
run: cargo build --release --target ${{ env.TARGET }} --no-default-features --features "${{ env.FEATURES }}"
- name: Create hex file
working-directory: firmware
run: cargo objcopy --release --target ${{ env.TARGET }} --no-default-features --features "${{ env.FEATURES }}" -- -O ihex ../target/${{ env.TARGET }}/release/guac-${{ matrix.variant }}.hex
- name: Package
run: |
out=target/${{ env.TARGET }}/release
cp "$out/guac" "$out/guac-${{ matrix.variant }}.elf"
mkdir -p dist
zip -j "dist/guac-firmware-${{ matrix.variant }}.zip" "$out/guac-${{ matrix.variant }}.elf" "$out/guac-${{ matrix.variant }}.hex"
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
name: firmware-${{ matrix.variant }}
path: dist/*.zip
cli:
runs-on: ubuntu-latest
container:
# Bundles the Rust toolchain, zig and a macOS SDK, which the generic builder images lack;
# we cross-compile every target from here with cargo-zigbuild.
image: ghcr.io/rust-cross/cargo-zigbuild:latest
strategy:
fail-fast: false
matrix:
target:
- aarch64-unknown-linux-musl
- x86_64-pc-windows-gnu
- x86_64-unknown-linux-musl
- universal2-apple-darwin
env:
RUSTUP_HOME: /usr/local/rustup
CARGO_HOME: /usr/local/cargo
steps:
# JavaScript actions need node, which the rust-cross image does not ship. Install it (and the
# rest of the tooling the actions rely on) before anything else, as a shell step.
- name: Install Actions tooling
run: |
apt-get update
apt-get install -y --no-install-recommends ca-certificates curl git zip zstd
if ! command -v node > /dev/null; then
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y --no-install-recommends nodejs
fi
- name: Checkout repository
uses: actions/checkout@v4
- name: Cache rustup
uses: actions/cache@v4
with:
path: ${{ env.RUSTUP_HOME }}
key: rustup-cli-${{ matrix.target }}-${{ runner.os }}
- name: Install Rust Toolchain
run: |
rustup target install ${{ matrix.target }}
# cargo-zigbuild builds both architectures and merges them for the universal binary.
if [[ "${{ matrix.target }}" == universal2-apple-darwin ]]; then
rustup target install aarch64-apple-darwin x86_64-apple-darwin
fi
shell: bash
- name: Cache cargo
uses: Swatinem/rust-cache@v2
with:
shared-key: cli-${{ matrix.target }}
# 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: Build cli (${{ matrix.target }})
working-directory: cli
run: cargo zigbuild --release --target ${{ matrix.target }}
- name: Package
run: |
bin=guac-cli
[[ "${{ matrix.target }}" == *windows* ]] && bin=guac-cli.exe
mkdir -p dist
zip -j "dist/guac-cli-${{ matrix.target }}.zip" "target/${{ matrix.target }}/release/$bin"
shell: bash
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
name: cli-${{ matrix.target }}
path: dist/*.zip
release:
needs: [firmware, cli]
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: catthehacker/ubuntu:act-latest image: catthehacker/ubuntu:act-latest
defaults:
run:
shell: bash
steps: steps:
- name: Download artifacts - name: Checkout repository
uses: actions/download-artifact@v3 uses: actions/checkout@v4
with:
path: dist - name: Install Rust Toolchain
uses: dtolnay/rust-toolchain@stable
- name: Install cargo-binutils
run: cargo install cargo-binutils
- name: Build Firmware Binaries
run: |
cd firmware
# Array of "variant_name:features"
VARIANTS=(
"cs4398:cs4398,hid"
"ak4490:ak4490,hid"
"evk:evk,hid"
)
mkdir -p ../dist
for entry in "${VARIANTS[@]}"; do
IFS=":" read -r name features <<< "$entry"
echo "Building variant: $name with features: $features"
# 1. Compile release binary
cargo build --release --target ${{ env.TARGET }} --no-default-features --features "$features"
# 2. Paths setup
ELF_PATH="../target/${{ env.TARGET }}/release/guac"
HEX_PATH="../target/${{ env.TARGET }}/release/guac-${name}.hex"
RENAMED_ELF="../target/${{ env.TARGET }}/release/guac-${name}.elf"
# 3. Create .hex file via rust-objcopy
cargo objcopy --release --target ${{ env.TARGET }} --no-default-features --features "$features" -- -O ihex "$HEX_PATH"
cp "$ELF_PATH" "$RENAMED_ELF"
# 4. Package ELF and HEX into target-specific ZIP
ZIP_NAME="guac-firmware-${name}.zip"
zip -j "../dist/${ZIP_NAME}" "$RENAMED_ELF" "$HEX_PATH"
done
- name: Create Gitea Release - name: Create Gitea Release
uses: akkuman/gitea-release-action@v1 uses: akkuman/gitea-release-action@v1
with: with:
files: dist/**/*.zip files: dist/*.zip
draft: false draft: false
prerelease: false prerelease: false
+1 -1
View File
@@ -3,7 +3,7 @@ repos:
hooks: hooks:
- id: cargo-check-host - id: cargo-check-host
name: Cargo check (host) name: Cargo check (host)
entry: cargo check -p guac-cli -p shared entry: cargo check -p cli -p shared
pass_filenames: false pass_filenames: false
types: [file, rust] types: [file, rust]
language: system language: system
Generated
+283 -649
View File
File diff suppressed because it is too large. Load diff
+4 -8
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "guac-cli" name = "cli"
version = "0.3.1" version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
@@ -8,12 +8,8 @@ async-hid = "0.5.1"
clap = { version = "4.6.1", features = ["derive"] } clap = { version = "4.6.1", features = ["derive"] }
colog = "1.4.0" colog = "1.4.0"
csv = "1.4.0" csv = "1.4.0"
ctrlc = "3.5.2"
deku = "0.20.3" deku = "0.20.3"
futures-lite = "2.6.1" futures-lite = "2.6.1"
log = { version = "0.4.29", features = ["std"] } log = { version = "0.4.29", features = ["std"] }
serde_json = "1.0.154" pollster = { version = "0.4.0", features = ["macro"] }
shared = { path = "../shared", features = ["serde", "std"] } shared = { path = "../shared", features = ["serde"] }
smol = "2.0.2"
smol-macros = "0.1.1"
smol-timeout = "0.6.1"
+36 -807
View File
@@ -1,155 +1,41 @@
use smol_macros::main; use std::io;
use std::{
io,
str::FromStr,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::{Duration, Instant},
};
use async_hid::{ use async_hid::{AsyncHidRead, HidBackend, HidResult};
AsyncHidFeatureHandle, AsyncHidRead, Device, DeviceFeatureHandle, DeviceReader, HidBackend, use clap::{Parser, ValueEnum};
HidError, HidResult,
};
use clap::{Parser, Subcommand, ValueEnum};
use deku::DekuContainerRead; use deku::DekuContainerRead;
use futures_lite::StreamExt; use futures_lite::StreamExt;
use shared::{ use shared::{AudioTelemetrySnapshot, hid::AudioTelemetryReport};
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)] #[derive(Clone, Copy, Debug, ValueEnum)]
enum Format { enum Format {
Debug, Debug,
Csv, Csv,
Json,
}
#[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 {
/// 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)] #[derive(Parser, Debug)]
#[command( #[command(version, about)]
version,
about = "Interact with GUAC UAC2 devices",
arg_required_else_help = true
)]
struct Args { struct Args {
#[arg(short, long, default_value = "1209:cc1d")] #[arg(short, long, default_value = "debug")]
/// USB device ID to operate on, format `1209:cc1d` (vendor:product, hex) format: Format,
device: UsbVidPid,
#[command(subcommand)]
command: Option<Command>,
} }
trait StateEmitter { trait StateEmitter<W: io::Write> {
fn from_writer(writer: W) -> Self
where
Self: Sized;
fn emit(&mut self, r: &AudioTelemetrySnapshot); fn emit(&mut self, r: &AudioTelemetrySnapshot);
fn close(&mut self) {}
} }
struct DebugEmitter<T: io::Write> { struct DebugEmitter<T: io::Write> {
writer: T, writer: T,
} }
impl<W: io::Write> DebugEmitter<W> { impl<W: io::Write> StateEmitter<W> for DebugEmitter<W> {
fn new(writer: W) -> Self { fn from_writer(writer: W) -> Self {
Self { writer } Self { writer }
} }
}
impl<W: io::Write> StateEmitter for DebugEmitter<W> {
fn emit(&mut self, r: &AudioTelemetrySnapshot) { fn emit(&mut self, r: &AudioTelemetrySnapshot) {
writeln!(self.writer, "{r:?}").ok(); writeln!(self.writer, "{r:?}");
} }
} }
@@ -157,15 +43,12 @@ struct CsvEmitter<W: io::Write> {
csv: csv::Writer<W>, csv: csv::Writer<W>,
} }
impl<W: io::Write> CsvEmitter<W> { impl<W: io::Write> StateEmitter<W> for CsvEmitter<W> {
fn new(writer: W) -> Self { fn from_writer(writer: W) -> Self {
Self { Self {
csv: csv::Writer::from_writer(writer), csv: csv::Writer::from_writer(writer),
} }
} }
}
impl<W: io::Write> StateEmitter for CsvEmitter<W> {
fn emit(&mut self, r: &AudioTelemetrySnapshot) { fn emit(&mut self, r: &AudioTelemetrySnapshot) {
if let Err(e) = self.csv.serialize(r) { if let Err(e) = self.csv.serialize(r) {
eprintln!("Serialization error: {e:?}"); eprintln!("Serialization error: {e:?}");
@@ -175,686 +58,32 @@ impl<W: io::Write> StateEmitter for CsvEmitter<W> {
} }
} }
struct JsonEmitter<W: io::Write> { #[pollster::main]
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,
}
}
}
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<()> { async fn main() -> HidResult<()> {
colog::init(); colog::init();
let args = Args::parse(); let args = Args::parse();
let usbhid = HidBackend::default();
let dev = usbhid
.enumerate()
.await?
.find(|d| d.product_id == 0xcc1d && d.vendor_id == 0x1209)
.await
.expect("GUAC device not found or not accessible (try as root?)");
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())),
};
match &args.command { let mut buf = [0u8; core::mem::size_of::<AudioTelemetryReport>()];
Some(Command::Monitor { format, count }) => { while let Ok(r) = reader.read_input_report(&mut buf).await {
log::info!("monitoring telemetry"); log::debug!("read {}: {:?}", r, &buf[..r]);
let dev = find_device(&args.device, USAGE_TELEMETRY).await?; let buf = &buf[..r];
let reader = dev.open_readable().await?; match AudioTelemetryReport::from_bytes((buf, 0)) {
let writer: Box<dyn StateEmitter> = match format { Ok((_, r)) => writer.emit(&r.into()),
Format::Debug => Box::new(DebugEmitter::new(io::stdout())), Err(e) => eprintln!("Unable to parse report: {:?}", e),
Format::Csv => Box::new(CsvEmitter::new(io::stdout())),
Format::Json => Box::new(JsonEmitter::new(io::stdout())),
};
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(&args.device, USAGE_COMMAND).await?;
let mut handle = dev.open_feature_handle().await?;
let kind = if *bootloader {
CommandKind::Bootloader
} else {
CommandKind::Reset
};
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(()) Ok(())
} }
}
+7 -8
View File
@@ -1,26 +1,26 @@
[package] [package]
name = "guac" name = "guac"
version = "0.3.1" version = "0.2.0"
edition = "2024" edition = "2024"
[features] [features]
default = ["evk", "hid"] default = ["nodac", "hid"]
ak4490 = [] ak4490 = []
cs4398 = [] cs4398 = []
nodac = [] nodac = []
wm8904 = [] wm8904 = []
hid = ["dep:usbd-hid", "dep:deku"] hid = [ "dep:usbd-hid" ]
evk = ["wm8904"] evk = [ "wm8904" ]
[dependencies] [dependencies]
shared = { path = "../shared" } shared = { path="../shared" }
atomic = "0.6.1" atomic = "0.6.1"
bbqueue = "0.7.0" bbqueue = "0.7.0"
bytemuck = { version = "1.25.0", features = ["derive"] }
cortex-m = { version = "0.7.7", features = ["critical-section-single-core"] } cortex-m = { version = "0.7.7", features = ["critical-section-single-core"] }
cortex-m-rt = "0.7.5" cortex-m-rt = "0.7.5"
defmt = "1.0.1" defmt = "1.0.1"
defmt-rtt = "1.1.0" defmt-rtt = "1.1.0"
deku = { version = "0.20.3", optional = true, default-features = false }
embedded-hal = "0.2.7" embedded-hal = "0.2.7"
embedded-io = "0.7.1" embedded-io = "0.7.1"
log-to-defmt = "0.1.0" log-to-defmt = "0.1.0"
@@ -32,8 +32,7 @@ panic-probe = { version = "1.0.0", features = ["print-defmt"] }
static_cell = "2.1.1" static_cell = "2.1.1"
usb-device = { version = "0.3", features = ["control-buffer-256"] } usb-device = { version = "0.3", features = ["control-buffer-256"] }
usbd-hid = { version = "0.10.0", optional = true } usbd-hid = { version = "0.10.0", optional = true }
usbd-uac2 = { version = "0.1.2", features = ["defmt"] } usbd-uac2 = { version = "0.1.2", features = ["defmt"]}
bitfield-struct = "0.13.0"
[profile.release] [profile.release]
opt-level = "z" opt-level = "z"
+3 -48
View File
@@ -1,50 +1,5 @@
use std::{env, path::Path, process::Command}; // Find the actual path of memory.x and add it to link search, required for building in workspace
/// 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() { fn main() {
if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") { let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
println!("cargo:rustc-link-search={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());
}
}
}
} }
+1 -6
View File
@@ -1,7 +1,6 @@
MEMORY MEMORY
{ {
FLASH : ORIGIN = 0x00000000 , LENGTH = 512K - 32K FLASH : ORIGIN = 0x00000000, LENGTH = 512K
CONFIG : ORIGIN = 0x00000000 + 512K - 32K, LENGTH = 32K
/* for use with standard link.x */ /* for use with standard link.x */
RAM : ORIGIN = 0x20000000, LENGTH = 192K RAM : ORIGIN = 0x20000000, LENGTH = 192K
@@ -20,7 +19,3 @@ MEMORY
/* USB1 SRAM regin */ /* USB1 SRAM regin */
/* USB1_SRAM : ORIGIN = 0x40100000, LENGTH = 16K */ /* USB1_SRAM : ORIGIN = 0x40100000, LENGTH = 16K */
} }
SECTIONS {
_config_start = ORIGIN(CONFIG);
_config_end = ORIGIN(CONFIG) + LENGTH(CONFIG);
}
-306
View File
@@ -1,306 +0,0 @@
use lpc55_hal as hal;
use hal::{FlashGordon, drivers::flash::GenericArray, raw as pac, traits::flash::WriteErase};
use shared::config::{
ConfigContainer, ConfigString, ConfigV1, ConfigVersion, DeviceConfig, TlvList,
};
use crate::{CONFIG_RESERVED, CONFIG_SLOT_COUNT, FLASH_PAGE_SIZE, SLOT_SIZE, config_base};
const SLOT_MAGIC: u32 = u32::from_le_bytes(*b"SLOT");
const FLASH_WORD_SIZE: usize = 16;
const READ_SINGLE_WORD: u32 = 0x3;
const READ_ECC_OFF: u32 = 1 << 2;
const COMMAND_TIMEOUT: u32 = 1_000_000;
static mut CONFIG_BUF: [u8; SLOT_SIZE] = [0u8; SLOT_SIZE];
#[cfg(feature = "hid")]
pub struct ConfigState {
pub running: DeviceConfig,
pub active_slot: u8,
}
#[cfg(feature = "hid")]
pub struct FlashState {
pub flash: FlashGordon,
}
#[derive(Clone, Copy, defmt::Format)]
enum FlashError {
IllegalCommand,
Failed,
Timeout,
}
fn halt() -> ! {
loop {
cortex_m::asm::wfi();
}
}
fn slot_page_address() -> usize {
config_base()
}
fn slot_address(index: usize) -> usize {
config_base() + CONFIG_RESERVED + index * SLOT_SIZE
}
fn config_buf() -> &'static mut [u8; SLOT_SIZE] {
// Safety: flash access is not reentrant and the buffer is only borrowed for one operation at a time.
unsafe { &mut *core::ptr::addr_of_mut!(CONFIG_BUF) }
}
fn read_word(
flash: &pac::flash::RegisterBlock,
address: usize,
) -> Result<[u8; FLASH_WORD_SIZE], FlashError> {
flash.int_clr_status.write(|w| {
w.done()
.set_bit()
.ecc_err()
.set_bit()
.err()
.set_bit()
.fail()
.set_bit()
});
flash
.starta
.write(|w| unsafe { w.starta().bits((address / FLASH_WORD_SIZE) as u32) });
flash.dataw[0].write(|w| unsafe { w.bits(READ_ECC_OFF) });
flash.cmd.write(|w| unsafe { w.bits(READ_SINGLE_WORD) });
let mut timeout = COMMAND_TIMEOUT;
while flash.int_status.read().done().bit_is_clear() {
timeout -= 1;
if timeout == 0 {
return Err(FlashError::Timeout);
}
}
let status = flash.int_status.read();
if status.err().bit_is_set() {
return Err(FlashError::IllegalCommand);
}
if status.fail().bit_is_set() {
return Err(FlashError::Failed);
}
let mut word = [0u8; FLASH_WORD_SIZE];
for (chunk, register) in word.chunks_mut(4).zip(flash.dataw.iter()) {
chunk.copy_from_slice(&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,11 +61,6 @@ where
volume: (0xff, 0xff), volume: (0xff, 0xff),
} }
} }
fn name(&self) -> &'static str {
"AK4490"
}
fn init(&mut self) { fn init(&mut self) {
// bring out of reset // bring out of reset
self.pins.reset.set_high(); self.pins.reset.set_high();
@@ -74,22 +69,18 @@ where
self.write_reg(RegisterAddress::Control2, 0x22 | ((dfs & 0x3) << 3)); self.write_reg(RegisterAddress::Control2, 0x22 | ((dfs & 0x3) << 3));
self.write_reg(RegisterAddress::Control4, (dfs & 0x4) >> 1); self.write_reg(RegisterAddress::Control4, (dfs & 0x4) >> 1);
} }
fn change_rate(&mut self, new_rate: u32) { fn change_rate(&mut self, new_rate: u32) {
let dfs = self.dfs_for_rate(new_rate); let dfs = self.dfs_for_rate(new_rate);
self.write_reg(RegisterAddress::Control2, 0x22 | ((dfs & 0x3) << 3)); self.write_reg(RegisterAddress::Control2, 0x22 | ((dfs & 0x3) << 3));
self.write_reg(RegisterAddress::Control4, (dfs & 0x4) >> 1); self.write_reg(RegisterAddress::Control4, (dfs & 0x4) >> 1);
} }
fn set_volume(&mut self, left: u8, right: u8) { fn set_volume(&mut self, left: u8, right: u8) {
self.set_volume_impl(left, right); self.set_volume_impl(left, right);
self.volume = (left, right); self.volume = (left, right);
} }
fn mute(&mut self) { fn mute(&mut self) {
self.set_volume_impl(0, 0); self.set_volume_impl(0, 0);
} }
fn unmute(&mut self) { fn unmute(&mut self) {
self.set_volume_impl(self.volume.0, self.volume.1); self.set_volume_impl(self.volume.0, self.volume.1);
} }
-5
View File
@@ -50,11 +50,6 @@ where
fn new(i2c: T, pins: CodecPins) -> Self { fn new(i2c: T, pins: CodecPins) -> Self {
Cs4398Dac { i2c, pins } Cs4398Dac { i2c, pins }
} }
fn name(&self) -> &'static str {
"CS4398"
}
fn init(&mut self) { fn init(&mut self) {
// reset // reset
self.pins.reset.set_low().ok(); self.pins.reset.set_low().ok();
-4
View File
@@ -7,10 +7,6 @@ pub struct NoopDac<T> {
__: PhantomData<T>, __: PhantomData<T>,
} }
impl<T> Dac<T> for NoopDac<T> { impl<T> Dac<T> for NoopDac<T> {
fn name(&self) -> &'static str {
"None"
}
fn init(&mut self) {} fn init(&mut self) {}
fn change_rate(&mut self, _new_rate: u32) {} fn change_rate(&mut self, _new_rate: u32) {}
fn mute(&mut self) {} fn mute(&mut self) {}
-5
View File
@@ -176,11 +176,6 @@ where
mclk: MCLK, mclk: MCLK,
} }
} }
fn name(&self) -> &'static str {
"WM8904"
}
fn init(&mut self) { fn init(&mut self) {
let mut buf = [0u8; 2]; let mut buf = [0u8; 2];
match self.i2c.write_read(WM8904_I2C_ADDRESS, &[0], &mut buf) { match self.i2c.write_read(WM8904_I2C_ADDRESS, &[0], &mut buf) {
+66 -78
View File
@@ -1,4 +1,3 @@
use bitfield_struct::bitfield;
use hal::Syscon; use hal::Syscon;
use hal::peripherals::syscon::ClockControl; use hal::peripherals::syscon::ClockControl;
@@ -8,6 +7,8 @@ use core::convert::Infallible;
use core::ptr::copy_nonoverlapping; use core::ptr::copy_nonoverlapping;
use core::sync::atomic::{AtomicUsize, Ordering, compiler_fence}; use core::sync::atomic::{AtomicUsize, Ordering, compiler_fence};
pub const DMA0_FLEXCOMM7_TX: u8 = 19;
#[repr(C)] #[repr(C)]
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct DmaDescriptor { pub struct DmaDescriptor {
@@ -17,56 +18,6 @@ pub struct DmaDescriptor {
pub next: *const DmaDescriptor, pub next: *const DmaDescriptor,
} }
const fn encode_transfers(transfers: u32) -> u16 {
(transfers.saturating_sub(1) & 0x3ff) as u16
}
const fn decode_transfers(raw_bits: u16) -> u32 {
(raw_bits as u32) + 1
}
/// WIDTH code: 0 = 8-bit, 1 = 16-bit, 2 = 32-bit
const fn encode_width(width_bytes: u8) -> u8 {
match width_bytes {
2 => 1,
4 => 2,
_ => 0,
}
}
const fn decode_width(raw_bits: u8) -> u8 {
match raw_bits {
1 => 2,
2 => 4,
_ => 1,
}
}
#[bitfield(u32)]
#[derive(PartialEq, Eq)]
pub struct XferCfg {
pub cfgvalid: bool, // Bit 0
pub reload: bool, // Bit 1
pub swtrig: bool, // Bit 2
pub clrtrig: bool, // Bit 3
pub inta: bool, // Bit 4
pub intb: bool, // Bit 5
#[bits(2)]
_pad1: u8, // Bits 6-7 (unused padding)
#[bits(2, from = decode_width, into = encode_width)]
pub width: u8, // Bits 8-9, in bytes (1/2/4)
#[bits(2)]
_pad2: u8, // Bits 10-11 (unused padding)
#[bits(2)]
pub src_inc: u8, // Bits 12-13
#[bits(2)]
pub dst_inc: u8, // Bits 14-15
#[bits(10, from = decode_transfers, into = encode_transfers)]
pub transfers: u32, // Bits 16-25 (fits 0x3FF max)
#[bits(6)]
_pad3: u8, // Bits 26-31 (unused padding)
}
impl defmt::Format for DmaDescriptor { impl defmt::Format for DmaDescriptor {
fn format(&self, fmt: defmt::Formatter) { fn format(&self, fmt: defmt::Formatter) {
defmt::write!( defmt::write!(
@@ -97,7 +48,7 @@ pub struct PushResult {
pub dropped: usize, pub dropped: usize,
} }
#[derive(Debug, Copy, Clone, defmt::Format, Eq, PartialEq)] #[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ConfigError { pub enum ConfigError {
SlotTooLarge, SlotTooLarge,
SlotTooSmall, SlotTooSmall,
@@ -127,7 +78,7 @@ pub struct DmaRing<const N: usize, const MAX_SLOT_BYTES: usize> {
/// Effective bytes per slot (atomic for interior mutability) /// Effective bytes per slot (atomic for interior mutability)
slot_bytes: AtomicUsize, slot_bytes: AtomicUsize,
word_bytes: u8, word_bytes: usize,
write_slot: UnsafeCell<usize>, write_slot: UnsafeCell<usize>,
write_off: UnsafeCell<usize>, write_off: UnsafeCell<usize>,
@@ -146,7 +97,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
dma: pac::DMA0, dma: pac::DMA0,
syscon: &mut Syscon, syscon: &mut Syscon,
dst_reg: *mut u32, dst_reg: *mut u32,
word_bytes: u8, word_bytes: usize,
) -> Result<Self, ConfigError> { ) -> Result<Self, ConfigError> {
if word_bytes != 1 && word_bytes != 2 && word_bytes != 4 { if word_bytes != 1 && word_bytes != 2 && word_bytes != 4 {
return Err(ConfigError::UnsupportedWidth); return Err(ConfigError::UnsupportedWidth);
@@ -156,7 +107,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
Ok(Self { Ok(Self {
dma, dma,
dst_reg, dst_reg: dst_reg,
channel_desc: UnsafeCell::new(DescriptorTable { channel_desc: UnsafeCell::new(DescriptorTable {
d: [DmaDescriptor { d: [DmaDescriptor {
xfercfg: 0, xfercfg: 0,
@@ -187,7 +138,6 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
} }
/// Optional: adjust safety gap (defaults to 1 empty slot). /// Optional: adjust safety gap (defaults to 1 empty slot).
#[allow(dead_code)]
pub fn set_safety_gap(&mut self, gap_slots: usize) { pub fn set_safety_gap(&mut self, gap_slots: usize) {
self.safety_gap = gap_slots.min(N); self.safety_gap = gap_slots.min(N);
} }
@@ -202,7 +152,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
if slot_bytes > MAX_SLOT_BYTES { if slot_bytes > MAX_SLOT_BYTES {
return Err(ConfigError::SlotTooLarge); return Err(ConfigError::SlotTooLarge);
} }
if !slot_bytes.is_multiple_of(self.word_bytes as usize) { if slot_bytes % self.word_bytes != 0 {
return Err(ConfigError::SlotNotAligned); return Err(ConfigError::SlotNotAligned);
} }
@@ -303,7 +253,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
let remaining_bytes = if reg_1 == 0x3FF { let remaining_bytes = if reg_1 == 0x3FF {
0 0
} else { } else {
(reg_1 as usize + 1) * self.word_bytes as usize (reg_1 as usize + 1) * self.word_bytes
}; };
// Active slot consumed calculation accounts for dynamic slot size // Active slot consumed calculation accounts for dynamic slot size
@@ -344,8 +294,6 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
} }
pub fn run(&self) { pub fn run(&self) {
self.dma.inta0.write(|w| unsafe { w.bits(1 << 19) });
self.dma.errint0.write(|w| unsafe { w.bits(1 << 19) });
self.dma.enableset0.write(|w| unsafe { w.bits(1 << 19) }); self.dma.enableset0.write(|w| unsafe { w.bits(1 << 19) });
} }
@@ -383,30 +331,30 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
let chan_desc = unsafe { &mut *self.channel_desc.get() }; let chan_desc = unsafe { &mut *self.channel_desc.get() };
// Pre-fill active slot regions with silence // Pre-fill active slot regions with silence
for slot in slots.iter_mut() { for i in 0..N {
slot.fill(0); slots[i][..slot_bytes].fill(0);
} }
let transfers = (slot_bytes / self.word_bytes as usize) as u32; let transfers = (slot_bytes / self.word_bytes) as u32;
for (i, slot) in slots.iter().enumerate() { for i in 0..N {
let src_start = slot.as_ptr() as usize; let src_start = slots[i].as_ptr() as usize;
let src_end = (src_start + slot_bytes - self.word_bytes as usize) as *const u8; let src_end = (src_start + slot_bytes - self.word_bytes) as *const u8;
let next = &desc.d[(i + 1) % N] as *const DmaDescriptor; let next = &desc.d[(i + 1) % N] as *const DmaDescriptor;
desc.d[i] = DmaDescriptor { desc.d[i] = DmaDescriptor {
xfercfg: XferCfg::new() xfercfg: encode_xfercfg(
.with_cfgvalid(true) // valid true, // valid
.with_reload(true) // reload true, // reload
.with_swtrig(false) // swtrig false, // swtrig
.with_clrtrig(false) // clrtrig false, // clrtrig
.with_inta(true) // intA true, // intA
.with_intb(false) // intB false, // intB
.with_width(self.word_bytes) self.word_bytes as u32,
.with_src_inc(1) // src_inc 1, // src_inc
.with_dst_inc(0) // dst_inc 0, // dst_inc
.with_transfers(transfers) transfers,
.into_bits(), ),
src_end, src_end,
dst_end: self.dst_reg, dst_end: self.dst_reg,
next, next,
@@ -424,3 +372,43 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
} }
unsafe impl<const N: usize, const MAX_SLOT_BYTES: usize> Sync for DmaRing<N, MAX_SLOT_BYTES> {} unsafe impl<const N: usize, const MAX_SLOT_BYTES: usize> Sync for DmaRing<N, MAX_SLOT_BYTES> {}
/// XFERCFG encoding follows the common LPC DMA layout:
/// - SETINTA at bit4, SETINTB at bit5
/// - WIDTH at bits 9:8
/// - SRCINC at bits 13:12
/// - DSTINC at bits 15:14
/// - XFERCOUNT at bits 25:16
/// This layout is shown in LPC DMA examples. [5](https://www.kernel.org/doc/html/latest/core-api/dma-api-howto.html)
fn encode_xfercfg(
cfgvalid: bool,
reload: bool,
swtrig: bool,
clrtrig: bool,
inta: bool,
intb: bool,
width_bytes: u32,
src_inc: u32,
dst_inc: u32,
transfers: u32,
) -> u32 {
let width_code = match width_bytes {
1 => 0,
2 => 1,
4 => 2,
_ => 0,
};
let count_field = transfers.saturating_sub(1) & 0x3FF;
((cfgvalid as u32) << 0)
| ((reload as u32) << 1)
| ((swtrig as u32) << 2)
| ((clrtrig as u32) << 3)
| ((inta as u32) << 4)
| ((intb as u32) << 5)
| ((width_code & 0x3) << 8)
| ((src_inc & 0x3) << 12)
| ((dst_inc & 0x3) << 14)
| (count_field << 16)
}
-455
View File
@@ -1,455 +0,0 @@
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();
crate::boot_to_bootloader();
}
Action::Commit => {
ack_delay();
if config::commit(flash, config).is_err() {
defmt::error!("config commit failed");
}
}
Action::ResetDefaults => {
ack_delay();
if config::commit_defaults(flash, config).is_err() {
defmt::error!("config reset failed");
}
}
}
}
return true;
}
if let Some(mut reply) = self.reply.take() {
let len = (reply.total_len - reply.offset).min(IN_PAYLOAD_LEN);
let mut report = [0u8; IN_REPORT_SIZE];
Header {
kind: reply.kind as u8,
seq: reply.seq,
total_len: reply.total_len as u16,
offset: reply.offset as u16,
len: len as u8,
}
.encode(&mut report[..HEADER_LEN]);
let start = reply.offset;
report[HEADER_LEN..HEADER_LEN + len]
.copy_from_slice(&self.reply_buf[start..start + len]);
match hid.push_raw_input(&report) {
Ok(_) => {
defmt::debug!(
"HID reply kind={:?} seq={} offset={} len={}/{}",
reply.kind,
reply.seq,
reply.offset,
len,
reply.total_len
);
reply.offset += len;
if reply.offset < reply.total_len {
self.reply = Some(reply);
}
}
Err(UsbError::WouldBlock) => self.reply = Some(reply),
Err(error) => defmt::error!("HID reply push failed: {:?}", error),
}
return true;
}
false
}
fn read<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);
}
+5 -9
View File
@@ -4,7 +4,7 @@ use core::mem::MaybeUninit;
use crate::hal; use crate::hal;
use crate::pac; use crate::pac;
use defmt::debug; use defmt::{debug, info};
use hal::{ use hal::{
Enabled, Iocon, Pin, Enabled, Iocon, Pin,
drivers::pins, drivers::pins,
@@ -124,16 +124,13 @@ pub(crate) fn init_sys_pll1() {
syscon.mainclkselb.modify(|_, w| w.sel().enum_0x2()); // pll1 syscon.mainclkselb.modify(|_, w| w.sel().enum_0x2()); // pll1
} }
// Fo = M/(N*2*P) * Fin
// Fo = 3072/(125*2*8) * 16MHz = 24.576MHz
const AUDIO_PLL: PllConstants = PllConstants::new(125, 3072, 8);
// Set PLL0 to 24.576MHz, start, and wait for lock // Set PLL0 to 24.576MHz, start, and wait for lock
// This is not exposed by lpc55-hal, unfortunately. Copy their implementation here. // This is not exposed by lpc55-hal, unfortunately. Copy their implementation here.
#[cfg(feature = "evk")]
pub(crate) fn init_audio_pll() { pub(crate) fn init_audio_pll() {
use defmt::info;
// Fo = M/(N*2*P) * Fin
// Fo = 3072/(125*2*8) * 16MHz = 24.576MHz
const AUDIO_PLL: PllConstants = PllConstants::new(125, 3072, 8);
let syscon = unsafe { &*pac::SYSCON::ptr() }; let syscon = unsafe { &*pac::SYSCON::ptr() };
let pmc = unsafe { &*pac::PMC::ptr() }; let pmc = unsafe { &*pac::PMC::ptr() };
let anactrl = unsafe { &*pac::ANACTRL::ptr() }; let anactrl = unsafe { &*pac::ANACTRL::ptr() };
@@ -203,7 +200,6 @@ pub struct SharedLed<T: OutputPin> {
inner: UnsafeCell<T>, inner: UnsafeCell<T>,
} }
unsafe impl<T: OutputPin> Sync for SharedLed<T> {} unsafe impl<T: OutputPin> Sync for SharedLed<T> {}
#[allow(dead_code)]
impl<T: OutputPin> SharedLed<T> { impl<T: OutputPin> SharedLed<T> {
pub fn new(inner: T) -> Self { pub fn new(inner: T) -> Self {
Self { Self {
+175 -350
View File
@@ -8,10 +8,9 @@ fn panic() -> ! {
} }
use atomic::Atomic; use atomic::Atomic;
use core::ptr; use core::sync::atomic::{AtomicBool, AtomicI32, AtomicUsize, Ordering};
use core::sync::atomic::AtomicPtr;
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use cortex_m_rt::entry; use cortex_m_rt::entry;
use defmt;
use defmt::debug; use defmt::debug;
use defmt_rtt as _; use defmt_rtt as _;
use hal::Pin; use hal::Pin;
@@ -24,8 +23,6 @@ use hal::typestates::pin::state::Gpio;
use lpc55_hal as hal; use lpc55_hal as hal;
use pac::interrupt; use pac::interrupt;
use static_cell::StaticCell; use static_cell::StaticCell;
#[cfg(feature = "hid")]
use usb_device::device::UsbDeviceState;
use usb_device::{ use usb_device::{
bus::{self}, bus::{self},
device::{StringDescriptors, UsbVidPid}, device::{StringDescriptors, UsbVidPid},
@@ -45,13 +42,7 @@ use crate::hw::led1;
use crate::hw::led2; use crate::hw::led2;
use crate::traits::Dac; use crate::traits::Dac;
use shared::AudioState; use shared::AudioState;
#[cfg(feature = "hid")]
use shared::config::ConfigString;
#[cfg(feature = "hid")]
use shared::hardware::HardwareInfo;
use shared::hid::AudioTelemetryReport; use shared::hid::AudioTelemetryReport;
#[cfg(feature = "hid")]
use shared::hid::DeviceCommandReport;
#[cfg(feature = "ak4490")] #[cfg(feature = "ak4490")]
pub mod dac { pub mod dac {
@@ -74,10 +65,7 @@ pub mod dac {
pub use self::wm8904::Wm8904Dac as DacImpl; pub use self::wm8904::Wm8904Dac as DacImpl;
} }
mod config;
mod dma; mod dma;
#[cfg(feature = "hid")]
mod hid_config;
mod hw; mod hw;
mod traits; mod traits;
@@ -117,42 +105,8 @@ 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 NODATA_TIMEOUT_FRAMES: usize = SAMPLE_RATE as usize / 100; // ~100ms
const HID_INTERVAL_MS: u8 = 10; const HID_INTERVAL_MS: u8 = 10;
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 { struct CodecPins {
#[allow(dead_code)]
reset: Pin<pins::Pio0_3, Gpio<Output>>, reset: Pin<pins::Pio0_3, Gpio<Output>>,
} }
@@ -163,29 +117,47 @@ struct ClockSelPins {
#[derive(Default)] #[derive(Default)]
struct PerfCounters { struct PerfCounters {
// state: Atomic<AudioState>, state: Atomic<AudioState>,
received_frames: AtomicUsize, received_frames: AtomicUsize,
played_frames: AtomicUsize, played_frames: AtomicUsize,
// min_fill: AtomicUsize, min_fill: AtomicUsize,
// avg_fill: AtomicUsize, avg_fill: AtomicUsize,
queue_underflows: AtomicUsize, queue_underflows: AtomicUsize,
queue_overflows: AtomicUsize, queue_overflows: AtomicUsize,
audio_underflows: AtomicUsize, audio_underflows: AtomicUsize,
// p: AtomicI32, integrator: AtomicI32,
// fb: AtomicI32, p: AtomicI32,
i: AtomicI32,
fb: AtomicI32,
} }
impl PerfCounters { impl PerfCounters {
fn reset(&self) { fn reset(&self) {
self.received_frames.store(0, Ordering::Relaxed); self.received_frames.store(0, Ordering::Relaxed);
self.played_frames.store(0, Ordering::Relaxed); self.played_frames.store(0, Ordering::Relaxed);
// self.min_fill self.min_fill
// .store(N_SLOTS * MAX_BYTES_PER_SLOT, Ordering::Relaxed); .store(N_SLOTS * MAX_BYTES_PER_SLOT, Ordering::Relaxed);
// self.avg_fill.store(0 as usize, Ordering::Relaxed); self.avg_fill.store(0 as usize, Ordering::Relaxed);
self.queue_underflows.store(0, Ordering::Relaxed); self.queue_underflows.store(0, Ordering::Relaxed);
self.queue_overflows.store(0, Ordering::Relaxed); self.queue_overflows.store(0, Ordering::Relaxed);
self.audio_underflows.store(0, Ordering::Relaxed); self.audio_underflows.store(0, Ordering::Relaxed);
// self.p.store(0, Ordering::Relaxed); self.p.store(0, Ordering::Relaxed);
self.i.store(0, Ordering::Relaxed);
// FB loop will have to take care of the fb value
}
fn build_report(&self) -> AudioTelemetryReport {
AudioTelemetryReport {
state: self.state.load(Ordering::Relaxed) as u8,
average_buffer_fill: self.avg_fill.load(Ordering::Relaxed) as u16,
frame_count: self.played_frames.load(Ordering::Relaxed) as i32,
dac_underflow_count: self.audio_underflows.load(Ordering::Relaxed) as u16,
usb_underflow_count: self.queue_underflows.load(Ordering::Relaxed) as u16,
dac_overflow_count: self.queue_overflows.load(Ordering::Relaxed) as u16,
integrator: self.integrator.load(Ordering::Relaxed),
p: self.p.load(Ordering::Relaxed),
i: self.i.load(Ordering::Relaxed),
fb: u32::cast_signed(self.fb.load(Ordering::Relaxed) as u32),
}
} }
} }
@@ -193,11 +165,11 @@ impl defmt::Format for PerfCounters {
fn format(&self, fmt: defmt::Formatter) { fn format(&self, fmt: defmt::Formatter) {
defmt::write!( defmt::write!(
fmt, fmt,
"frames: {}/{} a_underflows: {} q_underflows: {} q_overflows: {}", "frames: {}/{} min_fill: {} avg fill: {} a_underflows: {} q_underflows: {} q_overflows: {}",
self.played_frames.load(Ordering::Relaxed), self.played_frames.load(Ordering::Relaxed),
self.received_frames.load(Ordering::Relaxed), self.received_frames.load(Ordering::Relaxed),
// self.min_fill.load(Ordering::Relaxed), self.min_fill.load(Ordering::Relaxed),
// self.avg_fill.load(Ordering::Relaxed), self.avg_fill.load(Ordering::Relaxed),
self.audio_underflows.load(Ordering::Relaxed), self.audio_underflows.load(Ordering::Relaxed),
self.queue_underflows.load(Ordering::Relaxed), self.queue_underflows.load(Ordering::Relaxed),
self.queue_overflows.load(Ordering::Relaxed) self.queue_overflows.load(Ordering::Relaxed)
@@ -206,154 +178,27 @@ impl defmt::Format for PerfCounters {
} }
static PERF: PerfCounters = PerfCounters { static PERF: PerfCounters = PerfCounters {
// state: Atomic::new(AudioState::Stopped), state: Atomic::new(AudioState::Stopped),
received_frames: AtomicUsize::new(0), // received from USB received_frames: AtomicUsize::new(0), // received from USB
played_frames: AtomicUsize::new(0), // played audio frames played_frames: AtomicUsize::new(0), // played audio frames
// min_fill: AtomicUsize::new(0), // not recording this for now, need to figure out how to make it meaningful, since the queue starts empty min_fill: AtomicUsize::new(0), // not recording this for now, need to figure out how to make it meaningful, since the queue starts empty
// avg_fill: AtomicUsize::new(0), avg_fill: AtomicUsize::new(0),
queue_underflows: AtomicUsize::new(0), // ditto here, since we underflow at startup, but we record this one as it can be trended queue_underflows: AtomicUsize::new(0), // ditto here, since we underflow at startup, but we record this one as it can be trended
queue_overflows: AtomicUsize::new(0), queue_overflows: AtomicUsize::new(0),
audio_underflows: AtomicUsize::new(0), audio_underflows: AtomicUsize::new(0),
// p: AtomicI32::new(0), integrator: AtomicI32::new(0),
// fb: AtomicI32::new(0), p: AtomicI32::new(0),
i: AtomicI32::new(0),
fb: AtomicI32::new(0),
}; };
fn boot_to_bootloader() -> ! {
cortex_m::interrupt::disable();
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)));
}
cortex_m::peripheral::SCB::sys_reset()
}
fn build_telemetry_report<D: Dac<I>, I>(
perf: &PerfCounters,
audio: &Audio<D, I>,
) -> AudioTelemetryReport {
AudioTelemetryReport {
state: audio.state.load(Ordering::Relaxed) as u8,
average_buffer_fill: audio.fb.avg_fill as u16,
frame_count: perf.played_frames.load(Ordering::Relaxed).cast_signed() as i32,
dac_underflow_count: perf.audio_underflows.load(Ordering::Relaxed) as u16,
usb_underflow_count: perf.queue_underflows.load(Ordering::Relaxed) as u16,
dac_overflow_count: perf.queue_overflows.load(Ordering::Relaxed) as u16,
cur_rate: audio.cur_rate.cast_signed(),
fb_rate_estimate: audio.fb.current_freq_estimate() as i32,
}
}
#[derive(Clone, Copy, Debug)]
pub struct FeedbackConfig {
/// Nominal USB rate in Q12.13 fixed-point format (or target sample rate context).
pub nominal_rate: u32,
/// Target ring buffer fill level in bytes.
pub target_fill_bytes: i32,
/// Deadband threshold in bytes (e.g., 4).
pub deadband_bytes: i32,
/// Maximum allowed feedback deviation permille denominator (e.g., 500 => 0.2%).
pub max_deviation_divider: i32,
/// Master toggle for feedback correction.
pub correction_enabled: bool,
}
impl FeedbackConfig {
pub fn new(nominal_rate: u32, target_fill_bytes: usize) -> Self {
Self {
nominal_rate,
target_fill_bytes: target_fill_bytes as i32,
deadband_bytes: 4,
max_deviation_divider: 500, // 0.2%
correction_enabled: true,
}
}
pub fn for_rate(nominal_rate: u32) -> Self {
let target_fill_bytes = (bytes_per_slot(nominal_rate) * N_SLOTS) / 2;
Self::new(nominal_rate, target_fill_bytes)
}
}
pub struct FeedbackLoop {
pub config: FeedbackConfig,
pub avg_fill: usize,
last_freq: u32,
}
impl FeedbackLoop {
pub fn new(config: FeedbackConfig) -> Self {
Self {
config,
avg_fill: config.target_fill_bytes as usize,
last_freq: config.nominal_rate,
}
}
pub fn reset(&mut self) {
self.avg_fill = self.config.target_fill_bytes as usize;
self.last_freq = self.config.nominal_rate
}
pub fn update_config(&mut self, config: FeedbackConfig) {
self.config = config;
self.reset();
}
pub fn compute(
&mut self,
nominal_rate: UsbIsochronousFeedback,
current_fill_bytes: usize,
) -> UsbIsochronousFeedback {
if !self.config.correction_enabled {
return nominal_rate;
}
let current_bytes = current_fill_bytes as i32;
if current_bytes == 0 {
defmt::error!("[fb] dma underrun detected!");
PERF.queue_underflows.fetch_add(1, Ordering::Relaxed);
return nominal_rate;
}
self.avg_fill = ((self.avg_fill << 6) - self.avg_fill + current_bytes as usize) >> 6;
let target_fill = self.config.target_fill_bytes;
let raw_error = current_bytes - target_fill;
let nominal_v = nominal_rate.to_u32_12_13() as i32;
let max_allowed_deviation = nominal_v / self.config.max_deviation_divider;
let error_permille = (raw_error * 1000) / target_fill;
let p_term = (-((error_permille as i64) * (nominal_v as i64)) / (10 * 256000)) as i32;
let mut v = nominal_v + p_term;
v = v.clamp(
nominal_v - max_allowed_deviation,
nominal_v + max_allowed_deviation,
);
self.last_freq = v as u32;
UsbIsochronousFeedback::new(v as u32)
}
pub fn current_freq_estimate(&self) -> f32 {
// Divides by 8 (frame-to-microframe) and 65536.0 (Q16.16 shift)
(self.last_freq as f32 / (65536.0)) * USB_FRAME_RATE as f32
}
}
static NODATA_FLAG: AtomicBool = AtomicBool::new(false); static NODATA_FLAG: AtomicBool = AtomicBool::new(false);
static DMA_RING: StaticCell<DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT>> = StaticCell::new(); static DMA_RING: StaticCell<DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT>> = StaticCell::new();
static DMA_RING_PTR: AtomicPtr<DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT>> = static mut DMA_RING_REF: Option<&'static DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT>> = None;
AtomicPtr::new(ptr::null_mut());
#[inline] #[inline]
fn dma_ring() -> &'static DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT> { fn dma_ring() -> &'static DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT> {
let ptr = DMA_RING_PTR.load(Ordering::Acquire); unsafe { DMA_RING_REF.unwrap() }
unsafe { &*ptr }
} }
fn cur_fill() -> usize { fn cur_fill() -> usize {
@@ -364,14 +209,12 @@ fn cur_fill() -> usize {
produced_bytes.wrapping_sub(consumed_bytes) as usize produced_bytes.wrapping_sub(consumed_bytes) as usize
} }
/// frames per slot (based on current slot size) fn cur_fill_target() -> i32 {
fn frames_per_slot() -> usize { (dma_ring().slot_size() * N_SLOTS) as i32 / 2
dma_ring().slot_size() / BYTES_PER_FRAME
} }
/// bytes per slot (based on provided rate) fn frames_per_slot() -> usize {
fn bytes_per_slot(rate: u32) -> usize { dma_ring().slot_size() / BYTES_PER_FRAME
(rate as usize / DMA_RATE) * BYTES_PER_FRAME
} }
// 50% // 50%
@@ -433,13 +276,39 @@ fn FLEXCOMM7() {
.modify(|_, w| w.txerr().set_bit()) .modify(|_, w| w.txerr().set_bit())
} }
struct FeedbackState {
correction_enabled: AtomicBool,
integrator: AtomicI32,
filtered_fill: AtomicI32,
}
impl FeedbackState {
fn start(&mut self) {
self.correction_enabled.store(true, Ordering::Relaxed);
}
fn reset(&mut self) {
self.correction_enabled.store(false, Ordering::Relaxed);
self.integrator.store(0, Ordering::Relaxed);
self.filtered_fill
.store(cur_fill_target(), Ordering::Relaxed);
}
}
impl Default for FeedbackState {
fn default() -> Self {
Self {
correction_enabled: AtomicBool::new(false),
integrator: AtomicI32::new(0),
filtered_fill: AtomicI32::new(cur_fill_target()),
}
}
}
struct Audio<'a, D: Dac<I>, I> { struct Audio<'a, D: Dac<I>, I> {
state: Atomic<AudioState>, state: Atomic<AudioState>,
alt_setting: u8, alt_setting: u8,
i2s: I2sTx, i2s: I2sTx,
dac: D, dac: D,
dma: &'a DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT>, dma: &'a DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT>,
fb: FeedbackLoop, fb: FeedbackState,
nodata_timeout_frame: AtomicUsize, nodata_timeout_frame: AtomicUsize,
cur_rate: u32, cur_rate: u32,
clock_pins: ClockSelPins, clock_pins: ClockSelPins,
@@ -463,8 +332,8 @@ impl<D: Dac<I>, I> Audio<'_, D, I> {
AudioState::NoData => self.nodata(), AudioState::NoData => self.nodata(),
AudioState::Stopping => self.stopping(), AudioState::Stopping => self.stopping(),
} }
self.state.store(state, Ordering::Release); self.state.store(state, Ordering::SeqCst);
// PERF.state.store(state, Ordering::Relaxed); PERF.state.store(state, Ordering::Relaxed);
} }
fn init(&mut self) { fn init(&mut self) {
@@ -507,7 +376,6 @@ impl<D: Dac<I>, I> Audio<'_, D, I> {
}); });
unsafe { pac::NVIC::unmask(pac::Interrupt::FLEXCOMM7) }; unsafe { pac::NVIC::unmask(pac::Interrupt::FLEXCOMM7) };
self.dac.init(); self.dac.init();
} }
///Transition -> Stopped: ///Transition -> Stopped:
@@ -547,7 +415,7 @@ impl<D: Dac<I>, I> Audio<'_, D, I> {
///Transition -> Running ///Transition -> Running
///Unmask I2S ISR, start feedback ///Unmask I2S ISR, start feedback
fn run(&mut self) { fn run(&mut self) {
self.i2s.i2s.fifostat.write(|w| w.txerr().set_bit()); self.fb.start();
// FIFO threshold trigger enable // FIFO threshold trigger enable
self.i2s self.i2s
.i2s .i2s
@@ -557,14 +425,14 @@ impl<D: Dac<I>, I> Audio<'_, D, I> {
.i2s .i2s
.fifocfg .fifocfg
.modify(|_, w| w.enabletx().enabled().dmatx().enabled()); .modify(|_, w| w.enabletx().enabled().dmatx().enabled());
dma_ring().run();
// clear tx error status
self.i2s.i2s.fifostat.write(|w| w.txerr().set_bit());
// enable tx error interrupt
self.i2s.i2s.fifointenset.write(|w| w.txerr().enabled());
unsafe { unsafe {
pac::NVIC::unmask(pac::Interrupt::DMA0); pac::NVIC::unmask(pac::Interrupt::DMA0);
} }
dma_ring().run();
// clear tx error status
// self.i2s.i2s.fifostat.write(|w| w.txerr().set_bit());
// enable tx error interrupt
self.i2s.i2s.fifointenset.write(|w| w.txerr().enabled());
} }
///Transition->NoData ///Transition->NoData
///store framecount at transition so we can time out recovery ///store framecount at transition so we can time out recovery
@@ -604,18 +472,13 @@ impl<D: Dac<I>, I> ClockSource for Audio<'_, D, I> {
sample_rate: u32, sample_rate: u32,
) -> core::result::Result<(), usbd_uac2::UsbAudioClassError> { ) -> core::result::Result<(), usbd_uac2::UsbAudioClassError> {
defmt::info!("[clock] changing rate to {}", sample_rate); defmt::info!("[clock] changing rate to {}", sample_rate);
if self.state.load(Ordering::Acquire) != AudioState::Stopped { if self.state.load(Ordering::SeqCst) != AudioState::Stopped {
defmt::warn!("[clock] changing rate when not stopped, stopping first"); defmt::warn!("[clock] changing rate when not stopped, stopping first");
self.stop(); self.stop();
} }
let slot_bytes = (self.cur_rate as usize / DMA_RATE) * BYTES_PER_FRAME;
dma_ring().set_slot_size(slot_bytes);
self.cur_rate = sample_rate; self.cur_rate = sample_rate;
let slot_bytes = bytes_per_slot(self.cur_rate);
if let Err(e) = dma_ring().set_slot_size(slot_bytes) {
defmt::error!("Error configuring dma: {}", e);
return Err(UsbAudioClassError::Other);
}
self.fb
.update_config(FeedbackConfig::for_rate(self.cur_rate));
if 24_576_000u32.is_multiple_of(sample_rate) { if 24_576_000u32.is_multiple_of(sample_rate) {
defmt::info!("[clock] 24M osc selected"); defmt::info!("[clock] 24M osc selected");
self.clock_pins.sel_22m.set_low().ok(); self.clock_pins.sel_22m.set_low().ok();
@@ -643,7 +506,7 @@ impl<D: Dac<I>, I> ClockSource for Audio<'_, D, I> {
} }
impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> { impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
fn alternate_setting_changed(&mut self, _terminal: usb_device::UsbDirection, alt_setting: u8) { fn alternate_setting_changed(&mut self, _terminal: usb_device::UsbDirection, alt_setting: u8) {
let state = self.state.load(Ordering::Acquire); let state = self.state.load(Ordering::Relaxed);
match (alt_setting, state) { match (alt_setting, state) {
(0, AudioState::Armed | AudioState::Prefill | AudioState::NoData) => { (0, AudioState::Armed | AudioState::Prefill | AudioState::NoData) => {
self.transition(AudioState::Stopped) self.transition(AudioState::Stopped)
@@ -662,7 +525,7 @@ impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
&mut self, &mut self,
ep: &usb_device::endpoint::Endpoint<'_, B, usb_device::endpoint::Out>, ep: &usb_device::endpoint::Endpoint<'_, B, usb_device::endpoint::Out>,
) { ) {
let state = self.state.load(Ordering::Acquire); let state = self.state.load(Ordering::Relaxed);
let mut buf = let mut buf =
[0; (MAX_SAMPLE_RATE.div_ceil(USB_FRAME_RATE) + 1) as usize * BYTES_PER_FRAME]; [0; (MAX_SAMPLE_RATE.div_ceil(USB_FRAME_RATE) + 1) as usize * BYTES_PER_FRAME];
let len = match ep.read(&mut buf) { let len = match ep.read(&mut buf) {
@@ -693,8 +556,7 @@ impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
// Valid states here are Armed, Prefill, Running, Draining and NoData // Valid states here are Armed, Prefill, Running, Draining and NoData
match state { match state {
AudioState::Stopped | AudioState::Stopping => { AudioState::Stopped | AudioState::Stopping => {
defmt::warn!("Received audio data when stopped/stopping"); defmt::error!("Received audio data when stopped/stopping")
self.transition(AudioState::Prefill);
} }
// When armed, data rx goes to prefill // When armed, data rx goes to prefill
AudioState::Armed => self.transition(AudioState::Prefill), AudioState::Armed => self.transition(AudioState::Prefill),
@@ -710,7 +572,7 @@ impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
AudioState::Running => {} AudioState::Running => {}
// If draining, check cur_fill, if it rises above QUEUE_RUNNING_UP, move back to running. If it drops to 0, move to NoData or Stopped // If draining, check cur_fill, if it rises above QUEUE_RUNNING_UP, move back to running. If it drops to 0, move to NoData or Stopped
AudioState::LowData => { AudioState::LowData => {
let fill = cur_fill(); let fill = cur_fill() as usize;
// Do we check alt setting here? We shouldn't be receiving data at all if we are not in altSetting 1 // Do we check alt setting here? We shouldn't be receiving data at all if we are not in altSetting 1
if fill >= queue_running_up_threshold() { if fill >= queue_running_up_threshold() {
self.transition(AudioState::Running); self.transition(AudioState::Running);
@@ -721,7 +583,7 @@ impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
} }
} }
// Any data in NoData moves us into LowData. But maybe it should be more like prefill? // Any data in NoData moves us into LowData. But maybe it should be more like prefill?
AudioState::NoData => self.transition(AudioState::Prefill), AudioState::NoData => self.transition(AudioState::LowData),
} }
} }
fn audio_data_tx( fn audio_data_tx(
@@ -730,7 +592,11 @@ impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
) { ) {
} }
fn feedback(&mut self, nominal_rate: UsbIsochronousFeedback) -> Option<UsbIsochronousFeedback> { fn feedback(&mut self, nominal_rate: UsbIsochronousFeedback) -> Option<UsbIsochronousFeedback> {
let current_bytes = cur_fill(); if !self.fb.correction_enabled.load(Ordering::Relaxed) {
return Some(nominal_rate);
}
let current_bytes = cur_fill() as i32;
if current_bytes == 0 { if current_bytes == 0 {
defmt::error!("[fb] dma underrun detected!"); defmt::error!("[fb] dma underrun detected!");
@@ -738,11 +604,44 @@ impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
return Some(nominal_rate); return Some(nominal_rate);
} }
let v = self.fb.compute(nominal_rate, current_bytes); PERF.avg_fill
// PERF.avg_fill.store(self.fb.avg_fill, Ordering::Relaxed); .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| {
// PERF.fb.store(v as i32, Ordering::Relaxed); Some(((v << 6) - v + current_bytes as usize) >> 6)
})
.ok();
Some(v) let raw_error = current_bytes - cur_fill_target();
let i_error = if raw_error.abs() <= 4 { 0 } else { raw_error }; // deadband
let current_i = self.fb.integrator.load(Ordering::Relaxed);
let leak = current_i >> 7;
let new_i = current_i
.saturating_sub(leak)
.saturating_add(i_error)
.clamp(-5000, 5000);
self.fb.integrator.store(new_i, Ordering::Relaxed);
PERF.integrator.store(new_i, Ordering::Relaxed);
let nominal_v = nominal_rate.to_u32_12_13() as i32;
let max_allowed_deviation = nominal_v / 500; // 0.2%
// 3. SEPARATE GAINS FOR P AND I
// For P: Keep your working math (converting raw error to a permille equivalent scale)
let error_permille = (raw_error * 1000) / cur_fill_target();
let p_term = (-((error_permille as i64) * (nominal_v as i64)) / (10 * 256000)) as i32;
let i_term = (-((new_i as i64) * (nominal_v as i64)) / (256000 * 1000)) as i32;
let i_term = 0;
PERF.p.store(p_term, Ordering::Relaxed);
PERF.i.store(i_term, Ordering::Relaxed);
let mut v = nominal_v + p_term + i_term;
v = v.clamp(
nominal_v - max_allowed_deviation,
nominal_v + max_allowed_deviation,
);
PERF.fb.store(v, Ordering::Relaxed);
Some(UsbIsochronousFeedback::new(v as u32))
} }
} }
@@ -853,7 +752,7 @@ fn main() -> ! {
pins::Pio1_20::take().unwrap().into_i2c4_scl_pin(&mut iocon), pins::Pio1_20::take().unwrap().into_i2c4_scl_pin(&mut iocon),
pins::Pio1_21::take().unwrap().into_i2c4_sda_pin(&mut iocon), pins::Pio1_21::take().unwrap().into_i2c4_sda_pin(&mut iocon),
); );
let _codec_i2s_pins = ( let codec_i2s_pins = (
pins::Pio0_21::take().unwrap().into_spi7_sck_pin(&mut iocon), pins::Pio0_21::take().unwrap().into_spi7_sck_pin(&mut iocon),
pins::Pio0_20::take().unwrap().into_i2s7_sda_pin(&mut iocon), pins::Pio0_20::take().unwrap().into_i2s7_sda_pin(&mut iocon),
pins::Pio0_19::take().unwrap().into_i2s7_ws_pin(&mut iocon), pins::Pio0_19::take().unwrap().into_i2s7_ws_pin(&mut iocon),
@@ -885,22 +784,6 @@ fn main() -> ! {
.system_frequency(96.MHz()) .system_frequency(96.MHz())
.configure(&mut anactrl, &mut pmc, &mut syscon) .configure(&mut anactrl, &mut pmc, &mut syscon)
.unwrap(); .unwrap();
// Flash controller commands require a core clock of at most 100 MHz, so the config is read
// before the system PLL takes the core to 150 MHz.
let flash = hal.flash.enabled(&mut syscon);
let mut flash = hal::FlashGordon::new(flash);
defmt::info!("config: loading");
let (running_config, active_slot) = config::load(&mut flash);
defmt::info!(
"config: loaded slot={} vid={:04x} pid={:04x}",
active_slot,
running_config.usb_vendor_id,
running_config.usb_product_id
);
#[cfg(not(feature = "hid"))]
let _ = active_slot;
hw::init_sys_pll1(); hw::init_sys_pll1();
#[cfg(feature = "evk")] #[cfg(feature = "evk")]
hw::init_audio_pll(); hw::init_audio_pll();
@@ -948,17 +831,15 @@ fn main() -> ! {
) )
.unwrap(); .unwrap();
let dma_ref = DMA_RING.init(dma); let dma_ref = DMA_RING.init(dma);
DMA_RING_PTR.store(dma_ref as *const _ as *mut _, Ordering::Release); unsafe { DMA_RING_REF = Some(dma_ref) };
// unsafe { DMA_RING_PTR = Some(dma_ref) };
defmt::info!("audio init"); defmt::info!("audio init");
let mut audio = Audio { let mut audio = Audio {
state: Atomic::new(AudioState::Stopped), state: Atomic::new(AudioState::Stopped),
i2s: i2s_peripheral, i2s: i2s_peripheral,
dac: dac_impl, dac: dac_impl,
dma: dma_ring(), dma: dma_ring(),
fb: FeedbackLoop::new(FeedbackConfig::for_rate(SAMPLE_RATES[0].min)), fb: FeedbackState::default(),
alt_setting: 0, alt_setting: 0,
nodata_timeout_frame: AtomicUsize::new(0), nodata_timeout_frame: AtomicUsize::new(0),
cur_rate: SAMPLE_RATES[0].min, cur_rate: SAMPLE_RATES[0].min,
@@ -978,115 +859,58 @@ fn main() -> ! {
); );
let mut uac2 = config.build(&usb_bus).unwrap(); let mut uac2 = config.build(&usb_bus).unwrap();
#[cfg(feature = "hid")] #[cfg(feature = "hid")]
let (mut hid, mut hid_cmd) = { let mut hid = HIDClass::new_ep_in(&usb_bus, AudioTelemetryReport::desc(), HID_INTERVAL_MS);
let hid = HIDClass::new_ep_in(&usb_bus, AudioTelemetryReport::desc(), HID_INTERVAL_MS);
// Commands arrive as feature reports over the control pipe; Linux's usbhid needs an let mut usb_dev = usbd_uac2::builder(&usb_bus, UsbVidPid(0x1209, 0xcc1d))
// interrupt IN endpoint to bind the interface, and replies use it. .strings(&[StringDescriptors::default()
let hid_cmd = .manufacturer("VE7XEN")
HIDClass::new_ep_in(&usb_bus, DeviceCommandReport::desc(), HID_CMD_INTERVAL_MS); .product("Guac Tortilla")])
(hid, hid_cmd) .unwrap()
}; .max_packet_size_0(64)
.unwrap()
.build();
#[cfg(feature = "hid")] #[cfg(feature = "hid")]
let hardware_info = HardwareInfo { let mut poll_all = {
uuid: hal::uuid(), let mut hid_update_timer = Timer::new(
dac: ConfigString::try_from(uac2.handler().dac.name()).unwrap_or_default(),
version: ConfigString::try_from(env!("GUAC_VERSION")).unwrap_or_default(),
};
#[cfg(feature = "hid")]
defmt::info!(
"hardware: uuid={=[u8]:02x} dac={=str} firmware={=str}",
&hardware_info.uuid[..],
hardware_info.dac.as_str(),
hardware_info.version.as_str()
);
let mut usb_dev = usbd_uac2::builder(
&usb_bus,
UsbVidPid(running_config.usb_vendor_id, running_config.usb_product_id),
)
.strings(&[{
let descriptors = StringDescriptors::default()
.manufacturer(running_config.usb_manufacturer.as_str())
.product(running_config.usb_product.as_str());
match &running_config.usb_serial {
Some(serial) => descriptors.serial_number(serial.as_str()),
None => descriptors,
}
}])
.unwrap()
.max_packet_size_0(64)
.unwrap()
.build();
// 1. Initialize the HID timer conditionally outside the closure
#[cfg(feature = "hid")]
let mut hid_update_timer = {
let mut timer = Timer::new(
hal.ctimer hal.ctimer
.1 .1
.enabled(&mut syscon, clocks.support_1mhz_fro_token().unwrap()), .enabled(&mut syscon, clocks.support_1mhz_fro_token().unwrap()),
); );
timer.start(Microseconds::new(HID_INTERVAL_MS as u32 * 1000)); hid_update_timer.start(Microseconds::new(HID_INTERVAL_MS as u32 * 1000));
timer
};
#[cfg(feature = "hid")] move || {
let mut config_state = config::ConfigState { usb_dev.poll(&mut [&mut uac2, &mut hid]);
running: running_config.clone(), // DMA ring is empty; if altsetting = 0 then -> stopped else NoData
active_slot, // TODO: handle NoData state
}; if NODATA_FLAG.swap(false, Ordering::Acquire) {
#[cfg(feature = "hid")] match uac2.handler().state.load(Ordering::Acquire) {
let mut flash_state = config::FlashState { flash }; AudioState::Stopping => uac2.handler().transition(AudioState::Stopped),
#[cfg(feature = "hid")] _ => uac2.handler().transition(AudioState::Stopped),
let mut command_state = hid_config::CommandState::new();
// 2. Single consolidated poll_all closure
let mut poll_all = move || {
// Poll active USB classes
#[cfg(feature = "hid")]
usb_dev.poll(&mut [&mut uac2, &mut hid, &mut hid_cmd]);
#[cfg(not(feature = "hid"))]
usb_dev.poll(&mut [&mut uac2]);
// TODO: we should handle unexpected NODATA differently from 'Stopping'
if NODATA_FLAG.swap(false, Ordering::AcqRel) {
let audio = uac2.handler();
audio.transition(AudioState::Stopped);
// The host is still streaming (alt setting 1) so no alt setting change will
// re-arm us; re-arm now so the DMA channel is re-initialised before more data
// arrives.
if audio.alt_setting == 1 {
audio.transition(AudioState::Armed);
}
}
#[cfg(feature = "hid")]
{
if hid_update_timer.wait().is_ok() {
let report = build_telemetry_report(&PERF, uac2.handler());
if let Err(e) = hid.push_input(&report)
&& e != UsbError::WouldBlock
{
defmt::error!("Failed to send HID report: {:?}", e);
} }
// LPC55 CTIMER is not periodic; restart manually }
if hid_update_timer.wait().is_ok() {
let report = PERF.build_report();
match hid.push_input(&report) {
Ok(_) => {}
Err(UsbError::WouldBlock) => {}
Err(e) => defmt::error!("Failed to send HID report: {:?}", e),
}
// lpc55 ctimer is not Periodic, so restart it
hid_update_timer.start(Microseconds::new(HID_INTERVAL_MS as u32 * 1000)); hid_update_timer.start(Microseconds::new(HID_INTERVAL_MS as u32 * 1000));
} }
if usb_dev.state() != UsbDeviceState::Configured { }
command_state.reset(); };
#[cfg(not(feature = "hid"))]
let mut poll_all = {
move || {
usb_dev.poll(&mut [&mut uac2]);
if NODATA_FLAG.swap(false, Ordering::Acquire) {
match uac2.handler().state.load(Ordering::Acquire) {
AudioState::Stopping => uac2.handler().transition(AudioState::Stopped),
_ => uac2.handler().transition(AudioState::Stopped),
}
} }
hid_config::poll(
&mut hid_cmd,
&mut command_state,
&mut config_state,
&mut flash_state,
&hardware_info,
);
} }
}; };
@@ -1094,5 +918,6 @@ fn main() -> ! {
loop { loop {
poll_all(); poll_all();
// usb_dev.poll(&mut [&mut uac2]);
} }
} }
-2
View File
@@ -1,12 +1,10 @@
use crate::CodecPins; use crate::CodecPins;
pub trait Dac<T> { pub trait Dac<T> {
fn new(i2c: T, pins: CodecPins) -> Self; fn new(i2c: T, pins: CodecPins) -> Self;
fn name(&self) -> &'static str;
/// The DAC should start muted /// The DAC should start muted
fn init(&mut self); fn init(&mut self);
fn change_rate(&mut self, new_rate: u32); fn change_rate(&mut self, new_rate: u32);
#[allow(unused_variables)] #[allow(unused_variables)]
#[allow(dead_code)]
fn set_volume(&mut self, left: u8, right: u8) {} fn set_volume(&mut self, left: u8, right: u8) {}
fn mute(&mut self); fn mute(&mut self);
fn unmute(&mut self); fn unmute(&mut self);
+4
View File
@@ -0,0 +1,4 @@
[toolchain]
channel = "1.95.0"
targets = ["thumbv8m.main-none-eabihf"]
components = ["llvm-tools-preview"]
+2 -4
View File
@@ -3,15 +3,13 @@ name = "shared"
edition = "2024" edition = "2024"
[features] [features]
std = ["deku/alloc", "heapless/alloc", "wary/std", "wary/alloc"] std = []
serde = ["dep:serde", "heapless/serde"] serde = ["dep:serde"]
[dependencies] [dependencies]
bytemuck = { version = "1.25.0", features = ["derive"] } bytemuck = { version = "1.25.0", features = ["derive"] }
defmt = "1.1.1" defmt = "1.1.1"
deku = { version = "0.20.3", default-features = false } deku = { version = "0.20.3", default-features = false }
heapless = { version = "0.9.3", features = ["defmt"] }
num_enum = { version = "0.7.6", default-features = false } num_enum = { version = "0.7.6", default-features = false }
serde = { version = "1.0.228", optional = true, features = ["derive"] } serde = { version = "1.0.228", optional = true, features = ["derive"] }
usbd-hid = { version = "0.10.0" } usbd-hid = { version = "0.10.0" }
wary = { version = "0.3.2", default-features = false, features = ["derive"] }
-268
View File
@@ -1,268 +0,0 @@
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
@@ -1,89 +0,0 @@
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
@@ -1,607 +0,0 @@
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
@@ -1,198 +0,0 @@
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
@@ -1,26 +0,0 @@
#[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
@@ -1,179 +0,0 @@
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
@@ -1,182 +0,0 @@
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
@@ -1,136 +0,0 @@
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)
);
}
}
+25 -172
View File
@@ -1,22 +1,18 @@
#![no_std] #![no_std]
pub mod config;
pub mod hardware;
use bytemuck::NoUninit; use bytemuck::NoUninit;
use num_enum::TryFromPrimitive; use num_enum::TryFromPrimitive;
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, NoUninit, Eq, PartialEq, TryFromPrimitive)] #[derive(Clone, Copy, Debug, NoUninit, Eq, PartialEq, TryFromPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u8)] #[repr(u8)]
pub enum AudioState { pub enum AudioState {
/// Knowingly stopped, ie. AltSetting=0. DAC muted, I2S disabled. /// Knowingly stopped, ie. AltSetting=0. DAC muted, I2S disabled.
/// ///
/// AltSetting = 1 -> ARMED /// AltSetting = 1 -> ARMED
#[default]
Stopped = 0, Stopped = 0,
/// Waiting for data. DAC muted, I2S running sending 0s (FIFO not serviced). /// Waiting for data. DAC muted, I2S running sending 0s (FIFO not serviced).
/// ///
@@ -53,6 +49,11 @@ pub enum AudioState {
Stopping = 6, Stopping = 6,
} }
impl Default for AudioState {
fn default() -> Self {
AudioState::Stopped
}
}
impl defmt::Format for AudioState { impl defmt::Format for AudioState {
fn format(&self, fmt: defmt::Formatter) { fn format(&self, fmt: defmt::Formatter) {
defmt::write!( defmt::write!(
@@ -98,20 +99,19 @@ pub struct AudioTelemetrySnapshot {
pub dac_underflow_count: u16, pub dac_underflow_count: u16,
pub usb_underflow_count: u16, pub usb_underflow_count: u16,
pub dac_overflow_count: u16, pub dac_overflow_count: u16,
pub cur_rate: u32, pub p: i32,
pub fb_rate_estimate: f32, pub i: i32,
pub fb: i32,
} }
pub mod hid { pub mod hid {
use deku::DekuRead; use deku::DekuRead;
use usbd_hid::descriptor::generator_prelude::*; use usbd_hid::descriptor::generator_prelude::*;
use crate::{AudioState, AudioTelemetrySnapshot}; #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// HID usage IDs identifying each vendor interface. `gen_hid_descriptor` only accepts use crate::{AudioState, AudioTelemetrySnapshot};
/// literals, so the descriptors below repeat these values; keep them in sync.
pub const USAGE_TELEMETRY: u16 = 0x01;
pub const USAGE_COMMAND: u16 = 0x02;
#[derive(DekuRead)] #[derive(DekuRead)]
#[deku(endian = "little")] #[deku(endian = "little")]
@@ -123,8 +123,10 @@ pub mod hid {
dac_underflow_count=input; dac_underflow_count=input;
usb_underflow_count=input; usb_underflow_count=input;
dac_overflow_count=input; dac_overflow_count=input;
cur_rate=input; p=input;
fb_rate_estimate=input; i=input;
fb=input;
integrator=input;
} }
)] )]
#[repr(C, packed)] #[repr(C, packed)]
@@ -136,8 +138,10 @@ pub mod hid {
pub dac_underflow_count: u16, pub dac_underflow_count: u16,
pub usb_underflow_count: u16, pub usb_underflow_count: u16,
pub dac_overflow_count: u16, pub dac_overflow_count: u16,
pub cur_rate: i32, pub p: i32,
pub fb_rate_estimate: i32, pub i: i32,
pub fb: i32,
pub integrator: i32,
} }
impl From<AudioTelemetryReport> for AudioTelemetrySnapshot { impl From<AudioTelemetryReport> for AudioTelemetrySnapshot {
@@ -145,164 +149,13 @@ pub mod hid {
AudioTelemetrySnapshot { AudioTelemetrySnapshot {
state: AudioState::try_from(value.state).expect("Invalid AudioState"), state: AudioState::try_from(value.state).expect("Invalid AudioState"),
average_buffer_fill: value.average_buffer_fill, average_buffer_fill: value.average_buffer_fill,
frame_count: value.frame_count.cast_unsigned(), // on firmware side is usize == u32 frame_count: i32::cast_unsigned(value.frame_count), // on firmware side is usize == u32
dac_underflow_count: value.dac_underflow_count, dac_underflow_count: value.dac_underflow_count,
usb_underflow_count: value.usb_underflow_count, usb_underflow_count: value.usb_underflow_count,
dac_overflow_count: value.dac_overflow_count, dac_overflow_count: value.dac_overflow_count,
cur_rate: value.cur_rate.cast_unsigned(), p: value.p,
fb_rate_estimate: (value.fb_rate_estimate as f32), i: value.i,
} fb: value.fb,
}
}
#[gen_hid_descriptor((collection = APPLICATION, usage_page = VENDOR_DEFINED_START, usage = 0x02, ) = {
cmd=feature;
resp=input;
})]
#[repr(C, packed)]
pub struct DeviceCommandReport {
pub cmd: [u8; 63],
pub resp: [u8; 64],
}
#[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,
][..]
);
}
}
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());
} }
} }
} }