2 * This file is part of the libserialport project.
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2013 Martin Ling <martin-libserialport@earth.li>
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Lesser General Public License as
10 * published by the Free Software Foundation, either version 3 of the
11 * License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include <sys/types.h>
35 #include <sys/ioctl.h>
38 #include <IOKit/IOKitLib.h>
39 #include <IOKit/serial/IOSerialKeys.h>
40 #include <sys/syslimits.h>
44 #include "linux/serial.h"
47 #include "libserialport.h"
59 int sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
72 if (!(port = malloc(sizeof(struct sp_port))))
75 len = strlen(portname) + 1;
77 if (!(port->name = malloc(len)))
83 memcpy(port->name, portname, len);
90 int sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
97 if (!port || !port->name)
100 return sp_get_port_by_name(port->name, copy_ptr);
103 void sp_free_port(struct sp_port *port)
114 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
119 for (count = 0; list[count]; count++);
120 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
123 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
125 list[count + 1] = NULL;
129 sp_free_port_list(list);
133 int sp_list_ports(struct sp_port ***list_ptr)
135 struct sp_port **list;
138 if (!(list = malloc(sizeof(struct sp_port **))))
146 DWORD max_value_len, max_data_size, max_data_len;
147 DWORD value_len, data_size, data_len;
148 DWORD type, index = 0;
152 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
153 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
158 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
159 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
164 max_data_len = max_data_size / sizeof(TCHAR);
165 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
170 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
176 value_len = max_value_len + 1,
177 data_size = max_data_size,
178 RegEnumValue(key, index, value, &value_len,
179 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
181 data_len = data_size / sizeof(TCHAR);
182 data[data_len] = '\0';
184 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
186 name_len = data_len + 1;
188 if (!(name = malloc(name_len)))
194 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
198 if (type == REG_SZ && !(list = sp_list_append(list, name)))
215 CFMutableDictionaryRef classes;
222 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
228 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
234 CFDictionarySetValue(classes,
235 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
237 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS)
243 if (!(path = malloc(PATH_MAX)))
249 while ((port = IOIteratorNext(iter))) {
250 cf_path = IORegistryEntryCreateCFProperty(port,
251 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
253 result = CFStringGetCString(cf_path,
254 path, PATH_MAX, kCFStringEncodingASCII);
256 if (result && !(list = sp_list_append(list, path)))
259 IOObjectRelease(port);
263 IOObjectRelease(port);
268 IOObjectRelease(iter);
273 struct udev_enumerate *ud_enumerate;
274 struct udev_list_entry *ud_list;
275 struct udev_list_entry *ud_entry;
277 struct udev_device *ud_dev, *ud_parent;
280 int fd, ioctl_result;
281 struct serial_struct serial_info;
284 ud_enumerate = udev_enumerate_new(ud);
285 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
286 udev_enumerate_scan_devices(ud_enumerate);
287 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
288 udev_list_entry_foreach(ud_entry, ud_list)
290 path = udev_list_entry_get_name(ud_entry);
291 ud_dev = udev_device_new_from_syspath(ud, path);
292 /* If there is no parent device, this is a virtual tty. */
293 ud_parent = udev_device_get_parent(ud_dev);
294 if (ud_parent == NULL)
296 udev_device_unref(ud_dev);
299 name = udev_device_get_devnode(ud_dev);
300 /* The serial8250 driver has a hardcoded number of ports.
301 * The only way to tell which actually exist on a given system
302 * is to try to open them and make an ioctl call. */
303 driver = udev_device_get_driver(ud_parent);
304 if (driver && !strcmp(driver, "serial8250"))
306 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
308 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
310 if (ioctl_result != 0)
312 if (serial_info.type == PORT_UNKNOWN)
315 list = sp_list_append(list, name);
317 udev_device_unref(ud_dev);
325 udev_enumerate_unref(ud_enumerate);
336 sp_free_port_list(list);
344 void sp_free_port_list(struct sp_port **list)
348 for (i = 0; list[i]; i++)
349 sp_free_port(list[i]);
353 static int sp_validate_port(struct sp_port *port)
358 if (port->hdl == INVALID_HANDLE_VALUE)
367 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
369 int sp_open(struct sp_port *port, int flags)
375 DWORD desired_access = 0, flags_and_attributes = 0;
376 char *escaped_port_name;
378 /* Prefix port name with '\\.\' to work with ports above COM9. */
379 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
381 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
383 /* Map 'flags' to the OS-specific settings. */
384 desired_access |= GENERIC_READ;
385 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
386 if (flags & SP_MODE_RDWR)
387 desired_access |= GENERIC_WRITE;
388 if (flags & SP_MODE_NONBLOCK)
389 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
391 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
392 OPEN_EXISTING, flags_and_attributes, 0);
394 free(escaped_port_name);
396 if (port->hdl == INVALID_HANDLE_VALUE)
401 /* Map 'flags' to the OS-specific settings. */
402 if (flags & SP_MODE_RDWR)
403 flags_local |= O_RDWR;
404 if (flags & SP_MODE_RDONLY)
405 flags_local |= O_RDONLY;
406 if (flags & SP_MODE_NONBLOCK)
407 flags_local |= O_NONBLOCK;
409 if ((port->fd = open(port->name, flags_local)) < 0)
416 int sp_close(struct sp_port *port)
421 /* Returns non-zero upon success, 0 upon failure. */
422 if (CloseHandle(port->hdl) == 0)
425 /* Returns 0 upon success, -1 upon failure. */
426 if (close(port->fd) == -1)
433 int sp_flush(struct sp_port *port)
438 /* Returns non-zero upon success, 0 upon failure. */
439 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
442 /* Returns 0 upon success, -1 upon failure. */
443 if (tcflush(port->fd, TCIOFLUSH) < 0)
449 int sp_write(struct sp_port *port, const void *buf, size_t count)
459 /* Returns non-zero upon success, 0 upon failure. */
460 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
464 /* Returns the number of bytes written, or -1 upon failure. */
465 ssize_t written = write(port->fd, buf, count);
474 int sp_read(struct sp_port *port, void *buf, size_t count)
482 DWORD bytes_read = 0;
484 /* Returns non-zero upon success, 0 upon failure. */
485 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
491 /* Returns the number of bytes read, or -1 upon failure. */
492 if ((bytes_read = read(port->fd, buf, count)) < 0)
498 static int start_config(struct sp_port *port, struct sp_port_data *data)
502 if (!GetCommState(port->hdl, &data->dcb))
505 if (tcgetattr(port->fd, &data->term) < 0)
511 static int set_baudrate(struct sp_port_data *data, int baudrate)
516 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
517 * have documented CBR_* macros.
520 data->dcb.BaudRate = CBR_110;
523 data->dcb.BaudRate = CBR_300;
526 data->dcb.BaudRate = CBR_600;
529 data->dcb.BaudRate = CBR_1200;
532 data->dcb.BaudRate = CBR_2400;
535 data->dcb.BaudRate = CBR_4800;
538 data->dcb.BaudRate = CBR_9600;
541 data->dcb.BaudRate = CBR_14400; /* Not available on Unix? */
544 data->dcb.BaudRate = CBR_19200;
547 data->dcb.BaudRate = CBR_38400;
550 data->dcb.BaudRate = CBR_57600;
553 data->dcb.BaudRate = CBR_115200;
556 data->dcb.BaudRate = CBR_128000; /* Not available on Unix? */
559 data->dcb.BaudRate = CBR_256000; /* Not available on Unix? */
621 #if !defined(__APPLE__) && !defined(__OpenBSD__)
630 if (cfsetospeed(&data->term, baud) < 0)
633 if (cfsetispeed(&data->term, baud) < 0)
640 static int set_bits(struct sp_port_data *data, int bits)
643 data->dcb.ByteSize = bits;
645 data->term.c_cflag &= ~CSIZE;
648 data->term.c_cflag |= CS8;
651 data->term.c_cflag |= CS7;
654 data->term.c_cflag |= CS6;
663 static int set_parity(struct sp_port_data *data, int parity)
667 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
669 data->dcb.Parity = NOPARITY;
672 data->dcb.Parity = EVENPARITY;
675 data->dcb.Parity = ODDPARITY;
681 data->term.c_iflag &= ~IGNPAR;
682 data->term.c_cflag &= ~(PARENB | PARODD);
685 data->term.c_iflag |= IGNPAR;
688 data->term.c_cflag |= PARENB;
691 data->term.c_cflag |= PARENB | PARODD;
700 static int set_stopbits(struct sp_port_data *data, int stopbits)
704 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
706 data->dcb.StopBits = ONESTOPBIT;
709 data->dcb.StopBits = TWOSTOPBITS;
715 data->term.c_cflag &= ~CSTOPB;
718 data->term.c_cflag &= ~CSTOPB;
721 data->term.c_cflag |= CSTOPB;
730 static int set_flowcontrol(struct sp_port_data *data, int flowcontrol)
733 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
734 data->term.c_cflag &= ~CRTSCTS;
735 switch (flowcontrol) {
737 /* No flow control. */
740 data->term.c_cflag |= CRTSCTS;
743 data->term.c_iflag |= IXON | IXOFF | IXANY;
752 static int set_rts(struct sp_port_data *data, int rts)
756 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
758 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
765 static int set_dtr(struct sp_port_data *data, int dtr)
769 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
771 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
778 static int apply_config(struct sp_port *port, struct sp_port_data *data)
781 if (!SetCommState(port->hdl, &data->dcb))
786 /* Turn off all serial port cooking. */
787 data->term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
788 data->term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
789 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
790 data->term.c_oflag &= ~OFILL;
792 /* Disable canonical mode, and don't echo input characters. */
793 data->term.c_lflag &= ~(ICANON | ECHO);
795 /* Ignore modem status lines; enable receiver */
796 data->term.c_cflag |= (CLOCAL | CREAD);
798 /* Write the configured settings. */
799 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
802 if (data->rts != -1) {
803 controlbits = TIOCM_RTS;
804 if (ioctl(port->fd, data->rts ? TIOCMBIS : TIOCMBIC,
809 if (data->dtr != -1) {
810 controlbits = TIOCM_DTR;
811 if (ioctl(port->fd, data->dtr ? TIOCMBIS : TIOCMBIC,
819 #define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
820 #define TRY_SET(x) do { if (config->x >= 0) TRY(set_##x(&data, config->x)); } while (0)
822 int sp_set_config(struct sp_port *port, struct sp_port_config *config)
824 struct sp_port_data data;
826 TRY(start_config(port, &data));
831 TRY_SET(flowcontrol);
834 TRY(apply_config(port, &data));
839 int sp_last_error_code(void)
842 return GetLastError();
848 char *sp_last_error_message(void)
852 DWORD error = GetLastError();
855 FORMAT_MESSAGE_ALLOCATE_BUFFER |
856 FORMAT_MESSAGE_FROM_SYSTEM |
857 FORMAT_MESSAGE_IGNORE_INSERTS,
860 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
866 return strerror(errno);
870 void sp_free_error_message(char *message)