1use bytes::{Buf, BufMut, BytesMut};
10use tokio_util::codec::{Decoder, Encoder};
11
12pub const SOF: u8 = 0x01;
14pub const ACK: u8 = 0x06;
16pub const NAK: u8 = 0x15;
18pub const CAN: u8 = 0x18;
20
21pub const MAX_PAYLOAD: usize = 255 - 3;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum FrameType {
27 Request,
29 Response,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct DataFrame {
36 pub kind: FrameType,
38 pub function: u8,
40 pub payload: Vec<u8>,
42}
43
44impl DataFrame {
45 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 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 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
85pub fn checksum(bytes: &[u8]) -> u8 {
87 bytes.iter().fold(0xff, |acc, b| acc ^ b)
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
92pub enum Frame {
93 Ack,
95 Nak,
97 Can,
99 Data(DataFrame),
101 Invalid,
103}
104
105impl Frame {
106 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#[derive(Debug, Default, Clone)]
125pub struct FrameCodec {
126 skipped: usize,
127}
128
129impl FrameCodec {
130 pub fn skipped(&self) -> usize {
132 self.skipped
133 }
134
135 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 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
212pub 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 let f = DataFrame::request(0x07u8, vec![]);
231 assert_eq!(f.encode(), vec![0x01, 0x03, 0x00, 0x07, 0xfb]);
232 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 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}