Skip to main content

matter_kit/clusters/
descriptor.rs

1//! Descriptor cluster `0x001D` (Core §9.5) — what an endpoint *is*.
2//!
3//! > This cluster describes an endpoint instance on the node, independently from other
4//! > endpoints, but also allows composition of endpoints to conform to complex device type
5//! > patterns.
6//!
7//! Every endpoint has one, and a commissioner reads it first: `DeviceTypeList` says what the
8//! endpoint claims to be, `ServerList` and `ClientList` say what it speaks, `PartsList` says
9//! what it is composed of.
10//!
11//! # Three of its five attributes are derived, not stored
12//!
13//! `ServerList` is "each cluster ID for the server clusters present on the endpoint
14//! instance" — which the node's own [`Endpoint`] already says. So this
15//! cluster reads it out of the data model rather than holding a second copy, for exactly the
16//! reason §7.13's globals are synthesised: a hand-maintained list is a list that drifts, and
17//! a `ServerList` that disagrees with what the endpoint serves fails certification in a way
18//! that is tedious to find.
19//!
20//! `PartsList` is the exception that must be given: §9.2.3's endpoint composition is a
21//! *tree*, and a flat set of endpoints does not say which contains which. So the
22//! [`Descriptor`] is constructed per endpoint with its parts.
23//!
24//! # Revision 3
25//!
26//! | Revision | Change |
27//! |---|---|
28//! | 1 | Initial revision |
29//! | 2 | Semantic tag list; `TagList` feature |
30//! | 3 | Add `EndpointUniqueID` attribute |
31
32use crate::dm::meta::{AttributeDescriptor, AttributeQualities, ClusterDescriptor};
33use crate::dm::{Endpoint, Node, Resolved};
34use crate::im::{AttributeId, ClusterHandler, ClusterId, EndpointId, InteractionContext, Status};
35use crate::tlv::{Tag, TlvWriter};
36
37use super::Cluster;
38
39/// `0x001D` (§9.5.3).
40pub const ID: ClusterId = 0x001D;
41
42/// The highest revision in §9.5.1's table.
43pub const REVISION: u16 = 3;
44
45/// `DeviceTypeList` (§9.5.6.1) — `list[DeviceTypeStruct]`, min 1, `F`, `RV`, mandatory.
46pub const DEVICE_TYPE_LIST: AttributeId = 0x0000;
47/// `ServerList` (§9.5.6.2) — `list[cluster-id]`, `F`, `RV`, mandatory.
48pub const SERVER_LIST: AttributeId = 0x0001;
49/// `ClientList` (§9.5.6.3) — `list[cluster-id]`, `F`, `RV`, mandatory.
50pub const CLIENT_LIST: AttributeId = 0x0002;
51/// `PartsList` (§9.5.6.4) — `list[endpoint-no]`, `RV`, mandatory. Not `F`: a bridge's parts
52/// change as devices appear.
53pub const PARTS_LIST: AttributeId = 0x0003;
54/// `TagList` (§9.5.6.5) — `list[SemanticTagStruct]`, 1 to 6, `F`, `RV`, `TAGLIST`.
55pub const TAG_LIST: AttributeId = 0x0004;
56/// `EndpointUniqueID` (§9.5.6.6) — `string`, max 32, `F`, `RV`, optional.
57pub const ENDPOINT_UNIQUE_ID: AttributeId = 0x0005;
58
59/// `TAGLIST` (§9.5.4, bit 0) — "The TagList attribute is present".
60pub const FEATURE_TAG_LIST: u32 = 1 << 0;
61
62pub use crate::dm::DeviceType;
63
64/// A `SemanticTagStruct` (System Model §9.8.1), as carried by `TagList`.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct SemanticTag<'a> {
67    /// `MfgCode [0]` — the vendor that defined the namespace, or `None` for a standard one.
68    /// Nullable: "If the MfgCode field is not null, the namespace… SHALL be scoped to the
69    /// manufacturer."
70    pub mfg_code: Option<crate::msg::VendorId>,
71    /// `NamespaceID [1]` — which namespace the tag is drawn from.
72    pub namespace_id: u8,
73    /// `Tag [2]` — the tag within that namespace.
74    pub tag: u8,
75    /// `Label [3]` — an optional human-readable label, max 64, nullable.
76    pub label: Option<&'a str>,
77}
78
79/// The attribute descriptors §9.5.6 defines, without `TagList` or `EndpointUniqueID`.
80///
81/// All four are `RV` at View — §7.6's default — and all but `PartsList` are `F`.
82const BASE_ATTRIBUTES: [AttributeDescriptor; 4] = [
83    AttributeDescriptor::read_only(DEVICE_TYPE_LIST).with_qualities(AttributeQualities::FIXED),
84    AttributeDescriptor::read_only(SERVER_LIST).with_qualities(AttributeQualities::FIXED),
85    AttributeDescriptor::read_only(CLIENT_LIST).with_qualities(AttributeQualities::FIXED),
86    AttributeDescriptor::read_only(PARTS_LIST),
87];
88
89/// … and with `TagList`, for an endpoint that declares the `TAGLIST` feature.
90const TAGGED_ATTRIBUTES: [AttributeDescriptor; 5] = [
91    BASE_ATTRIBUTES[0],
92    BASE_ATTRIBUTES[1],
93    BASE_ATTRIBUTES[2],
94    BASE_ATTRIBUTES[3],
95    AttributeDescriptor::read_only(TAG_LIST).with_qualities(AttributeQualities::FIXED),
96];
97
98/// … and with `EndpointUniqueID` but no `TagList`.
99const IDENTIFIED_ATTRIBUTES: [AttributeDescriptor; 5] = [
100    BASE_ATTRIBUTES[0],
101    BASE_ATTRIBUTES[1],
102    BASE_ATTRIBUTES[2],
103    BASE_ATTRIBUTES[3],
104    AttributeDescriptor::read_only(ENDPOINT_UNIQUE_ID).with_qualities(AttributeQualities::FIXED),
105];
106
107/// … and with both.
108const FULL_ATTRIBUTES: [AttributeDescriptor; 6] = [
109    TAGGED_ATTRIBUTES[0],
110    TAGGED_ATTRIBUTES[1],
111    TAGGED_ATTRIBUTES[2],
112    TAGGED_ATTRIBUTES[3],
113    TAGGED_ATTRIBUTES[4],
114    AttributeDescriptor::read_only(ENDPOINT_UNIQUE_ID).with_qualities(AttributeQualities::FIXED),
115];
116
117/// The descriptor for an endpoint with neither optional attribute.
118#[must_use]
119pub const fn cluster() -> ClusterDescriptor<'static> {
120    descriptor_with(&BASE_ATTRIBUTES, 0)
121}
122
123/// The descriptor for an endpoint that serves `TagList`, declaring `TAGLIST`.
124#[must_use]
125pub const fn cluster_with_tags() -> ClusterDescriptor<'static> {
126    descriptor_with(&TAGGED_ATTRIBUTES, FEATURE_TAG_LIST)
127}
128
129/// The descriptor for an endpoint that serves `EndpointUniqueID` but not `TagList`.
130#[must_use]
131pub const fn cluster_with_unique_id() -> ClusterDescriptor<'static> {
132    descriptor_with(&IDENTIFIED_ATTRIBUTES, 0)
133}
134
135/// The descriptor for an endpoint that serves both optional attributes.
136#[must_use]
137pub const fn cluster_full() -> ClusterDescriptor<'static> {
138    descriptor_with(&FULL_ATTRIBUTES, FEATURE_TAG_LIST)
139}
140
141const fn descriptor_with(
142    attributes: &'static [AttributeDescriptor],
143    feature_map: u32,
144) -> ClusterDescriptor<'static> {
145    ClusterDescriptor {
146        id: ID,
147        revision: REVISION,
148        feature_map,
149        attributes,
150        accepted_commands: &[],
151        generated_commands: &[],
152        events: &[],
153    }
154}
155
156/// The Descriptor cluster on one endpoint.
157///
158/// Borrows the [`Node`] rather than copying anything out of it: `ServerList` and `ClientList`
159/// are views of the endpoint's own cluster set, and the whole point is that they cannot
160/// disagree with it.
161///
162/// One instance per endpoint, because §9.5 is scoped to an endpoint — [`Descriptor::endpoint`]
163/// is the endpoint it answers for, and a read of any other endpoint's Descriptor is a
164/// different instance.
165#[derive(Debug, Clone, Copy)]
166pub struct Descriptor<'a> {
167    /// The node this endpoint belongs to — the source of `ServerList`.
168    pub node: Node<'a>,
169    /// The endpoint this instance is on.
170    pub endpoint: EndpointId,
171    /// `PartsList` (§9.5.6.4) — the endpoints this one is composed of.
172    pub parts: &'a [EndpointId],
173    /// `TagList` (§9.5.6.5), when the instance declares `TAGLIST`.
174    pub tags: &'a [SemanticTag<'a>],
175    /// `EndpointUniqueID` (§9.5.6.6), when the instance serves it.
176    pub unique_id: Option<&'a str>,
177}
178
179impl<'a> Descriptor<'a> {
180    /// A Descriptor for an endpoint, with nothing composed under it.
181    ///
182    /// `DeviceTypeList` is not a parameter: §9.5.6.1's list is the endpoint's own, and it is
183    /// read from the node. Passing it separately would let a Descriptor publish device types
184    /// that the endpoint it names does not have — and §6.6.6.2's access control matches ACL
185    /// targets against the endpoint's, so the two disagreeing is a privilege decision made on
186    /// one list and reported from another.
187    #[must_use]
188    pub const fn new(node: Node<'a>, endpoint: EndpointId) -> Self {
189        Self {
190            node,
191            endpoint,
192            parts: &[],
193            tags: &[],
194            unique_id: None,
195        }
196    }
197
198    /// The device types of the endpoint this instance answers for (§9.5.6.1).
199    #[must_use]
200    pub fn device_types(&self) -> &'a [DeviceType] {
201        match self.node.endpoint(self.endpoint) {
202            Some(endpoint) => endpoint.device_types,
203            None => &[],
204        }
205    }
206
207    /// The clusters the endpoint speaks as a client (§9.5.6.3).
208    ///
209    /// Read from the node for the same reason `DeviceTypeList` is: a Descriptor that carried
210    /// its own copy could publish a `ClientList` the endpoint it names does not have, and
211    /// §9.2's device-type check reads the endpoint's.
212    #[must_use]
213    pub fn clients(&self) -> &'a [ClusterId] {
214        match self.node.endpoint(self.endpoint) {
215            Some(endpoint) => endpoint.clients,
216            None => &[],
217        }
218    }
219
220    /// The same instance with a `PartsList`.
221    #[must_use]
222    pub const fn with_parts(mut self, parts: &'a [EndpointId]) -> Self {
223        self.parts = parts;
224        self
225    }
226
227    /// The same instance with a `TagList` — requires the `TAGLIST` feature.
228    #[must_use]
229    pub const fn with_tags(mut self, tags: &'a [SemanticTag<'a>]) -> Self {
230        self.tags = tags;
231        self
232    }
233
234    /// The same instance with an `EndpointUniqueID`.
235    #[must_use]
236    pub const fn with_unique_id(mut self, unique_id: &'a str) -> Self {
237        self.unique_id = Some(unique_id);
238        self
239    }
240
241    /// The cluster descriptor matching what this instance serves.
242    ///
243    /// `TagList` and `EndpointUniqueID` are in the list exactly when this instance has them,
244    /// because §7.13.3's `AttributeList` is what a commissioner builds its model from — an
245    /// entry for an attribute that answers `UNSUPPORTED_ATTRIBUTE` is a certification
246    /// failure, and so is a served attribute missing from the list.
247    #[must_use]
248    pub fn descriptor(&self) -> ClusterDescriptor<'static> {
249        match (!self.tags.is_empty(), self.unique_id.is_some()) {
250            (false, false) => cluster(),
251            (true, false) => cluster_with_tags(),
252            (false, true) => cluster_with_unique_id(),
253            (true, true) => cluster_full(),
254        }
255    }
256
257    fn this_endpoint(&self) -> Option<&'a Endpoint<'a>> {
258        self.node.endpoint(self.endpoint)
259    }
260}
261
262impl ClusterHandler for Descriptor<'_> {
263    fn read(
264        &self,
265        resolved: &Resolved<'_>,
266        _ctx: &InteractionContext<'_>,
267        w: &mut TlvWriter<'_>,
268        tag: Tag,
269    ) -> core::result::Result<(), Status> {
270        // A Descriptor instance answers for one endpoint. Reading it through a path on a
271        // different endpoint would silently report the wrong endpoint's cluster list, which
272        // is worse than refusing: a commissioner would build its model from it.
273        if resolved.endpoint != self.endpoint {
274            return Err(Status::UnsupportedEndpoint);
275        }
276        match resolved.attribute {
277            DEVICE_TYPE_LIST => {
278                w.start_array(tag).map_err(|_| Status::ResourceExhausted)?;
279                for device_type in self.device_types() {
280                    w.start_structure(Tag::Anonymous)
281                        .map_err(|_| Status::ResourceExhausted)?;
282                    w.unsigned(Tag::Context(0), u64::from(device_type.device_type))
283                        .map_err(|_| Status::ResourceExhausted)?;
284                    w.unsigned(Tag::Context(1), u64::from(device_type.revision))
285                        .map_err(|_| Status::ResourceExhausted)?;
286                    w.end_container().map_err(|_| Status::ResourceExhausted)?;
287                }
288                w.end_container().map_err(|_| Status::ResourceExhausted)?;
289                Ok(())
290            }
291            SERVER_LIST => {
292                // Derived, never stored: the endpoint's own cluster set is the answer.
293                let endpoint = self.this_endpoint().ok_or(Status::UnsupportedEndpoint)?;
294                write_cluster_ids(w, tag, endpoint.clusters.iter().map(|c| c.id))
295            }
296            CLIENT_LIST => write_cluster_ids(w, tag, self.clients().iter().copied()),
297            PARTS_LIST => {
298                w.start_array(tag).map_err(|_| Status::ResourceExhausted)?;
299                for part in self.parts {
300                    w.unsigned(Tag::Anonymous, u64::from(*part))
301                        .map_err(|_| Status::ResourceExhausted)?;
302                }
303                w.end_container().map_err(|_| Status::ResourceExhausted)?;
304                Ok(())
305            }
306            TAG_LIST => {
307                w.start_array(tag).map_err(|_| Status::ResourceExhausted)?;
308                for semantic in self.tags {
309                    w.start_structure(Tag::Anonymous)
310                        .map_err(|_| Status::ResourceExhausted)?;
311                    match semantic.mfg_code {
312                        Some(vendor) => w.unsigned(Tag::Context(0), u64::from(vendor.0)),
313                        None => w.null(Tag::Context(0)),
314                    }
315                    .map_err(|_| Status::ResourceExhausted)?;
316                    w.unsigned(Tag::Context(1), u64::from(semantic.namespace_id))
317                        .map_err(|_| Status::ResourceExhausted)?;
318                    w.unsigned(Tag::Context(2), u64::from(semantic.tag))
319                        .map_err(|_| Status::ResourceExhausted)?;
320                    if let Some(label) = semantic.label {
321                        w.utf8(Tag::Context(3), label)
322                            .map_err(|_| Status::ResourceExhausted)?;
323                    }
324                    w.end_container().map_err(|_| Status::ResourceExhausted)?;
325                }
326                w.end_container().map_err(|_| Status::ResourceExhausted)?;
327                Ok(())
328            }
329            ENDPOINT_UNIQUE_ID => {
330                let unique_id = self.unique_id.ok_or(Status::UnsupportedAttribute)?;
331                w.utf8(tag, unique_id)
332                    .map_err(|_| Status::ResourceExhausted)
333            }
334            _ => Err(Status::UnsupportedAttribute),
335        }
336    }
337}
338
339fn write_cluster_ids(
340    w: &mut TlvWriter<'_>,
341    tag: Tag,
342    ids: impl Iterator<Item = ClusterId>,
343) -> core::result::Result<(), Status> {
344    w.start_array(tag).map_err(|_| Status::ResourceExhausted)?;
345    for id in ids {
346        w.unsigned(Tag::Anonymous, u64::from(id))
347            .map_err(|_| Status::ResourceExhausted)?;
348    }
349    w.end_container().map_err(|_| Status::ResourceExhausted)
350}
351
352impl Cluster for Descriptor<'_> {
353    const ID: ClusterId = ID;
354}