-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
315 lines (271 loc) · 9.53 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#![cfg_attr(not(any(feature = "std", test)), no_std)]
use core::fmt::Debug;
use constants::{CharBufferId, Commands, ConfirmationCode, PackageIdentifier};
use embedded_io_async::{ErrorType, Read, ReadExactError, Write};
use wire_traits::{FromWire, ToWire};
pub mod constants;
pub mod wire_traits;
//////////////////////////////////////////////////////////////////////////////
// Error
//////////////////////////////////////////////////////////////////////////////
pub enum Error<S>
where
S: ErrorType,
{
Wire(S::Error),
IncorrectData,
EndOfFile,
BadConfirmation(ConfirmationCode),
}
impl<S> Debug for Error<S>
where
S: ErrorType,
S::Error: Debug,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Error::Wire(w) => {
f.write_str("Error::Wire(")?;
f.write_fmt(format_args!("{w:?}"))?;
f.write_str(")")?;
Ok(())
}
Error::IncorrectData => f.write_str("Error::IncorrectData"),
Error::EndOfFile => f.write_str("Error::EndOfFile"),
Error::BadConfirmation(c) => {
f.write_str("Error::BadConfirmation(")?;
f.write_fmt(format_args!("{c:?}"))?;
f.write_str(")")?;
Ok(())
}
}
}
}
//////////////////////////////////////////////////////////////////////////////
// Command Packet Type
//////////////////////////////////////////////////////////////////////////////
pub struct Command<T: ToWire> {
address: u32,
instruction: Commands,
body: T,
}
impl<T: ToWire> Command<T> {
pub async fn to_wire<S>(&self, serial: &mut S) -> Result<(), Error<S>>
where
S: Read + Write + ErrorType,
{
// Header
0xEF01u16.to_wire(serial, None).await?;
// Adder
self.address.to_wire(serial, None).await?;
// CRC starts here!
let mut crc = Checksum::new();
// Package Identifier
PackageIdentifier::CommandPacket
.to_wire(serial, Some(&mut crc))
.await?;
// length
let blen = self.body.size_on_wire();
// command + CRC
((3 + blen) as u16).to_wire(serial, Some(&mut crc)).await?;
// command
self.instruction.to_wire(serial, Some(&mut crc)).await?;
// body (optional)
self.body.to_wire(serial, Some(&mut crc)).await?;
// CRC
crc.finalize().to_wire(serial, None).await?;
Ok(())
}
}
//////////////////////////////////////////////////////////////////////////////
// Acknowledge Packet Type
//////////////////////////////////////////////////////////////////////////////
pub struct Response<T> {
address: u32,
ident: u8,
confirmation: ConfirmationCode,
body: T,
}
impl<T> Response<T> {
pub async fn from_wire<S: ErrorType + Read>(serial: &mut S) -> Result<Self, Error<S>>
where
T: FromWire,
{
// Do we have the right header?
let hdr = u16::from_wire(serial, None).await?;
if hdr != 0xEF01 {
return Err(Error::IncorrectData);
}
let address = u32::from_wire(serial, None).await?;
// The remaining bits are checksum relevant!
let mut cksm = Checksum::new();
let ident = u8::from_wire(serial, Some(&mut cksm)).await?;
// TODO: check len?
let _len = u16::from_wire(serial, Some(&mut cksm)).await?;
let confirmation = ConfirmationCode::from_wire(serial, Some(&mut cksm)).await?;
let body = T::from_wire(serial, Some(&mut cksm)).await?;
let calc_cksm = cksm.finalize();
let rept_cksm = u16::from_wire(serial, None).await?;
if calc_cksm != rept_cksm {
return Err(Error::IncorrectData);
}
Ok(Self {
address,
ident,
confirmation,
body,
})
}
}
//////////////////////////////////////////////////////////////////////////////
// Checksum Handler
//////////////////////////////////////////////////////////////////////////////
pub struct Checksum {
state: u16,
}
impl Checksum {
pub fn new() -> Self {
Self { state: 0 }
}
pub fn update(&mut self, data: &[u8]) {
data.iter().copied().for_each(|b| {
self.state = self.state.wrapping_add(b.into());
});
}
pub fn finalize(self) -> u16 {
self.state
}
}
impl Default for Checksum {
fn default() -> Self {
Self::new()
}
}
//////////////////////////////////////////////////////////////////////////////
// R503
//////////////////////////////////////////////////////////////////////////////
pub struct R503 {
address: u32,
}
impl R503 {
pub fn new_with_address(addr: u32) -> Self {
Self { address: addr }
}
pub async fn stream_image<S: Read + ErrorType>(
&self,
serial: &mut S,
out_buf: &mut [u8],
) -> Result<usize, Error<S>> {
let mut more = true;
let ttl_len = out_buf.len();
let mut window = out_buf;
while more {
// Do we have the right header?
let hdr = u16::from_wire(serial, None).await?;
if hdr != 0xEF01 {
return Err(Error::IncorrectData);
}
let address = u32::from_wire(serial, None).await?;
if address != self.address {
return Err(Error::IncorrectData);
}
// The remaining bits are checksum relevant!
let mut cksm = Checksum::new();
let ident = u8::from_wire(serial, Some(&mut cksm)).await?;
match ident {
0x02 => {
// "Have following packet"
}
0x08 => {
// "end packet"
more = false;
}
_ => return Err(Error::IncorrectData),
}
let len = u16::from_wire(serial, Some(&mut cksm)).await?;
if len < 2 {
return Err(Error::IncorrectData);
}
let len_img = (len - 2) as usize;
if window.len() < len_img {
// TODO better error
return Err(Error::IncorrectData);
}
let (now, later) = window.split_at_mut(len_img);
window = later;
match serial.read_exact(now).await {
Ok(()) => {}
Err(ReadExactError::UnexpectedEof) => return Err(Error::EndOfFile),
Err(ReadExactError::Other(w)) => return Err(Error::Wire(w)),
};
cksm.update(now);
let calc_cksm = cksm.finalize();
let rept_cksm = u16::from_wire(serial, None).await?;
if calc_cksm != rept_cksm {
return Err(Error::IncorrectData);
}
}
let used = ttl_len - window.len();
Ok(used)
}
}
// Helper macro for implementing basic Command + Acknowledge patterns.
//
// Items can optionally take send or receive payloads, though they need to
// be "owned" items, so not good for streaming.
macro_rules! cmds_with_ack {
(
| Function | Code | CmdDataTy | RespDataTy |
| $(-)* | $(-)* | $(-)* | $(-)* |
$( | $func:ident | $code:ident | $($cdt:ty)? | $($rdy:ty)? | )*
) => {
$(
#[allow(unused_parens)]
pub async fn $func<S>(&self, serial: &mut S, $(arg: $cdt)?) -> Result<($($rdy)?), Error<S>>
where
S: Read + Write + ErrorType,
{
// Send the command
//
let cmd = Command {
address: self.address,
instruction: Commands::$code,
body: {
let _body = ();
$(
let _body: $cdt = arg;
)?
_body
},
};
cmd.to_wire(serial).await?;
// Receive the data
// TODO: Timeout?
let resp = Response::<($($rdy)?)>::from_wire(serial).await?;
let mut good = true;
good &= resp.address == self.address;
good &= resp.ident == PackageIdentifier::AcknowledgePacket.into();
if !good {
return Err(Error::IncorrectData);
}
if resp.confirmation != ConfirmationCode::SuccessCode {
return Err(Error::BadConfirmation(resp.confirmation));
}
Ok(resp.body)
}
)*
};
}
impl R503 {
cmds_with_ack! {
| Function | Code | CmdDataTy | RespDataTy |
| -------- | ---- | --------- | ---------- |
| get_rand_code | GetRandomCode | | u32 |
| read_system_parameter | ReadSystemParameter | | [u8; 16] |
| get_image | GetImage | | |
| upload_image | UpImage | | |
| generate_char | GenChar | CharBufferId | |
| generate_template | RegModel | | |
| upload_template | UpChar | CharBufferId | |
}
}