fix missing newline at end of src/test/Makefile
[fw/altos] / libaltos / libaltos.c
1 /*
2  * Copyright © 2010 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; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #include "libaltos.h"
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22
23 #define BLUETOOTH_PRODUCT_TELEBT        "TeleBT"
24
25 #define USE_POLL
26
27 PUBLIC int
28 altos_init(void)
29 {
30         return LIBALTOS_SUCCESS;
31 }
32
33 PUBLIC void
34 altos_fini(void)
35 {
36 }
37
38 static struct altos_error last_error;
39
40 static void
41 altos_set_last_error(int code, char *string)
42 {
43         last_error.code = code;
44         strncpy(last_error.string, string, sizeof (last_error.string) -1);
45         last_error.string[sizeof(last_error.string)-1] = '\0';
46 }
47
48 PUBLIC void
49 altos_get_last_error(struct altos_error *error)
50 {
51         *error = last_error;
52 }
53
54 #ifdef DARWIN
55
56 #include <unistd.h>
57
58 #undef USE_POLL
59
60 /* Mac OS X don't have strndup even if _GNU_SOURCE is defined */
61 static char *
62 altos_strndup (const char *s, size_t n)
63 {
64     size_t len = strlen (s);
65     char *ret;
66
67     if (len <= n)
68        return strdup (s);
69     ret = malloc(n + 1);
70     strncpy(ret, s, n);
71     ret[n] = '\0';
72     return ret;
73 }
74
75 #else
76 #define altos_strndup strndup
77 #endif
78
79 #ifdef POSIX_TTY
80
81 #include <stdio.h>
82 #include <stdlib.h>
83 #include <fcntl.h>
84 #include <termios.h>
85 #include <errno.h>
86
87 #define USB_BUF_SIZE    64
88
89 struct altos_file {
90         int                             fd;
91 #ifdef USE_POLL
92         int                             pipe[2];
93 #else
94         int                             out_fd;
95 #endif
96         unsigned char                   out_data[USB_BUF_SIZE];
97         int                             out_used;
98         unsigned char                   in_data[USB_BUF_SIZE];
99         int                             in_used;
100         int                             in_read;
101 };
102
103 static void
104 altos_set_last_posix_error(void)
105 {
106         altos_set_last_error(errno, strerror(errno));
107 }
108
109 PUBLIC struct altos_file *
110 altos_open(struct altos_device *device)
111 {
112         struct altos_file       *file = calloc (sizeof (struct altos_file), 1);
113         int                     ret;
114         struct termios          term;
115
116         if (!file) {
117                 altos_set_last_posix_error();
118                 return NULL;
119         }
120
121 //      altos_set_last_error(12, "yeah yeah, failed again");
122 //      free(file);
123 //      return NULL;
124
125         file->fd = open(device->path, O_RDWR | O_NOCTTY);
126         if (file->fd < 0) {
127                 altos_set_last_posix_error();
128                 free(file);
129                 return NULL;
130         }
131 #ifdef USE_POLL
132         pipe(file->pipe);
133 #else
134         file->out_fd = open(device->path, O_RDWR | O_NOCTTY);
135         if (file->out_fd < 0) {
136                 altos_set_last_posix_error();
137                 close(file->fd);
138                 free(file);
139                 return NULL;
140         }
141 #endif
142         ret = tcgetattr(file->fd, &term);
143         if (ret < 0) {
144                 altos_set_last_posix_error();
145                 close(file->fd);
146 #ifndef USE_POLL
147                 close(file->out_fd);
148 #endif
149                 free(file);
150                 return NULL;
151         }
152         cfmakeraw(&term);
153         cfsetospeed(&term, B9600);
154         cfsetispeed(&term, B9600);
155 #ifdef USE_POLL
156         term.c_cc[VMIN] = 1;
157         term.c_cc[VTIME] = 0;
158 #else
159         term.c_cc[VMIN] = 0;
160         term.c_cc[VTIME] = 1;
161 #endif
162         ret = tcsetattr(file->fd, TCSAFLUSH, &term);
163         if (ret < 0) {
164                 altos_set_last_posix_error();
165                 close(file->fd);
166 #ifndef USE_POLL
167                 close(file->out_fd);
168 #endif
169                 free(file);
170                 return NULL;
171         }
172         return file;
173 }
174
175 PUBLIC void
176 altos_close(struct altos_file *file)
177 {
178         if (file->fd != -1) {
179                 int     fd = file->fd;
180                 file->fd = -1;
181 #ifdef USE_POLL
182                 write(file->pipe[1], "\r", 1);
183 #else
184                 close(file->out_fd);
185                 file->out_fd = -1;
186 #endif
187                 close(fd);
188         }
189 }
190
191 PUBLIC void
192 altos_free(struct altos_file *file)
193 {
194         altos_close(file);
195         free(file);
196 }
197
198 PUBLIC int
199 altos_flush(struct altos_file *file)
200 {
201         if (file->out_used && 0) {
202                 printf ("flush \"");
203                 fwrite(file->out_data, 1, file->out_used, stdout);
204                 printf ("\"\n");
205         }
206         while (file->out_used) {
207                 int     ret;
208
209                 if (file->fd < 0)
210                         return -EBADF;
211 #ifdef USE_POLL
212                 ret = write (file->fd, file->out_data, file->out_used);
213 #else
214                 ret = write (file->out_fd, file->out_data, file->out_used);
215 #endif
216                 if (ret < 0) {
217                         altos_set_last_posix_error();
218                         return -last_error.code;
219                 }
220                 if (ret) {
221                         memmove(file->out_data, file->out_data + ret,
222                                 file->out_used - ret);
223                         file->out_used -= ret;
224                 }
225         }
226         return 0;
227 }
228
229 PUBLIC int
230 altos_putchar(struct altos_file *file, char c)
231 {
232         int     ret;
233
234         if (file->out_used == USB_BUF_SIZE) {
235                 ret = altos_flush(file);
236                 if (ret) {
237                         return ret;
238                 }
239         }
240         file->out_data[file->out_used++] = c;
241         ret = 0;
242         if (file->out_used == USB_BUF_SIZE)
243                 ret = altos_flush(file);
244         return ret;
245 }
246
247 #ifdef USE_POLL
248 #include <poll.h>
249 #endif
250
251 static int
252 altos_fill(struct altos_file *file, int timeout)
253 {
254         int             ret;
255 #ifdef USE_POLL
256         struct pollfd   fd[2];
257 #endif
258
259         if (timeout == 0)
260                 timeout = -1;
261         while (file->in_read == file->in_used) {
262                 if (file->fd < 0)
263                         return LIBALTOS_ERROR;
264 #ifdef USE_POLL
265                 fd[0].fd = file->fd;
266                 fd[0].events = POLLIN|POLLERR|POLLHUP|POLLNVAL;
267                 fd[1].fd = file->pipe[0];
268                 fd[1].events = POLLIN;
269                 ret = poll(fd, 2, timeout);
270                 if (ret < 0) {
271                         altos_set_last_posix_error();
272                         return LIBALTOS_ERROR;
273                 }
274                 if (ret == 0)
275                         return LIBALTOS_TIMEOUT;
276
277                 if (fd[0].revents & (POLLHUP|POLLERR|POLLNVAL))
278                         return LIBALTOS_ERROR;
279                 if (fd[0].revents & POLLIN)
280 #endif
281                 {
282                         ret = read(file->fd, file->in_data, USB_BUF_SIZE);
283                         if (ret < 0) {
284                                 altos_set_last_posix_error();
285                                 return LIBALTOS_ERROR;
286                         }
287                         file->in_read = 0;
288                         file->in_used = ret;
289 #ifndef USE_POLL
290                         if (ret == 0 && timeout > 0)
291                                 return LIBALTOS_TIMEOUT;
292 #endif
293                 }
294         }
295         if (file->in_used && 0) {
296                 printf ("fill \"");
297                 fwrite(file->in_data, 1, file->in_used, stdout);
298                 printf ("\"\n");
299         }
300         return 0;
301 }
302
303 PUBLIC int
304 altos_getchar(struct altos_file *file, int timeout)
305 {
306         int     ret;
307         while (file->in_read == file->in_used) {
308                 if (file->fd < 0)
309                         return LIBALTOS_ERROR;
310                 ret = altos_fill(file, timeout);
311                 if (ret)
312                         return ret;
313         }
314         return file->in_data[file->in_read++];
315 }
316
317 #endif /* POSIX_TTY */
318
319 /*
320  * Scan for Altus Metrum devices by looking through /sys
321  */
322
323 #ifdef LINUX
324
325 #define _GNU_SOURCE
326 #include <ctype.h>
327 #include <dirent.h>
328 #include <stdio.h>
329 #include <stdlib.h>
330 #include <string.h>
331 #include <bluetooth/bluetooth.h>
332 #include <bluetooth/hci.h>
333 #include <bluetooth/hci_lib.h>
334 #include <bluetooth/rfcomm.h>
335
336 static char *
337 cc_fullname (char *dir, char *file)
338 {
339         char    *new;
340         int     dlen = strlen (dir);
341         int     flen = strlen (file);
342         int     slen = 0;
343
344         if (dir[dlen-1] != '/')
345                 slen = 1;
346         new = malloc (dlen + slen + flen + 1);
347         if (!new)
348                 return 0;
349         strcpy(new, dir);
350         if (slen)
351                 strcat (new, "/");
352         strcat(new, file);
353         return new;
354 }
355
356 static char *
357 cc_basename(char *file)
358 {
359         char *b;
360
361         b = strrchr(file, '/');
362         if (!b)
363                 return file;
364         return b + 1;
365 }
366
367 static char *
368 load_string(char *dir, char *file)
369 {
370         char    *full = cc_fullname(dir, file);
371         char    line[4096];
372         char    *r;
373         FILE    *f;
374         int     rlen;
375
376         f = fopen(full, "r");
377         free(full);
378         if (!f)
379                 return NULL;
380         r = fgets(line, sizeof (line), f);
381         fclose(f);
382         if (!r)
383                 return NULL;
384         rlen = strlen(r);
385         if (r[rlen-1] == '\n')
386                 r[rlen-1] = '\0';
387         return strdup(r);
388 }
389
390 static int
391 load_hex(char *dir, char *file)
392 {
393         char    *line;
394         char    *end;
395         long    i;
396
397         line = load_string(dir, file);
398         if (!line)
399                 return -1;
400         i = strtol(line, &end, 16);
401         free(line);
402         if (end == line)
403                 return -1;
404         return i;
405 }
406
407 static int
408 load_dec(char *dir, char *file)
409 {
410         char    *line;
411         char    *end;
412         long    i;
413
414         line = load_string(dir, file);
415         if (!line)
416                 return -1;
417         i = strtol(line, &end, 10);
418         free(line);
419         if (end == line)
420                 return -1;
421         return i;
422 }
423
424 static int
425 dir_filter_tty_colon(const struct dirent *d)
426 {
427         return strncmp(d->d_name, "tty:", 4) == 0;
428 }
429
430 static int
431 dir_filter_tty(const struct dirent *d)
432 {
433         return strncmp(d->d_name, "tty", 3) == 0;
434 }
435
436 struct altos_usbdev {
437         char    *sys;
438         char    *tty;
439         char    *manufacturer;
440         char    *product_name;
441         int     serial; /* AltOS always uses simple integer serial numbers */
442         int     idProduct;
443         int     idVendor;
444 };
445
446 static char *
447 usb_tty(char *sys)
448 {
449         char *base;
450         int num_configs;
451         int config;
452         struct dirent **namelist;
453         int interface;
454         int num_interfaces;
455         char endpoint_base[20];
456         char *endpoint_full;
457         char *tty_dir;
458         int ntty;
459         char *tty;
460
461         base = cc_basename(sys);
462         num_configs = load_hex(sys, "bNumConfigurations");
463         num_interfaces = load_hex(sys, "bNumInterfaces");
464         for (config = 1; config <= num_configs; config++) {
465                 for (interface = 0; interface < num_interfaces; interface++) {
466                         sprintf(endpoint_base, "%s:%d.%d",
467                                 base, config, interface);
468                         endpoint_full = cc_fullname(sys, endpoint_base);
469
470
471                         /* Check for tty:ttyACMx style names
472                          */
473                         ntty = scandir(endpoint_full, &namelist,
474                                        dir_filter_tty_colon,
475                                        alphasort);
476                         if (ntty > 0) {
477                                 free(endpoint_full);
478                                 tty = cc_fullname("/dev", namelist[0]->d_name + 4);
479                                 free(namelist);
480                                 return tty;
481                         }
482
483                         /* Check for tty/ttyACMx style names
484                          */
485                         tty_dir = cc_fullname(endpoint_full, "tty");
486                         ntty = scandir(tty_dir, &namelist,
487                                        dir_filter_tty,
488                                        alphasort);
489                         free (tty_dir);
490                         if (ntty > 0) {
491                                 tty = cc_fullname("/dev", namelist[0]->d_name);
492                                 free(endpoint_full);
493                                 free(namelist);
494                                 return tty;
495                         }
496
497                         /* Check for ttyACMx style names
498                          */
499                         ntty = scandir(endpoint_full, &namelist,
500                                        dir_filter_tty,
501                                        alphasort);
502                         free(endpoint_full);
503                         if (ntty > 0) {
504                                 tty = cc_fullname("/dev", namelist[0]->d_name);
505                                 free(namelist);
506                                 return tty;
507                         }
508
509                 }
510         }
511         return NULL;
512 }
513
514 static struct altos_usbdev *
515 usb_scan_device(char *sys)
516 {
517         struct altos_usbdev *usbdev;
518         char *tty;
519
520         tty = usb_tty(sys);
521         if (!tty)
522                 return NULL;
523         usbdev = calloc(1, sizeof (struct altos_usbdev));
524         if (!usbdev)
525                 return NULL;
526         usbdev->sys = strdup(sys);
527         usbdev->manufacturer = load_string(sys, "manufacturer");
528         usbdev->product_name = load_string(sys, "product");
529         usbdev->serial = load_dec(sys, "serial");
530         usbdev->idProduct = load_hex(sys, "idProduct");
531         usbdev->idVendor = load_hex(sys, "idVendor");
532         usbdev->tty = tty;
533         return usbdev;
534 }
535
536 static void
537 usbdev_free(struct altos_usbdev *usbdev)
538 {
539         free(usbdev->sys);
540         free(usbdev->manufacturer);
541         free(usbdev->product_name);
542         /* this can get used as a return value */
543         if (usbdev->tty)
544                 free(usbdev->tty);
545         free(usbdev);
546 }
547
548 #define USB_DEVICES     "/sys/bus/usb/devices"
549
550 static int
551 dir_filter_dev(const struct dirent *d)
552 {
553         const char      *n = d->d_name;
554         char    c;
555
556         while ((c = *n++)) {
557                 if (isdigit(c))
558                         continue;
559                 if (c == '-')
560                         continue;
561                 if (c == '.' && n != d->d_name + 1)
562                         continue;
563                 return 0;
564         }
565         return 1;
566 }
567
568 struct altos_list {
569         struct altos_usbdev     **dev;
570         int                     current;
571         int                     ndev;
572 };
573
574 struct altos_list *
575 altos_list_start(void)
576 {
577         int                     e;
578         struct dirent           **ents;
579         char                    *dir;
580         struct altos_usbdev     *dev;
581         struct altos_list       *devs;
582         int                     n;
583
584         devs = calloc(1, sizeof (struct altos_list));
585         if (!devs)
586                 return NULL;
587
588         n = scandir (USB_DEVICES, &ents,
589                      dir_filter_dev,
590                      alphasort);
591         if (!n)
592                 return 0;
593         for (e = 0; e < n; e++) {
594                 dir = cc_fullname(USB_DEVICES, ents[e]->d_name);
595                 dev = usb_scan_device(dir);
596                 if (!dev)
597                         continue;
598                 free(dir);
599                 if (devs->dev)
600                         devs->dev = realloc(devs->dev,
601                                             (devs->ndev + 1) * sizeof (struct usbdev *));
602                 else
603                         devs->dev = malloc (sizeof (struct usbdev *));
604                 devs->dev[devs->ndev++] = dev;
605         }
606         free(ents);
607         devs->current = 0;
608         return devs;
609 }
610
611 PUBLIC struct altos_list *
612 altos_ftdi_list_start(void)
613 {
614         return altos_list_start();
615 }
616
617 int
618 altos_list_next(struct altos_list *list, struct altos_device *device)
619 {
620         struct altos_usbdev *dev;
621         if (list->current >= list->ndev) {
622                 return 0;
623         }
624         dev = list->dev[list->current];
625         strcpy(device->name, dev->product_name);
626         device->vendor = dev->idVendor;
627         device->product = dev->idProduct;
628         strcpy(device->path, dev->tty);
629         device->serial = dev->serial;
630         list->current++;
631         return 1;
632 }
633
634 void
635 altos_list_finish(struct altos_list *usbdevs)
636 {
637         int     i;
638
639         if (!usbdevs)
640                 return;
641         for (i = 0; i < usbdevs->ndev; i++)
642                 usbdev_free(usbdevs->dev[i]);
643         free(usbdevs);
644 }
645
646 struct altos_bt_list {
647         inquiry_info    *ii;
648         int             sock;
649         int             dev_id;
650         int             rsp;
651         int             num_rsp;
652 };
653
654 #define INQUIRY_MAX_RSP 255
655
656 struct altos_bt_list *
657 altos_bt_list_start(int inquiry_time)
658 {
659         struct altos_bt_list    *bt_list;
660
661         bt_list = calloc(1, sizeof (struct altos_bt_list));
662         if (!bt_list)
663                 goto no_bt_list;
664
665         bt_list->ii = calloc(INQUIRY_MAX_RSP, sizeof (inquiry_info));
666         if (!bt_list->ii)
667                 goto no_ii;
668         bt_list->dev_id = hci_get_route(NULL);
669         if (bt_list->dev_id < 0)
670                 goto no_dev_id;
671
672         bt_list->sock = hci_open_dev(bt_list->dev_id);
673         if (bt_list->sock < 0)
674                 goto no_sock;
675
676         bt_list->num_rsp = hci_inquiry(bt_list->dev_id,
677                                        inquiry_time,
678                                        INQUIRY_MAX_RSP,
679                                        NULL,
680                                        &bt_list->ii,
681                                        IREQ_CACHE_FLUSH);
682         if (bt_list->num_rsp < 0)
683                 goto no_rsp;
684
685         bt_list->rsp = 0;
686         return bt_list;
687
688 no_rsp:
689         close(bt_list->sock);
690 no_sock:
691 no_dev_id:
692         free(bt_list->ii);
693 no_ii:
694         free(bt_list);
695 no_bt_list:
696         return NULL;
697 }
698
699 int
700 altos_bt_list_next(struct altos_bt_list *bt_list,
701                    struct altos_bt_device *device)
702 {
703         inquiry_info    *ii;
704
705         if (bt_list->rsp >= bt_list->num_rsp)
706                 return 0;
707
708         ii = &bt_list->ii[bt_list->rsp];
709         ba2str(&ii->bdaddr, device->addr);
710         memset(&device->name, '\0', sizeof (device->name));
711         if (hci_read_remote_name(bt_list->sock, &ii->bdaddr,
712                                  sizeof (device->name),
713                                  device->name, 0) < 0) {
714                 strcpy(device->name, "[unknown]");
715         }
716         bt_list->rsp++;
717         return 1;
718 }
719
720 void
721 altos_bt_list_finish(struct altos_bt_list *bt_list)
722 {
723         close(bt_list->sock);
724         free(bt_list->ii);
725         free(bt_list);
726 }
727
728 void
729 altos_bt_fill_in(char *name, char *addr, struct altos_bt_device *device)
730 {
731         strncpy(device->name, name, sizeof (device->name));
732         device->name[sizeof(device->name)-1] = '\0';
733         strncpy(device->addr, addr, sizeof (device->addr));
734         device->addr[sizeof(device->addr)-1] = '\0';
735 }
736
737 struct altos_file *
738 altos_bt_open(struct altos_bt_device *device)
739 {
740         struct sockaddr_rc addr = { 0 };
741         int     status, i;
742         struct altos_file *file;
743
744         file = calloc(1, sizeof (struct altos_file));
745         if (!file)
746                 goto no_file;
747         addr.rc_family = AF_BLUETOOTH;
748         addr.rc_channel = 1;
749         str2ba(device->addr, &addr.rc_bdaddr);
750
751         for (i = 0; i < 5; i++) {
752                 file->fd = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
753                 if (file->fd < 0) {
754                         altos_set_last_posix_error();
755                         goto no_sock;
756                 }
757
758                 status = connect(file->fd,
759                                  (struct sockaddr *)&addr,
760                                  sizeof(addr));
761                 if (status >= 0 || errno != EBUSY)
762                         break;
763                 close(file->fd);
764                 usleep(100 * 1000);
765         }
766         if (status < 0) {
767                 altos_set_last_posix_error();
768                 goto no_link;
769         }
770         usleep(100 * 1000);
771
772 #ifdef USE_POLL
773         pipe(file->pipe);
774 #else
775         file->out_fd = dup(file->fd);
776 #endif
777         return file;
778 no_link:
779         close(file->fd);
780 no_sock:
781         free(file);
782 no_file:
783         return NULL;
784 }
785
786 #endif
787
788 #ifdef DARWIN
789
790 #include <IOKitLib.h>
791 #include <IOKit/usb/USBspec.h>
792 #include <sys/param.h>
793 #include <paths.h>
794 #include <CFNumber.h>
795 #include <IOBSD.h>
796 #include <string.h>
797 #include <stdio.h>
798 #include <stdlib.h>
799
800 struct altos_list {
801         io_iterator_t iterator;
802         int ftdi;
803 };
804
805 static int
806 get_string(io_object_t object, CFStringRef entry, char *result, int result_len)
807 {
808         CFTypeRef entry_as_string;
809         Boolean got_string;
810
811         entry_as_string = IORegistryEntrySearchCFProperty (object,
812                                                            kIOServicePlane,
813                                                            entry,
814                                                            kCFAllocatorDefault,
815                                                            kIORegistryIterateRecursively);
816         if (entry_as_string) {
817                 got_string = CFStringGetCString(entry_as_string,
818                                                 result, result_len,
819                                                 kCFStringEncodingASCII);
820     
821                 CFRelease(entry_as_string);
822                 if (got_string)
823                         return 1;
824         }
825         return 0;
826 }
827
828 static int
829 get_number(io_object_t object, CFStringRef entry, int *result)
830 {
831         CFTypeRef entry_as_number;
832         Boolean got_number;
833         
834         entry_as_number = IORegistryEntrySearchCFProperty (object,
835                                                            kIOServicePlane,
836                                                            entry,
837                                                            kCFAllocatorDefault,
838                                                            kIORegistryIterateRecursively);
839         if (entry_as_number) {
840                 got_number = CFNumberGetValue(entry_as_number,
841                                               kCFNumberIntType,
842                                               result);
843                 if (got_number)
844                         return 1;
845         }
846         return 0;
847 }
848
849 PUBLIC struct altos_list *
850 altos_list_start(void)
851 {
852         struct altos_list *list = calloc (sizeof (struct altos_list), 1);
853         CFMutableDictionaryRef matching_dictionary = IOServiceMatching("IOUSBDevice");
854         io_iterator_t tdIterator;
855         io_object_t tdObject;
856         kern_return_t ret;
857         int i;
858
859         ret = IOServiceGetMatchingServices(kIOMasterPortDefault, matching_dictionary, &list->iterator);
860         if (ret != kIOReturnSuccess) {
861                 free(list);
862                 return NULL;
863         }
864         list->ftdi = 0;
865         return list;
866 }
867
868 PUBLIC struct altos_list *
869 altos_ftdi_list_start(void)
870 {
871         struct altos_list *list = altos_list_start();
872
873         if (list)
874                 list->ftdi = 1;
875         return list;
876 }
877
878 PUBLIC int
879 altos_list_next(struct altos_list *list, struct altos_device *device)
880 {
881         io_object_t object;
882         char serial_string[128];
883
884         for (;;) {
885                 object = IOIteratorNext(list->iterator);
886                 if (!object)
887                         return 0;
888   
889                 if (!get_number (object, CFSTR(kUSBVendorID), &device->vendor) ||
890                     !get_number (object, CFSTR(kUSBProductID), &device->product))
891                         continue;
892                 if (get_string (object, CFSTR("IOCalloutDevice"), device->path, sizeof (device->path)) &&
893                     get_string (object, CFSTR("USB Product Name"), device->name, sizeof (device->name)) &&
894                     get_string (object, CFSTR("USB Serial Number"), serial_string, sizeof (serial_string))) {
895                         device->serial = atoi(serial_string);
896                         return 1;
897                 }
898         }
899 }
900
901 PUBLIC void
902 altos_list_finish(struct altos_list *list)
903 {
904         IOObjectRelease (list->iterator);
905         free(list);
906 }
907
908 struct altos_bt_list {
909         int             sock;
910         int             dev_id;
911         int             rsp;
912         int             num_rsp;
913 };
914
915 #define INQUIRY_MAX_RSP 255
916
917 struct altos_bt_list *
918 altos_bt_list_start(int inquiry_time)
919 {
920         return NULL;
921 }
922
923 int
924 altos_bt_list_next(struct altos_bt_list *bt_list,
925                    struct altos_bt_device *device)
926 {
927         return 0;
928 }
929
930 void
931 altos_bt_list_finish(struct altos_bt_list *bt_list)
932 {
933 }
934
935 void
936 altos_bt_fill_in(char *name, char *addr, struct altos_bt_device *device)
937 {
938         strncpy(device->name, name, sizeof (device->name));
939         device->name[sizeof(device->name)-1] = '\0';
940         strncpy(device->addr, addr, sizeof (device->addr));
941         device->addr[sizeof(device->addr)-1] = '\0';
942 }
943
944 struct altos_file *
945 altos_bt_open(struct altos_bt_device *device)
946 {
947         return NULL;
948 }
949
950 #endif
951
952
953 #ifdef WINDOWS
954
955 #include <stdlib.h>
956 #include <windows.h>
957 #include <setupapi.h>
958
959 struct altos_list {
960         HDEVINFO        dev_info;
961         int             index;
962         int             ftdi;
963 };
964
965 #define USB_BUF_SIZE    64
966
967 struct altos_file {
968         HANDLE                          handle;
969         unsigned char                   out_data[USB_BUF_SIZE];
970         int                             out_used;
971         unsigned char                   in_data[USB_BUF_SIZE];
972         int                             in_used;
973         int                             in_read;
974         OVERLAPPED                      ov_read;
975         BOOL                            pend_read;
976         OVERLAPPED                      ov_write;
977 };
978
979 #include <stdarg.h>
980
981 static void
982 log_message(char *fmt, ...)
983 {
984         static  FILE *log = NULL;
985         va_list a;
986
987         if (!log)
988                 log = fopen("\\temp\\altos.txt", "w");
989         if (log) {
990                 SYSTEMTIME time;
991                 GetLocalTime(&time);
992                 fprintf (log, "%4d-%02d-%02d %2d:%02d:%02d. ", 
993                          time.wYear, time.wMonth, time.wDay,
994                          time.wHour, time.wMinute, time.wSecond);
995                 va_start(a, fmt);
996                 vfprintf(log, fmt, a);
997                 va_end(a);
998                 fflush(log);
999         }
1000 }
1001
1002 static void
1003 _altos_set_last_windows_error(char *file, int line)
1004 {
1005         DWORD   error = GetLastError();
1006         TCHAR   message[1024];
1007         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
1008                       0,
1009                       error,
1010                       0,
1011                       message,
1012                       sizeof (message) / sizeof (TCHAR),
1013                       NULL);
1014         if (error != ERROR_SUCCESS)
1015                 log_message ("%s:%d %s\n", file, line, message);
1016         altos_set_last_error(error, message);
1017 }
1018
1019 #define altos_set_last_windows_error() _altos_set_last_windows_error(__FILE__, __LINE__)
1020
1021 PUBLIC struct altos_list *
1022 altos_list_start(void)
1023 {
1024         struct altos_list       *list = calloc(1, sizeof (struct altos_list));
1025
1026         if (!list)
1027                 return NULL;
1028         list->dev_info = SetupDiGetClassDevs(NULL, "USB", NULL,
1029                                              DIGCF_ALLCLASSES|DIGCF_PRESENT);
1030         if (list->dev_info == INVALID_HANDLE_VALUE) {
1031                 altos_set_last_windows_error();
1032                 free(list);
1033                 return NULL;
1034         }
1035         list->index = 0;
1036         list->ftdi = 0;
1037         return list;
1038 }
1039
1040 PUBLIC struct altos_list *
1041 altos_ftdi_list_start(void)
1042 {
1043         struct altos_list       *list = calloc(1, sizeof (struct altos_list));
1044
1045         if (!list)
1046                 return NULL;
1047         list->dev_info = SetupDiGetClassDevs(NULL, "FTDIBUS", NULL,
1048                                              DIGCF_ALLCLASSES|DIGCF_PRESENT);
1049         if (list->dev_info == INVALID_HANDLE_VALUE) {
1050                 altos_set_last_windows_error();
1051                 free(list);
1052                 return NULL;
1053         }
1054         list->index = 0;
1055         list->ftdi = 1;
1056         return list;
1057 }
1058
1059 PUBLIC int
1060 altos_list_next(struct altos_list *list, struct altos_device *device)
1061 {
1062         SP_DEVINFO_DATA dev_info_data;
1063         BYTE            port[128];
1064         DWORD           port_len;
1065         char            friendlyname[256];
1066         BYTE            symbolic[256];
1067         DWORD           symbolic_len;
1068         HKEY            dev_key;
1069         unsigned int    vid, pid;
1070         int             serial;
1071         HRESULT         result;
1072         DWORD           friendlyname_type;
1073         DWORD           friendlyname_len;
1074
1075         dev_info_data.cbSize = sizeof (SP_DEVINFO_DATA);
1076         while(SetupDiEnumDeviceInfo(list->dev_info, list->index,
1077                                     &dev_info_data))
1078         {
1079                 list->index++;
1080
1081                 dev_key = SetupDiOpenDevRegKey(list->dev_info, &dev_info_data,
1082                                                DICS_FLAG_GLOBAL, 0, DIREG_DEV,
1083                                                KEY_READ);
1084                 if (dev_key == INVALID_HANDLE_VALUE) {
1085                         altos_set_last_windows_error();
1086                         continue;
1087                 }
1088
1089                 if (list->ftdi) {
1090                         vid = 0x0403;
1091                         pid = 0x6015;
1092                         serial = 0;
1093                 } else {
1094                         /* Fetch symbolic name for this device and parse out
1095                          * the vid/pid/serial info */
1096                         symbolic_len = sizeof(symbolic);
1097                         result = RegQueryValueEx(dev_key, "SymbolicName", NULL, NULL,
1098                                                  symbolic, &symbolic_len);
1099                         if (result != 0) {
1100                                 altos_set_last_windows_error();
1101                                 RegCloseKey(dev_key);
1102                                 continue;
1103                         }
1104                         vid = pid = serial = 0;
1105                         sscanf((char *) symbolic + sizeof("\\??\\USB#VID_") - 1,
1106                                "%04X", &vid);
1107                         sscanf((char *) symbolic + sizeof("\\??\\USB#VID_XXXX&PID_") - 1,
1108                                "%04X", &pid);
1109                         sscanf((char *) symbolic + sizeof("\\??\\USB#VID_XXXX&PID_XXXX#") - 1,
1110                                "%d", &serial);
1111                 }
1112
1113                 /* Fetch the com port name */
1114                 port_len = sizeof (port);
1115                 result = RegQueryValueEx(dev_key, "PortName", NULL, NULL,
1116                                          port, &port_len);
1117                 RegCloseKey(dev_key);
1118                 if (result != 0) {
1119                         altos_set_last_windows_error();
1120                         continue;
1121                 }
1122
1123                 /* Fetch the device description which is the device name,
1124                  * with firmware that has unique USB ids */
1125                 friendlyname_len = sizeof (friendlyname);
1126                 if(!SetupDiGetDeviceRegistryProperty(list->dev_info,
1127                                                      &dev_info_data,
1128                                                      SPDRP_FRIENDLYNAME,
1129                                                      &friendlyname_type,
1130                                                      (BYTE *)friendlyname,
1131                                                      sizeof(friendlyname),
1132                                                      &friendlyname_len))
1133                 {
1134                         altos_set_last_windows_error();
1135                         continue;
1136                 }
1137                 device->vendor = vid;
1138                 device->product = pid;
1139                 device->serial = serial;
1140                 strcpy(device->name, friendlyname);
1141
1142                 strcpy(device->path, (char *) port);
1143                 return 1;
1144         }
1145         result = GetLastError();
1146         if (result != ERROR_NO_MORE_ITEMS)
1147                 altos_set_last_windows_error();
1148         return 0;
1149 }
1150
1151 PUBLIC void
1152 altos_list_finish(struct altos_list *list)
1153 {
1154         SetupDiDestroyDeviceInfoList(list->dev_info);
1155         free(list);
1156 }
1157
1158 static int
1159 altos_queue_read(struct altos_file *file)
1160 {
1161         DWORD   got;
1162         if (file->pend_read)
1163                 return LIBALTOS_SUCCESS;
1164
1165         if (!ReadFile(file->handle, file->in_data, USB_BUF_SIZE, &got, &file->ov_read)) {
1166                 if (GetLastError() != ERROR_IO_PENDING) {
1167                         altos_set_last_windows_error();
1168                         return LIBALTOS_ERROR;
1169                 }
1170                 file->pend_read = TRUE;
1171         } else {
1172                 file->pend_read = FALSE;
1173                 file->in_read = 0;
1174                 file->in_used = got;
1175         }
1176         return LIBALTOS_SUCCESS;
1177 }
1178
1179 static int
1180 altos_wait_read(struct altos_file *file, int timeout)
1181 {
1182         DWORD   ret;
1183         DWORD   got;
1184
1185         if (!file->pend_read)
1186                 return LIBALTOS_SUCCESS;
1187
1188         if (!timeout)
1189                 timeout = INFINITE;
1190
1191         ret = WaitForSingleObject(file->ov_read.hEvent, timeout);
1192         switch (ret) {
1193         case WAIT_OBJECT_0:
1194                 if (!GetOverlappedResult(file->handle, &file->ov_read, &got, FALSE)) {
1195                         altos_set_last_windows_error();
1196                         return LIBALTOS_ERROR;
1197                 }
1198                 file->pend_read = FALSE;
1199                 file->in_read = 0;
1200                 file->in_used = got;
1201                 break;
1202         case WAIT_TIMEOUT:
1203                 return LIBALTOS_TIMEOUT;
1204                 break;
1205         default:
1206                 altos_set_last_windows_error();
1207                 return LIBALTOS_ERROR;
1208         }
1209         return LIBALTOS_SUCCESS;
1210 }
1211
1212 static int
1213 altos_fill(struct altos_file *file, int timeout)
1214 {
1215         int     ret;
1216
1217         if (file->in_read < file->in_used)
1218                 return LIBALTOS_SUCCESS;
1219
1220         file->in_read = file->in_used = 0;
1221
1222         ret = altos_queue_read(file);
1223         if (ret)
1224                 return ret;
1225         ret = altos_wait_read(file, timeout);
1226         if (ret)
1227                 return ret;
1228
1229         return LIBALTOS_SUCCESS;
1230 }
1231
1232 PUBLIC int
1233 altos_flush(struct altos_file *file)
1234 {
1235         DWORD           put;
1236         unsigned char   *data = file->out_data;
1237         int             used = file->out_used;
1238         DWORD           ret;
1239
1240         while (used) {
1241                 if (!WriteFile(file->handle, data, used, &put, &file->ov_write)) {
1242                         if (GetLastError() != ERROR_IO_PENDING) {
1243                                 altos_set_last_windows_error();
1244                                 return LIBALTOS_ERROR;
1245                         }
1246                         ret = WaitForSingleObject(file->ov_write.hEvent, INFINITE);
1247                         switch (ret) {
1248                         case WAIT_OBJECT_0:
1249                                 if (!GetOverlappedResult(file->handle, &file->ov_write, &put, FALSE)) {
1250                                         altos_set_last_windows_error();
1251                                         return LIBALTOS_ERROR;
1252                                 }
1253                                 break;
1254                         default:
1255                                 altos_set_last_windows_error();
1256                                 return LIBALTOS_ERROR;
1257                         }
1258                 }
1259                 data += put;
1260                 used -= put;
1261         }
1262         file->out_used = 0;
1263         return LIBALTOS_SUCCESS;
1264 }
1265
1266 static HANDLE
1267 open_serial(char *full_name)
1268 {
1269         HANDLE  handle;
1270         DCB     dcb;
1271
1272         handle = CreateFile(full_name, GENERIC_READ|GENERIC_WRITE,
1273                             0, NULL, OPEN_EXISTING,
1274                             FILE_FLAG_OVERLAPPED, NULL);
1275
1276         if (handle == INVALID_HANDLE_VALUE) {
1277                 altos_set_last_windows_error();
1278                 return INVALID_HANDLE_VALUE;
1279         }
1280
1281         if (!GetCommState(handle, &dcb)) {
1282                 altos_set_last_windows_error();
1283                 CloseHandle(handle);
1284                 return INVALID_HANDLE_VALUE;
1285         }
1286         dcb.BaudRate = CBR_9600;
1287         dcb.fBinary = TRUE;
1288         dcb.fParity = FALSE;
1289         dcb.fOutxCtsFlow = FALSE;
1290         dcb.fOutxDsrFlow = FALSE;
1291         dcb.fDtrControl = DTR_CONTROL_ENABLE;
1292         dcb.fDsrSensitivity = FALSE;
1293         dcb.fTXContinueOnXoff = FALSE;
1294         dcb.fOutX = FALSE;
1295         dcb.fInX = FALSE;
1296         dcb.fErrorChar = FALSE;
1297         dcb.fNull = FALSE;
1298         dcb.fRtsControl = RTS_CONTROL_ENABLE;
1299         dcb.fAbortOnError = FALSE;
1300         dcb.XonLim = 10;
1301         dcb.XoffLim = 10;
1302         dcb.ByteSize = 8;
1303         dcb.Parity = NOPARITY;
1304         dcb.StopBits = ONESTOPBIT;
1305         dcb.XonChar = 17;
1306         dcb.XoffChar = 19;
1307 #if 0
1308         dcb.ErrorChar = 0;
1309         dcb.EofChar = 0;
1310         dcb.EvtChar = 0;
1311 #endif
1312         if (!SetCommState(handle, &dcb)) {
1313                 altos_set_last_windows_error();
1314                 CloseHandle(handle);
1315                 return INVALID_HANDLE_VALUE;
1316         }
1317         return handle;
1318 }
1319
1320 PUBLIC struct altos_file *
1321 altos_open(struct altos_device *device)
1322 {
1323         struct altos_file       *file = calloc (1, sizeof (struct altos_file));
1324         char    full_name[64];
1325         COMMTIMEOUTS timeouts;
1326         int i;
1327
1328         if (!file)
1329                 return NULL;
1330
1331         strcpy(full_name, "\\\\.\\");
1332         strcat(full_name, device->path);
1333
1334         file->handle = INVALID_HANDLE_VALUE;
1335
1336         for (i = 0; i < 5; i++) {
1337                 file->handle = open_serial(full_name);
1338                 if (file->handle != INVALID_HANDLE_VALUE)
1339                         break;
1340                 altos_set_last_windows_error();
1341                 Sleep(100);
1342         }
1343         
1344         if (file->handle == INVALID_HANDLE_VALUE) {
1345                 free(file);
1346                 return NULL;
1347         }
1348
1349         /* The FTDI driver doesn't appear to work right unless you open it twice */
1350         if (device->vendor == 0x0403) {
1351                 CloseHandle(file->handle);
1352                 file->handle = open_serial(full_name);
1353                 if (file->handle == INVALID_HANDLE_VALUE) {
1354                         free(file);
1355                         return NULL;
1356                 }
1357         }
1358
1359         timeouts.ReadIntervalTimeout = MAXDWORD;
1360         timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1361         timeouts.ReadTotalTimeoutConstant = 1 << 30;    /* almost forever */
1362         timeouts.WriteTotalTimeoutMultiplier = 0;
1363         timeouts.WriteTotalTimeoutConstant = 0;
1364         SetCommTimeouts(file->handle, &timeouts);
1365
1366         file->ov_read.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1367         file->ov_write.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1368
1369         return file;
1370 }
1371
1372 PUBLIC void
1373 altos_close(struct altos_file *file)
1374 {
1375         HANDLE  handle = file->handle;
1376         if (handle != INVALID_HANDLE_VALUE) {
1377                 HANDLE  ov_read = file->ov_read.hEvent;
1378                 HANDLE  ov_write = file->ov_write.hEvent;
1379                 file->handle = INVALID_HANDLE_VALUE;
1380                 file->ov_read.hEvent = INVALID_HANDLE_VALUE;
1381                 file->ov_write.hEvent = INVALID_HANDLE_VALUE;
1382                 PurgeComm(handle, PURGE_RXABORT|PURGE_RXCLEAR|PURGE_TXABORT|PURGE_TXCLEAR);
1383                 Sleep(100);
1384                 CloseHandle(handle);
1385                 file->handle = INVALID_HANDLE_VALUE;
1386                 CloseHandle(ov_read);
1387                 CloseHandle(ov_write);
1388         }
1389 }
1390
1391 PUBLIC void
1392 altos_free(struct altos_file *file)
1393 {
1394         altos_close(file);
1395         free(file);
1396 }
1397
1398 PUBLIC int
1399 altos_putchar(struct altos_file *file, char c)
1400 {
1401         int     ret;
1402
1403         if (file->out_used == USB_BUF_SIZE) {
1404                 ret = altos_flush(file);
1405                 if (ret)
1406                         return ret;
1407         }
1408         file->out_data[file->out_used++] = c;
1409         if (file->out_used == USB_BUF_SIZE)
1410                 return altos_flush(file);
1411         return LIBALTOS_SUCCESS;
1412 }
1413
1414 PUBLIC int
1415 altos_getchar(struct altos_file *file, int timeout)
1416 {
1417         int     ret;
1418         while (file->in_read == file->in_used) {
1419                 if (file->handle == INVALID_HANDLE_VALUE) {
1420                         altos_set_last_windows_error();
1421                         return LIBALTOS_ERROR;
1422                 }
1423                 ret = altos_fill(file, timeout);
1424                 if (ret)
1425                         return ret;
1426         }
1427         return file->in_data[file->in_read++];
1428 }
1429
1430 struct altos_bt_list *
1431 altos_bt_list_start(int inquiry_time)
1432 {
1433         return NULL;
1434 }
1435
1436 int
1437 altos_bt_list_next(struct altos_bt_list *bt_list,
1438                    struct altos_bt_device *device)
1439 {
1440         return 0;
1441 }
1442
1443 void
1444 altos_bt_list_finish(struct altos_bt_list *bt_list)
1445 {
1446         free(bt_list);
1447 }
1448
1449 void
1450 altos_bt_fill_in(char *name, char *addr, struct altos_bt_device *device)
1451 {
1452         strncpy(device->name, name, sizeof (device->name));
1453         device->name[sizeof(device->name)-1] = '\0';
1454         strncpy(device->addr, addr, sizeof (device->addr));
1455         device->addr[sizeof(device->addr)-1] = '\0';
1456 }
1457
1458 struct altos_file *
1459 altos_bt_open(struct altos_bt_device *device)
1460 {
1461         return NULL;
1462 }
1463
1464 #endif