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
//! What a device's standard clusters mean as JSON fields, and the Home
//! Assistant discovery that describes them.
//!
//! Everything here is from the ZCL specification, so it holds for every
//! device that implements the cluster: no per-device code. Device quirks
//! belong in device definitions, not here.

use serde_json::{json, Map, Value as Json};
use zigbee_host::Device;
use zigbee_primitives::Ieee;
use zigbee_zcl::{attr, cluster_id, Value};

/// How a raw attribute becomes a JSON value.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Convert {
    /// Multiply, rounding to `decimals`.
    Scale(f64, u32),
    /// Illuminance: lux = 10 ^ ((value - 1) / 10000).
    Lux,
    /// "ON" / "OFF".
    OnOff,
    /// One bit of a bitmap as a boolean.
    Bit(u8),
    /// The value as is.
    Raw,
}

/// The Home Assistant entity type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Component {
    /// A sensor.
    Sensor,
    /// A binary sensor.
    BinarySensor,
    /// A switch (on/off without level).
    Switch,
}

impl Component {
    fn name(self) -> &'static str {
        match self {
            Component::Sensor => "sensor",
            Component::BinarySensor => "binary_sensor",
            Component::Switch => "switch",
        }
    }
}

/// One attribute as a field.
#[derive(Debug)]
pub struct Expose {
    /// Cluster.
    pub cluster: u16,
    /// Attribute.
    pub attribute: u16,
    /// JSON field name.
    pub field: &'static str,
    /// Conversion.
    pub convert: Convert,
    /// Unit.
    pub unit: Option<&'static str>,
    /// Home Assistant device class.
    pub device_class: Option<&'static str>,
    /// Home Assistant state class.
    pub state_class: Option<&'static str>,
    /// Home Assistant entity type.
    pub component: Component,
    /// A diagnostic entity.
    pub diagnostic: bool,
}

macro_rules! expose {
    ($cluster:expr, $attr:expr, $field:literal, $convert:expr, $unit:expr, $class:expr, $state:expr, $component:expr, $diag:expr) => {
        Expose {
            cluster: $cluster,
            attribute: $attr,
            field: $field,
            convert: $convert,
            unit: $unit,
            device_class: $class,
            state_class: $state,
            component: $component,
            diagnostic: $diag,
        }
    };
}

const M: Option<&str> = Some("measurement");

/// Every standard attribute the bridge turns into a field.
pub static EXPOSES: &[Expose] = &[
    expose!(
        cluster_id::TEMPERATURE_MEASUREMENT,
        attr::temperature_measurement::MEASURED_VALUE,
        "temperature",
        Convert::Scale(0.01, 2),
        Some("°C"),
        Some("temperature"),
        M,
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::RELATIVE_HUMIDITY_MEASUREMENT,
        attr::relative_humidity_measurement::MEASURED_VALUE,
        "humidity",
        Convert::Scale(0.01, 2),
        Some("%"),
        Some("humidity"),
        M,
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::PRESSURE_MEASUREMENT,
        attr::pressure_measurement::MEASURED_VALUE,
        "pressure",
        Convert::Scale(1.0, 1),
        Some("hPa"),
        Some("pressure"),
        M,
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::ILLUMINANCE_MEASUREMENT,
        attr::illuminance_measurement::MEASURED_VALUE,
        "illuminance",
        Convert::Lux,
        Some("lx"),
        Some("illuminance"),
        M,
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::FLOW_MEASUREMENT,
        attr::flow_measurement::MEASURED_VALUE,
        "flow",
        Convert::Scale(0.1, 1),
        Some("m³/h"),
        None,
        M,
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::SOIL_MOISTURE_MEASUREMENT,
        attr::soil_moisture_measurement::MEASURED_VALUE,
        "soil_moisture",
        Convert::Scale(0.01, 2),
        Some("%"),
        Some("moisture"),
        M,
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::CARBON_DIOXIDE_MEASUREMENT,
        attr::carbon_dioxide_measurement::MEASURED_VALUE,
        "co2",
        Convert::Scale(1e6, 0),
        Some("ppm"),
        Some("carbon_dioxide"),
        M,
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::PM25_MEASUREMENT,
        attr::pm25_measurement::MEASURED_VALUE,
        "pm25",
        Convert::Scale(1.0, 1),
        Some("µg/m³"),
        Some("pm25"),
        M,
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::OCCUPANCY_SENSING,
        attr::occupancy_sensing::OCCUPANCY,
        "occupancy",
        Convert::Bit(0),
        None,
        Some("occupancy"),
        None,
        Component::BinarySensor,
        false
    ),
    expose!(
        cluster_id::ON_OFF,
        attr::on_off::ON_OFF,
        "state",
        Convert::OnOff,
        None,
        None,
        None,
        Component::Switch,
        false
    ),
    expose!(
        cluster_id::POWER_CONFIGURATION,
        attr::power_configuration::BATTERY_PERCENTAGE_REMAINING,
        "battery",
        Convert::Scale(0.5, 0),
        Some("%"),
        Some("battery"),
        M,
        Component::Sensor,
        true
    ),
    expose!(
        cluster_id::POWER_CONFIGURATION,
        attr::power_configuration::BATTERY_VOLTAGE,
        "battery_voltage",
        Convert::Scale(100.0, 0),
        Some("mV"),
        Some("voltage"),
        M,
        Component::Sensor,
        true
    ),
    expose!(
        cluster_id::ELECTRICAL_MEASUREMENT,
        attr::electrical_measurement::ACTIVE_POWER,
        "power",
        Convert::Scale(1.0, 1),
        Some("W"),
        Some("power"),
        M,
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::ELECTRICAL_MEASUREMENT,
        attr::electrical_measurement::RMS_VOLTAGE,
        "voltage",
        Convert::Scale(1.0, 1),
        Some("V"),
        Some("voltage"),
        M,
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::ELECTRICAL_MEASUREMENT,
        attr::electrical_measurement::RMS_CURRENT,
        "current",
        Convert::Scale(0.001, 3),
        Some("A"),
        Some("current"),
        M,
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::METERING,
        attr::metering::CURRENT_SUMMATION_DELIVERED,
        "energy",
        Convert::Scale(0.001, 3),
        Some("kWh"),
        Some("energy"),
        Some("total_increasing"),
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::THERMOSTAT,
        attr::thermostat::LOCAL_TEMPERATURE,
        "local_temperature",
        Convert::Scale(0.01, 2),
        Some("°C"),
        Some("temperature"),
        M,
        Component::Sensor,
        false
    ),
    expose!(
        cluster_id::DEVICE_TEMPERATURE_CONFIGURATION,
        attr::device_temperature_configuration::CURRENT_TEMPERATURE,
        "device_temperature",
        Convert::Raw,
        Some("°C"),
        Some("temperature"),
        M,
        Component::Sensor,
        true
    ),
];

