rs-matter 0.3.0

Native Rust implementation of the Matter (Smart-Home) ecosystem
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
/*
 *
 *    Copyright (c) 2022-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.
 */

//! This module contains the implementation of the Basic Information cluster and its handler.

use core::str::FromStr;

use crate::dm::{Cluster, Dataver, InvokeContext, ReadContext, WriteContext};
use crate::error::{Error, ErrorCode};
use crate::fabric::MAX_FABRICS;
use crate::persist::{KvBlobStore, KvBlobStoreAccess, Persist, BASIC_INFO_KEY};
use crate::tlv::{
    FromTLV, Nullable, NullableBuilder, TLVBuilderParent, TLVElement, ToTLV, Utf8StrBuilder,
};
use crate::transport::exchange::Exchange;
use crate::transport::session::MAX_SESSIONS;
use crate::utils::bitflags::bitflags;
use crate::utils::init::{init, Init};
use crate::{except, with};

pub use crate::dm::clusters::decl::basic_information::*;
pub use crate::dm::clusters::decl::general_commissioning::RegulatoryLocationTypeEnum;
pub use crate::dm::clusters::decl::globals::{
    AreaTypeTag, LocationDescriptorStruct, LocationDescriptorStructBuilder,
};

/// 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 5, which is enough to support typical batched invokes while
/// keeping the in-memory CommandRef tracking buffer in `dm::invoke()` small.
pub const DEFAULT_MAX_PATHS_PER_INVOKE: u16 = 5;

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.
    pub area_type: Option<AreaTypeTag>,
}

