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
/*
 *
 *    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.
 */

//! Native Rust implementation of the Matter protocol by CSA-IOT.
//!
//! This crate implements the Matter specification that can be run on embedded devices
//! to build Matter-compatible smart-home/IoT devices.
//!
//! Look at the examples project in the workspace for example applications built using this crate, and the tests directory for unit tests.
//!
//! Start off exploring by going to the [Matter] object.
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(async_fn_in_trait)]
#![allow(unknown_lints)]
#![allow(clippy::uninlined_format_args)]
#![recursion_limit = "1024"]

use crate::crypto::Crypto;
use crate::dm::clusters::basic_info::{
    self, BasicInfoConfig, BasicInfoSettings, FULL_CLUSTER as BASIC_INFO_CLUSTER,
};
use crate::dm::clusters::dev_att::DeviceAttestation;
use crate::dm::clusters::time_sync::Rtc;
use crate::dm::endpoints::ROOT_ENDPOINT_ID;
use crate::dm::AttrChangeNotifier;
use crate::error::{Error, ErrorCode};
use crate::fabric::Fabrics;
use crate::failsafe::FailSafe;
use crate::pairing::qr::{
    no_optional_data, CommFlowType, NoOptionalData, Qr, QrPayload, QrTextType,
};
use crate::pairing::DiscoveryCapabilities;
use crate::persist::{KvBlobStore, KvBlobStoreAccess, Persist, BASIC_INFO_KEY};
use crate::sc::pase::spake2p::{Spake2pVerifierPassword, SPAKE2P_VERIFIER_SALT_ZEROED};
use crate::sc::pase::Pase;
use crate::transport::network::MatterLocalService;
use crate::transport::network::{NetworkMulticast, NetworkReceive, NetworkSend};
use crate::transport::session::Sessions;
use crate::transport::{
    PacketBufferExternalAccess, Transport, TransportRunner, MAX_RX_BUF_SIZE, MAX_TX_BUF_SIZE,
};
use crate::utils::cell::RefCell;
use crate::utils::init::{init, Init};
use crate::utils::storage::pooled::Buffers;
use crate::utils::sync::blocking::Mutex;

use rand_core::RngCore;

#[cfg(feature = "alloc")]
extern crate alloc;

// This mod MUST go first, so that the others see its macros.
pub(crate) mod fmt;

pub mod acl;
pub mod attest;
pub mod bdx;
pub mod cert;
pub mod crypto;
pub mod dm;
pub mod error;
pub mod fabric;
pub mod failsafe;
pub mod group_keys;
pub mod im;
pub mod onboard;
pub mod pairing;
pub mod persist;
pub mod respond;
pub mod sc;
pub mod tlv;
pub mod transport;
pub mod utils;

/// Re-export several crates
///
/// This is necessary for crates used in the code generated by the proc-macros
pub mod reexport {
    pub use bitflags;
    #[cfg(feature = "defmt")]
    pub use defmt;
    #[cfg(feature = "log")]
    pub use log;
    pub use strum;
}

#[cfg(feature = "alloc")]
#[macro_export]
macro_rules! alloc {
    ($val:expr) => {
        alloc::boxed::Box::new($val)
    };
}

#[cfg(not(feature = "alloc"))]
#[macro_export]
macro_rules! alloc {
    ($val:expr) => {
        $val
    };
}

/// The Matter UDP port
pub const MATTER_PORT: u16 = 5540;

/// Device basic commissioning data
#[derive(Debug, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct BasicCommData {
    /// The password which is necessary to authenticate the device in either
    /// initial commissioning, or when the basic commissioning window is opened
    pub password: Spake2pVerifierPassword,
    /// The 12-bit discriminator used to differentiate between multiple devices
    pub discriminator: u16,
}

