zigbee-bridge 0.3.0

A standalone Zigbee to MQTT bridge with Home Assistant discovery, on the zigbee-host stack
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! The bridge: host events to MQTT, MQTT requests to the host.
//!
//! Topics, under the base topic (default `zigbee`):
//!
//! | Topic | Retained | What |
//! |---|---|---|
//! | `bridge/state` | yes | `{"state":"online"}` / `"offline"` (last will) |
//! | `bridge/info` | yes | version, coordinator, network, join state |
//! | `bridge/devices` | yes | every device and its interview |
//! | `bridge/event` | no | joins, announces, leaves, removals, interviews |
//! | `bridge/request/<name>` | no | requests: `permit_join`, `remove`, `rename`, `install_code`, `interview`, `backup`, `topology`, `scan_neighbors`, `energy_scan`, `change_channel`, `ota_check`, `ota_update` |
//! | `bridge/response/<name>` | no | `{"status":"ok","data":...}` or `{"status":"error","error":...}`, echoing `transaction` |
//! | `<device>` | configurable | the device's state: standard readings and `linkquality` |
//! | `<device>/set` | no | `{"state":"ON"}`, `{"brightness":128}`, `{"color_temp":300}` |
//! | `<device>/report` | no | every attribute report, raw, by cluster and attribute name |
//! | `<device>/action` | no | cluster commands the device sends (buttons, alarms) |
//!
//! `<device>` is the name a person gave it, or its IEEE address as
//! `0x00124b0001020304`. Keys never appear on MQTT.

use std::collections::HashMap;
use std::time::Duration;

use serde_json::{json, Map, Value as Json};
use tokio::sync::mpsc;
use zigbee_host::{AnyAdapter, Device, Host, HostEvent, InterviewStage};
use zigbee_primitives::Ieee;
use zigbee_zcl::{cluster_id, Value};

use crate::config::Config;
use crate::exposes::{self, DiscoveryContext};
use crate::mqtt::{self, Incoming, Mqtt};

/// The bridge's version.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Bridge state between events.
pub struct Bridge {
    host: Host<AnyAdapter>,
    mqtt: Mqtt,
    config: Config,
    states: HashMap<Ieee, Map<String, Json>>,
    discovery: HashMap<Ieee, Vec<String>>,
    permit_join: u8,
}

fn ok(data: Json) -> Json {
    json!({"status": "ok", "data": data})
}

fn error(message: impl std::fmt::Display) -> Json {
    json!({"status": "error", "error": message.to_string()})
}

fn interview_name(stage: InterviewStage) -> &'static str {
    match stage {
        InterviewStage::NodeDescriptor => "node_descriptor",
        InterviewStage::ActiveEndpoints => "active_endpoints",
        InterviewStage::SimpleDescriptors => "simple_descriptors",
        InterviewStage::Basic => "basic",
        InterviewStage::Configure => "configure",
        InterviewStage::Done => "done",
    }
}

impl Bridge {
    /// A bridge over a running host and an MQTT session.
    pub fn new(host: Host<AnyAdapter>, mqtt: Mqtt, config: Config) -> Bridge {
        Bridge {
            host,
            mqtt,
            config,
            states: HashMap::new(),
            discovery: HashMap::new(),
            permit_join: 0,
        }
    }

    fn base(&self) -> &str {
        &self.config.mqtt.base_topic
    }

    fn friendly(device: &Device) -> String {
        device
            .name
            .clone()
            .unwrap_or_else(|| device.ieee.to_prefixed_hex())
    }

    fn name_of(&self, ieee: Ieee) -> String {
        self.host
            .device(ieee)
            .map(|d| Self::friendly(&d))
            .unwrap_or_else(|| ieee.to_prefixed_hex())
    }

    fn resolve(&self, name: &str) -> Option<Device> {
        if let Ok(ieee) = name.parse::<Ieee>() {
            if let Some(d) = self.host.device(ieee) {
                return Some(d);
            }
        }
        self.host
            .devices()
            .into_iter()
            .find(|d| d.name.as_deref() == Some(name))
    }

