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"
58 /* Standard baud rates. */
60 #define BAUD_TYPE DWORD
61 #define BAUD(n) {CBR_##n, n}
63 #define BAUD_TYPE speed_t
64 #define BAUD(n) {B##n, n}
72 const struct std_baudrate std_baudrates[] = {
75 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
76 * have documented CBR_* macros.
78 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
79 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
80 BAUD(115200), BAUD(128000), BAUD(256000)
82 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200), BAUD(300),
83 BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800), BAUD(9600),
84 BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200), BAUD(230400),
85 #if !defined(__APPLE__) && !defined(__OpenBSD__)
91 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
92 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
94 /* Helper functions. */
95 static int validate_port(struct sp_port *port);
96 static struct sp_port **list_append(struct sp_port **list, const char *portname);
97 static int get_config(struct sp_port *port, struct port_data *data, struct sp_port_config *config);
98 static int set_config(struct sp_port *port, struct port_data *data, struct sp_port_config *config);
100 int sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
102 struct sp_port *port;
113 if (!(port = malloc(sizeof(struct sp_port))))
116 len = strlen(portname) + 1;
118 if (!(port->name = malloc(len)))
124 memcpy(port->name, portname, len);
127 port->hdl = INVALID_HANDLE_VALUE;
137 int sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
144 if (!port || !port->name)
147 return sp_get_port_by_name(port->name, copy_ptr);
150 void sp_free_port(struct sp_port *port)
161 static struct sp_port **list_append(struct sp_port **list, const char *portname)
166 for (count = 0; list[count]; count++);
167 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
170 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
172 list[count + 1] = NULL;
176 sp_free_port_list(list);
180 int sp_list_ports(struct sp_port ***list_ptr)
182 struct sp_port **list;
185 if (!(list = malloc(sizeof(struct sp_port **))))
193 DWORD max_value_len, max_data_size, max_data_len;
194 DWORD value_len, data_size, data_len;
195 DWORD type, index = 0;
199 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
200 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
205 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
206 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
211 max_data_len = max_data_size / sizeof(TCHAR);
212 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
217 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
223 value_len = max_value_len + 1,
224 data_size = max_data_size,
225 RegEnumValue(key, index, value, &value_len,
226 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
228 data_len = data_size / sizeof(TCHAR);
229 data[data_len] = '\0';
231 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
233 name_len = data_len + 1;
235 if (!(name = malloc(name_len)))
241 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
245 if (type == REG_SZ && !(list = list_append(list, name)))
262 CFMutableDictionaryRef classes;
269 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
275 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
281 CFDictionarySetValue(classes,
282 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
284 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS)
290 if (!(path = malloc(PATH_MAX)))
296 while ((port = IOIteratorNext(iter))) {
297 cf_path = IORegistryEntryCreateCFProperty(port,
298 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
300 result = CFStringGetCString(cf_path,
301 path, PATH_MAX, kCFStringEncodingASCII);
303 if (result && !(list = list_append(list, path)))
306 IOObjectRelease(port);
310 IOObjectRelease(port);
315 IOObjectRelease(iter);
320 struct udev_enumerate *ud_enumerate;
321 struct udev_list_entry *ud_list;
322 struct udev_list_entry *ud_entry;
324 struct udev_device *ud_dev, *ud_parent;
327 int fd, ioctl_result;
328 struct serial_struct serial_info;
331 ud_enumerate = udev_enumerate_new(ud);
332 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
333 udev_enumerate_scan_devices(ud_enumerate);
334 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
335 udev_list_entry_foreach(ud_entry, ud_list)
337 path = udev_list_entry_get_name(ud_entry);
338 ud_dev = udev_device_new_from_syspath(ud, path);
339 /* If there is no parent device, this is a virtual tty. */
340 ud_parent = udev_device_get_parent(ud_dev);
341 if (ud_parent == NULL)
343 udev_device_unref(ud_dev);
346 name = udev_device_get_devnode(ud_dev);
347 /* The serial8250 driver has a hardcoded number of ports.
348 * The only way to tell which actually exist on a given system
349 * is to try to open them and make an ioctl call. */
350 driver = udev_device_get_driver(ud_parent);
351 if (driver && !strcmp(driver, "serial8250"))
353 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
355 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
357 if (ioctl_result != 0)
359 if (serial_info.type == PORT_UNKNOWN)
362 list = list_append(list, name);
364 udev_device_unref(ud_dev);
372 udev_enumerate_unref(ud_enumerate);
383 sp_free_port_list(list);
391 void sp_free_port_list(struct sp_port **list)
395 for (i = 0; list[i]; i++)
396 sp_free_port(list[i]);
400 static int validate_port(struct sp_port *port)
405 if (port->hdl == INVALID_HANDLE_VALUE)
414 #define CHECK_PORT() do { if (!validate_port(port)) return SP_ERR_ARG; } while (0)
416 int sp_open(struct sp_port *port, int flags)
422 DWORD desired_access = 0, flags_and_attributes = 0;
423 char *escaped_port_name;
425 /* Prefix port name with '\\.\' to work with ports above COM9. */
426 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
428 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
430 /* Map 'flags' to the OS-specific settings. */
431 desired_access |= GENERIC_READ;
432 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
433 if (flags & SP_MODE_RDWR)
434 desired_access |= GENERIC_WRITE;
435 if (flags & SP_MODE_NONBLOCK)
436 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
438 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
439 OPEN_EXISTING, flags_and_attributes, 0);
441 free(escaped_port_name);
443 if (port->hdl == INVALID_HANDLE_VALUE)
447 struct port_data data;
448 struct sp_port_config config;
451 /* Map 'flags' to the OS-specific settings. */
452 if (flags & SP_MODE_RDWR)
453 flags_local |= O_RDWR;
454 if (flags & SP_MODE_RDONLY)
455 flags_local |= O_RDONLY;
456 if (flags & SP_MODE_NONBLOCK)
457 flags_local |= O_NONBLOCK;
459 if ((port->fd = open(port->name, flags_local)) < 0)
462 ret = get_config(port, &data, &config);
470 /* Turn off all serial port cooking. */
471 data.term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
472 data.term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
473 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
474 data.term.c_oflag &= ~OFILL;
476 /* Disable canonical mode, and don't echo input characters. */
477 data.term.c_lflag &= ~(ICANON | ECHO);
479 /* Ignore modem status lines; enable receiver */
480 data.term.c_cflag |= (CLOCAL | CREAD);
482 ret = set_config(port, &data, &config);
494 int sp_close(struct sp_port *port)
499 /* Returns non-zero upon success, 0 upon failure. */
500 if (CloseHandle(port->hdl) == 0)
502 port->hdl = INVALID_HANDLE_VALUE;
504 /* Returns 0 upon success, -1 upon failure. */
505 if (close(port->fd) == -1)
513 int sp_flush(struct sp_port *port)
518 /* Returns non-zero upon success, 0 upon failure. */
519 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
522 /* Returns 0 upon success, -1 upon failure. */
523 if (tcflush(port->fd, TCIOFLUSH) < 0)
529 int sp_write(struct sp_port *port, const void *buf, size_t count)
539 /* Returns non-zero upon success, 0 upon failure. */
540 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
544 /* Returns the number of bytes written, or -1 upon failure. */
545 ssize_t written = write(port->fd, buf, count);
554 int sp_read(struct sp_port *port, void *buf, size_t count)
562 DWORD bytes_read = 0;
564 /* Returns non-zero upon success, 0 upon failure. */
565 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
571 /* Returns the number of bytes read, or -1 upon failure. */
572 if ((bytes_read = read(port->fd, buf, count)) < 0)
578 static int get_config(struct sp_port *port, struct port_data *data, struct sp_port_config *config)
583 if (!GetCommState(port->hdl, &data->dcb))
586 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
587 if (data->dcb.BaudRate == std_baudrates[i].index) {
588 config->baudrate = std_baudrates[i].value;
593 if (i == NUM_STD_BAUDRATES)
594 /* BaudRate field can be either an index or a custom baud rate. */
595 config->baudrate = data->dcb.BaudRate;
597 config->bits = data->dcb.ByteSize;
599 if (data->dcb.fParity)
600 switch (data->dcb.Parity) {
602 config->parity = SP_PARITY_NONE;
605 config->parity = SP_PARITY_EVEN;
608 config->parity = SP_PARITY_ODD;
614 config->parity = SP_PARITY_NONE;
616 switch (data->dcb.StopBits) {
618 config->stopbits = 1;
621 config->stopbits = 2;
624 config->stopbits = -1;
627 switch (data->dcb.fRtsControl) {
628 case RTS_CONTROL_DISABLE:
629 config->rts = SP_RTS_OFF;
631 case RTS_CONTROL_ENABLE:
632 config->rts = SP_RTS_ON;
634 case RTS_CONTROL_HANDSHAKE:
635 config->rts = SP_RTS_FLOW_CONTROL;
641 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
643 switch (data->dcb.fDtrControl) {
644 case DTR_CONTROL_DISABLE:
645 config->dtr = SP_DTR_OFF;
647 case DTR_CONTROL_ENABLE:
648 config->dtr = SP_DTR_ON;
650 case DTR_CONTROL_HANDSHAKE:
651 config->dtr = SP_DTR_FLOW_CONTROL;
657 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
659 if (data->dcb.fInX) {
661 config->xon_xoff = SP_XONXOFF_INOUT;
663 config->xon_xoff = SP_XONXOFF_IN;
666 config->xon_xoff = SP_XONXOFF_OUT;
668 config->xon_xoff = SP_XONXOFF_DISABLED;
673 if (tcgetattr(port->fd, &data->term) < 0)
676 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
678 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
679 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
680 config->baudrate = std_baudrates[i].value;
685 if (i == NUM_STD_BAUDRATES)
686 config->baudrate = -1;
688 switch (data->term.c_cflag & CSIZE) {
705 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
706 config->parity = SP_PARITY_NONE;
707 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
710 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
712 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
714 if (data->term.c_cflag & CRTSCTS) {
715 config->rts = SP_RTS_FLOW_CONTROL;
716 config->cts = SP_CTS_FLOW_CONTROL;
718 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
719 config->cts = SP_CTS_IGNORE;
722 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
723 config->dsr = SP_DSR_IGNORE;
729 static int set_config(struct sp_port *port, struct port_data *data, struct sp_port_config *config)
734 if (config->baudrate >= 0)
736 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
737 if (config->baudrate == std_baudrates[i].value) {
738 data->dcb.BaudRate = std_baudrates[i].index;
743 if (i == NUM_STD_BAUDRATES)
744 data->dcb.BaudRate = config->baudrate;
747 if (config->bits >= 0)
748 data->dcb.ByteSize = config->bits;
750 if (config->parity >= 0) {
751 switch (config->parity) {
752 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
754 data->dcb.Parity = NOPARITY;
757 data->dcb.Parity = EVENPARITY;
760 data->dcb.Parity = ODDPARITY;
767 if (config->stopbits >= 0) {
768 switch (config->stopbits) {
769 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
771 data->dcb.StopBits = ONESTOPBIT;
774 data->dcb.StopBits = TWOSTOPBITS;
781 if (config->rts >= 0) {
782 switch (config->rts) {
784 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
787 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
789 case SP_RTS_FLOW_CONTROL:
790 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
797 if (config->cts >= 0) {
798 switch (config->cts) {
800 data->dcb.fOutxCtsFlow = FALSE;
802 case SP_CTS_FLOW_CONTROL:
803 data->dcb.fOutxCtsFlow = TRUE;
810 if (config->dtr >= 0) {
811 switch (config->dtr) {
813 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
816 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
818 case SP_DTR_FLOW_CONTROL:
819 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
826 if (config->dsr >= 0) {
827 switch (config->dsr) {
829 data->dcb.fOutxDsrFlow = FALSE;
831 case SP_DSR_FLOW_CONTROL:
832 data->dcb.fOutxDsrFlow = TRUE;
839 if (config->xon_xoff >= 0) {
840 switch (config->xon_xoff) {
841 case SP_XONXOFF_DISABLED:
842 data->dcb.fInX = FALSE;
843 data->dcb.fOutX = FALSE;
846 data->dcb.fInX = TRUE;
847 data->dcb.fOutX = FALSE;
850 data->dcb.fInX = FALSE;
851 data->dcb.fOutX = TRUE;
853 case SP_XONXOFF_INOUT:
854 data->dcb.fInX = TRUE;
855 data->dcb.fOutX = TRUE;
862 if (!SetCommState(port->hdl, &data->dcb))
867 if (config->baudrate >= 0)
869 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
870 if (config->baudrate == std_baudrates[i].value) {
871 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
874 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
880 if (i == NUM_STD_BAUDRATES)
884 if (config->bits >= 0) {
885 data->term.c_cflag &= ~CSIZE;
886 switch (config->bits) {
888 data->term.c_cflag |= CS8;
891 data->term.c_cflag |= CS7;
894 data->term.c_cflag |= CS6;
901 if (config->parity >= 0) {
902 data->term.c_iflag &= ~IGNPAR;
903 data->term.c_cflag &= ~(PARENB | PARODD);
904 switch (config->parity) {
906 data->term.c_iflag |= IGNPAR;
909 data->term.c_cflag |= PARENB;
912 data->term.c_cflag |= PARENB | PARODD;
919 if (config->stopbits >= 0) {
920 data->term.c_cflag &= ~CSTOPB;
921 switch (config->stopbits) {
923 data->term.c_cflag &= ~CSTOPB;
926 data->term.c_cflag |= CSTOPB;
933 if (config->rts >= 0 || config->cts >= 0)
935 /* Asymmetric use of RTS/CTS not supported yet. */
937 if (data->term.c_iflag & CRTSCTS) {
938 /* Flow control can only be disabled for both RTS & CTS together. */
939 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
940 if (config->cts != SP_CTS_IGNORE)
943 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
944 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
948 /* Flow control can only be enabled for both RTS & CTS together. */
949 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
950 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
954 if (config->rts >= 0) {
955 if (config->rts == SP_RTS_FLOW_CONTROL) {
956 data->term.c_iflag |= CRTSCTS;
958 int controlbits = TIOCM_RTS;
959 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
966 if (config->dtr >= 0 || config->dsr >= 0)
968 /* DTR/DSR flow control not supported yet. */
969 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
972 if (config->dtr >= 0) {
973 int controlbits = TIOCM_DTR;
974 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
980 if (config->xon_xoff >= 0) {
981 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
982 switch (config->xon_xoff) {
983 case SP_XONXOFF_DISABLED:
986 data->term.c_iflag |= IXOFF;
989 data->term.c_iflag |= IXON | IXANY;
991 case SP_XONXOFF_INOUT:
992 data->term.c_iflag |= IXON | IXOFF | IXANY;
999 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
1006 #define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
1008 int sp_set_config(struct sp_port *port, struct sp_port_config *config)
1010 struct port_data data;
1011 struct sp_port_config prev_config;
1013 TRY(get_config(port, &data, &prev_config));
1014 TRY(set_config(port, &data, config));
1019 #define CREATE_SETTER(x) int sp_set_##x(struct sp_port *port, int x) { \
1020 struct port_data data; \
1021 struct sp_port_config config; \
1022 TRY(get_config(port, &data, &config)); \
1024 TRY(set_config(port, &data, &config)); \
1028 CREATE_SETTER(baudrate)
1030 CREATE_SETTER(parity)
1031 CREATE_SETTER(stopbits)
1036 CREATE_SETTER(xon_xoff)
1038 int sp_set_flowcontrol(struct sp_port *port, int flowcontrol)
1040 struct port_data data;
1041 struct sp_port_config config;
1043 TRY(get_config(port, &data, &config));
1045 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
1046 config.xon_xoff = SP_XONXOFF_INOUT;
1048 config.xon_xoff = SP_XONXOFF_DISABLED;
1050 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
1051 config.rts = SP_RTS_FLOW_CONTROL;
1052 config.cts = SP_CTS_FLOW_CONTROL;
1054 if (config.rts == SP_RTS_FLOW_CONTROL)
1055 config.rts = SP_RTS_ON;
1056 config.cts = SP_CTS_IGNORE;
1059 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
1060 config.dtr = SP_DTR_FLOW_CONTROL;
1061 config.dsr = SP_DSR_FLOW_CONTROL;
1063 if (config.dtr == SP_DTR_FLOW_CONTROL)
1064 config.dtr = SP_DTR_ON;
1065 config.dsr = SP_DSR_IGNORE;
1068 TRY(set_config(port, &data, &config));
1073 int sp_last_error_code(void)
1076 return GetLastError();
1082 char *sp_last_error_message(void)
1086 DWORD error = GetLastError();
1089 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1090 FORMAT_MESSAGE_FROM_SYSTEM |
1091 FORMAT_MESSAGE_IGNORE_INSERTS,
1094 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1100 return strerror(errno);
1104 void sp_free_error_message(char *message)