Skip to main content

matter_bridge/
config.rs

1//! The bridge's configuration file (TOML). Every section is optional.
2
3use std::path::{Path, PathBuf};
4
5use serde::Deserialize;
6
7/// The whole configuration.
8#[derive(Debug, Clone, Default, Deserialize)]
9#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
10#[serde(deny_unknown_fields)]
11pub struct Config {
12    /// The MQTT broker.
13    #[serde(default)]
14    pub mqtt: MqttConfig,
15    /// Home Assistant discovery.
16    #[serde(default)]
17    pub homeassistant: HomeAssistantConfig,
18    /// The Matter controller.
19    #[serde(default)]
20    pub matter: MatterConfig,
21    /// Where state lives.
22    #[serde(default)]
23    pub data: DataConfig,
24}
25
26impl Config {
27    /// Read the configuration at `path`.
28    pub fn load(path: &Path) -> Result<Self, String> {
29        let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
30        toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))
31    }
32}
33
34/// The MQTT broker.
35#[derive(Debug, Clone, Deserialize)]
36#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
37#[serde(deny_unknown_fields, default)]
38pub struct MqttConfig {
39    /// Broker host.
40    pub host: String,
41    /// Broker port.
42    pub port: u16,
43    /// User name, if the broker wants one.
44    pub username: Option<String>,
45    /// A file holding the password (so it is not in the configuration).
46    pub password_file: Option<PathBuf>,
47    /// Client id.
48    pub client_id: String,
49    /// Prefix of every topic the bridge uses.
50    pub base_topic: String,
51    /// Keep-alive, seconds.
52    pub keepalive: u64,
53}
54
55impl Default for MqttConfig {
56    fn default() -> Self {
57        MqttConfig {
58            host: "localhost".into(),
59            port: 1883,
60            username: None,
61            password_file: None,
62            client_id: "matter-bridge".into(),
63            base_topic: "matter".into(),
64            keepalive: 30,
65        }
66    }
67}
68
69/// Home Assistant discovery.
70#[derive(Debug, Clone, Deserialize)]
71#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
72#[serde(deny_unknown_fields, default)]
73pub struct HomeAssistantConfig {
74    /// Publish discovery messages.
75    pub enabled: bool,
76    /// Home Assistant's discovery prefix.
77    pub discovery_prefix: String,
78    /// Home Assistant's birth topic; discovery is re-sent when it says "online".
79    pub status_topic: String,
80}
81
82impl Default for HomeAssistantConfig {
83    fn default() -> Self {
84        HomeAssistantConfig {
85            enabled: true,
86            discovery_prefix: "homeassistant".into(),
87            status_topic: "homeassistant/status".into(),
88        }
89    }
90}
91
92/// The Matter controller.
93#[derive(Debug, Clone, Deserialize)]
94#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
95#[serde(deny_unknown_fields, default)]
96pub struct MatterConfig {
97    /// UDP port for Matter.
98    pub port: u16,
99    /// Network interface for mDNS; the first with IPv6 if unset.
100    pub interface: Option<String>,
101    /// Fabric id of a new fabric (random if unset). Ignored once the fabric
102    /// exists.
103    pub fabric_id: Option<u64>,
104    /// Vendor id the controller administers nodes as.
105    pub vendor_id: u16,
106    /// Commission devices whose attestation is not verified. Required for
107    /// now: verification is not implemented yet (see the README).
108    pub allow_unverified_attestation: bool,
109    /// Longest silence before a subscription is renewed, seconds.
110    pub max_report_interval: u16,
111    /// How long to look for a device to commission, seconds.
112    pub discovery_timeout: u16,
113    /// The Bluetooth controller for commissioning over BLE: `hci0` (the
114    /// Linux HCI user channel; BlueZ must not hold it) or `tcp:host:port`.
115    pub bluetooth: Option<String>,
116    /// Where to read the Thread network's dataset for a Thread device: an
117    /// OpenThread border router's REST API, e.g.
118    /// `http://127.0.0.1:8081/node/dataset/active`.
119    pub thread_dataset_url: Option<String>,
120    /// The directory of Matter OTA image files offered to devices as
121    /// software updates; `<data.dir>/ota` if unset.
122    pub ota_dir: Option<PathBuf>,
123}
124
125impl Default for MatterConfig {
126    fn default() -> Self {
127        let c = matter_controller::Config::new("");
128        MatterConfig {
129            port: c.port,
130            interface: None,
131            fabric_id: None,
132            vendor_id: c.vendor_id,
133            allow_unverified_attestation: c.allow_unverified_attestation,
134            max_report_interval: c.max_report_interval,
135            discovery_timeout: 30,
136            bluetooth: None,
137            thread_dataset_url: None,
138            ota_dir: None,
139        }
140    }
141}
142
143/// Where state lives.
144#[derive(Debug, Clone, Deserialize)]
145#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
146#[serde(deny_unknown_fields, default)]
147pub struct DataConfig {
148    /// The directory for the fabric, the controller's identity and the node
149    /// store.
150    pub dir: PathBuf,
151}
152
153impl Default for DataConfig {
154    fn default() -> Self {
155        DataConfig {
156            dir: "/var/lib/matter-bridge".into(),
157        }
158    }
159}
160
161impl Config {
162    /// The controller's configuration.
163    pub fn controller(&self) -> matter_controller::Config {
164        let mut c = matter_controller::Config::new(&self.data.dir);
165        c.port = self.matter.port;
166        c.interface = self.matter.interface.clone();
167        c.fabric_id = self.matter.fabric_id;
168        c.vendor_id = self.matter.vendor_id;
169        c.allow_unverified_attestation = self.matter.allow_unverified_attestation;
170        c.max_report_interval = self.matter.max_report_interval;
171        c.bluetooth = self.matter.bluetooth.clone();
172        if let Some(dir) = &self.matter.ota_dir {
173            c.ota_dir = dir.clone();
174        }
175        c
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    #[test]
184    fn example_parses() {
185        let text = include_str!("../../../config.example.toml");
186        let config: Config = toml::from_str(text).unwrap();
187        assert_eq!(config.mqtt.base_topic, "matter");
188        assert!(config.homeassistant.enabled);
189    }
190
191    #[test]
192    fn empty_is_all_defaults() {
193        let config: Config = toml::from_str("").unwrap();
194        assert_eq!(config.mqtt.port, 1883);
195        assert_eq!(config.matter.port, 5541);
196    }
197
198    #[test]
199    fn unknown_keys_are_refused() {
200        assert!(toml::from_str::<Config>("[mqtt]\nhots = \"x\"").is_err());
201    }
202}