Skip to main content

bluetooth_bridge/
bridge.rs

1//! The bridge: the host's events out to MQTT, requests from MQTT in.
2//!
3//! Topics, under `base` (`bluetooth` by default):
4//!
5//! | Topic | Direction | What |
6//! |---|---|---|
7//! | `base/bridge/state` | out, retained | `{"state":"online"}` or `offline` (the will) |
8//! | `base/bridge/info` | out, retained | the controller and its capabilities |
9//! | `base/scan/<ADDRESS>` | out | every advertisement after duplicate filtering, parsed |
10//! | `base/device/<ADDRESS>` | out | a device's decoded readings, for Home Assistant |
11//! | `base/bridge/event` | out | connections, pairing, notifications, GATT writes, periodic reports |
12//! | `base/bridge/request/<op>` | in | a request, JSON, optionally with a `transaction` id |
13//! | `base/bridge/response/<op>` | out | `{"transaction", "status", "data" or "error"}`, status `ok` or `error` |
14//!
15//! Addresses in topics are twelve upper-case hex digits, most significant
16//! first (`BC5729000001`).
17
18use std::collections::HashSet;
19use std::sync::Arc;
20use std::time::Duration;
21
22use bluetooth_adv::beacon::{self, Beacon};
23use bluetooth_host::gatt::server::ServiceDef;
24use bluetooth_host::{
25    Address, AdvertisingParams, ConnEvent, ConnectParams, Connection, FixedAgent, Host, HostConfig,
26    HostEvent, ParamsRequest, PeriodicParams, Phy, Report, ScanConfig, TransportSpec,
27};
28use serde::Deserialize;
29use serde_json::{json, Value};
30
31use crate::config::Config;
32use crate::ha;
33use crate::mqtt::{self, Incoming, Mqtt};
34
35/// The topic form of an address.
36pub fn topic_id(a: &Address) -> String {
37    a.to_string().replace(':', "")
38}
39
40struct Bridge {
41    config: Config,
42    host: Host,
43    mqtt: Mqtt,
44    base: String,
45    beacon_ctx: beacon::Context,
46    allow: Vec<Vec<u8>>,
47    discovered: HashSet<(String, String)>,
48    mesh: Option<crate::mesh::BridgeMesh>,
49}
50
51/// Runs the bridge until a signal or a fatal error.
52pub async fn run(config: Config) -> Result<(), String> {
53    let base = config.mqtt.base_topic.clone();
54    let (mqtt, mut incoming) = mqtt::connect(&config.mqtt)?;
55    let spec: TransportSpec = config.adapter.transport.parse()?;
56    let host = open_host(&spec, &config).await;
57    let mut b = Bridge::new(config, host, mqtt, base)?;
58    b.setup().await;
59    let mut events = b.host.events();
60    loop {
61        tokio::select! {
62            e = events.recv() => match e {
63                Ok(HostEvent::Stopped(reason)) => {
64                    b.mqtt.publish_reliable(mqtt::state_topic(&b.base), r#"{"state":"offline"}"#, true).await;
65                    return Err(format!("the Bluetooth host stopped: {reason}"));
66                }
67                Ok(e) => b.on_host_event(e).await,
68                Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
69                    tracing::warn!("dropped {n} host events (MQTT too slow?)");
70                }
71                Err(_) => return Err("host event channel closed".into()),
72            },
73            m = incoming.recv() => match m {
74                Some(Incoming::Connected) => b.on_mqtt_connected().await,
75                Some(Incoming::Message { topic, payload }) => b.on_message(&topic, &payload).await,
76                None => return Err("MQTT session ended".into()),
77            },
78            _ = shutdown() => {
79                tracing::info!("stopping");
80                let _ = b.host.stop_scan().await;
81                b.mqtt.publish_reliable(mqtt::state_topic(&b.base), r#"{"state":"offline"}"#, true).await;
82                b.mqtt.disconnect().await;
83                return Ok(());
84            }
85        }
86    }
87}
88
89async fn shutdown() {
90    #[cfg(unix)]
91    {
92        let mut term =
93            match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
94                Ok(s) => s,
95                Err(_) => return std::future::pending().await,
96            };
97        tokio::select! {
98            _ = term.recv() => {},
99            _ = tokio::signal::ctrl_c() => {},
100        }
101    }
102    #[cfg(not(unix))]
103    {
104        let _ = tokio::signal::ctrl_c().await;
105    }
106}
107
108/// Opens the controller, retrying while it is absent (unplugged, or still
109/// loading firmware).
110async fn open_host(spec: &TransportSpec, config: &Config) -> Host {
111    let mut delay = Duration::from_secs(1);
112    loop {
113        match Host::open(spec, host_config(config)).await {
114            Ok(h) => return h,
115            Err(e) => {
116                tracing::warn!("opening {spec}: {e}; retrying in {}s", delay.as_secs());
117                tokio::time::sleep(delay).await;
118                delay = (delay * 2).min(Duration::from_secs(30));
119            }
120        }
121    }
122}
123
124fn host_config(c: &Config) -> HostConfig {
125    HostConfig {
126        data_dir: Some(c.data.dir.clone()),
127        device_name: c.adapter.name.clone(),
128        appearance: c.adapter.appearance,
129        io_capability: c.adapter.io_capability,
130        agent: Arc::new(FixedAgent {
131            passkey: c.adapter.passkey,
132            confirm: true,
133            oob: None,
134        }),
135        bonding: c.adapter.bonding,
136        mitm: c.adapter.mitm,
137        secure_connections_only: c.adapter.secure_connections_only,
138        use_public_address: !c.adapter.random_address,
139        ..HostConfig::default()
140    }
141}
142
143fn parse_prefix(p: &str) -> Vec<u8> {
144    let hex: String = p.chars().filter(|c| c.is_ascii_hexdigit()).collect();
145    hex::decode(if hex.len() % 2 == 1 {
146        &hex[..hex.len() - 1]
147    } else {
148        &hex
149    })
150    .unwrap_or_default()
151}
152
153impl Bridge {
154    fn new(config: Config, host: Host, mqtt: Mqtt, base: String) -> Result<Bridge, String> {
155        let mut ctx = beacon::Context::default();
156        for k in &config.bthome_keys {
157            let a: Address = k.address.parse().map_err(|e| format!("{e}"))?;
158            let key: [u8; 16] = hex::decode(&k.key)
159                .ok()
160                .and_then(|v| v.try_into().ok())
161                .ok_or("bthome key")?;
162            ctx.bthome_keys.insert(a.bytes, key);
163        }
164        for p in &config.kkm_passwords {
165            let a: Address = p.address.parse().map_err(|e| format!("{e}"))?;
166            ctx.kkm_passwords.insert(a.bytes, p.password.clone());
167        }
168        let allow = config.scan.allow.iter().map(|p| parse_prefix(p)).collect();
169        Ok(Bridge {
170            config,
171            host,
172            mqtt,
173            base,
174            beacon_ctx: ctx,
175            allow,
176            discovered: HashSet::new(),
177            mesh: None,
178        })
179    }
180
181    /// A scan configuration with Mesh's AD types always reported, when the
182    /// mesh is on: its retransmissions are identical, and must be heard.
183    fn scan_config(&self, mut c: ScanConfig) -> ScanConfig {
184        if self.config.mesh.enabled {
185            for t in crate::mesh::AD_TYPES {
186                if !c.always_report.contains(&t) {
187                    c.always_report.push(t);
188                }
189            }
190        }
191        c
192    }
193
194    async fn setup(&mut self) {
195        if self.config.mesh.enabled {
196            match crate::mesh::BridgeMesh::start(
197                &self.host,
198                self.config.data.dir.join("mesh"),
199                self.mqtt.clone(),
200                self.base.clone(),
201            ) {
202                Ok(m) => self.mesh = Some(m),
203                Err(e) => tracing::error!("mesh: {e}"),
204            }
205        }
206        for i in &self.config.irks {
207            let (Ok(a), Ok(irk)) = (
208                i.address.parse::<Address>(),
209                u128::from_str_radix(&i.irk, 16),
210            ) else {
211                continue;
212            };
213            if let Err(e) = self.host.keys().add_irk(a, irk, i.label.clone()) {
214                tracing::warn!("storing the IRK for {a}: {e}");
215            }
216        }
217        let server = self.host.gatt_server();
218        for s in self.config.gatt_services.clone() {
219            if let Err(e) = server.add(&s).await {
220                tracing::error!("GATT service {}: {e}", s.uuid);
221            }
222        }
223        for a in self.config.advertising.clone() {
224            let data = hex::decode(&a.data).unwrap_or_default();
225            let sr = hex::decode(&a.scan_response).unwrap_or_default();
226            if let Err(e) = self.host.advertise(&a.params, &data, &sr).await {
227                tracing::error!("advertising set: {e}");
228            }
229        }
230        if self.config.scan.enabled {
231            if let Err(e) = self
232                .host
233                .start_scan(self.scan_config(self.config.scan.config.clone()))
234                .await
235            {
236                tracing::error!("starting the scan: {e}");
237            }
238        }
239    }
240
241    async fn on_mqtt_connected(&mut self) {
242        let base = self.base.clone();
243        self.mqtt
244            .subscribe(&format!("{base}/bridge/request/#"))
245            .await;
246        if self.config.homeassistant.enabled {
247            self.mqtt
248                .subscribe(&self.config.homeassistant.status_topic.clone())
249                .await;
250        }
251        self.mqtt
252            .publish_reliable(mqtt::state_topic(&base), r#"{"state":"online"}"#, true)
253            .await;
254        self.mqtt
255            .publish_reliable(format!("{base}/bridge/info"), self.info().to_string(), true)
256            .await;
257        self.discovered.clear();
258        if self.config.homeassistant.enabled {
259            let (t, c) = ha::bridge_device(
260                &self.config.homeassistant.discovery_prefix,
261                &base,
262                env!("CARGO_PKG_VERSION"),
263            );
264            self.mqtt.publish_reliable(t, c.to_string(), true).await;
265        }
266    }
267
268    fn info(&self) -> Value {
269        let c = self.host.capabilities();
270        json!({
271            "version": env!("CARGO_PKG_VERSION"),
272            "address": self.host.address(),
273            "controller": c,
274            "manufacturer_name": c.manufacturer_name(),
275            "core_version": c.version_name(),
276            "le_features": c.le_feature_names(),
277            "transport": self.config.adapter.transport,
278        })
279    }
280
281    fn allowed(&self, a: &Address) -> bool {
282        if self.allow.is_empty() {
283            return true;
284        }
285        let msb: Vec<u8> = a.bytes.iter().rev().copied().collect();
286        self.allow
287            .iter()
288            .any(|p| !p.is_empty() && msb.starts_with(p))
289    }
290
291    async fn on_host_event(&mut self, e: HostEvent) {
292        let base = self.base.clone();
293        match e {
294            HostEvent::Advertisement(r) => self.on_report(&r).await,
295            HostEvent::Connected(c) => {
296                self.event(json!({"type": "connected", "handle": c.handle(), "address": c.peer(),
297                    "identity": c.identity(), "role": c.role()}));
298                self.watch_connection(c);
299            }
300            HostEvent::Disconnected { handle, peer, reason } => self.event(json!({
301                "type": "disconnected", "handle": handle, "address": peer, "reason": reason,
302                "reason_name": bluetooth_host::error::status_name(reason)})),
303            HostEvent::Paired { handle, identity, bonded, security } => self.event(json!({
304                "type": "paired", "handle": handle, "identity": identity, "bonded": bonded, "security": security,
305                "level": security.level()})),
306            HostEvent::PairingFailed { handle, reason } => {
307                self.event(json!({"type": "pairing_failed", "handle": handle, "reason": reason}))
308            }
309            HostEvent::GattWrite { handle, attribute, value } => self.event(json!({
310                "type": "gatt_write", "handle": handle, "attribute": attribute, "value": hex::encode(value)})),
311            HostEvent::GattSubscription { handle, attribute, notify, indicate } => self.event(json!({
312                "type": "gatt_subscription", "handle": handle, "attribute": attribute,
313                "notify": notify, "indicate": indicate})),
314            HostEvent::PeriodicReport(r) => self.event(json!({"type": "periodic_report", "report": *r,
315                "advertisement": bluetooth_adv::Advertisement::parse(&r.data)})),
316            HostEvent::PeriodicSyncLost { sync } => self.event(json!({"type": "periodic_sync_lost", "sync": sync})),
317            HostEvent::AdvertisingStopped { set, connection } => {
318                self.event(json!({"type": "advertising_stopped", "set": set, "connection": connection}))
319            }
320            HostEvent::ScanRequest { set, scanner } => {
321                self.event(json!({"type": "scan_request", "set": set, "scanner": scanner}))
322            }
323            other => tracing::debug!("{base}: {other:?}"),
324        }
325    }
326
327    fn event(&self, v: Value) {
328        self.mqtt
329            .publish_json(format!("{}/bridge/event", self.base), &v, false);
330    }
331
332    /// Forwards a connection's notifications as events.
333    fn watch_connection(&self, c: Connection) {
334        let mqtt = self.mqtt.clone();
335        let topic = format!("{}/bridge/event", self.base);
336        let mut rx = c.events();
337        tokio::spawn(async move {
338            loop {
339                match rx.recv().await {
340                    Ok(ConnEvent::Notification { handle, value, indication }) => mqtt.publish_json(
341                        topic.clone(),
342                        &json!({"type": "notification", "handle": c.handle(), "attribute": handle,
343                            "value": hex::encode(value), "indication": indication}),
344                        false,
345                    ),
346                    Ok(ConnEvent::Disconnected(_)) | Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
347                    Ok(other) => mqtt.publish_json(
348                        topic.clone(),
349                        &json!({"type": "connection", "handle": c.handle(), "change": format!("{other:?}")}),
350                        false,
351                    ),
352                    Err(_) => {}
353                }
354            }
355        });
356    }
357
358    async fn on_report(&mut self, r: &Report) {
359        if self.mesh.is_some() && crate::mesh::only_mesh(&r.data) {
360            // The mesh's own traffic, heard through its bearer; not a device.
361            return;
362        }
363        let device = r.device();
364        if r.rssi < self.config.scan.min_rssi
365            || !(self.allowed(&r.address) || self.allowed(&device))
366        {
367            return;
368        }
369        let adv = r.advertisement();
370        let mut ctx = self.beacon_ctx.clone();
371        ctx.address = Some(r.address.bytes);
372        // Keys are stored by identity; use them for a private address too.
373        if let Some(id) = r.identity {
374            if let Some(k) = self.beacon_ctx.bthome_keys.get(&id.bytes) {
375                ctx.bthome_keys.insert(r.address.bytes, *k);
376            }
377        }
378        let beacons = beacon::decode(&adv, &ctx);
379        let id = topic_id(&device);
380        if self.config.scan.publish_reports {
381            let mut v = serde_json::to_value(r).unwrap_or(Value::Null);
382            v["advertisement"] = serde_json::to_value(&adv).unwrap_or(Value::Null);
383            if let Some(n) = adv.local_name.as_ref() {
384                v["name"] = json!(n.name);
385            }
386            if !beacons.is_empty() {
387                v["beacons"] = serde_json::to_value(&beacons).unwrap_or(Value::Null);
388            }
389            self.mqtt
390                .publish_json(format!("{}/scan/{id}", self.base), &v, false);
391        }
392        let readings: Vec<_> = beacons.iter().flat_map(Beacon::readings).collect();
393        if readings.is_empty() {
394            return;
395        }
396        let mut state = serde_json::Map::new();
397        for x in &readings {
398            state.insert(x.key.clone(), json!(x.value));
399        }
400        state.insert("rssi".into(), json!(r.rssi));
401        state.insert(
402            "last_seen".into(),
403            json!(r
404                .time
405                .duration_since(std::time::UNIX_EPOCH)
406                .map(|d| d.as_millis() as u64)
407                .unwrap_or(0)),
408        );
409        self.mqtt.publish_json(
410            format!("{}/device/{id}", self.base),
411            &Value::Object(state),
412            false,
413        );
414        if self.config.homeassistant.enabled {
415            let name = adv
416                .local_name
417                .as_ref()
418                .map(|n| n.name.clone())
419                .unwrap_or_else(|| device.to_string());
420            let model = beacons
421                .first()
422                .map(|b| b.format())
423                .unwrap_or("Bluetooth LE")
424                .to_string();
425            let manufacturer = adv.manufacturer_data.first().and_then(|m| m.company);
426            let mut keys: Vec<(String, &'static str)> =
427                readings.iter().map(|x| (x.key.clone(), x.unit)).collect();
428            keys.push(("rssi".into(), "dBm"));
429            for (key, unit) in keys {
430                if self.discovered.insert((id.clone(), key.clone())) {
431                    let (t, c) = ha::entity(
432                        &self.config.homeassistant.discovery_prefix,
433                        &self.base,
434                        &id,
435                        &name,
436                        &model,
437                        manufacturer,
438                        &key,
439                        unit,
440                    );
441                    self.mqtt.publish(t, c.to_string(), true);
442                }
443            }
444        }
445    }
446
447    async fn on_message(&mut self, topic: &str, payload: &[u8]) {
448        if topic == self.config.homeassistant.status_topic {
449            if payload == b"online" {
450                // Home Assistant restarted: discovery again.
451                self.discovered.clear();
452            }
453            return;
454        }
455        let Some(op) = topic
456            .strip_prefix(&format!("{}/bridge/request/", self.base))
457            .map(str::to_string)
458        else {
459            return;
460        };
461        let body: Value = if payload.is_empty() {
462            json!({})
463        } else {
464            match serde_json::from_slice(payload) {
465                Ok(v) => v,
466                Err(e) => {
467                    self.respond(
468                        &op,
469                        &Value::Null,
470                        Err(format!("the request is not JSON: {e}")),
471                    );
472                    return;
473                }
474            }
475        };
476        let transaction = body.get("transaction").cloned().unwrap_or(Value::Null);
477        if let Some(mesh_op) = op.strip_prefix("mesh/") {
478            let Some(mesh) = self.mesh.clone() else {
479                self.respond(
480                    &op,
481                    &transaction,
482                    Err("the mesh is off ([mesh] enabled)".into()),
483                );
484                return;
485            };
486            let (mqtt, base, op, mesh_op) = (
487                self.mqtt.clone(),
488                self.base.clone(),
489                op.clone(),
490                mesh_op.to_string(),
491            );
492            tokio::spawn(async move {
493                let r = mesh.request(&mesh_op, &body).await;
494                respond(&mqtt, &base, &op, &transaction, r);
495            });
496            return;
497        }
498        // A scan started by request keeps hearing the mesh.
499        let mut body = body;
500        if op == "scan/start" {
501            if let Ok(c) = opt::<ScanConfig>(&body, "config") {
502                body["config"] = serde_json::to_value(self.scan_config(c)).unwrap_or(Value::Null);
503            }
504        }
505        // Requests that wait on the radio run on their own so scanning keeps flowing.
506        let host = self.host.clone();
507        let mqtt = self.mqtt.clone();
508        let base = self.base.clone();
509        let op2 = op.clone();
510        tokio::spawn(async move {
511            let r = request(&host, &op2, body).await;
512            respond(&mqtt, &base, &op2, &transaction, r);
513        });
514    }
515
516    fn respond(&self, op: &str, transaction: &Value, r: Result<Value, String>) {
517        respond(&self.mqtt, &self.base, op, transaction, r);
518    }
519}
520
521fn respond(mqtt: &Mqtt, base: &str, op: &str, transaction: &Value, r: Result<Value, String>) {
522    let mut v = match r {
523        Ok(data) => json!({"status": "ok", "data": data}),
524        Err(e) => json!({"status": "error", "error": e}),
525    };
526    if !transaction.is_null() {
527        v["transaction"] = transaction.clone();
528    }
529    mqtt.publish_json(format!("{base}/bridge/response/{op}"), &v, false);
530}
531
532fn field<T: for<'de> Deserialize<'de>>(body: &Value, name: &str) -> Result<T, String> {
533    serde_json::from_value(body.get(name).cloned().unwrap_or(Value::Null))
534        .map_err(|e| format!("`{name}`: {e}"))
535}
536
537fn opt<T: for<'de> Deserialize<'de> + Default>(body: &Value, name: &str) -> Result<T, String> {
538    match body.get(name) {
539        None | Some(Value::Null) => Ok(T::default()),
540        Some(v) => serde_json::from_value(v.clone()).map_err(|e| format!("`{name}`: {e}")),
541    }
542}
543
544fn hex_field(body: &Value, name: &str) -> Result<Vec<u8>, String> {
545    match body.get(name).and_then(Value::as_str) {
546        None => Ok(Vec::new()),
547        Some(s) => hex::decode(s).map_err(|e| format!("`{name}`: {e}")),
548    }
549}
550
551fn conn(host: &Host, body: &Value) -> Result<Connection, String> {
552    let h: u16 = field(body, "handle")?;
553    host.connection(h)
554        .ok_or_else(|| format!("no connection {h}"))
555}
556
557/// Runs one request.
558pub async fn request(host: &Host, op: &str, body: Value) -> Result<Value, String> {
559    let e = |x: bluetooth_host::Error| x.to_string();
560    match op {
561        "info" => Ok(json!({"address": host.address(), "controller": host.capabilities(),
562            "le_features": host.capabilities().le_feature_names()})),
563        "scan/start" => {
564            let c: ScanConfig = opt(&body, "config")?;
565            host.start_scan(c).await.map_err(e)?;
566            Ok(json!({}))
567        }
568        "scan/stop" => host.stop_scan().await.map(|_| json!({})).map_err(e),
569        "connect" => {
570            let a: Address = field(&body, "address")?;
571            let p: ConnectParams = opt(&body, "params")?;
572            let c = host.connect(a, &p).await.map_err(e)?;
573            Ok(json!({"handle": c.handle(), "params": c.params()}))
574        }
575        "disconnect" => conn(host, &body)?.disconnect().await.map(|_| json!({})).map_err(e),
576        "connections" => Ok(json!(host
577            .connections()
578            .iter()
579            .map(|c| json!({"handle": c.handle(), "address": c.peer(), "identity": c.identity(),
580                "role": c.role(), "params": c.params(), "security": c.security(), "mtu": c.att_mtu()}))
581            .collect::<Vec<_>>())),
582        "connection/params" => {
583            let p: ParamsRequest = field(&body, "params")?;
584            Ok(json!(conn(host, &body)?.update_params(p).await.map_err(e)?))
585        }
586        "connection/phy" => {
587            let tx: Vec<Phy> = field(&body, "tx")?;
588            let rx: Vec<Phy> = field(&body, "rx")?;
589            let s8: bool = opt(&body, "coded_s8")?;
590            let p = conn(host, &body)?.set_phy(&tx, &rx, s8).await.map_err(e)?;
591            Ok(json!({"tx": p.0, "rx": p.1}))
592        }
593        "connection/data_length" => {
594            let o: u16 = field(&body, "tx_octets")?;
595            let t: u16 = field(&body, "tx_time")?;
596            conn(host, &body)?.set_data_length(o, t).await.map(|_| json!({})).map_err(e)
597        }
598        "connection/rssi" => Ok(json!({"rssi": conn(host, &body)?.read_rssi().await.map_err(e)?})),
599        "gatt/mtu" => {
600            let m: u16 = field(&body, "mtu")?;
601            Ok(json!({"mtu": conn(host, &body)?.gatt().exchange_mtu(m).await.map_err(e)?}))
602        }
603        "gatt/discover" => Ok(json!(conn(host, &body)?.gatt().discover().await.map_err(e)?)),
604        "gatt/read" => {
605            let a: u16 = field(&body, "attribute")?;
606            Ok(json!({"value": hex::encode(conn(host, &body)?.gatt().read(a).await.map_err(e)?)}))
607        }
608        "gatt/write" => {
609            let a: u16 = field(&body, "attribute")?;
610            let v = hex_field(&body, "value")?;
611            let without: bool = opt(&body, "without_response")?;
612            let g = conn(host, &body)?.gatt();
613            if without {
614                g.write_without_response(a, &v).await.map_err(e)?;
615            } else {
616                g.write(a, &v).await.map_err(e)?;
617            }
618            Ok(json!({}))
619        }
620        "gatt/subscribe" => {
621            let a: u16 = field(&body, "attribute")?;
622            let notify: bool = opt(&body, "notify")?;
623            let indicate: bool = opt(&body, "indicate")?;
624            let g = conn(host, &body)?.gatt();
625            let c = g.characteristic_at(a).await.map_err(e)?;
626            g.subscribe(&c, notify, indicate).await.map(|_| json!({})).map_err(e)
627        }
628        "pair" => Ok(json!(conn(host, &body)?.pair().await.map_err(e)?)),
629        "secure" => Ok(json!(conn(host, &body)?.secure().await.map_err(e)?)),
630        "unpair" => {
631            let a: Address = field(&body, "address")?;
632            Ok(json!({"removed": host.keys().remove(&a).map_err(e)?}))
633        }
634        "bonds" => Ok(json!(host
635            .keys()
636            .bonds()
637            .iter()
638            // Never publish keys: only who, and what kind of bond.
639            .map(|b| json!({"identity": b.identity, "label": b.label, "has_ltk": b.ltk.is_some(),
640                "has_irk": b.irk.is_some(), "authenticated": b.authenticated,
641                "secure_connections": b.secure_connections}))
642            .collect::<Vec<_>>())),
643        "advertise/start" => {
644            let p: AdvertisingParams = opt(&body, "params")?;
645            let set = host
646                .advertise(&p, &hex_field(&body, "data")?, &hex_field(&body, "scan_response")?)
647                .await
648                .map_err(e)?;
649            Ok(json!({"set": set}))
650        }
651        "advertise/data" => {
652            let set: u8 = field(&body, "set")?;
653            let sr = body.get("scan_response").map(|_| hex_field(&body, "scan_response")).transpose()?;
654            host.set_advertising_data(set, &hex_field(&body, "data")?, sr.as_deref())
655                .await
656                .map(|_| json!({}))
657                .map_err(e)
658        }
659        "advertise/stop" => {
660            let set: u8 = field(&body, "set")?;
661            host.stop_advertising(set).await.map(|_| json!({})).map_err(e)
662        }
663        "periodic/start" => {
664            let set: u8 = field(&body, "set")?;
665            let p: PeriodicParams = opt(&body, "params")?;
666            host.start_periodic(set, &p, &hex_field(&body, "data")?)
667                .await
668                .map(|_| json!({}))
669                .map_err(e)
670        }
671        "periodic/stop" => {
672            let set: u8 = field(&body, "set")?;
673            host.stop_periodic(set).await.map(|_| json!({})).map_err(e)
674        }
675        "periodic/sync" => {
676            let a: Address = field(&body, "address")?;
677            let sid: u8 = field(&body, "sid")?;
678            let skip: u16 = opt(&body, "skip")?;
679            let timeout: Option<u32> = opt(&body, "timeout_ms")?;
680            let s = host.sync_periodic(a, sid, skip, timeout.unwrap_or(5000)).await.map_err(e)?;
681            Ok(json!({"sync": s}))
682        }
683        "periodic/terminate" => {
684            let s: u16 = field(&body, "sync")?;
685            host.terminate_sync(s).await.map(|_| json!({})).map_err(e)
686        }
687        "server/add" => {
688            let s: ServiceDef = field(&body, "service")?;
689            Ok(json!(host.gatt_server().add(&s).await.map_err(e)?))
690        }
691        "server/set" => {
692            let a: u16 = field(&body, "attribute")?;
693            let v = hex_field(&body, "value")?;
694            let notify: bool = opt(&body, "notify")?;
695            let server = host.gatt_server();
696            if notify {
697                Ok(json!({"notified": server.notify(a, &v).await.map_err(e)?}))
698            } else {
699                server.set(a, &v).map(|_| json!({})).map_err(e)
700            }
701        }
702        "server/get" => {
703            let a: u16 = field(&body, "attribute")?;
704            Ok(json!({"value": host.gatt_server().value(a).map(hex::encode)}))
705        }
706        other => Err(format!("unknown request {other:?}")),
707    }
708}
709
710#[cfg(test)]
711mod tests {
712    use super::*;
713
714    #[test]
715    fn ids_and_prefixes() {
716        let a: Address = "BC:57:29:00:00:01".parse().unwrap();
717        assert_eq!(topic_id(&a), "BC5729000001");
718        assert_eq!(parse_prefix("BC:57:29"), vec![0xbc, 0x57, 0x29]);
719        assert_eq!(parse_prefix("bc5"), vec![0xbc]);
720    }
721}