Skip to main content

zigbee_bridge/
exposes.rs

1//! What a device's standard clusters mean as JSON fields, and the Home
2//! Assistant discovery that describes them.
3//!
4//! Everything here is from the ZCL specification, so it holds for every
5//! device that implements the cluster: no per-device code. Device quirks
6//! belong in device definitions, not here.
7
8use serde_json::{json, Value as Json};
9use zigbee_host::Device;
10use zigbee_primitives::Ieee;
11use zigbee_zcl::{attr, cluster_id, Value};
12
13use crate::api::{
14    DiscoveryAvailability, DiscoveryConfig, DiscoveryDevice, DiscoveryOrigin, DiscoveryPayload,
15};
16
17/// How a raw attribute becomes a JSON value.
18#[derive(Debug, Clone, Copy, PartialEq)]
19pub enum Convert {
20    /// Multiply, rounding to `decimals`.
21    Scale(f64, u32),
22    /// Illuminance: lux = 10 ^ ((value - 1) / 10000).
23    Lux,
24    /// "ON" / "OFF".
25    OnOff,
26    /// One bit of a bitmap as a boolean.
27    Bit(u8),
28    /// The value as is.
29    Raw,
30}
31
32/// The Home Assistant entity type.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum Component {
35    /// A sensor.
36    Sensor,
37    /// A binary sensor.
38    BinarySensor,
39    /// A switch (on/off without level).
40    Switch,
41}
42
43impl Component {
44    fn name(self) -> &'static str {
45        match self {
46            Component::Sensor => "sensor",
47            Component::BinarySensor => "binary_sensor",
48            Component::Switch => "switch",
49        }
50    }
51}
52
53/// One attribute as a field.
54#[derive(Debug)]
55pub struct Expose {
56    /// Cluster.
57    pub cluster: u16,
58    /// Attribute.
59    pub attribute: u16,
60    /// JSON field name.
61    pub field: &'static str,
62    /// Conversion.
63    pub convert: Convert,
64    /// Unit.
65    pub unit: Option<&'static str>,
66    /// Home Assistant device class.
67    pub device_class: Option<&'static str>,
68    /// Home Assistant state class.
69    pub state_class: Option<&'static str>,
70    /// Home Assistant entity type.
71    pub component: Component,
72    /// A diagnostic entity.
73    pub diagnostic: bool,
74}
75
76macro_rules! expose {
77    ($cluster:expr, $attr:expr, $field:literal, $convert:expr, $unit:expr, $class:expr, $state:expr, $component:expr, $diag:expr) => {
78        Expose {
79            cluster: $cluster,
80            attribute: $attr,
81            field: $field,
82            convert: $convert,
83            unit: $unit,
84            device_class: $class,
85            state_class: $state,
86            component: $component,
87            diagnostic: $diag,
88        }
89    };
90}
91
92const M: Option<&str> = Some("measurement");
93
94/// Every standard attribute the bridge turns into a field.
95pub static EXPOSES: &[Expose] = &[
96    expose!(
97        cluster_id::TEMPERATURE_MEASUREMENT,
98        attr::temperature_measurement::MEASURED_VALUE,
99        "temperature",
100        Convert::Scale(0.01, 2),
101        Some("°C"),
102        Some("temperature"),
103        M,
104        Component::Sensor,
105        false
106    ),
107    expose!(
108        cluster_id::RELATIVE_HUMIDITY_MEASUREMENT,
109        attr::relative_humidity_measurement::MEASURED_VALUE,
110        "humidity",
111        Convert::Scale(0.01, 2),
112        Some("%"),
113        Some("humidity"),
114        M,
115        Component::Sensor,
116        false
117    ),
118    expose!(
119        cluster_id::PRESSURE_MEASUREMENT,
120        attr::pressure_measurement::MEASURED_VALUE,
121        "pressure",
122        Convert::Scale(1.0, 1),
123        Some("hPa"),
124        Some("pressure"),
125        M,
126        Component::Sensor,
127        false
128    ),
129    expose!(
130        cluster_id::ILLUMINANCE_MEASUREMENT,
131        attr::illuminance_measurement::MEASURED_VALUE,
132        "illuminance",
133        Convert::Lux,
134        Some("lx"),
135        Some("illuminance"),
136        M,
137        Component::Sensor,
138        false
139    ),
140    expose!(
141        cluster_id::FLOW_MEASUREMENT,
142        attr::flow_measurement::MEASURED_VALUE,
143        "flow",
144        Convert::Scale(0.1, 1),
145        Some("m³/h"),
146        None,
147        M,
148        Component::Sensor,
149        false
150    ),
151    expose!(
152        cluster_id::SOIL_MOISTURE_MEASUREMENT,
153        attr::soil_moisture_measurement::MEASURED_VALUE,
154        "soil_moisture",
155        Convert::Scale(0.01, 2),
156        Some("%"),
157        Some("moisture"),
158        M,
159        Component::Sensor,
160        false
161    ),
162    expose!(
163        cluster_id::CARBON_DIOXIDE_MEASUREMENT,
164        attr::carbon_dioxide_measurement::MEASURED_VALUE,
165        "co2",
166        Convert::Scale(1e6, 0),
167        Some("ppm"),
168        Some("carbon_dioxide"),
169        M,
170        Component::Sensor,
171        false
172    ),
173    expose!(
174        cluster_id::PM25_MEASUREMENT,
175        attr::pm25_measurement::MEASURED_VALUE,
176        "pm25",
177        Convert::Scale(1.0, 1),
178        Some("µg/m³"),
179        Some("pm25"),
180        M,
181        Component::Sensor,
182        false
183    ),
184    expose!(
185        cluster_id::OCCUPANCY_SENSING,
186        attr::occupancy_sensing::OCCUPANCY,
187        "occupancy",
188        Convert::Bit(0),
189        None,
190        Some("occupancy"),
191        None,
192        Component::BinarySensor,
193        false
194    ),
195    expose!(
196        cluster_id::ON_OFF,
197        attr::on_off::ON_OFF,
198        "state",
199        Convert::OnOff,
200        None,
201        None,
202        None,
203        Component::Switch,
204        false
205    ),
206    expose!(
207        cluster_id::POWER_CONFIGURATION,
208        attr::power_configuration::BATTERY_PERCENTAGE_REMAINING,
209        "battery",
210        Convert::Scale(0.5, 0),
211        Some("%"),
212        Some("battery"),
213        M,
214        Component::Sensor,
215        true
216    ),
217    expose!(
218        cluster_id::POWER_CONFIGURATION,
219        attr::power_configuration::BATTERY_VOLTAGE,
220        "battery_voltage",
221        Convert::Scale(100.0, 0),
222        Some("mV"),
223        Some("voltage"),
224        M,
225        Component::Sensor,
226        true
227    ),
228    expose!(
229        cluster_id::ELECTRICAL_MEASUREMENT,
230        attr::electrical_measurement::ACTIVE_POWER,
231        "power",
232        Convert::Scale(1.0, 1),
233        Some("W"),
234        Some("power"),
235        M,
236        Component::Sensor,
237        false
238    ),
239    expose!(
240        cluster_id::ELECTRICAL_MEASUREMENT,
241        attr::electrical_measurement::RMS_VOLTAGE,
242        "voltage",
243        Convert::Scale(1.0, 1),
244        Some("V"),
245        Some("voltage"),
246        M,
247        Component::Sensor,
248        false
249    ),
250    expose!(
251        cluster_id::ELECTRICAL_MEASUREMENT,
252        attr::electrical_measurement::RMS_CURRENT,
253        "current",
254        Convert::Scale(0.001, 3),
255        Some("A"),
256        Some("current"),
257        M,
258        Component::Sensor,
259        false
260    ),
261    expose!(
262        cluster_id::METERING,
263        attr::metering::CURRENT_SUMMATION_DELIVERED,
264        "energy",
265        Convert::Scale(0.001, 3),
266        Some("kWh"),
267        Some("energy"),
268        Some("total_increasing"),
269        Component::Sensor,
270        false
271    ),
272    expose!(
273        cluster_id::THERMOSTAT,
274        attr::thermostat::LOCAL_TEMPERATURE,
275        "local_temperature",
276        Convert::Scale(0.01, 2),
277        Some("°C"),
278        Some("temperature"),
279        M,
280        Component::Sensor,
281        false
282    ),
283    expose!(
284        cluster_id::DEVICE_TEMPERATURE_CONFIGURATION,
285        attr::device_temperature_configuration::CURRENT_TEMPERATURE,
286        "device_temperature",
287        Convert::Raw,
288        Some("°C"),
289        Some("temperature"),
290        M,
291        Component::Sensor,
292        true
293    ),
294];
295
296/// The expose for an attribute.
297pub fn find(cluster: u16, attribute: u16) -> Option<&'static Expose> {
298    EXPOSES
299        .iter()
300        .find(|e| e.cluster == cluster && e.attribute == attribute)
301}
302
303fn round(v: f64, decimals: u32) -> f64 {
304    let f = 10f64.powi(decimals as i32);
305    (v * f).round() / f
306}
307
308/// Convert a value; `None` for invalid ("no reading") values.
309pub fn convert(expose: &Expose, value: &Value) -> Option<Json> {
310    match expose.convert {
311        Convert::OnOff => value
312            .as_bool()
313            .map(|on| json!(if on { "ON" } else { "OFF" })),
314        Convert::Bit(bit) => value.as_u64().map(|v| json!(v & (1 << bit) != 0)),
315        Convert::Lux => value.as_f64().map(|v| {
316            json!(round(
317                if v <= 0.0 {
318                    0.0
319                } else {
320                    10f64.powf((v - 1.0) / 10000.0)
321                },
322                0
323            ))
324        }),
325        Convert::Scale(factor, decimals) => {
326            value.as_f64().map(|v| json!(round(v * factor, decimals)))
327        }
328        Convert::Raw => serde_json::to_value(value).ok().filter(|j| !j.is_null()),
329    }
330}
331
332/// The field name for an expose on an endpoint: plain on the first
333/// endpoint that has the cluster, `<field>_<endpoint>` on later ones.
334pub fn field_name(device: &Device, endpoint: u8, expose: &Expose) -> String {
335    match device
336        .endpoints
337        .iter()
338        .find(|e| e.input_clusters.contains(&expose.cluster))
339    {
340        Some(first) if first.endpoint != endpoint => format!("{}_{endpoint}", expose.field),
341        _ => expose.field.to_string(),
342    }
343}
344
345/// IAS zone fields for a zone status, by zone type.
346pub fn ias_fields(zone_type: Option<u16>, status: u16) -> Vec<(&'static str, Json)> {
347    let alarm = status & 0x0001 != 0;
348    let main = match zone_type {
349        Some(0x0015) => ("contact", json!(!alarm)),
350        Some(0x000D) => ("occupancy", json!(alarm)),
351        Some(0x002A) => ("water_leak", json!(alarm)),
352        Some(0x0028) => ("smoke", json!(alarm)),
353        Some(0x002B) => ("carbon_monoxide", json!(alarm)),
354        Some(0x002D) => ("vibration", json!(alarm)),
355        _ => ("alarm", json!(alarm)),
356    };
357    vec![
358        main,
359        ("tamper", json!(status & 0x0004 != 0)),
360        ("battery_low", json!(status & 0x0008 != 0)),
361    ]
362}
363
364fn ias_class(field: &str) -> Option<&'static str> {
365    Some(match field {
366        "contact" => "door",
367        "occupancy" => "motion",
368        "water_leak" => "moisture",
369        "smoke" => "smoke",
370        "carbon_monoxide" => "carbon_monoxide",
371        "vibration" => "vibration",
372        "tamper" => "tamper",
373        "battery_low" => "battery",
374        _ => "safety",
375    })
376}
377
378/// Everything a discovery message needs to know about the bridge.
379pub struct DiscoveryContext<'a> {
380    /// Home Assistant's discovery prefix.
381    pub prefix: &'a str,
382    /// The bridge's base topic.
383    pub base: &'a str,
384    /// The bridge's version.
385    pub version: &'a str,
386}
387
388fn title(field: &str) -> String {
389    let mut out = String::new();
390    for (i, word) in field.split('_').enumerate() {
391        if i > 0 {
392            out.push(' ');
393        }
394        let mut chars = word.chars();
395        if let Some(c) = chars.next() {
396            out.extend(c.to_uppercase());
397            out.push_str(chars.as_str());
398        }
399    }
400    out.replace("Co2", "CO2").replace("Pm25", "PM2.5")
401}
402
403fn id(ieee: Ieee) -> String {
404    ieee.to_prefixed_hex()
405}
406
407/// Discovery messages (topic, payload) for a device's standard clusters.
408pub fn discovery(
409    ctx: &DiscoveryContext<'_>,
410    device: &Device,
411    friendly: &str,
412) -> Vec<(String, DiscoveryConfig)> {
413    let ieee = id(device.ieee);
414    let state_topic = format!("{}/{friendly}", ctx.base);
415    let device_info = DiscoveryDevice {
416        identifiers: vec![format!("zigbee-bridge_{ieee}")],
417        name: friendly.to_string(),
418        manufacturer: device.manufacturer.clone(),
419        model: device.model.clone(),
420        sw_version: device.sw_build_id.clone(),
421    };
422    let base_payload = |field: &str, name: String| DiscoveryConfig {
423        name,
424        unique_id: format!("{ieee}_{field}_zigbee-bridge"),
425        object_id: format!("{}_{field}", friendly.replace(['/', ' '], "_")),
426        state_topic: state_topic.clone(),
427        value_template: Some(format!("{{{{ value_json.{field} }}}}")),
428        availability: vec![DiscoveryAvailability {
429            topic: format!("{}/bridge/state", ctx.base),
430            value_template: "{{ value_json.state }}".into(),
431        }],
432        device: device_info.clone(),
433        origin: DiscoveryOrigin {
434            name: "zigbee-bridge".into(),
435            sw_version: ctx.version.into(),
436        },
437        ..DiscoveryConfig::default()
438    };
439    let config_topic = |component: &str, field: &str| {
440        format!(
441            "{}/{component}/{}/{field}/config",
442            ctx.prefix,
443            ieee.trim_start_matches("0x")
444        )
445    };
446    let text = |s: &str| Some(s.to_string());
447    let mut out = Vec::new();
448    for ep in &device.endpoints {
449        let has = |c: u16| ep.input_clusters.contains(&c);
450        let light = has(cluster_id::ON_OFF) && has(cluster_id::LEVEL_CONTROL);
451        if light {
452            let field = match device
453                .endpoints
454                .iter()
455                .find(|e| e.input_clusters.contains(&cluster_id::ON_OFF))
456            {
457                Some(first) if first.endpoint != ep.endpoint => format!("light_{}", ep.endpoint),
458                _ => "light".to_string(),
459            };
460            let p = DiscoveryConfig {
461                value_template: None,
462                schema: text("json"),
463                command_topic: Some(format!("{state_topic}/set")),
464                brightness: Some(true),
465                brightness_scale: Some(254),
466                supported_color_modes: has(cluster_id::COLOR_CONTROL)
467                    .then(|| vec!["color_temp".to_string()]),
468                ..base_payload(&field, "Light".into())
469            };
470            out.push((config_topic("light", &field), p));
471        }
472        for e in EXPOSES.iter().filter(|e| has(e.cluster)) {
473            if light && e.cluster == cluster_id::ON_OFF {
474                continue;
475            }
476            // A battery cluster on a mains device has no battery.
477            if e.cluster == cluster_id::POWER_CONFIGURATION
478                && device
479                    .power_source
480                    .is_some_and(|p| p & 0x7F == 0x01 || p & 0x7F == 0x04)
481            {
482                continue;
483            }
484            let field = field_name(device, ep.endpoint, e);
485            let mut p = DiscoveryConfig {
486                unit_of_measurement: e.unit.map(str::to_string),
487                device_class: e.device_class.map(str::to_string),
488                state_class: e.state_class.map(str::to_string),
489                entity_category: e.diagnostic.then(|| "diagnostic".to_string()),
490                ..base_payload(&field, title(&field))
491            };
492            match e.component {
493                Component::BinarySensor => {
494                    p.payload_on = Some(DiscoveryPayload::Bool(true));
495                    p.payload_off = Some(DiscoveryPayload::Bool(false));
496                }
497                Component::Switch => {
498                    p.command_topic = Some(format!("{state_topic}/set"));
499                    p.payload_on = Some(DiscoveryPayload::Text(r#"{"state":"ON"}"#.into()));
500                    p.payload_off = Some(DiscoveryPayload::Text(r#"{"state":"OFF"}"#.into()));
501                    p.state_on = text("ON");
502                    p.state_off = text("OFF");
503                }
504                Component::Sensor => {}
505            }
506            out.push((config_topic(e.component.name(), &field), p));
507        }
508        if has(cluster_id::IAS_ZONE) {
509            for (field, _) in ias_fields(device.ias_zone_type, 0) {
510                // HA's door class is "on" when open, and `contact` is true
511                // when closed.
512                let p = DiscoveryConfig {
513                    payload_on: Some(DiscoveryPayload::Bool(field != "contact")),
514                    payload_off: Some(DiscoveryPayload::Bool(field == "contact")),
515                    device_class: ias_class(field).map(str::to_string),
516                    entity_category: matches!(field, "tamper" | "battery_low")
517                        .then(|| "diagnostic".to_string()),
518                    ..base_payload(field, title(field))
519                };
520                out.push((config_topic("binary_sensor", field), p));
521            }
522        }
523    }
524    let lq = DiscoveryConfig {
525        unit_of_measurement: text("lqi"),
526        state_class: text("measurement"),
527        entity_category: text("diagnostic"),
528        icon: text("mdi:signal"),
529        ..base_payload("linkquality", "Link quality".into())
530    };
531    out.push((config_topic("sensor", "linkquality"), lq));
532    out
533}
534
535#[cfg(test)]
536mod tests {
537    use super::*;
538    use zigbee_zdo::SimpleDescriptor;
539
540    fn device() -> Device {
541        let mut d = Device::new(Ieee(0x00124B0000000001), 0x1234, 0);
542        d.model = Some("SIM-TH1".into());
543        d.power_source = Some(3);
544        d.endpoints = vec![SimpleDescriptor {
545            endpoint: 1,
546            profile_id: 0x0104,
547            device_id: 0x0302,
548            device_version: 1,
549            input_clusters: vec![0, 1, 0x0402, 0x0405],
550            output_clusters: vec![],
551        }];
552        d
553    }
554
555    #[test]
556    fn converts_standard_readings() {
557        let t = find(cluster_id::TEMPERATURE_MEASUREMENT, 0).unwrap();
558        assert_eq!(convert(t, &Value::i16(2150)), Some(json!(21.5)));
559        assert_eq!(
560            convert(t, &Value::Int(zigbee_zcl::DataType::Int16, -32768)),
561            None
562        );
563        let b = find(
564            cluster_id::POWER_CONFIGURATION,
565            attr::power_configuration::BATTERY_PERCENTAGE_REMAINING,
566        )
567        .unwrap();
568        assert_eq!(convert(b, &Value::u8(200)), Some(json!(100.0)));
569        let l = find(cluster_id::ILLUMINANCE_MEASUREMENT, 0).unwrap();
570        assert_eq!(convert(l, &Value::u16(10001)), Some(json!(10.0)));
571        let o = find(cluster_id::ON_OFF, 0).unwrap();
572        assert_eq!(convert(o, &Value::bool(true)), Some(json!("ON")));
573        assert_eq!(
574            ias_fields(Some(0x0015), 0x0001)[0],
575            ("contact", json!(false))
576        );
577    }
578
579    #[test]
580    fn discovery_describes_each_reading() {
581        let d = device();
582        let ctx = DiscoveryContext {
583            prefix: "homeassistant",
584            base: "zigbee",
585            version: "0.1.0",
586        };
587        let messages = discovery(&ctx, &d, "0x00124b0000000001");
588        let topics: Vec<&str> = messages.iter().map(|(t, _)| t.as_str()).collect();
589        assert!(topics.contains(&"homeassistant/sensor/00124b0000000001/temperature/config"));
590        assert!(topics.contains(&"homeassistant/sensor/00124b0000000001/battery/config"));
591        assert!(topics.contains(&"homeassistant/sensor/00124b0000000001/linkquality/config"));
592        let (_, t) = messages
593            .iter()
594            .find(|(t, _)| t.ends_with("/temperature/config"))
595            .unwrap();
596        assert_eq!(t.state_topic, "zigbee/0x00124b0000000001");
597        assert_eq!(
598            t.value_template.as_deref(),
599            Some("{{ value_json.temperature }}")
600        );
601        assert_eq!(t.device_class.as_deref(), Some("temperature"));
602        assert_eq!(t.unique_id, "0x00124b0000000001_temperature_zigbee-bridge");
603    }
604}