Skip to main content

rs_matter_node_core/
basic_info.rs

1/*
2 *
3 *    Copyright (c) 2026 Project CHIP Authors
4 *
5 *    Licensed under the Apache License, Version 2.0 (the "License");
6 *    you may not use this file except in compliance with the License.
7 *    You may obtain a copy of the License at
8 *
9 *        http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *    Unless required by applicable law or agreed to in writing, software
12 *    distributed under the License is distributed on an "AS IS" BASIS,
13 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *    See the License for the specific language governing permissions and
15 *    limitations under the License.
16 */
17
18//! The basic information of the node: its configuration, which does not
19//! change at runtime, and its settings, which administrators change and which
20//! the node persists.
21
22use core::str::FromStr;
23
24use crate::dm::{AttrId, ClusterId};
25use crate::error::Error;
26use crate::im::SubscribeReq;
27use crate::persist::{KvBlobStore, KvBlobStoreAccess, Persist, BASIC_INFO_KEY};
28use crate::session::CASE_SESSIONS_PER_FABRIC;
29use crate::tlv::{FromTLV, Nullable, TLVElement, ToTLV};
30use crate::utils::bitflags::bitflags;
31use crate::utils::init::{init, Init};
32use crate::utils::storage::String;
33
34/// The ID of the Basic Information cluster
35pub const BASIC_INFO_CLUSTER_ID: ClusterId = 0x0028;
36/// The ID of the `ConfigurationVersion` attribute of the Basic Information cluster
37pub const CONFIGURATION_VERSION_ATTR_ID: AttrId = 0x0018;
38
39/// The default Matter App Clusters specification version
40///
41/// Currently set to V1.6.0.0.
42pub const DEFAULT_MATTER_SPEC_VERSION: u32 = 0x01060000;
43
44/// The default Matter Data Model revision
45///
46/// Currently set to V21, which was released with Matter Core spec V1.6
47pub const DEFAULT_DATA_MODEL_REVISION: u16 = 21;
48
49/// The default maximum number of paths that can be included in an Invoke request
50///
51/// Set to 1, the minimum. A node that accepts more has to support the
52/// General Diagnostics `DMTEST` feature, and the responses to a batch can
53/// then outgrow one message, which needs chunked Invoke responses. rs-matter
54/// has neither yet.
55pub const DEFAULT_MAX_PATHS_PER_INVOKE: u16 = 1;
56
57/// The default for [`BasicInfoConfig::min_subscription_max_interval_secs`].
58pub const DEFAULT_MIN_SUBSCRIPTION_MAX_INTERVAL_SECS: u16 = 40;
59
60/// The default for [`BasicInfoConfig::max_subscription_max_interval_secs`].
61pub const DEFAULT_MAX_SUBSCRIPTION_MAX_INTERVAL_SECS: u16 = 120;
62
63bitflags! {
64    #[repr(transparent)]
65    #[derive(Default)]
66    #[cfg_attr(not(feature = "defmt"), derive(Debug, Copy, Clone, Eq, PartialEq, Hash))]
67    pub struct PairingHintFlags: u32 {
68        /// Power Cycle False The Device will automatically enter Commissioning Mode upon
69        /// power cycle (unplug/replug, remove/re-insert batteries).
70        /// This bit SHALL be set to 1 for devices using Standard Commissioning Flow,
71        /// and set to 0 otherwise.
72        const POWER_CYCLE = 0x0000_0001;
73        /// This SHALL be set to 1 for devices requiring Custom Commissioning
74        /// Flow before they can be available for Commissioning by any Commissioner.
75        /// For such a flow, the user SHOULD be sent to the URL specified in the
76        /// CommissioningCustomFlowUrl of the DeviceModel schema entry indexed by the
77        /// Vendor ID and Product ID (e.g., as found in the announcement) in the
78        /// Distributed Compliance Ledger.
79        const DEV_MANUFACTURER_URL = 0x0000_0002;
80        /// The Device has been commissioned. Any Administrator that commissioned the
81        /// device provides a user interface that may be used to put the device
82        /// into Commissioning Mode.
83        const ADMINISTRATOR = 0x0000_0004;
84        /// The settings menu on the Device provides instructions to put it
85        /// into Commissioning Mode.
86        const SETTINGS_MENU = 0x0000_0008;
87        /// The PI key/value pair describes a custom way to put the Device into
88        /// Commissioning Mode. This Custom Instruction option is NOT recommended
89        /// for use by a Device that does not have knowledge of the user's language preference.
90        const CUSTOM_INSTRUCTION = 0x0000_0010;
91        /// The Device Manual provides special instructions to put the Device
92        /// into Commissioning Mode (see "UserManualUrl" in the Core Spec).
93        /// This is a catchall option to capture user interactions that are not codified by
94        /// other options in this flags type.
95        const DEVICE_MANUAL = 0x0000_0020;
96        /// The Device will enter Commissioning Mode when reset button is pressed.
97        const PRESS_RESET_BUTTON = 0x0000_0040;
98        /// The Device will enter Commissioning Mode when reset button is pressed when applying power to it.
99        const PRESS_RESET_BUTTON_WITH_POWER = 0x0000_0080;
100        /// The Device will enter Commissioning Mode when reset button is pressed for N seconds.
101        /// The exact value of N SHALL be made available via PI key.
102        const PRESS_RESET_BUTTON_FOR_N_SECONDS = 0x0000_0100;
103        /// The Device will enter Commissioning Mode when reset button is pressed until associated light blinks.
104        /// Information on color of light MAY be made available via PI key.
105        const PRESS_RESET_BUTTON_UNTIL_LIGHT_BLINKS = 0x0000_0200;
106        /// The Device will enter Commissioning Mode when reset button is pressed for N seconds
107        /// when applying power to it. The exact value of N SHALL be made available via PI key.
108        const PRESS_RESET_BUTTON_FOR_N_SECONDS_WITH_POWER = 0x0000_0400;
109        /// The Device will enter Commissioning Mode when reset button is pressed until associated
110        /// light blinks when applying power to the Device. Information on color of light MAY be
111        /// made available via PI key.
112        const PRESS_RESET_BUTTON_UNTIL_LIGHT_BLINKS_WITH_POWER = 0x0000_0800;
113        /// The Device will enter Commissioning Mode when reset button is pressed N times
114        /// with maximum 1 second between each press. The exact value of N SHALL be made available via PI key.
115        const PRESS_RESET_BUTTON_N_TIMES = 0x0000_1000;
116        /// The Device will enter Commissioning Mode when setup button is pressed.
117        const PRESS_SETUP_BUTTON = 0x0000_2000;
118        /// The Device will enter Commissioning Mode when setup button is pressed when applying power to it.
119        const PRESS_SETUP_BUTTON_WITH_POWER = 0x0000_4000;
120        /// The Device will enter Commissioning Mode when setup button is pressed for N seconds.
121        /// The exact value of N SHALL be made available via PI key.
122        const PRESS_SETUP_BUTTON_FOR_N_SECONDS = 0x0000_8000;
123        /// The Device will enter Commissioning Mode when setup button is pressed until associated
124        /// light blinks. Information on color of light MAY be made available via PI key.
125        const PRESS_SETUP_BUTTON_UNTIL_LIGHT_BLINKS = 0x0001_0000;
126        /// The Device will enter Commissioning Mode when setup button is pressed for N seconds
127        /// when applying power to it. The exact value of N SHALL be made available via PI key.
128        const PRESS_SETUP_BUTTON_FOR_N_SECONDS_WITH_POWER = 0x0002_0000;
129        /// The Device will enter Commissioning Mode when setup button is pressed until associated
130        /// light blinks when applying power to the Device. Information on color of light MAY be
131        /// made available via PI key.
132        const PRESS_SETUP_BUTTON_UNTIL_LIGHT_BLINKS_WITH_POWER = 0x0004_0000;
133        /// The Device will enter Commissioning Mode when setup button is pressed N times with
134        /// maximum 1 second between each press. The exact value of N SHALL be made available via PI key.
135        const PRESS_SETUP_BUTTON_N_TIMES = 0x0008_0000;
136    }
137}
138
139/// Factory-default value for the `BasicInformation::DeviceLocation`
140/// attribute - the borrowed, const-constructible counterpart of
141/// [`DeviceLocation`], suitable for embedding in [`BasicInfoConfig`].
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
143#[cfg_attr(feature = "defmt", derive(defmt::Format))]
144pub struct DeviceLocationConfig<'a> {
145    /// Free-form location description, at most 128 bytes.
146    pub location_name: &'a str,
147    /// Floor number, when applicable.
148    pub floor_number: Option<i16>,
149    /// Area type from the common Area namespace (the value of an `AreaTypeTag`).
150    pub area_type: Option<u8>,
151}
152
153/// Basic information which is immutable
154/// (i.e. valid for the lifetime of the device firmware)
155///
156/// Note that some of the fields will be reported only if their corresponding optional attributes are enabled.
157///
158/// By default, `BasicInfoHandler::CLUSTER` enables ALL optional attributes except `reachable` which is only valid for
159/// bridged devices.
160#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
161#[cfg_attr(feature = "defmt", derive(defmt::Format))]
162pub struct BasicInfoConfig<'a> {
163    /// Vendor name (up to 32 characters)
164    pub vendor_name: &'a str,
165    /// Vendor ID
166    pub vid: u16,
167    /// Product name (up to 32 characters)
168    pub product_name: &'a str,
169    /// Product ID
170    pub pid: u16,
171    /// Hardware version
172    pub hw_ver: u16,
173    /// Hardware version string (up to 64 characters)
174    pub hw_ver_str: &'a str,
175    /// Software version
176    pub sw_ver: u32,
177    /// Software version string (up to 64 characters)
178    pub sw_ver_str: &'a str,
179    /// Manufacturing date (up to 16 characters)
180    pub manufacturing_date: &'a str,
181    /// Part number (up to 32 characters)
182    pub part_number: &'a str,
183    /// Product URL (up to 256 characters)
184    pub product_url: &'a str,
185    /// Product label (up to 64 characters)
186    pub product_label: &'a str,
187    /// Serial number (up to 32 characters)
188    pub serial_no: &'a str,
189    /// Unique ID (up to 32 characters). When empty (the default), the node
190    /// makes a random one, keeps it, and makes a new one after a factory
191    /// reset, as the spec asks. A fixed value here stays the same across
192    /// factory resets.
193    pub unique_id: &'a str,
194    /// Factory default for the runtime-mutable, persisted
195    /// `BasicInformation::Location` attribute
196    pub location: Option<&'a str>,
197    /// Factory default for the runtime-mutable, persisted
198    /// `BasicInformation::DeviceLocation` attribute
199    pub device_location: Option<DeviceLocationConfig<'a>>,
200    /// Capability Minima
201    pub capability_minima: CapabilityMinima,
202    /// Product Appearance
203    pub product_appearance: ProductAppearance,
204    /// Specification Version
205    pub specification_version: u32,
206    /// Data Model Revision
207    pub data_model_revision: u16,
208    /// Max Paths Per Invoke
209    pub max_paths_per_invoke: u16,
210    /// Device Name
211    ///
212    /// Not a real attribute; used in the mDNS commissioning advertisement
213    pub device_name: &'a str,
214    /// Device Type
215    ///
216    /// Not a real attribute; used in the mDNS commissioning advertisement
217    pub device_type: Option<u16>,
218    /// Pairing Hint
219    ///
220    /// Not a real attribute; used in the mDNS commissioning advertisement
221    pub pairing_hint: PairingHintFlags,
222    /// Pairing Instruction
223    ///
224    /// Not a real attribute; used in the mDNS commissioning advertisement
225    pub pairing_instruction: &'a str,
226    /// Session Active Interval in ms
227    /// If not specified, defaults to 300
228    ///
229    /// Per the Matter Core Spec, the value is a 32-bit unsigned integer and
230    /// SHALL NOT exceed 3,600,000 (1 hour in milliseconds).
231    ///
232    /// Not a real attribute, just used to configure the session timeouts
233    pub sai: Option<u32>,
234    /// Session Idle Interval in ms
235    /// If not specified, it is not advertised, and peers assume the spec
236    /// default of 500
237    ///
238    /// Per the Matter Core Spec, the advertised value SHALL NOT exceed
239    /// 3,600,000 (1 hour in milliseconds), so a larger one is advertised as
240    /// that. Note that for a LIT ICD device which is in LIT mode, the idle interval
241    /// may be longer (up to 18 hours). While operating as a LIT, an ICD device
242    /// does not advertise this attribute.
243    ///
244    /// Not a real attribute, just used to configure the session timeouts
245    pub sii: Option<u32>,
246    /// The least max interval granted to a subscription, in seconds: what the
247    /// subscriber asks for, but no less than this. A subscription with nothing to
248    /// report keeps alive halfway through its max interval, so this bounds how
249    /// often such keep-alive reports go out.
250    ///
251    /// Not used by an Intermittently Connected Device, whose subscriptions take
252    /// their max interval from its idle mode duration.
253    ///
254    /// Not a real attribute.
255    pub min_subscription_max_interval_secs: u16,
256    /// The greatest max interval granted to a subscription, in seconds: what the
257    /// subscriber asks for, but no more than this. This bounds how long a
258    /// subscriber will wait before timing out a silent device, speeding up background
259    /// reconnects after reboots.
260    ///
261    /// [`Self::min_subscription_max_interval_secs`] and the subscriber's min interval
262    /// floor take precedence over this. Set to `u16::MAX` for no upper bound.
263    ///
264    /// Not used by an Intermittently Connected Device, whose subscriptions take
265    /// their max interval from its idle mode duration.
266    ///
267    /// Not a real attribute.
268    pub max_subscription_max_interval_secs: u16,
269}
270
271impl BasicInfoConfig<'_> {
272    pub const fn new() -> Self {
273        Self {
274            vid: 0,
275            pid: 0,
276            hw_ver: 0,
277            hw_ver_str: "",
278            sw_ver: 0,
279            sw_ver_str: "",
280            serial_no: "",
281            product_name: "",
282            vendor_name: "",
283            manufacturing_date: "",
284            part_number: "",
285            product_url: "",
286            product_label: "",
287            unique_id: "",
288            location: None,
289            device_location: None,
290            capability_minima: CapabilityMinima::new(),
291            product_appearance: ProductAppearance::new(),
292            specification_version: DEFAULT_MATTER_SPEC_VERSION,
293            data_model_revision: DEFAULT_DATA_MODEL_REVISION,
294            max_paths_per_invoke: DEFAULT_MAX_PATHS_PER_INVOKE,
295            device_name: "",
296            device_type: None,
297            pairing_hint: PairingHintFlags::empty(),
298            pairing_instruction: "",
299            sai: None,
300            sii: None,
301            min_subscription_max_interval_secs: DEFAULT_MIN_SUBSCRIPTION_MAX_INTERVAL_SECS,
302            max_subscription_max_interval_secs: DEFAULT_MAX_SUBSCRIPTION_MAX_INTERVAL_SECS,
303        }
304    }
305}
306
307impl Default for BasicInfoConfig<'_> {
308    fn default() -> Self {
309        Self::new()
310    }
311}
312
313/// Capability Minima as reported in the Basic Information cluster
314#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
315#[cfg_attr(feature = "defmt", derive(defmt::Format))]
316pub struct CapabilityMinima {
317    /// Maximum CASE sessions per fabric
318    pub case_sessions_per_fabric: u16,
319    /// Maximum subscriptions per fabric
320    pub subscriptions_per_fabric: u16,
321    /// Maximum concurrent Invoke interactions processed before the node may
322    /// start answering with `BUSY`
323    pub simultaneous_invocations_supported: u16,
324    /// Minimum concurrent Write interactions the node can process
325    pub simultaneous_writes_supported: u16,
326    /// Maximum number of read paths (`AttributePathIB` + `EventPathIB`) the
327    /// node guarantees to process in a single Read Request
328    pub read_paths_supported: u16,
329    /// Maximum number of subscribe paths (`AttributePathIB` + `EventPathIB`)
330    /// the node guarantees to process in a single Subscribe Request
331    pub subscribe_paths_supported: u16,
332}
333
334/// The Matter spec mandates `CapabilityMinima.SubscriptionsPerFabric >= 3`.
335/// rs-matter sizes its default subscription table as `MAX_FABRICS * 3` (see
336/// `DEFAULT_MAX_SUBSCRIPTIONS` of the IM engine), so this per-fabric minimum is
337/// what the device guarantees.
338const SUBSCRIPTIONS_PER_FABRIC: u16 = 3;
339
340/// Constraint is `1 to 10000`.
341const SIMULTANEOUS_INVOCATIONS_SUPPORTED: u16 = 1;
342/// Constraint is `1 to 10000`.
343const SIMULTANEOUS_WRITES_SUPPORTED: u16 = 1;
344/// Constraint is `9 to 10000`; see Core spec 2.11.2.1 "Read Interaction Limits".
345const READ_PATHS_SUPPORTED: u16 = 9;
346
347/// The size of the buffer which keeps the request of a subscription.
348///
349/// A larger request is kept without its data version filters, which only matter
350/// for the priming report.
351pub const SUBSCRIPTION_BUFFER_SIZE: usize = 256;
352
353/// The default `SubscribePathsSupported` of the Basic Information cluster: the paths which
354/// fit in [`SUBSCRIPTION_BUFFER_SIZE`] at their largest encoding. Constraint is `3 to 10000`.
355pub const SUBSCRIBE_PATHS_SUPPORTED: u16 =
356    ((SUBSCRIPTION_BUFFER_SIZE - SubscribeReq::MAX_FIXED_LEN) / SubscribeReq::MAX_PATH_LEN) as u16;
357
358const _: () = ::core::assert!(SUBSCRIBE_PATHS_SUPPORTED >= 3);
359
360impl CapabilityMinima {
361    /// Create a default instance of `CapabilityMinima`, with the CASE sessions
362    /// each fabric is guaranteed and the spec-minimum subscriptions per fabric.
363    pub const fn new() -> Self {
364        Self {
365            case_sessions_per_fabric: CASE_SESSIONS_PER_FABRIC as _,
366            subscriptions_per_fabric: SUBSCRIPTIONS_PER_FABRIC,
367            simultaneous_invocations_supported: SIMULTANEOUS_INVOCATIONS_SUPPORTED,
368            simultaneous_writes_supported: SIMULTANEOUS_WRITES_SUPPORTED,
369            read_paths_supported: READ_PATHS_SUPPORTED,
370            subscribe_paths_supported: SUBSCRIBE_PATHS_SUPPORTED,
371        }
372    }
373}
374
375impl Default for CapabilityMinima {
376    fn default() -> Self {
377        Self::new()
378    }
379}
380
381/// Product Appearance as reported in the Basic Information cluster
382#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
383#[cfg_attr(feature = "defmt", derive(defmt::Format))]
384pub struct ProductAppearance {
385    /// Product finish type
386    pub finish: ProductFinish,
387    /// Product primary color
388    pub color: Option<ProductColor>,
389}
390
391/// The finish of the product.
392///
393/// The variants are the ones of the Basic Information cluster.
394#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
395#[cfg_attr(feature = "defmt", derive(defmt::Format))]
396pub enum ProductFinish {
397    Other,
398    Matte,
399    Satin,
400    Polished,
401    Rugged,
402    Fabric,
403}
404
405/// The primary color of the product.
406///
407/// The variants are the ones of the Basic Information cluster.
408#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
409#[cfg_attr(feature = "defmt", derive(defmt::Format))]
410pub enum ProductColor {
411    Black,
412    Navy,
413    Green,
414    Teal,
415    Maroon,
416    Purple,
417    Olive,
418    Gray,
419    Blue,
420    Lime,
421    Aqua,
422    Red,
423    Fuchsia,
424    Yellow,
425    White,
426    Nickel,
427    Chrome,
428    Brass,
429    Copper,
430    Silver,
431    Gold,
432}
433
434impl ProductAppearance {
435    /// Create a default instance of `ProductAppearance`,
436    /// with `Other` finish and no color.
437    pub const fn new() -> Self {
438        Self {
439            finish: ProductFinish::Other,
440            color: None,
441        }
442    }
443}
444
445impl Default for ProductAppearance {
446    fn default() -> Self {
447        Self::new()
448    }
449}
450
451/// Owned mirror of the `LocationDescriptorStruct` global type, as stored for
452/// the `BasicInformation::DeviceLocation` attribute.
453#[derive(Debug, Clone, Eq, PartialEq, Hash, ToTLV, FromTLV)]
454#[cfg_attr(feature = "defmt", derive(defmt::Format))]
455pub struct DeviceLocation {
456    /// Free-form location description, at most 128 bytes.
457    pub location_name: String<128>,
458    /// Floor number, when applicable; `Null` on the wire when `None`.
459    pub floor_number: Option<i16>,
460    /// Area type from the common Area namespace (the value of an
461    /// `AreaTypeTag`); `Null` on the wire when `None`.
462    pub area_type: Option<u8>,
463}
464
465impl DeviceLocation {
466    /// Create an empty `DeviceLocation` (empty location name, no floor
467    /// number, no area type).
468    pub const fn new() -> Self {
469        Self {
470            location_name: String::new(),
471            floor_number: None,
472            area_type: None,
473        }
474    }
475}
476
477impl Default for DeviceLocation {
478    fn default() -> Self {
479        Self::new()
480    }
481}
482
483/// Mutable basic information
484#[derive(Debug, Clone, Eq, PartialEq, Hash, ToTLV, FromTLV)]
485#[cfg_attr(feature = "defmt", derive(defmt::Format))]
486pub struct BasicInfoSettings {
487    pub node_label: String<32>,      // Max node-label as per the spec
488    pub location: Option<String<2>>, // Max location as per the spec
489    /// The regulatory location type, as set via
490    /// `GeneralCommissioning::SetRegulatoryConfig`.
491    pub location_type: Option<RegulatoryLocationType>,
492    pub local_config_disabled: bool,
493    /// `BasicInformation::ConfigurationVersion` (Matter Core Spec).
494    /// Non-volatile, monotonically increasing, minimum 1.
495    /// Bumped by application code via
496    /// `InteractionModel::bump_configuration_version` whenever the node's
497    /// fixed-quality surface (Server/Parts list, device types, software
498    /// version, …) changes — see Matter Core Spec.
499    pub configuration_version: u32,
500    /// `BasicInformation::DeviceLocation` (provisional in the Matter 1.6
501    /// IDL): where the device is installed, admin-writable.
502    pub device_location: Option<Nullable<DeviceLocation>>,
503    /// `GeneralCommissioning::RecoveryIdentifier` (provisional in Matter 1.6):
504    /// a random 64-bit value that identifies this node during the
505    /// Network Recovery flow without revealing its Node ID.
506    pub recovery_identifier: Option<u64>,
507    /// `BasicInformation::UniqueID`: a random 64-bit value, minted on first
508    /// read and cleared by a factory reset, so that the device gets a new
509    /// one, as the spec asks.
510    ///
511    /// NOTE: keep new fields *last* - the persisted-blob TLV tags are
512    /// positional, and appending preserves compatibility with blobs written
513    /// before the field existed.
514    pub unique_id: Option<u64>,
515}
516
517impl BasicInfoSettings {
518    /// Create a new instance of `BasicInfoSettings`
519    pub const fn new() -> Self {
520        Self {
521            node_label: String::new(),
522            location: None,
523            location_type: None,
524            local_config_disabled: false,
525            // Spec fallback for `ConfigurationVersion` is 1 (`min 1`,
526            // Core Spec).
527            configuration_version: 1,
528            device_location: None,
529            recovery_identifier: None,
530            unique_id: None,
531        }
532    }
533
534    /// Return an in-place initializer for `BasicInfoSettings`
535    pub fn init() -> impl Init<Self> {
536        init!(Self {
537            node_label: String::new(),
538            location: None,
539            location_type: None,
540            local_config_disabled: false,
541            configuration_version: 1,
542            device_location: None,
543            recovery_identifier: None,
544            unique_id: None,
545        })
546    }
547
548    /// Resets the basic info to initial values
549    ///
550    /// # Arguments
551    /// - `flag_changed`: whether to mark the basic info settings as changed
552    pub fn reset(&mut self) {
553        self.node_label.clear();
554        self.location = None;
555        self.location_type = None;
556        self.local_config_disabled = false;
557        self.configuration_version = 1;
558        self.device_location = None;
559        self.recovery_identifier = None;
560        self.unique_id = None;
561    }
562
563    /// Bump `ConfigurationVersion` by one and return the new value.
564    ///
565    /// Saturates at `u32::MAX` (the spec gives no wrap semantics, so
566    /// staying at the max is safer than rolling over to 0 which would
567    /// violate the `min 1` constraint).
568    ///
569    /// This routine only mutates the in-memory value. Persistence and
570    /// subscriber notification are the caller's responsibility — use
571    /// `InteractionModel::bump_configuration_version` for the full
572    /// "bump + persist + notify + dataver-bump" pass.
573    pub fn bump_configuration_version(&mut self) -> u32 {
574        self.configuration_version = self.configuration_version.saturating_add(1);
575        self.configuration_version
576    }
577
578    /// Set the location (country code) to the given (2-character) value.
579    pub fn set_location(&mut self, location: &str) {
580        self.location = Some(unwrap!(String::<2>::from_str(location)));
581    }
582
583    /// Remove all basic info settings from the provided BLOB store as well as from memory
584    ///
585    /// # Arguments
586    /// - `store`: the BLOB store to remove the settings from
587    /// - `buf`: a temporary buffer to use for removing the settings
588    pub fn reset_persist<S: KvBlobStore>(
589        &mut self,
590        mut store: S,
591        buf: &mut [u8],
592    ) -> Result<(), Error> {
593        self.reset();
594
595        store.remove(BASIC_INFO_KEY, buf)?;
596
597        info!("Removed basic info settings from storage");
598
599        Ok(())
600    }
601
602    /// Load basic info settings from the provided byte slice
603    pub fn load(&mut self, data: &[u8]) -> Result<(), Error> {
604        let info = Self::from_tlv(&TLVElement::new(data))?;
605
606        self.node_label = info.node_label;
607        self.location = info.location;
608        self.location_type = info.location_type;
609        self.local_config_disabled = info.local_config_disabled;
610        self.configuration_version = info.configuration_version;
611        self.device_location = info.device_location;
612        self.recovery_identifier = info.recovery_identifier;
613        self.unique_id = info.unique_id;
614
615        Ok(())
616    }
617
618    /// Store the basic info settings via the provided `Persist` instance
619    ///
620    /// # Arguments
621    /// - `persist`: the `Persist` instance to serialize the settings into
622    ///
623    /// Deliberately outlined (`inline(never)`): the settings' TLV
624    /// serialization is sizeable, and every runtime-mutable-attribute setter
625    /// ends with this call - sharing a single copy keeps it out of each
626    /// attribute-dispatch path (flash size).
627    #[inline(never)]
628    pub fn store_persist<S: KvBlobStoreAccess>(
629        &self,
630        persist: &mut Persist<S>,
631    ) -> Result<(), Error> {
632        persist.store_tlv(BASIC_INFO_KEY, self)
633    }
634
635    /// Load all basic info settings from the provided key-value store
636    pub fn load_persist<S: KvBlobStoreAccess>(&mut self, kv: S) -> Result<(), Error> {
637        self.reset();
638
639        if Persist::new(kv)
640            .load(BASIC_INFO_KEY, |data| self.load(data))?
641            .is_some()
642        {
643            info!("Loaded basic info settings from storage");
644        }
645
646        Ok(())
647    }
648}
649
650impl Default for BasicInfoSettings {
651    fn default() -> Self {
652        Self::new()
653    }
654}
655
656/// The regulatory location type of the node.
657///
658/// The values are the ones of the General Commissioning cluster.
659#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, FromTLV, ToTLV)]
660#[tlvargs(datatype = "u8")]
661#[cfg_attr(feature = "defmt", derive(defmt::Format))]
662#[repr(u8)]
663pub enum RegulatoryLocationType {
664    #[enumval(0)]
665    Indoor = 0,
666    #[enumval(1)]
667    Outdoor = 1,
668    #[enumval(2)]
669    IndoorOutdoor = 2,
670}
671
672#[cfg(test)]
673#[cfg_attr(coverage_nightly, coverage(off))]
674mod tests {
675    use super::{BasicInfoSettings, DeviceLocation};
676
677    use crate::tlv::{Nullable, TLVElement, TLVTag, ToTLV};
678    use crate::utils::storage::WriteBuf;
679
680    /// Round-trip `settings` through the persisted-blob TLV representation.
681    fn round_trip(settings: &BasicInfoSettings) -> BasicInfoSettings {
682        let mut buf = [0; 512];
683        let mut wb = WriteBuf::new(&mut buf);
684        settings.to_tlv(&TLVTag::Anonymous, &mut wb).unwrap();
685
686        let mut loaded = BasicInfoSettings::new();
687        loaded.load(wb.as_slice()).unwrap();
688
689        loaded
690    }
691
692    /// An explicit `XX` ("unknown country") write must be stored - and
693    /// persisted - verbatim: `None` means "never configured" (and lets the
694    /// `Location` attribute report the `BasicInfoConfig::location` factory
695    /// default), which an explicit `XX` write is not.
696    #[test]
697    fn explicit_xx_location_is_kept() {
698        let mut settings = BasicInfoSettings::new();
699        assert!(settings.location.is_none());
700
701        settings.set_location("XX");
702        assert_eq!(settings.location.as_deref(), Some("XX"));
703        assert_eq!(round_trip(&settings).location.as_deref(), Some("XX"));
704    }
705
706    /// The three `device_location` states - never-written / explicit `Null` /
707    /// value - must survive the persisted-blob round-trip, or an admin
708    /// -written `Null` would resurrect the factory default after a reboot.
709    #[test]
710    fn device_location_states_survive_persistence() {
711        let mut settings = BasicInfoSettings::new();
712        assert!(round_trip(&settings).device_location.is_none());
713
714        settings.device_location = Some(Nullable::none());
715        let loaded = round_trip(&settings);
716        assert!(matches!(&loaded.device_location, Some(l) if l.is_none()));
717
718        settings.device_location = Some(Nullable::some(DeviceLocation {
719            location_name: "Basement".try_into().unwrap(),
720            floor_number: Some(-1),
721            area_type: None,
722        }));
723        let loaded = round_trip(&settings);
724        let location = loaded.device_location.unwrap().into_option().unwrap();
725        assert_eq!(location.location_name, "Basement");
726        assert_eq!(location.floor_number, Some(-1));
727        assert_eq!(location.area_type, None);
728    }
729
730    /// Settings predating the `device_location` field (or a factory-fresh
731    /// blob) must load as "never written".
732    #[test]
733    fn missing_device_location_field_loads_as_unset() {
734        // A blob serialized without the trailing `device_location` field:
735        // emulate by truncating... simpler - serialize a fresh settings
736        // (which encodes the field as absent) and check the tri-state.
737        let settings = BasicInfoSettings::new();
738        let loaded = round_trip(&settings);
739        assert!(loaded.device_location.is_none());
740
741        // And `reset()` returns every runtime-configured value to
742        // "never written", so the factory defaults apply again.
743        let mut settings = BasicInfoSettings::new();
744        settings.set_location("US");
745        settings.location_type = Some(super::RegulatoryLocationType::Indoor);
746        settings.device_location = Some(Nullable::none());
747        settings.reset();
748        assert!(settings.location.is_none());
749        assert!(settings.location_type.is_none());
750        assert!(settings.device_location.is_none());
751    }
752
753    /// The `GeneralCommissioning::RecoveryIdentifier` value must survive the
754    /// persisted-blob round-trip (stable across reboots, per Matter Core Spec
755    /// 11.10.6.11), load as "never minted" from a blob that predates the field,
756    /// and be cleared by `reset()` so a factory reset regenerates it.
757    #[test]
758    fn recovery_identifier_survives_persistence_and_resets() {
759        // Factory-fresh (and blobs predating the field) load as "never minted".
760        let mut settings = BasicInfoSettings::new();
761        assert!(settings.recovery_identifier.is_none());
762        assert!(round_trip(&settings).recovery_identifier.is_none());
763
764        // A minted value round-trips verbatim.
765        settings.recovery_identifier = Some(0x1122_3344_5566_7788);
766        assert_eq!(
767            round_trip(&settings).recovery_identifier,
768            Some(0x1122_3344_5566_7788)
769        );
770
771        // Factory reset clears it so the next read mints a fresh one.
772        settings.reset();
773        assert!(settings.recovery_identifier.is_none());
774    }
775
776    /// The `BasicInformation::UniqueID` value must survive the persisted-blob
777    /// round-trip, load as "never minted" from a blob that predates the
778    /// field, and be cleared by `reset()`, as a factory reset must give the
779    /// device a new one.
780    #[test]
781    fn unique_id_survives_persistence_and_resets() {
782        let mut settings = BasicInfoSettings::new();
783        assert!(settings.unique_id.is_none());
784        assert!(round_trip(&settings).unique_id.is_none());
785
786        settings.recovery_identifier = Some(1);
787        settings.unique_id = Some(0x0123_4567_89AB_CDEF);
788        let loaded = round_trip(&settings);
789        assert_eq!(loaded.unique_id, Some(0x0123_4567_89AB_CDEF));
790        assert_eq!(loaded.recovery_identifier, Some(1));
791
792        settings.reset();
793        assert!(settings.unique_id.is_none());
794    }
795
796    // Silence unused-import lint on no-test builds
797    #[allow(unused)]
798    fn _t(_: TLVElement) {}
799}