matter-kit 0.3.0

Matter (CSA smart-home standard) protocol implementation in Rust: no_std, no-alloc, executor-agnostic
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Cluster behaviour, over the shapes in [`generated`] (Core ch. 9 and ch. 11).
//!
//! A node is not just a data model — it has to *answer*. [`generated`] has every cluster's
//! shape; this module has the behaviour for the ones that have any, from the utility clusters
//! that make a device commissionable and describable to the application clusters a product is
//! built from. All of them are implemented against the same
//! [cluster descriptor](crate::dm::ClusterDescriptor) and [`ClusterHandler`] machinery, so
//! there is one mechanism and not a privileged one for the built-ins.
//!
//! Each module below documents the section it implements, and takes its `ID`, `REVISION` and
//! conformance from [`generated`] rather than restating them — a second copy of a number the
//! specification moves is a number that is wrong after the next revision.
//!
//! # Composition
//!
//! [`ClusterHandler`] is one trait for a whole device — a device
//! has one cluster implementation table and not one per cluster. So each cluster here
//! implements the narrower [`Cluster`] trait, which adds the one thing dispatch needs: the
//! cluster's id. A tuple of `Cluster`s is itself a `ClusterHandler`, dispatching on that id:
//!
//! ```
//! use matter_kit::clusters::basic_information::{Attributes, BasicInformation, Location, Product};
//! use matter_kit::clusters::descriptor::{self, DeviceType};
//! use matter_kit::clusters::general_commissioning::{self, GeneralCommissioning, RegulatoryLocation};
//! use matter_kit::clusters::network_commissioning::{
//!     self as netcomm, Capabilities, EthernetDriver, NetworkCommissioning,
//! };
//! use matter_kit::clusters::Descriptor;
//! use matter_kit::commissioning::window::CommissioningWindow;
//! use matter_kit::commissioning::failsafe::{BasicCommissioningInfo, FailSafe};
//! use matter_kit::dm::{Endpoint, Node};
//! use matter_kit::msg::VendorId;
//!
//! const PRODUCT: Product<'static> = Product::new(
//!     "Example Vendor", VendorId(0xFFF1), "Example Light", 0x8000, "unique-id",
//! );
//!
//! // The attribute list is derived from the product, not written twice.
//! let attributes = Attributes::new(&PRODUCT, false, false);
//! // Sorted by cluster id — 0x001D, 0x0028, 0x0030, 0x0031 — because the lookups binary-
//! // search and `Node::validate` is what catches getting it wrong.
//! let clusters = [
//!     descriptor::cluster(),            // 0x001D
//!     attributes.cluster(),             // 0x0028
//!     general_commissioning::cluster(), // 0x0030
//!     netcomm::ethernet(),              // 0x0031
//! ];
//! // §9.5 requires every endpoint to declare at least one device type. It lives on the
//! // endpoint rather than on the Descriptor cluster, because access control matches ACL
//! // targets against it too and the two must not be able to disagree.
//! const ROOT_NODE: &[DeviceType] = &[DeviceType::new(0x0016, 3)];
//! let endpoints = [Endpoint::new(0, &clusters).with_device_types(ROOT_NODE)];
//! let node = Node::new(&endpoints);
//! node.validate().expect("sorted, so the binary searches cannot silently miss");
//!
//! // One `Location` cell, shared: §11.10.7.4's SetRegulatoryConfig writes Basic
//! // Information's Location attribute.
//! let location = Location::region_agnostic();
//!
//! // The fail-safe is node state, not cluster state: §11.18's credential commands record
//! // against the same context General Commissioning arms.
//! let fail_safe = core::cell::RefCell::new(FailSafe::new(BasicCommissioningInfo::default()));
//! // And so is the commissioning window: §11.19 opens it, §11.10.7.2 gives a PASE
//! // commissioner priority while it is open, and §11.10.7.6 closes it.
//! let window = core::cell::RefCell::new(CommissioningWindow::new());
//!
//! // An Ethernet interface needs no driver and accepts no commands (§11.9.7's table is
//! // `WI | TH`); its one `Networks` entry is seeded by the server.
//! let ethernet = EthernetDriver;
//! let network = NetworkCommissioning::<_, 1>::new(&ethernet, &fail_safe, Capabilities::default());
//! network.store_mut().seed(b"eth0", true).expect("one entry fits");
//!
//! let handler = (
//!     Descriptor::new(node, 0),
//!     BasicInformation::new(&PRODUCT, &location),
//!     GeneralCommissioning::new(
//!         &location,
//!         RegulatoryLocation::IndoorOutdoor,
//!         &fail_safe,
//!         &window,
//!     ),
//!     network,
//! );
//! // `handler` is a `ClusterHandler`; hand it to `Server::new` with an access control.
//! # let _ = &handler;
//! ```
//!
//! The match is over `const` ids, so it compiles to a jump table and costs nothing at
//! runtime — the same dispatch a hand-written `match` would produce, without the chance of
//! forgetting an arm.
//!
//! # Why these types carry state and the descriptors do not
//!
//! A [cluster descriptor](crate::dm::ClusterDescriptor) is the cluster's *shape* and lives
//! in flash. What each type here adds is its *values* — a device's vendor name, its
//! breadcrumb, its fail-safe. [`ClusterHandler`] takes `&self`
//! because reads must be possible from a shared reference, so anything mutable is behind a
//! [`Cell`](core::cell::Cell): no allocation, no locking, and no `&mut` threaded through the
//! interaction model for the sake of two attributes.

