rs-matter-node-core 0.5.0

Native Rust implementation of the Matter (Smart-Home) ecosystem - what the node is built on: fabrics, ACL, fail-safe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
/*
 *
 *    Copyright (c) 2026 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

//! The basic information of the node: its configuration, which does not
//! change at runtime, and its settings, which administrators change and which
//! the node persists.

use core::str::FromStr;

use crate::dm::{AttrId, ClusterId};
use crate::error::Error;
use crate::im::SubscribeReq;
use crate::persist::{KvBlobStore, KvBlobStoreAccess, Persist, BASIC_INFO_KEY};
use crate::session::CASE_SESSIONS_PER_FABRIC;
use crate::tlv::{FromTLV, Nullable, TLVElement, ToTLV};
use crate::utils::bitflags::bitflags;
use crate::utils::init::{init, Init};
use crate::utils::storage::String;

/// The ID of the Basic Information cluster
pub const BASIC_INFO_CLUSTER_ID: ClusterId = 0x0028;
/// The ID of the `ConfigurationVersion` attribute of the Basic Information cluster
pub const CONFIGURATION_VERSION_ATTR_ID: AttrId = 0x0018;

/// The default Matter App Clusters specification version
///
/// Currently set to V1.6.0.0.
pub const DEFAULT_MATTER_SPEC_VERSION: u32 = 0x01060000;

/// The default Matter Data Model revision
///
/// Currently set to V21, which was released with Matter Core spec V1.6
pub const DEFAULT_DATA_MODEL_REVISION: u16 = 21;

/// The default maximum number of paths that can be included in an Invoke request
///
/// Set to 1, the minimum. A node that accepts more has to support the
/// General Diagnostics `DMTEST` feature, and the responses to a batch can
/// then outgrow one message, which needs chunked Invoke responses. rs-matter
/// has neither yet.
pub const DEFAULT_MAX_PATHS_PER_INVOKE: u16 = 1;

/// The default for [`BasicInfoConfig::min_subscription_max_interval_secs`].
pub const DEFAULT_MIN_SUBSCRIPTION_MAX_INTERVAL_SECS: u16 = 40;

/// The default for [`BasicInfoConfig::max_subscription_max_interval_secs`].
pub const DEFAULT_MAX_SUBSCRIPTION_MAX_INTERVAL_SECS: u16 = 120;

bitflags! {
    #[repr(transparent)]
    #[derive(Default)]
    #[cfg_attr(not(feature = "defmt"), derive(Debug, Copy, Clone, Eq, PartialEq, Hash))]
    pub struct PairingHintFlags: u32 {
        /// Power Cycle False The Device will automatically enter Commissioning Mode upon
        /// power cycle (unplug/replug, remove/re-insert batteries).
        /// This bit SHALL be set to 1 for devices using Standard Commissioning Flow,
        /// and set to 0 otherwise.
        const POWER_CYCLE = 0x0000_0001;
        /// This SHALL be set to 1 for devices requiring Custom Commissioning
        /// Flow before they can be available for Commissioning by any Commissioner.
        /// For such a flow, the user SHOULD be sent to the URL specified in the
        /// CommissioningCustomFlowUrl of the DeviceModel schema entry indexed by the
        /// Vendor ID and Product ID (e.g., as found in the announcement) in the
        /// Distributed Compliance Ledger.
        const DEV_MANUFACTURER_URL = 0x0000_0002;
        /// The Device has been commissioned. Any Administrator that commissioned the
        /// device provides a user interface that may be used to put the device
        /// into Commissioning Mode.
        const ADMINISTRATOR = 0x0000_0004;
        /// The settings menu on the Device provides instructions to put it
        /// into Commissioning Mode.
        const SETTINGS_MENU = 0x0000_0008;
        /// The PI key/value pair describes a custom way to put the Device into
        /// Commissioning Mode. This Custom Instruction option is NOT recommended
        /// for use by a Device that does not have knowledge of the user's language preference.
        const CUSTOM_INSTRUCTION = 0x0000_0010;
        /// The Device Manual provides special instructions to put the Device
        /// into Commissioning Mode (see "UserManualUrl" in the Core Spec).
        /// This is a catchall option to capture user interactions that are not codified by
        /// other options in this flags type.
        const DEVICE_MANUAL = 0x0000_0020;
        /// The Device will enter Commissioning Mode when reset button is pressed.
        const PRESS_RESET_BUTTON = 0x0000_0040;
        /// The Device will enter Commissioning Mode when reset button is pressed when applying power to it.
        const PRESS_RESET_BUTTON_WITH_POWER = 0x0000_0080;
        /// The Device will enter Commissioning Mode when reset button is pressed for N seconds.
        /// The exact value of N SHALL be made available via PI key.
        const PRESS_RESET_BUTTON_FOR_N_SECONDS = 0x0000_0100;
        /// The Device will enter Commissioning Mode when reset button is pressed until associated light blinks.
        /// Information on color of light MAY be made available via PI key.
        const PRESS_RESET_BUTTON_UNTIL_LIGHT_BLINKS = 0x0000_0200;
        /// The Device will enter Commissioning Mode when reset button is pressed for N seconds
        /// when applying power to it. The exact value of N SHALL be made available via PI key.
        const PRESS_RESET_BUTTON_FOR_N_SECONDS_WITH_POWER = 0x0000_0400;
        /// The Device will enter Commissioning Mode when reset button is pressed until associated
        /// light blinks when applying power to the Device. Information on color of light MAY be
        /// made available via PI key.
        const PRESS_RESET_BUTTON_UNTIL_LIGHT_BLINKS_WITH_POWER = 0x0000_0800;
        /// The Device will enter Commissioning Mode when reset button is pressed N times
        /// with maximum 1 second between each press. The exact value of N SHALL be made available via PI key.
        const PRESS_RESET_BUTTON_N_TIMES = 0x0000_1000;
        /// The Device will enter Commissioning Mode when setup button is pressed.
        const PRESS_SETUP_BUTTON = 0x0000_2000;
        /// The Device will enter Commissioning Mode when setup button is pressed when applying power to it.
        const PRESS_SETUP_BUTTON_WITH_POWER = 0x0000_4000;
        /// The Device will enter Commissioning Mode when setup button is pressed for N seconds.
        /// The exact value of N SHALL be made available via PI key.
        const PRESS_SETUP_BUTTON_FOR_N_SECONDS = 0x0000_8000;
        /// The Device will enter Commissioning Mode when setup button is pressed until associated
        /// light blinks. Information on color of light MAY be made available via PI key.
        const PRESS_SETUP_BUTTON_UNTIL_LIGHT_BLINKS = 0x0001_0000;
        /// The Device will enter Commissioning Mode when setup button is pressed for N seconds
        /// when applying power to it. The exact value of N SHALL be made available via PI key.
        const PRESS_SETUP_BUTTON_FOR_N_SECONDS_WITH_POWER = 0x0002_0000;
        /// The Device will enter Commissioning Mode when setup button is pressed until associated
        /// light blinks when applying power to the Device. Information on color of light MAY be
        /// made available via PI key.
        const PRESS_SETUP_BUTTON_UNTIL_LIGHT_BLINKS_WITH_POWER = 0x0004_0000;
        /// The Device will enter Commissioning Mode when setup button is pressed N times with
        /// maximum 1 second between each press. The exact value of N SHALL be made available via PI key.
        const PRESS_SETUP_BUTTON_N_TIMES = 0x0008_0000;
    }
}

/// Factory-default value for the `BasicInformation::DeviceLocation`
/// attribute - the borrowed, const-constructible counterpart of
/// [`DeviceLocation`], suitable for embedding in [`BasicInfoConfig`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DeviceLocationConfig<'a> {
    /// Free-form location description, at most 128 bytes.
    pub location_name: &'a str,
    /// Floor number, when applicable.
    pub floor_number: Option<i16>,
    /// Area type from the common Area namespace (the value of an `AreaTypeTag`).
    pub area_type: Option<u8>,
}

/// Basic information which is immutable
/// (i.e. valid for the lifetime of the device firmware)
///
/// Note that some of the fields will be reported only if their corresponding optional attributes are enabled.
///
/// By default, `BasicInfoHandler::CLUSTER` enables ALL optional attributes except `reachable` which is only valid for
/// bridged devices.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct BasicInfoConfig<'a> {
    /// Vendor name (up to 32 characters)
    pub vendor_name: &'a str,
    /// Vendor ID
    pub vid: u16,
    /// Product name (up to 32 characters)
    pub product_name: &'a str,
    /// Product ID
    pub pid: u16,
    /// Hardware version
    pub hw_ver: u16,
    /// Hardware version string (up to 64 characters)
    pub hw_ver_str: &'a str,
    /// Software version
    pub sw_ver: u32,
    /// Software version string (up to 64 characters)
    pub sw_ver_str: &'a str,
    /// Manufacturing date (up to 16 characters)
    pub manufacturing_date: &'a str,
    /// Part number (up to 32 characters)
    pub part_number: &'a str,
    /// Product URL (up to 256 characters)
    pub product_url: &'a str,
    /// Product label (up to 64 characters)
    pub product_label: &'a str,
    /// Serial number (up to 32 characters)
    pub serial_no: &'a str,
    /// Unique ID (up to 32 characters). When empty (the default), the node
    /// makes a random one, keeps it, and makes a new one after a factory
    /// reset, as the spec asks. A fixed value here stays the same across
    /// factory resets.
    pub unique_id: &'a str,
    /// Factory default for the runtime-mutable, persisted
    /// `BasicInformation::Location` attribute
    pub location: Option<&'a str>,
    /// Factory default for the runtime-mutable, persisted
    /// `BasicInformation::DeviceLocation` attribute
    pub device_location: Option<DeviceLocationConfig<'a>>,
    /// Capability Minima
    pub capability_minima: CapabilityMinima,
    /// Product Appearance
    pub product_appearance: ProductAppearance,
    /// Specification Version
    pub specification_version: u32,
    /// Data Model Revision
    pub data_model_revision: u16,
    /// Max Paths Per Invoke
    pub max_paths_per_invoke: u16,
    /// Device Name
    ///
    /// Not a real attribute; used in the mDNS commissioning advertisement
    pub device_name: &'a str,
    /// Device Type
    ///
    /// Not a real attribute; used in the mDNS commissioning advertisement
    pub device_type: Option<u16>,
    /// Pairing Hint
    ///
    /// Not a real attribute; used in the mDNS commissioning advertisement
    pub pairing_hint: PairingHintFlags,
    /// Pairing Instruction
    ///
    /// Not a real attribute; used in the mDNS commissioning advertisement
    pub pairing_instruction: &'a str,
    /// Session Active Interval in ms
    /// If not specified, defaults to 300
    ///
    /// Per the Matter Core Spec, the value is a 32-bit unsigned integer and
    /// SHALL NOT exceed 3,600,000 (1 hour in milliseconds).
    ///
    /// Not a real attribute, just used to configure the session timeouts
    pub sai: Option<u32>,
    /// Session Idle Interval in ms
    /// If not specified, it is not advertised, and peers assume the spec
    /// default of 500
    ///
    /// Per the Matter Core Spec, the advertised value SHALL NOT exceed
    /// 3,600,000 (1 hour in milliseconds), so a larger one is advertised as
    /// that. Note that for a LIT ICD device which is in LIT mode, the idle interval
    /// may be longer (up to 18 hours). While operating as a LIT, an ICD device
    /// does not advertise this attribute.
    ///
    /// Not a real attribute, just used to configure the session timeouts
    pub sii: Option<u32>,
    /// The least max interval granted to a subscription, in seconds: what the
    /// subscriber asks for, but no less than this. A subscription with nothing to
    /// report keeps alive halfway through its max interval, so this bounds how
    /// often such keep-alive reports go out.
    ///
    /// Not used by an Intermittently Connected Device, whose subscriptions take
    /// their max interval from its idle mode duration.
    ///
    /// Not a real attribute.
    pub min_subscription_max_interval_secs: u16,
    /// The greatest max interval granted to a subscription, in seconds: what the
    /// subscriber asks for, but no more than this. This bounds how long a
    /// subscriber will wait before timing out a silent device, speeding up background
    /// reconnects after reboots.
    ///
    /// [`Self::min_subscription_max_interval_secs`] and the subscriber's min interval
    /// floor take precedence over this. Set to `u16::MAX` for no upper bound.
    ///
    /// Not used by an Intermittently Connected Device, whose subscriptions take
    /// their max interval from its idle mode duration.
    ///
    /// Not a real attribute.
    pub max_subscription_max_interval_secs: u16,
}

impl BasicInfoConfig<'_> {
    pub const fn new() -> Self {
        Self {
            vid: 0,
            pid: 0,
            hw_ver: 0,
            hw_ver_str: "",
            sw_ver: 0,
            sw_ver_str: "",
            serial_no: "",
            product_name: "",
            vendor_name: "",
            manufacturing_date: "",
            part_number: "",
            product_url: "",
            product_label: "",
            unique_id: "",
            location: None,
            device_location: None,
            capability_minima: CapabilityMinima::new(),
            product_appearance: ProductAppearance::new(),
            specification_version: DEFAULT_MATTER_SPEC_VERSION,
            data_model_revision: DEFAULT_DATA_MODEL_REVISION,
            max_paths_per_invoke: DEFAULT_MAX_PATHS_PER_INVOKE,
            device_name: "",
            device_type: None,
            pairing_hint: PairingHintFlags::empty(),
            pairing_instruction: "",
            sai: None,
            sii: None,
            min_subscription_max_interval_secs: DEFAULT_MIN_SUBSCRIPTION_MAX_INTERVAL_SECS,
            max_subscription_max_interval_secs: DEFAULT_MAX_SUBSCRIPTION_MAX_INTERVAL_SECS,
        }
    }
}

impl Default for BasicInfoConfig<'_> {
    fn default() -> Self {
        Self::new()
    }
}

/// Capability Minima as reported in the Basic Information cluster
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct CapabilityMinima {
    /// Maximum CASE sessions per fabric
    pub case_sessions_per_fabric: u16,
    /// Maximum subscriptions per fabric
    pub subscriptions_per_fabric: u16,
    /// Maximum concurrent Invoke interactions processed before the node may
    /// start answering with `BUSY`
    pub simultaneous_invocations_supported: u16,
    /// Minimum concurrent Write interactions the node can process
    pub simultaneous_writes_supported: u16,
    /// Maximum number of read paths (`AttributePathIB` + `EventPathIB`) the
    /// node guarantees to process in a single Read Request
    pub read_paths_supported: u16,
    /// Maximum number of subscribe paths (`AttributePathIB` + `EventPathIB`)
    /// the node guarantees to process in a single Subscribe Request
    pub subscribe_paths_supported: u16,
}

/// The Matter spec mandates `CapabilityMinima.SubscriptionsPerFabric >= 3`.
/// rs-matter sizes its default subscription table as `MAX_FABRICS * 3` (see
/// `DEFAULT_MAX_SUBSCRIPTIONS` of the IM engine), so this per-fabric minimum is
/// what the device guarantees.
const SUBSCRIPTIONS_PER_FABRIC: u16 = 3;

/// Constraint is `1 to 10000`.
const SIMULTANEOUS_INVOCATIONS_SUPPORTED: u16 = 1;
/// Constraint is `1 to 10000`.
const SIMULTANEOUS_WRITES_SUPPORTED: u16 = 1;
/// Constraint is `9 to 10000`; see Core spec 2.11.2.1 "Read Interaction Limits".
const READ_PATHS_SUPPORTED: u16 = 9;

/// The size of the buffer which keeps the request of a subscription.
///
/// A larger request is kept without its data version filters, which only matter
/// for the priming report.
pub const SUBSCRIPTION_BUFFER_SIZE: usize = 256;

/// The default `SubscribePathsSupported` of the Basic Information cluster: the paths which
/// fit in [`SUBSCRIPTION_BUFFER_SIZE`] at their largest encoding. Constraint is `3 to 10000`.
pub const SUBSCRIBE_PATHS_SUPPORTED: u16 =
    ((SUBSCRIPTION_BUFFER_SIZE - SubscribeReq::MAX_FIXED_LEN) / SubscribeReq::MAX_PATH_LEN) as u16;

const _: () = ::core::assert!(SUBSCRIBE_PATHS_SUPPORTED >= 3);

impl CapabilityMinima {
    /// Create a default instance of `CapabilityMinima`, with the CASE sessions
    /// each fabric is guaranteed and the spec-minimum subscriptions per fabric.
    pub const fn new() -> Self {
        Self {
            case_sessions_per_fabric: CASE_SESSIONS_PER_FABRIC as _,
            subscriptions_per_fabric: SUBSCRIPTIONS_PER_FABRIC,
            simultaneous_invocations_supported: SIMULTANEOUS_INVOCATIONS_SUPPORTED,
            simultaneous_writes_supported: SIMULTANEOUS_WRITES_SUPPORTED,
            read_paths_supported: READ_PATHS_SUPPORTED,
            subscribe_paths_supported: SUBSCRIBE_PATHS_SUPPORTED,
        }
    }
}

impl Default for CapabilityMinima {
    fn default() -> Self {
        Self::new()
    }
}

/// Product Appearance as reported in the Basic Information cluster
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ProductAppearance {
    /// Product finish type
    pub finish: ProductFinish,
    /// Product primary color
    pub color: Option<ProductColor>,
}

/// The finish of the product.
///
/// The variants are the ones of the Basic Information cluster.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ProductFinish {
    Other,
    Matte,
    Satin,
    Polished,
    Rugged,
    Fabric,
}

/// The primary color of the product.
///
/// The variants are the ones of the Basic Information cluster.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ProductColor {
    Black,
    Navy,
    Green,
    Teal,
    Maroon,
    Purple,
    Olive,
    Gray,
    Blue,
    Lime,
    Aqua,
    Red,
    Fuchsia,
    Yellow,
    White,
    Nickel,
    Chrome,
    Brass,
    Copper,
    Silver,
    Gold,
}

impl ProductAppearance {
    /// Create a default instance of `ProductAppearance`,
    /// with `Other` finish and no color.
    pub const fn new() -> Self {
        Self {
            finish: ProductFinish::Other,
            color: None,
        }
    }
}

impl Default for ProductAppearance {
    fn default() -> Self {
        Self::new()
    }
}

/// Owned mirror of the `LocationDescriptorStruct` global type, as stored for
/// the `BasicInformation::DeviceLocation` attribute.
#[derive(Debug, Clone, Eq, PartialEq, Hash, ToTLV, FromTLV)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DeviceLocation {
    /// Free-form location description, at most 128 bytes.
    pub location_name: String<128>,
    /// Floor number, when applicable; `Null` on the wire when `None`.
    pub floor_number: Option<i16>,
    /// Area type from the common Area namespace (the value of an
    /// `AreaTypeTag`); `Null` on the wire when `None`.
    pub area_type: Option<u8>,
}

impl DeviceLocation {
    /// Create an empty `DeviceLocation` (empty location name, no floor
    /// number, no area type).
    pub const fn new() -> Self {
        Self {
            location_name: String::new(),
            floor_number: None,
            area_type: None,
        }
    }
}

impl Default for DeviceLocation {
    fn default() -> Self {
        Self::new()
    }
}

/// Mutable basic information
#[derive(Debug, Clone, Eq, PartialEq, Hash, ToTLV, FromTLV)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct BasicInfoSettings {
    pub node_label: String<32>,      // Max node-label as per the spec
    pub location: Option<String<2>>, // Max location as per the spec
    /// The regulatory location type, as set via
    /// `GeneralCommissioning::SetRegulatoryConfig`.
    pub location_type: Option<RegulatoryLocationType>,
    pub local_config_disabled: bool,
    /// `BasicInformation::ConfigurationVersion` (Matter Core Spec).
    /// Non-volatile, monotonically increasing, minimum 1.
    /// Bumped by application code via
    /// `InteractionModel::bump_configuration_version` whenever the node's
    /// fixed-quality surface (Server/Parts list, device types, software
    /// version, …) changes — see Matter Core Spec.
    pub configuration_version: u32,
    /// `BasicInformation::DeviceLocation` (provisional in the Matter 1.6
    /// IDL): where the device is installed, admin-writable.
    pub device_location: Option<Nullable<DeviceLocation>>,
    /// `GeneralCommissioning::RecoveryIdentifier` (provisional in Matter 1.6):
    /// a random 64-bit value that identifies this node during the
    /// Network Recovery flow without revealing its Node ID.
    pub recovery_identifier: Option<u64>,
    /// `BasicInformation::UniqueID`: a random 64-bit value, minted on first
    /// read and cleared by a factory reset, so that the device gets a new
    /// one, as the spec asks.
    ///
    /// NOTE: keep new fields *last* - the persisted-blob TLV tags are
    /// positional, and appending preserves compatibility with blobs written
    /// before the field existed.
    pub unique_id: Option<u64>,
}

impl BasicInfoSettings {
    /// Create a new instance of `BasicInfoSettings`
    pub const fn new() -> Self {
        Self {
            node_label: String::new(),
            location: None,
            location_type: None,
            local_config_disabled: false,
            // Spec fallback for `ConfigurationVersion` is 1 (`min 1`,
            // Core Spec).
            configuration_version: 1,
            device_location: None,
            recovery_identifier: None,
            unique_id: None,
        }
    }

    /// Return an in-place initializer for `BasicInfoSettings`
    pub fn init() -> impl Init<Self> {
        init!(Self {
            node_label: String::new(),
            location: None,
            location_type: None,
            local_config_disabled: false,
            configuration_version: 1,
            device_location: None,
            recovery_identifier: None,
            unique_id: None,
        })
    }

    /// Resets the basic info to initial values
    ///
    /// # Arguments
    /// - `flag_changed`: whether to mark the basic info settings as changed
    pub fn reset(&mut self) {
        self.node_label.clear();
        self.location = None;
        self.location_type = None;
        self.local_config_disabled = false;
        self.configuration_version = 1;
        self.device_location = None;
        self.recovery_identifier = None;
        self.unique_id = None;
    }

    /// Bump `ConfigurationVersion` by one and return the new value.
    ///
    /// Saturates at `u32::MAX` (the spec gives no wrap semantics, so
    /// staying at the max is safer than rolling over to 0 which would
    /// violate the `min 1` constraint).
    ///
    /// This routine only mutates the in-memory value. Persistence and
    /// subscriber notification are the caller's responsibility — use
    /// `InteractionModel::bump_configuration_version` for the full
    /// "bump + persist + notify + dataver-bump" pass.
    pub fn bump_configuration_version(&mut self) -> u32 {
        self.configuration_version = self.configuration_version.saturating_add(1);
        self.configuration_version
    }

    /// Set the location (country code) to the given (2-character) value.
    pub fn set_location(&mut self, location: &str) {
        self.location = Some(unwrap!(String::<2>::from_str(location)));
    }

    /// Remove all basic info settings from the provided BLOB store as well as from memory
    ///
    /// # Arguments
    /// - `store`: the BLOB store to remove the settings from
    /// - `buf`: a temporary buffer to use for removing the settings
    pub fn reset_persist<S: KvBlobStore>(
        &mut self,
        mut store: S,
        buf: &mut [u8],
    ) -> Result<(), Error> {
        self.reset();

        store.remove(BASIC_INFO_KEY, buf)?;

        info!("Removed basic info settings from storage");

        Ok(())
    }

    /// Load basic info settings from the provided byte slice
    pub fn load(&mut self, data: &[u8]) -> Result<(), Error> {
        let info = Self::from_tlv(&TLVElement::new(data))?;

        self.node_label = info.node_label;
        self.location = info.location;
        self.location_type = info.location_type;
        self.local_config_disabled = info.local_config_disabled;
        self.configuration_version = info.configuration_version;
        self.device_location = info.device_location;
        self.recovery_identifier = info.recovery_identifier;
        self.unique_id = info.unique_id;

        Ok(())
    }

    /// Store the basic info settings via the provided `Persist` instance
    ///
    /// # Arguments
    /// - `persist`: the `Persist` instance to serialize the settings into
    ///
    /// Deliberately outlined (`inline(never)`): the settings' TLV
    /// serialization is sizeable, and every runtime-mutable-attribute setter
    /// ends with this call - sharing a single copy keeps it out of each
    /// attribute-dispatch path (flash size).
    #[inline(never)]
    pub fn store_persist<S: KvBlobStoreAccess>(
        &self,
        persist: &mut Persist<S>,
    ) -> Result<(), Error> {
        persist.store_tlv(BASIC_INFO_KEY, self)
    }

    /// Load all basic info settings from the provided key-value store
    pub fn load_persist<S: KvBlobStoreAccess>(&mut self, kv: S) -> Result<(), Error> {
        self.reset();

        if Persist::new(kv)
            .load(BASIC_INFO_KEY, |data| self.load(data))?
            .is_some()
        {
            info!("Loaded basic info settings from storage");
        }

        Ok(())
    }
}

impl Default for BasicInfoSettings {
    fn default() -> Self {
        Self::new()
    }
}

/// The regulatory location type of the node.
///
/// The values are the ones of the General Commissioning cluster.
#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, FromTLV, ToTLV)]
#[tlvargs(datatype = "u8")]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum RegulatoryLocationType {
    #[enumval(0)]
    Indoor = 0,
    #[enumval(1)]
    Outdoor = 1,
    #[enumval(2)]
    IndoorOutdoor = 2,
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::{BasicInfoSettings, DeviceLocation};

    use crate::tlv::{Nullable, TLVElement, TLVTag, ToTLV};
    use crate::utils::storage::WriteBuf;

    /// Round-trip `settings` through the persisted-blob TLV representation.
    fn round_trip(settings: &BasicInfoSettings) -> BasicInfoSettings {
        let mut buf = [0; 512];
        let mut wb = WriteBuf::new(&mut buf);
        settings.to_tlv(&TLVTag::Anonymous, &mut wb).unwrap();

        let mut loaded = BasicInfoSettings::new();
        loaded.load(wb.as_slice()).unwrap();

        loaded
    }

    /// An explicit `XX` ("unknown country") write must be stored - and
    /// persisted - verbatim: `None` means "never configured" (and lets the
    /// `Location` attribute report the `BasicInfoConfig::location` factory
    /// default), which an explicit `XX` write is not.
    #[test]
    fn explicit_xx_location_is_kept() {
        let mut settings = BasicInfoSettings::new();
        assert!(settings.location.is_none());

        settings.set_location("XX");
        assert_eq!(settings.location.as_deref(), Some("XX"));
        assert_eq!(round_trip(&settings).location.as_deref(), Some("XX"));
    }

    /// The three `device_location` states - never-written / explicit `Null` /
    /// value - must survive the persisted-blob round-trip, or an admin
    /// -written `Null` would resurrect the factory default after a reboot.
    #[test]
    fn device_location_states_survive_persistence() {
        let mut settings = BasicInfoSettings::new();
        assert!(round_trip(&settings).device_location.is_none());

        settings.device_location = Some(Nullable::none());
        let loaded = round_trip(&settings);
        assert!(matches!(&loaded.device_location, Some(l) if l.is_none()));

        settings.device_location = Some(Nullable::some(DeviceLocation {
            location_name: "Basement".try_into().unwrap(),
            floor_number: Some(-1),
            area_type: None,
        }));
        let loaded = round_trip(&settings);
        let location = loaded.device_location.unwrap().into_option().unwrap();
        assert_eq!(location.location_name, "Basement");
        assert_eq!(location.floor_number, Some(-1));
        assert_eq!(location.area_type, None);
    }

    /// Settings predating the `device_location` field (or a factory-fresh
    /// blob) must load as "never written".
    #[test]
    fn missing_device_location_field_loads_as_unset() {
        // A blob serialized without the trailing `device_location` field:
        // emulate by truncating... simpler - serialize a fresh settings
        // (which encodes the field as absent) and check the tri-state.
        let settings = BasicInfoSettings::new();
        let loaded = round_trip(&settings);
        assert!(loaded.device_location.is_none());

        // And `reset()` returns every runtime-configured value to
        // "never written", so the factory defaults apply again.
        let mut settings = BasicInfoSettings::new();
        settings.set_location("US");
        settings.location_type = Some(super::RegulatoryLocationType::Indoor);
        settings.device_location = Some(Nullable::none());
        settings.reset();
        assert!(settings.location.is_none());
        assert!(settings.location_type.is_none());
        assert!(settings.device_location.is_none());
    }

    /// The `GeneralCommissioning::RecoveryIdentifier` value must survive the
    /// persisted-blob round-trip (stable across reboots, per Matter Core Spec
    /// 11.10.6.11), load as "never minted" from a blob that predates the field,
    /// and be cleared by `reset()` so a factory reset regenerates it.
    #[test]
    fn recovery_identifier_survives_persistence_and_resets() {
        // Factory-fresh (and blobs predating the field) load as "never minted".
        let mut settings = BasicInfoSettings::new();
        assert!(settings.recovery_identifier.is_none());
        assert!(round_trip(&settings).recovery_identifier.is_none());

        // A minted value round-trips verbatim.
        settings.recovery_identifier = Some(0x1122_3344_5566_7788);
        assert_eq!(
            round_trip(&settings).recovery_identifier,
            Some(0x1122_3344_5566_7788)
        );

        // Factory reset clears it so the next read mints a fresh one.
        settings.reset();
        assert!(settings.recovery_identifier.is_none());
    }

    /// The `BasicInformation::UniqueID` value must survive the persisted-blob
    /// round-trip, load as "never minted" from a blob that predates the
    /// field, and be cleared by `reset()`, as a factory reset must give the
    /// device a new one.
    #[test]
    fn unique_id_survives_persistence_and_resets() {
        let mut settings = BasicInfoSettings::new();
        assert!(settings.unique_id.is_none());
        assert!(round_trip(&settings).unique_id.is_none());

        settings.recovery_identifier = Some(1);
        settings.unique_id = Some(0x0123_4567_89AB_CDEF);
        let loaded = round_trip(&settings);
        assert_eq!(loaded.unique_id, Some(0x0123_4567_89AB_CDEF));
        assert_eq!(loaded.recovery_identifier, Some(1));

        settings.reset();
        assert!(settings.unique_id.is_none());
    }

    // Silence unused-import lint on no-test builds
    #[allow(unused)]
    fn _t(_: TLVElement) {}
}