/// The primary Matter Object
pub struct Matter<'a> {
    /// The internal state of the Matter Object, protected by a mutex for concurrent access from different threads and async tasks.
    state: Mutex<RefCell<MatterState>>,
    /// The transport state of the Matter Object
    transport: Transport,
    /// The basic information configuration for this Matter device
    dev_det: &'a BasicInfoConfig<'a>,
    /// The basic commissioning data for this Matter device
    dev_comm: BasicCommData,
    /// The device attestation data fetcher for this Matter device
    dev_att: &'a dyn DeviceAttestation,
    /// The port number on which the Matter stack will listen for incoming connections
    port: u16,
    /// The scratch buffer used by the key-value persistence machinery for
    /// (de)serializing BLOBs. Behind a blocking mutex so [`Matter::kv`] can
    /// recombine it with the user's raw [`KvBlobStore`](crate::persist::KvBlobStore)
    /// into a full [`KvBlobStoreAccess`](crate::persist::KvBlobStoreAccess). Its
    /// size is set by the `kv-blob-store-*` Cargo features (see
    /// [`KV_BUF_SIZE`](crate::persist::KV_BUF_SIZE)).
    kv_buf: Mutex<RefCell<[u8; crate::persist::KV_BUF_SIZE]>>,
}

impl<'a> Matter<'a> {
    /// Create a new Matter object.
    ///
    /// # Parameters
    /// * dev_det: An object of type [BasicInfoConfig].
    /// * dev_comm: An object of type [BasicCommData]. This object contains the basic commissioning
    ///   data required for the device.
    /// * dev_att: An object that implements the trait [DevAttDataFetcher]. Any Matter device
    ///   requires a set of device attestation certificates and keys. It is the responsibility of
    ///   this object to return the device attestation details when queried upon.
    /// * port: The port number on which the Matter stack will listen for incoming connections.
    #[inline(always)]
    pub const fn new(
        dev_det: &'a BasicInfoConfig<'a>,
        dev_comm: BasicCommData,
        dev_att: &'a dyn DeviceAttestation,
        port: u16,
    ) -> Self {
        Self {
            state: Mutex::new(RefCell::new(MatterState::new())),
            transport: Transport::new(dev_det),
            dev_det,
            dev_comm,
            dev_att,
            port,
            kv_buf: Mutex::new(RefCell::new([0; crate::persist::KV_BUF_SIZE])),
        }
    }

    /// Create an in-place initializer for a Matter object.
    ///
    /// # Parameters
    /// * dev_det: An object of type [BasicInfoConfig].
    /// * dev_comm: An object of type [BasicCommData]. This object contains the basic commissioning
    ///   data required for the device.
    /// * dev_att: An object that implements the trait [DevAttDataFetcher]. Any Matter device
    ///   requires a set of device attestation certificates and keys. It is the responsibility of
    ///   this object to return the device attestation details when queried upon.
    /// * port: The port number on which the Matter stack will listen for incoming connections.
    pub fn init(
        dev_det: &'a BasicInfoConfig<'a>,
        dev_comm: BasicCommData,
        dev_att: &'a dyn DeviceAttestation,
        port: u16,
    ) -> impl Init<Self> {
        init!(
            Self {
                state <- Mutex::init(RefCell::init(MatterState::init())),
                transport <- Transport::init(dev_det),
                dev_det,
                dev_comm,
                dev_att,
                port,
                kv_buf <- Mutex::init(RefCell::init(crate::utils::init::zeroed())),
            }
        )
    }

