| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- /* XMODEM receiver: 128-byte packets, 1-byte checksum. */
- #include "serial.h"
- #include "timer.h"
- #include "xmodem.h"
- #define SOH 0x01
- #define EOT 0x04
- #define ACK 0x06
- #define NAK 0x15
- #define CAN 0x18
- #define PACKET_HEADER 2 /* block number, 255-block (SOH already consumed) */
- #define PACKET_PAYLOAD 128
- #define PACKET_CSUM 1
- #define NAK_INTERVAL_MS 1000
- #define RECV_TIMEOUT_MS 3000
- static int get_byte(unsigned int timeout_ms)
- {
- return serial_getchar(timeout_ms);
- }
- static void send_byte(unsigned char b)
- {
- serial_putchar((char)b);
- }
- int xmodem_receive(void *buf, unsigned int max_len)
- {
- unsigned char *dst = (unsigned char *)buf;
- unsigned int total = 0;
- unsigned char block_num = 1;
- unsigned int last_nak = 0;
- /* Send NAK repeatedly until we get SOH (start of first packet) or EOT (empty file). */
- for (;;) {
- unsigned int now = get_ticks_ms();
- if (now - last_nak >= NAK_INTERVAL_MS) {
- send_byte(NAK);
- last_nak = now;
- }
- {
- int c = get_byte(100);
- if (c < 0)
- continue;
- if (c == EOT) {
- send_byte(ACK);
- return 0;
- }
- if (c == SOH)
- break;
- if (c == CAN)
- return -1;
- }
- }
- for (;;) {
- unsigned char header[PACKET_HEADER];
- unsigned char payload[PACKET_PAYLOAD];
- unsigned char csum;
- unsigned int i;
- unsigned char sum = 0;
- for (i = 0; i < PACKET_HEADER; i++) {
- int c = get_byte(RECV_TIMEOUT_MS);
- if (c < 0)
- return -1;
- header[i] = (unsigned char)c;
- }
- for (i = 0; i < PACKET_PAYLOAD; i++) {
- int c = get_byte(RECV_TIMEOUT_MS);
- if (c < 0)
- return -1;
- payload[i] = (unsigned char)c;
- sum += payload[i];
- }
- {
- int c = get_byte(RECV_TIMEOUT_MS);
- if (c < 0)
- return -1;
- csum = (unsigned char)c;
- }
- if (header[0] != block_num || header[1] != (unsigned char)(255 - block_num)) {
- send_byte(NAK);
- continue;
- }
- if (csum != sum) {
- send_byte(NAK);
- continue;
- }
- /* Copy payload; respect max_len. */
- for (i = 0; i < PACKET_PAYLOAD && total < max_len; i++, total++)
- dst[total] = payload[i];
- send_byte(ACK);
- block_num++;
- /* Next: expect another SOH or EOT. */
- {
- int c = get_byte(RECV_TIMEOUT_MS);
- if (c < 0)
- return -1;
- if (c == EOT) {
- send_byte(ACK);
- return (int)total;
- }
- if (c == CAN)
- return -1;
- if (c != SOH) {
- /* Unexpected; treat as abort. */
- return -1;
- }
- }
- }
- }
|