use std::{collections::BTreeMap, time::Duration};
use thiserror::Error;
pub const MAXIMUM_PROFILE_NAME_BYTES: usize = 256;
pub const MAXIMUM_PROFILE_MODULES: usize = 64;
pub const MAXIMUM_PROFILE_DURATION: Duration = Duration::from_hours(24);
pub const MAXIMUM_PROFILE_WAKE_PREFIX: usize = 256;
pub const MAXIMUM_ADDRESS_TIMING_OVERRIDES: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PollingWindow {
pub first: u8,
pub last: u8,
}
impl PollingWindow {
pub fn new(first: u8, last: u8) -> Result<Self, ProfileError> {
if first > last || last > 63 {
return Err(ProfileError::PollingWindow { first, last });
}
Ok(Self { first, last })
}
pub fn iter(self) -> core::ops::RangeInclusive<u8> {
self.first..=self.last
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ModuleWindow {
pub module: u16,
pub polling: PollingWindow,
pub address_shift: i8,
}
impl ModuleWindow {
pub const fn new(module: u16, polling: PollingWindow) -> Self {
Self {
module,
polling,
address_shift: 0,
}
}
pub const fn with_address_shift(mut self, address_shift: i8) -> Self {
self.address_shift = address_shift;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimingProfile {
pub connect_settle: Duration,
pub first_response: Duration,
pub steady_response: Duration,
pub scan_interval: Duration,
}
impl Default for TimingProfile {
fn default() -> Self {
Self {
connect_settle: Duration::from_millis(500),
first_response: Duration::from_secs(5),
steady_response: Duration::from_millis(1600),
scan_interval: Duration::from_millis(100),
}
}
}
impl TimingProfile {
pub fn validate(self) -> Result<(), ProfileError> {
if self.first_response.is_zero() || self.steady_response.is_zero() {
return Err(ProfileError::ZeroTimeout);
}
for duration in [
self.connect_settle,
self.first_response,
self.steady_response,
self.scan_interval,
] {
if duration > MAXIMUM_PROFILE_DURATION {
return Err(ProfileError::Duration(duration));
}
}
Ok(())
}
pub const fn with_connect_settle(mut self, duration: Duration) -> Self {
self.connect_settle = duration;
self
}
pub const fn with_first_response(mut self, duration: Duration) -> Self {
self.first_response = duration;
self
}
pub const fn with_steady_response(mut self, duration: Duration) -> Self {
self.steady_response = duration;
self
}
pub const fn with_scan_interval(mut self, duration: Duration) -> Self {
self.scan_interval = duration;
self
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct AddressTiming {
pub delay_before_probe: Duration,
pub response_timeout: Option<Duration>,
}
impl AddressTiming {
pub const fn new() -> Self {
Self {
delay_before_probe: Duration::ZERO,
response_timeout: None,
}
}
pub const fn with_delay_before_probe(mut self, delay: Duration) -> Self {
self.delay_before_probe = delay;
self
}
pub const fn with_response_timeout(mut self, timeout: Duration) -> Self {
self.response_timeout = Some(timeout);
self
}
fn validate(self) -> Result<(), AddressTimingError> {
if self
.response_timeout
.is_some_and(|timeout| timeout.is_zero())
{
return Err(AddressTimingError::ZeroTimeout);
}
for duration in [
self.delay_before_probe,
self.response_timeout.unwrap_or_default(),
] {
if duration > MAXIMUM_PROFILE_DURATION {
return Err(AddressTimingError::Duration(duration));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum AddressTimingError {
#[error("polling address {0} is outside 0..=63")]
PollingAddress(u8),
#[error("address-specific response timeout cannot be zero")]
ZeroTimeout,
#[error("address-specific duration {0:?} exceeds the supported maximum")]
Duration(Duration),
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AddressTimings {
values: BTreeMap<u8, AddressTiming>,
}
impl AddressTimings {
pub const fn new() -> Self {
Self {
values: BTreeMap::new(),
}
}
pub fn insert(
&mut self,
polling_address: u8,
timing: AddressTiming,
) -> Result<(), AddressTimingError> {
if usize::from(polling_address) >= MAXIMUM_ADDRESS_TIMING_OVERRIDES {
return Err(AddressTimingError::PollingAddress(polling_address));
}
timing.validate()?;
self.values.insert(polling_address, timing);
Ok(())
}
pub fn with(
mut self,
polling_address: u8,
timing: AddressTiming,
) -> Result<Self, AddressTimingError> {
self.insert(polling_address, timing)?;
Ok(self)
}
pub fn get(&self, polling_address: u8) -> Option<AddressTiming> {
self.values.get(&polling_address).copied()
}
pub fn iter(&self) -> impl Iterator<Item = (u8, AddressTiming)> + '_ {
self.values
.iter()
.map(|(&polling_address, &timing)| (polling_address, timing))
}
pub fn len(&self) -> usize {
self.values.len()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
}
#[derive(Debug, Clone)]
pub struct LineProfile {
pub name: String,
pub timing: TimingProfile,
pub modules: Vec<ModuleWindow>,
pub discovery_preambles: u8,
pub wake_prefix: Vec<u8>,
}
impl LineProfile {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
timing: TimingProfile::default(),
modules: Vec::new(),
discovery_preambles: 20,
wake_prefix: Vec::new(),
}
}
pub fn single_segment(name: impl Into<String>, polling: PollingWindow) -> Self {
Self::new(name).with_module(ModuleWindow::new(1, polling))
}
pub const fn with_timing(mut self, timing: TimingProfile) -> Self {
self.timing = timing;
self
}
pub fn with_module(mut self, module: ModuleWindow) -> Self {
self.modules.push(module);
self
}
pub fn with_modules(mut self, modules: impl Into<Vec<ModuleWindow>>) -> Self {
self.modules = modules.into();
self
}
pub const fn with_discovery_preambles(mut self, preambles: u8) -> Self {
self.discovery_preambles = preambles;
self
}
pub fn with_wake_prefix(mut self, prefix: impl Into<Vec<u8>>) -> Self {
self.wake_prefix = prefix.into();
self
}
pub fn validate(&self) -> Result<(), ProfileError> {
if self.name.trim().is_empty() {
return Err(ProfileError::EmptyName);
}
if self.name.len() > MAXIMUM_PROFILE_NAME_BYTES {
return Err(ProfileError::NameLength(self.name.len()));
}
if !(2..=40).contains(&self.discovery_preambles) {
return Err(ProfileError::Preambles(self.discovery_preambles));
}
if self.wake_prefix.len() > MAXIMUM_PROFILE_WAKE_PREFIX {
return Err(ProfileError::WakePrefix(self.wake_prefix.len()));
}
self.timing.validate()?;
if self.modules.is_empty() {
return Err(ProfileError::NoModules);
}
if self.modules.len() > MAXIMUM_PROFILE_MODULES {
return Err(ProfileError::ModuleLimit(self.modules.len()));
}
let mut physical_addresses = BTreeMap::new();
for (index, current) in self.modules.iter().enumerate() {
PollingWindow::new(current.polling.first, current.polling.last)?;
if self.modules[index + 1..]
.iter()
.any(|other| other.module == current.module)
{
return Err(ProfileError::DuplicateModule(current.module));
}
let mut reachable = false;
for local in current.polling.iter() {
let Some(address) = Self::shifted_address(*current, local) else {
continue;
};
reachable = true;
if let Some(previous) = physical_addresses.insert(address, current.module) {
return Err(ProfileError::AddressOverlap {
address,
first_module: previous,
second_module: current.module,
});
}
}
if !reachable {
return Err(ProfileError::UnreachableModule(current.module));
}
}
Ok(())
}
pub fn shifted_address(module: ModuleWindow, local: u8) -> Option<u8> {
if !module.polling.iter().contains(&local) {
return None;
}
let shifted = i16::from(local) + i16::from(module.address_shift);
u8::try_from(shifted).ok().filter(|value| *value <= 63)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum ProfileError {
#[error("link name cannot be empty")]
EmptyName,
#[error("link name contains {0} UTF-8 bytes")]
NameLength(usize),
#[error("invalid address range {first}..={last}")]
PollingWindow {
first: u8,
last: u8,
},
#[error("preamble count {0} is outside 2..=40")]
Preambles(u8),
#[error("{0}-byte wake-up prefix is too large")]
WakePrefix(usize),
#[error("timeout cannot be zero")]
ZeroTimeout,
#[error("profile duration {0:?} exceeds the supported maximum")]
Duration(Duration),
#[error("link profile has no modules")]
NoModules,
#[error("link profile contains too many modules: {0}")]
ModuleLimit(usize),
#[error("module {0} is declared more than once")]
DuplicateModule(u16),
#[error("module {0} does not map to any valid polling address")]
UnreachableModule(u16),
#[error(
"polling address {address} is produced by both module {first_module} and module {second_module}"
)]
AddressOverlap {
address: u8,
first_module: u16,
second_module: u16,
},
}