    pub fn dev_det(&self) -> &BasicInfoConfig<'_> {
        self.dev_det
    }

    pub fn dev_att(&self) -> &dyn DeviceAttestation {
        self.dev_att
    }

    pub fn dev_comm(&self) -> &BasicCommData {
        &self.dev_comm
    }

    pub fn port(&self) -> u16 {
        self.port
    }

    /// Combine a user-provided raw [`KvBlobStore`] with the scratch buffer owned
    /// by this `Matter` object to obtain a full [`KvBlobStoreAccess`].
    ///
    /// This is the single entry point for persistence: the application passes its
    /// raw store (sync `load`/`store`/`remove`) and gets back an access object
    /// that recombines it with `Matter`'s feature-sized scratch buffer (see
    /// [`KV_BUF_SIZE`](crate::persist::KV_BUF_SIZE)). The returned value is then
    /// lent (by `&`) to [`Matter::load_persist`], [`Matter::reset_persist`],
    /// [`InteractionModelState::load_persist`](crate::im::InteractionModelState::load_persist)
    /// and [`InteractionModel::new`](crate::im::InteractionModel::new).
    ///
    /// # Arguments
    /// - `store` - the raw [`KvBlobStore`] implementation to wrap
    pub fn kv<'s, S: KvBlobStore + 's>(&'s self, store: S) -> impl KvBlobStoreAccess + 's {
        crate::persist::SharedKvBlobStore::new(store, &self.kv_buf)
    }

    /// Get a reference to the transport state of this Matter object.
    ///
    /// All transport-related state and operations (mDNS change/resolve
    /// rendezvous, session/group notifications, RX/TX buffers, exchange
    /// initiation/acceptance) live on [`Transport`].
    #[inline(always)]
    pub const fn transport(&self) -> &Transport {
        &self.transport
    }

    pub fn transport_rx_buffer(&self) -> PacketBufferExternalAccess<'_, MAX_RX_BUF_SIZE> {
        self.transport().rx_buffer()
    }

    pub fn transport_tx_buffer(&self) -> PacketBufferExternalAccess<'_, MAX_TX_BUF_SIZE> {
        self.transport().tx_buffer()
    }

    /// A utility method to replace the initial Device Attestation with another one.
    pub fn replace_dev_att(&mut self, dev_att: &'a dyn DeviceAttestation) {
        self.dev_att = dev_att;
    }

    /// Print the standard QR code text to the console
    ///
    /// The printed QR code text corresponds to the standard commissioning flow (i.e. `CommFlowType::Standard`)
    /// and contains no optional data.
    ///
    /// This method is useful primarily during development, when the Matter device is
    /// attached to a console. It is expected that the developer will call this method prior to running the Matter transport.
    ///
    /// # Arguments
    /// - `disc_caps`: The discovery capabilities to be used in the QR code payload
    pub fn print_standard_qr_text(&self, disc_caps: DiscoveryCapabilities) -> Result<(), Error> {
        let rx_buf = self.transport().rx_buffer();

        let mut buf = rx_buf.get_immediate().ok_or(ErrorCode::NoMemory)?;
        let buf = &mut *buf;

        let payload = self.standard_qr_payload(disc_caps)?;

        let (text, _) = payload.as_str(buf)?;

        // Do not remove this logging line or change its formatting.
        // C++ E2E tests rely on this log line to grep the QR code
        info!("SetupQRCode: [{}]", text);

        Ok(())
    }

    /// Print the standard QR code to the console
    ///
    /// The printed QR code corresponds to the standard commissioning flow (i.e. `CommFlowType::Standard`)
    /// and contains no optional data.
    ///
    /// This method is useful primarily during development, when the Matter device is
    /// attached to a console. It is expected that the developer will call this method prior to running the Matter transport.
    ///
    /// # Arguments
    /// - `text_type`: The type of text representation to use when printing the QR code
    /// - `disc_caps`: The discovery capabilities to be used in the QR code payload
    pub fn print_standard_qr_code(
        &self,
        text_type: QrTextType,
        disc_caps: DiscoveryCapabilities,
    ) -> Result<(), Error> {
        // Also print the pairing code for convenience
        info!(
            "PairingCode: [{}]",
            self.dev_comm.compute_pretty_pairing_code()
        );

        let rx_buf = self.transport().rx_buffer();

        let mut buf = rx_buf.get_immediate().ok_or(ErrorCode::NoMemory)?;
        let buf = &mut *buf;

        let payload = self.standard_qr_payload(disc_caps)?;

        let (text, buf) = payload.as_str(buf)?;

        let (tmp_buf, out_buf) = buf.split_at_mut(buf.len() / 2);

        let qr = Qr::compute(text, tmp_buf, out_buf)?;

        const BORDER_SIZE: u8 = 4;

        for y in qr.lines_range(text_type, BORDER_SIZE) {
            info!(
                "{}",
                qr.line_as_str(text_type, BORDER_SIZE, false, false, y, tmp_buf)?
                    .0
            );
        }

        Ok(())
    }

    /// Return the standard QR code payload
    ///
    /// The returned QR code payload corresponds to the standard commissioning flow (i.e. `CommFlowType::Standard`)
    /// and contains no optional data.
    ///
    /// # Arguments
    /// - `disc_caps`: The discovery capabilities to be used in the QR code payload
    fn standard_qr_payload(
        &self,
        disc_caps: DiscoveryCapabilities,
    ) -> Result<QrPayload<'_, NoOptionalData>, Error> {
        let payload = QrPayload::new_from_basic_info(
            disc_caps,
            CommFlowType::Standard,
            self.dev_comm.clone(),
            self.dev_det,
            no_optional_data as _,
        );

        Ok(payload)
    }

    /// Return `true` if there is at least one commissioned fabric
    //
    // TODO:
    // The implementation of this method needs to change in future,
    // because the current implementation does not really track whether
    // `CommissioningComplete` had been actually received for the fabric.
    //
    // The fabric is created once we receive `AddNoc`, but that's just
    // not enough. The fabric should NOT be considered commissioned until
    // after we receive `CommissioningComplete` on behalf of a Case session
    // for the fabric in question.
    pub fn is_commissioned(&self) -> bool {
        self.with_state(|state| state.fabrics.iter().count() > 0)
    }

    /// Open a basic commissioning window
    ///
    /// The method will return an error if the commissioning window cannot be opened
    /// (due to another window already being opened, for example).
    ///
    /// # Arguments
    /// - `timeout_secs`: The timeout in seconds for the basic commissioning window
    ///
    /// **Note:** This is the low-level building block that mutates PASE
    /// state and routes a `notify_cluster_changed(...)` to subscribers
    /// via `notify`, but does **not** bump the per-cluster `Dataver` of
    /// `AdministratorCommissioning` — a subsequent dataver-filtered
    /// read could therefore cache-hit and miss the change. Application
    /// code that holds a `InteractionModel` should prefer
    /// [`crate::im::InteractionModel::open_basic_comm_window`], which delegates
    /// here and additionally bumps dataver via its
    /// [`AttrChangeNotifier`] impl.
    pub fn open_basic_comm_window<C: Crypto>(
        &self,
        timeout_secs: u16,
        crypto: C,
        notify: &dyn AttrChangeNotifier,
    ) -> Result<(), Error> {
        let notify_mdns = || self.transport().notify_mdns_changed();
        let notify_change = |endpt_id, clust_id| notify.notify_cluster_changed(endpt_id, clust_id);

        self.with_state(|state| {
            let mut rand = crypto.rand()?;

            let mdns_id = rand.next_u64();

            let mut salt = SPAKE2P_VERIFIER_SALT_ZEROED;
            rand.fill_bytes(salt.access_mut());

            state.pase.open_basic_comm_window(
                mdns_id,
                salt.access(),
                self.dev_comm.password.reference(),
                self.dev_comm.discriminator,
                timeout_secs,
                None,
                notify_mdns,
                notify_change,
            )
        })
    }

    /// Close the commissioning window (basic or other)
    ///
    /// The method will return Ok(false) if there is no active PASE commissioning window to close.
    ///
    /// **Note:** As with [`Matter::open_basic_comm_window`], this does
    /// not bump the per-cluster `Dataver` of
    /// `AdministratorCommissioning`. Prefer
    /// [`crate::im::InteractionModel::close_comm_window`] when a `InteractionModel`
    /// is available.
    pub fn close_comm_window(&self, notify: &dyn AttrChangeNotifier) -> Result<bool, Error> {
        let notify_mdns = || self.transport().notify_mdns_changed();
        let notify_change = |endpt_id, clust_id| notify.notify_cluster_changed(endpt_id, clust_id);

        self.with_state(|state| state.pase.close_comm_window(notify_mdns, notify_change))
    }

    /// Bump `BasicInformation::ConfigurationVersion` by one, persist
    /// the new value via `kv`, and route an attribute-change
    /// notification to subscribers via `notify`.
    ///
    /// Per Matter Core Spec, the device MUST bump
    /// this attribute on any change to its exposed fixed-quality
    /// surface (a firmware update that adds or removes functionality,
    /// internal reconfiguration that changes any `F`-quality attribute,
    /// bridged-node add/remove on a bridge). `rs-matter` cannot detect
    /// such events on its own — the application drives the bump.
    ///
    /// **Note:** Like the other low-level mutators on `Matter`, this
    /// does **not** bump the per-cluster `Dataver` of
    /// `BasicInformation`. A subsequent dataver-filtered read could
    /// therefore cache-hit and miss the change. Application code that
    /// holds a `InteractionModel` should prefer
    /// [`crate::im::InteractionModel::bump_configuration_version`], which
    /// delegates here and additionally bumps dataver via its
    /// [`AttrChangeNotifier`] impl.
    ///
    /// Returns the new `ConfigurationVersion` value.
    pub fn bump_configuration_version<S: KvBlobStoreAccess>(
        &self,
        kv: S,
        notify: &dyn AttrChangeNotifier,
    ) -> Result<u32, Error> {
        let mut persist = Persist::new(kv);

        let new_version = self.with_state(|state| {
            let new_version = state.basic_info_settings.bump_configuration_version();

            persist.store_tlv(BASIC_INFO_KEY, &state.basic_info_settings)?;

            notify.notify_attr_changed(
                ROOT_ENDPOINT_ID,
                BASIC_INFO_CLUSTER.id,
                basic_info::AttributeId::ConfigurationVersion as _,
            );

            Ok::<_, Error>(new_version)
        })?;

        persist.run()?;

        Ok(new_version)
    }

    /// Create a new transport runner instance
    pub fn transport_runner<C: Crypto>(&self, crypto: C) -> TransportRunner<'_, C> {
        TransportRunner::new(self, crypto)
    }

    /// Run the Matter transport layer.
    ///
    /// # Arguments
    /// - `crypto`: The crypto backend
    /// - `send`: The network send interface
    /// - `recv`: The network receive interface
    /// - `multicast`: The multicast network interface (for receiving groupcast messages)
    ///   When running on top of non-IP networks like BLE pass a no-op implementation like `NoNetwork` here and the multicast functionality will be disabled.
    pub async fn run<C, S, R, M>(
        &self,
        crypto: C,
        send: S,
        recv: R,
        multicast: M,
    ) -> Result<(), Error>
    where
        C: Crypto,
        S: NetworkSend,
        R: NetworkReceive,
        M: NetworkMulticast,
    {
        let mut transport_runner = self.transport_runner(crypto);

        transport_runner.run(send, recv, multicast).await
    }

    /// Access the Matter state by invoking a closure with a mutable reference to the state.
    pub fn with_state<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut MatterState) -> R,
    {
        self.state.lock(|state| {
            let mut state = state.borrow_mut();
            f(&mut state)
        })
    }

    /// Access the Real-Time-clock by invoking a closure with a mutable reference to it.
    pub fn with_rtc<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut Rtc) -> R,
    {
        self.with_state(|state| f(&mut state.rtc))
    }

    /// Reset the transport layer by clearing all sessions, exchanges, the RX buffer and the TX buffer
    /// NOTE: User should be careful _not_ to call this method while the transport layer and/or the built-in mDNS is running.
    pub fn reset_transport(&self) -> Result<(), Error> {
        self.with_state(|state| {
            state.sessions.reset();

            self.transport().reset()
        })
    }

    /// Reset the Matter persistable state by removing all fabrics and resetting basic info settings
    ///
    /// Arguments:
    /// - `kv`: The key-value store access (obtained via [`Matter::kv`]) to remove the fabrics
    ///   and basic info settings from. Provides both the store and the scratch buffer.
    pub async fn reset_persist<K: KvBlobStoreAccess>(&self, kv: K) -> Result<(), Error> {
        self.with_state(|state| {
            // The KV ops are sync, so do them all inside a single `access` closure.
            kv.access(|mut store, buf| {
                state.fabrics.reset_persist(&mut store, buf)?;
                state.basic_info_settings.reset_persist(&mut store, buf)?;
                state.rtc.reset_persist(&mut store, buf)?;

                Ok::<_, Error>(())
            })
        })?;

        self.transport().notify_mdns_changed();

        Ok(())
    }

    /// Load fabrics from the given data
    ///
    /// Arguments:
    /// - `kv`: The key-value store access (obtained via [`Matter::kv`]) to load the fabrics
    ///   and basic info settings from. Provides both the store and the scratch buffer.
    pub async fn load_persist<K: KvBlobStoreAccess>(&self, kv: K) -> Result<(), Error> {
        self.with_state(|state| {
            // The KV ops are sync, so do them all inside a single `access` closure.
            kv.access(|mut store, buf| {
                state.fabrics.load_persist(&mut store, buf)?;
                state.basic_info_settings.load_persist(&mut store, buf)?;
                state.rtc.load_persist(&mut store, buf)?;

                Ok::<_, Error>(())
            })
        })?;

        self.transport().notify_mdns_changed();

        Ok(())
    }

    /// Invoke the given closure for each currently published Matter mDNS service.
    pub fn mdns_services<F>(&self, mut f: F) -> Result<(), Error>
    where
        F: FnMut(MatterLocalService) -> Result<(), Error>,
    {
        debug!("=== Currently published mDNS services");

        self.with_state(|state| {
            if let Some(comm_window) = state.pase.comm_window() {
                // Do not remove this logging line or change its formatting.
                // C++ E2E tests rely on this log line to determine when the mDNS service is published
                debug!("mDNS service published: {:?}", comm_window.mdns_service());

                f(comm_window.mdns_service())?;
            }

            for fabric in state.fabrics.iter() {
                if let Some(service) = fabric.mdns_service() {
                    // Do not remove this logging line or change its formatting.
                    // C++ E2E tests rely on this log line to determine when the mDNS service is published
                    debug!("mDNS service published: {:?}", service);

                    f(service)?;
                }
            }

            debug!("===");

            Ok(())
        })
    }
}

