#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum NodeId {
Unconfigured,
Configured(ConfiguredNodeId),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ConfiguredNodeId(u8);
impl ConfiguredNodeId {
pub const fn new(value: u8) -> Result<Self, InvalidNodeIdError> {
if (value > 0 && value < 128) || value == 255 {
Ok(ConfiguredNodeId(value))
} else {
Err(InvalidNodeIdError)
}
}
pub fn raw(&self) -> u8 {
self.0
}
}
impl core::fmt::Display for ConfiguredNodeId {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<ConfiguredNodeId> for u8 {
fn from(value: ConfiguredNodeId) -> Self {
value.raw()
}
}
impl NodeId {
pub const fn new(value: u8) -> Result<Self, InvalidNodeIdError> {
if value == 255 {
Ok(NodeId::Unconfigured)
} else {
match ConfiguredNodeId::new(value) {
Ok(id) => Ok(NodeId::Configured(id)),
Err(e) => Err(e),
}
}
}
pub fn raw(&self) -> u8 {
match self {
NodeId::Unconfigured => 255,
NodeId::Configured(node_id_num) => node_id_num.0,
}
}
pub fn as_configured(&self) -> Option<ConfiguredNodeId> {
match self {
NodeId::Unconfigured => None,
NodeId::Configured(configured_node_id) => Some(*configured_node_id),
}
}
pub fn is_configured(&self) -> bool {
match self {
Self::Configured(_) => true,
Self::Unconfigured => false,
}
}
pub fn is_unconfigured(&self) -> bool {
match self {
Self::Configured(_) => false,
Self::Unconfigured => true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidNodeIdError;
impl core::fmt::Display for InvalidNodeIdError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Invalid node ID")
}
}
impl core::error::Error for InvalidNodeIdError {}
impl TryFrom<u8> for NodeId {
type Error = InvalidNodeIdError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
if value == 255 {
Ok(NodeId::Unconfigured)
} else {
Ok(NodeId::Configured(ConfiguredNodeId(value)))
}
}
}
impl From<NodeId> for u8 {
fn from(value: NodeId) -> Self {
value.raw()
}
}