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);
60 /* Timing abstraction */
68 struct time start, delta, now, end;
69 struct timeval delta_tv;
73 #define TIME_ZERO {.tv = {0, 0}}
74 #define TIME_MS(ms) {.tv = {ms / 1000, (ms % 1000) * 1000}}
76 const struct time max_delta = TIME_MS(INT_MAX);
78 static void time_get(struct time *time)
80 #ifdef HAVE_CLOCK_GETTIME
82 if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
83 clock_gettime(CLOCK_REALTIME, &ts);
84 time->tv.tv_sec = ts.tv_sec;
85 time->tv.tv_usec = ts.tv_nsec / 1000;
86 #elif defined(__APPLE__)
87 mach_timebase_info_data_t info;
88 mach_timebase_info(&info);
89 uint64_t ticks = mach_absolute_time();
90 uint64_t ns = (ticks * info.numer) / info.denom;
91 time->tv.tv_sec = ns / 1000000000;
92 time->tv.tv_usec = (ns % 1000000000) / 1000;
94 gettimeofday(&time->tv, NULL);
98 static void time_set_ms(struct time *time, unsigned int ms)
100 time->tv.tv_sec = ms / 1000;
101 time->tv.tv_usec = (ms % 1000) * 1000;
104 static void time_add(const struct time *a,
105 const struct time *b, struct time *result)
107 timeradd(&a->tv, &b->tv, &result->tv);
110 static void time_sub(const struct time *a,
111 const struct time *b, struct time *result)
113 timersub(&a->tv, &b->tv, &result->tv);
116 static bool time_greater(const struct time *a, const struct time *b)
118 return timercmp(&a->tv, &b->tv, >);
121 static void time_as_timeval(const struct time *time, struct timeval *tv)
126 static unsigned int time_as_ms(const struct time *time)
128 return time->tv.tv_sec * 1000 + time->tv.tv_usec / 1000;
131 static void timeout_start(struct timeout *timeout, unsigned int timeout_ms)
133 timeout->ms = timeout_ms;
135 timeout->overflow = (timeout->ms > INT_MAX);
137 /* Get time at start of operation. */
138 time_get(&timeout->start);
139 /* Define duration of timeout. */
140 time_set_ms(&timeout->delta, timeout_ms);
141 /* Calculate time at which we should give up. */
142 time_add(&timeout->start, &timeout->delta, &timeout->end);
145 static bool timeout_check(struct timeout *timeout)
147 if (timeout->ms == 0)
150 time_get(&timeout->now);
151 time_sub(&timeout->end, &timeout->now, &timeout->delta);
152 if ((timeout->overflow = time_greater(&timeout->delta, &max_delta)))
153 timeout->delta = max_delta;
155 return time_greater(&timeout->now, &timeout->end);
158 static struct timeval *timeout_timeval(struct timeout *timeout)
160 if (timeout->ms == 0)
163 time_as_timeval(&timeout->delta, &timeout->delta_tv);
165 return &timeout->delta_tv;
168 static unsigned int timeout_remaining_ms(struct timeout *timeout)
170 if (timeout->ms == 0)
172 else if (timeout->overflow)
175 return time_as_ms(&timeout->delta);
180 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
182 struct sp_port *port;
183 #ifndef NO_PORT_METADATA
188 TRACE("%s, %p", portname, port_ptr);
191 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
196 RETURN_ERROR(SP_ERR_ARG, "Null port name");
198 DEBUG_FMT("Building structure for port %s", portname);
200 #if !defined(_WIN32) && defined(HAVE_REALPATH)
202 * get_port_details() below tries to be too smart and figure out
203 * some transport properties from the port name which breaks with
204 * symlinks. Therefore we canonicalize the portname first.
206 char pathbuf[PATH_MAX + 1];
207 char *res = realpath(portname, pathbuf);
209 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
214 if (!(port = malloc(sizeof(struct sp_port))))
215 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
217 len = strlen(portname) + 1;
219 if (!(port->name = malloc(len))) {
221 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
224 memcpy(port->name, portname, len);
227 port->usb_path = NULL;
228 port->hdl = INVALID_HANDLE_VALUE;
229 port->write_buf = NULL;
230 port->write_buf_size = 0;
235 port->description = NULL;
236 port->transport = SP_TRANSPORT_NATIVE;
238 port->usb_address = -1;
241 port->usb_manufacturer = NULL;
242 port->usb_product = NULL;
243 port->usb_serial = NULL;
244 port->bluetooth_address = NULL;
246 #ifndef NO_PORT_METADATA
247 if ((ret = get_port_details(port)) != SP_OK) {
258 SP_API char *sp_get_port_name(const struct sp_port *port)
265 RETURN_STRING(port->name);
268 SP_API char *sp_get_port_description(const struct sp_port *port)
272 if (!port || !port->description)
275 RETURN_STRING(port->description);
278 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
283 RETURN_ERROR(SP_ERR_ARG, "Null port");
285 RETURN_INT(port->transport);
288 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
289 int *usb_bus,int *usb_address)
294 RETURN_ERROR(SP_ERR_ARG, "Null port");
295 if (port->transport != SP_TRANSPORT_USB)
296 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
297 if (port->usb_bus < 0 || port->usb_address < 0)
298 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
301 *usb_bus = port->usb_bus;
303 *usb_address = port->usb_address;
308 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
309 int *usb_vid, int *usb_pid)
314 RETURN_ERROR(SP_ERR_ARG, "Null port");
315 if (port->transport != SP_TRANSPORT_USB)
316 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
317 if (port->usb_vid < 0 || port->usb_pid < 0)
318 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
321 *usb_vid = port->usb_vid;
323 *usb_pid = port->usb_pid;
328 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
332 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
335 RETURN_STRING(port->usb_manufacturer);
338 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
342 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
345 RETURN_STRING(port->usb_product);
348 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
352 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
355 RETURN_STRING(port->usb_serial);
358 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
362 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
363 || !port->bluetooth_address)
366 RETURN_STRING(port->bluetooth_address);
369 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
372 TRACE("%p, %p", port, result_ptr);
375 RETURN_ERROR(SP_ERR_ARG, "Null port");
377 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
380 HANDLE *handle_ptr = result_ptr;
381 *handle_ptr = port->hdl;
383 int *fd_ptr = result_ptr;
390 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
391 struct sp_port **copy_ptr)
393 TRACE("%p, %p", port, copy_ptr);
396 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
401 RETURN_ERROR(SP_ERR_ARG, "Null port");
404 RETURN_ERROR(SP_ERR_ARG, "Null port name");
406 DEBUG("Copying port structure");
408 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
411 SP_API void sp_free_port(struct sp_port *port)
420 DEBUG("Freeing port structure");
424 if (port->description)
425 free(port->description);
426 if (port->usb_manufacturer)
427 free(port->usb_manufacturer);
428 if (port->usb_product)
429 free(port->usb_product);
430 if (port->usb_serial)
431 free(port->usb_serial);
432 if (port->bluetooth_address)
433 free(port->bluetooth_address);
436 free(port->usb_path);
438 free(port->write_buf);
446 SP_PRIV struct sp_port **list_append(struct sp_port **list,
447 const char *portname)
452 for (count = 0; list[count]; count++)
454 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
457 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
459 list[count + 1] = NULL;
463 sp_free_port_list(list);
467 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
469 #ifndef NO_ENUMERATION
470 struct sp_port **list;
474 TRACE("%p", list_ptr);
477 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
481 #ifdef NO_ENUMERATION
482 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
484 DEBUG("Enumerating ports");
486 if (!(list = malloc(sizeof(struct sp_port *))))
487 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
491 ret = list_ports(&list);
496 sp_free_port_list(list);
504 SP_API void sp_free_port_list(struct sp_port **list)
515 DEBUG("Freeing port list");
517 for (i = 0; list[i]; i++)
518 sp_free_port(list[i]);
524 #define CHECK_PORT() do { \
526 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
528 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
531 #define CHECK_PORT_HANDLE() do { \
532 if (port->hdl == INVALID_HANDLE_VALUE) \
533 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
536 #define CHECK_PORT_HANDLE() do { \
538 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
541 #define CHECK_OPEN_PORT() do { \
543 CHECK_PORT_HANDLE(); \
547 /** To be called after port receive buffer is emptied. */
548 static enum sp_return restart_wait(struct sp_port *port)
552 if (port->wait_running) {
553 /* Check status of running wait operation. */
554 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
555 &wait_result, FALSE)) {
556 DEBUG("Previous wait completed");
557 port->wait_running = FALSE;
558 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
559 DEBUG("Previous wait still running");
562 RETURN_FAIL("GetOverlappedResult() failed");
566 if (!port->wait_running) {
567 /* Start new wait operation. */
568 if (WaitCommEvent(port->hdl, &port->events,
570 DEBUG("New wait returned, events already pending");
571 } else if (GetLastError() == ERROR_IO_PENDING) {
572 DEBUG("New wait running in background");
573 port->wait_running = TRUE;
575 RETURN_FAIL("WaitCommEvent() failed");
583 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
585 struct port_data data;
586 struct sp_port_config config;
589 TRACE("%p, 0x%x", port, flags);
593 if (flags > SP_MODE_READ_WRITE)
594 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
596 DEBUG_FMT("Opening port %s", port->name);
599 DWORD desired_access = 0, flags_and_attributes = 0, errors;
600 char *escaped_port_name;
603 /* Prefix port name with '\\.\' to work with ports above COM9. */
604 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
605 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
606 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
608 /* Map 'flags' to the OS-specific settings. */
609 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
610 if (flags & SP_MODE_READ)
611 desired_access |= GENERIC_READ;
612 if (flags & SP_MODE_WRITE)
613 desired_access |= GENERIC_WRITE;
615 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
616 OPEN_EXISTING, flags_and_attributes, 0);
618 free(escaped_port_name);
620 if (port->hdl == INVALID_HANDLE_VALUE)
621 RETURN_FAIL("Port CreateFile() failed");
623 /* All timeouts initially disabled. */
624 port->timeouts.ReadIntervalTimeout = 0;
625 port->timeouts.ReadTotalTimeoutMultiplier = 0;
626 port->timeouts.ReadTotalTimeoutConstant = 0;
627 port->timeouts.WriteTotalTimeoutMultiplier = 0;
628 port->timeouts.WriteTotalTimeoutConstant = 0;
630 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
632 RETURN_FAIL("SetCommTimeouts() failed");
635 /* Prepare OVERLAPPED structures. */
636 #define INIT_OVERLAPPED(ovl) do { \
637 memset(&port->ovl, 0, sizeof(port->ovl)); \
638 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
639 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
640 == INVALID_HANDLE_VALUE) { \
642 RETURN_FAIL(#ovl "CreateEvent() failed"); \
646 INIT_OVERLAPPED(read_ovl);
647 INIT_OVERLAPPED(write_ovl);
648 INIT_OVERLAPPED(wait_ovl);
650 /* Set event mask for RX and error events. */
651 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
653 RETURN_FAIL("SetCommMask() failed");
656 port->writing = FALSE;
657 port->wait_running = FALSE;
659 ret = restart_wait(port);
666 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
668 /* Map 'flags' to the OS-specific settings. */
669 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
670 flags_local |= O_RDWR;
671 else if (flags & SP_MODE_READ)
672 flags_local |= O_RDONLY;
673 else if (flags & SP_MODE_WRITE)
674 flags_local |= O_WRONLY;
676 if ((port->fd = open(port->name, flags_local)) < 0)
677 RETURN_FAIL("open() failed");
680 ret = get_config(port, &data, &config);
687 /* Set sane port settings. */
689 data.dcb.fBinary = TRUE;
690 data.dcb.fDsrSensitivity = FALSE;
691 data.dcb.fErrorChar = FALSE;
692 data.dcb.fNull = FALSE;
693 data.dcb.fAbortOnError = FALSE;
695 /* Turn off all fancy termios tricks, give us a raw channel. */
696 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
698 data.term.c_iflag &= ~IUCLC;
700 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
702 data.term.c_oflag &= ~OLCUC;
705 data.term.c_oflag &= ~NLDLY;
708 data.term.c_oflag &= ~CRDLY;
711 data.term.c_oflag &= ~TABDLY;
714 data.term.c_oflag &= ~BSDLY;
717 data.term.c_oflag &= ~VTDLY;
720 data.term.c_oflag &= ~FFDLY;
723 data.term.c_oflag &= ~OFILL;
725 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
726 data.term.c_cc[VMIN] = 0;
727 data.term.c_cc[VTIME] = 0;
729 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
730 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
734 if (ClearCommError(port->hdl, &errors, &status) == 0)
735 RETURN_FAIL("ClearCommError() failed");
738 ret = set_config(port, &data, &config);
748 SP_API enum sp_return sp_close(struct sp_port *port)
754 DEBUG_FMT("Closing port %s", port->name);
757 /* Returns non-zero upon success, 0 upon failure. */
758 if (CloseHandle(port->hdl) == 0)
759 RETURN_FAIL("Port CloseHandle() failed");
760 port->hdl = INVALID_HANDLE_VALUE;
762 /* Close event handles for overlapped structures. */
763 #define CLOSE_OVERLAPPED(ovl) do { \
764 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
765 CloseHandle(port->ovl.hEvent) == 0) \
766 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
768 CLOSE_OVERLAPPED(read_ovl);
769 CLOSE_OVERLAPPED(write_ovl);
770 CLOSE_OVERLAPPED(wait_ovl);
772 if (port->write_buf) {
773 free(port->write_buf);
774 port->write_buf = NULL;
777 /* Returns 0 upon success, -1 upon failure. */
778 if (close(port->fd) == -1)
779 RETURN_FAIL("close() failed");
786 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
788 TRACE("%p, 0x%x", port, buffers);
792 if (buffers > SP_BUF_BOTH)
793 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
795 const char *buffer_names[] = {"no", "input", "output", "both"};
797 DEBUG_FMT("Flushing %s buffers on port %s",
798 buffer_names[buffers], port->name);
802 if (buffers & SP_BUF_INPUT)
803 flags |= PURGE_RXCLEAR;
804 if (buffers & SP_BUF_OUTPUT)
805 flags |= PURGE_TXCLEAR;
807 /* Returns non-zero upon success, 0 upon failure. */
808 if (PurgeComm(port->hdl, flags) == 0)
809 RETURN_FAIL("PurgeComm() failed");
811 if (buffers & SP_BUF_INPUT)
812 TRY(restart_wait(port));
815 if (buffers == SP_BUF_BOTH)
817 else if (buffers == SP_BUF_INPUT)
819 else if (buffers == SP_BUF_OUTPUT)
822 /* Returns 0 upon success, -1 upon failure. */
823 if (tcflush(port->fd, flags) < 0)
824 RETURN_FAIL("tcflush() failed");
829 SP_API enum sp_return sp_drain(struct sp_port *port)
835 DEBUG_FMT("Draining port %s", port->name);
838 /* Returns non-zero upon success, 0 upon failure. */
839 if (FlushFileBuffers(port->hdl) == 0)
840 RETURN_FAIL("FlushFileBuffers() failed");
845 #if defined(__ANDROID__) && (__ANDROID_API__ < 21)
846 /* Android only has tcdrain from platform 21 onwards.
847 * On previous API versions, use the ioctl directly. */
849 result = ioctl(port->fd, TCSBRK, &arg);
851 result = tcdrain(port->fd);
854 if (errno == EINTR) {
855 DEBUG("tcdrain() was interrupted");
858 RETURN_FAIL("tcdrain() failed");
868 static enum sp_return await_write_completion(struct sp_port *port)
874 /* Wait for previous non-blocking write to complete, if any. */
876 DEBUG("Waiting for previous write to complete");
877 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
880 RETURN_FAIL("Previous write failed to complete");
881 DEBUG("Previous write completed");
888 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
889 size_t count, unsigned int timeout_ms)
891 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
896 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
899 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
900 count, port->name, timeout_ms);
902 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
909 DWORD bytes_written = 0;
911 TRY(await_write_completion(port));
914 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
915 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
916 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
917 RETURN_FAIL("SetCommTimeouts() failed");
920 /* Reduce count if it exceeds the WriteFile limit. */
921 if (count > WRITEFILE_MAX_SIZE)
922 count = WRITEFILE_MAX_SIZE;
925 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
926 DEBUG("Write completed immediately");
928 } else if (GetLastError() == ERROR_IO_PENDING) {
929 DEBUG("Waiting for write to complete");
930 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
931 if (GetLastError() == ERROR_SEM_TIMEOUT) {
932 DEBUG("Write timed out");
935 RETURN_FAIL("GetOverlappedResult() failed");
938 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
939 RETURN_INT(bytes_written);
941 RETURN_FAIL("WriteFile() failed");
944 size_t bytes_written = 0;
945 unsigned char *ptr = (unsigned char *) buf;
946 struct timeout timeout;
951 timeout_start(&timeout, timeout_ms);
954 FD_SET(port->fd, &fds);
956 /* Loop until we have written the requested number of bytes. */
957 while (bytes_written < count) {
959 * Check timeout only if we have run select() at least once,
960 * to avoid any issues if a short timeout is reached before
961 * select() is even run.
963 if (started && timeout_check(&timeout))
966 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
969 if (errno == EINTR) {
970 DEBUG("select() call was interrupted, repeating");
973 RETURN_FAIL("select() failed");
975 } else if (result == 0) {
976 /* Timeout has expired. */
981 result = write(port->fd, ptr, count - bytes_written);
985 /* This shouldn't happen because we did a select() first, but handle anyway. */
988 /* This is an actual failure. */
989 RETURN_FAIL("write() failed");
992 bytes_written += result;
996 if (bytes_written < count)
997 DEBUG("Write timed out");
999 RETURN_INT(bytes_written);
1003 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
1004 const void *buf, size_t count)
1006 TRACE("%p, %p, %d", port, buf, count);
1011 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1013 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
1021 /* Check whether previous write is complete. */
1022 if (port->writing) {
1023 if (HasOverlappedIoCompleted(&port->write_ovl)) {
1024 DEBUG("Previous write completed");
1027 DEBUG("Previous write not complete");
1028 /* Can't take a new write until the previous one finishes. */
1034 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
1035 port->timeouts.WriteTotalTimeoutConstant = 0;
1036 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1037 RETURN_FAIL("SetCommTimeouts() failed");
1040 /* Reduce count if it exceeds the WriteFile limit. */
1041 if (count > WRITEFILE_MAX_SIZE)
1042 count = WRITEFILE_MAX_SIZE;
1044 /* Copy data to our write buffer. */
1045 buf_bytes = min(port->write_buf_size, count);
1046 memcpy(port->write_buf, buf, buf_bytes);
1048 /* Start asynchronous write. */
1049 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
1050 if (GetLastError() == ERROR_IO_PENDING) {
1051 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
1052 DEBUG("Asynchronous write completed immediately");
1054 DEBUG("Asynchronous write running");
1056 /* Actual failure of some kind. */
1057 RETURN_FAIL("WriteFile() failed");
1061 DEBUG("All bytes written immediately");
1063 RETURN_INT(buf_bytes);
1065 /* Returns the number of bytes written, or -1 upon failure. */
1066 ssize_t written = write(port->fd, buf, count);
1069 if (errno == EAGAIN)
1070 // Buffer is full, no bytes written.
1073 RETURN_FAIL("write() failed");
1075 RETURN_INT(written);
1081 /* Restart wait operation if buffer was emptied. */
1082 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1087 if (bytes_read == 0)
1090 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1091 RETURN_FAIL("ClearCommError() failed");
1093 if (comstat.cbInQue == 0)
1094 TRY(restart_wait(port));
1100 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1101 size_t count, unsigned int timeout_ms)
1103 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1108 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1111 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1112 count, port->name, timeout_ms);
1114 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1121 DWORD bytes_read = 0;
1124 if (port->timeouts.ReadIntervalTimeout != 0 ||
1125 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1126 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1127 port->timeouts.ReadIntervalTimeout = 0;
1128 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1129 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1130 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1131 RETURN_FAIL("SetCommTimeouts() failed");
1135 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1136 DEBUG("Read completed immediately");
1138 } else if (GetLastError() == ERROR_IO_PENDING) {
1139 DEBUG("Waiting for read to complete");
1140 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1141 RETURN_FAIL("GetOverlappedResult() failed");
1142 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1144 RETURN_FAIL("ReadFile() failed");
1147 TRY(restart_wait_if_needed(port, bytes_read));
1149 RETURN_INT(bytes_read);
1152 size_t bytes_read = 0;
1153 unsigned char *ptr = (unsigned char *) buf;
1154 struct timeout timeout;
1159 timeout_start(&timeout, timeout_ms);
1162 FD_SET(port->fd, &fds);
1164 /* Loop until we have the requested number of bytes. */
1165 while (bytes_read < count) {
1167 * Check timeout only if we have run select() at least once,
1168 * to avoid any issues if a short timeout is reached before
1169 * select() is even run.
1171 if (started && timeout_check(&timeout))
1172 /* Timeout has expired. */
1175 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1178 if (errno == EINTR) {
1179 DEBUG("select() call was interrupted, repeating");
1182 RETURN_FAIL("select() failed");
1184 } else if (result == 0) {
1185 /* Timeout has expired. */
1190 result = read(port->fd, ptr, count - bytes_read);
1193 if (errno == EAGAIN)
1195 * This shouldn't happen because we did a
1196 * select() first, but handle anyway.
1200 /* This is an actual failure. */
1201 RETURN_FAIL("read() failed");
1204 bytes_read += result;
1208 if (bytes_read < count)
1209 DEBUG("Read timed out");
1211 RETURN_INT(bytes_read);
1215 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1216 size_t count, unsigned int timeout_ms)
1218 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1223 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1226 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1229 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1230 count, port->name, timeout_ms);
1232 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1236 DWORD bytes_read = 0;
1238 /* If timeout_ms == 0, set maximum timeout. */
1239 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1242 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1243 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1244 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1245 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1246 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1247 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1248 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1249 RETURN_FAIL("SetCommTimeouts() failed");
1252 /* Loop until we have at least one byte, or timeout is reached. */
1253 while (bytes_read == 0) {
1255 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1256 DEBUG("Read completed immediately");
1257 } else if (GetLastError() == ERROR_IO_PENDING) {
1258 DEBUG("Waiting for read to complete");
1259 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1260 RETURN_FAIL("GetOverlappedResult() failed");
1261 if (bytes_read > 0) {
1262 DEBUG("Read completed");
1263 } else if (timeout_ms > 0) {
1264 DEBUG("Read timed out");
1267 DEBUG("Restarting read");
1270 RETURN_FAIL("ReadFile() failed");
1274 TRY(restart_wait_if_needed(port, bytes_read));
1276 RETURN_INT(bytes_read);
1279 size_t bytes_read = 0;
1280 struct timeout timeout;
1285 timeout_start(&timeout, timeout_ms);
1288 FD_SET(port->fd, &fds);
1290 /* Loop until we have at least one byte, or timeout is reached. */
1291 while (bytes_read == 0) {
1293 * Check timeout only if we have run select() at least once,
1294 * to avoid any issues if a short timeout is reached before
1295 * select() is even run.
1297 if (started && timeout_check(&timeout))
1298 /* Timeout has expired. */
1301 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1304 if (errno == EINTR) {
1305 DEBUG("select() call was interrupted, repeating");
1308 RETURN_FAIL("select() failed");
1310 } else if (result == 0) {
1311 /* Timeout has expired. */
1316 result = read(port->fd, buf, count);
1319 if (errno == EAGAIN)
1320 /* This shouldn't happen because we did a select() first, but handle anyway. */
1323 /* This is an actual failure. */
1324 RETURN_FAIL("read() failed");
1327 bytes_read = result;
1330 if (bytes_read == 0)
1331 DEBUG("Read timed out");
1333 RETURN_INT(bytes_read);
1337 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1340 TRACE("%p, %p, %d", port, buf, count);
1345 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1347 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1353 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1354 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1355 port->timeouts.ReadTotalTimeoutConstant != 0) {
1356 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1357 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1358 port->timeouts.ReadTotalTimeoutConstant = 0;
1359 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1360 RETURN_FAIL("SetCommTimeouts() failed");
1364 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1365 if (GetLastError() != ERROR_IO_PENDING)
1366 RETURN_FAIL("ReadFile() failed");
1368 /* Get number of bytes read. */
1369 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1370 RETURN_FAIL("GetOverlappedResult() failed");
1372 TRY(restart_wait_if_needed(port, bytes_read));
1374 RETURN_INT(bytes_read);
1378 /* Returns the number of bytes read, or -1 upon failure. */
1379 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1380 if (errno == EAGAIN)
1381 /* No bytes available. */
1384 /* This is an actual failure. */
1385 RETURN_FAIL("read() failed");
1387 RETURN_INT(bytes_read);
1391 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1397 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1403 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1404 RETURN_FAIL("ClearCommError() failed");
1405 RETURN_INT(comstat.cbInQue);
1408 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1409 RETURN_FAIL("TIOCINQ ioctl failed");
1410 RETURN_INT(bytes_waiting);
1414 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1420 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1426 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1427 RETURN_FAIL("ClearCommError() failed");
1428 RETURN_INT(comstat.cbOutQue);
1431 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1432 RETURN_FAIL("TIOCOUTQ ioctl failed");
1433 RETURN_INT(bytes_waiting);
1437 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1439 struct sp_event_set *result;
1441 TRACE("%p", result_ptr);
1444 RETURN_ERROR(SP_ERR_ARG, "Null result");
1448 if (!(result = malloc(sizeof(struct sp_event_set))))
1449 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1451 memset(result, 0, sizeof(struct sp_event_set));
1453 *result_ptr = result;
1458 static enum sp_return add_handle(struct sp_event_set *event_set,
1459 event_handle handle, enum sp_event mask)
1462 enum sp_event *new_masks;
1464 TRACE("%p, %d, %d", event_set, handle, mask);
1466 if (!(new_handles = realloc(event_set->handles,
1467 sizeof(event_handle) * (event_set->count + 1))))
1468 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1470 event_set->handles = new_handles;
1472 if (!(new_masks = realloc(event_set->masks,
1473 sizeof(enum sp_event) * (event_set->count + 1))))
1474 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1476 event_set->masks = new_masks;
1478 ((event_handle *) event_set->handles)[event_set->count] = handle;
1479 event_set->masks[event_set->count] = mask;
1486 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1487 const struct sp_port *port, enum sp_event mask)
1489 TRACE("%p, %p, %d", event_set, port, mask);
1492 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1495 RETURN_ERROR(SP_ERR_ARG, "Null port");
1497 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1498 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1504 enum sp_event handle_mask;
1505 if ((handle_mask = mask & SP_EVENT_TX_READY))
1506 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1507 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1508 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1510 TRY(add_handle(event_set, port->fd, mask));
1516 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1518 TRACE("%p", event_set);
1521 DEBUG("Null event set");
1525 DEBUG("Freeing event set");
1527 if (event_set->handles)
1528 free(event_set->handles);
1529 if (event_set->masks)
1530 free(event_set->masks);
1537 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1538 unsigned int timeout_ms)
1540 TRACE("%p, %d", event_set, timeout_ms);
1543 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1546 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1547 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1548 RETURN_FAIL("WaitForMultipleObjects() failed");
1552 struct timeout timeout;
1553 int started = 0, result;
1554 struct pollfd *pollfds;
1557 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1558 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1560 for (i = 0; i < event_set->count; i++) {
1561 pollfds[i].fd = ((int *)event_set->handles)[i];
1562 pollfds[i].events = 0;
1563 pollfds[i].revents = 0;
1564 if (event_set->masks[i] & SP_EVENT_RX_READY)
1565 pollfds[i].events |= POLLIN;
1566 if (event_set->masks[i] & SP_EVENT_TX_READY)
1567 pollfds[i].events |= POLLOUT;
1568 if (event_set->masks[i] & SP_EVENT_ERROR)
1569 pollfds[i].events |= POLLERR;
1572 timeout_start(&timeout, timeout_ms);
1574 /* Loop until an event occurs. */
1577 * Check timeout only if we have run poll() at least once,
1578 * to avoid any issues if a short timeout is reached before
1579 * poll() is even run.
1581 if (started && timeout_check(&timeout)) {
1582 DEBUG("Wait timed out");
1586 result = poll(pollfds, event_set->count, timeout_remaining_ms(&timeout));
1590 if (errno == EINTR) {
1591 DEBUG("poll() call was interrupted, repeating");
1595 RETURN_FAIL("poll() failed");
1597 } else if (result == 0) {
1598 DEBUG("poll() timed out");
1599 if (!timeout.overflow)
1602 DEBUG("poll() completed");
1612 #ifdef USE_TERMIOS_SPEED
1613 static enum sp_return get_baudrate(int fd, int *baudrate)
1617 TRACE("%d, %p", fd, baudrate);
1619 DEBUG("Getting baud rate");
1621 if (!(data = malloc(get_termios_size())))
1622 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1624 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1626 RETURN_FAIL("Getting termios failed");
1629 *baudrate = get_termios_speed(data);
1636 static enum sp_return set_baudrate(int fd, int baudrate)
1640 TRACE("%d, %d", fd, baudrate);
1642 DEBUG("Getting baud rate");
1644 if (!(data = malloc(get_termios_size())))
1645 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1647 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1649 RETURN_FAIL("Getting termios failed");
1652 DEBUG("Setting baud rate");
1654 set_termios_speed(data, baudrate);
1656 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1658 RETURN_FAIL("Setting termios failed");
1665 #endif /* USE_TERMIOS_SPEED */
1668 static enum sp_return get_flow(int fd, struct port_data *data)
1672 TRACE("%d, %p", fd, data);
1674 DEBUG("Getting advanced flow control");
1676 if (!(termx = malloc(get_termiox_size())))
1677 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1679 if (ioctl(fd, TCGETX, termx) < 0) {
1681 RETURN_FAIL("Getting termiox failed");
1684 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1685 &data->dtr_flow, &data->dsr_flow);
1692 static enum sp_return set_flow(int fd, struct port_data *data)
1696 TRACE("%d, %p", fd, data);
1698 DEBUG("Getting advanced flow control");
1700 if (!(termx = malloc(get_termiox_size())))
1701 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1703 if (ioctl(fd, TCGETX, termx) < 0) {
1705 RETURN_FAIL("Getting termiox failed");
1708 DEBUG("Setting advanced flow control");
1710 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1711 data->dtr_flow, data->dsr_flow);
1713 if (ioctl(fd, TCSETX, termx) < 0) {
1715 RETURN_FAIL("Setting termiox failed");
1722 #endif /* USE_TERMIOX */
1724 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1725 struct sp_port_config *config)
1729 TRACE("%p, %p, %p", port, data, config);
1731 DEBUG_FMT("Getting configuration for port %s", port->name);
1734 if (!GetCommState(port->hdl, &data->dcb))
1735 RETURN_FAIL("GetCommState() failed");
1737 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1738 if (data->dcb.BaudRate == std_baudrates[i].index) {
1739 config->baudrate = std_baudrates[i].value;
1744 if (i == NUM_STD_BAUDRATES)
1745 /* BaudRate field can be either an index or a custom baud rate. */
1746 config->baudrate = data->dcb.BaudRate;
1748 config->bits = data->dcb.ByteSize;
1750 if (data->dcb.fParity)
1751 switch (data->dcb.Parity) {
1753 config->parity = SP_PARITY_NONE;
1756 config->parity = SP_PARITY_ODD;
1759 config->parity = SP_PARITY_EVEN;
1762 config->parity = SP_PARITY_MARK;
1765 config->parity = SP_PARITY_SPACE;
1768 config->parity = -1;
1771 config->parity = SP_PARITY_NONE;
1773 switch (data->dcb.StopBits) {
1775 config->stopbits = 1;
1778 config->stopbits = 2;
1781 config->stopbits = -1;
1784 switch (data->dcb.fRtsControl) {
1785 case RTS_CONTROL_DISABLE:
1786 config->rts = SP_RTS_OFF;
1788 case RTS_CONTROL_ENABLE:
1789 config->rts = SP_RTS_ON;
1791 case RTS_CONTROL_HANDSHAKE:
1792 config->rts = SP_RTS_FLOW_CONTROL;
1798 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1800 switch (data->dcb.fDtrControl) {
1801 case DTR_CONTROL_DISABLE:
1802 config->dtr = SP_DTR_OFF;
1804 case DTR_CONTROL_ENABLE:
1805 config->dtr = SP_DTR_ON;
1807 case DTR_CONTROL_HANDSHAKE:
1808 config->dtr = SP_DTR_FLOW_CONTROL;
1814 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1816 if (data->dcb.fInX) {
1817 if (data->dcb.fOutX)
1818 config->xon_xoff = SP_XONXOFF_INOUT;
1820 config->xon_xoff = SP_XONXOFF_IN;
1822 if (data->dcb.fOutX)
1823 config->xon_xoff = SP_XONXOFF_OUT;
1825 config->xon_xoff = SP_XONXOFF_DISABLED;
1830 if (tcgetattr(port->fd, &data->term) < 0)
1831 RETURN_FAIL("tcgetattr() failed");
1833 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1834 RETURN_FAIL("TIOCMGET ioctl failed");
1837 int ret = get_flow(port->fd, data);
1839 if (ret == SP_ERR_FAIL && errno == EINVAL)
1840 data->termiox_supported = 0;
1842 RETURN_CODEVAL(ret);
1844 data->termiox_supported = 1;
1846 data->termiox_supported = 0;
1849 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1850 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1851 config->baudrate = std_baudrates[i].value;
1856 if (i == NUM_STD_BAUDRATES) {
1858 config->baudrate = (int)data->term.c_ispeed;
1859 #elif defined(USE_TERMIOS_SPEED)
1860 TRY(get_baudrate(port->fd, &config->baudrate));
1862 config->baudrate = -1;
1866 switch (data->term.c_cflag & CSIZE) {
1883 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1884 config->parity = SP_PARITY_NONE;
1885 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1886 config->parity = -1;
1888 else if (data->term.c_cflag & CMSPAR)
1889 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1892 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1894 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1896 if (data->term.c_cflag & CRTSCTS) {
1897 config->rts = SP_RTS_FLOW_CONTROL;
1898 config->cts = SP_CTS_FLOW_CONTROL;
1900 if (data->termiox_supported && data->rts_flow)
1901 config->rts = SP_RTS_FLOW_CONTROL;
1903 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1905 config->cts = (data->termiox_supported && data->cts_flow) ?
1906 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1909 if (data->termiox_supported && data->dtr_flow)
1910 config->dtr = SP_DTR_FLOW_CONTROL;
1912 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1914 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1915 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1917 if (data->term.c_iflag & IXOFF) {
1918 if (data->term.c_iflag & IXON)
1919 config->xon_xoff = SP_XONXOFF_INOUT;
1921 config->xon_xoff = SP_XONXOFF_IN;
1923 if (data->term.c_iflag & IXON)
1924 config->xon_xoff = SP_XONXOFF_OUT;
1926 config->xon_xoff = SP_XONXOFF_DISABLED;
1933 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1934 const struct sp_port_config *config)
1938 BAUD_TYPE baud_nonstd;
1942 #ifdef USE_TERMIOS_SPEED
1943 int baud_nonstd = 0;
1946 TRACE("%p, %p, %p", port, data, config);
1948 DEBUG_FMT("Setting configuration for port %s", port->name);
1952 TRY(await_write_completion(port));
1954 if (config->baudrate >= 0) {
1955 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1956 if (config->baudrate == std_baudrates[i].value) {
1957 data->dcb.BaudRate = std_baudrates[i].index;
1962 if (i == NUM_STD_BAUDRATES)
1963 data->dcb.BaudRate = config->baudrate;
1965 /* Allocate write buffer for 50ms of data at baud rate. */
1966 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1967 port->write_buf = realloc(port->write_buf,
1968 port->write_buf_size);
1970 if (!port->write_buf)
1971 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1974 if (config->bits >= 0)
1975 data->dcb.ByteSize = config->bits;
1977 if (config->parity >= 0) {
1978 switch (config->parity) {
1979 case SP_PARITY_NONE:
1980 data->dcb.Parity = NOPARITY;
1983 data->dcb.Parity = ODDPARITY;
1985 case SP_PARITY_EVEN:
1986 data->dcb.Parity = EVENPARITY;
1988 case SP_PARITY_MARK:
1989 data->dcb.Parity = MARKPARITY;
1991 case SP_PARITY_SPACE:
1992 data->dcb.Parity = SPACEPARITY;
1995 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1999 if (config->stopbits >= 0) {
2000 switch (config->stopbits) {
2001 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
2003 data->dcb.StopBits = ONESTOPBIT;
2006 data->dcb.StopBits = TWOSTOPBITS;
2009 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
2013 if (config->rts >= 0) {
2014 switch (config->rts) {
2016 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
2019 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
2021 case SP_RTS_FLOW_CONTROL:
2022 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
2025 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
2029 if (config->cts >= 0) {
2030 switch (config->cts) {
2032 data->dcb.fOutxCtsFlow = FALSE;
2034 case SP_CTS_FLOW_CONTROL:
2035 data->dcb.fOutxCtsFlow = TRUE;
2038 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
2042 if (config->dtr >= 0) {
2043 switch (config->dtr) {
2045 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
2048 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
2050 case SP_DTR_FLOW_CONTROL:
2051 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
2054 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
2058 if (config->dsr >= 0) {
2059 switch (config->dsr) {
2061 data->dcb.fOutxDsrFlow = FALSE;
2063 case SP_DSR_FLOW_CONTROL:
2064 data->dcb.fOutxDsrFlow = TRUE;
2067 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2071 if (config->xon_xoff >= 0) {
2072 switch (config->xon_xoff) {
2073 case SP_XONXOFF_DISABLED:
2074 data->dcb.fInX = FALSE;
2075 data->dcb.fOutX = FALSE;
2078 data->dcb.fInX = TRUE;
2079 data->dcb.fOutX = FALSE;
2081 case SP_XONXOFF_OUT:
2082 data->dcb.fInX = FALSE;
2083 data->dcb.fOutX = TRUE;
2085 case SP_XONXOFF_INOUT:
2086 data->dcb.fInX = TRUE;
2087 data->dcb.fOutX = TRUE;
2090 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2094 if (!SetCommState(port->hdl, &data->dcb))
2095 RETURN_FAIL("SetCommState() failed");
2101 if (config->baudrate >= 0) {
2102 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2103 if (config->baudrate == std_baudrates[i].value) {
2104 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2105 RETURN_FAIL("cfsetospeed() failed");
2107 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2108 RETURN_FAIL("cfsetispeed() failed");
2113 /* Non-standard baud rate */
2114 if (i == NUM_STD_BAUDRATES) {
2116 /* Set "dummy" baud rate. */
2117 if (cfsetspeed(&data->term, B9600) < 0)
2118 RETURN_FAIL("cfsetspeed() failed");
2119 baud_nonstd = config->baudrate;
2120 #elif defined(USE_TERMIOS_SPEED)
2123 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2128 if (config->bits >= 0) {
2129 data->term.c_cflag &= ~CSIZE;
2130 switch (config->bits) {
2132 data->term.c_cflag |= CS8;
2135 data->term.c_cflag |= CS7;
2138 data->term.c_cflag |= CS6;
2141 data->term.c_cflag |= CS5;
2144 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2148 if (config->parity >= 0) {
2149 data->term.c_iflag &= ~IGNPAR;
2150 data->term.c_cflag &= ~(PARENB | PARODD);
2152 data->term.c_cflag &= ~CMSPAR;
2154 switch (config->parity) {
2155 case SP_PARITY_NONE:
2156 data->term.c_iflag |= IGNPAR;
2158 case SP_PARITY_EVEN:
2159 data->term.c_cflag |= PARENB;
2162 data->term.c_cflag |= PARENB | PARODD;
2165 case SP_PARITY_MARK:
2166 data->term.c_cflag |= PARENB | PARODD;
2167 data->term.c_cflag |= CMSPAR;
2169 case SP_PARITY_SPACE:
2170 data->term.c_cflag |= PARENB;
2171 data->term.c_cflag |= CMSPAR;
2174 case SP_PARITY_MARK:
2175 case SP_PARITY_SPACE:
2176 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2179 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2183 if (config->stopbits >= 0) {
2184 data->term.c_cflag &= ~CSTOPB;
2185 switch (config->stopbits) {
2187 data->term.c_cflag &= ~CSTOPB;
2190 data->term.c_cflag |= CSTOPB;
2193 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2197 if (config->rts >= 0 || config->cts >= 0) {
2198 if (data->termiox_supported) {
2199 data->rts_flow = data->cts_flow = 0;
2200 switch (config->rts) {
2203 controlbits = TIOCM_RTS;
2204 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2205 RETURN_FAIL("Setting RTS signal level failed");
2207 case SP_RTS_FLOW_CONTROL:
2213 if (config->cts == SP_CTS_FLOW_CONTROL)
2216 if (data->rts_flow && data->cts_flow)
2217 data->term.c_iflag |= CRTSCTS;
2219 data->term.c_iflag &= ~CRTSCTS;
2221 /* Asymmetric use of RTS/CTS not supported. */
2222 if (data->term.c_iflag & CRTSCTS) {
2223 /* Flow control can only be disabled for both RTS & CTS together. */
2224 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2225 if (config->cts != SP_CTS_IGNORE)
2226 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2228 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2229 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2230 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2233 /* Flow control can only be enabled for both RTS & CTS together. */
2234 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2235 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2236 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2239 if (config->rts >= 0) {
2240 if (config->rts == SP_RTS_FLOW_CONTROL) {
2241 data->term.c_iflag |= CRTSCTS;
2243 controlbits = TIOCM_RTS;
2244 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2246 RETURN_FAIL("Setting RTS signal level failed");
2252 if (config->dtr >= 0 || config->dsr >= 0) {
2253 if (data->termiox_supported) {
2254 data->dtr_flow = data->dsr_flow = 0;
2255 switch (config->dtr) {
2258 controlbits = TIOCM_DTR;
2259 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2260 RETURN_FAIL("Setting DTR signal level failed");
2262 case SP_DTR_FLOW_CONTROL:
2268 if (config->dsr == SP_DSR_FLOW_CONTROL)
2271 /* DTR/DSR flow control not supported. */
2272 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2273 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2275 if (config->dtr >= 0) {
2276 controlbits = TIOCM_DTR;
2277 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2279 RETURN_FAIL("Setting DTR signal level failed");
2284 if (config->xon_xoff >= 0) {
2285 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2286 switch (config->xon_xoff) {
2287 case SP_XONXOFF_DISABLED:
2290 data->term.c_iflag |= IXOFF;
2292 case SP_XONXOFF_OUT:
2293 data->term.c_iflag |= IXON | IXANY;
2295 case SP_XONXOFF_INOUT:
2296 data->term.c_iflag |= IXON | IXOFF | IXANY;
2299 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2303 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2304 RETURN_FAIL("tcsetattr() failed");
2307 if (baud_nonstd != B0) {
2308 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2309 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2311 * Set baud rates in data->term to correct, but incompatible
2312 * with tcsetattr() value, same as delivered by tcgetattr().
2314 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2315 RETURN_FAIL("cfsetspeed() failed");
2317 #elif defined(__linux__)
2318 #ifdef USE_TERMIOS_SPEED
2320 TRY(set_baudrate(port->fd, config->baudrate));
2323 if (data->termiox_supported)
2324 TRY(set_flow(port->fd, data));
2328 #endif /* !_WIN32 */
2333 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2335 struct sp_port_config *config;
2337 TRACE("%p", config_ptr);
2340 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2344 if (!(config = malloc(sizeof(struct sp_port_config))))
2345 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2347 config->baudrate = -1;
2349 config->parity = -1;
2350 config->stopbits = -1;
2356 *config_ptr = config;
2361 SP_API void sp_free_config(struct sp_port_config *config)
2363 TRACE("%p", config);
2366 DEBUG("Null config");
2373 SP_API enum sp_return sp_get_config(struct sp_port *port,
2374 struct sp_port_config *config)
2376 struct port_data data;
2378 TRACE("%p, %p", port, config);
2383 RETURN_ERROR(SP_ERR_ARG, "Null config");
2385 TRY(get_config(port, &data, config));
2390 SP_API enum sp_return sp_set_config(struct sp_port *port,
2391 const struct sp_port_config *config)
2393 struct port_data data;
2394 struct sp_port_config prev_config;
2396 TRACE("%p, %p", port, config);
2401 RETURN_ERROR(SP_ERR_ARG, "Null config");
2403 TRY(get_config(port, &data, &prev_config));
2404 TRY(set_config(port, &data, config));
2409 #define CREATE_ACCESSORS(x, type) \
2410 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2411 struct port_data data; \
2412 struct sp_port_config config; \
2413 TRACE("%p, %d", port, x); \
2414 CHECK_OPEN_PORT(); \
2415 TRY(get_config(port, &data, &config)); \
2417 TRY(set_config(port, &data, &config)); \
2420 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2422 TRACE("%p, %p", config, x); \
2424 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2426 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2430 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2432 TRACE("%p, %d", config, x); \
2434 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2439 CREATE_ACCESSORS(baudrate, int)
2440 CREATE_ACCESSORS(bits, int)
2441 CREATE_ACCESSORS(parity, enum sp_parity)
2442 CREATE_ACCESSORS(stopbits, int)
2443 CREATE_ACCESSORS(rts, enum sp_rts)
2444 CREATE_ACCESSORS(cts, enum sp_cts)
2445 CREATE_ACCESSORS(dtr, enum sp_dtr)
2446 CREATE_ACCESSORS(dsr, enum sp_dsr)
2447 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2449 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2450 enum sp_flowcontrol flowcontrol)
2453 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2455 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2456 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2458 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2459 config->xon_xoff = SP_XONXOFF_INOUT;
2461 config->xon_xoff = SP_XONXOFF_DISABLED;
2463 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2464 config->rts = SP_RTS_FLOW_CONTROL;
2465 config->cts = SP_CTS_FLOW_CONTROL;
2467 if (config->rts == SP_RTS_FLOW_CONTROL)
2468 config->rts = SP_RTS_ON;
2469 config->cts = SP_CTS_IGNORE;
2472 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2473 config->dtr = SP_DTR_FLOW_CONTROL;
2474 config->dsr = SP_DSR_FLOW_CONTROL;
2476 if (config->dtr == SP_DTR_FLOW_CONTROL)
2477 config->dtr = SP_DTR_ON;
2478 config->dsr = SP_DSR_IGNORE;
2484 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2485 enum sp_flowcontrol flowcontrol)
2487 struct port_data data;
2488 struct sp_port_config config;
2490 TRACE("%p, %d", port, flowcontrol);
2494 TRY(get_config(port, &data, &config));
2496 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2498 TRY(set_config(port, &data, &config));
2503 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2504 enum sp_signal *signals)
2506 TRACE("%p, %p", port, signals);
2511 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2513 DEBUG_FMT("Getting control signals for port %s", port->name);
2518 if (GetCommModemStatus(port->hdl, &bits) == 0)
2519 RETURN_FAIL("GetCommModemStatus() failed");
2520 if (bits & MS_CTS_ON)
2521 *signals |= SP_SIG_CTS;
2522 if (bits & MS_DSR_ON)
2523 *signals |= SP_SIG_DSR;
2524 if (bits & MS_RLSD_ON)
2525 *signals |= SP_SIG_DCD;
2526 if (bits & MS_RING_ON)
2527 *signals |= SP_SIG_RI;
2530 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2531 RETURN_FAIL("TIOCMGET ioctl failed");
2532 if (bits & TIOCM_CTS)
2533 *signals |= SP_SIG_CTS;
2534 if (bits & TIOCM_DSR)
2535 *signals |= SP_SIG_DSR;
2536 if (bits & TIOCM_CAR)
2537 *signals |= SP_SIG_DCD;
2538 if (bits & TIOCM_RNG)
2539 *signals |= SP_SIG_RI;
2544 SP_API enum sp_return sp_start_break(struct sp_port *port)
2550 if (SetCommBreak(port->hdl) == 0)
2551 RETURN_FAIL("SetCommBreak() failed");
2553 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2554 RETURN_FAIL("TIOCSBRK ioctl failed");
2560 SP_API enum sp_return sp_end_break(struct sp_port *port)
2566 if (ClearCommBreak(port->hdl) == 0)
2567 RETURN_FAIL("ClearCommBreak() failed");
2569 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2570 RETURN_FAIL("TIOCCBRK ioctl failed");
2576 SP_API int sp_last_error_code(void)
2580 RETURN_INT(GetLastError());
2586 SP_API char *sp_last_error_message(void)
2592 DWORD error = GetLastError();
2594 DWORD length = FormatMessage(
2595 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2596 FORMAT_MESSAGE_FROM_SYSTEM |
2597 FORMAT_MESSAGE_IGNORE_INSERTS,
2600 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2604 if (length >= 2 && message[length - 2] == '\r')
2605 message[length - 2] = '\0';
2607 RETURN_STRING(message);
2609 RETURN_STRING(strerror(errno));
2613 SP_API void sp_free_error_message(char *message)
2615 TRACE("%s", message);
2626 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2628 TRACE("%p", handler);
2630 sp_debug_handler = handler;
2635 SP_API void sp_default_debug_handler(const char *format, ...)
2638 va_start(args, format);
2639 if (getenv("LIBSERIALPORT_DEBUG")) {
2640 fputs("sp: ", stderr);
2641 vfprintf(stderr, format, args);
2646 SP_API int sp_get_major_package_version(void)
2648 return SP_PACKAGE_VERSION_MAJOR;
2651 SP_API int sp_get_minor_package_version(void)
2653 return SP_PACKAGE_VERSION_MINOR;
2656 SP_API int sp_get_micro_package_version(void)
2658 return SP_PACKAGE_VERSION_MICRO;
2661 SP_API const char *sp_get_package_version_string(void)
2663 return SP_PACKAGE_VERSION_STRING;
2666 SP_API int sp_get_current_lib_version(void)
2668 return SP_LIB_VERSION_CURRENT;
2671 SP_API int sp_get_revision_lib_version(void)
2673 return SP_LIB_VERSION_REVISION;
2676 SP_API int sp_get_age_lib_version(void)
2678 return SP_LIB_VERSION_AGE;
2681 SP_API const char *sp_get_lib_version_string(void)
2683 return SP_LIB_VERSION_STRING;