Skip to main content

zigbee_bridge/
config.rs

1//! The bridge's configuration file (TOML).
2
3use std::path::{Path, PathBuf};
4
5use serde::Deserialize;
6
7/// The whole configuration.
8#[derive(Debug, Clone, Deserialize)]
9#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
10#[serde(deny_unknown_fields)]
11pub struct Config {
12    /// The coordinator's port.
13    pub serial: SerialConfig,
14    /// The MQTT broker.
15    #[serde(default)]
16    pub mqtt: MqttConfig,
17    /// Home Assistant discovery.
18    #[serde(default)]
19    pub homeassistant: HomeAssistantConfig,
20    /// The network to form on first start.
21    #[serde(default)]
22    pub network: NetworkConfig,
23    /// Trust center join policy.
24    #[serde(default)]
25    pub join: JoinConfig,
26    /// Where state lives.
27    #[serde(default)]
28    pub data: DataConfig,
29    /// Device firmware upgrades.
30    #[serde(default)]
31    pub ota: OtaConfig,
32}
33
34/// Device firmware upgrades.
35#[derive(Debug, Clone, Default, Deserialize)]
36#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
37#[serde(deny_unknown_fields)]
38pub struct OtaConfig {
39    /// A directory of OTA image files; `<data.dir>/ota` when unset. Images
40    /// are offered only when an `ota_update` request asks for one.
41    pub dir: Option<PathBuf>,
42}
43
44/// The coordinator's port.
45#[derive(Debug, Clone, Deserialize)]
46#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
47#[serde(deny_unknown_fields)]
48pub struct SerialConfig {
49    /// A serial device (`/dev/ttyUSB0`) or `tcp://host:port`.
50    pub port: String,
51    /// Baud rate.
52    #[serde(default = "default_baud")]
53    pub baud: u32,
54    /// `none`, `hardware` (RTS/CTS) or `software`.
55    #[serde(default)]
56    pub flow_control: FlowControl,
57    /// The coordinator family: `auto` (probe for it), `ezsp`, `znp` or
58    /// `deconz`.
59    #[serde(default)]
60    pub adapter: AdapterChoice,
61}
62
63/// Which coordinator family to speak.
64#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
65#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
66#[serde(rename_all = "lowercase")]
67pub enum AdapterChoice {
68    /// Probe the port for each family.
69    #[default]
70    Auto,
71    /// Silicon Labs EmberZNet.
72    Ezsp,
73    /// Texas Instruments Z-Stack.
74    Znp,
75    /// dresden elektronik deCONZ (ConBee, RaspBee).
76    Deconz,
77}
78
79/// Serial flow control.
80#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
81#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
82#[serde(rename_all = "lowercase")]
83pub enum FlowControl {
84    /// None.
85    #[default]
86    None,
87    /// RTS/CTS.
88    Hardware,
89    /// XON/XOFF.
90    Software,
91}
92
93fn default_baud() -> u32 {
94    115_200
95}
96
97/// The MQTT broker.
98#[derive(Debug, Clone, Deserialize)]
99#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
100#[serde(deny_unknown_fields, default)]
101pub struct MqttConfig {
102    /// Broker host.
103    pub host: String,
104    /// Broker port.
105    pub port: u16,
106    /// User name, if the broker wants one.
107    pub username: Option<String>,
108    /// A file holding the password (so it is not in the configuration).
109    pub password_file: Option<PathBuf>,
110    /// Client id.
111    pub client_id: String,
112    /// Prefix of every topic the bridge uses.
113    pub base_topic: String,
114    /// Keep-alive, seconds.
115    pub keepalive: u64,
116    /// Publish device state retained, so a subscriber sees it at once.
117    pub retain_state: bool,
118}
119
120impl Default for MqttConfig {
121    fn default() -> Self {
122        MqttConfig {
123            host: "localhost".into(),
124            port: 1883,
125            username: None,
126            password_file: None,
127            client_id: "zigbee-bridge".into(),
128            base_topic: "zigbee".into(),
129            keepalive: 30,
130            retain_state: true,
131        }
132    }
133}
134
135/// Home Assistant discovery.
136#[derive(Debug, Clone, Deserialize)]
137#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
138#[serde(deny_unknown_fields, default)]
139pub struct HomeAssistantConfig {
140    /// Publish discovery messages.
141    pub enabled: bool,
142    /// Home Assistant's discovery prefix.
143    pub discovery_prefix: String,
144    /// Home Assistant's birth topic; discovery is re-sent when it says "online".
145    pub status_topic: String,
146}
147
148impl Default for HomeAssistantConfig {
149    fn default() -> Self {
150        HomeAssistantConfig {
151            enabled: true,
152            discovery_prefix: "homeassistant".into(),
153            status_topic: "homeassistant/status".into(),
154        }
155    }
156}
157
158/// The network formed on first start. After that the network file in the
159/// data directory is the source of truth.
160#[derive(Debug, Clone, Deserialize)]
161#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
162#[serde(deny_unknown_fields, default)]
163pub struct NetworkConfig {
164    /// Channel, 11 to 26.
165    pub channel: u8,
166    /// Transmit power in dBm, if not the firmware's default.
167    pub tx_power: Option<i8>,
168    /// Leave a different network found on the coordinator and form this
169    /// one. Off by default: a coordinator with another network is never
170    /// wiped without being told to.
171    pub replace_other: bool,
172}
173
174impl Default for NetworkConfig {
175    fn default() -> Self {
176        NetworkConfig {
177            channel: 15,
178            tx_power: None,
179            replace_other: false,
180        }
181    }
182}
183
184/// Trust center join policy.
185#[derive(Debug, Clone, Deserialize)]
186#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
187#[serde(deny_unknown_fields, default)]
188pub struct JoinConfig {
189    /// Only devices with an install code may join.
190    pub install_code_only: bool,
191    /// Accept pre-Zigbee 3.0 devices (they keep the well-known link key).
192    pub allow_legacy: bool,
193}
194
195impl Default for JoinConfig {
196    fn default() -> Self {
197        JoinConfig {
198            install_code_only: false,
199            allow_legacy: true,
200        }
201    }
202}
203
204/// Where state lives.
205#[derive(Debug, Clone, Deserialize)]
206#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
207#[serde(deny_unknown_fields, default)]
208pub struct DataConfig {
209    /// The data directory: network keys, device store, backup.
210    pub dir: PathBuf,
211}
212
213impl Default for DataConfig {
214    fn default() -> Self {
215        DataConfig {
216            dir: PathBuf::from("/var/lib/zigbee-bridge"),
217        }
218    }
219}
220
221/// A configuration error.
222#[derive(Debug, thiserror::Error)]
223pub enum ConfigError {
224    /// The file could not be read.
225    #[error("reading {path}: {source}")]
226    Read {
227        /// The file.
228        path: PathBuf,
229        /// Why.
230        source: std::io::Error,
231    },
232    /// The file did not parse.
233    #[error("{path}: {message}")]
234    Parse {
235        /// The file.
236        path: PathBuf,
237        /// Why.
238        message: String,
239    },
240}
241
242impl Config {
243    /// Parse a configuration.
244    pub fn from_toml(text: &str) -> Result<Config, String> {
245        let config: Config = toml::from_str(text).map_err(|e| e.to_string())?;
246        if !(11..=26).contains(&config.network.channel) {
247            return Err(format!(
248                "network.channel {} is not 11 to 26",
249                config.network.channel
250            ));
251        }
252        if config.mqtt.base_topic.is_empty() || config.mqtt.base_topic.contains(['+', '#']) {
253            return Err("mqtt.base_topic must be a plain topic prefix".into());
254        }
255        Ok(config)
256    }
257
258    /// Read and parse a configuration file.
259    pub fn load(path: &Path) -> Result<Config, ConfigError> {
260        let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
261            path: path.into(),
262            source,
263        })?;
264        Config::from_toml(&text).map_err(|message| ConfigError::Parse {
265            path: path.into(),
266            message,
267        })
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    #[test]
276    fn minimal_and_full_configs_parse() {
277        let c = Config::from_toml("[serial]\nport = \"/dev/ttyUSB0\"\n").unwrap();
278        assert_eq!(c.serial.baud, 115_200);
279        assert_eq!(c.mqtt.base_topic, "zigbee");
280        assert!(c.homeassistant.enabled);
281        let c = Config::from_toml(
282            "[serial]\nport = \"tcp://10.0.0.5:6638\"\nflow_control = \"hardware\"\n[mqtt]\nhost = \"broker\"\nusername = \"z\"\n[network]\nchannel = 25\n[join]\ninstall_code_only = true\n[data]\ndir = \"/tmp/z\"\n",
283        )
284        .unwrap();
285        assert_eq!(c.serial.flow_control, FlowControl::Hardware);
286        assert_eq!(c.network.channel, 25);
287        assert!(Config::from_toml("[serial]\nport = \"x\"\n[network]\nchannel = 5\n").is_err());
288        assert!(Config::from_toml("[serial]\nport = \"x\"\nbogus = 1\n").is_err());
289    }
290}