2 * This file is part of the libserialport project.
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2015 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2013-2015 Martin Ling <martin-libserialport@earth.li>
7 * Copyright (C) 2013 Matthias Heidbrink <m-sigrok@heidbrink.biz>
8 * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation, either version 3 of the
13 * License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "libserialport.h"
26 #include "libserialport_internal.h"
28 static const struct std_baudrate std_baudrates[] = {
31 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
32 * have documented CBR_* macros.
34 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
35 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
36 BAUD(115200), BAUD(128000), BAUD(256000),
38 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
39 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
40 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
42 #if !defined(__APPLE__) && !defined(__OpenBSD__)
48 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
50 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
52 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
53 struct sp_port_config *config);
55 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
56 const struct sp_port_config *config);
58 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
61 #ifndef NO_PORT_METADATA
66 TRACE("%s, %p", portname, port_ptr);
69 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
74 RETURN_ERROR(SP_ERR_ARG, "Null port name");
76 DEBUG_FMT("Building structure for port %s", portname);
78 #if !defined(_WIN32) && defined(HAVE_REALPATH)
80 * get_port_details() below tries to be too smart and figure out
81 * some transport properties from the port name which breaks with
82 * symlinks. Therefore we canonicalize the portname first.
84 char pathbuf[PATH_MAX + 1];
85 char *res = realpath(portname, pathbuf);
87 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
92 if (!(port = malloc(sizeof(struct sp_port))))
93 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
95 len = strlen(portname) + 1;
97 if (!(port->name = malloc(len))) {
99 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
102 memcpy(port->name, portname, len);
105 port->usb_path = NULL;
106 port->hdl = INVALID_HANDLE_VALUE;
111 port->description = NULL;
112 port->transport = SP_TRANSPORT_NATIVE;
114 port->usb_address = -1;
117 port->usb_manufacturer = NULL;
118 port->usb_product = NULL;
119 port->usb_serial = NULL;
120 port->bluetooth_address = NULL;
122 #ifndef NO_PORT_METADATA
123 if ((ret = get_port_details(port)) != SP_OK) {
134 SP_API char *sp_get_port_name(const struct sp_port *port)
141 RETURN_STRING(port->name);
144 SP_API char *sp_get_port_description(const struct sp_port *port)
148 if (!port || !port->description)
151 RETURN_STRING(port->description);
154 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
159 RETURN_ERROR(SP_ERR_ARG, "Null port");
161 RETURN_INT(port->transport);
164 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
165 int *usb_bus,int *usb_address)
170 RETURN_ERROR(SP_ERR_ARG, "Null port");
171 if (port->transport != SP_TRANSPORT_USB)
172 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
173 if (port->usb_bus < 0 || port->usb_address < 0)
174 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
177 *usb_bus = port->usb_bus;
179 *usb_address = port->usb_address;
184 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
185 int *usb_vid, int *usb_pid)
190 RETURN_ERROR(SP_ERR_ARG, "Null port");
191 if (port->transport != SP_TRANSPORT_USB)
192 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
193 if (port->usb_vid < 0 || port->usb_pid < 0)
194 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
197 *usb_vid = port->usb_vid;
199 *usb_pid = port->usb_pid;
204 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
208 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
211 RETURN_STRING(port->usb_manufacturer);
214 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
218 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
221 RETURN_STRING(port->usb_product);
224 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
228 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
231 RETURN_STRING(port->usb_serial);
234 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
238 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
239 || !port->bluetooth_address)
242 RETURN_STRING(port->bluetooth_address);
245 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
248 TRACE("%p, %p", port, result_ptr);
251 RETURN_ERROR(SP_ERR_ARG, "Null port");
253 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
256 HANDLE *handle_ptr = result_ptr;
257 *handle_ptr = port->hdl;
259 int *fd_ptr = result_ptr;
266 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
267 struct sp_port **copy_ptr)
269 TRACE("%p, %p", port, copy_ptr);
272 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
277 RETURN_ERROR(SP_ERR_ARG, "Null port");
280 RETURN_ERROR(SP_ERR_ARG, "Null port name");
282 DEBUG("Copying port structure");
284 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
287 SP_API void sp_free_port(struct sp_port *port)
296 DEBUG("Freeing port structure");
300 if (port->description)
301 free(port->description);
302 if (port->usb_manufacturer)
303 free(port->usb_manufacturer);
304 if (port->usb_product)
305 free(port->usb_product);
306 if (port->usb_serial)
307 free(port->usb_serial);
308 if (port->bluetooth_address)
309 free(port->bluetooth_address);
312 free(port->usb_path);
320 SP_PRIV struct sp_port **list_append(struct sp_port **list,
321 const char *portname)
326 for (count = 0; list[count]; count++);
327 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
330 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
332 list[count + 1] = NULL;
336 sp_free_port_list(list);
340 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
342 #ifndef NO_ENUMERATION
343 struct sp_port **list;
347 TRACE("%p", list_ptr);
350 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
354 #ifdef NO_ENUMERATION
355 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
357 DEBUG("Enumerating ports");
359 if (!(list = malloc(sizeof(struct sp_port *))))
360 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
364 ret = list_ports(&list);
369 sp_free_port_list(list);
377 SP_API void sp_free_port_list(struct sp_port **list)
388 DEBUG("Freeing port list");
390 for (i = 0; list[i]; i++)
391 sp_free_port(list[i]);
397 #define CHECK_PORT() do { \
399 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
401 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
404 #define CHECK_PORT_HANDLE() do { \
405 if (port->hdl == INVALID_HANDLE_VALUE) \
406 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
409 #define CHECK_PORT_HANDLE() do { \
411 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
414 #define CHECK_OPEN_PORT() do { \
416 CHECK_PORT_HANDLE(); \
420 /** To be called after port receive buffer is emptied. */
421 static enum sp_return restart_wait(struct sp_port *port)
425 if (port->wait_running) {
426 /* Check status of running wait operation. */
427 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
428 &wait_result, FALSE)) {
429 DEBUG("Previous wait completed");
430 port->wait_running = FALSE;
431 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
432 DEBUG("Previous wait still running");
435 RETURN_FAIL("GetOverlappedResult() failed");
439 if (!port->wait_running) {
440 /* Start new wait operation. */
441 if (WaitCommEvent(port->hdl, &port->events,
443 DEBUG("New wait returned, events already pending");
444 } else if (GetLastError() == ERROR_IO_PENDING) {
445 DEBUG("New wait running in background");
446 port->wait_running = TRUE;
448 RETURN_FAIL("WaitCommEvent() failed");
456 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
458 struct port_data data;
459 struct sp_port_config config;
462 TRACE("%p, 0x%x", port, flags);
466 if (flags > SP_MODE_READ_WRITE)
467 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
469 DEBUG_FMT("Opening port %s", port->name);
472 DWORD desired_access = 0, flags_and_attributes = 0, errors;
473 char *escaped_port_name;
476 /* Prefix port name with '\\.\' to work with ports above COM9. */
477 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
478 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
479 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
481 /* Map 'flags' to the OS-specific settings. */
482 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
483 if (flags & SP_MODE_READ)
484 desired_access |= GENERIC_READ;
485 if (flags & SP_MODE_WRITE)
486 desired_access |= GENERIC_WRITE;
488 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
489 OPEN_EXISTING, flags_and_attributes, 0);
491 free(escaped_port_name);
493 if (port->hdl == INVALID_HANDLE_VALUE)
494 RETURN_FAIL("Port CreateFile() failed");
496 /* All timeouts initially disabled. */
497 port->timeouts.ReadIntervalTimeout = 0;
498 port->timeouts.ReadTotalTimeoutMultiplier = 0;
499 port->timeouts.ReadTotalTimeoutConstant = 0;
500 port->timeouts.WriteTotalTimeoutMultiplier = 0;
501 port->timeouts.WriteTotalTimeoutConstant = 0;
503 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
505 RETURN_FAIL("SetCommTimeouts() failed");
508 /* Prepare OVERLAPPED structures. */
509 #define INIT_OVERLAPPED(ovl) do { \
510 memset(&port->ovl, 0, sizeof(port->ovl)); \
511 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
512 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
513 == INVALID_HANDLE_VALUE) { \
515 RETURN_FAIL(#ovl "CreateEvent() failed"); \
519 INIT_OVERLAPPED(read_ovl);
520 INIT_OVERLAPPED(write_ovl);
521 INIT_OVERLAPPED(wait_ovl);
523 /* Set event mask for RX and error events. */
524 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
526 RETURN_FAIL("SetCommMask() failed");
529 port->writing = FALSE;
530 port->wait_running = FALSE;
532 ret = restart_wait(port);
539 int flags_local = O_NONBLOCK | O_NOCTTY;
541 /* Map 'flags' to the OS-specific settings. */
542 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
543 flags_local |= O_RDWR;
544 else if (flags & SP_MODE_READ)
545 flags_local |= O_RDONLY;
546 else if (flags & SP_MODE_WRITE)
547 flags_local |= O_WRONLY;
549 if ((port->fd = open(port->name, flags_local)) < 0)
550 RETURN_FAIL("open() failed");
553 ret = get_config(port, &data, &config);
560 /* Set sane port settings. */
562 data.dcb.fBinary = TRUE;
563 data.dcb.fDsrSensitivity = FALSE;
564 data.dcb.fErrorChar = FALSE;
565 data.dcb.fNull = FALSE;
566 data.dcb.fAbortOnError = FALSE;
568 /* Turn off all fancy termios tricks, give us a raw channel. */
569 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
571 data.term.c_iflag &= ~IUCLC;
573 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
575 data.term.c_oflag &= ~OLCUC;
578 data.term.c_oflag &= ~NLDLY;
581 data.term.c_oflag &= ~CRDLY;
584 data.term.c_oflag &= ~TABDLY;
587 data.term.c_oflag &= ~BSDLY;
590 data.term.c_oflag &= ~VTDLY;
593 data.term.c_oflag &= ~FFDLY;
596 data.term.c_oflag &= ~OFILL;
598 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
599 data.term.c_cc[VMIN] = 0;
600 data.term.c_cc[VTIME] = 0;
602 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
603 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
607 if (ClearCommError(port->hdl, &errors, &status) == 0)
608 RETURN_FAIL("ClearCommError() failed");
611 ret = set_config(port, &data, &config);
621 SP_API enum sp_return sp_close(struct sp_port *port)
627 DEBUG_FMT("Closing port %s", port->name);
630 /* Returns non-zero upon success, 0 upon failure. */
631 if (CloseHandle(port->hdl) == 0)
632 RETURN_FAIL("Port CloseHandle() failed");
633 port->hdl = INVALID_HANDLE_VALUE;
635 /* Close event handles for overlapped structures. */
636 #define CLOSE_OVERLAPPED(ovl) do { \
637 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
638 CloseHandle(port->ovl.hEvent) == 0) \
639 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
641 CLOSE_OVERLAPPED(read_ovl);
642 CLOSE_OVERLAPPED(write_ovl);
643 CLOSE_OVERLAPPED(wait_ovl);
646 /* Returns 0 upon success, -1 upon failure. */
647 if (close(port->fd) == -1)
648 RETURN_FAIL("close() failed");
655 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
657 TRACE("%p, 0x%x", port, buffers);
661 if (buffers > SP_BUF_BOTH)
662 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
664 const char *buffer_names[] = {"no", "input", "output", "both"};
666 DEBUG_FMT("Flushing %s buffers on port %s",
667 buffer_names[buffers], port->name);
671 if (buffers & SP_BUF_INPUT)
672 flags |= PURGE_RXCLEAR;
673 if (buffers & SP_BUF_OUTPUT)
674 flags |= PURGE_TXCLEAR;
676 /* Returns non-zero upon success, 0 upon failure. */
677 if (PurgeComm(port->hdl, flags) == 0)
678 RETURN_FAIL("PurgeComm() failed");
680 if (buffers & SP_BUF_INPUT)
681 TRY(restart_wait(port));
684 if (buffers == SP_BUF_BOTH)
686 else if (buffers == SP_BUF_INPUT)
688 else if (buffers == SP_BUF_OUTPUT)
691 /* Returns 0 upon success, -1 upon failure. */
692 if (tcflush(port->fd, flags) < 0)
693 RETURN_FAIL("tcflush() failed");
698 SP_API enum sp_return sp_drain(struct sp_port *port)
704 DEBUG_FMT("Draining port %s", port->name);
707 /* Returns non-zero upon success, 0 upon failure. */
708 if (FlushFileBuffers(port->hdl) == 0)
709 RETURN_FAIL("FlushFileBuffers() failed");
716 result = ioctl(port->fd, TCSBRK, &arg);
718 result = tcdrain(port->fd);
721 if (errno == EINTR) {
722 DEBUG("tcdrain() was interrupted");
725 RETURN_FAIL("tcdrain() failed");
734 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
735 size_t count, unsigned int timeout_ms)
737 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
742 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
745 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
746 count, port->name, timeout_ms);
748 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
755 DWORD bytes_written = 0;
758 /* Wait for previous non-blocking write to complete, if any. */
760 DEBUG("Waiting for previous write to complete");
761 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
764 RETURN_FAIL("Previous write failed to complete");
765 DEBUG("Previous write completed");
769 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
770 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
771 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
772 RETURN_FAIL("SetCommTimeouts() failed");
776 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
777 DEBUG("Write completed immediately");
779 } else if (GetLastError() == ERROR_IO_PENDING) {
780 DEBUG("Waiting for write to complete");
781 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
782 if (GetLastError() == ERROR_SEM_TIMEOUT) {
783 DEBUG("Write timed out");
786 RETURN_FAIL("GetOverlappedResult() failed");
789 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
790 RETURN_INT(bytes_written);
792 RETURN_FAIL("WriteFile() failed");
795 size_t bytes_written = 0;
796 unsigned char *ptr = (unsigned char *) buf;
797 struct timeval start, delta, now, end = {0, 0};
803 /* Get time at start of operation. */
804 gettimeofday(&start, NULL);
805 /* Define duration of timeout. */
806 delta.tv_sec = timeout_ms / 1000;
807 delta.tv_usec = (timeout_ms % 1000) * 1000;
808 /* Calculate time at which we should give up. */
809 timeradd(&start, &delta, &end);
813 FD_SET(port->fd, &fds);
815 /* Loop until we have written the requested number of bytes. */
816 while (bytes_written < count) {
818 * Check timeout only if we have run select() at least once,
819 * to avoid any issues if a short timeout is reached before
820 * select() is even run.
822 if (timeout_ms && started) {
823 gettimeofday(&now, NULL);
824 if (timercmp(&now, &end, >))
825 /* Timeout has expired. */
827 timersub(&end, &now, &delta);
829 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
832 if (errno == EINTR) {
833 DEBUG("select() call was interrupted, repeating");
836 RETURN_FAIL("select() failed");
838 } else if (result == 0) {
839 /* Timeout has expired. */
844 result = write(port->fd, ptr, count - bytes_written);
848 /* This shouldn't happen because we did a select() first, but handle anyway. */
851 /* This is an actual failure. */
852 RETURN_FAIL("write() failed");
855 bytes_written += result;
859 if (bytes_written < count)
860 DEBUG("Write timed out");
862 RETURN_INT(bytes_written);
866 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
867 const void *buf, size_t count)
869 TRACE("%p, %p, %d", port, buf, count);
874 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
876 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
883 BYTE *ptr = (BYTE *) buf;
885 /* Check whether previous write is complete. */
887 if (HasOverlappedIoCompleted(&port->write_ovl)) {
888 DEBUG("Previous write completed");
891 DEBUG("Previous write not complete");
892 /* Can't take a new write until the previous one finishes. */
898 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
899 port->timeouts.WriteTotalTimeoutConstant = 0;
900 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
901 RETURN_FAIL("SetCommTimeouts() failed");
905 * Keep writing data until the OS has to actually start an async IO
906 * for it. At that point we know the buffer is full.
908 while (written < count) {
909 /* Copy first byte of user buffer. */
910 port->pending_byte = *ptr++;
912 /* Start asynchronous write. */
913 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
914 if (GetLastError() == ERROR_IO_PENDING) {
915 if (HasOverlappedIoCompleted(&port->write_ovl)) {
916 DEBUG("Asynchronous write completed immediately");
921 DEBUG("Asynchronous write running");
923 RETURN_INT(++written);
926 /* Actual failure of some kind. */
927 RETURN_FAIL("WriteFile() failed");
930 DEBUG("Single byte written immediately");
935 DEBUG("All bytes written immediately");
939 /* Returns the number of bytes written, or -1 upon failure. */
940 ssize_t written = write(port->fd, buf, count);
943 RETURN_FAIL("write() failed");
950 /* Restart wait operation if buffer was emptied. */
951 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
959 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
960 RETURN_FAIL("ClearCommError() failed");
962 if (comstat.cbInQue == 0)
963 TRY(restart_wait(port));
969 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
970 size_t count, unsigned int timeout_ms)
972 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
977 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
980 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
981 count, port->name, timeout_ms);
983 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
990 DWORD bytes_read = 0;
993 if (port->timeouts.ReadIntervalTimeout != 0 ||
994 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
995 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
996 port->timeouts.ReadIntervalTimeout = 0;
997 port->timeouts.ReadTotalTimeoutMultiplier = 0;
998 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
999 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1000 RETURN_FAIL("SetCommTimeouts() failed");
1004 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1005 DEBUG("Read completed immediately");
1007 } else if (GetLastError() == ERROR_IO_PENDING) {
1008 DEBUG("Waiting for read to complete");
1009 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1010 RETURN_FAIL("GetOverlappedResult() failed");
1011 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1013 RETURN_FAIL("ReadFile() failed");
1016 TRY(restart_wait_if_needed(port, bytes_read));
1018 RETURN_INT(bytes_read);
1021 size_t bytes_read = 0;
1022 unsigned char *ptr = (unsigned char *) buf;
1023 struct timeval start, delta, now, end = {0, 0};
1029 /* Get time at start of operation. */
1030 gettimeofday(&start, NULL);
1031 /* Define duration of timeout. */
1032 delta.tv_sec = timeout_ms / 1000;
1033 delta.tv_usec = (timeout_ms % 1000) * 1000;
1034 /* Calculate time at which we should give up. */
1035 timeradd(&start, &delta, &end);
1039 FD_SET(port->fd, &fds);
1041 /* Loop until we have the requested number of bytes. */
1042 while (bytes_read < count) {
1044 * Check timeout only if we have run select() at least once,
1045 * to avoid any issues if a short timeout is reached before
1046 * select() is even run.
1048 if (timeout_ms && started) {
1049 gettimeofday(&now, NULL);
1050 if (timercmp(&now, &end, >))
1051 /* Timeout has expired. */
1053 timersub(&end, &now, &delta);
1055 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1058 if (errno == EINTR) {
1059 DEBUG("select() call was interrupted, repeating");
1062 RETURN_FAIL("select() failed");
1064 } else if (result == 0) {
1065 /* Timeout has expired. */
1070 result = read(port->fd, ptr, count - bytes_read);
1073 if (errno == EAGAIN)
1075 * This shouldn't happen because we did a
1076 * select() first, but handle anyway.
1080 /* This is an actual failure. */
1081 RETURN_FAIL("read() failed");
1084 bytes_read += result;
1088 if (bytes_read < count)
1089 DEBUG("Read timed out");
1091 RETURN_INT(bytes_read);
1095 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1096 size_t count, unsigned int timeout_ms)
1098 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1103 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1106 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1109 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1110 count, port->name, timeout_ms);
1112 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1116 DWORD bytes_read = 0;
1118 /* If timeout_ms == 0, set maximum timeout. */
1119 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1122 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1123 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1124 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1125 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1126 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1127 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1128 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1129 RETURN_FAIL("SetCommTimeouts() failed");
1132 /* Loop until we have at least one byte, or timeout is reached. */
1133 while (bytes_read == 0) {
1135 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1136 DEBUG("Read completed immediately");
1137 } else if (GetLastError() == ERROR_IO_PENDING) {
1138 DEBUG("Waiting for read to complete");
1139 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1140 RETURN_FAIL("GetOverlappedResult() failed");
1141 if (bytes_read > 0) {
1142 DEBUG("Read completed");
1143 } else if (timeout_ms > 0) {
1144 DEBUG("Read timed out");
1147 DEBUG("Restarting read");
1150 RETURN_FAIL("ReadFile() failed");
1154 TRY(restart_wait_if_needed(port, bytes_read));
1156 RETURN_INT(bytes_read);
1159 size_t bytes_read = 0;
1160 struct timeval start, delta, now, end = {0, 0};
1166 /* Get time at start of operation. */
1167 gettimeofday(&start, NULL);
1168 /* Define duration of timeout. */
1169 delta.tv_sec = timeout_ms / 1000;
1170 delta.tv_usec = (timeout_ms % 1000) * 1000;
1171 /* Calculate time at which we should give up. */
1172 timeradd(&start, &delta, &end);
1176 FD_SET(port->fd, &fds);
1178 /* Loop until we have at least one byte, or timeout is reached. */
1179 while (bytes_read == 0) {
1181 * Check timeout only if we have run select() at least once,
1182 * to avoid any issues if a short timeout is reached before
1183 * select() is even run.
1185 if (timeout_ms && started) {
1186 gettimeofday(&now, NULL);
1187 if (timercmp(&now, &end, >))
1188 /* Timeout has expired. */
1190 timersub(&end, &now, &delta);
1192 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1195 if (errno == EINTR) {
1196 DEBUG("select() call was interrupted, repeating");
1199 RETURN_FAIL("select() failed");
1201 } else if (result == 0) {
1202 /* Timeout has expired. */
1207 result = read(port->fd, buf, count);
1210 if (errno == EAGAIN)
1211 /* This shouldn't happen because we did a select() first, but handle anyway. */
1214 /* This is an actual failure. */
1215 RETURN_FAIL("read() failed");
1218 bytes_read = result;
1221 if (bytes_read == 0)
1222 DEBUG("Read timed out");
1224 RETURN_INT(bytes_read);
1228 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1231 TRACE("%p, %p, %d", port, buf, count);
1236 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1238 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1244 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1245 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1246 port->timeouts.ReadTotalTimeoutConstant != 0) {
1247 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1248 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1249 port->timeouts.ReadTotalTimeoutConstant = 0;
1250 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1251 RETURN_FAIL("SetCommTimeouts() failed");
1255 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1256 if (GetLastError() != ERROR_IO_PENDING)
1257 RETURN_FAIL("ReadFile() failed");
1259 /* Get number of bytes read. */
1260 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1261 RETURN_FAIL("GetOverlappedResult() failed");
1263 TRY(restart_wait_if_needed(port, bytes_read));
1265 RETURN_INT(bytes_read);
1269 /* Returns the number of bytes read, or -1 upon failure. */
1270 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1271 if (errno == EAGAIN)
1272 /* No bytes available. */
1275 /* This is an actual failure. */
1276 RETURN_FAIL("read() failed");
1278 RETURN_INT(bytes_read);
1282 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1288 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1294 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1295 RETURN_FAIL("ClearCommError() failed");
1296 RETURN_INT(comstat.cbInQue);
1299 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1300 RETURN_FAIL("TIOCINQ ioctl failed");
1301 RETURN_INT(bytes_waiting);
1305 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1311 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1317 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1318 RETURN_FAIL("ClearCommError() failed");
1319 RETURN_INT(comstat.cbOutQue);
1322 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1323 RETURN_FAIL("TIOCOUTQ ioctl failed");
1324 RETURN_INT(bytes_waiting);
1328 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1330 struct sp_event_set *result;
1332 TRACE("%p", result_ptr);
1335 RETURN_ERROR(SP_ERR_ARG, "Null result");
1339 if (!(result = malloc(sizeof(struct sp_event_set))))
1340 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1342 memset(result, 0, sizeof(struct sp_event_set));
1344 *result_ptr = result;
1349 static enum sp_return add_handle(struct sp_event_set *event_set,
1350 event_handle handle, enum sp_event mask)
1353 enum sp_event *new_masks;
1355 TRACE("%p, %d, %d", event_set, handle, mask);
1357 if (!(new_handles = realloc(event_set->handles,
1358 sizeof(event_handle) * (event_set->count + 1))))
1359 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1361 event_set->handles = new_handles;
1363 if (!(new_masks = realloc(event_set->masks,
1364 sizeof(enum sp_event) * (event_set->count + 1))))
1365 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1367 event_set->masks = new_masks;
1369 ((event_handle *) event_set->handles)[event_set->count] = handle;
1370 event_set->masks[event_set->count] = mask;
1377 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1378 const struct sp_port *port, enum sp_event mask)
1380 TRACE("%p, %p, %d", event_set, port, mask);
1383 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1386 RETURN_ERROR(SP_ERR_ARG, "Null port");
1388 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1389 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1395 enum sp_event handle_mask;
1396 if ((handle_mask = mask & SP_EVENT_TX_READY))
1397 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1398 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1399 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1401 TRY(add_handle(event_set, port->fd, mask));
1407 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1409 TRACE("%p", event_set);
1412 DEBUG("Null event set");
1416 DEBUG("Freeing event set");
1418 if (event_set->handles)
1419 free(event_set->handles);
1420 if (event_set->masks)
1421 free(event_set->masks);
1428 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1429 unsigned int timeout_ms)
1431 TRACE("%p, %d", event_set, timeout_ms);
1434 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1437 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1438 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1439 RETURN_FAIL("WaitForMultipleObjects() failed");
1443 struct timeval start, delta, now, end = {0, 0};
1444 const struct timeval max_delta = {
1445 (INT_MAX / 1000), (INT_MAX % 1000) * 1000};
1446 int started = 0, timeout_overflow = 0;
1447 int result, timeout_remaining_ms;
1448 struct pollfd *pollfds;
1451 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1452 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1454 for (i = 0; i < event_set->count; i++) {
1455 pollfds[i].fd = ((int *) event_set->handles)[i];
1456 pollfds[i].events = 0;
1457 pollfds[i].revents = 0;
1458 if (event_set->masks[i] & SP_EVENT_RX_READY)
1459 pollfds[i].events |= POLLIN;
1460 if (event_set->masks[i] & SP_EVENT_TX_READY)
1461 pollfds[i].events |= POLLOUT;
1462 if (event_set->masks[i] & SP_EVENT_ERROR)
1463 pollfds[i].events |= POLLERR;
1467 /* Get time at start of operation. */
1468 gettimeofday(&start, NULL);
1469 /* Define duration of timeout. */
1470 delta.tv_sec = timeout_ms / 1000;
1471 delta.tv_usec = (timeout_ms % 1000) * 1000;
1472 /* Calculate time at which we should give up. */
1473 timeradd(&start, &delta, &end);
1476 /* Loop until an event occurs. */
1479 * Check timeout only if we have run poll() at least once,
1480 * to avoid any issues if a short timeout is reached before
1481 * poll() is even run.
1484 timeout_remaining_ms = -1;
1485 } else if (!started) {
1486 timeout_overflow = (timeout_ms > INT_MAX);
1487 timeout_remaining_ms = timeout_overflow ? INT_MAX : timeout_ms;
1489 gettimeofday(&now, NULL);
1490 if (timercmp(&now, &end, >)) {
1491 DEBUG("Wait timed out");
1494 timersub(&end, &now, &delta);
1495 if ((timeout_overflow = timercmp(&delta, &max_delta, >)))
1497 timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1500 result = poll(pollfds, event_set->count, timeout_remaining_ms);
1504 if (errno == EINTR) {
1505 DEBUG("poll() call was interrupted, repeating");
1509 RETURN_FAIL("poll() failed");
1511 } else if (result == 0) {
1512 DEBUG("poll() timed out");
1513 if (!timeout_overflow)
1516 DEBUG("poll() completed");
1526 #ifdef USE_TERMIOS_SPEED
1527 static enum sp_return get_baudrate(int fd, int *baudrate)
1531 TRACE("%d, %p", fd, baudrate);
1533 DEBUG("Getting baud rate");
1535 if (!(data = malloc(get_termios_size())))
1536 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1538 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1540 RETURN_FAIL("Getting termios failed");
1543 *baudrate = get_termios_speed(data);
1550 static enum sp_return set_baudrate(int fd, int baudrate)
1554 TRACE("%d, %d", fd, baudrate);
1556 DEBUG("Getting baud rate");
1558 if (!(data = malloc(get_termios_size())))
1559 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1561 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1563 RETURN_FAIL("Getting termios failed");
1566 DEBUG("Setting baud rate");
1568 set_termios_speed(data, baudrate);
1570 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1572 RETURN_FAIL("Setting termios failed");
1579 #endif /* USE_TERMIOS_SPEED */
1582 static enum sp_return get_flow(int fd, struct port_data *data)
1586 TRACE("%d, %p", fd, data);
1588 DEBUG("Getting advanced flow control");
1590 if (!(termx = malloc(get_termiox_size())))
1591 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1593 if (ioctl(fd, TCGETX, termx) < 0) {
1595 RETURN_FAIL("Getting termiox failed");
1598 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1599 &data->dtr_flow, &data->dsr_flow);
1606 static enum sp_return set_flow(int fd, struct port_data *data)
1610 TRACE("%d, %p", fd, data);
1612 DEBUG("Getting advanced flow control");
1614 if (!(termx = malloc(get_termiox_size())))
1615 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1617 if (ioctl(fd, TCGETX, termx) < 0) {
1619 RETURN_FAIL("Getting termiox failed");
1622 DEBUG("Setting advanced flow control");
1624 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1625 data->dtr_flow, data->dsr_flow);
1627 if (ioctl(fd, TCSETX, termx) < 0) {
1629 RETURN_FAIL("Setting termiox failed");
1636 #endif /* USE_TERMIOX */
1638 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1639 struct sp_port_config *config)
1643 TRACE("%p, %p, %p", port, data, config);
1645 DEBUG_FMT("Getting configuration for port %s", port->name);
1648 if (!GetCommState(port->hdl, &data->dcb))
1649 RETURN_FAIL("GetCommState() failed");
1651 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1652 if (data->dcb.BaudRate == std_baudrates[i].index) {
1653 config->baudrate = std_baudrates[i].value;
1658 if (i == NUM_STD_BAUDRATES)
1659 /* BaudRate field can be either an index or a custom baud rate. */
1660 config->baudrate = data->dcb.BaudRate;
1662 config->bits = data->dcb.ByteSize;
1664 if (data->dcb.fParity)
1665 switch (data->dcb.Parity) {
1667 config->parity = SP_PARITY_NONE;
1670 config->parity = SP_PARITY_ODD;
1673 config->parity = SP_PARITY_EVEN;
1676 config->parity = SP_PARITY_MARK;
1679 config->parity = SP_PARITY_SPACE;
1682 config->parity = -1;
1685 config->parity = SP_PARITY_NONE;
1687 switch (data->dcb.StopBits) {
1689 config->stopbits = 1;
1692 config->stopbits = 2;
1695 config->stopbits = -1;
1698 switch (data->dcb.fRtsControl) {
1699 case RTS_CONTROL_DISABLE:
1700 config->rts = SP_RTS_OFF;
1702 case RTS_CONTROL_ENABLE:
1703 config->rts = SP_RTS_ON;
1705 case RTS_CONTROL_HANDSHAKE:
1706 config->rts = SP_RTS_FLOW_CONTROL;
1712 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1714 switch (data->dcb.fDtrControl) {
1715 case DTR_CONTROL_DISABLE:
1716 config->dtr = SP_DTR_OFF;
1718 case DTR_CONTROL_ENABLE:
1719 config->dtr = SP_DTR_ON;
1721 case DTR_CONTROL_HANDSHAKE:
1722 config->dtr = SP_DTR_FLOW_CONTROL;
1728 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1730 if (data->dcb.fInX) {
1731 if (data->dcb.fOutX)
1732 config->xon_xoff = SP_XONXOFF_INOUT;
1734 config->xon_xoff = SP_XONXOFF_IN;
1736 if (data->dcb.fOutX)
1737 config->xon_xoff = SP_XONXOFF_OUT;
1739 config->xon_xoff = SP_XONXOFF_DISABLED;
1744 if (tcgetattr(port->fd, &data->term) < 0)
1745 RETURN_FAIL("tcgetattr() failed");
1747 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1748 RETURN_FAIL("TIOCMGET ioctl failed");
1751 int ret = get_flow(port->fd, data);
1753 if (ret == SP_ERR_FAIL && errno == EINVAL)
1754 data->termiox_supported = 0;
1756 RETURN_CODEVAL(ret);
1758 data->termiox_supported = 1;
1760 data->termiox_supported = 0;
1763 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1764 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1765 config->baudrate = std_baudrates[i].value;
1770 if (i == NUM_STD_BAUDRATES) {
1772 config->baudrate = (int)data->term.c_ispeed;
1773 #elif defined(USE_TERMIOS_SPEED)
1774 TRY(get_baudrate(port->fd, &config->baudrate));
1776 config->baudrate = -1;
1780 switch (data->term.c_cflag & CSIZE) {
1797 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1798 config->parity = SP_PARITY_NONE;
1799 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1800 config->parity = -1;
1802 else if (data->term.c_cflag & CMSPAR)
1803 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1806 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1808 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1810 if (data->term.c_cflag & CRTSCTS) {
1811 config->rts = SP_RTS_FLOW_CONTROL;
1812 config->cts = SP_CTS_FLOW_CONTROL;
1814 if (data->termiox_supported && data->rts_flow)
1815 config->rts = SP_RTS_FLOW_CONTROL;
1817 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1819 config->cts = (data->termiox_supported && data->cts_flow) ?
1820 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1823 if (data->termiox_supported && data->dtr_flow)
1824 config->dtr = SP_DTR_FLOW_CONTROL;
1826 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1828 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1829 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1831 if (data->term.c_iflag & IXOFF) {
1832 if (data->term.c_iflag & IXON)
1833 config->xon_xoff = SP_XONXOFF_INOUT;
1835 config->xon_xoff = SP_XONXOFF_IN;
1837 if (data->term.c_iflag & IXON)
1838 config->xon_xoff = SP_XONXOFF_OUT;
1840 config->xon_xoff = SP_XONXOFF_DISABLED;
1847 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1848 const struct sp_port_config *config)
1852 BAUD_TYPE baud_nonstd;
1856 #ifdef USE_TERMIOS_SPEED
1857 int baud_nonstd = 0;
1860 TRACE("%p, %p, %p", port, data, config);
1862 DEBUG_FMT("Setting configuration for port %s", port->name);
1865 if (config->baudrate >= 0) {
1866 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1867 if (config->baudrate == std_baudrates[i].value) {
1868 data->dcb.BaudRate = std_baudrates[i].index;
1873 if (i == NUM_STD_BAUDRATES)
1874 data->dcb.BaudRate = config->baudrate;
1877 if (config->bits >= 0)
1878 data->dcb.ByteSize = config->bits;
1880 if (config->parity >= 0) {
1881 switch (config->parity) {
1882 case SP_PARITY_NONE:
1883 data->dcb.Parity = NOPARITY;
1886 data->dcb.Parity = ODDPARITY;
1888 case SP_PARITY_EVEN:
1889 data->dcb.Parity = EVENPARITY;
1891 case SP_PARITY_MARK:
1892 data->dcb.Parity = MARKPARITY;
1894 case SP_PARITY_SPACE:
1895 data->dcb.Parity = SPACEPARITY;
1898 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1902 if (config->stopbits >= 0) {
1903 switch (config->stopbits) {
1904 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1906 data->dcb.StopBits = ONESTOPBIT;
1909 data->dcb.StopBits = TWOSTOPBITS;
1912 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1916 if (config->rts >= 0) {
1917 switch (config->rts) {
1919 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1922 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1924 case SP_RTS_FLOW_CONTROL:
1925 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1928 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1932 if (config->cts >= 0) {
1933 switch (config->cts) {
1935 data->dcb.fOutxCtsFlow = FALSE;
1937 case SP_CTS_FLOW_CONTROL:
1938 data->dcb.fOutxCtsFlow = TRUE;
1941 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1945 if (config->dtr >= 0) {
1946 switch (config->dtr) {
1948 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1951 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1953 case SP_DTR_FLOW_CONTROL:
1954 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1957 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1961 if (config->dsr >= 0) {
1962 switch (config->dsr) {
1964 data->dcb.fOutxDsrFlow = FALSE;
1966 case SP_DSR_FLOW_CONTROL:
1967 data->dcb.fOutxDsrFlow = TRUE;
1970 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1974 if (config->xon_xoff >= 0) {
1975 switch (config->xon_xoff) {
1976 case SP_XONXOFF_DISABLED:
1977 data->dcb.fInX = FALSE;
1978 data->dcb.fOutX = FALSE;
1981 data->dcb.fInX = TRUE;
1982 data->dcb.fOutX = FALSE;
1984 case SP_XONXOFF_OUT:
1985 data->dcb.fInX = FALSE;
1986 data->dcb.fOutX = TRUE;
1988 case SP_XONXOFF_INOUT:
1989 data->dcb.fInX = TRUE;
1990 data->dcb.fOutX = TRUE;
1993 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1997 if (!SetCommState(port->hdl, &data->dcb))
1998 RETURN_FAIL("SetCommState() failed");
2004 if (config->baudrate >= 0) {
2005 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2006 if (config->baudrate == std_baudrates[i].value) {
2007 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2008 RETURN_FAIL("cfsetospeed() failed");
2010 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2011 RETURN_FAIL("cfsetispeed() failed");
2016 /* Non-standard baud rate */
2017 if (i == NUM_STD_BAUDRATES) {
2019 /* Set "dummy" baud rate. */
2020 if (cfsetspeed(&data->term, B9600) < 0)
2021 RETURN_FAIL("cfsetspeed() failed");
2022 baud_nonstd = config->baudrate;
2023 #elif defined(USE_TERMIOS_SPEED)
2026 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2031 if (config->bits >= 0) {
2032 data->term.c_cflag &= ~CSIZE;
2033 switch (config->bits) {
2035 data->term.c_cflag |= CS8;
2038 data->term.c_cflag |= CS7;
2041 data->term.c_cflag |= CS6;
2044 data->term.c_cflag |= CS5;
2047 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2051 if (config->parity >= 0) {
2052 data->term.c_iflag &= ~IGNPAR;
2053 data->term.c_cflag &= ~(PARENB | PARODD);
2055 data->term.c_cflag &= ~CMSPAR;
2057 switch (config->parity) {
2058 case SP_PARITY_NONE:
2059 data->term.c_iflag |= IGNPAR;
2061 case SP_PARITY_EVEN:
2062 data->term.c_cflag |= PARENB;
2065 data->term.c_cflag |= PARENB | PARODD;
2068 case SP_PARITY_MARK:
2069 data->term.c_cflag |= PARENB | PARODD;
2070 data->term.c_cflag |= CMSPAR;
2072 case SP_PARITY_SPACE:
2073 data->term.c_cflag |= PARENB;
2074 data->term.c_cflag |= CMSPAR;
2077 case SP_PARITY_MARK:
2078 case SP_PARITY_SPACE:
2079 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2082 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2086 if (config->stopbits >= 0) {
2087 data->term.c_cflag &= ~CSTOPB;
2088 switch (config->stopbits) {
2090 data->term.c_cflag &= ~CSTOPB;
2093 data->term.c_cflag |= CSTOPB;
2096 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2100 if (config->rts >= 0 || config->cts >= 0) {
2101 if (data->termiox_supported) {
2102 data->rts_flow = data->cts_flow = 0;
2103 switch (config->rts) {
2106 controlbits = TIOCM_RTS;
2107 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2108 RETURN_FAIL("Setting RTS signal level failed");
2110 case SP_RTS_FLOW_CONTROL:
2116 if (config->cts == SP_CTS_FLOW_CONTROL)
2119 if (data->rts_flow && data->cts_flow)
2120 data->term.c_iflag |= CRTSCTS;
2122 data->term.c_iflag &= ~CRTSCTS;
2124 /* Asymmetric use of RTS/CTS not supported. */
2125 if (data->term.c_iflag & CRTSCTS) {
2126 /* Flow control can only be disabled for both RTS & CTS together. */
2127 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2128 if (config->cts != SP_CTS_IGNORE)
2129 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2131 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2132 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2133 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2136 /* Flow control can only be enabled for both RTS & CTS together. */
2137 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2138 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2139 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2142 if (config->rts >= 0) {
2143 if (config->rts == SP_RTS_FLOW_CONTROL) {
2144 data->term.c_iflag |= CRTSCTS;
2146 controlbits = TIOCM_RTS;
2147 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2149 RETURN_FAIL("Setting RTS signal level failed");
2155 if (config->dtr >= 0 || config->dsr >= 0) {
2156 if (data->termiox_supported) {
2157 data->dtr_flow = data->dsr_flow = 0;
2158 switch (config->dtr) {
2161 controlbits = TIOCM_DTR;
2162 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2163 RETURN_FAIL("Setting DTR signal level failed");
2165 case SP_DTR_FLOW_CONTROL:
2171 if (config->dsr == SP_DSR_FLOW_CONTROL)
2174 /* DTR/DSR flow control not supported. */
2175 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2176 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2178 if (config->dtr >= 0) {
2179 controlbits = TIOCM_DTR;
2180 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2182 RETURN_FAIL("Setting DTR signal level failed");
2187 if (config->xon_xoff >= 0) {
2188 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2189 switch (config->xon_xoff) {
2190 case SP_XONXOFF_DISABLED:
2193 data->term.c_iflag |= IXOFF;
2195 case SP_XONXOFF_OUT:
2196 data->term.c_iflag |= IXON | IXANY;
2198 case SP_XONXOFF_INOUT:
2199 data->term.c_iflag |= IXON | IXOFF | IXANY;
2202 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2206 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2207 RETURN_FAIL("tcsetattr() failed");
2210 if (baud_nonstd != B0) {
2211 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2212 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2214 * Set baud rates in data->term to correct, but incompatible
2215 * with tcsetattr() value, same as delivered by tcgetattr().
2217 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2218 RETURN_FAIL("cfsetspeed() failed");
2220 #elif defined(__linux__)
2221 #ifdef USE_TERMIOS_SPEED
2223 TRY(set_baudrate(port->fd, config->baudrate));
2226 if (data->termiox_supported)
2227 TRY(set_flow(port->fd, data));
2231 #endif /* !_WIN32 */
2236 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2238 struct sp_port_config *config;
2240 TRACE("%p", config_ptr);
2243 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2247 if (!(config = malloc(sizeof(struct sp_port_config))))
2248 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2250 config->baudrate = -1;
2252 config->parity = -1;
2253 config->stopbits = -1;
2259 *config_ptr = config;
2264 SP_API void sp_free_config(struct sp_port_config *config)
2266 TRACE("%p", config);
2269 DEBUG("Null config");
2276 SP_API enum sp_return sp_get_config(struct sp_port *port,
2277 struct sp_port_config *config)
2279 struct port_data data;
2281 TRACE("%p, %p", port, config);
2286 RETURN_ERROR(SP_ERR_ARG, "Null config");
2288 TRY(get_config(port, &data, config));
2293 SP_API enum sp_return sp_set_config(struct sp_port *port,
2294 const struct sp_port_config *config)
2296 struct port_data data;
2297 struct sp_port_config prev_config;
2299 TRACE("%p, %p", port, config);
2304 RETURN_ERROR(SP_ERR_ARG, "Null config");
2306 TRY(get_config(port, &data, &prev_config));
2307 TRY(set_config(port, &data, config));
2312 #define CREATE_ACCESSORS(x, type) \
2313 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2314 struct port_data data; \
2315 struct sp_port_config config; \
2316 TRACE("%p, %d", port, x); \
2317 CHECK_OPEN_PORT(); \
2318 TRY(get_config(port, &data, &config)); \
2320 TRY(set_config(port, &data, &config)); \
2323 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2325 TRACE("%p, %p", config, x); \
2327 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2329 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2333 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2335 TRACE("%p, %d", config, x); \
2337 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2342 CREATE_ACCESSORS(baudrate, int)
2343 CREATE_ACCESSORS(bits, int)
2344 CREATE_ACCESSORS(parity, enum sp_parity)
2345 CREATE_ACCESSORS(stopbits, int)
2346 CREATE_ACCESSORS(rts, enum sp_rts)
2347 CREATE_ACCESSORS(cts, enum sp_cts)
2348 CREATE_ACCESSORS(dtr, enum sp_dtr)
2349 CREATE_ACCESSORS(dsr, enum sp_dsr)
2350 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2352 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2353 enum sp_flowcontrol flowcontrol)
2356 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2358 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2359 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2361 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2362 config->xon_xoff = SP_XONXOFF_INOUT;
2364 config->xon_xoff = SP_XONXOFF_DISABLED;
2366 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2367 config->rts = SP_RTS_FLOW_CONTROL;
2368 config->cts = SP_CTS_FLOW_CONTROL;
2370 if (config->rts == SP_RTS_FLOW_CONTROL)
2371 config->rts = SP_RTS_ON;
2372 config->cts = SP_CTS_IGNORE;
2375 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2376 config->dtr = SP_DTR_FLOW_CONTROL;
2377 config->dsr = SP_DSR_FLOW_CONTROL;
2379 if (config->dtr == SP_DTR_FLOW_CONTROL)
2380 config->dtr = SP_DTR_ON;
2381 config->dsr = SP_DSR_IGNORE;
2387 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2388 enum sp_flowcontrol flowcontrol)
2390 struct port_data data;
2391 struct sp_port_config config;
2393 TRACE("%p, %d", port, flowcontrol);
2397 TRY(get_config(port, &data, &config));
2399 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2401 TRY(set_config(port, &data, &config));
2406 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2407 enum sp_signal *signals)
2409 TRACE("%p, %p", port, signals);
2414 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2416 DEBUG_FMT("Getting control signals for port %s", port->name);
2421 if (GetCommModemStatus(port->hdl, &bits) == 0)
2422 RETURN_FAIL("GetCommModemStatus() failed");
2423 if (bits & MS_CTS_ON)
2424 *signals |= SP_SIG_CTS;
2425 if (bits & MS_DSR_ON)
2426 *signals |= SP_SIG_DSR;
2427 if (bits & MS_RLSD_ON)
2428 *signals |= SP_SIG_DCD;
2429 if (bits & MS_RING_ON)
2430 *signals |= SP_SIG_RI;
2433 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2434 RETURN_FAIL("TIOCMGET ioctl failed");
2435 if (bits & TIOCM_CTS)
2436 *signals |= SP_SIG_CTS;
2437 if (bits & TIOCM_DSR)
2438 *signals |= SP_SIG_DSR;
2439 if (bits & TIOCM_CAR)
2440 *signals |= SP_SIG_DCD;
2441 if (bits & TIOCM_RNG)
2442 *signals |= SP_SIG_RI;
2447 SP_API enum sp_return sp_start_break(struct sp_port *port)
2453 if (SetCommBreak(port->hdl) == 0)
2454 RETURN_FAIL("SetCommBreak() failed");
2456 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2457 RETURN_FAIL("TIOCSBRK ioctl failed");
2463 SP_API enum sp_return sp_end_break(struct sp_port *port)
2469 if (ClearCommBreak(port->hdl) == 0)
2470 RETURN_FAIL("ClearCommBreak() failed");
2472 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2473 RETURN_FAIL("TIOCCBRK ioctl failed");
2479 SP_API int sp_last_error_code(void)
2483 RETURN_INT(GetLastError());
2489 SP_API char *sp_last_error_message(void)
2495 DWORD error = GetLastError();
2497 DWORD length = FormatMessage(
2498 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2499 FORMAT_MESSAGE_FROM_SYSTEM |
2500 FORMAT_MESSAGE_IGNORE_INSERTS,
2503 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2507 if (length >= 2 && message[length - 2] == '\r')
2508 message[length - 2] = '\0';
2510 RETURN_STRING(message);
2512 RETURN_STRING(strerror(errno));
2516 SP_API void sp_free_error_message(char *message)
2518 TRACE("%s", message);
2529 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2531 TRACE("%p", handler);
2533 sp_debug_handler = handler;
2538 SP_API void sp_default_debug_handler(const char *format, ...)
2541 va_start(args, format);
2542 if (getenv("LIBSERIALPORT_DEBUG")) {
2543 fputs("sp: ", stderr);
2544 vfprintf(stderr, format, args);
2549 SP_API int sp_get_major_package_version(void)
2551 return SP_PACKAGE_VERSION_MAJOR;
2554 SP_API int sp_get_minor_package_version(void)
2556 return SP_PACKAGE_VERSION_MINOR;
2559 SP_API int sp_get_micro_package_version(void)
2561 return SP_PACKAGE_VERSION_MICRO;
2564 SP_API const char *sp_get_package_version_string(void)
2566 return SP_PACKAGE_VERSION_STRING;
2569 SP_API int sp_get_current_lib_version(void)
2571 return SP_LIB_VERSION_CURRENT;
2574 SP_API int sp_get_revision_lib_version(void)
2576 return SP_LIB_VERSION_REVISION;
2579 SP_API int sp_get_age_lib_version(void)
2581 return SP_LIB_VERSION_AGE;
2584 SP_API const char *sp_get_lib_version_string(void)
2586 return SP_LIB_VERSION_STRING;