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