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