/// 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 64 characters)
    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, defaults to 5000
    ///
    /// 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 sii: Option<u32>,
    /// Whether the device supports TCP transport.
    ///
    /// Not a real attribute; advertised via the `T` TXT record key in mDNS.
    /// Per the Matter Core Spec, `T` is a bitmap: bit 2 (value 4)
    /// indicates TCP server support. Required for large payloads such as WebRTC SDP
    /// exchanges and camera snapshots.
    pub tcp_supported: bool,
}

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,
            tcp_supported: false,
        }
    }
}

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`](crate::im::subscriptions::DEFAULT_MAX_SUBSCRIPTIONS)),
/// 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;
/// Constraint is `3 to 10000`; see Core spec 2.11.2.2 "Subscribe Interaction Limits".
const SUBSCRIBE_PATHS_SUPPORTED: u16 = 3;

impl CapabilityMinima {
    /// Create a default instance of `CapabilityMinima`, with CASE sessions per
    /// fabric derived from the session table and the spec-minimum subscriptions
    /// per fabric.
    pub const fn new() -> Self {
        Self {
            case_sessions_per_fabric: (MAX_SESSIONS / MAX_FABRICS) 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: ProductFinishEnum,
    /// Product primary color
    pub color: Option<ColorEnum>,
}

impl ProductAppearance {
    /// Create a default instance of `ProductAppearance`,
    /// with `Other` finish and no color.
    pub const fn new() -> Self {
        Self {
            finish: ProductFinishEnum::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: heapless::String<128>,
    /// Floor number, when applicable; `Null` on the wire when `None`.
    pub floor_number: Option<i16>,
    /// Area type from the common Area namespace; `Null` on the wire when
    /// `None`.
    pub area_type: Option<AreaTypeTag>,
}

impl DeviceLocation {
    /// Create an empty `DeviceLocation` (empty location name, no floor
    /// number, no area type).
    pub const fn new() -> Self {
        Self {
            location_name: heapless::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: heapless::String<32>, // Max node-label as per the spec
    pub location: Option<heapless::String<2>>, // Max location as per the spec
    /// The regulatory location type, as set via
    /// `GeneralCommissioning::SetRegulatoryConfig`.
    pub location_type: Option<RegulatoryLocationTypeEnum>,
    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.
    ///
    /// NOTE: keep this field *last* - the persisted-blob TLV tags are
    /// positional, and appending preserves compatibility with blobs written
    /// before the field existed.
    pub recovery_identifier: Option<u64>,
}

impl BasicInfoSettings {
    /// Create a new instance of `BasicInfoSettings`
    pub const fn new() -> Self {
        Self {
            node_label: heapless::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,
        }
    }

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

    /// 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!(heapless::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;

        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 BLOB store
    ///
    /// # Arguments
    /// - `store`: the BLOB store to load the fabrics from
    /// - `buf`: a temporary buffer to use for loading the fabrics
    pub fn load_persist<S: KvBlobStore>(
        &mut self,
        mut store: S,
        buf: &mut [u8],
    ) -> Result<(), Error> {
        self.reset();

        if let Some(data) = store.load(BASIC_INFO_KEY, buf)? {
            self.load(data)?;

            info!("Loaded basic info settings from storage");
        }

        Ok(())
    }
}

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

/// The system implementation of a handler for the Basic Information Matter cluster.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct BasicInfoHandler(Dataver);

impl BasicInfoHandler {
    /// Create a new instance of `BasicInfoHandler` with the given `Dataver`
    pub fn new(dataver: Dataver) -> Self {
        Self(dataver)
    }

    /// Adapt the handler instance to the generic `rs-matter` `Handler` trait
    pub const fn adapt(self) -> HandlerAdaptor<Self> {
        HandlerAdaptor(self)
    }

    fn config<'a>(exchange: &'a Exchange) -> &'a BasicInfoConfig<'a> {
        exchange.matter().dev_det()
    }

    fn with_settings<F, R>(exchange: &Exchange, f: F) -> Result<R, Error>
    where
        F: FnOnce(&mut BasicInfoSettings) -> Result<R, Error>,
    {
        exchange.with_state(|state| f(&mut state.basic_info_settings))
    }
}

/// `BasicInformation` cluster metadata that additionally advertises the
/// provisional `DeviceLocation` attribute (admin-writable, persisted in
/// [`BasicInfoSettings`]).
///
/// Use this in place of [`BasicInfoHandler::CLUSTER`] to serve the attribute -
/// the handler itself always implements it. It is deliberately not the
/// default: the attribute is provisional, and reference test suites that pin
/// `BasicInformation::AttributeList` to an exact set reject its presence.
///
/// The initial value is `Null`; set [`BasicInfoConfig::device_location`] for
/// a device whose location is factory-provisioned.
pub const CLUSTER_DEVICE_LOCATION: Cluster<'static> = FULL_CLUSTER
    .with_attrs(except!(AttributeId::Reachable))
    .with_cmds(with!());

impl ClusterHandler for BasicInfoHandler {
    const CLUSTER: Cluster<'static> = FULL_CLUSTER
        // Hide `Reachable` (TODO) from the default metadata.
        //
        // `DeviceLocation` IS implemented (see `device_location` /
        // `set_device_location` below) but stays out of the default metadata
        // because it is provisional: upstream's reference apps do not
        // advertise it, and test suites that pin `AttributeList` to an exact
        // set (e.g. the `TestBasicInformation` YAML) reject its presence.
        // Opt in with [`CLUSTER_DEVICE_LOCATION`].
        .with_attrs(except!(
            AttributeId::Reachable | AttributeId::DeviceLocation
        ))
        .with_cmds(with!());

    fn dataver(&self) -> u32 {
        self.0.get()
    }

    fn dataver_changed(&self) {
        self.0.changed();
    }

    fn data_model_revision(&self, ctx: impl ReadContext) -> Result<u16, Error> {
        Ok(Self::config(ctx.exchange()).data_model_revision)
    }

    fn vendor_id(&self, ctx: impl ReadContext) -> Result<u16, Error> {
        Ok(Self::config(ctx.exchange()).vid)
    }

    fn vendor_name<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        out: Utf8StrBuilder<P>,
    ) -> Result<P, Error> {
        out.set(Self::config(ctx.exchange()).vendor_name)
    }

    fn product_id(&self, ctx: impl ReadContext) -> Result<u16, Error> {
        Ok(Self::config(ctx.exchange()).pid)
    }

    fn product_name<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        out: Utf8StrBuilder<P>,
    ) -> Result<P, Error> {
        out.set(Self::config(ctx.exchange()).product_name)
    }

    fn hardware_version(&self, ctx: impl ReadContext) -> Result<u16, Error> {
        Ok(Self::config(ctx.exchange()).hw_ver)
    }

    fn hardware_version_string<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        out: Utf8StrBuilder<P>,
    ) -> Result<P, Error> {
        out.set(Self::config(ctx.exchange()).hw_ver_str)
    }

    fn software_version(&self, ctx: impl ReadContext) -> Result<u32, Error> {
        Ok(Self::config(ctx.exchange()).sw_ver)
    }

    fn software_version_string<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        out: Utf8StrBuilder<P>,
    ) -> Result<P, Error> {
        out.set(Self::config(ctx.exchange()).sw_ver_str)
    }

    fn node_label<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        out: Utf8StrBuilder<P>,
    ) -> Result<P, Error> {
        Self::with_settings(ctx.exchange(), |settings| {
            out.set(settings.node_label.as_str())
        })
    }

    fn set_node_label(&self, ctx: impl WriteContext, label: &str) -> Result<(), Error> {
        if label.len() > 32 {
            return Err(ErrorCode::ConstraintError.into());
        }

        let mut persist = Persist::new(ctx.kv());

        Self::with_settings(ctx.exchange(), |settings| {
            settings.node_label.clear();
            settings
                .node_label
                .push_str(label)
                .map_err(|_| ErrorCode::ConstraintError)?;

            settings.store_persist(&mut persist)
        })?;

        persist.run()
    }

    fn location<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        out: Utf8StrBuilder<P>,
    ) -> Result<P, Error> {
        // Until a value is set at runtime (`Location` write /
        // `SetRegulatoryConfig`), report the factory default from
        // `BasicInfoConfig`, falling back to the "unknown" country code.
        let config = Self::config(ctx.exchange());

        Self::with_settings(ctx.exchange(), |settings| {
            out.set(
                settings
                    .location
                    .as_deref()
                    .or(config.location)
                    .unwrap_or("XX"),
            )
        })
    }

    fn set_location(&self, ctx: impl WriteContext, location: &str) -> Result<(), Error> {
        if location.len() != 2 {
            return Err(ErrorCode::ConstraintError.into());
        }

        let mut persist = Persist::new(ctx.kv());

        Self::with_settings(ctx.exchange(), |settings| {
            settings.set_location(location);

            settings.store_persist(&mut persist)
        })?;

        persist.run()
    }

    fn capability_minima<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        builder: CapabilityMinimaStructBuilder<P>,
    ) -> Result<P, Error> {
        let cm = Self::config(ctx.exchange()).capability_minima;

        builder
            .case_sessions_per_fabric(cm.case_sessions_per_fabric)?
            .subscriptions_per_fabric(cm.subscriptions_per_fabric)?
            .simultaneous_invocations_supported(Some(cm.simultaneous_invocations_supported))?
            .simultaneous_writes_supported(Some(cm.simultaneous_writes_supported))?
            .read_paths_supported(Some(cm.read_paths_supported))?
            .subscribe_paths_supported(Some(cm.subscribe_paths_supported))?
            .end()
    }

    fn specification_version(&self, ctx: impl ReadContext) -> Result<u32, Error> {
        Ok(Self::config(ctx.exchange()).specification_version)
    }

    fn max_paths_per_invoke(&self, ctx: impl ReadContext) -> Result<u16, Error> {
        Ok(Self::config(ctx.exchange()).max_paths_per_invoke)
    }

    fn configuration_version(&self, ctx: impl ReadContext) -> Result<u32, Error> {
        // Non-volatile, runtime-mutable. Lives in `BasicInfoSettings`,
        // bumped via `InteractionModel::bump_configuration_version`.
        Self::with_settings(
            ctx.exchange(),
            |settings| Ok(settings.configuration_version),
        )
    }

    // Deliberately outlined (`inline(never)`): inlining duplicates the
    // builder chain in every read-dispatch instantiation (flash size)
    #[inline(never)]
    fn device_location<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        builder: NullableBuilder<P, LocationDescriptorStructBuilder<P>>,
    ) -> Result<P, Error> {
        let config = Self::config(ctx.exchange());

        Self::with_settings(ctx.exchange(), |settings| {
            // An admin-written value - including an explicitly-written `Null`
            // - takes precedence; until one exists, report the factory
            // default from `BasicInfoConfig`, falling back to `Null`.
            let (location_name, floor_number, area_type) = match settings.device_location.as_ref() {
                Some(location) => match location.as_opt_ref() {
                    Some(location) => (
                        location.location_name.as_str(),
                        location.floor_number,
                        location.area_type,
                    ),
                    None => return builder.null(),
                },
                None => match config.device_location {
                    Some(location) => (
                        location.location_name,
                        location.floor_number,
                        location.area_type,
                    ),
                    None => return builder.null(),
                },
            };

            builder
                .non_null()?
                .location_name(location_name)?
                .floor_number(Nullable::new(floor_number))?
                .area_type(Nullable::new(area_type))?
                .end()
        })
    }

    // Deliberately outlined (`inline(never)`): cold path with sizeable
    // TLV-parsing and persistence code (flash size)
    #[inline(never)]
    fn set_device_location(
        &self,
        ctx: impl WriteContext,
        value: Nullable<LocationDescriptorStruct<'_>>,
    ) -> Result<(), Error> {
        let mut persist = Persist::new(ctx.kv());

        Self::with_settings(ctx.exchange(), |settings| {
            if let Some(value) = value.as_opt_ref() {
                // Parse and validate everything up-front, so that a failed
                // write leaves the stored value intact
                let location_name = value.location_name()?;
                if location_name.len() > 128 {
                    return Err(ErrorCode::ConstraintError.into());
                }

                let floor_number = value.floor_number()?.into_option();
                let area_type = value.area_type()?.into_option();

                // ... and then update the stored value in-place: going
                // through an owned `DeviceLocation` temporary would move the
                // ~150-byte value several times through the stack (flash and
                // stack size)
                let location = settings.device_location.get_or_insert_with(Nullable::none);
                if location.is_none() {
                    *location = Nullable::some(DeviceLocation::new());
                }

                let location = unwrap!(location.as_opt_mut());

                location.location_name.clear();
                unwrap!(location.location_name.push_str(location_name));
                location.floor_number = floor_number;
                location.area_type = area_type;
            } else {
                settings.device_location = Some(Nullable::none());
            }

            settings.store_persist(&mut persist)
        })?;

        persist.run()
    }

    fn handle_mfg_specific_ping(&self, _ctx: impl InvokeContext) -> Result<(), Error> {
        Err(ErrorCode::CommandNotFound.into())
    }

    fn manufacturing_date<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        builder: Utf8StrBuilder<P>,
    ) -> Result<P, Error> {
        builder.set(Self::config(ctx.exchange()).manufacturing_date)
    }

    fn part_number<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        builder: Utf8StrBuilder<P>,
    ) -> Result<P, Error> {
        builder.set(Self::config(ctx.exchange()).part_number)
    }

    fn product_url<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        builder: Utf8StrBuilder<P>,
    ) -> Result<P, Error> {
        builder.set(Self::config(ctx.exchange()).product_url)
    }

    fn product_label<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        builder: Utf8StrBuilder<P>,
    ) -> Result<P, Error> {
        builder.set(Self::config(ctx.exchange()).product_label)
    }

    fn serial_number<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        builder: Utf8StrBuilder<P>,
    ) -> Result<P, Error> {
        builder.set(Self::config(ctx.exchange()).serial_no)
    }

    fn local_config_disabled(&self, ctx: impl ReadContext) -> Result<bool, Error> {
        Self::with_settings(
            ctx.exchange(),
            |settings| Ok(settings.local_config_disabled),
        )
    }

    fn set_local_config_disabled(&self, ctx: impl WriteContext, value: bool) -> Result<(), Error> {
        let mut persist = Persist::new(ctx.kv());

        Self::with_settings(ctx.exchange(), |settings| {
            settings.local_config_disabled = value;

            settings.store_persist(&mut persist)
        })?;

        persist.run()
    }

    fn unique_id<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        builder: Utf8StrBuilder<P>,
    ) -> Result<P, Error> {
        builder.set(Self::config(ctx.exchange()).unique_id)
    }

    fn product_appearance<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        builder: ProductAppearanceStructBuilder<P>,
    ) -> Result<P, Error> {
        let appearance = Self::config(ctx.exchange()).product_appearance;

        builder
            .finish(appearance.finish)?
            .primary_color(Nullable::new(appearance.color))?
            .end()
    }
}

#[cfg(test)]
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::RegulatoryLocationTypeEnum::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());
    }

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