pub mod access_control;
/// Administrator Commissioning needs [`crypto`](crate::crypto)'s SPAKE2+ verifier and
/// [`sc`](crate::sc)'s PBKDF parameters.
#[cfg(feature = "rustcrypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
pub mod administrator_commissioning;
pub mod basic_information;
pub mod binding;
pub mod bridged_device_basic_information;
pub mod commissioner_control;
pub mod descriptor;
pub mod device_energy_management;
pub mod electrical_measurement;
pub mod energy_evse;
pub mod ethernet_network_diagnostics;
pub mod general_commissioning;
pub mod general_diagnostics;
pub mod generated;
#[cfg(feature = "rustcrypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
pub mod group_key_management;
/// §11.27 is provisional (Core §2.13), and its key material is [`group`](crate::group)'s.
#[cfg(all(feature = "rustcrypto", feature = "provisional"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "rustcrypto", feature = "provisional"))))]
pub mod groupcast;
pub mod groups;
/// ICD Management needs [`icd`](crate::icd)'s Check-In Protocol, which is cryptography.
#[cfg(feature = "rustcrypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
pub mod icd_management;
pub mod identify;
#[cfg(feature = "rustcrypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
pub mod joint_fabric_administrator;
#[cfg(feature = "rustcrypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
pub mod joint_fabric_datastore;
pub mod label;
pub mod level_control;
pub mod mode;
pub mod network_commissioning;
pub mod on_off;
/// Operational Credentials needs [`cert`](crate::cert), [`attestation`](crate::attestation)
/// and [`fabric`](crate::fabric), which are all cryptography.
#[cfg(feature = "rustcrypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
pub mod operational_credentials;
pub mod ota_provider;
pub mod ota_requestor;
pub mod scenes;
pub mod software_diagnostics;
pub mod thermostat_suggestions;
pub mod thread_network_diagnostics;
#[cfg(feature = "rustcrypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
pub mod tls;
pub mod water_heater_management;
pub mod wi_fi_network_diagnostics;

#[cfg(feature = "rustcrypto")]
pub use administrator_commissioning::AdministratorCommissioning;
pub use basic_information::BasicInformation;
pub use descriptor::Descriptor;
pub use general_commissioning::GeneralCommissioning;
pub use network_commissioning::NetworkCommissioning;
#[cfg(feature = "rustcrypto")]
pub use operational_credentials::OperationalCredentials;

use crate::dm::{Resolved, ResolvedCommand};
use crate::im::{
    ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb, WriteOp,
};
use crate::tlv::{ContainerKind, Element, FromTlv, Tag, TlvReader, TlvWriter};

