rs-matter 0.2.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
/*
 *
 *    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, Persist, BASIC_INFO_KEY};
use crate::tlv::{FromTLV, Nullable, 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;

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

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

/// 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;
    }
}

/// 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,
    /// 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: "",
            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,
}

/// 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;

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,
        }
    }
}

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()
    }
}

/// 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
    pub location_type: 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,
}

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

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

    /// 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.local_config_disabled = false;
        self.configuration_version = 1;
    }

    /// 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
    }

    pub fn set_location(&mut self, location: &str) {
        if location == "XX" {
            self.location = None;
        } else {
            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;

        Ok(())
    }

    /// 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))
    }
}

impl ClusterHandler for BasicInfoHandler {
    const CLUSTER: Cluster<'static> = FULL_CLUSTER
        // Hide `Reachable` (TODO) and `ConfigurationVersion` from the default
        // metadata. `ConfigurationVersion` is provisional in Matter 1.5 and
        // upstream's 1.5 dataset (CHIP commit faf4d09ad1, "Remove
        // configuration version from 1.5 branch") explicitly excludes it from
        // `BasicInformation`'s `AttributeList`. The
        // `BasicInformation`/`BasicInfoSettings` plumbing for it stays in
        // place — read handler, persisted settings field, and the
        // `Matter::bump_configuration_version` / `InteractionModel::bump_configuration_version`
        // entry points — so a user that supplies their own cluster metadata
        // (i.e. one that drops `ConfigurationVersion` from `except!`) gets a
        // working implementation out of the box.
        .with_attrs(except!(
            AttributeId::Reachable | AttributeId::ConfigurationVersion
        ))
        .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)?;

            persist.store_tlv(BASIC_INFO_KEY, &*settings)
        })?;

        persist.run()
    }

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

    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);

            persist.store_tlv(BASIC_INFO_KEY, &*settings)
        })?;

        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)?
            .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),
        )
    }

    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;

            persist.store_tlv(BASIC_INFO_KEY, &*settings)
        })?;

        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()
    }
}