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"
61 int sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
74 if (!(port = malloc(sizeof(struct sp_port))))
77 len = strlen(portname) + 1;
79 if (!(port->name = malloc(len)))
85 memcpy(port->name, portname, len);
92 int sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
99 if (!port || !port->name)
102 return sp_get_port_by_name(port->name, copy_ptr);
105 void sp_free_port(struct sp_port *port)
116 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
121 for (count = 0; list[count]; count++);
122 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
125 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
127 list[count + 1] = NULL;
131 sp_free_port_list(list);
135 int sp_list_ports(struct sp_port ***list_ptr)
137 struct sp_port **list;
140 if (!(list = malloc(sizeof(struct sp_port **))))
148 DWORD max_value_len, max_data_size, max_data_len;
149 DWORD value_len, data_size, data_len;
150 DWORD type, index = 0;
154 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
155 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
160 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
161 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
166 max_data_len = max_data_size / sizeof(TCHAR);
167 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
172 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
178 value_len = max_value_len + 1,
179 data_size = max_data_size,
180 RegEnumValue(key, index, value, &value_len,
181 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
183 data_len = data_size / sizeof(TCHAR);
184 data[data_len] = '\0';
186 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
188 name_len = data_len + 1;
190 if (!(name = malloc(name_len)))
196 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
200 if (type == REG_SZ && !(list = sp_list_append(list, name)))
217 CFMutableDictionaryRef classes;
224 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
230 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
236 CFDictionarySetValue(classes,
237 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
239 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS)
245 if (!(path = malloc(PATH_MAX)))
251 while ((port = IOIteratorNext(iter))) {
252 cf_path = IORegistryEntryCreateCFProperty(port,
253 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
255 result = CFStringGetCString(cf_path,
256 path, PATH_MAX, kCFStringEncodingASCII);
258 if (result && !(list = sp_list_append(list, path)))
261 IOObjectRelease(port);
265 IOObjectRelease(port);
270 IOObjectRelease(iter);
275 struct udev_enumerate *ud_enumerate;
276 struct udev_list_entry *ud_list;
277 struct udev_list_entry *ud_entry;
279 struct udev_device *ud_dev, *ud_parent;
282 int fd, ioctl_result;
283 struct serial_struct serial_info;
286 ud_enumerate = udev_enumerate_new(ud);
287 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
288 udev_enumerate_scan_devices(ud_enumerate);
289 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
290 udev_list_entry_foreach(ud_entry, ud_list)
292 path = udev_list_entry_get_name(ud_entry);
293 ud_dev = udev_device_new_from_syspath(ud, path);
294 /* If there is no parent device, this is a virtual tty. */
295 ud_parent = udev_device_get_parent(ud_dev);
296 if (ud_parent == NULL)
298 udev_device_unref(ud_dev);
301 name = udev_device_get_devnode(ud_dev);
302 /* The serial8250 driver has a hardcoded number of ports.
303 * The only way to tell which actually exist on a given system
304 * is to try to open them and make an ioctl call. */
305 driver = udev_device_get_driver(ud_parent);
306 if (driver && !strcmp(driver, "serial8250"))
308 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
310 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
312 if (ioctl_result != 0)
314 if (serial_info.type == PORT_UNKNOWN)
317 list = sp_list_append(list, name);
319 udev_device_unref(ud_dev);
327 udev_enumerate_unref(ud_enumerate);
338 sp_free_port_list(list);
346 void sp_free_port_list(struct sp_port **list)
350 for (i = 0; list[i]; i++)
351 sp_free_port(list[i]);
355 static int sp_validate_port(struct sp_port *port)
360 if (port->hdl == INVALID_HANDLE_VALUE)
369 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
371 int sp_open(struct sp_port *port, int flags)
377 DWORD desired_access = 0, flags_and_attributes = 0;
378 char *escaped_port_name;
380 /* Prefix port name with '\\.\' to work with ports above COM9. */
381 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
383 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
385 /* Map 'flags' to the OS-specific settings. */
386 desired_access |= GENERIC_READ;
387 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
388 if (flags & SP_MODE_RDWR)
389 desired_access |= GENERIC_WRITE;
390 if (flags & SP_MODE_NONBLOCK)
391 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
393 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
394 OPEN_EXISTING, flags_and_attributes, 0);
396 free(escaped_port_name);
398 if (port->hdl == INVALID_HANDLE_VALUE)
403 /* Map 'flags' to the OS-specific settings. */
404 if (flags & SP_MODE_RDWR)
405 flags_local |= O_RDWR;
406 if (flags & SP_MODE_RDONLY)
407 flags_local |= O_RDONLY;
408 if (flags & SP_MODE_NONBLOCK)
409 flags_local |= O_NONBLOCK;
411 if ((port->fd = open(port->name, flags_local)) < 0)
418 int sp_close(struct sp_port *port)
423 /* Returns non-zero upon success, 0 upon failure. */
424 if (CloseHandle(port->hdl) == 0)
427 /* Returns 0 upon success, -1 upon failure. */
428 if (close(port->fd) == -1)
435 int sp_flush(struct sp_port *port)
440 /* Returns non-zero upon success, 0 upon failure. */
441 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
444 /* Returns 0 upon success, -1 upon failure. */
445 if (tcflush(port->fd, TCIOFLUSH) < 0)
451 int sp_write(struct sp_port *port, const void *buf, size_t count)
461 /* Returns non-zero upon success, 0 upon failure. */
462 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
466 /* Returns the number of bytes written, or -1 upon failure. */
467 ssize_t written = write(port->fd, buf, count);
476 int sp_read(struct sp_port *port, void *buf, size_t count)
484 DWORD bytes_read = 0;
486 /* Returns non-zero upon success, 0 upon failure. */
487 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
493 /* Returns the number of bytes read, or -1 upon failure. */
494 if ((bytes_read = read(port->fd, buf, count)) < 0)
500 static int start_config(struct sp_port *port, struct sp_port_data *data)
504 if (!GetCommState(port->hdl, &data->dcb))
509 if (tcgetattr(port->fd, &data->term) < 0)
512 if (ioctl(port->fd, TIOCMGET, &controlbits) < 0)
515 if (data->term.c_cflag & CRTSCTS) {
516 data->rts = SP_RTS_FLOW_CONTROL;
517 data->cts = SP_CTS_FLOW_CONTROL;
519 data->rts = (controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
520 data->cts = SP_CTS_IGNORE;
523 data->dtr = (controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
524 data->dsr = SP_DSR_IGNORE;
529 static int set_baudrate(struct sp_port_data *data, int baudrate)
534 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
535 * have documented CBR_* macros.
538 data->dcb.BaudRate = CBR_110;
541 data->dcb.BaudRate = CBR_300;
544 data->dcb.BaudRate = CBR_600;
547 data->dcb.BaudRate = CBR_1200;
550 data->dcb.BaudRate = CBR_2400;
553 data->dcb.BaudRate = CBR_4800;
556 data->dcb.BaudRate = CBR_9600;
559 data->dcb.BaudRate = CBR_14400; /* Not available on Unix? */
562 data->dcb.BaudRate = CBR_19200;
565 data->dcb.BaudRate = CBR_38400;
568 data->dcb.BaudRate = CBR_57600;
571 data->dcb.BaudRate = CBR_115200;
574 data->dcb.BaudRate = CBR_128000; /* Not available on Unix? */
577 data->dcb.BaudRate = CBR_256000; /* Not available on Unix? */
639 #if !defined(__APPLE__) && !defined(__OpenBSD__)
648 if (cfsetospeed(&data->term, baud) < 0)
651 if (cfsetispeed(&data->term, baud) < 0)
658 static int set_bits(struct sp_port_data *data, int bits)
661 data->dcb.ByteSize = bits;
663 data->term.c_cflag &= ~CSIZE;
666 data->term.c_cflag |= CS8;
669 data->term.c_cflag |= CS7;
672 data->term.c_cflag |= CS6;
681 static int set_parity(struct sp_port_data *data, int parity)
685 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
687 data->dcb.Parity = NOPARITY;
690 data->dcb.Parity = EVENPARITY;
693 data->dcb.Parity = ODDPARITY;
699 data->term.c_iflag &= ~IGNPAR;
700 data->term.c_cflag &= ~(PARENB | PARODD);
703 data->term.c_iflag |= IGNPAR;
706 data->term.c_cflag |= PARENB;
709 data->term.c_cflag |= PARENB | PARODD;
718 static int set_stopbits(struct sp_port_data *data, int stopbits)
722 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
724 data->dcb.StopBits = ONESTOPBIT;
727 data->dcb.StopBits = TWOSTOPBITS;
733 data->term.c_cflag &= ~CSTOPB;
736 data->term.c_cflag &= ~CSTOPB;
739 data->term.c_cflag |= CSTOPB;
748 static int set_rts(struct sp_port_data *data, int rts)
753 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
756 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
758 case SP_RTS_FLOW_CONTROL:
759 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
770 static int set_cts(struct sp_port_data *data, int cts)
775 data->dcb.fOutxCtsFlow = FALSE;
777 case SP_CTS_FLOW_CONTROL:
778 data->dcb.fOutxCtsFlow = TRUE;
789 static int set_dtr(struct sp_port_data *data, int dtr)
794 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
797 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
799 case SP_DTR_FLOW_CONTROL:
800 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
811 static int set_dsr(struct sp_port_data *data, int dsr)
816 data->dcb.fOutxDsrFlow = FALSE;
818 case SP_DSR_FLOW_CONTROL:
819 data->dcb.fOutxDsrFlow = TRUE;
830 static int set_xon_xoff(struct sp_port_data *data, int xon_xoff)
834 case SP_XONXOFF_DISABLED:
835 data->dcb.fInX = FALSE;
836 data->dcb.fOutX = FALSE;
839 data->dcb.fInX = TRUE;
840 data->dcb.fOutX = FALSE;
843 data->dcb.fInX = FALSE;
844 data->dcb.fOutX = TRUE;
846 case SP_XONXOFF_INOUT:
847 data->dcb.fInX = TRUE;
848 data->dcb.fOutX = TRUE;
854 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
856 case SP_XONXOFF_DISABLED:
859 data->term.c_iflag |= IXOFF;
862 data->term.c_iflag |= IXON | IXANY;
864 case SP_XONXOFF_INOUT:
865 data->term.c_iflag |= IXON | IXOFF | IXANY;
874 static int apply_config(struct sp_port *port, struct sp_port_data *data)
877 if (!SetCommState(port->hdl, &data->dcb))
882 /* Turn off all serial port cooking. */
883 data->term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
884 data->term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
885 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
886 data->term.c_oflag &= ~OFILL;
888 /* Disable canonical mode, and don't echo input characters. */
889 data->term.c_lflag &= ~(ICANON | ECHO);
891 /* Ignore modem status lines; enable receiver */
892 data->term.c_cflag |= (CLOCAL | CREAD);
894 /* Asymmetric use of RTS/CTS not supported yet. */
895 if ((data->rts == SP_RTS_FLOW_CONTROL) != (data->cts == SP_CTS_FLOW_CONTROL))
898 /* DTR/DSR flow control not supported yet. */
899 if (data->dtr == SP_DTR_FLOW_CONTROL || data->dsr == SP_DSR_FLOW_CONTROL)
902 if (data->rts == SP_RTS_FLOW_CONTROL)
903 data->term.c_iflag |= CRTSCTS;
906 controlbits = TIOCM_RTS;
907 if (ioctl(port->fd, data->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
912 controlbits = TIOCM_DTR;
913 if (ioctl(port->fd, data->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
917 /* Write the configured settings. */
918 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
924 #define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
925 #define TRY_SET(x) do { if (config->x >= 0) TRY(set_##x(&data, config->x)); } while (0)
927 int sp_set_config(struct sp_port *port, struct sp_port_config *config)
929 struct sp_port_data data;
931 TRY(start_config(port, &data));
941 TRY(apply_config(port, &data));
946 int sp_last_error_code(void)
949 return GetLastError();
955 char *sp_last_error_message(void)
959 DWORD error = GetLastError();
962 FORMAT_MESSAGE_ALLOCATE_BUFFER |
963 FORMAT_MESSAGE_FROM_SYSTEM |
964 FORMAT_MESSAGE_IGNORE_INSERTS,
967 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
973 return strerror(errno);
977 void sp_free_error_message(char *message)