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.
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    /// §9.6: the Binding table is fabric-scoped (`F`), so a removed fabric's targets go with
327    /// it — otherwise this node keeps trying to reach a peer on a fabric it has left.
328    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        // §7.19.1.8.1: a fabric-scoped list needs an accessing fabric to scope the write to.
366        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                // Only this fabric's entries are replaced; the others were never visible to
401                // the writer and are not its to remove. A replace that fails partway leaves
402                // this fabric's list partly rebuilt, which §10.6.4.3.1 sanctions directly:
403                // "clients that receive an error status for a write action to a list
404                // attribute SHOULD NOT assume that the list contents are unchanged".
405                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        // §9.6.5.1: `Group` is `!Endpoint` and `Endpoint` is `!Group`. A target that named
441        // both would have no meaning, and the node would have to guess at send time.
442        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        // "If the Endpoint field is present, this field SHALL be present" — an endpoint
458        // number on its own does not say whose.
459        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        // §7.21.2's MEI tables and §7.19.2.27's "Endpoint numbers SHALL NOT be 0xFFFF". A
477        // binding pointing at a cluster or an endpoint outside its range resolves to nothing,
478        // for ever, and nothing ever says so — the same shape as an Access Control target.
479        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        // And the shapes that are legal stay legal.
496        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        // §9.6.6.1's two published examples: a switch bound to a group for On/Off, and a
507        // sensor client bound to one cluster on one endpoint of one node.
508        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        // §9.6.6 gives `Binding` access `RW VM F` and quality `N`, and each letter does
520        // something. Dropping the `F` is the quiet one: the interaction model's own
521        // fabric-scoped check never fires, and the only thing scoping the list is the cluster
522        // remembering to — which makes a second guard the first one.
523        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        // §9.6.1: a device type's minimum must be available "for each fabric the node
540        // supports", so one fabric filling the table must not lock another out.
541        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        // Fabric 0 names no fabric, so such a binding could never be read back or removed.
566        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}