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,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)
|
||||
);
|
||||
}
|
||||
}
|
||||
+146
-36
@@ -1,9 +1,9 @@
|
||||
#![no_std]
|
||||
|
||||
pub mod config;
|
||||
pub mod hardware;
|
||||
|
||||
use bytemuck::NoUninit;
|
||||
use deku::DekuRead;
|
||||
#[cfg(feature = "std")]
|
||||
use deku::DekuWrite;
|
||||
use num_enum::TryFromPrimitive;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
@@ -102,26 +102,11 @@ pub struct AudioTelemetrySnapshot {
|
||||
pub fb_rate_estimate: f32,
|
||||
}
|
||||
|
||||
// Writing is host-side only (needs deku's `alloc`, enabled by the `std` feature)
|
||||
#[derive(Debug, DekuRead, Clone)]
|
||||
#[cfg_attr(feature = "std", derive(DekuWrite))]
|
||||
#[deku(id_type = "u8")]
|
||||
pub enum AudioDeviceCommand {
|
||||
#[deku(id = 0)]
|
||||
Noop,
|
||||
#[deku(id = 1)]
|
||||
Reset,
|
||||
#[deku(id = 2)]
|
||||
Bootloader,
|
||||
}
|
||||
|
||||
pub mod hid {
|
||||
use deku::{DekuContainerRead, DekuError, DekuRead};
|
||||
#[cfg(feature = "std")]
|
||||
use deku::{DekuContainerWrite, DekuWrite};
|
||||
use deku::DekuRead;
|
||||
use usbd_hid::descriptor::generator_prelude::*;
|
||||
|
||||
use crate::{AudioDeviceCommand, AudioState, AudioTelemetrySnapshot};
|
||||
use crate::{AudioState, AudioTelemetrySnapshot};
|
||||
|
||||
/// HID usage IDs identifying each vendor interface. `gen_hid_descriptor` only accepts
|
||||
/// literals, so the descriptors below repeat these values; keep them in sync.
|
||||
@@ -170,30 +155,155 @@ pub mod hid {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DekuRead)]
|
||||
#[cfg_attr(feature = "std", derive(DekuWrite))]
|
||||
#[deku(endian = "little")]
|
||||
#[gen_hid_descriptor((collection = APPLICATION, usage_page = VENDOR_DEFINED_START, usage = 0x02, ) = {
|
||||
cmd=output;
|
||||
cmd=feature;
|
||||
resp=input;
|
||||
})]
|
||||
#[repr(C, packed)]
|
||||
pub struct AudioDeviceCommandReport {
|
||||
pub cmd: [u8; 32],
|
||||
pub struct DeviceCommandReport {
|
||||
pub cmd: [u8; 63],
|
||||
pub resp: [u8; 64],
|
||||
}
|
||||
|
||||
impl TryFrom<AudioDeviceCommandReport> for AudioDeviceCommand {
|
||||
type Error = DekuError;
|
||||
fn try_from(value: AudioDeviceCommandReport) -> Result<Self, Self::Error> {
|
||||
Ok(AudioDeviceCommand::from_bytes((value.cmd.as_slice(), 0))?.1)
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use usbd_hid::descriptor::SerializedDescriptor;
|
||||
|
||||
#[test]
|
||||
fn command_descriptor_has_bidirectional_reports() {
|
||||
let descriptor = DeviceCommandReport::desc();
|
||||
|
||||
assert_eq!(
|
||||
descriptor,
|
||||
&[
|
||||
0x06, 0x00, 0xff, 0x09, 0x02, 0xa1, 0x01, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75,
|
||||
0x08, 0x95, 0x3f, 0xb1, 0x02, 0x95, 0x40, 0x81, 0x02, 0xc0,
|
||||
][..]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl From<AudioDeviceCommand> for AudioDeviceCommandReport {
|
||||
fn from(value: AudioDeviceCommand) -> Self {
|
||||
let mut buf = [0u8; core::mem::size_of::<Self>()];
|
||||
value.to_slice(&mut buf).unwrap();
|
||||
Self { cmd: buf }
|
||||
pub mod command {
|
||||
use num_enum::TryFromPrimitive;
|
||||
|
||||
pub const COMMAND_REPORT_SIZE: usize = 63;
|
||||
pub const IN_REPORT_SIZE: usize = 64;
|
||||
pub const HEADER_LEN: usize = 7;
|
||||
pub const COMMAND_PAYLOAD_LEN: usize = COMMAND_REPORT_SIZE - HEADER_LEN;
|
||||
pub const IN_PAYLOAD_LEN: usize = IN_REPORT_SIZE - HEADER_LEN;
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, TryFromPrimitive, defmt::Format)]
|
||||
pub enum CommandKind {
|
||||
Noop = 0,
|
||||
Reset = 1,
|
||||
Bootloader = 2,
|
||||
ReadConfig = 3,
|
||||
ReplaceTlv = 4,
|
||||
CommitConfig = 5,
|
||||
Hardware = 6,
|
||||
ResetConfig = 7,
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, TryFromPrimitive, defmt::Format)]
|
||||
pub enum ResponseKind {
|
||||
Ack = 0,
|
||||
Nack = 1,
|
||||
ConfigData = 2,
|
||||
Noop = 3,
|
||||
Hardware = 4,
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, TryFromPrimitive, defmt::Format)]
|
||||
pub enum NackCode {
|
||||
InvalidCommand = 0,
|
||||
InvalidPayload = 1,
|
||||
UnknownTag = 2,
|
||||
InvalidConfig = 3,
|
||||
FlashWriteFailed = 4,
|
||||
Busy = 5,
|
||||
ConfigTooLarge = 6,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Header {
|
||||
pub kind: u8,
|
||||
pub seq: u8,
|
||||
pub total_len: u16,
|
||||
pub offset: u16,
|
||||
pub len: u8,
|
||||
}
|
||||
|
||||
impl Header {
|
||||
pub fn encode(self, out: &mut [u8]) {
|
||||
out[0] = self.kind;
|
||||
out[1] = self.seq;
|
||||
out[2..4].copy_from_slice(&self.total_len.to_le_bytes());
|
||||
out[4..6].copy_from_slice(&self.offset.to_le_bytes());
|
||||
out[6] = self.len;
|
||||
}
|
||||
|
||||
pub fn parse(bytes: &[u8]) -> Option<Self> {
|
||||
if bytes.len() < HEADER_LEN {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(Self {
|
||||
kind: bytes[0],
|
||||
seq: bytes[1],
|
||||
total_len: u16::from_le_bytes([bytes[2], bytes[3]]),
|
||||
offset: u16::from_le_bytes([bytes[4], bytes[5]]),
|
||||
len: bytes[6],
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_complete(self) -> bool {
|
||||
usize::from(self.offset) + usize::from(self.len) == usize::from(self.total_len)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn legacy_reset_report_is_a_zero_length_header() {
|
||||
let mut report = [0u8; COMMAND_REPORT_SIZE];
|
||||
report[0] = CommandKind::Reset as u8;
|
||||
|
||||
let header = Header::parse(&report).unwrap();
|
||||
|
||||
assert_eq!(header.kind, CommandKind::Reset as u8);
|
||||
assert_eq!(header.total_len, 0);
|
||||
assert!(header.is_complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_roundtrip() {
|
||||
let header = Header {
|
||||
kind: CommandKind::ReplaceTlv as u8,
|
||||
seq: 7,
|
||||
total_len: 66,
|
||||
offset: 25,
|
||||
len: 25,
|
||||
};
|
||||
|
||||
let mut buf = [0u8; HEADER_LEN];
|
||||
header.encode(&mut buf);
|
||||
|
||||
assert_eq!(Header::parse(&buf), Some(header));
|
||||
assert!(!header.is_complete());
|
||||
|
||||
let header = Header {
|
||||
offset: 41,
|
||||
..header
|
||||
};
|
||||
|
||||
assert!(header.is_complete());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user