/// The expose for an attribute.
pub fn find(cluster: u16, attribute: u16) -> Option<&'static Expose> {
    EXPOSES
        .iter()
        .find(|e| e.cluster == cluster && e.attribute == attribute)
}

fn round(v: f64, decimals: u32) -> f64 {
    let f = 10f64.powi(decimals as i32);
    (v * f).round() / f
}

/// Convert a value; `None` for invalid ("no reading") values.
pub fn convert(expose: &Expose, value: &Value) -> Option<Json> {
    match expose.convert {
        Convert::OnOff => value
            .as_bool()
            .map(|on| json!(if on { "ON" } else { "OFF" })),
        Convert::Bit(bit) => value.as_u64().map(|v| json!(v & (1 << bit) != 0)),
        Convert::Lux => value.as_f64().map(|v| {
            json!(round(
                if v <= 0.0 {
                    0.0
                } else {
                    10f64.powf((v - 1.0) / 10000.0)
                },
                0
            ))
        }),
        Convert::Scale(factor, decimals) => {
            value.as_f64().map(|v| json!(round(v * factor, decimals)))
        }
        Convert::Raw => serde_json::to_value(value).ok().filter(|j| !j.is_null()),
    }
}

/// The field name for an expose on an endpoint: plain on the first
/// endpoint that has the cluster, `<field>_<endpoint>` on later ones.
pub fn field_name(device: &Device, endpoint: u8, expose: &Expose) -> String {
    match device
        .endpoints
        .iter()
        .find(|e| e.input_clusters.contains(&expose.cluster))
    {
        Some(first) if first.endpoint != endpoint => format!("{}_{endpoint}", expose.field),
        _ => expose.field.to_string(),
    }
}

/// IAS zone fields for a zone status, by zone type.
pub fn ias_fields(zone_type: Option<u16>, status: u16) -> Vec<(&'static str, Json)> {
    let alarm = status & 0x0001 != 0;
    let main = match zone_type {
        Some(0x0015) => ("contact", json!(!alarm)),
        Some(0x000D) => ("occupancy", json!(alarm)),
        Some(0x002A) => ("water_leak", json!(alarm)),
        Some(0x0028) => ("smoke", json!(alarm)),
        Some(0x002B) => ("carbon_monoxide", json!(alarm)),
        Some(0x002D) => ("vibration", json!(alarm)),
        _ => ("alarm", json!(alarm)),
    };
    vec![
        main,
        ("tamper", json!(status & 0x0004 != 0)),
        ("battery_low", json!(status & 0x0008 != 0)),
    ]
}

