Skip to main content

zwave_bridge/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4
5pub mod config;
6pub mod discovery;
7
8use anyhow::{Context, Result};
9use config::Config;
10use rumqttc::{AsyncClient, Event as MqttEvent, LastWill, MqttOptions, Packet, QoS};
11use serde_json::{json, Value as Json};
12use std::collections::{HashMap, HashSet};
13use std::path::Path;
14use std::time::{Duration, SystemTime, UNIX_EPOCH};
15use tokio::sync::mpsc;
16use tracing::{debug, info, warn};
17use zwave_host::{
18    Controller, Event, GrantPolicy, HostConfig, InclusionOptions, NetworkKeys, NodeStatus,
19    SecurityClass, ValueId, ValueKind,
20};
21use zwave_security::provisioning::Entry;
22use zwave_serial::port::Port;
23
24/// Loads `keys.json` from `dir`, creating it with fresh keys (mode 0600) on first start.
25pub fn load_or_create_keys(dir: &Path) -> Result<NetworkKeys> {
26    let path = dir.join("keys.json");
27    match std::fs::read(&path) {
28        Ok(b) => {
29            let mut keys: NetworkKeys = serde_json::from_slice(&b)
30                .with_context(|| format!("reading {}", path.display()))?;
31            // Keys made before Long Range support get Long Range keys of their own, once.
32            if keys.fill_long_range().map_err(|e| anyhow::anyhow!("{e}"))? {
33                let tmp = path.with_extension("json.tmp");
34                write_private(&tmp, &serde_json::to_vec_pretty(&keys)?)?;
35                std::fs::rename(&tmp, &path)?;
36                info!("added Long Range keys to {}", path.display());
37            }
38            Ok(keys)
39        }
40        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
41            std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
42            let keys = NetworkKeys::generate().map_err(|e| anyhow::anyhow!("{e}"))?;
43            let json = serde_json::to_vec_pretty(&keys)?;
44            let tmp = path.with_extension("json.tmp");
45            write_private(&tmp, &json)?;
46            std::fs::rename(&tmp, &path)?;
47            info!("generated network keys in {}", path.display());
48            Ok(keys)
49        }
50        Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
51    }
52}
53
54#[cfg(unix)]
55fn write_private(path: &Path, data: &[u8]) -> Result<()> {
56    use std::io::Write;
57    use std::os::unix::fs::OpenOptionsExt;
58    let mut f = std::fs::OpenOptions::new()
59        .write(true)
60        .create(true)
61        .truncate(true)
62        .mode(0o600)
63        .open(path)?;
64    f.write_all(data)?;
65    f.sync_all()?;
66    Ok(())
67}
68
69#[cfg(not(unix))]
70fn write_private(path: &Path, data: &[u8]) -> Result<()> {
71    std::fs::write(path, data)?;
72    Ok(())
73}
74
75fn now_ms() -> u64 {
76    SystemTime::now()
77        .duration_since(UNIX_EPOCH)
78        .map(|d| d.as_millis() as u64)
79        .unwrap_or(0)
80}
81
82fn status_name(s: NodeStatus) -> &'static str {
83    match s {
84        NodeStatus::Unknown => "unknown",
85        NodeStatus::Alive => "alive",
86        NodeStatus::Awake => "awake",
87        NodeStatus::Asleep => "asleep",
88        NodeStatus::Dead => "dead",
89    }
90}
91
92fn class_names(c: &[SecurityClass]) -> Vec<&'static str> {
93    c.iter().map(|c| c.name()).collect()
94}
95
96fn parse_classes(v: &Json) -> Vec<SecurityClass> {
97    let names: Vec<String> = serde_json::from_value(v.clone()).unwrap_or_default();
98    SecurityClass::HIGHEST_FIRST
99        .into_iter()
100        .filter(|c| names.iter().any(|n| n == c.name()))
101        .collect()
102}
103
104enum FromMqtt {
105    Connected,
106    Message(String, Vec<u8>),
107}
108
109struct Bridge {
110    cfg: Config,
111    restart: std::sync::Arc<tokio::sync::Notify>,
112    library: Option<std::sync::Arc<zwave_host::device_config::Library>>,
113    devices: HashMap<u16, std::sync::Arc<zwave_host::device_config::DeviceConfig>>,
114    c: Controller,
115    mqtt: AsyncClient,
116    base: String,
117    discovered: HashMap<u16, HashSet<String>>,
118    responses: mpsc::Sender<(String, Json)>,
119    /// The `transaction` of the request being handled, echoed in its response.
120    transaction: Option<Json>,
121}
122
123/// Runs the bridge on `port` until `shutdown` completes.
124pub async fn run<P: Port>(
125    cfg: Config,
126    port: P,
127    shutdown: impl std::future::Future<Output = ()>,
128) -> Result<()> {
129    let keys = load_or_create_keys(&cfg.store.dir)?;
130    let mut hc = HostConfig::new(keys, Some(cfg.store.dir.join("nodes.json")));
131    hc.wake_up_interval = cfg.network.wake_up_interval;
132    hc.inclusion_timeout = Duration::from_secs(cfg.network.inclusion_timeout);
133    let (c, mut events) = Controller::start(port, hc)
134        .await
135        .map_err(|e| anyhow::anyhow!("controller: {e}"))?;
136    let info = c.info();
137    info!(home = format!("{:08x}", info.home_id), node = info.node_id, version = %info.library_version, "controller ready");
138
139    let base = cfg.mqtt.base_topic.trim_end_matches('/').to_string();
140    let mut opts = MqttOptions::new(&cfg.mqtt.client_id, &cfg.mqtt.host, cfg.mqtt.port);
141    opts.set_keep_alive(Duration::from_secs(cfg.mqtt.keep_alive.max(5)));
142    opts.set_last_will(LastWill::new(
143        format!("{base}/bridge/state"),
144        "offline",
145        QoS::AtLeastOnce,
146        true,
147    ));
148    opts.set_max_packet_size(256 * 1024, 256 * 1024);
149    let password = match (&cfg.mqtt.password, &cfg.mqtt.password_file) {
150        (Some(p), _) => Some(p.clone()),
151        (None, Some(f)) => Some(
152            std::fs::read_to_string(f)
153                .with_context(|| format!("reading {}", f.display()))?
154                .trim_end()
155                .to_string(),
156        ),
157        _ => None,
158    };
159    if let Some(u) = &cfg.mqtt.username {
160        opts.set_credentials(u, password.unwrap_or_default());
161    }
162    let (mqtt, mut eventloop) = AsyncClient::new(opts, 256);
163    let (mtx, mut mrx) = mpsc::channel::<FromMqtt>(256);
164    tokio::spawn(async move {
165        loop {
166            match eventloop.poll().await {
167                Ok(MqttEvent::Incoming(Packet::ConnAck(_))) => {
168                    if mtx.send(FromMqtt::Connected).await.is_err() {
169                        return;
170                    }
171                }
172                Ok(MqttEvent::Incoming(Packet::Publish(p))) => {
173                    if mtx
174                        .send(FromMqtt::Message(p.topic, p.payload.to_vec()))
175                        .await
176                        .is_err()
177                    {
178                        return;
179                    }
180                }
181                Ok(_) => {}
182                Err(e) => {
183                    warn!("MQTT: {e}; reconnecting");
184                    tokio::time::sleep(Duration::from_secs(2)).await;
185                }
186            }
187        }
188    });
189    let (rtx, mut rrx) = mpsc::channel::<(String, Json)>(64);
190    let library = cfg.devices.dir.as_ref().map(|d| {
191        info!("device library: {}", d.display());
192        std::sync::Arc::new(zwave_host::device_config::Library::new(
193            zwave_host::device_config::DirSource::new(d),
194        ))
195    });
196    let restart = std::sync::Arc::new(tokio::sync::Notify::new());
197    let mut b = Bridge {
198        restart: restart.clone(),
199        cfg,
200        library,
201        devices: HashMap::new(),
202        c,
203        mqtt,
204        base,
205        discovered: HashMap::new(),
206        responses: rtx,
207        transaction: None,
208    };
209    for n in b.c.nodes() {
210        b.load_device(n.id);
211    }
212    tokio::pin!(shutdown);
213    loop {
214        tokio::select! {
215            m = mrx.recv() => match m {
216                Some(FromMqtt::Connected) => b.on_connected().await,
217                Some(FromMqtt::Message(t, p)) => b.on_message(&t, &p).await,
218                None => break,
219            },
220            e = events.recv() => match e {
221                Some(e) => b.on_event(e).await,
222                None => break,
223            },
224            r = rrx.recv() => if let Some((action, body)) = r {
225                b.publish_raw(&format!("{}/bridge/response/{action}", b.base), body.to_string().into_bytes(), false).await;
226            },
227            _ = &mut shutdown => break,
228            _ = restart.notified() => {
229                // The controller restarted with a restored memory: start over with a fresh host.
230                tokio::time::sleep(Duration::from_secs(1)).await;
231                b.publish_raw(&format!("{}/bridge/state", b.base), b"offline".to_vec(), true).await;
232                let _ = b.mqtt.disconnect().await;
233                return Err(anyhow::anyhow!("controller memory restored; restart zwave-bridge"));
234            }
235        }
236    }
237    b.publish_raw(
238        &format!("{}/bridge/state", b.base),
239        b"offline".to_vec(),
240        true,
241    )
242    .await;
243    let _ = b.mqtt.disconnect().await;
244    b.c.flush().map_err(|e| anyhow::anyhow!("{e}"))?;
245    Ok(())
246}
247
248impl Bridge {
249    async fn publish_raw(&self, topic: &str, payload: Vec<u8>, retain: bool) {
250        if let Err(e) = self
251            .mqtt
252            .publish(topic, QoS::AtLeastOnce, retain, payload)
253            .await
254        {
255            warn!("publish {topic}: {e}");
256        }
257    }
258
259    async fn publish(&self, topic: &str, body: &Json, retain: bool) {
260        if let (Some(t), true) = (&self.transaction, topic.contains("/bridge/response/")) {
261            let mut body = body.clone();
262            body["transaction"] = t.clone();
263            return self
264                .publish_raw(topic, body.to_string().into_bytes(), retain)
265                .await;
266        }
267        self.publish_raw(topic, body.to_string().into_bytes(), retain)
268            .await;
269    }
270
271    async fn on_connected(&mut self) {
272        info!("MQTT connected");
273        for t in [
274            format!("{}/bridge/request/+", self.base),
275            format!("{}/nodes/#", self.base),
276        ] {
277            if let Err(e) = self.mqtt.subscribe(t, QoS::AtLeastOnce).await {
278                warn!("subscribe: {e}");
279            }
280        }
281        self.publish_raw(
282            &format!("{}/bridge/state", self.base),
283            b"online".to_vec(),
284            true,
285        )
286        .await;
287        self.publish_info().await;
288        for n in self.c.nodes() {
289            self.publish_node(n.id).await;
290        }
291        self.discovered.clear();
292    }
293
294    async fn publish_info(&self) {
295        let i = self.c.info();
296        let body = json!({
297            "home_id": format!("{:08x}", i.home_id),
298            "node_id": i.node_id,
299            "library_version": i.library_version,
300            "library_type": i.library_type,
301            "firmware": i.firmware,
302            "manufacturer_id": i.manufacturer_id,
303            "product_type": i.product_type,
304            "product_id": i.product_id,
305            "chip_type": i.chip_type,
306            "sis": i.sis,
307            "region": i.region,
308            "dsk": self.c.dsk().to_string(),
309            "nodes": i.nodes,
310            "version": env!("CARGO_PKG_VERSION"),
311        });
312        self.publish(&format!("{}/bridge/info", self.base), &body, true)
313            .await;
314    }
315
316    async fn publish_node(&self, node: u16) {
317        let Some(rec) = self.c.node(node) else { return };
318        let mut body = serde_json::to_value(&rec).unwrap_or(Json::Null);
319        let status = status_name(self.c.status(node));
320        body["status"] = json!(status);
321        if let Some(d) = self.devices.get(&node) {
322            body["device"] = json!({"file": d.file, "manufacturer": d.manufacturer, "label": d.label, "description": d.description});
323        }
324        self.publish(&format!("{}/nodes/{node}", self.base), &body, true)
325            .await;
326        self.publish_raw(
327            &format!("{}/nodes/{node}/status", self.base),
328            status.as_bytes().to_vec(),
329            true,
330        )
331        .await;
332    }
333
334    /// Finds the node's device file in the library, if there is one.
335    fn load_device(&mut self, node: u16) {
336        let (Some(lib), Some(rec)) = (&self.library, self.c.node(node)) else {
337            return;
338        };
339        let Some(id) = zwave_host::device_config::device_id(&rec) else {
340            return;
341        };
342        match lib.lookup(&id) {
343            Ok(Some(d)) => {
344                info!(node, file = %d.file, "device file: {} {}", d.manufacturer, d.label);
345                self.devices.insert(node, std::sync::Arc::new(d));
346            }
347            Ok(None) => debug!(node, "no device file"),
348            Err(e) => warn!(node, "device file: {e}"),
349        }
350    }
351
352    async fn publish_parameters(&self, node: u16) {
353        let Some(d) = self.devices.get(&node) else {
354            return;
355        };
356        let params: Vec<Json> = d
357            .params
358            .iter()
359            .map(|p| {
360                json!({"key": p.key, "label": p.label, "description": p.description, "size": p.size, "min": p.min, "max": p.max,
361                       "default": p.default, "unsigned": p.unsigned, "read_only": p.read_only, "unit": p.unit,
362                       "options": p.options.iter().map(|(v, l)| json!({"value": v, "label": l})).collect::<Vec<_>>()})
363            })
364            .collect();
365        self.publish(
366            &format!("{}/nodes/{node}/parameters", self.base),
367            &json!(params),
368            true,
369        )
370        .await;
371    }
372
373    async fn event(&self, body: Json) {
374        self.publish(&format!("{}/bridge/event", self.base), &body, false)
375            .await;
376    }
377
378    async fn on_event(&mut self, e: Event) {
379        match e {
380            Event::Ready(_) => self.publish_info().await,
381            Event::Value(v) => {
382                let key = v.id.key();
383                let topic = format!("{}/nodes/{}/{key}", self.base, v.id.node);
384                let mut body = json!({ "time": now_ms(), "label": v.label });
385                match &v.value {
386                    ValueKind::Bool(b) => body["value"] = json!(b),
387                    ValueKind::Number(n) => body["value"] = json!(n),
388                    ValueKind::Level(l) => body["value"] = json!(l),
389                    ValueKind::State { id, label } => {
390                        body["value"] = json!(id);
391                        body["state"] = json!(label);
392                    }
393                }
394                if let Some(u) = v.unit {
395                    body["unit"] = json!(u);
396                }
397                if self.cfg.homeassistant.enabled && !self.discovered.get(&v.id.node).is_some_and(|s| s.contains(&key)) {
398                    if let Some(rec) = self.c.node(v.id.node) {
399                        if let Some(d) = discovery::for_value(&self.cfg.homeassistant.discovery_prefix, &self.base, self.c.info().home_id, &rec, self.devices.get(&v.id.node).map(|d| d.as_ref()), &v) {
400                            self.publish(&d.topic, &d.config, true).await;
401                        }
402                        self.discovered.entry(v.id.node).or_default().insert(key);
403                    }
404                }
405                self.publish(&topic, &body, true).await;
406            }
407            Event::NodeAdded { node } => {
408                self.event(json!({"event": "node_added", "node": node})).await;
409                self.publish_node(node).await;
410            }
411            Event::NodeRemoved { node } => {
412                self.event(json!({"event": "node_removed", "node": node})).await;
413                self.publish_raw(&format!("{}/nodes/{node}", self.base), vec![], true).await;
414                self.publish_raw(&format!("{}/nodes/{node}/status", self.base), vec![], true).await;
415                self.discovered.remove(&node);
416            }
417            Event::NodeUpdated { node } | Event::NodeStatus { node, .. } => self.publish_node(node).await,
418            Event::InterviewCompleted { node } => {
419                self.load_device(node);
420                self.publish_parameters(node).await;
421                self.event(json!({"event": "interview_completed", "node": node})).await;
422                self.publish_node(node).await;
423            }
424            Event::InterviewFailed { node, reason } => self.event(json!({"event": "interview_failed", "node": node, "reason": reason})).await,
425            Event::InterviewStage { node, stage } => self.event(json!({"event": "interview_stage", "node": node, "stage": stage})).await,
426            Event::InclusionStarted => self.event(json!({"event": "inclusion_started"})).await,
427            Event::InclusionStopped => self.event(json!({"event": "inclusion_stopped"})).await,
428            Event::ExclusionStarted => self.event(json!({"event": "exclusion_started"})).await,
429            Event::ExclusionStopped => self.event(json!({"event": "exclusion_stopped"})).await,
430            Event::GrantSecurityClasses { node, requested } => {
431                self.event(json!({"event": "grant_security_classes", "node": node, "requested": class_names(&requested)})).await
432            }
433            Event::ValidateDsk { node, dsk } => self.event(json!({"event": "validate_dsk", "node": node, "dsk": dsk})).await,
434            Event::SecurityBootstrapped { node, classes } => self.event(json!({"event": "security_bootstrapped", "node": node, "classes": class_names(&classes)})).await,
435            Event::SecurityFailed { node, reason } => self.event(json!({"event": "security_failed", "node": node, "reason": reason})).await,
436            Event::Route { node, repeaters, rssi } => {
437                self.publish(&format!("{}/nodes/{node}/route", self.base), &json!({"repeaters": repeaters, "rssi": rssi, "time": now_ms()}), true).await
438            }
439            Event::Command { node, endpoint, command } => {
440                let body = json!({"endpoint": endpoint, "cc": command.cc(), "command": command.name(), "frame": hex(&command.encode())});
441                self.publish(&format!("{}/nodes/{node}/command", self.base), &body, false).await;
442            }
443            Event::FirmwareUpdateProgress { node, sent, total } => {
444                self.event(json!({"event": "firmware_update_progress", "node": node, "sent": sent, "total": total})).await
445            }
446            Event::FirmwareUpdateFinished { node, status, success } => {
447                self.event(json!({"event": "firmware_update_finished", "node": node, "status": status, "success": success})).await
448            }
449            Event::ProvisioningChanged { entries } => self.event(json!({"event": "provisioning_changed", "entries": provisioning_json(&entries)})).await,
450        }
451    }
452
453    async fn on_message(&mut self, topic: &str, payload: &[u8]) {
454        let Some(rest) = topic.strip_prefix(&format!("{}/", self.base)) else {
455            return;
456        };
457        if let Some(action) = rest.strip_prefix("bridge/request/") {
458            let args: Json = if payload.is_empty() {
459                json!({})
460            } else {
461                serde_json::from_slice(payload).unwrap_or(json!({}))
462            };
463            self.request(action.to_string(), args).await;
464        } else if let Some(path) = rest
465            .strip_prefix("nodes/")
466            .and_then(|p| p.strip_suffix("/set"))
467        {
468            self.set(path, payload);
469        }
470    }
471
472    fn respond_later(
473        &self,
474        action: String,
475        fut: impl std::future::Future<Output = Json> + Send + 'static,
476    ) {
477        let tx = self.responses.clone();
478        let transaction = self.transaction.clone();
479        tokio::spawn(async move {
480            let mut body = fut.await;
481            if let Some(t) = transaction {
482                body["transaction"] = t;
483            }
484            let _ = tx.send((action, body)).await;
485        });
486    }
487
488    async fn request(&mut self, action: String, args: Json) {
489        self.transaction = args.get("transaction").cloned();
490        self.handle_request(action, args).await;
491        self.transaction = None;
492    }
493
494    async fn handle_request(&mut self, action: String, args: Json) {
495        debug!(%action, %args, "request");
496        let c = self.c.clone();
497        let node = args.get("node").and_then(Json::as_u64).map(|n| n as u16);
498        let reply = |r: Result<Json, String>| match r {
499            Ok(mut j) => {
500                j["ok"] = json!(true);
501                j
502            }
503            Err(e) => json!({"ok": false, "error": e}),
504        };
505        match action.as_str() {
506            "include" => {
507                let grant = match args.get("strategy").and_then(Json::as_str) {
508                    Some("requested") => GrantPolicy::Requested,
509                    Some("insecure") => GrantPolicy::Only(vec![]),
510                    _ => match args.get("classes") {
511                        Some(v) => GrantPolicy::Only(parse_classes(v)),
512                        None => GrantPolicy::Ask,
513                    },
514                };
515                let opts = InclusionOptions {
516                    insecure: args.get("strategy").and_then(Json::as_str) == Some("insecure"),
517                    pin: args
518                        .get("pin")
519                        .and_then(Json::as_str)
520                        .and_then(|p| zwave_security::dsk::parse_pin(p).ok()),
521                    grant,
522                    timeout: args
523                        .get("timeout")
524                        .and_then(Json::as_u64)
525                        .map(Duration::from_secs),
526                };
527                self.respond_later(action, async move {
528                    reply(c.include(opts).await.map(|r| json!({"node": r.node, "security": class_names(&r.security), "security_error": r.security_error})).map_err(|e| e.to_string()))
529                });
530            }
531            "exclude" => {
532                let t = args
533                    .get("timeout")
534                    .and_then(Json::as_u64)
535                    .map(Duration::from_secs);
536                self.respond_later(action, async move {
537                    reply(
538                        c.exclude(t)
539                            .await
540                            .map(|n| json!({"node": n}))
541                            .map_err(|e| e.to_string()),
542                    )
543                });
544            }
545            "stop" => {
546                let body = json!({"ok": c.stop_inclusion()});
547                self.publish(&format!("{}/bridge/response/stop", self.base), &body, false)
548                    .await;
549            }
550            "grant" => {
551                let ok = c.grant_security_classes(parse_classes(
552                    args.get("classes").unwrap_or(&json!([])),
553                ));
554                self.publish(
555                    &format!("{}/bridge/response/grant", self.base),
556                    &json!({"ok": ok}),
557                    false,
558                )
559                .await;
560            }
561            "validate_dsk" => {
562                let pin = args
563                    .get("pin")
564                    .and_then(Json::as_str)
565                    .and_then(|p| zwave_security::dsk::parse_pin(p).ok());
566                let ok = c.validate_dsk(pin);
567                self.publish(
568                    &format!("{}/bridge/response/validate_dsk", self.base),
569                    &json!({"ok": ok}),
570                    false,
571                )
572                .await;
573            }
574            "provision" => {
575                let entry = if let Some(qr) = args.get("qr").and_then(Json::as_str) {
576                    zwave_security::qr::parse(qr)
577                        .map(|q| Entry::from_qr(&q))
578                        .map_err(|e| e.to_string())
579                } else if let Some(dsk) = args.get("dsk").and_then(Json::as_str) {
580                    dsk.parse()
581                        .map_err(|e: zwave_security::Error| e.to_string())
582                        .map(|dsk| Entry {
583                            dsk,
584                            granted: parse_classes(
585                                args.get("classes")
586                                    .unwrap_or(&json!(["s2_authenticated", "s2_unauthenticated"])),
587                            ),
588                            status: Default::default(),
589                            node_id: None,
590                            name: args.get("name").and_then(Json::as_str).map(String::from),
591                        })
592                } else {
593                    Err("give \"qr\" or \"dsk\"".to_string())
594                };
595                self.respond_later(action, async move {
596                    match entry {
597                        Ok(e) => {
598                            let dsk = e.dsk.to_string();
599                            reply(
600                                c.provision(e)
601                                    .await
602                                    .map(|_| json!({"dsk": dsk}))
603                                    .map_err(|e| e.to_string()),
604                            )
605                        }
606                        Err(e) => reply(Err(e)),
607                    }
608                });
609            }
610            "unprovision" => {
611                let dsk = args
612                    .get("dsk")
613                    .and_then(Json::as_str)
614                    .and_then(|d| d.parse().ok());
615                self.respond_later(action, async move {
616                    match dsk {
617                        Some(d) => reply(Ok(json!({"removed": c.unprovision(&d).await.is_some()}))),
618                        None => reply(Err("give \"dsk\"".into())),
619                    }
620                });
621            }
622            "provisioning_list" => {
623                let body =
624                    json!({"ok": true, "entries": provisioning_json(&c.provisioning_list())});
625                self.publish(
626                    &format!("{}/bridge/response/provisioning_list", self.base),
627                    &body,
628                    false,
629                )
630                .await;
631            }
632            "backup" => {
633                let dir = self.cfg.store.dir.clone();
634                self.respond_later(action, async move {
635                    reply(match c.backup_nvm().await {
636                        Ok(image) => {
637                            let path = dir.join(format!("nvm-{}.bin", now_ms() / 1000));
638                            std::fs::write(&path, &image).map(|_| json!({"file": path.display().to_string(), "bytes": image.len()})).map_err(|e| e.to_string())
639                        }
640                        Err(e) => Err(e.to_string()),
641                    })
642                });
643            }
644            "reinterview" => {
645                let r = node
646                    .ok_or("give \"node\"".to_string())
647                    .and_then(|n| c.reinterview(n).map_err(|e| e.to_string()));
648                self.publish(
649                    &format!("{}/bridge/response/reinterview", self.base),
650                    &reply(r.map(|_| json!({}))),
651                    false,
652                )
653                .await;
654            }
655            "remove_failed" => {
656                self.respond_later(action, async move {
657                    match node {
658                        Some(n) => reply(
659                            c.remove_failed_node(n)
660                                .await
661                                .map(|_| json!({"node": n}))
662                                .map_err(|e| e.to_string()),
663                        ),
664                        None => reply(Err("give \"node\"".into())),
665                    }
666                });
667            }
668            "rename" => {
669                let name = args.get("name").and_then(Json::as_str).map(String::from);
670                let location = args
671                    .get("location")
672                    .and_then(Json::as_str)
673                    .map(String::from);
674                let r = node
675                    .ok_or("give \"node\"".to_string())
676                    .and_then(|n| c.set_name(n, name, location).map_err(|e| e.to_string()));
677                self.publish(
678                    &format!("{}/bridge/response/rename", self.base),
679                    &reply(r.map(|_| json!({}))),
680                    false,
681                )
682                .await;
683            }
684            "restore" => {
685                // A backup the bridge wrote (or the operator put) in the store directory.
686                let file = args.get("file").and_then(Json::as_str).map(String::from);
687                let dir = self.cfg.store.dir.clone();
688                let restarted = self.restart.clone();
689                self.respond_later(action, async move {
690                    let Some(file) = file
691                        .filter(|f| !f.contains('/') && !f.contains('\\') && !f.starts_with('.'))
692                    else {
693                        return reply(Err(
694                            "\"file\" is a backup's name in the store directory".into()
695                        ));
696                    };
697                    let image = match std::fs::read(dir.join(&file)) {
698                        Ok(b) => b,
699                        Err(e) => return reply(Err(format!("{file}: {e}"))),
700                    };
701                    match c.restore_nvm(&image).await {
702                        Ok(()) => {
703                            restarted.notify_one();
704                            reply(Ok(json!({"file": file, "restart": true})))
705                        }
706                        Err(e) => reply(Err(e.to_string())),
707                    }
708                });
709            }
710            "firmware_update" => {
711                // Only files the operator put in <store>/firmware, never a path from the network.
712                let dir = self.cfg.store.dir.join("firmware");
713                let file = args.get("file").and_then(Json::as_str).map(String::from);
714                let target = args.get("target").and_then(Json::as_u64).unwrap_or(0) as u8;
715                self.respond_later(action, async move {
716                    let (Some(n), Some(file)) = (node, file) else {
717                        return reply(Err("give \"node\" and \"file\"".into()));
718                    };
719                    if file.contains('/') || file.contains('\\') || file.starts_with('.') {
720                        return reply(Err("\"file\" is a name in the firmware directory".into()));
721                    }
722                    let bytes = match std::fs::read(dir.join(&file)) {
723                        Ok(b) => b,
724                        Err(e) => return reply(Err(format!("{file}: {e}"))),
725                    };
726                    let image = match zwave_host::firmware::read_image(&file, &bytes) {
727                        Ok(i) => i,
728                        Err(e) => return reply(Err(format!("{file}: {e}"))),
729                    };
730                    reply(
731                        c.update_firmware(n, &image, target)
732                            .await
733                            .map(|r| json!({"node": n, "status": r.status, "success": r.success(), "wait_time": r.wait_time, "activated": r.activated}))
734                            .map_err(|e| e.to_string()),
735                    )
736                });
737            }
738            "configure" => {
739                let device = node.and_then(|n| self.devices.get(&n).cloned());
740                let settings: Vec<(String, i64)> = args
741                    .get("settings")
742                    .and_then(Json::as_object)
743                    .map(|m| {
744                        m.iter()
745                            .filter_map(|(k, v)| Some((k.clone(), v.as_i64()?)))
746                            .collect()
747                    })
748                    .unwrap_or_default();
749                self.respond_later(action, async move {
750                    match (node, device) {
751                        (Some(n), Some(d)) => reply(
752                            c.configure(n, &d, &settings)
753                                .await
754                                .map(|_| json!({"node": n}))
755                                .map_err(|e| e.to_string()),
756                        ),
757                        (Some(n), None) => reply(Err(format!("no device file for node {n}"))),
758                        _ => reply(Err("give \"node\" and \"settings\"".into())),
759                    }
760                });
761            }
762            "topology" => {
763                self.respond_later(action, async move {
764                    for n in c.nodes() {
765                        let _ = c.refresh_neighbors(n.id).await;
766                    }
767                    let t = c.topology();
768                    let nodes: Vec<Json> = t
769                        .nodes
770                        .iter()
771                        .map(|n| json!({"id": n.id, "neighbors": n.neighbors, "route": n.last_route, "rssi": n.last_rssi, "listening": n.listening}))
772                        .collect();
773                    reply(Ok(json!({"controller": t.controller, "nodes": nodes})))
774                });
775            }
776            other => {
777                let body = json!({"ok": false, "error": format!("unknown request {other}")});
778                self.publish(
779                    &format!("{}/bridge/response/{other}", self.base),
780                    &body,
781                    false,
782                )
783                .await;
784            }
785        }
786    }
787
788    fn set(&self, path: &str, payload: &[u8]) {
789        // <node>/<class>/<property>[/<endpoint>]
790        let parts: Vec<&str> = path.split('/').collect();
791        let (node, class, property, endpoint) = match parts.as_slice() {
792            [n, c, p] => (n, c, p, "0"),
793            [n, c, p, e] => (n, c, p, *e),
794            _ => return,
795        };
796        let (Ok(node), Ok(endpoint)) = (node.parse::<u16>(), endpoint.parse::<u8>()) else {
797            return;
798        };
799        let Some(cc) = zwave_cc::COMMAND_CLASSES
800            .iter()
801            .find(|c| c.name == *class)
802            .map(|c| c.id)
803        else {
804            return;
805        };
806        let text = String::from_utf8_lossy(payload).trim().to_string();
807        let json: Option<Json> = serde_json::from_str(&text).ok();
808        let raw = match json.as_ref().and_then(|j| j.get("value")).cloned().or(json) {
809            Some(Json::Bool(b)) => Some(ValueKind::Bool(b)),
810            Some(Json::Number(n)) => n.as_f64().map(|f| {
811                if cc == 0x25 {
812                    ValueKind::Bool(f != 0.0)
813                } else {
814                    ValueKind::Level(f.clamp(0.0, 255.0) as u8)
815                }
816            }),
817            _ => match text.to_ascii_uppercase().as_str() {
818                "ON" | "TRUE" => Some(if cc == 0x25 {
819                    ValueKind::Bool(true)
820                } else {
821                    ValueKind::Level(0xff)
822                }),
823                "OFF" | "FALSE" => Some(if cc == 0x25 {
824                    ValueKind::Bool(false)
825                } else {
826                    ValueKind::Level(0)
827                }),
828                _ => None,
829            },
830        };
831        let Some(value) = raw else {
832            warn!(topic = path, "unreadable set payload");
833            return;
834        };
835        let id = ValueId {
836            node,
837            endpoint,
838            cc,
839            property: property.to_string(),
840        };
841        let c = self.c.clone();
842        tokio::spawn(async move {
843            if let Err(e) = c.set_value(&id, &value).await {
844                warn!("set {}: {e}", id.key());
845            }
846        });
847    }
848}
849
850fn hex(b: &[u8]) -> String {
851    b.iter().map(|x| format!("{x:02x}")).collect()
852}
853
854fn provisioning_json(entries: &[Entry]) -> Json {
855    Json::Array(
856        entries
857            .iter()
858            .map(|e| json!({"dsk": e.dsk.to_string(), "classes": class_names(&e.granted), "node": e.node_id, "name": e.name, "active": e.status == Default::default()}))
859            .collect(),
860    )
861}