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>
7 * Copyright (C) 2013 Matthias Heidbrink <m-sigrok@heidbrink.biz>
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Lesser General Public License as
11 * published by the Free Software Foundation, either version 3 of the
12 * License, or (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include <sys/types.h>
38 #include <sys/ioctl.h>
41 #include <IOKit/IOKitLib.h>
42 #include <IOKit/serial/IOSerialKeys.h>
43 #include <IOKit/serial/ioss.h>
44 #include <sys/syslimits.h>
48 #include "linux/serial.h"
49 #include "linux_termios.h"
50 #if defined(TCGETX) && defined(TCSETX) && defined(HAVE_TERMIOX)
56 #include "linux_termios.h"
59 #include "libserialport.h"
67 int termiox_supported;
72 /* Standard baud rates. */
74 #define BAUD_TYPE DWORD
75 #define BAUD(n) {CBR_##n, n}
77 #define BAUD_TYPE speed_t
78 #define BAUD(n) {B##n, n}
86 const struct std_baudrate std_baudrates[] = {
89 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
90 * have documented CBR_* macros.
92 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
93 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
94 BAUD(115200), BAUD(128000), BAUD(256000),
96 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
97 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
98 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
100 #if !defined(__APPLE__) && !defined(__OpenBSD__)
106 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
108 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
109 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
111 #define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
113 /* Helper functions. */
114 static enum sp_return validate_port(struct sp_port *port);
115 static struct sp_port **list_append(struct sp_port **list, const char *portname);
116 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
117 struct sp_port_config *config);
118 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
119 const struct sp_port_config *config);
121 enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
123 struct sp_port *port;
134 if (!(port = malloc(sizeof(struct sp_port))))
137 len = strlen(portname) + 1;
139 if (!(port->name = malloc(len))) {
144 memcpy(port->name, portname, len);
147 port->hdl = INVALID_HANDLE_VALUE;
157 enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
164 if (!port || !port->name)
167 return sp_get_port_by_name(port->name, copy_ptr);
170 void sp_free_port(struct sp_port *port)
181 static struct sp_port **list_append(struct sp_port **list, const char *portname)
186 for (count = 0; list[count]; count++);
187 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
190 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
192 list[count + 1] = NULL;
196 sp_free_port_list(list);
200 enum sp_return sp_list_ports(struct sp_port ***list_ptr)
202 struct sp_port **list;
205 if (!(list = malloc(sizeof(struct sp_port **))))
213 DWORD max_value_len, max_data_size, max_data_len;
214 DWORD value_len, data_size, data_len;
215 DWORD type, index = 0;
219 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
220 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
224 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
225 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
229 max_data_len = max_data_size / sizeof(TCHAR);
230 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
234 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
239 value_len = max_value_len + 1,
240 data_size = max_data_size,
241 RegEnumValue(key, index, value, &value_len,
242 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
244 data_len = data_size / sizeof(TCHAR);
245 data[data_len] = '\0';
247 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
249 name_len = data_len + 1;
251 if (!(name = malloc(name_len))) {
256 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
260 if (type == REG_SZ && !(list = list_append(list, name))) {
276 CFMutableDictionaryRef classes;
283 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS) {
288 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) {
293 CFDictionarySetValue(classes,
294 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
296 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS) {
301 if (!(path = malloc(PATH_MAX))) {
306 while ((port = IOIteratorNext(iter))) {
307 cf_path = IORegistryEntryCreateCFProperty(port,
308 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
310 result = CFStringGetCString(cf_path,
311 path, PATH_MAX, kCFStringEncodingASCII);
313 if (result && !(list = list_append(list, path))) {
315 IOObjectRelease(port);
319 IOObjectRelease(port);
324 IOObjectRelease(iter);
329 struct udev_enumerate *ud_enumerate;
330 struct udev_list_entry *ud_list;
331 struct udev_list_entry *ud_entry;
333 struct udev_device *ud_dev, *ud_parent;
336 int fd, ioctl_result;
337 struct serial_struct serial_info;
340 ud_enumerate = udev_enumerate_new(ud);
341 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
342 udev_enumerate_scan_devices(ud_enumerate);
343 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
344 udev_list_entry_foreach(ud_entry, ud_list) {
345 path = udev_list_entry_get_name(ud_entry);
346 ud_dev = udev_device_new_from_syspath(ud, path);
347 /* If there is no parent device, this is a virtual tty. */
348 ud_parent = udev_device_get_parent(ud_dev);
349 if (ud_parent == NULL) {
350 udev_device_unref(ud_dev);
353 name = udev_device_get_devnode(ud_dev);
354 /* The serial8250 driver has a hardcoded number of ports.
355 * The only way to tell which actually exist on a given system
356 * is to try to open them and make an ioctl call. */
357 driver = udev_device_get_driver(ud_parent);
358 if (driver && !strcmp(driver, "serial8250")) {
359 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
361 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
363 if (ioctl_result != 0)
365 if (serial_info.type == PORT_UNKNOWN)
368 list = list_append(list, name);
370 udev_device_unref(ud_dev);
377 udev_enumerate_unref(ud_enumerate);
385 sp_free_port_list(list);
392 void sp_free_port_list(struct sp_port **list)
396 for (i = 0; list[i]; i++)
397 sp_free_port(list[i]);
401 static enum sp_return validate_port(struct sp_port *port)
406 if (port->hdl == INVALID_HANDLE_VALUE)
415 #define CHECK_PORT() do { if (!validate_port(port)) return SP_ERR_ARG; } while (0)
417 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
423 DWORD desired_access = 0, flags_and_attributes = 0;
424 char *escaped_port_name;
426 /* Prefix port name with '\\.\' to work with ports above COM9. */
427 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
429 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
431 /* Map 'flags' to the OS-specific settings. */
432 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
433 if (flags & SP_MODE_READ)
434 desired_access |= GENERIC_READ;
435 if (flags & SP_MODE_WRITE)
436 desired_access |= GENERIC_WRITE;
437 if (flags & SP_MODE_NONBLOCK)
438 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
440 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
441 OPEN_EXISTING, flags_and_attributes, 0);
443 free(escaped_port_name);
445 if (port->hdl == INVALID_HANDLE_VALUE)
449 struct port_data data;
450 struct sp_port_config config;
453 /* Map 'flags' to the OS-specific settings. */
454 if (flags & (SP_MODE_READ | SP_MODE_WRITE))
455 flags_local |= O_RDWR;
456 else if (flags & SP_MODE_READ)
457 flags_local |= O_RDONLY;
458 else if (flags & SP_MODE_WRITE)
459 flags_local |= O_WRONLY;
460 if (flags & SP_MODE_NONBLOCK)
461 flags_local |= O_NONBLOCK;
463 if ((port->fd = open(port->name, flags_local)) < 0)
466 ret = get_config(port, &data, &config);
473 /* Turn off all serial port cooking. */
474 data.term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
475 data.term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
476 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
477 data.term.c_oflag &= ~OFILL;
479 /* Disable canonical mode, and don't echo input characters. */
480 data.term.c_lflag &= ~(ICANON | ECHO);
482 /* Ignore modem status lines; enable receiver */
483 data.term.c_cflag |= (CLOCAL | CREAD);
485 ret = set_config(port, &data, &config);
496 enum sp_return sp_close(struct sp_port *port)
501 /* Returns non-zero upon success, 0 upon failure. */
502 if (CloseHandle(port->hdl) == 0)
504 port->hdl = INVALID_HANDLE_VALUE;
506 /* Returns 0 upon success, -1 upon failure. */
507 if (close(port->fd) == -1)
515 enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
521 if (buffers & SP_BUF_INPUT)
522 flags |= PURGE_RXCLEAR;
523 if (buffers & SP_BUF_OUTPUT)
524 flags |= PURGE_TXCLEAR;
526 /* Returns non-zero upon success, 0 upon failure. */
527 if (PurgeComm(port->hdl, flags) == 0)
531 if (buffers & SP_BUF_BOTH)
533 else if (buffers & SP_BUF_INPUT)
535 else if (buffers & SP_BUF_OUTPUT)
538 /* Returns 0 upon success, -1 upon failure. */
539 if (tcflush(port->fd, flags) < 0)
545 enum sp_return sp_drain(struct sp_port *port)
550 /* Returns non-zero upon success, 0 upon failure. */
551 if (FlushFileBuffers(port->hdl) == 0)
554 /* Returns 0 upon success, -1 upon failure. */
555 if (tcdrain(port->fd) < 0)
562 enum sp_return sp_write(struct sp_port *port, const void *buf, size_t count)
572 /* Returns non-zero upon success, 0 upon failure. */
573 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
577 /* Returns the number of bytes written, or -1 upon failure. */
578 ssize_t written = write(port->fd, buf, count);
587 enum sp_return sp_read(struct sp_port *port, void *buf, size_t count)
595 DWORD bytes_read = 0;
597 /* Returns non-zero upon success, 0 upon failure. */
598 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
604 /* Returns the number of bytes read, or -1 upon failure. */
605 if ((bytes_read = read(port->fd, buf, count)) < 0)
612 static enum sp_return get_baudrate(int fd, int *baudrate)
616 if (!(data = malloc(get_termios_size())))
619 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
624 *baudrate = get_termios_speed(data);
631 static enum sp_return set_baudrate(int fd, int baudrate)
635 if (!(data = malloc(get_termios_size())))
638 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
643 set_termios_speed(data, baudrate);
645 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
656 static enum sp_return get_flow(int fd, int *flow)
660 if (!(data = malloc(get_termiox_size())))
663 if (ioctl(fd, TCGETX, data) < 0) {
668 *flow = get_termiox_flow(data);
675 static enum sp_return set_flow(int fd, int flow)
679 if (!(data = malloc(get_termiox_size())))
682 if (ioctl(fd, TCGETX, data) < 0) {
687 set_termiox_flow(data, flow);
689 if (ioctl(fd, TCSETX, data) < 0) {
698 #endif /* USE_TERMIOX */
699 #endif /* __linux__ */
701 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
702 struct sp_port_config *config)
707 if (!GetCommState(port->hdl, &data->dcb))
710 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
711 if (data->dcb.BaudRate == std_baudrates[i].index) {
712 config->baudrate = std_baudrates[i].value;
717 if (i == NUM_STD_BAUDRATES)
718 /* BaudRate field can be either an index or a custom baud rate. */
719 config->baudrate = data->dcb.BaudRate;
721 config->bits = data->dcb.ByteSize;
723 if (data->dcb.fParity)
724 switch (data->dcb.Parity) {
726 config->parity = SP_PARITY_NONE;
729 config->parity = SP_PARITY_EVEN;
732 config->parity = SP_PARITY_ODD;
738 config->parity = SP_PARITY_NONE;
740 switch (data->dcb.StopBits) {
742 config->stopbits = 1;
745 config->stopbits = 2;
748 config->stopbits = -1;
751 switch (data->dcb.fRtsControl) {
752 case RTS_CONTROL_DISABLE:
753 config->rts = SP_RTS_OFF;
755 case RTS_CONTROL_ENABLE:
756 config->rts = SP_RTS_ON;
758 case RTS_CONTROL_HANDSHAKE:
759 config->rts = SP_RTS_FLOW_CONTROL;
765 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
767 switch (data->dcb.fDtrControl) {
768 case DTR_CONTROL_DISABLE:
769 config->dtr = SP_DTR_OFF;
771 case DTR_CONTROL_ENABLE:
772 config->dtr = SP_DTR_ON;
774 case DTR_CONTROL_HANDSHAKE:
775 config->dtr = SP_DTR_FLOW_CONTROL;
781 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
783 if (data->dcb.fInX) {
785 config->xon_xoff = SP_XONXOFF_INOUT;
787 config->xon_xoff = SP_XONXOFF_IN;
790 config->xon_xoff = SP_XONXOFF_OUT;
792 config->xon_xoff = SP_XONXOFF_DISABLED;
797 if (tcgetattr(port->fd, &data->term) < 0)
800 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
804 int ret = get_flow(port->fd, &data->flow);
806 if (ret == SP_ERR_FAIL && errno == EINVAL)
807 data->termiox_supported = 0;
811 data->termiox_supported = 1;
813 data->termiox_supported = 0;
816 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
817 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
818 config->baudrate = std_baudrates[i].value;
823 if (i == NUM_STD_BAUDRATES) {
825 config->baudrate = (int)data->term.c_ispeed;
826 #elif defined(__linux__)
827 TRY(get_baudrate(port->fd, &config->baudrate));
829 config->baudrate = -1;
833 switch (data->term.c_cflag & CSIZE) {
850 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
851 config->parity = SP_PARITY_NONE;
852 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
855 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
857 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
859 if (data->term.c_cflag & CRTSCTS) {
860 config->rts = SP_RTS_FLOW_CONTROL;
861 config->cts = SP_CTS_FLOW_CONTROL;
863 if (data->termiox_supported && data->flow & RTS_FLOW)
864 config->rts = SP_RTS_FLOW_CONTROL;
866 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
868 config->cts = (data->termiox_supported && data->flow & CTS_FLOW) ?
869 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
872 if (data->termiox_supported && data->flow & DTR_FLOW)
873 config->dtr = SP_DTR_FLOW_CONTROL;
875 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
877 config->dsr = (data->termiox_supported && data->flow & DSR_FLOW) ?
878 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
880 if (data->term.c_iflag & IXOFF) {
881 if (data->term.c_iflag & IXON)
882 config->xon_xoff = SP_XONXOFF_INOUT;
884 config->xon_xoff = SP_XONXOFF_IN;
886 if (data->term.c_iflag & IXON)
887 config->xon_xoff = SP_XONXOFF_OUT;
889 config->xon_xoff = SP_XONXOFF_DISABLED;
896 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
897 const struct sp_port_config *config)
901 BAUD_TYPE baud_nonstd;
910 if (config->baudrate >= 0) {
911 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
912 if (config->baudrate == std_baudrates[i].value) {
913 data->dcb.BaudRate = std_baudrates[i].index;
918 if (i == NUM_STD_BAUDRATES)
919 data->dcb.BaudRate = config->baudrate;
922 if (config->bits >= 0)
923 data->dcb.ByteSize = config->bits;
925 if (config->parity >= 0) {
926 switch (config->parity) {
927 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
929 data->dcb.Parity = NOPARITY;
932 data->dcb.Parity = EVENPARITY;
935 data->dcb.Parity = ODDPARITY;
942 if (config->stopbits >= 0) {
943 switch (config->stopbits) {
944 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
946 data->dcb.StopBits = ONESTOPBIT;
949 data->dcb.StopBits = TWOSTOPBITS;
956 if (config->rts >= 0) {
957 switch (config->rts) {
959 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
962 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
964 case SP_RTS_FLOW_CONTROL:
965 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
972 if (config->cts >= 0) {
973 switch (config->cts) {
975 data->dcb.fOutxCtsFlow = FALSE;
977 case SP_CTS_FLOW_CONTROL:
978 data->dcb.fOutxCtsFlow = TRUE;
985 if (config->dtr >= 0) {
986 switch (config->dtr) {
988 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
991 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
993 case SP_DTR_FLOW_CONTROL:
994 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1001 if (config->dsr >= 0) {
1002 switch (config->dsr) {
1004 data->dcb.fOutxDsrFlow = FALSE;
1006 case SP_DSR_FLOW_CONTROL:
1007 data->dcb.fOutxDsrFlow = TRUE;
1014 if (config->xon_xoff >= 0) {
1015 switch (config->xon_xoff) {
1016 case SP_XONXOFF_DISABLED:
1017 data->dcb.fInX = FALSE;
1018 data->dcb.fOutX = FALSE;
1021 data->dcb.fInX = TRUE;
1022 data->dcb.fOutX = FALSE;
1024 case SP_XONXOFF_OUT:
1025 data->dcb.fInX = FALSE;
1026 data->dcb.fOutX = TRUE;
1028 case SP_XONXOFF_INOUT:
1029 data->dcb.fInX = TRUE;
1030 data->dcb.fOutX = TRUE;
1037 if (!SetCommState(port->hdl, &data->dcb))
1044 if (config->baudrate >= 0) {
1045 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1046 if (config->baudrate == std_baudrates[i].value) {
1047 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1050 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1056 /* Non-standard baud rate */
1057 if (i == NUM_STD_BAUDRATES) {
1059 /* Set "dummy" baud rate. */
1060 if (cfsetspeed(&data->term, B9600) < 0)
1062 baud_nonstd = config->baudrate;
1063 #elif defined(__linux__)
1071 if (config->bits >= 0) {
1072 data->term.c_cflag &= ~CSIZE;
1073 switch (config->bits) {
1075 data->term.c_cflag |= CS8;
1078 data->term.c_cflag |= CS7;
1081 data->term.c_cflag |= CS6;
1084 data->term.c_cflag |= CS5;
1091 if (config->parity >= 0) {
1092 data->term.c_iflag &= ~IGNPAR;
1093 data->term.c_cflag &= ~(PARENB | PARODD);
1094 switch (config->parity) {
1095 case SP_PARITY_NONE:
1096 data->term.c_iflag |= IGNPAR;
1098 case SP_PARITY_EVEN:
1099 data->term.c_cflag |= PARENB;
1102 data->term.c_cflag |= PARENB | PARODD;
1109 if (config->stopbits >= 0) {
1110 data->term.c_cflag &= ~CSTOPB;
1111 switch (config->stopbits) {
1113 data->term.c_cflag &= ~CSTOPB;
1116 data->term.c_cflag |= CSTOPB;
1123 if (config->rts >= 0 || config->cts >= 0) {
1124 if (data->termiox_supported) {
1125 data->flow &= ~(RTS_FLOW | CTS_FLOW);
1126 switch (config->rts) {
1129 controlbits = TIOCM_RTS;
1130 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1133 case SP_RTS_FLOW_CONTROL:
1134 data->flow |= RTS_FLOW;
1139 if (config->cts == SP_CTS_FLOW_CONTROL)
1140 data->flow |= CTS_FLOW;
1142 if (data->flow & (RTS_FLOW | CTS_FLOW))
1143 data->term.c_iflag |= CRTSCTS;
1145 data->term.c_iflag &= ~CRTSCTS;
1147 /* Asymmetric use of RTS/CTS not supported. */
1148 if (data->term.c_iflag & CRTSCTS) {
1149 /* Flow control can only be disabled for both RTS & CTS together. */
1150 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1151 if (config->cts != SP_CTS_IGNORE)
1154 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1155 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1159 /* Flow control can only be enabled for both RTS & CTS together. */
1160 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1161 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1165 if (config->rts >= 0) {
1166 if (config->rts == SP_RTS_FLOW_CONTROL) {
1167 data->term.c_iflag |= CRTSCTS;
1169 controlbits = TIOCM_RTS;
1170 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1178 if (config->dtr >= 0 || config->dsr >= 0) {
1179 if (data->termiox_supported) {
1180 data->flow &= ~(DTR_FLOW | DSR_FLOW);
1181 switch (config->dtr) {
1184 controlbits = TIOCM_DTR;
1185 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1188 case SP_DTR_FLOW_CONTROL:
1189 data->flow |= DTR_FLOW;
1194 if (config->dsr == SP_DSR_FLOW_CONTROL)
1195 data->flow |= DSR_FLOW;
1197 /* DTR/DSR flow control not supported. */
1198 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1201 if (config->dtr >= 0) {
1202 controlbits = TIOCM_DTR;
1203 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1210 if (config->xon_xoff >= 0) {
1211 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1212 switch (config->xon_xoff) {
1213 case SP_XONXOFF_DISABLED:
1216 data->term.c_iflag |= IXOFF;
1218 case SP_XONXOFF_OUT:
1219 data->term.c_iflag |= IXON | IXANY;
1221 case SP_XONXOFF_INOUT:
1222 data->term.c_iflag |= IXON | IXOFF | IXANY;
1229 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
1233 if (baud_nonstd != B0) {
1234 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1236 /* Set baud rates in data->term to correct, but incompatible
1237 * with tcsetattr() value, same as delivered by tcgetattr(). */
1238 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1241 #elif defined(__linux__)
1243 TRY(set_baudrate(port->fd, config->baudrate));
1245 if (data->termiox_supported)
1246 TRY(set_flow(port->fd, data->flow));
1250 #endif /* !_WIN32 */
1255 enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
1257 struct port_data data;
1258 struct sp_port_config prev_config;
1265 TRY(get_config(port, &data, &prev_config));
1266 TRY(set_config(port, &data, config));
1271 #define CREATE_SETTER(x, type) int sp_set_##x(struct sp_port *port, type x) { \
1272 struct port_data data; \
1273 struct sp_port_config config; \
1275 TRY(get_config(port, &data, &config)); \
1277 TRY(set_config(port, &data, &config)); \
1281 CREATE_SETTER(baudrate, int)
1282 CREATE_SETTER(bits, int)
1283 CREATE_SETTER(parity, enum sp_parity)
1284 CREATE_SETTER(stopbits, int)
1285 CREATE_SETTER(rts, enum sp_rts)
1286 CREATE_SETTER(cts, enum sp_cts)
1287 CREATE_SETTER(dtr, enum sp_dtr)
1288 CREATE_SETTER(dsr, enum sp_dsr)
1289 CREATE_SETTER(xon_xoff, enum sp_xonxoff)
1291 enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
1293 struct port_data data;
1294 struct sp_port_config config;
1298 TRY(get_config(port, &data, &config));
1300 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
1301 config.xon_xoff = SP_XONXOFF_INOUT;
1303 config.xon_xoff = SP_XONXOFF_DISABLED;
1305 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
1306 config.rts = SP_RTS_FLOW_CONTROL;
1307 config.cts = SP_CTS_FLOW_CONTROL;
1309 if (config.rts == SP_RTS_FLOW_CONTROL)
1310 config.rts = SP_RTS_ON;
1311 config.cts = SP_CTS_IGNORE;
1314 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
1315 config.dtr = SP_DTR_FLOW_CONTROL;
1316 config.dsr = SP_DSR_FLOW_CONTROL;
1318 if (config.dtr == SP_DTR_FLOW_CONTROL)
1319 config.dtr = SP_DTR_ON;
1320 config.dsr = SP_DSR_IGNORE;
1323 TRY(set_config(port, &data, &config));
1328 enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
1338 if (GetCommModemStatus(port->hdl, &bits) == 0)
1340 if (bits & MS_CTS_ON)
1341 *signals |= SP_SIG_CTS;
1342 if (bits & MS_DSR_ON)
1343 *signals |= SP_SIG_DSR;
1344 if (bits & MS_RING_ON)
1345 *signals |= SP_SIG_DCD;
1346 if (bits & MS_RLSD_ON)
1347 *signals |= SP_SIG_RI;
1350 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
1352 if (bits & TIOCM_CTS)
1353 *signals |= SP_SIG_CTS;
1354 if (bits & TIOCM_DSR)
1355 *signals |= SP_SIG_DSR;
1356 if (bits & TIOCM_CAR)
1357 *signals |= SP_SIG_DCD;
1358 if (bits & TIOCM_RNG)
1359 *signals |= SP_SIG_RI;
1364 enum sp_return sp_start_break(struct sp_port *port)
1368 if (SetCommBreak(port->hdl) == 0)
1371 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
1378 enum sp_return sp_end_break(struct sp_port *port)
1382 if (ClearCommBreak(port->hdl) == 0)
1385 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
1392 int sp_last_error_code(void)
1395 return GetLastError();
1401 char *sp_last_error_message(void)
1405 DWORD error = GetLastError();
1408 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1409 FORMAT_MESSAGE_FROM_SYSTEM |
1410 FORMAT_MESSAGE_IGNORE_INSERTS,
1413 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1419 return strerror(errno);
1423 void sp_free_error_message(char *message)
1432 void sp_set_debug_handler(void (*handler)(const char *format, ...))
1434 sp_debug_handler = handler;
1437 void sp_default_debug_handler(const char *format, ...)
1440 va_start(args, format);
1441 if (getenv("LIBSERIALPORT_DEBUG")) {
1442 fputs("libserialport: ", stderr);
1443 vfprintf(stderr, format, args);