2 * This file is part of the libserialport project.
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2015 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2013-2015 Martin Ling <martin-libserialport@earth.li>
7 * Copyright (C) 2013 Matthias Heidbrink <m-sigrok@heidbrink.biz>
8 * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation, either version 3 of the
13 * License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "libserialport.h"
26 #include "libserialport_internal.h"
28 static const struct std_baudrate std_baudrates[] = {
31 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
32 * have documented CBR_* macros.
34 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
35 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
36 BAUD(115200), BAUD(128000), BAUD(256000),
38 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
39 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
40 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
42 #if !defined(__APPLE__) && !defined(__OpenBSD__)
48 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
50 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
52 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
53 struct sp_port_config *config);
55 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
56 const struct sp_port_config *config);
58 /* Timing abstraction */
69 unsigned int ms, limit_ms;
70 struct time start, now, end, delta, delta_max;
71 struct timeval delta_tv;
72 bool calls_started, overflow;
75 static void time_get(struct time *time)
79 QueryPerformanceCounter(&count);
80 time->ticks = count.QuadPart;
81 #elif defined(HAVE_CLOCK_GETTIME)
83 if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
84 clock_gettime(CLOCK_REALTIME, &ts);
85 time->tv.tv_sec = ts.tv_sec;
86 time->tv.tv_usec = ts.tv_nsec / 1000;
87 #elif defined(__APPLE__)
88 mach_timebase_info_data_t info;
89 mach_timebase_info(&info);
90 uint64_t ticks = mach_absolute_time();
91 uint64_t ns = (ticks * info.numer) / info.denom;
92 time->tv.tv_sec = ns / 1000000000;
93 time->tv.tv_usec = (ns % 1000000000) / 1000;
95 gettimeofday(&time->tv, NULL);
99 static void time_set_ms(struct time *time, unsigned int ms)
102 LARGE_INTEGER frequency;
103 QueryPerformanceFrequency(&frequency);
104 time->ticks = ms * (frequency.QuadPart / 1000);
106 time->tv.tv_sec = ms / 1000;
107 time->tv.tv_usec = (ms % 1000) * 1000;
111 static void time_add(const struct time *a,
112 const struct time *b, struct time *result)
115 result->ticks = a->ticks + b->ticks;
117 timeradd(&a->tv, &b->tv, &result->tv);
121 static void time_sub(const struct time *a,
122 const struct time *b, struct time *result)
125 result->ticks = a->ticks - b->ticks;
127 timersub(&a->tv, &b->tv, &result->tv);
131 static bool time_greater(const struct time *a, const struct time *b)
134 return (a->ticks > b->ticks);
136 return timercmp(&a->tv, &b->tv, >);
140 static void time_as_timeval(const struct time *time, struct timeval *tv)
143 LARGE_INTEGER frequency;
144 QueryPerformanceFrequency(&frequency);
145 tv->tv_sec = time->ticks / frequency.QuadPart;
146 tv->tv_usec = (time->ticks % frequency.QuadPart) /
147 (frequency.QuadPart / 1000000);
153 static unsigned int time_as_ms(const struct time *time)
156 LARGE_INTEGER frequency;
157 QueryPerformanceFrequency(&frequency);
158 return time->ticks / (frequency.QuadPart / 1000);
160 return time->tv.tv_sec * 1000 + time->tv.tv_usec / 1000;
164 static void timeout_start(struct timeout *timeout, unsigned int timeout_ms)
166 timeout->ms = timeout_ms;
168 /* Get time at start of operation. */
169 time_get(&timeout->start);
170 /* Define duration of timeout. */
171 time_set_ms(&timeout->delta, timeout_ms);
172 /* Calculate time at which we should give up. */
173 time_add(&timeout->start, &timeout->delta, &timeout->end);
174 /* Disable limit unless timeout_limit() called. */
175 timeout->limit_ms = 0;
176 /* First blocking call has not yet been made. */
177 timeout->calls_started = false;
180 static void timeout_limit(struct timeout *timeout, unsigned int limit_ms)
182 timeout->limit_ms = limit_ms;
183 timeout->overflow = (timeout->ms > timeout->limit_ms);
184 time_set_ms(&timeout->delta_max, timeout->limit_ms);
187 static bool timeout_check(struct timeout *timeout)
189 if (!timeout->calls_started)
192 if (timeout->ms == 0)
195 time_get(&timeout->now);
196 time_sub(&timeout->end, &timeout->now, &timeout->delta);
197 if (timeout->limit_ms)
198 if ((timeout->overflow = time_greater(&timeout->delta, &timeout->delta_max)))
199 timeout->delta = timeout->delta_max;
201 return time_greater(&timeout->now, &timeout->end);
204 static void timeout_update(struct timeout *timeout)
206 timeout->calls_started = true;
210 static struct timeval *timeout_timeval(struct timeout *timeout)
212 if (timeout->ms == 0)
215 time_as_timeval(&timeout->delta, &timeout->delta_tv);
217 return &timeout->delta_tv;
221 static unsigned int timeout_remaining_ms(struct timeout *timeout)
223 if (timeout->limit_ms && timeout->overflow)
224 return timeout->limit_ms;
226 return time_as_ms(&timeout->delta);
229 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
231 struct sp_port *port;
232 #ifndef NO_PORT_METADATA
237 TRACE("%s, %p", portname, port_ptr);
240 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
245 RETURN_ERROR(SP_ERR_ARG, "Null port name");
247 DEBUG_FMT("Building structure for port %s", portname);
249 #if !defined(_WIN32) && defined(HAVE_REALPATH)
251 * get_port_details() below tries to be too smart and figure out
252 * some transport properties from the port name which breaks with
253 * symlinks. Therefore we canonicalize the portname first.
255 char pathbuf[PATH_MAX + 1];
256 char *res = realpath(portname, pathbuf);
258 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
263 if (!(port = malloc(sizeof(struct sp_port))))
264 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
266 len = strlen(portname) + 1;
268 if (!(port->name = malloc(len))) {
270 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
273 memcpy(port->name, portname, len);
276 port->usb_path = NULL;
277 port->hdl = INVALID_HANDLE_VALUE;
278 port->write_buf = NULL;
279 port->write_buf_size = 0;
284 port->description = NULL;
285 port->transport = SP_TRANSPORT_NATIVE;
287 port->usb_address = -1;
290 port->usb_manufacturer = NULL;
291 port->usb_product = NULL;
292 port->usb_serial = NULL;
293 port->bluetooth_address = NULL;
295 #ifndef NO_PORT_METADATA
296 if ((ret = get_port_details(port)) != SP_OK) {
307 SP_API char *sp_get_port_name(const struct sp_port *port)
314 RETURN_STRING(port->name);
317 SP_API char *sp_get_port_description(const struct sp_port *port)
321 if (!port || !port->description)
324 RETURN_STRING(port->description);
327 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
332 RETURN_ERROR(SP_ERR_ARG, "Null port");
334 RETURN_INT(port->transport);
337 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
338 int *usb_bus,int *usb_address)
343 RETURN_ERROR(SP_ERR_ARG, "Null port");
344 if (port->transport != SP_TRANSPORT_USB)
345 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
346 if (port->usb_bus < 0 || port->usb_address < 0)
347 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
350 *usb_bus = port->usb_bus;
352 *usb_address = port->usb_address;
357 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
358 int *usb_vid, int *usb_pid)
363 RETURN_ERROR(SP_ERR_ARG, "Null port");
364 if (port->transport != SP_TRANSPORT_USB)
365 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
366 if (port->usb_vid < 0 || port->usb_pid < 0)
367 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
370 *usb_vid = port->usb_vid;
372 *usb_pid = port->usb_pid;
377 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
381 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
384 RETURN_STRING(port->usb_manufacturer);
387 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
391 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
394 RETURN_STRING(port->usb_product);
397 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
401 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
404 RETURN_STRING(port->usb_serial);
407 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
411 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
412 || !port->bluetooth_address)
415 RETURN_STRING(port->bluetooth_address);
418 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
421 TRACE("%p, %p", port, result_ptr);
424 RETURN_ERROR(SP_ERR_ARG, "Null port");
426 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
429 HANDLE *handle_ptr = result_ptr;
430 *handle_ptr = port->hdl;
432 int *fd_ptr = result_ptr;
439 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
440 struct sp_port **copy_ptr)
442 TRACE("%p, %p", port, copy_ptr);
445 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
450 RETURN_ERROR(SP_ERR_ARG, "Null port");
453 RETURN_ERROR(SP_ERR_ARG, "Null port name");
455 DEBUG("Copying port structure");
457 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
460 SP_API void sp_free_port(struct sp_port *port)
469 DEBUG("Freeing port structure");
473 if (port->description)
474 free(port->description);
475 if (port->usb_manufacturer)
476 free(port->usb_manufacturer);
477 if (port->usb_product)
478 free(port->usb_product);
479 if (port->usb_serial)
480 free(port->usb_serial);
481 if (port->bluetooth_address)
482 free(port->bluetooth_address);
485 free(port->usb_path);
487 free(port->write_buf);
495 SP_PRIV struct sp_port **list_append(struct sp_port **list,
496 const char *portname)
501 for (count = 0; list[count]; count++)
503 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
506 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
508 list[count + 1] = NULL;
512 sp_free_port_list(list);
516 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
518 #ifndef NO_ENUMERATION
519 struct sp_port **list;
523 TRACE("%p", list_ptr);
526 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
530 #ifdef NO_ENUMERATION
531 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
533 DEBUG("Enumerating ports");
535 if (!(list = malloc(sizeof(struct sp_port *))))
536 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
540 ret = list_ports(&list);
545 sp_free_port_list(list);
553 SP_API void sp_free_port_list(struct sp_port **list)
564 DEBUG("Freeing port list");
566 for (i = 0; list[i]; i++)
567 sp_free_port(list[i]);
573 #define CHECK_PORT() do { \
575 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
577 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
580 #define CHECK_PORT_HANDLE() do { \
581 if (port->hdl == INVALID_HANDLE_VALUE) \
582 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
585 #define CHECK_PORT_HANDLE() do { \
587 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
590 #define CHECK_OPEN_PORT() do { \
592 CHECK_PORT_HANDLE(); \
596 /** To be called after port receive buffer is emptied. */
597 static enum sp_return restart_wait(struct sp_port *port)
601 if (port->wait_running) {
602 /* Check status of running wait operation. */
603 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
604 &wait_result, FALSE)) {
605 DEBUG("Previous wait completed");
606 port->wait_running = FALSE;
607 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
608 DEBUG("Previous wait still running");
611 RETURN_FAIL("GetOverlappedResult() failed");
615 if (!port->wait_running) {
616 /* Start new wait operation. */
617 if (WaitCommEvent(port->hdl, &port->events,
619 DEBUG("New wait returned, events already pending");
620 } else if (GetLastError() == ERROR_IO_PENDING) {
621 DEBUG("New wait running in background");
622 port->wait_running = TRUE;
624 RETURN_FAIL("WaitCommEvent() failed");
632 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
634 struct port_data data;
635 struct sp_port_config config;
638 TRACE("%p, 0x%x", port, flags);
642 if (flags > SP_MODE_READ_WRITE)
643 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
645 DEBUG_FMT("Opening port %s", port->name);
648 DWORD desired_access = 0, flags_and_attributes = 0, errors;
649 char *escaped_port_name;
652 /* Prefix port name with '\\.\' to work with ports above COM9. */
653 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
654 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
655 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
657 /* Map 'flags' to the OS-specific settings. */
658 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
659 if (flags & SP_MODE_READ)
660 desired_access |= GENERIC_READ;
661 if (flags & SP_MODE_WRITE)
662 desired_access |= GENERIC_WRITE;
664 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
665 OPEN_EXISTING, flags_and_attributes, 0);
667 free(escaped_port_name);
669 if (port->hdl == INVALID_HANDLE_VALUE)
670 RETURN_FAIL("Port CreateFile() failed");
672 /* All timeouts initially disabled. */
673 port->timeouts.ReadIntervalTimeout = 0;
674 port->timeouts.ReadTotalTimeoutMultiplier = 0;
675 port->timeouts.ReadTotalTimeoutConstant = 0;
676 port->timeouts.WriteTotalTimeoutMultiplier = 0;
677 port->timeouts.WriteTotalTimeoutConstant = 0;
679 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
681 RETURN_FAIL("SetCommTimeouts() failed");
684 /* Prepare OVERLAPPED structures. */
685 #define INIT_OVERLAPPED(ovl) do { \
686 memset(&port->ovl, 0, sizeof(port->ovl)); \
687 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
688 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
689 == INVALID_HANDLE_VALUE) { \
691 RETURN_FAIL(#ovl "CreateEvent() failed"); \
695 INIT_OVERLAPPED(read_ovl);
696 INIT_OVERLAPPED(write_ovl);
697 INIT_OVERLAPPED(wait_ovl);
699 /* Set event mask for RX and error events. */
700 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
702 RETURN_FAIL("SetCommMask() failed");
705 port->writing = FALSE;
706 port->wait_running = FALSE;
708 ret = restart_wait(port);
715 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
717 /* Map 'flags' to the OS-specific settings. */
718 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
719 flags_local |= O_RDWR;
720 else if (flags & SP_MODE_READ)
721 flags_local |= O_RDONLY;
722 else if (flags & SP_MODE_WRITE)
723 flags_local |= O_WRONLY;
725 if ((port->fd = open(port->name, flags_local)) < 0)
726 RETURN_FAIL("open() failed");
729 ret = get_config(port, &data, &config);
736 /* Set sane port settings. */
738 data.dcb.fBinary = TRUE;
739 data.dcb.fDsrSensitivity = FALSE;
740 data.dcb.fErrorChar = FALSE;
741 data.dcb.fNull = FALSE;
742 data.dcb.fAbortOnError = FALSE;
744 /* Turn off all fancy termios tricks, give us a raw channel. */
745 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
747 data.term.c_iflag &= ~IUCLC;
749 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
751 data.term.c_oflag &= ~OLCUC;
754 data.term.c_oflag &= ~NLDLY;
757 data.term.c_oflag &= ~CRDLY;
760 data.term.c_oflag &= ~TABDLY;
763 data.term.c_oflag &= ~BSDLY;
766 data.term.c_oflag &= ~VTDLY;
769 data.term.c_oflag &= ~FFDLY;
772 data.term.c_oflag &= ~OFILL;
774 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
775 data.term.c_cc[VMIN] = 0;
776 data.term.c_cc[VTIME] = 0;
778 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
779 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
783 if (ClearCommError(port->hdl, &errors, &status) == 0)
784 RETURN_FAIL("ClearCommError() failed");
787 ret = set_config(port, &data, &config);
797 SP_API enum sp_return sp_close(struct sp_port *port)
803 DEBUG_FMT("Closing port %s", port->name);
806 /* Returns non-zero upon success, 0 upon failure. */
807 if (CloseHandle(port->hdl) == 0)
808 RETURN_FAIL("Port CloseHandle() failed");
809 port->hdl = INVALID_HANDLE_VALUE;
811 /* Close event handles for overlapped structures. */
812 #define CLOSE_OVERLAPPED(ovl) do { \
813 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
814 CloseHandle(port->ovl.hEvent) == 0) \
815 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
817 CLOSE_OVERLAPPED(read_ovl);
818 CLOSE_OVERLAPPED(write_ovl);
819 CLOSE_OVERLAPPED(wait_ovl);
821 if (port->write_buf) {
822 free(port->write_buf);
823 port->write_buf = NULL;
826 /* Returns 0 upon success, -1 upon failure. */
827 if (close(port->fd) == -1)
828 RETURN_FAIL("close() failed");
835 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
837 TRACE("%p, 0x%x", port, buffers);
841 if (buffers > SP_BUF_BOTH)
842 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
844 const char *buffer_names[] = {"no", "input", "output", "both"};
846 DEBUG_FMT("Flushing %s buffers on port %s",
847 buffer_names[buffers], port->name);
851 if (buffers & SP_BUF_INPUT)
852 flags |= PURGE_RXCLEAR;
853 if (buffers & SP_BUF_OUTPUT)
854 flags |= PURGE_TXCLEAR;
856 /* Returns non-zero upon success, 0 upon failure. */
857 if (PurgeComm(port->hdl, flags) == 0)
858 RETURN_FAIL("PurgeComm() failed");
860 if (buffers & SP_BUF_INPUT)
861 TRY(restart_wait(port));
864 if (buffers == SP_BUF_BOTH)
866 else if (buffers == SP_BUF_INPUT)
868 else if (buffers == SP_BUF_OUTPUT)
871 /* Returns 0 upon success, -1 upon failure. */
872 if (tcflush(port->fd, flags) < 0)
873 RETURN_FAIL("tcflush() failed");
878 SP_API enum sp_return sp_drain(struct sp_port *port)
884 DEBUG_FMT("Draining port %s", port->name);
887 /* Returns non-zero upon success, 0 upon failure. */
888 if (FlushFileBuffers(port->hdl) == 0)
889 RETURN_FAIL("FlushFileBuffers() failed");
894 #if defined(__ANDROID__) && (__ANDROID_API__ < 21)
895 /* Android only has tcdrain from platform 21 onwards.
896 * On previous API versions, use the ioctl directly. */
898 result = ioctl(port->fd, TCSBRK, &arg);
900 result = tcdrain(port->fd);
903 if (errno == EINTR) {
904 DEBUG("tcdrain() was interrupted");
907 RETURN_FAIL("tcdrain() failed");
917 static enum sp_return await_write_completion(struct sp_port *port)
923 /* Wait for previous non-blocking write to complete, if any. */
925 DEBUG("Waiting for previous write to complete");
926 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
929 RETURN_FAIL("Previous write failed to complete");
930 DEBUG("Previous write completed");
937 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
938 size_t count, unsigned int timeout_ms)
940 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
945 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
948 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
949 count, port->name, timeout_ms);
951 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
958 DWORD bytes_written = 0;
960 TRY(await_write_completion(port));
963 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
964 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
965 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
966 RETURN_FAIL("SetCommTimeouts() failed");
969 /* Reduce count if it exceeds the WriteFile limit. */
970 if (count > WRITEFILE_MAX_SIZE)
971 count = WRITEFILE_MAX_SIZE;
974 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
975 DEBUG("Write completed immediately");
977 } else if (GetLastError() == ERROR_IO_PENDING) {
978 DEBUG("Waiting for write to complete");
979 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
980 if (GetLastError() == ERROR_SEM_TIMEOUT) {
981 DEBUG("Write timed out");
984 RETURN_FAIL("GetOverlappedResult() failed");
987 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
988 RETURN_INT(bytes_written);
990 RETURN_FAIL("WriteFile() failed");
993 size_t bytes_written = 0;
994 unsigned char *ptr = (unsigned char *) buf;
995 struct timeout timeout;
999 timeout_start(&timeout, timeout_ms);
1002 FD_SET(port->fd, &fds);
1004 /* Loop until we have written the requested number of bytes. */
1005 while (bytes_written < count) {
1007 if (timeout_check(&timeout))
1010 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
1012 timeout_update(&timeout);
1015 if (errno == EINTR) {
1016 DEBUG("select() call was interrupted, repeating");
1019 RETURN_FAIL("select() failed");
1021 } else if (result == 0) {
1022 /* Timeout has expired. */
1027 result = write(port->fd, ptr, count - bytes_written);
1030 if (errno == EAGAIN)
1031 /* This shouldn't happen because we did a select() first, but handle anyway. */
1034 /* This is an actual failure. */
1035 RETURN_FAIL("write() failed");
1038 bytes_written += result;
1042 if (bytes_written < count)
1043 DEBUG("Write timed out");
1045 RETURN_INT(bytes_written);
1049 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
1050 const void *buf, size_t count)
1052 TRACE("%p, %p, %d", port, buf, count);
1057 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1059 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
1067 /* Check whether previous write is complete. */
1068 if (port->writing) {
1069 if (HasOverlappedIoCompleted(&port->write_ovl)) {
1070 DEBUG("Previous write completed");
1073 DEBUG("Previous write not complete");
1074 /* Can't take a new write until the previous one finishes. */
1080 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
1081 port->timeouts.WriteTotalTimeoutConstant = 0;
1082 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1083 RETURN_FAIL("SetCommTimeouts() failed");
1086 /* Reduce count if it exceeds the WriteFile limit. */
1087 if (count > WRITEFILE_MAX_SIZE)
1088 count = WRITEFILE_MAX_SIZE;
1090 /* Copy data to our write buffer. */
1091 buf_bytes = min(port->write_buf_size, count);
1092 memcpy(port->write_buf, buf, buf_bytes);
1094 /* Start asynchronous write. */
1095 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
1096 if (GetLastError() == ERROR_IO_PENDING) {
1097 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
1098 DEBUG("Asynchronous write completed immediately");
1100 DEBUG("Asynchronous write running");
1102 /* Actual failure of some kind. */
1103 RETURN_FAIL("WriteFile() failed");
1107 DEBUG("All bytes written immediately");
1109 RETURN_INT(buf_bytes);
1111 /* Returns the number of bytes written, or -1 upon failure. */
1112 ssize_t written = write(port->fd, buf, count);
1115 if (errno == EAGAIN)
1116 // Buffer is full, no bytes written.
1119 RETURN_FAIL("write() failed");
1121 RETURN_INT(written);
1127 /* Restart wait operation if buffer was emptied. */
1128 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1133 if (bytes_read == 0)
1136 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1137 RETURN_FAIL("ClearCommError() failed");
1139 if (comstat.cbInQue == 0)
1140 TRY(restart_wait(port));
1146 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1147 size_t count, unsigned int timeout_ms)
1149 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1154 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1157 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1158 count, port->name, timeout_ms);
1160 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1167 DWORD bytes_read = 0;
1170 if (port->timeouts.ReadIntervalTimeout != 0 ||
1171 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1172 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1173 port->timeouts.ReadIntervalTimeout = 0;
1174 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1175 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1176 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1177 RETURN_FAIL("SetCommTimeouts() failed");
1181 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1182 DEBUG("Read completed immediately");
1184 } else if (GetLastError() == ERROR_IO_PENDING) {
1185 DEBUG("Waiting for read to complete");
1186 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1187 RETURN_FAIL("GetOverlappedResult() failed");
1188 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1190 RETURN_FAIL("ReadFile() failed");
1193 TRY(restart_wait_if_needed(port, bytes_read));
1195 RETURN_INT(bytes_read);
1198 size_t bytes_read = 0;
1199 unsigned char *ptr = (unsigned char *) buf;
1200 struct timeout timeout;
1204 timeout_start(&timeout, timeout_ms);
1207 FD_SET(port->fd, &fds);
1209 /* Loop until we have the requested number of bytes. */
1210 while (bytes_read < count) {
1212 if (timeout_check(&timeout))
1213 /* Timeout has expired. */
1216 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1218 timeout_update(&timeout);
1221 if (errno == EINTR) {
1222 DEBUG("select() call was interrupted, repeating");
1225 RETURN_FAIL("select() failed");
1227 } else if (result == 0) {
1228 /* Timeout has expired. */
1233 result = read(port->fd, ptr, count - bytes_read);
1236 if (errno == EAGAIN)
1238 * This shouldn't happen because we did a
1239 * select() first, but handle anyway.
1243 /* This is an actual failure. */
1244 RETURN_FAIL("read() failed");
1247 bytes_read += result;
1251 if (bytes_read < count)
1252 DEBUG("Read timed out");
1254 RETURN_INT(bytes_read);
1258 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1259 size_t count, unsigned int timeout_ms)
1261 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1266 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1269 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1272 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1273 count, port->name, timeout_ms);
1275 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1279 DWORD bytes_read = 0;
1281 /* If timeout_ms == 0, set maximum timeout. */
1282 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1285 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1286 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1287 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1288 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1289 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1290 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1291 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1292 RETURN_FAIL("SetCommTimeouts() failed");
1295 /* Loop until we have at least one byte, or timeout is reached. */
1296 while (bytes_read == 0) {
1298 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1299 DEBUG("Read completed immediately");
1300 } else if (GetLastError() == ERROR_IO_PENDING) {
1301 DEBUG("Waiting for read to complete");
1302 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1303 RETURN_FAIL("GetOverlappedResult() failed");
1304 if (bytes_read > 0) {
1305 DEBUG("Read completed");
1306 } else if (timeout_ms > 0) {
1307 DEBUG("Read timed out");
1310 DEBUG("Restarting read");
1313 RETURN_FAIL("ReadFile() failed");
1317 TRY(restart_wait_if_needed(port, bytes_read));
1319 RETURN_INT(bytes_read);
1322 size_t bytes_read = 0;
1323 struct timeout timeout;
1327 timeout_start(&timeout, timeout_ms);
1330 FD_SET(port->fd, &fds);
1332 /* Loop until we have at least one byte, or timeout is reached. */
1333 while (bytes_read == 0) {
1335 if (timeout_check(&timeout))
1336 /* Timeout has expired. */
1339 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1341 timeout_update(&timeout);
1344 if (errno == EINTR) {
1345 DEBUG("select() call was interrupted, repeating");
1348 RETURN_FAIL("select() failed");
1350 } else if (result == 0) {
1351 /* Timeout has expired. */
1356 result = read(port->fd, buf, count);
1359 if (errno == EAGAIN)
1360 /* This shouldn't happen because we did a select() first, but handle anyway. */
1363 /* This is an actual failure. */
1364 RETURN_FAIL("read() failed");
1367 bytes_read = result;
1370 if (bytes_read == 0)
1371 DEBUG("Read timed out");
1373 RETURN_INT(bytes_read);
1377 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1380 TRACE("%p, %p, %d", port, buf, count);
1385 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1387 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1393 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1394 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1395 port->timeouts.ReadTotalTimeoutConstant != 0) {
1396 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1397 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1398 port->timeouts.ReadTotalTimeoutConstant = 0;
1399 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1400 RETURN_FAIL("SetCommTimeouts() failed");
1404 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1405 if (GetLastError() != ERROR_IO_PENDING)
1406 RETURN_FAIL("ReadFile() failed");
1408 /* Get number of bytes read. */
1409 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1410 RETURN_FAIL("GetOverlappedResult() failed");
1412 TRY(restart_wait_if_needed(port, bytes_read));
1414 RETURN_INT(bytes_read);
1418 /* Returns the number of bytes read, or -1 upon failure. */
1419 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1420 if (errno == EAGAIN)
1421 /* No bytes available. */
1424 /* This is an actual failure. */
1425 RETURN_FAIL("read() failed");
1427 RETURN_INT(bytes_read);
1431 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1437 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1443 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1444 RETURN_FAIL("ClearCommError() failed");
1445 RETURN_INT(comstat.cbInQue);
1448 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1449 RETURN_FAIL("TIOCINQ ioctl failed");
1450 RETURN_INT(bytes_waiting);
1454 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1460 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1466 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1467 RETURN_FAIL("ClearCommError() failed");
1468 RETURN_INT(comstat.cbOutQue);
1471 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1472 RETURN_FAIL("TIOCOUTQ ioctl failed");
1473 RETURN_INT(bytes_waiting);
1477 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1479 struct sp_event_set *result;
1481 TRACE("%p", result_ptr);
1484 RETURN_ERROR(SP_ERR_ARG, "Null result");
1488 if (!(result = malloc(sizeof(struct sp_event_set))))
1489 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1491 memset(result, 0, sizeof(struct sp_event_set));
1493 *result_ptr = result;
1498 static enum sp_return add_handle(struct sp_event_set *event_set,
1499 event_handle handle, enum sp_event mask)
1502 enum sp_event *new_masks;
1504 TRACE("%p, %d, %d", event_set, handle, mask);
1506 if (!(new_handles = realloc(event_set->handles,
1507 sizeof(event_handle) * (event_set->count + 1))))
1508 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1510 event_set->handles = new_handles;
1512 if (!(new_masks = realloc(event_set->masks,
1513 sizeof(enum sp_event) * (event_set->count + 1))))
1514 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1516 event_set->masks = new_masks;
1518 ((event_handle *) event_set->handles)[event_set->count] = handle;
1519 event_set->masks[event_set->count] = mask;
1526 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1527 const struct sp_port *port, enum sp_event mask)
1529 TRACE("%p, %p, %d", event_set, port, mask);
1532 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1535 RETURN_ERROR(SP_ERR_ARG, "Null port");
1537 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1538 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1544 enum sp_event handle_mask;
1545 if ((handle_mask = mask & SP_EVENT_TX_READY))
1546 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1547 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1548 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1550 TRY(add_handle(event_set, port->fd, mask));
1556 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1558 TRACE("%p", event_set);
1561 DEBUG("Null event set");
1565 DEBUG("Freeing event set");
1567 if (event_set->handles)
1568 free(event_set->handles);
1569 if (event_set->masks)
1570 free(event_set->masks);
1577 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1578 unsigned int timeout_ms)
1580 TRACE("%p, %d", event_set, timeout_ms);
1583 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1586 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1587 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1588 RETURN_FAIL("WaitForMultipleObjects() failed");
1592 struct timeout timeout;
1594 struct pollfd *pollfds;
1597 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1598 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1600 for (i = 0; i < event_set->count; i++) {
1601 pollfds[i].fd = ((int *)event_set->handles)[i];
1602 pollfds[i].events = 0;
1603 pollfds[i].revents = 0;
1604 if (event_set->masks[i] & SP_EVENT_RX_READY)
1605 pollfds[i].events |= POLLIN;
1606 if (event_set->masks[i] & SP_EVENT_TX_READY)
1607 pollfds[i].events |= POLLOUT;
1608 if (event_set->masks[i] & SP_EVENT_ERROR)
1609 pollfds[i].events |= POLLERR;
1612 timeout_start(&timeout, timeout_ms);
1613 timeout_limit(&timeout, INT_MAX);
1615 /* Loop until an event occurs. */
1618 if (timeout_check(&timeout)) {
1619 DEBUG("Wait timed out");
1623 result = poll(pollfds, event_set->count, timeout_remaining_ms(&timeout) || -1);
1625 timeout_update(&timeout);
1628 if (errno == EINTR) {
1629 DEBUG("poll() call was interrupted, repeating");
1633 RETURN_FAIL("poll() failed");
1635 } else if (result == 0) {
1636 DEBUG("poll() timed out");
1637 if (!timeout.overflow)
1640 DEBUG("poll() completed");
1650 #ifdef USE_TERMIOS_SPEED
1651 static enum sp_return get_baudrate(int fd, int *baudrate)
1655 TRACE("%d, %p", fd, baudrate);
1657 DEBUG("Getting baud rate");
1659 if (!(data = malloc(get_termios_size())))
1660 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1662 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1664 RETURN_FAIL("Getting termios failed");
1667 *baudrate = get_termios_speed(data);
1674 static enum sp_return set_baudrate(int fd, int baudrate)
1678 TRACE("%d, %d", fd, baudrate);
1680 DEBUG("Getting baud rate");
1682 if (!(data = malloc(get_termios_size())))
1683 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1685 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1687 RETURN_FAIL("Getting termios failed");
1690 DEBUG("Setting baud rate");
1692 set_termios_speed(data, baudrate);
1694 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1696 RETURN_FAIL("Setting termios failed");
1703 #endif /* USE_TERMIOS_SPEED */
1706 static enum sp_return get_flow(int fd, struct port_data *data)
1710 TRACE("%d, %p", fd, data);
1712 DEBUG("Getting advanced flow control");
1714 if (!(termx = malloc(get_termiox_size())))
1715 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1717 if (ioctl(fd, TCGETX, termx) < 0) {
1719 RETURN_FAIL("Getting termiox failed");
1722 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1723 &data->dtr_flow, &data->dsr_flow);
1730 static enum sp_return set_flow(int fd, struct port_data *data)
1734 TRACE("%d, %p", fd, data);
1736 DEBUG("Getting advanced flow control");
1738 if (!(termx = malloc(get_termiox_size())))
1739 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1741 if (ioctl(fd, TCGETX, termx) < 0) {
1743 RETURN_FAIL("Getting termiox failed");
1746 DEBUG("Setting advanced flow control");
1748 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1749 data->dtr_flow, data->dsr_flow);
1751 if (ioctl(fd, TCSETX, termx) < 0) {
1753 RETURN_FAIL("Setting termiox failed");
1760 #endif /* USE_TERMIOX */
1762 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1763 struct sp_port_config *config)
1767 TRACE("%p, %p, %p", port, data, config);
1769 DEBUG_FMT("Getting configuration for port %s", port->name);
1772 if (!GetCommState(port->hdl, &data->dcb))
1773 RETURN_FAIL("GetCommState() failed");
1775 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1776 if (data->dcb.BaudRate == std_baudrates[i].index) {
1777 config->baudrate = std_baudrates[i].value;
1782 if (i == NUM_STD_BAUDRATES)
1783 /* BaudRate field can be either an index or a custom baud rate. */
1784 config->baudrate = data->dcb.BaudRate;
1786 config->bits = data->dcb.ByteSize;
1788 if (data->dcb.fParity)
1789 switch (data->dcb.Parity) {
1791 config->parity = SP_PARITY_NONE;
1794 config->parity = SP_PARITY_ODD;
1797 config->parity = SP_PARITY_EVEN;
1800 config->parity = SP_PARITY_MARK;
1803 config->parity = SP_PARITY_SPACE;
1806 config->parity = -1;
1809 config->parity = SP_PARITY_NONE;
1811 switch (data->dcb.StopBits) {
1813 config->stopbits = 1;
1816 config->stopbits = 2;
1819 config->stopbits = -1;
1822 switch (data->dcb.fRtsControl) {
1823 case RTS_CONTROL_DISABLE:
1824 config->rts = SP_RTS_OFF;
1826 case RTS_CONTROL_ENABLE:
1827 config->rts = SP_RTS_ON;
1829 case RTS_CONTROL_HANDSHAKE:
1830 config->rts = SP_RTS_FLOW_CONTROL;
1836 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1838 switch (data->dcb.fDtrControl) {
1839 case DTR_CONTROL_DISABLE:
1840 config->dtr = SP_DTR_OFF;
1842 case DTR_CONTROL_ENABLE:
1843 config->dtr = SP_DTR_ON;
1845 case DTR_CONTROL_HANDSHAKE:
1846 config->dtr = SP_DTR_FLOW_CONTROL;
1852 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1854 if (data->dcb.fInX) {
1855 if (data->dcb.fOutX)
1856 config->xon_xoff = SP_XONXOFF_INOUT;
1858 config->xon_xoff = SP_XONXOFF_IN;
1860 if (data->dcb.fOutX)
1861 config->xon_xoff = SP_XONXOFF_OUT;
1863 config->xon_xoff = SP_XONXOFF_DISABLED;
1868 if (tcgetattr(port->fd, &data->term) < 0)
1869 RETURN_FAIL("tcgetattr() failed");
1871 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1872 RETURN_FAIL("TIOCMGET ioctl failed");
1875 int ret = get_flow(port->fd, data);
1877 if (ret == SP_ERR_FAIL && errno == EINVAL)
1878 data->termiox_supported = 0;
1880 RETURN_CODEVAL(ret);
1882 data->termiox_supported = 1;
1884 data->termiox_supported = 0;
1887 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1888 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1889 config->baudrate = std_baudrates[i].value;
1894 if (i == NUM_STD_BAUDRATES) {
1896 config->baudrate = (int)data->term.c_ispeed;
1897 #elif defined(USE_TERMIOS_SPEED)
1898 TRY(get_baudrate(port->fd, &config->baudrate));
1900 config->baudrate = -1;
1904 switch (data->term.c_cflag & CSIZE) {
1921 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1922 config->parity = SP_PARITY_NONE;
1923 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1924 config->parity = -1;
1926 else if (data->term.c_cflag & CMSPAR)
1927 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1930 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1932 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1934 if (data->term.c_cflag & CRTSCTS) {
1935 config->rts = SP_RTS_FLOW_CONTROL;
1936 config->cts = SP_CTS_FLOW_CONTROL;
1938 if (data->termiox_supported && data->rts_flow)
1939 config->rts = SP_RTS_FLOW_CONTROL;
1941 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1943 config->cts = (data->termiox_supported && data->cts_flow) ?
1944 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1947 if (data->termiox_supported && data->dtr_flow)
1948 config->dtr = SP_DTR_FLOW_CONTROL;
1950 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1952 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1953 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1955 if (data->term.c_iflag & IXOFF) {
1956 if (data->term.c_iflag & IXON)
1957 config->xon_xoff = SP_XONXOFF_INOUT;
1959 config->xon_xoff = SP_XONXOFF_IN;
1961 if (data->term.c_iflag & IXON)
1962 config->xon_xoff = SP_XONXOFF_OUT;
1964 config->xon_xoff = SP_XONXOFF_DISABLED;
1971 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1972 const struct sp_port_config *config)
1976 BAUD_TYPE baud_nonstd;
1980 #ifdef USE_TERMIOS_SPEED
1981 int baud_nonstd = 0;
1984 TRACE("%p, %p, %p", port, data, config);
1986 DEBUG_FMT("Setting configuration for port %s", port->name);
1990 TRY(await_write_completion(port));
1992 if (config->baudrate >= 0) {
1993 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1994 if (config->baudrate == std_baudrates[i].value) {
1995 data->dcb.BaudRate = std_baudrates[i].index;
2000 if (i == NUM_STD_BAUDRATES)
2001 data->dcb.BaudRate = config->baudrate;
2003 /* Allocate write buffer for 50ms of data at baud rate. */
2004 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
2005 port->write_buf = realloc(port->write_buf,
2006 port->write_buf_size);
2008 if (!port->write_buf)
2009 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
2012 if (config->bits >= 0)
2013 data->dcb.ByteSize = config->bits;
2015 if (config->parity >= 0) {
2016 switch (config->parity) {
2017 case SP_PARITY_NONE:
2018 data->dcb.Parity = NOPARITY;
2021 data->dcb.Parity = ODDPARITY;
2023 case SP_PARITY_EVEN:
2024 data->dcb.Parity = EVENPARITY;
2026 case SP_PARITY_MARK:
2027 data->dcb.Parity = MARKPARITY;
2029 case SP_PARITY_SPACE:
2030 data->dcb.Parity = SPACEPARITY;
2033 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2037 if (config->stopbits >= 0) {
2038 switch (config->stopbits) {
2039 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
2041 data->dcb.StopBits = ONESTOPBIT;
2044 data->dcb.StopBits = TWOSTOPBITS;
2047 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
2051 if (config->rts >= 0) {
2052 switch (config->rts) {
2054 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
2057 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
2059 case SP_RTS_FLOW_CONTROL:
2060 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
2063 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
2067 if (config->cts >= 0) {
2068 switch (config->cts) {
2070 data->dcb.fOutxCtsFlow = FALSE;
2072 case SP_CTS_FLOW_CONTROL:
2073 data->dcb.fOutxCtsFlow = TRUE;
2076 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
2080 if (config->dtr >= 0) {
2081 switch (config->dtr) {
2083 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
2086 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
2088 case SP_DTR_FLOW_CONTROL:
2089 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
2092 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
2096 if (config->dsr >= 0) {
2097 switch (config->dsr) {
2099 data->dcb.fOutxDsrFlow = FALSE;
2101 case SP_DSR_FLOW_CONTROL:
2102 data->dcb.fOutxDsrFlow = TRUE;
2105 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2109 if (config->xon_xoff >= 0) {
2110 switch (config->xon_xoff) {
2111 case SP_XONXOFF_DISABLED:
2112 data->dcb.fInX = FALSE;
2113 data->dcb.fOutX = FALSE;
2116 data->dcb.fInX = TRUE;
2117 data->dcb.fOutX = FALSE;
2119 case SP_XONXOFF_OUT:
2120 data->dcb.fInX = FALSE;
2121 data->dcb.fOutX = TRUE;
2123 case SP_XONXOFF_INOUT:
2124 data->dcb.fInX = TRUE;
2125 data->dcb.fOutX = TRUE;
2128 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2132 if (!SetCommState(port->hdl, &data->dcb))
2133 RETURN_FAIL("SetCommState() failed");
2139 if (config->baudrate >= 0) {
2140 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2141 if (config->baudrate == std_baudrates[i].value) {
2142 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2143 RETURN_FAIL("cfsetospeed() failed");
2145 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2146 RETURN_FAIL("cfsetispeed() failed");
2151 /* Non-standard baud rate */
2152 if (i == NUM_STD_BAUDRATES) {
2154 /* Set "dummy" baud rate. */
2155 if (cfsetspeed(&data->term, B9600) < 0)
2156 RETURN_FAIL("cfsetspeed() failed");
2157 baud_nonstd = config->baudrate;
2158 #elif defined(USE_TERMIOS_SPEED)
2161 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2166 if (config->bits >= 0) {
2167 data->term.c_cflag &= ~CSIZE;
2168 switch (config->bits) {
2170 data->term.c_cflag |= CS8;
2173 data->term.c_cflag |= CS7;
2176 data->term.c_cflag |= CS6;
2179 data->term.c_cflag |= CS5;
2182 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2186 if (config->parity >= 0) {
2187 data->term.c_iflag &= ~IGNPAR;
2188 data->term.c_cflag &= ~(PARENB | PARODD);
2190 data->term.c_cflag &= ~CMSPAR;
2192 switch (config->parity) {
2193 case SP_PARITY_NONE:
2194 data->term.c_iflag |= IGNPAR;
2196 case SP_PARITY_EVEN:
2197 data->term.c_cflag |= PARENB;
2200 data->term.c_cflag |= PARENB | PARODD;
2203 case SP_PARITY_MARK:
2204 data->term.c_cflag |= PARENB | PARODD;
2205 data->term.c_cflag |= CMSPAR;
2207 case SP_PARITY_SPACE:
2208 data->term.c_cflag |= PARENB;
2209 data->term.c_cflag |= CMSPAR;
2212 case SP_PARITY_MARK:
2213 case SP_PARITY_SPACE:
2214 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2217 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2221 if (config->stopbits >= 0) {
2222 data->term.c_cflag &= ~CSTOPB;
2223 switch (config->stopbits) {
2225 data->term.c_cflag &= ~CSTOPB;
2228 data->term.c_cflag |= CSTOPB;
2231 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2235 if (config->rts >= 0 || config->cts >= 0) {
2236 if (data->termiox_supported) {
2237 data->rts_flow = data->cts_flow = 0;
2238 switch (config->rts) {
2241 controlbits = TIOCM_RTS;
2242 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2243 RETURN_FAIL("Setting RTS signal level failed");
2245 case SP_RTS_FLOW_CONTROL:
2251 if (config->cts == SP_CTS_FLOW_CONTROL)
2254 if (data->rts_flow && data->cts_flow)
2255 data->term.c_iflag |= CRTSCTS;
2257 data->term.c_iflag &= ~CRTSCTS;
2259 /* Asymmetric use of RTS/CTS not supported. */
2260 if (data->term.c_iflag & CRTSCTS) {
2261 /* Flow control can only be disabled for both RTS & CTS together. */
2262 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2263 if (config->cts != SP_CTS_IGNORE)
2264 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2266 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2267 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2268 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2271 /* Flow control can only be enabled for both RTS & CTS together. */
2272 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2273 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2274 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2277 if (config->rts >= 0) {
2278 if (config->rts == SP_RTS_FLOW_CONTROL) {
2279 data->term.c_iflag |= CRTSCTS;
2281 controlbits = TIOCM_RTS;
2282 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2284 RETURN_FAIL("Setting RTS signal level failed");
2290 if (config->dtr >= 0 || config->dsr >= 0) {
2291 if (data->termiox_supported) {
2292 data->dtr_flow = data->dsr_flow = 0;
2293 switch (config->dtr) {
2296 controlbits = TIOCM_DTR;
2297 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2298 RETURN_FAIL("Setting DTR signal level failed");
2300 case SP_DTR_FLOW_CONTROL:
2306 if (config->dsr == SP_DSR_FLOW_CONTROL)
2309 /* DTR/DSR flow control not supported. */
2310 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2311 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2313 if (config->dtr >= 0) {
2314 controlbits = TIOCM_DTR;
2315 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2317 RETURN_FAIL("Setting DTR signal level failed");
2322 if (config->xon_xoff >= 0) {
2323 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2324 switch (config->xon_xoff) {
2325 case SP_XONXOFF_DISABLED:
2328 data->term.c_iflag |= IXOFF;
2330 case SP_XONXOFF_OUT:
2331 data->term.c_iflag |= IXON | IXANY;
2333 case SP_XONXOFF_INOUT:
2334 data->term.c_iflag |= IXON | IXOFF | IXANY;
2337 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2341 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2342 RETURN_FAIL("tcsetattr() failed");
2345 if (baud_nonstd != B0) {
2346 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2347 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2349 * Set baud rates in data->term to correct, but incompatible
2350 * with tcsetattr() value, same as delivered by tcgetattr().
2352 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2353 RETURN_FAIL("cfsetspeed() failed");
2355 #elif defined(__linux__)
2356 #ifdef USE_TERMIOS_SPEED
2358 TRY(set_baudrate(port->fd, config->baudrate));
2361 if (data->termiox_supported)
2362 TRY(set_flow(port->fd, data));
2366 #endif /* !_WIN32 */
2371 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2373 struct sp_port_config *config;
2375 TRACE("%p", config_ptr);
2378 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2382 if (!(config = malloc(sizeof(struct sp_port_config))))
2383 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2385 config->baudrate = -1;
2387 config->parity = -1;
2388 config->stopbits = -1;
2394 *config_ptr = config;
2399 SP_API void sp_free_config(struct sp_port_config *config)
2401 TRACE("%p", config);
2404 DEBUG("Null config");
2411 SP_API enum sp_return sp_get_config(struct sp_port *port,
2412 struct sp_port_config *config)
2414 struct port_data data;
2416 TRACE("%p, %p", port, config);
2421 RETURN_ERROR(SP_ERR_ARG, "Null config");
2423 TRY(get_config(port, &data, config));
2428 SP_API enum sp_return sp_set_config(struct sp_port *port,
2429 const struct sp_port_config *config)
2431 struct port_data data;
2432 struct sp_port_config prev_config;
2434 TRACE("%p, %p", port, config);
2439 RETURN_ERROR(SP_ERR_ARG, "Null config");
2441 TRY(get_config(port, &data, &prev_config));
2442 TRY(set_config(port, &data, config));
2447 #define CREATE_ACCESSORS(x, type) \
2448 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2449 struct port_data data; \
2450 struct sp_port_config config; \
2451 TRACE("%p, %d", port, x); \
2452 CHECK_OPEN_PORT(); \
2453 TRY(get_config(port, &data, &config)); \
2455 TRY(set_config(port, &data, &config)); \
2458 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2460 TRACE("%p, %p", config, x); \
2462 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2464 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2468 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2470 TRACE("%p, %d", config, x); \
2472 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2477 CREATE_ACCESSORS(baudrate, int)
2478 CREATE_ACCESSORS(bits, int)
2479 CREATE_ACCESSORS(parity, enum sp_parity)
2480 CREATE_ACCESSORS(stopbits, int)
2481 CREATE_ACCESSORS(rts, enum sp_rts)
2482 CREATE_ACCESSORS(cts, enum sp_cts)
2483 CREATE_ACCESSORS(dtr, enum sp_dtr)
2484 CREATE_ACCESSORS(dsr, enum sp_dsr)
2485 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2487 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2488 enum sp_flowcontrol flowcontrol)
2491 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2493 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2494 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2496 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2497 config->xon_xoff = SP_XONXOFF_INOUT;
2499 config->xon_xoff = SP_XONXOFF_DISABLED;
2501 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2502 config->rts = SP_RTS_FLOW_CONTROL;
2503 config->cts = SP_CTS_FLOW_CONTROL;
2505 if (config->rts == SP_RTS_FLOW_CONTROL)
2506 config->rts = SP_RTS_ON;
2507 config->cts = SP_CTS_IGNORE;
2510 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2511 config->dtr = SP_DTR_FLOW_CONTROL;
2512 config->dsr = SP_DSR_FLOW_CONTROL;
2514 if (config->dtr == SP_DTR_FLOW_CONTROL)
2515 config->dtr = SP_DTR_ON;
2516 config->dsr = SP_DSR_IGNORE;
2522 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2523 enum sp_flowcontrol flowcontrol)
2525 struct port_data data;
2526 struct sp_port_config config;
2528 TRACE("%p, %d", port, flowcontrol);
2532 TRY(get_config(port, &data, &config));
2534 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2536 TRY(set_config(port, &data, &config));
2541 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2542 enum sp_signal *signals)
2544 TRACE("%p, %p", port, signals);
2549 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2551 DEBUG_FMT("Getting control signals for port %s", port->name);
2556 if (GetCommModemStatus(port->hdl, &bits) == 0)
2557 RETURN_FAIL("GetCommModemStatus() failed");
2558 if (bits & MS_CTS_ON)
2559 *signals |= SP_SIG_CTS;
2560 if (bits & MS_DSR_ON)
2561 *signals |= SP_SIG_DSR;
2562 if (bits & MS_RLSD_ON)
2563 *signals |= SP_SIG_DCD;
2564 if (bits & MS_RING_ON)
2565 *signals |= SP_SIG_RI;
2568 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2569 RETURN_FAIL("TIOCMGET ioctl failed");
2570 if (bits & TIOCM_CTS)
2571 *signals |= SP_SIG_CTS;
2572 if (bits & TIOCM_DSR)
2573 *signals |= SP_SIG_DSR;
2574 if (bits & TIOCM_CAR)
2575 *signals |= SP_SIG_DCD;
2576 if (bits & TIOCM_RNG)
2577 *signals |= SP_SIG_RI;
2582 SP_API enum sp_return sp_start_break(struct sp_port *port)
2588 if (SetCommBreak(port->hdl) == 0)
2589 RETURN_FAIL("SetCommBreak() failed");
2591 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2592 RETURN_FAIL("TIOCSBRK ioctl failed");
2598 SP_API enum sp_return sp_end_break(struct sp_port *port)
2604 if (ClearCommBreak(port->hdl) == 0)
2605 RETURN_FAIL("ClearCommBreak() failed");
2607 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2608 RETURN_FAIL("TIOCCBRK ioctl failed");
2614 SP_API int sp_last_error_code(void)
2618 RETURN_INT(GetLastError());
2624 SP_API char *sp_last_error_message(void)
2630 DWORD error = GetLastError();
2632 DWORD length = FormatMessage(
2633 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2634 FORMAT_MESSAGE_FROM_SYSTEM |
2635 FORMAT_MESSAGE_IGNORE_INSERTS,
2638 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2642 if (length >= 2 && message[length - 2] == '\r')
2643 message[length - 2] = '\0';
2645 RETURN_STRING(message);
2647 RETURN_STRING(strerror(errno));
2651 SP_API void sp_free_error_message(char *message)
2653 TRACE("%s", message);
2664 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2666 TRACE("%p", handler);
2668 sp_debug_handler = handler;
2673 SP_API void sp_default_debug_handler(const char *format, ...)
2676 va_start(args, format);
2677 if (getenv("LIBSERIALPORT_DEBUG")) {
2678 fputs("sp: ", stderr);
2679 vfprintf(stderr, format, args);
2684 SP_API int sp_get_major_package_version(void)
2686 return SP_PACKAGE_VERSION_MAJOR;
2689 SP_API int sp_get_minor_package_version(void)
2691 return SP_PACKAGE_VERSION_MINOR;
2694 SP_API int sp_get_micro_package_version(void)
2696 return SP_PACKAGE_VERSION_MICRO;
2699 SP_API const char *sp_get_package_version_string(void)
2701 return SP_PACKAGE_VERSION_STRING;
2704 SP_API int sp_get_current_lib_version(void)
2706 return SP_LIB_VERSION_CURRENT;
2709 SP_API int sp_get_revision_lib_version(void)
2711 return SP_LIB_VERSION_REVISION;
2714 SP_API int sp_get_age_lib_version(void)
2716 return SP_LIB_VERSION_AGE;
2719 SP_API const char *sp_get_lib_version_string(void)
2721 return SP_LIB_VERSION_STRING;