38dfff04936c87e6fbed2b8df73b5286edd92987
[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 /*
156  * Flush pending writes, fill pending reads
157  */
158
159 static int
160 _cc_usb_sync(struct cc_usb *cc, int wait_for_input, int write_timeout)
161 {
162         int             ret;
163         struct pollfd   fds;
164         int             timeout;
165
166         fds.fd = cc->fd;
167         for (;;) {
168                 if (cc->hex_count || cc->out_count)
169                         timeout = write_timeout;
170                 else if (wait_for_input && cc->in_pos == cc->in_count)
171                         timeout = wait_for_input;
172                 else
173                         timeout = 0;
174                 fds.events = 0;
175                 /* Move remaining bytes to the start of the input buffer */
176                 if (cc->in_pos) {
177                         memmove(cc->in_buf, cc->in_buf + cc->in_pos,
178                                 cc->in_count - cc->in_pos);
179                         cc->in_count -= cc->in_pos;
180                         cc->in_pos = 0;
181                 }
182                 if (cc->in_count < CC_IN_BUF)
183                         fds.events |= POLLIN;
184                 if (cc->out_count)
185                         fds.events |= POLLOUT;
186                 ret = poll(&fds, 1, timeout);
187                 if (ret == 0) {
188                         if (timeout)
189                                 return -1;
190                         break;
191                 }
192                 if (ret < 0) {
193                         perror("poll");
194                         return -1;
195                 }
196                 if (fds.revents & POLLIN) {
197                         ret = read(cc->fd, cc->in_buf + cc->in_count,
198                                    CC_IN_BUF - cc->in_count);
199                         if (ret > 0) {
200                                 cc_usb_dbg(24, cc->in_buf + cc->in_count, ret);
201                                 cc->in_count += ret;
202                                 if (cc->hex_count)
203                                         cc_handle_hex_read(cc);
204                                 if (cc->show_input && cc->in_count) {
205                                         write(2, cc->in_buf, cc->in_count);
206                                         cc->in_count = 0;
207                                 }
208                         } else if (ret < 0)
209                                 perror("read");
210                 }
211                 if (fds.revents & POLLOUT) {
212                         ret = write(cc->fd, cc->out_buf,
213                                     cc->out_count);
214                         if (ret > 0) {
215                                 cc_usb_dbg(0, cc->out_buf, ret);
216                                 memmove(cc->out_buf,
217                                         cc->out_buf + ret,
218                                         cc->out_count - ret);
219                                 cc->out_count -= ret;
220                         } else if (ret < 0)
221                                 perror("write");
222                 }
223         }
224         return 0;
225 }
226
227 void
228 cc_usb_sync(struct cc_usb *cc)
229 {
230         if (_cc_usb_sync(cc, 0, 5000) < 0) {
231                 fprintf(stderr, "USB link timeout\n");
232                 exit(1);
233         }
234 }
235
236 void
237 cc_usb_printf(struct cc_usb *cc, char *format, ...)
238 {
239         char    buf[1024], *b;
240         va_list ap;
241         int     ret, this_time;
242
243         /* sprintf to a local buffer */
244         va_start(ap, format);
245         ret = vsnprintf(buf, sizeof(buf), format, ap);
246         va_end(ap);
247         if (ret > sizeof(buf)) {
248                 fprintf(stderr, "printf overflow for format %s\n",
249                         format);
250         }
251
252         /* flush local buffer to the wire */
253         b = buf;
254         while (ret > 0) {
255                 this_time = ret;
256                 if (this_time > CC_OUT_BUF - cc->out_count)
257                         this_time = CC_OUT_BUF - cc->out_count;
258                 memcpy(cc->out_buf + cc->out_count, b, this_time);
259                 cc->out_count += this_time;
260                 ret -= this_time;
261                 b += this_time;
262                 while (cc->out_count >= CC_OUT_BUF)
263                         cc_usb_sync(cc);
264         }
265 }
266
267 int
268 cc_usb_getchar_timeout(struct cc_usb *cc, int timeout)
269 {
270         while (cc->in_pos == cc->in_count) {
271                 if (_cc_usb_sync(cc, timeout, 5000) < 0) {
272                         fprintf(stderr, "USB link timeout\n");
273                         exit(1);
274                 }
275         }
276         return cc->in_buf[cc->in_pos++];
277 }
278
279 int
280 cc_usb_getchar(struct cc_usb *cc)
281 {
282         return cc_usb_getchar_timeout(cc, 5000);
283 }
284
285 void
286 cc_usb_getline(struct cc_usb *cc, char *line, int max)
287 {
288         int     c;
289
290         while ((c = cc_usb_getchar(cc)) != '\n') {
291                 switch (c) {
292                 case '\r':
293                         break;
294                 default:
295                         if (max > 1) {
296                                 *line++ = c;
297                                 max--;
298                         }
299                         break;
300                 }
301         }
302         *line++ = '\0';
303 }
304
305 int
306 cc_usb_send_bytes(struct cc_usb *cc, uint8_t *bytes, int len)
307 {
308         int     this_len;
309         int     ret = len;
310
311         while (len) {
312                 this_len = len;
313                 if (this_len > 8)
314                         this_len = 8;
315                 len -= this_len;
316                 cc_usb_printf(cc, "P");
317                 while (this_len--)
318                         cc_usb_printf (cc, " %02x", (*bytes++) & 0xff);
319                 cc_usb_printf(cc, "\n");
320         }
321         return ret;
322 }
323
324 void
325 cc_queue_read(struct cc_usb *cc, uint8_t *buf, int len)
326 {
327         struct cc_hex_read      *hex_buf;
328
329         /* At the start of a command sequence, flush any pending input */
330         if (cc->hex_count == 0) {
331                 cc_usb_sync(cc);
332                 cc->in_count = 0;
333         }
334         while (cc->hex_count >= CC_NUM_HEX_READ)
335                 cc_usb_sync(cc);
336         hex_buf = &cc->hex_buf[cc->hex_count++];
337         hex_buf->buf = buf;
338         hex_buf->len = len;
339 }
340
341 int
342 cc_usb_recv_bytes(struct cc_usb *cc, uint8_t *buf, int len)
343 {
344         cc_queue_read(cc, buf, len);
345         cc_usb_printf(cc, "G %x\n", len);
346         return len;
347 }
348
349 int
350 cc_usb_write_memory(struct cc_usb *cc, uint16_t addr, uint8_t *bytes, int len)
351 {
352         cc_usb_printf(cc, "O %x %x\n", len, addr);
353         while (len--)
354                 cc_usb_printf(cc, "%02x", *bytes++);
355         cc_usb_sync(cc);
356         return 0;
357 }
358
359 int
360 cc_usb_read_memory(struct cc_usb *cc, uint16_t addr, uint8_t *bytes, int len)
361 {
362         int     i;
363         cc_queue_read(cc, bytes, len);
364         cc_usb_printf(cc, "I %x %x\n", len, addr);
365         cc_usb_sync(cc);
366         for (i = 0; i < len; i++) {
367                 if ((i & 15) == 0) {
368                         if (i)
369                                 ccdbg_debug(CC_DEBUG_MEMORY, "\n");
370                         ccdbg_debug(CC_DEBUG_MEMORY, "\t%04x", addr + i);
371                 }
372                 ccdbg_debug(CC_DEBUG_MEMORY, " %02x", bytes[i]);
373         }
374         ccdbg_debug(CC_DEBUG_MEMORY, "\n");
375         return 0;
376 }
377
378 int
379 cc_usb_debug_mode(struct cc_usb *cc)
380 {
381         cc_usb_sync(cc);
382         cc_usb_printf(cc, "D\n");
383         return 1;
384 }
385
386 int
387 cc_usb_reset(struct cc_usb *cc)
388 {
389         cc_usb_sync(cc);
390         cc_usb_printf(cc, "R\n");
391         return 1;
392 }
393
394 void
395 cc_usb_open_remote(struct cc_usb *cc, int freq, char *call)
396 {
397         if (!cc->remote) {
398                 fprintf (stderr, "freq %dkHz\n", freq);
399                 fprintf (stderr, "call %s\n", call);
400                 cc_usb_printf(cc, "\nc F %d\nc c %s\np\nE 0\n", freq, call);
401                 do {
402                         cc->in_count = cc->in_pos = 0;
403                         _cc_usb_sync(cc, 100, 5000);
404                 } while (cc->in_count > 0);
405                 cc->remote = 1;
406         }
407 }
408
409 void
410 cc_usb_close_remote(struct cc_usb *cc)
411 {
412         if (cc->remote) {
413                 cc_usb_printf(cc, "~");
414                 cc->remote = 0;
415         }
416 }
417
418 static struct termios   save_termios;
419
420 #include <errno.h>
421
422 struct cc_usb *
423 cc_usb_open(char *tty)
424 {
425         struct cc_usb   *cc;
426         struct termios  termios;
427         int             i;
428
429         if (!tty)
430                 tty = DEFAULT_TTY;
431         cc = calloc (sizeof (struct cc_usb), 1);
432         if (!cc)
433                 return NULL;
434         i = 0;
435         for (;;) {
436                 cc->fd = open(tty, O_RDWR | O_NONBLOCK);
437                 if (cc->fd >= 0)
438                         break;
439                 i++;
440                 if (errno == EBUSY || errno == EPERM || errno == EACCES) {
441                         fprintf(stderr, "open failed, pausing");
442                         perror(tty);
443                         if (i < 20) {
444                                 sleep(3);
445                                 continue;
446                         }
447                 }
448
449                 perror(tty);
450                 free (cc);
451                 return NULL;
452         }
453         tcgetattr(cc->fd, &termios);
454         save_termios = termios;
455         cfmakeraw(&termios);
456         cfsetospeed(&termios, B9600);
457         cfsetispeed(&termios, B9600);
458         tcsetattr(cc->fd, TCSAFLUSH, &termios);
459         cc_usb_printf(cc, "\nE 0\nm 0\n");
460         do {
461                 cc->in_count = cc->in_pos = 0;
462                 _cc_usb_sync(cc, 100, 5000);
463         } while (cc->in_count > 0);
464         return cc;
465 }
466
467 void
468 cc_usb_close(struct cc_usb *cc)
469 {
470         cc_usb_close_remote(cc);
471         cc_usb_sync(cc);
472         tcsetattr(cc->fd, TCSAFLUSH, &save_termios);
473         close (cc->fd);
474         free (cc);
475 }
476
477 int
478 cc_usb_write(struct cc_usb *cc, void *buf, int c)
479 {
480         uint8_t *b;
481         int this_time;
482
483         b = buf;
484         cc->show_input = 1;
485         while (c > 0) {
486                 this_time = c;
487                 if (this_time > CC_OUT_BUF - cc->out_count)
488                         this_time = CC_OUT_BUF - cc->out_count;
489                 memcpy(cc->out_buf + cc->out_count, b, this_time);
490                 cc->out_count += this_time;
491                 c -= this_time;
492                 b += this_time;
493                 while (cc->out_count >= CC_OUT_BUF) {
494                         _cc_usb_sync(cc, 0, -1);
495                 }
496         }
497         return 1;
498 }