Skip to main content

zigbee_bridge/
bridge.rs

1//! The bridge: host events to MQTT, MQTT requests to the host.
2//!
3//! Topics, under the base topic (default `zigbee`):
4//!
5//! | Topic | Retained | What |
6//! |---|---|---|
7//! | `bridge/state` | yes | `{"state":"online"}` / `"offline"` (last will) |
8//! | `bridge/info` | yes | version, coordinator, network, join state |
9//! | `bridge/devices` | yes | every device and its interview |
10//! | `bridge/event` | no | joins, announces, leaves, removals, interviews |
11//! | `bridge/request/<name>` | no | requests: `permit_join`, `remove`, `rename`, `install_code`, `interview`, `backup`, `topology`, `scan_neighbors`, `energy_scan`, `change_channel`, `ota_check`, `ota_update` |
12//! | `bridge/response/<name>` | no | `{"status":"ok","data":...}` or `{"status":"error","error":...}`, echoing `transaction` |
13//! | `<device>` | configurable | the device's state: standard readings and `linkquality` |
14//! | `<device>/set` | no | `{"state":"ON"}`, `{"brightness":128}`, `{"color_temp":300}` |
15//! | `<device>/report` | no | every attribute report, raw, by cluster and attribute name |
16//! | `<device>/action` | no | cluster commands the device sends (buttons, alarms) |
17//!
18//! `<device>` is the name a person gave it, or its IEEE address as
19//! `0x00124b0001020304`. Keys never appear on MQTT.
20
21use std::collections::HashMap;
22use std::time::Duration;
23
24use serde_json::{json, Map, Value as Json};
25use tokio::sync::mpsc;
26use zigbee_host::{AnyAdapter, Device, Host, HostEvent, InterviewStage};
27use zigbee_primitives::Ieee;
28use zigbee_zcl::{cluster_id, Value};
29
30use crate::config::Config;
31use crate::exposes::{self, DiscoveryContext};
32use crate::mqtt::{self, Incoming, Mqtt};
33
34/// The bridge's version.
35pub const VERSION: &str = env!("CARGO_PKG_VERSION");
36
37/// Bridge state between events.
38pub struct Bridge {
39    host: Host<AnyAdapter>,
40    mqtt: Mqtt,
41    config: Config,
42    states: HashMap<Ieee, Map<String, Json>>,
43    discovery: HashMap<Ieee, Vec<String>>,
44    permit_join: u8,
45}
46
47fn ok(data: Json) -> Json {
48    json!({"status": "ok", "data": data})
49}
50
51fn error(message: impl std::fmt::Display) -> Json {
52    json!({"status": "error", "error": message.to_string()})
53}
54
55fn interview_name(stage: InterviewStage) -> &'static str {
56    match stage {
57        InterviewStage::NodeDescriptor => "node_descriptor",
58        InterviewStage::ActiveEndpoints => "active_endpoints",
59        InterviewStage::SimpleDescriptors => "simple_descriptors",
60        InterviewStage::Basic => "basic",
61        InterviewStage::Configure => "configure",
62        InterviewStage::Done => "done",
63    }
64}
65
66impl Bridge {
67    /// A bridge over a running host and an MQTT session.
68    pub fn new(host: Host<AnyAdapter>, mqtt: Mqtt, config: Config) -> Bridge {
69        Bridge {
70            host,
71            mqtt,
72            config,
73            states: HashMap::new(),
74            discovery: HashMap::new(),
75            permit_join: 0,
76        }
77    }
78
79    fn base(&self) -> &str {
80        &self.config.mqtt.base_topic
81    }
82
83    fn friendly(device: &Device) -> String {
84        device
85            .name
86            .clone()
87            .unwrap_or_else(|| device.ieee.to_prefixed_hex())
88    }
89
90    fn name_of(&self, ieee: Ieee) -> String {
91        self.host
92            .device(ieee)
93            .map(|d| Self::friendly(&d))
94            .unwrap_or_else(|| ieee.to_prefixed_hex())
95    }
96
97    fn resolve(&self, name: &str) -> Option<Device> {
98        if let Ok(ieee) = name.parse::<Ieee>() {
99            if let Some(d) = self.host.device(ieee) {
100                return Some(d);
101            }
102        }
103        self.host
104            .devices()
105            .into_iter()
106            .find(|d| d.name.as_deref() == Some(name))
107    }
108
109    fn device_summary(device: &Device) -> Json {
110        json!({
111            "ieee_address": device.ieee.to_prefixed_hex(),
112            "network_address": device.nwk,
113            "friendly_name": Self::friendly(device),
114            "manufacturer": device.manufacturer,
115            "model": device.model,
116            "power_source": device.power_source,
117            "software_build_id": device.sw_build_id,
118            "date_code": device.date_code,
119            "type": device.node_descriptor.map(|d| match d.logical_type() {
120                zigbee_zdo::LogicalType::Coordinator => "coordinator",
121                zigbee_zdo::LogicalType::Router => "router",
122                zigbee_zdo::LogicalType::EndDevice => "end_device",
123                zigbee_zdo::LogicalType::Reserved(_) => "unknown",
124            }),
125            "interview": {"stage": interview_name(device.interview.stage), "done": device.interview.is_done(), "error": device.interview.error},
126            "unique_link_key": device.unique_link_key,
127            "endpoints": device.endpoints.iter().map(|e| json!({
128                "endpoint": e.endpoint,
129                "profile_id": e.profile_id,
130                "device_id": e.device_id,
131                "input_clusters": e.input_clusters.iter().map(|c| zigbee_zcl::cluster(*c).map(|d| d.name.to_string()).unwrap_or_else(|| format!("{c:#06x}"))).collect::<Vec<_>>(),
132                "output_clusters": e.output_clusters.iter().map(|c| zigbee_zcl::cluster(*c).map(|d| d.name.to_string()).unwrap_or_else(|| format!("{c:#06x}"))).collect::<Vec<_>>(),
133            })).collect::<Vec<_>>(),
134        })
135    }
136
137    async fn publish_info(&self) {
138        let n = self.host.network();
139        let a = self.host.adapter_info();
140        let info = json!({
141            "version": VERSION,
142            "coordinator": {"ieee_address": n.ieee.to_prefixed_hex(), "type": a.kind, "firmware": a.firmware, "protocol": a.protocol},
143            "network": {"channel": n.channel, "pan_id": n.pan_id, "extended_pan_id": n.extended_pan_id.to_string(), "update_id": n.nwk_update_id},
144            "permit_join": self.permit_join > 0,
145            "permit_join_timeout": self.permit_join,
146        });
147        self.mqtt
148            .publish_json(format!("{}/bridge/info", self.base()), &info, true)
149            .await;
150    }
151
152    async fn publish_devices(&self) {
153        let devices: Vec<Json> = self
154            .host
155            .devices()
156            .iter()
157            .map(Self::device_summary)
158            .collect();
159        self.mqtt
160            .publish_json(
161                format!("{}/bridge/devices", self.base()),
162                &Json::Array(devices),
163                true,
164            )
165            .await;
166    }
167
168    async fn event(&self, kind: &str, data: Json) {
169        self.mqtt
170            .publish_json(
171                format!("{}/bridge/event", self.base()),
172                &json!({"type": kind, "data": data}),
173                false,
174            )
175            .await;
176    }
177
178    async fn publish_discovery(&mut self, device: &Device) {
179        if !self.config.homeassistant.enabled || !device.interview.is_done() {
180            return;
181        }
182        let ctx = DiscoveryContext {
183            prefix: &self.config.homeassistant.discovery_prefix,
184            base: &self.config.mqtt.base_topic,
185            version: VERSION,
186        };
187        let messages = exposes::discovery(&ctx, device, &Self::friendly(device));
188        let topics: Vec<String> = messages.iter().map(|(t, _)| t.clone()).collect();
189        for (topic, payload) in messages {
190            self.mqtt.publish_json(topic, &payload, true).await;
191        }
192        // Clear entities this device no longer has.
193        if let Some(old) = self.discovery.insert(device.ieee, topics.clone()) {
194            for topic in old.into_iter().filter(|t| !topics.contains(t)) {
195                self.mqtt.publish(topic, Vec::new(), true).await;
196            }
197        }
198    }
199
200    async fn clear_device(&mut self, ieee: Ieee, friendly: &str) {
201        for topic in self.discovery.remove(&ieee).unwrap_or_default() {
202            self.mqtt.publish(topic, Vec::new(), true).await;
203        }
204        self.mqtt
205            .publish(format!("{}/{friendly}", self.base()), Vec::new(), true)
206            .await;
207        self.states.remove(&ieee);
208    }
209
210    async fn publish_state(&self, device: &Device) {
211        if let Some(state) = self.states.get(&device.ieee) {
212            let topic = format!("{}/{}", self.base(), Self::friendly(device));
213            self.mqtt
214                .publish_json(
215                    topic,
216                    &Json::Object(state.clone()),
217                    self.config.mqtt.retain_state,
218                )
219                .await;
220        }
221    }
222
223    /// Everything a fresh MQTT session needs: subscriptions, availability,
224    /// retained info, devices and discovery.
225    pub async fn on_connected(&mut self) {
226        let base = self.base().to_string();
227        self.mqtt
228            .subscribe(&format!("{base}/bridge/request/+"))
229            .await;
230        self.mqtt.subscribe(&format!("{base}/+/set")).await;
231        if self.config.homeassistant.enabled {
232            let status = self.config.homeassistant.status_topic.clone();
233            self.mqtt.subscribe(&status).await;
234        }
235        self.mqtt
236            .publish(mqtt::state_topic(&base), r#"{"state":"online"}"#, true)
237            .await;
238        self.publish_info().await;
239        self.publish_devices().await;
240        for device in self.host.devices() {
241            self.publish_discovery(&device).await;
242        }
243    }
244
245    /// Handle one host event.
246    pub async fn on_host_event(&mut self, event: HostEvent) {
247        match event {
248            HostEvent::Started { .. } => {}
249            HostEvent::PermitJoin { seconds, via } => {
250                self.permit_join = seconds;
251                self.publish_info().await;
252                self.event(
253                    "permit_join",
254                    json!({"time": seconds, "device": via.map(|i| i.to_prefixed_hex())}),
255                )
256                .await;
257            }
258            HostEvent::DeviceJoined { ieee, nwk, rejoin } => {
259                self.event("device_joined", json!({"ieee_address": ieee.to_prefixed_hex(), "network_address": nwk, "rejoin": rejoin})).await;
260            }
261            HostEvent::DeviceAnnounced { ieee, nwk } => {
262                self.event(
263                    "device_announce",
264                    json!({"ieee_address": ieee.to_prefixed_hex(), "network_address": nwk}),
265                )
266                .await;
267            }
268            HostEvent::OtaQuery {
269                ieee,
270                current_version,
271                available,
272            } => {
273                if available.is_some() {
274                    let name = self.name_of(ieee);
275                    self.event("ota_available", json!({"device": name, "ieee_address": ieee.to_prefixed_hex(), "installed_version": current_version, "latest_version": available})).await;
276                }
277            }
278            HostEvent::OtaProgress { ieee, percent } => {
279                let name = self.name_of(ieee);
280                self.event("ota_progress", json!({"device": name, "ieee_address": ieee.to_prefixed_hex(), "progress": percent})).await;
281            }
282            HostEvent::OtaFinished {
283                ieee,
284                from,
285                to,
286                success,
287                status,
288            } => {
289                let name = self.name_of(ieee);
290                self.event("ota_finished", json!({"device": name, "ieee_address": ieee.to_prefixed_hex(), "from_version": from, "to_version": to, "success": success, "status": status})).await;
291            }
292            HostEvent::ChannelChanged { network } => {
293                // A re-formation after a coordinator reset uses the new
294                // channel too.
295                let dir = &self.config.data.dir;
296                match crate::network::load_or_create(dir, network.channel, None) {
297                    Ok((mut settings, _)) => {
298                        settings.channel = network.channel;
299                        if let Err(e) = crate::network::save(dir, &settings) {
300                            tracing::warn!(error = %e, "saving the new channel");
301                        }
302                    }
303                    Err(e) => tracing::warn!(error = %e, "reading the network file"),
304                }
305                self.publish_info().await;
306                self.event(
307                    "channel_changed",
308                    json!({"channel": network.channel, "update_id": network.nwk_update_id}),
309                )
310                .await;
311            }
312            HostEvent::DeviceLeft { ieee } => {
313                self.clear_device(ieee, &ieee.to_prefixed_hex()).await;
314                self.event(
315                    "device_leave",
316                    json!({"ieee_address": ieee.to_prefixed_hex()}),
317                )
318                .await;
319                self.publish_devices().await;
320            }
321            HostEvent::DeviceRemoved { ieee, reason } => {
322                self.clear_device(ieee, &ieee.to_prefixed_hex()).await;
323                self.event(
324                    "device_removed",
325                    json!({"ieee_address": ieee.to_prefixed_hex(), "reason": reason}),
326                )
327                .await;
328                self.publish_devices().await;
329            }
330            HostEvent::InterviewStarted { ieee } => {
331                self.event(
332                    "device_interview",
333                    json!({"ieee_address": ieee.to_prefixed_hex(), "status": "started"}),
334                )
335                .await;
336            }
337            HostEvent::InterviewStep { .. } => {}
338            HostEvent::InterviewDone { device } => {
339                self.event(
340                    "device_interview",
341                    json!({"ieee_address": device.ieee.to_prefixed_hex(), "status": "successful", "manufacturer": device.manufacturer, "model": device.model, "definition": Self::device_summary(&device)}),
342                )
343                .await;
344                self.publish_devices().await;
345                self.publish_discovery(&device).await;
346            }
347            HostEvent::InterviewFailed { ieee, stage, error } => {
348                self.event("device_interview", json!({"ieee_address": ieee.to_prefixed_hex(), "status": "failed", "stage": interview_name(stage), "error": error})).await;
349            }
350            HostEvent::Attributes {
351                ieee,
352                endpoint,
353                cluster,
354                attributes,
355                lqi,
356            } => {
357                self.on_attributes(ieee, endpoint, cluster, attributes, lqi)
358                    .await
359            }
360            HostEvent::Command {
361                ieee,
362                endpoint,
363                cluster,
364                command,
365                name,
366                fields,
367                ..
368            } => {
369                let Some(device) = self.host.device(ieee) else {
370                    return;
371                };
372                if cluster == cluster_id::IAS_ZONE
373                    && name == Some("zone_status_change_notification")
374                {
375                    if let Some(status) = fields
376                        .iter()
377                        .find(|(n, _)| *n == "zone_status")
378                        .and_then(|(_, v)| v.as_u64())
379                    {
380                        self.apply_ias(&device, status as u16).await;
381                    }
382                }
383                let fields: Map<String, Json> = fields
384                    .into_iter()
385                    .map(|(n, v)| {
386                        (
387                            n.to_string(),
388                            serde_json::to_value(&v).unwrap_or(Json::Null),
389                        )
390                    })
391                    .collect();
392                let topic = format!("{}/{}/action", self.base(), Self::friendly(&device));
393                let cluster_name = zigbee_zcl::cluster(cluster)
394                    .map(|c| c.name.to_string())
395                    .unwrap_or_else(|| format!("{cluster:#06x}"));
396                let action = json!({"endpoint": endpoint, "cluster": cluster_name, "command": name.map(str::to_string).unwrap_or_else(|| format!("{command:#04x}")), "fields": fields});
397                self.mqtt.publish_json(topic, &action, false).await;
398            }
399            // The bridge publishes decoded readings; raw frames are for
400            // embedders with their own device library.
401            HostEvent::Frame { .. } => {}
402            HostEvent::BackupWritten { path } => {
403                tracing::info!(path = %path.display(), "backup written")
404            }
405            HostEvent::AdapterFailed { reason } => tracing::error!(%reason, "coordinator failed"),
406        }
407    }
408
409    async fn apply_ias(&mut self, device: &Device, status: u16) {
410        let state = self.states.entry(device.ieee).or_default();
411        for (field, value) in exposes::ias_fields(device.ias_zone_type, status) {
412            state.insert(field.to_string(), value);
413        }
414        self.publish_state(device).await;
415    }
416
417    async fn on_attributes(
418        &mut self,
419        ieee: Ieee,
420        endpoint: u8,
421        cluster: u16,
422        attributes: Vec<(u16, Value)>,
423        lqi: u8,
424    ) {
425        let Some(device) = self.host.device(ieee) else {
426            return;
427        };
428        let def = zigbee_zcl::cluster(cluster);
429        let raw: Map<String, Json> = attributes
430            .iter()
431            .map(|(id, v)| {
432                let name = def
433                    .and_then(|c| c.attribute(*id))
434                    .map(|a| a.name.to_string())
435                    .unwrap_or_else(|| format!("{id:#06x}"));
436                (name, serde_json::to_value(v).unwrap_or(Json::Null))
437            })
438            .collect();
439        let report = json!({"endpoint": endpoint, "cluster": def.map(|c| c.name.to_string()).unwrap_or_else(|| format!("{cluster:#06x}")), "attributes": raw});
440        self.mqtt
441            .publish_json(
442                format!("{}/{}/report", self.base(), Self::friendly(&device)),
443                &report,
444                false,
445            )
446            .await;
447
448        let state = self.states.entry(ieee).or_default();
449        for (id, value) in &attributes {
450            if cluster == cluster_id::IAS_ZONE && *id == zigbee_zcl::attr::ias_zone::ZONE_STATUS {
451                if let Some(status) = value.as_u64() {
452                    for (field, v) in exposes::ias_fields(device.ias_zone_type, status as u16) {
453                        state.insert(field.to_string(), v);
454                    }
455                }
456                continue;
457            }
458            if cluster == cluster_id::LEVEL_CONTROL
459                && *id == zigbee_zcl::attr::level_control::CURRENT_LEVEL
460            {
461                if let Some(level) = value.as_u64() {
462                    state.insert("brightness".into(), json!(level));
463                }
464                continue;
465            }
466            if let Some(e) = exposes::find(cluster, *id) {
467                if let Some(v) = exposes::convert(e, value) {
468                    state.insert(exposes::field_name(&device, endpoint, e), v);
469                }
470            }
471        }
472        state.insert("linkquality".into(), json!(lqi));
473        self.publish_state(&device).await;
474    }
475
476    /// Handle one MQTT message.
477    pub async fn on_message(&mut self, topic: &str, payload: &[u8]) {
478        let base = self.base().to_string();
479        if self.config.homeassistant.enabled && topic == self.config.homeassistant.status_topic {
480            if payload == b"online" {
481                for device in self.host.devices() {
482                    self.publish_discovery(&device).await;
483                }
484            }
485            return;
486        }
487        let Some(rest) = topic.strip_prefix(&format!("{base}/")) else {
488            return;
489        };
490        let body: Json = if payload.is_empty() {
491            json!({})
492        } else {
493            serde_json::from_slice(payload).unwrap_or(Json::Null)
494        };
495        if let Some(name) = rest.strip_prefix("bridge/request/") {
496            let transaction = body.get("transaction").cloned();
497            let mut response = self.request(name, &body).await;
498            if response.is_null() {
499                // Answered by a task of its own (a long OTA request).
500                return;
501            }
502            if let (Some(t), Some(o)) = (transaction, response.as_object_mut()) {
503                o.insert("transaction".into(), t);
504            }
505            self.mqtt
506                .publish_json(format!("{base}/bridge/response/{name}"), &response, false)
507                .await;
508        } else if let Some(device) = rest.strip_suffix("/set") {
509            if let Err(e) = self.set(device, &body).await {
510                tracing::warn!(device, error = %e, "set");
511            }
512        }
513    }
514
515    async fn request(&mut self, name: &str, body: &Json) -> Json {
516        let device = |key: &str| body.get(key).and_then(Json::as_str).map(str::to_string);
517        match name {
518            "permit_join" => {
519                let time = body
520                    .get("time")
521                    .and_then(Json::as_u64)
522                    .or_else(|| {
523                        body.get("value")
524                            .and_then(Json::as_bool)
525                            .map(|b| if b { 254 } else { 0 })
526                    })
527                    .unwrap_or(0);
528                let via = match device("device") {
529                    Some(name) => match self.resolve(&name) {
530                        Some(d) => Some(d.ieee),
531                        None => return error(format!("unknown device {name}")),
532                    },
533                    None => None,
534                };
535                match self.host.permit_join(time.min(254) as u8, via).await {
536                    Ok(()) => ok(json!({"time": time.min(254)})),
537                    Err(e) => error(e),
538                }
539            }
540            "remove" => {
541                let Some(d) = device("device")
542                    .or(device("id"))
543                    .and_then(|n| self.resolve(&n))
544                else {
545                    return error("unknown device");
546                };
547                let force = body.get("force").and_then(Json::as_bool).unwrap_or(false);
548                let friendly = Self::friendly(&d);
549                match self.host.remove(d.ieee, force).await {
550                    Ok(()) => {
551                        self.clear_device(d.ieee, &friendly).await;
552                        ok(json!({"device": friendly}))
553                    }
554                    Err(e) => error(e),
555                }
556            }
557            "rename" => {
558                let Some(d) = device("from")
559                    .or(device("device"))
560                    .and_then(|n| self.resolve(&n))
561                else {
562                    return error("unknown device");
563                };
564                let Some(to) = device("to").or(device("name")) else {
565                    return error("missing \"to\"");
566                };
567                if to.is_empty()
568                    || to.contains(['+', '#'])
569                    || to.starts_with('/')
570                    || to.ends_with('/')
571                    || to.ends_with("/set")
572                    || to == "bridge"
573                {
574                    return error("not a usable name");
575                }
576                let old = Self::friendly(&d);
577                // Clear the old retained topics, keep the readings.
578                let state = self.states.remove(&d.ieee);
579                self.clear_device(d.ieee, &old).await;
580                if let Err(e) = self.host.set_name(d.ieee, Some(to.clone())) {
581                    return error(e);
582                }
583                if let Some(state) = state {
584                    self.states.insert(d.ieee, state);
585                }
586                if let Some(d) = self.host.device(d.ieee) {
587                    self.publish_discovery(&d).await;
588                    self.publish_state(&d).await;
589                }
590                self.publish_devices().await;
591                ok(json!({"from": old, "to": to}))
592            }
593            "install_code" => {
594                let Some(ieee) = device("ieee_address")
595                    .or(device("device"))
596                    .and_then(|t| t.parse::<Ieee>().ok())
597                else {
598                    return error("missing ieee_address");
599                };
600                let Some(code) = device("code") else {
601                    return error("missing code");
602                };
603                let bytes = match zigbee_host::install_code::parse_hex(&code) {
604                    Ok(b) => b,
605                    Err(e) => return error(e),
606                };
607                match self.host.add_install_code(ieee, &bytes).await {
608                    Ok(()) => ok(json!({"ieee_address": ieee.to_prefixed_hex()})),
609                    Err(e) => error(e),
610                }
611            }
612            "interview" => {
613                let Some(d) = device("device").and_then(|n| self.resolve(&n)) else {
614                    return error("unknown device");
615                };
616                match self.host.reinterview(d.ieee) {
617                    Ok(()) => ok(json!({"device": Self::friendly(&d)})),
618                    Err(e) => error(e),
619                }
620            }
621            "backup" => match self.host.backup().await {
622                // The backup holds the network key: it goes to the data
623                // directory, never onto MQTT.
624                Ok(b) => ok(
625                    json!({"path": self.config.data.dir.join(crate::BACKUP_FILE).display().to_string(), "devices": b.devices.len(), "frame_counter": b.network_key.frame_counter}),
626                ),
627                Err(e) => error(e),
628            },
629            "topology" => {
630                let links: Vec<Json> = self
631                    .host
632                    .topology()
633                    .into_iter()
634                    .map(|(from, to, l)| {
635                        json!({
636                            "from": from.map(|i| i.to_prefixed_hex()), "to": to.map(|i| i.to_prefixed_hex()),
637                            "from_network_address": l.from, "to_network_address": l.to,
638                            "lqi": l.lqi, "rssi": l.rssi, "source": l.source, "seen": l.seen_unix,
639                        })
640                    })
641                    .collect();
642                ok(json!({"links": links}))
643            }
644            "scan_neighbors" => {
645                let target = match device("device") {
646                    Some(n) => match self.resolve(&n) {
647                        Some(d) => d.ieee,
648                        None => return error(format!("unknown device {n}")),
649                    },
650                    None => self.host.network().ieee,
651                };
652                match self.host.scan_neighbors(target).await {
653                    Ok(neighbors) => ok(json!({"neighbors": neighbors})),
654                    Err(e) => error(e),
655                }
656            }
657            "ota_check" | "ota_update" => {
658                let Some(d) = device("device").and_then(|n| self.resolve(&n)) else {
659                    return error("unknown device");
660                };
661                // A sleepy device answers when it next wakes: answer from a
662                // task so the bridge keeps working meanwhile.
663                let host = self.host.clone();
664                let mqtt = self.mqtt.clone();
665                let topic = format!("{}/bridge/response/{name}", self.base());
666                let transaction = body.get("transaction").cloned();
667                let update = name == "ota_update";
668                let friendly = Self::friendly(&d);
669                tokio::spawn(async move {
670                    let result = if update {
671                        host.ota_update(d.ieee).await
672                    } else {
673                        host.ota_check(d.ieee).await
674                    };
675                    let mut response = match result {
676                        Ok(o) => ok(json!({
677                            "device": friendly,
678                            "installed_version": o.current_version,
679                            "latest_version": o.available,
680                            "size": o.size,
681                            "updating": update,
682                        })),
683                        Err(e) => error(e),
684                    };
685                    if let (Some(t), Some(o)) = (transaction, response.as_object_mut()) {
686                        o.insert("transaction".into(), t);
687                    }
688                    mqtt.publish_json(topic, &response, false).await;
689                });
690                Json::Null
691            }
692            "change_channel" => {
693                let Some(channel) = body.get("channel").and_then(Json::as_u64) else {
694                    return error("change_channel needs {\"channel\": 11..26}");
695                };
696                match self.host.change_channel(channel.min(255) as u8).await {
697                    Ok(n) => ok(json!({"channel": n.channel, "update_id": n.nwk_update_id})),
698                    Err(e) => error(e),
699                }
700            }
701            "energy_scan" => match self.host.energy_scan().await {
702                Ok(results) => ok(
703                    json!({"channels": results.iter().map(|(c, r)| json!({"channel": c, "max_rssi": r})).collect::<Vec<_>>()}),
704                ),
705                Err(e) => error(e),
706            },
707            "devices" => {
708                self.publish_devices().await;
709                ok(json!({}))
710            }
711            other => error(format!("unknown request {other}")),
712        }
713    }
714
715    async fn set(&mut self, name: &str, body: &Json) -> Result<(), String> {
716        let device = self
717            .resolve(name)
718            .ok_or_else(|| format!("unknown device {name}"))?;
719        let ep = |cluster: u16| device.endpoint_with(cluster).map(|e| e.endpoint);
720        let transition = body
721            .get("transition")
722            .and_then(Json::as_f64)
723            .map(|s| (s * 10.0).round().clamp(0.0, 65534.0) as u16)
724            .unwrap_or(0);
725        if let Some(level) = body.get("brightness").and_then(Json::as_u64) {
726            let endpoint = ep(cluster_id::LEVEL_CONTROL).ok_or("no level control")?;
727            let level = level.min(254) as u8;
728            self.host
729                .command(
730                    device.ieee,
731                    endpoint,
732                    cluster_id::LEVEL_CONTROL,
733                    "move_to_level_with_on_off",
734                    &[Value::u8(level), Value::u16(transition)],
735                )
736                .await
737                .map_err(|e| e.to_string())?;
738            self.states
739                .entry(device.ieee)
740                .or_default()
741                .insert("brightness".into(), json!(level));
742        }
743        if let Some(mireds) = body.get("color_temp").and_then(Json::as_u64) {
744            let endpoint = ep(cluster_id::COLOR_CONTROL).ok_or("no color control")?;
745            self.host
746                .command(
747                    device.ieee,
748                    endpoint,
749                    cluster_id::COLOR_CONTROL,
750                    "move_to_color_temperature",
751                    &[
752                        Value::u16(mireds.min(0xFEFF) as u16),
753                        Value::u16(transition),
754                    ],
755                )
756                .await
757                .map_err(|e| e.to_string())?;
758        }
759        if let Some(state) = body.get("state").and_then(Json::as_str) {
760            let command = match state.to_ascii_uppercase().as_str() {
761                "ON" => "on",
762                "OFF" => "off",
763                "TOGGLE" => "toggle",
764                other => return Err(format!("state {other} is not ON, OFF or TOGGLE")),
765            };
766            if !(command == "on" && body.get("brightness").is_some()) {
767                let endpoint = ep(cluster_id::ON_OFF).ok_or("no on/off cluster")?;
768                self.host
769                    .command(device.ieee, endpoint, cluster_id::ON_OFF, command, &[])
770                    .await
771                    .map_err(|e| e.to_string())?;
772            }
773        }
774        Ok(())
775    }
776}
777
778/// Run the bridge until `stop` resolves or the coordinator fails.
779pub async fn run_loop(
780    mut bridge: Bridge,
781    mut host_events: mpsc::UnboundedReceiver<HostEvent>,
782    mut mqtt_in: mpsc::Receiver<Incoming>,
783    stop: impl std::future::Future<Output = ()>,
784) -> Result<(), String> {
785    tokio::pin!(stop);
786    let result = loop {
787        tokio::select! {
788            event = host_events.recv() => match event {
789                Some(HostEvent::AdapterFailed { reason }) => break Err(format!("coordinator failed: {reason}")),
790                Some(event) => bridge.on_host_event(event).await,
791                None => break Err("host stopped".into()),
792            },
793            incoming = mqtt_in.recv() => match incoming {
794                Some(Incoming::Connected) => bridge.on_connected().await,
795                Some(Incoming::Message { topic, payload }) => bridge.on_message(&topic, &payload).await,
796                None => break Err("MQTT session ended".into()),
797            },
798            _ = &mut stop => break Ok(()),
799        }
800    };
801    let base = bridge.base().to_string();
802    bridge
803        .mqtt
804        .publish(mqtt::state_topic(&base), r#"{"state":"offline"}"#, true)
805        .await;
806    tokio::time::sleep(Duration::from_millis(200)).await;
807    bridge.mqtt.disconnect().await;
808    if let Err(e) = bridge.host.shutdown().await {
809        tracing::warn!(error = %e, "writing the device store");
810    }
811    result
812}