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);
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;
272 DEBUG("Opening registry key");
273 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
274 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
275 SET_FAIL(ret, "RegOpenKeyEx() failed");
278 DEBUG("Querying registry key value and data sizes");
279 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
280 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
281 SET_FAIL(ret, "RegQueryInfoKey() failed");
284 max_data_len = max_data_size / sizeof(TCHAR);
285 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
286 SET_ERROR(ret, SP_ERR_MEM, "registry value malloc failed");
289 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
290 SET_ERROR(ret, SP_ERR_MEM, "registry data malloc failed");
293 DEBUG("Iterating over values");
295 value_len = max_value_len + 1,
296 data_size = max_data_size,
297 RegEnumValue(key, index, value, &value_len,
298 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
300 data_len = data_size / sizeof(TCHAR);
301 data[data_len] = '\0';
303 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
305 name_len = data_len + 1;
307 if (!(name = malloc(name_len))) {
308 SET_ERROR(ret, SP_ERR_MEM, "registry port name malloc failed");
312 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
316 if (type == REG_SZ) {
317 DEBUG("Found port %s", name);
318 if (!(list = list_append(list, name))) {
319 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
335 CFMutableDictionaryRef classes;
342 DEBUG("Getting IOKit master port");
343 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS) {
344 SET_FAIL(ret, "IOMasterPort() failed");
348 DEBUG("Creating matching dictionary");
349 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) {
350 SET_FAIL(ret, "IOServiceMatching() failed");
354 CFDictionarySetValue(classes,
355 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
357 DEBUG("Getting matching services");
358 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS) {
359 SET_FAIL(ret, "IOServiceGetMatchingServices() failed");
363 if (!(path = malloc(PATH_MAX))) {
364 SET_ERROR(ret, SP_ERR_MEM, "device path malloc failed");
368 DEBUG("Iterating over results");
369 while ((port = IOIteratorNext(iter))) {
370 cf_path = IORegistryEntryCreateCFProperty(port,
371 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
373 result = CFStringGetCString(cf_path,
374 path, PATH_MAX, kCFStringEncodingASCII);
377 DEBUG("Found port %s", path);
378 if (!(list = list_append(list, path))) {
379 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
380 IOObjectRelease(port);
385 IOObjectRelease(port);
390 IOObjectRelease(iter);
395 struct udev_enumerate *ud_enumerate;
396 struct udev_list_entry *ud_list;
397 struct udev_list_entry *ud_entry;
399 struct udev_device *ud_dev, *ud_parent;
402 int fd, ioctl_result;
403 struct serial_struct serial_info;
405 DEBUG("Enumerating tty devices");
407 ud_enumerate = udev_enumerate_new(ud);
408 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
409 udev_enumerate_scan_devices(ud_enumerate);
410 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
411 DEBUG("Iterating over results");
412 udev_list_entry_foreach(ud_entry, ud_list) {
413 path = udev_list_entry_get_name(ud_entry);
414 DEBUG("Found device %s", path);
415 ud_dev = udev_device_new_from_syspath(ud, path);
416 /* If there is no parent device, this is a virtual tty. */
417 ud_parent = udev_device_get_parent(ud_dev);
418 if (ud_parent == NULL) {
419 DEBUG("No parent device, assuming virtual tty");
420 udev_device_unref(ud_dev);
423 name = udev_device_get_devnode(ud_dev);
424 /* The serial8250 driver has a hardcoded number of ports.
425 * The only way to tell which actually exist on a given system
426 * is to try to open them and make an ioctl call. */
427 driver = udev_device_get_driver(ud_parent);
428 if (driver && !strcmp(driver, "serial8250")) {
429 DEBUG("serial8250 device, attempting to open");
430 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0) {
431 DEBUG("open failed, skipping");
434 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
436 if (ioctl_result != 0) {
437 DEBUG("ioctl failed, skipping");
440 if (serial_info.type == PORT_UNKNOWN) {
441 DEBUG("port type is unknown, skipping");
445 DEBUG("Found port %s", name);
446 list = list_append(list, name);
448 udev_device_unref(ud_dev);
450 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
455 udev_enumerate_unref(ud_enumerate);
464 sp_free_port_list(list);
470 void sp_free_port_list(struct sp_port **list)
481 DEBUG("Freeing port list");
483 for (i = 0; list[i]; i++)
484 sp_free_port(list[i]);
490 #define CHECK_PORT() do { \
492 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
493 if (port->name == NULL) \
494 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
497 #define CHECK_PORT_HANDLE() do { \
498 if (port->hdl == INVALID_HANDLE_VALUE) \
499 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
502 #define CHECK_PORT_HANDLE() do { \
504 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
507 #define CHECK_OPEN_PORT() do { \
509 CHECK_PORT_HANDLE(); \
512 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
514 TRACE("%p, %x", port, flags);
518 if (flags > (SP_MODE_READ | SP_MODE_WRITE | SP_MODE_NONBLOCK))
519 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
521 DEBUG("Opening port %s", port->name);
524 DWORD desired_access = 0, flags_and_attributes = 0;
525 char *escaped_port_name;
527 /* Prefix port name with '\\.\' to work with ports above COM9. */
528 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
529 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
530 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
532 /* Map 'flags' to the OS-specific settings. */
533 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
534 if (flags & SP_MODE_READ)
535 desired_access |= GENERIC_READ;
536 if (flags & SP_MODE_WRITE)
537 desired_access |= GENERIC_WRITE;
538 if (flags & SP_MODE_NONBLOCK)
539 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
541 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
542 OPEN_EXISTING, flags_and_attributes, 0);
544 free(escaped_port_name);
546 if (port->hdl == INVALID_HANDLE_VALUE)
547 RETURN_FAIL("CreateFile() failed");
550 struct port_data data;
551 struct sp_port_config config;
554 /* Map 'flags' to the OS-specific settings. */
555 if (flags & (SP_MODE_READ | SP_MODE_WRITE))
556 flags_local |= O_RDWR;
557 else if (flags & SP_MODE_READ)
558 flags_local |= O_RDONLY;
559 else if (flags & SP_MODE_WRITE)
560 flags_local |= O_WRONLY;
561 if (flags & SP_MODE_NONBLOCK)
562 flags_local |= O_NONBLOCK;
564 if ((port->fd = open(port->name, flags_local)) < 0)
565 RETURN_FAIL("open() failed");
567 ret = get_config(port, &data, &config);
574 /* Turn off all serial port cooking. */
575 data.term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
576 data.term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
577 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
578 data.term.c_oflag &= ~OFILL;
580 /* Disable canonical mode, and don't echo input characters. */
581 data.term.c_lflag &= ~(ICANON | ECHO);
583 /* Ignore modem status lines; enable receiver */
584 data.term.c_cflag |= (CLOCAL | CREAD);
586 ret = set_config(port, &data, &config);
597 enum sp_return sp_close(struct sp_port *port)
603 DEBUG("Closing port %s", port->name);
606 /* Returns non-zero upon success, 0 upon failure. */
607 if (CloseHandle(port->hdl) == 0)
608 RETURN_FAIL("CloseHandle() failed");
609 port->hdl = INVALID_HANDLE_VALUE;
611 /* Returns 0 upon success, -1 upon failure. */
612 if (close(port->fd) == -1)
613 RETURN_FAIL("close() failed");
620 enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
622 TRACE("%p, %x", port, buffers);
626 if (buffers > SP_BUF_BOTH)
627 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
629 const char *buffer_names[] = {"input", "output", "both"};
631 DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
635 if (buffers & SP_BUF_INPUT)
636 flags |= PURGE_RXCLEAR;
637 if (buffers & SP_BUF_OUTPUT)
638 flags |= PURGE_TXCLEAR;
640 /* Returns non-zero upon success, 0 upon failure. */
641 if (PurgeComm(port->hdl, flags) == 0)
642 RETURN_FAIL("PurgeComm() failed");
645 if (buffers & SP_BUF_BOTH)
647 else if (buffers & SP_BUF_INPUT)
649 else if (buffers & SP_BUF_OUTPUT)
652 /* Returns 0 upon success, -1 upon failure. */
653 if (tcflush(port->fd, flags) < 0)
654 RETURN_FAIL("tcflush() failed");
659 enum sp_return sp_drain(struct sp_port *port)
665 DEBUG("Draining port %s", port->name);
668 /* Returns non-zero upon success, 0 upon failure. */
669 if (FlushFileBuffers(port->hdl) == 0)
670 RETURN_FAIL("FlushFileBuffers() failed");
672 /* Returns 0 upon success, -1 upon failure. */
673 if (tcdrain(port->fd) < 0)
674 RETURN_FAIL("tcdrain() failed");
680 enum sp_return sp_write(struct sp_port *port, const void *buf, size_t count)
682 TRACE("%p, %p, %d", port, buf, count);
687 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
689 DEBUG("Writing up to %d bytes to port %s", count, port->name);
694 /* Returns non-zero upon success, 0 upon failure. */
695 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
696 RETURN_FAIL("WriteFile() failed");
697 RETURN_VALUE("%d", written);
699 /* Returns the number of bytes written, or -1 upon failure. */
700 ssize_t written = write(port->fd, buf, count);
703 RETURN_FAIL("write() failed");
705 RETURN_VALUE("%d", written);
709 enum sp_return sp_read(struct sp_port *port, void *buf, size_t count)
711 TRACE("%p, %p, %d", port, buf, count);
716 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
718 DEBUG("Reading up to %d bytes from port %s", count, port->name);
721 DWORD bytes_read = 0;
723 /* Returns non-zero upon success, 0 upon failure. */
724 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
725 RETURN_FAIL("ReadFile() failed");
726 RETURN_VALUE("%d", bytes_read);
730 /* Returns the number of bytes read, or -1 upon failure. */
731 if ((bytes_read = read(port->fd, buf, count)) < 0)
732 RETURN_FAIL("read() failed");
733 RETURN_VALUE("%d", bytes_read);
738 static enum sp_return get_baudrate(int fd, int *baudrate)
742 TRACE("%d, %p", fd, baudrate);
744 DEBUG("Getting baud rate");
746 if (!(data = malloc(get_termios_size())))
747 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
749 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
751 RETURN_FAIL("getting termios failed");
754 *baudrate = get_termios_speed(data);
761 static enum sp_return set_baudrate(int fd, int baudrate)
765 TRACE("%d, %d", fd, baudrate);
767 DEBUG("Getting baud rate");
769 if (!(data = malloc(get_termios_size())))
770 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
772 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
774 RETURN_FAIL("getting termios failed");
777 DEBUG("Setting baud rate");
779 set_termios_speed(data, baudrate);
781 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
783 RETURN_FAIL("setting termios failed");
792 static enum sp_return get_flow(int fd, int *flow)
796 TRACE("%d, %p", fd, flow);
798 DEBUG("Getting advanced flow control");
800 if (!(data = malloc(get_termiox_size())))
801 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
803 if (ioctl(fd, TCGETX, data) < 0) {
805 RETURN_FAIL("getting termiox failed");
808 *flow = get_termiox_flow(data);
815 static enum sp_return set_flow(int fd, int flow)
819 TRACE("%d, %d", fd, flow);
821 DEBUG("Getting advanced flow control");
823 if (!(data = malloc(get_termiox_size())))
824 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
826 if (ioctl(fd, TCGETX, data) < 0) {
828 RETURN_FAIL("getting termiox failed");
831 DEBUG("Setting advanced flow control");
833 set_termiox_flow(data, flow);
835 if (ioctl(fd, TCSETX, data) < 0) {
837 RETURN_FAIL("setting termiox failed");
844 #endif /* USE_TERMIOX */
845 #endif /* __linux__ */
847 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
848 struct sp_port_config *config)
852 TRACE("%p, %p, %p", port, data, config);
854 DEBUG("Getting configuration for port %s", port->name);
857 if (!GetCommState(port->hdl, &data->dcb))
858 RETURN_FAIL("GetCommState() failed");
860 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
861 if (data->dcb.BaudRate == std_baudrates[i].index) {
862 config->baudrate = std_baudrates[i].value;
867 if (i == NUM_STD_BAUDRATES)
868 /* BaudRate field can be either an index or a custom baud rate. */
869 config->baudrate = data->dcb.BaudRate;
871 config->bits = data->dcb.ByteSize;
873 if (data->dcb.fParity)
874 switch (data->dcb.Parity) {
876 config->parity = SP_PARITY_NONE;
879 config->parity = SP_PARITY_EVEN;
882 config->parity = SP_PARITY_ODD;
888 config->parity = SP_PARITY_NONE;
890 switch (data->dcb.StopBits) {
892 config->stopbits = 1;
895 config->stopbits = 2;
898 config->stopbits = -1;
901 switch (data->dcb.fRtsControl) {
902 case RTS_CONTROL_DISABLE:
903 config->rts = SP_RTS_OFF;
905 case RTS_CONTROL_ENABLE:
906 config->rts = SP_RTS_ON;
908 case RTS_CONTROL_HANDSHAKE:
909 config->rts = SP_RTS_FLOW_CONTROL;
915 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
917 switch (data->dcb.fDtrControl) {
918 case DTR_CONTROL_DISABLE:
919 config->dtr = SP_DTR_OFF;
921 case DTR_CONTROL_ENABLE:
922 config->dtr = SP_DTR_ON;
924 case DTR_CONTROL_HANDSHAKE:
925 config->dtr = SP_DTR_FLOW_CONTROL;
931 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
933 if (data->dcb.fInX) {
935 config->xon_xoff = SP_XONXOFF_INOUT;
937 config->xon_xoff = SP_XONXOFF_IN;
940 config->xon_xoff = SP_XONXOFF_OUT;
942 config->xon_xoff = SP_XONXOFF_DISABLED;
947 if (tcgetattr(port->fd, &data->term) < 0)
948 RETURN_FAIL("tcgetattr() failed");
950 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
951 RETURN_FAIL("TIOCMGET ioctl failed");
954 int ret = get_flow(port->fd, &data->flow);
956 if (ret == SP_ERR_FAIL && errno == EINVAL)
957 data->termiox_supported = 0;
961 data->termiox_supported = 1;
963 data->termiox_supported = 0;
966 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
967 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
968 config->baudrate = std_baudrates[i].value;
973 if (i == NUM_STD_BAUDRATES) {
975 config->baudrate = (int)data->term.c_ispeed;
976 #elif defined(__linux__)
977 TRY(get_baudrate(port->fd, &config->baudrate));
979 config->baudrate = -1;
983 switch (data->term.c_cflag & CSIZE) {
1000 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1001 config->parity = SP_PARITY_NONE;
1002 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1003 config->parity = -1;
1005 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1007 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1009 if (data->term.c_cflag & CRTSCTS) {
1010 config->rts = SP_RTS_FLOW_CONTROL;
1011 config->cts = SP_CTS_FLOW_CONTROL;
1013 if (data->termiox_supported && data->flow & RTS_FLOW)
1014 config->rts = SP_RTS_FLOW_CONTROL;
1016 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1018 config->cts = (data->termiox_supported && data->flow & CTS_FLOW) ?
1019 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1022 if (data->termiox_supported && data->flow & DTR_FLOW)
1023 config->dtr = SP_DTR_FLOW_CONTROL;
1025 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1027 config->dsr = (data->termiox_supported && data->flow & DSR_FLOW) ?
1028 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1030 if (data->term.c_iflag & IXOFF) {
1031 if (data->term.c_iflag & IXON)
1032 config->xon_xoff = SP_XONXOFF_INOUT;
1034 config->xon_xoff = SP_XONXOFF_IN;
1036 if (data->term.c_iflag & IXON)
1037 config->xon_xoff = SP_XONXOFF_OUT;
1039 config->xon_xoff = SP_XONXOFF_DISABLED;
1046 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1047 const struct sp_port_config *config)
1051 BAUD_TYPE baud_nonstd;
1056 int baud_nonstd = 0;
1059 TRACE("%p, %p, %p", port, data, config);
1061 DEBUG("Setting configuration for port %s", port->name);
1064 if (config->baudrate >= 0) {
1065 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1066 if (config->baudrate == std_baudrates[i].value) {
1067 data->dcb.BaudRate = std_baudrates[i].index;
1072 if (i == NUM_STD_BAUDRATES)
1073 data->dcb.BaudRate = config->baudrate;
1076 if (config->bits >= 0)
1077 data->dcb.ByteSize = config->bits;
1079 if (config->parity >= 0) {
1080 switch (config->parity) {
1081 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
1082 case SP_PARITY_NONE:
1083 data->dcb.Parity = NOPARITY;
1085 case SP_PARITY_EVEN:
1086 data->dcb.Parity = EVENPARITY;
1089 data->dcb.Parity = ODDPARITY;
1092 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1096 if (config->stopbits >= 0) {
1097 switch (config->stopbits) {
1098 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1100 data->dcb.StopBits = ONESTOPBIT;
1103 data->dcb.StopBits = TWOSTOPBITS;
1106 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1110 if (config->rts >= 0) {
1111 switch (config->rts) {
1113 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1116 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1118 case SP_RTS_FLOW_CONTROL:
1119 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1122 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1126 if (config->cts >= 0) {
1127 switch (config->cts) {
1129 data->dcb.fOutxCtsFlow = FALSE;
1131 case SP_CTS_FLOW_CONTROL:
1132 data->dcb.fOutxCtsFlow = TRUE;
1135 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1139 if (config->dtr >= 0) {
1140 switch (config->dtr) {
1142 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1145 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1147 case SP_DTR_FLOW_CONTROL:
1148 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1151 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1155 if (config->dsr >= 0) {
1156 switch (config->dsr) {
1158 data->dcb.fOutxDsrFlow = FALSE;
1160 case SP_DSR_FLOW_CONTROL:
1161 data->dcb.fOutxDsrFlow = TRUE;
1164 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1168 if (config->xon_xoff >= 0) {
1169 switch (config->xon_xoff) {
1170 case SP_XONXOFF_DISABLED:
1171 data->dcb.fInX = FALSE;
1172 data->dcb.fOutX = FALSE;
1175 data->dcb.fInX = TRUE;
1176 data->dcb.fOutX = FALSE;
1178 case SP_XONXOFF_OUT:
1179 data->dcb.fInX = FALSE;
1180 data->dcb.fOutX = TRUE;
1182 case SP_XONXOFF_INOUT:
1183 data->dcb.fInX = TRUE;
1184 data->dcb.fOutX = TRUE;
1187 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1191 if (!SetCommState(port->hdl, &data->dcb))
1192 RETURN_FAIL("SetCommState() failed");
1198 if (config->baudrate >= 0) {
1199 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1200 if (config->baudrate == std_baudrates[i].value) {
1201 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1202 RETURN_FAIL("cfsetospeed() failed");
1204 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1205 RETURN_FAIL("cfsetispeed() failed");
1210 /* Non-standard baud rate */
1211 if (i == NUM_STD_BAUDRATES) {
1213 /* Set "dummy" baud rate. */
1214 if (cfsetspeed(&data->term, B9600) < 0)
1215 RETURN_FAIL("cfsetspeed() failed");
1216 baud_nonstd = config->baudrate;
1217 #elif defined(__linux__)
1220 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1225 if (config->bits >= 0) {
1226 data->term.c_cflag &= ~CSIZE;
1227 switch (config->bits) {
1229 data->term.c_cflag |= CS8;
1232 data->term.c_cflag |= CS7;
1235 data->term.c_cflag |= CS6;
1238 data->term.c_cflag |= CS5;
1241 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1245 if (config->parity >= 0) {
1246 data->term.c_iflag &= ~IGNPAR;
1247 data->term.c_cflag &= ~(PARENB | PARODD);
1248 switch (config->parity) {
1249 case SP_PARITY_NONE:
1250 data->term.c_iflag |= IGNPAR;
1252 case SP_PARITY_EVEN:
1253 data->term.c_cflag |= PARENB;
1256 data->term.c_cflag |= PARENB | PARODD;
1259 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1263 if (config->stopbits >= 0) {
1264 data->term.c_cflag &= ~CSTOPB;
1265 switch (config->stopbits) {
1267 data->term.c_cflag &= ~CSTOPB;
1270 data->term.c_cflag |= CSTOPB;
1273 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1277 if (config->rts >= 0 || config->cts >= 0) {
1278 if (data->termiox_supported) {
1279 data->flow &= ~(RTS_FLOW | CTS_FLOW);
1280 switch (config->rts) {
1283 controlbits = TIOCM_RTS;
1284 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1285 RETURN_FAIL("Setting RTS signal level failed");
1287 case SP_RTS_FLOW_CONTROL:
1288 data->flow |= RTS_FLOW;
1293 if (config->cts == SP_CTS_FLOW_CONTROL)
1294 data->flow |= CTS_FLOW;
1296 if (data->flow & (RTS_FLOW | CTS_FLOW))
1297 data->term.c_iflag |= CRTSCTS;
1299 data->term.c_iflag &= ~CRTSCTS;
1301 /* Asymmetric use of RTS/CTS not supported. */
1302 if (data->term.c_iflag & CRTSCTS) {
1303 /* Flow control can only be disabled for both RTS & CTS together. */
1304 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1305 if (config->cts != SP_CTS_IGNORE)
1306 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1308 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1309 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1310 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1313 /* Flow control can only be enabled for both RTS & CTS together. */
1314 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1315 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1316 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1319 if (config->rts >= 0) {
1320 if (config->rts == SP_RTS_FLOW_CONTROL) {
1321 data->term.c_iflag |= CRTSCTS;
1323 controlbits = TIOCM_RTS;
1324 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1326 RETURN_FAIL("Setting RTS signal level failed");
1332 if (config->dtr >= 0 || config->dsr >= 0) {
1333 if (data->termiox_supported) {
1334 data->flow &= ~(DTR_FLOW | DSR_FLOW);
1335 switch (config->dtr) {
1338 controlbits = TIOCM_DTR;
1339 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1340 RETURN_FAIL("Setting DTR signal level failed");
1342 case SP_DTR_FLOW_CONTROL:
1343 data->flow |= DTR_FLOW;
1348 if (config->dsr == SP_DSR_FLOW_CONTROL)
1349 data->flow |= DSR_FLOW;
1351 /* DTR/DSR flow control not supported. */
1352 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1353 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1355 if (config->dtr >= 0) {
1356 controlbits = TIOCM_DTR;
1357 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1359 RETURN_FAIL("Setting DTR signal level failed");
1364 if (config->xon_xoff >= 0) {
1365 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1366 switch (config->xon_xoff) {
1367 case SP_XONXOFF_DISABLED:
1370 data->term.c_iflag |= IXOFF;
1372 case SP_XONXOFF_OUT:
1373 data->term.c_iflag |= IXON | IXANY;
1375 case SP_XONXOFF_INOUT:
1376 data->term.c_iflag |= IXON | IXOFF | IXANY;
1379 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1383 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
1384 RETURN_FAIL("tcsetattr() failed");
1387 if (baud_nonstd != B0) {
1388 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1389 RETURN_FAIL("IOSSIOSPEED ioctl failed");
1390 /* Set baud rates in data->term to correct, but incompatible
1391 * with tcsetattr() value, same as delivered by tcgetattr(). */
1392 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1393 RETURN_FAIL("cfsetspeed() failed");
1395 #elif defined(__linux__)
1397 TRY(set_baudrate(port->fd, config->baudrate));
1399 if (data->termiox_supported)
1400 TRY(set_flow(port->fd, data->flow));
1404 #endif /* !_WIN32 */
1409 enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
1411 struct port_data data;
1412 struct sp_port_config prev_config;
1414 TRACE("%p, %p", port, config);
1419 RETURN_ERROR(SP_ERR_ARG, "Null config");
1421 TRY(get_config(port, &data, &prev_config));
1422 TRY(set_config(port, &data, config));
1427 #define CREATE_SETTER(x, type) int sp_set_##x(struct sp_port *port, type x) { \
1428 struct port_data data; \
1429 struct sp_port_config config; \
1430 TRACE("%p, %d", port, x); \
1431 CHECK_OPEN_PORT(); \
1432 TRY(get_config(port, &data, &config)); \
1434 TRY(set_config(port, &data, &config)); \
1438 CREATE_SETTER(baudrate, int)
1439 CREATE_SETTER(bits, int)
1440 CREATE_SETTER(parity, enum sp_parity)
1441 CREATE_SETTER(stopbits, int)
1442 CREATE_SETTER(rts, enum sp_rts)
1443 CREATE_SETTER(cts, enum sp_cts)
1444 CREATE_SETTER(dtr, enum sp_dtr)
1445 CREATE_SETTER(dsr, enum sp_dsr)
1446 CREATE_SETTER(xon_xoff, enum sp_xonxoff)
1448 enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
1450 struct port_data data;
1451 struct sp_port_config config;
1453 TRACE("%p, %d", port, flowcontrol);
1457 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
1458 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
1460 TRY(get_config(port, &data, &config));
1462 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
1463 config.xon_xoff = SP_XONXOFF_INOUT;
1465 config.xon_xoff = SP_XONXOFF_DISABLED;
1467 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
1468 config.rts = SP_RTS_FLOW_CONTROL;
1469 config.cts = SP_CTS_FLOW_CONTROL;
1471 if (config.rts == SP_RTS_FLOW_CONTROL)
1472 config.rts = SP_RTS_ON;
1473 config.cts = SP_CTS_IGNORE;
1476 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
1477 config.dtr = SP_DTR_FLOW_CONTROL;
1478 config.dsr = SP_DSR_FLOW_CONTROL;
1480 if (config.dtr == SP_DTR_FLOW_CONTROL)
1481 config.dtr = SP_DTR_ON;
1482 config.dsr = SP_DSR_IGNORE;
1485 TRY(set_config(port, &data, &config));
1490 enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
1492 TRACE("%p, %p", port, signals);
1497 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1499 DEBUG("Getting control signals for port %s", port->name);
1504 if (GetCommModemStatus(port->hdl, &bits) == 0)
1505 RETURN_FAIL("GetCommModemStatus() failed");
1506 if (bits & MS_CTS_ON)
1507 *signals |= SP_SIG_CTS;
1508 if (bits & MS_DSR_ON)
1509 *signals |= SP_SIG_DSR;
1510 if (bits & MS_RING_ON)
1511 *signals |= SP_SIG_DCD;
1512 if (bits & MS_RLSD_ON)
1513 *signals |= SP_SIG_RI;
1516 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
1517 RETURN_FAIL("TIOCMGET ioctl failed");
1518 if (bits & TIOCM_CTS)
1519 *signals |= SP_SIG_CTS;
1520 if (bits & TIOCM_DSR)
1521 *signals |= SP_SIG_DSR;
1522 if (bits & TIOCM_CAR)
1523 *signals |= SP_SIG_DCD;
1524 if (bits & TIOCM_RNG)
1525 *signals |= SP_SIG_RI;
1530 enum sp_return sp_start_break(struct sp_port *port)
1536 if (SetCommBreak(port->hdl) == 0)
1537 RETURN_FAIL("SetCommBreak() failed");
1539 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
1540 RETURN_FAIL("TIOCSBRK ioctl failed");
1546 enum sp_return sp_end_break(struct sp_port *port)
1552 if (ClearCommBreak(port->hdl) == 0)
1553 RETURN_FAIL("ClearCommBreak() failed");
1555 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
1556 RETURN_FAIL("TIOCCBRK ioctl failed");
1562 int sp_last_error_code(void)
1566 RETURN_VALUE("%d", GetLastError());
1568 RETURN_VALUE("%d", errno);
1572 char *sp_last_error_message(void)
1578 DWORD error = GetLastError();
1581 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1582 FORMAT_MESSAGE_FROM_SYSTEM |
1583 FORMAT_MESSAGE_IGNORE_INSERTS,
1586 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1590 RETURN_VALUE("%s", message);
1592 RETURN_VALUE("%s", strerror(errno));
1596 void sp_free_error_message(char *message)
1598 TRACE("%s", message);
1609 void sp_set_debug_handler(void (*handler)(const char *format, ...))
1611 TRACE("%p", handler);
1613 sp_debug_handler = handler;
1618 void sp_default_debug_handler(const char *format, ...)
1621 va_start(args, format);
1622 if (getenv("LIBSERIALPORT_DEBUG")) {
1623 fputs("libserialport: ", stderr);
1624 vfprintf(stderr, format, args);