/// Decodes a command's `CommandFields` — the `CommandDataIB`'s context-1 member (§10.6.11).
///
/// Shared by every cluster that takes a payload, so the failure modes cannot drift between
/// them: a malformed encoding is `INVALID_ACTION`, a well-formed one carrying a value the
/// field cannot hold is `CONSTRAINT_ERROR`, and a missing mandatory field is
/// `INVALID_COMMAND`. §8.8.2.3 makes that distinction the client's only clue about whether
/// retrying with different arguments is worth anything.
pub(crate) fn decode_fields<'a, T: FromTlv<'a>>(fields: &'a [u8]) -> Result<T, StatusIb> {
    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
    let element: Element<'a> = reader
        .next_element()
        .map_err(|_| StatusIb::from(Status::InvalidAction))?
        .ok_or(StatusIb::from(Status::InvalidAction))?;
    T::from_tlv(&mut reader, &element).map_err(|error| {
        StatusIb::from(match error.code() {
            crate::ErrorCode::TlvNotFound => Status::InvalidCommand,
            crate::ErrorCode::TlvOutOfRange | crate::ErrorCode::TlvWrongType => {
                Status::ConstraintError
            }
            _ => Status::InvalidAction,
        })
    })
}

/// What a driver can say about a diagnostics attribute whose `null` means something.
///
/// The three network diagnostics clusters — [`ethernet_network_diagnostics`],
/// [`wi_fi_network_diagnostics`] and [`thread_network_diagnostics`] — all have attributes that
/// are *both* optional and nullable, and the specification gives the two states different
/// meanings: `null` is "the interface is not currently configured or operational", and leaving
/// the attribute out of `AttributeList` is "this device does not report it". `Option<Option<T>>`
/// would say both and say neither clearly, so a driver returns this and names the three answers:
///
/// * [`Reading::Value`] — measured, and this is it.
/// * [`Reading::NotOperational`] — measurable, but not right now; the specification's `null`.
/// * [`Reading::Unsupported`] — not implemented on this device, so it must not appear in
///   `AttributeList` either.
///
/// An attribute that is *mandatory* and nullable has only two of those answers, and its driver
/// method returns [`Option`] instead — a type that cannot say "unsupported" about an attribute
/// the specification requires.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Reading<T> {
    /// A measured value.
    Value(T),
    /// `null`: the interface is not configured or operational.
    NotOperational,
    /// The attribute is not implemented by this device.
    #[default]
    Unsupported,
}

impl<T> Reading<T> {
    /// Whether the device reports this attribute at all.
    #[must_use]
    pub const fn is_supported(&self) -> bool {
        !matches!(self, Self::Unsupported)
    }
}

/// One cluster implementation, tagged with the id it answers for.
///
/// The supertrait is what makes a `Cluster` usable on its own — a device with exactly one
/// cluster needs no dispatch — and the associated `ID` is what makes a tuple of them
/// dispatchable.
pub trait Cluster: ClusterHandler {
    /// The cluster id this implementation serves.
    const ID: ClusterId;
}

/// A shared reference to a cluster is a cluster, so a tuple of borrowed clusters dispatches
/// like a tuple of owned ones.
impl<T: Cluster + ?Sized> Cluster for &T {
    const ID: ClusterId = T::ID;
}

/// The status a dispatcher answers with for a cluster no member serves.
///
/// This should be unreachable in a well-formed device: the server resolves a path against
/// the [`Node`](crate::dm::Node) before calling the handler, so a cluster that is not in the
/// handler tuple is a cluster the node's descriptors claim and nothing implements. Answering
/// `UNSUPPORTED_CLUSTER` rather than panicking keeps that mistake a per-path failure instead
/// of taking the device down.
const UNMATCHED: Status = Status::UnsupportedCluster;

