1use std::path::{Path, PathBuf};
4
5use serde::Deserialize;
6
7#[derive(Debug, Clone, Deserialize)]
9#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
10#[serde(deny_unknown_fields)]
11pub struct Config {
12 pub serial: SerialConfig,
14 #[serde(default)]
16 pub mqtt: MqttConfig,
17 #[serde(default)]
19 pub homeassistant: HomeAssistantConfig,
20 #[serde(default)]
22 pub network: NetworkConfig,
23 #[serde(default)]
25 pub join: JoinConfig,
26 #[serde(default)]
28 pub data: DataConfig,
29 #[serde(default)]
31 pub ota: OtaConfig,
32}
33
34#[derive(Debug, Clone, Default, Deserialize)]
36#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
37#[serde(deny_unknown_fields)]
38pub struct OtaConfig {
39 pub dir: Option<PathBuf>,
42}
43
44#[derive(Debug, Clone, Deserialize)]
46#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
47#[serde(deny_unknown_fields)]
48pub struct SerialConfig {
49 pub port: String,
51 #[serde(default = "default_baud")]
53 pub baud: u32,
54 #[serde(default)]
56 pub flow_control: FlowControl,
57 #[serde(default)]
60 pub adapter: AdapterChoice,
61}
62
63#[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 #[default]
70 Auto,
71 Ezsp,
73 Znp,
75 Deconz,
77}
78
79#[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 #[default]
86 None,
87 Hardware,
89 Software,
91}
92
93fn default_baud() -> u32 {
94 115_200
95}
96
97#[derive(Debug, Clone, Deserialize)]
99#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
100#[serde(deny_unknown_fields, default)]
101pub struct MqttConfig {
102 pub host: String,
104 pub port: u16,
106 pub username: Option<String>,
108 pub password_file: Option<PathBuf>,
110 pub client_id: String,
112 pub base_topic: String,
114 pub keepalive: u64,
116 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#[derive(Debug, Clone, Deserialize)]
137#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
138#[serde(deny_unknown_fields, default)]
139pub struct HomeAssistantConfig {
140 pub enabled: bool,
142 pub discovery_prefix: String,
144 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#[derive(Debug, Clone, Deserialize)]
161#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
162#[serde(deny_unknown_fields, default)]
163pub struct NetworkConfig {
164 pub channel: u8,
166 pub tx_power: Option<i8>,
168 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#[derive(Debug, Clone, Deserialize)]
186#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
187#[serde(deny_unknown_fields, default)]
188pub struct JoinConfig {
189 pub install_code_only: bool,
191 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#[derive(Debug, Clone, Deserialize)]
206#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
207#[serde(deny_unknown_fields, default)]
208pub struct DataConfig {
209 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#[derive(Debug, thiserror::Error)]
223pub enum ConfigError {
224 #[error("reading {path}: {source}")]
226 Read {
227 path: PathBuf,
229 source: std::io::Error,
231 },
232 #[error("{path}: {message}")]
234 Parse {
235 path: PathBuf,
237 message: String,
239 },
240}
241
242impl Config {
243 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 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}