1use std::path::{Path, PathBuf};
4
5use bluetooth_host::gatt::server::ServiceDef;
6use bluetooth_host::{AdvertisingParams, IoCapability, ScanConfig};
7use serde::Deserialize;
8
9#[derive(Debug, Clone, Deserialize)]
11#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
12#[serde(deny_unknown_fields)]
13pub struct Config {
14 pub adapter: AdapterConfig,
16 #[serde(default)]
18 pub mqtt: MqttConfig,
19 #[serde(default)]
21 pub scan: ScanSection,
22 #[serde(default)]
24 pub homeassistant: HomeAssistantConfig,
25 #[serde(default)]
27 pub data: DataConfig,
28 #[serde(default)]
30 pub bthome_keys: Vec<KeyEntry>,
31 #[serde(default)]
33 pub kkm_passwords: Vec<PasswordEntry>,
34 #[serde(default)]
36 pub irks: Vec<IrkEntry>,
37 #[serde(default)]
39 pub gatt_services: Vec<ServiceDef>,
40 #[serde(default)]
42 pub advertising: Vec<AdvertisingEntry>,
43 #[serde(default)]
45 pub mesh: MeshConfig,
46}
47
48#[derive(Debug, Clone, Default, Deserialize)]
51#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
52#[serde(default, deny_unknown_fields)]
53pub struct MeshConfig {
54 pub enabled: bool,
56}
57
58#[derive(Debug, Clone, Deserialize)]
60#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
61#[serde(deny_unknown_fields)]
62pub struct AdapterConfig {
63 pub transport: String,
65 #[serde(default = "default_name")]
67 pub name: String,
68 #[serde(default)]
70 pub appearance: u16,
71 #[serde(default = "default_io")]
73 pub io_capability: IoCapability,
74 #[serde(default)]
76 pub passkey: Option<u32>,
77 #[serde(default = "yes")]
79 pub bonding: bool,
80 #[serde(default)]
82 pub mitm: bool,
83 #[serde(default)]
85 pub secure_connections_only: bool,
86 #[serde(default)]
88 pub random_address: bool,
89}
90
91fn default_name() -> String {
92 "bluetooth-bridge".into()
93}
94
95fn default_io() -> IoCapability {
96 IoCapability::NoInputNoOutput
97}
98
99fn yes() -> bool {
100 true
101}
102
103#[derive(Debug, Clone, Deserialize)]
105#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
106#[serde(default, deny_unknown_fields)]
107pub struct MqttConfig {
108 pub host: String,
110 pub port: u16,
112 pub username: Option<String>,
114 pub password_file: Option<PathBuf>,
116 pub client_id: String,
118 pub base_topic: String,
120 pub keepalive: u64,
122}
123
124impl Default for MqttConfig {
125 fn default() -> Self {
126 MqttConfig {
127 host: "localhost".into(),
128 port: 1883,
129 username: None,
130 password_file: None,
131 client_id: "bluetooth-bridge".into(),
132 base_topic: "bluetooth".into(),
133 keepalive: 30,
134 }
135 }
136}
137
138#[derive(Debug, Clone, Deserialize)]
141#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
142#[serde(default)]
143pub struct ScanSection {
144 pub enabled: bool,
146 #[serde(flatten)]
148 pub config: ScanConfig,
149 pub allow: Vec<String>,
152 pub min_rssi: i8,
154 pub publish_reports: bool,
156}
157
158impl Default for ScanSection {
159 fn default() -> Self {
160 ScanSection {
161 enabled: true,
162 config: ScanConfig::default(),
163 allow: Vec::new(),
164 min_rssi: -127,
165 publish_reports: true,
166 }
167 }
168}
169
170#[derive(Debug, Clone, Deserialize)]
172#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
173#[serde(default, deny_unknown_fields)]
174pub struct HomeAssistantConfig {
175 pub enabled: bool,
177 pub discovery_prefix: String,
179 pub status_topic: String,
181}
182
183impl Default for HomeAssistantConfig {
184 fn default() -> Self {
185 HomeAssistantConfig {
186 enabled: true,
187 discovery_prefix: "homeassistant".into(),
188 status_topic: "homeassistant/status".into(),
189 }
190 }
191}
192
193#[derive(Debug, Clone, Deserialize)]
195#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
196#[serde(default, deny_unknown_fields)]
197pub struct DataConfig {
198 pub dir: PathBuf,
200}
201
202impl Default for DataConfig {
203 fn default() -> Self {
204 DataConfig {
205 dir: PathBuf::from("/var/lib/bluetooth-bridge"),
206 }
207 }
208}
209
210#[derive(Debug, Clone, Deserialize)]
212#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
213#[serde(deny_unknown_fields)]
214pub struct KeyEntry {
215 pub address: String,
217 pub key: String,
219}
220
221#[derive(Debug, Clone, Deserialize)]
223#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
224#[serde(deny_unknown_fields)]
225pub struct PasswordEntry {
226 pub address: String,
228 pub password: String,
230}
231
232#[derive(Debug, Clone, Deserialize)]
234#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
235#[serde(deny_unknown_fields)]
236pub struct IrkEntry {
237 pub address: String,
239 pub irk: String,
241 #[serde(default)]
243 pub label: Option<String>,
244}
245
246#[derive(Debug, Clone, Deserialize)]
248#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
249#[serde(deny_unknown_fields)]
250pub struct AdvertisingEntry {
251 #[serde(default)]
253 pub params: AdvertisingParams,
254 #[serde(default)]
256 pub data: String,
257 #[serde(default)]
259 pub scan_response: String,
260}
261
262#[derive(Debug, thiserror::Error)]
264pub enum ConfigError {
265 #[error("{0}: {1}")]
267 Read(PathBuf, std::io::Error),
268 #[error("{0}: {1}")]
270 Parse(PathBuf, toml::de::Error),
271 #[error("{0}")]
273 Invalid(String),
274}
275
276impl Config {
277 pub fn load(path: &Path) -> Result<Config, ConfigError> {
279 let text =
280 std::fs::read_to_string(path).map_err(|e| ConfigError::Read(path.to_path_buf(), e))?;
281 let c: Config =
282 toml::from_str(&text).map_err(|e| ConfigError::Parse(path.to_path_buf(), e))?;
283 c.check()?;
284 Ok(c)
285 }
286
287 pub fn parse(text: &str) -> Result<Config, ConfigError> {
289 let c: Config =
290 toml::from_str(text).map_err(|e| ConfigError::Parse(PathBuf::from("<config>"), e))?;
291 c.check()?;
292 Ok(c)
293 }
294
295 fn check(&self) -> Result<(), ConfigError> {
296 let bad = |m: String| Err(ConfigError::Invalid(m));
297 if self
298 .adapter
299 .transport
300 .parse::<bluetooth_host::TransportSpec>()
301 .is_err()
302 {
303 return bad(format!(
304 "adapter.transport {:?} is not hciN, serial:PATH:BAUD or tcp:HOST:PORT",
305 self.adapter.transport
306 ));
307 }
308 if self.adapter.passkey.is_some_and(|p| p > 999_999) {
309 return bad("adapter.passkey has six digits at most".into());
310 }
311 for k in &self.bthome_keys {
312 if k.address.parse::<bluetooth_host::Address>().is_err()
313 || hex::decode(&k.key).map(|v| v.len()) != Ok(16)
314 {
315 return bad(format!(
316 "bthome_keys entry for {:?} needs an address and a 32-digit hex key",
317 k.address
318 ));
319 }
320 }
321 for k in &self.irks {
322 if k.address.parse::<bluetooth_host::Address>().is_err()
323 || u128::from_str_radix(&k.irk, 16).is_err()
324 {
325 return bad(format!(
326 "irks entry for {:?} needs an address and a 32-digit hex IRK",
327 k.address
328 ));
329 }
330 }
331 for p in &self.kkm_passwords {
332 if p.address.parse::<bluetooth_host::Address>().is_err() || p.password.len() > 16 {
333 return bad(format!(
334 "kkm_passwords entry {:?}: an address and a password of 16 characters at most",
335 p.address
336 ));
337 }
338 }
339 for a in &self.advertising {
340 if hex::decode(&a.data).is_err() || hex::decode(&a.scan_response).is_err() {
341 return bad("advertising data and scan_response are hex".into());
342 }
343 }
344 if self.mqtt.base_topic.is_empty() || self.mqtt.base_topic.contains(['+', '#']) {
345 return bad("mqtt.base_topic must be a plain topic".into());
346 }
347 Ok(())
348 }
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354
355 #[test]
356 fn example_parses() {
357 let c = Config::parse(include_str!("../../../config.example.toml")).unwrap();
358 assert_eq!(c.adapter.transport, "hci0");
359 assert_eq!(c.mqtt.base_topic, "bluetooth");
360 assert!(c.scan.enabled);
361 }
362
363 #[test]
364 fn minimal_and_errors() {
365 let c = Config::parse("[adapter]\ntransport = \"tcp:127.0.0.1:9000\"\n").unwrap();
366 assert!(c.homeassistant.enabled);
367 assert!(Config::parse("[adapter]\ntransport = \"usb:1\"\n").is_err());
368 assert!(Config::parse("[adapter]\ntransport = \"hci0\"\npasskey = 1234567\n").is_err());
369 assert!(Config::parse("[adapter]\ntransport = \"hci0\"\nbogus = 1\n").is_err());
370 }
371}