matter_kit/clusters/basic_information.rs
1//! Basic Information cluster `0x0028` (Core §11.1) — who this node is.
2//!
3//! > This cluster provides attributes and events for determining basic information about
4//! > Nodes, which supports both Commissioning and operational determination of Node
5//! > characteristics, such as Vendor ID, Product ID and serial number, which apply to the
6//! > whole Node.
7//!
8//! It lives on endpoint 0 and there is exactly one per node.
9//!
10//! # Almost all of it is `F` — fixed, and therefore `const`
11//!
12//! Sixteen of the nineteen attributes carry the `F` quality: their values are decided when
13//! the product is built and never change. So [`Product`] is a `const` record the application
14//! points at, held in flash, and only the three mutable attributes — `NodeLabel`,
15//! `Location`, `LocalConfigDisabled` — cost RAM.
16//!
17//! `Location` is the interesting one of the three. §11.10.7.4 says `SetRegulatoryConfig`'s
18//! `CountryCode` "SHALL be used to set the Location attribute reflected by the Basic
19//! Information Cluster" — so the General Commissioning cluster writes an attribute of *this*
20//! one, which is why [`Location`] is a separate shareable cell rather than a field.
21//!
22//! # Revision 6
23//!
24//! | Revision | Change |
25//! |---|---|
26//! | 1 | Initial revision |
27//! | 2 | Added `ProductAppearance` |
28//! | 3 | Added `SpecificationVersion` and `MaxPathsPerInvoke` |
29//! | 4 | `UniqueID` conformance became mandatory |
30//! | 5 | Added `ConfigurationVersion` as provisional |
31//! | 6 | Extended `CapabilityMinimaStruct`; `ConfigurationVersion` no longer provisional |
32
33use core::cell::Cell;
34
35use crate::dm::Resolved;
36use crate::dm::access::{Access, Privilege};
37use crate::dm::meta::{
38 AttributeDescriptor, AttributeQualities, ClusterDescriptor, EventDescriptor, EventPriority,
39};
40use crate::im::{
41 AttributeId, ClusterHandler, ClusterId, EventId, InteractionContext, Status, WriteOp,
42};
43use crate::msg::VendorId;
44use crate::tlv::{ContainerKind, Element, Tag, TlvReader, TlvWriter, Value};
45
46use super::Cluster;
47
48/// `0x0028` (§11.1.3).
49pub const ID: ClusterId = 0x0028;
50
51/// The highest revision in §11.1.1's table.
52pub const REVISION: u16 = 6;
53
54/// `SpecificationVersion` (§11.1.5.22) for Matter 1.6.
55///
56/// "The format of this number is segmented as its four component bytes": major, minor, dot,
57/// reserved. So 1.6.0.0 is `0x01_06_00_00` — and §11.1.5.22 is explicit that "Comparison of
58/// SpecificationVersion SHALL always include the total value over 32 bits, without masking
59/// reserved parts", which is why this is one constant and not four.
60pub const SPECIFICATION_VERSION: u32 = 0x0106_0000;
61
62#[doc(inline)]
63pub use crate::DATA_MODEL_REVISION;
64
65/// `DataModelRevision` — `uint16`, `F`, `RV`, mandatory.
66pub const DATA_MODEL_REVISION_ID: AttributeId = 0x0000;
67/// `VendorName` — `string` max 32, `F`, `RV`, mandatory.
68pub const VENDOR_NAME: AttributeId = 0x0001;
69/// `VendorID` — `vendor-id`, `F`, `RV`, mandatory.
70pub const VENDOR_ID: AttributeId = 0x0002;
71/// `ProductName` — `string` max 32, `F`, `RV`, mandatory.
72pub const PRODUCT_NAME: AttributeId = 0x0003;
73/// `ProductID` — `uint16`, `F`, `RV`, mandatory.
74pub const PRODUCT_ID: AttributeId = 0x0004;
75/// `NodeLabel` — `string` max 32, `N`, fallback `""`, `RW VM`, mandatory.
76pub const NODE_LABEL: AttributeId = 0x0005;
77/// `Location` — `string` exactly 2, `N`, fallback `"XX"`, `RW VA`, mandatory.
78pub const LOCATION: AttributeId = 0x0006;
79/// `HardwareVersion` — `uint16`, `F`, `RV`, mandatory.
80pub const HARDWARE_VERSION: AttributeId = 0x0007;
81/// `HardwareVersionString` — `string` 1 to 64, `F`, `RV`, mandatory.
82pub const HARDWARE_VERSION_STRING: AttributeId = 0x0008;
83/// `SoftwareVersion` — `uint32`, `F`, `RV`, mandatory.
84pub const SOFTWARE_VERSION: AttributeId = 0x0009;
85/// `SoftwareVersionString` — `string` 1 to 64, `F`, `RV`, mandatory.
86pub const SOFTWARE_VERSION_STRING: AttributeId = 0x000A;
87/// `ManufacturingDate` — `string` 8 to 16, `F`, `RV`, optional.
88pub const MANUFACTURING_DATE: AttributeId = 0x000B;
89/// `PartNumber` — `string` max 32, `F`, `RV`, optional.
90pub const PART_NUMBER: AttributeId = 0x000C;
91/// `ProductURL` — `string` max 256, `F`, `RV`, optional.
92pub const PRODUCT_URL: AttributeId = 0x000D;
93/// `ProductLabel` — `string` max 64, `F`, `RV`, optional.
94pub const PRODUCT_LABEL: AttributeId = 0x000E;
95/// `SerialNumber` — `string` max 32, `F`, `RV`, optional.
96pub const SERIAL_NUMBER: AttributeId = 0x000F;
97/// `LocalConfigDisabled` — `bool`, `N`, fallback false, `RW VM`, optional.
98pub const LOCAL_CONFIG_DISABLED: AttributeId = 0x0010;
99/// `Reachable` — `bool`, fallback true, `RV`, optional.
100pub const REACHABLE: AttributeId = 0x0011;
101/// `UniqueID` — `string` max 32, `F`, `RV`, mandatory from revision 4.
102pub const UNIQUE_ID: AttributeId = 0x0012;
103/// `CapabilityMinima` — `CapabilityMinimaStruct`, `F`, `RV`, mandatory.
104pub const CAPABILITY_MINIMA: AttributeId = 0x0013;
105/// `ProductAppearance` — `ProductAppearanceStruct`, `F`, `RV`, optional from revision 2.
106pub const PRODUCT_APPEARANCE: AttributeId = 0x0014;
107/// `SpecificationVersion` — `uint32`, `F`, `RV`, mandatory from revision 3.
108pub const SPECIFICATION_VERSION_ID: AttributeId = 0x0015;
109/// `MaxPathsPerInvoke` — `uint16` min 1, `F`, `RV`, mandatory from revision 3.
110pub const MAX_PATHS_PER_INVOKE: AttributeId = 0x0016;
111/// `ConfigurationVersion` — `uint32` min 1, `N`, fallback 1, `RV`, mandatory from revision 6.
112pub const CONFIGURATION_VERSION: AttributeId = 0x0018;
113
114/// `StartUp` (§11.1.6.1) — CRITICAL, `V`, mandatory.
115pub const START_UP: EventId = 0x00;
116/// `ShutDown` (§11.1.6.2) — CRITICAL, `V`, optional.
117pub const SHUT_DOWN: EventId = 0x01;
118/// `Leave` (§11.1.6.3) — INFO, `V`, optional.
119pub const LEAVE: EventId = 0x02;
120/// `ReachableChanged` (§11.1.6.4) — INFO, `V`, conformance `Reachable`.
121pub const REACHABLE_CHANGED: EventId = 0x03;
122
123/// `ProductFinishEnum` (§11.1.4.1).
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
125#[repr(u8)]
126#[non_exhaustive]
127pub enum ProductFinish {
128 /// Some other finish not listed.
129 Other = 0,
130 /// A matte finish.
131 Matte = 1,
132 /// A satin finish.
133 Satin = 2,
134 /// A polished or shiny finish.
135 Polished = 3,
136 /// A rugged finish.
137 Rugged = 4,
138 /// A fabric finish.
139 Fabric = 5,
140}
141
142/// `ProductAppearanceStruct` (§11.1.4.3) — "a description of the product's appearance".
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub struct ProductAppearance {
145 /// `Finish [0]` — "the visible finish of the product".
146 pub finish: ProductFinish,
147 /// `PrimaryColor [1]` — a `ColorEnum`, nullable: "If the product has no representative
148 /// color, the field SHALL be null."
149 pub primary_color: Option<u8>,
150}
151
152/// `CapabilityMinimaStruct` (§11.1.4.4) — "the minimum guaranteed value for some system-wide
153/// resource capabilities".
154///
155/// The last four fields arrived in cluster revision 6, where §11.1.4.4 makes them **mandatory**.
156/// They are `Option` so that a node declaring an older `ClusterRevision` can omit them — this
157/// crate declares revision 6, so its own defaults fill them in.
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub struct CapabilityMinima {
160 /// `CaseSessionsPerFabric [0]` — 3 to 10000, fallback 3. "SHALL NOT be smaller than the
161 /// required minimum indicated in Section 4.14.2.8".
162 pub case_sessions_per_fabric: u16,
163 /// `SubscriptionsPerFabric [1]` — 3 to 10000, fallback 3.
164 pub subscriptions_per_fabric: u16,
165 /// `SimultaneousInvocationsSupported [2]` — 1 to 10000, revision 6.
166 pub simultaneous_invocations: Option<u16>,
167 /// `SimultaneousWritesSupported [3]` — 1 to 10000, revision 6.
168 pub simultaneous_writes: Option<u16>,
169 /// `ReadPathsSupported [4]` — 9 to 10000, revision 6. §2.11.2.1's read limit.
170 pub read_paths: Option<u16>,
171 /// `SubscribePathsSupported [5]` — 3 to 10000, revision 6. §2.11.2.2's subscribe limit.
172 pub subscribe_paths: Option<u16>,
173}
174
175impl CapabilityMinima {
176 /// The values a node with this [`Config`](crate::config::Config) actually guarantees.
177 ///
178 /// §11.1.4.4 marks `SimultaneousInvocationsSupported`, `SimultaneousWritesSupported`,
179 /// `ReadPathsSupported` and `SubscribePathsSupported` **mandatory from cluster revision 6**,
180 /// and this cluster declares revision 6 — so [`CapabilityMinima::default`], which leaves
181 /// them absent, describes a node of an older revision than the one it claims to be.
182 ///
183 /// They are computed here rather than asked of the integrator because the integrator does
184 /// not know them: they are `Config`'s own limits, and a hand-written number beside a
185 /// `Config` is a number that stops being true the first time the `Config` changes. This is
186 /// the same rule as `config::MAX_UDP_PAYLOAD` and
187 /// `operational_credentials::max_nocs_len` — where only the library can compute a bound,
188 /// the library states it.
189 ///
190 /// `SimultaneousInvocationsSupported` and `SimultaneousWritesSupported` take the
191 /// specification's floor of 1: this crate serves one interaction at a time per exchange,
192 /// and §8.8.2.3's `MaxPathsPerInvoke` — a separate attribute — is what bounds the paths
193 /// inside one of them.
194 #[must_use]
195 pub const fn from_config<C: crate::config::Config>() -> Self {
196 // §4.14.2.8's "at least 3 CASE session contexts per fabric" is the floor; what this
197 // node guarantees is its session table divided among its fabrics.
198 let per_fabric = match C::SESSIONS.checked_div(C::FABRICS) {
199 Some(n) => n,
200 // `Config::FABRICS` is at least 5 by `AssertValid`, so this is unreachable; the
201 // match is here because a `const fn` may not unwrap.
202 None => 3,
203 };
204 let case_sessions_per_fabric = if per_fabric < 3 { 3 } else { per_fabric };
205 Self {
206 case_sessions_per_fabric: case_sessions_per_fabric as u16,
207 subscriptions_per_fabric: C::SUBSCRIPTIONS_PER_FABRIC as u16,
208 simultaneous_invocations: Some(1),
209 simultaneous_writes: Some(1),
210 read_paths: Some(C::READ_PATHS as u16),
211 subscribe_paths: Some(C::SUB_PATHS as u16),
212 }
213 }
214}
215
216impl Default for CapabilityMinima {
217 /// §11.1.4.4's fallbacks and floors, every field present.
218 ///
219 /// Revision 6's four fields are *not* left absent, because this cluster declares revision
220 /// 6 and §11.1.4.4 makes them mandatory there — a struct that omits them describes an
221 /// older node than the one sending it, which `TC_IDM_2_3` checks directly.
222 fn default() -> Self {
223 Self {
224 case_sessions_per_fabric: 3,
225 subscriptions_per_fabric: 3,
226 simultaneous_invocations: Some(1),
227 simultaneous_writes: Some(1),
228 read_paths: Some(9),
229 subscribe_paths: Some(3),
230 }
231 }
232}
233
234/// The `F`-quality attributes — everything a product knows about itself at build time.
235///
236/// A `const` record in flash. Every field the specification marks optional is an `Option`,
237/// and `None` means the attribute is not served, which is exactly what an absent optional
238/// attribute must look like: `UNSUPPORTED_ATTRIBUTE`, and absent from `AttributeList`.
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub struct Product<'a> {
241 /// `VendorName` (§11.1.5.2).
242 pub vendor_name: &'a str,
243 /// `VendorID` (§11.1.5.3).
244 pub vendor_id: VendorId,
245 /// `ProductName` (§11.1.5.4).
246 pub product_name: &'a str,
247 /// `ProductID` (§11.1.5.5).
248 pub product_id: u16,
249 /// `HardwareVersion` (§11.1.5.8).
250 pub hardware_version: u16,
251 /// `HardwareVersionString` (§11.1.5.9), 1 to 64 characters.
252 pub hardware_version_string: &'a str,
253 /// `SoftwareVersion` (§11.1.5.10).
254 pub software_version: u32,
255 /// `SoftwareVersionString` (§11.1.5.11), 1 to 64 characters.
256 pub software_version_string: &'a str,
257 /// `UniqueID` (§11.1.5.19) — mandatory from revision 4. "It SHALL NOT be identical to the
258 /// SerialNumber attribute" and "SHALL NOT be printed on the product".
259 pub unique_id: &'a str,
260 /// `CapabilityMinima` (§11.1.5.20).
261 pub capability_minima: CapabilityMinima,
262 /// `MaxPathsPerInvoke` (§11.1.5.23), min 1.
263 pub max_paths_per_invoke: u16,
264 /// `ManufacturingDate` (§11.1.5.12) — `YYYYMMDD` plus up to 8 vendor-defined characters.
265 pub manufacturing_date: Option<&'a str>,
266 /// `PartNumber` (§11.1.5.13).
267 pub part_number: Option<&'a str>,
268 /// `ProductURL` (§11.1.5.14) — "SHALL use the https scheme".
269 pub product_url: Option<&'a str>,
270 /// `ProductLabel` (§11.1.5.15).
271 pub product_label: Option<&'a str>,
272 /// `SerialNumber` (§11.1.5.16).
273 pub serial_number: Option<&'a str>,
274 /// `ProductAppearance` (§11.1.5.21).
275 pub appearance: Option<ProductAppearance>,
276 /// `ConfigurationVersion` (§11.1.5.24), min 1 — revision 6. `N`, but it changes only
277 /// with the node's configuration, so it is given rather than written.
278 pub configuration_version: u32,
279}
280
281impl<'a> Product<'a> {
282 /// A product with only the mandatory fixed attributes.
283 #[must_use]
284 pub const fn new(
285 vendor_name: &'a str,
286 vendor_id: VendorId,
287 product_name: &'a str,
288 product_id: u16,
289 unique_id: &'a str,
290 ) -> Self {
291 Self {
292 vendor_name,
293 vendor_id,
294 product_name,
295 product_id,
296 hardware_version: 0,
297 hardware_version_string: "0",
298 software_version: 0,
299 software_version_string: "0",
300 unique_id,
301 // §11.1.4.4's own fallbacks and floors, all *present*: this cluster declares
302 // revision 6, and fields 2 to 5 are mandatory from revision 6, so leaving them
303 // absent describes a node of an older revision than the one it claims. A device
304 // with real numbers uses `CapabilityMinima::from_config`.
305 capability_minima: CapabilityMinima {
306 case_sessions_per_fabric: 3,
307 subscriptions_per_fabric: 3,
308 simultaneous_invocations: Some(1),
309 simultaneous_writes: Some(1),
310 read_paths: Some(9),
311 subscribe_paths: Some(3),
312 },
313 max_paths_per_invoke: 1,
314 manufacturing_date: None,
315 part_number: None,
316 product_url: None,
317 product_label: None,
318 serial_number: None,
319 appearance: None,
320 configuration_version: 1,
321 }
322 }
323
324 /// The same product with hardware version information.
325 #[must_use]
326 pub const fn with_hardware(mut self, version: u16, string: &'a str) -> Self {
327 self.hardware_version = version;
328 self.hardware_version_string = string;
329 self
330 }
331
332 /// The same product with software version information.
333 #[must_use]
334 pub const fn with_software(mut self, version: u32, string: &'a str) -> Self {
335 self.software_version = version;
336 self.software_version_string = string;
337 self
338 }
339
340 /// The same product with a serial number.
341 #[must_use]
342 pub const fn with_serial_number(mut self, serial_number: &'a str) -> Self {
343 self.serial_number = Some(serial_number);
344 self
345 }
346
347 /// The same product with `CapabilityMinima`.
348 #[must_use]
349 pub const fn with_capability_minima(mut self, minima: CapabilityMinima) -> Self {
350 self.capability_minima = minima;
351 self
352 }
353
354 /// The same product with a `MaxPathsPerInvoke`.
355 #[must_use]
356 pub const fn with_max_paths_per_invoke(mut self, max: u16) -> Self {
357 self.max_paths_per_invoke = max;
358 self
359 }
360}
361
362/// `Location` (§11.1.5.7) — the node's ISO 3166-1 alpha-2 region code.
363///
364/// A cell of its own rather than a field of [`BasicInformation`], because two clusters write
365/// it: a client writing the attribute directly at Administer, and §11.10.7.4's
366/// `SetRegulatoryConfig`, whose `CountryCode` "SHALL be used to set the Location attribute
367/// reflected by the Basic Information Cluster". Sharing one cell is what keeps the two in
368/// agreement.
369///
370/// "The special value XX SHALL indicate that region-agnostic mode is used", which is the
371/// fallback, and "The Location's region code SHALL be interpreted in a case-insensitive
372/// manner".
373#[derive(Debug, Default)]
374pub struct Location(Cell<[u8; 2]>);
375
376impl Location {
377 /// The region-agnostic fallback, `"XX"`.
378 #[must_use]
379 pub const fn region_agnostic() -> Self {
380 Self(Cell::new(*b"XX"))
381 }
382
383 /// A location from a two-character region code.
384 ///
385 /// Returns `None` for anything that is not exactly two characters, which is §11.1.5's
386 /// `constraint 2` — a longer or shorter write is `CONSTRAINT_ERROR`, not a truncation.
387 #[must_use]
388 pub fn new(code: &str) -> Option<Self> {
389 let bytes = code.as_bytes();
390 match bytes {
391 [a, b] if a.is_ascii() && b.is_ascii() => Some(Self(Cell::new([*a, *b]))),
392 _ => None,
393 }
394 }
395
396 /// The current region code.
397 #[must_use]
398 pub fn get(&self) -> [u8; 2] {
399 self.0.get()
400 }
401
402 /// Sets the region code, refusing anything that is not two ASCII characters.
403 pub fn set(&self, code: &str) -> Result<(), Status> {
404 match code.as_bytes() {
405 [a, b] if a.is_ascii() && b.is_ascii() => {
406 self.0.set([*a, *b]);
407 Ok(())
408 }
409 _ => Err(Status::ConstraintError),
410 }
411 }
412
413 fn as_str(&self) -> heapless::String<2> {
414 let bytes = self.0.get();
415 let mut out = heapless::String::new();
416 // Both bytes were checked ASCII on the way in, so this cannot fail.
417 for byte in bytes {
418 let _ = out.push(byte as char);
419 }
420 out
421 }
422}
423
424/// The Basic Information cluster on endpoint 0.
425///
426/// Holds the fixed [`Product`] record by reference and the three mutable attributes in cells,
427/// so the whole cluster is `&self`-usable from the interaction model without a lock.
428#[derive(Debug)]
429pub struct BasicInformation<'a> {
430 /// The `F`-quality attributes.
431 pub product: &'a Product<'a>,
432 /// `Location` (§11.1.5.7), shared with General Commissioning.
433 pub location: &'a Location,
434 node_label: core::cell::RefCell<heapless::String<32>>,
435 local_config_disabled: Cell<Option<bool>>,
436 reachable: Cell<Option<bool>>,
437}
438
439impl<'a> BasicInformation<'a> {
440 /// The cluster over a product and a location.
441 #[must_use]
442 pub fn new(product: &'a Product<'a>, location: &'a Location) -> Self {
443 Self {
444 product,
445 location,
446 node_label: core::cell::RefCell::new(heapless::String::new()),
447 local_config_disabled: Cell::new(None),
448 reachable: Cell::new(None),
449 }
450 }
451
452 /// Serves `LocalConfigDisabled` (§11.1.5.17), starting at `initial`.
453 ///
454 /// Absent by default: the attribute is optional, and a node that does not have an on-node
455 /// user interface has nothing to disable.
456 #[must_use]
457 pub fn with_local_config_disabled(self, initial: bool) -> Self {
458 self.local_config_disabled.set(Some(initial));
459 self
460 }
461
462 /// Serves `Reachable` (§11.1.5.18), starting at `initial`.
463 ///
464 /// "For a native Node this is implicitly True (and its use is optional). Its main use case
465 /// is in the derived Bridged Device Basic Information cluster."
466 #[must_use]
467 pub fn with_reachable(self, initial: bool) -> Self {
468 self.reachable.set(Some(initial));
469 self
470 }
471
472 /// `NodeLabel` (§11.1.5.6).
473 #[must_use]
474 pub fn node_label(&self) -> heapless::String<32> {
475 self.node_label.borrow().clone()
476 }
477
478 /// Sets `NodeLabel`, refusing anything longer than the `max 32` constraint.
479 pub fn set_node_label(&self, label: &str) -> Result<(), Status> {
480 let mut next = heapless::String::new();
481 next.push_str(label).map_err(|_| Status::ConstraintError)?;
482 *self.node_label.borrow_mut() = next;
483 Ok(())
484 }
485
486 /// `Reachable` (§11.1.5.18), if served.
487 #[must_use]
488 pub fn reachable(&self) -> Option<bool> {
489 self.reachable.get()
490 }
491
492 /// Sets `Reachable`, and says whether it changed — which is the trigger for the
493 /// `ReachableChanged` event (§11.1.6.4). Does nothing if the attribute is not served.
494 pub fn set_reachable(&self, reachable: bool) -> bool {
495 match self.reachable.get() {
496 Some(current) if current == reachable => false,
497 Some(_) => {
498 self.reachable.set(Some(reachable));
499 true
500 }
501 None => false,
502 }
503 }
504
505 /// Whether this instance serves `LocalConfigDisabled` (§11.1.5.17).
506 #[must_use]
507 pub fn serves_local_config_disabled(&self) -> bool {
508 self.local_config_disabled.get().is_some()
509 }
510
511 /// Whether this instance serves `Reachable` (§11.1.5.18).
512 #[must_use]
513 pub fn serves_reachable(&self) -> bool {
514 self.reachable.get().is_some()
515 }
516}
517
518// Descriptors for the attributes, in ascending id order — the order `ClusterDescriptor`
519// binary-searches and `AttributeList` is emitted in.
520
521const fn fixed(id: AttributeId) -> AttributeDescriptor {
522 AttributeDescriptor::read_only(id).with_qualities(AttributeQualities::FIXED)
523}
524
525/// `NodeLabel` is `RW VM` — a user-visible name, so Manage rather than Administer.
526const NODE_LABEL_DESC: AttributeDescriptor = AttributeDescriptor::read_write(NODE_LABEL)
527 .with_access(Access::read_write_with(Privilege::View, Privilege::Manage))
528 .with_qualities(AttributeQualities::NON_VOLATILE);
529
530/// `Location` is `RW VA` — it can change radio behaviour, so only an Administrator.
531const LOCATION_DESC: AttributeDescriptor = AttributeDescriptor::read_write(LOCATION)
532 .with_access(Access::read_write_with(
533 Privilege::View,
534 Privilege::Administer,
535 ))
536 .with_qualities(AttributeQualities::NON_VOLATILE);
537
538const LOCAL_CONFIG_DISABLED_DESC: AttributeDescriptor =
539 AttributeDescriptor::read_write(LOCAL_CONFIG_DISABLED)
540 .with_access(Access::read_write_with(Privilege::View, Privilege::Manage))
541 .with_qualities(AttributeQualities::NON_VOLATILE);
542
543/// `StartUp` is mandatory; `ShutDown` and `Leave` are optional but universally useful, and
544/// §7.13's `EventList` has conformance `D` and is not served — so this list feeds access
545/// checks rather than a wire response.
546///
547/// `ReachableChanged` is absent: its conformance is `Reachable`, so it belongs only to a node
548/// that serves that attribute — a bridge, not a device describing itself.
549const EVENTS: &[EventDescriptor] = &[
550 EventDescriptor::new(START_UP).with_priority(EventPriority::Critical),
551 EventDescriptor::new(SHUT_DOWN).with_priority(EventPriority::Critical),
552 EventDescriptor::new(LEAVE),
553];
554
555/// Every attribute §11.1.5 defines, at revision 6.
556pub const MAX_ATTRIBUTES: usize = 24;
557
558/// The attribute list for one node, derived from its [`Product`].
559///
560/// §7.13.3's `AttributeList` is read by every commissioner, and an entry for an attribute
561/// that answers `UNSUPPORTED_ATTRIBUTE` — or a served attribute missing from the list — is a
562/// certification failure. So the list is *computed* from the same record the handler reads
563/// out of, and the two cannot drift.
564///
565/// A fixed array, not a `Vec`: a node has one of these for its whole life, and
566/// [`Attributes::cluster`] borrows from it.
567#[derive(Debug, Clone, Copy)]
568pub struct Attributes {
569 entries: [AttributeDescriptor; MAX_ATTRIBUTES],
570 len: usize,
571}
572
573impl Attributes {
574 /// The attributes a node serving `product` has, in ascending id order.
575 ///
576 /// `local_config_disabled` and `reachable` are the two optional attributes that are not
577 /// decided by [`Product`], because they are state rather than product data — see
578 /// [`BasicInformation::with_local_config_disabled`] and
579 /// [`BasicInformation::with_reachable`].
580 #[must_use]
581 pub fn new(product: &Product<'_>, local_config_disabled: bool, reachable: bool) -> Self {
582 let mut this = Self {
583 entries: [fixed(DATA_MODEL_REVISION_ID); MAX_ATTRIBUTES],
584 len: 0,
585 };
586 // Ascending by id, which is what `ClusterDescriptor` binary-searches and what
587 // `AttributeList` is emitted in.
588 this.push(fixed(DATA_MODEL_REVISION_ID));
589 this.push(fixed(VENDOR_NAME));
590 this.push(fixed(VENDOR_ID));
591 this.push(fixed(PRODUCT_NAME));
592 this.push(fixed(PRODUCT_ID));
593 this.push(NODE_LABEL_DESC);
594 this.push(LOCATION_DESC);
595 this.push(fixed(HARDWARE_VERSION));
596 this.push(fixed(HARDWARE_VERSION_STRING));
597 this.push(fixed(SOFTWARE_VERSION));
598 this.push(fixed(SOFTWARE_VERSION_STRING));
599 this.push_if(
600 product.manufacturing_date.is_some(),
601 fixed(MANUFACTURING_DATE),
602 );
603 this.push_if(product.part_number.is_some(), fixed(PART_NUMBER));
604 this.push_if(product.product_url.is_some(), fixed(PRODUCT_URL));
605 this.push_if(product.product_label.is_some(), fixed(PRODUCT_LABEL));
606 this.push_if(product.serial_number.is_some(), fixed(SERIAL_NUMBER));
607 this.push_if(local_config_disabled, LOCAL_CONFIG_DISABLED_DESC);
608 this.push_if(reachable, AttributeDescriptor::read_only(REACHABLE));
609 this.push(fixed(UNIQUE_ID));
610 this.push(fixed(CAPABILITY_MINIMA));
611 this.push_if(product.appearance.is_some(), fixed(PRODUCT_APPEARANCE));
612 this.push(fixed(SPECIFICATION_VERSION_ID));
613 this.push(fixed(MAX_PATHS_PER_INVOKE));
614 this.push(
615 AttributeDescriptor::read_only(CONFIGURATION_VERSION)
616 .with_qualities(AttributeQualities::NON_VOLATILE),
617 );
618 this
619 }
620
621 /// The attributes this node serves.
622 #[must_use]
623 pub fn as_slice(&self) -> &[AttributeDescriptor] {
624 self.entries.get(..self.len).unwrap_or(&[])
625 }
626
627 /// The cluster descriptor for a node serving these attributes.
628 #[must_use]
629 pub fn cluster(&self) -> ClusterDescriptor<'_> {
630 ClusterDescriptor {
631 id: ID,
632 revision: REVISION,
633 feature_map: 0,
634 attributes: self.as_slice(),
635 accepted_commands: &[],
636 generated_commands: &[],
637 events: EVENTS,
638 }
639 }
640
641 fn push(&mut self, descriptor: AttributeDescriptor) {
642 // `MAX_ATTRIBUTES` is the count of every attribute §11.1.5 defines, so the array
643 // cannot overflow; a silent drop would still be safer than a panic on a device.
644 if let Some(slot) = self.entries.get_mut(self.len) {
645 *slot = descriptor;
646 self.len = self.len.saturating_add(1);
647 }
648 }
649
650 fn push_if(&mut self, condition: bool, descriptor: AttributeDescriptor) {
651 if condition {
652 self.push(descriptor);
653 }
654 }
655}
656
657impl ClusterHandler for BasicInformation<'_> {
658 fn read(
659 &self,
660 resolved: &Resolved<'_>,
661 _ctx: &InteractionContext<'_>,
662 w: &mut TlvWriter<'_>,
663 tag: Tag,
664 ) -> Result<(), Status> {
665 let product = self.product;
666 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
667 match resolved.attribute {
668 DATA_MODEL_REVISION_ID => full(w.unsigned(tag, u64::from(DATA_MODEL_REVISION))),
669 VENDOR_NAME => full(w.utf8(tag, product.vendor_name)),
670 VENDOR_ID => full(w.unsigned(tag, u64::from(product.vendor_id.0))),
671 PRODUCT_NAME => full(w.utf8(tag, product.product_name)),
672 PRODUCT_ID => full(w.unsigned(tag, u64::from(product.product_id))),
673 NODE_LABEL => full(w.utf8(tag, self.node_label().as_str())),
674 LOCATION => full(w.utf8(tag, self.location.as_str().as_str())),
675 HARDWARE_VERSION => full(w.unsigned(tag, u64::from(product.hardware_version))),
676 HARDWARE_VERSION_STRING => full(w.utf8(tag, product.hardware_version_string)),
677 SOFTWARE_VERSION => full(w.unsigned(tag, u64::from(product.software_version))),
678 SOFTWARE_VERSION_STRING => full(w.utf8(tag, product.software_version_string)),
679 MANUFACTURING_DATE => optional_string(w, tag, product.manufacturing_date),
680 PART_NUMBER => optional_string(w, tag, product.part_number),
681 PRODUCT_URL => optional_string(w, tag, product.product_url),
682 PRODUCT_LABEL => optional_string(w, tag, product.product_label),
683 SERIAL_NUMBER => optional_string(w, tag, product.serial_number),
684 LOCAL_CONFIG_DISABLED => {
685 let value = self
686 .local_config_disabled
687 .get()
688 .ok_or(Status::UnsupportedAttribute)?;
689 full(w.bool(tag, value))
690 }
691 REACHABLE => {
692 let value = self.reachable.get().ok_or(Status::UnsupportedAttribute)?;
693 full(w.bool(tag, value))
694 }
695 UNIQUE_ID => full(w.utf8(tag, product.unique_id)),
696 CAPABILITY_MINIMA => write_capability_minima(w, tag, &product.capability_minima),
697 PRODUCT_APPEARANCE => {
698 let appearance = product.appearance.ok_or(Status::UnsupportedAttribute)?;
699 full(w.start_structure(tag))?;
700 full(w.unsigned(Tag::Context(0), appearance.finish as u64))?;
701 match appearance.primary_color {
702 Some(color) => full(w.unsigned(Tag::Context(1), u64::from(color)))?,
703 None => full(w.null(Tag::Context(1)))?,
704 }
705 full(w.end_container())
706 }
707 SPECIFICATION_VERSION_ID => full(w.unsigned(tag, u64::from(SPECIFICATION_VERSION))),
708 MAX_PATHS_PER_INVOKE => full(w.unsigned(tag, u64::from(product.max_paths_per_invoke))),
709 CONFIGURATION_VERSION => {
710 full(w.unsigned(tag, u64::from(product.configuration_version)))
711 }
712 _ => Err(Status::UnsupportedAttribute),
713 }
714 }
715
716 fn write(
717 &self,
718 resolved: &Resolved<'_>,
719 data: &[u8],
720 _op: WriteOp,
721 _ctx: &InteractionContext<'_>,
722 ) -> Result<(), Status> {
723 // The server has already checked access and the Timed quality; what is left is the
724 // cluster's own constraints, which §8.7.3.3 makes `CONSTRAINT_ERROR`.
725 match resolved.attribute {
726 NODE_LABEL => self.set_node_label(read_utf8(data)?),
727 LOCATION => self.location.set(read_utf8(data)?),
728 LOCAL_CONFIG_DISABLED => {
729 if self.local_config_disabled.get().is_none() {
730 return Err(Status::UnsupportedAttribute);
731 }
732 self.local_config_disabled.set(Some(read_bool(data)?));
733 Ok(())
734 }
735 _ => Err(Status::UnsupportedWrite),
736 }
737 }
738}
739
740fn optional_string(w: &mut TlvWriter<'_>, tag: Tag, value: Option<&str>) -> Result<(), Status> {
741 let value = value.ok_or(Status::UnsupportedAttribute)?;
742 w.utf8(tag, value).map_err(|_| Status::ResourceExhausted)
743}
744
745fn write_capability_minima(
746 w: &mut TlvWriter<'_>,
747 tag: Tag,
748 minima: &CapabilityMinima,
749) -> Result<(), Status> {
750 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
751 full(w.start_structure(tag))?;
752 full(w.unsigned(Tag::Context(0), u64::from(minima.case_sessions_per_fabric)))?;
753 full(w.unsigned(Tag::Context(1), u64::from(minima.subscriptions_per_fabric)))?;
754 // Revision 6's four fields, each written only when present — an absent optional field
755 // is absent from the structure, not null.
756 for (field, value) in [
757 (2, minima.simultaneous_invocations),
758 (3, minima.simultaneous_writes),
759 (4, minima.read_paths),
760 (5, minima.subscribe_paths),
761 ] {
762 if let Some(value) = value {
763 full(w.unsigned(Tag::Context(field), u64::from(value)))?;
764 }
765 }
766 full(w.end_container())
767}
768
769/// Decodes one TLV UTF-8 string element — what §10.6.4.3 hands a cluster as `Data`.
770///
771/// `Data` is the `AttributeDataIB`'s context-2 member, so it arrives *tagged*: it is a
772/// fragment of a structure, not a TLV document, and reading it as one would reject exactly
773/// the bytes that are correct.
774fn read_utf8(data: &[u8]) -> Result<&str, Status> {
775 let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
776 match reader.next_element() {
777 Ok(Some(Element {
778 value: Value::Utf8(text),
779 ..
780 })) => Ok(text),
781 Ok(Some(_)) => Err(Status::InvalidDataType),
782 _ => Err(Status::InvalidDataType),
783 }
784}
785
786fn read_bool(data: &[u8]) -> Result<bool, Status> {
787 let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
788 match reader.next_element() {
789 Ok(Some(Element {
790 value: Value::Bool(value),
791 ..
792 })) => Ok(value),
793 Ok(Some(_)) => Err(Status::InvalidDataType),
794 _ => Err(Status::InvalidDataType),
795 }
796}
797
798impl Cluster for BasicInformation<'_> {
799 const ID: ClusterId = ID;
800}