Skip to main content

matter_kit/clusters/
general_commissioning.rs

1//! General Commissioning cluster `0x0030` (Core §11.10) — the commissioning lifecycle.
2//!
3//! > This cluster is used to manage basic commissioning lifecycle.
4//!
5//! Three commands carry the whole of it: `ArmFailSafe` opens a transaction, everything else
6//! a commissioner does happens inside it, and `CommissioningComplete` closes it. If the
7//! commissioner never gets that far, the fail-safe expires and the device goes back to what
8//! it was — [`failsafe`](crate::commissioning::failsafe) is that state machine, and this
9//! cluster is its wire surface.
10//!
11//! # What this cluster does not own
12//!
13//! `ArmFailSafe`'s expiry has eleven cleanup steps, and they touch the fabric table, the
14//! session table, the key store and the network configuration. None of those belong to a
15//! cluster, so expiry hands back a [`Cleanup`] and the device applies it. Two commands
16//! therefore return work to be done rather than doing it:
17//! [`ArmFailSafeOutcome::cleanup`] and [`Completion::cleanup`].
18//!
19//! That is not a limitation of the design — it is what keeps §11.10.7.2.2's eleven steps
20//! auditable against the specification instead of buried across four modules.
21//!
22//! # `SetRegulatoryConfig` writes another cluster's attribute
23//!
24//! §11.10.7.4: the `CountryCode` field "SHALL be used to set the Location attribute reflected
25//! by the Basic Information Cluster". So this cluster holds a reference to the same
26//! [`Location`] cell Basic Information reads, and the two cannot disagree.
27//!
28//! Note the ordering §11.10.7.4 imposes, which reads like a mistake and is not: a country
29//! code the device has no regulatory data for "SHALL still set the Location attribute … but
30//! the SetRegulatoryConfigResponse replied SHALL have the ErrorCode field set to
31//! ValueOutsideRange". The location lands, the error is reported anyway. A mismatched
32//! `NewRegulatoryConfig`, by contrast, leaves `RegulatoryConfig` "unchanged".
33//!
34//! # Revision 2
35//!
36//! | Revision | Change |
37//! |---|---|
38//! | 1 | Initial revision |
39//! | 2 | Add Enhanced Setup Flow |
40
41use core::cell::{Cell, RefCell};
42
43use crate::clusters::basic_information::Location;
44use crate::commissioning::failsafe::{Cleanup, CommissioningError, FailSafe};
45use crate::dm::Resolved;
46use crate::dm::ResolvedCommand;
47use crate::dm::access::{Access, AccessQualities, Privilege};
48use crate::dm::meta::{
49    AttributeDescriptor, AttributeQualities, ClusterDescriptor, CommandDescriptor,
50};
51use crate::im::{
52    AttributeId, ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb,
53    WriteOp,
54};
55use crate::msg::FabricIndex;
56use crate::platform::{Duration, Instant};
57use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, set_once};
58
59use super::Cluster;
60
61/// `0x0030` (§11.10.3).
62pub const ID: ClusterId = 0x0030;
63
64/// The highest revision in §11.10.1's table.
65pub const REVISION: u16 = 2;
66
67/// `TC` (§11.10.4, bit 0) — Enhanced Setup Flow Terms & Conditions.
68pub const FEATURE_TERMS_AND_CONDITIONS: u32 = 1 << 0;
69/// `NR` (§11.10.4, bit 1) — Network Recovery. Provisional.
70pub const FEATURE_NETWORK_RECOVERY: u32 = 1 << 1;
71
72/// `Breadcrumb` (§11.10.6.1) — `uint64`, fallback 0, `RW VA`, mandatory.
73pub const BREADCRUMB: AttributeId = 0x0000;
74/// `BasicCommissioningInfo` (§11.10.6.2) — `F`, `RV`, mandatory.
75pub const BASIC_COMMISSIONING_INFO: AttributeId = 0x0001;
76/// `RegulatoryConfig` (§11.10.6.3) — `RV`, mandatory. Read-only on the wire: only
77/// `SetRegulatoryConfig` changes it.
78pub const REGULATORY_CONFIG: AttributeId = 0x0002;
79/// `LocationCapability` (§11.10.6.4) — `F`, `RV`, mandatory.
80pub const LOCATION_CAPABILITY: AttributeId = 0x0003;
81/// `SupportsConcurrentConnection` (§11.10.6.5) — `F`, `RV`, mandatory.
82pub const SUPPORTS_CONCURRENT_CONNECTION: AttributeId = 0x0004;
83
84/// `RecoveryIdentifier` (§11.10.6.11) — `NR`, and provisional.
85pub const RECOVERY_IDENTIFIER: AttributeId = 0x000A;
86
87/// `NetworkRecoveryReason` (§11.10.6.12) — `NR`, nullable, and provisional.
88pub const NETWORK_RECOVERY_REASON: AttributeId = 0x000B;
89
90/// `ArmFailSafe` (§11.10.7.2) — access `A`.
91pub const ARM_FAIL_SAFE: CommandId = 0x00;
92/// `ArmFailSafeResponse` (§11.10.7.3).
93pub const ARM_FAIL_SAFE_RESPONSE: CommandId = 0x01;
94/// `SetRegulatoryConfig` (§11.10.7.4) — access `A`.
95pub const SET_REGULATORY_CONFIG: CommandId = 0x02;
96/// `SetRegulatoryConfigResponse` (§11.10.7.5).
97pub const SET_REGULATORY_CONFIG_RESPONSE: CommandId = 0x03;
98/// `CommissioningComplete` (§11.10.7.6) — access `AF`: fabric-scoped, and CASE only.
99pub const COMMISSIONING_COMPLETE: CommandId = 0x04;
100/// `CommissioningCompleteResponse` (§11.10.7.7).
101pub const COMMISSIONING_COMPLETE_RESPONSE: CommandId = 0x05;
102
103/// `RegulatoryLocationTypeEnum` (§11.10.5.2) — "possible radio usage".
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
105#[repr(u8)]
106pub enum RegulatoryLocation {
107    /// `0` — indoor only.
108    Indoor = 0,
109    /// `1` — outdoor only.
110    Outdoor = 1,
111    /// `2` — indoor/outdoor. "For Nodes without radio network interfaces (e.g. Ethernet-only
112    /// devices), the value IndoorOutdoor SHALL always be used."
113    IndoorOutdoor = 2,
114}
115
116impl RegulatoryLocation {
117    /// The value the enum encodes as.
118    #[must_use]
119    pub const fn value(self) -> u8 {
120        self as u8
121    }
122
123    /// Decodes a wire value, refusing anything §11.10.5.2 does not define.
124    #[must_use]
125    pub const fn from_value(value: u8) -> Option<Self> {
126        match value {
127            0 => Some(Self::Indoor),
128            1 => Some(Self::Outdoor),
129            2 => Some(Self::IndoorOutdoor),
130            _ => None,
131        }
132    }
133}
134
135/// §5.9's Network Recovery state: how a node that has lost its network asks for a new one.
136///
137/// A node whose Wi-Fi password changed underneath it is not broken and not commissionable — it
138/// still holds its fabric, its NOC and its ACL. §5.9 is the way back: advertise over BLE or
139/// Wi-Fi PAF, let an administrator open a *CASE* session over that channel, and take new network
140/// credentials through it.
141///
142/// Three rules carry the flow, and all three are here rather than in the application because
143/// all three are about *timing* and are the ones a device gets wrong by being helpful:
144///
145/// * §5.9.3 step 3: a node "SHALL continue to attempt to connect to the operational network for
146///   a duration of at least 120 seconds using its existing credentials" before it may advertise.
147///   "Given that temporary network outages occur with some frequency, waiting before entering
148///   Network Recovery mode and commencing announcement limits wireless spectrum
149///   pollution/interference and helps to limit attack opportunities."
150/// * §5.9.3 step 10: on the CASE session the node "SHALL autonomously arm the fail-safe timer
151///   for a timeout of 60 seconds", against an administrator that connects and then wanders off.
152/// * §5.9.3 step 16: "The Recovery Node SHALL reject the CommissioningComplete that is not
153///   received over the operational network." Completing over the recovery channel would declare
154///   success at the exact moment nothing had been proved to work.
155#[derive(Debug)]
156pub struct Recovery {
157    /// §11.10.6.11's `RecoveryIdentifier`: "a random 64-bit value, that value SHALL be reset on
158    /// factory reset and SHALL remain unchanged until a next factory reset".
159    ///
160    /// It is what an administrator matches an advertisement against, and §11.10.6.11 says why
161    /// it is not the Node ID: the identifier lets an administrator "establish a Node's identity
162    /// without revealing its Node ID" to everyone in radio range.
163    identifier: u64,
164    /// When connectivity was first lost, or `None` while the network is fine.
165    lost_at: Cell<Option<Instant>>,
166    /// Why, once the node has entered recovery. Null at every other time (§11.10.6.12).
167    reason: Cell<Option<NetworkRecoveryReason>>,
168    /// Whether the node is advertising for recovery.
169    announcing: Cell<bool>,
170}
171
172/// §11.10.6.12's `NetworkRecoveryReasonEnum`: "the primary reason that triggered the Network
173/// Recovery flow".
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
175#[repr(u8)]
176pub enum NetworkRecoveryReason {
177    /// "Unspecified / unknown reason of network failure".
178    Unspecified = 0,
179    /// "Credentials for the configured operational network are not valid."
180    Auth = 1,
181    /// "Configured network cannot be found."
182    Visibility = 2,
183}
184
185impl NetworkRecoveryReason {
186    /// The wire value.
187    #[must_use]
188    pub const fn value(self) -> u8 {
189        self as u8
190    }
191}
192
193/// §5.9.3 step 3's floor: "at least 120 seconds using its existing credentials".
194pub const RECOVERY_HOLD_OFF: Duration = Duration::from_secs(120);
195
196/// §5.9.3 step 10's autonomous fail-safe: 60 seconds from the CASE session being established.
197pub const RECOVERY_FAIL_SAFE_SECONDS: u16 = 60;
198
199impl Recovery {
200    /// A node whose network is working, with the identifier it was given at factory reset.
201    #[must_use]
202    pub const fn new(identifier: u64) -> Self {
203        Self {
204            identifier,
205            lost_at: Cell::new(None),
206            reason: Cell::new(None),
207            announcing: Cell::new(false),
208        }
209    }
210
211    /// `RecoveryIdentifier` (§11.10.6.11).
212    #[must_use]
213    pub const fn identifier(&self) -> u64 {
214        self.identifier
215    }
216
217    /// `NetworkRecoveryReason` (§11.10.6.12), null unless the node is in recovery.
218    #[must_use]
219    pub fn reason(&self) -> Option<NetworkRecoveryReason> {
220        self.reason.get()
221    }
222
223    /// Whether the node is advertising for recovery.
224    #[must_use]
225    pub fn is_announcing(&self) -> bool {
226        self.announcing.get()
227    }
228
229    /// The node cannot reach its operational network.
230    ///
231    /// Idempotent: the clock starts at the *first* failure, so a device that calls this on every
232    /// retry does not keep pushing its own hold-off out.
233    pub fn network_lost(&self, now: Instant, reason: NetworkRecoveryReason) {
234        if self.lost_at.get().is_none() {
235            self.lost_at.set(Some(now));
236            self.reason.set(Some(reason));
237        }
238    }
239
240    /// The network came back, or recovery finished.
241    ///
242    /// §11.10.6.12: the reason "SHALL be null when the Node is not undergoing a Network Recovery
243    /// flow", so it goes with the state rather than lingering as a diagnostic.
244    pub fn network_restored(&self) {
245        self.lost_at.set(None);
246        self.reason.set(None);
247        self.announcing.set(false);
248    }
249
250    /// Whether §5.9.3 step 3's hold-off has elapsed, so announcement may begin.
251    #[must_use]
252    pub fn may_announce(&self, now: Instant) -> bool {
253        self.lost_at
254            .get()
255            .is_some_and(|lost| now.saturating_duration_since(lost) >= RECOVERY_HOLD_OFF)
256    }
257
258    /// Begins announcing, if §5.9.3 step 3 allows it yet.
259    ///
260    /// Returns whether it did. A device that announced early would be advertising through every
261    /// brief outage its access point has.
262    pub fn begin_announcing(&self, now: Instant) -> bool {
263        let allowed = self.may_announce(now);
264        if allowed {
265            self.announcing.set(true);
266        }
267        allowed
268    }
269
270    /// Whether a `CommissioningComplete` arriving over `operational_network` may be accepted
271    /// (§5.9.3 step 16).
272    ///
273    /// Outside a recovery flow this is always true — an ordinary commissioning completes over
274    /// whatever channel it ran on.
275    #[must_use]
276    pub fn may_complete(&self, over_operational_network: bool) -> bool {
277        !self.announcing.get() || over_operational_network
278    }
279}
280
281/// The attributes of §11.10.6 that are not gated on a feature.
282///
283/// `Breadcrumb` is the only writable one, at `RW VA`; `RegulatoryConfig` is `RV` even though
284/// a command changes it, which is the specification's way of saying that the change must go
285/// through `SetRegulatoryConfig` and pick up its regulatory checks.
286const ATTRIBUTES: &[AttributeDescriptor] = &[
287    AttributeDescriptor::read_write(BREADCRUMB).with_access(Access::read_write_with(
288        Privilege::View,
289        Privilege::Administer,
290    )),
291    AttributeDescriptor::read_only(BASIC_COMMISSIONING_INFO)
292        .with_qualities(AttributeQualities::FIXED),
293    AttributeDescriptor::read_only(REGULATORY_CONFIG),
294    AttributeDescriptor::read_only(LOCATION_CAPABILITY).with_qualities(AttributeQualities::FIXED),
295    AttributeDescriptor::read_only(SUPPORTS_CONCURRENT_CONNECTION)
296        .with_qualities(AttributeQualities::FIXED),
297];
298
299/// The same list with the two attributes §11.10.6 gates on the `NR` feature.
300///
301/// Everything unconditional is repeated rather than concatenated: a cluster descriptor is a
302/// `const` slice in flash, and §7.3's conformance makes the *whole* list a function of the
303/// feature map — so the two variants are two lists, checked against the specification's own
304/// tables by [`tests/conformance.rs`].
305///
306/// `RecoveryIdentifier` is `F` — "SHALL remain unchanged until a next factory reset" — and both
307/// are `RA`: only an administrator may read them, because together they say "this node has lost
308/// its network, and here is the identifier it is advertising", which is not for everyone with a
309/// session.
310#[cfg(feature = "provisional")]
311const RECOVERY_ATTRIBUTES: &[AttributeDescriptor] = &[
312    AttributeDescriptor::read_write(BREADCRUMB).with_access(Access::read_write_with(
313        Privilege::View,
314        Privilege::Administer,
315    )),
316    AttributeDescriptor::read_only(BASIC_COMMISSIONING_INFO)
317        .with_qualities(AttributeQualities::FIXED),
318    AttributeDescriptor::read_only(REGULATORY_CONFIG),
319    AttributeDescriptor::read_only(LOCATION_CAPABILITY).with_qualities(AttributeQualities::FIXED),
320    AttributeDescriptor::read_only(SUPPORTS_CONCURRENT_CONNECTION)
321        .with_qualities(AttributeQualities::FIXED),
322    AttributeDescriptor::read_only(RECOVERY_IDENTIFIER)
323        .with_access(Access::read_only(Privilege::Administer))
324        .with_qualities(AttributeQualities::FIXED),
325    AttributeDescriptor::read_only(NETWORK_RECOVERY_REASON)
326        .with_access(Access::read_only(Privilege::Administer))
327        .with_qualities(AttributeQualities::NULLABLE),
328];
329
330/// §11.10.7's command table.
331///
332/// All three are `A` — Administer — because each of them can leave the device in a state it
333/// cannot get out of. `CommissioningComplete` is additionally `F`: it is fabric-scoped, so
334/// §8.8.2.3 step b.v refuses it over a session with no accessing fabric before it reaches
335/// the handler at all.
336const COMMANDS: &[CommandDescriptor] = &[
337    CommandDescriptor::new(ARM_FAIL_SAFE)
338        .with_access(Access::invoke(Privilege::Administer))
339        .with_response(ARM_FAIL_SAFE_RESPONSE),
340    CommandDescriptor::new(SET_REGULATORY_CONFIG)
341        .with_access(Access::invoke(Privilege::Administer))
342        .with_response(SET_REGULATORY_CONFIG_RESPONSE),
343    CommandDescriptor::new(COMMISSIONING_COMPLETE)
344        .with_access(
345            Access::invoke(Privilege::Administer).with_qualities(AccessQualities::FABRIC_SCOPED),
346        )
347        .with_response(COMMISSIONING_COMPLETE_RESPONSE),
348];
349
350/// The cluster descriptor.
351#[must_use]
352pub const fn cluster() -> ClusterDescriptor<'static> {
353    ClusterDescriptor {
354        id: ID,
355        revision: REVISION,
356        feature_map: 0,
357        attributes: ATTRIBUTES,
358        accepted_commands: COMMANDS,
359        generated_commands: &[],
360        events: &[],
361    }
362}
363
364/// The cluster descriptor for a node that implements §5.9's Network Recovery.
365///
366/// The feature bit and the two attributes move together: §7.3's conformance makes
367/// `RecoveryIdentifier` and `NetworkRecoveryReason` mandatory exactly when `NR` is set, so a
368/// descriptor that advertised one without the other would fail
369/// [`dm::spec`](crate::dm::spec)'s own validation.
370///
371/// Behind `provisional`, because Network Recovery is Core §2.13.6's and its two attributes are
372/// marked `P`. This is the only constructor that furnishes them, so gating it is what makes
373/// "provisional means off" true for this cluster rather than merely asserted — and
374/// [`Cluster::validate`](crate::dm::spec::Cluster::validate) reports the same thing about any
375/// descriptor that furnishes a `P` element on a build that did not ask for one.
376#[cfg(feature = "provisional")]
377#[cfg_attr(docsrs, doc(cfg(feature = "provisional")))]
378#[must_use]
379pub const fn cluster_with_recovery() -> ClusterDescriptor<'static> {
380    ClusterDescriptor {
381        id: ID,
382        revision: REVISION,
383        feature_map: FEATURE_NETWORK_RECOVERY,
384        attributes: RECOVERY_ATTRIBUTES,
385        accepted_commands: COMMANDS,
386        generated_commands: &[],
387        events: &[],
388    }
389}
390
391/// What `ArmFailSafe` produced, beyond its response.
392#[derive(Debug, Clone, Copy, PartialEq, Eq)]
393pub struct ArmFailSafeOutcome {
394    /// The `ErrorCode` that went into the `ArmFailSafeResponse`.
395    pub error: CommissioningError,
396    /// The cleanup steps of §11.10.7.2.2, when `ExpiryLengthSeconds` was zero and the
397    /// fail-safe was disarmed on the spot.
398    pub cleanup: Option<Cleanup>,
399}
400
401/// What `CommissioningComplete` produced.
402///
403/// §11.10.7.6's five actions on success: steps 1 and 5 (disarm, reset the breadcrumb) happen
404/// inside the cluster; steps 2, 3 and 4 — close the commissioning window, revoke PASE
405/// privileges, clear PASE sessions — are the device's, and [`Completion::cleanup`] says so.
406#[derive(Debug, Clone, Copy, PartialEq, Eq)]
407pub struct Completion {
408    /// The `ErrorCode` that went into the response.
409    pub error: CommissioningError,
410    /// Set on success: steps 3 and 4 — revoke the temporary administrative privileges granted
411    /// to any open PASE session, and clear its Secure Session Context.
412    pub close_pase_sessions: bool,
413    /// §11.10.7.2.2's cleanup steps, owed to a fail-safe context that had already lapsed when
414    /// the command arrived. A successful completion is not a rollback and produces none.
415    pub cleanup: Option<Cleanup>,
416}
417
418/// What a command left for the device to do, which a cluster cannot do itself.
419///
420/// Both variants touch the session table, the fabric table or the commissioning window — none
421/// of which belong to a cluster. Keeping them as *reported work* rather than hidden effects
422/// is what keeps §11.10.7.2.2's eleven steps auditable against the specification instead of
423/// scattered across four modules.
424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
425pub enum Aftermath {
426    /// A fail-safe context ended without completing. Apply §11.10.7.2.2's steps.
427    Rollback(Cleanup),
428    /// `CommissioningComplete` succeeded. §11.10.7.6 steps 2 to 4: the commissioning window
429    /// is closed (this cluster has already recorded that), the temporary administrative
430    /// privileges granted to any open PASE session are revoked, and its Secure Session
431    /// Context is cleared.
432    Commissioned,
433}
434
435/// The General Commissioning cluster.
436///
437/// `location` is shared with [`BasicInformation`](super::BasicInformation) — see the module
438/// documentation.
439#[derive(Debug)]
440pub struct GeneralCommissioning<'a> {
441    /// The `Location` attribute of Basic Information, which `SetRegulatoryConfig` writes.
442    pub location: &'a Location,
443    /// `LocationCapability` (§11.10.6.4) — fixed by the manufacturer.
444    pub location_capability: RegulatoryLocation,
445    /// `SupportsConcurrentConnection` (§11.10.6.5).
446    pub supports_concurrent_connection: bool,
447    /// The node's fail-safe context.
448    ///
449    /// Borrowed, not owned: §11.18's `AddNOC`, `UpdateNOC`, `CSRRequest` and
450    /// `AddTrustedRootCertificate` all consult and record against the *same* context this
451    /// cluster arms, so it is node state that two clusters share — the same arrangement as
452    /// [`Location`], and for the same reason.
453    pub fail_safe: &'a RefCell<FailSafe>,
454    regulatory_config: Cell<RegulatoryLocation>,
455    /// The node's commissioning window, shared with Administrator Commissioning.
456    ///
457    /// §11.10.7.2 consults it to give a PASE commissioner priority over a CASE administrator,
458    /// and §11.10.7.6 step 2 closes it on `CommissioningComplete`. Both are about the *same*
459    /// window §11.19 opens, so it is node state rather than a flag each cluster keeps —
460    /// two copies would be two answers to "is a window open", and the priority rule is
461    /// precisely where they would disagree.
462    pub window: &'a RefCell<crate::commissioning::window::CommissioningWindow>,
463    /// §5.9's Network Recovery state, on a device that implements the `NR` feature.
464    ///
465    /// Optional because the feature is: a node without it has no `RecoveryIdentifier` to
466    /// advertise, and §11.10.6.11's attribute is conformant only when `NR` is set.
467    pub recovery: Option<&'a Recovery>,
468    /// What the last command invoked through the interaction model left for the device.
469    aftermath: Cell<Option<Aftermath>>,
470}
471
472impl<'a> GeneralCommissioning<'a> {
473    /// The cluster for a device.
474    ///
475    /// `location_capability` is also the initial `RegulatoryConfig`: §11.10.6.4 says "The
476    /// default value of the RegulatoryConfig attribute is the value of LocationCapability
477    /// attribute. This means devices always have a safe default value."
478    #[must_use]
479    pub fn new(
480        location: &'a Location,
481        location_capability: RegulatoryLocation,
482        fail_safe: &'a RefCell<FailSafe>,
483        window: &'a RefCell<crate::commissioning::window::CommissioningWindow>,
484    ) -> Self {
485        Self {
486            location,
487            location_capability,
488            supports_concurrent_connection: true,
489            fail_safe,
490            window,
491            regulatory_config: Cell::new(location_capability),
492            recovery: None,
493            aftermath: Cell::new(None),
494        }
495    }
496
497    /// The same cluster on a device that implements §5.9's Network Recovery.
498    #[must_use]
499    pub const fn with_recovery(mut self, recovery: &'a Recovery) -> Self {
500        self.recovery = Some(recovery);
501        self
502    }
503
504    /// The same cluster on a device that only supports the non-concurrent connection flow
505    /// (§5.5).
506    #[must_use]
507    pub fn without_concurrent_connection(mut self) -> Self {
508        self.supports_concurrent_connection = false;
509        self
510    }
511
512    /// The fail-safe state machine, for a device driving expiry from its own timer.
513    ///
514    /// [`FailSafe::next_deadline`] says when to call [`FailSafe::expire`]; the [`Cleanup`] it
515    /// returns is the device's to apply.
516    #[must_use]
517    pub fn fail_safe(&self) -> core::cell::Ref<'_, FailSafe> {
518        self.fail_safe.borrow()
519    }
520
521    /// Mutable access to the fail-safe, for recording `AddNOC`, `UpdateNOC` and the rest
522    /// ([`Progress`](crate::commissioning::failsafe::Progress)).
523    #[must_use]
524    pub fn fail_safe_mut(&self) -> core::cell::RefMut<'_, FailSafe> {
525        self.fail_safe.borrow_mut()
526    }
527
528    /// `RegulatoryConfig` (§11.10.6.3).
529    #[must_use]
530    pub fn regulatory_config(&self) -> RegulatoryLocation {
531        self.regulatory_config.get()
532    }
533
534    /// Whether a commissioning window is open as of `now` (§11.19.7.1).
535    #[must_use]
536    pub fn is_window_open(&self, now: crate::platform::Instant) -> bool {
537        self.window.borrow().open(now).is_some()
538    }
539
540    /// Takes the work the last command invoked through the interaction model left behind.
541    ///
542    /// A device calls this after every invoke against this cluster. Forgetting to means a
543    /// disarmed fail-safe leaves its fabric behind, or a completed commissioning leaves a
544    /// PASE session open with administrative privileges — which is the one that matters:
545    /// §11.10.7.6 steps 3 and 4 exist so that the passcode stops being a key to the device
546    /// the moment commissioning ends.
547    #[must_use]
548    pub fn take_aftermath(&self) -> Option<Aftermath> {
549        self.aftermath.take()
550    }
551
552    /// `ArmFailSafe` (§11.10.7.2).
553    pub fn arm_fail_safe(
554        &self,
555        expiry_length_seconds: u16,
556        breadcrumb: u64,
557        accessing_fabric: Option<FabricIndex>,
558        over_case: bool,
559        now: crate::platform::Instant,
560    ) -> ArmFailSafeOutcome {
561        let result = self.fail_safe.borrow_mut().arm(
562            expiry_length_seconds,
563            breadcrumb,
564            accessing_fabric,
565            now,
566            self.is_window_open(now) && over_case,
567        );
568        ArmFailSafeOutcome {
569            error: result.outcome.error_code(),
570            cleanup: result.cleanup,
571        }
572    }
573
574    /// `SetRegulatoryConfig` (§11.10.7.4).
575    ///
576    /// The two failures are asymmetric on purpose, and the specification is explicit about
577    /// both:
578    ///
579    /// * a `country_code` the device has no regulatory data for still sets `Location`, and
580    ///   the response reports `ValueOutsideRange`;
581    /// * a `new_config` that `LocationCapability` does not admit leaves `RegulatoryConfig`
582    ///   "unchanged".
583    ///
584    /// The `Breadcrumb` "SHALL be used to atomically set the Breadcrumb attribute on success
585    /// of this command … If the command fails, the Breadcrumb attribute SHALL be left
586    /// unchanged."
587    pub fn set_regulatory_config(
588        &self,
589        new_config: RegulatoryLocation,
590        country_code: &str,
591        breadcrumb: u64,
592    ) -> CommissioningError {
593        // "The CountryCode field SHALL … be used to set the Location attribute reflected by
594        // the Basic Information Cluster" — before the capability check, because a device
595        // that refuses the regulatory mode still learns where it is.
596        if self.location.set(country_code).is_err() {
597            return CommissioningError::ValueOutsideRange;
598        }
599
600        // "If the LocationCapability attribute is not Indoor/Outdoor and the
601        // NewRegulatoryConfig value received does not match either the Indoor or Outdoor
602        // fixed value in LocationCapability, then … ValueOutsideRange … and the
603        // RegulatoryConfig attribute … SHALL remain unchanged."
604        if self.location_capability != RegulatoryLocation::IndoorOutdoor
605            && new_config != self.location_capability
606        {
607            return CommissioningError::ValueOutsideRange;
608        }
609
610        self.regulatory_config.set(new_config);
611        self.fail_safe.borrow_mut().set_breadcrumb(breadcrumb);
612        CommissioningError::Ok
613    }
614
615    /// `CommissioningComplete` (§11.10.7.6).
616    pub fn commissioning_complete(
617        &self,
618        over_case: bool,
619        accessing_fabric: Option<FabricIndex>,
620        now: crate::platform::Instant,
621    ) -> Completion {
622        let result = self
623            .fail_safe
624            .borrow_mut()
625            .complete(over_case, accessing_fabric, now);
626        if result.error.is_ok() {
627            // Step 2: "The commissioning window at the Server SHALL be closed." Closing it
628            // here also destroys the ephemeral PAKE verifier §11.19.8.1 installed — "It SHALL
629            // be deleted by the Node at the end of commissioning".
630            self.window.borrow_mut().close();
631        }
632        Completion {
633            error: result.error,
634            close_pase_sessions: result.error.is_ok(),
635            cleanup: result.cleanup,
636        }
637    }
638}
639
640impl ClusterHandler for GeneralCommissioning<'_> {
641    fn read(
642        &self,
643        resolved: &Resolved<'_>,
644        _ctx: &InteractionContext<'_>,
645        w: &mut TlvWriter<'_>,
646        tag: Tag,
647    ) -> Result<(), Status> {
648        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
649        match resolved.attribute {
650            BREADCRUMB => full(w.unsigned(tag, self.fail_safe.borrow().breadcrumb())),
651            BASIC_COMMISSIONING_INFO => {
652                let info = self.fail_safe.borrow().info();
653                full(w.start_structure(tag))?;
654                full(w.unsigned(Tag::Context(0), u64::from(info.expiry_length_seconds)))?;
655                full(w.unsigned(Tag::Context(1), u64::from(info.max_cumulative_seconds)))?;
656                full(w.end_container())
657            }
658            REGULATORY_CONFIG => {
659                full(w.unsigned(tag, u64::from(self.regulatory_config.get().value())))
660            }
661            LOCATION_CAPABILITY => {
662                full(w.unsigned(tag, u64::from(self.location_capability.value())))
663            }
664            SUPPORTS_CONCURRENT_CONNECTION => {
665                full(w.bool(tag, self.supports_concurrent_connection))
666            }
667            RECOVERY_IDENTIFIER => {
668                let recovery = self.recovery.ok_or(Status::UnsupportedAttribute)?;
669                full(w.unsigned(tag, recovery.identifier()))
670            }
671            NETWORK_RECOVERY_REASON => {
672                let recovery = self.recovery.ok_or(Status::UnsupportedAttribute)?;
673                match recovery.reason() {
674                    Some(reason) => full(w.unsigned(tag, u64::from(reason.value()))),
675                    // §11.10.6.12: "This attribute SHALL be null when the Node is not
676                    // undergoing a Network Recovery flow."
677                    None => full(w.null(tag)),
678                }
679            }
680            _ => Err(Status::UnsupportedAttribute),
681        }
682    }
683
684    fn write(
685        &self,
686        resolved: &Resolved<'_>,
687        data: &[u8],
688        _op: WriteOp,
689        _ctx: &InteractionContext<'_>,
690    ) -> Result<(), Status> {
691        match resolved.attribute {
692            BREADCRUMB => {
693                // `Data` is the `AttributeDataIB`'s context-2 member, so it arrives tagged.
694                let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
695                let value = reader
696                    .next_element()
697                    .ok()
698                    .flatten()
699                    .and_then(|element| element.unsigned().ok())
700                    .ok_or(Status::InvalidDataType)?;
701                self.fail_safe.borrow_mut().set_breadcrumb(value);
702                Ok(())
703            }
704            _ => Err(Status::UnsupportedWrite),
705        }
706    }
707
708    fn invoke(
709        &self,
710        resolved: &ResolvedCommand<'_>,
711        fields: Option<&[u8]>,
712        ctx: &InteractionContext<'_>,
713        w: &mut TlvWriter<'_>,
714        tag: Tag,
715    ) -> Result<Option<CommandId>, StatusIb> {
716        match resolved.command.id {
717            ARM_FAIL_SAFE => {
718                let request = ArmFailSafeRequest::decode(fields)?;
719                let outcome = self.arm_fail_safe(
720                    request.expiry_length_seconds,
721                    request.breadcrumb,
722                    ctx.fabric_index,
723                    // §11.10.7.2's window rule turns on "the command was received over a CASE
724                    // session". An accessing fabric is exactly what a CASE session has and a
725                    // PASE session does not (§6.6.6.3).
726                    ctx.fabric_index.is_some(),
727                    ctx.now,
728                );
729                if let Some(cleanup) = outcome.cleanup {
730                    self.aftermath.set(Some(Aftermath::Rollback(cleanup)));
731                }
732                write_error_response(w, tag, outcome.error)?;
733                Ok(Some(ARM_FAIL_SAFE_RESPONSE))
734            }
735            SET_REGULATORY_CONFIG => {
736                let request = SetRegulatoryConfigRequest::decode(fields)?;
737                let error = self.set_regulatory_config(
738                    request.new_config,
739                    request.country_code,
740                    request.breadcrumb,
741                );
742                write_error_response(w, tag, error)?;
743                Ok(Some(SET_REGULATORY_CONFIG_RESPONSE))
744            }
745            COMMISSIONING_COMPLETE => {
746                let completion = self.commissioning_complete(
747                    // §8.8.2.3 step b.v has already refused this fabric-scoped command over a
748                    // session with no accessing fabric, so reaching here with one means CASE.
749                    ctx.fabric_index.is_some(),
750                    ctx.fabric_index,
751                    ctx.now,
752                );
753                match completion.cleanup {
754                    Some(cleanup) => self.aftermath.set(Some(Aftermath::Rollback(cleanup))),
755                    None if completion.close_pase_sessions => {
756                        self.aftermath.set(Some(Aftermath::Commissioned));
757                    }
758                    None => {}
759                }
760                write_error_response(w, tag, completion.error)?;
761                Ok(Some(COMMISSIONING_COMPLETE_RESPONSE))
762            }
763            _ => Err(Status::UnsupportedCommand.into()),
764        }
765    }
766}
767
768/// `ArmFailSafe`'s fields (§11.10.7.2).
769#[derive(Debug, Clone, Copy, PartialEq, Eq)]
770struct ArmFailSafeRequest {
771    expiry_length_seconds: u16,
772    breadcrumb: u64,
773}
774
775impl ArmFailSafeRequest {
776    fn decode(fields: Option<&[u8]>) -> Result<Self, Status> {
777        let fields = fields.ok_or(Status::InvalidCommand)?;
778        // `CommandFields` is §10.6.11's context-2 member of the `CommandDataIB`, so it
779        // arrives tagged — read it as the fragment it is, not as a whole TLV document.
780        let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
781        let element = reader
782            .next_element()
783            .map_err(|_| Status::InvalidCommand)?
784            .ok_or(Status::InvalidCommand)?;
785        if element.value.container() != Some(ContainerKind::Structure) {
786            return Err(Status::InvalidCommand);
787        }
788        // Both fields are mandatory, but `ExpiryLengthSeconds` has a fallback of 900 — a
789        // client that omits it is asking for the default, not making a malformed request.
790        let mut expiry: Option<u16> = None;
791        let mut breadcrumb: Option<u64> = None;
792        let start_depth = reader.depth();
793        loop {
794            // Two ways this loop must *not* end: a decode failure, and the buffer running
795            // out before the structure closes. Either treated as an end of input would
796            // accept a truncated ArmFailSafe and silently apply `ExpiryLengthSeconds`'
797            // fallback of 900 — arming the fail-safe for fifteen minutes on garbage.
798            let Some(field) = reader.next_element().map_err(|_| Status::InvalidCommand)? else {
799                return Err(Status::InvalidCommand);
800            };
801            if reader.depth() < start_depth {
802                break;
803            }
804            match field.tag {
805                Tag::Context(0) => {
806                    let value = field.unsigned().map_err(|_| Status::InvalidCommand)?;
807                    set_once(
808                        &mut expiry,
809                        u16::try_from(value).map_err(|_| Status::ConstraintError)?,
810                    )
811                    .map_err(|_| Status::InvalidCommand)?;
812                }
813                Tag::Context(1) => {
814                    let value = field.unsigned().map_err(|_| Status::InvalidCommand)?;
815                    set_once(&mut breadcrumb, value).map_err(|_| Status::InvalidCommand)?;
816                }
817                _ => reader
818                    .skip_value(&field)
819                    .map_err(|_| Status::InvalidCommand)?,
820            }
821        }
822        Ok(Self {
823            expiry_length_seconds: expiry
824                .unwrap_or(crate::commissioning::failsafe::DEFAULT_EXPIRY_SECONDS),
825            breadcrumb: breadcrumb.ok_or(Status::InvalidCommand)?,
826        })
827    }
828}
829
830/// `SetRegulatoryConfig`'s fields (§11.10.7.4).
831#[derive(Debug, Clone, Copy, PartialEq, Eq)]
832struct SetRegulatoryConfigRequest<'a> {
833    new_config: RegulatoryLocation,
834    country_code: &'a str,
835    breadcrumb: u64,
836}
837
838impl<'a> SetRegulatoryConfigRequest<'a> {
839    fn decode(fields: Option<&'a [u8]>) -> Result<Self, Status> {
840        let fields = fields.ok_or(Status::InvalidCommand)?;
841        // `CommandFields` is §10.6.11's context-2 member of the `CommandDataIB`, so it
842        // arrives tagged — read it as the fragment it is, not as a whole TLV document.
843        let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
844        let element = reader
845            .next_element()
846            .map_err(|_| Status::InvalidCommand)?
847            .ok_or(Status::InvalidCommand)?;
848        if element.value.container() != Some(ContainerKind::Structure) {
849            return Err(Status::InvalidCommand);
850        }
851        let mut new_config: Option<RegulatoryLocation> = None;
852        let mut country_code: Option<&str> = None;
853        let mut breadcrumb: Option<u64> = None;
854        let start_depth = reader.depth();
855        loop {
856            // As above: a malformed or truncated remainder fails the command, and only the
857            // structure's own end-of-container ends the loop.
858            let Some(field) = reader.next_element().map_err(|_| Status::InvalidCommand)? else {
859                return Err(Status::InvalidCommand);
860            };
861            if reader.depth() < start_depth {
862                break;
863            }
864            match field.tag {
865                Tag::Context(0) => {
866                    let value = field.unsigned().map_err(|_| Status::InvalidCommand)?;
867                    let value = u8::try_from(value).map_err(|_| Status::ConstraintError)?;
868                    // §11.10.5.2 defines three values; anything else is a constraint error
869                    // rather than a silently-clamped mode.
870                    let location =
871                        RegulatoryLocation::from_value(value).ok_or(Status::ConstraintError)?;
872                    set_once(&mut new_config, location).map_err(|_| Status::InvalidCommand)?;
873                }
874                Tag::Context(1) => {
875                    let text = field.utf8().map_err(|_| Status::InvalidCommand)?;
876                    set_once(&mut country_code, text).map_err(|_| Status::InvalidCommand)?;
877                }
878                Tag::Context(2) => {
879                    let value = field.unsigned().map_err(|_| Status::InvalidCommand)?;
880                    set_once(&mut breadcrumb, value).map_err(|_| Status::InvalidCommand)?;
881                }
882                _ => reader
883                    .skip_value(&field)
884                    .map_err(|_| Status::InvalidCommand)?,
885            }
886        }
887        Ok(Self {
888            new_config: new_config.ok_or(Status::InvalidCommand)?,
889            country_code: country_code.ok_or(Status::InvalidCommand)?,
890            breadcrumb: breadcrumb.ok_or(Status::InvalidCommand)?,
891        })
892    }
893}
894
895/// The response shape all three commands share: `ErrorCode [0]`, `DebugText [1]`.
896///
897/// §11.10.7.1: `DebugText` "SHOULD NOT be presented directly in user interfaces. Its purpose
898/// is to help developers in troubleshooting errors." It is mandatory with a fallback of `""`,
899/// and a device that filled it would be leaking its internals to anyone who can invoke the
900/// command — so this always writes the empty string.
901fn write_error_response(
902    w: &mut TlvWriter<'_>,
903    tag: Tag,
904    error: CommissioningError,
905) -> Result<(), Status> {
906    let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
907    full(w.start_structure(tag))?;
908    full(w.unsigned(Tag::Context(0), u64::from(error.value())))?;
909    full(w.utf8(Tag::Context(1), ""))?;
910    full(w.end_container())
911}
912
913impl Cluster for GeneralCommissioning<'_> {
914    const ID: ClusterId = ID;
915}