Skip to main content

matter_kit/clusters/
mod.rs

1//! The clusters every Matter node has (Core ch. 9 and ch. 11).
2//!
3//! A node is not just a data model — it has to *answer*. These are the utility clusters that
4//! make a device commissionable and describable, implemented against the same
5//! [cluster descriptor](crate::dm::ClusterDescriptor) and
6//! [`ClusterHandler`] machinery an application cluster uses, so
7//! there is one mechanism and not a privileged one for the built-ins.
8//!
9//! | Cluster | Id | Section | Revision | Feature |
10//! |---|---|---|---|---|
11//! | [`descriptor`] | `0x001D` | §9.5 | 3 | |
12//! | [`basic_information`] | `0x0028` | §11.1 | 6 | |
13//! | [`general_commissioning`] | `0x0030` | §11.10 | 2 | |
14//! | [`network_commissioning`] | `0x0031` | §11.9 | 2 | |
15//! | `administrator_commissioning` | `0x003C` | §11.19 | 1 | `rustcrypto` |
16//! | `operational_credentials` | `0x003E` | §11.18 | 2 | `rustcrypto` |
17//!
18//! # Composition
19//!
20//! [`ClusterHandler`] is one trait for a whole device — a device
21//! has one cluster implementation table and not one per cluster. So each cluster here
22//! implements the narrower [`Cluster`] trait, which adds the one thing dispatch needs: the
23//! cluster's id. A tuple of `Cluster`s is itself a `ClusterHandler`, dispatching on that id:
24//!
25//! ```
26//! use matter_kit::clusters::basic_information::{Attributes, BasicInformation, Location, Product};
27//! use matter_kit::clusters::descriptor::{self, DeviceType};
28//! use matter_kit::clusters::general_commissioning::{self, GeneralCommissioning, RegulatoryLocation};
29//! use matter_kit::clusters::network_commissioning::{
30//!     self as netcomm, Capabilities, EthernetDriver, NetworkCommissioning,
31//! };
32//! use matter_kit::clusters::Descriptor;
33//! use matter_kit::commissioning::window::CommissioningWindow;
34//! use matter_kit::commissioning::failsafe::{BasicCommissioningInfo, FailSafe};
35//! use matter_kit::dm::{Endpoint, Node};
36//! use matter_kit::msg::VendorId;
37//!
38//! const PRODUCT: Product<'static> = Product::new(
39//!     "Example Vendor", VendorId(0xFFF1), "Example Light", 0x8000, "unique-id",
40//! );
41//!
42//! // The attribute list is derived from the product, not written twice.
43//! let attributes = Attributes::new(&PRODUCT, false, false);
44//! // Sorted by cluster id — 0x001D, 0x0028, 0x0030, 0x0031 — because the lookups binary-
45//! // search and `Node::validate` is what catches getting it wrong.
46//! let clusters = [
47//!     descriptor::cluster(),            // 0x001D
48//!     attributes.cluster(),             // 0x0028
49//!     general_commissioning::cluster(), // 0x0030
50//!     netcomm::ethernet(),              // 0x0031
51//! ];
52//! // §9.5 requires every endpoint to declare at least one device type. It lives on the
53//! // endpoint rather than on the Descriptor cluster, because access control matches ACL
54//! // targets against it too and the two must not be able to disagree.
55//! const ROOT_NODE: &[DeviceType] = &[DeviceType::new(0x0016, 3)];
56//! let endpoints = [Endpoint::new(0, &clusters).with_device_types(ROOT_NODE)];
57//! let node = Node::new(&endpoints);
58//! node.validate().expect("sorted, so the binary searches cannot silently miss");
59//!
60//! // One `Location` cell, shared: §11.10.7.4's SetRegulatoryConfig writes Basic
61//! // Information's Location attribute.
62//! let location = Location::region_agnostic();
63//!
64//! // The fail-safe is node state, not cluster state: §11.18's credential commands record
65//! // against the same context General Commissioning arms.
66//! let fail_safe = core::cell::RefCell::new(FailSafe::new(BasicCommissioningInfo::default()));
67//! // And so is the commissioning window: §11.19 opens it, §11.10.7.2 gives a PASE
68//! // commissioner priority while it is open, and §11.10.7.6 closes it.
69//! let window = core::cell::RefCell::new(CommissioningWindow::new());
70//!
71//! // An Ethernet interface needs no driver and accepts no commands (§11.9.7's table is
72//! // `WI | TH`); its one `Networks` entry is seeded by the server.
73//! let ethernet = EthernetDriver;
74//! let network = NetworkCommissioning::<_, 1>::new(&ethernet, &fail_safe, Capabilities::default());
75//! network.store_mut().seed(b"eth0", true).expect("one entry fits");
76//!
77//! let handler = (
78//!     Descriptor::new(node, 0),
79//!     BasicInformation::new(&PRODUCT, &location),
80//!     GeneralCommissioning::new(
81//!         &location,
82//!         RegulatoryLocation::IndoorOutdoor,
83//!         &fail_safe,
84//!         &window,
85//!     ),
86//!     network,
87//! );
88//! // `handler` is a `ClusterHandler`; hand it to `Server::new` with an access control.
89//! # let _ = &handler;
90//! ```
91//!
92//! The match is over `const` ids, so it compiles to a jump table and costs nothing at
93//! runtime — the same dispatch a hand-written `match` would produce, without the chance of
94//! forgetting an arm.
95//!
96//! # Why these three carry state and the descriptors do not
97//!
98//! A [cluster descriptor](crate::dm::ClusterDescriptor) is the cluster's *shape* and lives
99//! in flash. What each type here adds is its *values* — a device's vendor name, its
100//! breadcrumb, its fail-safe. [`ClusterHandler`] takes `&self`
101//! because reads must be possible from a shared reference, so anything mutable is behind a
102//! [`Cell`](core::cell::Cell): no allocation, no locking, and no `&mut` threaded through the
103//! interaction model for the sake of two attributes.
104
105pub mod access_control;
106/// Administrator Commissioning needs [`crypto`](crate::crypto)'s SPAKE2+ verifier and
107/// [`sc`](crate::sc)'s PBKDF parameters.
108#[cfg(feature = "rustcrypto")]
109#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
110pub mod administrator_commissioning;
111pub mod basic_information;
112pub mod binding;
113pub mod bridged_device_basic_information;
114pub mod commissioner_control;
115pub mod descriptor;
116pub mod device_energy_management;
117pub mod electrical_measurement;
118pub mod energy_evse;
119pub mod ethernet_network_diagnostics;
120pub mod general_commissioning;
121pub mod general_diagnostics;
122pub mod generated;
123#[cfg(feature = "rustcrypto")]
124#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
125pub mod group_key_management;
126/// §11.27 is provisional (Core §2.13), and its key material is [`group`](crate::group)'s.
127#[cfg(all(feature = "rustcrypto", feature = "provisional"))]
128#[cfg_attr(docsrs, doc(cfg(all(feature = "rustcrypto", feature = "provisional"))))]
129pub mod groupcast;
130pub mod groups;
131/// ICD Management needs [`icd`](crate::icd)'s Check-In Protocol, which is cryptography.
132#[cfg(feature = "rustcrypto")]
133#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
134pub mod icd_management;
135pub mod identify;
136#[cfg(feature = "rustcrypto")]
137#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
138pub mod joint_fabric_administrator;
139#[cfg(feature = "rustcrypto")]
140#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
141pub mod joint_fabric_datastore;
142pub mod label;
143pub mod level_control;
144pub mod mode;
145pub mod network_commissioning;
146pub mod on_off;
147/// Operational Credentials needs [`cert`](crate::cert), [`attestation`](crate::attestation)
148/// and [`fabric`](crate::fabric), which are all cryptography.
149#[cfg(feature = "rustcrypto")]
150#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
151pub mod operational_credentials;
152pub mod ota_provider;
153pub mod ota_requestor;
154pub mod scenes;
155pub mod software_diagnostics;
156pub mod thermostat_suggestions;
157#[cfg(feature = "rustcrypto")]
158#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
159pub mod tls;
160pub mod water_heater_management;
161
162#[cfg(feature = "rustcrypto")]
163pub use administrator_commissioning::AdministratorCommissioning;
164pub use basic_information::BasicInformation;
165pub use descriptor::Descriptor;
166pub use general_commissioning::GeneralCommissioning;
167pub use network_commissioning::NetworkCommissioning;
168#[cfg(feature = "rustcrypto")]
169pub use operational_credentials::OperationalCredentials;
170
171use crate::dm::{Resolved, ResolvedCommand};
172use crate::im::{
173    ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb, WriteOp,
174};
175use crate::tlv::{ContainerKind, Element, FromTlv, Tag, TlvReader, TlvWriter};
176
177/// Decodes a command's `CommandFields` — the `CommandDataIB`'s context-1 member (§10.6.11).
178///
179/// Shared by every cluster that takes a payload, so the failure modes cannot drift between
180/// them: a malformed encoding is `INVALID_ACTION`, a well-formed one carrying a value the
181/// field cannot hold is `CONSTRAINT_ERROR`, and a missing mandatory field is
182/// `INVALID_COMMAND`. §8.8.2.3 makes that distinction the client's only clue about whether
183/// retrying with different arguments is worth anything.
184pub(crate) fn decode_fields<'a, T: FromTlv<'a>>(fields: &'a [u8]) -> Result<T, StatusIb> {
185    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
186    let element: Element<'a> = reader
187        .next_element()
188        .map_err(|_| StatusIb::from(Status::InvalidAction))?
189        .ok_or(StatusIb::from(Status::InvalidAction))?;
190    T::from_tlv(&mut reader, &element).map_err(|error| {
191        StatusIb::from(match error.code() {
192            crate::ErrorCode::TlvNotFound => Status::InvalidCommand,
193            crate::ErrorCode::TlvOutOfRange | crate::ErrorCode::TlvWrongType => {
194                Status::ConstraintError
195            }
196            _ => Status::InvalidAction,
197        })
198    })
199}
200
201/// One cluster implementation, tagged with the id it answers for.
202///
203/// The supertrait is what makes a `Cluster` usable on its own — a device with exactly one
204/// cluster needs no dispatch — and the associated `ID` is what makes a tuple of them
205/// dispatchable.
206pub trait Cluster: ClusterHandler {
207    /// The cluster id this implementation serves.
208    const ID: ClusterId;
209}
210
211/// A shared reference to a cluster is a cluster, so a tuple of borrowed clusters dispatches
212/// like a tuple of owned ones.
213impl<T: Cluster + ?Sized> Cluster for &T {
214    const ID: ClusterId = T::ID;
215}
216
217/// The status a dispatcher answers with for a cluster no member serves.
218///
219/// This should be unreachable in a well-formed device: the server resolves a path against
220/// the [`Node`](crate::dm::Node) before calling the handler, so a cluster that is not in the
221/// handler tuple is a cluster the node's descriptors claim and nothing implements. Answering
222/// `UNSUPPORTED_CLUSTER` rather than panicking keeps that mistake a per-path failure instead
223/// of taking the device down.
224const UNMATCHED: Status = Status::UnsupportedCluster;
225
226macro_rules! dispatch_tuple {
227    ($($name:ident => $slot:ident),+ $(,)?) => {
228        impl<$($name: Cluster),+> ClusterHandler for ($($name,)+) {
229            fn read(
230                &self,
231                resolved: &Resolved<'_>,
232                ctx: &InteractionContext<'_>,
233                w: &mut TlvWriter<'_>,
234                tag: Tag,
235            ) -> core::result::Result<(), Status> {
236                let ($($slot,)+) = self;
237                match resolved.cluster.id {
238                    $(id if id == $name::ID => $slot.read(resolved, ctx, w, tag),)+
239                    _ => Err(UNMATCHED),
240                }
241            }
242
243            fn data_version(&self, resolved: &Resolved<'_>) -> Option<u32> {
244                let ($($slot,)+) = self;
245                match resolved.cluster.id {
246                    $(id if id == $name::ID => $slot.data_version(resolved),)+
247                    _ => None,
248                }
249            }
250
251            fn write(
252                &self,
253                resolved: &Resolved<'_>,
254                data: &[u8],
255                op: WriteOp,
256                ctx: &InteractionContext<'_>,
257            ) -> core::result::Result<(), Status> {
258                let ($($slot,)+) = self;
259                match resolved.cluster.id {
260                    $(id if id == $name::ID => $slot.write(resolved, data, op, ctx),)+
261                    _ => Err(UNMATCHED),
262                }
263            }
264
265            fn invoke(
266                &self,
267                resolved: &ResolvedCommand<'_>,
268                fields: Option<&[u8]>,
269                ctx: &InteractionContext<'_>,
270                w: &mut TlvWriter<'_>,
271                tag: Tag,
272            ) -> core::result::Result<Option<CommandId>, StatusIb> {
273                let ($($slot,)+) = self;
274                match resolved.cluster.id {
275                    $(id if id == $name::ID => $slot.invoke(resolved, fields, ctx, w, tag),)+
276                    _ => Err(UNMATCHED.into()),
277                }
278            }
279        }
280    };
281}
282
283dispatch_tuple!(A => a);
284dispatch_tuple!(A => a, B => b);
285dispatch_tuple!(A => a, B => b, C => c);
286dispatch_tuple!(A => a, B => b, C => c, D => d);
287dispatch_tuple!(A => a, B => b, C => c, D => d, E => e);
288dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f);
289dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g);
290dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h);
291dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i);
292dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j);
293dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j, K => k);
294dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j, K => k, L => l);
295
296/// One endpoint's clusters, for a node that has more than one.
297///
298/// A tuple of clusters dispatches by cluster id alone, which is all a single-endpoint device
299/// needs. A node with two endpoints has the same cluster twice — every endpoint has its own
300/// Descriptor (§9.5), and a two-gang switch has On/Off on both — so the id no longer picks an
301/// instance. `At` supplies the missing half of the address, and [`Endpoints`] routes on it.
302///
303/// ```
304/// # use matter_kit::clusters::{At, Endpoints, descriptor::Descriptor};
305/// # use matter_kit::dm::{Endpoint, Node};
306/// # let clusters = [matter_kit::clusters::descriptor::cluster()];
307/// # let endpoints = [Endpoint::new(0, &clusters), Endpoint::new(1, &clusters)];
308/// # let node = Node::new(&endpoints);
309/// let handler = Endpoints((
310///     At::new(0, Descriptor::new(node, 0)),
311///     At::new(1, Descriptor::new(node, 1)),
312/// ));
313/// ```
314#[derive(Debug, Clone, Copy)]
315pub struct At<H> {
316    /// The endpoint this handler answers for.
317    pub endpoint: crate::im::EndpointId,
318    /// What serves it.
319    pub handler: H,
320}
321
322impl<H> At<H> {
323    /// Binds `handler` to `endpoint`.
324    pub const fn new(endpoint: crate::im::EndpointId, handler: H) -> Self {
325        Self { endpoint, handler }
326    }
327}
328
329/// A node's endpoints, each an [`At`].
330///
331/// Routes on the endpoint first and the cluster id second, which is the order §8.9.2's
332/// concrete path names them in. A path naming an endpoint no member holds is
333/// `UNSUPPORTED_ENDPOINT` — the same answer the server would give for an endpoint the node
334/// does not have, rather than another endpoint's data.
335#[derive(Debug, Clone, Copy)]
336pub struct Endpoints<T>(pub T);
337
338/// The status for a path whose endpoint no member serves.
339///
340/// Unreachable in a well-formed device — the server resolves the path against the
341/// [`Node`](crate::dm::Node) first — so this catches a node whose descriptors list an endpoint
342/// nothing implements, and catches it per path rather than by taking the device down.
343const NO_ENDPOINT: Status = Status::UnsupportedEndpoint;
344
345macro_rules! endpoint_tuple {
346    ($($name:ident => $slot:ident),+ $(,)?) => {
347        impl<$($name: ClusterHandler),+> ClusterHandler for Endpoints<($(At<$name>,)+)> {
348            fn read(
349                &self,
350                resolved: &Resolved<'_>,
351                ctx: &InteractionContext<'_>,
352                w: &mut TlvWriter<'_>,
353                tag: Tag,
354            ) -> core::result::Result<(), Status> {
355                let Endpoints(($($slot,)+)) = self;
356                $(if $slot.endpoint == resolved.endpoint {
357                    return $slot.handler.read(resolved, ctx, w, tag);
358                })+
359                Err(NO_ENDPOINT)
360            }
361
362            fn data_version(&self, resolved: &Resolved<'_>) -> Option<u32> {
363                let Endpoints(($($slot,)+)) = self;
364                $(if $slot.endpoint == resolved.endpoint {
365                    return $slot.handler.data_version(resolved);
366                })+
367                None
368            }
369
370            fn write(
371                &self,
372                resolved: &Resolved<'_>,
373                data: &[u8],
374                op: WriteOp,
375                ctx: &InteractionContext<'_>,
376            ) -> core::result::Result<(), Status> {
377                let Endpoints(($($slot,)+)) = self;
378                $(if $slot.endpoint == resolved.endpoint {
379                    return $slot.handler.write(resolved, data, op, ctx);
380                })+
381                Err(NO_ENDPOINT)
382            }
383
384            fn invoke(
385                &self,
386                resolved: &ResolvedCommand<'_>,
387                fields: Option<&[u8]>,
388                ctx: &InteractionContext<'_>,
389                w: &mut TlvWriter<'_>,
390                tag: Tag,
391            ) -> core::result::Result<Option<CommandId>, StatusIb> {
392                let Endpoints(($($slot,)+)) = self;
393                $(if $slot.endpoint == resolved.endpoint {
394                    return $slot.handler.invoke(resolved, fields, ctx, w, tag);
395                })+
396                Err(NO_ENDPOINT.into())
397            }
398        }
399    };
400}
401
402endpoint_tuple!(A => a);
403endpoint_tuple!(A => a, B => b);
404endpoint_tuple!(A => a, B => b, C => c);
405endpoint_tuple!(A => a, B => b, C => c, D => d);
406endpoint_tuple!(A => a, B => b, C => c, D => d, E => e);
407endpoint_tuple!(A => a, B => b, C => c, D => d, E => e, F => f);
408endpoint_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g);
409endpoint_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h);
410
411/// Checks an endpoint against a device type, using the generated cluster library to resolve
412/// the feature codes a device type names (§9.2).
413///
414/// **For a device's tests, not its start-up path.** Resolving a feature code needs
415/// [`generated::find`], which reaches the whole library — about 131 KB of read-only data that
416/// a device linking three clusters would otherwise never pay for. The check itself is a
417/// property of the *code*, not of the running device: an endpoint's furnishing is `const`, so
418/// once a test has passed it, running the same check on the device proves nothing new.
419///
420/// `Descriptor`'s `DeviceTypeList` is a *claim*: a commissioner reading "On/Off Light" expects
421/// Identify, Groups, On/Off with its Lighting feature and Scenes Management to be there. A
422/// device that advertises the type without furnishing it appears in an app and then does not
423/// work, which is a much worse failure than not appearing at all.
424pub fn validate_endpoint(
425    endpoint: &crate::dm::Endpoint<'_>,
426    device_type: &crate::dm::device::DeviceType,
427    found: impl FnMut(crate::dm::device::Defect),
428) {
429    device_type.validate(endpoint, generated::find, found);
430}
431
432/// Whether an endpoint is furnished for a device type it claims.
433#[must_use]
434pub fn endpoint_satisfies(
435    endpoint: &crate::dm::Endpoint<'_>,
436    device_type: &crate::dm::device::DeviceType,
437) -> bool {
438    device_type.is_satisfied_by(endpoint, generated::find)
439}