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                                    "endpoints": endpoint_labels(d.endpoints.as_ref())});
324        }
325        self.publish(&format!("{}/nodes/{node}", self.base), &body, true)
326            .await;
327        self.publish_raw(
328            &format!("{}/nodes/{node}/status", self.base),
329            status.as_bytes().to_vec(),
330            true,
331        )
332        .await;
333    }
334
335    /// Finds the node's device file in the library, if there is one.
336    fn load_device(&mut self, node: u16) {
337        let (Some(lib), Some(rec)) = (&self.library, self.c.node(node)) else {
338            return;
339        };
340        let Some(id) = zwave_host::device_config::device_id(&rec) else {
341            return;
342        };
343        match lib.lookup(&id) {
344            Ok(Some(d)) => {
345                info!(node, file = %d.file, "device file: {} {}", d.manufacturer, d.label);
346                self.devices.insert(node, std::sync::Arc::new(d));
347            }
348            Ok(None) => debug!(node, "no device file"),
349            Err(e) => warn!(node, "device file: {e}"),
350        }
351    }
352
353    async fn publish_parameters(&self, node: u16) {
354        let Some(d) = self.devices.get(&node) else {
355            return;
356        };
357        let params: Vec<Json> = d
358            .params
359            .iter()
360            .map(|p| {
361                json!({"key": p.key, "label": p.label, "description": p.description, "size": p.size, "min": p.min, "max": p.max,
362                       "default": p.default, "unsigned": p.unsigned, "read_only": p.read_only, "unit": p.unit,
363                       "options": p.options.iter().map(|(v, l)| json!({"value": v, "label": l})).collect::<Vec<_>>()})
364            })
365            .collect();
366        self.publish(
367            &format!("{}/nodes/{node}/parameters", self.base),
368            &json!(params),
369            true,
370        )
371        .await;
372    }
373
374    async fn event(&self, body: Json) {
375        self.publish(&format!("{}/bridge/event", self.base), &body, false)
376            .await;
377    }
378
379    async fn on_event(&mut self, e: Event) {
380        match e {
381            Event::Ready(_) => self.publish_info().await,
382            Event::Value(v) => {
383                let key = v.id.key();
384                let topic = format!("{}/nodes/{}/{key}", self.base, v.id.node);
385                let mut body = json!({ "time": now_ms(), "label": v.label });
386                match &v.value {
387                    ValueKind::Bool(b) => body["value"] = json!(b),
388                    ValueKind::Number(n) => body["value"] = json!(n),
389                    ValueKind::Level(l) => body["value"] = json!(l),
390                    ValueKind::State { id, label } => {
391                        body["value"] = json!(id);
392                        body["state"] = json!(label);
393                    }
394                }
395                if let Some(u) = v.unit {
396                    body["unit"] = json!(u);
397                }
398                if self.cfg.homeassistant.enabled && !self.discovered.get(&v.id.node).is_some_and(|s| s.contains(&key)) {
399                    if let Some(rec) = self.c.node(v.id.node) {
400                        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) {
401                            self.publish(&d.topic, &d.config, true).await;
402                        }
403                        self.discovered.entry(v.id.node).or_default().insert(key);
404                    }
405                }
406                self.publish(&topic, &body, true).await;
407            }
408            Event::NodeAdded { node } => {
409                self.event(json!({"event": "node_added", "node": node})).await;
410                self.publish_node(node).await;
411            }
412            Event::NodeRemoved { node } => {
413                self.event(json!({"event": "node_removed", "node": node})).await;
414                self.publish_raw(&format!("{}/nodes/{node}", self.base), vec![], true).await;
415                self.publish_raw(&format!("{}/nodes/{node}/status", self.base), vec![], true).await;
416                self.discovered.remove(&node);
417            }
418            Event::NodeUpdated { node } | Event::NodeStatus { node, .. } => self.publish_node(node).await,
419            Event::InterviewCompleted { node } => {
420                self.load_device(node);
421                self.publish_parameters(node).await;
422                self.event(json!({"event": "interview_completed", "node": node})).await;
423                self.publish_node(node).await;
424            }
425            Event::InterviewFailed { node, reason } => self.event(json!({"event": "interview_failed", "node": node, "reason": reason})).await,
426            Event::InterviewStage { node, stage } => self.event(json!({"event": "interview_stage", "node": node, "stage": stage})).await,
427            Event::InclusionStarted => self.event(json!({"event": "inclusion_started"})).await,
428            Event::InclusionStopped => self.event(json!({"event": "inclusion_stopped"})).await,
429            Event::ExclusionStarted => self.event(json!({"event": "exclusion_started"})).await,
430            Event::ExclusionStopped => self.event(json!({"event": "exclusion_stopped"})).await,
431            Event::GrantSecurityClasses { node, requested } => {
432                self.event(json!({"event": "grant_security_classes", "node": node, "requested": class_names(&requested)})).await
433            }
434            Event::ValidateDsk { node, dsk } => self.event(json!({"event": "validate_dsk", "node": node, "dsk": dsk})).await,
435            Event::SecurityBootstrapped { node, classes } => self.event(json!({"event": "security_bootstrapped", "node": node, "classes": class_names(&classes)})).await,
436            Event::SecurityFailed { node, reason } => self.event(json!({"event": "security_failed", "node": node, "reason": reason})).await,
437            Event::Route { node, repeaters, rssi } => {
438                self.publish(&format!("{}/nodes/{node}/route", self.base), &json!({"repeaters": repeaters, "rssi": rssi, "time": now_ms()}), true).await
439            }
440            Event::Command { node, endpoint, command } => {
441                let body = json!({"endpoint": endpoint, "cc": command.cc(), "command": command.name(), "frame": hex(&command.encode())});
442                self.publish(&format!("{}/nodes/{node}/command", self.base), &body, false).await;
443            }
444            Event::FirmwareUpdateProgress { node, sent, total } => {
445                self.event(json!({"event": "firmware_update_progress", "node": node, "sent": sent, "total": total})).await
446            }
447            Event::FirmwareUpdateFinished { node, status, success } => {
448                self.event(json!({"event": "firmware_update_finished", "node": node, "status": status, "success": success})).await
449            }
450            Event::ProvisioningChanged { entries } => self.event(json!({"event": "provisioning_changed", "entries": provisioning_json(&entries)})).await,
451        }
452    }
453
454    async fn on_message(&mut self, topic: &str, payload: &[u8]) {
455        let Some(rest) = topic.strip_prefix(&format!("{}/", self.base)) else {
456            return;
457        };
458        if let Some(action) = rest.strip_prefix("bridge/request/") {
459            let args: Json = if payload.is_empty() {
460                json!({})
461            } else {
462                serde_json::from_slice(payload).unwrap_or(json!({}))
463            };
464            self.request(action.to_string(), args).await;
465        } else if let Some(path) = rest
466            .strip_prefix("nodes/")
467            .and_then(|p| p.strip_suffix("/set"))
468        {
469            self.set(path, payload);
470        }
471    }
472
473    fn respond_later(
474        &self,
475        action: String,
476        fut: impl std::future::Future<Output = Json> + Send + 'static,
477    ) {
478        let tx = self.responses.clone();
479        let transaction = self.transaction.clone();
480        tokio::spawn(async move {
481            let mut body = fut.await;
482            if let Some(t) = transaction {
483                body["transaction"] = t;
484            }
485            let _ = tx.send((action, body)).await;
486        });
487    }
488
489    async fn request(&mut self, action: String, args: Json) {
490        self.transaction = args.get("transaction").cloned();
491        self.handle_request(action, args).await;
492        self.transaction = None;
493    }
494
495    async fn handle_request(&mut self, action: String, args: Json) {
496        debug!(%action, %args, "request");
497        let c = self.c.clone();
498        let node = args.get("node").and_then(Json::as_u64).map(|n| n as u16);
499        let reply = |r: Result<Json, String>| match r {
500            Ok(mut j) => {
501                j["ok"] = json!(true);
502                j
503            }
504            Err(e) => json!({"ok": false, "error": e}),
505        };
506        match action.as_str() {
507            "include" => {
508                let grant = match args.get("strategy").and_then(Json::as_str) {
509                    Some("requested") => GrantPolicy::Requested,
510                    Some("insecure") => GrantPolicy::Only(vec![]),
511                    _ => match args.get("classes") {
512                        Some(v) => GrantPolicy::Only(parse_classes(v)),
513                        None => GrantPolicy::Ask,
514                    },
515                };
516                let opts = InclusionOptions {
517                    insecure: args.get("strategy").and_then(Json::as_str) == Some("insecure"),
518                    pin: args
519                        .get("pin")
520                        .and_then(Json::as_str)
521                        .and_then(|p| zwave_security::dsk::parse_pin(p).ok()),
522                    grant,
523                    timeout: args
524                        .get("timeout")
525                        .and_then(Json::as_u64)
526                        .map(Duration::from_secs),
527                };
528                self.respond_later(action, async move {
529                    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()))
530                });
531            }
532            "exclude" => {
533                let t = args
534                    .get("timeout")
535                    .and_then(Json::as_u64)
536                    .map(Duration::from_secs);
537                self.respond_later(action, async move {
538                    reply(
539                        c.exclude(t)
540                            .await
541                            .map(|n| json!({"node": n}))
542                            .map_err(|e| e.to_string()),
543                    )
544                });
545            }
546            "stop" => {
547                let body = json!({"ok": c.stop_inclusion()});
548                self.publish(&format!("{}/bridge/response/stop", self.base), &body, false)
549                    .await;
550            }
551            "grant" => {
552                let ok = c.grant_security_classes(parse_classes(
553                    args.get("classes").unwrap_or(&json!([])),
554                ));
555                self.publish(
556                    &format!("{}/bridge/response/grant", self.base),
557                    &json!({"ok": ok}),
558                    false,
559                )
560                .await;
561            }
562            "validate_dsk" => {
563                let pin = args
564                    .get("pin")
565                    .and_then(Json::as_str)
566                    .and_then(|p| zwave_security::dsk::parse_pin(p).ok());
567                let ok = c.validate_dsk(pin);
568                self.publish(
569                    &format!("{}/bridge/response/validate_dsk", self.base),
570                    &json!({"ok": ok}),
571                    false,
572                )
573                .await;
574            }
575            "provision" => {
576                let entry = if let Some(qr) = args.get("qr").and_then(Json::as_str) {
577                    zwave_security::qr::parse(qr)
578                        .map(|q| Entry::from_qr(&q))
579                        .map_err(|e| e.to_string())
580                } else if let Some(dsk) = args.get("dsk").and_then(Json::as_str) {
581                    dsk.parse()
582                        .map_err(|e: zwave_security::Error| e.to_string())
583                        .map(|dsk| Entry {
584                            dsk,
585                            granted: parse_classes(
586                                args.get("classes")
587                                    .unwrap_or(&json!(["s2_authenticated", "s2_unauthenticated"])),
588                            ),
589                            status: Default::default(),
590                            node_id: None,
591                            name: args.get("name").and_then(Json::as_str).map(String::from),
592                        })
593                } else {
594                    Err("give \"qr\" or \"dsk\"".to_string())
595                };
596                self.respond_later(action, async move {
597                    match entry {
598                        Ok(e) => {
599                            let dsk = e.dsk.to_string();
600                            reply(
601                                c.provision(e)
602                                    .await
603                                    .map(|_| json!({"dsk": dsk}))
604                                    .map_err(|e| e.to_string()),
605                            )
606                        }
607                        Err(e) => reply(Err(e)),
608                    }
609                });
610            }
611            "unprovision" => {
612                let dsk = args
613                    .get("dsk")
614                    .and_then(Json::as_str)
615                    .and_then(|d| d.parse().ok());
616                self.respond_later(action, async move {
617                    match dsk {
618                        Some(d) => reply(Ok(json!({"removed": c.unprovision(&d).await.is_some()}))),
619                        None => reply(Err("give \"dsk\"".into())),
620                    }
621                });
622            }
623            "provisioning_list" => {
624                let body =
625                    json!({"ok": true, "entries": provisioning_json(&c.provisioning_list())});
626                self.publish(
627                    &format!("{}/bridge/response/provisioning_list", self.base),
628                    &body,
629                    false,
630                )
631                .await;
632            }
633            "backup" => {
634                let dir = self.cfg.store.dir.clone();
635                self.respond_later(action, async move {
636                    reply(match c.backup_nvm().await {
637                        Ok(image) => {
638                            let path = dir.join(format!("nvm-{}.bin", now_ms() / 1000));
639                            std::fs::write(&path, &image).map(|_| json!({"file": path.display().to_string(), "bytes": image.len()})).map_err(|e| e.to_string())
640                        }
641                        Err(e) => Err(e.to_string()),
642                    })
643                });
644            }
645            "reinterview" => {
646                let r = node
647                    .ok_or("give \"node\"".to_string())
648                    .and_then(|n| c.reinterview(n).map_err(|e| e.to_string()));
649                self.publish(
650                    &format!("{}/bridge/response/reinterview", self.base),
651                    &reply(r.map(|_| json!({}))),
652                    false,
653                )
654                .await;
655            }
656            "remove_failed" => {
657                self.respond_later(action, async move {
658                    match node {
659                        Some(n) => reply(
660                            c.remove_failed_node(n)
661                                .await
662                                .map(|_| json!({"node": n}))
663                                .map_err(|e| e.to_string()),
664                        ),
665                        None => reply(Err("give \"node\"".into())),
666                    }
667                });
668            }
669            "rename" => {
670                let name = args.get("name").and_then(Json::as_str).map(String::from);
671                let location = args
672                    .get("location")
673                    .and_then(Json::as_str)
674                    .map(String::from);
675                let r = node
676                    .ok_or("give \"node\"".to_string())
677                    .and_then(|n| c.set_name(n, name, location).map_err(|e| e.to_string()));
678                self.publish(
679                    &format!("{}/bridge/response/rename", self.base),
680                    &reply(r.map(|_| json!({}))),
681                    false,
682                )
683                .await;
684            }
685            "restore" => {
686                // A backup the bridge wrote (or the operator put) in the store directory.
687                let file = args.get("file").and_then(Json::as_str).map(String::from);
688                let dir = self.cfg.store.dir.clone();
689                let restarted = self.restart.clone();
690                self.respond_later(action, async move {
691                    let Some(file) = file
692                        .filter(|f| !f.contains('/') && !f.contains('\\') && !f.starts_with('.'))
693                    else {
694                        return reply(Err(
695                            "\"file\" is a backup's name in the store directory".into()
696                        ));
697                    };
698                    let image = match std::fs::read(dir.join(&file)) {
699                        Ok(b) => b,
700                        Err(e) => return reply(Err(format!("{file}: {e}"))),
701                    };
702                    match c.restore_nvm(&image).await {
703                        Ok(()) => {
704                            restarted.notify_one();
705                            reply(Ok(json!({"file": file, "restart": true})))
706                        }
707                        Err(e) => reply(Err(e.to_string())),
708                    }
709                });
710            }
711            "firmware_update" => {
712                // Only files the operator put in <store>/firmware, never a path from the network.
713                let dir = self.cfg.store.dir.join("firmware");
714                let file = args.get("file").and_then(Json::as_str).map(String::from);
715                let target = args.get("target").and_then(Json::as_u64).unwrap_or(0) as u8;
716                self.respond_later(action, async move {
717                    let (Some(n), Some(file)) = (node, file) else {
718                        return reply(Err("give \"node\" and \"file\"".into()));
719                    };
720                    if file.contains('/') || file.contains('\\') || file.starts_with('.') {
721                        return reply(Err("\"file\" is a name in the firmware directory".into()));
722                    }
723                    let bytes = match std::fs::read(dir.join(&file)) {
724                        Ok(b) => b,
725                        Err(e) => return reply(Err(format!("{file}: {e}"))),
726                    };
727                    let image = match zwave_host::firmware::read_image(&file, &bytes) {
728                        Ok(i) => i,
729                        Err(e) => return reply(Err(format!("{file}: {e}"))),
730                    };
731                    reply(
732                        c.update_firmware(n, &image, target)
733                            .await
734                            .map(|r| json!({"node": n, "status": r.status, "success": r.success(), "wait_time": r.wait_time, "activated": r.activated}))
735                            .map_err(|e| e.to_string()),
736                    )
737                });
738            }
739            "configure" => {
740                let device = node.and_then(|n| self.devices.get(&n).cloned());
741                let settings: Vec<(String, i64)> = args
742                    .get("settings")
743                    .and_then(Json::as_object)
744                    .map(|m| {
745                        m.iter()
746                            .filter_map(|(k, v)| Some((k.clone(), v.as_i64()?)))
747                            .collect()
748                    })
749                    .unwrap_or_default();
750                self.respond_later(action, async move {
751                    match (node, device) {
752                        (Some(n), Some(d)) => reply(
753                            c.configure(n, &d, &settings)
754                                .await
755                                .map(|_| json!({"node": n}))
756                                .map_err(|e| e.to_string()),
757                        ),
758                        (Some(n), None) => reply(Err(format!("no device file for node {n}"))),
759                        _ => reply(Err("give \"node\" and \"settings\"".into())),
760                    }
761                });
762            }
763            "topology" => {
764                self.respond_later(action, async move {
765                    for n in c.nodes() {
766                        let _ = c.refresh_neighbors(n.id).await;
767                    }
768                    let t = c.topology();
769                    let nodes: Vec<Json> = t
770                        .nodes
771                        .iter()
772                        .map(|n| json!({"id": n.id, "neighbors": n.neighbors, "route": n.last_route, "rssi": n.last_rssi, "listening": n.listening}))
773                        .collect();
774                    reply(Ok(json!({"controller": t.controller, "nodes": nodes})))
775                });
776            }
777            other => {
778                let body = json!({"ok": false, "error": format!("unknown request {other}")});
779                self.publish(
780                    &format!("{}/bridge/response/{other}", self.base),
781                    &body,
782                    false,
783                )
784                .await;
785            }
786        }
787    }
788
789    fn set(&self, path: &str, payload: &[u8]) {
790        // <node>/<class>/<property>[/<endpoint>]
791        let parts: Vec<&str> = path.split('/').collect();
792        let (node, class, property, endpoint) = match parts.as_slice() {
793            [n, c, p] => (n, c, p, "0"),
794            [n, c, p, e] => (n, c, p, *e),
795            _ => return,
796        };
797        let (Ok(node), Ok(endpoint)) = (node.parse::<u16>(), endpoint.parse::<u8>()) else {
798            return;
799        };
800        let Some(cc) = zwave_cc::COMMAND_CLASSES
801            .iter()
802            .find(|c| c.name == *class)
803            .map(|c| c.id)
804        else {
805            return;
806        };
807        let text = String::from_utf8_lossy(payload).trim().to_string();
808        let json: Option<Json> = serde_json::from_str(&text).ok();
809        let raw = match json.as_ref().and_then(|j| j.get("value")).cloned().or(json) {
810            Some(Json::Bool(b)) => Some(ValueKind::Bool(b)),
811            Some(Json::Number(n)) => n.as_f64().map(|f| {
812                if cc == 0x25 {
813                    ValueKind::Bool(f != 0.0)
814                } else {
815                    ValueKind::Level(f.clamp(0.0, 255.0) as u8)
816                }
817            }),
818            _ => match text.to_ascii_uppercase().as_str() {
819                "ON" | "TRUE" => Some(if cc == 0x25 {
820                    ValueKind::Bool(true)
821                } else {
822                    ValueKind::Level(0xff)
823                }),
824                "OFF" | "FALSE" => Some(if cc == 0x25 {
825                    ValueKind::Bool(false)
826                } else {
827                    ValueKind::Level(0)
828                }),
829                _ => None,
830            },
831        };
832        let Some(value) = raw else {
833            warn!(topic = path, "unreadable set payload");
834            return;
835        };
836        let id = ValueId {
837            node,
838            endpoint,
839            cc,
840            property: property.to_string(),
841        };
842        let c = self.c.clone();
843        tokio::spawn(async move {
844            if let Err(e) = c.set_value(&id, &value).await {
845                warn!("set {}: {e}", id.key());
846            }
847        });
848    }
849}
850
851fn hex(b: &[u8]) -> String {
852    b.iter().map(|x| format!("{x:02x}")).collect()
853}
854
855fn provisioning_json(entries: &[Entry]) -> Json {
856    Json::Array(
857        entries
858            .iter()
859            .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()}))
860            .collect(),
861    )
862}
863
864/// A device file's endpoint names, `{"1": "Relay 1", "2": "Relay 2"}`: what a
865/// multi-channel device calls each channel. Endpoints without a label are left
866/// out, so a device file that names none gives `{}`.
867fn endpoint_labels(endpoints: Option<&Json>) -> serde_json::Map<String, Json> {
868    endpoints
869        .and_then(Json::as_object)
870        .map(|eps| {
871            eps.iter()
872                .filter_map(|(ep, e)| Some((ep.clone(), json!(e.get("label")?.as_str()?))))
873                .collect()
874        })
875        .unwrap_or_default()
876}
877
878#[cfg(test)]
879mod endpoint_label_tests {
880    use super::*;
881
882    #[test]
883    fn names_the_labelled_endpoints() {
884        let file = json!({"0": {"associations": {}}, "1": {"label": "Relay 1"}, "2": {"label": "Relay 2"}});
885        assert_eq!(
886            Json::Object(endpoint_labels(Some(&file))),
887            json!({"1": "Relay 1", "2": "Relay 2"})
888        );
889        assert!(endpoint_labels(None).is_empty());
890    }
891}