altosui: Make flight data download work through TeleBT
[fw/altos] / altosui / 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 USE_POLL
24
25 PUBLIC int
26 altos_init(void)
27 {
28         return LIBALTOS_SUCCESS;
29 }
30
31 PUBLIC void
32 altos_fini(void)
33 {
34 }
35
36 #ifdef DARWIN
37
38 #undef USE_POLL
39
40 /* Mac OS X don't have strndup even if _GNU_SOURCE is defined */
41 static char *
42 altos_strndup (const char *s, size_t n)
43 {
44     size_t len = strlen (s);
45     char *ret;
46
47     if (len <= n)
48        return strdup (s);
49     ret = malloc(n + 1);
50     strncpy(ret, s, n);
51     ret[n] = '\0';
52     return ret;
53 }
54
55 #else
56 #define altos_strndup strndup
57 #endif
58
59 #ifdef POSIX_TTY
60
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <fcntl.h>
64 #include <termios.h>
65 #include <errno.h>
66
67 #define USB_BUF_SIZE    64
68
69 struct altos_file {
70         int                             fd;
71 #ifdef USE_POLL
72         int                             pipe[2];
73 #else
74         int                             out_fd;
75 #endif
76         unsigned char                   out_data[USB_BUF_SIZE];
77         int                             out_used;
78         unsigned char                   in_data[USB_BUF_SIZE];
79         int                             in_used;
80         int                             in_read;
81 };
82
83 PUBLIC struct altos_file *
84 altos_open(struct altos_device *device)
85 {
86         struct altos_file       *file = calloc (sizeof (struct altos_file), 1);
87         int                     ret;
88         struct termios          term;
89
90         if (!file)
91                 return NULL;
92
93         file->fd = open(device->path, O_RDWR | O_NOCTTY);
94         if (file->fd < 0) {
95                 perror(device->path);
96                 free(file);
97                 return NULL;
98         }
99 #ifdef USE_POLL
100         pipe(file->pipe);
101 #else
102         file->out_fd = open(device->path, O_RDWR | O_NOCTTY);
103         if (file->out_fd < 0) {
104                 perror(device->path);
105                 close(file->fd);
106                 free(file);
107                 return NULL;
108         }
109 #endif
110         ret = tcgetattr(file->fd, &term);
111         if (ret < 0) {
112                 perror("tcgetattr");
113                 close(file->fd);
114 #ifndef USE_POLL
115                 close(file->out_fd);
116 #endif
117                 free(file);
118                 return NULL;
119         }
120         cfmakeraw(&term);
121 #ifdef USE_POLL
122         term.c_cc[VMIN] = 1;
123         term.c_cc[VTIME] = 0;
124 #else
125         term.c_cc[VMIN] = 0;
126         term.c_cc[VTIME] = 1;
127 #endif
128         ret = tcsetattr(file->fd, TCSAFLUSH, &term);
129         if (ret < 0) {
130                 perror("tcsetattr");
131                 close(file->fd);
132 #ifndef USE_POLL
133                 close(file->out_fd);
134 #endif
135                 free(file);
136                 return NULL;
137         }
138         return file;
139 }
140
141 PUBLIC void
142 altos_close(struct altos_file *file)
143 {
144         if (file->fd != -1) {
145                 int     fd = file->fd;
146                 file->fd = -1;
147 #ifdef USE_POLL
148                 write(file->pipe[1], "\r", 1);
149 #else
150                 close(file->out_fd);
151                 file->out_fd = -1;
152 #endif
153                 close(fd);
154         }
155 }
156
157 PUBLIC void
158 altos_free(struct altos_file *file)
159 {
160         altos_close(file);
161         free(file);
162 }
163
164 PUBLIC int
165 altos_flush(struct altos_file *file)
166 {
167         if (file->out_used && 0) {
168                 printf ("flush \"");
169                 fwrite(file->out_data, 1, file->out_used, stdout);
170                 printf ("\"\n");
171         }
172         while (file->out_used) {
173                 int     ret;
174
175                 if (file->fd < 0)
176                         return -EBADF;
177 #ifdef USE_POLL
178                 ret = write (file->fd, file->out_data, file->out_used);
179 #else
180                 ret = write (file->out_fd, file->out_data, file->out_used);
181 #endif
182                 if (ret < 0)
183                         return -errno;
184                 if (ret) {
185                         memmove(file->out_data, file->out_data + ret,
186                                 file->out_used - ret);
187                         file->out_used -= ret;
188                 }
189         }
190         return 0;
191 }
192
193 PUBLIC int
194 altos_putchar(struct altos_file *file, char c)
195 {
196         int     ret;
197
198         if (file->out_used == USB_BUF_SIZE) {
199                 ret = altos_flush(file);
200                 if (ret) {
201                         return ret;
202                 }
203         }
204         file->out_data[file->out_used++] = c;
205         ret = 0;
206         if (file->out_used == USB_BUF_SIZE)
207                 ret = altos_flush(file);
208         return 0;
209 }
210
211 #ifdef USE_POLL
212 #include <poll.h>
213 #endif
214
215 static int
216 altos_fill(struct altos_file *file, int timeout)
217 {
218         int             ret;
219 #ifdef USE_POLL
220         struct pollfd   fd[2];
221 #endif
222
223         if (timeout == 0)
224                 timeout = -1;
225         while (file->in_read == file->in_used) {
226                 if (file->fd < 0)
227                         return LIBALTOS_ERROR;
228 #ifdef USE_POLL
229                 fd[0].fd = file->fd;
230                 fd[0].events = POLLIN|POLLERR|POLLHUP|POLLNVAL;
231                 fd[1].fd = file->pipe[0];
232                 fd[1].events = POLLIN;
233                 ret = poll(fd, 2, timeout);
234                 if (ret < 0) {
235                         perror("altos_getchar");
236                         return LIBALTOS_ERROR;
237                 }
238                 if (ret == 0)
239                         return LIBALTOS_TIMEOUT;
240
241                 if (fd[0].revents & (POLLHUP|POLLERR|POLLNVAL))
242                         return LIBALTOS_ERROR;
243                 if (fd[0].revents & POLLIN)
244 #endif
245                 {
246                         ret = read(file->fd, file->in_data, USB_BUF_SIZE);
247                         if (ret < 0) {
248                                 perror("altos_getchar");
249                                 return LIBALTOS_ERROR;
250                         }
251                         file->in_read = 0;
252                         file->in_used = ret;
253 #ifndef USE_POLL
254                         if (ret == 0 && timeout > 0)
255                                 return LIBALTOS_TIMEOUT;
256 #endif
257                 }
258         }
259         if (file->in_used && 0) {
260                 printf ("fill \"");
261                 fwrite(file->in_data, 1, file->in_used, stdout);
262                 printf ("\"\n");
263         }
264         return 0;
265 }
266
267 PUBLIC int
268 altos_getchar(struct altos_file *file, int timeout)
269 {
270         int     ret;
271         while (file->in_read == file->in_used) {
272                 if (file->fd < 0)
273                         return LIBALTOS_ERROR;
274                 ret = altos_fill(file, timeout);
275                 if (ret)
276                         return ret;
277         }
278         return file->in_data[file->in_read++];
279 }
280
281 #endif /* POSIX_TTY */
282
283 /*
284  * Scan for Altus Metrum devices by looking through /sys
285  */
286
287 #ifdef LINUX
288
289 #define _GNU_SOURCE
290 #include <ctype.h>
291 #include <dirent.h>
292 #include <stdio.h>
293 #include <stdlib.h>
294 #include <string.h>
295 #include <bluetooth/bluetooth.h>
296 #include <bluetooth/hci.h>
297 #include <bluetooth/hci_lib.h>
298 #include <bluetooth/rfcomm.h>
299
300 static char *
301 cc_fullname (char *dir, char *file)
302 {
303         char    *new;
304         int     dlen = strlen (dir);
305         int     flen = strlen (file);
306         int     slen = 0;
307
308         if (dir[dlen-1] != '/')
309                 slen = 1;
310         new = malloc (dlen + slen + flen + 1);
311         if (!new)
312                 return 0;
313         strcpy(new, dir);
314         if (slen)
315                 strcat (new, "/");
316         strcat(new, file);
317         return new;
318 }
319
320 static char *
321 cc_basename(char *file)
322 {
323         char *b;
324
325         b = strrchr(file, '/');
326         if (!b)
327                 return file;
328         return b + 1;
329 }
330
331 static char *
332 load_string(char *dir, char *file)
333 {
334         char    *full = cc_fullname(dir, file);
335         char    line[4096];
336         char    *r;
337         FILE    *f;
338         int     rlen;
339
340         f = fopen(full, "r");
341         free(full);
342         if (!f)
343                 return NULL;
344         r = fgets(line, sizeof (line), f);
345         fclose(f);
346         if (!r)
347                 return NULL;
348         rlen = strlen(r);
349         if (r[rlen-1] == '\n')
350                 r[rlen-1] = '\0';
351         return strdup(r);
352 }
353
354 static int
355 load_hex(char *dir, char *file)
356 {
357         char    *line;
358         char    *end;
359         long    i;
360
361         line = load_string(dir, file);
362         if (!line)
363                 return -1;
364         i = strtol(line, &end, 16);
365         free(line);
366         if (end == line)
367                 return -1;
368         return i;
369 }
370
371 static int
372 load_dec(char *dir, char *file)
373 {
374         char    *line;
375         char    *end;
376         long    i;
377
378         line = load_string(dir, file);
379         if (!line)
380                 return -1;
381         i = strtol(line, &end, 10);
382         free(line);
383         if (end == line)
384                 return -1;
385         return i;
386 }
387
388 static int
389 dir_filter_tty_colon(const struct dirent *d)
390 {
391         return strncmp(d->d_name, "tty:", 4) == 0;
392 }
393
394 static int
395 dir_filter_tty(const struct dirent *d)
396 {
397         return strncmp(d->d_name, "tty", 3) == 0;
398 }
399
400 struct altos_usbdev {
401         char    *sys;
402         char    *tty;
403         char    *manufacturer;
404         char    *product_name;
405         int     serial; /* AltOS always uses simple integer serial numbers */
406         int     idProduct;
407         int     idVendor;
408 };
409
410 static char *
411 usb_tty(char *sys)
412 {
413         char *base;
414         int num_configs;
415         int config;
416         struct dirent **namelist;
417         int interface;
418         int num_interfaces;
419         char endpoint_base[20];
420         char *endpoint_full;
421         char *tty_dir;
422         int ntty;
423         char *tty;
424
425         base = cc_basename(sys);
426         num_configs = load_hex(sys, "bNumConfigurations");
427         num_interfaces = load_hex(sys, "bNumInterfaces");
428         for (config = 1; config <= num_configs; config++) {
429                 for (interface = 0; interface < num_interfaces; interface++) {
430                         sprintf(endpoint_base, "%s:%d.%d",
431                                 base, config, interface);
432                         endpoint_full = cc_fullname(sys, endpoint_base);
433
434                         /* Check for tty:ttyACMx style names
435                          */
436                         ntty = scandir(endpoint_full, &namelist,
437                                        dir_filter_tty_colon,
438                                        alphasort);
439                         if (ntty > 0) {
440                                 free(endpoint_full);
441                                 tty = cc_fullname("/dev", namelist[0]->d_name + 4);
442                                 free(namelist);
443                                 return tty;
444                         }
445
446                         /* Check for tty/ttyACMx style names
447                          */
448                         tty_dir = cc_fullname(endpoint_full, "tty");
449                         free(endpoint_full);
450                         ntty = scandir(tty_dir, &namelist,
451                                        dir_filter_tty,
452                                        alphasort);
453                         free (tty_dir);
454                         if (ntty > 0) {
455                                 tty = cc_fullname("/dev", namelist[0]->d_name);
456                                 free(namelist);
457                                 return tty;
458                         }
459                 }
460         }
461         return NULL;
462 }
463
464 static struct altos_usbdev *
465 usb_scan_device(char *sys)
466 {
467         struct altos_usbdev *usbdev;
468
469         usbdev = calloc(1, sizeof (struct altos_usbdev));
470         if (!usbdev)
471                 return NULL;
472         usbdev->sys = strdup(sys);
473         usbdev->manufacturer = load_string(sys, "manufacturer");
474         usbdev->product_name = load_string(sys, "product");
475         usbdev->serial = load_dec(sys, "serial");
476         usbdev->idProduct = load_hex(sys, "idProduct");
477         usbdev->idVendor = load_hex(sys, "idVendor");
478         usbdev->tty = usb_tty(sys);
479         return usbdev;
480 }
481
482 static void
483 usbdev_free(struct altos_usbdev *usbdev)
484 {
485         free(usbdev->sys);
486         free(usbdev->manufacturer);
487         free(usbdev->product_name);
488         /* this can get used as a return value */
489         if (usbdev->tty)
490                 free(usbdev->tty);
491         free(usbdev);
492 }
493
494 #define USB_DEVICES     "/sys/bus/usb/devices"
495
496 static int
497 dir_filter_dev(const struct dirent *d)
498 {
499         const char      *n = d->d_name;
500         char    c;
501
502         while ((c = *n++)) {
503                 if (isdigit(c))
504                         continue;
505                 if (c == '-')
506                         continue;
507                 if (c == '.' && n != d->d_name + 1)
508                         continue;
509                 return 0;
510         }
511         return 1;
512 }
513
514 struct altos_list {
515         struct altos_usbdev     **dev;
516         int                     current;
517         int                     ndev;
518 };
519
520 struct altos_list *
521 altos_list_start(void)
522 {
523         int                     e;
524         struct dirent           **ents;
525         char                    *dir;
526         struct altos_usbdev     *dev;
527         struct altos_list       *devs;
528         int                     n;
529
530         devs = calloc(1, sizeof (struct altos_list));
531         if (!devs)
532                 return NULL;
533
534         n = scandir (USB_DEVICES, &ents,
535                      dir_filter_dev,
536                      alphasort);
537         if (!n)
538                 return 0;
539         for (e = 0; e < n; e++) {
540                 dir = cc_fullname(USB_DEVICES, ents[e]->d_name);
541                 dev = usb_scan_device(dir);
542                 free(dir);
543                 if (USB_IS_ALTUSMETRUM(dev->idVendor, dev->idProduct)) {
544                         if (devs->dev)
545                                 devs->dev = realloc(devs->dev,
546                                                     devs->ndev + 1 * sizeof (struct usbdev *));
547                         else
548                                 devs->dev = malloc (sizeof (struct usbdev *));
549                         devs->dev[devs->ndev++] = dev;
550                 }
551         }
552         free(ents);
553         devs->current = 0;
554         return devs;
555 }
556
557 int
558 altos_list_next(struct altos_list *list, struct altos_device *device)
559 {
560         struct altos_usbdev *dev;
561         if (list->current >= list->ndev)
562                 return 0;
563         dev = list->dev[list->current];
564         strcpy(device->name, dev->product_name);
565         device->vendor = dev->idVendor;
566         device->product = dev->idProduct;
567         strcpy(device->path, dev->tty);
568         device->serial = dev->serial;
569         list->current++;
570         return 1;
571 }
572
573 void
574 altos_list_finish(struct altos_list *usbdevs)
575 {
576         int     i;
577
578         if (!usbdevs)
579                 return;
580         for (i = 0; i < usbdevs->ndev; i++)
581                 usbdev_free(usbdevs->dev[i]);
582         free(usbdevs);
583 }
584
585 struct altos_bt_list {
586         inquiry_info    *ii;
587         int             sock;
588         int             dev_id;
589         int             rsp;
590         int             num_rsp;
591 };
592
593 #define INQUIRY_MAX_RSP 255
594
595 struct altos_bt_list *
596 altos_bt_list_start(int inquiry_time)
597 {
598         struct altos_bt_list    *bt_list;
599
600         bt_list = calloc(1, sizeof (struct altos_bt_list));
601         if (!bt_list)
602                 goto no_bt_list;
603
604         bt_list->ii = calloc(INQUIRY_MAX_RSP, sizeof (inquiry_info));
605         if (!bt_list->ii)
606                 goto no_ii;
607         bt_list->dev_id = hci_get_route(NULL);
608         if (bt_list->dev_id < 0)
609                 goto no_dev_id;
610
611         bt_list->sock = hci_open_dev(bt_list->dev_id);
612         if (bt_list->sock < 0)
613                 goto no_sock;
614
615         bt_list->num_rsp = hci_inquiry(bt_list->dev_id,
616                                        inquiry_time,
617                                        INQUIRY_MAX_RSP,
618                                        NULL,
619                                        &bt_list->ii,
620                                        IREQ_CACHE_FLUSH);
621         if (bt_list->num_rsp < 0)
622                 goto no_rsp;
623
624         bt_list->rsp = 0;
625         return bt_list;
626
627 no_rsp:
628         close(bt_list->sock);
629 no_sock:
630 no_dev_id:
631         free(bt_list->ii);
632 no_ii:
633         free(bt_list);
634 no_bt_list:
635         return NULL;
636 }
637
638 int
639 altos_bt_list_next(struct altos_bt_list *bt_list,
640                    struct altos_bt_device *device)
641 {
642         inquiry_info    *ii;
643
644         if (bt_list->rsp >= bt_list->num_rsp)
645                 return 0;
646
647         ii = &bt_list->ii[bt_list->rsp];
648         ba2str(&ii->bdaddr, device->addr);
649         memset(&device->name, '\0', sizeof (device->name));
650         if (hci_read_remote_name(bt_list->sock, &ii->bdaddr,
651                                  sizeof (device->name),
652                                  device->name, 0) < 0) {
653                 strcpy(device->name, "[unknown]");
654         }
655         bt_list->rsp++;
656         return 1;
657 }
658
659 void
660 altos_bt_list_finish(struct altos_bt_list *bt_list)
661 {
662         close(bt_list->sock);
663         free(bt_list->ii);
664         free(bt_list);
665 }
666
667 void
668 altos_bt_fill_in(char *name, char *addr, struct altos_bt_device *device)
669 {
670         strncpy(device->name, name, sizeof (device->name));
671         device->name[sizeof(device->name)-1] = '\0';
672         strncpy(device->addr, addr, sizeof (device->addr));
673         device->addr[sizeof(device->addr)-1] = '\0';
674 }
675
676 struct altos_file *
677 altos_bt_open(struct altos_bt_device *device)
678 {
679         struct sockaddr_rc addr = { 0 };
680         int     s, status;
681         struct altos_file *file;
682
683         file = calloc(1, sizeof (struct altos_file));
684         if (!file)
685                 goto no_file;
686         file->fd = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
687         if (file->fd < 0)
688                 goto no_sock;
689
690         addr.rc_family = AF_BLUETOOTH;
691         addr.rc_channel = 1;
692         str2ba(device->addr, &addr.rc_bdaddr);
693
694         status = connect(file->fd,
695                          (struct sockaddr *)&addr,
696                          sizeof(addr));
697         if (status < 0) {
698                 perror("connect");
699                 goto no_link;
700         }
701         sleep(1);
702
703 #ifdef USE_POLL
704         pipe(file->pipe);
705 #else
706         file->out_fd = dup(file->fd);
707 #endif
708         return file;
709 no_link:
710         close(s);
711 no_sock:
712         free(file);
713 no_file:
714         return NULL;
715 }
716
717 #endif
718
719 #ifdef DARWIN
720
721 #include <IOKitLib.h>
722 #include <IOKit/usb/USBspec.h>
723 #include <sys/param.h>
724 #include <paths.h>
725 #include <CFNumber.h>
726 #include <IOBSD.h>
727 #include <string.h>
728 #include <stdio.h>
729 #include <stdlib.h>
730
731 struct altos_list {
732         io_iterator_t iterator;
733 };
734
735 static int
736 get_string(io_object_t object, CFStringRef entry, char *result, int result_len)
737 {
738         CFTypeRef entry_as_string;
739         Boolean got_string;
740
741         entry_as_string = IORegistryEntrySearchCFProperty (object,
742                                                            kIOServicePlane,
743                                                            entry,
744                                                            kCFAllocatorDefault,
745                                                            kIORegistryIterateRecursively);
746         if (entry_as_string) {
747                 got_string = CFStringGetCString(entry_as_string,
748                                                 result, result_len,
749                                                 kCFStringEncodingASCII);
750     
751                 CFRelease(entry_as_string);
752                 if (got_string)
753                         return 1;
754         }
755         return 0;
756 }
757
758 static int
759 get_number(io_object_t object, CFStringRef entry, int *result)
760 {
761         CFTypeRef entry_as_number;
762         Boolean got_number;
763         
764         entry_as_number = IORegistryEntrySearchCFProperty (object,
765                                                            kIOServicePlane,
766                                                            entry,
767                                                            kCFAllocatorDefault,
768                                                            kIORegistryIterateRecursively);
769         if (entry_as_number) {
770                 got_number = CFNumberGetValue(entry_as_number,
771                                               kCFNumberIntType,
772                                               result);
773                 if (got_number)
774                         return 1;
775         }
776         return 0;
777 }
778
779 struct altos_list *
780 altos_list_start(int time)
781 {
782         struct altos_list *list = calloc (sizeof (struct altos_list), 1);
783         CFMutableDictionaryRef matching_dictionary = IOServiceMatching("IOUSBDevice");
784         io_iterator_t tdIterator;
785         io_object_t tdObject;
786         kern_return_t ret;
787         int i;
788
789         ret = IOServiceGetMatchingServices(kIOMasterPortDefault, matching_dictionary, &list->iterator);
790         if (ret != kIOReturnSuccess)
791                 return NULL;
792         return list;
793 }
794
795 int
796 altos_list_next(struct altos_list *list, struct altos_device *device)
797 {
798         io_object_t object;
799         char serial_string[128];
800
801         for (;;) {
802                 object = IOIteratorNext(list->iterator);
803                 if (!object)
804                         return 0;
805   
806                 if (!get_number (object, CFSTR(kUSBVendorID), &device->vendor) ||
807                     !get_number (object, CFSTR(kUSBProductID), &device->product))
808                         continue;
809                 if (device->vendor != 0xfffe)
810                         continue;
811                 if (device->product < 0x000a || 0x0013 < device->product)
812                         continue;
813                 if (get_string (object, CFSTR("IOCalloutDevice"), device->path, sizeof (device->path)) &&
814                     get_string (object, CFSTR("USB Product Name"), device->name, sizeof (device->name)) &&
815                     get_string (object, CFSTR("USB Serial Number"), serial_string, sizeof (serial_string))) {
816                         device->serial = atoi(serial_string);
817                         return 1;
818                 }
819         }
820 }
821
822 void
823 altos_list_finish(struct altos_list *list)
824 {
825         IOObjectRelease (list->iterator);
826         free(list);
827 }
828
829 #endif
830
831
832 #ifdef WINDOWS
833
834 #include <stdlib.h>
835 #include <windows.h>
836 #include <setupapi.h>
837
838 struct altos_list {
839         HDEVINFO        dev_info;
840         int             index;
841 };
842
843 #define USB_BUF_SIZE    64
844
845 struct altos_file {
846         HANDLE                          handle;
847         unsigned char                   out_data[USB_BUF_SIZE];
848         int                             out_used;
849         unsigned char                   in_data[USB_BUF_SIZE];
850         int                             in_used;
851         int                             in_read;
852         OVERLAPPED                      ov_read;
853         BOOL                            pend_read;
854         OVERLAPPED                      ov_write;
855 };
856
857 PUBLIC struct altos_list *
858 altos_list_start(void)
859 {
860         struct altos_list       *list = calloc(1, sizeof (struct altos_list));
861
862         if (!list)
863                 return NULL;
864         list->dev_info = SetupDiGetClassDevs(NULL, "USB", NULL,
865                                              DIGCF_ALLCLASSES|DIGCF_PRESENT);
866         if (list->dev_info == INVALID_HANDLE_VALUE) {
867                 printf("SetupDiGetClassDevs failed %d\n", GetLastError());
868                 free(list);
869                 return NULL;
870         }
871         list->index = 0;
872         return list;
873 }
874
875 PUBLIC int
876 altos_list_next(struct altos_list *list, struct altos_device *device)
877 {
878         SP_DEVINFO_DATA dev_info_data;
879         char            port[128];
880         DWORD           port_len;
881         char            friendlyname[256];
882         char            symbolic[256];
883         DWORD           symbolic_len;
884         HKEY            dev_key;
885         int             vid, pid;
886         int             serial;
887         HRESULT         result;
888         DWORD           friendlyname_type;
889         DWORD           friendlyname_len;
890
891         dev_info_data.cbSize = sizeof (SP_DEVINFO_DATA);
892         while(SetupDiEnumDeviceInfo(list->dev_info, list->index,
893                                     &dev_info_data))
894         {
895                 list->index++;
896
897                 dev_key = SetupDiOpenDevRegKey(list->dev_info, &dev_info_data,
898                                                DICS_FLAG_GLOBAL, 0, DIREG_DEV,
899                                                KEY_READ);
900                 if (dev_key == INVALID_HANDLE_VALUE) {
901                         printf("cannot open device registry key\n");
902                         continue;
903                 }
904
905                 /* Fetch symbolic name for this device and parse out
906                  * the vid/pid/serial info */
907                 symbolic_len = sizeof(symbolic);
908                 result = RegQueryValueEx(dev_key, "SymbolicName", NULL, NULL,
909                                          symbolic, &symbolic_len);
910                 if (result != 0) {
911                         printf("cannot find SymbolicName value\n");
912                         RegCloseKey(dev_key);
913                         continue;
914                 }
915                 vid = pid = serial = 0;
916                 sscanf(symbolic + sizeof("\\??\\USB#VID_") - 1,
917                        "%04X", &vid);
918                 sscanf(symbolic + sizeof("\\??\\USB#VID_XXXX&PID_") - 1,
919                        "%04X", &pid);
920                 sscanf(symbolic + sizeof("\\??\\USB#VID_XXXX&PID_XXXX#") - 1,
921                        "%d", &serial);
922                 if (!USB_IS_ALTUSMETRUM(vid, pid)) {
923                         RegCloseKey(dev_key);
924                         continue;
925                 }
926
927                 /* Fetch the com port name */
928                 port_len = sizeof (port);
929                 result = RegQueryValueEx(dev_key, "PortName", NULL, NULL,
930                                          port, &port_len);
931                 RegCloseKey(dev_key);
932                 if (result != 0) {
933                         printf("failed to get PortName\n");
934                         continue;
935                 }
936
937                 /* Fetch the device description which is the device name,
938                  * with firmware that has unique USB ids */
939                 friendlyname_len = sizeof (friendlyname);
940                 if(!SetupDiGetDeviceRegistryProperty(list->dev_info,
941                                                      &dev_info_data,
942                                                      SPDRP_FRIENDLYNAME,
943                                                      &friendlyname_type,
944                                                      (BYTE *)friendlyname,
945                                                      sizeof(friendlyname),
946                                                      &friendlyname_len))
947                 {
948                         printf("Failed to get friendlyname\n");
949                         continue;
950                 }
951                 device->vendor = vid;
952                 device->product = pid;
953                 device->serial = serial;
954                 strcpy(device->name, friendlyname);
955
956                 strcpy(device->path, port);
957                 return 1;
958         }
959         result = GetLastError();
960         if (result != ERROR_NO_MORE_ITEMS)
961                 printf ("SetupDiEnumDeviceInfo failed error %d\n", result);
962         return 0;
963 }
964
965 PUBLIC void
966 altos_list_finish(struct altos_list *list)
967 {
968         SetupDiDestroyDeviceInfoList(list->dev_info);
969         free(list);
970 }
971
972 static int
973 altos_queue_read(struct altos_file *file)
974 {
975         DWORD   got;
976         if (file->pend_read)
977                 return LIBALTOS_SUCCESS;
978
979         if (!ReadFile(file->handle, file->in_data, USB_BUF_SIZE, &got, &file->ov_read)) {
980                 if (GetLastError() != ERROR_IO_PENDING)
981                         return LIBALTOS_ERROR;
982                 file->pend_read = TRUE;
983         } else {
984                 file->pend_read = FALSE;
985                 file->in_read = 0;
986                 file->in_used = got;
987         }
988         return LIBALTOS_SUCCESS;
989 }
990
991 static int
992 altos_wait_read(struct altos_file *file, int timeout)
993 {
994         DWORD   ret;
995         DWORD   got;
996
997         if (!file->pend_read)
998                 return LIBALTOS_SUCCESS;
999
1000         if (!timeout)
1001                 timeout = INFINITE;
1002
1003         ret = WaitForSingleObject(file->ov_read.hEvent, timeout);
1004         switch (ret) {
1005         case WAIT_OBJECT_0:
1006                 if (!GetOverlappedResult(file->handle, &file->ov_read, &got, FALSE))
1007                         return LIBALTOS_ERROR;
1008                 file->pend_read = FALSE;
1009                 file->in_read = 0;
1010                 file->in_used = got;
1011                 break;
1012         case WAIT_TIMEOUT:
1013                 return LIBALTOS_TIMEOUT;
1014                 break;
1015         default:
1016                 return LIBALTOS_ERROR;
1017         }
1018         return LIBALTOS_SUCCESS;
1019 }
1020
1021 static int
1022 altos_fill(struct altos_file *file, int timeout)
1023 {
1024         int     ret;
1025
1026         if (file->in_read < file->in_used)
1027                 return LIBALTOS_SUCCESS;
1028
1029         file->in_read = file->in_used = 0;
1030
1031         ret = altos_queue_read(file);
1032         if (ret)
1033                 return ret;
1034         ret = altos_wait_read(file, timeout);
1035         if (ret)
1036                 return ret;
1037
1038         return LIBALTOS_SUCCESS;
1039 }
1040
1041 PUBLIC int
1042 altos_flush(struct altos_file *file)
1043 {
1044         DWORD   put;
1045         char    *data = file->out_data;
1046         char    used = file->out_used;
1047         DWORD   ret;
1048
1049         while (used) {
1050                 if (!WriteFile(file->handle, data, used, &put, &file->ov_write)) {
1051                         if (GetLastError() != ERROR_IO_PENDING)
1052                                 return LIBALTOS_ERROR;
1053                         ret = WaitForSingleObject(file->ov_write.hEvent, INFINITE);
1054                         switch (ret) {
1055                         case WAIT_OBJECT_0:
1056                                 if (!GetOverlappedResult(file->handle, &file->ov_write, &put, FALSE))
1057                                         return LIBALTOS_ERROR;
1058                                 break;
1059                         default:
1060                                 return LIBALTOS_ERROR;
1061                         }
1062                 }
1063                 data += put;
1064                 used -= put;
1065         }
1066         file->out_used = 0;
1067         return LIBALTOS_SUCCESS;
1068 }
1069
1070 PUBLIC struct altos_file *
1071 altos_open(struct altos_device *device)
1072 {
1073         struct altos_file       *file = calloc (1, sizeof (struct altos_file));
1074         char    full_name[64];
1075         DCB dcbSerialParams = {0};
1076         COMMTIMEOUTS timeouts;
1077
1078         if (!file)
1079                 return NULL;
1080
1081         strcpy(full_name, "\\\\.\\");
1082         strcat(full_name, device->path);
1083         file->handle = CreateFile(full_name, GENERIC_READ|GENERIC_WRITE,
1084                                   0, NULL, OPEN_EXISTING,
1085                                   FILE_FLAG_OVERLAPPED, NULL);
1086         if (file->handle == INVALID_HANDLE_VALUE) {
1087                 free(file);
1088                 return NULL;
1089         }
1090         file->ov_read.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1091         file->ov_write.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1092
1093         timeouts.ReadIntervalTimeout = MAXDWORD;
1094         timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1095         timeouts.ReadTotalTimeoutConstant = 1 << 30;    /* almost forever */
1096         timeouts.WriteTotalTimeoutMultiplier = 0;
1097         timeouts.WriteTotalTimeoutConstant = 0;
1098         SetCommTimeouts(file->handle, &timeouts);
1099
1100         dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
1101         if (!GetCommState(file->handle, &dcbSerialParams)) {
1102                 CloseHandle(file->handle);
1103                 free(file);
1104                 return NULL;
1105         }
1106         dcbSerialParams.BaudRate = CBR_9600;
1107         dcbSerialParams.ByteSize = 8;
1108         dcbSerialParams.StopBits = ONESTOPBIT;
1109         dcbSerialParams.Parity = NOPARITY;
1110         if (!SetCommState(file->handle, &dcbSerialParams)) {
1111                 CloseHandle(file->handle);
1112                 free(file);
1113                 return NULL;
1114         }
1115
1116         return file;
1117 }
1118
1119 PUBLIC void
1120 altos_close(struct altos_file *file)
1121 {
1122         if (file->handle != INVALID_HANDLE_VALUE) {
1123                 CloseHandle(file->handle);
1124                 file->handle = INVALID_HANDLE_VALUE;
1125         }
1126 }
1127
1128 PUBLIC void
1129 altos_free(struct altos_file *file)
1130 {
1131         altos_close(file);
1132         free(file);
1133 }
1134
1135 int
1136 altos_putchar(struct altos_file *file, char c)
1137 {
1138         int     ret;
1139
1140         if (file->out_used == USB_BUF_SIZE) {
1141                 ret = altos_flush(file);
1142                 if (ret)
1143                         return ret;
1144         }
1145         file->out_data[file->out_used++] = c;
1146         if (file->out_used == USB_BUF_SIZE)
1147                 return altos_flush(file);
1148         return LIBALTOS_SUCCESS;
1149 }
1150
1151 int
1152 altos_getchar(struct altos_file *file, int timeout)
1153 {
1154         int     ret;
1155         while (file->in_read == file->in_used) {
1156                 if (file->handle == INVALID_HANDLE_VALUE)
1157                         return LIBALTOS_ERROR;
1158                 ret = altos_fill(file, timeout);
1159                 if (ret)
1160                         return ret;
1161         }
1162         return file->in_data[file->in_read++];
1163 }
1164
1165 #endif