1use crate::{Error, Result};
13
14pub const ACK: u8 = 0xE5;
16const SHORT_START: u8 = 0x10;
17const LONG_START: u8 = 0x68;
18const STOP: u8 = 0x16;
19
20pub mod control {
22 pub const SND_NKE: u8 = 0x40;
24 pub const SND_UD: u8 = 0x53;
26 pub const REQ_UD2: u8 = 0x5B;
28 pub const FCB: u8 = 0x20;
30 pub const RSP_UD: u8 = 0x08;
32
33 pub const fn is_response(c: u8) -> bool {
36 c & 0xCF == RSP_UD
37 }
38}
39
40pub const BROADCAST: u8 = 0xFF;
42pub const NETWORK_LAYER: u8 = 0xFD;
44
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub enum Frame<'a> {
48 Ack,
50 Short {
52 c: u8,
54 a: u8,
56 },
57 Long {
59 c: u8,
61 a: u8,
63 ci: u8,
65 data: &'a [u8],
67 },
68}
69
70fn sum(bytes: &[u8]) -> u8 {
71 bytes.iter().fold(0u8, |s, &b| s.wrapping_add(b))
72}
73
74impl<'a> Frame<'a> {
75 pub fn parse(buf: &'a [u8]) -> Result<Option<(Self, usize)>> {
81 let Some(&start) = buf.first() else { return Ok(None) };
82 match start {
83 ACK => Ok(Some((Self::Ack, 1))),
84 SHORT_START => {
85 let Some(&[_, c, a, cs, stop]) = buf.get(..5).and_then(|s| <&[u8; 5]>::try_from(s).ok())
86 else {
87 return Ok(None);
88 };
89 check(sum(&[c, a]), cs, stop)?;
90 Ok(Some((Self::Short { c, a }, 5)))
91 }
92 LONG_START => {
93 let Some(&[_, l1, l2, s2]) = buf.get(..4).and_then(|s| <&[u8; 4]>::try_from(s).ok()) else {
94 return Ok(None);
95 };
96 if l1 != l2 || s2 != LONG_START || l1 < 3 {
97 return Err(Error::InvalidHeader);
98 }
99 let l = usize::from(l1);
100 let total = l + 6;
101 let Some(frame) = buf.get(..total) else { return Ok(None) };
102 let user = frame.get(4..4 + l).ok_or(Error::UnexpectedEnd)?;
103 let cs = frame.get(4 + l).copied().ok_or(Error::UnexpectedEnd)?;
104 let stop = frame.get(5 + l).copied().ok_or(Error::UnexpectedEnd)?;
105 check(sum(user), cs, stop)?;
106 let (&c, rest) = user.split_first().ok_or(Error::UnexpectedEnd)?;
107 let (&a, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
108 let (&ci, data) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
109 Ok(Some((Self::Long { c, a, ci, data }, total)))
110 }
111 other => Err(Error::InvalidStart(other)),
112 }
113 }
114
115 pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
117 match *self {
118 Self::Ack => {
119 *out.first_mut().ok_or(Error::OutputTooSmall)? = ACK;
120 Ok(1)
121 }
122 Self::Short { c, a } => {
123 let bytes = [SHORT_START, c, a, sum(&[c, a]), STOP];
124 out.get_mut(..5).ok_or(Error::OutputTooSmall)?.copy_from_slice(&bytes);
125 Ok(5)
126 }
127 Self::Long { c, a, ci, data } => {
128 let l = data.len().checked_add(3).filter(|&l| l <= 255).ok_or(Error::InvalidLength)?;
129 let total = l + 6;
130 let frame = out.get_mut(..total).ok_or(Error::OutputTooSmall)?;
131 let l8 = u8::try_from(l).map_err(|_| Error::InvalidLength)?;
132 let (head, rest) = frame.split_at_mut(7);
133 head.copy_from_slice(&[LONG_START, l8, l8, LONG_START, c, a, ci]);
134 let (body, tail) = rest.split_at_mut(data.len());
135 body.copy_from_slice(data);
136 let cs = sum(&[c, a, ci]).wrapping_add(sum(data));
137 tail.copy_from_slice(&[cs, STOP]);
138 Ok(total)
139 }
140 }
141 }
142}
143
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
146pub enum Scan<'a> {
147 Frame {
150 frame: Frame<'a>,
152 skip: usize,
154 len: usize,
156 },
157 NeedMore {
159 skip: usize,
161 },
162}
163
164pub fn scan(buf: &[u8]) -> Scan<'_> {
173 for start in 0..buf.len() {
174 let Some(rest) = buf.get(start..) else { break };
175 match Frame::parse(rest) {
176 Ok(Some((frame, len))) => return Scan::Frame { frame, skip: start, len },
177 Ok(None) => return Scan::NeedMore { skip: start },
178 Err(_) => {}
179 }
180 }
181 Scan::NeedMore { skip: buf.len() }
182}
183
184pub fn scan_ended(buf: &[u8]) -> Scan<'_> {
188 for start in 0..buf.len() {
189 if let Some(Ok(Some((frame, len)))) = buf.get(start..).map(Frame::parse) {
190 return Scan::Frame { frame, skip: start, len };
191 }
192 }
193 Scan::NeedMore { skip: buf.len() }
194}
195
196fn check(computed: u8, found: u8, stop: u8) -> Result<()> {
197 if computed != found {
198 return Err(Error::Checksum { computed, found });
199 }
200 if stop != STOP {
201 return Err(Error::MissingStop);
202 }
203 Ok(())
204}
205
206pub const fn snd_nke(address: u8) -> Frame<'static> {
208 Frame::Short { c: control::SND_NKE, a: address }
209}
210
211pub const fn req_ud2(address: u8, fcb: bool) -> Frame<'static> {
214 Frame::Short { c: control::REQ_UD2 | if fcb { control::FCB } else { 0 }, a: address }
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220
221 #[test]
222 fn short_frame_round_trip() {
223 let mut out = [0u8; 8];
224 let n = req_ud2(5, true).encode(&mut out).unwrap();
225 assert_eq!(&out[..n], &[0x10, 0x7B, 0x05, 0x80, 0x16]);
226 assert_eq!(Frame::parse(&out[..n]).unwrap(), Some((req_ud2(5, true), 5)));
227 }
228
229 #[test]
230 fn incomplete_frames_ask_for_more() {
231 let mut out = [0u8; 16];
232 let n = Frame::Long { c: 0x08, a: 1, ci: 0x72, data: &[1, 2, 3] }.encode(&mut out).unwrap();
233 for cut in 0..n {
234 assert_eq!(Frame::parse(&out[..cut]).unwrap(), None, "cut at {cut}");
235 }
236 assert!(Frame::parse(&out[..n]).unwrap().is_some());
237 }
238
239 #[test]
240 fn scan_skips_noise_and_false_starts() {
241 let mut buf = [0u8; 32];
242 let n = req_ud2(5, true).encode(&mut buf[3..]).unwrap();
243 buf[..3].copy_from_slice(&[0x00, 0x68, 0x42]); let all = &buf[..3 + n];
245 assert_eq!(scan(all), Scan::Frame { frame: req_ud2(5, true), skip: 3, len: 5 });
246 assert_eq!(scan(&all[..3 + 3]), Scan::NeedMore { skip: 3 });
248 assert_eq!(scan(&[0x00, 0x68, 0x05]), Scan::NeedMore { skip: 1 });
249 assert_eq!(scan(&[0x00, 0x01, 0x02]), Scan::NeedMore { skip: 3 });
250 assert_eq!(scan(&[]), Scan::NeedMore { skip: 0 });
251 let mut echo = [0u8; 6];
253 echo[..5].copy_from_slice(&all[3..]);
254 echo[5] = ACK;
255 assert_eq!(scan(&echo), Scan::Frame { frame: req_ud2(5, true), skip: 0, len: 5 });
256 let mut long = [0u8; 64];
258 let data =
259 [0x78, 0x56, 0x34, 0x12, 0x24, 0x40, 0x01, 0x07, 0x55, 0, 0, 0, 0x03, 0x13, 0xE5, 0x31, 0x00];
260 let n = Frame::Long { c: 0x08, a: 5, ci: 0x72, data: &data }.encode(&mut long).unwrap();
261 for cut in 1..n {
262 assert_eq!(scan(&long[..cut]), Scan::NeedMore { skip: 0 }, "cut {cut}");
263 }
264 assert!(matches!(scan(&long[..n]), Scan::Frame { skip: 0, .. }));
265 }
266
267 #[test]
268 fn bad_checksum_and_stop() {
269 assert!(matches!(Frame::parse(&[0x10, 0x5B, 0x01, 0x00, 0x16]), Err(Error::Checksum { .. })));
270 assert_eq!(Frame::parse(&[0x10, 0x5B, 0x01, 0x5C, 0x17]), Err(Error::MissingStop));
271 assert_eq!(Frame::parse(&[0x68, 0x05, 0x06, 0x68]), Err(Error::InvalidHeader));
272 assert_eq!(Frame::parse(&[0x42]), Err(Error::InvalidStart(0x42)));
273 }
274}