config: add persistent flash-backed configuration with a HID command interface and CLI management
Build and Release Firmware / firmware (ak4490) (push) Successful in 50s
Build and Release Firmware / firmware (cs4398) (push) Successful in 44s
Build and Release Firmware / firmware (evk) (push) Successful in 43s
Build and Release Firmware / cli (aarch64-unknown-linux-musl) (push) Successful in 1m8s
Build and Release Firmware / cli (x86_64-pc-windows-gnu) (push) Successful in 1m32s
Build and Release Firmware / cli (x86_64-unknown-linux-musl) (push) Successful in 1m6s
Build and Release Firmware / release (push) Successful in 7s
Build and Release Firmware / firmware (ak4490) (push) Successful in 50s
Build and Release Firmware / firmware (cs4398) (push) Successful in 44s
Build and Release Firmware / firmware (evk) (push) Successful in 43s
Build and Release Firmware / cli (aarch64-unknown-linux-musl) (push) Successful in 1m8s
Build and Release Firmware / cli (x86_64-pc-windows-gnu) (push) Successful in 1m32s
Build and Release Firmware / cli (x86_64-unknown-linux-musl) (push) Successful in 1m6s
Build and Release Firmware / release (push) Successful in 7s
This commit is contained in:
23 files changed
+3483
-148
No files matched your search
@@ -0,0 +1,306 @@
|
||||
use lpc55_hal as hal;
|
||||
|
||||
use hal::{FlashGordon, drivers::flash::GenericArray, raw as pac, traits::flash::WriteErase};
|
||||
use shared::config::{
|
||||
ConfigContainer, ConfigString, ConfigV1, ConfigVersion, DeviceConfig, TlvList,
|
||||
};
|
||||
|
||||
use crate::{CONFIG_RESERVED, CONFIG_SLOT_COUNT, FLASH_PAGE_SIZE, SLOT_SIZE, config_base};
|
||||
|
||||
const SLOT_MAGIC: u32 = u32::from_le_bytes(*b"SLOT");
|
||||
|
||||
const FLASH_WORD_SIZE: usize = 16;
|
||||
const READ_SINGLE_WORD: u32 = 0x3;
|
||||
const READ_ECC_OFF: u32 = 1 << 2;
|
||||
const COMMAND_TIMEOUT: u32 = 1_000_000;
|
||||
|
||||
static mut CONFIG_BUF: [u8; SLOT_SIZE] = [0u8; SLOT_SIZE];
|
||||
|
||||
#[cfg(feature = "hid")]
|
||||
pub struct ConfigState {
|
||||
pub running: DeviceConfig,
|
||||
pub active_slot: u8,
|
||||
}
|
||||
|
||||
#[cfg(feature = "hid")]
|
||||
pub struct FlashState {
|
||||
pub flash: FlashGordon,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, defmt::Format)]
|
||||
enum FlashError {
|
||||
IllegalCommand,
|
||||
Failed,
|
||||
Timeout,
|
||||
}
|
||||
|
||||
fn halt() -> ! {
|
||||
loop {
|
||||
cortex_m::asm::wfi();
|
||||
}
|
||||
}
|
||||
|
||||
fn slot_page_address() -> usize {
|
||||
config_base()
|
||||
}
|
||||
|
||||
fn slot_address(index: usize) -> usize {
|
||||
config_base() + CONFIG_RESERVED + index * SLOT_SIZE
|
||||
}
|
||||
|
||||
fn config_buf() -> &'static mut [u8; SLOT_SIZE] {
|
||||
// Safety: flash access is not reentrant and the buffer is only borrowed for one operation at a time.
|
||||
unsafe { &mut *core::ptr::addr_of_mut!(CONFIG_BUF) }
|
||||
}
|
||||
|
||||
fn read_word(
|
||||
flash: &pac::flash::RegisterBlock,
|
||||
address: usize,
|
||||
) -> Result<[u8; FLASH_WORD_SIZE], FlashError> {
|
||||
flash.int_clr_status.write(|w| {
|
||||
w.done()
|
||||
.set_bit()
|
||||
.ecc_err()
|
||||
.set_bit()
|
||||
.err()
|
||||
.set_bit()
|
||||
.fail()
|
||||
.set_bit()
|
||||
});
|
||||
flash
|
||||
.starta
|
||||
.write(|w| unsafe { w.starta().bits((address / FLASH_WORD_SIZE) as u32) });
|
||||
flash.dataw[0].write(|w| unsafe { w.bits(READ_ECC_OFF) });
|
||||
flash.cmd.write(|w| unsafe { w.bits(READ_SINGLE_WORD) });
|
||||
|
||||
let mut timeout = COMMAND_TIMEOUT;
|
||||
|
||||
while flash.int_status.read().done().bit_is_clear() {
|
||||
timeout -= 1;
|
||||
|
||||
if timeout == 0 {
|
||||
return Err(FlashError::Timeout);
|
||||
}
|
||||
}
|
||||
|
||||
let status = flash.int_status.read();
|
||||
|
||||
if status.err().bit_is_set() {
|
||||
return Err(FlashError::IllegalCommand);
|
||||
}
|
||||
|
||||
if status.fail().bit_is_set() {
|
||||
return Err(FlashError::Failed);
|
||||
}
|
||||
|
||||
let mut word = [0u8; FLASH_WORD_SIZE];
|
||||
|
||||
for (chunk, register) in word.chunks_mut(4).zip(flash.dataw.iter()) {
|
||||
chunk.copy_from_slice(®ister.read().bits().to_ne_bytes());
|
||||
}
|
||||
|
||||
Ok(word)
|
||||
}
|
||||
|
||||
fn read_flash(address: usize, buf: &mut [u8]) -> Result<(), FlashError> {
|
||||
// Safety: the flash controller registers are only ever accessed here and in the HAL, never concurrently.
|
||||
let flash = unsafe { &*pac::FLASH::ptr() };
|
||||
|
||||
for (index, chunk) in buf.chunks_mut(FLASH_WORD_SIZE).enumerate() {
|
||||
let word = read_word(flash, address + index * FLASH_WORD_SIZE)?;
|
||||
chunk.copy_from_slice(&word[..chunk.len()]);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_active_slot() -> Option<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),
|
||||
}
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"AK4490"
|
||||
}
|
||||
|
||||
fn init(&mut self) {
|
||||
// bring out of reset
|
||||
self.pins.reset.set_high();
|
||||
@@ -69,18 +74,22 @@ where
|
||||
self.write_reg(RegisterAddress::Control2, 0x22 | ((dfs & 0x3) << 3));
|
||||
self.write_reg(RegisterAddress::Control4, (dfs & 0x4) >> 1);
|
||||
}
|
||||
|
||||
fn change_rate(&mut self, new_rate: u32) {
|
||||
let dfs = self.dfs_for_rate(new_rate);
|
||||
self.write_reg(RegisterAddress::Control2, 0x22 | ((dfs & 0x3) << 3));
|
||||
self.write_reg(RegisterAddress::Control4, (dfs & 0x4) >> 1);
|
||||
}
|
||||
|
||||
fn set_volume(&mut self, left: u8, right: u8) {
|
||||
self.set_volume_impl(left, right);
|
||||
self.volume = (left, right);
|
||||
}
|
||||
|
||||
fn mute(&mut self) {
|
||||
self.set_volume_impl(0, 0);
|
||||
}
|
||||
|
||||
fn unmute(&mut self) {
|
||||
self.set_volume_impl(self.volume.0, self.volume.1);
|
||||
}
|
||||
|
||||
@@ -50,6 +50,11 @@ where
|
||||
fn new(i2c: T, pins: CodecPins) -> Self {
|
||||
Cs4398Dac { i2c, pins }
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"CS4398"
|
||||
}
|
||||
|
||||
fn init(&mut self) {
|
||||
// reset
|
||||
self.pins.reset.set_low().ok();
|
||||
|
||||
@@ -7,6 +7,10 @@ pub struct NoopDac<T> {
|
||||
__: PhantomData<T>,
|
||||
}
|
||||
impl<T> Dac<T> for NoopDac<T> {
|
||||
fn name(&self) -> &'static str {
|
||||
"None"
|
||||
}
|
||||
|
||||
fn init(&mut self) {}
|
||||
fn change_rate(&mut self, _new_rate: u32) {}
|
||||
fn mute(&mut self) {}
|
||||
|
||||
@@ -176,6 +176,11 @@ where
|
||||
mclk: MCLK,
|
||||
}
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"WM8904"
|
||||
}
|
||||
|
||||
fn init(&mut self) {
|
||||
let mut buf = [0u8; 2];
|
||||
match self.i2c.write_read(WM8904_I2C_ADDRESS, &[0], &mut buf) {
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
use shared::{
|
||||
config::{
|
||||
ConfigBytes, ConfigError, ConfigSnapshot, ConfigTag, ConfigV1, DeviceConfig, MAX_VALUE_LEN,
|
||||
Tlv,
|
||||
},
|
||||
hardware::HardwareInfo,
|
||||
hid::command::{
|
||||
COMMAND_REPORT_SIZE, CommandKind, HEADER_LEN, Header, IN_PAYLOAD_LEN, IN_REPORT_SIZE,
|
||||
NackCode, ResponseKind,
|
||||
},
|
||||
};
|
||||
use usb_device::{UsbError, bus::UsbBus};
|
||||
use usbd_hid::hid_class::HIDClass;
|
||||
|
||||
use crate::config::{self, ConfigState, FlashState};
|
||||
|
||||
const MAX_COMMAND_LEN: usize = 128;
|
||||
const REPLY_BUF_LEN: usize = 512;
|
||||
|
||||
struct Reassembly {
|
||||
kind: Option<CommandKind>,
|
||||
seq: u8,
|
||||
total_len: usize,
|
||||
received: usize,
|
||||
buf: [u8; MAX_COMMAND_LEN],
|
||||
}
|
||||
|
||||
enum Action {
|
||||
Nothing,
|
||||
Apply(DeviceConfig),
|
||||
Reset,
|
||||
Bootloader,
|
||||
Commit,
|
||||
ResetDefaults,
|
||||
}
|
||||
|
||||
enum Pending {
|
||||
Ack { seq: u8, action: Action },
|
||||
Nack { seq: u8, code: NackCode },
|
||||
}
|
||||
|
||||
enum Push {
|
||||
Sent,
|
||||
Blocked,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// A reply payload being segmented into IN reports.
|
||||
struct Reply {
|
||||
kind: ResponseKind,
|
||||
seq: u8,
|
||||
total_len: usize,
|
||||
offset: usize,
|
||||
}
|
||||
|
||||
pub struct CommandState {
|
||||
command: Reassembly,
|
||||
pending: Option<Pending>,
|
||||
reply: Option<Reply>,
|
||||
reply_buf: [u8; REPLY_BUF_LEN],
|
||||
}
|
||||
|
||||
impl CommandState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
command: Reassembly {
|
||||
kind: None,
|
||||
seq: 0,
|
||||
total_len: 0,
|
||||
received: 0,
|
||||
buf: [0; MAX_COMMAND_LEN],
|
||||
},
|
||||
pending: None,
|
||||
reply: None,
|
||||
reply_buf: [0; REPLY_BUF_LEN],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.command.kind = None;
|
||||
self.pending = None;
|
||||
self.reply = None;
|
||||
}
|
||||
|
||||
fn nack(&mut self, seq: u8, code: NackCode) {
|
||||
self.command.kind = None;
|
||||
self.reply = None;
|
||||
self.pending = Some(Pending::Nack { seq, code });
|
||||
}
|
||||
|
||||
fn reply(&mut self, kind: ResponseKind, seq: u8, len: usize) {
|
||||
self.reply = Some(Reply {
|
||||
kind,
|
||||
seq,
|
||||
total_len: len,
|
||||
offset: 0,
|
||||
});
|
||||
}
|
||||
|
||||
fn prepare(
|
||||
&mut self,
|
||||
kind: CommandKind,
|
||||
seq: u8,
|
||||
payload: &[u8],
|
||||
config: &ConfigState,
|
||||
hardware: &HardwareInfo,
|
||||
) {
|
||||
match kind {
|
||||
CommandKind::Noop => {
|
||||
self.pending = Some(Pending::Ack {
|
||||
seq,
|
||||
action: Action::Nothing,
|
||||
});
|
||||
}
|
||||
CommandKind::Reset => {
|
||||
self.pending = Some(Pending::Ack {
|
||||
seq,
|
||||
action: Action::Reset,
|
||||
});
|
||||
}
|
||||
CommandKind::Bootloader => {
|
||||
self.pending = Some(Pending::Ack {
|
||||
seq,
|
||||
action: Action::Bootloader,
|
||||
});
|
||||
}
|
||||
CommandKind::ReadConfig => {
|
||||
if !payload.is_empty() {
|
||||
self.nack(seq, NackCode::InvalidPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
let Ok(tlvs) = config.running.to_tlvs() else {
|
||||
self.nack(seq, NackCode::InvalidConfig);
|
||||
return;
|
||||
};
|
||||
|
||||
let snapshot = ConfigSnapshot {
|
||||
active_slot: config.active_slot,
|
||||
config: ConfigV1 { tlvs },
|
||||
};
|
||||
|
||||
match snapshot.encode(&mut self.reply_buf) {
|
||||
Ok(len) => self.reply(ResponseKind::ConfigData, seq, len),
|
||||
Err(error) => {
|
||||
defmt::warn!("config snapshot encode failed: {}", error);
|
||||
self.nack(seq, NackCode::ConfigTooLarge);
|
||||
}
|
||||
}
|
||||
}
|
||||
CommandKind::Hardware => {
|
||||
if !payload.is_empty() {
|
||||
self.nack(seq, NackCode::InvalidPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
match hardware.encode(&mut self.reply_buf) {
|
||||
Ok(len) => self.reply(ResponseKind::Hardware, seq, len),
|
||||
Err(error) => {
|
||||
defmt::warn!("hardware encode failed: {}", error);
|
||||
self.nack(seq, NackCode::ConfigTooLarge);
|
||||
}
|
||||
}
|
||||
}
|
||||
CommandKind::ReplaceTlv => {
|
||||
if payload.len() < 2 {
|
||||
self.nack(seq, NackCode::InvalidPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
let tag = ConfigTag(u16::from_le_bytes([payload[0], payload[1]]));
|
||||
let Ok(value) = ConfigBytes::<MAX_VALUE_LEN>::from_slice(&payload[2..]) else {
|
||||
self.nack(seq, NackCode::InvalidPayload);
|
||||
return;
|
||||
};
|
||||
|
||||
let mut staged = config.running.clone();
|
||||
match staged.replace_tlv(Tlv { tag, value }) {
|
||||
Ok(()) => {
|
||||
self.pending = Some(Pending::Ack {
|
||||
seq,
|
||||
action: Action::Apply(staged),
|
||||
});
|
||||
}
|
||||
Err(ConfigError::UnknownTag(_)) => self.nack(seq, NackCode::UnknownTag),
|
||||
Err(_) => self.nack(seq, NackCode::InvalidConfig),
|
||||
}
|
||||
}
|
||||
CommandKind::CommitConfig => {
|
||||
if !payload.is_empty() {
|
||||
self.nack(seq, NackCode::InvalidPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
self.pending = Some(Pending::Ack {
|
||||
seq,
|
||||
action: Action::Commit,
|
||||
});
|
||||
}
|
||||
CommandKind::ResetConfig => {
|
||||
if !payload.is_empty() {
|
||||
self.nack(seq, NackCode::InvalidPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
self.pending = Some(Pending::Ack {
|
||||
seq,
|
||||
action: Action::ResetDefaults,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn flush<B: UsbBus>(
|
||||
&mut self,
|
||||
hid: &HIDClass<'_, B>,
|
||||
config: &mut ConfigState,
|
||||
flash: &mut FlashState,
|
||||
) -> bool {
|
||||
if let Some(pending) = self.pending.take() {
|
||||
let pushed = match &pending {
|
||||
Pending::Ack { seq, .. } => push_ack(hid, *seq),
|
||||
Pending::Nack { seq, code } => push_nack(hid, *seq, *code),
|
||||
};
|
||||
|
||||
match pushed {
|
||||
Push::Blocked => {
|
||||
self.pending = Some(pending);
|
||||
return true;
|
||||
}
|
||||
Push::Failed => return true,
|
||||
Push::Sent => {}
|
||||
}
|
||||
|
||||
if let Pending::Ack { action, .. } = pending {
|
||||
match action {
|
||||
Action::Nothing => {}
|
||||
Action::Apply(staged) => config.running = staged,
|
||||
Action::Reset => {
|
||||
ack_delay();
|
||||
cortex_m::peripheral::SCB::sys_reset();
|
||||
}
|
||||
Action::Bootloader => {
|
||||
ack_delay();
|
||||
crate::boot_to_bootloader();
|
||||
}
|
||||
Action::Commit => {
|
||||
ack_delay();
|
||||
|
||||
if config::commit(flash, config).is_err() {
|
||||
defmt::error!("config commit failed");
|
||||
}
|
||||
}
|
||||
Action::ResetDefaults => {
|
||||
ack_delay();
|
||||
|
||||
if config::commit_defaults(flash, config).is_err() {
|
||||
defmt::error!("config reset failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if let Some(mut reply) = self.reply.take() {
|
||||
let len = (reply.total_len - reply.offset).min(IN_PAYLOAD_LEN);
|
||||
let mut report = [0u8; IN_REPORT_SIZE];
|
||||
|
||||
Header {
|
||||
kind: reply.kind as u8,
|
||||
seq: reply.seq,
|
||||
total_len: reply.total_len as u16,
|
||||
offset: reply.offset as u16,
|
||||
len: len as u8,
|
||||
}
|
||||
.encode(&mut report[..HEADER_LEN]);
|
||||
|
||||
let start = reply.offset;
|
||||
report[HEADER_LEN..HEADER_LEN + len]
|
||||
.copy_from_slice(&self.reply_buf[start..start + len]);
|
||||
|
||||
match hid.push_raw_input(&report) {
|
||||
Ok(_) => {
|
||||
defmt::debug!(
|
||||
"HID reply kind={:?} seq={} offset={} len={}/{}",
|
||||
reply.kind,
|
||||
reply.seq,
|
||||
reply.offset,
|
||||
len,
|
||||
reply.total_len
|
||||
);
|
||||
|
||||
reply.offset += len;
|
||||
|
||||
if reply.offset < reply.total_len {
|
||||
self.reply = Some(reply);
|
||||
}
|
||||
}
|
||||
Err(UsbError::WouldBlock) => self.reply = Some(reply),
|
||||
Err(error) => defmt::error!("HID reply push failed: {:?}", error),
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn read<B: UsbBus>(
|
||||
&mut self,
|
||||
hid: &mut HIDClass<'_, B>,
|
||||
config: &ConfigState,
|
||||
hardware: &HardwareInfo,
|
||||
) {
|
||||
let mut raw = [0u8; IN_REPORT_SIZE];
|
||||
|
||||
let len = match hid.pull_raw_report(&mut raw) {
|
||||
Ok(info) if info.report_id == 0 => info.len,
|
||||
Ok(_) => return,
|
||||
Err(UsbError::WouldBlock) => return,
|
||||
Err(error) => {
|
||||
defmt::error!("HID pull failed: {:?}", error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let len = len.min(COMMAND_REPORT_SIZE);
|
||||
let report = &raw[..len];
|
||||
|
||||
let Some(header) = Header::parse(report) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if HEADER_LEN + usize::from(header.len) > len
|
||||
|| usize::from(header.offset) + usize::from(header.len) > usize::from(header.total_len)
|
||||
{
|
||||
defmt::warn!("invalid HID command framing");
|
||||
self.nack(header.seq, NackCode::InvalidPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
let Ok(kind) = CommandKind::try_from(header.kind) else {
|
||||
defmt::warn!("unknown HID command {}", header.kind);
|
||||
self.nack(header.seq, NackCode::InvalidCommand);
|
||||
return;
|
||||
};
|
||||
|
||||
if header.offset == 0 {
|
||||
self.command.kind = Some(kind);
|
||||
self.command.seq = header.seq;
|
||||
self.command.total_len = usize::from(header.total_len);
|
||||
self.command.received = 0;
|
||||
|
||||
if self.command.total_len > MAX_COMMAND_LEN {
|
||||
defmt::warn!("HID command too large: {}", self.command.total_len);
|
||||
self.nack(header.seq, NackCode::InvalidPayload);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if self.command.kind != Some(kind)
|
||||
|| self.command.seq != header.seq
|
||||
|| usize::from(header.offset) != self.command.received
|
||||
{
|
||||
defmt::warn!("out of sequence HID command chunk");
|
||||
self.nack(header.seq, NackCode::InvalidPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
let start = usize::from(header.offset);
|
||||
let len = usize::from(header.len);
|
||||
self.command.buf[start..start + len].copy_from_slice(&report[HEADER_LEN..HEADER_LEN + len]);
|
||||
self.command.received += len;
|
||||
|
||||
if self.command.received == self.command.total_len {
|
||||
defmt::debug!(
|
||||
"HID command kind={:?} seq={} len={}",
|
||||
kind,
|
||||
header.seq,
|
||||
self.command.total_len
|
||||
);
|
||||
|
||||
let mut payload = [0u8; MAX_COMMAND_LEN];
|
||||
let total_len = self.command.total_len;
|
||||
payload[..total_len].copy_from_slice(&self.command.buf[..total_len]);
|
||||
self.command.kind = None;
|
||||
|
||||
if self.reply.take().is_some() {
|
||||
defmt::warn!("dropping unsent reply");
|
||||
}
|
||||
|
||||
self.prepare(kind, header.seq, &payload[..total_len], config, hardware);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_ack<B: UsbBus>(hid: &HIDClass<'_, B>, seq: u8) -> Push {
|
||||
let mut report = [0u8; IN_REPORT_SIZE];
|
||||
Header {
|
||||
kind: ResponseKind::Ack as u8,
|
||||
seq,
|
||||
total_len: 0,
|
||||
offset: 0,
|
||||
len: 0,
|
||||
}
|
||||
.encode(&mut report[..HEADER_LEN]);
|
||||
|
||||
match hid.push_raw_input(&report) {
|
||||
Ok(_) => Push::Sent,
|
||||
Err(UsbError::WouldBlock) => Push::Blocked,
|
||||
Err(error) => {
|
||||
defmt::error!("HID ACK failed: {:?}", error);
|
||||
Push::Failed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_nack<B: UsbBus>(hid: &HIDClass<'_, B>, seq: u8, code: NackCode) -> Push {
|
||||
let mut report = [0u8; IN_REPORT_SIZE];
|
||||
Header {
|
||||
kind: ResponseKind::Nack as u8,
|
||||
seq,
|
||||
total_len: 1,
|
||||
offset: 0,
|
||||
len: 1,
|
||||
}
|
||||
.encode(&mut report[..HEADER_LEN]);
|
||||
report[HEADER_LEN] = code as u8;
|
||||
|
||||
match hid.push_raw_input(&report) {
|
||||
Ok(_) => Push::Sent,
|
||||
Err(UsbError::WouldBlock) => Push::Blocked,
|
||||
Err(error) => {
|
||||
defmt::error!("HID NACK failed: {:?}", error);
|
||||
Push::Failed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ack_delay() {
|
||||
cortex_m::asm::delay(5_000_000);
|
||||
}
|
||||
|
||||
pub fn poll<B: UsbBus>(
|
||||
hid: &mut HIDClass<'_, B>,
|
||||
state: &mut CommandState,
|
||||
config: &mut ConfigState,
|
||||
flash: &mut FlashState,
|
||||
hardware: &HardwareInfo,
|
||||
) {
|
||||
state.read(hid, config, hardware);
|
||||
state.flush(hid, config, flash);
|
||||
}
|
||||
+118
-45
@@ -24,6 +24,8 @@ use hal::typestates::pin::state::Gpio;
|
||||
use lpc55_hal as hal;
|
||||
use pac::interrupt;
|
||||
use static_cell::StaticCell;
|
||||
#[cfg(feature = "hid")]
|
||||
use usb_device::device::UsbDeviceState;
|
||||
use usb_device::{
|
||||
bus::{self},
|
||||
device::{StringDescriptors, UsbVidPid},
|
||||
@@ -43,7 +45,13 @@ use crate::hw::led1;
|
||||
use crate::hw::led2;
|
||||
use crate::traits::Dac;
|
||||
use shared::AudioState;
|
||||
use shared::hid::{AudioDeviceCommandReport, AudioTelemetryReport};
|
||||
#[cfg(feature = "hid")]
|
||||
use shared::config::ConfigString;
|
||||
#[cfg(feature = "hid")]
|
||||
use shared::hardware::HardwareInfo;
|
||||
use shared::hid::AudioTelemetryReport;
|
||||
#[cfg(feature = "hid")]
|
||||
use shared::hid::DeviceCommandReport;
|
||||
|
||||
#[cfg(feature = "ak4490")]
|
||||
pub mod dac {
|
||||
@@ -66,7 +74,10 @@ pub mod dac {
|
||||
pub use self::wm8904::Wm8904Dac as DacImpl;
|
||||
}
|
||||
|
||||
mod config;
|
||||
mod dma;
|
||||
#[cfg(feature = "hid")]
|
||||
mod hid_config;
|
||||
mod hw;
|
||||
mod traits;
|
||||
|
||||
@@ -106,7 +117,39 @@ const USB_FRAME_RATE: u32 = 8000; // microframe rate: 8000 for HS, 1000 for FS
|
||||
// const NODATA_TIMEOUT_FRAMES: usize = SAMPLE_RATE as usize / 100; // ~100ms
|
||||
|
||||
const HID_INTERVAL_MS: u8 = 10;
|
||||
const HID_CMD_INTERVAL_MS: u8 = 100;
|
||||
const HID_CMD_INTERVAL_MS: u8 = 10;
|
||||
|
||||
const FLASH_PAGE_SIZE: usize = 512;
|
||||
|
||||
const CONFIG_LENGTH: usize = 32 * 1024;
|
||||
const CONFIG_SLOT_COUNT: usize = 2;
|
||||
// First page is reserved for slot selection, reserve two slots so remainder / 2 is aligned
|
||||
const CONFIG_RESERVED: usize = 2 * FLASH_PAGE_SIZE;
|
||||
|
||||
const SLOT_SIZE: usize = (CONFIG_LENGTH - CONFIG_RESERVED) / CONFIG_SLOT_COUNT;
|
||||
|
||||
// Ensure config page alignment
|
||||
const _: () = assert!(
|
||||
CONFIG_RESERVED.is_multiple_of(FLASH_PAGE_SIZE),
|
||||
"Reserved space must align to flash page size"
|
||||
);
|
||||
const _: () = assert!(
|
||||
SLOT_SIZE.is_multiple_of(FLASH_PAGE_SIZE),
|
||||
"Slot size must be a multiple of flash page size"
|
||||
);
|
||||
const _: () = assert!(
|
||||
CONFIG_SLOT_COUNT.is_multiple_of(2),
|
||||
"Slot count must be even"
|
||||
);
|
||||
|
||||
unsafe extern "C" {
|
||||
#[link_name = "_config_start"]
|
||||
static CONFIG_START: u8;
|
||||
}
|
||||
|
||||
pub fn config_base() -> usize {
|
||||
core::ptr::addr_of!(CONFIG_START) as usize
|
||||
}
|
||||
|
||||
struct CodecPins {
|
||||
#[allow(dead_code)]
|
||||
@@ -842,6 +885,22 @@ fn main() -> ! {
|
||||
.system_frequency(96.MHz())
|
||||
.configure(&mut anactrl, &mut pmc, &mut syscon)
|
||||
.unwrap();
|
||||
|
||||
// Flash controller commands require a core clock of at most 100 MHz, so the config is read
|
||||
// before the system PLL takes the core to 150 MHz.
|
||||
let flash = hal.flash.enabled(&mut syscon);
|
||||
let mut flash = hal::FlashGordon::new(flash);
|
||||
defmt::info!("config: loading");
|
||||
let (running_config, active_slot) = config::load(&mut flash);
|
||||
defmt::info!(
|
||||
"config: loaded slot={} vid={:04x} pid={:04x}",
|
||||
active_slot,
|
||||
running_config.usb_vendor_id,
|
||||
running_config.usb_product_id
|
||||
);
|
||||
#[cfg(not(feature = "hid"))]
|
||||
let _ = active_slot;
|
||||
|
||||
hw::init_sys_pll1();
|
||||
#[cfg(feature = "evk")]
|
||||
hw::init_audio_pll();
|
||||
@@ -921,24 +980,46 @@ fn main() -> ! {
|
||||
#[cfg(feature = "hid")]
|
||||
let (mut hid, mut hid_cmd) = {
|
||||
let hid = HIDClass::new_ep_in(&usb_bus, AudioTelemetryReport::desc(), HID_INTERVAL_MS);
|
||||
// Linux's usbhid refuses to bind an interface without an interrupt IN endpoint
|
||||
// (no hidraw node), so the command interface needs one even though it is unused.
|
||||
let hid_cmd = HIDClass::new(
|
||||
&usb_bus,
|
||||
AudioDeviceCommandReport::desc(),
|
||||
HID_CMD_INTERVAL_MS,
|
||||
);
|
||||
// Commands arrive as feature reports over the control pipe; Linux's usbhid needs an
|
||||
// interrupt IN endpoint to bind the interface, and replies use it.
|
||||
let hid_cmd =
|
||||
HIDClass::new_ep_in(&usb_bus, DeviceCommandReport::desc(), HID_CMD_INTERVAL_MS);
|
||||
(hid, hid_cmd)
|
||||
};
|
||||
|
||||
let mut usb_dev = usbd_uac2::builder(&usb_bus, UsbVidPid(0x1209, 0xcc1d))
|
||||
.strings(&[StringDescriptors::default()
|
||||
.manufacturer("VE7XEN")
|
||||
.product("Guac Tortilla")])
|
||||
.unwrap()
|
||||
.max_packet_size_0(64)
|
||||
.unwrap()
|
||||
.build();
|
||||
#[cfg(feature = "hid")]
|
||||
let hardware_info = HardwareInfo {
|
||||
uuid: hal::uuid(),
|
||||
dac: ConfigString::try_from(uac2.handler().dac.name()).unwrap_or_default(),
|
||||
version: ConfigString::try_from(env!("GUAC_VERSION")).unwrap_or_default(),
|
||||
};
|
||||
|
||||
#[cfg(feature = "hid")]
|
||||
defmt::info!(
|
||||
"hardware: uuid={=[u8]:02x} dac={=str} firmware={=str}",
|
||||
&hardware_info.uuid[..],
|
||||
hardware_info.dac.as_str(),
|
||||
hardware_info.version.as_str()
|
||||
);
|
||||
|
||||
let mut usb_dev = usbd_uac2::builder(
|
||||
&usb_bus,
|
||||
UsbVidPid(running_config.usb_vendor_id, running_config.usb_product_id),
|
||||
)
|
||||
.strings(&[{
|
||||
let descriptors = StringDescriptors::default()
|
||||
.manufacturer(running_config.usb_manufacturer.as_str())
|
||||
.product(running_config.usb_product.as_str());
|
||||
|
||||
match &running_config.usb_serial {
|
||||
Some(serial) => descriptors.serial_number(serial.as_str()),
|
||||
None => descriptors,
|
||||
}
|
||||
}])
|
||||
.unwrap()
|
||||
.max_packet_size_0(64)
|
||||
.unwrap()
|
||||
.build();
|
||||
|
||||
// 1. Initialize the HID timer conditionally outside the closure
|
||||
#[cfg(feature = "hid")]
|
||||
@@ -952,6 +1033,16 @@ fn main() -> ! {
|
||||
timer
|
||||
};
|
||||
|
||||
#[cfg(feature = "hid")]
|
||||
let mut config_state = config::ConfigState {
|
||||
running: running_config.clone(),
|
||||
active_slot,
|
||||
};
|
||||
#[cfg(feature = "hid")]
|
||||
let mut flash_state = config::FlashState { flash };
|
||||
#[cfg(feature = "hid")]
|
||||
let mut command_state = hid_config::CommandState::new();
|
||||
|
||||
// 2. Single consolidated poll_all closure
|
||||
let mut poll_all = move || {
|
||||
// Poll active USB classes
|
||||
@@ -975,22 +1066,6 @@ fn main() -> ! {
|
||||
|
||||
#[cfg(feature = "hid")]
|
||||
{
|
||||
use deku::DekuContainerRead;
|
||||
use shared::AudioDeviceCommand;
|
||||
|
||||
fn handle_cmd(cmd: AudioDeviceCommand) {
|
||||
use shared::AudioDeviceCommand;
|
||||
|
||||
match cmd {
|
||||
AudioDeviceCommand::Noop => {}
|
||||
AudioDeviceCommand::Reset => {
|
||||
cortex_m::interrupt::disable();
|
||||
cortex_m::peripheral::SCB::sys_reset();
|
||||
}
|
||||
AudioDeviceCommand::Bootloader => boot_to_bootloader(),
|
||||
}
|
||||
}
|
||||
|
||||
if hid_update_timer.wait().is_ok() {
|
||||
let report = build_telemetry_report(&PERF, uac2.handler());
|
||||
if let Err(e) = hid.push_input(&report)
|
||||
@@ -1001,19 +1076,17 @@ fn main() -> ! {
|
||||
// LPC55 CTIMER is not periodic; restart manually
|
||||
hid_update_timer.start(Microseconds::new(HID_INTERVAL_MS as u32 * 1000));
|
||||
}
|
||||
let mut cmd_report_buf = [0u8; core::mem::size_of::<AudioDeviceCommandReport>()];
|
||||
match hid_cmd.pull_raw_output(&mut cmd_report_buf) {
|
||||
Ok(len) => {
|
||||
if let Ok((_left, cmd)) =
|
||||
AudioDeviceCommandReport::from_bytes((&cmd_report_buf[0..len], 0))
|
||||
&& let Ok(cmd) = cmd.try_into()
|
||||
{
|
||||
handle_cmd(cmd)
|
||||
}
|
||||
}
|
||||
Err(UsbError::WouldBlock) => {}
|
||||
Err(e) => defmt::error!("Invalid report: {:?}", e),
|
||||
if usb_dev.state() != UsbDeviceState::Configured {
|
||||
command_state.reset();
|
||||
}
|
||||
|
||||
hid_config::poll(
|
||||
&mut hid_cmd,
|
||||
&mut command_state,
|
||||
&mut config_state,
|
||||
&mut flash_state,
|
||||
&hardware_info,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::CodecPins;
|
||||
pub trait Dac<T> {
|
||||
fn new(i2c: T, pins: CodecPins) -> Self;
|
||||
fn name(&self) -> &'static str;
|
||||
/// The DAC should start muted
|
||||
fn init(&mut self);
|
||||
fn change_rate(&mut self, new_rate: u32);
|
||||
|
||||
Reference in new issue
Block a user