1use bytes::{Bytes, BytesMut};
4use eds_core::crc::get_crc;
5use eds_core::frame::*;
6
7const MAX_LEN: usize = 4096;
8
9enum Status {
11 Lead(u8),
12 Start,
13 Length1,
14 Length2,
15 Load,
16 Crc1,
17 Crc2,
18 End,
19 Finish,
20}
21
22pub struct Reader {
24 lead_len: u8,
25 load: BytesMut,
27 load_len: u16,
29 load_crc: u16,
31 status: Status,
33}
34impl Reader {
35 pub fn new(lead_len: u8) -> Self {
37 Reader {
38 lead_len,
39 load: BytesMut::new(),
40 load_len: 0,
41 load_crc: 0,
42 status: Status::Lead(0),
43 }
44 }
45 pub fn is_empty(&self) -> bool {
47 self.load.is_empty()
48 }
49 fn clean(&mut self) {
51 self.load.clear();
52 self.status = Status::Lead(0);
53 }
54 fn recv_one(&mut self, res: u8) -> bool {
56 match self.status {
57 Status::Lead(mut count) => {
58 if res == CHAR_LEAD {
59 count += 1;
60 if count >= self.lead_len {
61 self.status = Status::Start;
62 } else {
63 self.status = Status::Lead(count);
64 }
65 } else {
66 self.clean();
67 }
68 }
69 Status::Start => {
70 if res == CHAR_LEAD {
71 } else if res == CHAR_START {
72 self.status = Status::Length1;
73 } else {
74 self.clean();
75 }
76 }
77 Status::Length1 => {
78 self.load_len = (res as u16) << 8;
79 self.status = Status::Length2;
80 }
81 Status::Length2 => {
82 self.load_len |= res as u16;
83 if self.load_len as usize > MAX_LEN {
84 self.clean();
85 self.recv_one(res);
86 } else {
87 self.status = Status::Load;
88 }
89 }
90 Status::Load => {
91 let _ = self.load.extend([res]);
92 if self.load.len() >= self.load_len as usize {
93 self.load_crc = get_crc(&self.load);
94 self.status = Status::Crc1;
95 }
96 }
97 Status::Crc1 => {
98 if res == (self.load_crc >> 8) as u8 {
99 self.status = Status::Crc2;
100 } else {
101 self.clean();
102 self.recv_one(res);
103 }
104 }
105 Status::Crc2 => {
106 if res == self.load_crc as u8 {
107 self.status = Status::End;
108 } else {
109 self.clean();
110 self.recv_one(res);
111 }
112 }
113 Status::End => {
114 if res == CHAR_END {
115 self.status = Status::Finish;
116 return true;
117 } else {
118 self.clean();
119 self.recv_one(res);
120 }
121 }
122 Status::Finish => {
123 self.clean();
124 self.recv_one(res);
125 }
126 }
127 return false;
128 }
129 pub fn recv(&mut self, buf: &[u8]) -> usize {
131 for i in 0..buf.len() {
132 let res = buf[i];
133 let finish = self.recv_one(res);
134 if finish {
135 return i + 1;
136 }
137 }
138 return buf.len();
139 }
140 pub fn is_ready(&self) -> bool {
142 if let Status::Finish = self.status {
143 true
144 } else {
145 false
146 }
147 }
148 pub fn get_load(&mut self) -> Option<Bytes> {
150 if let Status::Finish = self.status {
151 let load = core::mem::replace(&mut self.load, BytesMut::new());
152 self.status = Status::Lead(0);
153 Some(load.freeze())
154 } else {
155 None
156 }
157 }
158}