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];
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];
704 PUBLIC struct altos_list *
705 altos_list_start(void)
707 struct altos_list *list = calloc(1, sizeof (struct altos_list));
711 list->dev_info = SetupDiGetClassDevs(NULL, "USB", NULL,
712 DIGCF_ALLCLASSES|DIGCF_PRESENT);
713 if (list->dev_info == INVALID_HANDLE_VALUE) {
714 printf("SetupDiGetClassDevs failed %d\n", GetLastError());
723 altos_list_next(struct altos_list *list, struct altos_device *device)
725 SP_DEVINFO_DATA dev_info_data;
728 char friendlyname[256];
735 DWORD friendlyname_type;
736 DWORD friendlyname_len;
738 dev_info_data.cbSize = sizeof (SP_DEVINFO_DATA);
739 while(SetupDiEnumDeviceInfo(list->dev_info, list->index,
744 dev_key = SetupDiOpenDevRegKey(list->dev_info, &dev_info_data,
745 DICS_FLAG_GLOBAL, 0, DIREG_DEV,
747 if (dev_key == INVALID_HANDLE_VALUE) {
748 printf("cannot open device registry key\n");
752 /* Fetch symbolic name for this device and parse out
753 * the vid/pid/serial info */
754 symbolic_len = sizeof(symbolic);
755 result = RegQueryValueEx(dev_key, "SymbolicName", NULL, NULL,
756 symbolic, &symbolic_len);
758 printf("cannot find SymbolicName value\n");
759 RegCloseKey(dev_key);
762 vid = pid = serial = 0;
763 sscanf(symbolic + sizeof("\\??\\USB#VID_") - 1,
765 sscanf(symbolic + sizeof("\\??\\USB#VID_XXXX&PID_") - 1,
767 sscanf(symbolic + sizeof("\\??\\USB#VID_XXXX&PID_XXXX#") - 1,
769 if (!USB_IS_ALTUSMETRUM(vid, pid)) {
770 RegCloseKey(dev_key);
774 /* Fetch the com port name */
775 port_len = sizeof (port);
776 result = RegQueryValueEx(dev_key, "PortName", NULL, NULL,
778 RegCloseKey(dev_key);
780 printf("failed to get PortName\n");
784 /* Fetch the device description which is the device name,
785 * with firmware that has unique USB ids */
786 friendlyname_len = sizeof (friendlyname);
787 if(!SetupDiGetDeviceRegistryProperty(list->dev_info,
791 (BYTE *)friendlyname,
792 sizeof(friendlyname),
795 printf("Failed to get friendlyname\n");
798 device->vendor = vid;
799 device->product = pid;
800 device->serial = serial;
801 strcpy(device->name, friendlyname);
803 strcpy(device->path, port);
806 result = GetLastError();
807 if (result != ERROR_NO_MORE_ITEMS)
808 printf ("SetupDiEnumDeviceInfo failed error %d\n", result);
813 altos_list_finish(struct altos_list *list)
815 SetupDiDestroyDeviceInfoList(list->dev_info);
820 altos_fill(struct altos_file *file, int timeout)
824 COMMTIMEOUTS timeouts;
826 if (file->in_read < file->in_used)
827 return LIBALTOS_SUCCESS;
828 file->in_read = file->in_used = 0;
831 timeouts.ReadTotalTimeoutConstant = timeout;
833 timeouts.ReadTotalTimeoutConstant = 1000;
835 timeouts.ReadIntervalTimeout = MAXDWORD;
836 timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
837 timeouts.WriteTotalTimeoutMultiplier = 0;
838 timeouts.WriteTotalTimeoutConstant = 0;
840 if (!SetCommTimeouts(file->handle, &timeouts))
841 printf("SetCommTimeouts failed %d\n", GetLastError());
844 if (!ReadFile(file->handle, file->in_data, USB_BUF_SIZE, &got, NULL)) {
845 result = GetLastError();
846 return LIBALTOS_ERROR;
852 return LIBALTOS_SUCCESS;
854 return LIBALTOS_TIMEOUT;
859 altos_flush(struct altos_file *file)
862 char *data = file->out_data;
863 char used = file->out_used;
867 if (!WriteFile(file->handle, data, used, &put, NULL)) {
868 result = GetLastError();
869 return LIBALTOS_ERROR;
875 return LIBALTOS_SUCCESS;
878 PUBLIC struct altos_file *
879 altos_open(struct altos_device *device)
881 struct altos_file *file = calloc (1, sizeof (struct altos_file));
883 DCB dcbSerialParams = {0};
888 strcpy(full_name, "\\\\.\\");
889 strcat(full_name, device->path);
890 file->handle = CreateFile(full_name, GENERIC_READ|GENERIC_WRITE,
891 0, NULL, OPEN_EXISTING,
892 FILE_ATTRIBUTE_NORMAL, NULL);
893 if (file->handle == INVALID_HANDLE_VALUE) {
897 dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
898 if (!GetCommState(file->handle, &dcbSerialParams)) {
899 CloseHandle(file->handle);
903 dcbSerialParams.BaudRate = CBR_9600;
904 dcbSerialParams.ByteSize = 8;
905 dcbSerialParams.StopBits = ONESTOPBIT;
906 dcbSerialParams.Parity = NOPARITY;
907 if (!SetCommState(file->handle, &dcbSerialParams)) {
908 CloseHandle(file->handle);
917 altos_close(struct altos_file *file)
919 if (file->handle != INVALID_HANDLE_VALUE) {
920 CloseHandle(file->handle);
921 file->handle = INVALID_HANDLE_VALUE;
926 altos_free(struct altos_file *file)
933 altos_putchar(struct altos_file *file, char c)
937 if (file->out_used == USB_BUF_SIZE) {
938 ret = altos_flush(file);
942 file->out_data[file->out_used++] = c;
943 if (file->out_used == USB_BUF_SIZE)
944 return altos_flush(file);
945 return LIBALTOS_SUCCESS;
949 altos_getchar(struct altos_file *file, int timeout)
952 while (file->in_read == file->in_used) {
953 if (file->handle == INVALID_HANDLE_VALUE)
954 return LIBALTOS_ERROR;
955 ret = altos_fill(file, timeout);
959 return file->in_data[file->in_read++];