    fn device_summary(device: &Device) -> Json {
        json!({
            "ieee_address": device.ieee.to_prefixed_hex(),
            "network_address": device.nwk,
            "friendly_name": Self::friendly(device),
            "manufacturer": device.manufacturer,
            "model": device.model,
            "power_source": device.power_source,
            "software_build_id": device.sw_build_id,
            "date_code": device.date_code,
            "type": device.node_descriptor.map(|d| match d.logical_type() {
                zigbee_zdo::LogicalType::Coordinator => "coordinator",
                zigbee_zdo::LogicalType::Router => "router",
                zigbee_zdo::LogicalType::EndDevice => "end_device",
                zigbee_zdo::LogicalType::Reserved(_) => "unknown",
            }),
            "interview": {"stage": interview_name(device.interview.stage), "done": device.interview.is_done(), "error": device.interview.error},
            "unique_link_key": device.unique_link_key,
            "endpoints": device.endpoints.iter().map(|e| json!({
                "endpoint": e.endpoint,
                "profile_id": e.profile_id,
                "device_id": e.device_id,
                "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<_>>(),
                "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<_>>(),
            })).collect::<Vec<_>>(),
        })
    }

    async fn publish_info(&self) {
        let n = self.host.network();
        let a = self.host.adapter_info();
        let info = json!({
            "version": VERSION,
            "coordinator": {"ieee_address": n.ieee.to_prefixed_hex(), "type": a.kind, "firmware": a.firmware, "protocol": a.protocol},
            "network": {"channel": n.channel, "pan_id": n.pan_id, "extended_pan_id": n.extended_pan_id.to_string(), "update_id": n.nwk_update_id},
            "permit_join": self.permit_join > 0,
            "permit_join_timeout": self.permit_join,
        });
        self.mqtt
            .publish_json(format!("{}/bridge/info", self.base()), &info, true)
            .await;
    }

    async fn publish_devices(&self) {
        let devices: Vec<Json> = self
            .host
            .devices()
            .iter()
            .map(Self::device_summary)
            .collect();
        self.mqtt
            .publish_json(
                format!("{}/bridge/devices", self.base()),
                &Json::Array(devices),
                true,
            )
            .await;
    }

    async fn event(&self, kind: &str, data: Json) {
        self.mqtt
            .publish_json(
                format!("{}/bridge/event", self.base()),
                &json!({"type": kind, "data": data}),
                false,
            )
            .await;
    }

    async fn publish_discovery(&mut self, device: &Device) {
        if !self.config.homeassistant.enabled || !device.interview.is_done() {
            return;
        }
        let ctx = DiscoveryContext {
            prefix: &self.config.homeassistant.discovery_prefix,
            base: &self.config.mqtt.base_topic,
            version: VERSION,
        };
        let messages = exposes::discovery(&ctx, device, &Self::friendly(device));
        let topics: Vec<String> = messages.iter().map(|(t, _)| t.clone()).collect();
        for (topic, payload) in messages {
            self.mqtt.publish_json(topic, &payload, true).await;
        }
        // Clear entities this device no longer has.
        if let Some(old) = self.discovery.insert(device.ieee, topics.clone()) {
            for topic in old.into_iter().filter(|t| !topics.contains(t)) {
                self.mqtt.publish(topic, Vec::new(), true).await;
            }
        }
    }

    async fn clear_device(&mut self, ieee: Ieee, friendly: &str) {
        for topic in self.discovery.remove(&ieee).unwrap_or_default() {
            self.mqtt.publish(topic, Vec::new(), true).await;
        }
        self.mqtt
            .publish(format!("{}/{friendly}", self.base()), Vec::new(), true)
            .await;
        self.states.remove(&ieee);
    }

    async fn publish_state(&self, device: &Device) {
        if let Some(state) = self.states.get(&device.ieee) {
            let topic = format!("{}/{}", self.base(), Self::friendly(device));
            self.mqtt
                .publish_json(
                    topic,
                    &Json::Object(state.clone()),
                    self.config.mqtt.retain_state,
                )
                .await;
        }
    }

