use core::cell::RefCell;
use core::marker::PhantomData;
use crate::config::Config;
use crate::dm::{
Access, AccessQualities, AttributeDescriptor, AttributeQualities, ClusterDescriptor,
CommandDescriptor, Privilege, Resolved,
};
use crate::im::{
AttributeId, ClusterHandler, ClusterId, EndpointId, InteractionContext, Status, WriteOp,
};
use crate::msg::{FabricIndex, GroupId, NodeId};
use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, Value};
use super::Cluster;
pub const ID: ClusterId = 0x001E;
pub const REVISION: u16 = 1;
pub const BINDING: AttributeId = 0x0000;
pub const FABRIC_INDEX_FIELD: u8 = 254;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Target {
pub fabric_index: FabricIndex,
pub node: Option<NodeId>,
pub group: Option<GroupId>,
pub endpoint: Option<EndpointId>,
pub cluster: Option<ClusterId>,
}
impl Target {
#[must_use]
pub const fn unicast(fabric_index: FabricIndex, node: NodeId, endpoint: EndpointId) -> Self {
Self {
fabric_index,
node: Some(node),
group: None,
endpoint: Some(endpoint),
cluster: None,
}
}
#[must_use]
pub const fn groupcast(fabric_index: FabricIndex, group: GroupId) -> Self {
Self {
fabric_index,
node: None,
group: Some(group),
endpoint: None,
cluster: None,
}
}
#[must_use]
pub const fn with_cluster(mut self, cluster: ClusterId) -> Self {
self.cluster = Some(cluster);
self
}
#[must_use]
pub const fn is_valid(&self) -> bool {
if self.group.is_some() && self.endpoint.is_some() {
return false;
}
if self.endpoint.is_some() && self.node.is_none() {
return false;
}
if let Some(cluster) = self.cluster
&& !crate::dm::mei::cluster_is_valid(cluster)
{
return false;
}
if let Some(endpoint) = self.endpoint
&& endpoint == 0xFFFF
{
return false;
}
self.node.is_some() || self.group.is_some()
}
#[must_use]
pub const fn is_groupcast(&self) -> bool {
self.group.is_some()
}
fn encode(&self, w: &mut TlvWriter<'_>) -> crate::error::Result<()> {
w.start_structure(Tag::Anonymous)?;
if let Some(node) = self.node {
w.unsigned(Tag::Context(1), node.0)?;
}
if let Some(group) = self.group {
w.unsigned(Tag::Context(2), u64::from(group.0))?;
}
if let Some(endpoint) = self.endpoint {
w.unsigned(Tag::Context(3), u64::from(endpoint))?;
}
if let Some(cluster) = self.cluster {
w.unsigned(Tag::Context(4), u64::from(cluster))?;
}
w.unsigned(
Tag::Context(FABRIC_INDEX_FIELD),
u64::from(self.fabric_index.0),
)?;
w.end_container()
}
}
fn decode_target(reader: &mut TlvReader<'_>, fabric_index: FabricIndex) -> Result<Target, Status> {
let mut target = Target {
fabric_index,
..Target::default()
};
loop {
let Some(element) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
return Err(Status::InvalidAction);
};
if element.value == Value::EndOfContainer {
break;
}
let context = element.tag.context();
if element.value.is_null() || context == Some(FABRIC_INDEX_FIELD) {
reader
.skip_value(&element)
.map_err(|_| Status::InvalidAction)?;
continue;
}
let value = element.unsigned().map_err(|_| Status::ConstraintError)?;
match context {
Some(1) => target.node = Some(NodeId(value)),
Some(2) => {
let id = u16::try_from(value).map_err(|_| Status::ConstraintError)?;
if id == 0 {
return Err(Status::ConstraintError);
}
target.group = Some(GroupId(id));
}
Some(3) => {
target.endpoint = Some(u16::try_from(value).map_err(|_| Status::ConstraintError)?);
}
Some(4) => {
target.cluster = Some(u32::try_from(value).map_err(|_| Status::ConstraintError)?);
}
_ => {}
}
}
if !target.is_valid() {
return Err(Status::ConstraintError);
}
Ok(target)
}
const ATTRIBUTES: &[AttributeDescriptor] = &[AttributeDescriptor::read_write(BINDING)
.with_access(
Access::read_write_with(Privilege::View, Privilege::Manage)
.with_qualities(AccessQualities::FABRIC_SCOPED),
)
.with_qualities(AttributeQualities::NON_VOLATILE)];
const NO_COMMANDS: &[CommandDescriptor] = &[];
#[must_use]
pub const fn cluster() -> ClusterDescriptor<'static> {
ClusterDescriptor {
id: ID,
revision: REVISION,
feature_map: 0,
attributes: ATTRIBUTES,
accepted_commands: NO_COMMANDS,
generated_commands: &[],
events: &[],
}
}
#[derive(Debug)]
pub struct Binding<C: Config, const N: usize> {
targets: RefCell<heapless::Vec<Target, N>>,
per_fabric: usize,
_config: PhantomData<C>,
}
impl<C: Config, const N: usize> Binding<C, N> {
#[must_use]
pub const fn new(per_fabric: usize) -> Self {
Self {
targets: RefCell::new(heapless::Vec::new()),
per_fabric,
_config: PhantomData,
}
}
#[must_use]
pub const fn per_fabric(&self) -> usize {
self.per_fabric
}
#[must_use]
pub fn targets(&self) -> core::cell::Ref<'_, heapless::Vec<Target, N>> {
self.targets.borrow()
}
#[must_use]
pub fn len_of_fabric(&self, fabric: FabricIndex) -> usize {
self.targets
.borrow()
.iter()
.filter(|t| t.fabric_index == fabric)
.count()
}
pub fn add(&self, target: Target) -> Result<(), Status> {
if !target.is_valid() || target.fabric_index.0 == 0 {
return Err(Status::ConstraintError);
}
if self.len_of_fabric(target.fabric_index) >= self.per_fabric {
return Err(Status::ResourceExhausted);
}
self.targets
.borrow_mut()
.push(target)
.map_err(|_| Status::ResourceExhausted)
}
pub fn remove_fabric(&self, fabric: FabricIndex) {
self.targets
.borrow_mut()
.retain(|t| t.fabric_index != fabric);
}
fn visible(ctx: &InteractionContext<'_>, index: FabricIndex) -> bool {
!ctx.fabric_filtered || ctx.fabric_index == Some(index)
}
}
impl<C: Config, const N: usize> ClusterHandler for Binding<C, N> {
fn on_lifecycle(&self, event: crate::im::Lifecycle) {
if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
self.remove_fabric(fabric);
}
}
fn read(
&self,
resolved: &Resolved<'_>,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> Result<(), Status> {
if resolved.attribute != BINDING {
return Err(Status::UnsupportedAttribute);
}
let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
let targets = self.targets.borrow();
full(w.start_array(tag))?;
for target in targets
.iter()
.filter(|t| Self::visible(ctx, t.fabric_index))
{
full(target.encode(w))?;
}
full(w.end_container())
}
fn write(
&self,
resolved: &Resolved<'_>,
data: &[u8],
op: WriteOp,
ctx: &InteractionContext<'_>,
) -> Result<(), Status> {
if resolved.attribute != BINDING {
return Err(Status::UnsupportedWrite);
}
let Some(fabric_index) = ctx.fabric_index else {
return Err(Status::UnsupportedAccess);
};
let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
let element = reader
.next_element()
.map_err(|_| Status::InvalidAction)?
.ok_or(Status::InvalidAction)?;
match op {
WriteOp::Replace => {
if element.value.container() != Some(ContainerKind::Array) {
return Err(Status::InvalidAction);
}
let mut replacement: heapless::Vec<Target, N> = heapless::Vec::new();
loop {
let Some(item) = reader.next_element().map_err(|_| Status::InvalidAction)?
else {
return Err(Status::InvalidAction);
};
if item.value == Value::EndOfContainer {
break;
}
if item.value.container() != Some(ContainerKind::Structure) {
return Err(Status::InvalidAction);
}
replacement
.push(decode_target(&mut reader, fabric_index)?)
.map_err(|_| Status::ResourceExhausted)?;
}
if replacement.len() > self.per_fabric {
return Err(Status::ResourceExhausted);
}
let mut held = self.targets.borrow_mut();
held.retain(|t| t.fabric_index != fabric_index);
for target in replacement {
held.push(target).map_err(|_| Status::ResourceExhausted)?;
}
}
WriteOp::Append => {
if element.value.container() != Some(ContainerKind::Structure) {
return Err(Status::InvalidAction);
}
let target = decode_target(&mut reader, fabric_index)?;
self.add(target)?;
}
}
Ok(())
}
}
impl<C: Config, const N: usize> Cluster for Binding<C, N> {
const ID: ClusterId = ID;
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::DefaultConfig;
type Table = Binding<DefaultConfig, 8>;
const F1: FabricIndex = FabricIndex(1);
const F2: FabricIndex = FabricIndex(2);
const BULB: NodeId = NodeId(0x0000_0000_0006_F1F1);
#[test]
fn a_binding_is_unicast_or_groupcast_and_never_both() {
let both = Target {
fabric_index: F1,
node: Some(BULB),
group: Some(GroupId(7)),
endpoint: Some(1),
cluster: None,
};
assert!(!both.is_valid());
assert!(Target::unicast(F1, BULB, 1).is_valid());
assert!(Target::groupcast(F1, GroupId(7)).is_valid());
}
#[test]
fn an_endpoint_without_a_node_names_nothing() {
let orphan = Target {
fabric_index: F1,
node: None,
group: None,
endpoint: Some(1),
cluster: None,
};
assert!(!orphan.is_valid());
}
#[test]
fn an_empty_target_is_a_relationship_with_nobody() {
assert!(!Target::default().is_valid());
}
#[test]
fn a_target_naming_an_identifier_that_cannot_exist_is_refused() {
assert!(
!Target::groupcast(F1, GroupId(1))
.with_cluster(0xFFFF_FFFF)
.is_valid(),
"prefix 0xFFFF is Invalid in Table 103's own words"
);
assert!(
!Target::groupcast(F1, GroupId(1))
.with_cluster(0x0000_8000)
.is_valid(),
"the gap between a standard cluster and a manufacturer-specific one"
);
assert!(
!Target::unicast(F1, NodeId(456_789), 0xFFFF).is_valid(),
"0xFFFF is not an endpoint number"
);
assert!(
Target::groupcast(F1, GroupId(1))
.with_cluster(0xFFF1_FC00)
.is_valid()
);
assert!(Target::unicast(F1, NodeId(456_789), 0xFFFE).is_valid());
}
#[test]
fn a_cluster_narrows_either_kind() {
let switch = Target::groupcast(F1, GroupId(1234));
assert!(switch.is_valid() && switch.is_groupcast());
let sensor = Target::unicast(F1, NodeId(456_789), 3).with_cluster(1026);
assert!(sensor.is_valid());
assert_eq!(sensor.cluster, Some(1026));
assert!(!sensor.is_groupcast());
}
#[test]
fn the_binding_attribute_carries_every_quality_of_its_access_column() {
let descriptor = cluster();
assert_eq!(descriptor.id, 0x001E);
let attribute = descriptor.attribute(BINDING).expect("Binding");
assert_eq!(attribute.access.read, Some(Privilege::View));
assert_eq!(attribute.access.write, Some(Privilege::Manage));
assert!(attribute.access.is_fabric_scoped(), "the `F`");
assert!(
attribute
.qualities
.contains(AttributeQualities::NON_VOLATILE),
"the `N`"
);
}
#[test]
fn a_fabrics_quota_is_its_own() {
let table = Table::new(2);
table.add(Target::unicast(F1, BULB, 1)).expect("first");
table.add(Target::unicast(F1, BULB, 2)).expect("second");
assert_eq!(
table.add(Target::unicast(F1, BULB, 3)).unwrap_err(),
Status::ResourceExhausted
);
table
.add(Target::unicast(F2, BULB, 1))
.expect("another fabric has its own quota");
}
#[test]
fn removing_a_fabric_takes_its_bindings() {
let table = Table::new(4);
table.add(Target::unicast(F1, BULB, 1)).expect("add");
table.add(Target::unicast(F2, BULB, 1)).expect("add");
table.remove_fabric(F1);
assert_eq!(table.len_of_fabric(F1), 0);
assert_eq!(table.len_of_fabric(F2), 1, "another fabric is untouched");
}
#[test]
fn a_binding_on_no_fabric_is_refused() {
let table = Table::new(4);
assert_eq!(
table
.add(Target::unicast(FabricIndex(0), BULB, 1))
.unwrap_err(),
Status::ConstraintError
);
}
}