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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
use std::io::{Read, Write};
pub use xymodem_util::*;
// TODO: Send CAN byte after too many errors
// TODO: Handle CAN bytes while sending
// TODO: Implement Error for Error
const SOH: u8 = 0x01;
const STX: u8 = 0x02;
const EOT: u8 = 0x04;
const ACK: u8 = 0x06;
const NAK: u8 = 0x15;
const CAN: u8 = 0x18;
const CRC: u8 = 0x43;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Copy, Clone, Debug)]
pub enum Checksum {
Standard,
CRC16,
}
#[derive(Copy, Clone, Debug)]
pub enum BlockLength {
Standard = 128,
OneK = 1024,
}
/// Configuration for the XMODEM transfer.
#[derive(Copy, Clone, Debug)]
pub struct Xmodem {
/// The number of errors that can occur before the communication is
/// considered a failure. Errors include unexpected bytes and timeouts waiting for bytes.
pub max_errors: u32,
/// The number of errors that can occur before the communication is
/// considered a failure. Errors include unexpected bytes and timeouts waiting for bytes.
///
/// This only applies to the initial packet
pub max_initial_errors: u32,
/// The byte used to pad the last block. XMODEM can only send blocks of a certain size,
/// so if the message is not a multiple of that size the last block needs to be padded.
pub pad_byte: u8,
/// The length of each block. There are only two options: 128-byte blocks (standard
/// XMODEM) or 1024-byte blocks (XMODEM-1k).
pub block_length: BlockLength,
/// The checksum mode used by XMODEM. This is determined by the receiver.
checksum_mode: Checksum,
errors: u32,
initial_errors: u32,
}
impl Xmodem {
/// Creates the XMODEM config with default parameters.
pub fn new() -> Self {
Xmodem {
max_errors: 16,
max_initial_errors: 16,
pad_byte: 0x1a,
block_length: BlockLength::Standard,
checksum_mode: Checksum::Standard,
errors: 0,
initial_errors: 0,
}
}
/// Starts the XMODEM transmission.
///
/// `dev` should be the serial communication channel (e.g. the serial device).
/// `stream` should be the message to send (e.g. a file).
///
/// # Timeouts
/// This method has no way of setting the timeout of `dev`, so it's up to the caller
/// to set the timeout of the device before calling this method. Timeouts on receiving
/// bytes will be counted against `max_errors`, but timeouts on transmitting bytes
/// will be considered a fatal error.
pub fn send<D: Read + Write, R: Read>(&mut self, dev: &mut D, stream: &mut R) -> Result<()> {
self.errors = 0;
dbg!("Starting XMODEM transfer");
(self.start_send(dev))?;
dbg!("First byte received. Sending stream.");
(self.send_stream(dev, stream))?;
dbg!("Sending EOT");
(self.finish_send(dev))?;
Ok(())
}
/// Receive an XMODEM transmission.
///
/// `dev` should be the serial communication channel (e.g. the serial device).
/// The received data will be written to `outstream`.
/// `checksum` indicates which checksum mode should be used; Checksum::Standard is
/// a reasonable default.
///
/// # Timeouts
/// This method has no way of setting the timeout of `dev`, so it's up to the caller
/// to set the timeout of the device before calling this method. Timeouts on receiving
/// bytes will be counted against `max_errors`, but timeouts on transmitting bytes
/// will be considered a fatal error.
pub fn recv<D: Read + Write, W: Write>(
&mut self,
dev: &mut D,
outstream: &mut W,
checksum: Checksum,
) -> Result<()> {
self.errors = 0;
self.checksum_mode = checksum;
let mut handled_first_packet = false;
dbg!("Starting XMODEM receive");
let first_char;
loop {
(dev.write(&[match self.checksum_mode {
Checksum::Standard => NAK,
Checksum::CRC16 => CRC,
}])?);
match get_byte_timeout(dev)? {
bt @ Some(SOH) | bt @ Some(STX) => {
// The first SOH or STX is used to initialize the transfer
first_char = bt.unwrap();
break;
}
_ => {
self.initial_errors += 1;
if self.initial_errors > self.max_initial_errors {
eprint!(
"Exhausted max retries ({}) while waiting for SOH or STX",
self.max_initial_errors
);
return Err(Error::ExhaustedRetries);
}
}
}
}
dbg!("NCG sent. Receiving stream.");
let mut packet_num: u8 = 1;
loop {
match if handled_first_packet {
get_byte_timeout(dev)?
} else {
Some(first_char)
} {
bt @ Some(SOH) | bt @ Some(STX) => {
handled_first_packet = true;
// Handle next packet
let packet_size = match bt {
Some(SOH) => 128,
Some(STX) => 1024,
_ => 0, // Why does the compiler need this?
};
let pnum = (get_byte(dev))?; // specified packet number
let pnum_1c = (get_byte(dev))?; // same, 1's complemented
// We'll respond with cancel later if the packet number is wrong
let cancel_packet = packet_num != pnum || (255 - pnum) != pnum_1c;
let mut data: Vec<u8> = Vec::new();
data.resize(packet_size, 0);
(dev.read_exact(&mut data))?;
let success = match self.checksum_mode {
Checksum::Standard => {
let recv_checksum = (get_byte(dev))?;
calc_checksum(&data) == recv_checksum
}
Checksum::CRC16 => {
let recv_checksum =
(((get_byte(dev))? as u16) << 8) + (get_byte(dev))? as u16;
calc_crc(&data) == recv_checksum
}
};
if cancel_packet {
(dev.write(&[CAN]))?;
(dev.write(&[CAN]))?;
return Err(Error::Canceled);
}
if success {
packet_num = packet_num.wrapping_add(1);
(dev.write(&[ACK]))?;
(outstream.write_all(&data))?;
} else {
(dev.write(&[NAK]))?;
self.errors += 1;
}
}
Some(EOT) => {
// End of file
(dev.write(&[ACK]))?;
break;
}
Some(_) => {
warn!("Unrecognized symbol!");
}
None => {
if !handled_first_packet {
self.errors = self.max_errors;
} else {
self.errors += 1;
}
warn!("Timeout!")
}
}
if self.errors >= self.max_errors {
eprint!(
"Exhausted max retries ({}) while waiting for ACK for EOT",
self.max_errors
);
return Err(Error::ExhaustedRetries);
}
}
Ok(())
}
fn start_send<D: Read + Write>(&mut self, dev: &mut D) -> Result<()> {
let mut cancels = 0u32;
loop {
match (get_byte_timeout(dev))? {
Some(c) => match c {
NAK => {
dbg!("Standard checksum requested");
self.checksum_mode = Checksum::Standard;
return Ok(());
}
CRC => {
dbg!("16-bit CRC requested");
self.checksum_mode = Checksum::CRC16;
return Ok(());
}
CAN => {
warn!("Cancel (CAN) byte received");
cancels += 1;
}
c => warn!("Unknown byte received at start of XMODEM transfer: {}", c),
},
None => warn!("Timed out waiting for start of XMODEM transfer."),
}
self.errors += 1;
if cancels >= 2 {
eprint!(
"Transmission canceled: received two cancel (CAN) bytes \
at start of XMODEM transfer"
);
return Err(Error::Canceled);
}
if self.errors >= self.max_errors {
eprint!(
"Exhausted max retries ({}) at start of XMODEM transfer.",
self.max_errors
);
if let Err(err) = dev.write_all(&[CAN]) {
warn!("Error sending CAN byte: {}", err);
}
return Err(Error::ExhaustedRetries);
}
}
}
fn send_stream<D: Read + Write, R: Read>(&mut self, dev: &mut D, stream: &mut R) -> Result<()> {
let mut block_num = 0u32;
loop {
let mut buff = vec![self.pad_byte; self.block_length as usize + 3];
let n = (stream.read(&mut buff[3..]))?;
if n == 0 {
dbg!("Reached EOF");
return Ok(());
}
block_num += 1;
buff[0] = match self.block_length {
BlockLength::Standard => SOH,
BlockLength::OneK => STX,
};
buff[1] = (block_num & 0xFF) as u8;
buff[2] = 0xFF - buff[1];
match self.checksum_mode {
Checksum::Standard => {
let checksum = calc_checksum(&buff[3..]);
buff.push(checksum);
}
Checksum::CRC16 => {
let crc = calc_crc(&buff[3..]);
buff.push(((crc >> 8) & 0xFF) as u8);
buff.push((crc & 0xFF) as u8);
}
}
dbg!("Sending block {}", block_num);
(dev.write_all(&buff))?;
match (get_byte_timeout(dev))? {
Some(c) => {
if c == ACK {
dbg!("Received ACK for block {}", block_num);
continue;
} else {
warn!("Expected ACK, got {}", c);
}
// TODO handle CAN bytes
}
None => warn!("Timeout waiting for ACK for block {}", block_num),
}
self.errors += 1;
if self.errors >= self.max_errors {
eprint!(
"Exhausted max retries ({}) while sending block {} in XMODEM transfer",
self.max_errors, block_num
);
return Err(Error::ExhaustedRetries);
}
}
}
fn finish_send<D: Read + Write>(&mut self, dev: &mut D) -> Result<()> {
loop {
(dev.write_all(&[EOT]))?;
match (get_byte_timeout(dev))? {
Some(c) => {
if c == ACK {
info!("XMODEM transmission successful");
return Ok(());
} else {
warn!("Expected ACK, got {}", c);
}
}
None => warn!("Timeout waiting for ACK for EOT"),
}
self.errors += 1;
if self.errors >= self.max_errors {
eprint!(
"Exhausted max retries ({}) while waiting for ACK for EOT",
self.max_errors
);
return Err(Error::ExhaustedRetries);
}
}
}
}