Skip to main content

zigbee_bridge/
bridge.rs

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