-
Notifications
You must be signed in to change notification settings - Fork 0
/
xmodem.ino
121 lines (102 loc) · 1.88 KB
/
xmodem.ino
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
/**
* \file xmodem protocol
*
* Using USB serial
*/
#include "xmodem.h"
/** Send a block.
* Compute the checksum and complement.
*
* \return 0 if all is ok, -1 if a cancel is requested or more
* than 10 retries occur.
*/
int
xmodem_send(
xmodem_block_t * const block,
int wait_for_ack
)
{
// Compute the checksum and complement
uint8_t cksum = 0;
uint8_t i;
for (i = 0 ; i < sizeof(block->data) ; i++)
cksum += block->data[i];
block->cksum = cksum;
block->block_num++;
block->block_num_complement = 0xFF - block->block_num;
// Send the block, and wait for an ACK
uint8_t retry_count = 0;
while (retry_count++ < 10)
{
Serial.write((const uint8_t*) block, sizeof(*block));
Serial.send_now();
// Wait for an ACK (done), CAN (abort) or NAK (retry)
while (1)
{
const int c = Serial.read();
if (c == -1)
continue;
if (c == XMODEM_ACK)
return 0;
if (c == XMODEM_CAN)
return -1;
if (c == XMODEM_NAK)
break;
if (!wait_for_ack)
return 0;
}
}
// Failure or cancel
return -1;
}
int
xmodem_init(
xmodem_block_t * const block,
int already_received_first_nak
)
{
block->soh = 0x01;
block->block_num = 0x00;
if (already_received_first_nak)
return 0;
// wait for initial nak
while (1)
{
const int c = Serial.read();
if (c == -1)
continue;
if (c == XMODEM_NAK)
return 0;
if (c == XMODEM_CAN)
return -1;
}
}
int
xmodem_fini(
xmodem_block_t * const block
)
{
#if 0
/* Don't send EOF? rx adds it to the file? */
block->block_num++;
memset(block->data, XMODEM_EOF, sizeof(block->data));
if (xmodem_send_block(block) < 0)
return;
#endif
// File transmission complete. send an EOT
// wait for an ACK or CAN
while (1)
{
Serial.print((char) XMODEM_EOT);
while (1)
{
const int c = Serial.read();
if (c == -1)
continue;
if (c == XMODEM_ACK)
return 0;
if (c == XMODEM_CAN)
return -1;
}
}
}