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 */
66 #define TIME_ZERO {.tv = {0, 0}}
67 #define TIME_MS(ms) {.tv = {ms / 1000, (ms % 1000) * 1000}}
69 static void time_get(struct time *time)
71 #ifdef HAVE_CLOCK_GETTIME
73 if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
74 clock_gettime(CLOCK_REALTIME, &ts);
75 time->tv.tv_sec = ts.tv_sec;
76 time->tv.tv_usec = ts.tv_nsec / 1000;
77 #elif defined(__APPLE__)
78 mach_timebase_info_data_t info;
79 mach_timebase_info(&info);
80 uint64_t ticks = mach_absolute_time();
81 uint64_t ns = (ticks * info.numer) / info.denom;
82 time->tv.tv_sec = ns / 1000000000;
83 time->tv.tv_usec = (ns % 1000000000) / 1000;
85 gettimeofday(&time->tv, NULL);
89 static void time_set_ms(struct time *time, unsigned int ms)
91 time->tv.tv_sec = ms / 1000;
92 time->tv.tv_usec = (ms % 1000) * 1000;
95 static void time_add(const struct time *a,
96 const struct time *b, struct time *result)
98 timeradd(&a->tv, &b->tv, &result->tv);
101 static void time_sub(const struct time *a,
102 const struct time *b, struct time *result)
104 timersub(&a->tv, &b->tv, &result->tv);
107 static bool time_greater(const struct time *a, const struct time *b)
109 return timercmp(&a->tv, &b->tv, >);
112 static void time_as_timeval(const struct time *time, struct timeval *tv)
117 static unsigned int time_as_ms(const struct time *time)
119 return time->tv.tv_sec * 1000 + time->tv.tv_usec / 1000;
124 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
126 struct sp_port *port;
127 #ifndef NO_PORT_METADATA
132 TRACE("%s, %p", portname, port_ptr);
135 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
140 RETURN_ERROR(SP_ERR_ARG, "Null port name");
142 DEBUG_FMT("Building structure for port %s", portname);
144 #if !defined(_WIN32) && defined(HAVE_REALPATH)
146 * get_port_details() below tries to be too smart and figure out
147 * some transport properties from the port name which breaks with
148 * symlinks. Therefore we canonicalize the portname first.
150 char pathbuf[PATH_MAX + 1];
151 char *res = realpath(portname, pathbuf);
153 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
158 if (!(port = malloc(sizeof(struct sp_port))))
159 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
161 len = strlen(portname) + 1;
163 if (!(port->name = malloc(len))) {
165 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
168 memcpy(port->name, portname, len);
171 port->usb_path = NULL;
172 port->hdl = INVALID_HANDLE_VALUE;
173 port->write_buf = NULL;
174 port->write_buf_size = 0;
179 port->description = NULL;
180 port->transport = SP_TRANSPORT_NATIVE;
182 port->usb_address = -1;
185 port->usb_manufacturer = NULL;
186 port->usb_product = NULL;
187 port->usb_serial = NULL;
188 port->bluetooth_address = NULL;
190 #ifndef NO_PORT_METADATA
191 if ((ret = get_port_details(port)) != SP_OK) {
202 SP_API char *sp_get_port_name(const struct sp_port *port)
209 RETURN_STRING(port->name);
212 SP_API char *sp_get_port_description(const struct sp_port *port)
216 if (!port || !port->description)
219 RETURN_STRING(port->description);
222 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
227 RETURN_ERROR(SP_ERR_ARG, "Null port");
229 RETURN_INT(port->transport);
232 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
233 int *usb_bus,int *usb_address)
238 RETURN_ERROR(SP_ERR_ARG, "Null port");
239 if (port->transport != SP_TRANSPORT_USB)
240 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
241 if (port->usb_bus < 0 || port->usb_address < 0)
242 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
245 *usb_bus = port->usb_bus;
247 *usb_address = port->usb_address;
252 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
253 int *usb_vid, int *usb_pid)
258 RETURN_ERROR(SP_ERR_ARG, "Null port");
259 if (port->transport != SP_TRANSPORT_USB)
260 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
261 if (port->usb_vid < 0 || port->usb_pid < 0)
262 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
265 *usb_vid = port->usb_vid;
267 *usb_pid = port->usb_pid;
272 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
276 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
279 RETURN_STRING(port->usb_manufacturer);
282 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
286 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
289 RETURN_STRING(port->usb_product);
292 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
296 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
299 RETURN_STRING(port->usb_serial);
302 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
306 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
307 || !port->bluetooth_address)
310 RETURN_STRING(port->bluetooth_address);
313 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
316 TRACE("%p, %p", port, result_ptr);
319 RETURN_ERROR(SP_ERR_ARG, "Null port");
321 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
324 HANDLE *handle_ptr = result_ptr;
325 *handle_ptr = port->hdl;
327 int *fd_ptr = result_ptr;
334 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
335 struct sp_port **copy_ptr)
337 TRACE("%p, %p", port, copy_ptr);
340 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
345 RETURN_ERROR(SP_ERR_ARG, "Null port");
348 RETURN_ERROR(SP_ERR_ARG, "Null port name");
350 DEBUG("Copying port structure");
352 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
355 SP_API void sp_free_port(struct sp_port *port)
364 DEBUG("Freeing port structure");
368 if (port->description)
369 free(port->description);
370 if (port->usb_manufacturer)
371 free(port->usb_manufacturer);
372 if (port->usb_product)
373 free(port->usb_product);
374 if (port->usb_serial)
375 free(port->usb_serial);
376 if (port->bluetooth_address)
377 free(port->bluetooth_address);
380 free(port->usb_path);
382 free(port->write_buf);
390 SP_PRIV struct sp_port **list_append(struct sp_port **list,
391 const char *portname)
396 for (count = 0; list[count]; count++)
398 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
401 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
403 list[count + 1] = NULL;
407 sp_free_port_list(list);
411 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
413 #ifndef NO_ENUMERATION
414 struct sp_port **list;
418 TRACE("%p", list_ptr);
421 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
425 #ifdef NO_ENUMERATION
426 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
428 DEBUG("Enumerating ports");
430 if (!(list = malloc(sizeof(struct sp_port *))))
431 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
435 ret = list_ports(&list);
440 sp_free_port_list(list);
448 SP_API void sp_free_port_list(struct sp_port **list)
459 DEBUG("Freeing port list");
461 for (i = 0; list[i]; i++)
462 sp_free_port(list[i]);
468 #define CHECK_PORT() do { \
470 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
472 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
475 #define CHECK_PORT_HANDLE() do { \
476 if (port->hdl == INVALID_HANDLE_VALUE) \
477 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
480 #define CHECK_PORT_HANDLE() do { \
482 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
485 #define CHECK_OPEN_PORT() do { \
487 CHECK_PORT_HANDLE(); \
491 /** To be called after port receive buffer is emptied. */
492 static enum sp_return restart_wait(struct sp_port *port)
496 if (port->wait_running) {
497 /* Check status of running wait operation. */
498 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
499 &wait_result, FALSE)) {
500 DEBUG("Previous wait completed");
501 port->wait_running = FALSE;
502 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
503 DEBUG("Previous wait still running");
506 RETURN_FAIL("GetOverlappedResult() failed");
510 if (!port->wait_running) {
511 /* Start new wait operation. */
512 if (WaitCommEvent(port->hdl, &port->events,
514 DEBUG("New wait returned, events already pending");
515 } else if (GetLastError() == ERROR_IO_PENDING) {
516 DEBUG("New wait running in background");
517 port->wait_running = TRUE;
519 RETURN_FAIL("WaitCommEvent() failed");
527 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
529 struct port_data data;
530 struct sp_port_config config;
533 TRACE("%p, 0x%x", port, flags);
537 if (flags > SP_MODE_READ_WRITE)
538 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
540 DEBUG_FMT("Opening port %s", port->name);
543 DWORD desired_access = 0, flags_and_attributes = 0, errors;
544 char *escaped_port_name;
547 /* Prefix port name with '\\.\' to work with ports above COM9. */
548 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
549 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
550 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
552 /* Map 'flags' to the OS-specific settings. */
553 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
554 if (flags & SP_MODE_READ)
555 desired_access |= GENERIC_READ;
556 if (flags & SP_MODE_WRITE)
557 desired_access |= GENERIC_WRITE;
559 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
560 OPEN_EXISTING, flags_and_attributes, 0);
562 free(escaped_port_name);
564 if (port->hdl == INVALID_HANDLE_VALUE)
565 RETURN_FAIL("Port CreateFile() failed");
567 /* All timeouts initially disabled. */
568 port->timeouts.ReadIntervalTimeout = 0;
569 port->timeouts.ReadTotalTimeoutMultiplier = 0;
570 port->timeouts.ReadTotalTimeoutConstant = 0;
571 port->timeouts.WriteTotalTimeoutMultiplier = 0;
572 port->timeouts.WriteTotalTimeoutConstant = 0;
574 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
576 RETURN_FAIL("SetCommTimeouts() failed");
579 /* Prepare OVERLAPPED structures. */
580 #define INIT_OVERLAPPED(ovl) do { \
581 memset(&port->ovl, 0, sizeof(port->ovl)); \
582 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
583 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
584 == INVALID_HANDLE_VALUE) { \
586 RETURN_FAIL(#ovl "CreateEvent() failed"); \
590 INIT_OVERLAPPED(read_ovl);
591 INIT_OVERLAPPED(write_ovl);
592 INIT_OVERLAPPED(wait_ovl);
594 /* Set event mask for RX and error events. */
595 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
597 RETURN_FAIL("SetCommMask() failed");
600 port->writing = FALSE;
601 port->wait_running = FALSE;
603 ret = restart_wait(port);
610 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
612 /* Map 'flags' to the OS-specific settings. */
613 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
614 flags_local |= O_RDWR;
615 else if (flags & SP_MODE_READ)
616 flags_local |= O_RDONLY;
617 else if (flags & SP_MODE_WRITE)
618 flags_local |= O_WRONLY;
620 if ((port->fd = open(port->name, flags_local)) < 0)
621 RETURN_FAIL("open() failed");
624 ret = get_config(port, &data, &config);
631 /* Set sane port settings. */
633 data.dcb.fBinary = TRUE;
634 data.dcb.fDsrSensitivity = FALSE;
635 data.dcb.fErrorChar = FALSE;
636 data.dcb.fNull = FALSE;
637 data.dcb.fAbortOnError = FALSE;
639 /* Turn off all fancy termios tricks, give us a raw channel. */
640 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
642 data.term.c_iflag &= ~IUCLC;
644 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
646 data.term.c_oflag &= ~OLCUC;
649 data.term.c_oflag &= ~NLDLY;
652 data.term.c_oflag &= ~CRDLY;
655 data.term.c_oflag &= ~TABDLY;
658 data.term.c_oflag &= ~BSDLY;
661 data.term.c_oflag &= ~VTDLY;
664 data.term.c_oflag &= ~FFDLY;
667 data.term.c_oflag &= ~OFILL;
669 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
670 data.term.c_cc[VMIN] = 0;
671 data.term.c_cc[VTIME] = 0;
673 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
674 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
678 if (ClearCommError(port->hdl, &errors, &status) == 0)
679 RETURN_FAIL("ClearCommError() failed");
682 ret = set_config(port, &data, &config);
692 SP_API enum sp_return sp_close(struct sp_port *port)
698 DEBUG_FMT("Closing port %s", port->name);
701 /* Returns non-zero upon success, 0 upon failure. */
702 if (CloseHandle(port->hdl) == 0)
703 RETURN_FAIL("Port CloseHandle() failed");
704 port->hdl = INVALID_HANDLE_VALUE;
706 /* Close event handles for overlapped structures. */
707 #define CLOSE_OVERLAPPED(ovl) do { \
708 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
709 CloseHandle(port->ovl.hEvent) == 0) \
710 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
712 CLOSE_OVERLAPPED(read_ovl);
713 CLOSE_OVERLAPPED(write_ovl);
714 CLOSE_OVERLAPPED(wait_ovl);
716 if (port->write_buf) {
717 free(port->write_buf);
718 port->write_buf = NULL;
721 /* Returns 0 upon success, -1 upon failure. */
722 if (close(port->fd) == -1)
723 RETURN_FAIL("close() failed");
730 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
732 TRACE("%p, 0x%x", port, buffers);
736 if (buffers > SP_BUF_BOTH)
737 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
739 const char *buffer_names[] = {"no", "input", "output", "both"};
741 DEBUG_FMT("Flushing %s buffers on port %s",
742 buffer_names[buffers], port->name);
746 if (buffers & SP_BUF_INPUT)
747 flags |= PURGE_RXCLEAR;
748 if (buffers & SP_BUF_OUTPUT)
749 flags |= PURGE_TXCLEAR;
751 /* Returns non-zero upon success, 0 upon failure. */
752 if (PurgeComm(port->hdl, flags) == 0)
753 RETURN_FAIL("PurgeComm() failed");
755 if (buffers & SP_BUF_INPUT)
756 TRY(restart_wait(port));
759 if (buffers == SP_BUF_BOTH)
761 else if (buffers == SP_BUF_INPUT)
763 else if (buffers == SP_BUF_OUTPUT)
766 /* Returns 0 upon success, -1 upon failure. */
767 if (tcflush(port->fd, flags) < 0)
768 RETURN_FAIL("tcflush() failed");
773 SP_API enum sp_return sp_drain(struct sp_port *port)
779 DEBUG_FMT("Draining port %s", port->name);
782 /* Returns non-zero upon success, 0 upon failure. */
783 if (FlushFileBuffers(port->hdl) == 0)
784 RETURN_FAIL("FlushFileBuffers() failed");
789 #if defined(__ANDROID__) && (__ANDROID_API__ < 21)
790 /* Android only has tcdrain from platform 21 onwards.
791 * On previous API versions, use the ioctl directly. */
793 result = ioctl(port->fd, TCSBRK, &arg);
795 result = tcdrain(port->fd);
798 if (errno == EINTR) {
799 DEBUG("tcdrain() was interrupted");
802 RETURN_FAIL("tcdrain() failed");
812 static enum sp_return await_write_completion(struct sp_port *port)
818 /* Wait for previous non-blocking write to complete, if any. */
820 DEBUG("Waiting for previous write to complete");
821 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
824 RETURN_FAIL("Previous write failed to complete");
825 DEBUG("Previous write completed");
832 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
833 size_t count, unsigned int timeout_ms)
835 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
840 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
843 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
844 count, port->name, timeout_ms);
846 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
853 DWORD bytes_written = 0;
855 TRY(await_write_completion(port));
858 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
859 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
860 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
861 RETURN_FAIL("SetCommTimeouts() failed");
864 /* Reduce count if it exceeds the WriteFile limit. */
865 if (count > WRITEFILE_MAX_SIZE)
866 count = WRITEFILE_MAX_SIZE;
869 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
870 DEBUG("Write completed immediately");
872 } else if (GetLastError() == ERROR_IO_PENDING) {
873 DEBUG("Waiting for write to complete");
874 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
875 if (GetLastError() == ERROR_SEM_TIMEOUT) {
876 DEBUG("Write timed out");
879 RETURN_FAIL("GetOverlappedResult() failed");
882 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
883 RETURN_INT(bytes_written);
885 RETURN_FAIL("WriteFile() failed");
888 size_t bytes_written = 0;
889 unsigned char *ptr = (unsigned char *) buf;
890 struct time start, delta, now, end = TIME_ZERO;
896 /* Get time at start of operation. */
898 /* Define duration of timeout. */
899 time_set_ms(&delta, timeout_ms);
900 /* Calculate time at which we should give up. */
901 time_add(&start, &delta, &end);
905 FD_SET(port->fd, &fds);
907 /* Loop until we have written the requested number of bytes. */
908 while (bytes_written < count) {
910 * Check timeout only if we have run select() at least once,
911 * to avoid any issues if a short timeout is reached before
912 * select() is even run.
915 if (timeout_ms && started) {
917 if (time_greater(&now, &end))
918 /* Timeout has expired. */
920 time_sub(&end, &now, &delta);
921 time_as_timeval(&delta, &tv);
923 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &tv : NULL);
926 if (errno == EINTR) {
927 DEBUG("select() call was interrupted, repeating");
930 RETURN_FAIL("select() failed");
932 } else if (result == 0) {
933 /* Timeout has expired. */
938 result = write(port->fd, ptr, count - bytes_written);
942 /* This shouldn't happen because we did a select() first, but handle anyway. */
945 /* This is an actual failure. */
946 RETURN_FAIL("write() failed");
949 bytes_written += result;
953 if (bytes_written < count)
954 DEBUG("Write timed out");
956 RETURN_INT(bytes_written);
960 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
961 const void *buf, size_t count)
963 TRACE("%p, %p, %d", port, buf, count);
968 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
970 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
978 /* Check whether previous write is complete. */
980 if (HasOverlappedIoCompleted(&port->write_ovl)) {
981 DEBUG("Previous write completed");
984 DEBUG("Previous write not complete");
985 /* Can't take a new write until the previous one finishes. */
991 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
992 port->timeouts.WriteTotalTimeoutConstant = 0;
993 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
994 RETURN_FAIL("SetCommTimeouts() failed");
997 /* Reduce count if it exceeds the WriteFile limit. */
998 if (count > WRITEFILE_MAX_SIZE)
999 count = WRITEFILE_MAX_SIZE;
1001 /* Copy data to our write buffer. */
1002 buf_bytes = min(port->write_buf_size, count);
1003 memcpy(port->write_buf, buf, buf_bytes);
1005 /* Start asynchronous write. */
1006 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
1007 if (GetLastError() == ERROR_IO_PENDING) {
1008 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
1009 DEBUG("Asynchronous write completed immediately");
1011 DEBUG("Asynchronous write running");
1013 /* Actual failure of some kind. */
1014 RETURN_FAIL("WriteFile() failed");
1018 DEBUG("All bytes written immediately");
1020 RETURN_INT(buf_bytes);
1022 /* Returns the number of bytes written, or -1 upon failure. */
1023 ssize_t written = write(port->fd, buf, count);
1026 if (errno == EAGAIN)
1027 // Buffer is full, no bytes written.
1030 RETURN_FAIL("write() failed");
1032 RETURN_INT(written);
1038 /* Restart wait operation if buffer was emptied. */
1039 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1044 if (bytes_read == 0)
1047 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1048 RETURN_FAIL("ClearCommError() failed");
1050 if (comstat.cbInQue == 0)
1051 TRY(restart_wait(port));
1057 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1058 size_t count, unsigned int timeout_ms)
1060 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1065 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1068 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1069 count, port->name, timeout_ms);
1071 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1078 DWORD bytes_read = 0;
1081 if (port->timeouts.ReadIntervalTimeout != 0 ||
1082 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1083 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1084 port->timeouts.ReadIntervalTimeout = 0;
1085 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1086 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1087 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1088 RETURN_FAIL("SetCommTimeouts() failed");
1092 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1093 DEBUG("Read completed immediately");
1095 } else if (GetLastError() == ERROR_IO_PENDING) {
1096 DEBUG("Waiting for read to complete");
1097 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1098 RETURN_FAIL("GetOverlappedResult() failed");
1099 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1101 RETURN_FAIL("ReadFile() failed");
1104 TRY(restart_wait_if_needed(port, bytes_read));
1106 RETURN_INT(bytes_read);
1109 size_t bytes_read = 0;
1110 unsigned char *ptr = (unsigned char *) buf;
1111 struct time start, delta, now, end = TIME_ZERO;
1117 /* Get time at start of operation. */
1119 /* Define duration of timeout. */
1120 time_set_ms(&delta, timeout_ms);
1121 /* Calculate time at which we should give up. */
1122 time_add(&start, &delta, &end);
1126 FD_SET(port->fd, &fds);
1128 /* Loop until we have the requested number of bytes. */
1129 while (bytes_read < count) {
1131 * Check timeout only if we have run select() at least once,
1132 * to avoid any issues if a short timeout is reached before
1133 * select() is even run.
1136 if (timeout_ms && started) {
1138 if (time_greater(&now, &end))
1139 /* Timeout has expired. */
1141 time_sub(&end, &now, &delta);
1142 time_as_timeval(&delta, &tv);
1144 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &tv : NULL);
1147 if (errno == EINTR) {
1148 DEBUG("select() call was interrupted, repeating");
1151 RETURN_FAIL("select() failed");
1153 } else if (result == 0) {
1154 /* Timeout has expired. */
1159 result = read(port->fd, ptr, count - bytes_read);
1162 if (errno == EAGAIN)
1164 * This shouldn't happen because we did a
1165 * select() first, but handle anyway.
1169 /* This is an actual failure. */
1170 RETURN_FAIL("read() failed");
1173 bytes_read += result;
1177 if (bytes_read < count)
1178 DEBUG("Read timed out");
1180 RETURN_INT(bytes_read);
1184 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1185 size_t count, unsigned int timeout_ms)
1187 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1192 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1195 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1198 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1199 count, port->name, timeout_ms);
1201 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1205 DWORD bytes_read = 0;
1207 /* If timeout_ms == 0, set maximum timeout. */
1208 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1211 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1212 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1213 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1214 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1215 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1216 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1217 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1218 RETURN_FAIL("SetCommTimeouts() failed");
1221 /* Loop until we have at least one byte, or timeout is reached. */
1222 while (bytes_read == 0) {
1224 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1225 DEBUG("Read completed immediately");
1226 } else if (GetLastError() == ERROR_IO_PENDING) {
1227 DEBUG("Waiting for read to complete");
1228 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1229 RETURN_FAIL("GetOverlappedResult() failed");
1230 if (bytes_read > 0) {
1231 DEBUG("Read completed");
1232 } else if (timeout_ms > 0) {
1233 DEBUG("Read timed out");
1236 DEBUG("Restarting read");
1239 RETURN_FAIL("ReadFile() failed");
1243 TRY(restart_wait_if_needed(port, bytes_read));
1245 RETURN_INT(bytes_read);
1248 size_t bytes_read = 0;
1249 struct time start, delta, now, end = TIME_ZERO;
1255 /* Get time at start of operation. */
1257 /* Define duration of timeout. */
1258 time_set_ms(&delta, timeout_ms);
1259 /* Calculate time at which we should give up. */
1260 time_add(&start, &delta, &end);
1264 FD_SET(port->fd, &fds);
1266 /* Loop until we have at least one byte, or timeout is reached. */
1267 while (bytes_read == 0) {
1269 * Check timeout only if we have run select() at least once,
1270 * to avoid any issues if a short timeout is reached before
1271 * select() is even run.
1274 if (timeout_ms && started) {
1276 if (time_greater(&now, &end))
1277 /* Timeout has expired. */
1279 time_sub(&end, &now, &delta);
1280 time_as_timeval(&delta, &tv);
1282 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &tv : NULL);
1285 if (errno == EINTR) {
1286 DEBUG("select() call was interrupted, repeating");
1289 RETURN_FAIL("select() failed");
1291 } else if (result == 0) {
1292 /* Timeout has expired. */
1297 result = read(port->fd, buf, count);
1300 if (errno == EAGAIN)
1301 /* This shouldn't happen because we did a select() first, but handle anyway. */
1304 /* This is an actual failure. */
1305 RETURN_FAIL("read() failed");
1308 bytes_read = result;
1311 if (bytes_read == 0)
1312 DEBUG("Read timed out");
1314 RETURN_INT(bytes_read);
1318 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1321 TRACE("%p, %p, %d", port, buf, count);
1326 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1328 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1334 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1335 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1336 port->timeouts.ReadTotalTimeoutConstant != 0) {
1337 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1338 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1339 port->timeouts.ReadTotalTimeoutConstant = 0;
1340 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1341 RETURN_FAIL("SetCommTimeouts() failed");
1345 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1346 if (GetLastError() != ERROR_IO_PENDING)
1347 RETURN_FAIL("ReadFile() failed");
1349 /* Get number of bytes read. */
1350 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1351 RETURN_FAIL("GetOverlappedResult() failed");
1353 TRY(restart_wait_if_needed(port, bytes_read));
1355 RETURN_INT(bytes_read);
1359 /* Returns the number of bytes read, or -1 upon failure. */
1360 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1361 if (errno == EAGAIN)
1362 /* No bytes available. */
1365 /* This is an actual failure. */
1366 RETURN_FAIL("read() failed");
1368 RETURN_INT(bytes_read);
1372 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1378 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1384 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1385 RETURN_FAIL("ClearCommError() failed");
1386 RETURN_INT(comstat.cbInQue);
1389 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1390 RETURN_FAIL("TIOCINQ ioctl failed");
1391 RETURN_INT(bytes_waiting);
1395 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1401 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1407 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1408 RETURN_FAIL("ClearCommError() failed");
1409 RETURN_INT(comstat.cbOutQue);
1412 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1413 RETURN_FAIL("TIOCOUTQ ioctl failed");
1414 RETURN_INT(bytes_waiting);
1418 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1420 struct sp_event_set *result;
1422 TRACE("%p", result_ptr);
1425 RETURN_ERROR(SP_ERR_ARG, "Null result");
1429 if (!(result = malloc(sizeof(struct sp_event_set))))
1430 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1432 memset(result, 0, sizeof(struct sp_event_set));
1434 *result_ptr = result;
1439 static enum sp_return add_handle(struct sp_event_set *event_set,
1440 event_handle handle, enum sp_event mask)
1443 enum sp_event *new_masks;
1445 TRACE("%p, %d, %d", event_set, handle, mask);
1447 if (!(new_handles = realloc(event_set->handles,
1448 sizeof(event_handle) * (event_set->count + 1))))
1449 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1451 event_set->handles = new_handles;
1453 if (!(new_masks = realloc(event_set->masks,
1454 sizeof(enum sp_event) * (event_set->count + 1))))
1455 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1457 event_set->masks = new_masks;
1459 ((event_handle *) event_set->handles)[event_set->count] = handle;
1460 event_set->masks[event_set->count] = mask;
1467 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1468 const struct sp_port *port, enum sp_event mask)
1470 TRACE("%p, %p, %d", event_set, port, mask);
1473 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1476 RETURN_ERROR(SP_ERR_ARG, "Null port");
1478 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1479 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1485 enum sp_event handle_mask;
1486 if ((handle_mask = mask & SP_EVENT_TX_READY))
1487 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1488 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1489 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1491 TRY(add_handle(event_set, port->fd, mask));
1497 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1499 TRACE("%p", event_set);
1502 DEBUG("Null event set");
1506 DEBUG("Freeing event set");
1508 if (event_set->handles)
1509 free(event_set->handles);
1510 if (event_set->masks)
1511 free(event_set->masks);
1518 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1519 unsigned int timeout_ms)
1521 TRACE("%p, %d", event_set, timeout_ms);
1524 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1527 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1528 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1529 RETURN_FAIL("WaitForMultipleObjects() failed");
1533 struct time start, delta, now, end = TIME_ZERO;
1534 const struct time max_delta = TIME_MS(INT_MAX);
1535 int started = 0, timeout_overflow = 0;
1536 int result, timeout_remaining_ms;
1537 struct pollfd *pollfds;
1540 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1541 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1543 for (i = 0; i < event_set->count; i++) {
1544 pollfds[i].fd = ((int *)event_set->handles)[i];
1545 pollfds[i].events = 0;
1546 pollfds[i].revents = 0;
1547 if (event_set->masks[i] & SP_EVENT_RX_READY)
1548 pollfds[i].events |= POLLIN;
1549 if (event_set->masks[i] & SP_EVENT_TX_READY)
1550 pollfds[i].events |= POLLOUT;
1551 if (event_set->masks[i] & SP_EVENT_ERROR)
1552 pollfds[i].events |= POLLERR;
1556 /* Get time at start of operation. */
1558 /* Define duration of timeout. */
1559 time_set_ms(&delta, timeout_ms);
1560 /* Calculate time at which we should give up. */
1561 time_add(&start, &delta, &end);
1564 /* Loop until an event occurs. */
1567 * Check timeout only if we have run poll() at least once,
1568 * to avoid any issues if a short timeout is reached before
1569 * poll() is even run.
1572 timeout_remaining_ms = -1;
1573 } else if (!started) {
1574 timeout_overflow = (timeout_ms > INT_MAX);
1575 timeout_remaining_ms = timeout_overflow ? INT_MAX : timeout_ms;
1578 if (time_greater(&now, &end)) {
1579 DEBUG("Wait timed out");
1582 time_sub(&end, &now, &delta);
1583 if ((timeout_overflow = time_greater(&delta, &max_delta)))
1585 timeout_remaining_ms = time_as_ms(&delta);
1588 result = poll(pollfds, event_set->count, timeout_remaining_ms);
1592 if (errno == EINTR) {
1593 DEBUG("poll() call was interrupted, repeating");
1597 RETURN_FAIL("poll() failed");
1599 } else if (result == 0) {
1600 DEBUG("poll() timed out");
1601 if (!timeout_overflow)
1604 DEBUG("poll() completed");
1614 #ifdef USE_TERMIOS_SPEED
1615 static enum sp_return get_baudrate(int fd, int *baudrate)
1619 TRACE("%d, %p", fd, baudrate);
1621 DEBUG("Getting baud rate");
1623 if (!(data = malloc(get_termios_size())))
1624 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1626 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1628 RETURN_FAIL("Getting termios failed");
1631 *baudrate = get_termios_speed(data);
1638 static enum sp_return set_baudrate(int fd, int baudrate)
1642 TRACE("%d, %d", fd, baudrate);
1644 DEBUG("Getting baud rate");
1646 if (!(data = malloc(get_termios_size())))
1647 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1649 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1651 RETURN_FAIL("Getting termios failed");
1654 DEBUG("Setting baud rate");
1656 set_termios_speed(data, baudrate);
1658 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1660 RETURN_FAIL("Setting termios failed");
1667 #endif /* USE_TERMIOS_SPEED */
1670 static enum sp_return get_flow(int fd, struct port_data *data)
1674 TRACE("%d, %p", fd, data);
1676 DEBUG("Getting advanced flow control");
1678 if (!(termx = malloc(get_termiox_size())))
1679 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1681 if (ioctl(fd, TCGETX, termx) < 0) {
1683 RETURN_FAIL("Getting termiox failed");
1686 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1687 &data->dtr_flow, &data->dsr_flow);
1694 static enum sp_return set_flow(int fd, struct port_data *data)
1698 TRACE("%d, %p", fd, data);
1700 DEBUG("Getting advanced flow control");
1702 if (!(termx = malloc(get_termiox_size())))
1703 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1705 if (ioctl(fd, TCGETX, termx) < 0) {
1707 RETURN_FAIL("Getting termiox failed");
1710 DEBUG("Setting advanced flow control");
1712 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1713 data->dtr_flow, data->dsr_flow);
1715 if (ioctl(fd, TCSETX, termx) < 0) {
1717 RETURN_FAIL("Setting termiox failed");
1724 #endif /* USE_TERMIOX */
1726 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1727 struct sp_port_config *config)
1731 TRACE("%p, %p, %p", port, data, config);
1733 DEBUG_FMT("Getting configuration for port %s", port->name);
1736 if (!GetCommState(port->hdl, &data->dcb))
1737 RETURN_FAIL("GetCommState() failed");
1739 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1740 if (data->dcb.BaudRate == std_baudrates[i].index) {
1741 config->baudrate = std_baudrates[i].value;
1746 if (i == NUM_STD_BAUDRATES)
1747 /* BaudRate field can be either an index or a custom baud rate. */
1748 config->baudrate = data->dcb.BaudRate;
1750 config->bits = data->dcb.ByteSize;
1752 if (data->dcb.fParity)
1753 switch (data->dcb.Parity) {
1755 config->parity = SP_PARITY_NONE;
1758 config->parity = SP_PARITY_ODD;
1761 config->parity = SP_PARITY_EVEN;
1764 config->parity = SP_PARITY_MARK;
1767 config->parity = SP_PARITY_SPACE;
1770 config->parity = -1;
1773 config->parity = SP_PARITY_NONE;
1775 switch (data->dcb.StopBits) {
1777 config->stopbits = 1;
1780 config->stopbits = 2;
1783 config->stopbits = -1;
1786 switch (data->dcb.fRtsControl) {
1787 case RTS_CONTROL_DISABLE:
1788 config->rts = SP_RTS_OFF;
1790 case RTS_CONTROL_ENABLE:
1791 config->rts = SP_RTS_ON;
1793 case RTS_CONTROL_HANDSHAKE:
1794 config->rts = SP_RTS_FLOW_CONTROL;
1800 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1802 switch (data->dcb.fDtrControl) {
1803 case DTR_CONTROL_DISABLE:
1804 config->dtr = SP_DTR_OFF;
1806 case DTR_CONTROL_ENABLE:
1807 config->dtr = SP_DTR_ON;
1809 case DTR_CONTROL_HANDSHAKE:
1810 config->dtr = SP_DTR_FLOW_CONTROL;
1816 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1818 if (data->dcb.fInX) {
1819 if (data->dcb.fOutX)
1820 config->xon_xoff = SP_XONXOFF_INOUT;
1822 config->xon_xoff = SP_XONXOFF_IN;
1824 if (data->dcb.fOutX)
1825 config->xon_xoff = SP_XONXOFF_OUT;
1827 config->xon_xoff = SP_XONXOFF_DISABLED;
1832 if (tcgetattr(port->fd, &data->term) < 0)
1833 RETURN_FAIL("tcgetattr() failed");
1835 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1836 RETURN_FAIL("TIOCMGET ioctl failed");
1839 int ret = get_flow(port->fd, data);
1841 if (ret == SP_ERR_FAIL && errno == EINVAL)
1842 data->termiox_supported = 0;
1844 RETURN_CODEVAL(ret);
1846 data->termiox_supported = 1;
1848 data->termiox_supported = 0;
1851 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1852 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1853 config->baudrate = std_baudrates[i].value;
1858 if (i == NUM_STD_BAUDRATES) {
1860 config->baudrate = (int)data->term.c_ispeed;
1861 #elif defined(USE_TERMIOS_SPEED)
1862 TRY(get_baudrate(port->fd, &config->baudrate));
1864 config->baudrate = -1;
1868 switch (data->term.c_cflag & CSIZE) {
1885 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1886 config->parity = SP_PARITY_NONE;
1887 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1888 config->parity = -1;
1890 else if (data->term.c_cflag & CMSPAR)
1891 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1894 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1896 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1898 if (data->term.c_cflag & CRTSCTS) {
1899 config->rts = SP_RTS_FLOW_CONTROL;
1900 config->cts = SP_CTS_FLOW_CONTROL;
1902 if (data->termiox_supported && data->rts_flow)
1903 config->rts = SP_RTS_FLOW_CONTROL;
1905 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1907 config->cts = (data->termiox_supported && data->cts_flow) ?
1908 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1911 if (data->termiox_supported && data->dtr_flow)
1912 config->dtr = SP_DTR_FLOW_CONTROL;
1914 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1916 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1917 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1919 if (data->term.c_iflag & IXOFF) {
1920 if (data->term.c_iflag & IXON)
1921 config->xon_xoff = SP_XONXOFF_INOUT;
1923 config->xon_xoff = SP_XONXOFF_IN;
1925 if (data->term.c_iflag & IXON)
1926 config->xon_xoff = SP_XONXOFF_OUT;
1928 config->xon_xoff = SP_XONXOFF_DISABLED;
1935 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1936 const struct sp_port_config *config)
1940 BAUD_TYPE baud_nonstd;
1944 #ifdef USE_TERMIOS_SPEED
1945 int baud_nonstd = 0;
1948 TRACE("%p, %p, %p", port, data, config);
1950 DEBUG_FMT("Setting configuration for port %s", port->name);
1954 TRY(await_write_completion(port));
1956 if (config->baudrate >= 0) {
1957 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1958 if (config->baudrate == std_baudrates[i].value) {
1959 data->dcb.BaudRate = std_baudrates[i].index;
1964 if (i == NUM_STD_BAUDRATES)
1965 data->dcb.BaudRate = config->baudrate;
1967 /* Allocate write buffer for 50ms of data at baud rate. */
1968 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1969 port->write_buf = realloc(port->write_buf,
1970 port->write_buf_size);
1972 if (!port->write_buf)
1973 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1976 if (config->bits >= 0)
1977 data->dcb.ByteSize = config->bits;
1979 if (config->parity >= 0) {
1980 switch (config->parity) {
1981 case SP_PARITY_NONE:
1982 data->dcb.Parity = NOPARITY;
1985 data->dcb.Parity = ODDPARITY;
1987 case SP_PARITY_EVEN:
1988 data->dcb.Parity = EVENPARITY;
1990 case SP_PARITY_MARK:
1991 data->dcb.Parity = MARKPARITY;
1993 case SP_PARITY_SPACE:
1994 data->dcb.Parity = SPACEPARITY;
1997 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2001 if (config->stopbits >= 0) {
2002 switch (config->stopbits) {
2003 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
2005 data->dcb.StopBits = ONESTOPBIT;
2008 data->dcb.StopBits = TWOSTOPBITS;
2011 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
2015 if (config->rts >= 0) {
2016 switch (config->rts) {
2018 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
2021 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
2023 case SP_RTS_FLOW_CONTROL:
2024 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
2027 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
2031 if (config->cts >= 0) {
2032 switch (config->cts) {
2034 data->dcb.fOutxCtsFlow = FALSE;
2036 case SP_CTS_FLOW_CONTROL:
2037 data->dcb.fOutxCtsFlow = TRUE;
2040 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
2044 if (config->dtr >= 0) {
2045 switch (config->dtr) {
2047 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
2050 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
2052 case SP_DTR_FLOW_CONTROL:
2053 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
2056 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
2060 if (config->dsr >= 0) {
2061 switch (config->dsr) {
2063 data->dcb.fOutxDsrFlow = FALSE;
2065 case SP_DSR_FLOW_CONTROL:
2066 data->dcb.fOutxDsrFlow = TRUE;
2069 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2073 if (config->xon_xoff >= 0) {
2074 switch (config->xon_xoff) {
2075 case SP_XONXOFF_DISABLED:
2076 data->dcb.fInX = FALSE;
2077 data->dcb.fOutX = FALSE;
2080 data->dcb.fInX = TRUE;
2081 data->dcb.fOutX = FALSE;
2083 case SP_XONXOFF_OUT:
2084 data->dcb.fInX = FALSE;
2085 data->dcb.fOutX = TRUE;
2087 case SP_XONXOFF_INOUT:
2088 data->dcb.fInX = TRUE;
2089 data->dcb.fOutX = TRUE;
2092 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2096 if (!SetCommState(port->hdl, &data->dcb))
2097 RETURN_FAIL("SetCommState() failed");
2103 if (config->baudrate >= 0) {
2104 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2105 if (config->baudrate == std_baudrates[i].value) {
2106 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2107 RETURN_FAIL("cfsetospeed() failed");
2109 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2110 RETURN_FAIL("cfsetispeed() failed");
2115 /* Non-standard baud rate */
2116 if (i == NUM_STD_BAUDRATES) {
2118 /* Set "dummy" baud rate. */
2119 if (cfsetspeed(&data->term, B9600) < 0)
2120 RETURN_FAIL("cfsetspeed() failed");
2121 baud_nonstd = config->baudrate;
2122 #elif defined(USE_TERMIOS_SPEED)
2125 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2130 if (config->bits >= 0) {
2131 data->term.c_cflag &= ~CSIZE;
2132 switch (config->bits) {
2134 data->term.c_cflag |= CS8;
2137 data->term.c_cflag |= CS7;
2140 data->term.c_cflag |= CS6;
2143 data->term.c_cflag |= CS5;
2146 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2150 if (config->parity >= 0) {
2151 data->term.c_iflag &= ~IGNPAR;
2152 data->term.c_cflag &= ~(PARENB | PARODD);
2154 data->term.c_cflag &= ~CMSPAR;
2156 switch (config->parity) {
2157 case SP_PARITY_NONE:
2158 data->term.c_iflag |= IGNPAR;
2160 case SP_PARITY_EVEN:
2161 data->term.c_cflag |= PARENB;
2164 data->term.c_cflag |= PARENB | PARODD;
2167 case SP_PARITY_MARK:
2168 data->term.c_cflag |= PARENB | PARODD;
2169 data->term.c_cflag |= CMSPAR;
2171 case SP_PARITY_SPACE:
2172 data->term.c_cflag |= PARENB;
2173 data->term.c_cflag |= CMSPAR;
2176 case SP_PARITY_MARK:
2177 case SP_PARITY_SPACE:
2178 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2181 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2185 if (config->stopbits >= 0) {
2186 data->term.c_cflag &= ~CSTOPB;
2187 switch (config->stopbits) {
2189 data->term.c_cflag &= ~CSTOPB;
2192 data->term.c_cflag |= CSTOPB;
2195 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2199 if (config->rts >= 0 || config->cts >= 0) {
2200 if (data->termiox_supported) {
2201 data->rts_flow = data->cts_flow = 0;
2202 switch (config->rts) {
2205 controlbits = TIOCM_RTS;
2206 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2207 RETURN_FAIL("Setting RTS signal level failed");
2209 case SP_RTS_FLOW_CONTROL:
2215 if (config->cts == SP_CTS_FLOW_CONTROL)
2218 if (data->rts_flow && data->cts_flow)
2219 data->term.c_iflag |= CRTSCTS;
2221 data->term.c_iflag &= ~CRTSCTS;
2223 /* Asymmetric use of RTS/CTS not supported. */
2224 if (data->term.c_iflag & CRTSCTS) {
2225 /* Flow control can only be disabled for both RTS & CTS together. */
2226 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2227 if (config->cts != SP_CTS_IGNORE)
2228 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2230 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2231 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2232 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2235 /* Flow control can only be enabled for both RTS & CTS together. */
2236 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2237 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2238 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2241 if (config->rts >= 0) {
2242 if (config->rts == SP_RTS_FLOW_CONTROL) {
2243 data->term.c_iflag |= CRTSCTS;
2245 controlbits = TIOCM_RTS;
2246 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2248 RETURN_FAIL("Setting RTS signal level failed");
2254 if (config->dtr >= 0 || config->dsr >= 0) {
2255 if (data->termiox_supported) {
2256 data->dtr_flow = data->dsr_flow = 0;
2257 switch (config->dtr) {
2260 controlbits = TIOCM_DTR;
2261 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2262 RETURN_FAIL("Setting DTR signal level failed");
2264 case SP_DTR_FLOW_CONTROL:
2270 if (config->dsr == SP_DSR_FLOW_CONTROL)
2273 /* DTR/DSR flow control not supported. */
2274 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2275 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2277 if (config->dtr >= 0) {
2278 controlbits = TIOCM_DTR;
2279 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2281 RETURN_FAIL("Setting DTR signal level failed");
2286 if (config->xon_xoff >= 0) {
2287 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2288 switch (config->xon_xoff) {
2289 case SP_XONXOFF_DISABLED:
2292 data->term.c_iflag |= IXOFF;
2294 case SP_XONXOFF_OUT:
2295 data->term.c_iflag |= IXON | IXANY;
2297 case SP_XONXOFF_INOUT:
2298 data->term.c_iflag |= IXON | IXOFF | IXANY;
2301 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2305 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2306 RETURN_FAIL("tcsetattr() failed");
2309 if (baud_nonstd != B0) {
2310 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2311 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2313 * Set baud rates in data->term to correct, but incompatible
2314 * with tcsetattr() value, same as delivered by tcgetattr().
2316 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2317 RETURN_FAIL("cfsetspeed() failed");
2319 #elif defined(__linux__)
2320 #ifdef USE_TERMIOS_SPEED
2322 TRY(set_baudrate(port->fd, config->baudrate));
2325 if (data->termiox_supported)
2326 TRY(set_flow(port->fd, data));
2330 #endif /* !_WIN32 */
2335 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2337 struct sp_port_config *config;
2339 TRACE("%p", config_ptr);
2342 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2346 if (!(config = malloc(sizeof(struct sp_port_config))))
2347 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2349 config->baudrate = -1;
2351 config->parity = -1;
2352 config->stopbits = -1;
2358 *config_ptr = config;
2363 SP_API void sp_free_config(struct sp_port_config *config)
2365 TRACE("%p", config);
2368 DEBUG("Null config");
2375 SP_API enum sp_return sp_get_config(struct sp_port *port,
2376 struct sp_port_config *config)
2378 struct port_data data;
2380 TRACE("%p, %p", port, config);
2385 RETURN_ERROR(SP_ERR_ARG, "Null config");
2387 TRY(get_config(port, &data, config));
2392 SP_API enum sp_return sp_set_config(struct sp_port *port,
2393 const struct sp_port_config *config)
2395 struct port_data data;
2396 struct sp_port_config prev_config;
2398 TRACE("%p, %p", port, config);
2403 RETURN_ERROR(SP_ERR_ARG, "Null config");
2405 TRY(get_config(port, &data, &prev_config));
2406 TRY(set_config(port, &data, config));
2411 #define CREATE_ACCESSORS(x, type) \
2412 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2413 struct port_data data; \
2414 struct sp_port_config config; \
2415 TRACE("%p, %d", port, x); \
2416 CHECK_OPEN_PORT(); \
2417 TRY(get_config(port, &data, &config)); \
2419 TRY(set_config(port, &data, &config)); \
2422 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2424 TRACE("%p, %p", config, x); \
2426 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2428 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2432 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2434 TRACE("%p, %d", config, x); \
2436 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2441 CREATE_ACCESSORS(baudrate, int)
2442 CREATE_ACCESSORS(bits, int)
2443 CREATE_ACCESSORS(parity, enum sp_parity)
2444 CREATE_ACCESSORS(stopbits, int)
2445 CREATE_ACCESSORS(rts, enum sp_rts)
2446 CREATE_ACCESSORS(cts, enum sp_cts)
2447 CREATE_ACCESSORS(dtr, enum sp_dtr)
2448 CREATE_ACCESSORS(dsr, enum sp_dsr)
2449 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2451 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2452 enum sp_flowcontrol flowcontrol)
2455 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2457 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2458 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2460 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2461 config->xon_xoff = SP_XONXOFF_INOUT;
2463 config->xon_xoff = SP_XONXOFF_DISABLED;
2465 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2466 config->rts = SP_RTS_FLOW_CONTROL;
2467 config->cts = SP_CTS_FLOW_CONTROL;
2469 if (config->rts == SP_RTS_FLOW_CONTROL)
2470 config->rts = SP_RTS_ON;
2471 config->cts = SP_CTS_IGNORE;
2474 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2475 config->dtr = SP_DTR_FLOW_CONTROL;
2476 config->dsr = SP_DSR_FLOW_CONTROL;
2478 if (config->dtr == SP_DTR_FLOW_CONTROL)
2479 config->dtr = SP_DTR_ON;
2480 config->dsr = SP_DSR_IGNORE;
2486 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2487 enum sp_flowcontrol flowcontrol)
2489 struct port_data data;
2490 struct sp_port_config config;
2492 TRACE("%p, %d", port, flowcontrol);
2496 TRY(get_config(port, &data, &config));
2498 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2500 TRY(set_config(port, &data, &config));
2505 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2506 enum sp_signal *signals)
2508 TRACE("%p, %p", port, signals);
2513 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2515 DEBUG_FMT("Getting control signals for port %s", port->name);
2520 if (GetCommModemStatus(port->hdl, &bits) == 0)
2521 RETURN_FAIL("GetCommModemStatus() failed");
2522 if (bits & MS_CTS_ON)
2523 *signals |= SP_SIG_CTS;
2524 if (bits & MS_DSR_ON)
2525 *signals |= SP_SIG_DSR;
2526 if (bits & MS_RLSD_ON)
2527 *signals |= SP_SIG_DCD;
2528 if (bits & MS_RING_ON)
2529 *signals |= SP_SIG_RI;
2532 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2533 RETURN_FAIL("TIOCMGET ioctl failed");
2534 if (bits & TIOCM_CTS)
2535 *signals |= SP_SIG_CTS;
2536 if (bits & TIOCM_DSR)
2537 *signals |= SP_SIG_DSR;
2538 if (bits & TIOCM_CAR)
2539 *signals |= SP_SIG_DCD;
2540 if (bits & TIOCM_RNG)
2541 *signals |= SP_SIG_RI;
2546 SP_API enum sp_return sp_start_break(struct sp_port *port)
2552 if (SetCommBreak(port->hdl) == 0)
2553 RETURN_FAIL("SetCommBreak() failed");
2555 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2556 RETURN_FAIL("TIOCSBRK ioctl failed");
2562 SP_API enum sp_return sp_end_break(struct sp_port *port)
2568 if (ClearCommBreak(port->hdl) == 0)
2569 RETURN_FAIL("ClearCommBreak() failed");
2571 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2572 RETURN_FAIL("TIOCCBRK ioctl failed");
2578 SP_API int sp_last_error_code(void)
2582 RETURN_INT(GetLastError());
2588 SP_API char *sp_last_error_message(void)
2594 DWORD error = GetLastError();
2596 DWORD length = FormatMessage(
2597 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2598 FORMAT_MESSAGE_FROM_SYSTEM |
2599 FORMAT_MESSAGE_IGNORE_INSERTS,
2602 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2606 if (length >= 2 && message[length - 2] == '\r')
2607 message[length - 2] = '\0';
2609 RETURN_STRING(message);
2611 RETURN_STRING(strerror(errno));
2615 SP_API void sp_free_error_message(char *message)
2617 TRACE("%s", message);
2628 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2630 TRACE("%p", handler);
2632 sp_debug_handler = handler;
2637 SP_API void sp_default_debug_handler(const char *format, ...)
2640 va_start(args, format);
2641 if (getenv("LIBSERIALPORT_DEBUG")) {
2642 fputs("sp: ", stderr);
2643 vfprintf(stderr, format, args);
2648 SP_API int sp_get_major_package_version(void)
2650 return SP_PACKAGE_VERSION_MAJOR;
2653 SP_API int sp_get_minor_package_version(void)
2655 return SP_PACKAGE_VERSION_MINOR;
2658 SP_API int sp_get_micro_package_version(void)
2660 return SP_PACKAGE_VERSION_MICRO;
2663 SP_API const char *sp_get_package_version_string(void)
2665 return SP_PACKAGE_VERSION_STRING;
2668 SP_API int sp_get_current_lib_version(void)
2670 return SP_LIB_VERSION_CURRENT;
2673 SP_API int sp_get_revision_lib_version(void)
2675 return SP_LIB_VERSION_REVISION;
2678 SP_API int sp_get_age_lib_version(void)
2680 return SP_LIB_VERSION_AGE;
2683 SP_API const char *sp_get_lib_version_string(void)
2685 return SP_LIB_VERSION_STRING;