macro_rules! dispatch_tuple {
    ($($name:ident => $slot:ident),+ $(,)?) => {
        impl<$($name: Cluster),+> ClusterHandler for ($($name,)+) {
            fn read(
                &self,
                resolved: &Resolved<'_>,
                ctx: &InteractionContext<'_>,
                w: &mut TlvWriter<'_>,
                tag: Tag,
            ) -> core::result::Result<(), Status> {
                let ($($slot,)+) = self;
                match resolved.cluster.id {
                    $(id if id == $name::ID => $slot.read(resolved, ctx, w, tag),)+
                    _ => Err(UNMATCHED),
                }
            }

            fn data_version(&self, resolved: &Resolved<'_>) -> Option<u32> {
                let ($($slot,)+) = self;
                match resolved.cluster.id {
                    $(id if id == $name::ID => $slot.data_version(resolved),)+
                    _ => None,
                }
            }

            fn write(
                &self,
                resolved: &Resolved<'_>,
                data: &[u8],
                op: WriteOp,
                ctx: &InteractionContext<'_>,
            ) -> core::result::Result<(), Status> {
                let ($($slot,)+) = self;
                match resolved.cluster.id {
                    $(id if id == $name::ID => $slot.write(resolved, data, op, ctx),)+
                    _ => Err(UNMATCHED),
                }
            }

            fn invoke(
                &self,
                resolved: &ResolvedCommand<'_>,
                fields: Option<&[u8]>,
                ctx: &InteractionContext<'_>,
                w: &mut TlvWriter<'_>,
                tag: Tag,
            ) -> core::result::Result<Option<CommandId>, StatusIb> {
                let ($($slot,)+) = self;
                match resolved.cluster.id {
                    $(id if id == $name::ID => $slot.invoke(resolved, fields, ctx, w, tag),)+
                    _ => Err(UNMATCHED.into()),
                }
            }

            /// Broadcast, not routed: a fabric going away is a fact about the node, and
            /// every cluster in the tuple is downstream of it.
            fn on_lifecycle(&self, event: crate::im::Lifecycle) {
                let ($($slot,)+) = self;
                $($slot.on_lifecycle(event);)+
            }
        }
    };
}

dispatch_tuple!(A => a);
dispatch_tuple!(A => a, B => b);
dispatch_tuple!(A => a, B => b, C => c);
dispatch_tuple!(A => a, B => b, C => c, D => d);
dispatch_tuple!(A => a, B => b, C => c, D => d, E => e);
dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f);
dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g);
dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h);
dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i);
dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j);
dispatch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j, K => k);
dispatch_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);

/// One endpoint's clusters, for a node that has more than one.
///
/// A tuple of clusters dispatches by cluster id alone, which is all a single-endpoint device
/// needs. A node with two endpoints has the same cluster twice — every endpoint has its own
/// Descriptor (§9.5), and a two-gang switch has On/Off on both — so the id no longer picks an
/// instance. `At` supplies the missing half of the address, and [`Endpoints`] routes on it.
///
/// ```
/// # use matter_kit::clusters::{At, Endpoints, descriptor::Descriptor};
/// # use matter_kit::dm::{Endpoint, Node};
/// # let clusters = [matter_kit::clusters::descriptor::cluster()];
/// # let endpoints = [Endpoint::new(0, &clusters), Endpoint::new(1, &clusters)];
/// # let node = Node::new(&endpoints);
/// let handler = Endpoints((
///     At::new(0, Descriptor::new(node, 0)),
///     At::new(1, Descriptor::new(node, 1)),
/// ));
/// ```
#[derive(Debug, Clone, Copy)]
pub struct At<H> {
    /// The endpoint this handler answers for.
    pub endpoint: crate::im::EndpointId,
    /// What serves it.
    pub handler: H,
}

impl<H> At<H> {
    /// Binds `handler` to `endpoint`.
    pub const fn new(endpoint: crate::im::EndpointId, handler: H) -> Self {
        Self { endpoint, handler }
    }
}

/// A node's endpoints, each an [`At`].
///
/// Routes on the endpoint first and the cluster id second, which is the order §8.9.2's
/// concrete path names them in. A path naming an endpoint no member holds is
/// `UNSUPPORTED_ENDPOINT` — the same answer the server would give for an endpoint the node
/// does not have, rather than another endpoint's data.
#[derive(Debug, Clone, Copy)]
pub struct Endpoints<T>(pub T);

/// The status for a path whose endpoint no member serves.
///
/// Unreachable in a well-formed device — the server resolves the path against the
/// [`Node`](crate::dm::Node) first — so this catches a node whose descriptors list an endpoint
/// nothing implements, and catches it per path rather than by taking the device down.
const NO_ENDPOINT: Status = Status::UnsupportedEndpoint;

