use thiserror::Error;
use zigbee_macros::impl_byte;
use zigbee_types::IeeeAddress;
use zigbee_types::StorageVec;
impl_byte! {
#[tag(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BindingAddrMode {
Group = 0x01,
Device = 0x03,
#[fallback = true]
Reserved(u8),
}
}
impl BindingAddrMode {
pub fn is_group(self) -> bool {
self == Self::Group
}
pub fn is_device(self) -> bool {
self == Self::Device
}
}
impl Default for BindingAddrMode {
fn default() -> Self {
Self::Device
}
}
impl_byte! {
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Binding {
pub src_endpoint: u8,
pub cluster_id: u16,
pub dst_addr_mode: BindingAddrMode,
#[parse_if = dst_addr_mode.is_group()]
pub dst_group: Option<u16>,
#[parse_if = dst_addr_mode.is_device()]
pub dst_ieee: Option<IeeeAddress>,
#[parse_if = dst_addr_mode.is_device()]
pub dst_endpoint: Option<u8>,
}
}
impl Binding {
pub fn device(
src_endpoint: u8,
cluster_id: u16,
dst_ieee: IeeeAddress,
dst_endpoint: u8,
) -> Self {
Self {
src_endpoint,
cluster_id,
dst_addr_mode: BindingAddrMode::Device,
dst_group: None,
dst_ieee: Some(dst_ieee),
dst_endpoint: Some(dst_endpoint),
}
}
pub fn group(src_endpoint: u8, cluster_id: u16, dst_group: u16) -> Self {
Self {
src_endpoint,
cluster_id,
dst_addr_mode: BindingAddrMode::Group,
dst_group: Some(dst_group),
dst_ieee: None,
dst_endpoint: None,
}
}
pub fn matches(&self, src_endpoint: u8, cluster_id: u16) -> bool {
self.src_endpoint == src_endpoint && self.cluster_id == cluster_id
}
}
pub type BindingTable<const N: usize> = StorageVec<Binding, N>;
pub(crate) fn create_binding_link<const N: usize>(
table: &mut BindingTable<N>,
binding: Binding,
) -> Result<(), BindingError> {
if table.contains(&binding) {
return Ok(());
}
table.push(binding).map_err(|_| BindingError::TableFull)
}
pub(crate) fn remove_binding_link<const N: usize>(
table: &mut BindingTable<N>,
binding: &Binding,
) -> Result<(), BindingError> {
let Some(index) = table.iter().position(|entry| entry == binding) else {
return Err(BindingError::InvalidBinding);
};
table.remove(index);
Ok(())
}
#[derive(Error, Debug)]
#[error("SourceError")]
pub(crate) enum BindingError {
IllegalRequest,
InvalidBinding,
TableFull,
}