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.
23 #define USB_VENDOR_FSF 0xfffe
24 #define USB_VENDOR_ALTUSMETRUM USB_VENDOR_FSF
25 #define USB_PRODUCT_ALTUSMETRUM 0x000a
26 #define USB_PRODUCT_TELEMETRUM 0x000b
27 #define USB_PRODUCT_TELEDONGLE 0x000c
28 #define USB_PRODUCT_TELETERRA 0x000d
29 #define USB_PRODUCT_TELEBT 0x000e
30 #define USB_PRODUCT_ALTUSMETRUM_MIN 0x000a
31 #define USB_PRODUCT_ALTUSMETRUM_MAX 0x0013
33 #define USB_IS_ALTUSMETRUM(v,p) ((v) == USB_VENDOR_ALTUSMETRUM && \
34 (USB_PRODUCT_ALTUSMETRUM_MIN <= (p) && \
35 (p) <= USB_PRODUCT_ALTUSMETRUM_MAX))
37 #define BLUETOOTH_PRODUCT_TELEBT "TeleBT"
44 return LIBALTOS_SUCCESS;
56 /* Mac OS X don't have strndup even if _GNU_SOURCE is defined */
58 altos_strndup (const char *s, size_t n)
60 size_t len = strlen (s);
72 #define altos_strndup strndup
83 #define USB_BUF_SIZE 64
92 unsigned char out_data[USB_BUF_SIZE];
94 unsigned char in_data[USB_BUF_SIZE];
99 PUBLIC struct altos_file *
100 altos_open(struct altos_device *device)
102 struct altos_file *file = calloc (sizeof (struct altos_file), 1);
109 file->fd = open(device->path, O_RDWR | O_NOCTTY);
111 perror(device->path);
118 file->out_fd = open(device->path, O_RDWR | O_NOCTTY);
119 if (file->out_fd < 0) {
120 perror(device->path);
126 ret = tcgetattr(file->fd, &term);
139 term.c_cc[VTIME] = 0;
142 term.c_cc[VTIME] = 1;
144 ret = tcsetattr(file->fd, TCSAFLUSH, &term);
158 altos_close(struct altos_file *file)
160 if (file->fd != -1) {
164 write(file->pipe[1], "\r", 1);
174 altos_free(struct altos_file *file)
181 altos_flush(struct altos_file *file)
183 if (file->out_used && 0) {
185 fwrite(file->out_data, 1, file->out_used, stdout);
188 while (file->out_used) {
194 ret = write (file->fd, file->out_data, file->out_used);
196 ret = write (file->out_fd, file->out_data, file->out_used);
201 memmove(file->out_data, file->out_data + ret,
202 file->out_used - ret);
203 file->out_used -= ret;
210 altos_putchar(struct altos_file *file, char c)
214 if (file->out_used == USB_BUF_SIZE) {
215 ret = altos_flush(file);
220 file->out_data[file->out_used++] = c;
222 if (file->out_used == USB_BUF_SIZE)
223 ret = altos_flush(file);
232 altos_fill(struct altos_file *file, int timeout)
241 while (file->in_read == file->in_used) {
243 return LIBALTOS_ERROR;
246 fd[0].events = POLLIN|POLLERR|POLLHUP|POLLNVAL;
247 fd[1].fd = file->pipe[0];
248 fd[1].events = POLLIN;
249 ret = poll(fd, 2, timeout);
251 perror("altos_getchar");
252 return LIBALTOS_ERROR;
255 return LIBALTOS_TIMEOUT;
257 if (fd[0].revents & (POLLHUP|POLLERR|POLLNVAL))
258 return LIBALTOS_ERROR;
259 if (fd[0].revents & POLLIN)
262 ret = read(file->fd, file->in_data, USB_BUF_SIZE);
264 perror("altos_getchar");
265 return LIBALTOS_ERROR;
270 if (ret == 0 && timeout > 0)
271 return LIBALTOS_TIMEOUT;
275 if (file->in_used && 0) {
277 fwrite(file->in_data, 1, file->in_used, stdout);
284 altos_getchar(struct altos_file *file, int timeout)
287 while (file->in_read == file->in_used) {
289 return LIBALTOS_ERROR;
290 ret = altos_fill(file, timeout);
294 return file->in_data[file->in_read++];
297 #endif /* POSIX_TTY */
300 * Scan for Altus Metrum devices by looking through /sys
313 cc_fullname (char *dir, char *file)
316 int dlen = strlen (dir);
317 int flen = strlen (file);
320 if (dir[dlen-1] != '/')
322 new = malloc (dlen + slen + flen + 1);
333 cc_basename(char *file)
337 b = strrchr(file, '/');
344 load_string(char *dir, char *file)
346 char *full = cc_fullname(dir, file);
352 f = fopen(full, "r");
356 r = fgets(line, sizeof (line), f);
361 if (r[rlen-1] == '\n')
367 load_hex(char *dir, char *file)
373 line = load_string(dir, file);
376 i = strtol(line, &end, 16);
384 load_dec(char *dir, char *file)
390 line = load_string(dir, file);
393 i = strtol(line, &end, 10);
401 dir_filter_tty_colon(const struct dirent *d)
403 return strncmp(d->d_name, "tty:", 4) == 0;
407 dir_filter_tty(const struct dirent *d)
409 return strncmp(d->d_name, "tty", 3) == 0;
412 struct altos_usbdev {
417 int serial; /* AltOS always uses simple integer serial numbers */
428 struct dirent **namelist;
431 char endpoint_base[20];
437 base = cc_basename(sys);
438 num_configs = load_hex(sys, "bNumConfigurations");
439 num_interfaces = load_hex(sys, "bNumInterfaces");
440 for (config = 1; config <= num_configs; config++) {
441 for (interface = 0; interface < num_interfaces; interface++) {
442 sprintf(endpoint_base, "%s:%d.%d",
443 base, config, interface);
444 endpoint_full = cc_fullname(sys, endpoint_base);
446 /* Check for tty:ttyACMx style names
448 ntty = scandir(endpoint_full, &namelist,
449 dir_filter_tty_colon,
453 tty = cc_fullname("/dev", namelist[0]->d_name + 4);
458 /* Check for tty/ttyACMx style names
460 tty_dir = cc_fullname(endpoint_full, "tty");
462 ntty = scandir(tty_dir, &namelist,
467 tty = cc_fullname("/dev", namelist[0]->d_name);
476 static struct altos_usbdev *
477 usb_scan_device(char *sys)
479 struct altos_usbdev *usbdev;
481 usbdev = calloc(1, sizeof (struct altos_usbdev));
484 usbdev->sys = strdup(sys);
485 usbdev->manufacturer = load_string(sys, "manufacturer");
486 usbdev->product_name = load_string(sys, "product");
487 usbdev->serial = load_dec(sys, "serial");
488 usbdev->idProduct = load_hex(sys, "idProduct");
489 usbdev->idVendor = load_hex(sys, "idVendor");
490 usbdev->tty = usb_tty(sys);
495 usbdev_free(struct altos_usbdev *usbdev)
498 free(usbdev->manufacturer);
499 free(usbdev->product_name);
500 /* this can get used as a return value */
506 #define USB_DEVICES "/sys/bus/usb/devices"
509 dir_filter_dev(const struct dirent *d)
511 const char *n = d->d_name;
519 if (c == '.' && n != d->d_name + 1)
527 struct altos_usbdev **dev;
533 altos_list_start(void)
536 struct dirent **ents;
538 struct altos_usbdev *dev;
539 struct altos_list *devs;
542 devs = calloc(1, sizeof (struct altos_list));
546 n = scandir (USB_DEVICES, &ents,
551 for (e = 0; e < n; e++) {
552 dir = cc_fullname(USB_DEVICES, ents[e]->d_name);
553 dev = usb_scan_device(dir);
555 if (USB_IS_ALTUSMETRUM(dev->idVendor, dev->idProduct)) {
557 devs->dev = realloc(devs->dev,
558 (devs->ndev + 1) * sizeof (struct usbdev *));
560 devs->dev = malloc (sizeof (struct usbdev *));
561 devs->dev[devs->ndev++] = dev;
570 altos_list_next(struct altos_list *list, struct altos_device *device)
572 struct altos_usbdev *dev;
573 if (list->current >= list->ndev)
575 dev = list->dev[list->current];
576 strcpy(device->name, dev->product_name);
577 device->vendor = dev->idVendor;
578 device->product = dev->idProduct;
579 strcpy(device->path, dev->tty);
580 device->serial = dev->serial;
586 altos_list_finish(struct altos_list *usbdevs)
592 for (i = 0; i < usbdevs->ndev; i++)
593 usbdev_free(usbdevs->dev[i]);
598 struct altos_bt_list {
606 #define INQUIRY_MAX_RSP 255
608 struct altos_bt_list *
609 altos_bt_list_start(int inquiry_time)
611 struct altos_bt_list *bt_list;
613 bt_list = calloc(1, sizeof (struct altos_bt_list));
617 bt_list->ii = calloc(INQUIRY_MAX_RSP, sizeof (inquiry_info));
620 bt_list->dev_id = hci_get_route(NULL);
621 if (bt_list->dev_id < 0)
624 bt_list->sock = hci_open_dev(bt_list->dev_id);
625 if (bt_list->sock < 0)
628 bt_list->num_rsp = hci_inquiry(bt_list->dev_id,
634 if (bt_list->num_rsp < 0)
641 close(bt_list->sock);
652 altos_bt_list_next(struct altos_bt_list *bt_list,
653 struct altos_bt_device *device)
657 if (bt_list->rsp >= bt_list->num_rsp)
660 ii = &bt_list->ii[bt_list->rsp];
661 ba2str(&ii->bdaddr, device->addr);
662 memset(&device->name, '\0', sizeof (device->name));
663 if (hci_read_remote_name(bt_list->sock, &ii->bdaddr,
664 sizeof (device->name),
665 device->name, 0) < 0) {
666 strcpy(device->name, "[unknown]");
673 altos_bt_list_finish(struct altos_bt_list *bt_list)
675 close(bt_list->sock);
681 altos_bt_fill_in(char *name, char *addr, struct altos_bt_device *device)
683 strncpy(device->name, name, sizeof (device->name));
684 device->name[sizeof(device->name)-1] = '\0';
685 strncpy(device->addr, addr, sizeof (device->addr));
686 device->addr[sizeof(device->addr)-1] = '\0';
690 altos_bt_open(struct altos_bt_device *device)
692 struct sockaddr_rc addr = { 0 };
694 struct altos_file *file;
696 file = calloc(1, sizeof (struct altos_file));
699 file->fd = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
703 addr.rc_family = AF_BLUETOOTH;
705 str2ba(device->addr, &addr.rc_bdaddr);
707 status = connect(file->fd,
708 (struct sockaddr *)&addr,
719 file->out_fd = dup(file->fd);
729 #endif /* HAS_BLUETOOTH */
735 #include <IOKitLib.h>
736 #include <IOKit/usb/USBspec.h>
737 #include <sys/param.h>
739 #include <CFNumber.h>
746 io_iterator_t iterator;
750 get_string(io_object_t object, CFStringRef entry, char *result, int result_len)
752 CFTypeRef entry_as_string;
755 entry_as_string = IORegistryEntrySearchCFProperty (object,
759 kIORegistryIterateRecursively);
760 if (entry_as_string) {
761 got_string = CFStringGetCString(entry_as_string,
763 kCFStringEncodingASCII);
765 CFRelease(entry_as_string);
773 get_number(io_object_t object, CFStringRef entry, int *result)
775 CFTypeRef entry_as_number;
778 entry_as_number = IORegistryEntrySearchCFProperty (object,
782 kIORegistryIterateRecursively);
783 if (entry_as_number) {
784 got_number = CFNumberGetValue(entry_as_number,
793 PUBLIC struct altos_list *
794 altos_list_start(void)
796 struct altos_list *list = calloc (sizeof (struct altos_list), 1);
797 CFMutableDictionaryRef matching_dictionary = IOServiceMatching("IOUSBDevice");
798 io_iterator_t tdIterator;
799 io_object_t tdObject;
803 ret = IOServiceGetMatchingServices(kIOMasterPortDefault, matching_dictionary, &list->iterator);
804 if (ret != kIOReturnSuccess)
810 altos_list_next(struct altos_list *list, struct altos_device *device)
813 char serial_string[128];
816 object = IOIteratorNext(list->iterator);
820 if (!get_number (object, CFSTR(kUSBVendorID), &device->vendor) ||
821 !get_number (object, CFSTR(kUSBProductID), &device->product))
823 if (device->vendor != 0xfffe)
825 if (device->product < 0x000a || 0x0013 < device->product)
827 if (get_string (object, CFSTR("IOCalloutDevice"), device->path, sizeof (device->path)) &&
828 get_string (object, CFSTR("USB Product Name"), device->name, sizeof (device->name)) &&
829 get_string (object, CFSTR("USB Serial Number"), serial_string, sizeof (serial_string))) {
830 device->serial = atoi(serial_string);
837 altos_list_finish(struct altos_list *list)
839 IOObjectRelease (list->iterator);
850 #include <setupapi.h>
857 #define USB_BUF_SIZE 64
861 unsigned char out_data[USB_BUF_SIZE];
863 unsigned char in_data[USB_BUF_SIZE];
871 PUBLIC struct altos_list *
872 altos_list_start(void)
874 struct altos_list *list = calloc(1, sizeof (struct altos_list));
878 list->dev_info = SetupDiGetClassDevs(NULL, "USB", NULL,
879 DIGCF_ALLCLASSES|DIGCF_PRESENT);
880 if (list->dev_info == INVALID_HANDLE_VALUE) {
881 printf("SetupDiGetClassDevs failed %ld\n", GetLastError());
890 altos_list_next(struct altos_list *list, struct altos_device *device)
892 SP_DEVINFO_DATA dev_info_data;
895 char friendlyname[256];
899 unsigned int vid, pid;
902 DWORD friendlyname_type;
903 DWORD friendlyname_len;
905 dev_info_data.cbSize = sizeof (SP_DEVINFO_DATA);
906 while(SetupDiEnumDeviceInfo(list->dev_info, list->index,
911 dev_key = SetupDiOpenDevRegKey(list->dev_info, &dev_info_data,
912 DICS_FLAG_GLOBAL, 0, DIREG_DEV,
914 if (dev_key == INVALID_HANDLE_VALUE) {
915 printf("cannot open device registry key\n");
919 /* Fetch symbolic name for this device and parse out
920 * the vid/pid/serial info */
921 symbolic_len = sizeof(symbolic);
922 result = RegQueryValueEx(dev_key, "SymbolicName", NULL, NULL,
923 symbolic, &symbolic_len);
925 printf("cannot find SymbolicName value\n");
926 RegCloseKey(dev_key);
929 vid = pid = serial = 0;
930 sscanf((char *) symbolic + sizeof("\\??\\USB#VID_") - 1,
932 sscanf((char *) symbolic + sizeof("\\??\\USB#VID_XXXX&PID_") - 1,
934 sscanf((char *) symbolic + sizeof("\\??\\USB#VID_XXXX&PID_XXXX#") - 1,
936 if (!USB_IS_ALTUSMETRUM(vid, pid)) {
937 RegCloseKey(dev_key);
941 /* Fetch the com port name */
942 port_len = sizeof (port);
943 result = RegQueryValueEx(dev_key, "PortName", NULL, NULL,
945 RegCloseKey(dev_key);
947 printf("failed to get PortName\n");
951 /* Fetch the device description which is the device name,
952 * with firmware that has unique USB ids */
953 friendlyname_len = sizeof (friendlyname);
954 if(!SetupDiGetDeviceRegistryProperty(list->dev_info,
958 (BYTE *)friendlyname,
959 sizeof(friendlyname),
962 printf("Failed to get friendlyname\n");
965 device->vendor = vid;
966 device->product = pid;
967 device->serial = serial;
968 strcpy(device->name, friendlyname);
970 strcpy(device->path, (char *) port);
973 result = GetLastError();
974 if (result != ERROR_NO_MORE_ITEMS)
975 printf ("SetupDiEnumDeviceInfo failed error %d\n", (int) result);
980 altos_list_finish(struct altos_list *list)
982 SetupDiDestroyDeviceInfoList(list->dev_info);
987 altos_queue_read(struct altos_file *file)
991 return LIBALTOS_SUCCESS;
993 if (!ReadFile(file->handle, file->in_data, USB_BUF_SIZE, &got, &file->ov_read)) {
994 if (GetLastError() != ERROR_IO_PENDING)
995 return LIBALTOS_ERROR;
996 file->pend_read = TRUE;
998 file->pend_read = FALSE;
1000 file->in_used = got;
1002 return LIBALTOS_SUCCESS;
1006 altos_wait_read(struct altos_file *file, int timeout)
1011 if (!file->pend_read)
1012 return LIBALTOS_SUCCESS;
1017 ret = WaitForSingleObject(file->ov_read.hEvent, timeout);
1020 if (!GetOverlappedResult(file->handle, &file->ov_read, &got, FALSE))
1021 return LIBALTOS_ERROR;
1022 file->pend_read = FALSE;
1024 file->in_used = got;
1027 return LIBALTOS_TIMEOUT;
1030 return LIBALTOS_ERROR;
1032 return LIBALTOS_SUCCESS;
1036 altos_fill(struct altos_file *file, int timeout)
1040 if (file->in_read < file->in_used)
1041 return LIBALTOS_SUCCESS;
1043 file->in_read = file->in_used = 0;
1045 ret = altos_queue_read(file);
1048 ret = altos_wait_read(file, timeout);
1052 return LIBALTOS_SUCCESS;
1056 altos_flush(struct altos_file *file)
1059 unsigned char *data = file->out_data;
1060 int used = file->out_used;
1064 if (!WriteFile(file->handle, data, used, &put, &file->ov_write)) {
1065 if (GetLastError() != ERROR_IO_PENDING)
1066 return LIBALTOS_ERROR;
1067 ret = WaitForSingleObject(file->ov_write.hEvent, INFINITE);
1070 if (!GetOverlappedResult(file->handle, &file->ov_write, &put, FALSE))
1071 return LIBALTOS_ERROR;
1074 return LIBALTOS_ERROR;
1081 return LIBALTOS_SUCCESS;
1084 PUBLIC struct altos_file *
1085 altos_open(struct altos_device *device)
1087 struct altos_file *file = calloc (1, sizeof (struct altos_file));
1089 DCB dcbSerialParams = {0};
1090 COMMTIMEOUTS timeouts;
1095 strcpy(full_name, "\\\\.\\");
1096 strcat(full_name, device->path);
1097 file->handle = CreateFile(full_name, GENERIC_READ|GENERIC_WRITE,
1098 0, NULL, OPEN_EXISTING,
1099 FILE_FLAG_OVERLAPPED, NULL);
1100 if (file->handle == INVALID_HANDLE_VALUE) {
1104 file->ov_read.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1105 file->ov_write.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1107 timeouts.ReadIntervalTimeout = MAXDWORD;
1108 timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1109 timeouts.ReadTotalTimeoutConstant = 1 << 30; /* almost forever */
1110 timeouts.WriteTotalTimeoutMultiplier = 0;
1111 timeouts.WriteTotalTimeoutConstant = 0;
1112 SetCommTimeouts(file->handle, &timeouts);
1114 dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
1115 if (!GetCommState(file->handle, &dcbSerialParams)) {
1116 CloseHandle(file->handle);
1120 dcbSerialParams.BaudRate = CBR_9600;
1121 dcbSerialParams.ByteSize = 8;
1122 dcbSerialParams.StopBits = ONESTOPBIT;
1123 dcbSerialParams.Parity = NOPARITY;
1124 if (!SetCommState(file->handle, &dcbSerialParams)) {
1125 CloseHandle(file->handle);
1134 altos_close(struct altos_file *file)
1136 if (file->handle != INVALID_HANDLE_VALUE) {
1137 CloseHandle(file->handle);
1138 file->handle = INVALID_HANDLE_VALUE;
1143 altos_free(struct altos_file *file)
1150 altos_putchar(struct altos_file *file, char c)
1154 if (file->out_used == USB_BUF_SIZE) {
1155 ret = altos_flush(file);
1159 file->out_data[file->out_used++] = c;
1160 if (file->out_used == USB_BUF_SIZE)
1161 return altos_flush(file);
1162 return LIBALTOS_SUCCESS;
1166 altos_getchar(struct altos_file *file, int timeout)
1169 while (file->in_read == file->in_used) {
1170 if (file->handle == INVALID_HANDLE_VALUE)
1171 return LIBALTOS_ERROR;
1172 ret = altos_fill(file, timeout);
1176 return file->in_data[file->in_read++];