Skip to main content

bluetooth_bridge/
config.rs

1//! The bridge's configuration file (TOML).
2
3use std::path::{Path, PathBuf};
4
5use bluetooth_host::gatt::server::ServiceDef;
6use bluetooth_host::{AdvertisingParams, IoCapability, ScanConfig};
7use serde::Deserialize;
8
9/// The whole file.
10#[derive(Debug, Clone, Deserialize)]
11#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
12#[serde(deny_unknown_fields)]
13pub struct Config {
14    /// The controller.
15    pub adapter: AdapterConfig,
16    /// The broker.
17    #[serde(default)]
18    pub mqtt: MqttConfig,
19    /// Scanning.
20    #[serde(default)]
21    pub scan: ScanSection,
22    /// Home Assistant discovery.
23    #[serde(default)]
24    pub homeassistant: HomeAssistantConfig,
25    /// Where bonds and the local identity live.
26    #[serde(default)]
27    pub data: DataConfig,
28    /// BTHome bind keys, for encrypted BTHome devices.
29    #[serde(default)]
30    pub bthome_keys: Vec<KeyEntry>,
31    /// KKM beacon passwords, for encrypted KKM sensor frames.
32    #[serde(default)]
33    pub kkm_passwords: Vec<PasswordEntry>,
34    /// IRKs of devices known without pairing, so their private addresses resolve.
35    #[serde(default)]
36    pub irks: Vec<IrkEntry>,
37    /// GATT services the bridge serves.
38    #[serde(default)]
39    pub gatt_services: Vec<ServiceDef>,
40    /// Advertising sets started with the bridge.
41    #[serde(default)]
42    pub advertising: Vec<AdvertisingEntry>,
43    /// Bluetooth Mesh, with the bridge as the provisioner.
44    #[serde(default)]
45    pub mesh: MeshConfig,
46}
47
48/// Bluetooth Mesh: the bridge provisions, configures and controls nodes on
49/// the advertising bearer, its network kept in `<data>/mesh`.
50#[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    /// On. The first start creates the network, with the bridge at 0x0001.
55    pub enabled: bool,
56}
57
58/// The controller.
59#[derive(Debug, Clone, Deserialize)]
60#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
61#[serde(deny_unknown_fields)]
62pub struct AdapterConfig {
63    /// `hci0`, `serial:/dev/ttyAMA0:115200`, or `tcp:host:port`.
64    pub transport: String,
65    /// The GAP device name.
66    #[serde(default = "default_name")]
67    pub name: String,
68    /// The GAP appearance.
69    #[serde(default)]
70    pub appearance: u16,
71    /// Input and output capabilities for pairing.
72    #[serde(default = "default_io")]
73    pub io_capability: IoCapability,
74    /// A fixed passkey to show and type when pairing needs one (six digits).
75    #[serde(default)]
76    pub passkey: Option<u32>,
77    /// Bond when pairing.
78    #[serde(default = "yes")]
79    pub bonding: bool,
80    /// Require MITM protection.
81    #[serde(default)]
82    pub mitm: bool,
83    /// Refuse legacy pairing.
84    #[serde(default)]
85    pub secure_connections_only: bool,
86    /// Use a static random address even when the controller has a public one.
87    #[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/// The broker.
104#[derive(Debug, Clone, Deserialize)]
105#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
106#[serde(default, deny_unknown_fields)]
107pub struct MqttConfig {
108    /// Host name.
109    pub host: String,
110    /// Port.
111    pub port: u16,
112    /// User name.
113    pub username: Option<String>,
114    /// A file holding the password (so it is not in this file).
115    pub password_file: Option<PathBuf>,
116    /// Client id.
117    pub client_id: String,
118    /// Every topic starts with this.
119    pub base_topic: String,
120    /// Keep-alive, seconds.
121    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/// Scanning. (Unknown keys cannot be refused here: serde does not allow
139/// that with a flattened section.)
140#[derive(Debug, Clone, Deserialize)]
141#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
142#[serde(default)]
143pub struct ScanSection {
144    /// Scan from start.
145    pub enabled: bool,
146    /// How.
147    #[serde(flatten)]
148    pub config: ScanConfig,
149    /// Publish only devices whose address starts with one of these
150    /// (`BC:57:29`, say); empty publishes everything.
151    pub allow: Vec<String>,
152    /// Ignore weaker signals, dBm.
153    pub min_rssi: i8,
154    /// Publish every report on `<base>/scan/<address>`.
155    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/// Home Assistant discovery.
171#[derive(Debug, Clone, Deserialize)]
172#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
173#[serde(default, deny_unknown_fields)]
174pub struct HomeAssistantConfig {
175    /// Publish discovery for devices with decoded readings.
176    pub enabled: bool,
177    /// The discovery prefix.
178    pub discovery_prefix: String,
179    /// Home Assistant's birth topic; discovery is sent again when it comes online.
180    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/// Storage.
194#[derive(Debug, Clone, Deserialize)]
195#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
196#[serde(default, deny_unknown_fields)]
197pub struct DataConfig {
198    /// The data directory.
199    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/// A device's key.
211#[derive(Debug, Clone, Deserialize)]
212#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
213#[serde(deny_unknown_fields)]
214pub struct KeyEntry {
215    /// The device's address.
216    pub address: String,
217    /// The 16-byte key, hex.
218    pub key: String,
219}
220
221/// A device's password.
222#[derive(Debug, Clone, Deserialize)]
223#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
224#[serde(deny_unknown_fields)]
225pub struct PasswordEntry {
226    /// The device's address.
227    pub address: String,
228    /// The password.
229    pub password: String,
230}
231
232/// A known IRK.
233#[derive(Debug, Clone, Deserialize)]
234#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
235#[serde(deny_unknown_fields)]
236pub struct IrkEntry {
237    /// The identity address the device's private addresses stand for.
238    pub address: String,
239    /// The IRK, hex, most significant byte first.
240    pub irk: String,
241    /// A label.
242    #[serde(default)]
243    pub label: Option<String>,
244}
245
246/// An advertising set.
247#[derive(Debug, Clone, Deserialize)]
248#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
249#[serde(deny_unknown_fields)]
250pub struct AdvertisingEntry {
251    /// How.
252    #[serde(default)]
253    pub params: AdvertisingParams,
254    /// Advertising data, hex (AD structures).
255    #[serde(default)]
256    pub data: String,
257    /// Scan response, hex.
258    #[serde(default)]
259    pub scan_response: String,
260}
261
262/// A configuration problem.
263#[derive(Debug, thiserror::Error)]
264pub enum ConfigError {
265    /// Reading the file.
266    #[error("{0}: {1}")]
267    Read(PathBuf, std::io::Error),
268    /// Parsing it.
269    #[error("{0}: {1}")]
270    Parse(PathBuf, toml::de::Error),
271    /// A value that parses but makes no sense.
272    #[error("{0}")]
273    Invalid(String),
274}
275
276impl Config {
277    /// Reads and checks a file.
278    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    /// Parses from a string (tests).
288    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}