Skip to main content

matter_bridge/
homeassistant.rs

1//! Home Assistant MQTT discovery, from what a node says it is: entities are
2//! chosen by the clusters an endpoint serves (and its device type, where the
3//! cluster alone is ambiguous), so no per-device table is needed.
4
5use matter_controller::Node;
6use serde_json::{json, Value};
7
8use crate::topics;
9
10const ON_OFF: u32 = 0x0006;
11const LEVEL_CONTROL: u32 = 0x0008;
12const POWER_SOURCE: u32 = 0x002F;
13const BOOLEAN_STATE: u32 = 0x0045;
14const ILLUMINANCE: u32 = 0x0400;
15const TEMPERATURE: u32 = 0x0402;
16const PRESSURE: u32 = 0x0403;
17const HUMIDITY: u32 = 0x0405;
18const OCCUPANCY: u32 = 0x0406;
19
20/// Light device types: On/Off, Dimmable, Color Temperature and Extended
21/// Color Light.
22const LIGHTS: [u32; 4] = [0x0100, 0x0101, 0x010C, 0x010D];
23const CONTACT_SENSOR: u32 = 0x0015;
24const WATER_LEAK_DETECTOR: u32 = 0x0043;
25
26/// Where discovery goes and what the bridge's topics are.
27pub struct Discovery<'a> {
28    /// Home Assistant's discovery prefix.
29    pub prefix: &'a str,
30    /// The bridge's base topic.
31    pub base: &'a str,
32    /// The compressed fabric id, which keeps ids unique across fabrics.
33    pub fabric: u64,
34}
35
36impl Discovery<'_> {
37    fn node_key(&self, node: &Node) -> String {
38        format!("matter_{:016x}_{:016x}", self.fabric, node.node_id)
39    }
40
41    /// Every discovery message for `node`, as (topic, config).
42    pub fn configs(&self, node: &Node) -> Vec<(String, Value)> {
43        let base = self.base;
44        let name = &node.name;
45        let key = self.node_key(node);
46        let device = json!({
47            "identifiers": [key],
48            "name": name,
49            "manufacturer": node.basic.vendor_name,
50            "model": node.basic.product_name,
51            "sw_version": node.basic.software_version,
52            "hw_version": node.basic.hardware_version,
53            "serial_number": node.basic.serial_number,
54            "via_device": format!("matter_bridge_{:016x}", self.fabric),
55        });
56        let availability = json!([
57            {"topic": format!("{base}/bridge/state"), "value_template": "{{ value_json.state }}"},
58            {"topic": format!("{base}/{name}/availability")},
59        ]);
60
61        let mut out = Vec::new();
62        for (&ep, endpoint) in &node.endpoints {
63            let serves = |c: u32| endpoint.server_clusters.contains(&c);
64            let is = |t: u32| endpoint.device_types.iter().any(|d| d.id == t);
65            let topic = |cluster: u32, attribute: u32| {
66                format!(
67                    "{base}/{name}/{ep}/{}/{}",
68                    topics::cluster(cluster),
69                    topics::attribute(cluster, attribute)
70                )
71            };
72            let mut entity = |component: &str, cluster: u32, label: &str, extra: Value| {
73                let mut config = json!({
74                    "name": label,
75                    "unique_id": format!("{key}_{ep}_{cluster:x}"),
76                    "object_id": format!("{name}_{ep}_{}", topics::cluster(cluster)),
77                    "device": device,
78                    "availability": availability,
79                    "availability_mode": "all",
80                });
81                merge(&mut config, extra);
82                strip_nulls(&mut config);
83                out.push((
84                    format!("{}/{component}/{key}/{ep}_{cluster:x}/config", self.prefix),
85                    config,
86                ));
87            };
88
89            // The root endpoint carries only the node's own clusters; a
90            // power source there is the node's battery.
91            if ep == 0 && !serves(POWER_SOURCE) {
92                continue;
93            }
94
95            if serves(ON_OFF) {
96                let state = json!({
97                    "command_topic": format!("{base}/{name}/{ep}/on_off/set"),
98                    "state_topic": topic(ON_OFF, 0),
99                });
100                if LIGHTS.iter().any(|&t| is(t)) {
101                    let mut light = json!({
102                        "state_value_template": "{{ 'ON' if value_json else 'OFF' }}",
103                    });
104                    merge(&mut light, state);
105                    if serves(LEVEL_CONTROL) {
106                        merge(
107                            &mut light,
108                            json!({
109                                "brightness_command_topic": format!("{base}/{name}/{ep}/level_control/set"),
110                                "brightness_state_topic": topic(LEVEL_CONTROL, 0),
111                                "brightness_scale": 254,
112                                "brightness_value_template": "{{ value_json if value_json is not none else 0 }}",
113                            }),
114                        );
115                    }
116                    entity("light", ON_OFF, "Light", light);
117                } else {
118                    let mut switch = json!({
119                        "value_template": "{{ 'ON' if value_json else 'OFF' }}",
120                        "state_on": "ON",
121                        "state_off": "OFF",
122                    });
123                    merge(&mut switch, state);
124                    entity("switch", ON_OFF, "Switch", switch);
125                }
126            }
127
128            let mut sensor =
129                |cluster: u32, label: &str, class: &str, unit: &str, template: &str| {
130                    entity(
131                        "sensor",
132                        cluster,
133                        label,
134                        json!({
135                            "state_topic": topic(cluster, 0),
136                            "value_template": template,
137                            "device_class": class,
138                            "unit_of_measurement": unit,
139                            "state_class": "measurement",
140                        }),
141                    );
142                };
143            if serves(TEMPERATURE) {
144                sensor(
145                    TEMPERATURE,
146                    "Temperature",
147                    "temperature",
148                    "°C",
149                    "{{ (value_json / 100) | round(2) if value_json is not none else none }}",
150                );
151            }
152            if serves(HUMIDITY) {
153                sensor(
154                    HUMIDITY,
155                    "Humidity",
156                    "humidity",
157                    "%",
158                    "{{ (value_json / 100) | round(2) if value_json is not none else none }}",
159                );
160            }
161            if serves(PRESSURE) {
162                sensor(
163                    PRESSURE,
164                    "Pressure",
165                    "pressure",
166                    "kPa",
167                    "{{ (value_json / 10) | round(1) if value_json is not none else none }}",
168                );
169            }
170            if serves(ILLUMINANCE) {
171                sensor(
172                    ILLUMINANCE,
173                    "Illuminance",
174                    "illuminance",
175                    "lx",
176                    "{{ (10 ** ((value_json - 1) / 10000)) | round(1) if value_json else 0 }}",
177                );
178            }
179
180            if serves(OCCUPANCY) {
181                entity(
182                    "binary_sensor",
183                    OCCUPANCY,
184                    "Occupancy",
185                    json!({
186                        "state_topic": topic(OCCUPANCY, 0),
187                        "value_template": "{{ 'ON' if (value_json | int) | bitwise_and(1) else 'OFF' }}",
188                        "device_class": "occupancy",
189                    }),
190                );
191            }
192            if serves(BOOLEAN_STATE) {
193                // A contact sensor's state is true when in contact (closed);
194                // Home Assistant's door is on when open.
195                let (class, template) = if is(CONTACT_SENSOR) {
196                    (Some("door"), "{{ 'OFF' if value_json else 'ON' }}")
197                } else if is(WATER_LEAK_DETECTOR) {
198                    (Some("moisture"), "{{ 'ON' if value_json else 'OFF' }}")
199                } else {
200                    (None, "{{ 'ON' if value_json else 'OFF' }}")
201                };
202                entity(
203                    "binary_sensor",
204                    BOOLEAN_STATE,
205                    "State",
206                    json!({
207                        "state_topic": topic(BOOLEAN_STATE, 0),
208                        "value_template": template,
209                        "device_class": class,
210                    }),
211                );
212            }
213            if serves(POWER_SOURCE) {
214                entity(
215                    "sensor",
216                    POWER_SOURCE,
217                    "Battery",
218                    json!({
219                        "state_topic": topic(POWER_SOURCE, 0x000C),
220                        "value_template": "{{ (value_json / 2) | round(0) if value_json is not none else none }}",
221                        "device_class": "battery",
222                        "unit_of_measurement": "%",
223                        "state_class": "measurement",
224                        "entity_category": "diagnostic",
225                    }),
226                );
227            }
228        }
229        out
230    }
231}
232
233/// Home Assistant wants a key left out rather than null.
234fn strip_nulls(v: &mut Value) {
235    if let Value::Object(map) = v {
236        map.retain(|_, v| !v.is_null());
237        map.values_mut().for_each(strip_nulls);
238    }
239}
240
241fn merge(into: &mut Value, from: Value) {
242    if let (Value::Object(a), Value::Object(b)) = (into, from) {
243        a.extend(b);
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use matter_controller::{BasicInfo, DeviceType, Endpoint};
251
252    fn node(device_type: u32, clusters: &[u32]) -> Node {
253        let mut endpoints = std::collections::BTreeMap::new();
254        endpoints.insert(
255            0,
256            Endpoint {
257                device_types: vec![DeviceType {
258                    id: 0x0016,
259                    revision: 1,
260                }],
261                server_clusters: vec![0x001D, 0x0028],
262                ..Default::default()
263            },
264        );
265        endpoints.insert(
266            1,
267            Endpoint {
268                device_types: vec![DeviceType {
269                    id: device_type,
270                    revision: 1,
271                }],
272                server_clusters: clusters.to_vec(),
273                ..Default::default()
274            },
275        );
276        Node {
277            node_id: 2,
278            name: "lamp".into(),
279            basic: BasicInfo::default(),
280            endpoints,
281            interviewed: true,
282            commissioned_at: 0,
283        }
284    }
285
286    const D: Discovery<'static> = Discovery {
287        prefix: "homeassistant",
288        base: "matter",
289        fabric: 0xAB,
290    };
291
292    #[test]
293    fn dimmable_light() {
294        let configs = D.configs(&node(0x0101, &[ON_OFF, LEVEL_CONTROL]));
295        assert_eq!(configs.len(), 1);
296        let (topic, config) = &configs[0];
297        assert_eq!(
298            topic,
299            "homeassistant/light/matter_00000000000000ab_0000000000000002/1_6/config"
300        );
301        assert_eq!(config["command_topic"], "matter/lamp/1/on_off/set");
302        assert_eq!(config["state_topic"], "matter/lamp/1/on_off/on_off");
303        assert_eq!(
304            config["brightness_state_topic"],
305            "matter/lamp/1/level_control/current_level"
306        );
307    }
308
309    #[test]
310    fn plug_and_sensors() {
311        let configs = D.configs(&node(0x010A, &[ON_OFF, TEMPERATURE, HUMIDITY]));
312        let components: Vec<_> = configs
313            .iter()
314            .map(|(t, _)| t.split('/').nth(1).unwrap().to_string())
315            .collect();
316        assert_eq!(components, ["switch", "sensor", "sensor"]);
317        assert_eq!(
318            configs[1].1["state_topic"],
319            "matter/lamp/1/temperature_measurement/measured_value"
320        );
321    }
322
323    #[test]
324    fn contact_sensor_is_a_door() {
325        let configs = D.configs(&node(CONTACT_SENSOR, &[BOOLEAN_STATE]));
326        assert_eq!(configs[0].1["device_class"], "door");
327        assert_eq!(
328            configs[0].1["state_topic"],
329            "matter/lamp/1/boolean_state/state_value"
330        );
331    }
332}