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
/*
*
* 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::icd_mgmt::OperatingModeEnum;
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};
#[cfg(feature = "case-resumption")]
use crate::sc::case::ResumableSessions;
use crate::sc::pase::spake2p::{Spake2pVerifierPassword, SPAKE2P_VERIFIER_SALT_ZEROED};
use crate::sc::pase::{CommWindowState, 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 Groupcast testing-mode bridge - shared between the transport RX
/// path, the Interaction Model's invoke processing and the Groupcast
/// cluster handler. See `dm::clusters::groupcast::TestingBridge`.
#[cfg(feature = "groups")]
groupcast_testing: crate::dm::clusters::groupcast::TestingBridge,
/// 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,
#[cfg(feature = "groups")]
groupcast_testing: crate::dm::clusters::groupcast::TestingBridge::new(),
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> {
// Two variants because the `init!` macro does not accept `#[cfg]`
// on fields
#[cfg(feature = "groups")]
{
init!(
Self {
state <- Mutex::init(RefCell::init(MatterState::init())),
transport <- Transport::init(dev_det),
dev_det,
dev_comm,
dev_att,
port,
groupcast_testing <- crate::dm::clusters::groupcast::TestingBridge::init(),
kv_buf <- Mutex::init(RefCell::init(crate::utils::init::zeroed())),
}
)
}
#[cfg(not(feature = "groups"))]
{
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
}
/// The ICD operating mode to advertise in the operational `ICD` DNS-SD TXT
/// key, or `None` when the device is not a Long-Idle-Time ICD.
pub fn icd_mode(&self) -> Option<OperatingModeEnum> {
self.with_state(|state| state.icd_mode)
}
/// Set the ICD operating mode advertised in mDNS and, if it changed, signal
/// the mDNS layer to re-publish.
pub fn set_icd_mode(&self, mode: Option<OperatingModeEnum>) {
let changed = self.with_state(|state| {
let changed = state.icd_mode != mode;
state.icd_mode = mode;
changed
});
if changed {
self.transport.notify_mdns_changed();
}
}
/// 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::startup`], [`Matter::factory_reset`]
/// 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 fabric.
///
/// Note that this is emphatically *not* "the device is commissioned": a fabric is created
/// as soon as `AddNOC` is received, which is well before the commissioner has established a
/// CASE session over the operational network and sent `CommissioningComplete`. Code that
/// needs to know whether commissioning is still in progress should use
/// [`Matter::is_comm_window_open`] instead, as the commissioning window stays open for exactly
/// that long.
pub fn has_fabrics(&self) -> bool {
self.with_state(|state| state.fabrics.iter().next().is_some())
}
/// Return the state of the commissioning window - whether one is open, and if so who
/// opened it. See [`CommWindowState`] for what the answer is good for.
pub fn comm_window_state(&self) -> CommWindowState {
self.with_state(|state| state.pase.comm_window_state())
}
/// 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();
state.basic_info_settings.store_persist(&mut persist)?;
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)
})
}
/// Return the Groupcast testing-mode bridge.
#[cfg(feature = "groups")]
pub(crate) fn groupcast_testing(&self) -> &crate::dm::clusters::groupcast::TestingBridge {
&self.groupcast_testing
}
/// 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()
})
}
/// Factory-reset the `Matter` persistable state by removing all fabrics and
/// resetting the basic info settings, the RTC state and (if compiled in) the
/// CASE resumption cache and the group data message counter - both in-memory
/// and in the provided KV store.
///
/// The counterpart of [`Matter::startup`]. Call when the node is
/// factory-reset, alongside
/// [`InteractionModel::factory_reset`](crate::im::InteractionModel::factory_reset).
///
/// 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 fn factory_reset<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)?;
#[cfg(feature = "case-resumption")]
state.resumption.reset_persist(&mut store, buf)?;
#[cfg(feature = "groups")]
state.sessions.reset_persist(&mut store, buf)?;
Ok::<_, Error>(())
})
})?;
self.transport().notify_mdns_changed();
Ok(())
}
/// Re-hydrate the `Matter` persistable state - the fabrics, the basic info
/// settings, the RTC state and (if compiled in) the CASE resumption cache
/// and the group data message counter - from the provided KV store.
///
/// Call once at startup, before the transport starts serving traffic. The
/// Data-Model counterpart is
/// [`InteractionModel::startup`](crate::im::InteractionModel::startup).
///
/// 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 fn startup<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)?;
#[cfg(feature = "case-resumption")]
state.resumption.load_persist(&mut store, buf)?;
#[cfg(feature = "groups")]
state.sessions.load_persist(&mut store, buf)?;
Ok::<_, Error>(())
})
})?;
self.transport().notify_mdns_changed();
Ok(())
}
/// Background task that flushes the CASE session resumption cache
/// to persistent storage whenever it is mutated.
///
/// The task waits for a mutation event fired by the CASE handshake
/// paths (both full handshake and resumption), sleeps for
/// `min_interval` so a burst of handshakes coalesces into one
/// write, and then serialises the current cache to `kv` under
/// [`crate::persist::CASE_RESUMPTION_KEY`].
///
/// `min_interval` therefore doubles as (a) a burst-coalescing
/// debounce and (b) a hard lower bound on the time between two
/// consecutive persists — a mutation‑storm cannot drive more than
/// one write per `min_interval` regardless of arrival rate. Pick
/// something appropriate for the underlying medium:
///
/// - POSIX / dev builds: anything from a few hundred ms upwards is
/// fine; `Duration::from_millis(500)` matches the pre‑existing
/// hard‑coded behaviour.
/// - MCU firmwares writing to internal flash: prefer tens of
/// seconds (e.g. `Duration::from_secs(30)`) so a
/// commissioner-driven wave of CASE handshakes doesn't churn the
/// flash write endurance budget. The cache is a soft cache — a
/// power cut that loses the most recent entry only forces a
/// full CASE handshake the next time the peer connects, which
/// is the same fallback any resumption failure produces.
///
/// Intended to be spawned alongside [`Matter::run`], for example
/// via `embassy_futures::select` or a dedicated executor task. It
/// never returns on the happy path — a `Result` is only produced
/// if the KV backend errors.
///
/// # Arguments
/// - `kv`: The key-value store access (obtained via [`Matter::kv`])
/// used to persist the cache. Provides both the store and the
/// scratch buffer.
/// - `min_interval`: Minimum time between two consecutive persists
/// (see above).
#[cfg(feature = "case-resumption")]
pub async fn run_persist_resumption<K: KvBlobStoreAccess>(
&self,
kv: K,
min_interval: embassy_time::Duration,
) -> Result<(), Error> {
loop {
self.transport().wait_resumption_dirty().await;
embassy_time::Timer::after(min_interval).await;
self.with_state(|state| {
kv.access(|mut store, buf| state.resumption.store_persist(&mut store, buf))
})?;
debug!("CASE session resumption cache persisted");
}
}
/// 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,
/// CASE session resumption cache
///
/// Public for unit tests
#[cfg(feature = "case-resumption")]
pub resumption: ResumableSessions,
/// 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,
/// The ICD operating mode advertised in the operational `ICD` DNS-SD TXT key.
/// The ICD Management handler keeps this in sync with its registration set.
icd_mode: Option<OperatingModeEnum>,
}
impl MatterState {
/// Create a new instance of MatterState
#[inline(always)]
const fn new() -> Self {
Self {
fabrics: Fabrics::new(),
sessions: Sessions::new(),
#[cfg(feature = "case-resumption")]
resumption: ResumableSessions::new(),
pase: Pase::new(),
failsafe: FailSafe::new(),
basic_info_settings: BasicInfoSettings::new(),
rtc: Rtc::new(),
icd_mode: None,
}
}
/// Return an in-place initializer for MatterState
// NOTE: `init!` (pinned-init) rejects `#[cfg]` on its fields, so the
// `case-resumption` field forces two full variants of this initializer.
#[cfg(feature = "case-resumption")]
fn init() -> impl Init<Self> {
init!(Self {
fabrics <- Fabrics::init(),
sessions <- Sessions::init(),
resumption <- crate::sc::case::ResumableSessions::init(),
pase <- Pase::init(),
failsafe <- FailSafe::init(),
basic_info_settings <- BasicInfoSettings::init(),
rtc <- Rtc::init(),
icd_mode: None,
})
}
/// Return an in-place initializer for MatterState
#[cfg(not(feature = "case-resumption"))]
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(),
icd_mode: None,
})
}
}
#[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,
)
}
}