Skip to main content

matter_kit/clusters/
mod.rs

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