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
/*
 *
 *    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 General Commissioning cluster and its handler.

use core::fmt::Debug;

use either::Either;

use crate::dm::clusters::net_comm::NetworksAccess;
use crate::dm::{Cluster, Dataver, InvokeContext, OperationContext, ReadContext, WriteContext};
use crate::error::{Error, ErrorCode};
use crate::fabric::FabricPersist;
use crate::persist::{Persist, BASIC_INFO_KEY, NETWORKS_KEY};
use crate::sc::pase::MAX_COMM_WINDOW_TIMEOUT_SECS;
use crate::tlv::TLVBuilderParent;
use crate::transport::session::SessionMode;
use crate::utils::sync::DynBase;
use crate::{except, with, MatterState};

pub use crate::dm::clusters::decl::general_commissioning::*;

impl CommissioningErrorEnum {
    fn map(result: Result<(), Error>) -> Result<Self, Error> {
        Self::map_result(result).map(Self::ok)
    }

    fn map_result<T>(result: Result<T, Error>) -> Result<Either<T, Self>, Error> {
        match result {
            Ok(value) => Ok(Either::Left(value)),
            Err(err) => match err.code() {
                ErrorCode::Busy | ErrorCode::NocInvalidFabricIndex => {
                    Ok(Either::Right(Self::BusyWithOtherAdmin))
                }
                ErrorCode::GennCommInvalidAuthentication => {
                    Ok(Either::Right(Self::InvalidAuthentication))
                }
                ErrorCode::FailSafeRequired => Ok(Either::Right(Self::NoFailSafe)),
                _ => Err(err),
            },
        }
    }

    fn ok<T>(value: Either<T, Self>) -> Self {
        match value {
            Either::Left(_) => Self::OK,
            Either::Right(code) => code,
        }
    }
}

/// A trait indicating the commissioning policy supported by `rs-matter`.
/// (i.e. co-existence of the BLE/BTP network and the operational network during commissioning).
pub trait CommPolicy: DynBase {
    /// Return true if the device supports concurrent connection
    /// (i.e. co-existence of the BLE/BTP network and the operational network during commissioning).
    fn concurrent_connection_supported(&self) -> bool;

    /// Return the expiry length of the fail-safe in seconds.
    fn failsafe_expiry_len_secs(&self) -> u16;

    /// Return the maximum cumulative fail-safe time in seconds.
    fn failsafe_max_cml_secs(&self) -> u16;

    /// Return the regulatory configuration of the device.
    fn regulatory_config(&self) -> RegulatoryLocationTypeEnum;

    /// Return the location capability of the device.
    fn location_cap(&self) -> RegulatoryLocationTypeEnum;
}

impl<T> CommPolicy for &T
where
    T: CommPolicy,
{
    fn concurrent_connection_supported(&self) -> bool {
        (*self).concurrent_connection_supported()
    }

    fn failsafe_expiry_len_secs(&self) -> u16 {
        (*self).failsafe_expiry_len_secs()
    }

    fn failsafe_max_cml_secs(&self) -> u16 {
        (*self).failsafe_max_cml_secs()
    }

    fn regulatory_config(&self) -> RegulatoryLocationTypeEnum {
        (*self).regulatory_config()
    }

    fn location_cap(&self) -> RegulatoryLocationTypeEnum {
        (*self).location_cap()
    }
}

impl DynBase for bool {}

impl CommPolicy for bool {
    fn concurrent_connection_supported(&self) -> bool {
        *self
    }

    fn failsafe_expiry_len_secs(&self) -> u16 {
        120
    }

    fn failsafe_max_cml_secs(&self) -> u16 {
        // Aligned with the Matter reference SDK example implementations and
        // with `MAX_COMM_WINDOW_TIMEOUT_SECS` in `sc::pase`. Some Python tests
        // (e.g. TC_ACL_2_9) read this attribute and reuse it as the
        // `commissioning_timeout` for `OpenCommissioningWindow`, which the spec
        // bounds at [180, 900] seconds; reporting 900 keeps such tests within
        // the valid range while still being a reasonable upper bound.
        MAX_COMM_WINDOW_TIMEOUT_SECS
    }

    fn regulatory_config(&self) -> RegulatoryLocationTypeEnum {
        RegulatoryLocationTypeEnum::IndoorOutdoor
    }

    fn location_cap(&self) -> RegulatoryLocationTypeEnum {
        RegulatoryLocationTypeEnum::IndoorOutdoor
    }
}

/// The system implementation of a handler for the General Commissioning Matter cluster.
pub struct GenCommHandler<'a> {
    dataver: Dataver,
    commissioning_policy: &'a dyn CommPolicy,
}

impl<'a> GenCommHandler<'a> {
    /// Create a new instance of `GenCommHandler` with the given `Dataver` and `CommissioningPolicy`.
    pub const fn new(dataver: Dataver, commissioning_policy: &'a dyn CommPolicy) -> Self {
        Self {
            dataver,
            commissioning_policy,
        }
    }

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

    /// Execute the provided closure after checking that the failsafe is armed for the
    /// fabric of this session.
    ///
    /// If the check fail, an appropriate error is returned.
    pub(crate) fn with_armed_failsafe<F, T>(ctx: impl OperationContext, f: F) -> Result<T, Error>
    where
        F: FnOnce(&mut MatterState, &mut dyn FnMut()) -> Result<T, Error>,
    {
        Self::with_armed_failsafe_ex(ctx, f)
    }

    /// Return whether the supplied `NewRegulatoryConfig` value is allowed
    /// given the device's `LocationCapability`. Mirrors the matrix in Matter
    /// Core spec.
    fn is_regulatory_config_supported(
        policy: &dyn CommPolicy,
        new_config: RegulatoryLocationTypeEnum,
    ) -> bool {
        match policy.location_cap() {
            RegulatoryLocationTypeEnum::Indoor => {
                matches!(new_config, RegulatoryLocationTypeEnum::Indoor)
            }
            RegulatoryLocationTypeEnum::Outdoor => {
                matches!(new_config, RegulatoryLocationTypeEnum::Outdoor)
            }
            RegulatoryLocationTypeEnum::IndoorOutdoor => true,
        }
    }

    /// Execute the provided closure after checking that the failsafe is armed for the
    /// fabric of this session.
    ///
    /// If the check fail, an appropriate error is returned.
    pub(crate) fn with_armed_failsafe_ex<F, T, E>(ctx: impl OperationContext, f: F) -> Result<T, E>
    where
        F: FnOnce(&mut MatterState, &mut dyn FnMut()) -> Result<T, E>,
        E: From<Error>,
    {
        let mut notify_mdns = || ctx.exchange().matter().transport().notify_mdns_changed();

        ctx.exchange().with_state_ex(|state| {
            let sess = ctx.exchange().id().session(&mut state.sessions);

            state
                .failsafe
                .check_armed(sess.get_session_mode())
                .map_err(|err| match err.code() {
                    ErrorCode::NocInvalidFabricIndex => {
                        Error::new(ErrorCode::GennCommInvalidAuthentication)
                    }
                    _ => err,
                })?;

            f(state, &mut notify_mdns)
        })
    }
}

impl ClusterHandler for GenCommHandler<'_> {
    const CLUSTER: Cluster<'static> = FULL_CLUSTER
        .with_attrs(with!(required))
        .with_cmds(except!(CommandId::SetTCAcknowledgements));

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

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

    fn breadcrumb(&self, ctx: impl ReadContext) -> Result<u64, Error> {
        ctx.exchange()
            .with_state(|state| Ok(state.failsafe.breadcrumb()))
    }

    fn set_breadcrumb(&self, ctx: impl WriteContext, value: u64) -> Result<(), Error> {
        ctx.exchange().with_state(|state| {
            state.failsafe.set_breadcrumb(value);

            Ok(())
        })
    }

    fn basic_commissioning_info<P: TLVBuilderParent>(
        &self,
        _ctx: impl ReadContext,
        builder: BasicCommissioningInfoBuilder<P>,
    ) -> Result<P, Error> {
        builder
            .fail_safe_expiry_length_seconds(self.commissioning_policy.failsafe_expiry_len_secs())?
            .max_cumulative_failsafe_seconds(self.commissioning_policy.failsafe_max_cml_secs())?
            .end()
    }

    fn regulatory_config(
        &self,
        ctx: impl ReadContext,
    ) -> Result<RegulatoryLocationTypeEnum, Error> {
        ctx.exchange()
            .with_state(|state| Ok(state.basic_info_settings.location_type))
    }

    fn location_capability(
        &self,
        _ctx: impl ReadContext,
    ) -> Result<RegulatoryLocationTypeEnum, Error> {
        Ok(self.commissioning_policy.location_cap())
    }

    fn supports_concurrent_connection(&self, _ctx: impl ReadContext) -> Result<bool, Error> {
        Ok(self.commissioning_policy.concurrent_connection_supported())
    }

    fn handle_arm_fail_safe<P: TLVBuilderParent>(
        &self,
        ctx: impl InvokeContext,
        request: ArmFailSafeRequest<'_>,
        response: ArmFailSafeResponseBuilder<P>,
    ) -> Result<P, Error> {
        let expiry_length_seconds = request.expiry_length_seconds()?;

        info!(
            "Got Arm Fail Safe Request, expiry {}s",
            expiry_length_seconds
        );

        // `ArmFailSafe(0)` means "force-expire the fail-safe context" per
        // Matter Core spec: if the fail-safe is armed,
        // the device SHALL roll back any uncommitted fabric / network state
        // and reset the breadcrumb. Route through `force_expiry` so that
        // in-flight `AddNOC` / `SetRegulatoryConfig` changes are reverted —
        // the bare `failsafe.arm(0, ...)` path only flips the state to
        // `Idle` and would leave the staged fabric committed.
        let status = if expiry_length_seconds == 0 {
            let notify_mdns = || ctx.exchange().matter().transport().notify_mdns_changed();
            let notify_change = |endpt_id, clust_id| ctx.notify_cluster_changed(endpt_id, clust_id);

            CommissioningErrorEnum::map(ctx.exchange().with_state(|state| {
                let sess = ctx.exchange().id().session(&mut state.sessions);
                let pase_sess_id =
                    matches!(sess.get_session_mode(), SessionMode::Pase { .. }).then(|| sess.id());

                state.failsafe.expire(
                    &mut state.fabrics,
                    &mut state.sessions,
                    pase_sess_id,
                    ctx.networks(),
                    ctx.kv(),
                    notify_mdns,
                    notify_change,
                )?;

                Ok(())
            }))?
        } else {
            CommissioningErrorEnum::map(ctx.exchange().with_state(|state| {
                let sess = ctx.exchange().id().session(&mut state.sessions);

                state.failsafe.arm(
                    expiry_length_seconds,
                    request.breadcrumb()?,
                    sess.get_session_mode(),
                    &mut state.pase,
                )
            }))?
        };

        // Breadcrumb (and possibly failsafe-arm state) may have changed
        ctx.notify_own_cluster_changed();

        response.error_code(status)?.debug_text("")?.end()
    }

    fn handle_set_regulatory_config<P: TLVBuilderParent>(
        &self,
        ctx: impl InvokeContext,
        request: SetRegulatoryConfigRequest<'_>,
        response: SetRegulatoryConfigResponseBuilder<P>,
    ) -> Result<P, Error> {
        info!("Got Set Regulatory Config Request");

        let country_code = request.country_code()?;
        if country_code.len() != 2 {
            return Err(ErrorCode::ConstraintError.into());
        }

        // Per Matter Core spec, `NewRegulatoryConfig`
        // SHALL be one of the values supported by the device's
        // `LocationCapability`:
        //
        //   * `LocationCapability::Indoor`         -> only `Indoor`
        //   * `LocationCapability::Outdoor`        -> only `Outdoor`
        //   * `LocationCapability::IndoorOutdoor`  -> any of the three
        //
        // A request that violates this — including an enum value the device
        // doesn't even recognise — must be rejected with the cluster-level
        // `ValueOutsideRange` rather than a generic IM `Failure`. Decode the
        // enum defensively because TLV decoding will reject an unknown
        // variant before we ever see it (the test sends `3`).
        let location_type = request.new_regulatory_config();
        let breadcrumb = request.breadcrumb()?;

        let location_type = match location_type {
            Ok(loc) if Self::is_regulatory_config_supported(self.commissioning_policy, loc) => loc,
            _ => {
                return response
                    .error_code(CommissioningErrorEnum::ValueOutsideRange)?
                    .debug_text("")?
                    .end();
            }
        };

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

        let status = CommissioningErrorEnum::map(ctx.exchange().with_state(|state| {
            state.basic_info_settings.set_location(country_code);
            state.basic_info_settings.location_type = location_type;

            state.failsafe.set_breadcrumb(breadcrumb);

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

            Ok(())
        }))?;

        persist.run()?;

        // Regulatory config mutates both this cluster (RegulatoryConfig, Breadcrumb)
        // and Basic Information (Location) on the same endpoint
        ctx.notify_own_endpoint_changed();

        response.error_code(status)?.debug_text("")?.end()
    }

    fn handle_commissioning_complete<P: TLVBuilderParent>(
        &self,
        ctx: impl InvokeContext,
        response: CommissioningCompleteResponseBuilder<P>,
    ) -> Result<P, Error> {
        info!("Got Commissioning Complete Request");

        let notify_change = |endpt_id, clust_id| ctx.notify_cluster_changed(endpt_id, clust_id);

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

        let status =
            CommissioningErrorEnum::map(Self::with_armed_failsafe(&ctx, |state, notify_mdns| {
                let sess = ctx.exchange().id().session(&mut state.sessions);
                // Spec: on
                // `CommissioningComplete` the PASE session SHALL be
                // terminated. The current command is being delivered over
                // that PASE, so mark it `expired` (response can still go
                // out, no further exchanges accepted) and let the LRU
                // eviction reclaim the slot. Without this the promoted
                // PASE leaks across commissioning rounds and eventually
                // exhausts the session table — visible as `BUSY` on the
                // next round's `PBKDFParamRequest` (TC_CADMIN_1_19 hit
                // this on the 4th round of `SupportedFabrics` rounds).
                // Modern controllers (CHIP SDK 1.4+) run a
                // `FindOperationalForCommissioningComplete` step before
                // sending `CommissioningComplete`, so this command
                // typically arrives over the new operational CASE session
                // rather than over PASE. In that case the current session
                // doesn't need preserving and we just drop every PASE
                // session unconditionally. (For legacy behaviour where the
                // command does come over PASE we still preserve the
                // current one.)
                let pase_sess_id =
                    matches!(sess.get_session_mode(), SessionMode::Pase { .. }).then(|| sess.id());

                let fabric = state
                    .failsafe
                    .disarm(sess.get_session_mode(), &mut state.fabrics)?;

                state.pase.close_comm_window(notify_mdns, notify_change)?;
                state.sessions.remove_pase(pase_sess_id);
                ctx.exchange().matter().transport().notify_session_removed();

                // Finally, persist the fabric and the network settings, prior to sending the other party a "success" status
                persist.store(fabric)?;
                ctx.networks().access(|networks| {
                    networks.set_commissioned(true)?;

                    persist
                        .persist_mut()
                        .store(NETWORKS_KEY, |buf| networks.save(buf))
                })?;

                info!("Commissioning complete, fabric and network settings persisted");

                Ok(())
            }))?;

        persist.run()?;

        // Commissioning-complete mutates many clusters on the root endpoint:
        // breadcrumb (this cluster), fabrics (NOC), networks (NetCommissioning).
        // The closed commissioning window was already notified via `notify_change`.
        ctx.notify_own_endpoint_changed();

        response.error_code(status)?.debug_text("")?.end()
    }

    fn handle_set_tc_acknowledgements<P: TLVBuilderParent>(
        &self,
        _ctx: impl InvokeContext,
        _request: SetTCAcknowledgementsRequest<'_>,
        _response: SetTCAcknowledgementsResponseBuilder<P>,
    ) -> Result<P, Error> {
        Err(ErrorCode::CommandNotFound.into())
    }
}

impl Debug for GenCommHandler<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("GenCommHandler")
            .field("dataver", &self.dataver)
            .finish()
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for GenCommHandler<'_> {
    fn format(&self, fmt: defmt::Formatter) {
        defmt::write!(fmt, "GenCommHandler {{ dataver: {} }}", self.dataver);
    }
}