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->ms == 0)
215 else if (timeout->limit_ms && timeout->overflow)
216 return timeout->limit_ms;
218 return time_as_ms(&timeout->delta);
221 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
223 struct sp_port *port;
224 #ifndef NO_PORT_METADATA
229 TRACE("%s, %p", portname, port_ptr);
232 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
237 RETURN_ERROR(SP_ERR_ARG, "Null port name");
239 DEBUG_FMT("Building structure for port %s", portname);
241 #if !defined(_WIN32) && defined(HAVE_REALPATH)
243 * get_port_details() below tries to be too smart and figure out
244 * some transport properties from the port name which breaks with
245 * symlinks. Therefore we canonicalize the portname first.
247 char pathbuf[PATH_MAX + 1];
248 char *res = realpath(portname, pathbuf);
250 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
255 if (!(port = malloc(sizeof(struct sp_port))))
256 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
258 len = strlen(portname) + 1;
260 if (!(port->name = malloc(len))) {
262 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
265 memcpy(port->name, portname, len);
268 port->usb_path = NULL;
269 port->hdl = INVALID_HANDLE_VALUE;
270 port->write_buf = NULL;
271 port->write_buf_size = 0;
276 port->description = NULL;
277 port->transport = SP_TRANSPORT_NATIVE;
279 port->usb_address = -1;
282 port->usb_manufacturer = NULL;
283 port->usb_product = NULL;
284 port->usb_serial = NULL;
285 port->bluetooth_address = NULL;
287 #ifndef NO_PORT_METADATA
288 if ((ret = get_port_details(port)) != SP_OK) {
299 SP_API char *sp_get_port_name(const struct sp_port *port)
306 RETURN_STRING(port->name);
309 SP_API char *sp_get_port_description(const struct sp_port *port)
313 if (!port || !port->description)
316 RETURN_STRING(port->description);
319 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
324 RETURN_ERROR(SP_ERR_ARG, "Null port");
326 RETURN_INT(port->transport);
329 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
330 int *usb_bus,int *usb_address)
335 RETURN_ERROR(SP_ERR_ARG, "Null port");
336 if (port->transport != SP_TRANSPORT_USB)
337 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
338 if (port->usb_bus < 0 || port->usb_address < 0)
339 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
342 *usb_bus = port->usb_bus;
344 *usb_address = port->usb_address;
349 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
350 int *usb_vid, int *usb_pid)
355 RETURN_ERROR(SP_ERR_ARG, "Null port");
356 if (port->transport != SP_TRANSPORT_USB)
357 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
358 if (port->usb_vid < 0 || port->usb_pid < 0)
359 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
362 *usb_vid = port->usb_vid;
364 *usb_pid = port->usb_pid;
369 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
373 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
376 RETURN_STRING(port->usb_manufacturer);
379 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
383 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
386 RETURN_STRING(port->usb_product);
389 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
393 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
396 RETURN_STRING(port->usb_serial);
399 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
403 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
404 || !port->bluetooth_address)
407 RETURN_STRING(port->bluetooth_address);
410 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
413 TRACE("%p, %p", port, result_ptr);
416 RETURN_ERROR(SP_ERR_ARG, "Null port");
418 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
421 HANDLE *handle_ptr = result_ptr;
422 *handle_ptr = port->hdl;
424 int *fd_ptr = result_ptr;
431 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
432 struct sp_port **copy_ptr)
434 TRACE("%p, %p", port, copy_ptr);
437 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
442 RETURN_ERROR(SP_ERR_ARG, "Null port");
445 RETURN_ERROR(SP_ERR_ARG, "Null port name");
447 DEBUG("Copying port structure");
449 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
452 SP_API void sp_free_port(struct sp_port *port)
461 DEBUG("Freeing port structure");
465 if (port->description)
466 free(port->description);
467 if (port->usb_manufacturer)
468 free(port->usb_manufacturer);
469 if (port->usb_product)
470 free(port->usb_product);
471 if (port->usb_serial)
472 free(port->usb_serial);
473 if (port->bluetooth_address)
474 free(port->bluetooth_address);
477 free(port->usb_path);
479 free(port->write_buf);
487 SP_PRIV struct sp_port **list_append(struct sp_port **list,
488 const char *portname)
493 for (count = 0; list[count]; count++)
495 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
498 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
500 list[count + 1] = NULL;
504 sp_free_port_list(list);
508 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
510 #ifndef NO_ENUMERATION
511 struct sp_port **list;
515 TRACE("%p", list_ptr);
518 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
522 #ifdef NO_ENUMERATION
523 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
525 DEBUG("Enumerating ports");
527 if (!(list = malloc(sizeof(struct sp_port *))))
528 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
532 ret = list_ports(&list);
537 sp_free_port_list(list);
545 SP_API void sp_free_port_list(struct sp_port **list)
556 DEBUG("Freeing port list");
558 for (i = 0; list[i]; i++)
559 sp_free_port(list[i]);
565 #define CHECK_PORT() do { \
567 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
569 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
572 #define CHECK_PORT_HANDLE() do { \
573 if (port->hdl == INVALID_HANDLE_VALUE) \
574 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
577 #define CHECK_PORT_HANDLE() do { \
579 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
582 #define CHECK_OPEN_PORT() do { \
584 CHECK_PORT_HANDLE(); \
588 /** To be called after port receive buffer is emptied. */
589 static enum sp_return restart_wait(struct sp_port *port)
593 if (port->wait_running) {
594 /* Check status of running wait operation. */
595 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
596 &wait_result, FALSE)) {
597 DEBUG("Previous wait completed");
598 port->wait_running = FALSE;
599 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
600 DEBUG("Previous wait still running");
603 RETURN_FAIL("GetOverlappedResult() failed");
607 if (!port->wait_running) {
608 /* Start new wait operation. */
609 if (WaitCommEvent(port->hdl, &port->events,
611 DEBUG("New wait returned, events already pending");
612 } else if (GetLastError() == ERROR_IO_PENDING) {
613 DEBUG("New wait running in background");
614 port->wait_running = TRUE;
616 RETURN_FAIL("WaitCommEvent() failed");
624 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
626 struct port_data data;
627 struct sp_port_config config;
630 TRACE("%p, 0x%x", port, flags);
634 if (flags > SP_MODE_READ_WRITE)
635 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
637 DEBUG_FMT("Opening port %s", port->name);
640 DWORD desired_access = 0, flags_and_attributes = 0, errors;
641 char *escaped_port_name;
644 /* Prefix port name with '\\.\' to work with ports above COM9. */
645 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
646 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
647 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
649 /* Map 'flags' to the OS-specific settings. */
650 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
651 if (flags & SP_MODE_READ)
652 desired_access |= GENERIC_READ;
653 if (flags & SP_MODE_WRITE)
654 desired_access |= GENERIC_WRITE;
656 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
657 OPEN_EXISTING, flags_and_attributes, 0);
659 free(escaped_port_name);
661 if (port->hdl == INVALID_HANDLE_VALUE)
662 RETURN_FAIL("Port CreateFile() failed");
664 /* All timeouts initially disabled. */
665 port->timeouts.ReadIntervalTimeout = 0;
666 port->timeouts.ReadTotalTimeoutMultiplier = 0;
667 port->timeouts.ReadTotalTimeoutConstant = 0;
668 port->timeouts.WriteTotalTimeoutMultiplier = 0;
669 port->timeouts.WriteTotalTimeoutConstant = 0;
671 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
673 RETURN_FAIL("SetCommTimeouts() failed");
676 /* Prepare OVERLAPPED structures. */
677 #define INIT_OVERLAPPED(ovl) do { \
678 memset(&port->ovl, 0, sizeof(port->ovl)); \
679 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
680 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
681 == INVALID_HANDLE_VALUE) { \
683 RETURN_FAIL(#ovl "CreateEvent() failed"); \
687 INIT_OVERLAPPED(read_ovl);
688 INIT_OVERLAPPED(write_ovl);
689 INIT_OVERLAPPED(wait_ovl);
691 /* Set event mask for RX and error events. */
692 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
694 RETURN_FAIL("SetCommMask() failed");
697 port->writing = FALSE;
698 port->wait_running = FALSE;
700 ret = restart_wait(port);
707 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
709 /* Map 'flags' to the OS-specific settings. */
710 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
711 flags_local |= O_RDWR;
712 else if (flags & SP_MODE_READ)
713 flags_local |= O_RDONLY;
714 else if (flags & SP_MODE_WRITE)
715 flags_local |= O_WRONLY;
717 if ((port->fd = open(port->name, flags_local)) < 0)
718 RETURN_FAIL("open() failed");
721 ret = get_config(port, &data, &config);
728 /* Set sane port settings. */
730 data.dcb.fBinary = TRUE;
731 data.dcb.fDsrSensitivity = FALSE;
732 data.dcb.fErrorChar = FALSE;
733 data.dcb.fNull = FALSE;
734 data.dcb.fAbortOnError = FALSE;
736 /* Turn off all fancy termios tricks, give us a raw channel. */
737 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
739 data.term.c_iflag &= ~IUCLC;
741 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
743 data.term.c_oflag &= ~OLCUC;
746 data.term.c_oflag &= ~NLDLY;
749 data.term.c_oflag &= ~CRDLY;
752 data.term.c_oflag &= ~TABDLY;
755 data.term.c_oflag &= ~BSDLY;
758 data.term.c_oflag &= ~VTDLY;
761 data.term.c_oflag &= ~FFDLY;
764 data.term.c_oflag &= ~OFILL;
766 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
767 data.term.c_cc[VMIN] = 0;
768 data.term.c_cc[VTIME] = 0;
770 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
771 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
775 if (ClearCommError(port->hdl, &errors, &status) == 0)
776 RETURN_FAIL("ClearCommError() failed");
779 ret = set_config(port, &data, &config);
789 SP_API enum sp_return sp_close(struct sp_port *port)
795 DEBUG_FMT("Closing port %s", port->name);
798 /* Returns non-zero upon success, 0 upon failure. */
799 if (CloseHandle(port->hdl) == 0)
800 RETURN_FAIL("Port CloseHandle() failed");
801 port->hdl = INVALID_HANDLE_VALUE;
803 /* Close event handles for overlapped structures. */
804 #define CLOSE_OVERLAPPED(ovl) do { \
805 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
806 CloseHandle(port->ovl.hEvent) == 0) \
807 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
809 CLOSE_OVERLAPPED(read_ovl);
810 CLOSE_OVERLAPPED(write_ovl);
811 CLOSE_OVERLAPPED(wait_ovl);
813 if (port->write_buf) {
814 free(port->write_buf);
815 port->write_buf = NULL;
818 /* Returns 0 upon success, -1 upon failure. */
819 if (close(port->fd) == -1)
820 RETURN_FAIL("close() failed");
827 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
829 TRACE("%p, 0x%x", port, buffers);
833 if (buffers > SP_BUF_BOTH)
834 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
836 const char *buffer_names[] = {"no", "input", "output", "both"};
838 DEBUG_FMT("Flushing %s buffers on port %s",
839 buffer_names[buffers], port->name);
843 if (buffers & SP_BUF_INPUT)
844 flags |= PURGE_RXCLEAR;
845 if (buffers & SP_BUF_OUTPUT)
846 flags |= PURGE_TXCLEAR;
848 /* Returns non-zero upon success, 0 upon failure. */
849 if (PurgeComm(port->hdl, flags) == 0)
850 RETURN_FAIL("PurgeComm() failed");
852 if (buffers & SP_BUF_INPUT)
853 TRY(restart_wait(port));
856 if (buffers == SP_BUF_BOTH)
858 else if (buffers == SP_BUF_INPUT)
860 else if (buffers == SP_BUF_OUTPUT)
863 /* Returns 0 upon success, -1 upon failure. */
864 if (tcflush(port->fd, flags) < 0)
865 RETURN_FAIL("tcflush() failed");
870 SP_API enum sp_return sp_drain(struct sp_port *port)
876 DEBUG_FMT("Draining port %s", port->name);
879 /* Returns non-zero upon success, 0 upon failure. */
880 if (FlushFileBuffers(port->hdl) == 0)
881 RETURN_FAIL("FlushFileBuffers() failed");
886 #if defined(__ANDROID__) && (__ANDROID_API__ < 21)
887 /* Android only has tcdrain from platform 21 onwards.
888 * On previous API versions, use the ioctl directly. */
890 result = ioctl(port->fd, TCSBRK, &arg);
892 result = tcdrain(port->fd);
895 if (errno == EINTR) {
896 DEBUG("tcdrain() was interrupted");
899 RETURN_FAIL("tcdrain() failed");
909 static enum sp_return await_write_completion(struct sp_port *port)
915 /* Wait for previous non-blocking write to complete, if any. */
917 DEBUG("Waiting for previous write to complete");
918 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
921 RETURN_FAIL("Previous write failed to complete");
922 DEBUG("Previous write completed");
929 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
930 size_t count, unsigned int timeout_ms)
932 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
937 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
940 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
941 count, port->name, timeout_ms);
943 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
950 DWORD bytes_written = 0;
952 TRY(await_write_completion(port));
955 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
956 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
957 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
958 RETURN_FAIL("SetCommTimeouts() failed");
961 /* Reduce count if it exceeds the WriteFile limit. */
962 if (count > WRITEFILE_MAX_SIZE)
963 count = WRITEFILE_MAX_SIZE;
966 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
967 DEBUG("Write completed immediately");
969 } else if (GetLastError() == ERROR_IO_PENDING) {
970 DEBUG("Waiting for write to complete");
971 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
972 if (GetLastError() == ERROR_SEM_TIMEOUT) {
973 DEBUG("Write timed out");
976 RETURN_FAIL("GetOverlappedResult() failed");
979 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
980 RETURN_INT(bytes_written);
982 RETURN_FAIL("WriteFile() failed");
985 size_t bytes_written = 0;
986 unsigned char *ptr = (unsigned char *) buf;
987 struct timeout timeout;
992 timeout_start(&timeout, timeout_ms);
995 FD_SET(port->fd, &fds);
997 /* Loop until we have written the requested number of bytes. */
998 while (bytes_written < count) {
1000 * Check timeout only if we have run select() at least once,
1001 * to avoid any issues if a short timeout is reached before
1002 * select() is even run.
1004 if (started && timeout_check(&timeout))
1007 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
1010 if (errno == EINTR) {
1011 DEBUG("select() call was interrupted, repeating");
1014 RETURN_FAIL("select() failed");
1016 } else if (result == 0) {
1017 /* Timeout has expired. */
1022 result = write(port->fd, ptr, count - bytes_written);
1025 if (errno == EAGAIN)
1026 /* This shouldn't happen because we did a select() first, but handle anyway. */
1029 /* This is an actual failure. */
1030 RETURN_FAIL("write() failed");
1033 bytes_written += result;
1037 if (bytes_written < count)
1038 DEBUG("Write timed out");
1040 RETURN_INT(bytes_written);
1044 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
1045 const void *buf, size_t count)
1047 TRACE("%p, %p, %d", port, buf, count);
1052 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1054 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
1062 /* Check whether previous write is complete. */
1063 if (port->writing) {
1064 if (HasOverlappedIoCompleted(&port->write_ovl)) {
1065 DEBUG("Previous write completed");
1068 DEBUG("Previous write not complete");
1069 /* Can't take a new write until the previous one finishes. */
1075 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
1076 port->timeouts.WriteTotalTimeoutConstant = 0;
1077 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1078 RETURN_FAIL("SetCommTimeouts() failed");
1081 /* Reduce count if it exceeds the WriteFile limit. */
1082 if (count > WRITEFILE_MAX_SIZE)
1083 count = WRITEFILE_MAX_SIZE;
1085 /* Copy data to our write buffer. */
1086 buf_bytes = min(port->write_buf_size, count);
1087 memcpy(port->write_buf, buf, buf_bytes);
1089 /* Start asynchronous write. */
1090 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
1091 if (GetLastError() == ERROR_IO_PENDING) {
1092 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
1093 DEBUG("Asynchronous write completed immediately");
1095 DEBUG("Asynchronous write running");
1097 /* Actual failure of some kind. */
1098 RETURN_FAIL("WriteFile() failed");
1102 DEBUG("All bytes written immediately");
1104 RETURN_INT(buf_bytes);
1106 /* Returns the number of bytes written, or -1 upon failure. */
1107 ssize_t written = write(port->fd, buf, count);
1110 if (errno == EAGAIN)
1111 // Buffer is full, no bytes written.
1114 RETURN_FAIL("write() failed");
1116 RETURN_INT(written);
1122 /* Restart wait operation if buffer was emptied. */
1123 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1128 if (bytes_read == 0)
1131 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1132 RETURN_FAIL("ClearCommError() failed");
1134 if (comstat.cbInQue == 0)
1135 TRY(restart_wait(port));
1141 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1142 size_t count, unsigned int timeout_ms)
1144 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1149 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1152 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1153 count, port->name, timeout_ms);
1155 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1162 DWORD bytes_read = 0;
1165 if (port->timeouts.ReadIntervalTimeout != 0 ||
1166 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1167 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1168 port->timeouts.ReadIntervalTimeout = 0;
1169 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1170 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1171 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1172 RETURN_FAIL("SetCommTimeouts() failed");
1176 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1177 DEBUG("Read completed immediately");
1179 } else if (GetLastError() == ERROR_IO_PENDING) {
1180 DEBUG("Waiting for read to complete");
1181 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1182 RETURN_FAIL("GetOverlappedResult() failed");
1183 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1185 RETURN_FAIL("ReadFile() failed");
1188 TRY(restart_wait_if_needed(port, bytes_read));
1190 RETURN_INT(bytes_read);
1193 size_t bytes_read = 0;
1194 unsigned char *ptr = (unsigned char *) buf;
1195 struct timeout timeout;
1200 timeout_start(&timeout, timeout_ms);
1203 FD_SET(port->fd, &fds);
1205 /* Loop until we have the requested number of bytes. */
1206 while (bytes_read < count) {
1208 * Check timeout only if we have run select() at least once,
1209 * to avoid any issues if a short timeout is reached before
1210 * select() is even run.
1212 if (started && timeout_check(&timeout))
1213 /* Timeout has expired. */
1216 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1219 if (errno == EINTR) {
1220 DEBUG("select() call was interrupted, repeating");
1223 RETURN_FAIL("select() failed");
1225 } else if (result == 0) {
1226 /* Timeout has expired. */
1231 result = read(port->fd, ptr, count - bytes_read);
1234 if (errno == EAGAIN)
1236 * This shouldn't happen because we did a
1237 * select() first, but handle anyway.
1241 /* This is an actual failure. */
1242 RETURN_FAIL("read() failed");
1245 bytes_read += result;
1249 if (bytes_read < count)
1250 DEBUG("Read timed out");
1252 RETURN_INT(bytes_read);
1256 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1257 size_t count, unsigned int timeout_ms)
1259 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1264 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1267 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1270 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1271 count, port->name, timeout_ms);
1273 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1277 DWORD bytes_read = 0;
1279 /* If timeout_ms == 0, set maximum timeout. */
1280 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1283 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1284 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1285 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1286 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1287 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1288 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1289 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1290 RETURN_FAIL("SetCommTimeouts() failed");
1293 /* Loop until we have at least one byte, or timeout is reached. */
1294 while (bytes_read == 0) {
1296 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1297 DEBUG("Read completed immediately");
1298 } else if (GetLastError() == ERROR_IO_PENDING) {
1299 DEBUG("Waiting for read to complete");
1300 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1301 RETURN_FAIL("GetOverlappedResult() failed");
1302 if (bytes_read > 0) {
1303 DEBUG("Read completed");
1304 } else if (timeout_ms > 0) {
1305 DEBUG("Read timed out");
1308 DEBUG("Restarting read");
1311 RETURN_FAIL("ReadFile() failed");
1315 TRY(restart_wait_if_needed(port, bytes_read));
1317 RETURN_INT(bytes_read);
1320 size_t bytes_read = 0;
1321 struct timeout timeout;
1326 timeout_start(&timeout, timeout_ms);
1329 FD_SET(port->fd, &fds);
1331 /* Loop until we have at least one byte, or timeout is reached. */
1332 while (bytes_read == 0) {
1334 * Check timeout only if we have run select() at least once,
1335 * to avoid any issues if a short timeout is reached before
1336 * select() is even run.
1338 if (started && timeout_check(&timeout))
1339 /* Timeout has expired. */
1342 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1345 if (errno == EINTR) {
1346 DEBUG("select() call was interrupted, repeating");
1349 RETURN_FAIL("select() failed");
1351 } else if (result == 0) {
1352 /* Timeout has expired. */
1357 result = read(port->fd, buf, count);
1360 if (errno == EAGAIN)
1361 /* This shouldn't happen because we did a select() first, but handle anyway. */
1364 /* This is an actual failure. */
1365 RETURN_FAIL("read() failed");
1368 bytes_read = result;
1371 if (bytes_read == 0)
1372 DEBUG("Read timed out");
1374 RETURN_INT(bytes_read);
1378 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1381 TRACE("%p, %p, %d", port, buf, count);
1386 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1388 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1394 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1395 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1396 port->timeouts.ReadTotalTimeoutConstant != 0) {
1397 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1398 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1399 port->timeouts.ReadTotalTimeoutConstant = 0;
1400 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1401 RETURN_FAIL("SetCommTimeouts() failed");
1405 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1406 if (GetLastError() != ERROR_IO_PENDING)
1407 RETURN_FAIL("ReadFile() failed");
1409 /* Get number of bytes read. */
1410 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1411 RETURN_FAIL("GetOverlappedResult() failed");
1413 TRY(restart_wait_if_needed(port, bytes_read));
1415 RETURN_INT(bytes_read);
1419 /* Returns the number of bytes read, or -1 upon failure. */
1420 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1421 if (errno == EAGAIN)
1422 /* No bytes available. */
1425 /* This is an actual failure. */
1426 RETURN_FAIL("read() failed");
1428 RETURN_INT(bytes_read);
1432 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1438 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1444 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1445 RETURN_FAIL("ClearCommError() failed");
1446 RETURN_INT(comstat.cbInQue);
1449 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1450 RETURN_FAIL("TIOCINQ ioctl failed");
1451 RETURN_INT(bytes_waiting);
1455 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1461 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1467 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1468 RETURN_FAIL("ClearCommError() failed");
1469 RETURN_INT(comstat.cbOutQue);
1472 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1473 RETURN_FAIL("TIOCOUTQ ioctl failed");
1474 RETURN_INT(bytes_waiting);
1478 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1480 struct sp_event_set *result;
1482 TRACE("%p", result_ptr);
1485 RETURN_ERROR(SP_ERR_ARG, "Null result");
1489 if (!(result = malloc(sizeof(struct sp_event_set))))
1490 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1492 memset(result, 0, sizeof(struct sp_event_set));
1494 *result_ptr = result;
1499 static enum sp_return add_handle(struct sp_event_set *event_set,
1500 event_handle handle, enum sp_event mask)
1503 enum sp_event *new_masks;
1505 TRACE("%p, %d, %d", event_set, handle, mask);
1507 if (!(new_handles = realloc(event_set->handles,
1508 sizeof(event_handle) * (event_set->count + 1))))
1509 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1511 event_set->handles = new_handles;
1513 if (!(new_masks = realloc(event_set->masks,
1514 sizeof(enum sp_event) * (event_set->count + 1))))
1515 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1517 event_set->masks = new_masks;
1519 ((event_handle *) event_set->handles)[event_set->count] = handle;
1520 event_set->masks[event_set->count] = mask;
1527 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1528 const struct sp_port *port, enum sp_event mask)
1530 TRACE("%p, %p, %d", event_set, port, mask);
1533 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1536 RETURN_ERROR(SP_ERR_ARG, "Null port");
1538 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1539 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1545 enum sp_event handle_mask;
1546 if ((handle_mask = mask & SP_EVENT_TX_READY))
1547 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1548 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1549 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1551 TRY(add_handle(event_set, port->fd, mask));
1557 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1559 TRACE("%p", event_set);
1562 DEBUG("Null event set");
1566 DEBUG("Freeing event set");
1568 if (event_set->handles)
1569 free(event_set->handles);
1570 if (event_set->masks)
1571 free(event_set->masks);
1578 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1579 unsigned int timeout_ms)
1581 TRACE("%p, %d", event_set, timeout_ms);
1584 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1587 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1588 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1589 RETURN_FAIL("WaitForMultipleObjects() failed");
1593 struct timeout timeout;
1594 int started = 0, result;
1595 struct pollfd *pollfds;
1598 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1599 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1601 for (i = 0; i < event_set->count; i++) {
1602 pollfds[i].fd = ((int *)event_set->handles)[i];
1603 pollfds[i].events = 0;
1604 pollfds[i].revents = 0;
1605 if (event_set->masks[i] & SP_EVENT_RX_READY)
1606 pollfds[i].events |= POLLIN;
1607 if (event_set->masks[i] & SP_EVENT_TX_READY)
1608 pollfds[i].events |= POLLOUT;
1609 if (event_set->masks[i] & SP_EVENT_ERROR)
1610 pollfds[i].events |= POLLERR;
1613 timeout_start(&timeout, timeout_ms);
1614 timeout_limit(&timeout, INT_MAX);
1616 /* Loop until an event occurs. */
1619 * Check timeout only if we have run poll() at least once,
1620 * to avoid any issues if a short timeout is reached before
1621 * poll() is even run.
1623 if (started && timeout_check(&timeout)) {
1624 DEBUG("Wait timed out");
1628 result = poll(pollfds, event_set->count, timeout_remaining_ms(&timeout));
1632 if (errno == EINTR) {
1633 DEBUG("poll() call was interrupted, repeating");
1637 RETURN_FAIL("poll() failed");
1639 } else if (result == 0) {
1640 DEBUG("poll() timed out");
1641 if (!timeout.overflow)
1644 DEBUG("poll() completed");
1654 #ifdef USE_TERMIOS_SPEED
1655 static enum sp_return get_baudrate(int fd, int *baudrate)
1659 TRACE("%d, %p", fd, baudrate);
1661 DEBUG("Getting baud rate");
1663 if (!(data = malloc(get_termios_size())))
1664 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1666 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1668 RETURN_FAIL("Getting termios failed");
1671 *baudrate = get_termios_speed(data);
1678 static enum sp_return set_baudrate(int fd, int baudrate)
1682 TRACE("%d, %d", fd, baudrate);
1684 DEBUG("Getting baud rate");
1686 if (!(data = malloc(get_termios_size())))
1687 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1689 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1691 RETURN_FAIL("Getting termios failed");
1694 DEBUG("Setting baud rate");
1696 set_termios_speed(data, baudrate);
1698 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1700 RETURN_FAIL("Setting termios failed");
1707 #endif /* USE_TERMIOS_SPEED */
1710 static enum sp_return get_flow(int fd, struct port_data *data)
1714 TRACE("%d, %p", fd, data);
1716 DEBUG("Getting advanced flow control");
1718 if (!(termx = malloc(get_termiox_size())))
1719 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1721 if (ioctl(fd, TCGETX, termx) < 0) {
1723 RETURN_FAIL("Getting termiox failed");
1726 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1727 &data->dtr_flow, &data->dsr_flow);
1734 static enum sp_return set_flow(int fd, struct port_data *data)
1738 TRACE("%d, %p", fd, data);
1740 DEBUG("Getting advanced flow control");
1742 if (!(termx = malloc(get_termiox_size())))
1743 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1745 if (ioctl(fd, TCGETX, termx) < 0) {
1747 RETURN_FAIL("Getting termiox failed");
1750 DEBUG("Setting advanced flow control");
1752 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1753 data->dtr_flow, data->dsr_flow);
1755 if (ioctl(fd, TCSETX, termx) < 0) {
1757 RETURN_FAIL("Setting termiox failed");
1764 #endif /* USE_TERMIOX */
1766 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1767 struct sp_port_config *config)
1771 TRACE("%p, %p, %p", port, data, config);
1773 DEBUG_FMT("Getting configuration for port %s", port->name);
1776 if (!GetCommState(port->hdl, &data->dcb))
1777 RETURN_FAIL("GetCommState() failed");
1779 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1780 if (data->dcb.BaudRate == std_baudrates[i].index) {
1781 config->baudrate = std_baudrates[i].value;
1786 if (i == NUM_STD_BAUDRATES)
1787 /* BaudRate field can be either an index or a custom baud rate. */
1788 config->baudrate = data->dcb.BaudRate;
1790 config->bits = data->dcb.ByteSize;
1792 if (data->dcb.fParity)
1793 switch (data->dcb.Parity) {
1795 config->parity = SP_PARITY_NONE;
1798 config->parity = SP_PARITY_ODD;
1801 config->parity = SP_PARITY_EVEN;
1804 config->parity = SP_PARITY_MARK;
1807 config->parity = SP_PARITY_SPACE;
1810 config->parity = -1;
1813 config->parity = SP_PARITY_NONE;
1815 switch (data->dcb.StopBits) {
1817 config->stopbits = 1;
1820 config->stopbits = 2;
1823 config->stopbits = -1;
1826 switch (data->dcb.fRtsControl) {
1827 case RTS_CONTROL_DISABLE:
1828 config->rts = SP_RTS_OFF;
1830 case RTS_CONTROL_ENABLE:
1831 config->rts = SP_RTS_ON;
1833 case RTS_CONTROL_HANDSHAKE:
1834 config->rts = SP_RTS_FLOW_CONTROL;
1840 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1842 switch (data->dcb.fDtrControl) {
1843 case DTR_CONTROL_DISABLE:
1844 config->dtr = SP_DTR_OFF;
1846 case DTR_CONTROL_ENABLE:
1847 config->dtr = SP_DTR_ON;
1849 case DTR_CONTROL_HANDSHAKE:
1850 config->dtr = SP_DTR_FLOW_CONTROL;
1856 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1858 if (data->dcb.fInX) {
1859 if (data->dcb.fOutX)
1860 config->xon_xoff = SP_XONXOFF_INOUT;
1862 config->xon_xoff = SP_XONXOFF_IN;
1864 if (data->dcb.fOutX)
1865 config->xon_xoff = SP_XONXOFF_OUT;
1867 config->xon_xoff = SP_XONXOFF_DISABLED;
1872 if (tcgetattr(port->fd, &data->term) < 0)
1873 RETURN_FAIL("tcgetattr() failed");
1875 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1876 RETURN_FAIL("TIOCMGET ioctl failed");
1879 int ret = get_flow(port->fd, data);
1881 if (ret == SP_ERR_FAIL && errno == EINVAL)
1882 data->termiox_supported = 0;
1884 RETURN_CODEVAL(ret);
1886 data->termiox_supported = 1;
1888 data->termiox_supported = 0;
1891 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1892 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1893 config->baudrate = std_baudrates[i].value;
1898 if (i == NUM_STD_BAUDRATES) {
1900 config->baudrate = (int)data->term.c_ispeed;
1901 #elif defined(USE_TERMIOS_SPEED)
1902 TRY(get_baudrate(port->fd, &config->baudrate));
1904 config->baudrate = -1;
1908 switch (data->term.c_cflag & CSIZE) {
1925 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1926 config->parity = SP_PARITY_NONE;
1927 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1928 config->parity = -1;
1930 else if (data->term.c_cflag & CMSPAR)
1931 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1934 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1936 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1938 if (data->term.c_cflag & CRTSCTS) {
1939 config->rts = SP_RTS_FLOW_CONTROL;
1940 config->cts = SP_CTS_FLOW_CONTROL;
1942 if (data->termiox_supported && data->rts_flow)
1943 config->rts = SP_RTS_FLOW_CONTROL;
1945 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1947 config->cts = (data->termiox_supported && data->cts_flow) ?
1948 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1951 if (data->termiox_supported && data->dtr_flow)
1952 config->dtr = SP_DTR_FLOW_CONTROL;
1954 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1956 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1957 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1959 if (data->term.c_iflag & IXOFF) {
1960 if (data->term.c_iflag & IXON)
1961 config->xon_xoff = SP_XONXOFF_INOUT;
1963 config->xon_xoff = SP_XONXOFF_IN;
1965 if (data->term.c_iflag & IXON)
1966 config->xon_xoff = SP_XONXOFF_OUT;
1968 config->xon_xoff = SP_XONXOFF_DISABLED;
1975 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1976 const struct sp_port_config *config)
1980 BAUD_TYPE baud_nonstd;
1984 #ifdef USE_TERMIOS_SPEED
1985 int baud_nonstd = 0;
1988 TRACE("%p, %p, %p", port, data, config);
1990 DEBUG_FMT("Setting configuration for port %s", port->name);
1994 TRY(await_write_completion(port));
1996 if (config->baudrate >= 0) {
1997 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1998 if (config->baudrate == std_baudrates[i].value) {
1999 data->dcb.BaudRate = std_baudrates[i].index;
2004 if (i == NUM_STD_BAUDRATES)
2005 data->dcb.BaudRate = config->baudrate;
2007 /* Allocate write buffer for 50ms of data at baud rate. */
2008 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
2009 port->write_buf = realloc(port->write_buf,
2010 port->write_buf_size);
2012 if (!port->write_buf)
2013 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
2016 if (config->bits >= 0)
2017 data->dcb.ByteSize = config->bits;
2019 if (config->parity >= 0) {
2020 switch (config->parity) {
2021 case SP_PARITY_NONE:
2022 data->dcb.Parity = NOPARITY;
2025 data->dcb.Parity = ODDPARITY;
2027 case SP_PARITY_EVEN:
2028 data->dcb.Parity = EVENPARITY;
2030 case SP_PARITY_MARK:
2031 data->dcb.Parity = MARKPARITY;
2033 case SP_PARITY_SPACE:
2034 data->dcb.Parity = SPACEPARITY;
2037 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2041 if (config->stopbits >= 0) {
2042 switch (config->stopbits) {
2043 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
2045 data->dcb.StopBits = ONESTOPBIT;
2048 data->dcb.StopBits = TWOSTOPBITS;
2051 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
2055 if (config->rts >= 0) {
2056 switch (config->rts) {
2058 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
2061 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
2063 case SP_RTS_FLOW_CONTROL:
2064 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
2067 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
2071 if (config->cts >= 0) {
2072 switch (config->cts) {
2074 data->dcb.fOutxCtsFlow = FALSE;
2076 case SP_CTS_FLOW_CONTROL:
2077 data->dcb.fOutxCtsFlow = TRUE;
2080 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
2084 if (config->dtr >= 0) {
2085 switch (config->dtr) {
2087 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
2090 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
2092 case SP_DTR_FLOW_CONTROL:
2093 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
2096 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
2100 if (config->dsr >= 0) {
2101 switch (config->dsr) {
2103 data->dcb.fOutxDsrFlow = FALSE;
2105 case SP_DSR_FLOW_CONTROL:
2106 data->dcb.fOutxDsrFlow = TRUE;
2109 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2113 if (config->xon_xoff >= 0) {
2114 switch (config->xon_xoff) {
2115 case SP_XONXOFF_DISABLED:
2116 data->dcb.fInX = FALSE;
2117 data->dcb.fOutX = FALSE;
2120 data->dcb.fInX = TRUE;
2121 data->dcb.fOutX = FALSE;
2123 case SP_XONXOFF_OUT:
2124 data->dcb.fInX = FALSE;
2125 data->dcb.fOutX = TRUE;
2127 case SP_XONXOFF_INOUT:
2128 data->dcb.fInX = TRUE;
2129 data->dcb.fOutX = TRUE;
2132 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2136 if (!SetCommState(port->hdl, &data->dcb))
2137 RETURN_FAIL("SetCommState() failed");
2143 if (config->baudrate >= 0) {
2144 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2145 if (config->baudrate == std_baudrates[i].value) {
2146 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2147 RETURN_FAIL("cfsetospeed() failed");
2149 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2150 RETURN_FAIL("cfsetispeed() failed");
2155 /* Non-standard baud rate */
2156 if (i == NUM_STD_BAUDRATES) {
2158 /* Set "dummy" baud rate. */
2159 if (cfsetspeed(&data->term, B9600) < 0)
2160 RETURN_FAIL("cfsetspeed() failed");
2161 baud_nonstd = config->baudrate;
2162 #elif defined(USE_TERMIOS_SPEED)
2165 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2170 if (config->bits >= 0) {
2171 data->term.c_cflag &= ~CSIZE;
2172 switch (config->bits) {
2174 data->term.c_cflag |= CS8;
2177 data->term.c_cflag |= CS7;
2180 data->term.c_cflag |= CS6;
2183 data->term.c_cflag |= CS5;
2186 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2190 if (config->parity >= 0) {
2191 data->term.c_iflag &= ~IGNPAR;
2192 data->term.c_cflag &= ~(PARENB | PARODD);
2194 data->term.c_cflag &= ~CMSPAR;
2196 switch (config->parity) {
2197 case SP_PARITY_NONE:
2198 data->term.c_iflag |= IGNPAR;
2200 case SP_PARITY_EVEN:
2201 data->term.c_cflag |= PARENB;
2204 data->term.c_cflag |= PARENB | PARODD;
2207 case SP_PARITY_MARK:
2208 data->term.c_cflag |= PARENB | PARODD;
2209 data->term.c_cflag |= CMSPAR;
2211 case SP_PARITY_SPACE:
2212 data->term.c_cflag |= PARENB;
2213 data->term.c_cflag |= CMSPAR;
2216 case SP_PARITY_MARK:
2217 case SP_PARITY_SPACE:
2218 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2221 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2225 if (config->stopbits >= 0) {
2226 data->term.c_cflag &= ~CSTOPB;
2227 switch (config->stopbits) {
2229 data->term.c_cflag &= ~CSTOPB;
2232 data->term.c_cflag |= CSTOPB;
2235 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2239 if (config->rts >= 0 || config->cts >= 0) {
2240 if (data->termiox_supported) {
2241 data->rts_flow = data->cts_flow = 0;
2242 switch (config->rts) {
2245 controlbits = TIOCM_RTS;
2246 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2247 RETURN_FAIL("Setting RTS signal level failed");
2249 case SP_RTS_FLOW_CONTROL:
2255 if (config->cts == SP_CTS_FLOW_CONTROL)
2258 if (data->rts_flow && data->cts_flow)
2259 data->term.c_iflag |= CRTSCTS;
2261 data->term.c_iflag &= ~CRTSCTS;
2263 /* Asymmetric use of RTS/CTS not supported. */
2264 if (data->term.c_iflag & CRTSCTS) {
2265 /* Flow control can only be disabled for both RTS & CTS together. */
2266 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2267 if (config->cts != SP_CTS_IGNORE)
2268 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2270 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2271 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2272 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2275 /* Flow control can only be enabled for both RTS & CTS together. */
2276 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2277 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2278 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2281 if (config->rts >= 0) {
2282 if (config->rts == SP_RTS_FLOW_CONTROL) {
2283 data->term.c_iflag |= CRTSCTS;
2285 controlbits = TIOCM_RTS;
2286 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2288 RETURN_FAIL("Setting RTS signal level failed");
2294 if (config->dtr >= 0 || config->dsr >= 0) {
2295 if (data->termiox_supported) {
2296 data->dtr_flow = data->dsr_flow = 0;
2297 switch (config->dtr) {
2300 controlbits = TIOCM_DTR;
2301 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2302 RETURN_FAIL("Setting DTR signal level failed");
2304 case SP_DTR_FLOW_CONTROL:
2310 if (config->dsr == SP_DSR_FLOW_CONTROL)
2313 /* DTR/DSR flow control not supported. */
2314 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2315 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2317 if (config->dtr >= 0) {
2318 controlbits = TIOCM_DTR;
2319 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2321 RETURN_FAIL("Setting DTR signal level failed");
2326 if (config->xon_xoff >= 0) {
2327 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2328 switch (config->xon_xoff) {
2329 case SP_XONXOFF_DISABLED:
2332 data->term.c_iflag |= IXOFF;
2334 case SP_XONXOFF_OUT:
2335 data->term.c_iflag |= IXON | IXANY;
2337 case SP_XONXOFF_INOUT:
2338 data->term.c_iflag |= IXON | IXOFF | IXANY;
2341 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2345 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2346 RETURN_FAIL("tcsetattr() failed");
2349 if (baud_nonstd != B0) {
2350 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2351 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2353 * Set baud rates in data->term to correct, but incompatible
2354 * with tcsetattr() value, same as delivered by tcgetattr().
2356 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2357 RETURN_FAIL("cfsetspeed() failed");
2359 #elif defined(__linux__)
2360 #ifdef USE_TERMIOS_SPEED
2362 TRY(set_baudrate(port->fd, config->baudrate));
2365 if (data->termiox_supported)
2366 TRY(set_flow(port->fd, data));
2370 #endif /* !_WIN32 */
2375 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2377 struct sp_port_config *config;
2379 TRACE("%p", config_ptr);
2382 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2386 if (!(config = malloc(sizeof(struct sp_port_config))))
2387 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2389 config->baudrate = -1;
2391 config->parity = -1;
2392 config->stopbits = -1;
2398 *config_ptr = config;
2403 SP_API void sp_free_config(struct sp_port_config *config)
2405 TRACE("%p", config);
2408 DEBUG("Null config");
2415 SP_API enum sp_return sp_get_config(struct sp_port *port,
2416 struct sp_port_config *config)
2418 struct port_data data;
2420 TRACE("%p, %p", port, config);
2425 RETURN_ERROR(SP_ERR_ARG, "Null config");
2427 TRY(get_config(port, &data, config));
2432 SP_API enum sp_return sp_set_config(struct sp_port *port,
2433 const struct sp_port_config *config)
2435 struct port_data data;
2436 struct sp_port_config prev_config;
2438 TRACE("%p, %p", port, config);
2443 RETURN_ERROR(SP_ERR_ARG, "Null config");
2445 TRY(get_config(port, &data, &prev_config));
2446 TRY(set_config(port, &data, config));
2451 #define CREATE_ACCESSORS(x, type) \
2452 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2453 struct port_data data; \
2454 struct sp_port_config config; \
2455 TRACE("%p, %d", port, x); \
2456 CHECK_OPEN_PORT(); \
2457 TRY(get_config(port, &data, &config)); \
2459 TRY(set_config(port, &data, &config)); \
2462 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2464 TRACE("%p, %p", config, x); \
2466 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2468 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2472 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2474 TRACE("%p, %d", config, x); \
2476 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2481 CREATE_ACCESSORS(baudrate, int)
2482 CREATE_ACCESSORS(bits, int)
2483 CREATE_ACCESSORS(parity, enum sp_parity)
2484 CREATE_ACCESSORS(stopbits, int)
2485 CREATE_ACCESSORS(rts, enum sp_rts)
2486 CREATE_ACCESSORS(cts, enum sp_cts)
2487 CREATE_ACCESSORS(dtr, enum sp_dtr)
2488 CREATE_ACCESSORS(dsr, enum sp_dsr)
2489 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2491 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2492 enum sp_flowcontrol flowcontrol)
2495 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2497 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2498 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2500 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2501 config->xon_xoff = SP_XONXOFF_INOUT;
2503 config->xon_xoff = SP_XONXOFF_DISABLED;
2505 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2506 config->rts = SP_RTS_FLOW_CONTROL;
2507 config->cts = SP_CTS_FLOW_CONTROL;
2509 if (config->rts == SP_RTS_FLOW_CONTROL)
2510 config->rts = SP_RTS_ON;
2511 config->cts = SP_CTS_IGNORE;
2514 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2515 config->dtr = SP_DTR_FLOW_CONTROL;
2516 config->dsr = SP_DSR_FLOW_CONTROL;
2518 if (config->dtr == SP_DTR_FLOW_CONTROL)
2519 config->dtr = SP_DTR_ON;
2520 config->dsr = SP_DSR_IGNORE;
2526 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2527 enum sp_flowcontrol flowcontrol)
2529 struct port_data data;
2530 struct sp_port_config config;
2532 TRACE("%p, %d", port, flowcontrol);
2536 TRY(get_config(port, &data, &config));
2538 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2540 TRY(set_config(port, &data, &config));
2545 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2546 enum sp_signal *signals)
2548 TRACE("%p, %p", port, signals);
2553 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2555 DEBUG_FMT("Getting control signals for port %s", port->name);
2560 if (GetCommModemStatus(port->hdl, &bits) == 0)
2561 RETURN_FAIL("GetCommModemStatus() failed");
2562 if (bits & MS_CTS_ON)
2563 *signals |= SP_SIG_CTS;
2564 if (bits & MS_DSR_ON)
2565 *signals |= SP_SIG_DSR;
2566 if (bits & MS_RLSD_ON)
2567 *signals |= SP_SIG_DCD;
2568 if (bits & MS_RING_ON)
2569 *signals |= SP_SIG_RI;
2572 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2573 RETURN_FAIL("TIOCMGET ioctl failed");
2574 if (bits & TIOCM_CTS)
2575 *signals |= SP_SIG_CTS;
2576 if (bits & TIOCM_DSR)
2577 *signals |= SP_SIG_DSR;
2578 if (bits & TIOCM_CAR)
2579 *signals |= SP_SIG_DCD;
2580 if (bits & TIOCM_RNG)
2581 *signals |= SP_SIG_RI;
2586 SP_API enum sp_return sp_start_break(struct sp_port *port)
2592 if (SetCommBreak(port->hdl) == 0)
2593 RETURN_FAIL("SetCommBreak() failed");
2595 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2596 RETURN_FAIL("TIOCSBRK ioctl failed");
2602 SP_API enum sp_return sp_end_break(struct sp_port *port)
2608 if (ClearCommBreak(port->hdl) == 0)
2609 RETURN_FAIL("ClearCommBreak() failed");
2611 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2612 RETURN_FAIL("TIOCCBRK ioctl failed");
2618 SP_API int sp_last_error_code(void)
2622 RETURN_INT(GetLastError());
2628 SP_API char *sp_last_error_message(void)
2634 DWORD error = GetLastError();
2636 DWORD length = FormatMessage(
2637 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2638 FORMAT_MESSAGE_FROM_SYSTEM |
2639 FORMAT_MESSAGE_IGNORE_INSERTS,
2642 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2646 if (length >= 2 && message[length - 2] == '\r')
2647 message[length - 2] = '\0';
2649 RETURN_STRING(message);
2651 RETURN_STRING(strerror(errno));
2655 SP_API void sp_free_error_message(char *message)
2657 TRACE("%s", message);
2668 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2670 TRACE("%p", handler);
2672 sp_debug_handler = handler;
2677 SP_API void sp_default_debug_handler(const char *format, ...)
2680 va_start(args, format);
2681 if (getenv("LIBSERIALPORT_DEBUG")) {
2682 fputs("sp: ", stderr);
2683 vfprintf(stderr, format, args);
2688 SP_API int sp_get_major_package_version(void)
2690 return SP_PACKAGE_VERSION_MAJOR;
2693 SP_API int sp_get_minor_package_version(void)
2695 return SP_PACKAGE_VERSION_MINOR;
2698 SP_API int sp_get_micro_package_version(void)
2700 return SP_PACKAGE_VERSION_MICRO;
2703 SP_API const char *sp_get_package_version_string(void)
2705 return SP_PACKAGE_VERSION_STRING;
2708 SP_API int sp_get_current_lib_version(void)
2710 return SP_LIB_VERSION_CURRENT;
2713 SP_API int sp_get_revision_lib_version(void)
2715 return SP_LIB_VERSION_REVISION;
2718 SP_API int sp_get_age_lib_version(void)
2720 return SP_LIB_VERSION_AGE;
2723 SP_API const char *sp_get_lib_version_string(void)
2725 return SP_LIB_VERSION_STRING;