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 struct sp_port **list_append(struct sp_port **list, const char *portname);
142 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
143 struct sp_port_config *config);
144 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
145 const struct sp_port_config *config);
147 enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
149 struct sp_port *port;
152 TRACE("%s, %p", portname, port_ptr);
155 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
160 RETURN_ERROR(SP_ERR_ARG, "Null port name");
162 DEBUG("Building structure for port %s", portname);
164 if (!(port = malloc(sizeof(struct sp_port))))
165 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
167 len = strlen(portname) + 1;
169 if (!(port->name = malloc(len))) {
171 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
174 memcpy(port->name, portname, len);
177 port->hdl = INVALID_HANDLE_VALUE;
187 enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
189 TRACE("%p, %p", port, copy_ptr);
192 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
197 RETURN_ERROR(SP_ERR_ARG, "Null port");
200 RETURN_ERROR(SP_ERR_ARG, "Null port name");
202 DEBUG("Copying port structure");
204 RETURN_VALUE("%p", sp_get_port_by_name(port->name, copy_ptr));
207 void sp_free_port(struct sp_port *port)
217 DEBUG("Freeing port structure");
227 static struct sp_port **list_append(struct sp_port **list, const char *portname)
232 for (count = 0; list[count]; count++);
233 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
236 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
238 list[count + 1] = NULL;
242 sp_free_port_list(list);
246 enum sp_return sp_list_ports(struct sp_port ***list_ptr)
248 struct sp_port **list;
251 TRACE("%p", list_ptr);
253 DEBUG("Enumerating ports");
255 if (!(list = malloc(sizeof(struct sp_port **))))
256 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
263 DWORD max_value_len, max_data_size, max_data_len;
264 DWORD value_len, data_size, data_len;
265 DWORD type, index = 0;
269 DEBUG("Opening registry key");
270 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
271 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
272 SET_FAIL(ret, "RegOpenKeyEx() failed");
275 DEBUG("Querying registry key value and data sizes");
276 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
277 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
278 SET_FAIL(ret, "RegQueryInfoKey() failed");
281 max_data_len = max_data_size / sizeof(TCHAR);
282 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
283 SET_ERROR(ret, SP_ERR_MEM, "registry value malloc failed");
286 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
287 SET_ERROR(ret, SP_ERR_MEM, "registry data malloc failed");
290 DEBUG("Iterating over values");
292 value_len = max_value_len + 1,
293 data_size = max_data_size,
294 RegEnumValue(key, index, value, &value_len,
295 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
297 data_len = data_size / sizeof(TCHAR);
298 data[data_len] = '\0';
300 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
302 name_len = data_len + 1;
304 if (!(name = malloc(name_len))) {
305 SET_ERROR(ret, SP_ERR_MEM, "registry port name malloc failed");
309 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
313 if (type == REG_SZ) {
314 DEBUG("Found port %s", name);
315 if (!(list = list_append(list, name))) {
316 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
332 CFMutableDictionaryRef classes;
339 DEBUG("Getting IOKit master port");
340 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS) {
341 SET_FAIL(ret, "IOMasterPort() failed");
345 DEBUG("Creating matching dictionary");
346 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) {
347 SET_FAIL(ret, "IOServiceMatching() failed");
351 CFDictionarySetValue(classes,
352 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
354 DEBUG("Getting matching services");
355 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS) {
356 SET_FAIL(ret, "IOServiceGetMatchingServices() failed");
360 if (!(path = malloc(PATH_MAX))) {
361 SET_ERROR(ret, SP_ERR_MEM, "device path malloc failed");
365 DEBUG("Iterating over results");
366 while ((port = IOIteratorNext(iter))) {
367 cf_path = IORegistryEntryCreateCFProperty(port,
368 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
370 result = CFStringGetCString(cf_path,
371 path, PATH_MAX, kCFStringEncodingASCII);
374 DEBUG("Found port %s", path);
375 if (!(list = list_append(list, path))) {
376 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
377 IOObjectRelease(port);
382 IOObjectRelease(port);
387 IOObjectRelease(iter);
392 struct udev_enumerate *ud_enumerate;
393 struct udev_list_entry *ud_list;
394 struct udev_list_entry *ud_entry;
396 struct udev_device *ud_dev, *ud_parent;
399 int fd, ioctl_result;
400 struct serial_struct serial_info;
402 DEBUG("Enumerating tty devices");
404 ud_enumerate = udev_enumerate_new(ud);
405 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
406 udev_enumerate_scan_devices(ud_enumerate);
407 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
408 DEBUG("Iterating over results");
409 udev_list_entry_foreach(ud_entry, ud_list) {
410 path = udev_list_entry_get_name(ud_entry);
411 DEBUG("Found device %s", path);
412 ud_dev = udev_device_new_from_syspath(ud, path);
413 /* If there is no parent device, this is a virtual tty. */
414 ud_parent = udev_device_get_parent(ud_dev);
415 if (ud_parent == NULL) {
416 DEBUG("No parent device, assuming virtual tty");
417 udev_device_unref(ud_dev);
420 name = udev_device_get_devnode(ud_dev);
421 /* The serial8250 driver has a hardcoded number of ports.
422 * The only way to tell which actually exist on a given system
423 * is to try to open them and make an ioctl call. */
424 driver = udev_device_get_driver(ud_parent);
425 if (driver && !strcmp(driver, "serial8250")) {
426 DEBUG("serial8250 device, attempting to open");
427 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0) {
428 DEBUG("open failed, skipping");
431 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
433 if (ioctl_result != 0) {
434 DEBUG("ioctl failed, skipping");
437 if (serial_info.type == PORT_UNKNOWN) {
438 DEBUG("port type is unknown, skipping");
442 DEBUG("Found port %s", name);
443 list = list_append(list, name);
445 udev_device_unref(ud_dev);
447 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
452 udev_enumerate_unref(ud_enumerate);
461 sp_free_port_list(list);
467 void sp_free_port_list(struct sp_port **list)
473 DEBUG("Freeing port list");
475 for (i = 0; list[i]; i++)
476 sp_free_port(list[i]);
483 #define CHECK_PORT() do { \
485 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
486 if (port->hdl == INVALID_HANDLE_VALUE) \
487 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
490 #define CHECK_PORT() do { \
492 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
494 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
498 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
500 TRACE("%p, %x", port, flags);
503 RETURN_ERROR(SP_ERR_ARG, "Null port");
505 DEBUG("Opening port %s", port->name);
508 DWORD desired_access = 0, flags_and_attributes = 0;
509 char *escaped_port_name;
511 /* Prefix port name with '\\.\' to work with ports above COM9. */
512 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
513 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
514 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
516 /* Map 'flags' to the OS-specific settings. */
517 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
518 if (flags & SP_MODE_READ)
519 desired_access |= GENERIC_READ;
520 if (flags & SP_MODE_WRITE)
521 desired_access |= GENERIC_WRITE;
522 if (flags & SP_MODE_NONBLOCK)
523 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
525 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
526 OPEN_EXISTING, flags_and_attributes, 0);
528 free(escaped_port_name);
530 if (port->hdl == INVALID_HANDLE_VALUE)
531 RETURN_FAIL("CreateFile() failed");
534 struct port_data data;
535 struct sp_port_config config;
538 /* Map 'flags' to the OS-specific settings. */
539 if (flags & (SP_MODE_READ | SP_MODE_WRITE))
540 flags_local |= O_RDWR;
541 else if (flags & SP_MODE_READ)
542 flags_local |= O_RDONLY;
543 else if (flags & SP_MODE_WRITE)
544 flags_local |= O_WRONLY;
545 if (flags & SP_MODE_NONBLOCK)
546 flags_local |= O_NONBLOCK;
548 if ((port->fd = open(port->name, flags_local)) < 0)
549 RETURN_FAIL("open() failed");
551 ret = get_config(port, &data, &config);
558 /* Turn off all serial port cooking. */
559 data.term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
560 data.term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
561 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
562 data.term.c_oflag &= ~OFILL;
564 /* Disable canonical mode, and don't echo input characters. */
565 data.term.c_lflag &= ~(ICANON | ECHO);
567 /* Ignore modem status lines; enable receiver */
568 data.term.c_cflag |= (CLOCAL | CREAD);
570 ret = set_config(port, &data, &config);
581 enum sp_return sp_close(struct sp_port *port)
587 DEBUG("Closing port %s", port->name);
590 /* Returns non-zero upon success, 0 upon failure. */
591 if (CloseHandle(port->hdl) == 0)
592 RETURN_FAIL("CloseHandle() failed");
593 port->hdl = INVALID_HANDLE_VALUE;
595 /* Returns 0 upon success, -1 upon failure. */
596 if (close(port->fd) == -1)
597 RETURN_FAIL("close() failed");
604 enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
606 TRACE("%p, %x", port, buffers);
610 const char *buffer_names[] = {"input", "output", "both"};
612 DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
616 if (buffers & SP_BUF_INPUT)
617 flags |= PURGE_RXCLEAR;
618 if (buffers & SP_BUF_OUTPUT)
619 flags |= PURGE_TXCLEAR;
621 /* Returns non-zero upon success, 0 upon failure. */
622 if (PurgeComm(port->hdl, flags) == 0)
623 RETURN_FAIL("PurgeComm() failed");
626 if (buffers & SP_BUF_BOTH)
628 else if (buffers & SP_BUF_INPUT)
630 else if (buffers & SP_BUF_OUTPUT)
633 /* Returns 0 upon success, -1 upon failure. */
634 if (tcflush(port->fd, flags) < 0)
635 RETURN_FAIL("tcflush() failed");
640 enum sp_return sp_drain(struct sp_port *port)
646 DEBUG("Draining port %s", port->name);
649 /* Returns non-zero upon success, 0 upon failure. */
650 if (FlushFileBuffers(port->hdl) == 0)
651 RETURN_FAIL("FlushFileBuffers() failed");
653 /* Returns 0 upon success, -1 upon failure. */
654 if (tcdrain(port->fd) < 0)
655 RETURN_FAIL("tcdrain() failed");
661 enum sp_return sp_write(struct sp_port *port, const void *buf, size_t count)
663 TRACE("%p, %p, %d", port, buf, count);
668 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
670 DEBUG("Writing up to %d bytes to port %s", count, port->name);
675 /* Returns non-zero upon success, 0 upon failure. */
676 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
677 RETURN_FAIL("WriteFile() failed");
678 RETURN_VALUE("%d", written);
680 /* Returns the number of bytes written, or -1 upon failure. */
681 ssize_t written = write(port->fd, buf, count);
684 RETURN_FAIL("write() failed");
686 RETURN_VALUE("%d", written);
690 enum sp_return sp_read(struct sp_port *port, void *buf, size_t count)
692 TRACE("%p, %p, %d", port, buf, count);
697 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
699 DEBUG("Reading up to %d bytes from port %s", count, port->name);
702 DWORD bytes_read = 0;
704 /* Returns non-zero upon success, 0 upon failure. */
705 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
706 RETURN_FAIL("ReadFile() failed");
707 RETURN_VALUE("%d", bytes_read);
711 /* Returns the number of bytes read, or -1 upon failure. */
712 if ((bytes_read = read(port->fd, buf, count)) < 0)
713 RETURN_FAIL("read() failed");
714 RETURN_VALUE("%d", bytes_read);
719 static enum sp_return get_baudrate(int fd, int *baudrate)
723 TRACE("%d, %p", fd, baudrate);
725 DEBUG("Getting baud rate");
727 if (!(data = malloc(get_termios_size())))
728 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
730 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
732 RETURN_FAIL("getting termios failed");
735 *baudrate = get_termios_speed(data);
742 static enum sp_return set_baudrate(int fd, int baudrate)
746 TRACE("%d, %d", fd, baudrate);
748 DEBUG("Getting baud rate");
750 if (!(data = malloc(get_termios_size())))
751 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
753 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
755 RETURN_FAIL("getting termios failed");
758 DEBUG("Setting baud rate");
760 set_termios_speed(data, baudrate);
762 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
764 RETURN_FAIL("setting termios failed");
773 static enum sp_return get_flow(int fd, int *flow)
777 TRACE("%d, %p", fd, flow);
779 DEBUG("Getting advanced flow control");
781 if (!(data = malloc(get_termiox_size())))
782 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
784 if (ioctl(fd, TCGETX, data) < 0) {
786 RETURN_FAIL("getting termiox failed");
789 *flow = get_termiox_flow(data);
796 static enum sp_return set_flow(int fd, int flow)
800 TRACE("%d, %d", fd, flow);
802 DEBUG("Getting advanced flow control");
804 if (!(data = malloc(get_termiox_size())))
805 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
807 if (ioctl(fd, TCGETX, data) < 0) {
809 RETURN_FAIL("getting termiox failed");
812 DEBUG("Setting advanced flow control");
814 set_termiox_flow(data, flow);
816 if (ioctl(fd, TCSETX, data) < 0) {
818 RETURN_FAIL("setting termiox failed");
825 #endif /* USE_TERMIOX */
826 #endif /* __linux__ */
828 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
829 struct sp_port_config *config)
833 TRACE("%p, %p, %p", port, data, config);
835 DEBUG("Getting configuration for port %s", port->name);
838 if (!GetCommState(port->hdl, &data->dcb))
839 RETURN_FAIL("GetCommState() failed");
841 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
842 if (data->dcb.BaudRate == std_baudrates[i].index) {
843 config->baudrate = std_baudrates[i].value;
848 if (i == NUM_STD_BAUDRATES)
849 /* BaudRate field can be either an index or a custom baud rate. */
850 config->baudrate = data->dcb.BaudRate;
852 config->bits = data->dcb.ByteSize;
854 if (data->dcb.fParity)
855 switch (data->dcb.Parity) {
857 config->parity = SP_PARITY_NONE;
860 config->parity = SP_PARITY_EVEN;
863 config->parity = SP_PARITY_ODD;
869 config->parity = SP_PARITY_NONE;
871 switch (data->dcb.StopBits) {
873 config->stopbits = 1;
876 config->stopbits = 2;
879 config->stopbits = -1;
882 switch (data->dcb.fRtsControl) {
883 case RTS_CONTROL_DISABLE:
884 config->rts = SP_RTS_OFF;
886 case RTS_CONTROL_ENABLE:
887 config->rts = SP_RTS_ON;
889 case RTS_CONTROL_HANDSHAKE:
890 config->rts = SP_RTS_FLOW_CONTROL;
896 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
898 switch (data->dcb.fDtrControl) {
899 case DTR_CONTROL_DISABLE:
900 config->dtr = SP_DTR_OFF;
902 case DTR_CONTROL_ENABLE:
903 config->dtr = SP_DTR_ON;
905 case DTR_CONTROL_HANDSHAKE:
906 config->dtr = SP_DTR_FLOW_CONTROL;
912 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
914 if (data->dcb.fInX) {
916 config->xon_xoff = SP_XONXOFF_INOUT;
918 config->xon_xoff = SP_XONXOFF_IN;
921 config->xon_xoff = SP_XONXOFF_OUT;
923 config->xon_xoff = SP_XONXOFF_DISABLED;
928 if (tcgetattr(port->fd, &data->term) < 0)
929 RETURN_FAIL("tcgetattr() failed");
931 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
932 RETURN_FAIL("TIOCMGET ioctl failed");
935 int ret = get_flow(port->fd, &data->flow);
937 if (ret == SP_ERR_FAIL && errno == EINVAL)
938 data->termiox_supported = 0;
942 data->termiox_supported = 1;
944 data->termiox_supported = 0;
947 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
948 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
949 config->baudrate = std_baudrates[i].value;
954 if (i == NUM_STD_BAUDRATES) {
956 config->baudrate = (int)data->term.c_ispeed;
957 #elif defined(__linux__)
958 TRY(get_baudrate(port->fd, &config->baudrate));
960 config->baudrate = -1;
964 switch (data->term.c_cflag & CSIZE) {
981 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
982 config->parity = SP_PARITY_NONE;
983 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
986 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
988 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
990 if (data->term.c_cflag & CRTSCTS) {
991 config->rts = SP_RTS_FLOW_CONTROL;
992 config->cts = SP_CTS_FLOW_CONTROL;
994 if (data->termiox_supported && data->flow & RTS_FLOW)
995 config->rts = SP_RTS_FLOW_CONTROL;
997 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
999 config->cts = (data->termiox_supported && data->flow & CTS_FLOW) ?
1000 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1003 if (data->termiox_supported && data->flow & DTR_FLOW)
1004 config->dtr = SP_DTR_FLOW_CONTROL;
1006 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1008 config->dsr = (data->termiox_supported && data->flow & DSR_FLOW) ?
1009 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1011 if (data->term.c_iflag & IXOFF) {
1012 if (data->term.c_iflag & IXON)
1013 config->xon_xoff = SP_XONXOFF_INOUT;
1015 config->xon_xoff = SP_XONXOFF_IN;
1017 if (data->term.c_iflag & IXON)
1018 config->xon_xoff = SP_XONXOFF_OUT;
1020 config->xon_xoff = SP_XONXOFF_DISABLED;
1027 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1028 const struct sp_port_config *config)
1032 BAUD_TYPE baud_nonstd;
1037 int baud_nonstd = 0;
1040 TRACE("%p, %p, %p", port, data, config);
1042 DEBUG("Setting configuration for port %s", port->name);
1045 if (config->baudrate >= 0) {
1046 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1047 if (config->baudrate == std_baudrates[i].value) {
1048 data->dcb.BaudRate = std_baudrates[i].index;
1053 if (i == NUM_STD_BAUDRATES)
1054 data->dcb.BaudRate = config->baudrate;
1057 if (config->bits >= 0)
1058 data->dcb.ByteSize = config->bits;
1060 if (config->parity >= 0) {
1061 switch (config->parity) {
1062 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
1063 case SP_PARITY_NONE:
1064 data->dcb.Parity = NOPARITY;
1066 case SP_PARITY_EVEN:
1067 data->dcb.Parity = EVENPARITY;
1070 data->dcb.Parity = ODDPARITY;
1073 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1077 if (config->stopbits >= 0) {
1078 switch (config->stopbits) {
1079 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1081 data->dcb.StopBits = ONESTOPBIT;
1084 data->dcb.StopBits = TWOSTOPBITS;
1087 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1091 if (config->rts >= 0) {
1092 switch (config->rts) {
1094 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1097 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1099 case SP_RTS_FLOW_CONTROL:
1100 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1103 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1107 if (config->cts >= 0) {
1108 switch (config->cts) {
1110 data->dcb.fOutxCtsFlow = FALSE;
1112 case SP_CTS_FLOW_CONTROL:
1113 data->dcb.fOutxCtsFlow = TRUE;
1116 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1120 if (config->dtr >= 0) {
1121 switch (config->dtr) {
1123 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1126 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1128 case SP_DTR_FLOW_CONTROL:
1129 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1132 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1136 if (config->dsr >= 0) {
1137 switch (config->dsr) {
1139 data->dcb.fOutxDsrFlow = FALSE;
1141 case SP_DSR_FLOW_CONTROL:
1142 data->dcb.fOutxDsrFlow = TRUE;
1145 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1149 if (config->xon_xoff >= 0) {
1150 switch (config->xon_xoff) {
1151 case SP_XONXOFF_DISABLED:
1152 data->dcb.fInX = FALSE;
1153 data->dcb.fOutX = FALSE;
1156 data->dcb.fInX = TRUE;
1157 data->dcb.fOutX = FALSE;
1159 case SP_XONXOFF_OUT:
1160 data->dcb.fInX = FALSE;
1161 data->dcb.fOutX = TRUE;
1163 case SP_XONXOFF_INOUT:
1164 data->dcb.fInX = TRUE;
1165 data->dcb.fOutX = TRUE;
1168 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1172 if (!SetCommState(port->hdl, &data->dcb))
1173 RETURN_FAIL("SetCommState() failed");
1179 if (config->baudrate >= 0) {
1180 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1181 if (config->baudrate == std_baudrates[i].value) {
1182 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1183 RETURN_FAIL("cfsetospeed() failed");
1185 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1186 RETURN_FAIL("cfsetispeed() failed");
1191 /* Non-standard baud rate */
1192 if (i == NUM_STD_BAUDRATES) {
1194 /* Set "dummy" baud rate. */
1195 if (cfsetspeed(&data->term, B9600) < 0)
1196 RETURN_FAIL("cfsetspeed() failed");
1197 baud_nonstd = config->baudrate;
1198 #elif defined(__linux__)
1201 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1206 if (config->bits >= 0) {
1207 data->term.c_cflag &= ~CSIZE;
1208 switch (config->bits) {
1210 data->term.c_cflag |= CS8;
1213 data->term.c_cflag |= CS7;
1216 data->term.c_cflag |= CS6;
1219 data->term.c_cflag |= CS5;
1222 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1226 if (config->parity >= 0) {
1227 data->term.c_iflag &= ~IGNPAR;
1228 data->term.c_cflag &= ~(PARENB | PARODD);
1229 switch (config->parity) {
1230 case SP_PARITY_NONE:
1231 data->term.c_iflag |= IGNPAR;
1233 case SP_PARITY_EVEN:
1234 data->term.c_cflag |= PARENB;
1237 data->term.c_cflag |= PARENB | PARODD;
1240 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1244 if (config->stopbits >= 0) {
1245 data->term.c_cflag &= ~CSTOPB;
1246 switch (config->stopbits) {
1248 data->term.c_cflag &= ~CSTOPB;
1251 data->term.c_cflag |= CSTOPB;
1254 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1258 if (config->rts >= 0 || config->cts >= 0) {
1259 if (data->termiox_supported) {
1260 data->flow &= ~(RTS_FLOW | CTS_FLOW);
1261 switch (config->rts) {
1264 controlbits = TIOCM_RTS;
1265 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1266 RETURN_FAIL("Setting RTS signal level failed");
1268 case SP_RTS_FLOW_CONTROL:
1269 data->flow |= RTS_FLOW;
1274 if (config->cts == SP_CTS_FLOW_CONTROL)
1275 data->flow |= CTS_FLOW;
1277 if (data->flow & (RTS_FLOW | CTS_FLOW))
1278 data->term.c_iflag |= CRTSCTS;
1280 data->term.c_iflag &= ~CRTSCTS;
1282 /* Asymmetric use of RTS/CTS not supported. */
1283 if (data->term.c_iflag & CRTSCTS) {
1284 /* Flow control can only be disabled for both RTS & CTS together. */
1285 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1286 if (config->cts != SP_CTS_IGNORE)
1287 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1289 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1290 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1291 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1294 /* Flow control can only be enabled for both RTS & CTS together. */
1295 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1296 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1297 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1300 if (config->rts >= 0) {
1301 if (config->rts == SP_RTS_FLOW_CONTROL) {
1302 data->term.c_iflag |= CRTSCTS;
1304 controlbits = TIOCM_RTS;
1305 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1307 RETURN_FAIL("Setting RTS signal level failed");
1313 if (config->dtr >= 0 || config->dsr >= 0) {
1314 if (data->termiox_supported) {
1315 data->flow &= ~(DTR_FLOW | DSR_FLOW);
1316 switch (config->dtr) {
1319 controlbits = TIOCM_DTR;
1320 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1321 RETURN_FAIL("Setting DTR signal level failed");
1323 case SP_DTR_FLOW_CONTROL:
1324 data->flow |= DTR_FLOW;
1329 if (config->dsr == SP_DSR_FLOW_CONTROL)
1330 data->flow |= DSR_FLOW;
1332 /* DTR/DSR flow control not supported. */
1333 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1334 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1336 if (config->dtr >= 0) {
1337 controlbits = TIOCM_DTR;
1338 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1340 RETURN_FAIL("Setting DTR signal level failed");
1345 if (config->xon_xoff >= 0) {
1346 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1347 switch (config->xon_xoff) {
1348 case SP_XONXOFF_DISABLED:
1351 data->term.c_iflag |= IXOFF;
1353 case SP_XONXOFF_OUT:
1354 data->term.c_iflag |= IXON | IXANY;
1356 case SP_XONXOFF_INOUT:
1357 data->term.c_iflag |= IXON | IXOFF | IXANY;
1360 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1364 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
1365 RETURN_FAIL("tcsetattr() failed");
1368 if (baud_nonstd != B0) {
1369 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1370 RETURN_FAIL("IOSSIOSPEED ioctl failed");
1371 /* Set baud rates in data->term to correct, but incompatible
1372 * with tcsetattr() value, same as delivered by tcgetattr(). */
1373 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1374 RETURN_FAIL("cfsetspeed() failed");
1376 #elif defined(__linux__)
1378 TRY(set_baudrate(port->fd, config->baudrate));
1380 if (data->termiox_supported)
1381 TRY(set_flow(port->fd, data->flow));
1385 #endif /* !_WIN32 */
1390 enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
1392 struct port_data data;
1393 struct sp_port_config prev_config;
1395 TRACE("%p, %p", port, config);
1400 RETURN_ERROR(SP_ERR_ARG, "Null config");
1402 TRY(get_config(port, &data, &prev_config));
1403 TRY(set_config(port, &data, config));
1408 #define CREATE_SETTER(x, type) int sp_set_##x(struct sp_port *port, type x) { \
1409 struct port_data data; \
1410 struct sp_port_config config; \
1411 TRACE("%p, %d", port, x); \
1413 TRY(get_config(port, &data, &config)); \
1415 TRY(set_config(port, &data, &config)); \
1419 CREATE_SETTER(baudrate, int)
1420 CREATE_SETTER(bits, int)
1421 CREATE_SETTER(parity, enum sp_parity)
1422 CREATE_SETTER(stopbits, int)
1423 CREATE_SETTER(rts, enum sp_rts)
1424 CREATE_SETTER(cts, enum sp_cts)
1425 CREATE_SETTER(dtr, enum sp_dtr)
1426 CREATE_SETTER(dsr, enum sp_dsr)
1427 CREATE_SETTER(xon_xoff, enum sp_xonxoff)
1429 enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
1431 struct port_data data;
1432 struct sp_port_config config;
1434 TRACE("%p, %d", port, flowcontrol);
1438 TRY(get_config(port, &data, &config));
1440 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
1441 config.xon_xoff = SP_XONXOFF_INOUT;
1443 config.xon_xoff = SP_XONXOFF_DISABLED;
1445 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
1446 config.rts = SP_RTS_FLOW_CONTROL;
1447 config.cts = SP_CTS_FLOW_CONTROL;
1449 if (config.rts == SP_RTS_FLOW_CONTROL)
1450 config.rts = SP_RTS_ON;
1451 config.cts = SP_CTS_IGNORE;
1454 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
1455 config.dtr = SP_DTR_FLOW_CONTROL;
1456 config.dsr = SP_DSR_FLOW_CONTROL;
1458 if (config.dtr == SP_DTR_FLOW_CONTROL)
1459 config.dtr = SP_DTR_ON;
1460 config.dsr = SP_DSR_IGNORE;
1463 TRY(set_config(port, &data, &config));
1468 enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
1470 TRACE("%p, %p", port, signals);
1475 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1477 DEBUG("Getting control signals for port %s", port->name);
1482 if (GetCommModemStatus(port->hdl, &bits) == 0)
1483 RETURN_FAIL("GetCommModemStatus() failed");
1484 if (bits & MS_CTS_ON)
1485 *signals |= SP_SIG_CTS;
1486 if (bits & MS_DSR_ON)
1487 *signals |= SP_SIG_DSR;
1488 if (bits & MS_RING_ON)
1489 *signals |= SP_SIG_DCD;
1490 if (bits & MS_RLSD_ON)
1491 *signals |= SP_SIG_RI;
1494 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
1495 RETURN_FAIL("TIOCMGET ioctl failed");
1496 if (bits & TIOCM_CTS)
1497 *signals |= SP_SIG_CTS;
1498 if (bits & TIOCM_DSR)
1499 *signals |= SP_SIG_DSR;
1500 if (bits & TIOCM_CAR)
1501 *signals |= SP_SIG_DCD;
1502 if (bits & TIOCM_RNG)
1503 *signals |= SP_SIG_RI;
1508 enum sp_return sp_start_break(struct sp_port *port)
1514 if (SetCommBreak(port->hdl) == 0)
1515 RETURN_FAIL("SetCommBreak() failed");
1517 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
1518 RETURN_FAIL("TIOCSBRK ioctl failed");
1524 enum sp_return sp_end_break(struct sp_port *port)
1530 if (ClearCommBreak(port->hdl) == 0)
1531 RETURN_FAIL("ClearCommBreak() failed");
1533 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
1534 RETURN_FAIL("TIOCCBRK ioctl failed");
1540 int sp_last_error_code(void)
1544 RETURN_VALUE("%d", GetLastError());
1546 RETURN_VALUE("%d", errno);
1550 char *sp_last_error_message(void)
1556 DWORD error = GetLastError();
1559 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1560 FORMAT_MESSAGE_FROM_SYSTEM |
1561 FORMAT_MESSAGE_IGNORE_INSERTS,
1564 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1568 RETURN_VALUE("%s", message);
1570 RETURN_VALUE("%s", strerror(errno));
1574 void sp_free_error_message(char *message)
1576 TRACE("%s", message);
1587 void sp_set_debug_handler(void (*handler)(const char *format, ...))
1589 TRACE("%p", handler);
1591 sp_debug_handler = handler;
1596 void sp_default_debug_handler(const char *format, ...)
1599 va_start(args, format);
1600 if (getenv("LIBSERIALPORT_DEBUG")) {
1601 fputs("libserialport: ", stderr);
1602 vfprintf(stderr, format, args);