Skip to main content

zwave_bridge/
discovery.rs

1//! Home Assistant MQTT discovery configs for values.
2
3use serde_json::{json, Value as Json};
4use zwave_host::{NodeRecord, ValueKind, ValueUpdate};
5
6/// A discovery config: the topic to publish it on and its body.
7pub struct Discovery {
8    /// `<prefix>/<component>/<node id>/<object id>/config`.
9    pub topic: String,
10    /// The config.
11    pub config: Json,
12}
13
14fn object_id(key: &str) -> String {
15    key.replace('/', "_")
16}
17
18fn sensor_class(property: &str) -> Option<&'static str> {
19    let p = property;
20    Some(match p {
21        _ if p.ends_with("temperature") => "temperature",
22        "humidity" => "humidity",
23        "illuminance" => "illuminance",
24        "power" => "power",
25        "voltage" => "voltage",
26        "current" => "current",
27        "carbon_dioxide_co2_level" => "carbon_dioxide",
28        "carbon_monoxide_co_level" => "carbon_monoxide",
29        "atmospheric_pressure" | "barometric_pressure" => "pressure",
30        "ultraviolet" => "uv_index",
31        "particulate_matter_2_5" => "pm25",
32        "particulate_matter_10" => "pm10",
33        "volatile_organic_compound_level" => "volatile_organic_compounds",
34        _ => return None,
35    })
36}
37
38fn binary_class(property: &str) -> Option<&'static str> {
39    let p = property;
40    Some(match p {
41        _ if p.contains("motion") => "motion",
42        _ if p.contains("door") || p.contains("window") || p == "access_control_door_state" => {
43            "door"
44        }
45        _ if p.contains("water") || p.contains("leak") => "moisture",
46        _ if p.starts_with("smoke") => "smoke",
47        _ if p.starts_with("co_alarm") || p == "co" => "carbon_monoxide",
48        _ if p.contains("tamper") || p.contains("cover") => "tamper",
49        _ if p.starts_with("heat") => "heat",
50        "low" => "battery",
51        _ => return None,
52    })
53}
54
55/// The Home Assistant unit for a Z-Wave unit symbol.
56fn ha_unit(unit: &str) -> &str {
57    match unit {
58        "Lux" => "lx",
59        other => other,
60    }
61}
62
63/// The discovery config for a value, or `None` when it should not appear in Home Assistant.
64pub fn for_value(
65    prefix: &str,
66    base: &str,
67    home_id: u32,
68    node: &NodeRecord,
69    device_cfg: Option<&zwave_host::device_config::DeviceConfig>,
70    v: &ValueUpdate,
71) -> Option<Discovery> {
72    let key = v.id.key();
73    let state_topic = format!("{base}/nodes/{}/{key}", v.id.node);
74    let device_id = format!("zwave_{home_id:08x}_{}", v.id.node);
75    let unique_id = format!("{device_id}_{}", object_id(&key));
76    let mut device = json!({
77        "identifiers": [device_id],
78        "name": node.name.clone().unwrap_or_else(|| format!("Z-Wave node {}", v.id.node)),
79        "via_device": format!("zwave_{home_id:08x}_controller"),
80    });
81    if let Some(m) = node.manufacturer {
82        device["manufacturer"] = json!(format!("{:#06x}", m.manufacturer_id));
83        device["model"] = json!(format!("{:#06x}:{:#06x}", m.product_type, m.product_id));
84    }
85    if let Some(d) = device_cfg {
86        if node.name.is_none() {
87            device["name"] = json!(format!("{} {}", d.manufacturer, d.label).trim().to_string());
88        }
89        device["manufacturer"] = json!(d.manufacturer);
90        device["model"] = json!(d.label);
91    }
92    if let Some(fw) = &node.firmware {
93        device["sw_version"] = json!(fw);
94    }
95    if let Some(loc) = &node.location {
96        device["suggested_area"] = json!(loc);
97    }
98    let mut c = json!({
99        "name": v.label,
100        "unique_id": unique_id,
101        "object_id": unique_id,
102        "state_topic": state_topic,
103        "availability_topic": format!("{base}/bridge/state"),
104        "device": device,
105    });
106    let set = format!("{state_topic}/set");
107    let component = match (v.id.cc, &v.value) {
108        (0x25, _) => {
109            c["command_topic"] = json!(set);
110            c["value_template"] = json!("{{ 'ON' if value_json.value else 'OFF' }}");
111            c["payload_on"] = json!("ON");
112            c["payload_off"] = json!("OFF");
113            "switch"
114        }
115        (0x26, _) => {
116            c["command_topic"] = json!(set);
117            c["state_value_template"] = json!("{{ 'ON' if value_json.value > 0 else 'OFF' }}");
118            c["brightness_state_topic"] = json!(state_topic);
119            c["brightness_value_template"] = json!("{{ [value_json.value, 99] | min }}");
120            c["brightness_command_topic"] = json!(set);
121            c["brightness_scale"] = json!(99);
122            c["on_command_type"] = json!("brightness");
123            c["payload_on"] = json!("ON");
124            c["payload_off"] = json!("OFF");
125            "light"
126        }
127        (0x20, _) | (0x70, _) => return None,
128        (_, ValueKind::Bool(_)) => {
129            c["value_template"] = json!("{{ 'ON' if value_json.value else 'OFF' }}");
130            if let Some(dc) = binary_class(&v.id.property) {
131                c["device_class"] = json!(dc);
132            }
133            if v.id.cc == 0x80 {
134                c["entity_category"] = json!("diagnostic");
135            }
136            "binary_sensor"
137        }
138        (0x71, ValueKind::State { .. }) => match binary_class(&v.id.property) {
139            Some(dc) => {
140                c["value_template"] = json!("{{ 'ON' if value_json.value != 0 else 'OFF' }}");
141                c["device_class"] = json!(dc);
142                "binary_sensor"
143            }
144            None => {
145                c["value_template"] = json!("{{ value_json.state }}");
146                "sensor"
147            }
148        },
149        (_, ValueKind::Number(_) | ValueKind::Level(_)) => {
150            c["value_template"] = json!("{{ value_json.value }}");
151            if let Some(u) = v.unit {
152                c["unit_of_measurement"] = json!(ha_unit(u));
153            }
154            if v.id.cc == 0x32 {
155                match v.unit {
156                    Some("kWh") => {
157                        c["device_class"] = json!("energy");
158                        c["state_class"] = json!("total_increasing");
159                    }
160                    Some("W") => c["device_class"] = json!("power"),
161                    Some("V") => c["device_class"] = json!("voltage"),
162                    Some("A") => c["device_class"] = json!("current"),
163                    Some("m³") => c["device_class"] = json!("gas"),
164                    _ => {}
165                }
166                if c.get("state_class").is_none() {
167                    c["state_class"] = json!("measurement");
168                }
169            } else if v.id.cc == 0x80 {
170                c["device_class"] = json!("battery");
171                c["entity_category"] = json!("diagnostic");
172                c["state_class"] = json!("measurement");
173            } else {
174                if let Some(dc) = sensor_class(&v.id.property) {
175                    c["device_class"] = json!(dc);
176                }
177                c["state_class"] = json!("measurement");
178            }
179            "sensor"
180        }
181        _ => return None,
182    };
183    Some(Discovery {
184        topic: format!(
185            "{prefix}/{component}/{device_id}/{}/config",
186            object_id(&key)
187        ),
188        config: c,
189    })
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195    use zwave_host::ValueId;
196
197    fn upd(cc: u16, property: &str, value: ValueKind, unit: Option<&'static str>) -> ValueUpdate {
198        ValueUpdate {
199            id: ValueId {
200                node: 4,
201                endpoint: 0,
202                cc,
203                property: property.into(),
204            },
205            value,
206            unit,
207            label: "L".into(),
208            writable: false,
209            rssi: None,
210        }
211    }
212
213    #[test]
214    fn components() {
215        let n = NodeRecord::new(4);
216        let d = for_value(
217            "homeassistant",
218            "zwave",
219            0xc0ffee01,
220            &n,
221            None,
222            &upd(0x31, "air_temperature", ValueKind::Number(1.0), Some("°C")),
223        )
224        .unwrap();
225        assert_eq!(
226            d.topic,
227            "homeassistant/sensor/zwave_c0ffee01_4/multilevel_sensor_air_temperature/config"
228        );
229        assert_eq!(d.config["device_class"], "temperature");
230        assert_eq!(
231            d.config["state_topic"],
232            "zwave/nodes/4/multilevel_sensor/air_temperature"
233        );
234        let d = for_value(
235            "ha",
236            "zwave",
237            1,
238            &n,
239            None,
240            &upd(
241                0x71,
242                "home_security_motion_sensor_status",
243                ValueKind::State {
244                    id: 8,
245                    label: "x".into(),
246                },
247                None,
248            ),
249        )
250        .unwrap();
251        assert!(d.topic.starts_with("ha/binary_sensor/"));
252        assert_eq!(d.config["device_class"], "motion");
253        let d = for_value(
254            "ha",
255            "zwave",
256            1,
257            &n,
258            None,
259            &upd(0x25, "current", ValueKind::Bool(true), None),
260        )
261        .unwrap();
262        assert_eq!(
263            d.config["command_topic"],
264            "zwave/nodes/4/binary_switch/current/set"
265        );
266        let d = for_value(
267            "ha",
268            "zwave",
269            1,
270            &n,
271            None,
272            &upd(0x32, "electric_kwh", ValueKind::Number(1.0), Some("kWh")),
273        )
274        .unwrap();
275        assert_eq!(d.config["state_class"], "total_increasing");
276        assert!(for_value(
277            "ha",
278            "zwave",
279            1,
280            &n,
281            None,
282            &upd(0x70, "parameter_1", ValueKind::Number(1.0), None)
283        )
284        .is_none());
285    }
286}