Skip to main content

zwave_cc/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4
5pub mod crc16;
6mod reader;
7pub mod tables;
8pub mod transport_service;
9mod value;
10
11pub use value::{decode_duration, encode_duration, Value};
12
13#[allow(
14    missing_docs,
15    clippy::ptr_arg,
16    clippy::identity_op,
17    clippy::needless_late_init
18)]
19mod generated {
20    include!(concat!(env!("OUT_DIR"), "/generated.rs"));
21}
22pub use generated::*;
23
24/// A command the definitions do not cover, kept as bytes.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct RawCommand {
27    /// Command class id.
28    pub cc: u16,
29    /// Command id.
30    pub command: u8,
31    /// Payload after the command id.
32    pub payload: Vec<u8>,
33}
34
35/// Metadata of a command class.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub struct CcInfo {
38    /// Command class id.
39    pub id: u16,
40    /// Snake-case name.
41    pub name: &'static str,
42    /// Title.
43    pub title: &'static str,
44    /// Highest version the definitions cover.
45    pub version: u8,
46}
47
48/// The metadata for a command class id.
49pub fn cc_info(id: u16) -> Option<&'static CcInfo> {
50    COMMAND_CLASSES.iter().find(|c| c.id == id)
51}
52
53/// A command whose bytes do not match its definition.
54#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
55#[error("malformed command {cc:#04x}/{command:#04x}: {kind}")]
56pub struct ParseError {
57    /// Command class id.
58    pub cc: u16,
59    /// Command id.
60    pub command: u8,
61    /// What was wrong.
62    pub kind: ParseErrorKind,
63}
64
65/// What was wrong with a command.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
67pub enum ParseErrorKind {
68    /// The frame ended before a required field.
69    #[error("too short")]
70    TooShort,
71    /// A size field held something other than 0, 1, 2 or 4.
72    #[error("invalid size {0}")]
73    InvalidSize(u8),
74    /// No bytes at all.
75    #[error("empty frame")]
76    Empty,
77}
78
79impl Command {
80    /// Parses a command class frame: class id (two bytes from `0xF1`),
81    /// command id, payload. Unknown classes and commands come back as
82    /// [`Command::Unknown`].
83    pub fn parse(frame: &[u8]) -> Result<Command, ParseError> {
84        let err = |kind| ParseError {
85            cc: 0,
86            command: 0,
87            kind,
88        };
89        let (&first, rest) = frame.split_first().ok_or(err(ParseErrorKind::Empty))?;
90        if first == 0x00 {
91            return Ok(Command::NoOperation);
92        }
93        let (cc, rest) = if first >= 0xf1 {
94            let (&lo, rest) = rest.split_first().ok_or(err(ParseErrorKind::TooShort))?;
95            ((u16::from(first) << 8) | u16::from(lo), rest)
96        } else {
97            (u16::from(first), rest)
98        };
99        let Some((&command, payload)) = rest.split_first() else {
100            return Err(ParseError {
101                cc,
102                command: 0,
103                kind: ParseErrorKind::TooShort,
104            });
105        };
106        match Command::parse_known(cc, command, payload)? {
107            Some(c) => Ok(c),
108            None => Ok(Command::Unknown(RawCommand {
109                cc,
110                command,
111                payload: payload.to_vec(),
112            })),
113        }
114    }
115
116    /// Serializes the command: class id, command id, payload.
117    pub fn encode(&self) -> Vec<u8> {
118        let mut w = Vec::with_capacity(16);
119        if matches!(self, Command::NoOperation) {
120            w.push(0);
121            return w;
122        }
123        let cc = self.cc();
124        if cc > 0xff {
125            w.extend_from_slice(&cc.to_be_bytes());
126        } else {
127            w.push(cc as u8);
128        }
129        w.push(self.command_id());
130        self.encode_payload(&mut w);
131        w
132    }
133}
134
135/// Decodes a bit mask: bit `n` of the mask is value `n + offset`.
136pub fn decode_bitmask(mask: &[u8], offset: u16) -> Vec<u16> {
137    let mut v = Vec::new();
138    for (i, b) in mask.iter().enumerate() {
139        for bit in 0..8 {
140            if b & (1 << bit) != 0 {
141                v.push(offset + (i * 8 + bit) as u16);
142            }
143        }
144    }
145    v
146}
147
148/// Encodes values as a bit mask, the shortest that holds the largest.
149pub fn encode_bitmask(values: &[u16], offset: u16) -> Vec<u8> {
150    let Some(max) = values.iter().filter(|&&v| v >= offset).max() else {
151        return Vec::new();
152    };
153    let mut m = vec![0u8; usize::from(max - offset) / 8 + 1];
154    for &v in values.iter().filter(|&&v| v >= offset) {
155        let i = usize::from(v - offset);
156        m[i / 8] |= 1 << (i % 8);
157    }
158    m
159}
160
161/// Decodes a command class list (two-byte ids from `0xF1`), stopping at the
162/// `0xEF` mark that separates supported from controlled classes.
163pub fn decode_cc_list(p: &[u8]) -> Vec<u16> {
164    let mut v = Vec::new();
165    let mut i = 0;
166    while i < p.len() {
167        let b = p[i];
168        if b == 0xef {
169            break;
170        }
171        if b >= 0xf1 {
172            let Some(&lo) = p.get(i + 1) else { break };
173            v.push((u16::from(b) << 8) | u16::from(lo));
174            i += 2;
175        } else {
176            v.push(u16::from(b));
177            i += 1;
178        }
179    }
180    v
181}
182
183/// Encodes a command class list.
184pub fn encode_cc_list(ccs: &[u16], w: &mut Vec<u8>) {
185    for &cc in ccs {
186        if cc > 0xff {
187            w.extend_from_slice(&cc.to_be_bytes());
188        } else {
189            w.push(cc as u8);
190        }
191    }
192}
193
194/// Writes `v` as a big-endian integer of `size` bytes (0, 1, 2 or 4).
195pub fn write_sized(w: &mut Vec<u8>, v: i32, size: u8) {
196    let b = v.to_be_bytes();
197    match size {
198        1 => w.push(b[3]),
199        2 => w.extend_from_slice(&b[2..]),
200        4 => w.extend_from_slice(&b),
201        _ => {}
202    }
203}