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 /* Debug output macros. */
112 #define DEBUG(fmt, ...) do { if (sp_debug_handler) sp_debug_handler(fmt ".\n", ##__VA_ARGS__); } while (0)
113 #define DEBUG_ERROR(err, msg) DEBUG("%s returning " #err ": " msg, __func__)
114 #define DEBUG_FAIL(msg) do { \
115 char *errmsg = sp_last_error_message(); \
116 DEBUG("%s returning SP_ERR_FAIL: " msg ": %s", __func__, errmsg); \
117 sp_free_error_message(errmsg); \
119 #define RETURN() do { DEBUG("%s returning", __func__); return; } while(0)
120 #define RETURN_CODE(x) do { DEBUG("%s returning " #x, __func__); return x; } while (0)
121 #define RETURN_CODEVAL(x) do { \
123 case SP_OK: RETURN_CODE(SP_OK); \
124 case SP_ERR_ARG: RETURN_CODE(SP_ERR_ARG); \
125 case SP_ERR_FAIL: RETURN_CODE(SP_ERR_FAIL); \
126 case SP_ERR_MEM: RETURN_CODE(SP_ERR_MEM); \
127 case SP_ERR_SUPP: RETURN_CODE(SP_ERR_SUPP); \
130 #define RETURN_OK() RETURN_CODE(SP_OK);
131 #define RETURN_ERROR(err, msg) do { DEBUG_ERROR(err, msg); return err; } while (0)
132 #define RETURN_FAIL(msg) do { DEBUG_FAIL(msg); return SP_ERR_FAIL; } while (0)
133 #define RETURN_VALUE(fmt, x) do { DEBUG("%s returning " fmt, __func__, x); return x; } while (0)
134 #define SET_ERROR(val, err, msg) do { DEBUG_ERROR(err, msg); val = err; } while (0)
135 #define SET_FAIL(val, msg) do { DEBUG_FAIL(msg); val = err; } while (0)
136 #define TRACE(fmt, ...) DEBUG("%s(" fmt ") called", __func__, ##__VA_ARGS__)
138 #define TRY(x) do { int ret = x; if (ret != SP_OK) RETURN_CODEVAL(ret); } while (0)
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;
249 int ret = SP_ERR_SUPP;
251 TRACE("%p", list_ptr);
254 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
256 DEBUG("Enumerating ports");
258 if (!(list = malloc(sizeof(struct sp_port **))))
259 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
266 DWORD max_value_len, max_data_size, max_data_len;
267 DWORD value_len, data_size, data_len;
268 DWORD type, index = 0;
274 DEBUG("Opening registry key");
275 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
276 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
277 SET_FAIL(ret, "RegOpenKeyEx() failed");
280 DEBUG("Querying registry key value and data sizes");
281 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
282 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
283 SET_FAIL(ret, "RegQueryInfoKey() failed");
286 max_data_len = max_data_size / sizeof(TCHAR);
287 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
288 SET_ERROR(ret, SP_ERR_MEM, "registry value malloc failed");
291 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
292 SET_ERROR(ret, SP_ERR_MEM, "registry data malloc failed");
295 DEBUG("Iterating over values");
297 value_len = max_value_len + 1,
298 data_size = max_data_size,
299 RegEnumValue(key, index, value, &value_len,
300 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
302 data_len = data_size / sizeof(TCHAR);
303 data[data_len] = '\0';
305 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
307 name_len = data_len + 1;
309 if (!(name = malloc(name_len))) {
310 SET_ERROR(ret, SP_ERR_MEM, "registry port name malloc failed");
314 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
318 if (type == REG_SZ) {
319 DEBUG("Found port %s", name);
320 if (!(list = list_append(list, name))) {
321 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
337 CFMutableDictionaryRef classes;
346 DEBUG("Getting IOKit master port");
347 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS) {
348 SET_FAIL(ret, "IOMasterPort() failed");
352 DEBUG("Creating matching dictionary");
353 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) {
354 SET_FAIL(ret, "IOServiceMatching() failed");
358 CFDictionarySetValue(classes,
359 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
361 DEBUG("Getting matching services");
362 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS) {
363 SET_FAIL(ret, "IOServiceGetMatchingServices() failed");
367 if (!(path = malloc(PATH_MAX))) {
368 SET_ERROR(ret, SP_ERR_MEM, "device path malloc failed");
372 DEBUG("Iterating over results");
373 while ((port = IOIteratorNext(iter))) {
374 cf_path = IORegistryEntryCreateCFProperty(port,
375 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
377 result = CFStringGetCString(cf_path,
378 path, PATH_MAX, kCFStringEncodingASCII);
381 DEBUG("Found port %s", path);
382 if (!(list = list_append(list, path))) {
383 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
384 IOObjectRelease(port);
389 IOObjectRelease(port);
394 IOObjectRelease(iter);
399 struct udev_enumerate *ud_enumerate;
400 struct udev_list_entry *ud_list;
401 struct udev_list_entry *ud_entry;
403 struct udev_device *ud_dev, *ud_parent;
406 int fd, ioctl_result;
407 struct serial_struct serial_info;
411 DEBUG("Enumerating tty devices");
413 ud_enumerate = udev_enumerate_new(ud);
414 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
415 udev_enumerate_scan_devices(ud_enumerate);
416 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
417 DEBUG("Iterating over results");
418 udev_list_entry_foreach(ud_entry, ud_list) {
419 path = udev_list_entry_get_name(ud_entry);
420 DEBUG("Found device %s", path);
421 ud_dev = udev_device_new_from_syspath(ud, path);
422 /* If there is no parent device, this is a virtual tty. */
423 ud_parent = udev_device_get_parent(ud_dev);
424 if (ud_parent == NULL) {
425 DEBUG("No parent device, assuming virtual tty");
426 udev_device_unref(ud_dev);
429 name = udev_device_get_devnode(ud_dev);
430 /* The serial8250 driver has a hardcoded number of ports.
431 * The only way to tell which actually exist on a given system
432 * is to try to open them and make an ioctl call. */
433 driver = udev_device_get_driver(ud_parent);
434 if (driver && !strcmp(driver, "serial8250")) {
435 DEBUG("serial8250 device, attempting to open");
436 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0) {
437 DEBUG("open failed, skipping");
440 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
442 if (ioctl_result != 0) {
443 DEBUG("ioctl failed, skipping");
446 if (serial_info.type == PORT_UNKNOWN) {
447 DEBUG("port type is unknown, skipping");
451 DEBUG("Found port %s", name);
452 list = list_append(list, name);
454 udev_device_unref(ud_dev);
456 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
461 udev_enumerate_unref(ud_enumerate);
470 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform.");
473 sp_free_port_list(list);
479 void sp_free_port_list(struct sp_port **list)
490 DEBUG("Freeing port list");
492 for (i = 0; list[i]; i++)
493 sp_free_port(list[i]);
499 #define CHECK_PORT() do { \
501 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
502 if (port->name == NULL) \
503 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
506 #define CHECK_PORT_HANDLE() do { \
507 if (port->hdl == INVALID_HANDLE_VALUE) \
508 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
511 #define CHECK_PORT_HANDLE() do { \
513 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
516 #define CHECK_OPEN_PORT() do { \
518 CHECK_PORT_HANDLE(); \
521 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
523 TRACE("%p, %x", port, flags);
527 if (flags > (SP_MODE_READ | SP_MODE_WRITE | SP_MODE_NONBLOCK))
528 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
530 DEBUG("Opening port %s", port->name);
533 DWORD desired_access = 0, flags_and_attributes = 0;
534 char *escaped_port_name;
536 /* Prefix port name with '\\.\' to work with ports above COM9. */
537 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
538 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
539 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
541 /* Map 'flags' to the OS-specific settings. */
542 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
543 if (flags & SP_MODE_READ)
544 desired_access |= GENERIC_READ;
545 if (flags & SP_MODE_WRITE)
546 desired_access |= GENERIC_WRITE;
547 if (flags & SP_MODE_NONBLOCK)
548 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
550 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
551 OPEN_EXISTING, flags_and_attributes, 0);
553 free(escaped_port_name);
555 if (port->hdl == INVALID_HANDLE_VALUE)
556 RETURN_FAIL("CreateFile() failed");
559 struct port_data data;
560 struct sp_port_config config;
563 /* Map 'flags' to the OS-specific settings. */
564 if (flags & (SP_MODE_READ | SP_MODE_WRITE))
565 flags_local |= O_RDWR;
566 else if (flags & SP_MODE_READ)
567 flags_local |= O_RDONLY;
568 else if (flags & SP_MODE_WRITE)
569 flags_local |= O_WRONLY;
570 if (flags & SP_MODE_NONBLOCK)
571 flags_local |= O_NONBLOCK;
573 if ((port->fd = open(port->name, flags_local)) < 0)
574 RETURN_FAIL("open() failed");
576 ret = get_config(port, &data, &config);
583 /* Turn off all serial port cooking. */
584 data.term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
585 data.term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
586 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
587 data.term.c_oflag &= ~OFILL;
589 /* Disable canonical mode, and don't echo input characters. */
590 data.term.c_lflag &= ~(ICANON | ECHO);
592 /* Ignore modem status lines; enable receiver */
593 data.term.c_cflag |= (CLOCAL | CREAD);
595 ret = set_config(port, &data, &config);
606 enum sp_return sp_close(struct sp_port *port)
612 DEBUG("Closing port %s", port->name);
615 /* Returns non-zero upon success, 0 upon failure. */
616 if (CloseHandle(port->hdl) == 0)
617 RETURN_FAIL("CloseHandle() failed");
618 port->hdl = INVALID_HANDLE_VALUE;
620 /* Returns 0 upon success, -1 upon failure. */
621 if (close(port->fd) == -1)
622 RETURN_FAIL("close() failed");
629 enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
631 TRACE("%p, %x", port, buffers);
635 if (buffers > SP_BUF_BOTH)
636 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
638 const char *buffer_names[] = {"input", "output", "both"};
640 DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
644 if (buffers & SP_BUF_INPUT)
645 flags |= PURGE_RXCLEAR;
646 if (buffers & SP_BUF_OUTPUT)
647 flags |= PURGE_TXCLEAR;
649 /* Returns non-zero upon success, 0 upon failure. */
650 if (PurgeComm(port->hdl, flags) == 0)
651 RETURN_FAIL("PurgeComm() failed");
654 if (buffers & SP_BUF_BOTH)
656 else if (buffers & SP_BUF_INPUT)
658 else if (buffers & SP_BUF_OUTPUT)
661 /* Returns 0 upon success, -1 upon failure. */
662 if (tcflush(port->fd, flags) < 0)
663 RETURN_FAIL("tcflush() failed");
668 enum sp_return sp_drain(struct sp_port *port)
674 DEBUG("Draining port %s", port->name);
677 /* Returns non-zero upon success, 0 upon failure. */
678 if (FlushFileBuffers(port->hdl) == 0)
679 RETURN_FAIL("FlushFileBuffers() failed");
681 /* Returns 0 upon success, -1 upon failure. */
682 if (tcdrain(port->fd) < 0)
683 RETURN_FAIL("tcdrain() failed");
689 enum sp_return sp_write(struct sp_port *port, const void *buf, size_t count)
691 TRACE("%p, %p, %d", port, buf, count);
696 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
698 DEBUG("Writing up to %d bytes to port %s", count, port->name);
703 /* Returns non-zero upon success, 0 upon failure. */
704 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
705 RETURN_FAIL("WriteFile() failed");
706 RETURN_VALUE("%d", written);
708 /* Returns the number of bytes written, or -1 upon failure. */
709 ssize_t written = write(port->fd, buf, count);
712 RETURN_FAIL("write() failed");
714 RETURN_VALUE("%d", written);
718 enum sp_return sp_read(struct sp_port *port, void *buf, size_t count)
720 TRACE("%p, %p, %d", port, buf, count);
725 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
727 DEBUG("Reading up to %d bytes from port %s", count, port->name);
730 DWORD bytes_read = 0;
732 /* Returns non-zero upon success, 0 upon failure. */
733 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
734 RETURN_FAIL("ReadFile() failed");
735 RETURN_VALUE("%d", bytes_read);
739 /* Returns the number of bytes read, or -1 upon failure. */
740 if ((bytes_read = read(port->fd, buf, count)) < 0)
741 RETURN_FAIL("read() failed");
742 RETURN_VALUE("%d", bytes_read);
747 static enum sp_return get_baudrate(int fd, int *baudrate)
751 TRACE("%d, %p", fd, baudrate);
753 DEBUG("Getting baud rate");
755 if (!(data = malloc(get_termios_size())))
756 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
758 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
760 RETURN_FAIL("getting termios failed");
763 *baudrate = get_termios_speed(data);
770 static enum sp_return set_baudrate(int fd, int baudrate)
774 TRACE("%d, %d", fd, baudrate);
776 DEBUG("Getting baud rate");
778 if (!(data = malloc(get_termios_size())))
779 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
781 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
783 RETURN_FAIL("getting termios failed");
786 DEBUG("Setting baud rate");
788 set_termios_speed(data, baudrate);
790 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
792 RETURN_FAIL("setting termios failed");
801 static enum sp_return get_flow(int fd, int *flow)
805 TRACE("%d, %p", fd, flow);
807 DEBUG("Getting advanced flow control");
809 if (!(data = malloc(get_termiox_size())))
810 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
812 if (ioctl(fd, TCGETX, data) < 0) {
814 RETURN_FAIL("getting termiox failed");
817 *flow = get_termiox_flow(data);
824 static enum sp_return set_flow(int fd, int flow)
828 TRACE("%d, %d", fd, flow);
830 DEBUG("Getting advanced flow control");
832 if (!(data = malloc(get_termiox_size())))
833 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
835 if (ioctl(fd, TCGETX, data) < 0) {
837 RETURN_FAIL("getting termiox failed");
840 DEBUG("Setting advanced flow control");
842 set_termiox_flow(data, flow);
844 if (ioctl(fd, TCSETX, data) < 0) {
846 RETURN_FAIL("setting termiox failed");
853 #endif /* USE_TERMIOX */
854 #endif /* __linux__ */
856 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
857 struct sp_port_config *config)
861 TRACE("%p, %p, %p", port, data, config);
863 DEBUG("Getting configuration for port %s", port->name);
866 if (!GetCommState(port->hdl, &data->dcb))
867 RETURN_FAIL("GetCommState() failed");
869 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
870 if (data->dcb.BaudRate == std_baudrates[i].index) {
871 config->baudrate = std_baudrates[i].value;
876 if (i == NUM_STD_BAUDRATES)
877 /* BaudRate field can be either an index or a custom baud rate. */
878 config->baudrate = data->dcb.BaudRate;
880 config->bits = data->dcb.ByteSize;
882 if (data->dcb.fParity)
883 switch (data->dcb.Parity) {
885 config->parity = SP_PARITY_NONE;
888 config->parity = SP_PARITY_EVEN;
891 config->parity = SP_PARITY_ODD;
897 config->parity = SP_PARITY_NONE;
899 switch (data->dcb.StopBits) {
901 config->stopbits = 1;
904 config->stopbits = 2;
907 config->stopbits = -1;
910 switch (data->dcb.fRtsControl) {
911 case RTS_CONTROL_DISABLE:
912 config->rts = SP_RTS_OFF;
914 case RTS_CONTROL_ENABLE:
915 config->rts = SP_RTS_ON;
917 case RTS_CONTROL_HANDSHAKE:
918 config->rts = SP_RTS_FLOW_CONTROL;
924 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
926 switch (data->dcb.fDtrControl) {
927 case DTR_CONTROL_DISABLE:
928 config->dtr = SP_DTR_OFF;
930 case DTR_CONTROL_ENABLE:
931 config->dtr = SP_DTR_ON;
933 case DTR_CONTROL_HANDSHAKE:
934 config->dtr = SP_DTR_FLOW_CONTROL;
940 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
942 if (data->dcb.fInX) {
944 config->xon_xoff = SP_XONXOFF_INOUT;
946 config->xon_xoff = SP_XONXOFF_IN;
949 config->xon_xoff = SP_XONXOFF_OUT;
951 config->xon_xoff = SP_XONXOFF_DISABLED;
956 if (tcgetattr(port->fd, &data->term) < 0)
957 RETURN_FAIL("tcgetattr() failed");
959 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
960 RETURN_FAIL("TIOCMGET ioctl failed");
963 int ret = get_flow(port->fd, &data->flow);
965 if (ret == SP_ERR_FAIL && errno == EINVAL)
966 data->termiox_supported = 0;
970 data->termiox_supported = 1;
972 data->termiox_supported = 0;
975 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
976 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
977 config->baudrate = std_baudrates[i].value;
982 if (i == NUM_STD_BAUDRATES) {
984 config->baudrate = (int)data->term.c_ispeed;
985 #elif defined(__linux__)
986 TRY(get_baudrate(port->fd, &config->baudrate));
988 config->baudrate = -1;
992 switch (data->term.c_cflag & CSIZE) {
1009 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1010 config->parity = SP_PARITY_NONE;
1011 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1012 config->parity = -1;
1014 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1016 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1018 if (data->term.c_cflag & CRTSCTS) {
1019 config->rts = SP_RTS_FLOW_CONTROL;
1020 config->cts = SP_CTS_FLOW_CONTROL;
1022 if (data->termiox_supported && data->flow & RTS_FLOW)
1023 config->rts = SP_RTS_FLOW_CONTROL;
1025 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1027 config->cts = (data->termiox_supported && data->flow & CTS_FLOW) ?
1028 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1031 if (data->termiox_supported && data->flow & DTR_FLOW)
1032 config->dtr = SP_DTR_FLOW_CONTROL;
1034 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1036 config->dsr = (data->termiox_supported && data->flow & DSR_FLOW) ?
1037 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1039 if (data->term.c_iflag & IXOFF) {
1040 if (data->term.c_iflag & IXON)
1041 config->xon_xoff = SP_XONXOFF_INOUT;
1043 config->xon_xoff = SP_XONXOFF_IN;
1045 if (data->term.c_iflag & IXON)
1046 config->xon_xoff = SP_XONXOFF_OUT;
1048 config->xon_xoff = SP_XONXOFF_DISABLED;
1055 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1056 const struct sp_port_config *config)
1060 BAUD_TYPE baud_nonstd;
1065 int baud_nonstd = 0;
1068 TRACE("%p, %p, %p", port, data, config);
1070 DEBUG("Setting configuration for port %s", port->name);
1073 if (config->baudrate >= 0) {
1074 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1075 if (config->baudrate == std_baudrates[i].value) {
1076 data->dcb.BaudRate = std_baudrates[i].index;
1081 if (i == NUM_STD_BAUDRATES)
1082 data->dcb.BaudRate = config->baudrate;
1085 if (config->bits >= 0)
1086 data->dcb.ByteSize = config->bits;
1088 if (config->parity >= 0) {
1089 switch (config->parity) {
1090 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
1091 case SP_PARITY_NONE:
1092 data->dcb.Parity = NOPARITY;
1094 case SP_PARITY_EVEN:
1095 data->dcb.Parity = EVENPARITY;
1098 data->dcb.Parity = ODDPARITY;
1101 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1105 if (config->stopbits >= 0) {
1106 switch (config->stopbits) {
1107 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1109 data->dcb.StopBits = ONESTOPBIT;
1112 data->dcb.StopBits = TWOSTOPBITS;
1115 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1119 if (config->rts >= 0) {
1120 switch (config->rts) {
1122 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1125 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1127 case SP_RTS_FLOW_CONTROL:
1128 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1131 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1135 if (config->cts >= 0) {
1136 switch (config->cts) {
1138 data->dcb.fOutxCtsFlow = FALSE;
1140 case SP_CTS_FLOW_CONTROL:
1141 data->dcb.fOutxCtsFlow = TRUE;
1144 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1148 if (config->dtr >= 0) {
1149 switch (config->dtr) {
1151 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1154 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1156 case SP_DTR_FLOW_CONTROL:
1157 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1160 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1164 if (config->dsr >= 0) {
1165 switch (config->dsr) {
1167 data->dcb.fOutxDsrFlow = FALSE;
1169 case SP_DSR_FLOW_CONTROL:
1170 data->dcb.fOutxDsrFlow = TRUE;
1173 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1177 if (config->xon_xoff >= 0) {
1178 switch (config->xon_xoff) {
1179 case SP_XONXOFF_DISABLED:
1180 data->dcb.fInX = FALSE;
1181 data->dcb.fOutX = FALSE;
1184 data->dcb.fInX = TRUE;
1185 data->dcb.fOutX = FALSE;
1187 case SP_XONXOFF_OUT:
1188 data->dcb.fInX = FALSE;
1189 data->dcb.fOutX = TRUE;
1191 case SP_XONXOFF_INOUT:
1192 data->dcb.fInX = TRUE;
1193 data->dcb.fOutX = TRUE;
1196 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1200 if (!SetCommState(port->hdl, &data->dcb))
1201 RETURN_FAIL("SetCommState() failed");
1207 if (config->baudrate >= 0) {
1208 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1209 if (config->baudrate == std_baudrates[i].value) {
1210 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1211 RETURN_FAIL("cfsetospeed() failed");
1213 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1214 RETURN_FAIL("cfsetispeed() failed");
1219 /* Non-standard baud rate */
1220 if (i == NUM_STD_BAUDRATES) {
1222 /* Set "dummy" baud rate. */
1223 if (cfsetspeed(&data->term, B9600) < 0)
1224 RETURN_FAIL("cfsetspeed() failed");
1225 baud_nonstd = config->baudrate;
1226 #elif defined(__linux__)
1229 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1234 if (config->bits >= 0) {
1235 data->term.c_cflag &= ~CSIZE;
1236 switch (config->bits) {
1238 data->term.c_cflag |= CS8;
1241 data->term.c_cflag |= CS7;
1244 data->term.c_cflag |= CS6;
1247 data->term.c_cflag |= CS5;
1250 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1254 if (config->parity >= 0) {
1255 data->term.c_iflag &= ~IGNPAR;
1256 data->term.c_cflag &= ~(PARENB | PARODD);
1257 switch (config->parity) {
1258 case SP_PARITY_NONE:
1259 data->term.c_iflag |= IGNPAR;
1261 case SP_PARITY_EVEN:
1262 data->term.c_cflag |= PARENB;
1265 data->term.c_cflag |= PARENB | PARODD;
1268 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1272 if (config->stopbits >= 0) {
1273 data->term.c_cflag &= ~CSTOPB;
1274 switch (config->stopbits) {
1276 data->term.c_cflag &= ~CSTOPB;
1279 data->term.c_cflag |= CSTOPB;
1282 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1286 if (config->rts >= 0 || config->cts >= 0) {
1287 if (data->termiox_supported) {
1288 data->flow &= ~(RTS_FLOW | CTS_FLOW);
1289 switch (config->rts) {
1292 controlbits = TIOCM_RTS;
1293 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1294 RETURN_FAIL("Setting RTS signal level failed");
1296 case SP_RTS_FLOW_CONTROL:
1297 data->flow |= RTS_FLOW;
1302 if (config->cts == SP_CTS_FLOW_CONTROL)
1303 data->flow |= CTS_FLOW;
1305 if (data->flow & (RTS_FLOW | CTS_FLOW))
1306 data->term.c_iflag |= CRTSCTS;
1308 data->term.c_iflag &= ~CRTSCTS;
1310 /* Asymmetric use of RTS/CTS not supported. */
1311 if (data->term.c_iflag & CRTSCTS) {
1312 /* Flow control can only be disabled for both RTS & CTS together. */
1313 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1314 if (config->cts != SP_CTS_IGNORE)
1315 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1317 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1318 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1319 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1322 /* Flow control can only be enabled for both RTS & CTS together. */
1323 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1324 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1325 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1328 if (config->rts >= 0) {
1329 if (config->rts == SP_RTS_FLOW_CONTROL) {
1330 data->term.c_iflag |= CRTSCTS;
1332 controlbits = TIOCM_RTS;
1333 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1335 RETURN_FAIL("Setting RTS signal level failed");
1341 if (config->dtr >= 0 || config->dsr >= 0) {
1342 if (data->termiox_supported) {
1343 data->flow &= ~(DTR_FLOW | DSR_FLOW);
1344 switch (config->dtr) {
1347 controlbits = TIOCM_DTR;
1348 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1349 RETURN_FAIL("Setting DTR signal level failed");
1351 case SP_DTR_FLOW_CONTROL:
1352 data->flow |= DTR_FLOW;
1357 if (config->dsr == SP_DSR_FLOW_CONTROL)
1358 data->flow |= DSR_FLOW;
1360 /* DTR/DSR flow control not supported. */
1361 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1362 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1364 if (config->dtr >= 0) {
1365 controlbits = TIOCM_DTR;
1366 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1368 RETURN_FAIL("Setting DTR signal level failed");
1373 if (config->xon_xoff >= 0) {
1374 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1375 switch (config->xon_xoff) {
1376 case SP_XONXOFF_DISABLED:
1379 data->term.c_iflag |= IXOFF;
1381 case SP_XONXOFF_OUT:
1382 data->term.c_iflag |= IXON | IXANY;
1384 case SP_XONXOFF_INOUT:
1385 data->term.c_iflag |= IXON | IXOFF | IXANY;
1388 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1392 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
1393 RETURN_FAIL("tcsetattr() failed");
1396 if (baud_nonstd != B0) {
1397 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1398 RETURN_FAIL("IOSSIOSPEED ioctl failed");
1399 /* Set baud rates in data->term to correct, but incompatible
1400 * with tcsetattr() value, same as delivered by tcgetattr(). */
1401 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1402 RETURN_FAIL("cfsetspeed() failed");
1404 #elif defined(__linux__)
1406 TRY(set_baudrate(port->fd, config->baudrate));
1408 if (data->termiox_supported)
1409 TRY(set_flow(port->fd, data->flow));
1413 #endif /* !_WIN32 */
1418 enum sp_return sp_get_config(struct sp_port *port, struct sp_port_config *config)
1420 struct port_data data;
1422 TRACE("%p, %p", port, config);
1427 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1429 TRY(get_config(port, &data, config));
1434 enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
1436 struct port_data data;
1437 struct sp_port_config prev_config;
1439 TRACE("%p, %p", port, config);
1444 RETURN_ERROR(SP_ERR_ARG, "Null config");
1446 TRY(get_config(port, &data, &prev_config));
1447 TRY(set_config(port, &data, config));
1452 #define CREATE_SETTER(x, type) int sp_set_##x(struct sp_port *port, type x) { \
1453 struct port_data data; \
1454 struct sp_port_config config; \
1455 TRACE("%p, %d", port, x); \
1456 CHECK_OPEN_PORT(); \
1457 TRY(get_config(port, &data, &config)); \
1459 TRY(set_config(port, &data, &config)); \
1463 CREATE_SETTER(baudrate, int)
1464 CREATE_SETTER(bits, int)
1465 CREATE_SETTER(parity, enum sp_parity)
1466 CREATE_SETTER(stopbits, int)
1467 CREATE_SETTER(rts, enum sp_rts)
1468 CREATE_SETTER(cts, enum sp_cts)
1469 CREATE_SETTER(dtr, enum sp_dtr)
1470 CREATE_SETTER(dsr, enum sp_dsr)
1471 CREATE_SETTER(xon_xoff, enum sp_xonxoff)
1473 enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
1475 struct port_data data;
1476 struct sp_port_config config;
1478 TRACE("%p, %d", port, flowcontrol);
1482 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
1483 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
1485 TRY(get_config(port, &data, &config));
1487 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
1488 config.xon_xoff = SP_XONXOFF_INOUT;
1490 config.xon_xoff = SP_XONXOFF_DISABLED;
1492 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
1493 config.rts = SP_RTS_FLOW_CONTROL;
1494 config.cts = SP_CTS_FLOW_CONTROL;
1496 if (config.rts == SP_RTS_FLOW_CONTROL)
1497 config.rts = SP_RTS_ON;
1498 config.cts = SP_CTS_IGNORE;
1501 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
1502 config.dtr = SP_DTR_FLOW_CONTROL;
1503 config.dsr = SP_DSR_FLOW_CONTROL;
1505 if (config.dtr == SP_DTR_FLOW_CONTROL)
1506 config.dtr = SP_DTR_ON;
1507 config.dsr = SP_DSR_IGNORE;
1510 TRY(set_config(port, &data, &config));
1515 enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
1517 TRACE("%p, %p", port, signals);
1522 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1524 DEBUG("Getting control signals for port %s", port->name);
1529 if (GetCommModemStatus(port->hdl, &bits) == 0)
1530 RETURN_FAIL("GetCommModemStatus() failed");
1531 if (bits & MS_CTS_ON)
1532 *signals |= SP_SIG_CTS;
1533 if (bits & MS_DSR_ON)
1534 *signals |= SP_SIG_DSR;
1535 if (bits & MS_RLSD_ON)
1536 *signals |= SP_SIG_DCD;
1537 if (bits & MS_RING_ON)
1538 *signals |= SP_SIG_RI;
1541 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
1542 RETURN_FAIL("TIOCMGET ioctl failed");
1543 if (bits & TIOCM_CTS)
1544 *signals |= SP_SIG_CTS;
1545 if (bits & TIOCM_DSR)
1546 *signals |= SP_SIG_DSR;
1547 if (bits & TIOCM_CAR)
1548 *signals |= SP_SIG_DCD;
1549 if (bits & TIOCM_RNG)
1550 *signals |= SP_SIG_RI;
1555 enum sp_return sp_start_break(struct sp_port *port)
1561 if (SetCommBreak(port->hdl) == 0)
1562 RETURN_FAIL("SetCommBreak() failed");
1564 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
1565 RETURN_FAIL("TIOCSBRK ioctl failed");
1571 enum sp_return sp_end_break(struct sp_port *port)
1577 if (ClearCommBreak(port->hdl) == 0)
1578 RETURN_FAIL("ClearCommBreak() failed");
1580 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
1581 RETURN_FAIL("TIOCCBRK ioctl failed");
1587 int sp_last_error_code(void)
1591 RETURN_VALUE("%d", GetLastError());
1593 RETURN_VALUE("%d", errno);
1597 char *sp_last_error_message(void)
1603 DWORD error = GetLastError();
1606 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1607 FORMAT_MESSAGE_FROM_SYSTEM |
1608 FORMAT_MESSAGE_IGNORE_INSERTS,
1611 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1615 RETURN_VALUE("%s", message);
1617 RETURN_VALUE("%s", strerror(errno));
1621 void sp_free_error_message(char *message)
1623 TRACE("%s", message);
1634 void sp_set_debug_handler(void (*handler)(const char *format, ...))
1636 TRACE("%p", handler);
1638 sp_debug_handler = handler;
1643 void sp_default_debug_handler(const char *format, ...)
1646 va_start(args, format);
1647 if (getenv("LIBSERIALPORT_DEBUG")) {
1648 fputs("libserialport: ", stderr);
1649 vfprintf(stderr, format, args);