Skip to main content

zwave_cc/
value.rs

1//! Z-Wave's sized decimal values and durations.
2
3/// A sensor, meter or battery health value: a signed integer of 1, 2 or 4
4/// bytes with a decimal precision and a scale.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6pub struct Value {
7    /// Decimal places (0 to 7).
8    pub precision: u8,
9    /// Scale (unit) bits stored with the value (0 to 3).
10    pub scale: u8,
11    /// Size in bytes: 1, 2 or 4.
12    pub size: u8,
13    /// The integer as sent.
14    pub raw: i32,
15}
16
17impl Default for Value {
18    fn default() -> Self {
19        Value {
20            precision: 0,
21            scale: 0,
22            size: 1,
23            raw: 0,
24        }
25    }
26}
27
28impl Value {
29    /// The value as a float.
30    pub fn to_f64(&self) -> f64 {
31        f64::from(self.raw) / 10f64.powi(i32::from(self.precision))
32    }
33
34    /// Encodes `v` with `precision` decimals in the smallest size that fits.
35    pub fn from_f64(v: f64, precision: u8, scale: u8) -> Value {
36        let precision = precision.min(7);
37        let raw = (v * 10f64.powi(i32::from(precision))).round();
38        let raw = raw.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32;
39        let size = if i8::try_from(raw).is_ok() {
40            1
41        } else if i16::try_from(raw).is_ok() {
42            2
43        } else {
44            4
45        };
46        Value {
47            precision,
48            scale: scale & 0x03,
49            size,
50            raw,
51        }
52    }
53
54    /// Appends the precision/scale/size byte and the value.
55    pub fn encode(&self, w: &mut Vec<u8>) {
56        w.push(((self.precision & 0x07) << 5) | ((self.scale & 0x03) << 3) | (self.size & 0x07));
57        crate::write_sized(w, self.raw, self.size);
58    }
59}
60
61/// Decodes a duration byte: `None` for unknown (`0xFE`) or reserved values.
62/// 0 is instantly, up to `0x7F` seconds, `0x80..=0xFD` minutes.
63pub fn decode_duration(b: u8) -> Option<std::time::Duration> {
64    match b {
65        0x00..=0x7f => Some(std::time::Duration::from_secs(u64::from(b))),
66        0x80..=0xfd => Some(std::time::Duration::from_secs(60 * u64::from(b - 0x7f))),
67        _ => None,
68    }
69}
70
71/// Encodes a duration (rounded; capped at 126 minutes). `None` means "device default" (`0xFF`).
72pub fn encode_duration(d: Option<std::time::Duration>) -> u8 {
73    match d {
74        None => 0xff,
75        Some(d) if d.as_secs() <= 0x7f => d.as_secs() as u8,
76        Some(d) => (0x7f + d.as_secs().div_ceil(60).min(126)) as u8,
77    }
78}