use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;
use bluetooth_adv::beacon::{self, Beacon};
use bluetooth_host::gatt::server::ServiceDef;
use bluetooth_host::{
Address, AdvertisingParams, ConnEvent, ConnectParams, Connection, FixedAgent, Host, HostConfig,
HostEvent, ParamsRequest, PeriodicParams, Phy, Report, ScanConfig, TransportSpec,
};
use serde::Deserialize;
use serde_json::{json, Value};
use crate::config::Config;
use crate::ha;
use crate::mqtt::{self, Incoming, Mqtt};
pub fn topic_id(a: &Address) -> String {
a.to_string().replace(':', "")
}
struct Bridge {
config: Config,
host: Host,
mqtt: Mqtt,
base: String,
beacon_ctx: beacon::Context,
allow: Vec<Vec<u8>>,
discovered: HashSet<(String, String)>,
mesh: Option<crate::mesh::BridgeMesh>,
}
pub async fn run(config: Config) -> Result<(), String> {
let base = config.mqtt.base_topic.clone();
let (mqtt, mut incoming) = mqtt::connect(&config.mqtt)?;
let spec: TransportSpec = config.adapter.transport.parse()?;
let host = open_host(&spec, &config).await;
let mut b = Bridge::new(config, host, mqtt, base)?;
b.setup().await;
let mut events = b.host.events();
loop {
tokio::select! {
e = events.recv() => match e {
Ok(HostEvent::Stopped(reason)) => {
b.mqtt.publish_reliable(mqtt::state_topic(&b.base), r#"{"state":"offline"}"#, true).await;
return Err(format!("the Bluetooth host stopped: {reason}"));
}
Ok(e) => b.on_host_event(e).await,
Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
tracing::warn!("dropped {n} host events (MQTT too slow?)");
}
Err(_) => return Err("host event channel closed".into()),
},
m = incoming.recv() => match m {
Some(Incoming::Connected) => b.on_mqtt_connected().await,
Some(Incoming::Message { topic, payload }) => b.on_message(&topic, &payload).await,
None => return Err("MQTT session ended".into()),
},
_ = shutdown() => {
tracing::info!("stopping");
let _ = b.host.stop_scan().await;
b.mqtt.publish_reliable(mqtt::state_topic(&b.base), r#"{"state":"offline"}"#, true).await;
b.mqtt.disconnect().await;
return Ok(());
}
}
}
}
async fn shutdown() {
#[cfg(unix)]
{
let mut term =
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
Ok(s) => s,
Err(_) => return std::future::pending().await,
};
tokio::select! {
_ = term.recv() => {},
_ = tokio::signal::ctrl_c() => {},
}
}
#[cfg(not(unix))]
{
let _ = tokio::signal::ctrl_c().await;
}
}
async fn open_host(spec: &TransportSpec, config: &Config) -> Host {
let mut delay = Duration::from_secs(1);
loop {
match Host::open(spec, host_config(config)).await {
Ok(h) => return h,
Err(e) => {
tracing::warn!("opening {spec}: {e}; retrying in {}s", delay.as_secs());
tokio::time::sleep(delay).await;
delay = (delay * 2).min(Duration::from_secs(30));
}
}
}
}
fn host_config(c: &Config) -> HostConfig {
HostConfig {
data_dir: Some(c.data.dir.clone()),
device_name: c.adapter.name.clone(),
appearance: c.adapter.appearance,
io_capability: c.adapter.io_capability,
agent: Arc::new(FixedAgent {
passkey: c.adapter.passkey,
confirm: true,
oob: None,
}),
bonding: c.adapter.bonding,
mitm: c.adapter.mitm,
secure_connections_only: c.adapter.secure_connections_only,
use_public_address: !c.adapter.random_address,
..HostConfig::default()
}
}
fn parse_prefix(p: &str) -> Vec<u8> {
let hex: String = p.chars().filter(|c| c.is_ascii_hexdigit()).collect();
hex::decode(if hex.len() % 2 == 1 {
&hex[..hex.len() - 1]
} else {
&hex
})
.unwrap_or_default()
}
impl Bridge {
fn new(config: Config, host: Host, mqtt: Mqtt, base: String) -> Result<Bridge, String> {
let mut ctx = beacon::Context::default();
for k in &config.bthome_keys {
let a: Address = k.address.parse().map_err(|e| format!("{e}"))?;
let key: [u8; 16] = hex::decode(&k.key)
.ok()
.and_then(|v| v.try_into().ok())
.ok_or("bthome key")?;
ctx.bthome_keys.insert(a.bytes, key);
}
for p in &config.kkm_passwords {
let a: Address = p.address.parse().map_err(|e| format!("{e}"))?;
ctx.kkm_passwords.insert(a.bytes, p.password.clone());
}
let allow = config.scan.allow.iter().map(|p| parse_prefix(p)).collect();
Ok(Bridge {
config,
host,
mqtt,
base,
beacon_ctx: ctx,
allow,
discovered: HashSet::new(),
mesh: None,
})
}
fn scan_config(&self, mut c: ScanConfig) -> ScanConfig {
if self.config.mesh.enabled {
for t in crate::mesh::AD_TYPES {
if !c.always_report.contains(&t) {
c.always_report.push(t);
}
}
}
c
}
async fn setup(&mut self) {
if self.config.mesh.enabled {
match crate::mesh::BridgeMesh::start(
&self.host,
self.config.data.dir.join("mesh"),
self.mqtt.clone(),
self.base.clone(),
) {
Ok(m) => self.mesh = Some(m),
Err(e) => tracing::error!("mesh: {e}"),
}
}
for i in &self.config.irks {
let (Ok(a), Ok(irk)) = (
i.address.parse::<Address>(),
u128::from_str_radix(&i.irk, 16),
) else {
continue;
};
if let Err(e) = self.host.keys().add_irk(a, irk, i.label.clone()) {
tracing::warn!("storing the IRK for {a}: {e}");
}
}
let server = self.host.gatt_server();
for s in self.config.gatt_services.clone() {
if let Err(e) = server.add(&s).await {
tracing::error!("GATT service {}: {e}", s.uuid);
}
}
for a in self.config.advertising.clone() {
let data = hex::decode(&a.data).unwrap_or_default();
let sr = hex::decode(&a.scan_response).unwrap_or_default();
if let Err(e) = self.host.advertise(&a.params, &data, &sr).await {
tracing::error!("advertising set: {e}");
}
}
if self.config.scan.enabled {
if let Err(e) = self
.host
.start_scan(self.scan_config(self.config.scan.config.clone()))
.await
{
tracing::error!("starting the scan: {e}");
}
}
}
async fn on_mqtt_connected(&mut self) {
let base = self.base.clone();
self.mqtt
.subscribe(&format!("{base}/bridge/request/#"))
.await;
if self.config.homeassistant.enabled {
self.mqtt
.subscribe(&self.config.homeassistant.status_topic.clone())
.await;
}
self.mqtt
.publish_reliable(mqtt::state_topic(&base), r#"{"state":"online"}"#, true)
.await;
self.mqtt
.publish_reliable(format!("{base}/bridge/info"), self.info().to_string(), true)
.await;
self.discovered.clear();
if self.config.homeassistant.enabled {
let (t, c) = ha::bridge_device(
&self.config.homeassistant.discovery_prefix,
&base,
env!("CARGO_PKG_VERSION"),
);
self.mqtt.publish_reliable(t, c.to_string(), true).await;
}
}
fn info(&self) -> Value {
let c = self.host.capabilities();
json!({
"version": env!("CARGO_PKG_VERSION"),
"address": self.host.address(),
"controller": c,
"manufacturer_name": c.manufacturer_name(),
"core_version": c.version_name(),
"le_features": c.le_feature_names(),
"transport": self.config.adapter.transport,
})
}
fn allowed(&self, a: &Address) -> bool {
if self.allow.is_empty() {
return true;
}
let msb: Vec<u8> = a.bytes.iter().rev().copied().collect();
self.allow
.iter()
.any(|p| !p.is_empty() && msb.starts_with(p))
}
async fn on_host_event(&mut self, e: HostEvent) {
let base = self.base.clone();
match e {
HostEvent::Advertisement(r) => self.on_report(&r).await,
HostEvent::Connected(c) => {
self.event(json!({"type": "connected", "handle": c.handle(), "address": c.peer(),
"identity": c.identity(), "role": c.role()}));
self.watch_connection(c);
}
HostEvent::Disconnected { handle, peer, reason } => self.event(json!({
"type": "disconnected", "handle": handle, "address": peer, "reason": reason,
"reason_name": bluetooth_host::error::status_name(reason)})),
HostEvent::Paired { handle, identity, bonded, security } => self.event(json!({
"type": "paired", "handle": handle, "identity": identity, "bonded": bonded, "security": security,
"level": security.level()})),
HostEvent::PairingFailed { handle, reason } => {
self.event(json!({"type": "pairing_failed", "handle": handle, "reason": reason}))
}
HostEvent::GattWrite { handle, attribute, value } => self.event(json!({
"type": "gatt_write", "handle": handle, "attribute": attribute, "value": hex::encode(value)})),
HostEvent::GattSubscription { handle, attribute, notify, indicate } => self.event(json!({
"type": "gatt_subscription", "handle": handle, "attribute": attribute,
"notify": notify, "indicate": indicate})),
HostEvent::PeriodicReport(r) => self.event(json!({"type": "periodic_report", "report": *r,
"advertisement": bluetooth_adv::Advertisement::parse(&r.data)})),
HostEvent::PeriodicSyncLost { sync } => self.event(json!({"type": "periodic_sync_lost", "sync": sync})),
HostEvent::AdvertisingStopped { set, connection } => {
self.event(json!({"type": "advertising_stopped", "set": set, "connection": connection}))
}
HostEvent::ScanRequest { set, scanner } => {
self.event(json!({"type": "scan_request", "set": set, "scanner": scanner}))
}
other => tracing::debug!("{base}: {other:?}"),
}
}
fn event(&self, v: Value) {
self.mqtt
.publish_json(format!("{}/bridge/event", self.base), &v, false);
}
fn watch_connection(&self, c: Connection) {
let mqtt = self.mqtt.clone();
let topic = format!("{}/bridge/event", self.base);
let mut rx = c.events();
tokio::spawn(async move {
loop {
match rx.recv().await {
Ok(ConnEvent::Notification { handle, value, indication }) => mqtt.publish_json(
topic.clone(),
&json!({"type": "notification", "handle": c.handle(), "attribute": handle,
"value": hex::encode(value), "indication": indication}),
false,
),
Ok(ConnEvent::Disconnected(_)) | Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
Ok(other) => mqtt.publish_json(
topic.clone(),
&json!({"type": "connection", "handle": c.handle(), "change": format!("{other:?}")}),
false,
),
Err(_) => {}
}
}
});
}
async fn on_report(&mut self, r: &Report) {
if self.mesh.is_some() && crate::mesh::only_mesh(&r.data) {
return;
}
let device = r.device();
if r.rssi < self.config.scan.min_rssi
|| !(self.allowed(&r.address) || self.allowed(&device))
{
return;
}
let adv = r.advertisement();
let mut ctx = self.beacon_ctx.clone();
ctx.address = Some(r.address.bytes);
if let Some(id) = r.identity {
if let Some(k) = self.beacon_ctx.bthome_keys.get(&id.bytes) {
ctx.bthome_keys.insert(r.address.bytes, *k);
}
}
let beacons = beacon::decode(&adv, &ctx);
let id = topic_id(&device);
if self.config.scan.publish_reports {
let mut v = serde_json::to_value(r).unwrap_or(Value::Null);
v["advertisement"] = serde_json::to_value(&adv).unwrap_or(Value::Null);
if let Some(n) = adv.local_name.as_ref() {
v["name"] = json!(n.name);
}
if !beacons.is_empty() {
v["beacons"] = serde_json::to_value(&beacons).unwrap_or(Value::Null);
}
self.mqtt
.publish_json(format!("{}/scan/{id}", self.base), &v, false);
}
let readings: Vec<_> = beacons.iter().flat_map(Beacon::readings).collect();
if readings.is_empty() {
return;
}
let mut state = serde_json::Map::new();
for x in &readings {
state.insert(x.key.clone(), json!(x.value));
}
state.insert("rssi".into(), json!(r.rssi));
state.insert(
"last_seen".into(),
json!(r
.time
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0)),
);
self.mqtt.publish_json(
format!("{}/device/{id}", self.base),
&Value::Object(state),
false,
);
if self.config.homeassistant.enabled {
let name = adv
.local_name
.as_ref()
.map(|n| n.name.clone())
.unwrap_or_else(|| device.to_string());
let model = beacons
.first()
.map(|b| b.format())
.unwrap_or("Bluetooth LE")
.to_string();
let manufacturer = adv.manufacturer_data.first().and_then(|m| m.company);
let mut keys: Vec<(String, &'static str)> =
readings.iter().map(|x| (x.key.clone(), x.unit)).collect();
keys.push(("rssi".into(), "dBm"));
for (key, unit) in keys {
if self.discovered.insert((id.clone(), key.clone())) {
let (t, c) = ha::entity(
&self.config.homeassistant.discovery_prefix,
&self.base,
&id,
&name,
&model,
manufacturer,
&key,
unit,
);
self.mqtt.publish(t, c.to_string(), true);
}
}
}
}
async fn on_message(&mut self, topic: &str, payload: &[u8]) {
if topic == self.config.homeassistant.status_topic {
if payload == b"online" {
self.discovered.clear();
}
return;
}
let Some(op) = topic
.strip_prefix(&format!("{}/bridge/request/", self.base))
.map(str::to_string)
else {
return;
};
let body: Value = if payload.is_empty() {
json!({})
} else {
match serde_json::from_slice(payload) {
Ok(v) => v,
Err(e) => {
self.respond(
&op,
&Value::Null,
Err(format!("the request is not JSON: {e}")),
);
return;
}
}
};
let transaction = body.get("transaction").cloned().unwrap_or(Value::Null);
if let Some(mesh_op) = op.strip_prefix("mesh/") {
let Some(mesh) = self.mesh.clone() else {
self.respond(
&op,
&transaction,
Err("the mesh is off ([mesh] enabled)".into()),
);
return;
};
let (mqtt, base, op, mesh_op) = (
self.mqtt.clone(),
self.base.clone(),
op.clone(),
mesh_op.to_string(),
);
tokio::spawn(async move {
let r = mesh.request(&mesh_op, &body).await;
respond(&mqtt, &base, &op, &transaction, r);
});
return;
}
let mut body = body;
if op == "scan/start" {
if let Ok(c) = opt::<ScanConfig>(&body, "config") {
body["config"] = serde_json::to_value(self.scan_config(c)).unwrap_or(Value::Null);
}
}
let host = self.host.clone();
let mqtt = self.mqtt.clone();
let base = self.base.clone();
let op2 = op.clone();
tokio::spawn(async move {
let r = request(&host, &op2, body).await;
respond(&mqtt, &base, &op2, &transaction, r);
});
}
fn respond(&self, op: &str, transaction: &Value, r: Result<Value, String>) {
respond(&self.mqtt, &self.base, op, transaction, r);
}
}
fn respond(mqtt: &Mqtt, base: &str, op: &str, transaction: &Value, r: Result<Value, String>) {
let mut v = match r {
Ok(data) => json!({"status": "ok", "data": data}),
Err(e) => json!({"status": "error", "error": e}),
};
if !transaction.is_null() {
v["transaction"] = transaction.clone();
}
mqtt.publish_json(format!("{base}/bridge/response/{op}"), &v, false);
}
fn field<T: for<'de> Deserialize<'de>>(body: &Value, name: &str) -> Result<T, String> {
serde_json::from_value(body.get(name).cloned().unwrap_or(Value::Null))
.map_err(|e| format!("`{name}`: {e}"))
}
fn opt<T: for<'de> Deserialize<'de> + Default>(body: &Value, name: &str) -> Result<T, String> {
match body.get(name) {
None | Some(Value::Null) => Ok(T::default()),
Some(v) => serde_json::from_value(v.clone()).map_err(|e| format!("`{name}`: {e}")),
}
}
fn hex_field(body: &Value, name: &str) -> Result<Vec<u8>, String> {
match body.get(name).and_then(Value::as_str) {
None => Ok(Vec::new()),
Some(s) => hex::decode(s).map_err(|e| format!("`{name}`: {e}")),
}
}
fn conn(host: &Host, body: &Value) -> Result<Connection, String> {
let h: u16 = field(body, "handle")?;
host.connection(h)
.ok_or_else(|| format!("no connection {h}"))
}
pub async fn request(host: &Host, op: &str, body: Value) -> Result<Value, String> {
let e = |x: bluetooth_host::Error| x.to_string();
match op {
"info" => Ok(json!({"address": host.address(), "controller": host.capabilities(),
"le_features": host.capabilities().le_feature_names()})),
"scan/start" => {
let c: ScanConfig = opt(&body, "config")?;
host.start_scan(c).await.map_err(e)?;
Ok(json!({}))
}
"scan/stop" => host.stop_scan().await.map(|_| json!({})).map_err(e),
"connect" => {
let a: Address = field(&body, "address")?;
let p: ConnectParams = opt(&body, "params")?;
let c = host.connect(a, &p).await.map_err(e)?;
Ok(json!({"handle": c.handle(), "params": c.params()}))
}
"disconnect" => conn(host, &body)?.disconnect().await.map(|_| json!({})).map_err(e),
"connections" => Ok(json!(host
.connections()
.iter()
.map(|c| json!({"handle": c.handle(), "address": c.peer(), "identity": c.identity(),
"role": c.role(), "params": c.params(), "security": c.security(), "mtu": c.att_mtu()}))
.collect::<Vec<_>>())),
"connection/params" => {
let p: ParamsRequest = field(&body, "params")?;
Ok(json!(conn(host, &body)?.update_params(p).await.map_err(e)?))
}
"connection/phy" => {
let tx: Vec<Phy> = field(&body, "tx")?;
let rx: Vec<Phy> = field(&body, "rx")?;
let s8: bool = opt(&body, "coded_s8")?;
let p = conn(host, &body)?.set_phy(&tx, &rx, s8).await.map_err(e)?;
Ok(json!({"tx": p.0, "rx": p.1}))
}
"connection/data_length" => {
let o: u16 = field(&body, "tx_octets")?;
let t: u16 = field(&body, "tx_time")?;
conn(host, &body)?.set_data_length(o, t).await.map(|_| json!({})).map_err(e)
}
"connection/rssi" => Ok(json!({"rssi": conn(host, &body)?.read_rssi().await.map_err(e)?})),
"gatt/mtu" => {
let m: u16 = field(&body, "mtu")?;
Ok(json!({"mtu": conn(host, &body)?.gatt().exchange_mtu(m).await.map_err(e)?}))
}
"gatt/discover" => Ok(json!(conn(host, &body)?.gatt().discover().await.map_err(e)?)),
"gatt/read" => {
let a: u16 = field(&body, "attribute")?;
Ok(json!({"value": hex::encode(conn(host, &body)?.gatt().read(a).await.map_err(e)?)}))
}
"gatt/write" => {
let a: u16 = field(&body, "attribute")?;
let v = hex_field(&body, "value")?;
let without: bool = opt(&body, "without_response")?;
let g = conn(host, &body)?.gatt();
if without {
g.write_without_response(a, &v).await.map_err(e)?;
} else {
g.write(a, &v).await.map_err(e)?;
}
Ok(json!({}))
}
"gatt/subscribe" => {
let a: u16 = field(&body, "attribute")?;
let notify: bool = opt(&body, "notify")?;
let indicate: bool = opt(&body, "indicate")?;
let g = conn(host, &body)?.gatt();
let c = g.characteristic_at(a).await.map_err(e)?;
g.subscribe(&c, notify, indicate).await.map(|_| json!({})).map_err(e)
}
"pair" => Ok(json!(conn(host, &body)?.pair().await.map_err(e)?)),
"secure" => Ok(json!(conn(host, &body)?.secure().await.map_err(e)?)),
"unpair" => {
let a: Address = field(&body, "address")?;
Ok(json!({"removed": host.keys().remove(&a).map_err(e)?}))
}
"bonds" => Ok(json!(host
.keys()
.bonds()
.iter()
.map(|b| json!({"identity": b.identity, "label": b.label, "has_ltk": b.ltk.is_some(),
"has_irk": b.irk.is_some(), "authenticated": b.authenticated,
"secure_connections": b.secure_connections}))
.collect::<Vec<_>>())),
"advertise/start" => {
let p: AdvertisingParams = opt(&body, "params")?;
let set = host
.advertise(&p, &hex_field(&body, "data")?, &hex_field(&body, "scan_response")?)
.await
.map_err(e)?;
Ok(json!({"set": set}))
}
"advertise/data" => {
let set: u8 = field(&body, "set")?;
let sr = body.get("scan_response").map(|_| hex_field(&body, "scan_response")).transpose()?;
host.set_advertising_data(set, &hex_field(&body, "data")?, sr.as_deref())
.await
.map(|_| json!({}))
.map_err(e)
}
"advertise/stop" => {
let set: u8 = field(&body, "set")?;
host.stop_advertising(set).await.map(|_| json!({})).map_err(e)
}
"periodic/start" => {
let set: u8 = field(&body, "set")?;
let p: PeriodicParams = opt(&body, "params")?;
host.start_periodic(set, &p, &hex_field(&body, "data")?)
.await
.map(|_| json!({}))
.map_err(e)
}
"periodic/stop" => {
let set: u8 = field(&body, "set")?;
host.stop_periodic(set).await.map(|_| json!({})).map_err(e)
}
"periodic/sync" => {
let a: Address = field(&body, "address")?;
let sid: u8 = field(&body, "sid")?;
let skip: u16 = opt(&body, "skip")?;
let timeout: Option<u32> = opt(&body, "timeout_ms")?;
let s = host.sync_periodic(a, sid, skip, timeout.unwrap_or(5000)).await.map_err(e)?;
Ok(json!({"sync": s}))
}
"periodic/terminate" => {
let s: u16 = field(&body, "sync")?;
host.terminate_sync(s).await.map(|_| json!({})).map_err(e)
}
"server/add" => {
let s: ServiceDef = field(&body, "service")?;
Ok(json!(host.gatt_server().add(&s).await.map_err(e)?))
}
"server/set" => {
let a: u16 = field(&body, "attribute")?;
let v = hex_field(&body, "value")?;
let notify: bool = opt(&body, "notify")?;
let server = host.gatt_server();
if notify {
Ok(json!({"notified": server.notify(a, &v).await.map_err(e)?}))
} else {
server.set(a, &v).map(|_| json!({})).map_err(e)
}
}
"server/get" => {
let a: u16 = field(&body, "attribute")?;
Ok(json!({"value": host.gatt_server().value(a).map(hex::encode)}))
}
other => Err(format!("unknown request {other:?}")),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_and_prefixes() {
let a: Address = "BC:57:29:00:00:01".parse().unwrap();
assert_eq!(topic_id(&a), "BC5729000001");
assert_eq!(parse_prefix("BC:57:29"), vec![0xbc, 0x57, 0x29]);
assert_eq!(parse_prefix("bc5"), vec![0xbc]);
}
}