ao-tools/lib: Deal with binary USB data in debugging output
[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
57         int                     remote;
58 };
59
60 #define NOT_HEX 0xff
61
62 static uint8_t
63 cc_hex_nibble(uint8_t c)
64 {
65         if ('0' <= c && c <= '9')
66                 return c - '0';
67         if ('a' <= c && c <= 'f')
68                 return c - 'a' + 10;
69         if ('A' <= c && c <= 'F')
70                 return c - 'A' + 10;
71         return NOT_HEX;
72 }
73
74 /*
75  * Take raw input bytes, parse them as hex
76  * and write them to the waiting buffer
77  */
78 static void
79 cc_handle_hex_read(struct cc_usb *cc)
80 {
81         uint8_t h, l;
82         int     hex_pos;
83
84         hex_pos = 0;
85         while (hex_pos < cc->hex_count && cc->in_pos < cc->in_count) {
86                 /*
87                  * Skip to next hex character
88                  */
89                 while (cc->in_pos < cc->in_count &&
90                        cc_hex_nibble(cc->in_buf[cc->in_pos]) == NOT_HEX)
91                         cc->in_pos++;
92                 /*
93                  * Make sure we have two characters left
94                  */
95                 if (cc->in_count - cc->in_pos < 2)
96                         break;
97                 /*
98                  * Parse hex number
99                  */
100                 h = cc_hex_nibble(cc->in_buf[cc->in_pos]);
101                 l = cc_hex_nibble(cc->in_buf[cc->in_pos+1]);
102                 if (h == NOT_HEX || l == NOT_HEX) {
103                         fprintf(stderr, "hex read error\n");
104                         break;
105                 }
106                 cc->in_pos += 2;
107                 /*
108                  * Store hex number
109                  */
110                 *cc->hex_buf[hex_pos].buf++ = (h << 4) | l;
111                 if (--cc->hex_buf[hex_pos].len <= 0)
112                         hex_pos++;
113         }
114
115         /* Move pending hex reads to the start of the array */
116         if (hex_pos) {
117                 memmove(cc->hex_buf, cc->hex_buf + hex_pos,
118                         (cc->hex_count - hex_pos) * sizeof (cc->hex_buf[0]));
119                 cc->hex_count -= hex_pos;
120         }
121 }
122
123 static void
124 cc_usb_dbg(int indent, uint8_t *bytes, int len)
125 {
126         int     eol = 1;
127         int     i;
128         uint8_t c;
129         while (len--) {
130                 c = *bytes++;
131                 if (eol) {
132                         for (i = 0; i < indent; i++)
133                                 ccdbg_debug(CC_DEBUG_BITBANG, " ");
134                         eol = 0;
135                 }
136                 switch (c) {
137                 case '\r':
138                         ccdbg_debug(CC_DEBUG_BITBANG, "^M");
139                         break;
140                 case '\n':
141                         eol = 1;
142                 default:
143                         if (c < ' ' || c > '~')
144                                 ccdbg_debug(CC_DEBUG_BITBANG, "\\%02x", c);
145                         else
146                                 ccdbg_debug(CC_DEBUG_BITBANG, "%c", c);
147                 }
148         }
149 }
150
151 /*
152  * Flush pending writes, fill pending reads
153  */
154
155 static int
156 _cc_usb_sync(struct cc_usb *cc, int wait_for_input)
157 {
158         int             ret;
159         struct pollfd   fds;
160         int             timeout;
161
162         fds.fd = cc->fd;
163         for (;;) {
164                 if (cc->hex_count || cc->out_count)
165                         timeout = 5000;
166                 else if (wait_for_input && cc->in_pos == cc->in_count)
167                         timeout = wait_for_input;
168                 else
169                         timeout = 0;
170                 fds.events = 0;
171                 /* Move remaining bytes to the start of the input buffer */
172                 if (cc->in_pos) {
173                         memmove(cc->in_buf, cc->in_buf + cc->in_pos,
174                                 cc->in_count - cc->in_pos);
175                         cc->in_count -= cc->in_pos;
176                         cc->in_pos = 0;
177                 }
178                 if (cc->in_count < CC_IN_BUF)
179                         fds.events |= POLLIN;
180                 if (cc->out_count)
181                         fds.events |= POLLOUT;
182                 ret = poll(&fds, 1, timeout);
183                 if (ret == 0) {
184                         if (timeout)
185                                 return -1;
186                         break;
187                 }
188                 if (ret < 0) {
189                         perror("poll");
190                         return -1;
191                 }
192                 if (fds.revents & POLLIN) {
193                         ret = read(cc->fd, cc->in_buf + cc->in_count,
194                                    CC_IN_BUF - cc->in_count);
195                         if (ret > 0) {
196                                 int i;
197                                 cc_usb_dbg(24, cc->in_buf + cc->in_count, ret);
198                                 cc->in_count += ret;
199                                 if (cc->hex_count)
200                                         cc_handle_hex_read(cc);
201                         } else if (ret < 0)
202                                 perror("read");
203                 }
204                 if (fds.revents & POLLOUT) {
205                         ret = write(cc->fd, cc->out_buf,
206                                     cc->out_count);
207                         if (ret > 0) {
208                                 cc_usb_dbg(0, cc->out_buf, ret);
209                                 memmove(cc->out_buf,
210                                         cc->out_buf + ret,
211                                         cc->out_count - ret);
212                                 cc->out_count -= ret;
213                         } else if (ret < 0)
214                                 perror("write");
215                 }
216         }
217         return 0;
218 }
219
220 void
221 cc_usb_sync(struct cc_usb *cc)
222 {
223         if (_cc_usb_sync(cc, 0) < 0) {
224                 fprintf(stderr, "USB link timeout\n");
225                 exit(1);
226         }
227 }
228
229 void
230 cc_usb_printf(struct cc_usb *cc, char *format, ...)
231 {
232         char    buf[1024], *b;
233         va_list ap;
234         int     ret, this_time;
235
236         /* sprintf to a local buffer */
237         va_start(ap, format);
238         ret = vsnprintf(buf, sizeof(buf), format, ap);
239         va_end(ap);
240         if (ret > sizeof(buf)) {
241                 fprintf(stderr, "printf overflow for format %s\n",
242                         format);
243         }
244
245         /* flush local buffer to the wire */
246         b = buf;
247         while (ret > 0) {
248                 this_time = ret;
249                 if (this_time > CC_OUT_BUF - cc->out_count)
250                         this_time = CC_OUT_BUF - cc->out_count;
251                 memcpy(cc->out_buf + cc->out_count, b, this_time);
252                 cc->out_count += this_time;
253                 ret -= this_time;
254                 b += this_time;
255                 while (cc->out_count >= CC_OUT_BUF)
256                         cc_usb_sync(cc);
257         }
258 }
259
260 int
261 cc_usb_getchar_timeout(struct cc_usb *cc, int timeout)
262 {
263         while (cc->in_pos == cc->in_count) {
264                 if (_cc_usb_sync(cc, timeout) < 0) {
265                         fprintf(stderr, "USB link timeout\n");
266                         exit(1);
267                 }
268         }
269         return cc->in_buf[cc->in_pos++];
270 }
271
272 int
273 cc_usb_getchar(struct cc_usb *cc)
274 {
275         return cc_usb_getchar_timeout(cc, 5000);
276 }
277
278 void
279 cc_usb_getline(struct cc_usb *cc, char *line, int max)
280 {
281         int     c;
282
283         while ((c = cc_usb_getchar(cc)) != '\n') {
284                 switch (c) {
285                 case '\r':
286                         break;
287                 default:
288                         if (max > 1) {
289                                 *line++ = c;
290                                 max--;
291                         }
292                         break;
293                 }
294         }
295         *line++ = '\0';
296 }
297
298 int
299 cc_usb_send_bytes(struct cc_usb *cc, uint8_t *bytes, int len)
300 {
301         int     this_len;
302         int     ret = len;
303
304         while (len) {
305                 this_len = len;
306                 if (this_len > 8)
307                         this_len = 8;
308                 len -= this_len;
309                 cc_usb_printf(cc, "P");
310                 while (this_len--)
311                         cc_usb_printf (cc, " %02x", (*bytes++) & 0xff);
312                 cc_usb_printf(cc, "\n");
313         }
314         return ret;
315 }
316
317 void
318 cc_queue_read(struct cc_usb *cc, uint8_t *buf, int len)
319 {
320         struct cc_hex_read      *hex_buf;
321
322         /* At the start of a command sequence, flush any pending input */
323         if (cc->hex_count == 0) {
324                 cc_usb_sync(cc);
325                 cc->in_count = 0;
326         }
327         while (cc->hex_count >= CC_NUM_HEX_READ)
328                 cc_usb_sync(cc);
329         hex_buf = &cc->hex_buf[cc->hex_count++];
330         hex_buf->buf = buf;
331         hex_buf->len = len;
332 }
333
334 int
335 cc_usb_recv_bytes(struct cc_usb *cc, uint8_t *buf, int len)
336 {
337         cc_queue_read(cc, buf, len);
338         cc_usb_printf(cc, "G %x\n", len);
339         return len;
340 }
341
342 int
343 cc_usb_write_memory(struct cc_usb *cc, uint16_t addr, uint8_t *bytes, int len)
344 {
345         cc_usb_printf(cc, "O %x %x\n", len, addr);
346         while (len--)
347                 cc_usb_printf(cc, "%02x", *bytes++);
348         cc_usb_sync(cc);
349         return 0;
350 }
351
352 int
353 cc_usb_read_memory(struct cc_usb *cc, uint16_t addr, uint8_t *bytes, int len)
354 {
355         int     i;
356         cc_queue_read(cc, bytes, len);
357         cc_usb_printf(cc, "I %x %x\n", len, addr);
358         cc_usb_sync(cc);
359         for (i = 0; i < len; i++) {
360                 if ((i & 15) == 0) {
361                         if (i)
362                                 ccdbg_debug(CC_DEBUG_MEMORY, "\n");
363                         ccdbg_debug(CC_DEBUG_MEMORY, "\t%04x", addr + i);
364                 }
365                 ccdbg_debug(CC_DEBUG_MEMORY, " %02x", bytes[i]);
366         }
367         ccdbg_debug(CC_DEBUG_MEMORY, "\n");
368         return 0;
369 }
370
371 int
372 cc_usb_debug_mode(struct cc_usb *cc)
373 {
374         cc_usb_sync(cc);
375         cc_usb_printf(cc, "D\n");
376         return 1;
377 }
378
379 int
380 cc_usb_reset(struct cc_usb *cc)
381 {
382         cc_usb_sync(cc);
383         cc_usb_printf(cc, "R\n");
384         return 1;
385 }
386
387 void
388 cc_usb_open_remote(struct cc_usb *cc, int freq, char *call)
389 {
390         if (!cc->remote) {
391                 fprintf (stderr, "freq %dkHz\n", freq);
392                 fprintf (stderr, "call %s\n", call);
393                 cc_usb_printf(cc, "\nc F %d\nc c %s\np\nE 0\n", freq, call);
394                 do {
395                         cc->in_count = cc->in_pos = 0;
396                         _cc_usb_sync(cc, 100);
397                 } while (cc->in_count > 0);
398                 cc->remote = 1;
399         }
400 }
401
402 void
403 cc_usb_close_remote(struct cc_usb *cc)
404 {
405         if (cc->remote) {
406                 cc_usb_printf(cc, "~");
407                 cc->remote = 0;
408         }
409 }
410
411 static struct termios   save_termios;
412
413 struct cc_usb *
414 cc_usb_open(char *tty)
415 {
416         struct cc_usb   *cc;
417         struct termios  termios;
418
419         if (!tty)
420                 tty = DEFAULT_TTY;
421         cc = calloc (sizeof (struct cc_usb), 1);
422         if (!cc)
423                 return NULL;
424         cc->fd = open(tty, O_RDWR | O_NONBLOCK);
425         if (cc->fd < 0) {
426                 perror(tty);
427                 free (cc);
428                 return NULL;
429         }
430         tcgetattr(cc->fd, &termios);
431         save_termios = termios;
432         cfmakeraw(&termios);
433         cfsetospeed(&termios, B9600);
434         cfsetispeed(&termios, B9600);
435         tcsetattr(cc->fd, TCSAFLUSH, &termios);
436         cc_usb_printf(cc, "\nE 0\nm 0\n");
437         do {
438                 cc->in_count = cc->in_pos = 0;
439                 _cc_usb_sync(cc, 100);
440         } while (cc->in_count > 0);
441         return cc;
442 }
443
444 void
445 cc_usb_close(struct cc_usb *cc)
446 {
447         cc_usb_close_remote(cc);
448         cc_usb_sync(cc);
449         tcsetattr(cc->fd, TCSAFLUSH, &save_termios);
450         close (cc->fd);
451         free (cc);
452 }