matter_controller/lib.rs
1#![doc = include_str!("../README.md")]
2#![allow(async_fn_in_trait)]
3
4#[cfg(feature = "ble")]
5mod ble;
6pub mod ca;
7mod controller;
8mod fsutil;
9mod groups;
10mod icd;
11mod identity;
12mod mdns;
13pub mod network;
14pub mod onboarding;
15pub mod ota;
16mod reports;
17pub mod store;
18pub mod x509;
19
20use std::net::SocketAddr;
21use std::path::PathBuf;
22
23use serde::Serialize;
24use serde_json::Value;
25
26pub use ca::{
27 install_intermediate, intermediate_csr, intermediate_path, CertificateAuthority, FileCa,
28 IntermediateCa, Issued, NodeIdRange,
29};
30pub use controller::Controller;
31pub use onboarding::{Discriminator, Onboarding};
32pub use ota::OtaImage;
33pub use reports::decode_report_data;
34pub use store::{BasicInfo, DeviceType, Endpoint, Node, NodeStore};
35
36// The embassy-time driver and timer queue rs-matter's timers run on.
37use embassy_time as _;
38use embassy_time_queue_utils as _;
39
40/// What can go wrong.
41#[derive(Debug, thiserror::Error)]
42pub enum Error {
43 /// rs-matter reported an error.
44 #[error("matter: {0}")]
45 Matter(String),
46 /// A node answered with a status other than success.
47 #[error("{0}")]
48 Status(String),
49 /// The onboarding payload is not valid.
50 #[error("{0}")]
51 Onboarding(String),
52 /// The request does not make sense (unknown node, cluster, field, ...).
53 #[error("{0}")]
54 Invalid(String),
55 /// JSON did not fit the data model.
56 #[error("{0}")]
57 Convert(#[from] matter_model::ConvertError),
58 /// No device answered in time.
59 #[error("{0}")]
60 Timeout(String),
61 /// The store or the CA file could not be read or written.
62 #[error("store: {0}")]
63 Store(String),
64 /// I/O.
65 #[error("io: {0}")]
66 Io(#[from] std::io::Error),
67 /// Something ran out.
68 #[error("out of {0}")]
69 Exhausted(&'static str),
70 /// Not supported (yet).
71 #[error("not supported: {0}")]
72 Unsupported(String),
73 /// Bluetooth failed.
74 #[error("bluetooth: {0}")]
75 Bluetooth(String),
76 /// The controller has stopped.
77 #[error("the controller has stopped")]
78 Stopped,
79}
80
81impl From<rs_matter::error::Error> for Error {
82 fn from(e: rs_matter::error::Error) -> Self {
83 Error::Matter(format!("{e:?}"))
84 }
85}
86
87impl From<serde_json::Error> for Error {
88 fn from(e: serde_json::Error) -> Self {
89 Error::Store(e.to_string())
90 }
91}
92
93/// How the controller runs.
94#[derive(Debug, Clone)]
95pub struct Config {
96 /// Where the CA, the controller's identity and the node store live.
97 pub state_dir: PathBuf,
98 /// UDP port for Matter traffic.
99 pub port: u16,
100 /// Network interface for mDNS (DNS-SD); the first with IPv6 if `None`.
101 pub interface: Option<String>,
102 /// The fabric id of a new fabric; random if `None`. Ignored once the
103 /// fabric exists.
104 pub fabric_id: Option<u64>,
105 /// Where the fabric's certificates come from.
106 pub ca: CaChoice,
107 /// Vendor id the controller administers nodes as (`0xFFF1` is the CSA's
108 /// test vendor id, for uncertified controllers).
109 pub vendor_id: u16,
110 /// Commission devices whose attestation has not been verified.
111 ///
112 /// rs-matter does not verify device attestation yet (see
113 /// `docs/design.md`), so commissioning refuses every device unless this is
114 /// set.
115 pub allow_unverified_attestation: bool,
116 /// The Bluetooth controller for commissioning over BLE: `hci0` (the Linux
117 /// HCI user channel; BlueZ must not be using it) or `tcp:host:port` (H4
118 /// over TCP). Needs the `ble` feature.
119 pub bluetooth: Option<String>,
120 /// Run Bluetooth on a static random address instead of the controller's
121 /// public one (simulated controllers such as Bumble's route only those).
122 pub bluetooth_random_address: bool,
123 /// The longest a subscription may stay silent before it is renewed,
124 /// seconds (the device may agree to less).
125 pub max_report_interval: u16,
126 /// The directory of Matter OTA image files offered to the nodes; the
127 /// newest that applies to a node is the update it is offered.
128 pub ota_dir: PathBuf,
129}
130
131impl Config {
132 /// Defaults for a controller keeping its state in `state_dir`.
133 pub fn new(state_dir: impl Into<PathBuf>) -> Self {
134 let state_dir: PathBuf = state_dir.into();
135 Self {
136 ota_dir: state_dir.join("ota"),
137 state_dir,
138 port: 5541,
139 interface: None,
140 fabric_id: None,
141 ca: CaChoice::File,
142 vendor_id: 0xFFF1,
143 allow_unverified_attestation: true,
144 bluetooth: None,
145 bluetooth_random_address: false,
146 max_report_interval: 60,
147 }
148 }
149}
150
151/// Where a controller's fabric certificates come from.
152#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
153pub enum CaChoice {
154 /// A fabric of its own, its CA in `ca.json` in the state directory
155 /// ([`FileCa`]), made on first start.
156 #[default]
157 File,
158 /// An intermediate under a root CA elsewhere, installed in
159 /// `intermediate.json` with [`install_intermediate`].
160 Intermediate,
161}
162
163/// What to commission.
164#[derive(Debug, Clone)]
165pub struct CommissionRequest {
166 /// The QR code payload or manual pairing code.
167 pub code: String,
168 /// The device's address, to skip discovery.
169 pub address: Option<SocketAddr>,
170 /// The name to give the node; a default if `None`.
171 pub name: Option<String>,
172 /// How long to look for the device, seconds.
173 pub discovery_timeout: u16,
174 /// The networks a device commissioned over Bluetooth may be given; the
175 /// device's Network Commissioning cluster says which kind it takes.
176 pub networks: Networks,
177}
178
179/// Operational networks for devices being commissioned over Bluetooth.
180#[derive(Clone, Default, PartialEq, Eq)]
181pub struct Networks {
182 /// A Thread network's active operational dataset, as TLVs (what a
183 /// border router's `dataset active -x` prints).
184 pub thread_dataset: Option<Vec<u8>>,
185 /// A Wi-Fi network.
186 pub wifi: Option<WiFi>,
187}
188
189/// A Wi-Fi network.
190#[derive(Clone, PartialEq, Eq)]
191pub struct WiFi {
192 /// SSID.
193 pub ssid: Vec<u8>,
194 /// Passphrase or PSK (empty for an open network).
195 pub credentials: Vec<u8>,
196}
197
198// The credentials are secrets: never in a log.
199impl std::fmt::Debug for Networks {
200 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201 let thread = self.thread_dataset.as_deref().map(|d| {
202 network::thread_extended_pan_id(d).map_or_else(|_| "invalid".to_string(), hex::encode)
203 });
204 let ssid = self
205 .wifi
206 .as_ref()
207 .map(|w| String::from_utf8_lossy(&w.ssid).into_owned());
208 f.debug_struct("Networks")
209 .field("thread_extended_pan_id", &thread)
210 .field("wifi_ssid", &ssid)
211 .finish()
212 }
213}
214
215/// A path to one attribute or a wildcard over several.
216#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
217pub struct AttributePath {
218 /// Endpoint, or every endpoint.
219 pub endpoint: Option<u16>,
220 /// Cluster, or every cluster.
221 pub cluster: Option<u32>,
222 /// Attribute, or every attribute.
223 pub attribute: Option<u32>,
224}
225
226/// An attribute's value, or why it has none.
227#[derive(Debug, Clone, PartialEq, Serialize)]
228pub struct AttributeValue {
229 /// The node.
230 pub node: u64,
231 /// Endpoint.
232 pub endpoint: u16,
233 /// Cluster id.
234 pub cluster: u32,
235 /// Attribute id.
236 pub attribute: u32,
237 /// The value, decoded with the data model.
238 pub value: Value,
239 /// The status, when the node had no value to give (e.g.
240 /// `UnsupportedAttribute`); `value` is null then.
241 #[serde(skip_serializing_if = "Option::is_none")]
242 pub status: Option<String>,
243}
244
245/// An event a node emitted.
246#[derive(Debug, Clone, PartialEq, Serialize)]
247pub struct EventValue {
248 /// The node.
249 pub node: u64,
250 /// Endpoint.
251 pub endpoint: u16,
252 /// Cluster id.
253 pub cluster: u32,
254 /// Event id.
255 pub event: u32,
256 /// The node's event number, increasing.
257 pub number: u64,
258 /// The event's fields, decoded with the data model.
259 pub data: Value,
260}
261
262/// A commissioning step, as it happens.
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
264#[serde(rename_all = "snake_case")]
265pub enum CommissionStep {
266 /// Looking for the device.
267 Discovery,
268 /// Establishing PASE with the passcode.
269 Pase,
270 /// Arming the fail-safe.
271 ArmFailSafe,
272 /// Checking the device's attestation.
273 DeviceAttestation,
274 /// Asking for its CSR.
275 CsrRequest,
276 /// Installing our root certificate.
277 AddTrustedRootCertificate,
278 /// Installing its operational certificate.
279 AddNoc,
280 /// Finding it on the operational network.
281 FindOperational,
282 /// Giving the device its Thread or Wi-Fi network.
283 NetworkSetup,
284 /// The device joining that network.
285 NetworkConnect,
286 /// Completing commissioning over CASE.
287 CommissioningComplete,
288 /// Rolling back after a failure.
289 Cleanup,
290 /// Reading what it is.
291 Interview,
292}
293
294/// What the controller tells its users, as it happens.
295#[derive(Debug, Clone, PartialEq, Serialize)]
296#[serde(tag = "type", rename_all = "snake_case")]
297pub enum Event {
298 /// An attribute changed (or was reported in a subscription's priming).
299 Attribute(AttributeValue),
300 /// A node emitted an event.
301 Event(EventValue),
302 /// A commissioning advanced.
303 Commissioning {
304 /// The node id it will have.
305 node: u64,
306 /// The step it started.
307 step: CommissionStep,
308 },
309 /// A node was added or changed in the store.
310 NodeUpdated(Node),
311 /// A node was removed.
312 NodeRemoved {
313 /// The node.
314 node: u64,
315 },
316 /// A node's subscription was established or lapsed.
317 Availability {
318 /// The node.
319 node: u64,
320 /// Whether it is reachable.
321 online: bool,
322 },
323 /// An intermittently connected node woke and checked in: its
324 /// subscription is renewed and requests queued for it go out.
325 CheckIn {
326 /// The node.
327 node: u64,
328 },
329 /// A step of a node's software update from this controller.
330 Ota {
331 /// The node.
332 node: u64,
333 /// The step.
334 step: OtaStep,
335 /// The version offered, being applied, or now running.
336 version: u32,
337 },
338}
339
340/// A step of a software update, as the controller (its OTA provider) sees
341/// it. The node's own OTA Requestor events tell the download's progress.
342#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
343#[serde(rename_all = "snake_case")]
344pub enum OtaStep {
345 /// The node asked for an update and was offered `version`.
346 Offered,
347 /// The node downloaded it and was told to apply it.
348 Applying,
349 /// The node reports it now runs `version`.
350 Applied,
351}
352
353/// A node advertising itself as commissionable.
354#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
355pub struct Commissionable {
356 /// Its DNS-SD instance id.
357 pub instance: String,
358 /// Where it answers.
359 pub addresses: Vec<SocketAddr>,
360}
361
362/// A commissioning window opened on a node, for another administrator.
363#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
364pub struct CommissioningWindow {
365 /// The node.
366 pub node: u64,
367 /// The 11-digit manual pairing code, with separators.
368 pub manual_code: String,
369 /// The QR code payload.
370 pub qr_code: String,
371 /// The discriminator the node advertises while the window is open.
372 pub discriminator: u16,
373 /// How long the window stays open, seconds.
374 pub timeout: u16,
375}
376
377/// The controller's identity on its fabric.
378#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
379pub struct ControllerInfo {
380 /// Fabric id.
381 pub fabric_id: u64,
382 /// Compressed fabric id, as nodes advertise it in DNS-SD.
383 pub compressed_fabric_id: u64,
384 /// The controller's own node id.
385 pub node_id: u64,
386 /// Vendor id it administers as.
387 pub vendor_id: u16,
388}