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;
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;
178 static void timeout_limit(struct timeout *timeout, unsigned int limit_ms)
180 timeout->limit_ms = limit_ms;
181 timeout->overflow = (timeout->ms > timeout->limit_ms);
182 time_set_ms(&timeout->delta_max, timeout->limit_ms);
185 static bool timeout_check(struct timeout *timeout)
187 if (timeout->ms == 0)
190 time_get(&timeout->now);
191 time_sub(&timeout->end, &timeout->now, &timeout->delta);
192 if (timeout->limit_ms)
193 if ((timeout->overflow = time_greater(&timeout->delta, &timeout->delta_max)))
194 timeout->delta = timeout->delta_max;
196 return time_greater(&timeout->now, &timeout->end);
200 static struct timeval *timeout_timeval(struct timeout *timeout)
202 if (timeout->ms == 0)
205 time_as_timeval(&timeout->delta, &timeout->delta_tv);
207 return &timeout->delta_tv;
211 static unsigned int timeout_remaining_ms(struct timeout *timeout)
213 if (timeout->limit_ms && timeout->overflow)
214 return timeout->limit_ms;
216 return time_as_ms(&timeout->delta);
219 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
221 struct sp_port *port;
222 #ifndef NO_PORT_METADATA
227 TRACE("%s, %p", portname, port_ptr);
230 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
235 RETURN_ERROR(SP_ERR_ARG, "Null port name");
237 DEBUG_FMT("Building structure for port %s", portname);
239 #if !defined(_WIN32) && defined(HAVE_REALPATH)
241 * get_port_details() below tries to be too smart and figure out
242 * some transport properties from the port name which breaks with
243 * symlinks. Therefore we canonicalize the portname first.
245 char pathbuf[PATH_MAX + 1];
246 char *res = realpath(portname, pathbuf);
248 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
253 if (!(port = malloc(sizeof(struct sp_port))))
254 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
256 len = strlen(portname) + 1;
258 if (!(port->name = malloc(len))) {
260 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
263 memcpy(port->name, portname, len);
266 port->usb_path = NULL;
267 port->hdl = INVALID_HANDLE_VALUE;
268 port->write_buf = NULL;
269 port->write_buf_size = 0;
274 port->description = NULL;
275 port->transport = SP_TRANSPORT_NATIVE;
277 port->usb_address = -1;
280 port->usb_manufacturer = NULL;
281 port->usb_product = NULL;
282 port->usb_serial = NULL;
283 port->bluetooth_address = NULL;
285 #ifndef NO_PORT_METADATA
286 if ((ret = get_port_details(port)) != SP_OK) {
297 SP_API char *sp_get_port_name(const struct sp_port *port)
304 RETURN_STRING(port->name);
307 SP_API char *sp_get_port_description(const struct sp_port *port)
311 if (!port || !port->description)
314 RETURN_STRING(port->description);
317 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
322 RETURN_ERROR(SP_ERR_ARG, "Null port");
324 RETURN_INT(port->transport);
327 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
328 int *usb_bus,int *usb_address)
333 RETURN_ERROR(SP_ERR_ARG, "Null port");
334 if (port->transport != SP_TRANSPORT_USB)
335 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
336 if (port->usb_bus < 0 || port->usb_address < 0)
337 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
340 *usb_bus = port->usb_bus;
342 *usb_address = port->usb_address;
347 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
348 int *usb_vid, int *usb_pid)
353 RETURN_ERROR(SP_ERR_ARG, "Null port");
354 if (port->transport != SP_TRANSPORT_USB)
355 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
356 if (port->usb_vid < 0 || port->usb_pid < 0)
357 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
360 *usb_vid = port->usb_vid;
362 *usb_pid = port->usb_pid;
367 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
371 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
374 RETURN_STRING(port->usb_manufacturer);
377 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
381 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
384 RETURN_STRING(port->usb_product);
387 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
391 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
394 RETURN_STRING(port->usb_serial);
397 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
401 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
402 || !port->bluetooth_address)
405 RETURN_STRING(port->bluetooth_address);
408 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
411 TRACE("%p, %p", port, result_ptr);
414 RETURN_ERROR(SP_ERR_ARG, "Null port");
416 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
419 HANDLE *handle_ptr = result_ptr;
420 *handle_ptr = port->hdl;
422 int *fd_ptr = result_ptr;
429 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
430 struct sp_port **copy_ptr)
432 TRACE("%p, %p", port, copy_ptr);
435 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
440 RETURN_ERROR(SP_ERR_ARG, "Null port");
443 RETURN_ERROR(SP_ERR_ARG, "Null port name");
445 DEBUG("Copying port structure");
447 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
450 SP_API void sp_free_port(struct sp_port *port)
459 DEBUG("Freeing port structure");
463 if (port->description)
464 free(port->description);
465 if (port->usb_manufacturer)
466 free(port->usb_manufacturer);
467 if (port->usb_product)
468 free(port->usb_product);
469 if (port->usb_serial)
470 free(port->usb_serial);
471 if (port->bluetooth_address)
472 free(port->bluetooth_address);
475 free(port->usb_path);
477 free(port->write_buf);
485 SP_PRIV struct sp_port **list_append(struct sp_port **list,
486 const char *portname)
491 for (count = 0; list[count]; count++)
493 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
496 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
498 list[count + 1] = NULL;
502 sp_free_port_list(list);
506 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
508 #ifndef NO_ENUMERATION
509 struct sp_port **list;
513 TRACE("%p", list_ptr);
516 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
520 #ifdef NO_ENUMERATION
521 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
523 DEBUG("Enumerating ports");
525 if (!(list = malloc(sizeof(struct sp_port *))))
526 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
530 ret = list_ports(&list);
535 sp_free_port_list(list);
543 SP_API void sp_free_port_list(struct sp_port **list)
554 DEBUG("Freeing port list");
556 for (i = 0; list[i]; i++)
557 sp_free_port(list[i]);
563 #define CHECK_PORT() do { \
565 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
567 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
570 #define CHECK_PORT_HANDLE() do { \
571 if (port->hdl == INVALID_HANDLE_VALUE) \
572 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
575 #define CHECK_PORT_HANDLE() do { \
577 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
580 #define CHECK_OPEN_PORT() do { \
582 CHECK_PORT_HANDLE(); \
586 /** To be called after port receive buffer is emptied. */
587 static enum sp_return restart_wait(struct sp_port *port)
591 if (port->wait_running) {
592 /* Check status of running wait operation. */
593 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
594 &wait_result, FALSE)) {
595 DEBUG("Previous wait completed");
596 port->wait_running = FALSE;
597 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
598 DEBUG("Previous wait still running");
601 RETURN_FAIL("GetOverlappedResult() failed");
605 if (!port->wait_running) {
606 /* Start new wait operation. */
607 if (WaitCommEvent(port->hdl, &port->events,
609 DEBUG("New wait returned, events already pending");
610 } else if (GetLastError() == ERROR_IO_PENDING) {
611 DEBUG("New wait running in background");
612 port->wait_running = TRUE;
614 RETURN_FAIL("WaitCommEvent() failed");
622 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
624 struct port_data data;
625 struct sp_port_config config;
628 TRACE("%p, 0x%x", port, flags);
632 if (flags > SP_MODE_READ_WRITE)
633 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
635 DEBUG_FMT("Opening port %s", port->name);
638 DWORD desired_access = 0, flags_and_attributes = 0, errors;
639 char *escaped_port_name;
642 /* Prefix port name with '\\.\' to work with ports above COM9. */
643 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
644 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
645 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
647 /* Map 'flags' to the OS-specific settings. */
648 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
649 if (flags & SP_MODE_READ)
650 desired_access |= GENERIC_READ;
651 if (flags & SP_MODE_WRITE)
652 desired_access |= GENERIC_WRITE;
654 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
655 OPEN_EXISTING, flags_and_attributes, 0);
657 free(escaped_port_name);
659 if (port->hdl == INVALID_HANDLE_VALUE)
660 RETURN_FAIL("Port CreateFile() failed");
662 /* All timeouts initially disabled. */
663 port->timeouts.ReadIntervalTimeout = 0;
664 port->timeouts.ReadTotalTimeoutMultiplier = 0;
665 port->timeouts.ReadTotalTimeoutConstant = 0;
666 port->timeouts.WriteTotalTimeoutMultiplier = 0;
667 port->timeouts.WriteTotalTimeoutConstant = 0;
669 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
671 RETURN_FAIL("SetCommTimeouts() failed");
674 /* Prepare OVERLAPPED structures. */
675 #define INIT_OVERLAPPED(ovl) do { \
676 memset(&port->ovl, 0, sizeof(port->ovl)); \
677 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
678 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
679 == INVALID_HANDLE_VALUE) { \
681 RETURN_FAIL(#ovl "CreateEvent() failed"); \
685 INIT_OVERLAPPED(read_ovl);
686 INIT_OVERLAPPED(write_ovl);
687 INIT_OVERLAPPED(wait_ovl);
689 /* Set event mask for RX and error events. */
690 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
692 RETURN_FAIL("SetCommMask() failed");
695 port->writing = FALSE;
696 port->wait_running = FALSE;
698 ret = restart_wait(port);
705 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
707 /* Map 'flags' to the OS-specific settings. */
708 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
709 flags_local |= O_RDWR;
710 else if (flags & SP_MODE_READ)
711 flags_local |= O_RDONLY;
712 else if (flags & SP_MODE_WRITE)
713 flags_local |= O_WRONLY;
715 if ((port->fd = open(port->name, flags_local)) < 0)
716 RETURN_FAIL("open() failed");
719 ret = get_config(port, &data, &config);
726 /* Set sane port settings. */
728 data.dcb.fBinary = TRUE;
729 data.dcb.fDsrSensitivity = FALSE;
730 data.dcb.fErrorChar = FALSE;
731 data.dcb.fNull = FALSE;
732 data.dcb.fAbortOnError = FALSE;
734 /* Turn off all fancy termios tricks, give us a raw channel. */
735 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
737 data.term.c_iflag &= ~IUCLC;
739 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
741 data.term.c_oflag &= ~OLCUC;
744 data.term.c_oflag &= ~NLDLY;
747 data.term.c_oflag &= ~CRDLY;
750 data.term.c_oflag &= ~TABDLY;
753 data.term.c_oflag &= ~BSDLY;
756 data.term.c_oflag &= ~VTDLY;
759 data.term.c_oflag &= ~FFDLY;
762 data.term.c_oflag &= ~OFILL;
764 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
765 data.term.c_cc[VMIN] = 0;
766 data.term.c_cc[VTIME] = 0;
768 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
769 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
773 if (ClearCommError(port->hdl, &errors, &status) == 0)
774 RETURN_FAIL("ClearCommError() failed");
777 ret = set_config(port, &data, &config);
787 SP_API enum sp_return sp_close(struct sp_port *port)
793 DEBUG_FMT("Closing port %s", port->name);
796 /* Returns non-zero upon success, 0 upon failure. */
797 if (CloseHandle(port->hdl) == 0)
798 RETURN_FAIL("Port CloseHandle() failed");
799 port->hdl = INVALID_HANDLE_VALUE;
801 /* Close event handles for overlapped structures. */
802 #define CLOSE_OVERLAPPED(ovl) do { \
803 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
804 CloseHandle(port->ovl.hEvent) == 0) \
805 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
807 CLOSE_OVERLAPPED(read_ovl);
808 CLOSE_OVERLAPPED(write_ovl);
809 CLOSE_OVERLAPPED(wait_ovl);
811 if (port->write_buf) {
812 free(port->write_buf);
813 port->write_buf = NULL;
816 /* Returns 0 upon success, -1 upon failure. */
817 if (close(port->fd) == -1)
818 RETURN_FAIL("close() failed");
825 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
827 TRACE("%p, 0x%x", port, buffers);
831 if (buffers > SP_BUF_BOTH)
832 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
834 const char *buffer_names[] = {"no", "input", "output", "both"};
836 DEBUG_FMT("Flushing %s buffers on port %s",
837 buffer_names[buffers], port->name);
841 if (buffers & SP_BUF_INPUT)
842 flags |= PURGE_RXCLEAR;
843 if (buffers & SP_BUF_OUTPUT)
844 flags |= PURGE_TXCLEAR;
846 /* Returns non-zero upon success, 0 upon failure. */
847 if (PurgeComm(port->hdl, flags) == 0)
848 RETURN_FAIL("PurgeComm() failed");
850 if (buffers & SP_BUF_INPUT)
851 TRY(restart_wait(port));
854 if (buffers == SP_BUF_BOTH)
856 else if (buffers == SP_BUF_INPUT)
858 else if (buffers == SP_BUF_OUTPUT)
861 /* Returns 0 upon success, -1 upon failure. */
862 if (tcflush(port->fd, flags) < 0)
863 RETURN_FAIL("tcflush() failed");
868 SP_API enum sp_return sp_drain(struct sp_port *port)
874 DEBUG_FMT("Draining port %s", port->name);
877 /* Returns non-zero upon success, 0 upon failure. */
878 if (FlushFileBuffers(port->hdl) == 0)
879 RETURN_FAIL("FlushFileBuffers() failed");
884 #if defined(__ANDROID__) && (__ANDROID_API__ < 21)
885 /* Android only has tcdrain from platform 21 onwards.
886 * On previous API versions, use the ioctl directly. */
888 result = ioctl(port->fd, TCSBRK, &arg);
890 result = tcdrain(port->fd);
893 if (errno == EINTR) {
894 DEBUG("tcdrain() was interrupted");
897 RETURN_FAIL("tcdrain() failed");
907 static enum sp_return await_write_completion(struct sp_port *port)
913 /* Wait for previous non-blocking write to complete, if any. */
915 DEBUG("Waiting for previous write to complete");
916 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
919 RETURN_FAIL("Previous write failed to complete");
920 DEBUG("Previous write completed");
927 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
928 size_t count, unsigned int timeout_ms)
930 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
935 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
938 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
939 count, port->name, timeout_ms);
941 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
948 DWORD bytes_written = 0;
950 TRY(await_write_completion(port));
953 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
954 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
955 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
956 RETURN_FAIL("SetCommTimeouts() failed");
959 /* Reduce count if it exceeds the WriteFile limit. */
960 if (count > WRITEFILE_MAX_SIZE)
961 count = WRITEFILE_MAX_SIZE;
964 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
965 DEBUG("Write completed immediately");
967 } else if (GetLastError() == ERROR_IO_PENDING) {
968 DEBUG("Waiting for write to complete");
969 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
970 if (GetLastError() == ERROR_SEM_TIMEOUT) {
971 DEBUG("Write timed out");
974 RETURN_FAIL("GetOverlappedResult() failed");
977 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
978 RETURN_INT(bytes_written);
980 RETURN_FAIL("WriteFile() failed");
983 size_t bytes_written = 0;
984 unsigned char *ptr = (unsigned char *) buf;
985 struct timeout timeout;
990 timeout_start(&timeout, timeout_ms);
993 FD_SET(port->fd, &fds);
995 /* Loop until we have written the requested number of bytes. */
996 while (bytes_written < count) {
998 * Check timeout only if we have run select() at least once,
999 * to avoid any issues if a short timeout is reached before
1000 * select() is even run.
1002 if (started && timeout_check(&timeout))
1005 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
1008 if (errno == EINTR) {
1009 DEBUG("select() call was interrupted, repeating");
1012 RETURN_FAIL("select() failed");
1014 } else if (result == 0) {
1015 /* Timeout has expired. */
1020 result = write(port->fd, ptr, count - bytes_written);
1023 if (errno == EAGAIN)
1024 /* This shouldn't happen because we did a select() first, but handle anyway. */
1027 /* This is an actual failure. */
1028 RETURN_FAIL("write() failed");
1031 bytes_written += result;
1035 if (bytes_written < count)
1036 DEBUG("Write timed out");
1038 RETURN_INT(bytes_written);
1042 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
1043 const void *buf, size_t count)
1045 TRACE("%p, %p, %d", port, buf, count);
1050 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1052 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
1060 /* Check whether previous write is complete. */
1061 if (port->writing) {
1062 if (HasOverlappedIoCompleted(&port->write_ovl)) {
1063 DEBUG("Previous write completed");
1066 DEBUG("Previous write not complete");
1067 /* Can't take a new write until the previous one finishes. */
1073 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
1074 port->timeouts.WriteTotalTimeoutConstant = 0;
1075 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1076 RETURN_FAIL("SetCommTimeouts() failed");
1079 /* Reduce count if it exceeds the WriteFile limit. */
1080 if (count > WRITEFILE_MAX_SIZE)
1081 count = WRITEFILE_MAX_SIZE;
1083 /* Copy data to our write buffer. */
1084 buf_bytes = min(port->write_buf_size, count);
1085 memcpy(port->write_buf, buf, buf_bytes);
1087 /* Start asynchronous write. */
1088 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
1089 if (GetLastError() == ERROR_IO_PENDING) {
1090 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
1091 DEBUG("Asynchronous write completed immediately");
1093 DEBUG("Asynchronous write running");
1095 /* Actual failure of some kind. */
1096 RETURN_FAIL("WriteFile() failed");
1100 DEBUG("All bytes written immediately");
1102 RETURN_INT(buf_bytes);
1104 /* Returns the number of bytes written, or -1 upon failure. */
1105 ssize_t written = write(port->fd, buf, count);
1108 if (errno == EAGAIN)
1109 // Buffer is full, no bytes written.
1112 RETURN_FAIL("write() failed");
1114 RETURN_INT(written);
1120 /* Restart wait operation if buffer was emptied. */
1121 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1126 if (bytes_read == 0)
1129 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1130 RETURN_FAIL("ClearCommError() failed");
1132 if (comstat.cbInQue == 0)
1133 TRY(restart_wait(port));
1139 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1140 size_t count, unsigned int timeout_ms)
1142 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1147 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1150 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1151 count, port->name, timeout_ms);
1153 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1160 DWORD bytes_read = 0;
1163 if (port->timeouts.ReadIntervalTimeout != 0 ||
1164 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1165 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1166 port->timeouts.ReadIntervalTimeout = 0;
1167 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1168 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1169 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1170 RETURN_FAIL("SetCommTimeouts() failed");
1174 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1175 DEBUG("Read completed immediately");
1177 } else if (GetLastError() == ERROR_IO_PENDING) {
1178 DEBUG("Waiting for read to complete");
1179 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1180 RETURN_FAIL("GetOverlappedResult() failed");
1181 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1183 RETURN_FAIL("ReadFile() failed");
1186 TRY(restart_wait_if_needed(port, bytes_read));
1188 RETURN_INT(bytes_read);
1191 size_t bytes_read = 0;
1192 unsigned char *ptr = (unsigned char *) buf;
1193 struct timeout timeout;
1198 timeout_start(&timeout, timeout_ms);
1201 FD_SET(port->fd, &fds);
1203 /* Loop until we have the requested number of bytes. */
1204 while (bytes_read < count) {
1206 * Check timeout only if we have run select() at least once,
1207 * to avoid any issues if a short timeout is reached before
1208 * select() is even run.
1210 if (started && timeout_check(&timeout))
1211 /* Timeout has expired. */
1214 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1217 if (errno == EINTR) {
1218 DEBUG("select() call was interrupted, repeating");
1221 RETURN_FAIL("select() failed");
1223 } else if (result == 0) {
1224 /* Timeout has expired. */
1229 result = read(port->fd, ptr, count - bytes_read);
1232 if (errno == EAGAIN)
1234 * This shouldn't happen because we did a
1235 * select() first, but handle anyway.
1239 /* This is an actual failure. */
1240 RETURN_FAIL("read() failed");
1243 bytes_read += result;
1247 if (bytes_read < count)
1248 DEBUG("Read timed out");
1250 RETURN_INT(bytes_read);
1254 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1255 size_t count, unsigned int timeout_ms)
1257 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1262 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1265 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1268 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1269 count, port->name, timeout_ms);
1271 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1275 DWORD bytes_read = 0;
1277 /* If timeout_ms == 0, set maximum timeout. */
1278 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1281 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1282 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1283 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1284 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1285 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1286 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1287 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1288 RETURN_FAIL("SetCommTimeouts() failed");
1291 /* Loop until we have at least one byte, or timeout is reached. */
1292 while (bytes_read == 0) {
1294 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1295 DEBUG("Read completed immediately");
1296 } else if (GetLastError() == ERROR_IO_PENDING) {
1297 DEBUG("Waiting for read to complete");
1298 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1299 RETURN_FAIL("GetOverlappedResult() failed");
1300 if (bytes_read > 0) {
1301 DEBUG("Read completed");
1302 } else if (timeout_ms > 0) {
1303 DEBUG("Read timed out");
1306 DEBUG("Restarting read");
1309 RETURN_FAIL("ReadFile() failed");
1313 TRY(restart_wait_if_needed(port, bytes_read));
1315 RETURN_INT(bytes_read);
1318 size_t bytes_read = 0;
1319 struct timeout timeout;
1324 timeout_start(&timeout, timeout_ms);
1327 FD_SET(port->fd, &fds);
1329 /* Loop until we have at least one byte, or timeout is reached. */
1330 while (bytes_read == 0) {
1332 * Check timeout only if we have run select() at least once,
1333 * to avoid any issues if a short timeout is reached before
1334 * select() is even run.
1336 if (started && timeout_check(&timeout))
1337 /* Timeout has expired. */
1340 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1343 if (errno == EINTR) {
1344 DEBUG("select() call was interrupted, repeating");
1347 RETURN_FAIL("select() failed");
1349 } else if (result == 0) {
1350 /* Timeout has expired. */
1355 result = read(port->fd, buf, count);
1358 if (errno == EAGAIN)
1359 /* This shouldn't happen because we did a select() first, but handle anyway. */
1362 /* This is an actual failure. */
1363 RETURN_FAIL("read() failed");
1366 bytes_read = result;
1369 if (bytes_read == 0)
1370 DEBUG("Read timed out");
1372 RETURN_INT(bytes_read);
1376 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1379 TRACE("%p, %p, %d", port, buf, count);
1384 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1386 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1392 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1393 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1394 port->timeouts.ReadTotalTimeoutConstant != 0) {
1395 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1396 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1397 port->timeouts.ReadTotalTimeoutConstant = 0;
1398 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1399 RETURN_FAIL("SetCommTimeouts() failed");
1403 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1404 if (GetLastError() != ERROR_IO_PENDING)
1405 RETURN_FAIL("ReadFile() failed");
1407 /* Get number of bytes read. */
1408 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1409 RETURN_FAIL("GetOverlappedResult() failed");
1411 TRY(restart_wait_if_needed(port, bytes_read));
1413 RETURN_INT(bytes_read);
1417 /* Returns the number of bytes read, or -1 upon failure. */
1418 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1419 if (errno == EAGAIN)
1420 /* No bytes available. */
1423 /* This is an actual failure. */
1424 RETURN_FAIL("read() failed");
1426 RETURN_INT(bytes_read);
1430 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1436 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1442 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1443 RETURN_FAIL("ClearCommError() failed");
1444 RETURN_INT(comstat.cbInQue);
1447 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1448 RETURN_FAIL("TIOCINQ ioctl failed");
1449 RETURN_INT(bytes_waiting);
1453 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1459 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1465 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1466 RETURN_FAIL("ClearCommError() failed");
1467 RETURN_INT(comstat.cbOutQue);
1470 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1471 RETURN_FAIL("TIOCOUTQ ioctl failed");
1472 RETURN_INT(bytes_waiting);
1476 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1478 struct sp_event_set *result;
1480 TRACE("%p", result_ptr);
1483 RETURN_ERROR(SP_ERR_ARG, "Null result");
1487 if (!(result = malloc(sizeof(struct sp_event_set))))
1488 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1490 memset(result, 0, sizeof(struct sp_event_set));
1492 *result_ptr = result;
1497 static enum sp_return add_handle(struct sp_event_set *event_set,
1498 event_handle handle, enum sp_event mask)
1501 enum sp_event *new_masks;
1503 TRACE("%p, %d, %d", event_set, handle, mask);
1505 if (!(new_handles = realloc(event_set->handles,
1506 sizeof(event_handle) * (event_set->count + 1))))
1507 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1509 event_set->handles = new_handles;
1511 if (!(new_masks = realloc(event_set->masks,
1512 sizeof(enum sp_event) * (event_set->count + 1))))
1513 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1515 event_set->masks = new_masks;
1517 ((event_handle *) event_set->handles)[event_set->count] = handle;
1518 event_set->masks[event_set->count] = mask;
1525 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1526 const struct sp_port *port, enum sp_event mask)
1528 TRACE("%p, %p, %d", event_set, port, mask);
1531 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1534 RETURN_ERROR(SP_ERR_ARG, "Null port");
1536 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1537 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1543 enum sp_event handle_mask;
1544 if ((handle_mask = mask & SP_EVENT_TX_READY))
1545 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1546 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1547 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1549 TRY(add_handle(event_set, port->fd, mask));
1555 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1557 TRACE("%p", event_set);
1560 DEBUG("Null event set");
1564 DEBUG("Freeing event set");
1566 if (event_set->handles)
1567 free(event_set->handles);
1568 if (event_set->masks)
1569 free(event_set->masks);
1576 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1577 unsigned int timeout_ms)
1579 TRACE("%p, %d", event_set, timeout_ms);
1582 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1585 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1586 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1587 RETURN_FAIL("WaitForMultipleObjects() failed");
1591 struct timeout timeout;
1592 int started = 0, result;
1593 struct pollfd *pollfds;
1596 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1597 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1599 for (i = 0; i < event_set->count; i++) {
1600 pollfds[i].fd = ((int *)event_set->handles)[i];
1601 pollfds[i].events = 0;
1602 pollfds[i].revents = 0;
1603 if (event_set->masks[i] & SP_EVENT_RX_READY)
1604 pollfds[i].events |= POLLIN;
1605 if (event_set->masks[i] & SP_EVENT_TX_READY)
1606 pollfds[i].events |= POLLOUT;
1607 if (event_set->masks[i] & SP_EVENT_ERROR)
1608 pollfds[i].events |= POLLERR;
1611 timeout_start(&timeout, timeout_ms);
1612 timeout_limit(&timeout, INT_MAX);
1614 /* Loop until an event occurs. */
1617 * Check timeout only if we have run poll() at least once,
1618 * to avoid any issues if a short timeout is reached before
1619 * poll() is even run.
1621 if (started && timeout_check(&timeout)) {
1622 DEBUG("Wait timed out");
1626 result = poll(pollfds, event_set->count, timeout_remaining_ms(&timeout) || -1);
1630 if (errno == EINTR) {
1631 DEBUG("poll() call was interrupted, repeating");
1635 RETURN_FAIL("poll() failed");
1637 } else if (result == 0) {
1638 DEBUG("poll() timed out");
1639 if (!timeout.overflow)
1642 DEBUG("poll() completed");
1652 #ifdef USE_TERMIOS_SPEED
1653 static enum sp_return get_baudrate(int fd, int *baudrate)
1657 TRACE("%d, %p", fd, baudrate);
1659 DEBUG("Getting baud rate");
1661 if (!(data = malloc(get_termios_size())))
1662 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1664 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1666 RETURN_FAIL("Getting termios failed");
1669 *baudrate = get_termios_speed(data);
1676 static enum sp_return set_baudrate(int fd, int baudrate)
1680 TRACE("%d, %d", fd, baudrate);
1682 DEBUG("Getting baud rate");
1684 if (!(data = malloc(get_termios_size())))
1685 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1687 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1689 RETURN_FAIL("Getting termios failed");
1692 DEBUG("Setting baud rate");
1694 set_termios_speed(data, baudrate);
1696 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1698 RETURN_FAIL("Setting termios failed");
1705 #endif /* USE_TERMIOS_SPEED */
1708 static enum sp_return get_flow(int fd, struct port_data *data)
1712 TRACE("%d, %p", fd, data);
1714 DEBUG("Getting advanced flow control");
1716 if (!(termx = malloc(get_termiox_size())))
1717 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1719 if (ioctl(fd, TCGETX, termx) < 0) {
1721 RETURN_FAIL("Getting termiox failed");
1724 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1725 &data->dtr_flow, &data->dsr_flow);
1732 static enum sp_return set_flow(int fd, struct port_data *data)
1736 TRACE("%d, %p", fd, data);
1738 DEBUG("Getting advanced flow control");
1740 if (!(termx = malloc(get_termiox_size())))
1741 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1743 if (ioctl(fd, TCGETX, termx) < 0) {
1745 RETURN_FAIL("Getting termiox failed");
1748 DEBUG("Setting advanced flow control");
1750 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1751 data->dtr_flow, data->dsr_flow);
1753 if (ioctl(fd, TCSETX, termx) < 0) {
1755 RETURN_FAIL("Setting termiox failed");
1762 #endif /* USE_TERMIOX */
1764 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1765 struct sp_port_config *config)
1769 TRACE("%p, %p, %p", port, data, config);
1771 DEBUG_FMT("Getting configuration for port %s", port->name);
1774 if (!GetCommState(port->hdl, &data->dcb))
1775 RETURN_FAIL("GetCommState() failed");
1777 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1778 if (data->dcb.BaudRate == std_baudrates[i].index) {
1779 config->baudrate = std_baudrates[i].value;
1784 if (i == NUM_STD_BAUDRATES)
1785 /* BaudRate field can be either an index or a custom baud rate. */
1786 config->baudrate = data->dcb.BaudRate;
1788 config->bits = data->dcb.ByteSize;
1790 if (data->dcb.fParity)
1791 switch (data->dcb.Parity) {
1793 config->parity = SP_PARITY_NONE;
1796 config->parity = SP_PARITY_ODD;
1799 config->parity = SP_PARITY_EVEN;
1802 config->parity = SP_PARITY_MARK;
1805 config->parity = SP_PARITY_SPACE;
1808 config->parity = -1;
1811 config->parity = SP_PARITY_NONE;
1813 switch (data->dcb.StopBits) {
1815 config->stopbits = 1;
1818 config->stopbits = 2;
1821 config->stopbits = -1;
1824 switch (data->dcb.fRtsControl) {
1825 case RTS_CONTROL_DISABLE:
1826 config->rts = SP_RTS_OFF;
1828 case RTS_CONTROL_ENABLE:
1829 config->rts = SP_RTS_ON;
1831 case RTS_CONTROL_HANDSHAKE:
1832 config->rts = SP_RTS_FLOW_CONTROL;
1838 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1840 switch (data->dcb.fDtrControl) {
1841 case DTR_CONTROL_DISABLE:
1842 config->dtr = SP_DTR_OFF;
1844 case DTR_CONTROL_ENABLE:
1845 config->dtr = SP_DTR_ON;
1847 case DTR_CONTROL_HANDSHAKE:
1848 config->dtr = SP_DTR_FLOW_CONTROL;
1854 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1856 if (data->dcb.fInX) {
1857 if (data->dcb.fOutX)
1858 config->xon_xoff = SP_XONXOFF_INOUT;
1860 config->xon_xoff = SP_XONXOFF_IN;
1862 if (data->dcb.fOutX)
1863 config->xon_xoff = SP_XONXOFF_OUT;
1865 config->xon_xoff = SP_XONXOFF_DISABLED;
1870 if (tcgetattr(port->fd, &data->term) < 0)
1871 RETURN_FAIL("tcgetattr() failed");
1873 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1874 RETURN_FAIL("TIOCMGET ioctl failed");
1877 int ret = get_flow(port->fd, data);
1879 if (ret == SP_ERR_FAIL && errno == EINVAL)
1880 data->termiox_supported = 0;
1882 RETURN_CODEVAL(ret);
1884 data->termiox_supported = 1;
1886 data->termiox_supported = 0;
1889 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1890 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1891 config->baudrate = std_baudrates[i].value;
1896 if (i == NUM_STD_BAUDRATES) {
1898 config->baudrate = (int)data->term.c_ispeed;
1899 #elif defined(USE_TERMIOS_SPEED)
1900 TRY(get_baudrate(port->fd, &config->baudrate));
1902 config->baudrate = -1;
1906 switch (data->term.c_cflag & CSIZE) {
1923 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1924 config->parity = SP_PARITY_NONE;
1925 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1926 config->parity = -1;
1928 else if (data->term.c_cflag & CMSPAR)
1929 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1932 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1934 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1936 if (data->term.c_cflag & CRTSCTS) {
1937 config->rts = SP_RTS_FLOW_CONTROL;
1938 config->cts = SP_CTS_FLOW_CONTROL;
1940 if (data->termiox_supported && data->rts_flow)
1941 config->rts = SP_RTS_FLOW_CONTROL;
1943 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1945 config->cts = (data->termiox_supported && data->cts_flow) ?
1946 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1949 if (data->termiox_supported && data->dtr_flow)
1950 config->dtr = SP_DTR_FLOW_CONTROL;
1952 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1954 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1955 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1957 if (data->term.c_iflag & IXOFF) {
1958 if (data->term.c_iflag & IXON)
1959 config->xon_xoff = SP_XONXOFF_INOUT;
1961 config->xon_xoff = SP_XONXOFF_IN;
1963 if (data->term.c_iflag & IXON)
1964 config->xon_xoff = SP_XONXOFF_OUT;
1966 config->xon_xoff = SP_XONXOFF_DISABLED;
1973 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1974 const struct sp_port_config *config)
1978 BAUD_TYPE baud_nonstd;
1982 #ifdef USE_TERMIOS_SPEED
1983 int baud_nonstd = 0;
1986 TRACE("%p, %p, %p", port, data, config);
1988 DEBUG_FMT("Setting configuration for port %s", port->name);
1992 TRY(await_write_completion(port));
1994 if (config->baudrate >= 0) {
1995 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1996 if (config->baudrate == std_baudrates[i].value) {
1997 data->dcb.BaudRate = std_baudrates[i].index;
2002 if (i == NUM_STD_BAUDRATES)
2003 data->dcb.BaudRate = config->baudrate;
2005 /* Allocate write buffer for 50ms of data at baud rate. */
2006 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
2007 port->write_buf = realloc(port->write_buf,
2008 port->write_buf_size);
2010 if (!port->write_buf)
2011 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
2014 if (config->bits >= 0)
2015 data->dcb.ByteSize = config->bits;
2017 if (config->parity >= 0) {
2018 switch (config->parity) {
2019 case SP_PARITY_NONE:
2020 data->dcb.Parity = NOPARITY;
2023 data->dcb.Parity = ODDPARITY;
2025 case SP_PARITY_EVEN:
2026 data->dcb.Parity = EVENPARITY;
2028 case SP_PARITY_MARK:
2029 data->dcb.Parity = MARKPARITY;
2031 case SP_PARITY_SPACE:
2032 data->dcb.Parity = SPACEPARITY;
2035 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2039 if (config->stopbits >= 0) {
2040 switch (config->stopbits) {
2041 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
2043 data->dcb.StopBits = ONESTOPBIT;
2046 data->dcb.StopBits = TWOSTOPBITS;
2049 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
2053 if (config->rts >= 0) {
2054 switch (config->rts) {
2056 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
2059 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
2061 case SP_RTS_FLOW_CONTROL:
2062 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
2065 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
2069 if (config->cts >= 0) {
2070 switch (config->cts) {
2072 data->dcb.fOutxCtsFlow = FALSE;
2074 case SP_CTS_FLOW_CONTROL:
2075 data->dcb.fOutxCtsFlow = TRUE;
2078 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
2082 if (config->dtr >= 0) {
2083 switch (config->dtr) {
2085 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
2088 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
2090 case SP_DTR_FLOW_CONTROL:
2091 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
2094 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
2098 if (config->dsr >= 0) {
2099 switch (config->dsr) {
2101 data->dcb.fOutxDsrFlow = FALSE;
2103 case SP_DSR_FLOW_CONTROL:
2104 data->dcb.fOutxDsrFlow = TRUE;
2107 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2111 if (config->xon_xoff >= 0) {
2112 switch (config->xon_xoff) {
2113 case SP_XONXOFF_DISABLED:
2114 data->dcb.fInX = FALSE;
2115 data->dcb.fOutX = FALSE;
2118 data->dcb.fInX = TRUE;
2119 data->dcb.fOutX = FALSE;
2121 case SP_XONXOFF_OUT:
2122 data->dcb.fInX = FALSE;
2123 data->dcb.fOutX = TRUE;
2125 case SP_XONXOFF_INOUT:
2126 data->dcb.fInX = TRUE;
2127 data->dcb.fOutX = TRUE;
2130 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2134 if (!SetCommState(port->hdl, &data->dcb))
2135 RETURN_FAIL("SetCommState() failed");
2141 if (config->baudrate >= 0) {
2142 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2143 if (config->baudrate == std_baudrates[i].value) {
2144 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2145 RETURN_FAIL("cfsetospeed() failed");
2147 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2148 RETURN_FAIL("cfsetispeed() failed");
2153 /* Non-standard baud rate */
2154 if (i == NUM_STD_BAUDRATES) {
2156 /* Set "dummy" baud rate. */
2157 if (cfsetspeed(&data->term, B9600) < 0)
2158 RETURN_FAIL("cfsetspeed() failed");
2159 baud_nonstd = config->baudrate;
2160 #elif defined(USE_TERMIOS_SPEED)
2163 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2168 if (config->bits >= 0) {
2169 data->term.c_cflag &= ~CSIZE;
2170 switch (config->bits) {
2172 data->term.c_cflag |= CS8;
2175 data->term.c_cflag |= CS7;
2178 data->term.c_cflag |= CS6;
2181 data->term.c_cflag |= CS5;
2184 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2188 if (config->parity >= 0) {
2189 data->term.c_iflag &= ~IGNPAR;
2190 data->term.c_cflag &= ~(PARENB | PARODD);
2192 data->term.c_cflag &= ~CMSPAR;
2194 switch (config->parity) {
2195 case SP_PARITY_NONE:
2196 data->term.c_iflag |= IGNPAR;
2198 case SP_PARITY_EVEN:
2199 data->term.c_cflag |= PARENB;
2202 data->term.c_cflag |= PARENB | PARODD;
2205 case SP_PARITY_MARK:
2206 data->term.c_cflag |= PARENB | PARODD;
2207 data->term.c_cflag |= CMSPAR;
2209 case SP_PARITY_SPACE:
2210 data->term.c_cflag |= PARENB;
2211 data->term.c_cflag |= CMSPAR;
2214 case SP_PARITY_MARK:
2215 case SP_PARITY_SPACE:
2216 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2219 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2223 if (config->stopbits >= 0) {
2224 data->term.c_cflag &= ~CSTOPB;
2225 switch (config->stopbits) {
2227 data->term.c_cflag &= ~CSTOPB;
2230 data->term.c_cflag |= CSTOPB;
2233 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2237 if (config->rts >= 0 || config->cts >= 0) {
2238 if (data->termiox_supported) {
2239 data->rts_flow = data->cts_flow = 0;
2240 switch (config->rts) {
2243 controlbits = TIOCM_RTS;
2244 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2245 RETURN_FAIL("Setting RTS signal level failed");
2247 case SP_RTS_FLOW_CONTROL:
2253 if (config->cts == SP_CTS_FLOW_CONTROL)
2256 if (data->rts_flow && data->cts_flow)
2257 data->term.c_iflag |= CRTSCTS;
2259 data->term.c_iflag &= ~CRTSCTS;
2261 /* Asymmetric use of RTS/CTS not supported. */
2262 if (data->term.c_iflag & CRTSCTS) {
2263 /* Flow control can only be disabled for both RTS & CTS together. */
2264 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2265 if (config->cts != SP_CTS_IGNORE)
2266 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2268 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2269 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2270 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2273 /* Flow control can only be enabled for both RTS & CTS together. */
2274 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2275 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2276 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2279 if (config->rts >= 0) {
2280 if (config->rts == SP_RTS_FLOW_CONTROL) {
2281 data->term.c_iflag |= CRTSCTS;
2283 controlbits = TIOCM_RTS;
2284 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2286 RETURN_FAIL("Setting RTS signal level failed");
2292 if (config->dtr >= 0 || config->dsr >= 0) {
2293 if (data->termiox_supported) {
2294 data->dtr_flow = data->dsr_flow = 0;
2295 switch (config->dtr) {
2298 controlbits = TIOCM_DTR;
2299 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2300 RETURN_FAIL("Setting DTR signal level failed");
2302 case SP_DTR_FLOW_CONTROL:
2308 if (config->dsr == SP_DSR_FLOW_CONTROL)
2311 /* DTR/DSR flow control not supported. */
2312 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2313 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2315 if (config->dtr >= 0) {
2316 controlbits = TIOCM_DTR;
2317 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2319 RETURN_FAIL("Setting DTR signal level failed");
2324 if (config->xon_xoff >= 0) {
2325 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2326 switch (config->xon_xoff) {
2327 case SP_XONXOFF_DISABLED:
2330 data->term.c_iflag |= IXOFF;
2332 case SP_XONXOFF_OUT:
2333 data->term.c_iflag |= IXON | IXANY;
2335 case SP_XONXOFF_INOUT:
2336 data->term.c_iflag |= IXON | IXOFF | IXANY;
2339 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2343 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2344 RETURN_FAIL("tcsetattr() failed");
2347 if (baud_nonstd != B0) {
2348 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2349 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2351 * Set baud rates in data->term to correct, but incompatible
2352 * with tcsetattr() value, same as delivered by tcgetattr().
2354 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2355 RETURN_FAIL("cfsetspeed() failed");
2357 #elif defined(__linux__)
2358 #ifdef USE_TERMIOS_SPEED
2360 TRY(set_baudrate(port->fd, config->baudrate));
2363 if (data->termiox_supported)
2364 TRY(set_flow(port->fd, data));
2368 #endif /* !_WIN32 */
2373 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2375 struct sp_port_config *config;
2377 TRACE("%p", config_ptr);
2380 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2384 if (!(config = malloc(sizeof(struct sp_port_config))))
2385 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2387 config->baudrate = -1;
2389 config->parity = -1;
2390 config->stopbits = -1;
2396 *config_ptr = config;
2401 SP_API void sp_free_config(struct sp_port_config *config)
2403 TRACE("%p", config);
2406 DEBUG("Null config");
2413 SP_API enum sp_return sp_get_config(struct sp_port *port,
2414 struct sp_port_config *config)
2416 struct port_data data;
2418 TRACE("%p, %p", port, config);
2423 RETURN_ERROR(SP_ERR_ARG, "Null config");
2425 TRY(get_config(port, &data, config));
2430 SP_API enum sp_return sp_set_config(struct sp_port *port,
2431 const struct sp_port_config *config)
2433 struct port_data data;
2434 struct sp_port_config prev_config;
2436 TRACE("%p, %p", port, config);
2441 RETURN_ERROR(SP_ERR_ARG, "Null config");
2443 TRY(get_config(port, &data, &prev_config));
2444 TRY(set_config(port, &data, config));
2449 #define CREATE_ACCESSORS(x, type) \
2450 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2451 struct port_data data; \
2452 struct sp_port_config config; \
2453 TRACE("%p, %d", port, x); \
2454 CHECK_OPEN_PORT(); \
2455 TRY(get_config(port, &data, &config)); \
2457 TRY(set_config(port, &data, &config)); \
2460 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2462 TRACE("%p, %p", config, x); \
2464 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2466 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2470 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2472 TRACE("%p, %d", config, x); \
2474 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2479 CREATE_ACCESSORS(baudrate, int)
2480 CREATE_ACCESSORS(bits, int)
2481 CREATE_ACCESSORS(parity, enum sp_parity)
2482 CREATE_ACCESSORS(stopbits, int)
2483 CREATE_ACCESSORS(rts, enum sp_rts)
2484 CREATE_ACCESSORS(cts, enum sp_cts)
2485 CREATE_ACCESSORS(dtr, enum sp_dtr)
2486 CREATE_ACCESSORS(dsr, enum sp_dsr)
2487 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2489 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2490 enum sp_flowcontrol flowcontrol)
2493 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2495 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2496 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2498 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2499 config->xon_xoff = SP_XONXOFF_INOUT;
2501 config->xon_xoff = SP_XONXOFF_DISABLED;
2503 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2504 config->rts = SP_RTS_FLOW_CONTROL;
2505 config->cts = SP_CTS_FLOW_CONTROL;
2507 if (config->rts == SP_RTS_FLOW_CONTROL)
2508 config->rts = SP_RTS_ON;
2509 config->cts = SP_CTS_IGNORE;
2512 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2513 config->dtr = SP_DTR_FLOW_CONTROL;
2514 config->dsr = SP_DSR_FLOW_CONTROL;
2516 if (config->dtr == SP_DTR_FLOW_CONTROL)
2517 config->dtr = SP_DTR_ON;
2518 config->dsr = SP_DSR_IGNORE;
2524 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2525 enum sp_flowcontrol flowcontrol)
2527 struct port_data data;
2528 struct sp_port_config config;
2530 TRACE("%p, %d", port, flowcontrol);
2534 TRY(get_config(port, &data, &config));
2536 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2538 TRY(set_config(port, &data, &config));
2543 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2544 enum sp_signal *signals)
2546 TRACE("%p, %p", port, signals);
2551 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2553 DEBUG_FMT("Getting control signals for port %s", port->name);
2558 if (GetCommModemStatus(port->hdl, &bits) == 0)
2559 RETURN_FAIL("GetCommModemStatus() failed");
2560 if (bits & MS_CTS_ON)
2561 *signals |= SP_SIG_CTS;
2562 if (bits & MS_DSR_ON)
2563 *signals |= SP_SIG_DSR;
2564 if (bits & MS_RLSD_ON)
2565 *signals |= SP_SIG_DCD;
2566 if (bits & MS_RING_ON)
2567 *signals |= SP_SIG_RI;
2570 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2571 RETURN_FAIL("TIOCMGET ioctl failed");
2572 if (bits & TIOCM_CTS)
2573 *signals |= SP_SIG_CTS;
2574 if (bits & TIOCM_DSR)
2575 *signals |= SP_SIG_DSR;
2576 if (bits & TIOCM_CAR)
2577 *signals |= SP_SIG_DCD;
2578 if (bits & TIOCM_RNG)
2579 *signals |= SP_SIG_RI;
2584 SP_API enum sp_return sp_start_break(struct sp_port *port)
2590 if (SetCommBreak(port->hdl) == 0)
2591 RETURN_FAIL("SetCommBreak() failed");
2593 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2594 RETURN_FAIL("TIOCSBRK ioctl failed");
2600 SP_API enum sp_return sp_end_break(struct sp_port *port)
2606 if (ClearCommBreak(port->hdl) == 0)
2607 RETURN_FAIL("ClearCommBreak() failed");
2609 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2610 RETURN_FAIL("TIOCCBRK ioctl failed");
2616 SP_API int sp_last_error_code(void)
2620 RETURN_INT(GetLastError());
2626 SP_API char *sp_last_error_message(void)
2632 DWORD error = GetLastError();
2634 DWORD length = FormatMessage(
2635 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2636 FORMAT_MESSAGE_FROM_SYSTEM |
2637 FORMAT_MESSAGE_IGNORE_INSERTS,
2640 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2644 if (length >= 2 && message[length - 2] == '\r')
2645 message[length - 2] = '\0';
2647 RETURN_STRING(message);
2649 RETURN_STRING(strerror(errno));
2653 SP_API void sp_free_error_message(char *message)
2655 TRACE("%s", message);
2666 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2668 TRACE("%p", handler);
2670 sp_debug_handler = handler;
2675 SP_API void sp_default_debug_handler(const char *format, ...)
2678 va_start(args, format);
2679 if (getenv("LIBSERIALPORT_DEBUG")) {
2680 fputs("sp: ", stderr);
2681 vfprintf(stderr, format, args);
2686 SP_API int sp_get_major_package_version(void)
2688 return SP_PACKAGE_VERSION_MAJOR;
2691 SP_API int sp_get_minor_package_version(void)
2693 return SP_PACKAGE_VERSION_MINOR;
2696 SP_API int sp_get_micro_package_version(void)
2698 return SP_PACKAGE_VERSION_MICRO;
2701 SP_API const char *sp_get_package_version_string(void)
2703 return SP_PACKAGE_VERSION_STRING;
2706 SP_API int sp_get_current_lib_version(void)
2708 return SP_LIB_VERSION_CURRENT;
2711 SP_API int sp_get_revision_lib_version(void)
2713 return SP_LIB_VERSION_REVISION;
2716 SP_API int sp_get_age_lib_version(void)
2718 return SP_LIB_VERSION_AGE;
2721 SP_API const char *sp_get_lib_version_string(void)
2723 return SP_LIB_VERSION_STRING;