/// The internal state of the Matter Object
///
/// Public for unit tests.
pub struct MatterState {
    /// All fabrics
    ///
    /// Public for unit tests
    pub fabrics: Fabrics,
    /// All sessions
    sessions: Sessions,
    /// The PASE session state
    pase: Pase,
    /// The Failsafe state
    failsafe: FailSafe,
    /// The mutable basic information settings
    basic_info_settings: BasicInfoSettings,
    /// Real Time Clock state and Last-Known-Good UTC Time tracking (Matter Core spec).
    rtc: Rtc,
}

impl MatterState {
    /// Create a new instance of MatterState
    #[inline(always)]
    const fn new() -> Self {
        Self {
            fabrics: Fabrics::new(),
            sessions: Sessions::new(),
            pase: Pase::new(),
            failsafe: FailSafe::new(),
            basic_info_settings: BasicInfoSettings::new(),
            rtc: Rtc::new(),
        }
    }

    /// Return an in-place initializer for MatterState
    fn init() -> impl Init<Self> {
        init!(Self {
            fabrics <- Fabrics::init(),
            sessions <- Sessions::init(),
            pase <- Pase::init(),
            failsafe <- FailSafe::init(),
            basic_info_settings <- BasicInfoSettings::init(),
            rtc <- Rtc::init(),
        })
    }
}

#[cfg(test)]
pub mod test {
    use crate::Matter;

    pub fn test_matter() -> Matter<'static> {
        Matter::new(
            &crate::dm::devices::test::TEST_DEV_DET,
            crate::dm::devices::test::TEST_DEV_COMM,
            &crate::dm::devices::test::TEST_DEV_ATT,
            0,
        )
    }
}