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