Compare commits
18
Commits
e1d7be5e76
..
v0.3.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8917696367
|
||
|
|
cc92b55df4
|
||
|
|
27c8fa6a32
|
||
|
|
44679cda2c
|
||
|
|
7b49f116d4 | ||
|
|
fabacf0a04 | ||
|
|
e255636f3a | ||
|
|
bb7f701f20 | ||
|
|
245c45c682 | ||
|
|
93a20cf8e1
|
||
|
|
9d66ee6ab8
|
||
|
|
ef39602b63
|
||
|
|
34df570dda
|
||
|
|
bdd946ad11
|
||
|
|
31edf91933
|
||
|
|
ab09c98084
|
||
|
|
5e8d6e2a34
|
||
|
|
69511f4061
|
No files matched your search
@@ -0,0 +1,31 @@
|
|||||||
|
FROM ghcr.io/rust-cross/cargo-zigbuild:latest
|
||||||
|
|
||||||
|
# The base image may resolve its toolchain through $HOME, which the runner does not preserve for
|
||||||
|
# action containers, so pin it to a fixed path. entrypoint.sh re-exports this because the runner
|
||||||
|
# injects the workflow environment into action containers as well.
|
||||||
|
ENV RUSTUP_HOME=/usr/local/rustup
|
||||||
|
|
||||||
|
RUN if ! rustup default >/dev/null 2>&1; then \
|
||||||
|
rustup toolchain install stable --profile minimal --no-self-update; \
|
||||||
|
rustup default stable; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
# The image ships the toolchain, zig, a macOS SDK and cargo-zigbuild, but not the bits the build and
|
||||||
|
# packaging scripts need.
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends ca-certificates zip zstd \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Install every target up front so building needs no network access. `universal2-apple-darwin` is
|
||||||
|
# not a rustc target: cargo-zigbuild builds both architectures and merges them.
|
||||||
|
RUN rustup target install \
|
||||||
|
aarch64-unknown-linux-musl \
|
||||||
|
x86_64-unknown-linux-musl \
|
||||||
|
x86_64-pc-windows-gnu \
|
||||||
|
aarch64-apple-darwin \
|
||||||
|
x86_64-apple-darwin
|
||||||
|
|
||||||
|
COPY entrypoint.sh /entrypoint.sh
|
||||||
|
RUN chmod +x /entrypoint.sh
|
||||||
|
|
||||||
|
ENTRYPOINT ["/entrypoint.sh"]
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
name: Build guac CLI
|
||||||
|
description: Cross-compile the guac CLI with cargo-zigbuild and package the artifact
|
||||||
|
|
||||||
|
inputs:
|
||||||
|
target:
|
||||||
|
description: Rust target triple, or universal2-apple-darwin
|
||||||
|
required: true
|
||||||
|
|
||||||
|
runs:
|
||||||
|
using: docker
|
||||||
|
image: Dockerfile
|
||||||
|
args:
|
||||||
|
- ${{ inputs.target }}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
target="$1"
|
||||||
|
|
||||||
|
cd "${GITHUB_WORKSPACE:-$(pwd)}"
|
||||||
|
|
||||||
|
# The runner overrides env vars from the workflow for action containers, so re-assert the
|
||||||
|
# toolchain path the image installed to, and keep the registry in the workspace for caching.
|
||||||
|
export RUSTUP_HOME=/usr/local/rustup
|
||||||
|
export CARGO_HOME="${PWD}/.cargo-cache"
|
||||||
|
|
||||||
|
bin=guac-cli
|
||||||
|
case "$target" in
|
||||||
|
*windows*) bin=guac-cli.exe ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
(cd cli && cargo zigbuild --release --target "$target")
|
||||||
|
|
||||||
|
artifact="target/${target}/release/${bin}"
|
||||||
|
if [ ! -f "$artifact" ]; then
|
||||||
|
artifact="cli/${artifact}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p dist
|
||||||
|
zip -j "dist/guac-cli-${target}.zip" "$artifact"
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
name: Build and Release Firmware
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
firmware:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: catthehacker/ubuntu:rust-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: true
|
||||||
|
matrix:
|
||||||
|
variant: [cs4398, ak4490, evk]
|
||||||
|
# Job-scoped on purpose: the runner also injects workflow env into action containers, where it
|
||||||
|
# would override the cli image's own toolchain paths.
|
||||||
|
env:
|
||||||
|
FEATURES: ${{ matrix.variant }},hid
|
||||||
|
TARGET: thumbv8m.main-none-eabihf
|
||||||
|
# The catthehacker image installs rust here and only symlinks ~/.rustup and ~/.cargo to it.
|
||||||
|
# actions/cache archives the symlink, not its contents, so point at the real paths.
|
||||||
|
RUSTUP_HOME: /usr/share/rust/.rustup
|
||||||
|
CARGO_HOME: /usr/share/rust/.cargo
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- 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
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
target:
|
||||||
|
- aarch64-unknown-linux-musl
|
||||||
|
- x86_64-pc-windows-gnu
|
||||||
|
- x86_64-unknown-linux-musl
|
||||||
|
- universal2-apple-darwin
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# Building and packaging both happen in .gitea/actions/cli-build, whose image the runner
|
||||||
|
# builds from its Dockerfile and keeps in the Docker layer cache. That image carries the
|
||||||
|
# toolchain, zig, the macOS SDK and every target, so none of that is installed per job.
|
||||||
|
- name: Cache cargo registry
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: .cargo-cache
|
||||||
|
key: cli-registry-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
restore-keys: cli-registry-
|
||||||
|
|
||||||
|
- name: Cache build artifacts
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: target
|
||||||
|
key: cli-target-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
restore-keys: cli-target-${{ matrix.target }}-
|
||||||
|
|
||||||
|
- name: Build cli (${{ matrix.target }})
|
||||||
|
uses: ./.gitea/actions/cli-build
|
||||||
|
with:
|
||||||
|
target: ${{ matrix.target }}
|
||||||
|
|
||||||
|
- name: Upload artifact
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: cli-${{ matrix.target }}
|
||||||
|
path: dist/*.zip
|
||||||
|
|
||||||
|
release:
|
||||||
|
needs: [firmware, cli]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: catthehacker/ubuntu:act-latest
|
||||||
|
steps:
|
||||||
|
- name: Download artifacts
|
||||||
|
uses: actions/download-artifact@v3
|
||||||
|
with:
|
||||||
|
path: dist
|
||||||
|
|
||||||
|
- name: Create Gitea Release
|
||||||
|
uses: akkuman/gitea-release-action@v1
|
||||||
|
with:
|
||||||
|
files: dist/**/*.zip
|
||||||
|
draft: false
|
||||||
|
prerelease: false
|
||||||
@@ -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 cli -p shared
|
entry: cargo check -p guac-cli -p shared
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
types: [file, rust]
|
types: [file, rust]
|
||||||
language: system
|
language: system
|
||||||
|
|||||||
Generated
+897
-283
File diff suppressed because it is too large.
Load diff
+12
-4
@@ -1,11 +1,19 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "cli"
|
name = "guac-cli"
|
||||||
version = "0.1.0"
|
version = "0.3.2"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-hid = "0.5.1"
|
async-hid = "0.5.1"
|
||||||
|
clap = { version = "4.6.1", features = ["derive"] }
|
||||||
|
colog = "1.4.0"
|
||||||
|
csv = "1.4.0"
|
||||||
|
ctrlc = "3.5.2"
|
||||||
deku = "0.20.3"
|
deku = "0.20.3"
|
||||||
futures-lite = "2.6.1"
|
futures-lite = "2.6.1"
|
||||||
pollster = { version = "0.4.0", features = ["macro"] }
|
log = { version = "0.4.29", features = ["std"] }
|
||||||
shared = { path = "../shared" }
|
serde_json = "1.0.154"
|
||||||
|
shared = { path = "../shared", features = ["serde", "std"] }
|
||||||
|
smol = "2.0.2"
|
||||||
|
smol-macros = "0.1.1"
|
||||||
|
smol-timeout = "0.6.1"
|
||||||
+846
-13
@@ -1,27 +1,860 @@
|
|||||||
use async_hid::{AsyncHidRead, HidBackend, HidResult};
|
use smol_macros::main;
|
||||||
|
use std::{
|
||||||
|
io,
|
||||||
|
str::FromStr,
|
||||||
|
sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
|
},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
|
use async_hid::{
|
||||||
|
AsyncHidFeatureHandle, AsyncHidRead, Device, DeviceFeatureHandle, DeviceReader, HidBackend,
|
||||||
|
HidError, HidResult,
|
||||||
|
};
|
||||||
|
use clap::{Parser, Subcommand, ValueEnum};
|
||||||
use deku::DekuContainerRead;
|
use deku::DekuContainerRead;
|
||||||
use futures_lite::StreamExt;
|
use futures_lite::StreamExt;
|
||||||
use shared::hid::AudioTelemetryReport;
|
use shared::{
|
||||||
|
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;
|
||||||
|
|
||||||
#[pollster::main]
|
#[derive(Clone, Copy, Debug, ValueEnum)]
|
||||||
async fn main() -> HidResult<()> {
|
enum Format {
|
||||||
let usbhid = HidBackend::default();
|
Debug,
|
||||||
let dev = usbhid
|
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)]
|
||||||
|
#[command(
|
||||||
|
version,
|
||||||
|
about = "Interact with GUAC UAC2 devices",
|
||||||
|
arg_required_else_help = true
|
||||||
|
)]
|
||||||
|
struct Args {
|
||||||
|
#[arg(short, long, default_value = "1209:cc1d")]
|
||||||
|
/// USB device ID to operate on, format `1209:cc1d` (vendor:product, hex)
|
||||||
|
device: UsbVidPid,
|
||||||
|
#[command(subcommand)]
|
||||||
|
command: Option<Command>,
|
||||||
|
}
|
||||||
|
|
||||||
|
trait StateEmitter {
|
||||||
|
fn emit(&mut self, r: &AudioTelemetrySnapshot);
|
||||||
|
fn close(&mut self) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct DebugEmitter<T: io::Write> {
|
||||||
|
writer: T,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: io::Write> DebugEmitter<W> {
|
||||||
|
fn new(writer: W) -> Self {
|
||||||
|
Self { writer }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: io::Write> StateEmitter for DebugEmitter<W> {
|
||||||
|
fn emit(&mut self, r: &AudioTelemetrySnapshot) {
|
||||||
|
writeln!(self.writer, "{r:?}").ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct CsvEmitter<W: io::Write> {
|
||||||
|
csv: csv::Writer<W>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: io::Write> CsvEmitter<W> {
|
||||||
|
fn new(writer: W) -> Self {
|
||||||
|
Self {
|
||||||
|
csv: csv::Writer::from_writer(writer),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: io::Write> StateEmitter for CsvEmitter<W> {
|
||||||
|
fn emit(&mut self, r: &AudioTelemetrySnapshot) {
|
||||||
|
if let Err(e) = self.csv.serialize(r) {
|
||||||
|
eprintln!("Serialization error: {e:?}");
|
||||||
|
} else {
|
||||||
|
self.csv.flush().ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct JsonEmitter<W: io::Write> {
|
||||||
|
writer: W,
|
||||||
|
first: bool,
|
||||||
|
}
|
||||||
|
impl<W: io::Write> JsonEmitter<W> {
|
||||||
|
fn new(mut writer: W) -> Self {
|
||||||
|
if let Err(e) = write!(writer, "[") {
|
||||||
|
eprintln!("Write error: {e:?}")
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
writer,
|
||||||
|
first: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
.enumerate()
|
||||||
.await?
|
.await?
|
||||||
.find(|d| d.product_id == 0xcc1d && d.vendor_id == 0x1209)
|
.find(|d| d.product_id == vidpid.pid && d.vendor_id == vidpid.vid && d.usage_id == usage_id)
|
||||||
.await
|
.await;
|
||||||
.expect("GUAC device not found or not accessible (try as root?)");
|
|
||||||
let mut reader = dev.open_readable().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 mut buf = [0u8; core::mem::size_of::<AudioTelemetryReport>()];
|
||||||
while let Ok(r) = reader.read_input_report(&mut buf).await {
|
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];
|
let buf = &buf[..r];
|
||||||
match AudioTelemetryReport::from_bytes((buf, 0)) {
|
match AudioTelemetryReport::from_bytes((buf, 0)) {
|
||||||
Ok((_, r)) => println!("{:?}", r),
|
Ok((_, r)) => Ok(r),
|
||||||
Err(e) => eprintln!("Unable to parse report: {:?}", e),
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn read_header_report(
|
||||||
|
reader: &mut DeviceReader,
|
||||||
|
) -> HidResult<([u8; IN_REPORT_SIZE], Header)> {
|
||||||
|
let mut report = [0u8; IN_REPORT_SIZE];
|
||||||
|
let len = reader
|
||||||
|
.read_input_report(&mut report)
|
||||||
|
.timeout(Duration::from_secs(2))
|
||||||
|
.await
|
||||||
|
.ok_or_else(|| HidError::message("timed out waiting for device response"))??;
|
||||||
|
|
||||||
|
let header =
|
||||||
|
Header::parse(&report[..len]).ok_or_else(|| HidError::message("invalid HID response"))?;
|
||||||
|
|
||||||
|
log::debug!("rx {:?}: {:02x?}", header, &report[..len]);
|
||||||
|
|
||||||
|
if HEADER_LEN + usize::from(header.len) > len {
|
||||||
|
log::error!(
|
||||||
|
"invalid response length: header {} in {} bytes",
|
||||||
|
header.len,
|
||||||
|
len
|
||||||
|
);
|
||||||
|
return Err(HidError::message("invalid HID response length"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((report, header))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn nack_error(code: Option<NackCode>) -> HidError {
|
||||||
|
HidError::message(match code {
|
||||||
|
Some(code) => format!("device rejected command: {code:?}"),
|
||||||
|
None => "device rejected command".to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn wait_ack(reader: &mut DeviceReader, seq: u8) -> HidResult<()> {
|
||||||
|
log::debug!("waiting for ACK seq={}", seq);
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let (report, header) = read_header_report(reader).await?;
|
||||||
|
|
||||||
|
if header.seq != seq {
|
||||||
|
log::debug!("ignoring stale response for seq={}", header.seq);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
match ResponseKind::try_from(header.kind) {
|
||||||
|
Ok(ResponseKind::Ack) => {
|
||||||
|
log::info!("acknowledged seq={}", seq);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Ok(ResponseKind::Nack) => {
|
||||||
|
let code = report
|
||||||
|
.get(HEADER_LEN)
|
||||||
|
.copied()
|
||||||
|
.and_then(|byte| NackCode::try_from(byte).ok());
|
||||||
|
log::error!("nack seq={} code={:?}", seq, code);
|
||||||
|
return Err(nack_error(code));
|
||||||
|
}
|
||||||
|
Ok(ResponseKind::Noop) => continue,
|
||||||
|
Ok(ResponseKind::ConfigData) | Ok(ResponseKind::Hardware) => {
|
||||||
|
log::error!("expected ACK seq={} but got data", seq);
|
||||||
|
return Err(HidError::message("unexpected data"));
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
log::error!("invalid response kind {}", header.kind);
|
||||||
|
return Err(HidError::message("invalid response kind"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_message(
|
||||||
|
reader: &mut DeviceReader,
|
||||||
|
seq: u8,
|
||||||
|
expected: ResponseKind,
|
||||||
|
) -> HidResult<Vec<u8>> {
|
||||||
|
let mut data = Vec::new();
|
||||||
|
let mut total_len = None;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let (report, header) = read_header_report(reader).await?;
|
||||||
|
|
||||||
|
if header.seq != seq {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
match ResponseKind::try_from(header.kind) {
|
||||||
|
Ok(kind) if kind == expected => {
|
||||||
|
let offset = usize::from(header.offset);
|
||||||
|
let len = usize::from(header.len);
|
||||||
|
let total = usize::from(header.total_len);
|
||||||
|
|
||||||
|
if len > IN_PAYLOAD_LEN || offset != data.len() || data.len() + len > total {
|
||||||
|
log::error!(
|
||||||
|
"invalid chunk: offset={} len={} total={} received={}",
|
||||||
|
offset,
|
||||||
|
len,
|
||||||
|
total,
|
||||||
|
data.len()
|
||||||
|
);
|
||||||
|
return Err(HidError::message("invalid response chunk"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(existing) = total_len
|
||||||
|
&& existing != total
|
||||||
|
{
|
||||||
|
log::error!("inconsistent response length: {} != {}", existing, total);
|
||||||
|
return Err(HidError::message("inconsistent response length"));
|
||||||
|
}
|
||||||
|
total_len = Some(total);
|
||||||
|
|
||||||
|
log::debug!(
|
||||||
|
"rx chunk seq={} offset={}/{} len={}",
|
||||||
|
seq,
|
||||||
|
offset,
|
||||||
|
total,
|
||||||
|
len
|
||||||
|
);
|
||||||
|
|
||||||
|
data.extend_from_slice(&report[HEADER_LEN..HEADER_LEN + len]);
|
||||||
|
|
||||||
|
if data.len() == total {
|
||||||
|
log::info!("received {} bytes seq={}", data.len(), seq);
|
||||||
|
return Ok(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(ResponseKind::Nack) => {
|
||||||
|
let code = report
|
||||||
|
.get(HEADER_LEN)
|
||||||
|
.copied()
|
||||||
|
.and_then(|byte| NackCode::try_from(byte).ok());
|
||||||
|
log::error!("nack seq={} code={:?}", seq, code);
|
||||||
|
return Err(nack_error(code));
|
||||||
|
}
|
||||||
|
Ok(ResponseKind::Ack) | Ok(ResponseKind::Noop) => continue,
|
||||||
|
Ok(kind) => {
|
||||||
|
log::error!("unexpected response {:?}, wanted {:?}", kind, expected);
|
||||||
|
return Err(HidError::message("unexpected response"));
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
log::error!("invalid response kind {}", header.kind);
|
||||||
|
return Err(HidError::message("invalid response kind"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_config(
|
||||||
|
reader: &mut DeviceReader,
|
||||||
|
handle: &mut DeviceFeatureHandle,
|
||||||
|
seq: u8,
|
||||||
|
) -> HidResult<ConfigSnapshot> {
|
||||||
|
send_command(handle, seq, CommandKind::ReadConfig, &[]).await?;
|
||||||
|
let data = read_message(reader, seq, ResponseKind::ConfigData).await?;
|
||||||
|
|
||||||
|
let snapshot = ConfigSnapshot::parse(&data)
|
||||||
|
.map_err(|error| HidError::message(format!("invalid config: {error}")))?;
|
||||||
|
|
||||||
|
log::info!(
|
||||||
|
"config from slot {} ({} tags)",
|
||||||
|
snapshot.active_slot,
|
||||||
|
snapshot.config.tlvs.len()
|
||||||
|
);
|
||||||
|
log::debug!("config tlvs: {:?}", snapshot.config.tlvs);
|
||||||
|
|
||||||
|
Ok(snapshot)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn replace_tlv(
|
||||||
|
reader: &mut DeviceReader,
|
||||||
|
handle: &mut DeviceFeatureHandle,
|
||||||
|
seq: u8,
|
||||||
|
tag: ConfigTag,
|
||||||
|
value: &[u8],
|
||||||
|
) -> HidResult<()> {
|
||||||
|
let mut payload = Vec::with_capacity(2 + value.len());
|
||||||
|
payload.extend_from_slice(&tag.0.to_le_bytes());
|
||||||
|
payload.extend_from_slice(value);
|
||||||
|
|
||||||
|
log::info!("setting {:?} ({} bytes)", tag, value.len());
|
||||||
|
log::debug!("value for {:?}: {:02x?}", tag, value);
|
||||||
|
|
||||||
|
send_command(handle, seq, CommandKind::ReplaceTlv, &payload).await?;
|
||||||
|
wait_ack(reader, seq).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_hardware(
|
||||||
|
reader: &mut DeviceReader,
|
||||||
|
handle: &mut DeviceFeatureHandle,
|
||||||
|
) -> HidResult<HardwareInfo> {
|
||||||
|
send_command(handle, 0, CommandKind::Hardware, &[])
|
||||||
|
.await
|
||||||
|
.map_err(|error| HidError::message(format!("hardware command write failed: {error}")))?;
|
||||||
|
let data = read_message(reader, 0, ResponseKind::Hardware)
|
||||||
|
.await
|
||||||
|
.map_err(|error| HidError::message(format!("hardware data failed: {error}")))?;
|
||||||
|
|
||||||
|
let info = HardwareInfo::parse(&data)
|
||||||
|
.map_err(|error| HidError::message(format!("invalid hardware info: {error}")))?;
|
||||||
|
|
||||||
|
log::debug!(
|
||||||
|
"hardware: uuid={:02x?} dac={:?} firmware={:?}",
|
||||||
|
&info.uuid[..],
|
||||||
|
info.dac.as_str(),
|
||||||
|
info.version.as_str()
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(info)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commands are written as feature reports over the control pipe; replies arrive on the interrupt
|
||||||
|
/// IN endpoint.
|
||||||
|
async fn open_command(dev: &Device) -> HidResult<(DeviceReader, DeviceFeatureHandle)> {
|
||||||
|
log::debug!("opening command interface");
|
||||||
|
|
||||||
|
Ok((dev.open_readable().await?, dev.open_feature_handle().await?))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tlv_u16(tlvs: &TlvList, tag: ConfigTag) -> Option<u16> {
|
||||||
|
let value = tlvs.find(tag)?.value.as_slice();
|
||||||
|
(value.len() == 2).then(|| u16::from_le_bytes([value[0], value[1]]))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_hex(name: &str, tag: ConfigTag, value: &[u8]) {
|
||||||
|
print!("{name} (0x{:04x}):", tag.0);
|
||||||
|
|
||||||
|
for byte in value {
|
||||||
|
print!(" {byte:02x}");
|
||||||
|
}
|
||||||
|
|
||||||
|
println!();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_config(snapshot: &ConfigSnapshot) {
|
||||||
|
println!("Active slot: {}", snapshot.active_slot);
|
||||||
|
|
||||||
|
for tlv in snapshot.config.tlvs.iter() {
|
||||||
|
let name = tlv.tag.name().unwrap_or("Unknown");
|
||||||
|
let value = tlv.value.as_slice();
|
||||||
|
|
||||||
|
if tlv.tag == tags::VENDOR_ID || tlv.tag == tags::PRODUCT_ID {
|
||||||
|
match value {
|
||||||
|
[lo, hi] => println!(
|
||||||
|
"{name} (0x{:04x}): 0x{:04x}",
|
||||||
|
tlv.tag.0,
|
||||||
|
u16::from_le_bytes([*lo, *hi])
|
||||||
|
),
|
||||||
|
_ => print_hex(name, tlv.tag, value),
|
||||||
|
}
|
||||||
|
} else if tlv.tag == tags::MANUF_STRING
|
||||||
|
|| tlv.tag == tags::PRODUCT_STRING
|
||||||
|
|| tlv.tag == tags::SERIAL_STRING
|
||||||
|
{
|
||||||
|
match core::str::from_utf8(value) {
|
||||||
|
Ok(value) => println!("{name} (0x{:04x}): {value:?}", tlv.tag.0),
|
||||||
|
Err(_) => print_hex(name, tlv.tag, value),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
print_hex(name, tlv.tag, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn show_config(device: &UsbVidPid) -> HidResult<()> {
|
||||||
|
let dev = find_device(device, USAGE_COMMAND).await?;
|
||||||
|
let (mut reader, mut handle) = open_command(&dev).await?;
|
||||||
|
let snapshot = read_config(&mut reader, &mut handle, 0).await?;
|
||||||
|
|
||||||
|
log::info!("printing configuration");
|
||||||
|
print_config(&snapshot);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn show_hardware(device: &UsbVidPid) -> HidResult<()> {
|
||||||
|
let dev = find_device(device, USAGE_COMMAND).await?;
|
||||||
|
let (mut reader, mut handle) = open_command(&dev).await?;
|
||||||
|
let info = read_hardware(&mut reader, &mut handle).await?;
|
||||||
|
|
||||||
|
log::info!("printing hardware info");
|
||||||
|
print!("UUID: ");
|
||||||
|
for byte in info.uuid {
|
||||||
|
print!("{byte:02X}");
|
||||||
|
}
|
||||||
|
println!();
|
||||||
|
println!("DAC: {}", info.dac.as_str());
|
||||||
|
println!("Firmware: {}", info.version.as_str());
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn apply_config(device: &UsbVidPid, args: &ConfigArgs) -> HidResult<()> {
|
||||||
|
if args.reset {
|
||||||
|
return reset_config(device).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let dev = find_device(device, USAGE_COMMAND).await?;
|
||||||
|
let (mut reader, mut handle) = open_command(&dev).await?;
|
||||||
|
|
||||||
|
let current = read_config(&mut reader, &mut handle, 0).await?;
|
||||||
|
let mut expected = current.config.tlvs.clone();
|
||||||
|
let mut replacements: Vec<(ConfigTag, Vec<u8>)> = Vec::new();
|
||||||
|
|
||||||
|
if let Some(value) = args.vendor_id {
|
||||||
|
replacements.push((tags::VENDOR_ID, value.to_le_bytes().to_vec()));
|
||||||
|
}
|
||||||
|
if let Some(value) = args.product_id {
|
||||||
|
replacements.push((tags::PRODUCT_ID, value.to_le_bytes().to_vec()));
|
||||||
|
}
|
||||||
|
if let Some(value) = &args.manufacturer {
|
||||||
|
replacements.push((tags::MANUF_STRING, value.as_bytes().to_vec()));
|
||||||
|
}
|
||||||
|
if let Some(value) = &args.product {
|
||||||
|
replacements.push((tags::PRODUCT_STRING, value.as_bytes().to_vec()));
|
||||||
|
}
|
||||||
|
if let Some(value) = &args.serial {
|
||||||
|
replacements.push((tags::SERIAL_STRING, value.as_bytes().to_vec()));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (tag, value) in &replacements {
|
||||||
|
let value = ConfigBytes::from_slice(value)
|
||||||
|
.map_err(|error| HidError::message(format!("invalid value for {tag:?}: {error}")))?;
|
||||||
|
expected
|
||||||
|
.upsert(Tlv { tag: *tag, value })
|
||||||
|
.map_err(|error| HidError::message(format!("config too large: {error}")))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
DeviceConfig::from_tlvs(&expected)
|
||||||
|
.map_err(|error| HidError::message(format!("invalid configuration: {error}")))?;
|
||||||
|
|
||||||
|
log::info!("applying {} change(s)", replacements.len());
|
||||||
|
|
||||||
|
let mut seq = 1u8;
|
||||||
|
for (tag, value) in &replacements {
|
||||||
|
replace_tlv(&mut reader, &mut handle, seq, *tag, value).await?;
|
||||||
|
seq = seq.wrapping_add(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
log::info!("committing configuration to flash");
|
||||||
|
send_command(&mut handle, seq, CommandKind::CommitConfig, &[]).await?;
|
||||||
|
wait_ack(&mut reader, seq).await?;
|
||||||
|
|
||||||
|
drop(reader);
|
||||||
|
drop(handle);
|
||||||
|
drop(dev);
|
||||||
|
|
||||||
|
let expected_device = device_for(&expected)?;
|
||||||
|
let slot = await_config(expected_device, &expected).await?;
|
||||||
|
|
||||||
|
println!("Configuration updated successfully (active slot {slot}).");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn reset_config(device: &UsbVidPid) -> HidResult<()> {
|
||||||
|
let dev = find_device(device, USAGE_COMMAND).await?;
|
||||||
|
let (mut reader, mut handle) = open_command(&dev).await?;
|
||||||
|
|
||||||
|
let info = read_hardware(&mut reader, &mut handle).await?;
|
||||||
|
let defaults = DeviceConfig::with_defaults(DeviceConfig::serial_from_uuid(&info.uuid))
|
||||||
|
.map_err(|error| HidError::message(format!("invalid default configuration: {error}")))?;
|
||||||
|
let expected = defaults
|
||||||
|
.to_tlvs()
|
||||||
|
.map_err(|error| HidError::message(format!("invalid default configuration: {error}")))?;
|
||||||
|
|
||||||
|
log::info!("restoring default configuration");
|
||||||
|
send_command(&mut handle, 0, CommandKind::ResetConfig, &[]).await?;
|
||||||
|
wait_ack(&mut reader, 0).await?;
|
||||||
|
|
||||||
|
drop(reader);
|
||||||
|
drop(handle);
|
||||||
|
drop(dev);
|
||||||
|
|
||||||
|
let expected_device = device_for(&expected)?;
|
||||||
|
let slot = await_config(expected_device, &expected).await?;
|
||||||
|
|
||||||
|
println!("Configuration reset to defaults (active slot {slot}).");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn device_for(tlvs: &TlvList) -> HidResult<UsbVidPid> {
|
||||||
|
Ok(UsbVidPid {
|
||||||
|
vid: tlv_u16(tlvs, tags::VENDOR_ID)
|
||||||
|
.ok_or_else(|| HidError::message("missing vendor id"))?,
|
||||||
|
pid: tlv_u16(tlvs, tags::PRODUCT_ID)
|
||||||
|
.ok_or_else(|| HidError::message("missing product id"))?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Waits for the device to come back with `expected_device` and report exactly `expected`.
|
||||||
|
async fn await_config(expected_device: UsbVidPid, expected: &TlvList) -> HidResult<u8> {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(10);
|
||||||
|
|
||||||
|
log::info!(
|
||||||
|
"waiting for device to restart as {:04x}:{:04x}",
|
||||||
|
expected_device.vid,
|
||||||
|
expected_device.pid
|
||||||
|
);
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if let Some(dev) = try_find_device(&expected_device, USAGE_COMMAND).await?
|
||||||
|
&& let Ok((mut reader, mut handle)) = open_command(&dev).await
|
||||||
|
&& let Ok(snapshot) = read_config(&mut reader, &mut handle, 0).await
|
||||||
|
&& snapshot.config.tlvs == *expected
|
||||||
|
{
|
||||||
|
log::info!("configuration verified in slot {}", snapshot.active_slot);
|
||||||
|
return Ok(snapshot.active_slot);
|
||||||
|
}
|
||||||
|
|
||||||
|
if Instant::now() >= deadline {
|
||||||
|
log::error!("configuration verification timed out");
|
||||||
|
return Err(HidError::message("configuration verification failed"));
|
||||||
|
}
|
||||||
|
|
||||||
|
log::debug!("device not ready yet, retrying");
|
||||||
|
smol::Timer::after(Duration::from_millis(200)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main! {
|
||||||
|
async fn main() -> HidResult<()> {
|
||||||
|
colog::init();
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
match &args.command {
|
||||||
|
Some(Command::Monitor { format, count }) => {
|
||||||
|
log::info!("monitoring telemetry");
|
||||||
|
let dev = find_device(&args.device, USAGE_TELEMETRY).await?;
|
||||||
|
let reader = dev.open_readable().await?;
|
||||||
|
let writer: Box<dyn StateEmitter> = match format {
|
||||||
|
Format::Debug => Box::new(DebugEmitter::new(io::stdout())),
|
||||||
|
Format::Csv => Box::new(CsvEmitter::new(io::stdout())),
|
||||||
|
Format::Json => Box::new(JsonEmitter::new(io::stdout())),
|
||||||
|
};
|
||||||
|
|
||||||
|
let 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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-6
@@ -1,24 +1,26 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "guac"
|
name = "guac"
|
||||||
version = "0.1.0"
|
version = "0.3.2"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["nodac", "hid"]
|
default = ["evk", "hid"]
|
||||||
ak4490 = []
|
ak4490 = []
|
||||||
cs4398 = []
|
cs4398 = []
|
||||||
nodac = []
|
nodac = []
|
||||||
hid = [ "dep:usbd-hid", "dep:shared" ]
|
wm8904 = []
|
||||||
|
hid = ["dep:usbd-hid", "dep:deku"]
|
||||||
|
evk = ["wm8904"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
shared = { path="../shared", optional = true }
|
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"
|
||||||
@@ -30,7 +32,8 @@ 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.0", 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"
|
||||||
|
|||||||
+48
-3
@@ -1,5 +1,50 @@
|
|||||||
// Find the actual path of memory.x and add it to link search, required for building in workspace
|
use std::{env, path::Path, process::Command};
|
||||||
|
|
||||||
|
/// Paths that change when `HEAD`, a branch, or a tag moves. `HEAD` itself is only rewritten on
|
||||||
|
/// checkout, so commits are tracked through the reflog and the ref directories.
|
||||||
|
const GIT_WATCH: [&str; 5] = [
|
||||||
|
"../.git/HEAD",
|
||||||
|
"../.git/logs/HEAD",
|
||||||
|
"../.git/refs/heads",
|
||||||
|
"../.git/refs/tags",
|
||||||
|
"../.git/packed-refs",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn git_output(args: &[&str], dir: &str) -> Option<String> {
|
||||||
|
let output = Command::new("git")
|
||||||
|
.args(["-C", dir])
|
||||||
|
.args(args)
|
||||||
|
.output()
|
||||||
|
.ok()?;
|
||||||
|
|
||||||
|
if !output.status.success() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let value = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||||
|
(!value.is_empty()).then_some(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn firmware_version(dir: &str) -> String {
|
||||||
|
git_output(&["describe", "--tags", "--exact-match", "HEAD"], dir)
|
||||||
|
.or_else(|| git_output(&["rev-parse", "--short=12", "HEAD"], dir))
|
||||||
|
.unwrap_or_else(|| env::var("CARGO_PKG_VERSION").unwrap_or_else(|_| "unknown".to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
|
if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
|
||||||
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+6
-1
@@ -1,6 +1,7 @@
|
|||||||
MEMORY
|
MEMORY
|
||||||
{
|
{
|
||||||
FLASH : ORIGIN = 0x00000000, LENGTH = 512K
|
FLASH : ORIGIN = 0x00000000 , LENGTH = 512K - 32K
|
||||||
|
CONFIG : ORIGIN = 0x00000000 + 512K - 32K, LENGTH = 32K
|
||||||
|
|
||||||
/* for use with standard link.x */
|
/* for use with standard link.x */
|
||||||
RAM : ORIGIN = 0x20000000, LENGTH = 192K
|
RAM : ORIGIN = 0x20000000, LENGTH = 192K
|
||||||
@@ -19,3 +20,7 @@ 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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,373 @@
|
|||||||
|
use lpc55_hal as hal;
|
||||||
|
|
||||||
|
use hal::{FlashGordon, drivers::flash::GenericArray, raw as pac, traits::flash::WriteErase};
|
||||||
|
use shared::config::{
|
||||||
|
ConfigContainer, ConfigString, ConfigV1, ConfigVersion, DeviceConfig, TlvList,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{CONFIG_RESERVED, CONFIG_SLOT_COUNT, FLASH_PAGE_SIZE, SLOT_SIZE, config_base};
|
||||||
|
|
||||||
|
const SLOT_MAGIC: u32 = u32::from_le_bytes(*b"SLOT");
|
||||||
|
|
||||||
|
const FLASH_WORD_SIZE: usize = 16;
|
||||||
|
const READ_SINGLE_WORD: u32 = 0x3;
|
||||||
|
const READ_ECC_OFF: u32 = 1 << 2;
|
||||||
|
const COMMAND_TIMEOUT: u32 = 1_000_000;
|
||||||
|
|
||||||
|
static mut CONFIG_BUF: [u8; SLOT_SIZE] = [0u8; SLOT_SIZE];
|
||||||
|
|
||||||
|
#[cfg(feature = "hid")]
|
||||||
|
pub struct ConfigState {
|
||||||
|
pub running: DeviceConfig,
|
||||||
|
pub active_slot: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "hid")]
|
||||||
|
pub struct FlashState {
|
||||||
|
pub flash: FlashGordon,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, defmt::Format)]
|
||||||
|
enum FlashError {
|
||||||
|
IllegalCommand,
|
||||||
|
Failed,
|
||||||
|
Timeout,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn halt() -> ! {
|
||||||
|
loop {
|
||||||
|
cortex_m::asm::wfi();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn slot_page_address() -> usize {
|
||||||
|
config_base()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn slot_address(index: usize) -> usize {
|
||||||
|
config_base() + CONFIG_RESERVED + index * SLOT_SIZE
|
||||||
|
}
|
||||||
|
|
||||||
|
// The spare page in the reserved area, used to carry a boot request across a reset.
|
||||||
|
const BOOT_REQUEST_MAGIC: u32 = u32::from_le_bytes(*b"BOOT");
|
||||||
|
|
||||||
|
fn boot_request_address() -> usize {
|
||||||
|
config_base() + FLASH_PAGE_SIZE
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes a boot request and resets. The next boot hands over to the ROM before configuring
|
||||||
|
/// anything, which is the only way it gets a chip that is still in its reset state.
|
||||||
|
#[cfg(feature = "hid")]
|
||||||
|
pub fn request_bootloader(state: &mut FlashState) -> Result<(), ()> {
|
||||||
|
defmt::info!("config: requesting bootloader");
|
||||||
|
|
||||||
|
cortex_m::interrupt::free(|_| {
|
||||||
|
slow_clock_for_flash();
|
||||||
|
|
||||||
|
let address = boot_request_address();
|
||||||
|
let mut page = [0xffu8; FLASH_PAGE_SIZE];
|
||||||
|
page[..4].copy_from_slice(&BOOT_REQUEST_MAGIC.to_le_bytes());
|
||||||
|
|
||||||
|
if state.flash.erase_page(address / FLASH_PAGE_SIZE).is_err() {
|
||||||
|
defmt::error!("config: boot request erase failed");
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if state
|
||||||
|
.flash
|
||||||
|
.write_native(address, GenericArray::from_slice(&page))
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
defmt::error!("config: boot request write failed");
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// Let the probe client drain RTT before the reset tears it down.
|
||||||
|
cortex_m::asm::delay(15_000_000);
|
||||||
|
|
||||||
|
cortex_m::peripheral::SCB::sys_reset()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Consumes a pending boot request, clearing it first so a hand-off that fails to enter ISP cannot
|
||||||
|
/// cause a boot loop.
|
||||||
|
pub fn take_bootloader_request(flash: &mut FlashGordon) -> bool {
|
||||||
|
slow_clock_for_flash();
|
||||||
|
|
||||||
|
let address = boot_request_address();
|
||||||
|
let mut word = [0u8; FLASH_WORD_SIZE];
|
||||||
|
|
||||||
|
if read_flash(address, &mut word).is_err() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if u32::from_le_bytes([word[0], word[1], word[2], word[3]]) != BOOT_REQUEST_MAGIC {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if flash.erase_page(address / FLASH_PAGE_SIZE).is_err() {
|
||||||
|
defmt::error!("config: boot request clear failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
defmt::info!("config: boot request found");
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config_buf() -> &'static mut [u8; SLOT_SIZE] {
|
||||||
|
// Safety: flash access is not reentrant and the buffer is only borrowed for one operation at a time.
|
||||||
|
unsafe { &mut *core::ptr::addr_of_mut!(CONFIG_BUF) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_word(
|
||||||
|
flash: &pac::flash::RegisterBlock,
|
||||||
|
address: usize,
|
||||||
|
) -> Result<[u8; FLASH_WORD_SIZE], FlashError> {
|
||||||
|
flash.int_clr_status.write(|w| {
|
||||||
|
w.done()
|
||||||
|
.set_bit()
|
||||||
|
.ecc_err()
|
||||||
|
.set_bit()
|
||||||
|
.err()
|
||||||
|
.set_bit()
|
||||||
|
.fail()
|
||||||
|
.set_bit()
|
||||||
|
});
|
||||||
|
flash
|
||||||
|
.starta
|
||||||
|
.write(|w| unsafe { w.starta().bits((address / FLASH_WORD_SIZE) as u32) });
|
||||||
|
flash.dataw[0].write(|w| unsafe { w.bits(READ_ECC_OFF) });
|
||||||
|
flash.cmd.write(|w| unsafe { w.bits(READ_SINGLE_WORD) });
|
||||||
|
|
||||||
|
let mut timeout = COMMAND_TIMEOUT;
|
||||||
|
|
||||||
|
while flash.int_status.read().done().bit_is_clear() {
|
||||||
|
timeout -= 1;
|
||||||
|
|
||||||
|
if timeout == 0 {
|
||||||
|
return Err(FlashError::Timeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let status = flash.int_status.read();
|
||||||
|
|
||||||
|
if status.err().bit_is_set() {
|
||||||
|
return Err(FlashError::IllegalCommand);
|
||||||
|
}
|
||||||
|
|
||||||
|
if status.fail().bit_is_set() {
|
||||||
|
return Err(FlashError::Failed);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut word = [0u8; FLASH_WORD_SIZE];
|
||||||
|
|
||||||
|
for (chunk, register) in word.chunks_mut(4).zip(flash.dataw.iter()) {
|
||||||
|
chunk.copy_from_slice(®ister.read().bits().to_ne_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(word)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_flash(address: usize, buf: &mut [u8]) -> Result<(), FlashError> {
|
||||||
|
// Safety: the flash controller registers are only ever accessed here and in the HAL, never concurrently.
|
||||||
|
let flash = unsafe { &*pac::FLASH::ptr() };
|
||||||
|
|
||||||
|
for (index, chunk) in buf.chunks_mut(FLASH_WORD_SIZE).enumerate() {
|
||||||
|
let word = read_word(flash, address + index * FLASH_WORD_SIZE)?;
|
||||||
|
chunk.copy_from_slice(&word[..chunk.len()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_active_slot() -> Option<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)
|
||||||
|
}
|
||||||
@@ -61,6 +61,11 @@ 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();
|
||||||
@@ -69,18 +74,22 @@ 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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,6 +50,11 @@ 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();
|
||||||
|
|||||||
@@ -7,6 +7,10 @@ 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) {}
|
||||||
|
|||||||
@@ -0,0 +1,262 @@
|
|||||||
|
use crate::{CodecPins, traits::Dac};
|
||||||
|
use embedded_hal::prelude::{
|
||||||
|
_embedded_hal_blocking_i2c_Write, _embedded_hal_blocking_i2c_WriteRead,
|
||||||
|
};
|
||||||
|
const WM8904_I2C_ADDRESS: u8 = 0b0011010;
|
||||||
|
const MCLK: u32 = 24576000 / 2; // assume EVK TODO: better
|
||||||
|
|
||||||
|
#[repr(u8)]
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
enum RegisterAddress {
|
||||||
|
SwResetId = 0x00,
|
||||||
|
BiasControl0 = 0x04,
|
||||||
|
VmidControl = 0x05,
|
||||||
|
MicBiasControl0 = 0x06,
|
||||||
|
MicBiasControl1 = 0x07,
|
||||||
|
AnaAdc0 = 0x0a,
|
||||||
|
PowerMgmt0 = 0x0c,
|
||||||
|
PowerMgmt2 = 0x0e,
|
||||||
|
PowerMgmt3 = 0x0f,
|
||||||
|
PowerMgmt6 = 0x12,
|
||||||
|
ClockRates0 = 0x14,
|
||||||
|
ClockRates1 = 0x15,
|
||||||
|
ClockRates2 = 0x16,
|
||||||
|
AudioInterface0 = 0x18,
|
||||||
|
AudioInterface1 = 0x19,
|
||||||
|
AudioInterface2 = 0x1a,
|
||||||
|
AudioInterface3 = 0x1b,
|
||||||
|
DacDigiVolLeft = 0x1e,
|
||||||
|
DacDigiVolRight = 0x1f,
|
||||||
|
DacDigital0 = 0x20,
|
||||||
|
DacDigi1 = 0x21,
|
||||||
|
AdcDigiVolLeft = 0x24,
|
||||||
|
AdcDigiVolRight = 0x25,
|
||||||
|
AdcDigital0 = 0x26,
|
||||||
|
DigiMic0 = 0x27,
|
||||||
|
Drc0 = 0x28,
|
||||||
|
Drc1 = 0x29,
|
||||||
|
Drc2 = 0x2a,
|
||||||
|
Drc3 = 0x2b,
|
||||||
|
AnaLeftIn0 = 0x2c,
|
||||||
|
AnaRightIn0 = 0x2d,
|
||||||
|
AnaLeftIn1 = 0x2e,
|
||||||
|
AnaRightIn1 = 0x2f,
|
||||||
|
AnaOut1Left = 0x39,
|
||||||
|
AnaOut1Right = 0x3a,
|
||||||
|
AnaOut2Left = 0x3b,
|
||||||
|
AnaOut2Right = 0x3c,
|
||||||
|
AnaOut12Zc = 0x3d,
|
||||||
|
DcServo0 = 0x43,
|
||||||
|
DcServo1 = 0x44,
|
||||||
|
DcServo2 = 0x45,
|
||||||
|
DcServo4 = 0x47,
|
||||||
|
DcServo5 = 0x48,
|
||||||
|
DcServo6 = 0x49,
|
||||||
|
DcServo7 = 0x4a,
|
||||||
|
DcServo8 = 0x4b,
|
||||||
|
DcServo9 = 0x4c,
|
||||||
|
DcServoRb0 = 0x4d,
|
||||||
|
AnaHp0 = 0x5a,
|
||||||
|
AnaLineOut0 = 0x5e,
|
||||||
|
ChargePump0 = 0x62,
|
||||||
|
ClassW = 0x68,
|
||||||
|
WriteSeq0 = 0x6c,
|
||||||
|
WriteSeq1 = 0x6d,
|
||||||
|
WriteSeq2 = 0x6e,
|
||||||
|
WriteSeq3 = 0x6f,
|
||||||
|
WriteSeq4 = 0x70,
|
||||||
|
FllControl1 = 0x74,
|
||||||
|
FllControl2 = 0x75,
|
||||||
|
FllControl3 = 0x76,
|
||||||
|
FllControl4 = 0x77,
|
||||||
|
FllControl5 = 0x78,
|
||||||
|
GpioControl1 = 0x79,
|
||||||
|
GpioControl2 = 0x7a,
|
||||||
|
GpioControl3 = 0x7b,
|
||||||
|
GpioControl4 = 0x7c,
|
||||||
|
DigiPulls = 0x7e,
|
||||||
|
IntStatus = 0x7f,
|
||||||
|
IntStatusMask = 0x80,
|
||||||
|
IntPriority = 0x81,
|
||||||
|
IntDebounce = 0x82,
|
||||||
|
Eq1 = 0x86,
|
||||||
|
Eq2 = 0x87,
|
||||||
|
Eq3 = 0x88,
|
||||||
|
Eq4 = 0x89,
|
||||||
|
Eq5 = 0x8a,
|
||||||
|
Eq6 = 0x8b,
|
||||||
|
Eq7 = 0x8c,
|
||||||
|
Eq8 = 0x8d,
|
||||||
|
Eq9 = 0x8e,
|
||||||
|
Eq10 = 0x8f,
|
||||||
|
Eq11 = 0x90,
|
||||||
|
Eq12 = 0x91,
|
||||||
|
Eq13 = 0x92,
|
||||||
|
Eq14 = 0x93,
|
||||||
|
Eq15 = 0x94,
|
||||||
|
Eq16 = 0x95,
|
||||||
|
Eq17 = 0x96,
|
||||||
|
Eq18 = 0x97,
|
||||||
|
Eq19 = 0x98,
|
||||||
|
Eq20 = 0x99,
|
||||||
|
Eq21 = 0x9a,
|
||||||
|
Eq22 = 0x9b,
|
||||||
|
Eq23 = 0x9c,
|
||||||
|
Eq24 = 0x9d,
|
||||||
|
AdcTest0 = 0xc6,
|
||||||
|
FllNcoTest0 = 0xf7,
|
||||||
|
FllNcoTest1 = 0xf8,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Wm8904Dac<T> {
|
||||||
|
i2c: T,
|
||||||
|
pins: CodecPins,
|
||||||
|
mclk: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Wm8904Dac<T>
|
||||||
|
where
|
||||||
|
T: _embedded_hal_blocking_i2c_WriteRead + _embedded_hal_blocking_i2c_Write,
|
||||||
|
{
|
||||||
|
#[inline]
|
||||||
|
fn write_reg(&mut self, reg: RegisterAddress, val: u16) {
|
||||||
|
let b = val.to_be_bytes();
|
||||||
|
defmt::info!("i2c w [{:?}]", &[reg as u8, b[0], b[1]]);
|
||||||
|
self.i2c
|
||||||
|
.write(WM8904_I2C_ADDRESS, &[reg as u8, b[0], b[1]])
|
||||||
|
.ok();
|
||||||
|
}
|
||||||
|
fn cr1_for_rate(&self, rate: u32) -> u16 {
|
||||||
|
let fs_ratio = self.mclk / rate;
|
||||||
|
if !self.mclk.is_multiple_of(rate) {
|
||||||
|
defmt::warn!("[wm8904] sample rate should be a multiple of mclk");
|
||||||
|
}
|
||||||
|
let clk_sys_rate: u16 = match fs_ratio {
|
||||||
|
64 => 0,
|
||||||
|
128 => 1,
|
||||||
|
192 => 2,
|
||||||
|
256 => 3,
|
||||||
|
384 => 4,
|
||||||
|
512 => 5,
|
||||||
|
768 => 6,
|
||||||
|
1024 => 7,
|
||||||
|
1408 => 8,
|
||||||
|
1536 => 9,
|
||||||
|
_ => {
|
||||||
|
defmt::warn!("[wm8904] unsupport ratio {}", fs_ratio);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let sample_rate: u16 = match rate {
|
||||||
|
r if r < 11025 => 0, // 0-11024
|
||||||
|
r if r < 16000 => 1, // 11025 - 15999
|
||||||
|
r if r < 22050 => 2, // 16000 - 22049
|
||||||
|
r if r < 32000 => 3, // 22050 - 31999
|
||||||
|
r if r < 44100 => 4, // 32000 - 44099
|
||||||
|
_ => 5, // 44100+
|
||||||
|
};
|
||||||
|
(clk_sys_rate << 10) | sample_rate
|
||||||
|
}
|
||||||
|
fn blck_div_for_rate(&self, rate: u32) -> u16 {
|
||||||
|
let bits_per_frame = 64;
|
||||||
|
let bits_per_second = bits_per_frame * rate;
|
||||||
|
(self.mclk / bits_per_second) as u16
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Dac<T> for Wm8904Dac<T>
|
||||||
|
where
|
||||||
|
T: _embedded_hal_blocking_i2c_WriteRead + _embedded_hal_blocking_i2c_Write,
|
||||||
|
{
|
||||||
|
fn new(i2c: T, pins: CodecPins) -> Self {
|
||||||
|
Self {
|
||||||
|
i2c,
|
||||||
|
pins,
|
||||||
|
mclk: MCLK,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name(&self) -> &'static str {
|
||||||
|
"WM8904"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn init(&mut self) {
|
||||||
|
let mut buf = [0u8; 2];
|
||||||
|
match self.i2c.write_read(WM8904_I2C_ADDRESS, &[0], &mut buf) {
|
||||||
|
Ok(_) => {
|
||||||
|
let chip_id = ((buf[0] as u16) << 8) | buf[1] as u16;
|
||||||
|
defmt::info!("[wm8904] Read chip ID: {:x}", chip_id)
|
||||||
|
}
|
||||||
|
Err(_) => defmt::error!("[wm8904] Error reading I2C"),
|
||||||
|
}
|
||||||
|
|
||||||
|
self.write_reg(RegisterAddress::ClockRates2, 0x000f); // OPCLK_ENA | CLK_SYS_ENA | CLK_DSP_ENA | TOCLK_ENA
|
||||||
|
self.write_reg(RegisterAddress::WriteSeq0, 0x0100); // write sequencer 0 ENA
|
||||||
|
self.write_reg(RegisterAddress::WriteSeq3, 0x0100); // write sequencer 3 START, INDEX=0
|
||||||
|
// wait on write sequencer
|
||||||
|
defmt::info!("[wm8904] waiting on write seq");
|
||||||
|
loop {
|
||||||
|
let mut buf = [0; 2];
|
||||||
|
self.i2c
|
||||||
|
.write_read(
|
||||||
|
WM8904_I2C_ADDRESS,
|
||||||
|
&[RegisterAddress::WriteSeq4 as u8],
|
||||||
|
&mut buf,
|
||||||
|
)
|
||||||
|
.ok();
|
||||||
|
if buf[1] & 1 == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
defmt::debug!("[wm8904] write seq done");
|
||||||
|
self.write_reg(RegisterAddress::ClockRates0, 0);
|
||||||
|
self.write_reg(RegisterAddress::PowerMgmt0, 0); // IN PGAs disabled
|
||||||
|
self.write_reg(RegisterAddress::PowerMgmt2, 0x0003); // HPL_PGA_ENA | HPR_PGA_ENA
|
||||||
|
self.write_reg(RegisterAddress::PowerMgmt3, 0); //line outs disabled
|
||||||
|
|
||||||
|
self.write_reg(RegisterAddress::PowerMgmt6, 0x000c); // power management 6 = DACL_ENA | DACR_ENA
|
||||||
|
self.write_reg(RegisterAddress::AudioInterface0, 0x0050); // audio if 0 = AIFADCR_SRC | AIFDACR_SRC
|
||||||
|
self.write_reg(RegisterAddress::DacDigi1, 0x0040); // dac digital 1 = DAC_OSR128
|
||||||
|
self.write_reg(RegisterAddress::AnaLeftIn0, 0x0005);
|
||||||
|
self.write_reg(RegisterAddress::AnaRightIn0, 0x0005);
|
||||||
|
self.write_reg(RegisterAddress::AnaOut1Left, 0x0039); // analog out1 left = vol=0dB
|
||||||
|
self.write_reg(RegisterAddress::AnaOut1Right, 0x0039); // analog out1 right = vol=0dB
|
||||||
|
self.write_reg(RegisterAddress::AnaOut2Left, 0x0039); // analog out2 left = vol=0dB
|
||||||
|
self.write_reg(RegisterAddress::AnaOut2Right, 0x0039); // analog out2 right = vol=0dB
|
||||||
|
self.write_reg(RegisterAddress::DcServo0, 0x0003); // dc servo 0 = HPOUTL_ENA | HPOUTR_ENA
|
||||||
|
self.write_reg(RegisterAddress::AnaHp0, 0x00ff); // analog hp 0 = remove all shorts etc
|
||||||
|
self.write_reg(RegisterAddress::AnaLineOut0, 0x00ff); // analog lineout 0 = remove all shorts etc
|
||||||
|
self.write_reg(RegisterAddress::ClassW, 0x0001); // enable class w charge pump
|
||||||
|
self.write_reg(RegisterAddress::ChargePump0, 0x0001); // enable charge pump
|
||||||
|
self.write_reg(RegisterAddress::AudioInterface1, (3 << 2) | 2); // audio if 1 = i2s, 32 bit per sample
|
||||||
|
|
||||||
|
self.write_reg(RegisterAddress::ClockRates1, self.cr1_for_rate(96000)); // Set up for 48k, impl will change if needed
|
||||||
|
self.write_reg(RegisterAddress::ClockRates2, 0x000f); // clock rates 2 = CLK_SYS_ENA
|
||||||
|
|
||||||
|
self.write_reg(
|
||||||
|
RegisterAddress::AudioInterface2,
|
||||||
|
self.blck_div_for_rate(96000),
|
||||||
|
);
|
||||||
|
|
||||||
|
self.write_reg(RegisterAddress::AudioInterface3, 0); // audio interface 3 = input lrclock
|
||||||
|
self.write_reg(RegisterAddress::AnaOut12Zc, 0); // analog out12 zc = play source = dac
|
||||||
|
self.write_reg(RegisterAddress::DacDigiVolLeft, 0x01ff); // dac vol left = update left/right = 0dB
|
||||||
|
}
|
||||||
|
fn change_rate(&mut self, new_rate: u32) {
|
||||||
|
// TODO: mute, stop clocks etc.
|
||||||
|
defmt::info!("[wm8904] dac rate -> {}", new_rate);
|
||||||
|
self.write_reg(RegisterAddress::ClockRates1, self.cr1_for_rate(new_rate));
|
||||||
|
self.write_reg(
|
||||||
|
RegisterAddress::AudioInterface2,
|
||||||
|
self.blck_div_for_rate(new_rate),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
fn mute(&mut self) {
|
||||||
|
// self.write_reg(RegisterAddress::DacDigiVolLeft, 0x0100);
|
||||||
|
}
|
||||||
|
fn unmute(&mut self) {
|
||||||
|
// TODO: restore previous volume
|
||||||
|
// self.write_reg(RegisterAddress::DacDigiVolLeft, 0x01ff);
|
||||||
|
}
|
||||||
|
}
|
||||||
+113
-114
@@ -1,3 +1,4 @@
|
|||||||
|
use bitfield_struct::bitfield;
|
||||||
use hal::Syscon;
|
use hal::Syscon;
|
||||||
use hal::peripherals::syscon::ClockControl;
|
use hal::peripherals::syscon::ClockControl;
|
||||||
|
|
||||||
@@ -7,8 +8,6 @@ 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 {
|
||||||
@@ -18,6 +17,56 @@ 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!(
|
||||||
@@ -48,7 +97,7 @@ pub struct PushResult {
|
|||||||
pub dropped: usize,
|
pub dropped: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
#[derive(Debug, Copy, Clone, defmt::Format, Eq, PartialEq)]
|
||||||
pub enum ConfigError {
|
pub enum ConfigError {
|
||||||
SlotTooLarge,
|
SlotTooLarge,
|
||||||
SlotTooSmall,
|
SlotTooSmall,
|
||||||
@@ -70,29 +119,22 @@ impl core::fmt::Display for DmaError {
|
|||||||
/// Slot-based DMA ring
|
/// Slot-based DMA ring
|
||||||
pub struct DmaRing<const N: usize, const MAX_SLOT_BYTES: usize> {
|
pub struct DmaRing<const N: usize, const MAX_SLOT_BYTES: usize> {
|
||||||
dma: pac::DMA0,
|
dma: pac::DMA0,
|
||||||
|
|
||||||
/// Destination peripheral register (FIFO write register)
|
|
||||||
dst_reg: *mut u32,
|
dst_reg: *mut u32,
|
||||||
|
|
||||||
// SAFETY: only written by USB task (on start)
|
|
||||||
pub(crate) channel_desc: UnsafeCell<DescriptorTable>,
|
pub(crate) channel_desc: UnsafeCell<DescriptorTable>,
|
||||||
// SAFETY: only written by USB task (on start)
|
|
||||||
pub(crate) desc: UnsafeCell<RingDescriptors<N>>,
|
pub(crate) desc: UnsafeCell<RingDescriptors<N>>,
|
||||||
slots: UnsafeCell<[[u8; MAX_SLOT_BYTES]; N]>,
|
slots: UnsafeCell<[[u8; MAX_SLOT_BYTES]; N]>,
|
||||||
|
|
||||||
/// Effective bytes per slot. Maybe be smaller than MAX_SLOT_BYTES (e.g. at lower sample rates), as the setup is designed for constant rate not constant size.
|
/// Effective bytes per slot (atomic for interior mutability)
|
||||||
slot_bytes: usize,
|
slot_bytes: AtomicUsize,
|
||||||
/// How many bytes to transfer to the FIFO
|
word_bytes: u8,
|
||||||
word_bytes: usize,
|
|
||||||
|
|
||||||
// SAFETY: producer only
|
|
||||||
write_slot: UnsafeCell<usize>,
|
write_slot: UnsafeCell<usize>,
|
||||||
write_off: UnsafeCell<usize>,
|
write_off: UnsafeCell<usize>,
|
||||||
|
|
||||||
produced: AtomicUsize,
|
produced: AtomicUsize,
|
||||||
consumed: AtomicUsize,
|
consumed: AtomicUsize,
|
||||||
|
|
||||||
/// Leave at least one slot empty so producer never overwrites a slot DMA may still read.
|
|
||||||
safety_gap: usize,
|
safety_gap: usize,
|
||||||
pub produced_bytes: AtomicUsize,
|
pub produced_bytes: AtomicUsize,
|
||||||
pub consumed_bytes: AtomicUsize,
|
pub consumed_bytes: AtomicUsize,
|
||||||
@@ -104,7 +146,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: usize,
|
word_bytes: u8,
|
||||||
) -> 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);
|
||||||
@@ -114,7 +156,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,
|
||||||
@@ -132,7 +174,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
|||||||
}; N],
|
}; N],
|
||||||
}),
|
}),
|
||||||
slots: UnsafeCell::new([[0u8; MAX_SLOT_BYTES]; N]),
|
slots: UnsafeCell::new([[0u8; MAX_SLOT_BYTES]; N]),
|
||||||
slot_bytes: MAX_SLOT_BYTES,
|
slot_bytes: AtomicUsize::new(MAX_SLOT_BYTES),
|
||||||
word_bytes,
|
word_bytes,
|
||||||
write_slot: UnsafeCell::new(0),
|
write_slot: UnsafeCell::new(0),
|
||||||
write_off: UnsafeCell::new(0),
|
write_off: UnsafeCell::new(0),
|
||||||
@@ -145,24 +187,31 @@ 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);
|
||||||
}
|
}
|
||||||
pub fn slot_size(&self) -> usize {
|
pub fn slot_size(&self) -> usize {
|
||||||
self.slot_bytes
|
self.slot_bytes.load(Ordering::Acquire)
|
||||||
}
|
}
|
||||||
pub fn set_slot_size(&mut self, slot_bytes: usize) -> Result<(), ConfigError> {
|
|
||||||
|
pub fn set_slot_size(&self, slot_bytes: usize) -> Result<(), ConfigError> {
|
||||||
if slot_bytes == 0 {
|
if slot_bytes == 0 {
|
||||||
return Err(ConfigError::SlotTooSmall);
|
return Err(ConfigError::SlotTooSmall);
|
||||||
}
|
}
|
||||||
if slot_bytes > MAX_SLOT_BYTES {
|
if slot_bytes > MAX_SLOT_BYTES {
|
||||||
return Err(ConfigError::SlotTooLarge);
|
return Err(ConfigError::SlotTooLarge);
|
||||||
}
|
}
|
||||||
if slot_bytes % self.word_bytes != 0 {
|
if !slot_bytes.is_multiple_of(self.word_bytes as usize) {
|
||||||
return Err(ConfigError::SlotNotAligned);
|
return Err(ConfigError::SlotNotAligned);
|
||||||
}
|
}
|
||||||
self.slot_bytes = slot_bytes;
|
|
||||||
self.reset_producer();
|
// Update atomic size
|
||||||
|
self.slot_bytes.store(slot_bytes, Ordering::Release);
|
||||||
|
|
||||||
|
// Re-initialize descriptors and reset producer state safely through internal mutability
|
||||||
|
self.init_descriptors();
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,7 +234,8 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
let cap = self.slot_bytes - *write_off;
|
let slot_bytes = self.slot_bytes.load(Ordering::Acquire);
|
||||||
|
let cap = slot_bytes - *write_off;
|
||||||
let n = core::cmp::min(cap, data.len());
|
let n = core::cmp::min(cap, data.len());
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
@@ -197,7 +247,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
|||||||
written += n;
|
written += n;
|
||||||
data = &data[n..];
|
data = &data[n..];
|
||||||
|
|
||||||
if *write_off == self.slot_bytes {
|
if *write_off == slot_bytes {
|
||||||
// publish completed slot
|
// publish completed slot
|
||||||
compiler_fence(Ordering::Release);
|
compiler_fence(Ordering::Release);
|
||||||
self.produced.fetch_add(1, Ordering::Release);
|
self.produced.fetch_add(1, Ordering::Release);
|
||||||
@@ -221,8 +271,9 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
|||||||
let consumed = self.consumed.load(Ordering::Relaxed);
|
let consumed = self.consumed.load(Ordering::Relaxed);
|
||||||
if consumed < produced {
|
if consumed < produced {
|
||||||
self.consumed.fetch_add(slots, Ordering::Release);
|
self.consumed.fetch_add(slots, Ordering::Release);
|
||||||
|
let slot_bytes = self.slot_bytes.load(Ordering::Acquire);
|
||||||
self.consumed_bytes
|
self.consumed_bytes
|
||||||
.fetch_add(slots * self.slot_bytes, Ordering::Relaxed);
|
.fetch_add(slots * slot_bytes, Ordering::Relaxed);
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
defmt::error!("DMA underrun!");
|
defmt::error!("DMA underrun!");
|
||||||
@@ -243,25 +294,23 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
|||||||
loop {
|
loop {
|
||||||
let consumed_start = self.consumed.load(Ordering::Acquire);
|
let consumed_start = self.consumed.load(Ordering::Acquire);
|
||||||
|
|
||||||
let reg_1 = self.dma.channel19.xfercfg.read().bits() as usize >> 16 & 0x3ff;
|
let reg_1 = (self.dma.channel19.xfercfg.read().bits() >> 16) & 0x3FF;
|
||||||
let reg_2 = self.dma.channel19.xfercfg.read().bits() as usize >> 16 & 0x3ff;
|
let reg_2 = (self.dma.channel19.xfercfg.read().bits() >> 16) & 0x3FF;
|
||||||
|
|
||||||
let consumed_end = self.consumed.load(Ordering::Acquire);
|
let consumed_end = self.consumed.load(Ordering::Acquire);
|
||||||
|
|
||||||
if consumed_start == consumed_end && reg_1 == reg_2 {
|
if consumed_start == consumed_end && reg_1 == reg_2 {
|
||||||
// 1. Map the hardware remaining countdown into a clean byte count
|
let remaining_bytes = if reg_1 == 0x3FF {
|
||||||
let remaining_bytes = if reg_1 == 0x3ff {
|
0
|
||||||
0 // 0x3FF means all transfers completed, 0 bytes remaining
|
|
||||||
} else {
|
} else {
|
||||||
// Formula from NXP manual: (XFERCOUNT + 1) * Data Width
|
(reg_1 as usize + 1) * self.word_bytes as usize
|
||||||
(reg_1 + 1) * self.word_bytes
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 2. Total bytes consumed in this specific active slot
|
// Active slot consumed calculation accounts for dynamic slot size
|
||||||
let active_slot_consumed = self.slot_bytes - remaining_bytes;
|
let slot_bytes = self.slot_bytes.load(Ordering::Acquire);
|
||||||
|
let active_slot_consumed = slot_bytes.saturating_sub(remaining_bytes);
|
||||||
|
|
||||||
// 3. Combine with your software index history accumulator
|
return consumed_start * slot_bytes + active_slot_consumed;
|
||||||
return consumed_start * self.slot_bytes + active_slot_consumed;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -295,6 +344,8 @@ 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) });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -311,8 +362,8 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
|||||||
|
|
||||||
fn reset_producer(&self) {
|
fn reset_producer(&self) {
|
||||||
unsafe {
|
unsafe {
|
||||||
*(&mut *self.write_slot.get()) = 0;
|
*self.write_slot.get() = 0;
|
||||||
*(&mut *self.write_off.get()) = 0;
|
*self.write_off.get() = 0;
|
||||||
}
|
}
|
||||||
self.produced.store(0, Ordering::Relaxed);
|
self.produced.store(0, Ordering::Relaxed);
|
||||||
self.produced_bytes.store(0, Ordering::Relaxed);
|
self.produced_bytes.store(0, Ordering::Relaxed);
|
||||||
@@ -324,104 +375,52 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
|||||||
let fill = self.fill_slots();
|
let fill = self.fill_slots();
|
||||||
fill >= N.wrapping_sub(self.safety_gap)
|
fill >= N.wrapping_sub(self.safety_gap)
|
||||||
}
|
}
|
||||||
fn reset_producer_init_only(&self) {
|
|
||||||
unsafe {
|
|
||||||
*self.write_slot.get() = 0;
|
|
||||||
}
|
|
||||||
unsafe {
|
|
||||||
*self.write_off.get() = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.produced.store(0, Ordering::Relaxed);
|
|
||||||
self.consumed.store(0, Ordering::Relaxed);
|
|
||||||
|
|
||||||
self.produced_bytes.store(0, Ordering::Relaxed);
|
|
||||||
self.consumed_bytes.store(0, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn init_descriptors(&self) {
|
fn init_descriptors(&self) {
|
||||||
|
let slot_bytes = self.slot_bytes.load(Ordering::Acquire);
|
||||||
let slots = unsafe { &mut *self.slots.get() };
|
let slots = unsafe { &mut *self.slots.get() };
|
||||||
let desc = unsafe { &mut *self.desc.get() };
|
let desc = unsafe { &mut *self.desc.get() };
|
||||||
let chan_desc = unsafe { &mut *self.channel_desc.get() };
|
let chan_desc = unsafe { &mut *self.channel_desc.get() };
|
||||||
defmt::debug!("slots base: &{:x}", self.slots.get());
|
|
||||||
|
|
||||||
// Pre-fill with silence so underrun replays silence.
|
// Pre-fill active slot regions with silence
|
||||||
for i in 0..N {
|
for slot in slots.iter_mut() {
|
||||||
slots[i][..self.slot_bytes].fill(0);
|
slot.fill(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
let transfers = (self.slot_bytes / self.word_bytes) as u32;
|
let transfers = (slot_bytes / self.word_bytes as usize) as u32;
|
||||||
|
|
||||||
for i in 0..N {
|
|
||||||
let src_start = slots[i].as_ptr() as usize;
|
|
||||||
let src_end = (src_start + self.slot_bytes - self.word_bytes) as *const u8;
|
|
||||||
|
|
||||||
|
for (i, slot) in slots.iter().enumerate() {
|
||||||
|
let src_start = slot.as_ptr() as usize;
|
||||||
|
let src_end = (src_start + slot_bytes - self.word_bytes as usize) 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: encode_xfercfg(
|
xfercfg: XferCfg::new()
|
||||||
true, // valid
|
.with_cfgvalid(true) // valid
|
||||||
true, // reload
|
.with_reload(true) // reload
|
||||||
false, // swtrig (we use XFERCFG SWTRIG kick)
|
.with_swtrig(false) // swtrig
|
||||||
false, // clrtrig
|
.with_clrtrig(false) // clrtrig
|
||||||
true, // intA
|
.with_inta(true) // intA
|
||||||
false, // intB
|
.with_intb(false) // intB
|
||||||
self.word_bytes as u32,
|
.with_width(self.word_bytes)
|
||||||
1, // src_inc
|
.with_src_inc(1) // src_inc
|
||||||
0, // dst_inc
|
.with_dst_inc(0) // dst_inc
|
||||||
transfers,
|
.with_transfers(transfers)
|
||||||
),
|
.into_bits(),
|
||||||
src_end,
|
src_end,
|
||||||
dst_end: self.dst_reg,
|
dst_end: self.dst_reg,
|
||||||
next,
|
next,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ensure memory writes complete before reloading DMA hardware pointers
|
||||||
|
compiler_fence(Ordering::Release);
|
||||||
|
|
||||||
chan_desc.d[19] = desc.d[0];
|
chan_desc.d[19] = desc.d[0];
|
||||||
chan_desc.d[19].xfercfg = 0;
|
chan_desc.d[19].xfercfg = 0;
|
||||||
|
|
||||||
// reset producer indices + counters (init-only action)
|
self.reset_producer();
|
||||||
self.reset_producer_init_only();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
use usbd_hid::descriptor::generator_prelude::*;
|
|
||||||
|
|
||||||
#[gen_hid_descriptor(
|
|
||||||
(collection = APPLICATION, usage_page = VENDOR_DEFINED_START, usage = 0x01, ) = {
|
|
||||||
average_buffer_fill=input;
|
|
||||||
frame_count=input;
|
|
||||||
dac_underflow_count=input;
|
|
||||||
usb_underflow_count=input;
|
|
||||||
dac_overflow_count=input;
|
|
||||||
}
|
|
||||||
)]
|
|
||||||
#[repr(C)]
|
|
||||||
// Note these are all actually u32
|
|
||||||
pub struct AudioTelemetryReport {
|
|
||||||
pub average_buffer_fill: i32,
|
|
||||||
pub frame_count: i32,
|
|
||||||
pub dac_underflow_count: i32,
|
|
||||||
pub usb_underflow_count: i32,
|
|
||||||
pub dac_overflow_count: i32,
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,458 @@
|
|||||||
|
use shared::{
|
||||||
|
config::{
|
||||||
|
ConfigBytes, ConfigError, ConfigSnapshot, ConfigTag, ConfigV1, DeviceConfig, MAX_VALUE_LEN,
|
||||||
|
Tlv,
|
||||||
|
},
|
||||||
|
hardware::HardwareInfo,
|
||||||
|
hid::command::{
|
||||||
|
COMMAND_REPORT_SIZE, CommandKind, HEADER_LEN, Header, IN_PAYLOAD_LEN, IN_REPORT_SIZE,
|
||||||
|
NackCode, ResponseKind,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use usb_device::{UsbError, bus::UsbBus};
|
||||||
|
use usbd_hid::hid_class::HIDClass;
|
||||||
|
|
||||||
|
use crate::config::{self, ConfigState, FlashState};
|
||||||
|
|
||||||
|
const MAX_COMMAND_LEN: usize = 128;
|
||||||
|
const REPLY_BUF_LEN: usize = 512;
|
||||||
|
|
||||||
|
struct Reassembly {
|
||||||
|
kind: Option<CommandKind>,
|
||||||
|
seq: u8,
|
||||||
|
total_len: usize,
|
||||||
|
received: usize,
|
||||||
|
buf: [u8; MAX_COMMAND_LEN],
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Action {
|
||||||
|
Nothing,
|
||||||
|
Apply(DeviceConfig),
|
||||||
|
Reset,
|
||||||
|
Bootloader,
|
||||||
|
Commit,
|
||||||
|
ResetDefaults,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Pending {
|
||||||
|
Ack { seq: u8, action: Action },
|
||||||
|
Nack { seq: u8, code: NackCode },
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Push {
|
||||||
|
Sent,
|
||||||
|
Blocked,
|
||||||
|
Failed,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reply payload being segmented into IN reports.
|
||||||
|
struct Reply {
|
||||||
|
kind: ResponseKind,
|
||||||
|
seq: u8,
|
||||||
|
total_len: usize,
|
||||||
|
offset: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CommandState {
|
||||||
|
command: Reassembly,
|
||||||
|
pending: Option<Pending>,
|
||||||
|
reply: Option<Reply>,
|
||||||
|
reply_buf: [u8; REPLY_BUF_LEN],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CommandState {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
command: Reassembly {
|
||||||
|
kind: None,
|
||||||
|
seq: 0,
|
||||||
|
total_len: 0,
|
||||||
|
received: 0,
|
||||||
|
buf: [0; MAX_COMMAND_LEN],
|
||||||
|
},
|
||||||
|
pending: None,
|
||||||
|
reply: None,
|
||||||
|
reply_buf: [0; REPLY_BUF_LEN],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reset(&mut self) {
|
||||||
|
self.command.kind = None;
|
||||||
|
self.pending = None;
|
||||||
|
self.reply = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn nack(&mut self, seq: u8, code: NackCode) {
|
||||||
|
self.command.kind = None;
|
||||||
|
self.reply = None;
|
||||||
|
self.pending = Some(Pending::Nack { seq, code });
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reply(&mut self, kind: ResponseKind, seq: u8, len: usize) {
|
||||||
|
self.reply = Some(Reply {
|
||||||
|
kind,
|
||||||
|
seq,
|
||||||
|
total_len: len,
|
||||||
|
offset: 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prepare(
|
||||||
|
&mut self,
|
||||||
|
kind: CommandKind,
|
||||||
|
seq: u8,
|
||||||
|
payload: &[u8],
|
||||||
|
config: &ConfigState,
|
||||||
|
hardware: &HardwareInfo,
|
||||||
|
) {
|
||||||
|
match kind {
|
||||||
|
CommandKind::Noop => {
|
||||||
|
self.pending = Some(Pending::Ack {
|
||||||
|
seq,
|
||||||
|
action: Action::Nothing,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
CommandKind::Reset => {
|
||||||
|
self.pending = Some(Pending::Ack {
|
||||||
|
seq,
|
||||||
|
action: Action::Reset,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
CommandKind::Bootloader => {
|
||||||
|
self.pending = Some(Pending::Ack {
|
||||||
|
seq,
|
||||||
|
action: Action::Bootloader,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
CommandKind::ReadConfig => {
|
||||||
|
if !payload.is_empty() {
|
||||||
|
self.nack(seq, NackCode::InvalidPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let Ok(tlvs) = config.running.to_tlvs() else {
|
||||||
|
self.nack(seq, NackCode::InvalidConfig);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let snapshot = ConfigSnapshot {
|
||||||
|
active_slot: config.active_slot,
|
||||||
|
config: ConfigV1 { tlvs },
|
||||||
|
};
|
||||||
|
|
||||||
|
match snapshot.encode(&mut self.reply_buf) {
|
||||||
|
Ok(len) => self.reply(ResponseKind::ConfigData, seq, len),
|
||||||
|
Err(error) => {
|
||||||
|
defmt::warn!("config snapshot encode failed: {}", error);
|
||||||
|
self.nack(seq, NackCode::ConfigTooLarge);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CommandKind::Hardware => {
|
||||||
|
if !payload.is_empty() {
|
||||||
|
self.nack(seq, NackCode::InvalidPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
match hardware.encode(&mut self.reply_buf) {
|
||||||
|
Ok(len) => self.reply(ResponseKind::Hardware, seq, len),
|
||||||
|
Err(error) => {
|
||||||
|
defmt::warn!("hardware encode failed: {}", error);
|
||||||
|
self.nack(seq, NackCode::ConfigTooLarge);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CommandKind::ReplaceTlv => {
|
||||||
|
if payload.len() < 2 {
|
||||||
|
self.nack(seq, NackCode::InvalidPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let tag = ConfigTag(u16::from_le_bytes([payload[0], payload[1]]));
|
||||||
|
let Ok(value) = ConfigBytes::<MAX_VALUE_LEN>::from_slice(&payload[2..]) else {
|
||||||
|
self.nack(seq, NackCode::InvalidPayload);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut staged = config.running.clone();
|
||||||
|
match staged.replace_tlv(Tlv { tag, value }) {
|
||||||
|
Ok(()) => {
|
||||||
|
self.pending = Some(Pending::Ack {
|
||||||
|
seq,
|
||||||
|
action: Action::Apply(staged),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Err(ConfigError::UnknownTag(_)) => self.nack(seq, NackCode::UnknownTag),
|
||||||
|
Err(_) => self.nack(seq, NackCode::InvalidConfig),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CommandKind::CommitConfig => {
|
||||||
|
if !payload.is_empty() {
|
||||||
|
self.nack(seq, NackCode::InvalidPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.pending = Some(Pending::Ack {
|
||||||
|
seq,
|
||||||
|
action: Action::Commit,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
CommandKind::ResetConfig => {
|
||||||
|
if !payload.is_empty() {
|
||||||
|
self.nack(seq, NackCode::InvalidPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.pending = Some(Pending::Ack {
|
||||||
|
seq,
|
||||||
|
action: Action::ResetDefaults,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush<B: UsbBus>(
|
||||||
|
&mut self,
|
||||||
|
hid: &HIDClass<'_, B>,
|
||||||
|
config: &mut ConfigState,
|
||||||
|
flash: &mut FlashState,
|
||||||
|
) -> bool {
|
||||||
|
if let Some(pending) = self.pending.take() {
|
||||||
|
let pushed = match &pending {
|
||||||
|
Pending::Ack { seq, .. } => push_ack(hid, *seq),
|
||||||
|
Pending::Nack { seq, code } => push_nack(hid, *seq, *code),
|
||||||
|
};
|
||||||
|
|
||||||
|
match pushed {
|
||||||
|
Push::Blocked => {
|
||||||
|
self.pending = Some(pending);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
Push::Failed => return true,
|
||||||
|
Push::Sent => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Pending::Ack { action, .. } = pending {
|
||||||
|
match action {
|
||||||
|
Action::Nothing => {}
|
||||||
|
Action::Apply(staged) => config.running = staged,
|
||||||
|
Action::Reset => {
|
||||||
|
ack_delay();
|
||||||
|
cortex_m::peripheral::SCB::sys_reset();
|
||||||
|
}
|
||||||
|
Action::Bootloader => {
|
||||||
|
ack_delay();
|
||||||
|
|
||||||
|
if config::request_bootloader(flash).is_err() {
|
||||||
|
defmt::error!("boot request failed, staying in the application");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::Commit => {
|
||||||
|
ack_delay();
|
||||||
|
|
||||||
|
if config::commit(flash, config).is_err() {
|
||||||
|
defmt::error!("config commit failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::ResetDefaults => {
|
||||||
|
ack_delay();
|
||||||
|
|
||||||
|
if config::commit_defaults(flash, config).is_err() {
|
||||||
|
defmt::error!("config reset failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(mut reply) = self.reply.take() {
|
||||||
|
let len = (reply.total_len - reply.offset).min(IN_PAYLOAD_LEN);
|
||||||
|
let mut report = [0u8; IN_REPORT_SIZE];
|
||||||
|
|
||||||
|
Header {
|
||||||
|
kind: reply.kind as u8,
|
||||||
|
seq: reply.seq,
|
||||||
|
total_len: reply.total_len as u16,
|
||||||
|
offset: reply.offset as u16,
|
||||||
|
len: len as u8,
|
||||||
|
}
|
||||||
|
.encode(&mut report[..HEADER_LEN]);
|
||||||
|
|
||||||
|
let start = reply.offset;
|
||||||
|
report[HEADER_LEN..HEADER_LEN + len]
|
||||||
|
.copy_from_slice(&self.reply_buf[start..start + len]);
|
||||||
|
|
||||||
|
match hid.push_raw_input(&report) {
|
||||||
|
Ok(_) => {
|
||||||
|
defmt::debug!(
|
||||||
|
"HID reply kind={:?} seq={} offset={} len={}/{}",
|
||||||
|
reply.kind,
|
||||||
|
reply.seq,
|
||||||
|
reply.offset,
|
||||||
|
len,
|
||||||
|
reply.total_len
|
||||||
|
);
|
||||||
|
|
||||||
|
reply.offset += len;
|
||||||
|
|
||||||
|
if reply.offset < reply.total_len {
|
||||||
|
self.reply = Some(reply);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(UsbError::WouldBlock) => self.reply = Some(reply),
|
||||||
|
Err(error) => defmt::error!("HID reply push failed: {:?}", error),
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read<B: UsbBus>(
|
||||||
|
&mut self,
|
||||||
|
hid: &mut HIDClass<'_, B>,
|
||||||
|
config: &ConfigState,
|
||||||
|
hardware: &HardwareInfo,
|
||||||
|
) {
|
||||||
|
let mut raw = [0u8; IN_REPORT_SIZE];
|
||||||
|
|
||||||
|
let len = match hid.pull_raw_report(&mut raw) {
|
||||||
|
Ok(info) if info.report_id == 0 => info.len,
|
||||||
|
Ok(_) => return,
|
||||||
|
Err(UsbError::WouldBlock) => return,
|
||||||
|
Err(error) => {
|
||||||
|
defmt::error!("HID pull failed: {:?}", error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let len = len.min(COMMAND_REPORT_SIZE);
|
||||||
|
let report = &raw[..len];
|
||||||
|
|
||||||
|
let Some(header) = Header::parse(report) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
if HEADER_LEN + usize::from(header.len) > len
|
||||||
|
|| usize::from(header.offset) + usize::from(header.len) > usize::from(header.total_len)
|
||||||
|
{
|
||||||
|
defmt::warn!("invalid HID command framing");
|
||||||
|
self.nack(header.seq, NackCode::InvalidPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let Ok(kind) = CommandKind::try_from(header.kind) else {
|
||||||
|
defmt::warn!("unknown HID command {}", header.kind);
|
||||||
|
self.nack(header.seq, NackCode::InvalidCommand);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
if header.offset == 0 {
|
||||||
|
self.command.kind = Some(kind);
|
||||||
|
self.command.seq = header.seq;
|
||||||
|
self.command.total_len = usize::from(header.total_len);
|
||||||
|
self.command.received = 0;
|
||||||
|
|
||||||
|
if self.command.total_len > MAX_COMMAND_LEN {
|
||||||
|
defmt::warn!("HID command too large: {}", self.command.total_len);
|
||||||
|
self.nack(header.seq, NackCode::InvalidPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.command.kind != Some(kind)
|
||||||
|
|| self.command.seq != header.seq
|
||||||
|
|| usize::from(header.offset) != self.command.received
|
||||||
|
{
|
||||||
|
defmt::warn!("out of sequence HID command chunk");
|
||||||
|
self.nack(header.seq, NackCode::InvalidPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let start = usize::from(header.offset);
|
||||||
|
let len = usize::from(header.len);
|
||||||
|
self.command.buf[start..start + len].copy_from_slice(&report[HEADER_LEN..HEADER_LEN + len]);
|
||||||
|
self.command.received += len;
|
||||||
|
|
||||||
|
if self.command.received == self.command.total_len {
|
||||||
|
defmt::debug!(
|
||||||
|
"HID command kind={:?} seq={} len={}",
|
||||||
|
kind,
|
||||||
|
header.seq,
|
||||||
|
self.command.total_len
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut payload = [0u8; MAX_COMMAND_LEN];
|
||||||
|
let total_len = self.command.total_len;
|
||||||
|
payload[..total_len].copy_from_slice(&self.command.buf[..total_len]);
|
||||||
|
self.command.kind = None;
|
||||||
|
|
||||||
|
if self.reply.take().is_some() {
|
||||||
|
defmt::warn!("dropping unsent reply");
|
||||||
|
}
|
||||||
|
|
||||||
|
self.prepare(kind, header.seq, &payload[..total_len], config, hardware);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_ack<B: UsbBus>(hid: &HIDClass<'_, B>, seq: u8) -> Push {
|
||||||
|
let mut report = [0u8; IN_REPORT_SIZE];
|
||||||
|
Header {
|
||||||
|
kind: ResponseKind::Ack as u8,
|
||||||
|
seq,
|
||||||
|
total_len: 0,
|
||||||
|
offset: 0,
|
||||||
|
len: 0,
|
||||||
|
}
|
||||||
|
.encode(&mut report[..HEADER_LEN]);
|
||||||
|
|
||||||
|
match hid.push_raw_input(&report) {
|
||||||
|
Ok(_) => Push::Sent,
|
||||||
|
Err(UsbError::WouldBlock) => Push::Blocked,
|
||||||
|
Err(error) => {
|
||||||
|
defmt::error!("HID ACK failed: {:?}", error);
|
||||||
|
Push::Failed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_nack<B: UsbBus>(hid: &HIDClass<'_, B>, seq: u8, code: NackCode) -> Push {
|
||||||
|
let mut report = [0u8; IN_REPORT_SIZE];
|
||||||
|
Header {
|
||||||
|
kind: ResponseKind::Nack as u8,
|
||||||
|
seq,
|
||||||
|
total_len: 1,
|
||||||
|
offset: 0,
|
||||||
|
len: 1,
|
||||||
|
}
|
||||||
|
.encode(&mut report[..HEADER_LEN]);
|
||||||
|
report[HEADER_LEN] = code as u8;
|
||||||
|
|
||||||
|
match hid.push_raw_input(&report) {
|
||||||
|
Ok(_) => Push::Sent,
|
||||||
|
Err(UsbError::WouldBlock) => Push::Blocked,
|
||||||
|
Err(error) => {
|
||||||
|
defmt::error!("HID NACK failed: {:?}", error);
|
||||||
|
Push::Failed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ack_delay() {
|
||||||
|
cortex_m::asm::delay(5_000_000);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn poll<B: UsbBus>(
|
||||||
|
hid: &mut HIDClass<'_, B>,
|
||||||
|
state: &mut CommandState,
|
||||||
|
config: &mut ConfigState,
|
||||||
|
flash: &mut FlashState,
|
||||||
|
hardware: &HardwareInfo,
|
||||||
|
) {
|
||||||
|
state.read(hid, config, hardware);
|
||||||
|
state.flush(hid, config, flash);
|
||||||
|
}
|
||||||
@@ -1,5 +1,16 @@
|
|||||||
|
use core::cell::UnsafeCell;
|
||||||
|
use core::mem::MaybeUninit;
|
||||||
|
|
||||||
|
use crate::hal;
|
||||||
use crate::pac;
|
use crate::pac;
|
||||||
|
|
||||||
use defmt::debug;
|
use defmt::debug;
|
||||||
|
use hal::{
|
||||||
|
Enabled, Iocon, Pin,
|
||||||
|
drivers::pins,
|
||||||
|
traits::wg::digital::v2::{OutputPin, ToggleableOutputPin},
|
||||||
|
typestates::pin::{gpio::direction::Output, state::Gpio},
|
||||||
|
};
|
||||||
|
|
||||||
pub(crate) struct PllConstants {
|
pub(crate) struct PllConstants {
|
||||||
pub m: u16, // 1-65535
|
pub m: u16, // 1-65535
|
||||||
@@ -112,3 +123,138 @@ pub(crate) fn init_sys_pll1() {
|
|||||||
syscon.fmccr.modify(|_, w| w.flashtim().flashtim11());
|
syscon.fmccr.modify(|_, w| w.flashtim().flashtim11());
|
||||||
syscon.mainclkselb.modify(|_, w| w.sel().enum_0x2()); // pll1
|
syscon.mainclkselb.modify(|_, w| w.sel().enum_0x2()); // pll1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Set PLL0 to 24.576MHz, start, and wait for lock
|
||||||
|
// This is not exposed by lpc55-hal, unfortunately. Copy their implementation here.
|
||||||
|
#[cfg(feature = "evk")]
|
||||||
|
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 pmc = unsafe { &*pac::PMC::ptr() };
|
||||||
|
let anactrl = unsafe { &*pac::ANACTRL::ptr() };
|
||||||
|
|
||||||
|
debug!("start clk_in");
|
||||||
|
pmc.pdruncfg0
|
||||||
|
.modify(|_, w| w.pden_xtal32m().poweredon().pden_ldoxo32m().poweredon());
|
||||||
|
syscon.clock_ctrl.modify(|_, w| w.clkin_ena().enable());
|
||||||
|
anactrl
|
||||||
|
.xo32m_ctrl
|
||||||
|
.modify(|_, w| w.enable_system_clk_out().enable());
|
||||||
|
|
||||||
|
debug!("init pll0: {}", AUDIO_PLL);
|
||||||
|
pmc.pdruncfg0
|
||||||
|
.modify(|_, w| w.pden_pll0().poweredoff().pden_pll0_sscg().poweredoff());
|
||||||
|
syscon.pll0clksel.write(|w| w.sel().enum_0x1()); // clk_in
|
||||||
|
syscon.pll0ctrl.write(|w| unsafe {
|
||||||
|
w.clken()
|
||||||
|
.enable()
|
||||||
|
.seli()
|
||||||
|
.bits(AUDIO_PLL.seli)
|
||||||
|
.selp()
|
||||||
|
.bits(AUDIO_PLL.selp)
|
||||||
|
});
|
||||||
|
|
||||||
|
syscon
|
||||||
|
.pll0ndec
|
||||||
|
.write(|w| unsafe { w.ndiv().bits(AUDIO_PLL.n) });
|
||||||
|
syscon.pll0ndec.write(|w| unsafe {
|
||||||
|
w.ndiv().bits(AUDIO_PLL.n).nreq().set_bit() // latch
|
||||||
|
});
|
||||||
|
|
||||||
|
syscon
|
||||||
|
.pll0pdec
|
||||||
|
.write(|w| unsafe { w.pdiv().bits(AUDIO_PLL.p) });
|
||||||
|
syscon.pll0pdec.write(|w| unsafe {
|
||||||
|
w.pdiv().bits(AUDIO_PLL.p).preq().set_bit() // latch
|
||||||
|
});
|
||||||
|
|
||||||
|
syscon.pll0sscg0.write(|w| unsafe { w.md_lbs().bits(0) });
|
||||||
|
|
||||||
|
syscon
|
||||||
|
.pll0sscg1
|
||||||
|
.write(|w| unsafe { w.mdiv_ext().bits(AUDIO_PLL.m).sel_ext().set_bit() });
|
||||||
|
syscon.pll0sscg1.write(|w| unsafe {
|
||||||
|
w.mdiv_ext()
|
||||||
|
.bits(AUDIO_PLL.m)
|
||||||
|
.sel_ext()
|
||||||
|
.set_bit()
|
||||||
|
.mreq()
|
||||||
|
.set_bit() // latch
|
||||||
|
.md_req()
|
||||||
|
.set_bit() // latch
|
||||||
|
});
|
||||||
|
|
||||||
|
pmc.pdruncfg0
|
||||||
|
.modify(|_, w| w.pden_pll0().poweredon().pden_pll0_sscg().poweredon());
|
||||||
|
info!("pll0 wait for lock");
|
||||||
|
let mut i = 0usize;
|
||||||
|
while syscon.pll0stat.read().lock().bit_is_clear() {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
info!("pll0 locked after {} loops", i);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SharedLed<T: OutputPin> {
|
||||||
|
inner: UnsafeCell<T>,
|
||||||
|
}
|
||||||
|
unsafe impl<T: OutputPin> Sync for SharedLed<T> {}
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl<T: OutputPin> SharedLed<T> {
|
||||||
|
pub fn new(inner: T) -> Self {
|
||||||
|
Self {
|
||||||
|
inner: UnsafeCell::new(inner),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn on(&self) {
|
||||||
|
unsafe {
|
||||||
|
(*self.inner.get()).set_low().ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn off(&self) {
|
||||||
|
unsafe {
|
||||||
|
(*self.inner.get()).set_high().ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T: OutputPin + ToggleableOutputPin> SharedLed<T> {
|
||||||
|
pub fn toggle(&self) {
|
||||||
|
unsafe {
|
||||||
|
(*self.inner.get()).toggle().ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Led1 = Pin<pins::Pio0_13, Gpio<Output>>;
|
||||||
|
type Led2 = Pin<pins::Pio0_14, Gpio<Output>>;
|
||||||
|
pub static LED1: MaybeUninit<SharedLed<Led1>> = MaybeUninit::uninit();
|
||||||
|
pub static LED2: MaybeUninit<SharedLed<Led2>> = MaybeUninit::uninit();
|
||||||
|
|
||||||
|
pub fn init_leds(iocon: &mut Iocon<Enabled>, gpio: &mut hal::Gpio<Enabled>) {
|
||||||
|
let led1 = SharedLed::new(
|
||||||
|
pins::Pio0_13::take()
|
||||||
|
.unwrap()
|
||||||
|
.into_gpio_pin(iocon, gpio)
|
||||||
|
.into_output_low(),
|
||||||
|
);
|
||||||
|
let led2 = SharedLed::new(
|
||||||
|
pins::Pio0_14::take()
|
||||||
|
.unwrap()
|
||||||
|
.into_gpio_pin(iocon, gpio)
|
||||||
|
.into_output_low(),
|
||||||
|
);
|
||||||
|
unsafe {
|
||||||
|
core::ptr::write(LED1.as_ptr() as *mut SharedLed<Led1>, led1);
|
||||||
|
core::ptr::write(LED2.as_ptr() as *mut SharedLed<Led2>, led2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn led1() -> &'static SharedLed<Led1> {
|
||||||
|
unsafe { &*LED1.as_ptr() }
|
||||||
|
}
|
||||||
|
pub fn led2() -> &'static SharedLed<Led2> {
|
||||||
|
unsafe { &*LED2.as_ptr() }
|
||||||
|
}
|
||||||
+543
-230
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,12 @@
|
|||||||
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);
|
||||||
|
|||||||
@@ -1,39 +0,0 @@
|
|||||||
from dataclasses import dataclass
|
|
||||||
import struct
|
|
||||||
from time import sleep
|
|
||||||
from typing import Self
|
|
||||||
import hid
|
|
||||||
|
|
||||||
VID = 0x1209
|
|
||||||
PID = 0xCC1D
|
|
||||||
INTERVAL = 0.1
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class AudioTelemetry:
|
|
||||||
STRUCT = "<LLLLL"
|
|
||||||
LEN = struct.calcsize(STRUCT)
|
|
||||||
|
|
||||||
average_buffer_fill: int
|
|
||||||
frame_count: int
|
|
||||||
dac_underflow_count: int
|
|
||||||
usb_underflow_count: int
|
|
||||||
dac_overflow_count: int
|
|
||||||
|
|
||||||
def from_bytes(b: bytes) -> Self:
|
|
||||||
if len(b) != AudioTelemetry.LEN:
|
|
||||||
raise ValueError(f"wrong size report ({len(b)} != {AudioTelemetry.LEN})")
|
|
||||||
fields = struct.unpack(AudioTelemetry.STRUCT, b)
|
|
||||||
return AudioTelemetry(*fields)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
with hid.Device(VID, PID) as h:
|
|
||||||
while True:
|
|
||||||
report = AudioTelemetry.from_bytes(h.read(AudioTelemetry.LEN))
|
|
||||||
print(f"{report}")
|
|
||||||
sleep(INTERVAL)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
[project]
|
|
||||||
name = "guac-scripts"
|
|
||||||
version = "0.1.0"
|
|
||||||
description = "Scripts to work with GUAC devices"
|
|
||||||
readme = "README.md"
|
|
||||||
requires-python = ">=3.12"
|
|
||||||
dependencies = [
|
|
||||||
"hid>=1.0.9",
|
|
||||||
"rich-click>=1.9.7",
|
|
||||||
]
|
|
||||||
@@ -2,6 +2,16 @@
|
|||||||
name = "shared"
|
name = "shared"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
std = ["deku/alloc", "heapless/alloc", "wary/std", "wary/alloc"]
|
||||||
|
serde = ["dep:serde", "heapless/serde"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
bytemuck = { version = "1.25.0", features = ["derive"] }
|
||||||
|
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 }
|
||||||
|
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"] }
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
use super::schema::DeviceConfig;
|
||||||
|
use super::{ConfigError, Tlv, TlvList};
|
||||||
|
|
||||||
|
pub const MAGIC: [u8; 4] = *b"GUAC";
|
||||||
|
|
||||||
|
const HEADER_LEN: usize = 8;
|
||||||
|
const CRC_LEN: usize = 4;
|
||||||
|
|
||||||
|
pub fn crc32(data: &[u8]) -> u32 {
|
||||||
|
let mut crc = 0xffff_ffffu32;
|
||||||
|
|
||||||
|
for &byte in data {
|
||||||
|
crc ^= byte as u32;
|
||||||
|
for _ in 0..8 {
|
||||||
|
let mask = (crc & 1).wrapping_neg();
|
||||||
|
crc = (crc >> 1) ^ (0xedb8_8320 & mask);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
!crc
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[cfg_attr(feature = "serde", serde(transparent))]
|
||||||
|
pub struct ConfigV1 {
|
||||||
|
pub tlvs: TlvList,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConfigV1 {
|
||||||
|
pub fn encoded_len(&self) -> usize {
|
||||||
|
2 + self.tlvs.encoded_len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(payload: &[u8]) -> Result<Self, ConfigError> {
|
||||||
|
if payload.len() < 2 {
|
||||||
|
return Err(ConfigError::Truncated {
|
||||||
|
needed: 2,
|
||||||
|
available: payload.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let count = u16::from_le_bytes([payload[0], payload[1]]);
|
||||||
|
let mut tlvs = TlvList::new();
|
||||||
|
let mut offset = 2;
|
||||||
|
|
||||||
|
for _ in 0..count {
|
||||||
|
let (tlv, used) = Tlv::parse(&payload[offset..])?;
|
||||||
|
tlvs.push(tlv)?;
|
||||||
|
offset += used;
|
||||||
|
}
|
||||||
|
|
||||||
|
if offset != payload.len() {
|
||||||
|
return Err(ConfigError::TrailingBytes(payload.len() - offset));
|
||||||
|
}
|
||||||
|
|
||||||
|
let config = Self { tlvs };
|
||||||
|
config.validate()?;
|
||||||
|
Ok(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate(&self) -> Result<(), ConfigError> {
|
||||||
|
DeviceConfig::from_tlvs(&self.tlvs).map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encode(&self, out: &mut [u8]) -> Result<usize, ConfigError> {
|
||||||
|
self.validate()?;
|
||||||
|
|
||||||
|
let needed = self.encoded_len();
|
||||||
|
if out.len() < needed {
|
||||||
|
return Err(ConfigError::BufferTooSmall {
|
||||||
|
needed,
|
||||||
|
available: out.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.tlvs.len() > u16::MAX as usize {
|
||||||
|
return Err(ConfigError::ConfigTooLarge(self.tlvs.len()));
|
||||||
|
}
|
||||||
|
|
||||||
|
out[..2].copy_from_slice(&(self.tlvs.len() as u16).to_le_bytes());
|
||||||
|
|
||||||
|
let mut offset = 2;
|
||||||
|
for tlv in self.tlvs.iter() {
|
||||||
|
offset += tlv.encode(&mut out[offset..])?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(offset)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
pub enum ConfigVersion {
|
||||||
|
V1(ConfigV1),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConfigVersion {
|
||||||
|
pub const fn version(&self) -> u16 {
|
||||||
|
match self {
|
||||||
|
Self::V1(_) => 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encoded_len(&self) -> usize {
|
||||||
|
match self {
|
||||||
|
Self::V1(config) => config.encoded_len(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse(version: u16, payload: &[u8]) -> Result<Self, ConfigError> {
|
||||||
|
match version {
|
||||||
|
1 => ConfigV1::parse(payload).map(Self::V1),
|
||||||
|
version => Err(ConfigError::UnsupportedVersion(version)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate(&self) -> Result<(), ConfigError> {
|
||||||
|
match self {
|
||||||
|
Self::V1(config) => config.validate(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode(&self, out: &mut [u8]) -> Result<usize, ConfigError> {
|
||||||
|
match self {
|
||||||
|
Self::V1(config) => config.encode(out),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct ConfigSnapshot {
|
||||||
|
pub active_slot: u8,
|
||||||
|
pub config: ConfigV1,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConfigSnapshot {
|
||||||
|
pub fn encoded_len(&self) -> usize {
|
||||||
|
1 + self.config.encoded_len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(bytes: &[u8]) -> Result<Self, ConfigError> {
|
||||||
|
let Some((&active_slot, payload)) = bytes.split_first() else {
|
||||||
|
return Err(ConfigError::Truncated {
|
||||||
|
needed: 1,
|
||||||
|
available: 0,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
active_slot,
|
||||||
|
config: ConfigV1::parse(payload)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encode(&self, out: &mut [u8]) -> Result<usize, ConfigError> {
|
||||||
|
if out.is_empty() {
|
||||||
|
return Err(ConfigError::BufferTooSmall {
|
||||||
|
needed: self.encoded_len(),
|
||||||
|
available: 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
out[0] = self.active_slot;
|
||||||
|
Ok(1 + self.config.encode(&mut out[1..])?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[cfg_attr(feature = "serde", serde(transparent))]
|
||||||
|
pub struct ConfigContainer {
|
||||||
|
pub config: ConfigVersion,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConfigContainer {
|
||||||
|
pub fn new(config: ConfigVersion) -> Self {
|
||||||
|
Self { config }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn version(&self) -> u16 {
|
||||||
|
self.config.version()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn payload_len(&self) -> usize {
|
||||||
|
self.config.encoded_len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encoded_len(&self) -> usize {
|
||||||
|
HEADER_LEN + self.payload_len() + CRC_LEN
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(bytes: &[u8]) -> Result<(Self, usize), ConfigError> {
|
||||||
|
if bytes.len() < HEADER_LEN + CRC_LEN || bytes.iter().all(|&byte| byte == 0xff) {
|
||||||
|
return Err(ConfigError::NotPresent);
|
||||||
|
}
|
||||||
|
|
||||||
|
if bytes[..4] != MAGIC {
|
||||||
|
return Err(ConfigError::BadMagic);
|
||||||
|
}
|
||||||
|
|
||||||
|
let version = u16::from_le_bytes([bytes[4], bytes[5]]);
|
||||||
|
let payload_len = u16::from_le_bytes([bytes[6], bytes[7]]) as usize;
|
||||||
|
let total = HEADER_LEN + payload_len + CRC_LEN;
|
||||||
|
|
||||||
|
if bytes.len() < total {
|
||||||
|
return Err(ConfigError::Truncated {
|
||||||
|
needed: total,
|
||||||
|
available: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let crc_offset = HEADER_LEN + payload_len;
|
||||||
|
let expected = u32::from_le_bytes([
|
||||||
|
bytes[crc_offset],
|
||||||
|
bytes[crc_offset + 1],
|
||||||
|
bytes[crc_offset + 2],
|
||||||
|
bytes[crc_offset + 3],
|
||||||
|
]);
|
||||||
|
let actual = crc32(&bytes[..crc_offset]);
|
||||||
|
|
||||||
|
if expected != actual {
|
||||||
|
return Err(ConfigError::CrcMismatch { expected, actual });
|
||||||
|
}
|
||||||
|
|
||||||
|
let config = ConfigVersion::parse(version, &bytes[HEADER_LEN..HEADER_LEN + payload_len])?;
|
||||||
|
|
||||||
|
Ok((Self { config }, total))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encode(&self, out: &mut [u8]) -> Result<usize, ConfigError> {
|
||||||
|
self.config.validate()?;
|
||||||
|
|
||||||
|
let payload_len = self.payload_len();
|
||||||
|
let total = HEADER_LEN + payload_len + CRC_LEN;
|
||||||
|
|
||||||
|
if out.len() < total {
|
||||||
|
return Err(ConfigError::BufferTooSmall {
|
||||||
|
needed: total,
|
||||||
|
available: out.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if payload_len > u16::MAX as usize {
|
||||||
|
return Err(ConfigError::ConfigTooLarge(payload_len));
|
||||||
|
}
|
||||||
|
|
||||||
|
out[..4].copy_from_slice(&MAGIC);
|
||||||
|
out[4..6].copy_from_slice(&self.version().to_le_bytes());
|
||||||
|
out[6..8].copy_from_slice(&(payload_len as u16).to_le_bytes());
|
||||||
|
|
||||||
|
let written = self
|
||||||
|
.config
|
||||||
|
.encode(&mut out[HEADER_LEN..HEADER_LEN + payload_len])?;
|
||||||
|
debug_assert_eq!(written, payload_len);
|
||||||
|
|
||||||
|
let crc = crc32(&out[..HEADER_LEN + payload_len]);
|
||||||
|
out[HEADER_LEN + payload_len..total].copy_from_slice(&crc.to_le_bytes());
|
||||||
|
|
||||||
|
Ok(total)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<ConfigVersion> for ConfigContainer {
|
||||||
|
fn from(config: ConfigVersion) -> Self {
|
||||||
|
Self::new(config)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
use super::ConfigTag;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, defmt::Format)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
NotPresent,
|
||||||
|
BadMagic,
|
||||||
|
Truncated {
|
||||||
|
needed: usize,
|
||||||
|
available: usize,
|
||||||
|
},
|
||||||
|
UnsupportedVersion(u16),
|
||||||
|
ValueTooLong {
|
||||||
|
len: usize,
|
||||||
|
max: usize,
|
||||||
|
},
|
||||||
|
BadValueLength {
|
||||||
|
tag: ConfigTag,
|
||||||
|
expected: usize,
|
||||||
|
actual: usize,
|
||||||
|
},
|
||||||
|
InvalidUtf8 {
|
||||||
|
tag: ConfigTag,
|
||||||
|
},
|
||||||
|
Invalid {
|
||||||
|
errors: usize,
|
||||||
|
},
|
||||||
|
UnknownTag(ConfigTag),
|
||||||
|
InvalidHardwareInfo,
|
||||||
|
TooManyTlvs,
|
||||||
|
TrailingBytes(usize),
|
||||||
|
CrcMismatch {
|
||||||
|
expected: u32,
|
||||||
|
actual: u32,
|
||||||
|
},
|
||||||
|
Missing(ConfigTag),
|
||||||
|
BufferTooSmall {
|
||||||
|
needed: usize,
|
||||||
|
available: usize,
|
||||||
|
},
|
||||||
|
ConfigTooLarge(usize),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl core::fmt::Display for ConfigError {
|
||||||
|
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::NotPresent => write!(f, "config not present"),
|
||||||
|
Self::BadMagic => write!(f, "bad config magic"),
|
||||||
|
Self::Truncated { needed, available } => {
|
||||||
|
write!(f, "config truncated: need {needed} bytes, have {available}")
|
||||||
|
}
|
||||||
|
Self::UnsupportedVersion(version) => {
|
||||||
|
write!(f, "unsupported config version {version}")
|
||||||
|
}
|
||||||
|
Self::ValueTooLong { len, max } => {
|
||||||
|
write!(f, "config value too long: {len} > {max}")
|
||||||
|
}
|
||||||
|
Self::BadValueLength {
|
||||||
|
tag,
|
||||||
|
expected,
|
||||||
|
actual,
|
||||||
|
} => write!(
|
||||||
|
f,
|
||||||
|
"bad value length for tag {:?}: expected {expected}, got {actual}",
|
||||||
|
tag
|
||||||
|
),
|
||||||
|
Self::InvalidUtf8 { tag } => write!(f, "invalid UTF-8 for tag {tag:?}"),
|
||||||
|
Self::Invalid { errors } => {
|
||||||
|
write!(f, "config validation failed ({errors} errors)")
|
||||||
|
}
|
||||||
|
Self::UnknownTag(tag) => write!(f, "unknown config tag {tag:?}"),
|
||||||
|
Self::InvalidHardwareInfo => write!(f, "invalid hardware info"),
|
||||||
|
Self::TooManyTlvs => write!(f, "too many TLVs"),
|
||||||
|
Self::TrailingBytes(len) => write!(f, "trailing config bytes: {len}"),
|
||||||
|
Self::CrcMismatch { expected, actual } => {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"CRC mismatch: expected {expected:#010x}, got {actual:#010x}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Self::Missing(tag) => write!(f, "missing config tag {tag:?}"),
|
||||||
|
Self::BufferTooSmall { needed, available } => {
|
||||||
|
write!(f, "buffer too small: need {needed}, have {available}")
|
||||||
|
}
|
||||||
|
Self::ConfigTooLarge(len) => write!(f, "config too large: {len}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl core::error::Error for ConfigError {}
|
||||||
@@ -0,0 +1,607 @@
|
|||||||
|
mod container;
|
||||||
|
mod error;
|
||||||
|
mod schema;
|
||||||
|
mod tag;
|
||||||
|
mod tlv;
|
||||||
|
mod value;
|
||||||
|
|
||||||
|
pub use container::{ConfigContainer, ConfigSnapshot, ConfigV1, ConfigVersion, MAGIC, crc32};
|
||||||
|
pub use error::ConfigError;
|
||||||
|
pub use schema::DeviceConfig;
|
||||||
|
pub use tag::{ConfigTag, tags};
|
||||||
|
pub use tlv::{ConfigKey, MAX_TLVS, Tlv, TlvList};
|
||||||
|
pub use value::{ConfigBytes, ConfigString, ConfigValue, MAX_VALUE_LEN};
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::schema::{ManufString, ProductId, ProductString, SerialString, VendorId};
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const MANUF_STRING: &[u8] = b"VE7XEN";
|
||||||
|
|
||||||
|
fn bytes(value: &[u8]) -> ConfigBytes<MAX_VALUE_LEN> {
|
||||||
|
ConfigBytes::from_slice(value).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn payload(tlvs: &[Tlv]) -> ([u8; 64], usize) {
|
||||||
|
let mut buf = [0u8; 64];
|
||||||
|
buf[..2].copy_from_slice(&(tlvs.len() as u16).to_le_bytes());
|
||||||
|
|
||||||
|
let mut offset = 2;
|
||||||
|
for tlv in tlvs {
|
||||||
|
offset += tlv.encode(&mut buf[offset..]).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
(buf, offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn manuf_tlv() -> Tlv {
|
||||||
|
Tlv {
|
||||||
|
tag: tags::MANUF_STRING,
|
||||||
|
value: bytes(MANUF_STRING),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn v1_with_manuf() -> ConfigV1 {
|
||||||
|
let mut tlvs = TlvList::new();
|
||||||
|
tlvs.push(manuf_tlv()).unwrap();
|
||||||
|
ConfigV1 { tlvs }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn container_with_manuf() -> ConfigContainer {
|
||||||
|
ConfigContainer::new(ConfigVersion::V1(v1_with_manuf()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tlv_wire_format_is_stable() {
|
||||||
|
let tlv = manuf_tlv();
|
||||||
|
let mut buf = [0u8; 16];
|
||||||
|
let len = tlv.encode(&mut buf).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
&buf[..len],
|
||||||
|
&[0x03, 0x00, 0x06, 0x00, b'V', b'E', b'7', b'X', b'E', b'N']
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tlv_roundtrip() {
|
||||||
|
let tlv = manuf_tlv();
|
||||||
|
let mut buf = [0u8; 16];
|
||||||
|
let len = tlv.encode(&mut buf).unwrap();
|
||||||
|
|
||||||
|
let (decoded, consumed) = Tlv::parse(&buf[..len]).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(decoded, tlv);
|
||||||
|
assert_eq!(consumed, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_v1_roundtrip() {
|
||||||
|
let config = v1_with_manuf();
|
||||||
|
let mut buf = [0u8; 32];
|
||||||
|
let len = config.encode(&mut buf).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(&buf[..2], &[0x01, 0x00]);
|
||||||
|
|
||||||
|
let decoded = ConfigV1::parse(&buf[..len]).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(decoded, config);
|
||||||
|
assert_eq!(len, config.encoded_len());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_config_roundtrip() {
|
||||||
|
let config = ConfigV1::default();
|
||||||
|
let mut buf = [0u8; 4];
|
||||||
|
let len = config.encode(&mut buf).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(&buf[..len], &[0x00, 0x00]);
|
||||||
|
assert_eq!(ConfigV1::parse(&buf[..len]).unwrap(), config);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_container_roundtrip() {
|
||||||
|
let container = container_with_manuf();
|
||||||
|
let mut buf = [0u8; 64];
|
||||||
|
let len = container.encode(&mut buf).unwrap();
|
||||||
|
|
||||||
|
let (decoded, consumed) = ConfigContainer::parse(&buf[..len]).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(decoded, container);
|
||||||
|
assert_eq!(consumed, len);
|
||||||
|
assert_eq!(len, container.encoded_len());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_container_wire_format_is_stable() {
|
||||||
|
let container = container_with_manuf();
|
||||||
|
let mut buf = [0u8; 64];
|
||||||
|
let len = container.encode(&mut buf).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
&buf[..len],
|
||||||
|
&[
|
||||||
|
0x47, 0x55, 0x41, 0x43, // magic
|
||||||
|
0x01, 0x00, // version
|
||||||
|
0x0c, 0x00, // payload length
|
||||||
|
0x01, 0x00, // tlv count
|
||||||
|
0x03, 0x00, 0x06, 0x00, b'V', b'E', b'7', b'X', b'E', b'N', // tlv
|
||||||
|
0x22, 0x95, 0x37, 0x8b, // crc32
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_container_ignores_trailing_slot_bytes() {
|
||||||
|
let container = container_with_manuf();
|
||||||
|
let mut buf = [0xffu8; 64];
|
||||||
|
let len = container.encode(&mut buf).unwrap();
|
||||||
|
|
||||||
|
let (decoded, consumed) = ConfigContainer::parse(&buf).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(decoded, container);
|
||||||
|
assert_eq!(consumed, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_container_rejects_erased_slot() {
|
||||||
|
assert_eq!(
|
||||||
|
ConfigContainer::parse(&[0xff; 32]).unwrap_err(),
|
||||||
|
ConfigError::NotPresent
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_container_rejects_bad_magic() {
|
||||||
|
assert_eq!(
|
||||||
|
ConfigContainer::parse(&[0x00; 32]).unwrap_err(),
|
||||||
|
ConfigError::BadMagic
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_container_rejects_bad_crc() {
|
||||||
|
let container = container_with_manuf();
|
||||||
|
let mut buf = [0u8; 64];
|
||||||
|
let len = container.encode(&mut buf).unwrap();
|
||||||
|
buf[10] ^= 0xff;
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
ConfigContainer::parse(&buf[..len]),
|
||||||
|
Err(ConfigError::CrcMismatch { .. })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_container_rejects_unsupported_version() {
|
||||||
|
let container = container_with_manuf();
|
||||||
|
let mut buf = [0u8; 64];
|
||||||
|
let len = container.encode(&mut buf).unwrap();
|
||||||
|
let payload_len = u16::from_le_bytes([buf[6], buf[7]]) as usize;
|
||||||
|
|
||||||
|
buf[4..6].copy_from_slice(&2u16.to_le_bytes());
|
||||||
|
let crc = crc32(&buf[..8 + payload_len]);
|
||||||
|
buf[8 + payload_len..len].copy_from_slice(&crc.to_le_bytes());
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
ConfigContainer::parse(&buf[..len]).unwrap_err(),
|
||||||
|
ConfigError::UnsupportedVersion(2)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_container_rejects_truncated_payload() {
|
||||||
|
let container = container_with_manuf();
|
||||||
|
let mut buf = [0u8; 64];
|
||||||
|
let len = container.encode(&mut buf).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
ConfigContainer::parse(&buf[..len - 1]).unwrap_err(),
|
||||||
|
ConfigError::Truncated {
|
||||||
|
needed: len,
|
||||||
|
available: len - 1,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_v1_rejects_too_many_tlvs() {
|
||||||
|
let mut payload = [0u8; 2 + (MAX_TLVS + 1) * 4];
|
||||||
|
payload[..2].copy_from_slice(&((MAX_TLVS + 1) as u16).to_le_bytes());
|
||||||
|
|
||||||
|
for offset in (2..payload.len()).step_by(4) {
|
||||||
|
payload[offset..offset + 4].copy_from_slice(&[0x99, 0x99, 0x00, 0x00]);
|
||||||
|
}
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
ConfigV1::parse(&payload).unwrap_err(),
|
||||||
|
ConfigError::TooManyTlvs
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_v1_rejects_trailing_bytes() {
|
||||||
|
let config = v1_with_manuf();
|
||||||
|
let mut buf = [0u8; 16];
|
||||||
|
let len = config.encode(&mut buf).unwrap();
|
||||||
|
buf[len] = 0x00;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
ConfigV1::parse(&buf[..=len]).unwrap_err(),
|
||||||
|
ConfigError::TrailingBytes(1)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tlv_rejects_oversized_value() {
|
||||||
|
assert_eq!(
|
||||||
|
Tlv::parse(&[0x03, 0x00, 0x41, 0x00]).unwrap_err(),
|
||||||
|
ConfigError::ValueTooLong {
|
||||||
|
len: 65,
|
||||||
|
max: MAX_VALUE_LEN,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tlv_rejects_truncated_value() {
|
||||||
|
assert_eq!(
|
||||||
|
Tlv::parse(&[0x03, 0x00, 0x06, 0x00, b'V']).unwrap_err(),
|
||||||
|
ConfigError::Truncated {
|
||||||
|
needed: 10,
|
||||||
|
available: 5,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_tag_roundtrips() {
|
||||||
|
let mut tlvs = TlvList::new();
|
||||||
|
tlvs.push(Tlv {
|
||||||
|
tag: ConfigTag(0x9999),
|
||||||
|
value: bytes(b"raw"),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let container = ConfigContainer::new(ConfigVersion::V1(ConfigV1 { tlvs }));
|
||||||
|
let mut buf = [0u8; 64];
|
||||||
|
let len = container.encode(&mut buf).unwrap();
|
||||||
|
let (decoded, _) = ConfigContainer::parse(&buf[..len]).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(decoded, container);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_container_rejects_small_buffer() {
|
||||||
|
let container = container_with_manuf();
|
||||||
|
let mut buf = [0u8; 4];
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
container.encode(&mut buf).unwrap_err(),
|
||||||
|
ConfigError::BufferTooSmall {
|
||||||
|
needed: 24,
|
||||||
|
available: 4,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn typed_value_roundtrip() {
|
||||||
|
let mut tlvs = TlvList::new();
|
||||||
|
tlvs.set::<VendorId>(0x1209).unwrap();
|
||||||
|
tlvs.set::<ManufString>(ConfigString::<32>::try_from("VE7XEN").unwrap())
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(tlvs.get::<VendorId>().unwrap(), Some(0x1209));
|
||||||
|
assert_eq!(
|
||||||
|
tlvs.get::<ManufString>().unwrap(),
|
||||||
|
Some(ConfigString::<32>::try_from("VE7XEN").unwrap())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn typed_value_uses_little_endian() {
|
||||||
|
let mut tlvs = TlvList::new();
|
||||||
|
tlvs.set::<VendorId>(0x1209).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
tlvs.find(tags::VENDOR_ID).unwrap().value.as_slice(),
|
||||||
|
&[0x09, 0x12]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn typed_value_rejects_bad_length() {
|
||||||
|
let mut tlvs = TlvList::new();
|
||||||
|
tlvs.push(Tlv {
|
||||||
|
tag: tags::VENDOR_ID,
|
||||||
|
value: bytes(&[1, 2, 3]),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
tlvs.get::<VendorId>().unwrap_err(),
|
||||||
|
ConfigError::BadValueLength {
|
||||||
|
tag: tags::VENDOR_ID,
|
||||||
|
expected: 2,
|
||||||
|
actual: 3,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn string_value_rejects_invalid_utf8() {
|
||||||
|
let mut tlvs = TlvList::new();
|
||||||
|
tlvs.push(Tlv {
|
||||||
|
tag: tags::MANUF_STRING,
|
||||||
|
value: bytes(&[0xff]),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
tlvs.get::<ManufString>().unwrap_err(),
|
||||||
|
ConfigError::InvalidUtf8 {
|
||||||
|
tag: tags::MANUF_STRING,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn string_value_rejects_too_long() {
|
||||||
|
assert_eq!(
|
||||||
|
ConfigString::<4>::try_from("hello").unwrap_err(),
|
||||||
|
ConfigError::ValueTooLong { len: 5, max: 4 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicate_tags_first_match_wins() {
|
||||||
|
let mut tlvs = TlvList::new();
|
||||||
|
tlvs.push(Tlv {
|
||||||
|
tag: tags::VENDOR_ID,
|
||||||
|
value: bytes(&0x1111u16.to_le_bytes()),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
tlvs.push(Tlv {
|
||||||
|
tag: tags::VENDOR_ID,
|
||||||
|
value: bytes(&0x2222u16.to_le_bytes()),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(tlvs.get::<VendorId>().unwrap(), Some(0x1111));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn set_replaces_existing_tag() {
|
||||||
|
let mut tlvs = TlvList::new();
|
||||||
|
tlvs.set::<VendorId>(0x1111).unwrap();
|
||||||
|
tlvs.set::<VendorId>(0x2222).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(tlvs.len(), 1);
|
||||||
|
assert_eq!(tlvs.get::<VendorId>().unwrap(), Some(0x2222));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_key_returns_none() {
|
||||||
|
assert_eq!(TlvList::new().get::<VendorId>().unwrap(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_v1_rejects_zero_vendor_id() {
|
||||||
|
let (buf, len) = payload(&[Tlv {
|
||||||
|
tag: tags::VENDOR_ID,
|
||||||
|
value: bytes(&0u16.to_le_bytes()),
|
||||||
|
}]);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
ConfigV1::parse(&buf[..len]).unwrap_err(),
|
||||||
|
ConfigError::Invalid { errors: 1 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_v1_rejects_bad_known_value_length() {
|
||||||
|
let (buf, len) = payload(&[Tlv {
|
||||||
|
tag: tags::VENDOR_ID,
|
||||||
|
value: bytes(&[1, 2, 3]),
|
||||||
|
}]);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
ConfigV1::parse(&buf[..len]).unwrap_err(),
|
||||||
|
ConfigError::BadValueLength {
|
||||||
|
tag: tags::VENDOR_ID,
|
||||||
|
expected: 2,
|
||||||
|
actual: 3,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_v1_rejects_invalid_known_utf8() {
|
||||||
|
let (buf, len) = payload(&[Tlv {
|
||||||
|
tag: tags::MANUF_STRING,
|
||||||
|
value: bytes(&[0xff]),
|
||||||
|
}]);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
ConfigV1::parse(&buf[..len]).unwrap_err(),
|
||||||
|
ConfigError::InvalidUtf8 {
|
||||||
|
tag: tags::MANUF_STRING,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_v1_rejects_empty_serial() {
|
||||||
|
let (buf, len) = payload(&[Tlv {
|
||||||
|
tag: tags::SERIAL_STRING,
|
||||||
|
value: bytes(&[]),
|
||||||
|
}]);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
ConfigV1::parse(&buf[..len]).unwrap_err(),
|
||||||
|
ConfigError::Invalid { errors: 1 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_v1_counts_validation_errors() {
|
||||||
|
let (buf, len) = payload(&[
|
||||||
|
Tlv {
|
||||||
|
tag: tags::VENDOR_ID,
|
||||||
|
value: bytes(&0u16.to_le_bytes()),
|
||||||
|
},
|
||||||
|
Tlv {
|
||||||
|
tag: tags::PRODUCT_ID,
|
||||||
|
value: bytes(&0u16.to_le_bytes()),
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
ConfigV1::parse(&buf[..len]).unwrap_err(),
|
||||||
|
ConfigError::Invalid { errors: 2 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_v1_rejects_empty_manufacturer() {
|
||||||
|
let (buf, len) = payload(&[Tlv {
|
||||||
|
tag: tags::MANUF_STRING,
|
||||||
|
value: bytes(&[]),
|
||||||
|
}]);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
ConfigV1::parse(&buf[..len]).unwrap_err(),
|
||||||
|
ConfigError::Invalid { errors: 1 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encode_rejects_invalid_config() {
|
||||||
|
let mut tlvs = TlvList::new();
|
||||||
|
tlvs.push(Tlv {
|
||||||
|
tag: tags::VENDOR_ID,
|
||||||
|
value: bytes(&0u16.to_le_bytes()),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let mut buf = [0u8; 64];
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
ConfigV1 { tlvs }.encode(&mut buf).unwrap_err(),
|
||||||
|
ConfigError::Invalid { errors: 1 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn device_config_defaults() {
|
||||||
|
let config = DeviceConfig::with_defaults(None).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(config.usb_vendor_id, 0x1209);
|
||||||
|
assert_eq!(config.usb_product_id, 0xcc1d);
|
||||||
|
assert_eq!(config.usb_manufacturer.as_str(), "VE7XEN");
|
||||||
|
assert_eq!(config.usb_product.as_str(), "Guac Tortilla");
|
||||||
|
assert!(config.usb_serial.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn device_config_from_tlvs() {
|
||||||
|
let mut tlvs = TlvList::new();
|
||||||
|
tlvs.set::<VendorId>(0x1234).unwrap();
|
||||||
|
tlvs.set::<ProductId>(0x5678).unwrap();
|
||||||
|
tlvs.set::<ManufString>(ConfigString::try_from("Maker").unwrap())
|
||||||
|
.unwrap();
|
||||||
|
tlvs.set::<ProductString>(ConfigString::try_from("Widget").unwrap())
|
||||||
|
.unwrap();
|
||||||
|
tlvs.set::<SerialString>(ConfigString::try_from("SN123").unwrap())
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let config = DeviceConfig::from_tlvs(&tlvs).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(config.usb_vendor_id, 0x1234);
|
||||||
|
assert_eq!(config.usb_product_id, 0x5678);
|
||||||
|
assert_eq!(config.usb_manufacturer.as_str(), "Maker");
|
||||||
|
assert_eq!(config.usb_product.as_str(), "Widget");
|
||||||
|
assert_eq!(config.usb_serial.as_ref().unwrap().as_str(), "SN123");
|
||||||
|
assert_eq!(
|
||||||
|
DeviceConfig::from_tlvs(&config.to_tlvs().unwrap()).unwrap(),
|
||||||
|
config
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn device_config_with_serial_defaults() {
|
||||||
|
let serial = ConfigString::<32>::try_from("0123456789ABCDEF0123456789ABCDEF").unwrap();
|
||||||
|
let config = DeviceConfig::with_defaults(Some(serial.clone())).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(config.usb_vendor_id, 0x1209);
|
||||||
|
assert_eq!(config.usb_manufacturer.as_str(), "VE7XEN");
|
||||||
|
assert_eq!(config.usb_serial, Some(serial));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_snapshot_roundtrip() {
|
||||||
|
let snapshot = ConfigSnapshot {
|
||||||
|
active_slot: 1,
|
||||||
|
config: v1_with_manuf(),
|
||||||
|
};
|
||||||
|
let mut buf = [0u8; 64];
|
||||||
|
let len = snapshot.encode(&mut buf).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(len, snapshot.encoded_len());
|
||||||
|
assert_eq!(ConfigSnapshot::parse(&buf[..len]).unwrap(), snapshot);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replace_tlv_updates_config() {
|
||||||
|
let mut config = DeviceConfig::with_defaults(None).unwrap();
|
||||||
|
|
||||||
|
config
|
||||||
|
.replace_tlv(Tlv {
|
||||||
|
tag: tags::VENDOR_ID,
|
||||||
|
value: bytes(&0x1234u16.to_le_bytes()),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(config.usb_vendor_id, 0x1234);
|
||||||
|
|
||||||
|
config
|
||||||
|
.replace_tlv(Tlv {
|
||||||
|
tag: tags::SERIAL_STRING,
|
||||||
|
value: bytes(b"SN123"),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(config.usb_serial.as_ref().unwrap().as_str(), "SN123");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
config
|
||||||
|
.replace_tlv(Tlv {
|
||||||
|
tag: ConfigTag(0x9999),
|
||||||
|
value: bytes(b"x"),
|
||||||
|
})
|
||||||
|
.unwrap_err(),
|
||||||
|
ConfigError::UnknownTag(ConfigTag(0x9999))
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
config
|
||||||
|
.replace_tlv(Tlv {
|
||||||
|
tag: tags::VENDOR_ID,
|
||||||
|
value: bytes(&0u16.to_le_bytes()),
|
||||||
|
})
|
||||||
|
.unwrap_err(),
|
||||||
|
ConfigError::Invalid { errors: 1 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn crc32_known_vector() {
|
||||||
|
assert_eq!(crc32(b"123456789"), 0xcbf4_3926);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tag_name() {
|
||||||
|
assert_eq!(tags::VENDOR_ID.name(), Some("VendorId"));
|
||||||
|
assert_eq!(ConfigTag(0x9999).name(), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
use wary::Validate;
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
ConfigError, ConfigKey, ConfigString, ConfigTag, ConfigV1, ConfigVersion, Tlv, TlvList, tags,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, wary::Wary)]
|
||||||
|
pub struct DeviceConfig {
|
||||||
|
#[validate(range(1..))]
|
||||||
|
pub usb_vendor_id: u16,
|
||||||
|
|
||||||
|
#[validate(range(1..))]
|
||||||
|
pub usb_product_id: u16,
|
||||||
|
|
||||||
|
#[validate(dive)]
|
||||||
|
pub usb_manufacturer: ConfigString<32>,
|
||||||
|
|
||||||
|
#[validate(dive)]
|
||||||
|
pub usb_product: ConfigString<64>,
|
||||||
|
|
||||||
|
#[validate(dive)]
|
||||||
|
pub usb_serial: Option<ConfigString<32>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeviceConfig {
|
||||||
|
pub fn from_tlvs(tlvs: &TlvList) -> Result<Self, ConfigError> {
|
||||||
|
let config = Self {
|
||||||
|
usb_vendor_id: resolve::<VendorId>(tlvs)?,
|
||||||
|
usb_product_id: resolve::<ProductId>(tlvs)?,
|
||||||
|
usb_manufacturer: resolve::<ManufString>(tlvs)?,
|
||||||
|
usb_product: resolve::<ProductString>(tlvs)?,
|
||||||
|
usb_serial: tlvs.get::<SerialString>()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
config
|
||||||
|
.validate(&())
|
||||||
|
.map_err(|report| ConfigError::Invalid {
|
||||||
|
errors: report.len(),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_defaults(usb_serial: Option<ConfigString<32>>) -> Result<Self, ConfigError> {
|
||||||
|
let mut config = Self::from_tlvs(&TlvList::new())?;
|
||||||
|
config.usb_serial = usb_serial;
|
||||||
|
|
||||||
|
config
|
||||||
|
.validate(&())
|
||||||
|
.map_err(|report| ConfigError::Invalid {
|
||||||
|
errors: report.len(),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serial used for the default configuration, rendered as upper case hex.
|
||||||
|
pub fn serial_from_uuid(uuid: &[u8; 16]) -> Option<ConfigString<32>> {
|
||||||
|
const HEX: &[u8; 16] = b"0123456789ABCDEF";
|
||||||
|
|
||||||
|
let mut serial = [0u8; 32];
|
||||||
|
|
||||||
|
for (index, &byte) in uuid.iter().enumerate() {
|
||||||
|
serial[index * 2] = HEX[usize::from(byte >> 4)];
|
||||||
|
serial[index * 2 + 1] = HEX[usize::from(byte & 0x0f)];
|
||||||
|
}
|
||||||
|
|
||||||
|
let serial = core::str::from_utf8(&serial).ok()?;
|
||||||
|
ConfigString::try_from(serial).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn replace_tlv(&mut self, tlv: Tlv) -> Result<(), ConfigError> {
|
||||||
|
if tlv.tag.name().is_none() {
|
||||||
|
return Err(ConfigError::UnknownTag(tlv.tag));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut tlvs = self.to_tlvs()?;
|
||||||
|
tlvs.upsert(tlv)?;
|
||||||
|
*self = Self::from_tlvs(&tlvs)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_tlvs(&self) -> Result<TlvList, ConfigError> {
|
||||||
|
let mut tlvs = TlvList::new();
|
||||||
|
tlvs.set::<VendorId>(self.usb_vendor_id)?;
|
||||||
|
tlvs.set::<ProductId>(self.usb_product_id)?;
|
||||||
|
tlvs.set::<ManufString>(self.usb_manufacturer.clone())?;
|
||||||
|
tlvs.set::<ProductString>(self.usb_product.clone())?;
|
||||||
|
|
||||||
|
if let Some(serial) = &self.usb_serial {
|
||||||
|
tlvs.set::<SerialString>(serial.clone())?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(tlvs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<&ConfigVersion> for DeviceConfig {
|
||||||
|
type Error = ConfigError;
|
||||||
|
|
||||||
|
fn try_from(value: &ConfigVersion) -> Result<Self, Self::Error> {
|
||||||
|
match value {
|
||||||
|
ConfigVersion::V1(config) => Self::try_from(config),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<&ConfigV1> for DeviceConfig {
|
||||||
|
type Error = ConfigError;
|
||||||
|
|
||||||
|
fn try_from(value: &ConfigV1) -> Result<Self, Self::Error> {
|
||||||
|
Self::from_tlvs(&value.tlvs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve<K: ConfigKey>(tlvs: &TlvList) -> Result<K::Value, ConfigError> {
|
||||||
|
tlvs.get::<K>()?
|
||||||
|
.or_else(K::default_value)
|
||||||
|
.ok_or(ConfigError::Missing(K::TAG))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct VendorId;
|
||||||
|
impl ConfigKey for VendorId {
|
||||||
|
const TAG: ConfigTag = tags::VENDOR_ID;
|
||||||
|
type Value = u16;
|
||||||
|
|
||||||
|
fn default_value() -> Option<Self::Value> {
|
||||||
|
Some(0x1209)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct ProductId;
|
||||||
|
impl ConfigKey for ProductId {
|
||||||
|
const TAG: ConfigTag = tags::PRODUCT_ID;
|
||||||
|
type Value = u16;
|
||||||
|
|
||||||
|
fn default_value() -> Option<Self::Value> {
|
||||||
|
Some(0xcc1d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct ManufString;
|
||||||
|
impl ConfigKey for ManufString {
|
||||||
|
const TAG: ConfigTag = tags::MANUF_STRING;
|
||||||
|
type Value = ConfigString<32>;
|
||||||
|
|
||||||
|
fn default_value() -> Option<Self::Value> {
|
||||||
|
Some(ConfigString::try_from("VE7XEN").unwrap_or_default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct ProductString;
|
||||||
|
impl ConfigKey for ProductString {
|
||||||
|
const TAG: ConfigTag = tags::PRODUCT_STRING;
|
||||||
|
type Value = ConfigString<64>;
|
||||||
|
|
||||||
|
fn default_value() -> Option<Self::Value> {
|
||||||
|
Some(ConfigString::try_from("Guac Tortilla").unwrap_or_default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct SerialString;
|
||||||
|
impl ConfigKey for SerialString {
|
||||||
|
const TAG: ConfigTag = tags::SERIAL_STRING;
|
||||||
|
type Value = ConfigString<32>;
|
||||||
|
|
||||||
|
fn default_value() -> Option<Self::Value> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serial_from_uuid_is_uppercase_hex() {
|
||||||
|
let uuid = [
|
||||||
|
0x35, 0x60, 0x14, 0xf7, 0x7b, 0x65, 0xb4, 0x5d, 0x9d, 0xbf, 0x81, 0x11, 0xc5, 0xc4,
|
||||||
|
0x29, 0xa5,
|
||||||
|
];
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
DeviceConfig::serial_from_uuid(&uuid).unwrap().as_str(),
|
||||||
|
"356014F77B65B45D9DBF8111C5C429A5"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn defaults_are_valid() {
|
||||||
|
let config = DeviceConfig::with_defaults(None).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(config.usb_vendor_id, 0x1209);
|
||||||
|
assert_eq!(config.usb_product_id, 0xcc1d);
|
||||||
|
assert!(config.usb_serial.is_none());
|
||||||
|
assert_eq!(config.to_tlvs().unwrap().len(), 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, defmt::Format)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
pub struct ConfigTag(pub u16);
|
||||||
|
|
||||||
|
pub mod tags {
|
||||||
|
use super::ConfigTag;
|
||||||
|
|
||||||
|
pub const VENDOR_ID: ConfigTag = ConfigTag(0x0001);
|
||||||
|
pub const PRODUCT_ID: ConfigTag = ConfigTag(0x0002);
|
||||||
|
pub const MANUF_STRING: ConfigTag = ConfigTag(0x0003);
|
||||||
|
pub const PRODUCT_STRING: ConfigTag = ConfigTag(0x0004);
|
||||||
|
pub const SERIAL_STRING: ConfigTag = ConfigTag(0x0005);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConfigTag {
|
||||||
|
pub const fn name(self) -> Option<&'static str> {
|
||||||
|
match self.0 {
|
||||||
|
0x0001 => Some("VendorId"),
|
||||||
|
0x0002 => Some("ProductId"),
|
||||||
|
0x0003 => Some("ManufString"),
|
||||||
|
0x0004 => Some("ProductString"),
|
||||||
|
0x0005 => Some("SerialString"),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
use super::{ConfigBytes, ConfigError, ConfigTag, ConfigValue, MAX_VALUE_LEN};
|
||||||
|
|
||||||
|
pub const MAX_TLVS: usize = 64;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
pub struct Tlv {
|
||||||
|
pub tag: ConfigTag,
|
||||||
|
pub value: ConfigBytes<MAX_VALUE_LEN>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Tlv {
|
||||||
|
pub fn encoded_len(&self) -> usize {
|
||||||
|
4 + self.value.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(bytes: &[u8]) -> Result<(Self, usize), ConfigError> {
|
||||||
|
if bytes.len() < 4 {
|
||||||
|
return Err(ConfigError::Truncated {
|
||||||
|
needed: 4,
|
||||||
|
available: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let tag = ConfigTag(u16::from_le_bytes([bytes[0], bytes[1]]));
|
||||||
|
let len = u16::from_le_bytes([bytes[2], bytes[3]]) as usize;
|
||||||
|
|
||||||
|
if len > MAX_VALUE_LEN {
|
||||||
|
return Err(ConfigError::ValueTooLong {
|
||||||
|
len,
|
||||||
|
max: MAX_VALUE_LEN,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let needed = 4 + len;
|
||||||
|
if bytes.len() < needed {
|
||||||
|
return Err(ConfigError::Truncated {
|
||||||
|
needed,
|
||||||
|
available: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let value = ConfigBytes::from_slice(&bytes[4..needed])?;
|
||||||
|
|
||||||
|
Ok((Self { tag, value }, needed))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encode(&self, out: &mut [u8]) -> Result<usize, ConfigError> {
|
||||||
|
let needed = self.encoded_len();
|
||||||
|
if out.len() < needed {
|
||||||
|
return Err(ConfigError::BufferTooSmall {
|
||||||
|
needed,
|
||||||
|
available: out.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
out[..2].copy_from_slice(&self.tag.0.to_le_bytes());
|
||||||
|
out[2..4].copy_from_slice(&(self.value.len() as u16).to_le_bytes());
|
||||||
|
out[4..needed].copy_from_slice(self.value.as_slice());
|
||||||
|
|
||||||
|
Ok(needed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait ConfigKey {
|
||||||
|
const TAG: ConfigTag;
|
||||||
|
type Value: ConfigValue;
|
||||||
|
|
||||||
|
fn default_value() -> Option<Self::Value>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[cfg_attr(feature = "serde", serde(transparent))]
|
||||||
|
pub struct TlvList {
|
||||||
|
items: heapless::Vec<Tlv, MAX_TLVS>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TlvList {
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
items: heapless::Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_slice(&self) -> &[Tlv] {
|
||||||
|
self.items.as_slice()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn iter(&self) -> core::slice::Iter<'_, Tlv> {
|
||||||
|
self.items.iter()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.items.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.items.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push(&mut self, tlv: Tlv) -> Result<(), ConfigError> {
|
||||||
|
self.items.push(tlv).map_err(|_| ConfigError::TooManyTlvs)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find(&self, tag: ConfigTag) -> Option<&Tlv> {
|
||||||
|
self.items.iter().find(|tlv| tlv.tag == tag)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get<K: ConfigKey>(&self) -> Result<Option<K::Value>, ConfigError> {
|
||||||
|
self.find(K::TAG)
|
||||||
|
.map(|tlv| K::Value::decode(K::TAG, tlv.value.as_slice()))
|
||||||
|
.transpose()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set<K: ConfigKey>(&mut self, value: K::Value) -> Result<(), ConfigError> {
|
||||||
|
let mut bytes = ConfigBytes::new();
|
||||||
|
value.encode(&mut bytes)?;
|
||||||
|
self.upsert(Tlv {
|
||||||
|
tag: K::TAG,
|
||||||
|
value: bytes,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn upsert(&mut self, tlv: Tlv) -> Result<(), ConfigError> {
|
||||||
|
if let Some(existing) = self
|
||||||
|
.items
|
||||||
|
.iter_mut()
|
||||||
|
.find(|existing| existing.tag == tlv.tag)
|
||||||
|
{
|
||||||
|
existing.value = tlv.value;
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
self.push(tlv)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove(&mut self, tag: ConfigTag) -> bool {
|
||||||
|
if let Some(index) = self.items.iter().position(|tlv| tlv.tag == tag) {
|
||||||
|
self.items.remove(index);
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encoded_len(&self) -> usize {
|
||||||
|
self.items.iter().map(Tlv::encoded_len).sum()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for TlvList {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsRef<[Tlv]> for TlvList {
|
||||||
|
fn as_ref(&self) -> &[Tlv] {
|
||||||
|
self.as_slice()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl core::ops::Deref for TlvList {
|
||||||
|
type Target = [Tlv];
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
self.as_slice()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> IntoIterator for &'a TlvList {
|
||||||
|
type Item = &'a Tlv;
|
||||||
|
type IntoIter = core::slice::Iter<'a, Tlv>;
|
||||||
|
|
||||||
|
fn into_iter(self) -> Self::IntoIter {
|
||||||
|
self.iter()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
use super::{ConfigError, ConfigTag};
|
||||||
|
|
||||||
|
pub const MAX_VALUE_LEN: usize = 64;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
pub struct ConfigBytes<const N: usize = MAX_VALUE_LEN>(heapless::Vec<u8, N>);
|
||||||
|
|
||||||
|
impl<const N: usize> ConfigBytes<N> {
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self(heapless::Vec::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_slice(bytes: &[u8]) -> Result<Self, ConfigError> {
|
||||||
|
heapless::Vec::from_slice(bytes)
|
||||||
|
.map(Self)
|
||||||
|
.map_err(|_| ConfigError::ValueTooLong {
|
||||||
|
len: bytes.len(),
|
||||||
|
max: N,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_slice(&self) -> &[u8] {
|
||||||
|
self.0.as_slice()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.0.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.0.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn extend_from_slice(&mut self, bytes: &[u8]) -> Result<(), ConfigError> {
|
||||||
|
self.0
|
||||||
|
.extend_from_slice(bytes)
|
||||||
|
.map_err(|_| ConfigError::ValueTooLong {
|
||||||
|
len: self.0.len() + bytes.len(),
|
||||||
|
max: N,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> Default for ConfigBytes<N> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> AsRef<[u8]> for ConfigBytes<N> {
|
||||||
|
fn as_ref(&self) -> &[u8] {
|
||||||
|
self.as_slice()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> core::ops::Deref for ConfigBytes<N> {
|
||||||
|
type Target = [u8];
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
self.as_slice()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> TryFrom<&[u8]> for ConfigBytes<N> {
|
||||||
|
type Error = ConfigError;
|
||||||
|
|
||||||
|
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
|
||||||
|
Self::from_slice(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait ConfigValue: Sized {
|
||||||
|
fn decode(tag: ConfigTag, bytes: &[u8]) -> Result<Self, ConfigError>;
|
||||||
|
fn encode(&self, out: &mut ConfigBytes<MAX_VALUE_LEN>) -> Result<(), ConfigError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> ConfigValue for ConfigBytes<N> {
|
||||||
|
fn decode(_tag: ConfigTag, bytes: &[u8]) -> Result<Self, ConfigError> {
|
||||||
|
Self::from_slice(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode(&self, out: &mut ConfigBytes<MAX_VALUE_LEN>) -> Result<(), ConfigError> {
|
||||||
|
out.extend_from_slice(self.as_slice())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, wary::Wary)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[wary(transparent)]
|
||||||
|
pub struct ConfigString<const N: usize>(
|
||||||
|
#[validate(length(code_units, 1..=126))] heapless::String<N>,
|
||||||
|
);
|
||||||
|
|
||||||
|
impl<const N: usize> ConfigString<N> {
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self(heapless::String::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_str(&self) -> &str {
|
||||||
|
self.0.as_str()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_bytes(&self) -> &[u8] {
|
||||||
|
self.0.as_str().as_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.0.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.0.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> Default for ConfigString<N> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> AsRef<str> for ConfigString<N> {
|
||||||
|
fn as_ref(&self) -> &str {
|
||||||
|
self.as_str()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> core::ops::Deref for ConfigString<N> {
|
||||||
|
type Target = str;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
self.as_str()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> core::fmt::Display for ConfigString<N> {
|
||||||
|
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||||
|
f.write_str(self.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> TryFrom<&str> for ConfigString<N> {
|
||||||
|
type Error = ConfigError;
|
||||||
|
|
||||||
|
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||||
|
heapless::String::try_from(value)
|
||||||
|
.map(Self)
|
||||||
|
.map_err(|_| ConfigError::ValueTooLong {
|
||||||
|
len: value.len(),
|
||||||
|
max: N,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> ConfigValue for ConfigString<N> {
|
||||||
|
fn decode(tag: ConfigTag, bytes: &[u8]) -> Result<Self, ConfigError> {
|
||||||
|
let value = core::str::from_utf8(bytes).map_err(|_| ConfigError::InvalidUtf8 { tag })?;
|
||||||
|
|
||||||
|
Self::try_from(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode(&self, out: &mut ConfigBytes<MAX_VALUE_LEN>) -> Result<(), ConfigError> {
|
||||||
|
out.extend_from_slice(self.as_bytes())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConfigValue for u16 {
|
||||||
|
fn decode(tag: ConfigTag, bytes: &[u8]) -> Result<Self, ConfigError> {
|
||||||
|
let bytes: [u8; 2] = bytes.try_into().map_err(|_| ConfigError::BadValueLength {
|
||||||
|
tag,
|
||||||
|
expected: 2,
|
||||||
|
actual: bytes.len(),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(Self::from_le_bytes(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode(&self, out: &mut ConfigBytes<MAX_VALUE_LEN>) -> Result<(), ConfigError> {
|
||||||
|
out.extend_from_slice(&self.to_le_bytes())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
use crate::config::{ConfigError, ConfigString};
|
||||||
|
|
||||||
|
pub const UUID_LEN: usize = 16;
|
||||||
|
pub const MAX_DAC_NAME_LEN: usize = 32;
|
||||||
|
pub const MAX_VERSION_LEN: usize = 128;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct HardwareInfo {
|
||||||
|
pub uuid: [u8; UUID_LEN],
|
||||||
|
pub dac: ConfigString<MAX_DAC_NAME_LEN>,
|
||||||
|
pub version: ConfigString<MAX_VERSION_LEN>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HardwareInfo {
|
||||||
|
pub fn encoded_len(&self) -> usize {
|
||||||
|
UUID_LEN + 1 + self.dac.len() + 1 + self.version.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encode(&self, out: &mut [u8]) -> Result<usize, ConfigError> {
|
||||||
|
let dac = self.dac.as_bytes();
|
||||||
|
let version = self.version.as_bytes();
|
||||||
|
let needed = self.encoded_len();
|
||||||
|
|
||||||
|
if out.len() < needed {
|
||||||
|
return Err(ConfigError::BufferTooSmall {
|
||||||
|
needed,
|
||||||
|
available: out.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
out[..UUID_LEN].copy_from_slice(&self.uuid);
|
||||||
|
|
||||||
|
let mut offset = UUID_LEN;
|
||||||
|
out[offset] = dac.len() as u8;
|
||||||
|
offset += 1;
|
||||||
|
out[offset..offset + dac.len()].copy_from_slice(dac);
|
||||||
|
offset += dac.len();
|
||||||
|
|
||||||
|
out[offset] = version.len() as u8;
|
||||||
|
offset += 1;
|
||||||
|
out[offset..offset + version.len()].copy_from_slice(version);
|
||||||
|
|
||||||
|
Ok(needed)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(bytes: &[u8]) -> Result<Self, ConfigError> {
|
||||||
|
let mut offset = UUID_LEN;
|
||||||
|
|
||||||
|
if bytes.len() < offset + 1 {
|
||||||
|
return Err(ConfigError::Truncated {
|
||||||
|
needed: offset + 1,
|
||||||
|
available: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let uuid = bytes[..UUID_LEN]
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| ConfigError::InvalidHardwareInfo)?;
|
||||||
|
|
||||||
|
let dac_len = usize::from(bytes[offset]);
|
||||||
|
offset += 1;
|
||||||
|
|
||||||
|
if bytes.len() < offset + dac_len + 1 {
|
||||||
|
return Err(ConfigError::Truncated {
|
||||||
|
needed: offset + dac_len + 1,
|
||||||
|
available: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let dac = core::str::from_utf8(&bytes[offset..offset + dac_len])
|
||||||
|
.map_err(|_| ConfigError::InvalidHardwareInfo)?;
|
||||||
|
let dac = ConfigString::try_from(dac).map_err(|_| ConfigError::InvalidHardwareInfo)?;
|
||||||
|
offset += dac_len;
|
||||||
|
|
||||||
|
let version_len = usize::from(bytes[offset]);
|
||||||
|
offset += 1;
|
||||||
|
|
||||||
|
if bytes.len() < offset + version_len {
|
||||||
|
return Err(ConfigError::Truncated {
|
||||||
|
needed: offset + version_len,
|
||||||
|
available: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let version = core::str::from_utf8(&bytes[offset..offset + version_len])
|
||||||
|
.map_err(|_| ConfigError::InvalidHardwareInfo)?;
|
||||||
|
let version =
|
||||||
|
ConfigString::try_from(version).map_err(|_| ConfigError::InvalidHardwareInfo)?;
|
||||||
|
offset += version_len;
|
||||||
|
|
||||||
|
if offset != bytes.len() {
|
||||||
|
return Err(ConfigError::TrailingBytes(bytes.len() - offset));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self { uuid, dac, version })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn roundtrip() {
|
||||||
|
let info = HardwareInfo {
|
||||||
|
uuid: [
|
||||||
|
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
|
||||||
|
0xee, 0xff,
|
||||||
|
],
|
||||||
|
dac: ConfigString::try_from("AK4490").unwrap(),
|
||||||
|
version: ConfigString::try_from("v1.2.3").unwrap(),
|
||||||
|
};
|
||||||
|
let mut buf = [0u8; 128];
|
||||||
|
let len = info.encode(&mut buf).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(len, info.encoded_len());
|
||||||
|
assert_eq!(HardwareInfo::parse(&buf[..len]).unwrap(), info);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_trailing_bytes() {
|
||||||
|
let info = HardwareInfo {
|
||||||
|
uuid: [0; UUID_LEN],
|
||||||
|
dac: ConfigString::try_from("DAC").unwrap(),
|
||||||
|
version: ConfigString::try_from("abc").unwrap(),
|
||||||
|
};
|
||||||
|
let mut buf = [0u8; 128];
|
||||||
|
let len = info.encode(&mut buf).unwrap();
|
||||||
|
buf[len] = 0;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
HardwareInfo::parse(&buf[..=len]).unwrap_err(),
|
||||||
|
ConfigError::TrailingBytes(1)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+288
-6
@@ -1,27 +1,309 @@
|
|||||||
#![no_std]
|
#![no_std]
|
||||||
|
|
||||||
|
pub mod config;
|
||||||
|
pub mod hardware;
|
||||||
|
|
||||||
|
use bytemuck::NoUninit;
|
||||||
|
use num_enum::TryFromPrimitive;
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, NoUninit, Eq, PartialEq, TryFromPrimitive)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[repr(u8)]
|
||||||
|
pub enum AudioState {
|
||||||
|
/// Knowingly stopped, ie. AltSetting=0. DAC muted, I2S disabled.
|
||||||
|
///
|
||||||
|
/// AltSetting = 1 -> ARMED
|
||||||
|
#[default]
|
||||||
|
Stopped = 0,
|
||||||
|
/// Waiting for data. DAC muted, I2S running sending 0s (FIFO not serviced).
|
||||||
|
///
|
||||||
|
/// USB OUT data packet -> ARMED
|
||||||
|
/// AltSetting = 0 -> STOPPED
|
||||||
|
Armed = 1,
|
||||||
|
/// Filling the buffer before playback starts. Feedback does not run,
|
||||||
|
/// playout does not start draining the queue. Gets us better feedback
|
||||||
|
/// behaviour and a full buffer without a feedback rate spike at startup.
|
||||||
|
///
|
||||||
|
/// queue reaches <QUEUE_RUNNING_UP> -> RUNNING
|
||||||
|
/// AltSetting = 0 -> STOPPED
|
||||||
|
///
|
||||||
|
Prefill = 2,
|
||||||
|
/// Normal running state. Start servicing FIFO and begin playing out from the buffer.
|
||||||
|
///
|
||||||
|
/// queue reaches <QUEUE_RUNNING_DOWN> -> DRAINING
|
||||||
|
/// AltSetting = 0 -> DRAINING
|
||||||
|
Running = 3,
|
||||||
|
/// The queue is low. We will continue playout.
|
||||||
|
///
|
||||||
|
/// queue is empty && altSetting 1 -> NODATA
|
||||||
|
/// queue is empty && altSetting 0 -> STOPPED
|
||||||
|
/// queue reaches <QUEUE_RUNNING_UP> && altSetting 1 -> RUNNING
|
||||||
|
LowData = 4,
|
||||||
|
/// There is no data in the queue. We will count underflows for a while, send 0s, and hope the host comes back.
|
||||||
|
///
|
||||||
|
/// countdown reaches DATA_TIMEOUT -> STOPPED
|
||||||
|
/// AltSetting = 0 -> STOPPED
|
||||||
|
NoData = 5,
|
||||||
|
/// The host has asked us to stop (altSetting 0), but we need to play out the remaining buffer
|
||||||
|
///
|
||||||
|
/// queue is empty -> STOPPED
|
||||||
|
Stopping = 6,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl defmt::Format for AudioState {
|
||||||
|
fn format(&self, fmt: defmt::Formatter) {
|
||||||
|
defmt::write!(
|
||||||
|
fmt,
|
||||||
|
"{}",
|
||||||
|
match self {
|
||||||
|
Self::Stopped => "Stopped",
|
||||||
|
Self::Armed => "Armed",
|
||||||
|
Self::Prefill => "Prefill",
|
||||||
|
Self::Running => "Running",
|
||||||
|
Self::LowData => "Draining",
|
||||||
|
Self::NoData => "NoData",
|
||||||
|
Self::Stopping => "Stopping",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl core::fmt::Display for AudioState {
|
||||||
|
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"{}",
|
||||||
|
match self {
|
||||||
|
Self::Stopped => "Stopped",
|
||||||
|
Self::Armed => "Armed",
|
||||||
|
Self::Prefill => "Prefill",
|
||||||
|
Self::Running => "Running",
|
||||||
|
Self::LowData => "Draining",
|
||||||
|
Self::NoData => "NoData",
|
||||||
|
Self::Stopping => "Stopping",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub struct AudioTelemetrySnapshot {
|
||||||
|
pub state: AudioState,
|
||||||
|
pub average_buffer_fill: u16,
|
||||||
|
pub frame_count: u32,
|
||||||
|
pub dac_underflow_count: u16,
|
||||||
|
pub usb_underflow_count: u16,
|
||||||
|
pub dac_overflow_count: u16,
|
||||||
|
pub cur_rate: u32,
|
||||||
|
pub fb_rate_estimate: f32,
|
||||||
|
}
|
||||||
|
|
||||||
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};
|
||||||
|
|
||||||
|
/// HID usage IDs identifying each vendor interface. `gen_hid_descriptor` only accepts
|
||||||
|
/// 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")]
|
||||||
#[gen_hid_descriptor(
|
#[gen_hid_descriptor(
|
||||||
(collection = APPLICATION, usage_page = VENDOR_DEFINED_START, usage = 0x01, ) = {
|
(collection = APPLICATION, usage_page = VENDOR_DEFINED_START, usage = 0x01, ) = {
|
||||||
|
state=input;
|
||||||
average_buffer_fill=input;
|
average_buffer_fill=input;
|
||||||
frame_count=input;
|
frame_count=input;
|
||||||
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;
|
||||||
|
fb_rate_estimate=input;
|
||||||
}
|
}
|
||||||
)]
|
)]
|
||||||
#[repr(C)]
|
#[repr(C, packed)]
|
||||||
// Note these are all actually u32
|
// TODO: Fix that most of these values are actually u32, but usbd_hid macro doesn't work properly on u32
|
||||||
pub struct AudioTelemetryReport {
|
pub struct AudioTelemetryReport {
|
||||||
pub average_buffer_fill: i32,
|
pub state: u8,
|
||||||
|
pub average_buffer_fill: u16,
|
||||||
pub frame_count: i32,
|
pub frame_count: i32,
|
||||||
pub dac_underflow_count: i32,
|
pub dac_underflow_count: u16,
|
||||||
pub usb_underflow_count: i32,
|
pub usb_underflow_count: u16,
|
||||||
pub dac_overflow_count: i32,
|
pub dac_overflow_count: u16,
|
||||||
|
pub cur_rate: i32,
|
||||||
|
pub fb_rate_estimate: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<AudioTelemetryReport> for AudioTelemetrySnapshot {
|
||||||
|
fn from(value: AudioTelemetryReport) -> Self {
|
||||||
|
AudioTelemetrySnapshot {
|
||||||
|
state: AudioState::try_from(value.state).expect("Invalid AudioState"),
|
||||||
|
average_buffer_fill: value.average_buffer_fill,
|
||||||
|
frame_count: value.frame_count.cast_unsigned(), // on firmware side is usize == u32
|
||||||
|
dac_underflow_count: value.dac_underflow_count,
|
||||||
|
usb_underflow_count: value.usb_underflow_count,
|
||||||
|
dac_overflow_count: value.dac_overflow_count,
|
||||||
|
cur_rate: value.cur_rate.cast_unsigned(),
|
||||||
|
fb_rate_estimate: (value.fb_rate_estimate as f32),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user