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 */
67 unsigned int ms, limit_ms;
68 struct time start, now, end, delta, delta_max;
69 struct timeval delta_tv;
73 static void time_get(struct time *time)
75 #ifdef HAVE_CLOCK_GETTIME
77 if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
78 clock_gettime(CLOCK_REALTIME, &ts);
79 time->tv.tv_sec = ts.tv_sec;
80 time->tv.tv_usec = ts.tv_nsec / 1000;
81 #elif defined(__APPLE__)
82 mach_timebase_info_data_t info;
83 mach_timebase_info(&info);
84 uint64_t ticks = mach_absolute_time();
85 uint64_t ns = (ticks * info.numer) / info.denom;
86 time->tv.tv_sec = ns / 1000000000;
87 time->tv.tv_usec = (ns % 1000000000) / 1000;
89 gettimeofday(&time->tv, NULL);
93 static void time_set_ms(struct time *time, unsigned int ms)
95 time->tv.tv_sec = ms / 1000;
96 time->tv.tv_usec = (ms % 1000) * 1000;
99 static void time_add(const struct time *a,
100 const struct time *b, struct time *result)
102 timeradd(&a->tv, &b->tv, &result->tv);
105 static void time_sub(const struct time *a,
106 const struct time *b, struct time *result)
108 timersub(&a->tv, &b->tv, &result->tv);
111 static bool time_greater(const struct time *a, const struct time *b)
113 return timercmp(&a->tv, &b->tv, >);
116 static void time_as_timeval(const struct time *time, struct timeval *tv)
121 static unsigned int time_as_ms(const struct time *time)
123 return time->tv.tv_sec * 1000 + time->tv.tv_usec / 1000;
126 static void timeout_start(struct timeout *timeout, unsigned int timeout_ms)
128 timeout->ms = timeout_ms;
130 /* Get time at start of operation. */
131 time_get(&timeout->start);
132 /* Define duration of timeout. */
133 time_set_ms(&timeout->delta, timeout_ms);
134 /* Calculate time at which we should give up. */
135 time_add(&timeout->start, &timeout->delta, &timeout->end);
136 /* Disable limit unless timeout_limit() called. */
137 timeout->limit_ms = 0;
140 static void timeout_limit(struct timeout *timeout, unsigned int limit_ms)
142 timeout->limit_ms = limit_ms;
143 timeout->overflow = (timeout->ms > timeout->limit_ms);
144 time_set_ms(&timeout->delta_max, timeout->limit_ms);
147 static bool timeout_check(struct timeout *timeout)
149 if (timeout->ms == 0)
152 time_get(&timeout->now);
153 time_sub(&timeout->end, &timeout->now, &timeout->delta);
154 if (timeout->limit_ms)
155 if ((timeout->overflow = time_greater(&timeout->delta, &timeout->delta_max)))
156 timeout->delta = timeout->delta_max;
158 return time_greater(&timeout->now, &timeout->end);
161 static struct timeval *timeout_timeval(struct timeout *timeout)
163 if (timeout->ms == 0)
166 time_as_timeval(&timeout->delta, &timeout->delta_tv);
168 return &timeout->delta_tv;
171 static unsigned int timeout_remaining_ms(struct timeout *timeout)
173 if (timeout->ms == 0)
175 else if (timeout->limit_ms && timeout->overflow)
176 return timeout->limit_ms;
178 return time_as_ms(&timeout->delta);
183 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
185 struct sp_port *port;
186 #ifndef NO_PORT_METADATA
191 TRACE("%s, %p", portname, port_ptr);
194 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
199 RETURN_ERROR(SP_ERR_ARG, "Null port name");
201 DEBUG_FMT("Building structure for port %s", portname);
203 #if !defined(_WIN32) && defined(HAVE_REALPATH)
205 * get_port_details() below tries to be too smart and figure out
206 * some transport properties from the port name which breaks with
207 * symlinks. Therefore we canonicalize the portname first.
209 char pathbuf[PATH_MAX + 1];
210 char *res = realpath(portname, pathbuf);
212 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
217 if (!(port = malloc(sizeof(struct sp_port))))
218 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
220 len = strlen(portname) + 1;
222 if (!(port->name = malloc(len))) {
224 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
227 memcpy(port->name, portname, len);
230 port->usb_path = NULL;
231 port->hdl = INVALID_HANDLE_VALUE;
232 port->write_buf = NULL;
233 port->write_buf_size = 0;
238 port->description = NULL;
239 port->transport = SP_TRANSPORT_NATIVE;
241 port->usb_address = -1;
244 port->usb_manufacturer = NULL;
245 port->usb_product = NULL;
246 port->usb_serial = NULL;
247 port->bluetooth_address = NULL;
249 #ifndef NO_PORT_METADATA
250 if ((ret = get_port_details(port)) != SP_OK) {
261 SP_API char *sp_get_port_name(const struct sp_port *port)
268 RETURN_STRING(port->name);
271 SP_API char *sp_get_port_description(const struct sp_port *port)
275 if (!port || !port->description)
278 RETURN_STRING(port->description);
281 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
286 RETURN_ERROR(SP_ERR_ARG, "Null port");
288 RETURN_INT(port->transport);
291 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
292 int *usb_bus,int *usb_address)
297 RETURN_ERROR(SP_ERR_ARG, "Null port");
298 if (port->transport != SP_TRANSPORT_USB)
299 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
300 if (port->usb_bus < 0 || port->usb_address < 0)
301 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
304 *usb_bus = port->usb_bus;
306 *usb_address = port->usb_address;
311 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
312 int *usb_vid, int *usb_pid)
317 RETURN_ERROR(SP_ERR_ARG, "Null port");
318 if (port->transport != SP_TRANSPORT_USB)
319 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
320 if (port->usb_vid < 0 || port->usb_pid < 0)
321 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
324 *usb_vid = port->usb_vid;
326 *usb_pid = port->usb_pid;
331 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
335 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
338 RETURN_STRING(port->usb_manufacturer);
341 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
345 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
348 RETURN_STRING(port->usb_product);
351 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
355 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
358 RETURN_STRING(port->usb_serial);
361 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
365 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
366 || !port->bluetooth_address)
369 RETURN_STRING(port->bluetooth_address);
372 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
375 TRACE("%p, %p", port, result_ptr);
378 RETURN_ERROR(SP_ERR_ARG, "Null port");
380 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
383 HANDLE *handle_ptr = result_ptr;
384 *handle_ptr = port->hdl;
386 int *fd_ptr = result_ptr;
393 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
394 struct sp_port **copy_ptr)
396 TRACE("%p, %p", port, copy_ptr);
399 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
404 RETURN_ERROR(SP_ERR_ARG, "Null port");
407 RETURN_ERROR(SP_ERR_ARG, "Null port name");
409 DEBUG("Copying port structure");
411 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
414 SP_API void sp_free_port(struct sp_port *port)
423 DEBUG("Freeing port structure");
427 if (port->description)
428 free(port->description);
429 if (port->usb_manufacturer)
430 free(port->usb_manufacturer);
431 if (port->usb_product)
432 free(port->usb_product);
433 if (port->usb_serial)
434 free(port->usb_serial);
435 if (port->bluetooth_address)
436 free(port->bluetooth_address);
439 free(port->usb_path);
441 free(port->write_buf);
449 SP_PRIV struct sp_port **list_append(struct sp_port **list,
450 const char *portname)
455 for (count = 0; list[count]; count++)
457 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
460 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
462 list[count + 1] = NULL;
466 sp_free_port_list(list);
470 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
472 #ifndef NO_ENUMERATION
473 struct sp_port **list;
477 TRACE("%p", list_ptr);
480 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
484 #ifdef NO_ENUMERATION
485 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
487 DEBUG("Enumerating ports");
489 if (!(list = malloc(sizeof(struct sp_port *))))
490 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
494 ret = list_ports(&list);
499 sp_free_port_list(list);
507 SP_API void sp_free_port_list(struct sp_port **list)
518 DEBUG("Freeing port list");
520 for (i = 0; list[i]; i++)
521 sp_free_port(list[i]);
527 #define CHECK_PORT() do { \
529 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
531 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
534 #define CHECK_PORT_HANDLE() do { \
535 if (port->hdl == INVALID_HANDLE_VALUE) \
536 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
539 #define CHECK_PORT_HANDLE() do { \
541 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
544 #define CHECK_OPEN_PORT() do { \
546 CHECK_PORT_HANDLE(); \
550 /** To be called after port receive buffer is emptied. */
551 static enum sp_return restart_wait(struct sp_port *port)
555 if (port->wait_running) {
556 /* Check status of running wait operation. */
557 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
558 &wait_result, FALSE)) {
559 DEBUG("Previous wait completed");
560 port->wait_running = FALSE;
561 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
562 DEBUG("Previous wait still running");
565 RETURN_FAIL("GetOverlappedResult() failed");
569 if (!port->wait_running) {
570 /* Start new wait operation. */
571 if (WaitCommEvent(port->hdl, &port->events,
573 DEBUG("New wait returned, events already pending");
574 } else if (GetLastError() == ERROR_IO_PENDING) {
575 DEBUG("New wait running in background");
576 port->wait_running = TRUE;
578 RETURN_FAIL("WaitCommEvent() failed");
586 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
588 struct port_data data;
589 struct sp_port_config config;
592 TRACE("%p, 0x%x", port, flags);
596 if (flags > SP_MODE_READ_WRITE)
597 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
599 DEBUG_FMT("Opening port %s", port->name);
602 DWORD desired_access = 0, flags_and_attributes = 0, errors;
603 char *escaped_port_name;
606 /* Prefix port name with '\\.\' to work with ports above COM9. */
607 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
608 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
609 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
611 /* Map 'flags' to the OS-specific settings. */
612 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
613 if (flags & SP_MODE_READ)
614 desired_access |= GENERIC_READ;
615 if (flags & SP_MODE_WRITE)
616 desired_access |= GENERIC_WRITE;
618 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
619 OPEN_EXISTING, flags_and_attributes, 0);
621 free(escaped_port_name);
623 if (port->hdl == INVALID_HANDLE_VALUE)
624 RETURN_FAIL("Port CreateFile() failed");
626 /* All timeouts initially disabled. */
627 port->timeouts.ReadIntervalTimeout = 0;
628 port->timeouts.ReadTotalTimeoutMultiplier = 0;
629 port->timeouts.ReadTotalTimeoutConstant = 0;
630 port->timeouts.WriteTotalTimeoutMultiplier = 0;
631 port->timeouts.WriteTotalTimeoutConstant = 0;
633 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
635 RETURN_FAIL("SetCommTimeouts() failed");
638 /* Prepare OVERLAPPED structures. */
639 #define INIT_OVERLAPPED(ovl) do { \
640 memset(&port->ovl, 0, sizeof(port->ovl)); \
641 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
642 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
643 == INVALID_HANDLE_VALUE) { \
645 RETURN_FAIL(#ovl "CreateEvent() failed"); \
649 INIT_OVERLAPPED(read_ovl);
650 INIT_OVERLAPPED(write_ovl);
651 INIT_OVERLAPPED(wait_ovl);
653 /* Set event mask for RX and error events. */
654 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
656 RETURN_FAIL("SetCommMask() failed");
659 port->writing = FALSE;
660 port->wait_running = FALSE;
662 ret = restart_wait(port);
669 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
671 /* Map 'flags' to the OS-specific settings. */
672 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
673 flags_local |= O_RDWR;
674 else if (flags & SP_MODE_READ)
675 flags_local |= O_RDONLY;
676 else if (flags & SP_MODE_WRITE)
677 flags_local |= O_WRONLY;
679 if ((port->fd = open(port->name, flags_local)) < 0)
680 RETURN_FAIL("open() failed");
683 ret = get_config(port, &data, &config);
690 /* Set sane port settings. */
692 data.dcb.fBinary = TRUE;
693 data.dcb.fDsrSensitivity = FALSE;
694 data.dcb.fErrorChar = FALSE;
695 data.dcb.fNull = FALSE;
696 data.dcb.fAbortOnError = FALSE;
698 /* Turn off all fancy termios tricks, give us a raw channel. */
699 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
701 data.term.c_iflag &= ~IUCLC;
703 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
705 data.term.c_oflag &= ~OLCUC;
708 data.term.c_oflag &= ~NLDLY;
711 data.term.c_oflag &= ~CRDLY;
714 data.term.c_oflag &= ~TABDLY;
717 data.term.c_oflag &= ~BSDLY;
720 data.term.c_oflag &= ~VTDLY;
723 data.term.c_oflag &= ~FFDLY;
726 data.term.c_oflag &= ~OFILL;
728 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
729 data.term.c_cc[VMIN] = 0;
730 data.term.c_cc[VTIME] = 0;
732 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
733 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
737 if (ClearCommError(port->hdl, &errors, &status) == 0)
738 RETURN_FAIL("ClearCommError() failed");
741 ret = set_config(port, &data, &config);
751 SP_API enum sp_return sp_close(struct sp_port *port)
757 DEBUG_FMT("Closing port %s", port->name);
760 /* Returns non-zero upon success, 0 upon failure. */
761 if (CloseHandle(port->hdl) == 0)
762 RETURN_FAIL("Port CloseHandle() failed");
763 port->hdl = INVALID_HANDLE_VALUE;
765 /* Close event handles for overlapped structures. */
766 #define CLOSE_OVERLAPPED(ovl) do { \
767 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
768 CloseHandle(port->ovl.hEvent) == 0) \
769 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
771 CLOSE_OVERLAPPED(read_ovl);
772 CLOSE_OVERLAPPED(write_ovl);
773 CLOSE_OVERLAPPED(wait_ovl);
775 if (port->write_buf) {
776 free(port->write_buf);
777 port->write_buf = NULL;
780 /* Returns 0 upon success, -1 upon failure. */
781 if (close(port->fd) == -1)
782 RETURN_FAIL("close() failed");
789 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
791 TRACE("%p, 0x%x", port, buffers);
795 if (buffers > SP_BUF_BOTH)
796 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
798 const char *buffer_names[] = {"no", "input", "output", "both"};
800 DEBUG_FMT("Flushing %s buffers on port %s",
801 buffer_names[buffers], port->name);
805 if (buffers & SP_BUF_INPUT)
806 flags |= PURGE_RXCLEAR;
807 if (buffers & SP_BUF_OUTPUT)
808 flags |= PURGE_TXCLEAR;
810 /* Returns non-zero upon success, 0 upon failure. */
811 if (PurgeComm(port->hdl, flags) == 0)
812 RETURN_FAIL("PurgeComm() failed");
814 if (buffers & SP_BUF_INPUT)
815 TRY(restart_wait(port));
818 if (buffers == SP_BUF_BOTH)
820 else if (buffers == SP_BUF_INPUT)
822 else if (buffers == SP_BUF_OUTPUT)
825 /* Returns 0 upon success, -1 upon failure. */
826 if (tcflush(port->fd, flags) < 0)
827 RETURN_FAIL("tcflush() failed");
832 SP_API enum sp_return sp_drain(struct sp_port *port)
838 DEBUG_FMT("Draining port %s", port->name);
841 /* Returns non-zero upon success, 0 upon failure. */
842 if (FlushFileBuffers(port->hdl) == 0)
843 RETURN_FAIL("FlushFileBuffers() failed");
848 #if defined(__ANDROID__) && (__ANDROID_API__ < 21)
849 /* Android only has tcdrain from platform 21 onwards.
850 * On previous API versions, use the ioctl directly. */
852 result = ioctl(port->fd, TCSBRK, &arg);
854 result = tcdrain(port->fd);
857 if (errno == EINTR) {
858 DEBUG("tcdrain() was interrupted");
861 RETURN_FAIL("tcdrain() failed");
871 static enum sp_return await_write_completion(struct sp_port *port)
877 /* Wait for previous non-blocking write to complete, if any. */
879 DEBUG("Waiting for previous write to complete");
880 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
883 RETURN_FAIL("Previous write failed to complete");
884 DEBUG("Previous write completed");
891 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
892 size_t count, unsigned int timeout_ms)
894 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
899 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
902 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
903 count, port->name, timeout_ms);
905 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
912 DWORD bytes_written = 0;
914 TRY(await_write_completion(port));
917 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
918 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
919 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
920 RETURN_FAIL("SetCommTimeouts() failed");
923 /* Reduce count if it exceeds the WriteFile limit. */
924 if (count > WRITEFILE_MAX_SIZE)
925 count = WRITEFILE_MAX_SIZE;
928 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
929 DEBUG("Write completed immediately");
931 } else if (GetLastError() == ERROR_IO_PENDING) {
932 DEBUG("Waiting for write to complete");
933 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
934 if (GetLastError() == ERROR_SEM_TIMEOUT) {
935 DEBUG("Write timed out");
938 RETURN_FAIL("GetOverlappedResult() failed");
941 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
942 RETURN_INT(bytes_written);
944 RETURN_FAIL("WriteFile() failed");
947 size_t bytes_written = 0;
948 unsigned char *ptr = (unsigned char *) buf;
949 struct timeout timeout;
954 timeout_start(&timeout, timeout_ms);
957 FD_SET(port->fd, &fds);
959 /* Loop until we have written the requested number of bytes. */
960 while (bytes_written < count) {
962 * Check timeout only if we have run select() at least once,
963 * to avoid any issues if a short timeout is reached before
964 * select() is even run.
966 if (started && timeout_check(&timeout))
969 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
972 if (errno == EINTR) {
973 DEBUG("select() call was interrupted, repeating");
976 RETURN_FAIL("select() failed");
978 } else if (result == 0) {
979 /* Timeout has expired. */
984 result = write(port->fd, ptr, count - bytes_written);
988 /* This shouldn't happen because we did a select() first, but handle anyway. */
991 /* This is an actual failure. */
992 RETURN_FAIL("write() failed");
995 bytes_written += result;
999 if (bytes_written < count)
1000 DEBUG("Write timed out");
1002 RETURN_INT(bytes_written);
1006 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
1007 const void *buf, size_t count)
1009 TRACE("%p, %p, %d", port, buf, count);
1014 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1016 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
1024 /* Check whether previous write is complete. */
1025 if (port->writing) {
1026 if (HasOverlappedIoCompleted(&port->write_ovl)) {
1027 DEBUG("Previous write completed");
1030 DEBUG("Previous write not complete");
1031 /* Can't take a new write until the previous one finishes. */
1037 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
1038 port->timeouts.WriteTotalTimeoutConstant = 0;
1039 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1040 RETURN_FAIL("SetCommTimeouts() failed");
1043 /* Reduce count if it exceeds the WriteFile limit. */
1044 if (count > WRITEFILE_MAX_SIZE)
1045 count = WRITEFILE_MAX_SIZE;
1047 /* Copy data to our write buffer. */
1048 buf_bytes = min(port->write_buf_size, count);
1049 memcpy(port->write_buf, buf, buf_bytes);
1051 /* Start asynchronous write. */
1052 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
1053 if (GetLastError() == ERROR_IO_PENDING) {
1054 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
1055 DEBUG("Asynchronous write completed immediately");
1057 DEBUG("Asynchronous write running");
1059 /* Actual failure of some kind. */
1060 RETURN_FAIL("WriteFile() failed");
1064 DEBUG("All bytes written immediately");
1066 RETURN_INT(buf_bytes);
1068 /* Returns the number of bytes written, or -1 upon failure. */
1069 ssize_t written = write(port->fd, buf, count);
1072 if (errno == EAGAIN)
1073 // Buffer is full, no bytes written.
1076 RETURN_FAIL("write() failed");
1078 RETURN_INT(written);
1084 /* Restart wait operation if buffer was emptied. */
1085 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1090 if (bytes_read == 0)
1093 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1094 RETURN_FAIL("ClearCommError() failed");
1096 if (comstat.cbInQue == 0)
1097 TRY(restart_wait(port));
1103 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1104 size_t count, unsigned int timeout_ms)
1106 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1111 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1114 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1115 count, port->name, timeout_ms);
1117 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1124 DWORD bytes_read = 0;
1127 if (port->timeouts.ReadIntervalTimeout != 0 ||
1128 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1129 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1130 port->timeouts.ReadIntervalTimeout = 0;
1131 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1132 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1133 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1134 RETURN_FAIL("SetCommTimeouts() failed");
1138 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1139 DEBUG("Read completed immediately");
1141 } else if (GetLastError() == ERROR_IO_PENDING) {
1142 DEBUG("Waiting for read to complete");
1143 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1144 RETURN_FAIL("GetOverlappedResult() failed");
1145 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1147 RETURN_FAIL("ReadFile() failed");
1150 TRY(restart_wait_if_needed(port, bytes_read));
1152 RETURN_INT(bytes_read);
1155 size_t bytes_read = 0;
1156 unsigned char *ptr = (unsigned char *) buf;
1157 struct timeout timeout;
1162 timeout_start(&timeout, timeout_ms);
1165 FD_SET(port->fd, &fds);
1167 /* Loop until we have the requested number of bytes. */
1168 while (bytes_read < count) {
1170 * Check timeout only if we have run select() at least once,
1171 * to avoid any issues if a short timeout is reached before
1172 * select() is even run.
1174 if (started && timeout_check(&timeout))
1175 /* Timeout has expired. */
1178 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1181 if (errno == EINTR) {
1182 DEBUG("select() call was interrupted, repeating");
1185 RETURN_FAIL("select() failed");
1187 } else if (result == 0) {
1188 /* Timeout has expired. */
1193 result = read(port->fd, ptr, count - bytes_read);
1196 if (errno == EAGAIN)
1198 * This shouldn't happen because we did a
1199 * select() first, but handle anyway.
1203 /* This is an actual failure. */
1204 RETURN_FAIL("read() failed");
1207 bytes_read += result;
1211 if (bytes_read < count)
1212 DEBUG("Read timed out");
1214 RETURN_INT(bytes_read);
1218 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1219 size_t count, unsigned int timeout_ms)
1221 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1226 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1229 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1232 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1233 count, port->name, timeout_ms);
1235 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1239 DWORD bytes_read = 0;
1241 /* If timeout_ms == 0, set maximum timeout. */
1242 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1245 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1246 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1247 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1248 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1249 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1250 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1251 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1252 RETURN_FAIL("SetCommTimeouts() failed");
1255 /* Loop until we have at least one byte, or timeout is reached. */
1256 while (bytes_read == 0) {
1258 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1259 DEBUG("Read completed immediately");
1260 } else if (GetLastError() == ERROR_IO_PENDING) {
1261 DEBUG("Waiting for read to complete");
1262 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1263 RETURN_FAIL("GetOverlappedResult() failed");
1264 if (bytes_read > 0) {
1265 DEBUG("Read completed");
1266 } else if (timeout_ms > 0) {
1267 DEBUG("Read timed out");
1270 DEBUG("Restarting read");
1273 RETURN_FAIL("ReadFile() failed");
1277 TRY(restart_wait_if_needed(port, bytes_read));
1279 RETURN_INT(bytes_read);
1282 size_t bytes_read = 0;
1283 struct timeout timeout;
1288 timeout_start(&timeout, timeout_ms);
1291 FD_SET(port->fd, &fds);
1293 /* Loop until we have at least one byte, or timeout is reached. */
1294 while (bytes_read == 0) {
1296 * Check timeout only if we have run select() at least once,
1297 * to avoid any issues if a short timeout is reached before
1298 * select() is even run.
1300 if (started && timeout_check(&timeout))
1301 /* Timeout has expired. */
1304 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1307 if (errno == EINTR) {
1308 DEBUG("select() call was interrupted, repeating");
1311 RETURN_FAIL("select() failed");
1313 } else if (result == 0) {
1314 /* Timeout has expired. */
1319 result = read(port->fd, buf, count);
1322 if (errno == EAGAIN)
1323 /* This shouldn't happen because we did a select() first, but handle anyway. */
1326 /* This is an actual failure. */
1327 RETURN_FAIL("read() failed");
1330 bytes_read = result;
1333 if (bytes_read == 0)
1334 DEBUG("Read timed out");
1336 RETURN_INT(bytes_read);
1340 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1343 TRACE("%p, %p, %d", port, buf, count);
1348 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1350 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1356 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1357 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1358 port->timeouts.ReadTotalTimeoutConstant != 0) {
1359 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1360 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1361 port->timeouts.ReadTotalTimeoutConstant = 0;
1362 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1363 RETURN_FAIL("SetCommTimeouts() failed");
1367 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1368 if (GetLastError() != ERROR_IO_PENDING)
1369 RETURN_FAIL("ReadFile() failed");
1371 /* Get number of bytes read. */
1372 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1373 RETURN_FAIL("GetOverlappedResult() failed");
1375 TRY(restart_wait_if_needed(port, bytes_read));
1377 RETURN_INT(bytes_read);
1381 /* Returns the number of bytes read, or -1 upon failure. */
1382 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1383 if (errno == EAGAIN)
1384 /* No bytes available. */
1387 /* This is an actual failure. */
1388 RETURN_FAIL("read() failed");
1390 RETURN_INT(bytes_read);
1394 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1400 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1406 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1407 RETURN_FAIL("ClearCommError() failed");
1408 RETURN_INT(comstat.cbInQue);
1411 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1412 RETURN_FAIL("TIOCINQ ioctl failed");
1413 RETURN_INT(bytes_waiting);
1417 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1423 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1429 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1430 RETURN_FAIL("ClearCommError() failed");
1431 RETURN_INT(comstat.cbOutQue);
1434 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1435 RETURN_FAIL("TIOCOUTQ ioctl failed");
1436 RETURN_INT(bytes_waiting);
1440 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1442 struct sp_event_set *result;
1444 TRACE("%p", result_ptr);
1447 RETURN_ERROR(SP_ERR_ARG, "Null result");
1451 if (!(result = malloc(sizeof(struct sp_event_set))))
1452 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1454 memset(result, 0, sizeof(struct sp_event_set));
1456 *result_ptr = result;
1461 static enum sp_return add_handle(struct sp_event_set *event_set,
1462 event_handle handle, enum sp_event mask)
1465 enum sp_event *new_masks;
1467 TRACE("%p, %d, %d", event_set, handle, mask);
1469 if (!(new_handles = realloc(event_set->handles,
1470 sizeof(event_handle) * (event_set->count + 1))))
1471 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1473 event_set->handles = new_handles;
1475 if (!(new_masks = realloc(event_set->masks,
1476 sizeof(enum sp_event) * (event_set->count + 1))))
1477 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1479 event_set->masks = new_masks;
1481 ((event_handle *) event_set->handles)[event_set->count] = handle;
1482 event_set->masks[event_set->count] = mask;
1489 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1490 const struct sp_port *port, enum sp_event mask)
1492 TRACE("%p, %p, %d", event_set, port, mask);
1495 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1498 RETURN_ERROR(SP_ERR_ARG, "Null port");
1500 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1501 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1507 enum sp_event handle_mask;
1508 if ((handle_mask = mask & SP_EVENT_TX_READY))
1509 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1510 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1511 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1513 TRY(add_handle(event_set, port->fd, mask));
1519 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1521 TRACE("%p", event_set);
1524 DEBUG("Null event set");
1528 DEBUG("Freeing event set");
1530 if (event_set->handles)
1531 free(event_set->handles);
1532 if (event_set->masks)
1533 free(event_set->masks);
1540 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1541 unsigned int timeout_ms)
1543 TRACE("%p, %d", event_set, timeout_ms);
1546 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1549 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1550 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1551 RETURN_FAIL("WaitForMultipleObjects() failed");
1555 struct timeout timeout;
1556 int started = 0, result;
1557 struct pollfd *pollfds;
1560 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1561 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1563 for (i = 0; i < event_set->count; i++) {
1564 pollfds[i].fd = ((int *)event_set->handles)[i];
1565 pollfds[i].events = 0;
1566 pollfds[i].revents = 0;
1567 if (event_set->masks[i] & SP_EVENT_RX_READY)
1568 pollfds[i].events |= POLLIN;
1569 if (event_set->masks[i] & SP_EVENT_TX_READY)
1570 pollfds[i].events |= POLLOUT;
1571 if (event_set->masks[i] & SP_EVENT_ERROR)
1572 pollfds[i].events |= POLLERR;
1575 timeout_start(&timeout, timeout_ms);
1576 timeout_limit(&timeout, INT_MAX);
1578 /* Loop until an event occurs. */
1581 * Check timeout only if we have run poll() at least once,
1582 * to avoid any issues if a short timeout is reached before
1583 * poll() is even run.
1585 if (started && timeout_check(&timeout)) {
1586 DEBUG("Wait timed out");
1590 result = poll(pollfds, event_set->count, timeout_remaining_ms(&timeout));
1594 if (errno == EINTR) {
1595 DEBUG("poll() call was interrupted, repeating");
1599 RETURN_FAIL("poll() failed");
1601 } else if (result == 0) {
1602 DEBUG("poll() timed out");
1603 if (!timeout.overflow)
1606 DEBUG("poll() completed");
1616 #ifdef USE_TERMIOS_SPEED
1617 static enum sp_return get_baudrate(int fd, int *baudrate)
1621 TRACE("%d, %p", fd, baudrate);
1623 DEBUG("Getting baud rate");
1625 if (!(data = malloc(get_termios_size())))
1626 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1628 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1630 RETURN_FAIL("Getting termios failed");
1633 *baudrate = get_termios_speed(data);
1640 static enum sp_return set_baudrate(int fd, int baudrate)
1644 TRACE("%d, %d", fd, baudrate);
1646 DEBUG("Getting baud rate");
1648 if (!(data = malloc(get_termios_size())))
1649 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1651 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1653 RETURN_FAIL("Getting termios failed");
1656 DEBUG("Setting baud rate");
1658 set_termios_speed(data, baudrate);
1660 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1662 RETURN_FAIL("Setting termios failed");
1669 #endif /* USE_TERMIOS_SPEED */
1672 static enum sp_return get_flow(int fd, struct port_data *data)
1676 TRACE("%d, %p", fd, data);
1678 DEBUG("Getting advanced flow control");
1680 if (!(termx = malloc(get_termiox_size())))
1681 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1683 if (ioctl(fd, TCGETX, termx) < 0) {
1685 RETURN_FAIL("Getting termiox failed");
1688 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1689 &data->dtr_flow, &data->dsr_flow);
1696 static enum sp_return set_flow(int fd, struct port_data *data)
1700 TRACE("%d, %p", fd, data);
1702 DEBUG("Getting advanced flow control");
1704 if (!(termx = malloc(get_termiox_size())))
1705 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1707 if (ioctl(fd, TCGETX, termx) < 0) {
1709 RETURN_FAIL("Getting termiox failed");
1712 DEBUG("Setting advanced flow control");
1714 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1715 data->dtr_flow, data->dsr_flow);
1717 if (ioctl(fd, TCSETX, termx) < 0) {
1719 RETURN_FAIL("Setting termiox failed");
1726 #endif /* USE_TERMIOX */
1728 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1729 struct sp_port_config *config)
1733 TRACE("%p, %p, %p", port, data, config);
1735 DEBUG_FMT("Getting configuration for port %s", port->name);
1738 if (!GetCommState(port->hdl, &data->dcb))
1739 RETURN_FAIL("GetCommState() failed");
1741 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1742 if (data->dcb.BaudRate == std_baudrates[i].index) {
1743 config->baudrate = std_baudrates[i].value;
1748 if (i == NUM_STD_BAUDRATES)
1749 /* BaudRate field can be either an index or a custom baud rate. */
1750 config->baudrate = data->dcb.BaudRate;
1752 config->bits = data->dcb.ByteSize;
1754 if (data->dcb.fParity)
1755 switch (data->dcb.Parity) {
1757 config->parity = SP_PARITY_NONE;
1760 config->parity = SP_PARITY_ODD;
1763 config->parity = SP_PARITY_EVEN;
1766 config->parity = SP_PARITY_MARK;
1769 config->parity = SP_PARITY_SPACE;
1772 config->parity = -1;
1775 config->parity = SP_PARITY_NONE;
1777 switch (data->dcb.StopBits) {
1779 config->stopbits = 1;
1782 config->stopbits = 2;
1785 config->stopbits = -1;
1788 switch (data->dcb.fRtsControl) {
1789 case RTS_CONTROL_DISABLE:
1790 config->rts = SP_RTS_OFF;
1792 case RTS_CONTROL_ENABLE:
1793 config->rts = SP_RTS_ON;
1795 case RTS_CONTROL_HANDSHAKE:
1796 config->rts = SP_RTS_FLOW_CONTROL;
1802 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1804 switch (data->dcb.fDtrControl) {
1805 case DTR_CONTROL_DISABLE:
1806 config->dtr = SP_DTR_OFF;
1808 case DTR_CONTROL_ENABLE:
1809 config->dtr = SP_DTR_ON;
1811 case DTR_CONTROL_HANDSHAKE:
1812 config->dtr = SP_DTR_FLOW_CONTROL;
1818 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1820 if (data->dcb.fInX) {
1821 if (data->dcb.fOutX)
1822 config->xon_xoff = SP_XONXOFF_INOUT;
1824 config->xon_xoff = SP_XONXOFF_IN;
1826 if (data->dcb.fOutX)
1827 config->xon_xoff = SP_XONXOFF_OUT;
1829 config->xon_xoff = SP_XONXOFF_DISABLED;
1834 if (tcgetattr(port->fd, &data->term) < 0)
1835 RETURN_FAIL("tcgetattr() failed");
1837 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1838 RETURN_FAIL("TIOCMGET ioctl failed");
1841 int ret = get_flow(port->fd, data);
1843 if (ret == SP_ERR_FAIL && errno == EINVAL)
1844 data->termiox_supported = 0;
1846 RETURN_CODEVAL(ret);
1848 data->termiox_supported = 1;
1850 data->termiox_supported = 0;
1853 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1854 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1855 config->baudrate = std_baudrates[i].value;
1860 if (i == NUM_STD_BAUDRATES) {
1862 config->baudrate = (int)data->term.c_ispeed;
1863 #elif defined(USE_TERMIOS_SPEED)
1864 TRY(get_baudrate(port->fd, &config->baudrate));
1866 config->baudrate = -1;
1870 switch (data->term.c_cflag & CSIZE) {
1887 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1888 config->parity = SP_PARITY_NONE;
1889 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1890 config->parity = -1;
1892 else if (data->term.c_cflag & CMSPAR)
1893 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1896 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1898 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1900 if (data->term.c_cflag & CRTSCTS) {
1901 config->rts = SP_RTS_FLOW_CONTROL;
1902 config->cts = SP_CTS_FLOW_CONTROL;
1904 if (data->termiox_supported && data->rts_flow)
1905 config->rts = SP_RTS_FLOW_CONTROL;
1907 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1909 config->cts = (data->termiox_supported && data->cts_flow) ?
1910 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1913 if (data->termiox_supported && data->dtr_flow)
1914 config->dtr = SP_DTR_FLOW_CONTROL;
1916 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1918 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1919 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1921 if (data->term.c_iflag & IXOFF) {
1922 if (data->term.c_iflag & IXON)
1923 config->xon_xoff = SP_XONXOFF_INOUT;
1925 config->xon_xoff = SP_XONXOFF_IN;
1927 if (data->term.c_iflag & IXON)
1928 config->xon_xoff = SP_XONXOFF_OUT;
1930 config->xon_xoff = SP_XONXOFF_DISABLED;
1937 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1938 const struct sp_port_config *config)
1942 BAUD_TYPE baud_nonstd;
1946 #ifdef USE_TERMIOS_SPEED
1947 int baud_nonstd = 0;
1950 TRACE("%p, %p, %p", port, data, config);
1952 DEBUG_FMT("Setting configuration for port %s", port->name);
1956 TRY(await_write_completion(port));
1958 if (config->baudrate >= 0) {
1959 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1960 if (config->baudrate == std_baudrates[i].value) {
1961 data->dcb.BaudRate = std_baudrates[i].index;
1966 if (i == NUM_STD_BAUDRATES)
1967 data->dcb.BaudRate = config->baudrate;
1969 /* Allocate write buffer for 50ms of data at baud rate. */
1970 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1971 port->write_buf = realloc(port->write_buf,
1972 port->write_buf_size);
1974 if (!port->write_buf)
1975 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1978 if (config->bits >= 0)
1979 data->dcb.ByteSize = config->bits;
1981 if (config->parity >= 0) {
1982 switch (config->parity) {
1983 case SP_PARITY_NONE:
1984 data->dcb.Parity = NOPARITY;
1987 data->dcb.Parity = ODDPARITY;
1989 case SP_PARITY_EVEN:
1990 data->dcb.Parity = EVENPARITY;
1992 case SP_PARITY_MARK:
1993 data->dcb.Parity = MARKPARITY;
1995 case SP_PARITY_SPACE:
1996 data->dcb.Parity = SPACEPARITY;
1999 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2003 if (config->stopbits >= 0) {
2004 switch (config->stopbits) {
2005 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
2007 data->dcb.StopBits = ONESTOPBIT;
2010 data->dcb.StopBits = TWOSTOPBITS;
2013 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
2017 if (config->rts >= 0) {
2018 switch (config->rts) {
2020 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
2023 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
2025 case SP_RTS_FLOW_CONTROL:
2026 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
2029 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
2033 if (config->cts >= 0) {
2034 switch (config->cts) {
2036 data->dcb.fOutxCtsFlow = FALSE;
2038 case SP_CTS_FLOW_CONTROL:
2039 data->dcb.fOutxCtsFlow = TRUE;
2042 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
2046 if (config->dtr >= 0) {
2047 switch (config->dtr) {
2049 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
2052 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
2054 case SP_DTR_FLOW_CONTROL:
2055 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
2058 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
2062 if (config->dsr >= 0) {
2063 switch (config->dsr) {
2065 data->dcb.fOutxDsrFlow = FALSE;
2067 case SP_DSR_FLOW_CONTROL:
2068 data->dcb.fOutxDsrFlow = TRUE;
2071 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2075 if (config->xon_xoff >= 0) {
2076 switch (config->xon_xoff) {
2077 case SP_XONXOFF_DISABLED:
2078 data->dcb.fInX = FALSE;
2079 data->dcb.fOutX = FALSE;
2082 data->dcb.fInX = TRUE;
2083 data->dcb.fOutX = FALSE;
2085 case SP_XONXOFF_OUT:
2086 data->dcb.fInX = FALSE;
2087 data->dcb.fOutX = TRUE;
2089 case SP_XONXOFF_INOUT:
2090 data->dcb.fInX = TRUE;
2091 data->dcb.fOutX = TRUE;
2094 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2098 if (!SetCommState(port->hdl, &data->dcb))
2099 RETURN_FAIL("SetCommState() failed");
2105 if (config->baudrate >= 0) {
2106 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2107 if (config->baudrate == std_baudrates[i].value) {
2108 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2109 RETURN_FAIL("cfsetospeed() failed");
2111 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2112 RETURN_FAIL("cfsetispeed() failed");
2117 /* Non-standard baud rate */
2118 if (i == NUM_STD_BAUDRATES) {
2120 /* Set "dummy" baud rate. */
2121 if (cfsetspeed(&data->term, B9600) < 0)
2122 RETURN_FAIL("cfsetspeed() failed");
2123 baud_nonstd = config->baudrate;
2124 #elif defined(USE_TERMIOS_SPEED)
2127 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2132 if (config->bits >= 0) {
2133 data->term.c_cflag &= ~CSIZE;
2134 switch (config->bits) {
2136 data->term.c_cflag |= CS8;
2139 data->term.c_cflag |= CS7;
2142 data->term.c_cflag |= CS6;
2145 data->term.c_cflag |= CS5;
2148 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2152 if (config->parity >= 0) {
2153 data->term.c_iflag &= ~IGNPAR;
2154 data->term.c_cflag &= ~(PARENB | PARODD);
2156 data->term.c_cflag &= ~CMSPAR;
2158 switch (config->parity) {
2159 case SP_PARITY_NONE:
2160 data->term.c_iflag |= IGNPAR;
2162 case SP_PARITY_EVEN:
2163 data->term.c_cflag |= PARENB;
2166 data->term.c_cflag |= PARENB | PARODD;
2169 case SP_PARITY_MARK:
2170 data->term.c_cflag |= PARENB | PARODD;
2171 data->term.c_cflag |= CMSPAR;
2173 case SP_PARITY_SPACE:
2174 data->term.c_cflag |= PARENB;
2175 data->term.c_cflag |= CMSPAR;
2178 case SP_PARITY_MARK:
2179 case SP_PARITY_SPACE:
2180 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2183 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2187 if (config->stopbits >= 0) {
2188 data->term.c_cflag &= ~CSTOPB;
2189 switch (config->stopbits) {
2191 data->term.c_cflag &= ~CSTOPB;
2194 data->term.c_cflag |= CSTOPB;
2197 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2201 if (config->rts >= 0 || config->cts >= 0) {
2202 if (data->termiox_supported) {
2203 data->rts_flow = data->cts_flow = 0;
2204 switch (config->rts) {
2207 controlbits = TIOCM_RTS;
2208 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2209 RETURN_FAIL("Setting RTS signal level failed");
2211 case SP_RTS_FLOW_CONTROL:
2217 if (config->cts == SP_CTS_FLOW_CONTROL)
2220 if (data->rts_flow && data->cts_flow)
2221 data->term.c_iflag |= CRTSCTS;
2223 data->term.c_iflag &= ~CRTSCTS;
2225 /* Asymmetric use of RTS/CTS not supported. */
2226 if (data->term.c_iflag & CRTSCTS) {
2227 /* Flow control can only be disabled for both RTS & CTS together. */
2228 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2229 if (config->cts != SP_CTS_IGNORE)
2230 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2232 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2233 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2234 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2237 /* Flow control can only be enabled for both RTS & CTS together. */
2238 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2239 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2240 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2243 if (config->rts >= 0) {
2244 if (config->rts == SP_RTS_FLOW_CONTROL) {
2245 data->term.c_iflag |= CRTSCTS;
2247 controlbits = TIOCM_RTS;
2248 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2250 RETURN_FAIL("Setting RTS signal level failed");
2256 if (config->dtr >= 0 || config->dsr >= 0) {
2257 if (data->termiox_supported) {
2258 data->dtr_flow = data->dsr_flow = 0;
2259 switch (config->dtr) {
2262 controlbits = TIOCM_DTR;
2263 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2264 RETURN_FAIL("Setting DTR signal level failed");
2266 case SP_DTR_FLOW_CONTROL:
2272 if (config->dsr == SP_DSR_FLOW_CONTROL)
2275 /* DTR/DSR flow control not supported. */
2276 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2277 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2279 if (config->dtr >= 0) {
2280 controlbits = TIOCM_DTR;
2281 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2283 RETURN_FAIL("Setting DTR signal level failed");
2288 if (config->xon_xoff >= 0) {
2289 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2290 switch (config->xon_xoff) {
2291 case SP_XONXOFF_DISABLED:
2294 data->term.c_iflag |= IXOFF;
2296 case SP_XONXOFF_OUT:
2297 data->term.c_iflag |= IXON | IXANY;
2299 case SP_XONXOFF_INOUT:
2300 data->term.c_iflag |= IXON | IXOFF | IXANY;
2303 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2307 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2308 RETURN_FAIL("tcsetattr() failed");
2311 if (baud_nonstd != B0) {
2312 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2313 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2315 * Set baud rates in data->term to correct, but incompatible
2316 * with tcsetattr() value, same as delivered by tcgetattr().
2318 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2319 RETURN_FAIL("cfsetspeed() failed");
2321 #elif defined(__linux__)
2322 #ifdef USE_TERMIOS_SPEED
2324 TRY(set_baudrate(port->fd, config->baudrate));
2327 if (data->termiox_supported)
2328 TRY(set_flow(port->fd, data));
2332 #endif /* !_WIN32 */
2337 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2339 struct sp_port_config *config;
2341 TRACE("%p", config_ptr);
2344 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2348 if (!(config = malloc(sizeof(struct sp_port_config))))
2349 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2351 config->baudrate = -1;
2353 config->parity = -1;
2354 config->stopbits = -1;
2360 *config_ptr = config;
2365 SP_API void sp_free_config(struct sp_port_config *config)
2367 TRACE("%p", config);
2370 DEBUG("Null config");
2377 SP_API enum sp_return sp_get_config(struct sp_port *port,
2378 struct sp_port_config *config)
2380 struct port_data data;
2382 TRACE("%p, %p", port, config);
2387 RETURN_ERROR(SP_ERR_ARG, "Null config");
2389 TRY(get_config(port, &data, config));
2394 SP_API enum sp_return sp_set_config(struct sp_port *port,
2395 const struct sp_port_config *config)
2397 struct port_data data;
2398 struct sp_port_config prev_config;
2400 TRACE("%p, %p", port, config);
2405 RETURN_ERROR(SP_ERR_ARG, "Null config");
2407 TRY(get_config(port, &data, &prev_config));
2408 TRY(set_config(port, &data, config));
2413 #define CREATE_ACCESSORS(x, type) \
2414 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2415 struct port_data data; \
2416 struct sp_port_config config; \
2417 TRACE("%p, %d", port, x); \
2418 CHECK_OPEN_PORT(); \
2419 TRY(get_config(port, &data, &config)); \
2421 TRY(set_config(port, &data, &config)); \
2424 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2426 TRACE("%p, %p", config, x); \
2428 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2430 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2434 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2436 TRACE("%p, %d", config, x); \
2438 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2443 CREATE_ACCESSORS(baudrate, int)
2444 CREATE_ACCESSORS(bits, int)
2445 CREATE_ACCESSORS(parity, enum sp_parity)
2446 CREATE_ACCESSORS(stopbits, int)
2447 CREATE_ACCESSORS(rts, enum sp_rts)
2448 CREATE_ACCESSORS(cts, enum sp_cts)
2449 CREATE_ACCESSORS(dtr, enum sp_dtr)
2450 CREATE_ACCESSORS(dsr, enum sp_dsr)
2451 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2453 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2454 enum sp_flowcontrol flowcontrol)
2457 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2459 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2460 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2462 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2463 config->xon_xoff = SP_XONXOFF_INOUT;
2465 config->xon_xoff = SP_XONXOFF_DISABLED;
2467 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2468 config->rts = SP_RTS_FLOW_CONTROL;
2469 config->cts = SP_CTS_FLOW_CONTROL;
2471 if (config->rts == SP_RTS_FLOW_CONTROL)
2472 config->rts = SP_RTS_ON;
2473 config->cts = SP_CTS_IGNORE;
2476 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2477 config->dtr = SP_DTR_FLOW_CONTROL;
2478 config->dsr = SP_DSR_FLOW_CONTROL;
2480 if (config->dtr == SP_DTR_FLOW_CONTROL)
2481 config->dtr = SP_DTR_ON;
2482 config->dsr = SP_DSR_IGNORE;
2488 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2489 enum sp_flowcontrol flowcontrol)
2491 struct port_data data;
2492 struct sp_port_config config;
2494 TRACE("%p, %d", port, flowcontrol);
2498 TRY(get_config(port, &data, &config));
2500 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2502 TRY(set_config(port, &data, &config));
2507 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2508 enum sp_signal *signals)
2510 TRACE("%p, %p", port, signals);
2515 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2517 DEBUG_FMT("Getting control signals for port %s", port->name);
2522 if (GetCommModemStatus(port->hdl, &bits) == 0)
2523 RETURN_FAIL("GetCommModemStatus() failed");
2524 if (bits & MS_CTS_ON)
2525 *signals |= SP_SIG_CTS;
2526 if (bits & MS_DSR_ON)
2527 *signals |= SP_SIG_DSR;
2528 if (bits & MS_RLSD_ON)
2529 *signals |= SP_SIG_DCD;
2530 if (bits & MS_RING_ON)
2531 *signals |= SP_SIG_RI;
2534 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2535 RETURN_FAIL("TIOCMGET ioctl failed");
2536 if (bits & TIOCM_CTS)
2537 *signals |= SP_SIG_CTS;
2538 if (bits & TIOCM_DSR)
2539 *signals |= SP_SIG_DSR;
2540 if (bits & TIOCM_CAR)
2541 *signals |= SP_SIG_DCD;
2542 if (bits & TIOCM_RNG)
2543 *signals |= SP_SIG_RI;
2548 SP_API enum sp_return sp_start_break(struct sp_port *port)
2554 if (SetCommBreak(port->hdl) == 0)
2555 RETURN_FAIL("SetCommBreak() failed");
2557 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2558 RETURN_FAIL("TIOCSBRK ioctl failed");
2564 SP_API enum sp_return sp_end_break(struct sp_port *port)
2570 if (ClearCommBreak(port->hdl) == 0)
2571 RETURN_FAIL("ClearCommBreak() failed");
2573 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2574 RETURN_FAIL("TIOCCBRK ioctl failed");
2580 SP_API int sp_last_error_code(void)
2584 RETURN_INT(GetLastError());
2590 SP_API char *sp_last_error_message(void)
2596 DWORD error = GetLastError();
2598 DWORD length = FormatMessage(
2599 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2600 FORMAT_MESSAGE_FROM_SYSTEM |
2601 FORMAT_MESSAGE_IGNORE_INSERTS,
2604 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2608 if (length >= 2 && message[length - 2] == '\r')
2609 message[length - 2] = '\0';
2611 RETURN_STRING(message);
2613 RETURN_STRING(strerror(errno));
2617 SP_API void sp_free_error_message(char *message)
2619 TRACE("%s", message);
2630 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2632 TRACE("%p", handler);
2634 sp_debug_handler = handler;
2639 SP_API void sp_default_debug_handler(const char *format, ...)
2642 va_start(args, format);
2643 if (getenv("LIBSERIALPORT_DEBUG")) {
2644 fputs("sp: ", stderr);
2645 vfprintf(stderr, format, args);
2650 SP_API int sp_get_major_package_version(void)
2652 return SP_PACKAGE_VERSION_MAJOR;
2655 SP_API int sp_get_minor_package_version(void)
2657 return SP_PACKAGE_VERSION_MINOR;
2660 SP_API int sp_get_micro_package_version(void)
2662 return SP_PACKAGE_VERSION_MICRO;
2665 SP_API const char *sp_get_package_version_string(void)
2667 return SP_PACKAGE_VERSION_STRING;
2670 SP_API int sp_get_current_lib_version(void)
2672 return SP_LIB_VERSION_CURRENT;
2675 SP_API int sp_get_revision_lib_version(void)
2677 return SP_LIB_VERSION_REVISION;
2680 SP_API int sp_get_age_lib_version(void)
2682 return SP_LIB_VERSION_AGE;
2685 SP_API const char *sp_get_lib_version_string(void)
2687 return SP_LIB_VERSION_STRING;