1use std::collections::HashMap;
20use std::sync::{Arc, Mutex};
21use std::time::{Duration, SystemTime, UNIX_EPOCH};
22
23use bluetooth_host::Host;
24use bluetooth_mesh_stack::access::{Composition, ModelId};
25use bluetooth_mesh_stack::provisioning::Auth;
26use bluetooth_mesh_stack::runtime::{ad, run_host_bearer, HostBearer, Mesh, MeshEvent};
27use serde_json::{json, Value};
28
29use crate::mqtt::Mqtt;
30
31pub const AD_TYPES: [u8; 3] = [ad::PB_ADV, ad::MESSAGE, ad::BEACON];
33
34type Heard = Arc<Mutex<HashMap<[u8; 16], (u16, u64)>>>;
36
37#[derive(Clone)]
39pub struct BridgeMesh {
40 mesh: Mesh,
41 heard: Heard,
42}
43
44fn now() -> u64 {
45 SystemTime::now()
46 .duration_since(UNIX_EPOCH)
47 .map(|d| d.as_secs())
48 .unwrap_or(0)
49}
50
51fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
52 m.lock().unwrap_or_else(|e| e.into_inner())
53}
54
55impl BridgeMesh {
56 pub fn start(
58 host: &Host,
59 dir: std::path::PathBuf,
60 mqtt: Mqtt,
61 base: String,
62 ) -> Result<BridgeMesh, String> {
63 let mesh = Mesh::open(HostBearer::new(host.clone()), Some(dir), [0; 16])
64 .map_err(|e| format!("the mesh store: {e}"))?;
65 if mesh.store().net_keys.is_empty() {
66 mesh.create_network();
67 tracing::info!("mesh: created a network, the bridge at 0x0001");
68 }
69 tokio::spawn(run_host_bearer(host.clone(), mesh.clone()));
70 let heard: Heard = Arc::default();
71 let (h, mut events) = (heard.clone(), mesh.events());
72 tokio::spawn(async move {
73 loop {
74 match events.recv().await {
75 Ok(MeshEvent::Unprovisioned { uuid, oob_info }) => {
76 let new = lock(&h).insert(uuid, (oob_info, now())).is_none();
77 if new {
78 mqtt.publish_json(
79 format!("{base}/mesh/event"),
80 &json!({"type": "unprovisioned", "uuid": hex::encode(uuid), "oob_info": oob_info}),
81 false,
82 );
83 }
84 }
85 Ok(MeshEvent::Message {
86 src,
87 dst,
88 opcode,
89 params,
90 }) => mqtt.publish_json(
91 format!("{base}/mesh/event"),
92 &json!({"type": "message", "src": src, "dst": dst,
93 "opcode": format!("{opcode:?}"), "params": hex::encode(params)}),
94 false,
95 ),
96 Ok(_) => {}
97 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
98 Err(_) => return,
99 }
100 }
101 });
102 Ok(BridgeMesh { mesh, heard })
103 }
104
105 pub async fn request(&self, op: &str, body: &Value) -> Result<Value, String> {
107 let address = || -> Result<u16, String> {
108 body.get("address")
109 .and_then(Value::as_u64)
110 .and_then(|a| u16::try_from(a).ok())
111 .filter(|a| *a != 0 && a & 0x8000 == 0)
112 .ok_or_else(|| "`address` must be a node's unicast address".to_string())
113 };
114 let key16 = |name: &str| -> Result<Option<[u8; 16]>, String> {
115 match body.get(name).and_then(Value::as_str) {
116 None => Ok(None),
117 Some(s) => hex::decode(s)
118 .ok()
119 .and_then(|v| v.try_into().ok())
120 .map(Some)
121 .ok_or_else(|| format!("`{name}` must be 16 octets in hex")),
122 }
123 };
124 match op {
125 "network" => {
126 let s = self.mesh.store();
127 Ok(json!({
128 "address": s.address,
129 "iv_index": s.iv_index,
130 "nodes": s.nodes.iter().map(|n| json!({
131 "uuid": hex::encode(n.uuid), "address": n.address, "elements": n.elements,
132 })).collect::<Vec<_>>(),
133 }))
134 }
135 "unprovisioned" => {
136 let mut v: Vec<_> = lock(&self.heard)
137 .iter()
138 .map(|(u, (oob, at))| {
139 (
140 *at,
141 json!({"uuid": hex::encode(u), "oob_info": oob, "heard": at}),
142 )
143 })
144 .collect();
145 v.sort_by_key(|x| std::cmp::Reverse(x.0));
146 Ok(json!(v.into_iter().map(|(_, j)| j).collect::<Vec<_>>()))
147 }
148 "provision" => {
149 let uuid = key16("uuid")?.ok_or("`uuid` is required")?;
150 let auth = match key16("static_oob")? {
151 Some(k) => Auth::Static(k),
152 None => Auth::None,
153 };
154 let n =
155 tokio::time::timeout(Duration::from_secs(120), self.mesh.provision(uuid, auth))
156 .await
157 .map_err(|_| "provisioning timed out".to_string())?
158 .map_err(|e| e.to_string())?;
159 lock(&self.heard).remove(&uuid);
160 Ok(
161 json!({"uuid": hex::encode(n.uuid), "address": n.address, "elements": n.elements}),
162 )
163 }
164 "configure" => {
165 let a = address()?;
166 let node = self
167 .mesh
168 .store()
169 .nodes
170 .into_iter()
171 .find(|n| n.address == a)
172 .ok_or("no node with that address was provisioned here")?;
173 let c = tokio::time::timeout(Duration::from_secs(60), self.mesh.configure(&node))
174 .await
175 .map_err(|_| "configuration timed out".to_string())?
176 .map_err(|e| e.to_string())?;
177 Ok(composition(&c))
178 }
179 "onoff" => {
180 let a = address()?;
181 let on = body
182 .get("on")
183 .and_then(Value::as_bool)
184 .ok_or("`on` must be true or false")?;
185 let tid = (now() & 0xff) as u8;
186 let present =
187 tokio::time::timeout(Duration::from_secs(30), self.mesh.onoff_set(a, on, tid))
188 .await
189 .map_err(|_| "no answer".to_string())?
190 .map_err(|e| e.to_string())?;
191 Ok(json!({"on": present}))
192 }
193 _ => Err(format!("unknown request mesh/{op}")),
194 }
195 }
196}
197
198fn composition(c: &Composition) -> Value {
199 let model = |m: &ModelId| match m {
200 ModelId::Sig(id) => json!({
201 "id": format!("{id:04x}"),
202 "name": bluetooth_numbers::mesh_model(*id),
203 }),
204 ModelId::Vendor(company, id) => json!({
205 "company": company,
206 "company_name": bluetooth_numbers::company(*company),
207 "id": format!("{id:04x}"),
208 }),
209 };
210 json!({
211 "company": c.cid,
212 "company_name": bluetooth_numbers::company(c.cid),
213 "product": c.pid,
214 "version": c.vid,
215 "features": {
216 "relay": c.features & 1 != 0,
217 "proxy": c.features & 2 != 0,
218 "friend": c.features & 4 != 0,
219 "low_power": c.features & 8 != 0,
220 },
221 "elements": c.elements.iter().map(|e| json!({
222 "location": e.location,
223 "models": e.models.iter().map(model).collect::<Vec<_>>(),
224 })).collect::<Vec<_>>(),
225 })
226}
227
228pub fn only_mesh(data: &[u8]) -> bool {
230 let mut any = false;
231 for s in bluetooth_host::adv::AdStructures::new(data).flatten() {
232 if !AD_TYPES.contains(&s.ad_type) {
233 return false;
234 }
235 any = true;
236 }
237 any
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 #[test]
245 fn mesh_only_advertisements() {
246 assert!(only_mesh(&[4, 0x29, 1, 2, 3]));
247 assert!(only_mesh(&[3, 0x2a, 1, 2, 3, 0x2b, 9, 9]));
248 assert!(!only_mesh(&[2, 1, 6, 4, 0x29, 1, 2, 3]));
249 assert!(!only_mesh(&[]));
250 }
251}