use std::path::{Path, PathBuf};
use bluetooth_host::gatt::server::ServiceDef;
use bluetooth_host::{AdvertisingParams, IoCapability, ScanConfig};
use serde::Deserialize;
#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Config {
pub adapter: AdapterConfig,
#[serde(default)]
pub mqtt: MqttConfig,
#[serde(default)]
pub scan: ScanSection,
#[serde(default)]
pub homeassistant: HomeAssistantConfig,
#[serde(default)]
pub data: DataConfig,
#[serde(default)]
pub bthome_keys: Vec<KeyEntry>,
#[serde(default)]
pub kkm_passwords: Vec<PasswordEntry>,
#[serde(default)]
pub irks: Vec<IrkEntry>,
#[serde(default)]
pub gatt_services: Vec<ServiceDef>,
#[serde(default)]
pub advertising: Vec<AdvertisingEntry>,
#[serde(default)]
pub mesh: MeshConfig,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
#[serde(default, deny_unknown_fields)]
pub struct MeshConfig {
pub enabled: bool,
}
#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct AdapterConfig {
pub transport: String,
#[serde(default = "default_name")]
pub name: String,
#[serde(default)]
pub appearance: u16,
#[serde(default = "default_io")]
pub io_capability: IoCapability,
#[serde(default)]
pub passkey: Option<u32>,
#[serde(default = "yes")]
pub bonding: bool,
#[serde(default)]
pub mitm: bool,
#[serde(default)]
pub secure_connections_only: bool,
#[serde(default)]
pub random_address: bool,
}
fn default_name() -> String {
"bluetooth-bridge".into()
}
fn default_io() -> IoCapability {
IoCapability::NoInputNoOutput
}
fn yes() -> bool {
true
}
#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
#[serde(default, deny_unknown_fields)]
pub struct MqttConfig {
pub host: String,
pub port: u16,
pub username: Option<String>,
pub password_file: Option<PathBuf>,
pub client_id: String,
pub base_topic: String,
pub keepalive: u64,
}
impl Default for MqttConfig {
fn default() -> Self {
MqttConfig {
host: "localhost".into(),
port: 1883,
username: None,
password_file: None,
client_id: "bluetooth-bridge".into(),
base_topic: "bluetooth".into(),
keepalive: 30,
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
#[serde(default)]
pub struct ScanSection {
pub enabled: bool,
#[serde(flatten)]
pub config: ScanConfig,
pub allow: Vec<String>,
pub min_rssi: i8,
pub publish_reports: bool,
}
impl Default for ScanSection {
fn default() -> Self {
ScanSection {
enabled: true,
config: ScanConfig::default(),
allow: Vec::new(),
min_rssi: -127,
publish_reports: true,
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
#[serde(default, deny_unknown_fields)]
pub struct HomeAssistantConfig {
pub enabled: bool,
pub discovery_prefix: String,
pub status_topic: String,
}
impl Default for HomeAssistantConfig {
fn default() -> Self {
HomeAssistantConfig {
enabled: true,
discovery_prefix: "homeassistant".into(),
status_topic: "homeassistant/status".into(),
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
#[serde(default, deny_unknown_fields)]
pub struct DataConfig {
pub dir: PathBuf,
}
impl Default for DataConfig {
fn default() -> Self {
DataConfig {
dir: PathBuf::from("/var/lib/bluetooth-bridge"),
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct KeyEntry {
pub address: String,
pub key: String,
}
#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct PasswordEntry {
pub address: String,
pub password: String,
}
#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct IrkEntry {
pub address: String,
pub irk: String,
#[serde(default)]
pub label: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "schema", derive(serde::Serialize, schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct AdvertisingEntry {
#[serde(default)]
pub params: AdvertisingParams,
#[serde(default)]
pub data: String,
#[serde(default)]
pub scan_response: String,
}
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
#[error("{0}: {1}")]
Read(PathBuf, std::io::Error),
#[error("{0}: {1}")]
Parse(PathBuf, toml::de::Error),
#[error("{0}")]
Invalid(String),
}
impl Config {
pub fn load(path: &Path) -> Result<Config, ConfigError> {
let text =
std::fs::read_to_string(path).map_err(|e| ConfigError::Read(path.to_path_buf(), e))?;
let c: Config =
toml::from_str(&text).map_err(|e| ConfigError::Parse(path.to_path_buf(), e))?;
c.check()?;
Ok(c)
}
pub fn parse(text: &str) -> Result<Config, ConfigError> {
let c: Config =
toml::from_str(text).map_err(|e| ConfigError::Parse(PathBuf::from("<config>"), e))?;
c.check()?;
Ok(c)
}
fn check(&self) -> Result<(), ConfigError> {
let bad = |m: String| Err(ConfigError::Invalid(m));
if self
.adapter
.transport
.parse::<bluetooth_host::TransportSpec>()
.is_err()
{
return bad(format!(
"adapter.transport {:?} is not hciN, serial:PATH:BAUD or tcp:HOST:PORT",
self.adapter.transport
));
}
if self.adapter.passkey.is_some_and(|p| p > 999_999) {
return bad("adapter.passkey has six digits at most".into());
}
for k in &self.bthome_keys {
if k.address.parse::<bluetooth_host::Address>().is_err()
|| hex::decode(&k.key).map(|v| v.len()) != Ok(16)
{
return bad(format!(
"bthome_keys entry for {:?} needs an address and a 32-digit hex key",
k.address
));
}
}
for k in &self.irks {
if k.address.parse::<bluetooth_host::Address>().is_err()
|| u128::from_str_radix(&k.irk, 16).is_err()
{
return bad(format!(
"irks entry for {:?} needs an address and a 32-digit hex IRK",
k.address
));
}
}
for p in &self.kkm_passwords {
if p.address.parse::<bluetooth_host::Address>().is_err() || p.password.len() > 16 {
return bad(format!(
"kkm_passwords entry {:?}: an address and a password of 16 characters at most",
p.address
));
}
}
for a in &self.advertising {
if hex::decode(&a.data).is_err() || hex::decode(&a.scan_response).is_err() {
return bad("advertising data and scan_response are hex".into());
}
}
if self.mqtt.base_topic.is_empty() || self.mqtt.base_topic.contains(['+', '#']) {
return bad("mqtt.base_topic must be a plain topic".into());
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example_parses() {
let c = Config::parse(include_str!("../../../config.example.toml")).unwrap();
assert_eq!(c.adapter.transport, "hci0");
assert_eq!(c.mqtt.base_topic, "bluetooth");
assert!(c.scan.enabled);
}
#[test]
fn minimal_and_errors() {
let c = Config::parse("[adapter]\ntransport = \"tcp:127.0.0.1:9000\"\n").unwrap();
assert!(c.homeassistant.enabled);
assert!(Config::parse("[adapter]\ntransport = \"usb:1\"\n").is_err());
assert!(Config::parse("[adapter]\ntransport = \"hci0\"\npasskey = 1234567\n").is_err());
assert!(Config::parse("[adapter]\ntransport = \"hci0\"\nbogus = 1\n").is_err());
}
}