macro_rules! endpoint_tuple {
    ($($name:ident => $slot:ident),+ $(,)?) => {
        impl<$($name: ClusterHandler),+> ClusterHandler for Endpoints<($(At<$name>,)+)> {
            fn read(
                &self,
                resolved: &Resolved<'_>,
                ctx: &InteractionContext<'_>,
                w: &mut TlvWriter<'_>,
                tag: Tag,
            ) -> core::result::Result<(), Status> {
                let Endpoints(($($slot,)+)) = self;
                $(if $slot.endpoint == resolved.endpoint {
                    return $slot.handler.read(resolved, ctx, w, tag);
                })+
                Err(NO_ENDPOINT)
            }

            fn data_version(&self, resolved: &Resolved<'_>) -> Option<u32> {
                let Endpoints(($($slot,)+)) = self;
                $(if $slot.endpoint == resolved.endpoint {
                    return $slot.handler.data_version(resolved);
                })+
                None
            }

            fn write(
                &self,
                resolved: &Resolved<'_>,
                data: &[u8],
                op: WriteOp,
                ctx: &InteractionContext<'_>,
            ) -> core::result::Result<(), Status> {
                let Endpoints(($($slot,)+)) = self;
                $(if $slot.endpoint == resolved.endpoint {
                    return $slot.handler.write(resolved, data, op, ctx);
                })+
                Err(NO_ENDPOINT)
            }

            fn invoke(
                &self,
                resolved: &ResolvedCommand<'_>,
                fields: Option<&[u8]>,
                ctx: &InteractionContext<'_>,
                w: &mut TlvWriter<'_>,
                tag: Tag,
            ) -> core::result::Result<Option<CommandId>, StatusIb> {
                let Endpoints(($($slot,)+)) = self;
                $(if $slot.endpoint == resolved.endpoint {
                    return $slot.handler.invoke(resolved, fields, ctx, w, tag);
                })+
                Err(NO_ENDPOINT.into())
            }

            /// Every endpoint, not the one a path named: the node's endpoints are all on the
            /// fabric that went away.
            fn on_lifecycle(&self, event: crate::im::Lifecycle) {
                let Endpoints(($($slot,)+)) = self;
                $($slot.handler.on_lifecycle(event);)+
            }
        }
    };
}

endpoint_tuple!(A => a);
endpoint_tuple!(A => a, B => b);
endpoint_tuple!(A => a, B => b, C => c);
endpoint_tuple!(A => a, B => b, C => c, D => d);
endpoint_tuple!(A => a, B => b, C => c, D => d, E => e);
endpoint_tuple!(A => a, B => b, C => c, D => d, E => e, F => f);
endpoint_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g);
endpoint_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h);

/// Checks an endpoint against a device type, using the generated cluster library to resolve
/// the feature codes a device type names (§9.2).
///
/// **For a device's tests, not its start-up path.** Resolving a feature code needs
/// [`generated::find`], which reaches the whole library — about 131 KB of read-only data that
/// a device linking three clusters would otherwise never pay for. The check itself is a
/// property of the *code*, not of the running device: an endpoint's furnishing is `const`, so
/// once a test has passed it, running the same check on the device proves nothing new.
///
/// `Descriptor`'s `DeviceTypeList` is a *claim*: a commissioner reading "On/Off Light" expects
/// Identify, Groups, On/Off with its Lighting feature and Scenes Management to be there. A
/// device that advertises the type without furnishing it appears in an app and then does not
/// work, which is a much worse failure than not appearing at all.
pub fn validate_endpoint(
    endpoint: &crate::dm::Endpoint<'_>,
    device_type: &crate::dm::device::DeviceType,
    found: impl FnMut(crate::dm::device::Defect),
) {
    device_type.validate(endpoint, generated::find, found);
}

/// Whether an endpoint is furnished for a device type it claims.
#[must_use]
pub fn endpoint_satisfies(
    endpoint: &crate::dm::Endpoint<'_>,
    device_type: &crate::dm::device::DeviceType,
) -> bool {
    device_type.is_satisfied_by(endpoint, generated::find)
}