    /// Everything a fresh MQTT session needs: subscriptions, availability,
    /// retained info, devices and discovery.
    pub async fn on_connected(&mut self) {
        let base = self.base().to_string();
        self.mqtt
            .subscribe(&format!("{base}/bridge/request/+"))
            .await;
        self.mqtt.subscribe(&format!("{base}/+/set")).await;
        if self.config.homeassistant.enabled {
            let status = self.config.homeassistant.status_topic.clone();
            self.mqtt.subscribe(&status).await;
        }
        self.mqtt
            .publish(mqtt::state_topic(&base), r#"{"state":"online"}"#, true)
            .await;
        self.publish_info().await;
        self.publish_devices().await;
        for device in self.host.devices() {
            self.publish_discovery(&device).await;
        }
    }

    /// Handle one host event.
    pub async fn on_host_event(&mut self, event: HostEvent) {
        match event {
            HostEvent::Started { .. } => {}
            HostEvent::PermitJoin { seconds, via } => {
                self.permit_join = seconds;
                self.publish_info().await;
                self.event(
                    "permit_join",
                    json!({"time": seconds, "device": via.map(|i| i.to_prefixed_hex())}),
                )
                .await;
            }
            HostEvent::DeviceJoined { ieee, nwk, rejoin } => {
                self.event("device_joined", json!({"ieee_address": ieee.to_prefixed_hex(), "network_address": nwk, "rejoin": rejoin})).await;
            }
            HostEvent::DeviceAnnounced { ieee, nwk } => {
                self.event(
                    "device_announce",
                    json!({"ieee_address": ieee.to_prefixed_hex(), "network_address": nwk}),
                )
                .await;
            }
            HostEvent::OtaQuery {
                ieee,
                current_version,
                available,
            } => {
                if available.is_some() {
                    let name = self.name_of(ieee);
                    self.event("ota_available", json!({"device": name, "ieee_address": ieee.to_prefixed_hex(), "installed_version": current_version, "latest_version": available})).await;
                }
            }
            HostEvent::OtaProgress { ieee, percent } => {
                let name = self.name_of(ieee);
                self.event("ota_progress", json!({"device": name, "ieee_address": ieee.to_prefixed_hex(), "progress": percent})).await;
            }
            HostEvent::OtaFinished {
                ieee,
                from,
                to,
                success,
                status,
            } => {
                let name = self.name_of(ieee);
                self.event("ota_finished", json!({"device": name, "ieee_address": ieee.to_prefixed_hex(), "from_version": from, "to_version": to, "success": success, "status": status})).await;
            }
            HostEvent::ChannelChanged { network } => {
                // A re-formation after a coordinator reset uses the new
                // channel too.
                let dir = &self.config.data.dir;
                match crate::network::load_or_create(dir, network.channel, None) {
                    Ok((mut settings, _)) => {
                        settings.channel = network.channel;
                        if let Err(e) = crate::network::save(dir, &settings) {
                            tracing::warn!(error = %e, "saving the new channel");
                        }
                    }
                    Err(e) => tracing::warn!(error = %e, "reading the network file"),
                }
                self.publish_info().await;
                self.event(
                    "channel_changed",
                    json!({"channel": network.channel, "update_id": network.nwk_update_id}),
                )
                .await;
            }
            HostEvent::DeviceLeft { ieee } => {
                self.clear_device(ieee, &ieee.to_prefixed_hex()).await;
                self.event(
                    "device_leave",
                    json!({"ieee_address": ieee.to_prefixed_hex()}),
                )
                .await;
                self.publish_devices().await;
            }
            HostEvent::DeviceRemoved { ieee, reason } => {
                self.clear_device(ieee, &ieee.to_prefixed_hex()).await;
                self.event(
                    "device_removed",
                    json!({"ieee_address": ieee.to_prefixed_hex(), "reason": reason}),
                )
                .await;
                self.publish_devices().await;
            }
            HostEvent::InterviewStarted { ieee } => {
                self.event(
                    "device_interview",
                    json!({"ieee_address": ieee.to_prefixed_hex(), "status": "started"}),
                )
                .await;
            }
            HostEvent::InterviewStep { .. } => {}
            HostEvent::InterviewDone { device } => {
                self.event(
                    "device_interview",
                    json!({"ieee_address": device.ieee.to_prefixed_hex(), "status": "successful", "manufacturer": device.manufacturer, "model": device.model, "definition": Self::device_summary(&device)}),
                )
                .await;
                self.publish_devices().await;
                self.publish_discovery(&device).await;
            }
            HostEvent::InterviewFailed { ieee, stage, error } => {
                self.event("device_interview", json!({"ieee_address": ieee.to_prefixed_hex(), "status": "failed", "stage": interview_name(stage), "error": error})).await;
            }
            HostEvent::Attributes {
                ieee,
                endpoint,
                cluster,
                attributes,
                lqi,
            } => {
                self.on_attributes(ieee, endpoint, cluster, attributes, lqi)
                    .await
            }
            HostEvent::Command {
                ieee,
                endpoint,
                cluster,
                command,
                name,
                fields,
                ..
            } => {
                let Some(device) = self.host.device(ieee) else {
                    return;
                };
                if cluster == cluster_id::IAS_ZONE
                    && name == Some("zone_status_change_notification")
                {
                    if let Some(status) = fields
                        .iter()
                        .find(|(n, _)| *n == "zone_status")
                        .and_then(|(_, v)| v.as_u64())
                    {
                        self.apply_ias(&device, status as u16).await;
                    }
                }
                let fields: Map<String, Json> = fields
                    .into_iter()
                    .map(|(n, v)| {
                        (
                            n.to_string(),
                            serde_json::to_value(&v).unwrap_or(Json::Null),
                        )
                    })
                    .collect();
                let topic = format!("{}/{}/action", self.base(), Self::friendly(&device));
                let cluster_name = zigbee_zcl::cluster(cluster)
                    .map(|c| c.name.to_string())
                    .unwrap_or_else(|| format!("{cluster:#06x}"));
                let action = json!({"endpoint": endpoint, "cluster": cluster_name, "command": name.map(str::to_string).unwrap_or_else(|| format!("{command:#04x}")), "fields": fields});
                self.mqtt.publish_json(topic, &action, false).await;
            }
            // The bridge publishes decoded readings; raw frames are for
            // embedders with their own device library.
            HostEvent::Frame { .. } => {}
            HostEvent::BackupWritten { path } => {
                tracing::info!(path = %path.display(), "backup written")
            }
            HostEvent::AdapterFailed { reason } => tracing::error!(%reason, "coordinator failed"),
        }
    }

    async fn apply_ias(&mut self, device: &Device, status: u16) {
        let state = self.states.entry(device.ieee).or_default();
        for (field, value) in exposes::ias_fields(device.ias_zone_type, status) {
            state.insert(field.to_string(), value);
        }
        self.publish_state(device).await;
    }

    async fn on_attributes(
        &mut self,
        ieee: Ieee,
        endpoint: u8,
        cluster: u16,
        attributes: Vec<(u16, Value)>,
        lqi: u8,
    ) {
        let Some(device) = self.host.device(ieee) else {
            return;
        };
        let def = zigbee_zcl::cluster(cluster);
        let raw: Map<String, Json> = attributes
            .iter()
            .map(|(id, v)| {
                let name = def
                    .and_then(|c| c.attribute(*id))
                    .map(|a| a.name.to_string())
                    .unwrap_or_else(|| format!("{id:#06x}"));
                (name, serde_json::to_value(v).unwrap_or(Json::Null))
            })
            .collect();
        let report = json!({"endpoint": endpoint, "cluster": def.map(|c| c.name.to_string()).unwrap_or_else(|| format!("{cluster:#06x}")), "attributes": raw});
        self.mqtt
            .publish_json(
                format!("{}/{}/report", self.base(), Self::friendly(&device)),
                &report,
                false,
            )
            .await;

        let state = self.states.entry(ieee).or_default();
        for (id, value) in &attributes {
            if cluster == cluster_id::IAS_ZONE && *id == zigbee_zcl::attr::ias_zone::ZONE_STATUS {
                if let Some(status) = value.as_u64() {
                    for (field, v) in exposes::ias_fields(device.ias_zone_type, status as u16) {
                        state.insert(field.to_string(), v);
                    }
                }
                continue;
            }
            if cluster == cluster_id::LEVEL_CONTROL
                && *id == zigbee_zcl::attr::level_control::CURRENT_LEVEL
            {
                if let Some(level) = value.as_u64() {
                    state.insert("brightness".into(), json!(level));
                }
                continue;
            }
            if let Some(e) = exposes::find(cluster, *id) {
                if let Some(v) = exposes::convert(e, value) {
                    state.insert(exposes::field_name(&device, endpoint, e), v);
                }
            }
        }
        state.insert("linkquality".into(), json!(lqi));
        self.publish_state(&device).await;
    }

    /// Handle one MQTT message.
    pub async fn on_message(&mut self, topic: &str, payload: &[u8]) {
        let base = self.base().to_string();
        if self.config.homeassistant.enabled && topic == self.config.homeassistant.status_topic {
            if payload == b"online" {
                for device in self.host.devices() {
                    self.publish_discovery(&device).await;
                }
            }
            return;
        }
        let Some(rest) = topic.strip_prefix(&format!("{base}/")) else {
            return;
        };
        let body: Json = if payload.is_empty() {
            json!({})
        } else {
            serde_json::from_slice(payload).unwrap_or(Json::Null)
        };
        if let Some(name) = rest.strip_prefix("bridge/request/") {
            let transaction = body.get("transaction").cloned();
            let mut response = self.request(name, &body).await;
            if response.is_null() {
                // Answered by a task of its own (a long OTA request).
                return;
            }
            if let (Some(t), Some(o)) = (transaction, response.as_object_mut()) {
                o.insert("transaction".into(), t);
            }
            self.mqtt
                .publish_json(format!("{base}/bridge/response/{name}"), &response, false)
                .await;
        } else if let Some(device) = rest.strip_suffix("/set") {
            if let Err(e) = self.set(device, &body).await {
                tracing::warn!(device, error = %e, "set");
            }
        }
    }

    async fn request(&mut self, name: &str, body: &Json) -> Json {
        let device = |key: &str| body.get(key).and_then(Json::as_str).map(str::to_string);
        match name {
            "permit_join" => {
                let time = body
                    .get("time")
                    .and_then(Json::as_u64)
                    .or_else(|| {
                        body.get("value")
                            .and_then(Json::as_bool)
                            .map(|b| if b { 254 } else { 0 })
                    })
                    .unwrap_or(0);
                let via = match device("device") {
                    Some(name) => match self.resolve(&name) {
                        Some(d) => Some(d.ieee),
                        None => return error(format!("unknown device {name}")),
                    },
                    None => None,
                };
                match self.host.permit_join(time.min(254) as u8, via).await {
                    Ok(()) => ok(json!({"time": time.min(254)})),
                    Err(e) => error(e),
                }
            }
            "remove" => {
                let Some(d) = device("device")
                    .or(device("id"))
                    .and_then(|n| self.resolve(&n))
                else {
                    return error("unknown device");
                };
                let force = body.get("force").and_then(Json::as_bool).unwrap_or(false);
                let friendly = Self::friendly(&d);
                match self.host.remove(d.ieee, force).await {
                    Ok(()) => {
                        self.clear_device(d.ieee, &friendly).await;
                        ok(json!({"device": friendly}))
                    }
                    Err(e) => error(e),
                }
            }
            "rename" => {
                let Some(d) = device("from")
                    .or(device("device"))
                    .and_then(|n| self.resolve(&n))
                else {
                    return error("unknown device");
                };
                let Some(to) = device("to").or(device("name")) else {
                    return error("missing \"to\"");
                };
                if to.is_empty()
                    || to.contains(['+', '#'])
                    || to.starts_with('/')
                    || to.ends_with('/')
                    || to.ends_with("/set")
                    || to == "bridge"
                {
                    return error("not a usable name");
                }
                let old = Self::friendly(&d);
                // Clear the old retained topics, keep the readings.
                let state = self.states.remove(&d.ieee);
                self.clear_device(d.ieee, &old).await;
                if let Err(e) = self.host.set_name(d.ieee, Some(to.clone())) {
                    return error(e);
                }
                if let Some(state) = state {
                    self.states.insert(d.ieee, state);
                }
                if let Some(d) = self.host.device(d.ieee) {
                    self.publish_discovery(&d).await;
                    self.publish_state(&d).await;
                }
                self.publish_devices().await;
                ok(json!({"from": old, "to": to}))
            }
            "install_code" => {
                let Some(ieee) = device("ieee_address")
                    .or(device("device"))
                    .and_then(|t| t.parse::<Ieee>().ok())
                else {
                    return error("missing ieee_address");
                };
                let Some(code) = device("code") else {
                    return error("missing code");
                };
                let bytes = match zigbee_host::install_code::parse_hex(&code) {
                    Ok(b) => b,
                    Err(e) => return error(e),
                };
                match self.host.add_install_code(ieee, &bytes).await {
                    Ok(()) => ok(json!({"ieee_address": ieee.to_prefixed_hex()})),
                    Err(e) => error(e),
                }
            }
            "interview" => {
                let Some(d) = device("device").and_then(|n| self.resolve(&n)) else {
                    return error("unknown device");
                };
                match self.host.reinterview(d.ieee) {
                    Ok(()) => ok(json!({"device": Self::friendly(&d)})),
                    Err(e) => error(e),
                }
            }
            "backup" => match self.host.backup().await {
                // The backup holds the network key: it goes to the data
                // directory, never onto MQTT.
                Ok(b) => ok(
                    json!({"path": self.config.data.dir.join(crate::BACKUP_FILE).display().to_string(), "devices": b.devices.len(), "frame_counter": b.network_key.frame_counter}),
                ),
                Err(e) => error(e),
            },
            "topology" => {
                let links: Vec<Json> = self
                    .host
                    .topology()
                    .into_iter()
                    .map(|(from, to, l)| {
                        json!({
                            "from": from.map(|i| i.to_prefixed_hex()), "to": to.map(|i| i.to_prefixed_hex()),
                            "from_network_address": l.from, "to_network_address": l.to,
                            "lqi": l.lqi, "rssi": l.rssi, "source": l.source, "seen": l.seen_unix,
                        })
                    })
                    .collect();
                ok(json!({"links": links}))
            }
            "scan_neighbors" => {
                let target = match device("device") {
                    Some(n) => match self.resolve(&n) {
                        Some(d) => d.ieee,
                        None => return error(format!("unknown device {n}")),
                    },
                    None => self.host.network().ieee,
                };
                match self.host.scan_neighbors(target).await {
                    Ok(neighbors) => ok(json!({"neighbors": neighbors})),
                    Err(e) => error(e),
                }
            }
            "ota_check" | "ota_update" => {
                let Some(d) = device("device").and_then(|n| self.resolve(&n)) else {
                    return error("unknown device");
                };
                // A sleepy device answers when it next wakes: answer from a
                // task so the bridge keeps working meanwhile.
                let host = self.host.clone();
                let mqtt = self.mqtt.clone();
                let topic = format!("{}/bridge/response/{name}", self.base());
                let transaction = body.get("transaction").cloned();
                let update = name == "ota_update";
                let friendly = Self::friendly(&d);
                tokio::spawn(async move {
                    let result = if update {
                        host.ota_update(d.ieee).await
                    } else {
                        host.ota_check(d.ieee).await
                    };
                    let mut response = match result {
                        Ok(o) => ok(json!({
                            "device": friendly,
                            "installed_version": o.current_version,
                            "latest_version": o.available,
                            "size": o.size,
                            "updating": update,
                        })),
                        Err(e) => error(e),
                    };
                    if let (Some(t), Some(o)) = (transaction, response.as_object_mut()) {
                        o.insert("transaction".into(), t);
                    }
                    mqtt.publish_json(topic, &response, false).await;
                });
                Json::Null
            }
            "change_channel" => {
                let Some(channel) = body.get("channel").and_then(Json::as_u64) else {
                    return error("change_channel needs {\"channel\": 11..26}");
                };
                match self.host.change_channel(channel.min(255) as u8).await {
                    Ok(n) => ok(json!({"channel": n.channel, "update_id": n.nwk_update_id})),
                    Err(e) => error(e),
                }
            }
            "energy_scan" => match self.host.energy_scan().await {
                Ok(results) => ok(
                    json!({"channels": results.iter().map(|(c, r)| json!({"channel": c, "max_rssi": r})).collect::<Vec<_>>()}),
                ),
                Err(e) => error(e),
            },
            "devices" => {
                self.publish_devices().await;
                ok(json!({}))
            }
            other => error(format!("unknown request {other}")),
        }
    }

    async fn set(&mut self, name: &str, body: &Json) -> Result<(), String> {
        let device = self
            .resolve(name)
            .ok_or_else(|| format!("unknown device {name}"))?;
        let ep = |cluster: u16| device.endpoint_with(cluster).map(|e| e.endpoint);
        let transition = body
            .get("transition")
            .and_then(Json::as_f64)
            .map(|s| (s * 10.0).round().clamp(0.0, 65534.0) as u16)
            .unwrap_or(0);
        if let Some(level) = body.get("brightness").and_then(Json::as_u64) {
            let endpoint = ep(cluster_id::LEVEL_CONTROL).ok_or("no level control")?;
            let level = level.min(254) as u8;
            self.host
                .command(
                    device.ieee,
                    endpoint,
                    cluster_id::LEVEL_CONTROL,
                    "move_to_level_with_on_off",
                    &[Value::u8(level), Value::u16(transition)],
                )
                .await
                .map_err(|e| e.to_string())?;
            self.states
                .entry(device.ieee)
                .or_default()
                .insert("brightness".into(), json!(level));
        }
        if let Some(mireds) = body.get("color_temp").and_then(Json::as_u64) {
            let endpoint = ep(cluster_id::COLOR_CONTROL).ok_or("no color control")?;
            self.host
                .command(
                    device.ieee,
                    endpoint,
                    cluster_id::COLOR_CONTROL,
                    "move_to_color_temperature",
                    &[
                        Value::u16(mireds.min(0xFEFF) as u16),
                        Value::u16(transition),
                    ],
                )
                .await
                .map_err(|e| e.to_string())?;
        }
        if let Some(state) = body.get("state").and_then(Json::as_str) {
            let command = match state.to_ascii_uppercase().as_str() {
                "ON" => "on",
                "OFF" => "off",
                "TOGGLE" => "toggle",
                other => return Err(format!("state {other} is not ON, OFF or TOGGLE")),
            };
            if !(command == "on" && body.get("brightness").is_some()) {
                let endpoint = ep(cluster_id::ON_OFF).ok_or("no on/off cluster")?;
                self.host
                    .command(device.ieee, endpoint, cluster_id::ON_OFF, command, &[])
                    .await
                    .map_err(|e| e.to_string())?;
            }
        }
        Ok(())
    }
}

/// Run the bridge until `stop` resolves or the coordinator fails.
pub async fn run_loop(
    mut bridge: Bridge,
    mut host_events: mpsc::UnboundedReceiver<HostEvent>,
    mut mqtt_in: mpsc::Receiver<Incoming>,
    stop: impl std::future::Future<Output = ()>,
) -> Result<(), String> {
    tokio::pin!(stop);
    let result = loop {
        tokio::select! {
            event = host_events.recv() => match event {
                Some(HostEvent::AdapterFailed { reason }) => break Err(format!("coordinator failed: {reason}")),
                Some(event) => bridge.on_host_event(event).await,
                None => break Err("host stopped".into()),
            },
            incoming = mqtt_in.recv() => match incoming {
                Some(Incoming::Connected) => bridge.on_connected().await,
                Some(Incoming::Message { topic, payload }) => bridge.on_message(&topic, &payload).await,
                None => break Err("MQTT session ended".into()),
            },
            _ = &mut stop => break Ok(()),
        }
    };
    let base = bridge.base().to_string();
    bridge
        .mqtt
        .publish(mqtt::state_topic(&base), r#"{"state":"offline"}"#, true)
        .await;
    tokio::time::sleep(Duration::from_millis(200)).await;
    bridge.mqtt.disconnect().await;
    if let Err(e) = bridge.host.shutdown().await {
        tracing::warn!(error = %e, "writing the device store");
    }
    result
}