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 read(
327 &self,
328 resolved: &Resolved<'_>,
329 ctx: &InteractionContext<'_>,
330 w: &mut TlvWriter<'_>,
331 tag: Tag,
332 ) -> Result<(), Status> {
333 if resolved.attribute != BINDING {
334 return Err(Status::UnsupportedAttribute);
335 }
336 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
337 let targets = self.targets.borrow();
338 full(w.start_array(tag))?;
339 for target in targets
340 .iter()
341 .filter(|t| Self::visible(ctx, t.fabric_index))
342 {
343 full(target.encode(w))?;
344 }
345 full(w.end_container())
346 }
347
348 fn write(
349 &self,
350 resolved: &Resolved<'_>,
351 data: &[u8],
352 op: WriteOp,
353 ctx: &InteractionContext<'_>,
354 ) -> Result<(), Status> {
355 if resolved.attribute != BINDING {
356 return Err(Status::UnsupportedWrite);
357 }
358 let Some(fabric_index) = ctx.fabric_index else {
360 return Err(Status::UnsupportedAccess);
361 };
362
363 let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
364 let element = reader
365 .next_element()
366 .map_err(|_| Status::InvalidAction)?
367 .ok_or(Status::InvalidAction)?;
368
369 match op {
370 WriteOp::Replace => {
371 if element.value.container() != Some(ContainerKind::Array) {
372 return Err(Status::InvalidAction);
373 }
374 let mut replacement: heapless::Vec<Target, N> = heapless::Vec::new();
375 loop {
376 let Some(item) = reader.next_element().map_err(|_| Status::InvalidAction)?
377 else {
378 return Err(Status::InvalidAction);
379 };
380 if item.value == Value::EndOfContainer {
381 break;
382 }
383 if item.value.container() != Some(ContainerKind::Structure) {
384 return Err(Status::InvalidAction);
385 }
386 replacement
387 .push(decode_target(&mut reader, fabric_index)?)
388 .map_err(|_| Status::ResourceExhausted)?;
389 }
390 if replacement.len() > self.per_fabric {
391 return Err(Status::ResourceExhausted);
392 }
393 let mut held = self.targets.borrow_mut();
399 held.retain(|t| t.fabric_index != fabric_index);
400 for target in replacement {
401 held.push(target).map_err(|_| Status::ResourceExhausted)?;
402 }
403 }
404 WriteOp::Append => {
405 if element.value.container() != Some(ContainerKind::Structure) {
406 return Err(Status::InvalidAction);
407 }
408 let target = decode_target(&mut reader, fabric_index)?;
409 self.add(target)?;
410 }
411 }
412 Ok(())
413 }
414}
415
416impl<C: Config, const N: usize> Cluster for Binding<C, N> {
417 const ID: ClusterId = ID;
418}
419
420#[cfg(test)]
421mod tests {
422 use super::*;
423 use crate::config::DefaultConfig;
424
425 type Table = Binding<DefaultConfig, 8>;
426
427 const F1: FabricIndex = FabricIndex(1);
428 const F2: FabricIndex = FabricIndex(2);
429 const BULB: NodeId = NodeId(0x0000_0000_0006_F1F1);
430
431 #[test]
432 fn a_binding_is_unicast_or_groupcast_and_never_both() {
433 let both = Target {
436 fabric_index: F1,
437 node: Some(BULB),
438 group: Some(GroupId(7)),
439 endpoint: Some(1),
440 cluster: None,
441 };
442 assert!(!both.is_valid());
443
444 assert!(Target::unicast(F1, BULB, 1).is_valid());
445 assert!(Target::groupcast(F1, GroupId(7)).is_valid());
446 }
447
448 #[test]
449 fn an_endpoint_without_a_node_names_nothing() {
450 let orphan = Target {
453 fabric_index: F1,
454 node: None,
455 group: None,
456 endpoint: Some(1),
457 cluster: None,
458 };
459 assert!(!orphan.is_valid());
460 }
461
462 #[test]
463 fn an_empty_target_is_a_relationship_with_nobody() {
464 assert!(!Target::default().is_valid());
465 }
466
467 #[test]
468 fn a_target_naming_an_identifier_that_cannot_exist_is_refused() {
469 assert!(
473 !Target::groupcast(F1, GroupId(1))
474 .with_cluster(0xFFFF_FFFF)
475 .is_valid(),
476 "prefix 0xFFFF is Invalid in Table 103's own words"
477 );
478 assert!(
479 !Target::groupcast(F1, GroupId(1))
480 .with_cluster(0x0000_8000)
481 .is_valid(),
482 "the gap between a standard cluster and a manufacturer-specific one"
483 );
484 assert!(
485 !Target::unicast(F1, NodeId(456_789), 0xFFFF).is_valid(),
486 "0xFFFF is not an endpoint number"
487 );
488 assert!(
490 Target::groupcast(F1, GroupId(1))
491 .with_cluster(0xFFF1_FC00)
492 .is_valid()
493 );
494 assert!(Target::unicast(F1, NodeId(456_789), 0xFFFE).is_valid());
495 }
496
497 #[test]
498 fn a_cluster_narrows_either_kind() {
499 let switch = Target::groupcast(F1, GroupId(1234));
502 assert!(switch.is_valid() && switch.is_groupcast());
503
504 let sensor = Target::unicast(F1, NodeId(456_789), 3).with_cluster(1026);
505 assert!(sensor.is_valid());
506 assert_eq!(sensor.cluster, Some(1026));
507 assert!(!sensor.is_groupcast());
508 }
509
510 #[test]
511 fn the_binding_attribute_carries_every_quality_of_its_access_column() {
512 let descriptor = cluster();
517 assert_eq!(descriptor.id, 0x001E);
518 let attribute = descriptor.attribute(BINDING).expect("Binding");
519 assert_eq!(attribute.access.read, Some(Privilege::View));
520 assert_eq!(attribute.access.write, Some(Privilege::Manage));
521 assert!(attribute.access.is_fabric_scoped(), "the `F`");
522 assert!(
523 attribute
524 .qualities
525 .contains(AttributeQualities::NON_VOLATILE),
526 "the `N`"
527 );
528 }
529
530 #[test]
531 fn a_fabrics_quota_is_its_own() {
532 let table = Table::new(2);
535 table.add(Target::unicast(F1, BULB, 1)).expect("first");
536 table.add(Target::unicast(F1, BULB, 2)).expect("second");
537 assert_eq!(
538 table.add(Target::unicast(F1, BULB, 3)).unwrap_err(),
539 Status::ResourceExhausted
540 );
541 table
542 .add(Target::unicast(F2, BULB, 1))
543 .expect("another fabric has its own quota");
544 }
545
546 #[test]
547 fn removing_a_fabric_takes_its_bindings() {
548 let table = Table::new(4);
549 table.add(Target::unicast(F1, BULB, 1)).expect("add");
550 table.add(Target::unicast(F2, BULB, 1)).expect("add");
551 table.remove_fabric(F1);
552 assert_eq!(table.len_of_fabric(F1), 0);
553 assert_eq!(table.len_of_fabric(F2), 1, "another fabric is untouched");
554 }
555
556 #[test]
557 fn a_binding_on_no_fabric_is_refused() {
558 let table = Table::new(4);
560 assert_eq!(
561 table
562 .add(Target::unicast(FabricIndex(0), BULB, 1))
563 .unwrap_err(),
564 Status::ConstraintError
565 );
566 }
567}