2 * Copyright © 2010 Keith Packard <keithp@keithp.com>
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.
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.
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.
28 return LIBALTOS_SUCCESS;
40 /* Mac OS X don't have strndup even if _GNU_SOURCE is defined */
42 altos_strndup (const char *s, size_t n)
44 size_t len = strlen (s);
56 #define altos_strndup strndup
60 * Scan for Altus Metrum devices by looking through /sys
73 cc_fullname (char *dir, char *file)
76 int dlen = strlen (dir);
77 int flen = strlen (file);
80 if (dir[dlen-1] != '/')
82 new = malloc (dlen + slen + flen + 1);
93 cc_basename(char *file)
97 b = strrchr(file, '/');
104 load_string(char *dir, char *file)
106 char *full = cc_fullname(dir, file);
112 f = fopen(full, "r");
116 r = fgets(line, sizeof (line), f);
121 if (r[rlen-1] == '\n')
127 load_hex(char *dir, char *file)
133 line = load_string(dir, file);
136 i = strtol(line, &end, 16);
144 load_dec(char *dir, char *file)
150 line = load_string(dir, file);
153 i = strtol(line, &end, 10);
161 dir_filter_tty_colon(const struct dirent *d)
163 return strncmp(d->d_name, "tty:", 4) == 0;
167 dir_filter_tty(const struct dirent *d)
169 return strncmp(d->d_name, "tty", 3) == 0;
172 struct altos_usbdev {
177 int serial; /* AltOS always uses simple integer serial numbers */
188 struct dirent **namelist;
191 char endpoint_base[20];
197 base = cc_basename(sys);
198 num_configs = load_hex(sys, "bNumConfigurations");
199 num_interfaces = load_hex(sys, "bNumInterfaces");
200 for (config = 1; config <= num_configs; config++) {
201 for (interface = 0; interface < num_interfaces; interface++) {
202 sprintf(endpoint_base, "%s:%d.%d",
203 base, config, interface);
204 endpoint_full = cc_fullname(sys, endpoint_base);
206 /* Check for tty:ttyACMx style names
208 ntty = scandir(endpoint_full, &namelist,
209 dir_filter_tty_colon,
213 tty = cc_fullname("/dev", namelist[0]->d_name + 4);
218 /* Check for tty/ttyACMx style names
220 tty_dir = cc_fullname(endpoint_full, "tty");
222 ntty = scandir(tty_dir, &namelist,
227 tty = cc_fullname("/dev", namelist[0]->d_name);
236 static struct altos_usbdev *
237 usb_scan_device(char *sys)
239 struct altos_usbdev *usbdev;
241 usbdev = calloc(1, sizeof (struct altos_usbdev));
244 usbdev->sys = strdup(sys);
245 usbdev->manufacturer = load_string(sys, "manufacturer");
246 usbdev->product_name = load_string(sys, "product");
247 usbdev->serial = load_dec(sys, "serial");
248 usbdev->idProduct = load_hex(sys, "idProduct");
249 usbdev->idVendor = load_hex(sys, "idVendor");
250 usbdev->tty = usb_tty(sys);
255 usbdev_free(struct altos_usbdev *usbdev)
258 free(usbdev->manufacturer);
259 free(usbdev->product_name);
260 /* this can get used as a return value */
266 #define USB_DEVICES "/sys/bus/usb/devices"
269 dir_filter_dev(const struct dirent *d)
271 const char *n = d->d_name;
279 if (c == '.' && n != d->d_name + 1)
287 struct altos_usbdev **dev;
293 altos_list_start(void)
296 struct dirent **ents;
298 struct altos_usbdev *dev;
299 struct altos_list *devs;
302 devs = calloc(1, sizeof (struct altos_list));
306 n = scandir (USB_DEVICES, &ents,
311 for (e = 0; e < n; e++) {
312 dir = cc_fullname(USB_DEVICES, ents[e]->d_name);
313 dev = usb_scan_device(dir);
315 if (USB_IS_ALTUSMETRUM(dev->idVendor, dev->idProduct)) {
317 devs->dev = realloc(devs->dev,
318 devs->ndev + 1 * sizeof (struct usbdev *));
320 devs->dev = malloc (sizeof (struct usbdev *));
321 devs->dev[devs->ndev++] = dev;
330 altos_list_next(struct altos_list *list, struct altos_device *device)
332 struct altos_usbdev *dev;
333 if (list->current >= list->ndev)
335 dev = list->dev[list->current];
336 strcpy(device->name, dev->product_name);
337 device->vendor = dev->idVendor;
338 device->product = dev->idProduct;
339 strcpy(device->path, dev->tty);
340 device->serial = dev->serial;
346 altos_list_finish(struct altos_list *usbdevs)
352 for (i = 0; i < usbdevs->ndev; i++)
353 usbdev_free(usbdevs->dev[i]);
361 #include <IOKitLib.h>
362 #include <IOKit/usb/USBspec.h>
363 #include <sys/param.h>
365 #include <CFNumber.h>
372 io_iterator_t iterator;
376 get_string(io_object_t object, CFStringRef entry, char *result, int result_len)
378 CFTypeRef entry_as_string;
381 entry_as_string = IORegistryEntrySearchCFProperty (object,
385 kIORegistryIterateRecursively);
386 if (entry_as_string) {
387 got_string = CFStringGetCString(entry_as_string,
389 kCFStringEncodingASCII);
391 CFRelease(entry_as_string);
399 get_number(io_object_t object, CFStringRef entry, int *result)
401 CFTypeRef entry_as_number;
404 entry_as_number = IORegistryEntrySearchCFProperty (object,
408 kIORegistryIterateRecursively);
409 if (entry_as_number) {
410 got_number = CFNumberGetValue(entry_as_number,
420 altos_list_start(void)
422 struct altos_list *list = calloc (sizeof (struct altos_list), 1);
423 CFMutableDictionaryRef matching_dictionary = IOServiceMatching("IOUSBDevice");
424 io_iterator_t tdIterator;
425 io_object_t tdObject;
429 ret = IOServiceGetMatchingServices(kIOMasterPortDefault, matching_dictionary, &list->iterator);
430 if (ret != kIOReturnSuccess)
436 altos_list_next(struct altos_list *list, struct altos_device *device)
439 char serial_string[128];
442 object = IOIteratorNext(list->iterator);
446 if (!get_number (object, CFSTR(kUSBVendorID), &device->vendor) ||
447 !get_number (object, CFSTR(kUSBProductID), &device->product))
449 if (device->vendor != 0xfffe)
451 if (device->product < 0x000a || 0x0013 < device->product)
453 if (get_string (object, CFSTR("IOCalloutDevice"), device->path, sizeof (device->path)) &&
454 get_string (object, CFSTR("USB Product Name"), device->name, sizeof (device->name)) &&
455 get_string (object, CFSTR("USB Serial Number"), serial_string, sizeof (serial_string))) {
456 device->serial = atoi(serial_string);
463 altos_list_finish(struct altos_list *list)
465 IOObjectRelease (list->iterator);
479 #define USB_BUF_SIZE 64
488 unsigned char out_data[USB_BUF_SIZE];
490 unsigned char in_data[USB_BUF_SIZE];
495 PUBLIC struct altos_file *
496 altos_open(struct altos_device *device)
498 struct altos_file *file = calloc (sizeof (struct altos_file), 1);
505 file->fd = open(device->path, O_RDWR | O_NOCTTY);
507 perror(device->path);
514 file->out_fd = open(device->path, O_RDWR | O_NOCTTY);
515 if (file->out_fd < 0) {
516 perror(device->path);
522 ret = tcgetattr(file->fd, &term);
535 term.c_cc[VTIME] = 0;
538 term.c_cc[VTIME] = 1;
540 ret = tcsetattr(file->fd, TCSAFLUSH, &term);
554 altos_close(struct altos_file *file)
556 if (file->fd != -1) {
560 write(file->pipe[1], "\r", 1);
570 altos_free(struct altos_file *file)
577 altos_flush(struct altos_file *file)
579 while (file->out_used) {
585 ret = write (file->fd, file->out_data, file->out_used);
587 ret = write (file->out_fd, file->out_data, file->out_used);
592 memmove(file->out_data, file->out_data + ret,
593 file->out_used - ret);
594 file->out_used -= ret;
601 altos_putchar(struct altos_file *file, char c)
605 if (file->out_used == USB_BUF_SIZE) {
606 ret = altos_flush(file);
611 file->out_data[file->out_used++] = c;
613 if (file->out_used == USB_BUF_SIZE)
614 ret = altos_flush(file);
623 altos_fill(struct altos_file *file, int timeout)
632 while (file->in_read == file->in_used) {
634 return LIBALTOS_ERROR;
637 fd[0].events = POLLIN;
638 fd[1].fd = file->pipe[0];
639 fd[1].events = POLLIN;
640 ret = poll(fd, 2, timeout);
642 perror("altos_getchar");
643 return LIBALTOS_ERROR;
646 return LIBALTOS_TIMEOUT;
647 if (fd[0].revents & POLLIN)
650 ret = read(file->fd, file->in_data, USB_BUF_SIZE);
652 perror("altos_getchar");
653 return LIBALTOS_ERROR;
658 if (ret == 0 && timeout > 0)
659 return LIBALTOS_TIMEOUT;
667 altos_getchar(struct altos_file *file, int timeout)
670 while (file->in_read == file->in_used) {
672 return LIBALTOS_ERROR;
673 ret = altos_fill(file, timeout);
677 return file->in_data[file->in_read++];
680 #endif /* POSIX_TTY */
686 #include <setupapi.h>
693 #define USB_BUF_SIZE 64
697 unsigned char out_data[USB_BUF_SIZE];
699 unsigned char in_data[USB_BUF_SIZE];
707 PUBLIC struct altos_list *
708 altos_list_start(void)
710 struct altos_list *list = calloc(1, sizeof (struct altos_list));
714 list->dev_info = SetupDiGetClassDevs(NULL, "USB", NULL,
715 DIGCF_ALLCLASSES|DIGCF_PRESENT);
716 if (list->dev_info == INVALID_HANDLE_VALUE) {
717 printf("SetupDiGetClassDevs failed %d\n", GetLastError());
726 altos_list_next(struct altos_list *list, struct altos_device *device)
728 SP_DEVINFO_DATA dev_info_data;
731 char friendlyname[256];
738 DWORD friendlyname_type;
739 DWORD friendlyname_len;
741 dev_info_data.cbSize = sizeof (SP_DEVINFO_DATA);
742 while(SetupDiEnumDeviceInfo(list->dev_info, list->index,
747 dev_key = SetupDiOpenDevRegKey(list->dev_info, &dev_info_data,
748 DICS_FLAG_GLOBAL, 0, DIREG_DEV,
750 if (dev_key == INVALID_HANDLE_VALUE) {
751 printf("cannot open device registry key\n");
755 /* Fetch symbolic name for this device and parse out
756 * the vid/pid/serial info */
757 symbolic_len = sizeof(symbolic);
758 result = RegQueryValueEx(dev_key, "SymbolicName", NULL, NULL,
759 symbolic, &symbolic_len);
761 printf("cannot find SymbolicName value\n");
762 RegCloseKey(dev_key);
765 vid = pid = serial = 0;
766 sscanf(symbolic + sizeof("\\??\\USB#VID_") - 1,
768 sscanf(symbolic + sizeof("\\??\\USB#VID_XXXX&PID_") - 1,
770 sscanf(symbolic + sizeof("\\??\\USB#VID_XXXX&PID_XXXX#") - 1,
772 if (!USB_IS_ALTUSMETRUM(vid, pid)) {
773 RegCloseKey(dev_key);
777 /* Fetch the com port name */
778 port_len = sizeof (port);
779 result = RegQueryValueEx(dev_key, "PortName", NULL, NULL,
781 RegCloseKey(dev_key);
783 printf("failed to get PortName\n");
787 /* Fetch the device description which is the device name,
788 * with firmware that has unique USB ids */
789 friendlyname_len = sizeof (friendlyname);
790 if(!SetupDiGetDeviceRegistryProperty(list->dev_info,
794 (BYTE *)friendlyname,
795 sizeof(friendlyname),
798 printf("Failed to get friendlyname\n");
801 device->vendor = vid;
802 device->product = pid;
803 device->serial = serial;
804 strcpy(device->name, friendlyname);
806 strcpy(device->path, port);
809 result = GetLastError();
810 if (result != ERROR_NO_MORE_ITEMS)
811 printf ("SetupDiEnumDeviceInfo failed error %d\n", result);
816 altos_list_finish(struct altos_list *list)
818 SetupDiDestroyDeviceInfoList(list->dev_info);
823 altos_queue_read(struct altos_file *file)
827 return LIBALTOS_SUCCESS;
829 if (!ReadFile(file->handle, file->in_data, USB_BUF_SIZE, &got, &file->ov_read)) {
830 if (GetLastError() != ERROR_IO_PENDING)
831 return LIBALTOS_ERROR;
832 file->pend_read = TRUE;
834 file->pend_read = FALSE;
838 return LIBALTOS_SUCCESS;
842 altos_wait_read(struct altos_file *file, int timeout)
847 if (!file->pend_read)
848 return LIBALTOS_SUCCESS;
853 ret = WaitForSingleObject(file->ov_read.hEvent, timeout);
856 if (!GetOverlappedResult(file->handle, &file->ov_read, &got, FALSE))
857 return LIBALTOS_ERROR;
858 file->pend_read = FALSE;
863 return LIBALTOS_TIMEOUT;
866 return LIBALTOS_ERROR;
868 return LIBALTOS_SUCCESS;
872 altos_fill(struct altos_file *file, int timeout)
876 if (file->in_read < file->in_used)
877 return LIBALTOS_SUCCESS;
879 file->in_read = file->in_used = 0;
881 ret = altos_queue_read(file);
884 ret = altos_wait_read(file, timeout);
888 return LIBALTOS_SUCCESS;
892 altos_flush(struct altos_file *file)
895 char *data = file->out_data;
896 char used = file->out_used;
900 if (!WriteFile(file->handle, data, used, &put, &file->ov_write)) {
901 if (GetLastError() != ERROR_IO_PENDING)
902 return LIBALTOS_ERROR;
903 ret = WaitForSingleObject(file->ov_write.hEvent, INFINITE);
906 if (!GetOverlappedResult(file->handle, &file->ov_write, &put, FALSE))
907 return LIBALTOS_ERROR;
910 return LIBALTOS_ERROR;
917 return LIBALTOS_SUCCESS;
920 PUBLIC struct altos_file *
921 altos_open(struct altos_device *device)
923 struct altos_file *file = calloc (1, sizeof (struct altos_file));
925 DCB dcbSerialParams = {0};
926 COMMTIMEOUTS timeouts;
931 strcpy(full_name, "\\\\.\\");
932 strcat(full_name, device->path);
933 file->handle = CreateFile(full_name, GENERIC_READ|GENERIC_WRITE,
934 0, NULL, OPEN_EXISTING,
935 FILE_FLAG_OVERLAPPED, NULL);
936 if (file->handle == INVALID_HANDLE_VALUE) {
940 file->ov_read.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
941 file->ov_write.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
943 timeouts.ReadIntervalTimeout = MAXDWORD;
944 timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
945 timeouts.ReadTotalTimeoutConstant = 1 << 30; /* almost forever */
946 timeouts.WriteTotalTimeoutMultiplier = 0;
947 timeouts.WriteTotalTimeoutConstant = 0;
948 SetCommTimeouts(file->handle, &timeouts);
950 dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
951 if (!GetCommState(file->handle, &dcbSerialParams)) {
952 CloseHandle(file->handle);
956 dcbSerialParams.BaudRate = CBR_9600;
957 dcbSerialParams.ByteSize = 8;
958 dcbSerialParams.StopBits = ONESTOPBIT;
959 dcbSerialParams.Parity = NOPARITY;
960 if (!SetCommState(file->handle, &dcbSerialParams)) {
961 CloseHandle(file->handle);
970 altos_close(struct altos_file *file)
972 if (file->handle != INVALID_HANDLE_VALUE) {
973 CloseHandle(file->handle);
974 file->handle = INVALID_HANDLE_VALUE;
979 altos_free(struct altos_file *file)
986 altos_putchar(struct altos_file *file, char c)
990 if (file->out_used == USB_BUF_SIZE) {
991 ret = altos_flush(file);
995 file->out_data[file->out_used++] = c;
996 if (file->out_used == USB_BUF_SIZE)
997 return altos_flush(file);
998 return LIBALTOS_SUCCESS;
1002 altos_getchar(struct altos_file *file, int timeout)
1005 while (file->in_read == file->in_used) {
1006 if (file->handle == INVALID_HANDLE_VALUE)
1007 return LIBALTOS_ERROR;
1008 ret = altos_fill(file, timeout);
1012 return file->in_data[file->in_read++];