Skip to main content

matter_kit/clusters/
binding.rs

1//! Binding, cluster `0x001E` (Core §9.6).
2//!
3//! A binding is "a persistent relationship between an endpoint and one or more other local or
4//! remote endpoints" — how a switch is told which bulbs it controls. The cluster lives on the
5//! **client** endpoint, and §9.6 is careful that it only records an intention:
6//!
7//! > A binding does not require that the relationship exists. It is up to the node
8//! > application to set up the relationship.
9//!
10//! So this stores and validates the table; acting on it — opening a CASE session to the
11//! target, sending the command — is the application's.
12//!
13//! # The three fields are mutually exclusive in a way that matters
14//!
15//! §9.6.5.1's `TargetStruct` has `Node`, `Group`, `Endpoint` and `Cluster`, and its conformance
16//! column is the whole design:
17//!
18//! * `Node` is `Endpoint` — required when an endpoint is named.
19//! * `Group` is `!Endpoint` — and an endpoint is `!Group`. A binding is *either* unicast
20//!   (node + endpoint) *or* groupcast (group), never both.
21//! * `Cluster` is optional, and narrows whichever of the two it is.
22//!
23//! A table that accepted both at once would describe a target with no meaning, and the node
24//! would have to guess at send time — which is exactly the moment there is nobody to ask.
25//! [`Target::is_valid`] refuses it at the door instead.
26
27use 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
43/// `0x001E` (§9.6.4).
44pub const ID: ClusterId = 0x001E;
45
46/// The revision §9.6.2's table ends on.
47pub const REVISION: u16 = 1;
48
49/// `Binding` (§9.6.6) — `list[TargetStruct]`, `RW VM F`, `N`, mandatory.
50pub const BINDING: AttributeId = 0x0000;
51
52/// The global `FabricIndex` field of a fabric-scoped struct (§7.19.1.9).
53pub const FABRIC_INDEX_FIELD: u8 = 254;
54
55/// One binding (§9.6.5.1's `TargetStruct`).
56///
57/// Either unicast — a `node` and an `endpoint` — or groupcast — a `group`. Never both, and
58/// never neither. `cluster` narrows whichever it is.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub struct Target {
61    /// The fabric this binding belongs to, and the only one that can see it.
62    pub fabric_index: FabricIndex,
63    /// `Node [1]` — "the remote target node ID. If the Endpoint field is present, this field
64    /// SHALL be present."
65    pub node: Option<NodeId>,
66    /// `Group [2]` — "the target group ID that represents remote endpoints".
67    pub group: Option<GroupId>,
68    /// `Endpoint [3]` — "the remote endpoint that the local endpoint is bound to".
69    pub endpoint: Option<EndpointId>,
70    /// `Cluster [4]` — optional, and narrows the target to one cluster on it.
71    pub cluster: Option<ClusterId>,
72}
73
74impl Target {
75    /// A unicast binding to one endpoint on one node.
76    #[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    /// A groupcast binding to every endpoint in a group.
88    #[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    /// The same binding, narrowed to one cluster on the target.
100    #[must_use]
101    pub const fn with_cluster(mut self, cluster: ClusterId) -> Self {
102        self.cluster = Some(cluster);
103        self
104    }
105
106    /// §9.6.5.1's conformance, as a predicate.
107    ///
108    /// * A group and an endpoint are mutually exclusive (`Group` is `!Endpoint`, and the
109    ///   other way round): a binding is unicast or groupcast, not a contradiction.
110    /// * An endpoint requires a node ("If the Endpoint field is present, this field SHALL be
111    ///   present"), because an endpoint number alone names nothing.
112    /// * Something must be named. An empty target is a relationship with nobody.
113    #[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        // §7.21.2's tables bound a cluster id, and §7.19.2.27 bounds an endpoint number:
122        // "Endpoint numbers SHALL NOT be 0xFFFF". A binding naming either outside its range
123        // points at nothing that could exist, and is stored, read back and never resolved —
124        // the same shape as an Access Control target, and the same answer (D100).
125        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        // A node with no endpoint is still a target — §9.6.6.1's second example binds a
136        // cluster on a node — so "names nothing" means neither a node nor a group.
137        self.node.is_some() || self.group.is_some()
138    }
139
140    /// Whether this is a groupcast binding.
141    #[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
168/// Reads one `TargetStruct` whose opening structure the caller has taken.
169fn 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        // The `FabricIndex` a client sends is ignored: §7.19.1.9's field is set by the server
183        // from the accessing fabric, so a client cannot write into another's table.
184        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                // §9.6.5.1 constrains Group to "min 1"; group 0 is the null group.
196                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
216/// §9.6.6's one attribute: `RW VM F` and `N`.
217const ATTRIBUTES: &[AttributeDescriptor] = &[AttributeDescriptor::read_write(BINDING)
218    .with_access(
219        Access::read_write_with(Privilege::View, Privilege::Manage)
220            // The `F` of §9.6.6's `RW VM F`. Without it the interaction model's own
221            // fabric check never fires, and the only thing scoping the list would be this
222            // cluster remembering to do it — a second guard is not a first one.
223            .with_qualities(AccessQualities::FABRIC_SCOPED),
224    )
225    .with_qualities(AttributeQualities::NON_VOLATILE)];
226
227const NO_COMMANDS: &[CommandDescriptor] = &[];
228
229/// The descriptor for this cluster.
230#[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/// The Binding cluster's table (§9.6.6.1).
244///
245/// `N` is the total across every fabric; §9.6.1 asks that a device type's minimum be available
246/// "for each fabric the node supports", which is what [`Binding::per_fabric`] enforces.
247#[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    /// A table with no bindings — §9.6.6's fallback of `[]`.
256    ///
257    /// `per_fabric` is how many entries any one fabric may hold, so that the first fabric to
258    /// fill the table cannot leave a later one unable to bind anything.
259    #[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    /// The per-fabric quota.
269    #[must_use]
270    pub const fn per_fabric(&self) -> usize {
271        self.per_fabric
272    }
273
274    /// Every binding, for a device about to persist them.
275    #[must_use]
276    pub fn targets(&self) -> core::cell::Ref<'_, heapless::Vec<Target, N>> {
277        self.targets.borrow()
278    }
279
280    /// How many bindings one fabric holds.
281    #[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    /// Adds one binding.
291    ///
292    /// §9.6.1: "If, during the creation of multiple bindings, there are no available resources
293    /// to create an entry … the client SHALL respond with a status of RESOURCE_EXHAUSTED, and
294    /// the binding SHALL NOT be created."
295    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    /// Removes every binding of one fabric — what `RemoveFabric` must do.
309    ///
310    /// §9.6.1: "When a binding is removed, the client endpoint SHALL end the binding
311    /// relationship with the removed binding target." Ending it is the application's; this is
312    /// the table's half.
313    pub fn remove_fabric(&self, fabric: FabricIndex) {
314        self.targets
315            .borrow_mut()
316            .retain(|t| t.fabric_index != fabric);
317    }
318
319    /// Whether a fabric's entries belong in this read (§7.19.1.8.2).
320    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        // §7.19.1.8.1: a fabric-scoped list needs an accessing fabric to scope the write to.
359        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                // Only this fabric's entries are replaced; the others were never visible to
394                // the writer and are not its to remove. A replace that fails partway leaves
395                // this fabric's list partly rebuilt, which §10.6.4.3.1 sanctions directly:
396                // "clients that receive an error status for a write action to a list
397                // attribute SHOULD NOT assume that the list contents are unchanged".
398                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        // §9.6.5.1: `Group` is `!Endpoint` and `Endpoint` is `!Group`. A target that named
434        // both would have no meaning, and the node would have to guess at send time.
435        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        // "If the Endpoint field is present, this field SHALL be present" — an endpoint
451        // number on its own does not say whose.
452        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        // §7.21.2's MEI tables and §7.19.2.27's "Endpoint numbers SHALL NOT be 0xFFFF". A
470        // binding pointing at a cluster or an endpoint outside its range resolves to nothing,
471        // for ever, and nothing ever says so — the same shape as an Access Control target.
472        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        // And the shapes that are legal stay legal.
489        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        // §9.6.6.1's two published examples: a switch bound to a group for On/Off, and a
500        // sensor client bound to one cluster on one endpoint of one node.
501        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        // §9.6.6 gives `Binding` access `RW VM F` and quality `N`, and each letter does
513        // something. Dropping the `F` is the quiet one: the interaction model's own
514        // fabric-scoped check never fires, and the only thing scoping the list is the cluster
515        // remembering to — which makes a second guard the first one.
516        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        // §9.6.1: a device type's minimum must be available "for each fabric the node
533        // supports", so one fabric filling the table must not lock another out.
534        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        // Fabric 0 names no fabric, so such a binding could never be read back or removed.
559        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}