summaryrefslogtreecommitdiff
path: root/upload.c
blob: 36434ac772da2c77425869c0acd0b4beb5a03d13 (plain)
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
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>

#include <getopt.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <search.h>
#include <errno.h>

#define PACKET_SIZE 8

#define LEN(x) (sizeof(x) / sizeof(x[0]))

typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;
typedef unsigned long long ulonglong;

enum verbose_level {
    NONE,
    DEBUG,
    WARNING,
    ERROR
};

// in bootloader spam \n or anything? until some buffer is full

speed_t baud = 0;
char port[32] = {0};
int serial_fd = -1;
FILE *file = NULL;
const char *flush = "aaaaaaaaaaaaa\n";
int verbose = 0;

void help()
{
    puts("help");
    exit(EXIT_SUCCESS);
}

void die()
{
    if (file)
        fclose(file);
    if (serial_fd < 0)
        close(serial_fd);
    exit(EXIT_FAILURE);
}

int log_msg(int lvl, const char *fmt, ...)
{
    int ret = 0;
    va_list args;
    if (verbose >= lvl) {
        va_start(args, fmt);
        ret = vprintf(fmt, args);
        fflush(stdout);
        va_end(args);
    }
    return ret;
}

struct baud_pair {
    const char *b;
    speed_t c;
};

// Conversion table for baud rates
const struct baud_pair baud_rates[] = {
    {"1200",  B1200},
    {"2400",  B2400},
    {"4800",  B4800},
    {"9600",  B9600},
    {"19200", B19200},
};

int parse_argv(int argc, char *const argv[])
{
    struct option long_opts[] = {
        { "baud",    required_argument, 0, 'b'},
        { "verbose", no_argument,       0, 'v'},
        { "port",    required_argument, 0, 'p'},
        { "help",    no_argument,       0, 'h'},
        {      0,    0,                 0, 0  }
    };

    int long_index = 0;
    int c;

    while ((c = getopt_long(argc, argv, "b:p:h",
                            long_opts, &long_index)) != -1) {
        switch (c) {
        case 'b':
            for (int i = 0; i < LEN(baud_rates); i++) {
                if (!strcmp(baud_rates[i].b, optarg)) {
                    baud = baud_rates[i].c;
                    break;
                }
            }

            if (baud == 0) {
                fprintf(stderr, "Error: Invalid baud rate '%s'\n", optarg);
                exit(EXIT_FAILURE);
            }
            break;

        case 'v':
            verbose = 1;
            break;

        case 'p':
            strncpy(port, optarg, LEN(port));
            break;

        case 'h':
            help();
            break;

        case '?':
            help();
            break;

        default:
            break;
        }
    }

    if (argc <= optind) {
        fprintf(stderr, "Error: No file was provided to upload\n\n");
        help();
    }

    return optind;
}

int open_tty(const char *port)
{
    int fd = open(port, O_RDWR);

    if (fd < 0) {
        fprintf(stderr, "Error: Port '%s' could not be opened\n", port);
        exit(EXIT_FAILURE);
    }

    struct termios term;
    tcgetattr(fd, &term);

    cfmakeraw(&term);
    term.c_cc[VTIME] = 1;
    term.c_cc[VMIN] = 0;
    term.c_lflag &= ~OCRNL;
    cfsetspeed(&term, baud);

    tcsetattr(fd, TCSANOW, &term);

    return fd;
}

ssize_t read_line(int fd, uchar *buf, size_t len)
{
    int ret = 0;
    ssize_t bytes_read = 0;

    // The Serial port runs at ~9600 baud. This loop, as inefficient as it is,
    // won' t ever be a bottleneck
    for (int i = 0; bytes_read < len; i++) {
        ssize_t rd = read(fd, &buf[bytes_read], 1);
        if (rd < 0) {
            fprintf(stderr, "Error: read from port failed\n%s\n",
                    strerror(errno));
            die();
        }

        if (rd == 0)
            return -1;

        bytes_read += rd;
        if (buf[bytes_read - 1] == '\n')
            break;
    }

    buf[bytes_read] = 0;
    return bytes_read;
}

void flush_bootloader(int serial_fd)
{
    /* Clean up */
    // tcflush(serial_fd, TCIOFLUSH);
    /* Send empty line to get a ready prompt from bootloader */
    write(serial_fd, flush, strlen(flush));
    tcdrain(serial_fd);
}

/*
 * Get the bootloader in a ready state, cleaning up any previous errors
 */
void begin_command(int serial_fd)
{
    char buf[32];
    int timeout = 1;

    buf[0] = 0;

    while (timeout) {
        /* Comparing should stop after \n even if buf is undefined */
        while (strcmp("ready\r\n", buf) != 0) {
            if (read_line(serial_fd, buf, LEN(buf)) < 0) {
                timeout = 1;
                log_msg(DEBUG, "timeout\n%32s\n", buf);
                flush_bootloader(serial_fd);
                break;
            } else {
                timeout = 0;
            }
        }
    }
}

void send_packet(int index, uint address, int plen, const uchar *packet)
{
    char obuf[128];
    int len = sprintf(obuf, "W %04X %02X ", address, plen);

    for (int i = 0; i < plen; i++)
        len += sprintf(&obuf[len], "%02X", packet[i]);

    obuf[len++] = '\r';
    obuf[len++] = '\n';
    obuf[len] = '\0';

    int cmp = 1;
    char ibuf[128];
    char ebuf[128];

    for (int attempt = 1; cmp != 0; attempt++) {
        log_msg(DEBUG, "Sending packet %d, attempt %d\n", index, attempt);

        begin_command(serial_fd);
        write(serial_fd, obuf, len);

        if((read_line(serial_fd, ibuf, LEN(ibuf)) == -1)
           || (read_line(serial_fd, ebuf, LEN(ebuf)) == -1)) {
            continue;
        }

        log_msg(DEBUG, "sent: %s", obuf);
        log_msg(DEBUG, "recv: %s", ibuf);
        log_msg(DEBUG, "ebuf: %s", ebuf);

        cmp = strncmp(ibuf, obuf, LEN(ibuf));
        if (cmp != 0) {
            usleep(100);
        }
    }
}

int upload_file(FILE *file, int serial_fd)
{
    int file_size = 0;
    fseek(file, 0, SEEK_END);
    file_size = ftell(file);
    fseek(file, 0, SEEK_SET);

    int total = (file_size / PACKET_SIZE
                 + ((file_size % PACKET_SIZE) == 0 ? 0 : 1));

    printf("Sending %d bytes\n", file_size);
    printf("Progress: [ %3d%% ]", 0);
    fflush(stdout);

    uint address = 0x4000;
    uchar packet[PACKET_SIZE];

    for (int i = 1; !feof(file); i++) {
        size_t n = fread(packet, sizeof(uchar), LEN(packet), file);
        if (n > 0) {
            send_packet(i, address, n, packet);
            address += n;
        }
        printf("\rProgress: [ %3d%% ]", 100 * i / total);
        fflush(stdout);
    }
    return 0;
}

int main(int argc, char *argv[])
{
    int ind = parse_argv(argc, argv);
    serial_fd = open_tty(port);
    FILE *file = fopen(argv[ind], "r");

    if (!file) {
        fprintf(stderr, "Error: File '%s' could not be opened\n", argv[ind]);
        close(serial_fd);
        exit(EXIT_FAILURE);
    }

    tcflush(serial_fd, TCIOFLUSH);
    flush_bootloader(serial_fd);

    upload_file(file, serial_fd);
    puts("\ndone");

    fclose(file);
    close(serial_fd);

    exit(EXIT_SUCCESS);
}