1use core::cell::RefCell;
28use core::marker::PhantomData;
29
30use crate::config::Config;
31use crate::dm::{
32 Access, AccessQualities, AttributeDescriptor, AttributeQualities, ClusterDescriptor,
33 CommandDescriptor, Privilege, Resolved,
34};
35use crate::im::{
36 AttributeId, ClusterHandler, ClusterId, EndpointId, InteractionContext, Status, WriteOp,
37};
38use crate::msg::{FabricIndex, GroupId, NodeId};
39use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, Value};
40
41use super::Cluster;
42
43pub const ID: ClusterId = 0x001E;
45
46pub const REVISION: u16 = 1;
48
49pub const BINDING: AttributeId = 0x0000;
51
52pub const FABRIC_INDEX_FIELD: u8 = 254;
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub struct Target {
61 pub fabric_index: FabricIndex,
63 pub node: Option<NodeId>,
66 pub group: Option<GroupId>,
68 pub endpoint: Option<EndpointId>,
70 pub cluster: Option<ClusterId>,
72}
73
74impl Target {
75 #[must_use]
77 pub const fn unicast(fabric_index: FabricIndex, node: NodeId, endpoint: EndpointId) -> Self {
78 Self {
79 fabric_index,
80 node: Some(node),
81 group: None,
82 endpoint: Some(endpoint),
83 cluster: None,
84 }
85 }
86
87 #[must_use]
89 pub const fn groupcast(fabric_index: FabricIndex, group: GroupId) -> Self {
90 Self {
91 fabric_index,
92 node: None,
93 group: Some(group),
94 endpoint: None,
95 cluster: None,
96 }
97 }
98
99 #[must_use]
101 pub const fn with_cluster(mut self, cluster: ClusterId) -> Self {
102 self.cluster = Some(cluster);
103 self
104 }
105
106 #[must_use]
114 pub const fn is_valid(&self) -> bool {
115 if self.group.is_some() && self.endpoint.is_some() {
116 return false;
117 }
118 if self.endpoint.is_some() && self.node.is_none() {
119 return false;
120 }
121 if let Some(cluster) = self.cluster
126 && !crate::dm::mei::cluster_is_valid(cluster)
127 {
128 return false;
129 }
130 if let Some(endpoint) = self.endpoint
131 && endpoint == 0xFFFF
132 {
133 return false;
134 }
135 self.node.is_some() || self.group.is_some()
138 }
139
140 #[must_use]
142 pub const fn is_groupcast(&self) -> bool {
143 self.group.is_some()
144 }
145
146 fn encode(&self, w: &mut TlvWriter<'_>) -> crate::error::Result<()> {
147 w.start_structure(Tag::Anonymous)?;
148 if let Some(node) = self.node {
149 w.unsigned(Tag::Context(1), node.0)?;
150 }
151 if let Some(group) = self.group {
152 w.unsigned(Tag::Context(2), u64::from(group.0))?;
153 }
154 if let Some(endpoint) = self.endpoint {
155 w.unsigned(Tag::Context(3), u64::from(endpoint))?;
156 }
157 if let Some(cluster) = self.cluster {
158 w.unsigned(Tag::Context(4), u64::from(cluster))?;
159 }
160 w.unsigned(
161 Tag::Context(FABRIC_INDEX_FIELD),
162 u64::from(self.fabric_index.0),
163 )?;
164 w.end_container()
165 }
166}
167
168fn decode_target(reader: &mut TlvReader<'_>, fabric_index: FabricIndex) -> Result<Target, Status> {
170 let mut target = Target {
171 fabric_index,
172 ..Target::default()
173 };
174 loop {
175 let Some(element) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
176 return Err(Status::InvalidAction);
177 };
178 if element.value == Value::EndOfContainer {
179 break;
180 }
181 let context = element.tag.context();
182 if element.value.is_null() || context == Some(FABRIC_INDEX_FIELD) {
185 reader
186 .skip_value(&element)
187 .map_err(|_| Status::InvalidAction)?;
188 continue;
189 }
190 let value = element.unsigned().map_err(|_| Status::ConstraintError)?;
191 match context {
192 Some(1) => target.node = Some(NodeId(value)),
193 Some(2) => {
194 let id = u16::try_from(value).map_err(|_| Status::ConstraintError)?;
195 if id == 0 {
197 return Err(Status::ConstraintError);
198 }
199 target.group = Some(GroupId(id));
200 }
201 Some(3) => {
202 target.endpoint = Some(u16::try_from(value).map_err(|_| Status::ConstraintError)?);
203 }
204 Some(4) => {
205 target.cluster = Some(u32::try_from(value).map_err(|_| Status::ConstraintError)?);
206 }
207 _ => {}
208 }
209 }
210 if !target.is_valid() {
211 return Err(Status::ConstraintError);
212 }
213 Ok(target)
214}
215
216const ATTRIBUTES: &[AttributeDescriptor] = &[AttributeDescriptor::read_write(BINDING)
218 .with_access(
219 Access::read_write_with(Privilege::View, Privilege::Manage)
220 .with_qualities(AccessQualities::FABRIC_SCOPED),
224 )
225 .with_qualities(AttributeQualities::NON_VOLATILE)];
226
227const NO_COMMANDS: &[CommandDescriptor] = &[];
228
229#[must_use]
231pub const fn cluster() -> ClusterDescriptor<'static> {
232 ClusterDescriptor {
233 id: ID,
234 revision: REVISION,
235 feature_map: 0,
236 attributes: ATTRIBUTES,
237 accepted_commands: NO_COMMANDS,
238 generated_commands: &[],
239 events: &[],
240 }
241}
242
243#[derive(Debug)]
248pub struct Binding<C: Config, const N: usize> {
249 targets: RefCell<heapless::Vec<Target, N>>,
250 per_fabric: usize,
251 _config: PhantomData<C>,
252}
253
254impl<C: Config, const N: usize> Binding<C, N> {
255 #[must_use]
260 pub const fn new(per_fabric: usize) -> Self {
261 Self {
262 targets: RefCell::new(heapless::Vec::new()),
263 per_fabric,
264 _config: PhantomData,
265 }
266 }
267
268 #[must_use]
270 pub const fn per_fabric(&self) -> usize {
271 self.per_fabric
272 }
273
274 #[must_use]
276 pub fn targets(&self) -> core::cell::Ref<'_, heapless::Vec<Target, N>> {
277 self.targets.borrow()
278 }
279
280 #[must_use]
282 pub fn len_of_fabric(&self, fabric: FabricIndex) -> usize {
283 self.targets
284 .borrow()
285 .iter()
286 .filter(|t| t.fabric_index == fabric)
287 .count()
288 }
289
290 pub fn add(&self, target: Target) -> Result<(), Status> {
296 if !target.is_valid() || target.fabric_index.0 == 0 {
297 return Err(Status::ConstraintError);
298 }
299 if self.len_of_fabric(target.fabric_index) >= self.per_fabric {
300 return Err(Status::ResourceExhausted);
301 }
302 self.targets
303 .borrow_mut()
304 .push(target)
305 .map_err(|_| Status::ResourceExhausted)
306 }
307
308 pub fn remove_fabric(&self, fabric: FabricIndex) {
314 self.targets
315 .borrow_mut()
316 .retain(|t| t.fabric_index != fabric);
317 }
318
319 fn visible(ctx: &InteractionContext<'_>, index: FabricIndex) -> bool {
321 !ctx.fabric_filtered || ctx.fabric_index == Some(index)
322 }
323}
324
325impl<C: Config, const N: usize> ClusterHandler for Binding<C, N> {
326 fn on_lifecycle(&self, event: crate::im::Lifecycle) {
329 if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
330 self.remove_fabric(fabric);
331 }
332 }
333 fn read(
334 &self,
335 resolved: &Resolved<'_>,
336 ctx: &InteractionContext<'_>,
337 w: &mut TlvWriter<'_>,
338 tag: Tag,
339 ) -> Result<(), Status> {
340 if resolved.attribute != BINDING {
341 return Err(Status::UnsupportedAttribute);
342 }
343 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
344 let targets = self.targets.borrow();
345 full(w.start_array(tag))?;
346 for target in targets
347 .iter()
348 .filter(|t| Self::visible(ctx, t.fabric_index))
349 {
350 full(target.encode(w))?;
351 }
352 full(w.end_container())
353 }
354
355 fn write(
356 &self,
357 resolved: &Resolved<'_>,
358 data: &[u8],
359 op: WriteOp,
360 ctx: &InteractionContext<'_>,
361 ) -> Result<(), Status> {
362 if resolved.attribute != BINDING {
363 return Err(Status::UnsupportedWrite);
364 }
365 let Some(fabric_index) = ctx.fabric_index else {
367 return Err(Status::UnsupportedAccess);
368 };
369
370 let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
371 let element = reader
372 .next_element()
373 .map_err(|_| Status::InvalidAction)?
374 .ok_or(Status::InvalidAction)?;
375
376 match op {
377 WriteOp::Replace => {
378 if element.value.container() != Some(ContainerKind::Array) {
379 return Err(Status::InvalidAction);
380 }
381 let mut replacement: heapless::Vec<Target, N> = heapless::Vec::new();
382 loop {
383 let Some(item) = reader.next_element().map_err(|_| Status::InvalidAction)?
384 else {
385 return Err(Status::InvalidAction);
386 };
387 if item.value == Value::EndOfContainer {
388 break;
389 }
390 if item.value.container() != Some(ContainerKind::Structure) {
391 return Err(Status::InvalidAction);
392 }
393 replacement
394 .push(decode_target(&mut reader, fabric_index)?)
395 .map_err(|_| Status::ResourceExhausted)?;
396 }
397 if replacement.len() > self.per_fabric {
398 return Err(Status::ResourceExhausted);
399 }
400 let mut held = self.targets.borrow_mut();
406 held.retain(|t| t.fabric_index != fabric_index);
407 for target in replacement {
408 held.push(target).map_err(|_| Status::ResourceExhausted)?;
409 }
410 }
411 WriteOp::Append => {
412 if element.value.container() != Some(ContainerKind::Structure) {
413 return Err(Status::InvalidAction);
414 }
415 let target = decode_target(&mut reader, fabric_index)?;
416 self.add(target)?;
417 }
418 }
419 Ok(())
420 }
421}
422
423impl<C: Config, const N: usize> Cluster for Binding<C, N> {
424 const ID: ClusterId = ID;
425}
426
427#[cfg(test)]
428mod tests {
429 use super::*;
430 use crate::config::DefaultConfig;
431
432 type Table = Binding<DefaultConfig, 8>;
433
434 const F1: FabricIndex = FabricIndex(1);
435 const F2: FabricIndex = FabricIndex(2);
436 const BULB: NodeId = NodeId(0x0000_0000_0006_F1F1);
437
438 #[test]
439 fn a_binding_is_unicast_or_groupcast_and_never_both() {
440 let both = Target {
443 fabric_index: F1,
444 node: Some(BULB),
445 group: Some(GroupId(7)),
446 endpoint: Some(1),
447 cluster: None,
448 };
449 assert!(!both.is_valid());
450
451 assert!(Target::unicast(F1, BULB, 1).is_valid());
452 assert!(Target::groupcast(F1, GroupId(7)).is_valid());
453 }
454
455 #[test]
456 fn an_endpoint_without_a_node_names_nothing() {
457 let orphan = Target {
460 fabric_index: F1,
461 node: None,
462 group: None,
463 endpoint: Some(1),
464 cluster: None,
465 };
466 assert!(!orphan.is_valid());
467 }
468
469 #[test]
470 fn an_empty_target_is_a_relationship_with_nobody() {
471 assert!(!Target::default().is_valid());
472 }
473
474 #[test]
475 fn a_target_naming_an_identifier_that_cannot_exist_is_refused() {
476 assert!(
480 !Target::groupcast(F1, GroupId(1))
481 .with_cluster(0xFFFF_FFFF)
482 .is_valid(),
483 "prefix 0xFFFF is Invalid in Table 103's own words"
484 );
485 assert!(
486 !Target::groupcast(F1, GroupId(1))
487 .with_cluster(0x0000_8000)
488 .is_valid(),
489 "the gap between a standard cluster and a manufacturer-specific one"
490 );
491 assert!(
492 !Target::unicast(F1, NodeId(456_789), 0xFFFF).is_valid(),
493 "0xFFFF is not an endpoint number"
494 );
495 assert!(
497 Target::groupcast(F1, GroupId(1))
498 .with_cluster(0xFFF1_FC00)
499 .is_valid()
500 );
501 assert!(Target::unicast(F1, NodeId(456_789), 0xFFFE).is_valid());
502 }
503
504 #[test]
505 fn a_cluster_narrows_either_kind() {
506 let switch = Target::groupcast(F1, GroupId(1234));
509 assert!(switch.is_valid() && switch.is_groupcast());
510
511 let sensor = Target::unicast(F1, NodeId(456_789), 3).with_cluster(1026);
512 assert!(sensor.is_valid());
513 assert_eq!(sensor.cluster, Some(1026));
514 assert!(!sensor.is_groupcast());
515 }
516
517 #[test]
518 fn the_binding_attribute_carries_every_quality_of_its_access_column() {
519 let descriptor = cluster();
524 assert_eq!(descriptor.id, 0x001E);
525 let attribute = descriptor.attribute(BINDING).expect("Binding");
526 assert_eq!(attribute.access.read, Some(Privilege::View));
527 assert_eq!(attribute.access.write, Some(Privilege::Manage));
528 assert!(attribute.access.is_fabric_scoped(), "the `F`");
529 assert!(
530 attribute
531 .qualities
532 .contains(AttributeQualities::NON_VOLATILE),
533 "the `N`"
534 );
535 }
536
537 #[test]
538 fn a_fabrics_quota_is_its_own() {
539 let table = Table::new(2);
542 table.add(Target::unicast(F1, BULB, 1)).expect("first");
543 table.add(Target::unicast(F1, BULB, 2)).expect("second");
544 assert_eq!(
545 table.add(Target::unicast(F1, BULB, 3)).unwrap_err(),
546 Status::ResourceExhausted
547 );
548 table
549 .add(Target::unicast(F2, BULB, 1))
550 .expect("another fabric has its own quota");
551 }
552
553 #[test]
554 fn removing_a_fabric_takes_its_bindings() {
555 let table = Table::new(4);
556 table.add(Target::unicast(F1, BULB, 1)).expect("add");
557 table.add(Target::unicast(F2, BULB, 1)).expect("add");
558 table.remove_fabric(F1);
559 assert_eq!(table.len_of_fabric(F1), 0);
560 assert_eq!(table.len_of_fabric(F2), 1, "another fabric is untouched");
561 }
562
563 #[test]
564 fn a_binding_on_no_fabric_is_refused() {
565 let table = Table::new(4);
567 assert_eq!(
568 table
569 .add(Target::unicast(FabricIndex(0), BULB, 1))
570 .unwrap_err(),
571 Status::ConstraintError
572 );
573 }
574}