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 /* Debug output macros. */
114 #define DEBUG(fmt, ...) do { if (sp_debug_handler) sp_debug_handler(fmt ".\n", ##__VA_ARGS__); } while (0)
115 #define DEBUG_ERROR(err, msg) DEBUG("%s returning " #err ": " msg, __func__)
116 #define DEBUG_FAIL(msg) do { \
117 char *errmsg = sp_last_error_message(); \
118 DEBUG("%s returning SP_ERR_FAIL: " msg ": %s", __func__, errmsg); \
119 sp_free_error_message(errmsg); \
121 #define RETURN() do { DEBUG("%s returning", __func__); return; } while(0)
122 #define RETURN_CODE(x) do { DEBUG("%s returning " #x, __func__); return x; } while (0)
123 #define RETURN_CODEVAL(x) do { \
125 case SP_OK: RETURN_CODE(SP_OK); \
126 case SP_ERR_ARG: RETURN_CODE(SP_ERR_ARG); \
127 case SP_ERR_FAIL: RETURN_CODE(SP_ERR_FAIL); \
128 case SP_ERR_MEM: RETURN_CODE(SP_ERR_MEM); \
129 case SP_ERR_SUPP: RETURN_CODE(SP_ERR_SUPP); \
132 #define RETURN_OK() RETURN_CODE(SP_OK);
133 #define RETURN_ERROR(err, msg) do { DEBUG_ERROR(err, msg); return err; } while (0)
134 #define RETURN_FAIL(msg) do { DEBUG_FAIL(msg); return SP_ERR_FAIL; } while (0)
135 #define RETURN_VALUE(fmt, x) do { DEBUG("%s returning " fmt, __func__, x); return x; } while (0)
136 #define SET_ERROR(val, err, msg) do { DEBUG_ERROR(err, msg); val = err; } while (0)
137 #define SET_FAIL(val, msg) do { DEBUG_FAIL(msg); val = err; } while (0)
138 #define TRACE(fmt, ...) DEBUG("%s(" fmt ") called", __func__, ##__VA_ARGS__)
140 /* Helper functions. */
141 static enum sp_return validate_port(struct sp_port *port);
142 static struct sp_port **list_append(struct sp_port **list, const char *portname);
143 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
144 struct sp_port_config *config);
145 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
146 const struct sp_port_config *config);
148 enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
150 struct sp_port *port;
161 if (!(port = malloc(sizeof(struct sp_port))))
164 len = strlen(portname) + 1;
166 if (!(port->name = malloc(len))) {
171 memcpy(port->name, portname, len);
174 port->hdl = INVALID_HANDLE_VALUE;
184 enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
191 if (!port || !port->name)
194 return sp_get_port_by_name(port->name, copy_ptr);
197 void sp_free_port(struct sp_port *port)
208 static struct sp_port **list_append(struct sp_port **list, const char *portname)
213 for (count = 0; list[count]; count++);
214 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
217 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
219 list[count + 1] = NULL;
223 sp_free_port_list(list);
227 enum sp_return sp_list_ports(struct sp_port ***list_ptr)
229 struct sp_port **list;
232 if (!(list = malloc(sizeof(struct sp_port **))))
240 DWORD max_value_len, max_data_size, max_data_len;
241 DWORD value_len, data_size, data_len;
242 DWORD type, index = 0;
246 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
247 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
251 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
252 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
256 max_data_len = max_data_size / sizeof(TCHAR);
257 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
261 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
266 value_len = max_value_len + 1,
267 data_size = max_data_size,
268 RegEnumValue(key, index, value, &value_len,
269 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
271 data_len = data_size / sizeof(TCHAR);
272 data[data_len] = '\0';
274 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
276 name_len = data_len + 1;
278 if (!(name = malloc(name_len))) {
283 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
287 if (type == REG_SZ && !(list = list_append(list, name))) {
303 CFMutableDictionaryRef classes;
310 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS) {
315 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) {
320 CFDictionarySetValue(classes,
321 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
323 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS) {
328 if (!(path = malloc(PATH_MAX))) {
333 while ((port = IOIteratorNext(iter))) {
334 cf_path = IORegistryEntryCreateCFProperty(port,
335 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
337 result = CFStringGetCString(cf_path,
338 path, PATH_MAX, kCFStringEncodingASCII);
340 if (result && !(list = list_append(list, path))) {
342 IOObjectRelease(port);
346 IOObjectRelease(port);
351 IOObjectRelease(iter);
356 struct udev_enumerate *ud_enumerate;
357 struct udev_list_entry *ud_list;
358 struct udev_list_entry *ud_entry;
360 struct udev_device *ud_dev, *ud_parent;
363 int fd, ioctl_result;
364 struct serial_struct serial_info;
367 ud_enumerate = udev_enumerate_new(ud);
368 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
369 udev_enumerate_scan_devices(ud_enumerate);
370 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
371 udev_list_entry_foreach(ud_entry, ud_list) {
372 path = udev_list_entry_get_name(ud_entry);
373 ud_dev = udev_device_new_from_syspath(ud, path);
374 /* If there is no parent device, this is a virtual tty. */
375 ud_parent = udev_device_get_parent(ud_dev);
376 if (ud_parent == NULL) {
377 udev_device_unref(ud_dev);
380 name = udev_device_get_devnode(ud_dev);
381 /* The serial8250 driver has a hardcoded number of ports.
382 * The only way to tell which actually exist on a given system
383 * is to try to open them and make an ioctl call. */
384 driver = udev_device_get_driver(ud_parent);
385 if (driver && !strcmp(driver, "serial8250")) {
386 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
388 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
390 if (ioctl_result != 0)
392 if (serial_info.type == PORT_UNKNOWN)
395 list = list_append(list, name);
397 udev_device_unref(ud_dev);
404 udev_enumerate_unref(ud_enumerate);
412 sp_free_port_list(list);
419 void sp_free_port_list(struct sp_port **list)
423 for (i = 0; list[i]; i++)
424 sp_free_port(list[i]);
428 static enum sp_return validate_port(struct sp_port *port)
433 if (port->hdl == INVALID_HANDLE_VALUE)
442 #define CHECK_PORT() do { if (!validate_port(port)) return SP_ERR_ARG; } while (0)
444 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
450 DWORD desired_access = 0, flags_and_attributes = 0;
451 char *escaped_port_name;
453 /* Prefix port name with '\\.\' to work with ports above COM9. */
454 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
456 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
458 /* Map 'flags' to the OS-specific settings. */
459 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
460 if (flags & SP_MODE_READ)
461 desired_access |= GENERIC_READ;
462 if (flags & SP_MODE_WRITE)
463 desired_access |= GENERIC_WRITE;
464 if (flags & SP_MODE_NONBLOCK)
465 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
467 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
468 OPEN_EXISTING, flags_and_attributes, 0);
470 free(escaped_port_name);
472 if (port->hdl == INVALID_HANDLE_VALUE)
476 struct port_data data;
477 struct sp_port_config config;
480 /* Map 'flags' to the OS-specific settings. */
481 if (flags & (SP_MODE_READ | SP_MODE_WRITE))
482 flags_local |= O_RDWR;
483 else if (flags & SP_MODE_READ)
484 flags_local |= O_RDONLY;
485 else if (flags & SP_MODE_WRITE)
486 flags_local |= O_WRONLY;
487 if (flags & SP_MODE_NONBLOCK)
488 flags_local |= O_NONBLOCK;
490 if ((port->fd = open(port->name, flags_local)) < 0)
493 ret = get_config(port, &data, &config);
500 /* Turn off all serial port cooking. */
501 data.term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
502 data.term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
503 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
504 data.term.c_oflag &= ~OFILL;
506 /* Disable canonical mode, and don't echo input characters. */
507 data.term.c_lflag &= ~(ICANON | ECHO);
509 /* Ignore modem status lines; enable receiver */
510 data.term.c_cflag |= (CLOCAL | CREAD);
512 ret = set_config(port, &data, &config);
523 enum sp_return sp_close(struct sp_port *port)
528 /* Returns non-zero upon success, 0 upon failure. */
529 if (CloseHandle(port->hdl) == 0)
531 port->hdl = INVALID_HANDLE_VALUE;
533 /* Returns 0 upon success, -1 upon failure. */
534 if (close(port->fd) == -1)
542 enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
548 if (buffers & SP_BUF_INPUT)
549 flags |= PURGE_RXCLEAR;
550 if (buffers & SP_BUF_OUTPUT)
551 flags |= PURGE_TXCLEAR;
553 /* Returns non-zero upon success, 0 upon failure. */
554 if (PurgeComm(port->hdl, flags) == 0)
558 if (buffers & SP_BUF_BOTH)
560 else if (buffers & SP_BUF_INPUT)
562 else if (buffers & SP_BUF_OUTPUT)
565 /* Returns 0 upon success, -1 upon failure. */
566 if (tcflush(port->fd, flags) < 0)
572 enum sp_return sp_drain(struct sp_port *port)
577 /* Returns non-zero upon success, 0 upon failure. */
578 if (FlushFileBuffers(port->hdl) == 0)
581 /* Returns 0 upon success, -1 upon failure. */
582 if (tcdrain(port->fd) < 0)
589 enum sp_return sp_write(struct sp_port *port, const void *buf, size_t count)
599 /* Returns non-zero upon success, 0 upon failure. */
600 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
604 /* Returns the number of bytes written, or -1 upon failure. */
605 ssize_t written = write(port->fd, buf, count);
614 enum sp_return sp_read(struct sp_port *port, void *buf, size_t count)
622 DWORD bytes_read = 0;
624 /* Returns non-zero upon success, 0 upon failure. */
625 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
631 /* Returns the number of bytes read, or -1 upon failure. */
632 if ((bytes_read = read(port->fd, buf, count)) < 0)
639 static enum sp_return get_baudrate(int fd, int *baudrate)
643 if (!(data = malloc(get_termios_size())))
646 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
651 *baudrate = get_termios_speed(data);
658 static enum sp_return set_baudrate(int fd, int baudrate)
662 if (!(data = malloc(get_termios_size())))
665 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
670 set_termios_speed(data, baudrate);
672 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
683 static enum sp_return get_flow(int fd, int *flow)
687 if (!(data = malloc(get_termiox_size())))
690 if (ioctl(fd, TCGETX, data) < 0) {
695 *flow = get_termiox_flow(data);
702 static enum sp_return set_flow(int fd, int flow)
706 if (!(data = malloc(get_termiox_size())))
709 if (ioctl(fd, TCGETX, data) < 0) {
714 set_termiox_flow(data, flow);
716 if (ioctl(fd, TCSETX, data) < 0) {
725 #endif /* USE_TERMIOX */
726 #endif /* __linux__ */
728 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
729 struct sp_port_config *config)
734 if (!GetCommState(port->hdl, &data->dcb))
737 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
738 if (data->dcb.BaudRate == std_baudrates[i].index) {
739 config->baudrate = std_baudrates[i].value;
744 if (i == NUM_STD_BAUDRATES)
745 /* BaudRate field can be either an index or a custom baud rate. */
746 config->baudrate = data->dcb.BaudRate;
748 config->bits = data->dcb.ByteSize;
750 if (data->dcb.fParity)
751 switch (data->dcb.Parity) {
753 config->parity = SP_PARITY_NONE;
756 config->parity = SP_PARITY_EVEN;
759 config->parity = SP_PARITY_ODD;
765 config->parity = SP_PARITY_NONE;
767 switch (data->dcb.StopBits) {
769 config->stopbits = 1;
772 config->stopbits = 2;
775 config->stopbits = -1;
778 switch (data->dcb.fRtsControl) {
779 case RTS_CONTROL_DISABLE:
780 config->rts = SP_RTS_OFF;
782 case RTS_CONTROL_ENABLE:
783 config->rts = SP_RTS_ON;
785 case RTS_CONTROL_HANDSHAKE:
786 config->rts = SP_RTS_FLOW_CONTROL;
792 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
794 switch (data->dcb.fDtrControl) {
795 case DTR_CONTROL_DISABLE:
796 config->dtr = SP_DTR_OFF;
798 case DTR_CONTROL_ENABLE:
799 config->dtr = SP_DTR_ON;
801 case DTR_CONTROL_HANDSHAKE:
802 config->dtr = SP_DTR_FLOW_CONTROL;
808 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
810 if (data->dcb.fInX) {
812 config->xon_xoff = SP_XONXOFF_INOUT;
814 config->xon_xoff = SP_XONXOFF_IN;
817 config->xon_xoff = SP_XONXOFF_OUT;
819 config->xon_xoff = SP_XONXOFF_DISABLED;
824 if (tcgetattr(port->fd, &data->term) < 0)
827 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
831 int ret = get_flow(port->fd, &data->flow);
833 if (ret == SP_ERR_FAIL && errno == EINVAL)
834 data->termiox_supported = 0;
838 data->termiox_supported = 1;
840 data->termiox_supported = 0;
843 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
844 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
845 config->baudrate = std_baudrates[i].value;
850 if (i == NUM_STD_BAUDRATES) {
852 config->baudrate = (int)data->term.c_ispeed;
853 #elif defined(__linux__)
854 TRY(get_baudrate(port->fd, &config->baudrate));
856 config->baudrate = -1;
860 switch (data->term.c_cflag & CSIZE) {
877 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
878 config->parity = SP_PARITY_NONE;
879 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
882 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
884 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
886 if (data->term.c_cflag & CRTSCTS) {
887 config->rts = SP_RTS_FLOW_CONTROL;
888 config->cts = SP_CTS_FLOW_CONTROL;
890 if (data->termiox_supported && data->flow & RTS_FLOW)
891 config->rts = SP_RTS_FLOW_CONTROL;
893 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
895 config->cts = (data->termiox_supported && data->flow & CTS_FLOW) ?
896 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
899 if (data->termiox_supported && data->flow & DTR_FLOW)
900 config->dtr = SP_DTR_FLOW_CONTROL;
902 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
904 config->dsr = (data->termiox_supported && data->flow & DSR_FLOW) ?
905 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
907 if (data->term.c_iflag & IXOFF) {
908 if (data->term.c_iflag & IXON)
909 config->xon_xoff = SP_XONXOFF_INOUT;
911 config->xon_xoff = SP_XONXOFF_IN;
913 if (data->term.c_iflag & IXON)
914 config->xon_xoff = SP_XONXOFF_OUT;
916 config->xon_xoff = SP_XONXOFF_DISABLED;
923 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
924 const struct sp_port_config *config)
928 BAUD_TYPE baud_nonstd;
937 if (config->baudrate >= 0) {
938 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
939 if (config->baudrate == std_baudrates[i].value) {
940 data->dcb.BaudRate = std_baudrates[i].index;
945 if (i == NUM_STD_BAUDRATES)
946 data->dcb.BaudRate = config->baudrate;
949 if (config->bits >= 0)
950 data->dcb.ByteSize = config->bits;
952 if (config->parity >= 0) {
953 switch (config->parity) {
954 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
956 data->dcb.Parity = NOPARITY;
959 data->dcb.Parity = EVENPARITY;
962 data->dcb.Parity = ODDPARITY;
969 if (config->stopbits >= 0) {
970 switch (config->stopbits) {
971 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
973 data->dcb.StopBits = ONESTOPBIT;
976 data->dcb.StopBits = TWOSTOPBITS;
983 if (config->rts >= 0) {
984 switch (config->rts) {
986 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
989 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
991 case SP_RTS_FLOW_CONTROL:
992 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
999 if (config->cts >= 0) {
1000 switch (config->cts) {
1002 data->dcb.fOutxCtsFlow = FALSE;
1004 case SP_CTS_FLOW_CONTROL:
1005 data->dcb.fOutxCtsFlow = TRUE;
1012 if (config->dtr >= 0) {
1013 switch (config->dtr) {
1015 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1018 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1020 case SP_DTR_FLOW_CONTROL:
1021 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1028 if (config->dsr >= 0) {
1029 switch (config->dsr) {
1031 data->dcb.fOutxDsrFlow = FALSE;
1033 case SP_DSR_FLOW_CONTROL:
1034 data->dcb.fOutxDsrFlow = TRUE;
1041 if (config->xon_xoff >= 0) {
1042 switch (config->xon_xoff) {
1043 case SP_XONXOFF_DISABLED:
1044 data->dcb.fInX = FALSE;
1045 data->dcb.fOutX = FALSE;
1048 data->dcb.fInX = TRUE;
1049 data->dcb.fOutX = FALSE;
1051 case SP_XONXOFF_OUT:
1052 data->dcb.fInX = FALSE;
1053 data->dcb.fOutX = TRUE;
1055 case SP_XONXOFF_INOUT:
1056 data->dcb.fInX = TRUE;
1057 data->dcb.fOutX = TRUE;
1064 if (!SetCommState(port->hdl, &data->dcb))
1071 if (config->baudrate >= 0) {
1072 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1073 if (config->baudrate == std_baudrates[i].value) {
1074 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1077 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1083 /* Non-standard baud rate */
1084 if (i == NUM_STD_BAUDRATES) {
1086 /* Set "dummy" baud rate. */
1087 if (cfsetspeed(&data->term, B9600) < 0)
1089 baud_nonstd = config->baudrate;
1090 #elif defined(__linux__)
1098 if (config->bits >= 0) {
1099 data->term.c_cflag &= ~CSIZE;
1100 switch (config->bits) {
1102 data->term.c_cflag |= CS8;
1105 data->term.c_cflag |= CS7;
1108 data->term.c_cflag |= CS6;
1111 data->term.c_cflag |= CS5;
1118 if (config->parity >= 0) {
1119 data->term.c_iflag &= ~IGNPAR;
1120 data->term.c_cflag &= ~(PARENB | PARODD);
1121 switch (config->parity) {
1122 case SP_PARITY_NONE:
1123 data->term.c_iflag |= IGNPAR;
1125 case SP_PARITY_EVEN:
1126 data->term.c_cflag |= PARENB;
1129 data->term.c_cflag |= PARENB | PARODD;
1136 if (config->stopbits >= 0) {
1137 data->term.c_cflag &= ~CSTOPB;
1138 switch (config->stopbits) {
1140 data->term.c_cflag &= ~CSTOPB;
1143 data->term.c_cflag |= CSTOPB;
1150 if (config->rts >= 0 || config->cts >= 0) {
1151 if (data->termiox_supported) {
1152 data->flow &= ~(RTS_FLOW | CTS_FLOW);
1153 switch (config->rts) {
1156 controlbits = TIOCM_RTS;
1157 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1160 case SP_RTS_FLOW_CONTROL:
1161 data->flow |= RTS_FLOW;
1166 if (config->cts == SP_CTS_FLOW_CONTROL)
1167 data->flow |= CTS_FLOW;
1169 if (data->flow & (RTS_FLOW | CTS_FLOW))
1170 data->term.c_iflag |= CRTSCTS;
1172 data->term.c_iflag &= ~CRTSCTS;
1174 /* Asymmetric use of RTS/CTS not supported. */
1175 if (data->term.c_iflag & CRTSCTS) {
1176 /* Flow control can only be disabled for both RTS & CTS together. */
1177 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1178 if (config->cts != SP_CTS_IGNORE)
1181 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1182 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1186 /* Flow control can only be enabled for both RTS & CTS together. */
1187 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1188 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1192 if (config->rts >= 0) {
1193 if (config->rts == SP_RTS_FLOW_CONTROL) {
1194 data->term.c_iflag |= CRTSCTS;
1196 controlbits = TIOCM_RTS;
1197 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1205 if (config->dtr >= 0 || config->dsr >= 0) {
1206 if (data->termiox_supported) {
1207 data->flow &= ~(DTR_FLOW | DSR_FLOW);
1208 switch (config->dtr) {
1211 controlbits = TIOCM_DTR;
1212 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1215 case SP_DTR_FLOW_CONTROL:
1216 data->flow |= DTR_FLOW;
1221 if (config->dsr == SP_DSR_FLOW_CONTROL)
1222 data->flow |= DSR_FLOW;
1224 /* DTR/DSR flow control not supported. */
1225 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1228 if (config->dtr >= 0) {
1229 controlbits = TIOCM_DTR;
1230 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1237 if (config->xon_xoff >= 0) {
1238 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1239 switch (config->xon_xoff) {
1240 case SP_XONXOFF_DISABLED:
1243 data->term.c_iflag |= IXOFF;
1245 case SP_XONXOFF_OUT:
1246 data->term.c_iflag |= IXON | IXANY;
1248 case SP_XONXOFF_INOUT:
1249 data->term.c_iflag |= IXON | IXOFF | IXANY;
1256 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
1260 if (baud_nonstd != B0) {
1261 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1263 /* Set baud rates in data->term to correct, but incompatible
1264 * with tcsetattr() value, same as delivered by tcgetattr(). */
1265 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1268 #elif defined(__linux__)
1270 TRY(set_baudrate(port->fd, config->baudrate));
1272 if (data->termiox_supported)
1273 TRY(set_flow(port->fd, data->flow));
1277 #endif /* !_WIN32 */
1282 enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
1284 struct port_data data;
1285 struct sp_port_config prev_config;
1292 TRY(get_config(port, &data, &prev_config));
1293 TRY(set_config(port, &data, config));
1298 #define CREATE_SETTER(x, type) int sp_set_##x(struct sp_port *port, type x) { \
1299 struct port_data data; \
1300 struct sp_port_config config; \
1302 TRY(get_config(port, &data, &config)); \
1304 TRY(set_config(port, &data, &config)); \
1308 CREATE_SETTER(baudrate, int)
1309 CREATE_SETTER(bits, int)
1310 CREATE_SETTER(parity, enum sp_parity)
1311 CREATE_SETTER(stopbits, int)
1312 CREATE_SETTER(rts, enum sp_rts)
1313 CREATE_SETTER(cts, enum sp_cts)
1314 CREATE_SETTER(dtr, enum sp_dtr)
1315 CREATE_SETTER(dsr, enum sp_dsr)
1316 CREATE_SETTER(xon_xoff, enum sp_xonxoff)
1318 enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
1320 struct port_data data;
1321 struct sp_port_config config;
1325 TRY(get_config(port, &data, &config));
1327 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
1328 config.xon_xoff = SP_XONXOFF_INOUT;
1330 config.xon_xoff = SP_XONXOFF_DISABLED;
1332 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
1333 config.rts = SP_RTS_FLOW_CONTROL;
1334 config.cts = SP_CTS_FLOW_CONTROL;
1336 if (config.rts == SP_RTS_FLOW_CONTROL)
1337 config.rts = SP_RTS_ON;
1338 config.cts = SP_CTS_IGNORE;
1341 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
1342 config.dtr = SP_DTR_FLOW_CONTROL;
1343 config.dsr = SP_DSR_FLOW_CONTROL;
1345 if (config.dtr == SP_DTR_FLOW_CONTROL)
1346 config.dtr = SP_DTR_ON;
1347 config.dsr = SP_DSR_IGNORE;
1350 TRY(set_config(port, &data, &config));
1355 enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
1365 if (GetCommModemStatus(port->hdl, &bits) == 0)
1367 if (bits & MS_CTS_ON)
1368 *signals |= SP_SIG_CTS;
1369 if (bits & MS_DSR_ON)
1370 *signals |= SP_SIG_DSR;
1371 if (bits & MS_RING_ON)
1372 *signals |= SP_SIG_DCD;
1373 if (bits & MS_RLSD_ON)
1374 *signals |= SP_SIG_RI;
1377 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
1379 if (bits & TIOCM_CTS)
1380 *signals |= SP_SIG_CTS;
1381 if (bits & TIOCM_DSR)
1382 *signals |= SP_SIG_DSR;
1383 if (bits & TIOCM_CAR)
1384 *signals |= SP_SIG_DCD;
1385 if (bits & TIOCM_RNG)
1386 *signals |= SP_SIG_RI;
1391 enum sp_return sp_start_break(struct sp_port *port)
1395 if (SetCommBreak(port->hdl) == 0)
1398 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
1405 enum sp_return sp_end_break(struct sp_port *port)
1409 if (ClearCommBreak(port->hdl) == 0)
1412 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
1419 int sp_last_error_code(void)
1422 return GetLastError();
1428 char *sp_last_error_message(void)
1432 DWORD error = GetLastError();
1435 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1436 FORMAT_MESSAGE_FROM_SYSTEM |
1437 FORMAT_MESSAGE_IGNORE_INSERTS,
1440 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1446 return strerror(errno);
1450 void sp_free_error_message(char *message)
1459 void sp_set_debug_handler(void (*handler)(const char *format, ...))
1461 sp_debug_handler = handler;
1464 void sp_default_debug_handler(const char *format, ...)
1467 va_start(args, format);
1468 if (getenv("LIBSERIALPORT_DEBUG")) {
1469 fputs("libserialport: ", stderr);
1470 vfprintf(stderr, format, args);