Skip to main content

matter_controller/
controller.rs

1//! `MatterController` — the public entry point. A cheap, cloneable handle
2//! over the owning actor task (a crate-internal `tokio` task).
3
4use std::sync::Arc;
5
6use matter_commissioning::driver::AsyncDatagram;
7use matter_commissioning::{NocRng, SystemNocRng};
8use matter_transport::Discovery;
9use tokio::sync::{mpsc, oneshot};
10
11use crate::actor::{Actor, Command};
12use crate::builder::MatterControllerBuilder;
13use crate::error::Error;
14use crate::fabric::FabricConfig;
15use crate::node::Node;
16use crate::node_info::NodeInfo;
17use crate::snapshot;
18use crate::state::ControllerState;
19use crate::store::ControllerStore;
20use crate::trust::AttestationTrust;
21
22/// `BasicInformation` cluster id (Matter §11.1) — read post-commission for the
23/// device's `VendorID`/`ProductID`. Sourced from the generated cluster
24/// definitions so it stays tied to the codegen source of truth.
25const BASIC_INFORMATION_CLUSTER: u32 = matter_clusters::gen::basic_information::CLUSTER_ID;
26/// `BasicInformation.VendorID` attribute id.
27const BASIC_INFO_ATTR_VENDOR_ID: u32 =
28    matter_clusters::gen::basic_information::attribute_id::VENDOR_ID;
29/// `BasicInformation.ProductID` attribute id.
30const BASIC_INFO_ATTR_PRODUCT_ID: u32 =
31    matter_clusters::gen::basic_information::attribute_id::PRODUCT_ID;
32
33const COMMAND_CHANNEL_DEPTH: usize = 32;
34
35/// Addresses to advertise for a self-hosted operational service (OTA provider,
36/// ICD check-in listener). A wildcard bind (`[::]`) reports an unspecified
37/// `local_addr` that a peer cannot resolve to anything routable, so substitute
38/// the host's real routable address(es); fall back to the bind address only if
39/// none can be found (e.g. fully offline).
40fn advertise_addrs(local: std::net::SocketAddr) -> Vec<std::net::IpAddr> {
41    if local.ip().is_unspecified() {
42        let real = matter_transport::local_advertise_addrs();
43        if real.is_empty() {
44            vec![local.ip()]
45        } else {
46            real
47        }
48    } else {
49        vec![local.ip()]
50    }
51}
52
53/// The high-level Matter controller. Cloneable; all clones talk to one
54/// owning task.
55#[derive(Clone)]
56pub struct MatterController {
57    tx: mpsc::Sender<Command>,
58    /// Retained so the OTA provider server ([`Self::serve_provider_once`]) can
59    /// load the stable, committed operational identity without routing through
60    /// the actor (the identity is minted once and never mutated after).
61    store: Arc<dyn ControllerStore>,
62}
63
64impl MatterController {
65    /// Begin configuring a controller (attestation trust, admin vendor id).
66    #[must_use]
67    pub fn builder(store: Arc<dyn ControllerStore>) -> MatterControllerBuilder {
68        MatterControllerBuilder::new(store)
69    }
70
71    /// Open a controller with default settings and **no** attestation trust —
72    /// sufficient for operating already-commissioned devices, but `commission`
73    /// will return [`Error::NoTrust`]. Use [`Self::builder`] to commission.
74    ///
75    /// # Errors
76    ///
77    /// As [`MatterControllerBuilder::build`].
78    pub async fn open(store: Arc<dyn ControllerStore>) -> Result<Self, Error> {
79        Self::spawn_default(store, None, crate::builder::DEFAULT_ADMIN_VENDOR_ID, None).await
80    }
81
82    pub(crate) async fn spawn_default(
83        store: Arc<dyn ControllerStore>,
84        trust: Option<AttestationTrust>,
85        admin_vendor_id: u16,
86        multicast_if: Option<u32>,
87    ) -> Result<Self, Error> {
88        let transport =
89            matter_transport::TokioUdpTransport::bind_with_multicast_if(0, multicast_if)
90                .await
91                .map_err(|e| Error::Operational(format!("bind: {e}")))?;
92        let discovery = matter_transport::MdnsSdDiscovery::new()
93            .map_err(|e| Error::Operational(format!("mdns: {e}")))?;
94        Self::with_components_and_multicast_if(
95            store,
96            transport,
97            discovery,
98            Arc::new(SystemNocRng),
99            trust,
100            admin_vendor_id,
101            multicast_if,
102        )
103    }
104
105    /// Construct over caller-supplied transport + discovery (used by tests to
106    /// inject `InMemoryDatagram` + a mock `Discovery`).
107    ///
108    /// # Errors
109    ///
110    /// [`Error::Store`] / [`Error::Snapshot`] if the persisted snapshot is
111    /// unreadable.
112    #[cfg(test)] // production construction goes through `with_components_and_multicast_if`.
113    pub(crate) fn with_components<T, D>(
114        store: Arc<dyn ControllerStore>,
115        transport: T,
116        discovery: D,
117        rng: Arc<dyn NocRng>,
118        trust: Option<AttestationTrust>,
119        admin_vendor_id: u16,
120    ) -> Result<Self, Error>
121    where
122        T: AsyncDatagram + Send + Sync + 'static,
123        D: Discovery + Send + 'static,
124    {
125        Self::with_components_and_multicast_if(
126            store,
127            transport,
128            discovery,
129            rng,
130            trust,
131            admin_vendor_id,
132            None,
133        )
134    }
135
136    #[allow(clippy::too_many_arguments)] // Component-injection seam; mirrors Actor::new.
137    pub(crate) fn with_components_and_multicast_if<T, D>(
138        store: Arc<dyn ControllerStore>,
139        transport: T,
140        discovery: D,
141        rng: Arc<dyn NocRng>,
142        trust: Option<AttestationTrust>,
143        admin_vendor_id: u16,
144        multicast_if: Option<u32>,
145    ) -> Result<Self, Error>
146    where
147        // `Sync` because the spawned actor future holds `&self.transport`
148        // across awaits (inside `run_case`/`secured_round_trip`); `Send` so the
149        // future can be `tokio::spawn`ed onto the multi-thread runtime.
150        T: AsyncDatagram + Send + Sync + 'static,
151        D: Discovery + Send + 'static,
152    {
153        let state = match store.load()? {
154            Some(bytes) => snapshot::deserialize(&bytes)?,
155            None => ControllerState::default(),
156        };
157        let (tx, rx) = mpsc::channel(COMMAND_CHANNEL_DEPTH);
158        let actor = Actor::new(
159            transport,
160            discovery,
161            store.clone(),
162            rng,
163            state,
164            trust,
165            admin_vendor_id,
166        )
167        .with_multicast_if(multicast_if);
168        tokio::spawn(actor.run(rx));
169        Ok(Self { tx, store })
170    }
171
172    /// Serve the OTA **provider** role once: advertise our operational service,
173    /// accept one inbound CASE session, and dispatch up to `max_invokes`
174    /// server-side `InvokeRequest`s through `handler`, then withdraw the
175    /// advertisement. `handler` maps a parsed request to the encoded
176    /// `InvokeResponse` bytes (e.g. via `matter_interaction::build_invoke_response_*`).
177    ///
178    /// The server runs on its **own** freshly-bound UDP socket and its own mDNS
179    /// daemon — it does not touch the client actor (the long-running accept is
180    /// kept off the proven request/MRP loop). It authenticates as our persisted
181    /// operational identity (the M8 commissioner NOC/IPK/root).
182    ///
183    /// This ships the generic provider plumbing; the OTA `QueryImage` handler
184    /// and the BDX transfer build on it. Note: advertising a wildcard-bound
185    /// address may not be routable to a foreign requestor — see the runbook
186    /// for the interface-selection caveat (the automated validation is the
187    /// in-process loopback test).
188    ///
189    /// # Errors
190    ///
191    /// [`Error::NotCommissioned`] if no fabric exists; [`Error::Operational`] on
192    /// bind / mDNS / clock failure; otherwise any CASE-accept or dispatch error
193    /// from [`crate::provider_server::ProviderServer`].
194    #[cfg(feature = "unstable-provider")]
195    pub async fn serve_provider_once<H>(
196        &self,
197        port: u16,
198        handler: H,
199        max_invokes: usize,
200    ) -> Result<usize, Error>
201    where
202        H: FnMut(&matter_interaction::ParsedInvokeRequest) -> Vec<u8>,
203    {
204        use crate::provider_server::{build_operational_service, ProviderServer};
205
206        // 1. Load our persisted fabric + build the responder identity.
207        let state = match self.store.load()? {
208            Some(bytes) => snapshot::deserialize(&bytes)?,
209            None => return Err(Error::NotCommissioned("no fabric to serve from".into())),
210        };
211        let fabric = state
212            .fabrics
213            .first()
214            .ok_or_else(|| Error::NotCommissioned("no fabric to serve from".into()))?;
215        let (credentials, roots, compressed) = crate::credentials::operational_credentials(fabric)?;
216        let node_id = fabric.commissioner.node_id;
217        let now = crate::actor::current_matter_time()?;
218
219        // 2. Bind our own socket + advertise the operational service.
220        let socket = matter_transport::TokioUdpTransport::bind(port)
221            .await
222            .map_err(|e| Error::Operational(format!("provider bind: {e}")))?;
223        let local = socket
224            .socket()
225            .local_addr()
226            .map_err(|e| Error::Operational(format!("provider local_addr: {e}")))?;
227        let mut discovery = matter_transport::MdnsSdDiscovery::new()
228            .map_err(|e| Error::Operational(format!("provider mdns: {e}")))?;
229        let service =
230            build_operational_service(compressed, node_id, advertise_addrs(local), local.port());
231        matter_transport::Discovery::publish(&mut discovery, &service)?;
232
233        // 3. Accept one session + dispatch up to `max_invokes` invokes.
234        let result = ProviderServer::new(
235            socket,
236            vec![credentials],
237            roots,
238            /* base_session_id */ 0x01,
239            now,
240        )
241        .accept_and_dispatch_once(handler, max_invokes)
242        .await;
243
244        // 4. Withdraw the advertisement regardless of outcome.
245        let _ = matter_transport::Discovery::unpublish(
246            &mut discovery,
247            &service.instance_name,
248            matter_transport::ServiceKind::Operational,
249        );
250        result
251    }
252
253    /// Announce ourselves as an OTA provider to `target_node_id`, advertise our
254    /// operational service, and serve `image` over the full OTA flow (the
255    /// requestor resolves us, opens CASE, queries, BDX-downloads, applies, and
256    /// — possibly after rebooting into the new image — sends
257    /// `NotifyUpdateApplied`). Returns once `NotifyUpdateApplied` is received.
258    ///
259    /// `software_version` is offered in `QueryImageResponse` (must exceed the
260    /// requestor's current version for it to update — and match the version
261    /// baked into the `.ota` header for a live requestor). `port` binds the
262    /// provider socket (0 = ephemeral). The image is served verbatim over BDX
263    /// (unsigned; the requestor parses the `OTAImageHeader`).
264    ///
265    /// Because a real requestor reboots into the new image before notifying,
266    /// the call may block for an extended period. Callers should bound the wait
267    /// with [`tokio::time::timeout`]. Each accepted CASE session's resumption
268    /// record is persisted immediately via an internal sink (best-effort: a
269    /// failed store only costs a future fast path).
270    ///
271    /// # Errors
272    ///
273    /// [`Error::NotCommissioned`] if no fabric exists; [`Error::Operational`] on
274    /// bind / mDNS / clock failure; otherwise any announce or serve error.
275    pub async fn serve_ota(
276        &self,
277        target_node_id: u64,
278        image: Vec<u8>,
279        software_version: u32,
280        port: u16,
281    ) -> Result<(), Error> {
282        // 960 keeps each BDX DataBlock (block + counter + BDX/IM framing) under
283        // the transport's 1024-byte secured-payload budget — correct for Wi-Fi
284        // and IP. For a Thread-routed requestor use
285        // [`Self::serve_ota_with_block_size`] with ~512: at 960 a single block
286        // spans ~a dozen 802.15.4 fragments that must ALL arrive, so a smaller
287        // block cuts the per-block loss probability on the mesh (BDX-4).
288        self.serve_ota_with_block_size(target_node_id, image, software_version, port, 960)
289            .await
290    }
291
292    /// [`Self::serve_ota`] with an explicit BDX `max_block_size`. Pass a smaller
293    /// value (~512) for a Thread-routed requestor so each block fits fewer
294    /// 6LoWPAN fragments; 960 is the Wi-Fi/IP default (see [`Self::serve_ota`]).
295    ///
296    /// # Errors
297    ///
298    /// Same as [`Self::serve_ota`].
299    pub async fn serve_ota_with_block_size(
300        &self,
301        target_node_id: u64,
302        image: Vec<u8>,
303        software_version: u32,
304        port: u16,
305        max_block_size: u16,
306    ) -> Result<(), Error> {
307        use crate::provider_server::{build_operational_service, ProviderServer};
308
309        // Credential pool: one identity per CASE accept (first session +
310        // post-reboot session + retry slack — see the spec).
311        const PROVIDER_CREDENTIAL_POOL: usize = 4;
312
313        // Identity + offer.
314        let state = match self.store.load()? {
315            Some(bytes) => snapshot::deserialize(&bytes)?,
316            None => return Err(Error::NotCommissioned("no fabric to serve from".into())),
317        };
318        let fabric = state
319            .fabrics
320            .first()
321            .ok_or_else(|| Error::NotCommissioned("no fabric to serve from".into()))?;
322        let mut pool = Vec::with_capacity(PROVIDER_CREDENTIAL_POOL);
323
324        let mut roots_compressed = None;
325        for _ in 0..PROVIDER_CREDENTIAL_POOL {
326            let (c, r, comp) = crate::credentials::operational_credentials(fabric)?;
327            pool.push(c);
328            roots_compressed = Some((r, comp));
329        }
330        let (roots, compressed) =
331            roots_compressed.ok_or_else(|| Error::Operational("empty credential pool".into()))?;
332        let node_id = fabric.commissioner.node_id;
333        let now = crate::actor::current_matter_time()?;
334        let offer = matter_ota::ImageOffer {
335            software_version,
336            software_version_string: software_version.to_string(),
337            image_uri: format!("bdx://{node_id:016X}/fw.ota"),
338            update_token: vec![0xAB; 16],
339        };
340
341        // Bind + advertise.
342        let socket = matter_transport::TokioUdpTransport::bind(port)
343            .await
344            .map_err(|e| Error::Operational(format!("provider bind: {e}")))?;
345        let local = socket
346            .socket()
347            .local_addr()
348            .map_err(|e| Error::Operational(format!("provider local_addr: {e}")))?;
349        let mut discovery = matter_transport::MdnsSdDiscovery::new()
350            .map_err(|e| Error::Operational(format!("provider mdns: {e}")))?;
351        let service =
352            build_operational_service(compressed, node_id, advertise_addrs(local), local.port());
353        matter_transport::Discovery::publish(&mut discovery, &service)?;
354
355        // Announce FIRST (a client invoke to the device over a fresh CASE
356        // connect), and only then build the server: the requestor's QueryImage
357        // Sigma1 requests RESUMPTION of the session the announce just
358        // established, so the server must be seeded with the resumption
359        // record that connect persisted — which exists only after the
360        // announce completes. The provider socket is already bound and
361        // advertised above, so a Sigma1 arriving in the gap merely waits in
362        // the socket buffer (and chip MRP-retransmits it regardless).
363        let node = self.node(target_node_id);
364        let announce_res = node
365            .announce_ota_provider(node_id, crate::builder::DEFAULT_ADMIN_VENDOR_ID, 0)
366            .await;
367        if let Err(e) = announce_res {
368            let _ = matter_transport::Discovery::unpublish(
369                &mut discovery,
370                &service.instance_name,
371                matter_transport::ServiceKind::Operational,
372            );
373            return Err(e);
374        }
375
376        // Fetch the announce connect's resumption record from live actor
377        // state (guaranteed present: the announce rode that session). A
378        // missing/corrupt record only costs the fast path — the server then
379        // declines and falls back to a full handshake.
380        let records = match self.resumption_record_for(target_node_id).await {
381            Ok(Some(r)) => vec![r],
382            Ok(None) | Err(_) => Vec::new(),
383        };
384
385        let sink_controller = self.clone();
386        let server = ProviderServer::new(socket, pool, roots, /* base_session_id */ 0x01, now)
387            .with_resumption_records(records)
388            .with_expected_peer(target_node_id)
389            .with_record_sink(Box::new(move |record| {
390                let c = sink_controller.clone();
391                tokio::spawn(async move {
392                    // Best-effort: a failed store only costs a future fast path.
393                    let node = record.peer.node_id;
394                    let _ = c.store_resumption_record(node, &record).await;
395                });
396            }));
397        // `max_block_size` must keep each BDX DataBlock (block + 4-byte counter
398        // + BDX/IM framing) under the transport's 1024-byte secured-payload
399        // budget — 960 is the Wi-Fi/IP default (1024 overflows by 14 bytes once
400        // framed); a Thread caller passes ~512 (BDX-4).
401        let serve_res = server.serve_ota_once(offer, image, max_block_size).await;
402
403        let _ = matter_transport::Discovery::unpublish(
404            &mut discovery,
405            &service.instance_name,
406            matter_transport::ServiceKind::Operational,
407        );
408
409        serve_res?;
410        Ok(())
411    }
412
413    /// Advertise our operational service and listen for ONE inbound Check-In
414    /// from a registered ICD, verify it against the stored registration key
415    /// (enforcing counter monotonicity), and return it — the caller then
416    /// re-establishes a session and reads/subscribes / `stay_active_request`s
417    /// while the device is briefly active.
418    ///
419    /// Runs on its **own** freshly-bound UDP socket + mDNS daemon, off the
420    /// client actor. Requires at least one registration from
421    /// [`Node::register_icd_client`](crate::Node::register_icd_client).
422    ///
423    /// # Errors
424    ///
425    /// [`Error::NotCommissioned`] if no fabric exists; [`Error::Operational`] if
426    /// no ICD clients are registered, on bind / mDNS failure, or if no
427    /// verifiable Check-In arrives before the internal frame budget is reached.
428    pub async fn listen_for_checkin_once(
429        &self,
430        port: u16,
431    ) -> Result<crate::icd_listener::CheckIn, Error> {
432        use crate::provider_server::build_operational_service;
433
434        // Load registrations + advertising identity from the persisted fabric.
435        let state = match self.store.load()? {
436            Some(bytes) => snapshot::deserialize(&bytes)?,
437            None => return Err(Error::NotCommissioned("no fabric to listen from".into())),
438        };
439        let fabric = state
440            .fabrics
441            .first()
442            .ok_or_else(|| Error::NotCommissioned("no fabric to listen from".into()))?;
443        let registrations = fabric.icd_clients.clone();
444        if registrations.is_empty() {
445            return Err(Error::Operational(
446                "no registered ICD clients to listen for".into(),
447            ));
448        }
449        let (_creds, _roots, compressed) = crate::credentials::operational_credentials(fabric)?;
450        let node_id = fabric.commissioner.node_id;
451
452        // Bind our own socket + advertise (so a registered ICD can resolve us).
453        let socket = matter_transport::TokioUdpTransport::bind(port)
454            .await
455            .map_err(|e| Error::Operational(format!("ICD listener bind: {e}")))?;
456        let local = socket
457            .socket()
458            .local_addr()
459            .map_err(|e| Error::Operational(format!("ICD listener local_addr: {e}")))?;
460        let mut discovery = matter_transport::MdnsSdDiscovery::new()
461            .map_err(|e| Error::Operational(format!("ICD listener mdns: {e}")))?;
462        let service =
463            build_operational_service(compressed, node_id, advertise_addrs(local), local.port());
464        matter_transport::Discovery::publish(&mut discovery, &service)?;
465
466        // Listen for one verifiable Check-In (generous frame budget for noise).
467        let result = crate::icd_listener::recv_checkin_once(&socket, &registrations, 256).await;
468
469        let _ = matter_transport::Discovery::unpublish(
470            &mut discovery,
471            &service.instance_name,
472            matter_transport::ServiceKind::Operational,
473        );
474        result
475    }
476
477    /// Create and persist a new fabric (mints the stable commissioner
478    /// identity). Returns the new fabric id.
479    ///
480    /// # Errors
481    ///
482    /// [`Error::ControllerStopped`] if the task has stopped; otherwise any
483    /// minting / persistence error.
484    pub async fn create_fabric(&self, cfg: FabricConfig) -> Result<u64, Error> {
485        let (reply, rx) = oneshot::channel();
486        self.tx
487            .send(Command::CreateFabric { cfg, reply })
488            .await
489            .map_err(|_| Error::ControllerStopped)?;
490        rx.await.map_err(|_| Error::ControllerStopped)?
491    }
492
493    /// Commission a device from a QR (`MT:...`) or manual pairing code, bring it
494    /// onto the controller's fabric, and persist it. Returns a [`NodeInfo`] for
495    /// the commissioned device.
496    ///
497    /// After the device is on the fabric, a best-effort `BasicInformation` read
498    /// captures its `VendorID`/`ProductID` into the returned `NodeInfo` and
499    /// persists them on the device entry. That read is best-effort: if it fails,
500    /// commissioning still succeeds and `NodeInfo::vendor_id`/`product_id` are
501    /// left `None` (re-readable later via [`Self::nodes`]).
502    ///
503    /// `label` is an opaque, caller-supplied string (e.g. a friendly name like
504    /// `"kitchen plug"`) persisted on the device's entry atomically with the
505    /// rest of the commissioning result — a crash after this call returns
506    /// either sees the fully-commissioned device with its label, or nothing
507    /// at all, never a device missing its label. Pass `None` if you have no
508    /// label to attach yet; it can be left unset.
509    ///
510    /// # Errors
511    ///
512    /// [`Error::NoTrust`] if no attestation trust was configured,
513    /// [`Error::SetupCode`] if the code is invalid, [`Error::ControllerStopped`]
514    /// if the task stopped, or any driver/commissioning error.
515    pub async fn commission(
516        &self,
517        setup_code: &str,
518        label: Option<String>,
519    ) -> Result<NodeInfo, Error> {
520        let setup_payload = parse_setup_code(setup_code)?;
521        let (reply, rx) = oneshot::channel();
522        self.tx
523            .send(Command::Commission {
524                setup_payload,
525                label,
526                reply,
527            })
528            .await
529            .map_err(|_| Error::ControllerStopped)?;
530        let mut info = rx.await.map_err(|_| Error::ControllerStopped)??;
531        self.capture_basic_info(&mut info).await;
532        Ok(info)
533    }
534
535    /// Commission a Wi-Fi or Thread device over **BLE/BTP** (feature `ble`):
536    /// scan for the device by discriminator, open a BTP session, run PASE and
537    /// every pre-operational stage (attestation, NOC install, network
538    /// provisioning) over BTP, then complete the operational CASE session over
539    /// IP once the device joins the operational network. Brings the device
540    /// onto the controller's fabric, persists it, and returns a [`NodeInfo`]
541    /// (including a best-effort `BasicInformation` `VendorID`/`ProductID`
542    /// capture, exactly as [`Self::commission`]).
543    ///
544    /// `network` selects which provisioning sub-flow runs after `AddNOC`:
545    /// [`NetworkCredentials::WiFi`](matter_commissioning::NetworkCredentials::WiFi)
546    /// or
547    /// [`NetworkCredentials::Thread`](matter_commissioning::NetworkCredentials::Thread).
548    /// Some network credentials are **required** for a BLE-only device with no
549    /// operational connectivity yet — a BLE-only device with no network to
550    /// join is unprovisionable;
551    /// [`NetworkCredentials::AlreadyOnNetwork`](matter_commissioning::NetworkCredentials::AlreadyOnNetwork)
552    /// only makes sense for a device that already has operational connectivity
553    /// independent of BLE (e.g. Ethernet).
554    ///
555    /// **Requires macOS Bluetooth permission (TCC).** The first call
556    /// instantiates `CoreBluetooth` and may raise the one-time Bluetooth prompt,
557    /// attributed to the terminal application — see
558    /// `docs/runbooks/ble-commissioning.md`.
559    ///
560    /// `label` is the same opaque, caller-supplied string as
561    /// [`Self::commission`]'s — persisted on the device's entry atomically
562    /// with the rest of the commissioning result. Pass `None` if you have no
563    /// label to attach yet.
564    ///
565    /// # Errors
566    ///
567    /// [`Error::NoTrust`] if no attestation trust was configured,
568    /// [`Error::SetupCode`] if the code is invalid, [`Error::ControllerStopped`]
569    /// if the task stopped (including a btleplug-internal panic in the spawned
570    /// commission task), [`Error::Operational`] for a BLE-layer failure (no
571    /// adapter / denied permission, scan timeout, connect, GATT, or BTP
572    /// handshake), or any driver/commissioning error.
573    #[cfg(feature = "ble")]
574    pub async fn commission_ble(
575        &self,
576        setup_code: &str,
577        network: matter_commissioning::NetworkCredentials,
578        label: Option<String>,
579    ) -> Result<NodeInfo, Error> {
580        let setup_payload = parse_setup_code(setup_code)?;
581        let (reply, rx) = oneshot::channel();
582        self.tx
583            .send(Command::CommissionBle {
584                setup_payload,
585                network,
586                label,
587                reply,
588            })
589            .await
590            .map_err(|_| Error::ControllerStopped)?;
591        let mut info = rx.await.map_err(|_| Error::ControllerStopped)??;
592        self.capture_basic_info(&mut info).await;
593        Ok(info)
594    }
595
596    /// Best-effort: read `VendorID`/`ProductID` from the device's
597    /// `BasicInformation` cluster (endpoint 0) and persist them onto the node's
598    /// stored entry, filling `info.vendor_id`/`info.product_id`.
599    ///
600    /// Deliberately infallible from the caller's view: commissioning has
601    /// already succeeded and the device is on the fabric, so a flaky metadata
602    /// read (or a device that answers something unexpected) must never turn a
603    /// completed commission into an error. On any failure the ids stay `None`
604    /// and can be re-read later.
605    async fn capture_basic_info(&self, info: &mut NodeInfo) {
606        let node = self.node(info.node_id);
607        let paths = [
608            crate::ReadPath::concrete(0, BASIC_INFORMATION_CLUSTER, BASIC_INFO_ATTR_VENDOR_ID),
609            crate::ReadPath::concrete(0, BASIC_INFORMATION_CLUSTER, BASIC_INFO_ATTR_PRODUCT_ID),
610        ];
611        let Ok(reports) = node.read(&paths).await else {
612            return;
613        };
614        let mut vendor_id = None;
615        let mut product_id = None;
616        for (path, value) in &reports {
617            let crate::Value::Uint(n) = value else {
618                continue;
619            };
620            let Ok(n16) = u16::try_from(*n) else { continue };
621            if path.attribute == BASIC_INFO_ATTR_VENDOR_ID {
622                vendor_id = Some(n16);
623            } else if path.attribute == BASIC_INFO_ATTR_PRODUCT_ID {
624                product_id = Some(n16);
625            }
626        }
627        if vendor_id.is_none() && product_id.is_none() {
628            return;
629        }
630        info.vendor_id = vendor_id;
631        info.product_id = product_id;
632        // Persist best-effort — a store failure here only means a future
633        // `nodes()` re-reads `None`; it does not fail the commission.
634        let (reply, rx) = oneshot::channel();
635        if self
636            .tx
637            .send(Command::SetNodeVidPid {
638                node_id: info.node_id,
639                vendor_id,
640                product_id,
641                reply,
642            })
643            .await
644            .is_ok()
645        {
646            let _ = rx.await;
647        }
648    }
649
650    /// Enumerate every node this controller has commissioned, across all
651    /// fabrics, as typed [`NodeInfo`]. Replaces the need to deserialize the
652    /// on-disk snapshot to discover node ids and metadata.
653    ///
654    /// # Errors
655    ///
656    /// [`Error::ControllerStopped`] if the owning task has stopped.
657    pub async fn nodes(&self) -> Result<Vec<NodeInfo>, Error> {
658        let (reply, rx) = oneshot::channel();
659        self.tx
660            .send(Command::ListNodes { reply })
661            .await
662            .map_err(|_| Error::ControllerStopped)?;
663        rx.await.map_err(|_| Error::ControllerStopped)
664    }
665
666    /// Forget a node: drop ALL of the controller's own state for it — the
667    /// persisted device record, any cached CASE session, and its resumption
668    /// data — WITHOUT contacting the device. Use this to reclaim a node that is
669    /// unreachable or already factory-reset (where `remove_fabric` cannot run).
670    ///
671    /// Returns `true` if a node was found and removed, `false` if no such node
672    /// was commissioned. This does NOT remove the controller's fabric from the
673    /// device; a still-live device keeps its NOC until it is reset or its fabric
674    /// removed via `Node::remove_fabric`.
675    ///
676    /// # Errors
677    ///
678    /// [`Error::ControllerStopped`] if the task stopped, or a store error while
679    /// persisting the removal.
680    pub async fn forget_node(&self, node_id: u64) -> Result<bool, Error> {
681        let (reply, rx) = oneshot::channel();
682        self.tx
683            .send(Command::ForgetNode { node_id, reply })
684            .await
685            .map_err(|_| Error::ControllerStopped)?;
686        rx.await.map_err(|_| Error::ControllerStopped)?
687    }
688
689    /// Handle addressing a device by node id (single-fabric).
690    #[must_use]
691    pub fn node(&self, node_id: u64) -> Node {
692        Node {
693            tx: self.tx.clone(),
694            node_id,
695        }
696    }
697
698    /// Create a group key set on the controller's fabric: mints a fresh 16-byte
699    /// epoch key from the CSPRNG, persists a `GroupKeySetConfig` under
700    /// `key_set_id`, and returns the [`GroupKeySet`](crate::GroupKeySet) so the caller can program
701    /// it onto each member device via
702    /// [`Node::write_group_key_set`](crate::Node::write_group_key_set) and map a
703    /// group to it. The key set is stored durably before this returns, so the
704    /// controller can encrypt outbound group messages for it immediately
705    /// (see [`Self::invoke_group`]).
706    ///
707    /// `epoch_start_time` is the Matter-epoch start time recorded in the
708    /// returned `GroupKeySet` (the device-side `KeySetWrite` echoes it).
709    ///
710    /// # Errors
711    ///
712    /// [`Error::NotCommissioned`] if no single fabric exists,
713    /// [`Error::ControllerStopped`] if the task has stopped, or any
714    /// CSPRNG / persistence error.
715    pub async fn create_group(
716        &self,
717        key_set_id: u16,
718        epoch_start_time: u64,
719    ) -> Result<crate::GroupKeySet, Error> {
720        let (reply, rx) = oneshot::channel();
721        self.tx
722            .send(Command::CreateGroup {
723                key_set_id,
724                epoch_start_time,
725                reply,
726            })
727            .await
728            .map_err(|_| Error::ControllerStopped)?;
729        rx.await.map_err(|_| Error::ControllerStopped)?
730    }
731
732    /// Fire-and-forget multicast group invoke: send `path`/`fields` to every
733    /// device in `group_id`, encrypted with the operational group key derived
734    /// from the persisted `key_set_id`. Returns as soon as the datagram is sent
735    /// — group commands are unacknowledged, so there is no response.
736    ///
737    /// The caller supplies `key_set_id` (the key set the group was bound to when
738    /// it was created): the controller's persisted `group_keys` are keyed by
739    /// key set id, avoiding a separate group→key-set map. The outbound group
740    /// message counter is bumped and persisted **before** the send so a counter
741    /// is never reused across a crash.
742    ///
743    /// Real multicast delivery requires the host network to route the Matter
744    /// site-local group address; on a host without it the send still succeeds at
745    /// the socket layer (the bytes are correct — see the loopback test).
746    ///
747    /// # Errors
748    ///
749    /// [`Error::GroupNotProvisioned`] if `key_set_id` has no persisted key set,
750    /// [`Error::NotCommissioned`] if no single fabric exists,
751    /// [`Error::Operational`] on counter exhaustion or send failure,
752    /// [`Error::ControllerStopped`] if the task has stopped, or any
753    /// crypto / persistence error.
754    pub async fn invoke_group(
755        &self,
756        group_id: u16,
757        key_set_id: u16,
758        path: crate::CommandPath,
759        fields: crate::Value,
760    ) -> Result<(), Error> {
761        let fields_tlv = crate::node::value_to_tlv(&fields)?;
762        let (reply, rx) = oneshot::channel();
763        self.tx
764            .send(Command::InvokeGroup {
765                group_id,
766                key_set_id,
767                path,
768                fields_tlv,
769                reply,
770            })
771            .await
772            .map_err(|_| Error::ControllerStopped)?;
773        rx.await.map_err(|_| Error::ControllerStopped)?
774    }
775
776    #[cfg(test)]
777    pub(crate) async fn session_count(&self) -> usize {
778        let (reply, rx) = oneshot::channel();
779        if self.tx.send(Command::SessionCount { reply }).await.is_err() {
780            return 0;
781        }
782        rx.await.unwrap_or(0)
783    }
784
785    /// Fetch the stored CASE resumption record for `node_id` from the actor's
786    /// live state (deserialized; `None` if the device has none). Used by
787    /// [`Self::serve_ota`] to let the provider server accept the requestor's
788    /// resumption attempt.
789    ///
790    /// # Errors
791    ///
792    /// [`Error::ControllerStopped`] if the owning task stopped,
793    /// [`Error::NotCommissioned`] if no sole fabric exists, or a
794    /// [`Error::Snapshot`]/[`Error::Codec`]/[`Error::Cert`] deserialization
795    /// failure for a corrupt stored record.
796    pub(crate) async fn resumption_record_for(
797        &self,
798        node_id: u64,
799    ) -> Result<Option<matter_crypto::ResumptionRecord>, Error> {
800        let (reply, rx) = oneshot::channel();
801        self.tx
802            .send(Command::ResumptionRecordFor { node_id, reply })
803            .await
804            .map_err(|_| Error::ControllerStopped)?;
805        let bytes = rx.await.map_err(|_| Error::ControllerStopped)??;
806        match bytes {
807            Some(b) => Ok(Some(crate::resumption::deserialize_record(&b)?)),
808            None => Ok(None),
809        }
810    }
811
812    /// Store `record` as the CASE resumption record for `node_id` (replacing
813    /// any prior one; best-effort persist). Invoked by [`Self::serve_ota`]'s
814    /// provider server's `record_sink`, once per completed CASE accept.
815    ///
816    /// # Errors
817    ///
818    /// [`Error::ControllerStopped`] if the owning task stopped,
819    /// [`Error::NotCommissioned`] if no sole fabric exists, or
820    /// [`Error::Operational`] if the device has no entry on the fabric.
821    pub(crate) async fn store_resumption_record(
822        &self,
823        node_id: u64,
824        record: &matter_crypto::ResumptionRecord,
825    ) -> Result<(), Error> {
826        let record_bytes = crate::resumption::serialize_record(record)?;
827        let (reply, rx) = oneshot::channel();
828        self.tx
829            .send(Command::StoreResumptionRecord {
830                node_id,
831                record_bytes,
832                reply,
833            })
834            .await
835            .map_err(|_| Error::ControllerStopped)?;
836        rx.await.map_err(|_| Error::ControllerStopped)?
837    }
838}
839
840/// Parse a QR (`MT:...`) or manual pairing code into a [`matter_commissioning::SetupPayload`].
841///
842/// QR codes are identified by the `MT:` prefix (Matter Core Spec §5.1.3.1).
843/// Anything else is treated as a manual pairing code.
844///
845/// # Errors
846///
847/// Returns [`Error::SetupCode`] if the string is not a valid QR or manual code.
848fn parse_setup_code(code: &str) -> Result<matter_commissioning::SetupPayload, Error> {
849    let trimmed = code.trim();
850    let parsed = if trimmed.starts_with("MT:") {
851        matter_commissioning::parse_qr(trimmed)
852    } else {
853        matter_commissioning::parse_manual_code(trimmed)
854    };
855    parsed.map_err(|e| Error::SetupCode(format!("{e:?}")))
856}