use heapless::String;
use crate::error::{Error, ErrorCode, Result};
use crate::msg::VendorId;
use super::push_decimal;
pub const TXT_MAX: usize = 512;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(u8)]
pub enum CommissioningMode {
#[default]
None = 0,
Basic = 1,
Enhanced = 2,
JointFabric = 3,
}
impl CommissioningMode {
#[must_use]
pub const fn value(self) -> u8 {
self as u8
}
#[must_use]
pub const fn from_value(value: u8) -> Self {
match value {
1 => Self::Basic,
2 => Self::Enhanced,
3 => Self::JointFabric,
_ => Self::None,
}
}
#[must_use]
pub const fn publishes_subtype(self) -> bool {
!matches!(self, Self::None)
}
}
pub use crate::transport::TransportModes;
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct JointFabric: u32 {
const AVAILABLE = 1 << 0;
const ADMINISTRATOR = 1 << 1;
const ANCHOR = 1 << 2;
const DATASTORE = 1 << 3;
}
}
impl JointFabric {
#[must_use]
pub const fn is_valid(self) -> bool {
let acting = Self::ADMINISTRATOR.bits() | Self::ANCHOR.bits() | Self::DATASTORE.bits();
!(self.contains(Self::AVAILABLE) && (self.bits() & acting) != 0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct MrpAdvertisement {
pub idle_interval_ms: Option<u32>,
pub active_interval_ms: Option<u32>,
pub active_threshold_ms: Option<u16>,
}
pub const MRP_INTERVAL_MAX_MS: u32 = 3_600_000;
impl MrpAdvertisement {
#[must_use]
pub const fn is_valid(&self) -> bool {
let idle_ok = match self.idle_interval_ms {
Some(value) => value <= MRP_INTERVAL_MAX_MS,
None => true,
};
let active_ok = match self.active_interval_ms {
Some(value) => value <= MRP_INTERVAL_MAX_MS,
None => true,
};
idle_ok && active_ok
}
}
#[derive(Debug, Default)]
pub struct TxtWriter {
buf: heapless::Vec<u8, TXT_MAX>,
}
impl TxtWriter {
#[must_use]
pub const fn new() -> Self {
Self {
buf: heapless::Vec::new(),
}
}
pub fn push(&mut self, key: &str, value: &str) -> Result<()> {
let len = key
.len()
.checked_add(1)
.and_then(|n| n.checked_add(value.len()))
.ok_or_else(no_space)?;
let len = u8::try_from(len).map_err(|_| no_space())?;
self.buf.push(len).map_err(|_| no_space())?;
self.buf
.extend_from_slice(key.as_bytes())
.map_err(|_| no_space())?;
self.buf.push(b'=').map_err(|_| no_space())?;
self.buf
.extend_from_slice(value.as_bytes())
.map_err(|_| no_space())
}
pub fn push_decimal(&mut self, key: &str, value: u32) -> Result<()> {
let mut text = String::<10>::new();
push_decimal(&mut text, value);
self.push(key, &text)
}
#[must_use]
pub fn finish(&self) -> &[u8] {
if self.buf.is_empty() {
&[0u8]
} else {
&self.buf
}
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.buf.is_empty()
}
}
fn no_space() -> Error {
Error::new(ErrorCode::NoSpace)
}
#[derive(Debug, Clone)]
pub struct TxtReader<'a> {
rest: &'a [u8],
}
impl<'a> TxtReader<'a> {
#[must_use]
pub const fn new(bytes: &'a [u8]) -> Self {
Self { rest: bytes }
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&'a [u8]> {
self.clone()
.find(|(k, _)| k.eq_ignore_ascii_case(key.as_bytes()))
.map(|(_, value)| value)
}
#[must_use]
pub fn decimal(&self, key: &str) -> Option<u32> {
parse_decimal(self.get(key)?)
}
}
impl<'a> Iterator for TxtReader<'a> {
type Item = (&'a [u8], &'a [u8]);
fn next(&mut self) -> Option<Self::Item> {
loop {
let (&len, tail) = self.rest.split_first()?;
let len = usize::from(len);
let string = tail.get(..len)?;
self.rest = tail.get(len..)?;
if string.is_empty() {
continue;
}
let split = string.iter().position(|&b| b == b'=');
return Some(match split {
Some(at) => (
string.get(..at).unwrap_or(&[]),
string.get(at.saturating_add(1)..).unwrap_or(&[]),
),
None => (string, &[]),
});
}
}
}
#[must_use]
pub fn parse_decimal(value: &[u8]) -> Option<u32> {
if value.is_empty() || value.len() > 10 {
return None;
}
let mut out = 0u32;
for byte in value {
let digit = byte.checked_sub(b'0').filter(|d| *d <= 9)?;
out = out.checked_mul(10)?.checked_add(u32::from(digit))?;
}
Some(out)
}
#[derive(Debug, Clone, Copy, Default)]
pub struct CommissionableTxt<'a> {
pub discriminator: u16,
pub vendor_id: Option<VendorId>,
pub product_id: Option<u16>,
pub commissioning_mode: CommissioningMode,
pub device_type: Option<u32>,
pub device_name: Option<&'a str>,
pub rotating_id: Option<&'a [u8]>,
pub pairing_hint: Option<u32>,
pub pairing_instruction: Option<&'a str>,
pub joint_fabric: Option<JointFabric>,
pub mrp: MrpAdvertisement,
}
pub const ROTATING_ID_MAX_OCTETS: usize = 50;
pub const DEVICE_NAME_MAX: usize = 32;
pub const PAIRING_INSTRUCTION_MAX: usize = 128;
impl CommissionableTxt<'_> {
pub fn encode(&self) -> Result<TxtWriter> {
let mut w = TxtWriter::new();
w.push_decimal("D", u32::from(self.discriminator & 0x0FFF))?;
if let Some(vendor) = self.vendor_id {
let mut value = String::<16>::new();
push_decimal(&mut value, u32::from(vendor.0));
if let Some(product) = self.product_id {
let _ = value.push('+');
push_decimal(&mut value, u32::from(product));
}
w.push("VP", &value)?;
} else if self.product_id.is_some() {
return Err(Error::new(ErrorCode::InvalidArgument));
}
w.push_decimal("CM", u32::from(self.commissioning_mode.value()))?;
if let Some(device_type) = self.device_type {
w.push_decimal("DT", device_type)?;
}
if let Some(name) = self.device_name {
if name.len() > DEVICE_NAME_MAX {
return Err(Error::new(ErrorCode::InvalidArgument));
}
w.push("DN", name)?;
}
if let Some(rotating) = self.rotating_id {
if rotating.len() > ROTATING_ID_MAX_OCTETS {
return Err(Error::new(ErrorCode::InvalidArgument));
}
let mut value = String::<{ ROTATING_ID_MAX_OCTETS * 2 }>::new();
super::push_hex(&mut value, rotating);
w.push("RI", &value)?;
}
if let Some(hint) = self.pairing_hint {
w.push_decimal("PH", hint)?;
}
if let Some(instruction) = self.pairing_instruction {
if instruction.len() > PAIRING_INSTRUCTION_MAX {
return Err(Error::new(ErrorCode::InvalidArgument));
}
w.push("PI", instruction)?;
}
if let Some(joint) = self.joint_fabric {
if !joint.is_valid() {
return Err(Error::new(ErrorCode::InvalidArgument));
}
w.push_decimal("JF", joint.bits())?;
}
push_mrp(&mut w, &self.mrp)?;
Ok(w)
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct OperationalTxt {
pub mrp: MrpAdvertisement,
pub transports: TransportModes,
pub long_idle_time_icd: Option<bool>,
pub incomplete_commissioning: Option<bool>,
}
impl OperationalTxt {
pub fn encode(&self) -> Result<TxtWriter> {
let mut w = TxtWriter::new();
push_mrp(&mut w, &self.mrp)?;
if !self.transports.is_empty() {
w.push_decimal("T", self.transports.bits())?;
}
if let Some(icd) = self.long_idle_time_icd {
w.push_decimal("ICD", u32::from(icd))?;
}
if let Some(incomplete) = self.incomplete_commissioning {
w.push_decimal("IC", u32::from(incomplete))?;
}
Ok(w)
}
}
fn push_mrp(w: &mut TxtWriter, mrp: &MrpAdvertisement) -> Result<()> {
if !mrp.is_valid() {
return Err(Error::new(ErrorCode::InvalidArgument));
}
if let Some(idle) = mrp.idle_interval_ms {
w.push_decimal("SII", idle)?;
}
if let Some(active) = mrp.active_interval_ms {
w.push_decimal("SAI", active)?;
}
if let Some(threshold) = mrp.active_threshold_ms {
w.push_decimal("SAT", u32::from(threshold))?;
}
Ok(())
}