Skip to main content

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 actually guarantees, taken from the tables that will answer for them.
177    ///
178    /// §11.1.4.4 says each field "SHALL indicate the **actual**" number the node supports, so
179    /// every one of them has exactly one honest source: the table. `S` is the session table and
180    /// `B` the subscription table, both of which publish their real capacity through
181    /// [`Capacity`](crate::config::Capacity); `read_paths` is
182    /// [`Config::READ_PATHS`](crate::config::Config::READ_PATHS), the one figure here that is a
183    /// promise about work rather than storage.
184    ///
185    /// ```
186    /// # #[cfg(feature = "rustcrypto")] fn main() {
187    /// use matter_kit::clusters::basic_information::CapabilityMinima;
188    /// use matter_kit::{DefaultConfig, im::SubscriptionTable, session::SessionTable};
189    ///
190    /// type Sessions = SessionTable<DefaultConfig, 16>;
191    /// type Subs = SubscriptionTable<DefaultConfig>;
192    /// let minima = CapabilityMinima::from_tables::<DefaultConfig, Sessions, Subs>();
193    /// assert_eq!(minima.case_sessions_per_fabric, 3); // 16 sessions over 5 fabrics
194    /// # }
195    /// # #[cfg(not(feature = "rustcrypto"))] fn main() {}
196    /// ```
197    ///
198    /// There is deliberately no `from_config`. A `Config` cannot size a table, so a figure
199    /// derived from one describes whatever the integrator wrote next to it — and this attribute
200    /// is read during certification.
201    ///
202    /// `SimultaneousInvocationsSupported` and `SimultaneousWritesSupported` take the
203    /// specification's floor of 1: this crate serves one interaction at a time per exchange,
204    /// and §8.8.2.3's `MaxPathsPerInvoke` — a separate attribute — is what bounds the paths
205    /// inside one of them.
206    #[must_use]
207    pub const fn from_tables<C, S, B>() -> Self
208    where
209        C: crate::config::Config,
210        S: crate::config::Capacity,
211        B: crate::config::SubscriptionCapacity,
212    {
213        Self {
214            case_sessions_per_fabric: saturate(S::PER_FABRIC),
215            subscriptions_per_fabric: saturate(B::PER_FABRIC),
216            simultaneous_invocations: Some(1),
217            simultaneous_writes: Some(1),
218            read_paths: Some(saturate(C::READ_PATHS)),
219            subscribe_paths: Some(saturate(B::PATHS)),
220        }
221    }
222}
223
224/// `usize` to `uint16`, clamped rather than wrapped.
225///
226/// §11.1.4.4 caps every field at 10000, and a node that somehow held more would otherwise
227/// report the low sixteen bits of it — a smaller number than the truth, which is the one
228/// direction this attribute must never be wrong in.
229#[expect(
230    clippy::cast_possible_truncation,
231    reason = "the branch above is the truncation check — §11.1.4.4 caps every field at 10000"
232)]
233const fn saturate(n: usize) -> u16 {
234    if n > 10_000 { 10_000 } else { n as u16 }
235}
236
237impl Default for CapabilityMinima {
238    /// §11.1.4.4's fallbacks and floors, every field present.
239    ///
240    /// Revision 6's four fields are *not* left absent, because this cluster declares revision
241    /// 6 and §11.1.4.4 makes them mandatory there — a struct that omits them describes an
242    /// older node than the one sending it, which `TC_IDM_2_3` checks directly.
243    fn default() -> Self {
244        Self {
245            case_sessions_per_fabric: 3,
246            subscriptions_per_fabric: 3,
247            simultaneous_invocations: Some(1),
248            simultaneous_writes: Some(1),
249            read_paths: Some(9),
250            subscribe_paths: Some(3),
251        }
252    }
253}
254
255/// The `F`-quality attributes — everything a product knows about itself at build time.
256///
257/// A `const` record in flash. Every field the specification marks optional is an `Option`,
258/// and `None` means the attribute is not served, which is exactly what an absent optional
259/// attribute must look like: `UNSUPPORTED_ATTRIBUTE`, and absent from `AttributeList`.
260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261pub struct Product<'a> {
262    /// `VendorName` (§11.1.5.2).
263    pub vendor_name: &'a str,
264    /// `VendorID` (§11.1.5.3).
265    pub vendor_id: VendorId,
266    /// `ProductName` (§11.1.5.4).
267    pub product_name: &'a str,
268    /// `ProductID` (§11.1.5.5).
269    pub product_id: u16,
270    /// `HardwareVersion` (§11.1.5.8).
271    pub hardware_version: u16,
272    /// `HardwareVersionString` (§11.1.5.9), 1 to 64 characters.
273    pub hardware_version_string: &'a str,
274    /// `SoftwareVersion` (§11.1.5.10).
275    pub software_version: u32,
276    /// `SoftwareVersionString` (§11.1.5.11), 1 to 64 characters.
277    pub software_version_string: &'a str,
278    /// `UniqueID` (§11.1.5.19) — mandatory from revision 4. "It SHALL NOT be identical to the
279    /// SerialNumber attribute" and "SHALL NOT be printed on the product".
280    pub unique_id: &'a str,
281    /// `CapabilityMinima` (§11.1.5.20).
282    pub capability_minima: CapabilityMinima,
283    /// `MaxPathsPerInvoke` (§11.1.5.23), min 1.
284    pub max_paths_per_invoke: u16,
285    /// `ManufacturingDate` (§11.1.5.12) — `YYYYMMDD` plus up to 8 vendor-defined characters.
286    pub manufacturing_date: Option<&'a str>,
287    /// `PartNumber` (§11.1.5.13).
288    pub part_number: Option<&'a str>,
289    /// `ProductURL` (§11.1.5.14) — "SHALL use the https scheme".
290    pub product_url: Option<&'a str>,
291    /// `ProductLabel` (§11.1.5.15).
292    pub product_label: Option<&'a str>,
293    /// `SerialNumber` (§11.1.5.16).
294    pub serial_number: Option<&'a str>,
295    /// `ProductAppearance` (§11.1.5.21).
296    pub appearance: Option<ProductAppearance>,
297    /// `ConfigurationVersion` (§11.1.5.24), min 1 — revision 6. `N`, but it changes only
298    /// with the node's configuration, so it is given rather than written.
299    pub configuration_version: u32,
300}
301
302impl<'a> Product<'a> {
303    /// A product with only the mandatory fixed attributes.
304    #[must_use]
305    pub const fn new(
306        vendor_name: &'a str,
307        vendor_id: VendorId,
308        product_name: &'a str,
309        product_id: u16,
310        unique_id: &'a str,
311    ) -> Self {
312        Self {
313            vendor_name,
314            vendor_id,
315            product_name,
316            product_id,
317            hardware_version: 0,
318            hardware_version_string: "0",
319            software_version: 0,
320            software_version_string: "0",
321            unique_id,
322            // §11.1.4.4's own fallbacks and floors, all *present*: this cluster declares
323            // revision 6, and fields 2 to 5 are mandatory from revision 6, so leaving them
324            // absent describes a node of an older revision than the one it claims. A device
325            // with real numbers uses `CapabilityMinima::from_config`.
326            capability_minima: CapabilityMinima {
327                case_sessions_per_fabric: 3,
328                subscriptions_per_fabric: 3,
329                simultaneous_invocations: Some(1),
330                simultaneous_writes: Some(1),
331                read_paths: Some(9),
332                subscribe_paths: Some(3),
333            },
334            max_paths_per_invoke: 1,
335            manufacturing_date: None,
336            part_number: None,
337            product_url: None,
338            product_label: None,
339            serial_number: None,
340            appearance: None,
341            configuration_version: 1,
342        }
343    }
344
345    /// The same product with hardware version information.
346    #[must_use]
347    pub const fn with_hardware(mut self, version: u16, string: &'a str) -> Self {
348        self.hardware_version = version;
349        self.hardware_version_string = string;
350        self
351    }
352
353    /// The same product with software version information.
354    #[must_use]
355    pub const fn with_software(mut self, version: u32, string: &'a str) -> Self {
356        self.software_version = version;
357        self.software_version_string = string;
358        self
359    }
360
361    /// The same product with a serial number.
362    #[must_use]
363    pub const fn with_serial_number(mut self, serial_number: &'a str) -> Self {
364        self.serial_number = Some(serial_number);
365        self
366    }
367
368    /// The same product with `CapabilityMinima`.
369    #[must_use]
370    pub const fn with_capability_minima(mut self, minima: CapabilityMinima) -> Self {
371        self.capability_minima = minima;
372        self
373    }
374
375    /// The same product with a `MaxPathsPerInvoke`.
376    #[must_use]
377    pub const fn with_max_paths_per_invoke(mut self, max: u16) -> Self {
378        self.max_paths_per_invoke = max;
379        self
380    }
381}
382
383/// `Location` (§11.1.5.7) — the node's ISO 3166-1 alpha-2 region code.
384///
385/// A cell of its own rather than a field of [`BasicInformation`], because two clusters write
386/// it: a client writing the attribute directly at Administer, and §11.10.7.4's
387/// `SetRegulatoryConfig`, whose `CountryCode` "SHALL be used to set the Location attribute
388/// reflected by the Basic Information Cluster". Sharing one cell is what keeps the two in
389/// agreement.
390///
391/// "The special value XX SHALL indicate that region-agnostic mode is used", which is the
392/// fallback, and "The Location's region code SHALL be interpreted in a case-insensitive
393/// manner".
394#[derive(Debug, Default)]
395pub struct Location(Cell<[u8; 2]>);
396
397impl Location {
398    /// The region-agnostic fallback, `"XX"`.
399    #[must_use]
400    pub const fn region_agnostic() -> Self {
401        Self(Cell::new(*b"XX"))
402    }
403
404    /// A location from a two-character region code.
405    ///
406    /// Returns `None` for anything that is not exactly two characters, which is §11.1.5's
407    /// `constraint 2` — a longer or shorter write is `CONSTRAINT_ERROR`, not a truncation.
408    #[must_use]
409    pub fn new(code: &str) -> Option<Self> {
410        let bytes = code.as_bytes();
411        match bytes {
412            [a, b] if a.is_ascii() && b.is_ascii() => Some(Self(Cell::new([*a, *b]))),
413            _ => None,
414        }
415    }
416
417    /// The current region code.
418    #[must_use]
419    pub fn get(&self) -> [u8; 2] {
420        self.0.get()
421    }
422
423    /// Sets the region code, refusing anything that is not two ASCII characters.
424    pub fn set(&self, code: &str) -> Result<(), Status> {
425        match code.as_bytes() {
426            [a, b] if a.is_ascii() && b.is_ascii() => {
427                self.0.set([*a, *b]);
428                Ok(())
429            }
430            _ => Err(Status::ConstraintError),
431        }
432    }
433
434    fn as_str(&self) -> heapless::String<2> {
435        let bytes = self.0.get();
436        let mut out = heapless::String::new();
437        // Both bytes were checked ASCII on the way in, so this cannot fail.
438        for byte in bytes {
439            let _ = out.push(byte as char);
440        }
441        out
442    }
443}
444
445/// The Basic Information cluster on endpoint 0.
446///
447/// Holds the fixed [`Product`] record by reference and the three mutable attributes in cells,
448/// so the whole cluster is `&self`-usable from the interaction model without a lock.
449#[derive(Debug)]
450pub struct BasicInformation<'a> {
451    /// The `F`-quality attributes.
452    pub product: &'a Product<'a>,
453    /// `Location` (§11.1.5.7), shared with General Commissioning.
454    pub location: &'a Location,
455    node_label: core::cell::RefCell<heapless::String<32>>,
456    local_config_disabled: Cell<Option<bool>>,
457    reachable: Cell<Option<bool>>,
458}
459
460impl<'a> BasicInformation<'a> {
461    /// The cluster over a product and a location.
462    #[must_use]
463    pub fn new(product: &'a Product<'a>, location: &'a Location) -> Self {
464        Self {
465            product,
466            location,
467            node_label: core::cell::RefCell::new(heapless::String::new()),
468            local_config_disabled: Cell::new(None),
469            reachable: Cell::new(None),
470        }
471    }
472
473    /// Serves `LocalConfigDisabled` (§11.1.5.17), starting at `initial`.
474    ///
475    /// Absent by default: the attribute is optional, and a node that does not have an on-node
476    /// user interface has nothing to disable.
477    #[must_use]
478    pub fn with_local_config_disabled(self, initial: bool) -> Self {
479        self.local_config_disabled.set(Some(initial));
480        self
481    }
482
483    /// Serves `Reachable` (§11.1.5.18), starting at `initial`.
484    ///
485    /// "For a native Node this is implicitly True (and its use is optional). Its main use case
486    /// is in the derived Bridged Device Basic Information cluster."
487    #[must_use]
488    pub fn with_reachable(self, initial: bool) -> Self {
489        self.reachable.set(Some(initial));
490        self
491    }
492
493    /// `NodeLabel` (§11.1.5.6).
494    #[must_use]
495    pub fn node_label(&self) -> heapless::String<32> {
496        self.node_label.borrow().clone()
497    }
498
499    /// Sets `NodeLabel`, refusing anything longer than the `max 32` constraint.
500    pub fn set_node_label(&self, label: &str) -> Result<(), Status> {
501        let mut next = heapless::String::new();
502        next.push_str(label).map_err(|_| Status::ConstraintError)?;
503        *self.node_label.borrow_mut() = next;
504        Ok(())
505    }
506
507    /// `Reachable` (§11.1.5.18), if served.
508    #[must_use]
509    pub fn reachable(&self) -> Option<bool> {
510        self.reachable.get()
511    }
512
513    /// Sets `Reachable`, and says whether it changed — which is the trigger for the
514    /// `ReachableChanged` event (§11.1.6.4). Does nothing if the attribute is not served.
515    pub fn set_reachable(&self, reachable: bool) -> bool {
516        match self.reachable.get() {
517            Some(current) if current == reachable => false,
518            Some(_) => {
519                self.reachable.set(Some(reachable));
520                true
521            }
522            None => false,
523        }
524    }
525
526    /// Whether this instance serves `LocalConfigDisabled` (§11.1.5.17).
527    #[must_use]
528    pub fn serves_local_config_disabled(&self) -> bool {
529        self.local_config_disabled.get().is_some()
530    }
531
532    /// Whether this instance serves `Reachable` (§11.1.5.18).
533    #[must_use]
534    pub fn serves_reachable(&self) -> bool {
535        self.reachable.get().is_some()
536    }
537}
538
539// Descriptors for the attributes, in ascending id order — the order `ClusterDescriptor`
540// binary-searches and `AttributeList` is emitted in.
541
542const fn fixed(id: AttributeId) -> AttributeDescriptor {
543    AttributeDescriptor::read_only(id).with_qualities(AttributeQualities::FIXED)
544}
545
546/// `NodeLabel` is `RW VM` — a user-visible name, so Manage rather than Administer.
547const NODE_LABEL_DESC: AttributeDescriptor = AttributeDescriptor::read_write(NODE_LABEL)
548    .with_access(Access::read_write_with(Privilege::View, Privilege::Manage))
549    .with_qualities(AttributeQualities::NON_VOLATILE);
550
551/// `Location` is `RW VA` — it can change radio behaviour, so only an Administrator.
552const LOCATION_DESC: AttributeDescriptor = AttributeDescriptor::read_write(LOCATION)
553    .with_access(Access::read_write_with(
554        Privilege::View,
555        Privilege::Administer,
556    ))
557    .with_qualities(AttributeQualities::NON_VOLATILE);
558
559const LOCAL_CONFIG_DISABLED_DESC: AttributeDescriptor =
560    AttributeDescriptor::read_write(LOCAL_CONFIG_DISABLED)
561        .with_access(Access::read_write_with(Privilege::View, Privilege::Manage))
562        .with_qualities(AttributeQualities::NON_VOLATILE);
563
564/// `StartUp` is mandatory; `ShutDown` and `Leave` are optional but universally useful, and
565/// §7.13's `EventList` has conformance `D` and is not served — so this list feeds access
566/// checks rather than a wire response.
567///
568/// `ReachableChanged` is absent: its conformance is `Reachable`, so it belongs only to a node
569/// that serves that attribute — a bridge, not a device describing itself.
570const EVENTS: &[EventDescriptor] = &[
571    EventDescriptor::new(START_UP).with_priority(EventPriority::Critical),
572    EventDescriptor::new(SHUT_DOWN).with_priority(EventPriority::Critical),
573    EventDescriptor::new(LEAVE),
574];
575
576/// Every attribute §11.1.5 defines, at revision 6.
577pub const MAX_ATTRIBUTES: usize = 24;
578
579/// The attribute list for one node, derived from its [`Product`].
580///
581/// §7.13.3's `AttributeList` is read by every commissioner, and an entry for an attribute
582/// that answers `UNSUPPORTED_ATTRIBUTE` — or a served attribute missing from the list — is a
583/// certification failure. So the list is *computed* from the same record the handler reads
584/// out of, and the two cannot drift.
585///
586/// A fixed array, not a `Vec`: a node has one of these for its whole life, and
587/// [`Attributes::cluster`] borrows from it.
588#[derive(Debug, Clone, Copy)]
589pub struct Attributes {
590    entries: [AttributeDescriptor; MAX_ATTRIBUTES],
591    len: usize,
592}
593
594impl Attributes {
595    /// The attributes a node serving `product` has, in ascending id order.
596    ///
597    /// `local_config_disabled` and `reachable` are the two optional attributes that are not
598    /// decided by [`Product`], because they are state rather than product data — see
599    /// [`BasicInformation::with_local_config_disabled`] and
600    /// [`BasicInformation::with_reachable`].
601    #[must_use]
602    pub fn new(product: &Product<'_>, local_config_disabled: bool, reachable: bool) -> Self {
603        let mut this = Self {
604            entries: [fixed(DATA_MODEL_REVISION_ID); MAX_ATTRIBUTES],
605            len: 0,
606        };
607        // Ascending by id, which is what `ClusterDescriptor` binary-searches and what
608        // `AttributeList` is emitted in.
609        this.push(fixed(DATA_MODEL_REVISION_ID));
610        this.push(fixed(VENDOR_NAME));
611        this.push(fixed(VENDOR_ID));
612        this.push(fixed(PRODUCT_NAME));
613        this.push(fixed(PRODUCT_ID));
614        this.push(NODE_LABEL_DESC);
615        this.push(LOCATION_DESC);
616        this.push(fixed(HARDWARE_VERSION));
617        this.push(fixed(HARDWARE_VERSION_STRING));
618        this.push(fixed(SOFTWARE_VERSION));
619        this.push(fixed(SOFTWARE_VERSION_STRING));
620        this.push_if(
621            product.manufacturing_date.is_some(),
622            fixed(MANUFACTURING_DATE),
623        );
624        this.push_if(product.part_number.is_some(), fixed(PART_NUMBER));
625        this.push_if(product.product_url.is_some(), fixed(PRODUCT_URL));
626        this.push_if(product.product_label.is_some(), fixed(PRODUCT_LABEL));
627        this.push_if(product.serial_number.is_some(), fixed(SERIAL_NUMBER));
628        this.push_if(local_config_disabled, LOCAL_CONFIG_DISABLED_DESC);
629        this.push_if(reachable, AttributeDescriptor::read_only(REACHABLE));
630        this.push(fixed(UNIQUE_ID));
631        this.push(fixed(CAPABILITY_MINIMA));
632        this.push_if(product.appearance.is_some(), fixed(PRODUCT_APPEARANCE));
633        this.push(fixed(SPECIFICATION_VERSION_ID));
634        this.push(fixed(MAX_PATHS_PER_INVOKE));
635        this.push(
636            AttributeDescriptor::read_only(CONFIGURATION_VERSION)
637                .with_qualities(AttributeQualities::NON_VOLATILE),
638        );
639        this
640    }
641
642    /// The attributes this node serves.
643    #[must_use]
644    pub fn as_slice(&self) -> &[AttributeDescriptor] {
645        self.entries.get(..self.len).unwrap_or(&[])
646    }
647
648    /// The cluster descriptor for a node serving these attributes.
649    #[must_use]
650    pub fn cluster(&self) -> ClusterDescriptor<'_> {
651        ClusterDescriptor {
652            id: ID,
653            revision: REVISION,
654            feature_map: 0,
655            attributes: self.as_slice(),
656            accepted_commands: &[],
657            generated_commands: &[],
658            events: EVENTS,
659        }
660    }
661
662    fn push(&mut self, descriptor: AttributeDescriptor) {
663        // `MAX_ATTRIBUTES` is the count of every attribute §11.1.5 defines, so the array
664        // cannot overflow; a silent drop would still be safer than a panic on a device.
665        if let Some(slot) = self.entries.get_mut(self.len) {
666            *slot = descriptor;
667            self.len = self.len.saturating_add(1);
668        }
669    }
670
671    fn push_if(&mut self, condition: bool, descriptor: AttributeDescriptor) {
672        if condition {
673            self.push(descriptor);
674        }
675    }
676}
677
678impl ClusterHandler for BasicInformation<'_> {
679    fn read(
680        &self,
681        resolved: &Resolved<'_>,
682        _ctx: &InteractionContext<'_>,
683        w: &mut TlvWriter<'_>,
684        tag: Tag,
685    ) -> Result<(), Status> {
686        let product = self.product;
687        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
688        match resolved.attribute {
689            DATA_MODEL_REVISION_ID => full(w.unsigned(tag, u64::from(DATA_MODEL_REVISION))),
690            VENDOR_NAME => full(w.utf8(tag, product.vendor_name)),
691            VENDOR_ID => full(w.unsigned(tag, u64::from(product.vendor_id.0))),
692            PRODUCT_NAME => full(w.utf8(tag, product.product_name)),
693            PRODUCT_ID => full(w.unsigned(tag, u64::from(product.product_id))),
694            NODE_LABEL => full(w.utf8(tag, self.node_label().as_str())),
695            LOCATION => full(w.utf8(tag, self.location.as_str().as_str())),
696            HARDWARE_VERSION => full(w.unsigned(tag, u64::from(product.hardware_version))),
697            HARDWARE_VERSION_STRING => full(w.utf8(tag, product.hardware_version_string)),
698            SOFTWARE_VERSION => full(w.unsigned(tag, u64::from(product.software_version))),
699            SOFTWARE_VERSION_STRING => full(w.utf8(tag, product.software_version_string)),
700            MANUFACTURING_DATE => optional_string(w, tag, product.manufacturing_date),
701            PART_NUMBER => optional_string(w, tag, product.part_number),
702            PRODUCT_URL => optional_string(w, tag, product.product_url),
703            PRODUCT_LABEL => optional_string(w, tag, product.product_label),
704            SERIAL_NUMBER => optional_string(w, tag, product.serial_number),
705            LOCAL_CONFIG_DISABLED => {
706                let value = self
707                    .local_config_disabled
708                    .get()
709                    .ok_or(Status::UnsupportedAttribute)?;
710                full(w.bool(tag, value))
711            }
712            REACHABLE => {
713                let value = self.reachable.get().ok_or(Status::UnsupportedAttribute)?;
714                full(w.bool(tag, value))
715            }
716            UNIQUE_ID => full(w.utf8(tag, product.unique_id)),
717            CAPABILITY_MINIMA => write_capability_minima(w, tag, &product.capability_minima),
718            PRODUCT_APPEARANCE => {
719                let appearance = product.appearance.ok_or(Status::UnsupportedAttribute)?;
720                full(w.start_structure(tag))?;
721                full(w.unsigned(Tag::Context(0), appearance.finish as u64))?;
722                match appearance.primary_color {
723                    Some(color) => full(w.unsigned(Tag::Context(1), u64::from(color)))?,
724                    None => full(w.null(Tag::Context(1)))?,
725                }
726                full(w.end_container())
727            }
728            SPECIFICATION_VERSION_ID => full(w.unsigned(tag, u64::from(SPECIFICATION_VERSION))),
729            MAX_PATHS_PER_INVOKE => full(w.unsigned(tag, u64::from(product.max_paths_per_invoke))),
730            CONFIGURATION_VERSION => {
731                full(w.unsigned(tag, u64::from(product.configuration_version)))
732            }
733            _ => Err(Status::UnsupportedAttribute),
734        }
735    }
736
737    fn write(
738        &self,
739        resolved: &Resolved<'_>,
740        data: &[u8],
741        _op: WriteOp,
742        _ctx: &InteractionContext<'_>,
743    ) -> Result<(), Status> {
744        // The server has already checked access and the Timed quality; what is left is the
745        // cluster's own constraints, which §8.7.3.3 makes `CONSTRAINT_ERROR`.
746        match resolved.attribute {
747            NODE_LABEL => self.set_node_label(read_utf8(data)?),
748            LOCATION => self.location.set(read_utf8(data)?),
749            LOCAL_CONFIG_DISABLED => {
750                if self.local_config_disabled.get().is_none() {
751                    return Err(Status::UnsupportedAttribute);
752                }
753                self.local_config_disabled.set(Some(read_bool(data)?));
754                Ok(())
755            }
756            _ => Err(Status::UnsupportedWrite),
757        }
758    }
759}
760
761fn optional_string(w: &mut TlvWriter<'_>, tag: Tag, value: Option<&str>) -> Result<(), Status> {
762    let value = value.ok_or(Status::UnsupportedAttribute)?;
763    w.utf8(tag, value).map_err(|_| Status::ResourceExhausted)
764}
765
766fn write_capability_minima(
767    w: &mut TlvWriter<'_>,
768    tag: Tag,
769    minima: &CapabilityMinima,
770) -> Result<(), Status> {
771    let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
772    full(w.start_structure(tag))?;
773    full(w.unsigned(Tag::Context(0), u64::from(minima.case_sessions_per_fabric)))?;
774    full(w.unsigned(Tag::Context(1), u64::from(minima.subscriptions_per_fabric)))?;
775    // Revision 6's four fields, each written only when present — an absent optional field
776    // is absent from the structure, not null.
777    for (field, value) in [
778        (2, minima.simultaneous_invocations),
779        (3, minima.simultaneous_writes),
780        (4, minima.read_paths),
781        (5, minima.subscribe_paths),
782    ] {
783        if let Some(value) = value {
784            full(w.unsigned(Tag::Context(field), u64::from(value)))?;
785        }
786    }
787    full(w.end_container())
788}
789
790/// Decodes one TLV UTF-8 string element — what §10.6.4.3 hands a cluster as `Data`.
791///
792/// `Data` is the `AttributeDataIB`'s context-2 member, so it arrives *tagged*: it is a
793/// fragment of a structure, not a TLV document, and reading it as one would reject exactly
794/// the bytes that are correct.
795fn read_utf8(data: &[u8]) -> Result<&str, Status> {
796    let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
797    match reader.next_element() {
798        Ok(Some(Element {
799            value: Value::Utf8(text),
800            ..
801        })) => Ok(text),
802        Ok(Some(_)) => Err(Status::InvalidDataType),
803        _ => Err(Status::InvalidDataType),
804    }
805}
806
807fn read_bool(data: &[u8]) -> Result<bool, Status> {
808    let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
809    match reader.next_element() {
810        Ok(Some(Element {
811            value: Value::Bool(value),
812            ..
813        })) => Ok(value),
814        Ok(Some(_)) => Err(Status::InvalidDataType),
815        _ => Err(Status::InvalidDataType),
816    }
817}
818
819impl Cluster for BasicInformation<'_> {
820    const ID: ClusterId = ID;
821}