ao-tools: Add --wait option to ao-usbload
[fw/altos] / ao-tools / lib / cc-usb.c
1 /*
2  * Copyright © 2009 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <fcntl.h>
22 #include <stdarg.h>
23 #include <poll.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <unistd.h>
27 #include <string.h>
28 #include <termios.h>
29 #include "ccdbg-debug.h"
30 #include "cc-usb.h"
31
32
33 #define CC_NUM_HEX_READ         64
34 /*
35  * AltOS has different buffer sizes for in/out packets
36  */
37 #define CC_IN_BUF               65536
38 #define CC_OUT_BUF              64
39 #define DEFAULT_TTY             "/dev/ttyACM0"
40
41 struct cc_hex_read {
42         uint8_t *buf;
43         int     len;
44 };
45
46 struct cc_usb {
47         int                     fd;
48         uint8_t                 in_buf[CC_IN_BUF];
49         int                     in_pos;
50         int                     in_count;
51         uint8_t                 out_buf[CC_OUT_BUF];
52         int                     out_count;
53
54         struct cc_hex_read      hex_buf[CC_NUM_HEX_READ];
55         int                     hex_count;
56         int                     show_input;
57
58         int                     remote;
59 };
60
61 #define NOT_HEX 0xff
62
63 static uint8_t
64 cc_hex_nibble(uint8_t c)
65 {
66         if ('0' <= c && c <= '9')
67                 return c - '0';
68         if ('a' <= c && c <= 'f')
69                 return c - 'a' + 10;
70         if ('A' <= c && c <= 'F')
71                 return c - 'A' + 10;
72         return NOT_HEX;
73 }
74
75 /*
76  * Take raw input bytes, parse them as hex
77  * and write them to the waiting buffer
78  */
79 static void
80 cc_handle_hex_read(struct cc_usb *cc)
81 {
82         uint8_t h, l;
83         int     hex_pos;
84
85         hex_pos = 0;
86         while (hex_pos < cc->hex_count && cc->in_pos < cc->in_count) {
87                 /*
88                  * Skip to next hex character
89                  */
90                 while (cc->in_pos < cc->in_count &&
91                        cc_hex_nibble(cc->in_buf[cc->in_pos]) == NOT_HEX)
92                         cc->in_pos++;
93                 /*
94                  * Make sure we have two characters left
95                  */
96                 if (cc->in_count - cc->in_pos < 2)
97                         break;
98                 /*
99                  * Parse hex number
100                  */
101                 h = cc_hex_nibble(cc->in_buf[cc->in_pos]);
102                 l = cc_hex_nibble(cc->in_buf[cc->in_pos+1]);
103                 if (h == NOT_HEX || l == NOT_HEX) {
104                         fprintf(stderr, "hex read error\n");
105                         break;
106                 }
107                 cc->in_pos += 2;
108                 /*
109                  * Store hex number
110                  */
111                 *cc->hex_buf[hex_pos].buf++ = (h << 4) | l;
112                 if (--cc->hex_buf[hex_pos].len <= 0)
113                         hex_pos++;
114         }
115
116         /* Move pending hex reads to the start of the array */
117         if (hex_pos) {
118                 memmove(cc->hex_buf, cc->hex_buf + hex_pos,
119                         (cc->hex_count - hex_pos) * sizeof (cc->hex_buf[0]));
120                 cc->hex_count -= hex_pos;
121         }
122 }
123
124 static void
125 cc_usb_dbg(int indent, uint8_t *bytes, int len)
126 {
127         static int      eol = 1;
128         int     i;
129         uint8_t c;
130         ccdbg_debug(CC_DEBUG_BITBANG, "<<<%d bytes>>>", len);
131         while (len--) {
132                 c = *bytes++;
133                 if (eol) {
134                         for (i = 0; i < indent; i++)
135                                 ccdbg_debug(CC_DEBUG_BITBANG, " ");
136                         eol = 0;
137                 }
138                 switch (c) {
139                 case '\r':
140                         ccdbg_debug(CC_DEBUG_BITBANG, "\\r");
141                         break;
142                 case '\n':
143                         eol = 1;
144                         ccdbg_debug(CC_DEBUG_BITBANG, "\\n\n");
145                         break;
146                 default:
147                         if (c < ' ' || c > '~')
148                                 ccdbg_debug(CC_DEBUG_BITBANG, "\\%02x", c);
149                         else
150                                 ccdbg_debug(CC_DEBUG_BITBANG, "%c", c);
151                 }
152         }
153 }
154
155 int     cc_default_timeout = 5000;
156
157 /*
158  * Flush pending writes, fill pending reads
159  */
160
161 static int
162 _cc_usb_sync(struct cc_usb *cc, int wait_for_input, int write_timeout)
163 {
164         int             ret;
165         struct pollfd   fds;
166         int             timeout;
167
168         fds.fd = cc->fd;
169         for (;;) {
170                 if (cc->hex_count || cc->out_count)
171                         timeout = write_timeout;
172                 else if (wait_for_input && cc->in_pos == cc->in_count)
173                         timeout = wait_for_input;
174                 else
175                         timeout = 0;
176                 fds.events = 0;
177                 /* Move remaining bytes to the start of the input buffer */
178                 if (cc->in_pos) {
179                         memmove(cc->in_buf, cc->in_buf + cc->in_pos,
180                                 cc->in_count - cc->in_pos);
181                         cc->in_count -= cc->in_pos;
182                         cc->in_pos = 0;
183                 }
184                 if (cc->in_count < CC_IN_BUF)
185                         fds.events |= POLLIN;
186                 if (cc->out_count)
187                         fds.events |= POLLOUT;
188                 ret = poll(&fds, 1, timeout);
189                 if (ret == 0) {
190                         if (timeout)
191                                 return -1;
192                         break;
193                 }
194                 if (ret < 0) {
195                         perror("poll");
196                         return -1;
197                 }
198                 if (fds.revents & POLLIN) {
199                         ret = read(cc->fd, cc->in_buf + cc->in_count,
200                                    CC_IN_BUF - cc->in_count);
201                         if (ret > 0) {
202                                 cc_usb_dbg(24, cc->in_buf + cc->in_count, ret);
203                                 cc->in_count += ret;
204                                 if (cc->hex_count)
205                                         cc_handle_hex_read(cc);
206                                 if (cc->show_input && cc->in_count) {
207                                         write(2, cc->in_buf, cc->in_count);
208                                         cc->in_count = 0;
209                                 }
210                         } else if (ret < 0)
211                                 perror("read");
212                 }
213                 if (fds.revents & POLLOUT) {
214                         ret = write(cc->fd, cc->out_buf,
215                                     cc->out_count);
216                         if (ret > 0) {
217                                 cc_usb_dbg(0, cc->out_buf, ret);
218                                 memmove(cc->out_buf,
219                                         cc->out_buf + ret,
220                                         cc->out_count - ret);
221                                 cc->out_count -= ret;
222                         } else if (ret < 0)
223                                 perror("write");
224                 }
225         }
226         return 0;
227 }
228
229 void
230 cc_usb_sync(struct cc_usb *cc)
231 {
232         if (_cc_usb_sync(cc, 0, cc_default_timeout) < 0) {
233                 fprintf(stderr, "USB link timeout\n");
234                 exit(1);
235         }
236 }
237
238 void
239 cc_usb_printf(struct cc_usb *cc, char *format, ...)
240 {
241         char    buf[1024], *b;
242         va_list ap;
243         int     ret, this_time;
244
245         /* sprintf to a local buffer */
246         va_start(ap, format);
247         ret = vsnprintf(buf, sizeof(buf), format, ap);
248         va_end(ap);
249         if (ret > sizeof(buf)) {
250                 fprintf(stderr, "printf overflow for format %s\n",
251                         format);
252         }
253
254         /* flush local buffer to the wire */
255         b = buf;
256         while (ret > 0) {
257                 this_time = ret;
258                 if (this_time > CC_OUT_BUF - cc->out_count)
259                         this_time = CC_OUT_BUF - cc->out_count;
260                 memcpy(cc->out_buf + cc->out_count, b, this_time);
261                 cc->out_count += this_time;
262                 ret -= this_time;
263                 b += this_time;
264                 while (cc->out_count >= CC_OUT_BUF)
265                         cc_usb_sync(cc);
266         }
267 }
268
269 int
270 cc_usb_getchar_timeout(struct cc_usb *cc, int timeout)
271 {
272         while (cc->in_pos == cc->in_count) {
273                 if (_cc_usb_sync(cc, timeout, cc_default_timeout) < 0) {
274                         fprintf(stderr, "USB link timeout\n");
275                         exit(1);
276                 }
277         }
278         return cc->in_buf[cc->in_pos++];
279 }
280
281 int
282 cc_usb_getchar(struct cc_usb *cc)
283 {
284         return cc_usb_getchar_timeout(cc, cc_default_timeout);
285 }
286
287 void
288 cc_usb_getline(struct cc_usb *cc, char *line, int max)
289 {
290         int     c;
291
292         while ((c = cc_usb_getchar(cc)) != '\n') {
293                 switch (c) {
294                 case '\r':
295                         break;
296                 default:
297                         if (max > 1) {
298                                 *line++ = c;
299                                 max--;
300                         }
301                         break;
302                 }
303         }
304         *line++ = '\0';
305 }
306
307 int
308 cc_usb_send_bytes(struct cc_usb *cc, uint8_t *bytes, int len)
309 {
310         int     this_len;
311         int     ret = len;
312
313         while (len) {
314                 this_len = len;
315                 if (this_len > 8)
316                         this_len = 8;
317                 len -= this_len;
318                 cc_usb_printf(cc, "P");
319                 while (this_len--)
320                         cc_usb_printf (cc, " %02x", (*bytes++) & 0xff);
321                 cc_usb_printf(cc, "\n");
322         }
323         return ret;
324 }
325
326 void
327 cc_queue_read(struct cc_usb *cc, uint8_t *buf, int len)
328 {
329         struct cc_hex_read      *hex_buf;
330
331         /* At the start of a command sequence, flush any pending input */
332         if (cc->hex_count == 0) {
333                 cc_usb_sync(cc);
334                 cc->in_count = 0;
335         }
336         while (cc->hex_count >= CC_NUM_HEX_READ)
337                 cc_usb_sync(cc);
338         hex_buf = &cc->hex_buf[cc->hex_count++];
339         hex_buf->buf = buf;
340         hex_buf->len = len;
341 }
342
343 int
344 cc_usb_recv_bytes(struct cc_usb *cc, uint8_t *buf, int len)
345 {
346         cc_queue_read(cc, buf, len);
347         cc_usb_printf(cc, "G %x\n", len);
348         return len;
349 }
350
351 int
352 cc_usb_write_memory(struct cc_usb *cc, uint16_t addr, uint8_t *bytes, int len)
353 {
354         cc_usb_printf(cc, "O %x %x\n", len, addr);
355         while (len--)
356                 cc_usb_printf(cc, "%02x", *bytes++);
357         cc_usb_sync(cc);
358         return 0;
359 }
360
361 int
362 cc_usb_read_memory(struct cc_usb *cc, uint16_t addr, uint8_t *bytes, int len)
363 {
364         int     i;
365         cc_queue_read(cc, bytes, len);
366         cc_usb_printf(cc, "I %x %x\n", len, addr);
367         cc_usb_sync(cc);
368         for (i = 0; i < len; i++) {
369                 if ((i & 15) == 0) {
370                         if (i)
371                                 ccdbg_debug(CC_DEBUG_MEMORY, "\n");
372                         ccdbg_debug(CC_DEBUG_MEMORY, "\t%04x", addr + i);
373                 }
374                 ccdbg_debug(CC_DEBUG_MEMORY, " %02x", bytes[i]);
375         }
376         ccdbg_debug(CC_DEBUG_MEMORY, "\n");
377         return 0;
378 }
379
380 int
381 cc_usb_debug_mode(struct cc_usb *cc)
382 {
383         cc_usb_sync(cc);
384         cc_usb_printf(cc, "D\n");
385         return 1;
386 }
387
388 int
389 cc_usb_reset(struct cc_usb *cc)
390 {
391         cc_usb_sync(cc);
392         cc_usb_printf(cc, "R\n");
393         return 1;
394 }
395
396 void
397 cc_usb_open_remote(struct cc_usb *cc, int freq, char *call)
398 {
399         if (!cc->remote) {
400                 fprintf (stderr, "freq %dkHz\n", freq);
401                 fprintf (stderr, "call %s\n", call);
402                 cc_usb_printf(cc, "\nc F %d\nc c %s\np\nE 0\n", freq, call);
403                 do {
404                         cc->in_count = cc->in_pos = 0;
405                         _cc_usb_sync(cc, 100, cc_default_timeout);
406                 } while (cc->in_count > 0);
407                 cc->remote = 1;
408         }
409 }
410
411 void
412 cc_usb_close_remote(struct cc_usb *cc)
413 {
414         if (cc->remote) {
415                 cc_usb_printf(cc, "~");
416                 cc->remote = 0;
417         }
418 }
419
420 static struct termios   save_termios;
421
422 #include <errno.h>
423
424 struct cc_usb *
425 cc_usb_open(char *tty)
426 {
427         struct cc_usb   *cc;
428         struct termios  termios;
429         int             i;
430
431         if (!tty)
432                 tty = DEFAULT_TTY;
433         cc = calloc (sizeof (struct cc_usb), 1);
434         if (!cc)
435                 return NULL;
436         i = 0;
437         for (;;) {
438                 cc->fd = open(tty, O_RDWR | O_NONBLOCK);
439                 if (cc->fd >= 0)
440                         break;
441                 i++;
442                 if (errno == EBUSY || errno == EPERM || errno == EACCES) {
443                         fprintf(stderr, "open failed, pausing");
444                         perror(tty);
445                         if (i < 20) {
446                                 sleep(3);
447                                 continue;
448                         }
449                 }
450
451                 perror(tty);
452                 free (cc);
453                 return NULL;
454         }
455         tcgetattr(cc->fd, &termios);
456         save_termios = termios;
457         cfmakeraw(&termios);
458         cfsetospeed(&termios, B9600);
459         cfsetispeed(&termios, B9600);
460         tcsetattr(cc->fd, TCSAFLUSH, &termios);
461         cc_usb_printf(cc, "\nE 0\nm 0\n");
462         do {
463                 cc->in_count = cc->in_pos = 0;
464                 _cc_usb_sync(cc, 100, cc_default_timeout);
465         } while (cc->in_count > 0);
466         return cc;
467 }
468
469 void
470 cc_usb_close(struct cc_usb *cc)
471 {
472         cc_usb_close_remote(cc);
473         cc_usb_sync(cc);
474         tcsetattr(cc->fd, TCSAFLUSH, &save_termios);
475         close (cc->fd);
476         free (cc);
477 }
478
479 int
480 cc_usb_write(struct cc_usb *cc, void *buf, int c)
481 {
482         uint8_t *b;
483         int this_time;
484
485         b = buf;
486         cc->show_input = 1;
487         while (c > 0) {
488                 this_time = c;
489                 if (this_time > CC_OUT_BUF - cc->out_count)
490                         this_time = CC_OUT_BUF - cc->out_count;
491                 memcpy(cc->out_buf + cc->out_count, b, this_time);
492                 cc->out_count += this_time;
493                 c -= this_time;
494                 b += this_time;
495                 while (cc->out_count >= CC_OUT_BUF) {
496                         _cc_usb_sync(cc, 0, -1);
497                 }
498         }
499         return 1;
500 }