Skip to main content

zwave_host/
values.rs

1//! Values: what reports mean, as numbers with units, independent of the
2//! command class that carried them.
3
4use crate::NodeId;
5use zwave_cc::{
6    basic, battery, binary_sensor, binary_switch, configuration, meter, multilevel_sensor,
7    multilevel_switch, notification, tables, Command,
8};
9
10/// Identifies one value of one node.
11#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
12pub struct ValueId {
13    /// The node.
14    pub node: NodeId,
15    /// The endpoint (0 is the root device).
16    pub endpoint: u8,
17    /// The command class it belongs to.
18    pub cc: u16,
19    /// A stable snake-case property: `air_temperature`, `electric_kwh`,
20    /// `home_security_motion_sensor_status`, `level`, `current`.
21    pub property: String,
22}
23
24impl ValueId {
25    /// `<cc name>/<property>`, or with an endpoint `<cc name>/<property>/<endpoint>`.
26    pub fn key(&self) -> String {
27        let cc = zwave_cc::cc_info(self.cc)
28            .map(|c| c.name.to_string())
29            .unwrap_or_else(|| format!("{:#06x}", self.cc));
30        if self.endpoint == 0 {
31            format!("{cc}/{}", self.property)
32        } else {
33            format!("{cc}/{}/{}", self.property, self.endpoint)
34        }
35    }
36}
37
38/// A value.
39#[derive(Debug, Clone, PartialEq)]
40pub enum ValueKind {
41    /// On/off, open/closed, detected/idle.
42    Bool(bool),
43    /// A measurement.
44    Number(f64),
45    /// A level, 0 to 99 (0xFF for "on at the last level").
46    Level(u8),
47    /// A notification state or event: its id and label.
48    State {
49        /// Event id (0 is idle).
50        id: u8,
51        /// Its label.
52        label: String,
53    },
54}
55
56/// A value as reported.
57#[derive(Debug, Clone, PartialEq)]
58pub struct ValueUpdate {
59    /// Which value.
60    pub id: ValueId,
61    /// The value.
62    pub value: ValueKind,
63    /// The unit symbol, if any.
64    pub unit: Option<&'static str>,
65    /// A label for people.
66    pub label: String,
67    /// Whether the value can be set (switches, levels).
68    pub writable: bool,
69    /// Signal strength of the frame that carried it at the controller, dBm.
70    pub rssi: Option<i8>,
71}
72
73fn snake(s: &str) -> String {
74    let mut out = String::new();
75    for c in s.chars() {
76        if c.is_ascii_alphanumeric() {
77            out.push(c.to_ascii_lowercase());
78        } else if !out.ends_with('_') {
79            out.push('_');
80        }
81    }
82    out.trim_matches('_').to_string()
83}
84
85fn unit_key(unit: &str, label: &str) -> String {
86    let s = snake(if unit.is_empty() { label } else { unit });
87    if s.is_empty() {
88        "value".into()
89    } else {
90        s
91    }
92}
93
94/// The values a command carries. Commands that carry none give an empty list.
95pub fn from_command(node: NodeId, endpoint: u8, cmd: &Command) -> Vec<ValueUpdate> {
96    let id = |cc: u16, property: &str| ValueId {
97        node,
98        endpoint,
99        cc,
100        property: property.to_string(),
101    };
102    let mut out = Vec::new();
103    match cmd {
104        Command::Basic(basic::Command::Report(r)) if r.current <= 99 || r.current == 0xff => out
105            .push(ValueUpdate {
106                id: id(basic::ID, "current"),
107                value: ValueKind::Level(r.current),
108                unit: None,
109                label: "Basic".into(),
110                writable: true,
111                rssi: None,
112            }),
113        Command::BinarySwitch(binary_switch::Command::Report(r)) if r.current != 0xfe => {
114            out.push(ValueUpdate {
115                id: id(binary_switch::ID, "current"),
116                value: ValueKind::Bool(r.current != 0),
117                unit: None,
118                label: "Switch".into(),
119                writable: true,
120                rssi: None,
121            })
122        }
123        Command::MultilevelSwitch(multilevel_switch::Command::Report(r)) if r.current != 0xfe => {
124            out.push(ValueUpdate {
125                id: id(multilevel_switch::ID, "current"),
126                value: ValueKind::Level(r.current),
127                unit: None,
128                label: "Level".into(),
129                writable: true,
130                rssi: None,
131            })
132        }
133        Command::MultilevelSensor(multilevel_sensor::Command::Report(r)) => {
134            let t = tables::sensor_type(r.sensor_type);
135            let scale = t.and_then(|t| t.scale(r.value.scale));
136            let name = t
137                .map(|t| t.name.to_string())
138                .unwrap_or_else(|| format!("sensor_{}", r.sensor_type));
139            out.push(ValueUpdate {
140                id: id(multilevel_sensor::ID, &name),
141                value: ValueKind::Number(r.value.to_f64()),
142                unit: scale.map(|s| s.unit).filter(|u| !u.is_empty()),
143                label: t.map(|t| t.label.to_string()).unwrap_or(name),
144                writable: false,
145                rssi: None,
146            });
147        }
148        Command::Meter(meter::Command::Report(r)) => {
149            let mut scale = r.value.scale | if r.scale_bit2 { 0x04 } else { 0 };
150            if scale == 7 {
151                if let Some(s2) = r.scale2 {
152                    scale = 8 + s2;
153                }
154            }
155            let t = tables::meter_type(r.meter_type);
156            let s = t.and_then(|t| t.scale(scale));
157            let tname = t
158                .map(|t| t.name.to_string())
159                .unwrap_or_else(|| format!("meter_{}", r.meter_type));
160            let skey = s
161                .map(|s| unit_key(s.unit, s.label))
162                .unwrap_or_else(|| format!("scale_{scale}"));
163            out.push(ValueUpdate {
164                id: id(meter::ID, &format!("{tname}_{skey}")),
165                value: ValueKind::Number(r.value.to_f64()),
166                unit: s.map(|s| s.unit).filter(|u| !u.is_empty()),
167                label: format!(
168                    "{} {}",
169                    t.map(|t| t.label).unwrap_or("Meter"),
170                    s.map(|s| s.label).unwrap_or("")
171                )
172                .trim()
173                .to_string(),
174                writable: false,
175                rssi: None,
176            });
177        }
178        Command::Notification(notification::Command::Report(r)) => {
179            if let (Some(ty), Some(event)) = (r.notification_type, r.event) {
180                let t = tables::notification_type(ty);
181                let tname = t
182                    .map(|t| t.name.to_string())
183                    .unwrap_or_else(|| format!("notification_{ty}"));
184                let ev = t.and_then(|t| t.event(event));
185                // Idle (event 0) clears the variable named in the first parameter byte.
186                let variable = if event == 0 {
187                    r.params
188                        .first()
189                        .and_then(|&p| t.and_then(|t| t.event(p)))
190                        .map(|e| e.variable)
191                } else {
192                    ev.map(|e| e.variable)
193                };
194                let (prop, label) = match variable {
195                    Some(v) if !v.is_empty() => (
196                        format!("{tname}_{}", snake(v)),
197                        format!("{} {}", t.map(|t| t.label).unwrap_or(""), v),
198                    ),
199                    _ => (
200                        format!("{tname}_event"),
201                        format!("{} event", t.map(|t| t.label).unwrap_or("Notification")),
202                    ),
203                };
204                out.push(ValueUpdate {
205                    id: id(notification::ID, &prop),
206                    value: ValueKind::State {
207                        id: event,
208                        label: if event == 0 {
209                            "Idle".into()
210                        } else {
211                            ev.map(|e| e.label.to_string())
212                                .unwrap_or_else(|| format!("Event {event}"))
213                        },
214                    },
215                    unit: None,
216                    label: label.trim().to_string(),
217                    writable: false,
218                    rssi: None,
219                });
220            } else {
221                out.push(ValueUpdate {
222                    id: id(notification::ID, &format!("alarm_{}", r.v1_alarm_type)),
223                    value: ValueKind::Number(f64::from(r.v1_alarm_level)),
224                    unit: None,
225                    label: format!("Alarm {}", r.v1_alarm_type),
226                    writable: false,
227                    rssi: None,
228                });
229            }
230        }
231        Command::Battery(battery::Command::Report(r)) => {
232            out.push(ValueUpdate {
233                id: id(battery::ID, "level"),
234                value: ValueKind::Number(if r.level == 0xff {
235                    0.0
236                } else {
237                    f64::from(r.level.min(100))
238                }),
239                unit: Some("%"),
240                label: "Battery".into(),
241                writable: false,
242                rssi: None,
243            });
244            out.push(ValueUpdate {
245                id: id(battery::ID, "low"),
246                value: ValueKind::Bool(r.level == 0xff),
247                unit: None,
248                label: "Battery low".into(),
249                writable: false,
250                rssi: None,
251            });
252        }
253        Command::BinarySensor(binary_sensor::Command::Report(r)) => {
254            let name = match r.sensor_type {
255                Some(1) => "general_purpose",
256                Some(2) => "smoke",
257                Some(3) => "co",
258                Some(4) => "co2",
259                Some(5) => "heat",
260                Some(6) => "water",
261                Some(7) => "freeze",
262                Some(8) => "tamper",
263                Some(9) => "aux",
264                Some(10) => "door_window",
265                Some(11) => "tilt",
266                Some(12) => "motion",
267                Some(13) => "glass_break",
268                _ => "any",
269            };
270            out.push(ValueUpdate {
271                id: id(binary_sensor::ID, name),
272                value: ValueKind::Bool(r.value != 0),
273                unit: None,
274                label: format!("Binary sensor {}", name.replace('_', " ")),
275                writable: false,
276                rssi: None,
277            });
278        }
279        Command::Configuration(configuration::Command::Report(r)) => out.push(ValueUpdate {
280            id: id(configuration::ID, &format!("parameter_{}", r.parameter)),
281            value: ValueKind::Number(f64::from(r.value)),
282            unit: None,
283            label: format!("Parameter {}", r.parameter),
284            writable: true,
285            rssi: None,
286        }),
287        _ => {}
288    }
289    out
290}
291
292/// The command that sets a writable value, if there is one.
293pub fn set_command(id: &ValueId, value: &ValueKind) -> Option<Command> {
294    let level = |v: &ValueKind| -> Option<u8> {
295        Some(match v {
296            ValueKind::Bool(b) => {
297                if *b {
298                    0xff
299                } else {
300                    0
301                }
302            }
303            ValueKind::Level(l) => *l,
304            ValueKind::Number(n) if (0.0..=99.0).contains(n) => *n as u8,
305            ValueKind::Number(n) if *n == 255.0 => 0xff,
306            _ => return None,
307        })
308    };
309    match (id.cc, id.property.as_str()) {
310        (basic::ID, "current") => Some(
311            basic::Set {
312                value: level(value)?,
313            }
314            .into(),
315        ),
316        (binary_switch::ID, "current") => Some(
317            binary_switch::Set {
318                target: level(value)?.min(1) * 0xff,
319                duration: None,
320            }
321            .into(),
322        ),
323        (multilevel_switch::ID, "current") => Some(
324            multilevel_switch::Set {
325                value: level(value)?,
326                duration: None,
327            }
328            .into(),
329        ),
330        _ => None,
331    }
332}
333
334/// The Get that refreshes a value after it was set.
335pub fn get_command(id: &ValueId) -> Option<Command> {
336    match id.cc {
337        basic::ID => Some(basic::Get {}.into()),
338        binary_switch::ID => Some(binary_switch::Get {}.into()),
339        multilevel_switch::ID => Some(multilevel_switch::Get {}.into()),
340        _ => None,
341    }
342}
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347
348    #[test]
349    fn sensor_and_meter_values() {
350        let c = Command::parse(&[0x31, 0x05, 0x01, 0x22, 0x00, 0xe1]).unwrap();
351        let v = from_command(4, 0, &c);
352        assert_eq!(v[0].id.property, "air_temperature");
353        assert_eq!(v[0].unit, Some("°C"));
354        assert_eq!(v[0].value, ValueKind::Number(22.5));
355        assert_eq!(v[0].id.key(), "multilevel_sensor/air_temperature");
356        let c = Command::parse(&[0x32, 0x02, 0x21, 0x62, 0x04, 0xd2]).unwrap();
357        assert_eq!(from_command(4, 2, &c)[0].id.key(), "meter/electric_kwh/2");
358    }
359
360    #[test]
361    fn notification_states() {
362        let motion = Command::parse(&[0x71, 0x05, 0, 0, 0, 0xff, 0x07, 0x08, 0x00]).unwrap();
363        let v = &from_command(3, 0, &motion)[0];
364        assert_eq!(v.id.property, "home_security_motion_sensor_status");
365        assert_eq!(
366            v.value,
367            ValueKind::State {
368                id: 8,
369                label: "Motion detection".into()
370            }
371        );
372        let idle = Command::parse(&[0x71, 0x05, 0, 0, 0, 0xff, 0x07, 0x00, 0x01, 0x08]).unwrap();
373        let v = &from_command(3, 0, &idle)[0];
374        assert_eq!(v.id.property, "home_security_motion_sensor_status");
375        assert!(matches!(v.value, ValueKind::State { id: 0, .. }));
376    }
377
378    #[test]
379    fn set_commands() {
380        let id = ValueId {
381            node: 2,
382            endpoint: 0,
383            cc: 0x25,
384            property: "current".into(),
385        };
386        assert_eq!(
387            set_command(&id, &ValueKind::Bool(true)).unwrap().encode(),
388            vec![0x25, 0x01, 0xff]
389        );
390        let id = ValueId {
391            node: 2,
392            endpoint: 0,
393            cc: 0x26,
394            property: "current".into(),
395        };
396        assert_eq!(
397            set_command(&id, &ValueKind::Number(42.0)).unwrap().encode(),
398            vec![0x26, 0x01, 42]
399        );
400        let id = ValueId {
401            node: 2,
402            endpoint: 0,
403            cc: 0x31,
404            property: "air_temperature".into(),
405        };
406        assert!(set_command(&id, &ValueKind::Number(1.0)).is_none());
407    }
408}