Skip to main content

zwave_serial/
frame.rs

1//! Serial API frames.
2//!
3//! A data frame is `SOF LEN TYPE FUNC PAYLOAD.. CHECKSUM`, where `LEN` counts
4//! the bytes after itself (type, function, payload and checksum) and the
5//! checksum is `0xFF` XOR every byte from `LEN` to the end of the payload.
6//! Single-byte frames acknowledge (`ACK`), reject (`NAK`) or signal a
7//! collision (`CAN`).
8
9use bytes::{Buf, BufMut, BytesMut};
10use tokio_util::codec::{Decoder, Encoder};
11
12/// Start of frame.
13pub const SOF: u8 = 0x01;
14/// Acknowledge.
15pub const ACK: u8 = 0x06;
16/// Negative acknowledge (bad checksum or timeout on the receiver).
17pub const NAK: u8 = 0x15;
18/// Cancel: the receiver was sending a frame itself.
19pub const CAN: u8 = 0x18;
20
21/// Longest payload a frame can carry: LEN is one byte and counts type, function and checksum too.
22pub const MAX_PAYLOAD: usize = 255 - 3;
23
24/// Request (host to controller, or an unsolicited controller frame) or response.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum FrameType {
27    /// `0x00`: a request, a callback or an unsolicited frame.
28    Request,
29    /// `0x01`: the controller's response to a request.
30    Response,
31}
32
33/// A data frame.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct DataFrame {
36    /// Request or response.
37    pub kind: FrameType,
38    /// Function id.
39    pub function: u8,
40    /// Payload, at most [`MAX_PAYLOAD`] bytes.
41    pub payload: Vec<u8>,
42}
43
44impl DataFrame {
45    /// A request frame.
46    pub fn request(function: impl Into<u8>, payload: Vec<u8>) -> Self {
47        DataFrame {
48            kind: FrameType::Request,
49            function: function.into(),
50            payload,
51        }
52    }
53
54    /// A response frame.
55    pub fn response(function: impl Into<u8>, payload: Vec<u8>) -> Self {
56        DataFrame {
57            kind: FrameType::Response,
58            function: function.into(),
59            payload,
60        }
61    }
62
63    /// Serializes the frame. Panics if the payload exceeds [`MAX_PAYLOAD`],
64    /// which every builder in this crate rules out.
65    pub fn encode(&self) -> Vec<u8> {
66        assert!(
67            self.payload.len() <= MAX_PAYLOAD,
68            "Serial API payload too long"
69        );
70        let len = (self.payload.len() + 3) as u8;
71        let mut v = Vec::with_capacity(self.payload.len() + 5);
72        v.push(SOF);
73        v.push(len);
74        v.push(match self.kind {
75            FrameType::Request => 0x00,
76            FrameType::Response => 0x01,
77        });
78        v.push(self.function);
79        v.extend_from_slice(&self.payload);
80        v.push(checksum(&v[1..]));
81        v
82    }
83}
84
85/// The Serial API checksum over `LEN..=last payload byte`.
86pub fn checksum(bytes: &[u8]) -> u8 {
87    bytes.iter().fold(0xff, |acc, b| acc ^ b)
88}
89
90/// One unit on the wire.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub enum Frame {
93    /// ACK.
94    Ack,
95    /// NAK.
96    Nak,
97    /// CAN.
98    Can,
99    /// A data frame with a valid checksum.
100    Data(DataFrame),
101    /// A data frame whose checksum or type byte was wrong; answer with NAK.
102    Invalid,
103}
104
105impl Frame {
106    /// Serializes the frame (`Invalid` encodes as nothing).
107    pub fn encode(&self) -> Vec<u8> {
108        match self {
109            Frame::Ack => vec![ACK],
110            Frame::Nak => vec![NAK],
111            Frame::Can => vec![CAN],
112            Frame::Data(d) => d.encode(),
113            Frame::Invalid => vec![],
114        }
115    }
116}
117
118/// Streaming codec for Serial API frames.
119///
120/// Bytes that cannot start a frame are skipped. A data frame whose length
121/// byte is below the minimum is skipped as noise. A frame that is still
122/// incomplete is kept until more bytes arrive; the caller's read timeout
123/// decides when a partial frame is abandoned (see [`FrameCodec::reset`]).
124#[derive(Debug, Default, Clone)]
125pub struct FrameCodec {
126    skipped: usize,
127}
128
129impl FrameCodec {
130    /// Bytes skipped as noise so far.
131    pub fn skipped(&self) -> usize {
132        self.skipped
133    }
134
135    /// Drops a partial frame from `buf` (the receive timeout expired mid-frame).
136    pub fn reset(&mut self, buf: &mut BytesMut) {
137        self.skipped += buf.len();
138        buf.clear();
139    }
140}
141
142impl Decoder for FrameCodec {
143    type Item = Frame;
144    type Error = std::io::Error;
145
146    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Frame>, std::io::Error> {
147        loop {
148            let Some(&first) = buf.first() else {
149                return Ok(None);
150            };
151            match first {
152                ACK => {
153                    buf.advance(1);
154                    return Ok(Some(Frame::Ack));
155                }
156                NAK => {
157                    buf.advance(1);
158                    return Ok(Some(Frame::Nak));
159                }
160                CAN => {
161                    buf.advance(1);
162                    return Ok(Some(Frame::Can));
163                }
164                SOF => {
165                    let Some(&len) = buf.get(1) else {
166                        return Ok(None);
167                    };
168                    let len = len as usize;
169                    if len < 3 {
170                        // Not a frame; resynchronize on the next byte.
171                        buf.advance(1);
172                        self.skipped += 1;
173                        continue;
174                    }
175                    if buf.len() < len + 2 {
176                        buf.reserve(len + 2 - buf.len());
177                        return Ok(None);
178                    }
179                    let raw = buf.split_to(len + 2);
180                    let kind = match raw[2] {
181                        0x00 => FrameType::Request,
182                        0x01 => FrameType::Response,
183                        _ => return Ok(Some(Frame::Invalid)),
184                    };
185                    if checksum(&raw[1..len + 1]) != raw[len + 1] {
186                        return Ok(Some(Frame::Invalid));
187                    }
188                    return Ok(Some(Frame::Data(DataFrame {
189                        kind,
190                        function: raw[3],
191                        payload: raw[4..len + 1].to_vec(),
192                    })));
193                }
194                _ => {
195                    buf.advance(1);
196                    self.skipped += 1;
197                }
198            }
199        }
200    }
201}
202
203impl Encoder<Frame> for FrameCodec {
204    type Error = std::io::Error;
205
206    fn encode(&mut self, item: Frame, dst: &mut BytesMut) -> Result<(), std::io::Error> {
207        dst.put_slice(&item.encode());
208        Ok(())
209    }
210}
211
212/// Decodes every complete frame in `bytes` (for tests and fuzzing).
213pub fn decode_all(bytes: &[u8]) -> Vec<Frame> {
214    let mut codec = FrameCodec::default();
215    let mut buf = BytesMut::from(bytes);
216    let mut out = Vec::new();
217    while let Ok(Some(f)) = codec.decode(&mut buf) {
218        out.push(f);
219    }
220    out
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn known_frames() {
229        // GetSerialApiCapabilities request, as every host sends it.
230        let f = DataFrame::request(0x07u8, vec![]);
231        assert_eq!(f.encode(), vec![0x01, 0x03, 0x00, 0x07, 0xfb]);
232        // GetControllerId response: home id 0xC0FFEE01, node 1.
233        let r = DataFrame::response(0x20u8, vec![0xc0, 0xff, 0xee, 0x01, 0x01]);
234        let enc = r.encode();
235        assert_eq!(decode_all(&enc), vec![Frame::Data(r)]);
236    }
237
238    #[test]
239    fn noise_partial_and_bad_checksum() {
240        let good = DataFrame::request(0x04u8, vec![0x00, 0x02, 0x03, 0x25, 0x03, 0xff]).encode();
241        let mut bad = good.clone();
242        let last = bad.len() - 1;
243        bad[last] ^= 0xff;
244        let mut stream = vec![0x42, 0x00, SOF, 0x02];
245        stream.extend_from_slice(&[ACK, NAK, CAN]);
246        stream.extend_from_slice(&bad);
247        stream.extend_from_slice(&good);
248        let frames = decode_all(&stream);
249        assert_eq!(frames.len(), 5);
250        assert_eq!(frames[0], Frame::Ack);
251        assert_eq!(frames[3], Frame::Invalid);
252        assert!(matches!(frames[4], Frame::Data(_)));
253
254        // A partial frame waits for more bytes.
255        let mut codec = FrameCodec::default();
256        let mut buf = BytesMut::from(&good[..4]);
257        assert_eq!(codec.decode(&mut buf).unwrap(), None);
258        buf.extend_from_slice(&good[4..]);
259        assert!(matches!(
260            codec.decode(&mut buf).unwrap(),
261            Some(Frame::Data(_))
262        ));
263    }
264
265    #[test]
266    fn bad_type_byte_is_invalid() {
267        let mut raw = DataFrame::request(0x04u8, vec![1]).encode();
268        raw[2] = 0x07;
269        let n = raw.len() - 1;
270        raw[n] = checksum(&raw[1..n]);
271        assert_eq!(decode_all(&raw), vec![Frame::Invalid]);
272    }
273}