fn ias_class(field: &str) -> Option<&'static str> {
    Some(match field {
        "contact" => "door",
        "occupancy" => "motion",
        "water_leak" => "moisture",
        "smoke" => "smoke",
        "carbon_monoxide" => "carbon_monoxide",
        "vibration" => "vibration",
        "tamper" => "tamper",
        "battery_low" => "battery",
        _ => "safety",
    })
}

/// Everything a discovery message needs to know about the bridge.
pub struct DiscoveryContext<'a> {
    /// Home Assistant's discovery prefix.
    pub prefix: &'a str,
    /// The bridge's base topic.
    pub base: &'a str,
    /// The bridge's version.
    pub version: &'a str,
}

fn title(field: &str) -> String {
    let mut out = String::new();
    for (i, word) in field.split('_').enumerate() {
        if i > 0 {
            out.push(' ');
        }
        let mut chars = word.chars();
        if let Some(c) = chars.next() {
            out.extend(c.to_uppercase());
            out.push_str(chars.as_str());
        }
    }
    out.replace("Co2", "CO2").replace("Pm25", "PM2.5")
}

fn id(ieee: Ieee) -> String {
    ieee.to_prefixed_hex()
}

/// Discovery messages (topic, payload) for a device's standard clusters.
pub fn discovery(
    ctx: &DiscoveryContext<'_>,
    device: &Device,
    friendly: &str,
) -> Vec<(String, Json)> {
    let ieee = id(device.ieee);
    let state_topic = format!("{}/{friendly}", ctx.base);
    let device_info = {
        let mut d = Map::new();
        d.insert(
            "identifiers".into(),
            json!([format!("zigbee-bridge_{ieee}")]),
        );
        d.insert("name".into(), json!(friendly));
        if let Some(m) = &device.manufacturer {
            d.insert("manufacturer".into(), json!(m));
        }
        if let Some(m) = &device.model {
            d.insert("model".into(), json!(m));
        }
        if let Some(v) = &device.sw_build_id {
            d.insert("sw_version".into(), json!(v));
        }
        Json::Object(d)
    };
    let base_payload = |field: &str, name: String| {
        json!({
            "name": name,
            "unique_id": format!("{ieee}_{field}_zigbee-bridge"),
            "object_id": format!("{}_{field}", friendly.replace(['/', ' '], "_")),
            "state_topic": state_topic,
            "value_template": format!("{{{{ value_json.{field} }}}}"),
            "availability": [{"topic": format!("{}/bridge/state", ctx.base), "value_template": "{{ value_json.state }}"}],
            "device": device_info,
            "origin": {"name": "zigbee-bridge", "sw_version": ctx.version},
        })
    };
    let config_topic = |component: &str, field: &str| {
        format!(
            "{}/{component}/{}/{field}/config",
            ctx.prefix,
            ieee.trim_start_matches("0x")
        )
    };
    let mut out = Vec::new();
    for ep in &device.endpoints {
        let has = |c: u16| ep.input_clusters.contains(&c);
        let light = has(cluster_id::ON_OFF) && has(cluster_id::LEVEL_CONTROL);
        if light {
            let field = match device
                .endpoints
                .iter()
                .find(|e| e.input_clusters.contains(&cluster_id::ON_OFF))
            {
                Some(first) if first.endpoint != ep.endpoint => format!("light_{}", ep.endpoint),
                _ => "light".to_string(),
            };
            let mut p = base_payload(&field, "Light".into());
            if let Some(o) = p.as_object_mut() {
                o.remove("value_template");
                o.insert("schema".into(), json!("json"));
                o.insert("command_topic".into(), json!(format!("{state_topic}/set")));
                o.insert("brightness".into(), json!(true));
                o.insert("brightness_scale".into(), json!(254));
                if has(cluster_id::COLOR_CONTROL) {
                    o.insert("supported_color_modes".into(), json!(["color_temp"]));
                }
            }
            out.push((config_topic("light", &field), p));
        }
        for e in EXPOSES.iter().filter(|e| has(e.cluster)) {
            if light && e.cluster == cluster_id::ON_OFF {
                continue;
            }
            // A battery cluster on a mains device has no battery.
            if e.cluster == cluster_id::POWER_CONFIGURATION
                && device
                    .power_source
                    .is_some_and(|p| p & 0x7F == 0x01 || p & 0x7F == 0x04)
            {
                continue;
            }
            let field = field_name(device, ep.endpoint, e);
            let mut p = base_payload(&field, title(&field));
            if let Some(o) = p.as_object_mut() {
                if let Some(u) = e.unit {
                    o.insert("unit_of_measurement".into(), json!(u));
                }
                if let Some(c) = e.device_class {
                    o.insert("device_class".into(), json!(c));
                }
                if let Some(s) = e.state_class {
                    o.insert("state_class".into(), json!(s));
                }
                if e.diagnostic {
                    o.insert("entity_category".into(), json!("diagnostic"));
                }
                match e.component {
                    Component::BinarySensor => {
                        o.insert("payload_on".into(), json!(true));
                        o.insert("payload_off".into(), json!(false));
                    }
                    Component::Switch => {
                        o.insert("command_topic".into(), json!(format!("{state_topic}/set")));
                        o.insert("payload_on".into(), json!(r#"{"state":"ON"}"#));
                        o.insert("payload_off".into(), json!(r#"{"state":"OFF"}"#));
                        o.insert("state_on".into(), json!("ON"));
                        o.insert("state_off".into(), json!("OFF"));
                    }
                    Component::Sensor => {}
                }
            }
            out.push((config_topic(e.component.name(), &field), p));
        }
        if has(cluster_id::IAS_ZONE) {
            for (field, _) in ias_fields(device.ias_zone_type, 0) {
                let mut p = base_payload(field, title(field));
                if let Some(o) = p.as_object_mut() {
                    o.insert("payload_on".into(), json!(field != "contact"));
                    o.insert("payload_off".into(), json!(field == "contact"));
                    if let Some(c) = ias_class(field) {
                        o.insert("device_class".into(), json!(c));
                    }
                    if field == "contact" {
                        // HA's door class is "on" when open.
                        o.insert("payload_on".into(), json!(false));
                        o.insert("payload_off".into(), json!(true));
                    }
                    if matches!(field, "tamper" | "battery_low") {
                        o.insert("entity_category".into(), json!("diagnostic"));
                    }
                }
                out.push((config_topic("binary_sensor", field), p));
            }
        }
    }
    let mut lq = base_payload("linkquality", "Link quality".into());
    if let Some(o) = lq.as_object_mut() {
        o.insert("unit_of_measurement".into(), json!("lqi"));
        o.insert("state_class".into(), json!("measurement"));
        o.insert("entity_category".into(), json!("diagnostic"));
        o.insert("icon".into(), json!("mdi:signal"));
    }
    out.push((config_topic("sensor", "linkquality"), lq));
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use zigbee_zdo::SimpleDescriptor;

    fn device() -> Device {
        let mut d = Device::new(Ieee(0x00124B0000000001), 0x1234, 0);
        d.model = Some("SIM-TH1".into());
        d.power_source = Some(3);
        d.endpoints = vec![SimpleDescriptor {
            endpoint: 1,
            profile_id: 0x0104,
            device_id: 0x0302,
            device_version: 1,
            input_clusters: vec![0, 1, 0x0402, 0x0405],
            output_clusters: vec![],
        }];
        d
    }

    #[test]
    fn converts_standard_readings() {
        let t = find(cluster_id::TEMPERATURE_MEASUREMENT, 0).unwrap();
        assert_eq!(convert(t, &Value::i16(2150)), Some(json!(21.5)));
        assert_eq!(
            convert(t, &Value::Int(zigbee_zcl::DataType::Int16, -32768)),
            None
        );
        let b = find(
            cluster_id::POWER_CONFIGURATION,
            attr::power_configuration::BATTERY_PERCENTAGE_REMAINING,
        )
        .unwrap();
        assert_eq!(convert(b, &Value::u8(200)), Some(json!(100.0)));
        let l = find(cluster_id::ILLUMINANCE_MEASUREMENT, 0).unwrap();
        assert_eq!(convert(l, &Value::u16(10001)), Some(json!(10.0)));
        let o = find(cluster_id::ON_OFF, 0).unwrap();
        assert_eq!(convert(o, &Value::bool(true)), Some(json!("ON")));
        assert_eq!(
            ias_fields(Some(0x0015), 0x0001)[0],
            ("contact", json!(false))
        );
    }

    #[test]
    fn discovery_describes_each_reading() {
        let d = device();
        let ctx = DiscoveryContext {
            prefix: "homeassistant",
            base: "zigbee",
            version: "0.1.0",
        };
        let messages = discovery(&ctx, &d, "0x00124b0000000001");
        let topics: Vec<&str> = messages.iter().map(|(t, _)| t.as_str()).collect();
        assert!(topics.contains(&"homeassistant/sensor/00124b0000000001/temperature/config"));
        assert!(topics.contains(&"homeassistant/sensor/00124b0000000001/battery/config"));
        assert!(topics.contains(&"homeassistant/sensor/00124b0000000001/linkquality/config"));
        let (_, t) = messages
            .iter()
            .find(|(t, _)| t.ends_with("/temperature/config"))
            .unwrap();
        assert_eq!(t["state_topic"], "zigbee/0x00124b0000000001");
        assert_eq!(t["value_template"], "{{ value_json.temperature }}");
        assert_eq!(t["device_class"], "temperature");
        assert_eq!(
            t["unique_id"],
            "0x00124b0000000001_temperature_zigbee-bridge"
        );
    }
}