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 (!(port = malloc(sizeof(struct sp_port))))
79 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
81 len = strlen(portname) + 1;
83 if (!(port->name = malloc(len))) {
85 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
88 memcpy(port->name, portname, len);
91 port->usb_path = NULL;
92 port->hdl = INVALID_HANDLE_VALUE;
97 port->description = NULL;
98 port->transport = SP_TRANSPORT_NATIVE;
100 port->usb_address = -1;
103 port->usb_manufacturer = NULL;
104 port->usb_product = NULL;
105 port->usb_serial = NULL;
106 port->bluetooth_address = NULL;
108 #ifndef NO_PORT_METADATA
109 if ((ret = get_port_details(port)) != SP_OK) {
120 SP_API char *sp_get_port_name(const struct sp_port *port)
127 RETURN_STRING(port->name);
130 SP_API char *sp_get_port_description(const struct sp_port *port)
134 if (!port || !port->description)
137 RETURN_STRING(port->description);
140 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
145 RETURN_ERROR(SP_ERR_ARG, "Null port");
147 RETURN_INT(port->transport);
150 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
151 int *usb_bus,int *usb_address)
156 RETURN_ERROR(SP_ERR_ARG, "Null port");
157 if (port->transport != SP_TRANSPORT_USB)
158 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
159 if (port->usb_bus < 0 || port->usb_address < 0)
160 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
163 *usb_bus = port->usb_bus;
165 *usb_address = port->usb_address;
170 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
171 int *usb_vid, int *usb_pid)
176 RETURN_ERROR(SP_ERR_ARG, "Null port");
177 if (port->transport != SP_TRANSPORT_USB)
178 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
179 if (port->usb_vid < 0 || port->usb_pid < 0)
180 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
183 *usb_vid = port->usb_vid;
185 *usb_pid = port->usb_pid;
190 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
194 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
197 RETURN_STRING(port->usb_manufacturer);
200 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
204 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
207 RETURN_STRING(port->usb_product);
210 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
214 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
217 RETURN_STRING(port->usb_serial);
220 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
224 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
225 || !port->bluetooth_address)
228 RETURN_STRING(port->bluetooth_address);
231 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
234 TRACE("%p, %p", port, result_ptr);
237 RETURN_ERROR(SP_ERR_ARG, "Null port");
239 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
242 HANDLE *handle_ptr = result_ptr;
243 *handle_ptr = port->hdl;
245 int *fd_ptr = result_ptr;
252 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
253 struct sp_port **copy_ptr)
255 TRACE("%p, %p", port, copy_ptr);
258 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
263 RETURN_ERROR(SP_ERR_ARG, "Null port");
266 RETURN_ERROR(SP_ERR_ARG, "Null port name");
268 DEBUG("Copying port structure");
270 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
273 SP_API void sp_free_port(struct sp_port *port)
282 DEBUG("Freeing port structure");
286 if (port->description)
287 free(port->description);
288 if (port->usb_manufacturer)
289 free(port->usb_manufacturer);
290 if (port->usb_product)
291 free(port->usb_product);
292 if (port->usb_serial)
293 free(port->usb_serial);
294 if (port->bluetooth_address)
295 free(port->bluetooth_address);
298 free(port->usb_path);
306 SP_PRIV struct sp_port **list_append(struct sp_port **list,
307 const char *portname)
312 for (count = 0; list[count]; count++);
313 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
316 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
318 list[count + 1] = NULL;
322 sp_free_port_list(list);
326 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
328 #ifndef NO_ENUMERATION
329 struct sp_port **list;
333 TRACE("%p", list_ptr);
336 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
340 #ifdef NO_ENUMERATION
341 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
343 DEBUG("Enumerating ports");
345 if (!(list = malloc(sizeof(struct sp_port *))))
346 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
350 ret = list_ports(&list);
355 sp_free_port_list(list);
363 SP_API void sp_free_port_list(struct sp_port **list)
374 DEBUG("Freeing port list");
376 for (i = 0; list[i]; i++)
377 sp_free_port(list[i]);
383 #define CHECK_PORT() do { \
385 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
387 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
390 #define CHECK_PORT_HANDLE() do { \
391 if (port->hdl == INVALID_HANDLE_VALUE) \
392 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
395 #define CHECK_PORT_HANDLE() do { \
397 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
400 #define CHECK_OPEN_PORT() do { \
402 CHECK_PORT_HANDLE(); \
406 /** To be called after port receive buffer is emptied. */
407 static enum sp_return restart_wait(struct sp_port *port)
411 if (port->wait_running) {
412 /* Check status of running wait operation. */
413 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
414 &wait_result, FALSE)) {
415 DEBUG("Previous wait completed");
416 port->wait_running = FALSE;
417 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
418 DEBUG("Previous wait still running");
421 RETURN_FAIL("GetOverlappedResult() failed");
425 if (!port->wait_running) {
426 /* Start new wait operation. */
427 if (WaitCommEvent(port->hdl, &port->events,
429 DEBUG("New wait returned, events already pending");
430 } else if (GetLastError() == ERROR_IO_PENDING) {
431 DEBUG("New wait running in background");
432 port->wait_running = TRUE;
434 RETURN_FAIL("WaitCommEvent() failed");
442 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
444 struct port_data data;
445 struct sp_port_config config;
448 TRACE("%p, 0x%x", port, flags);
452 if (flags > SP_MODE_READ_WRITE)
453 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
455 DEBUG_FMT("Opening port %s", port->name);
458 DWORD desired_access = 0, flags_and_attributes = 0, errors;
459 char *escaped_port_name;
462 /* Prefix port name with '\\.\' to work with ports above COM9. */
463 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
464 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
465 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
467 /* Map 'flags' to the OS-specific settings. */
468 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
469 if (flags & SP_MODE_READ)
470 desired_access |= GENERIC_READ;
471 if (flags & SP_MODE_WRITE)
472 desired_access |= GENERIC_WRITE;
474 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
475 OPEN_EXISTING, flags_and_attributes, 0);
477 free(escaped_port_name);
479 if (port->hdl == INVALID_HANDLE_VALUE)
480 RETURN_FAIL("Port CreateFile() failed");
482 /* All timeouts initially disabled. */
483 port->timeouts.ReadIntervalTimeout = 0;
484 port->timeouts.ReadTotalTimeoutMultiplier = 0;
485 port->timeouts.ReadTotalTimeoutConstant = 0;
486 port->timeouts.WriteTotalTimeoutMultiplier = 0;
487 port->timeouts.WriteTotalTimeoutConstant = 0;
489 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
491 RETURN_FAIL("SetCommTimeouts() failed");
494 /* Prepare OVERLAPPED structures. */
495 #define INIT_OVERLAPPED(ovl) do { \
496 memset(&port->ovl, 0, sizeof(port->ovl)); \
497 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
498 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
499 == INVALID_HANDLE_VALUE) { \
501 RETURN_FAIL(#ovl "CreateEvent() failed"); \
505 INIT_OVERLAPPED(read_ovl);
506 INIT_OVERLAPPED(write_ovl);
507 INIT_OVERLAPPED(wait_ovl);
509 /* Set event mask for RX and error events. */
510 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
512 RETURN_FAIL("SetCommMask() failed");
515 port->writing = FALSE;
516 port->wait_running = FALSE;
518 ret = restart_wait(port);
525 int flags_local = O_NONBLOCK | O_NOCTTY;
527 /* Map 'flags' to the OS-specific settings. */
528 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
529 flags_local |= O_RDWR;
530 else if (flags & SP_MODE_READ)
531 flags_local |= O_RDONLY;
532 else if (flags & SP_MODE_WRITE)
533 flags_local |= O_WRONLY;
535 if ((port->fd = open(port->name, flags_local)) < 0)
536 RETURN_FAIL("open() failed");
539 ret = get_config(port, &data, &config);
546 /* Set sane port settings. */
548 data.dcb.fBinary = TRUE;
549 data.dcb.fDsrSensitivity = FALSE;
550 data.dcb.fErrorChar = FALSE;
551 data.dcb.fNull = FALSE;
552 data.dcb.fAbortOnError = FALSE;
554 /* Turn off all fancy termios tricks, give us a raw channel. */
555 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
557 data.term.c_iflag &= ~IUCLC;
559 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
561 data.term.c_oflag &= ~OLCUC;
564 data.term.c_oflag &= ~NLDLY;
567 data.term.c_oflag &= ~CRDLY;
570 data.term.c_oflag &= ~TABDLY;
573 data.term.c_oflag &= ~BSDLY;
576 data.term.c_oflag &= ~VTDLY;
579 data.term.c_oflag &= ~FFDLY;
582 data.term.c_oflag &= ~OFILL;
584 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
585 data.term.c_cc[VMIN] = 0;
586 data.term.c_cc[VTIME] = 0;
588 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
589 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
593 if (ClearCommError(port->hdl, &errors, &status) == 0)
594 RETURN_FAIL("ClearCommError() failed");
597 ret = set_config(port, &data, &config);
607 SP_API enum sp_return sp_close(struct sp_port *port)
613 DEBUG_FMT("Closing port %s", port->name);
616 /* Returns non-zero upon success, 0 upon failure. */
617 if (CloseHandle(port->hdl) == 0)
618 RETURN_FAIL("Port CloseHandle() failed");
619 port->hdl = INVALID_HANDLE_VALUE;
621 /* Close event handles for overlapped structures. */
622 #define CLOSE_OVERLAPPED(ovl) do { \
623 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
624 CloseHandle(port->ovl.hEvent) == 0) \
625 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
627 CLOSE_OVERLAPPED(read_ovl);
628 CLOSE_OVERLAPPED(write_ovl);
629 CLOSE_OVERLAPPED(wait_ovl);
632 /* Returns 0 upon success, -1 upon failure. */
633 if (close(port->fd) == -1)
634 RETURN_FAIL("close() failed");
641 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
643 TRACE("%p, 0x%x", port, buffers);
647 if (buffers > SP_BUF_BOTH)
648 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
650 const char *buffer_names[] = {"no", "input", "output", "both"};
652 DEBUG_FMT("Flushing %s buffers on port %s",
653 buffer_names[buffers], port->name);
657 if (buffers & SP_BUF_INPUT)
658 flags |= PURGE_RXCLEAR;
659 if (buffers & SP_BUF_OUTPUT)
660 flags |= PURGE_TXCLEAR;
662 /* Returns non-zero upon success, 0 upon failure. */
663 if (PurgeComm(port->hdl, flags) == 0)
664 RETURN_FAIL("PurgeComm() failed");
666 if (buffers & SP_BUF_INPUT)
667 TRY(restart_wait(port));
670 if (buffers == SP_BUF_BOTH)
672 else if (buffers == SP_BUF_INPUT)
674 else if (buffers == SP_BUF_OUTPUT)
677 /* Returns 0 upon success, -1 upon failure. */
678 if (tcflush(port->fd, flags) < 0)
679 RETURN_FAIL("tcflush() failed");
684 SP_API enum sp_return sp_drain(struct sp_port *port)
690 DEBUG_FMT("Draining port %s", port->name);
693 /* Returns non-zero upon success, 0 upon failure. */
694 if (FlushFileBuffers(port->hdl) == 0)
695 RETURN_FAIL("FlushFileBuffers() failed");
702 result = ioctl(port->fd, TCSBRK, &arg);
704 result = tcdrain(port->fd);
707 if (errno == EINTR) {
708 DEBUG("tcdrain() was interrupted");
711 RETURN_FAIL("tcdrain() failed");
720 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
721 size_t count, unsigned int timeout_ms)
723 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
728 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
731 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
732 count, port->name, timeout_ms);
734 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
741 DWORD bytes_written = 0;
744 /* Wait for previous non-blocking write to complete, if any. */
746 DEBUG("Waiting for previous write to complete");
747 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
750 RETURN_FAIL("Previous write failed to complete");
751 DEBUG("Previous write completed");
755 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
756 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
757 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
758 RETURN_FAIL("SetCommTimeouts() failed");
762 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
763 DEBUG("Write completed immediately");
765 } else if (GetLastError() == ERROR_IO_PENDING) {
766 DEBUG("Waiting for write to complete");
767 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
768 if (GetLastError() == ERROR_SEM_TIMEOUT) {
769 DEBUG("Write timed out");
772 RETURN_FAIL("GetOverlappedResult() failed");
775 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
776 RETURN_INT(bytes_written);
778 RETURN_FAIL("WriteFile() failed");
781 size_t bytes_written = 0;
782 unsigned char *ptr = (unsigned char *) buf;
783 struct timeval start, delta, now, end = {0, 0};
789 /* Get time at start of operation. */
790 gettimeofday(&start, NULL);
791 /* Define duration of timeout. */
792 delta.tv_sec = timeout_ms / 1000;
793 delta.tv_usec = (timeout_ms % 1000) * 1000;
794 /* Calculate time at which we should give up. */
795 timeradd(&start, &delta, &end);
799 FD_SET(port->fd, &fds);
801 /* Loop until we have written the requested number of bytes. */
802 while (bytes_written < count) {
804 * Check timeout only if we have run select() at least once,
805 * to avoid any issues if a short timeout is reached before
806 * select() is even run.
808 if (timeout_ms && started) {
809 gettimeofday(&now, NULL);
810 if (timercmp(&now, &end, >))
811 /* Timeout has expired. */
813 timersub(&end, &now, &delta);
815 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
818 if (errno == EINTR) {
819 DEBUG("select() call was interrupted, repeating");
822 RETURN_FAIL("select() failed");
824 } else if (result == 0) {
825 /* Timeout has expired. */
830 result = write(port->fd, ptr, count - bytes_written);
834 /* This shouldn't happen because we did a select() first, but handle anyway. */
837 /* This is an actual failure. */
838 RETURN_FAIL("write() failed");
841 bytes_written += result;
845 if (bytes_written < count)
846 DEBUG("Write timed out");
848 RETURN_INT(bytes_written);
852 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
853 const void *buf, size_t count)
855 TRACE("%p, %p, %d", port, buf, count);
860 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
862 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
869 BYTE *ptr = (BYTE *) buf;
871 /* Check whether previous write is complete. */
873 if (HasOverlappedIoCompleted(&port->write_ovl)) {
874 DEBUG("Previous write completed");
877 DEBUG("Previous write not complete");
878 /* Can't take a new write until the previous one finishes. */
884 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
885 port->timeouts.WriteTotalTimeoutConstant = 0;
886 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
887 RETURN_FAIL("SetCommTimeouts() failed");
891 * Keep writing data until the OS has to actually start an async IO
892 * for it. At that point we know the buffer is full.
894 while (written < count) {
895 /* Copy first byte of user buffer. */
896 port->pending_byte = *ptr++;
898 /* Start asynchronous write. */
899 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
900 if (GetLastError() == ERROR_IO_PENDING) {
901 if (HasOverlappedIoCompleted(&port->write_ovl)) {
902 DEBUG("Asynchronous write completed immediately");
907 DEBUG("Asynchronous write running");
909 RETURN_INT(++written);
912 /* Actual failure of some kind. */
913 RETURN_FAIL("WriteFile() failed");
916 DEBUG("Single byte written immediately");
921 DEBUG("All bytes written immediately");
925 /* Returns the number of bytes written, or -1 upon failure. */
926 ssize_t written = write(port->fd, buf, count);
929 RETURN_FAIL("write() failed");
936 /* Restart wait operation if buffer was emptied. */
937 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
945 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
946 RETURN_FAIL("ClearCommError() failed");
948 if (comstat.cbInQue == 0)
949 TRY(restart_wait(port));
955 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
956 size_t count, unsigned int timeout_ms)
958 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
963 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
966 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
967 count, port->name, timeout_ms);
969 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
976 DWORD bytes_read = 0;
979 if (port->timeouts.ReadIntervalTimeout != 0 ||
980 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
981 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
982 port->timeouts.ReadIntervalTimeout = 0;
983 port->timeouts.ReadTotalTimeoutMultiplier = 0;
984 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
985 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
986 RETURN_FAIL("SetCommTimeouts() failed");
990 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
991 DEBUG("Read completed immediately");
993 } else if (GetLastError() == ERROR_IO_PENDING) {
994 DEBUG("Waiting for read to complete");
995 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
996 RETURN_FAIL("GetOverlappedResult() failed");
997 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
999 RETURN_FAIL("ReadFile() failed");
1002 TRY(restart_wait_if_needed(port, bytes_read));
1004 RETURN_INT(bytes_read);
1007 size_t bytes_read = 0;
1008 unsigned char *ptr = (unsigned char *) buf;
1009 struct timeval start, delta, now, end = {0, 0};
1015 /* Get time at start of operation. */
1016 gettimeofday(&start, NULL);
1017 /* Define duration of timeout. */
1018 delta.tv_sec = timeout_ms / 1000;
1019 delta.tv_usec = (timeout_ms % 1000) * 1000;
1020 /* Calculate time at which we should give up. */
1021 timeradd(&start, &delta, &end);
1025 FD_SET(port->fd, &fds);
1027 /* Loop until we have the requested number of bytes. */
1028 while (bytes_read < count) {
1030 * Check timeout only if we have run select() at least once,
1031 * to avoid any issues if a short timeout is reached before
1032 * select() is even run.
1034 if (timeout_ms && started) {
1035 gettimeofday(&now, NULL);
1036 if (timercmp(&now, &end, >))
1037 /* Timeout has expired. */
1039 timersub(&end, &now, &delta);
1041 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1044 if (errno == EINTR) {
1045 DEBUG("select() call was interrupted, repeating");
1048 RETURN_FAIL("select() failed");
1050 } else if (result == 0) {
1051 /* Timeout has expired. */
1056 result = read(port->fd, ptr, count - bytes_read);
1059 if (errno == EAGAIN)
1061 * This shouldn't happen because we did a
1062 * select() first, but handle anyway.
1066 /* This is an actual failure. */
1067 RETURN_FAIL("read() failed");
1070 bytes_read += result;
1074 if (bytes_read < count)
1075 DEBUG("Read timed out");
1077 RETURN_INT(bytes_read);
1081 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1082 size_t count, unsigned int timeout_ms)
1084 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1089 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1092 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1095 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1096 count, port->name, timeout_ms);
1098 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1102 DWORD bytes_read = 0;
1104 /* If timeout_ms == 0, set maximum timeout. */
1105 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1108 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1109 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1110 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1111 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1112 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1113 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1114 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1115 RETURN_FAIL("SetCommTimeouts() failed");
1118 /* Loop until we have at least one byte, or timeout is reached. */
1119 while (bytes_read == 0) {
1121 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1122 DEBUG("Read completed immediately");
1123 } else if (GetLastError() == ERROR_IO_PENDING) {
1124 DEBUG("Waiting for read to complete");
1125 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1126 RETURN_FAIL("GetOverlappedResult() failed");
1127 if (bytes_read > 0) {
1128 DEBUG("Read completed");
1129 } else if (timeout_ms > 0) {
1130 DEBUG("Read timed out");
1133 DEBUG("Restarting read");
1136 RETURN_FAIL("ReadFile() failed");
1140 TRY(restart_wait_if_needed(port, bytes_read));
1142 RETURN_INT(bytes_read);
1145 size_t bytes_read = 0;
1146 struct timeval start, delta, now, end = {0, 0};
1152 /* Get time at start of operation. */
1153 gettimeofday(&start, NULL);
1154 /* Define duration of timeout. */
1155 delta.tv_sec = timeout_ms / 1000;
1156 delta.tv_usec = (timeout_ms % 1000) * 1000;
1157 /* Calculate time at which we should give up. */
1158 timeradd(&start, &delta, &end);
1162 FD_SET(port->fd, &fds);
1164 /* Loop until we have at least one byte, or timeout is reached. */
1165 while (bytes_read == 0) {
1167 * Check timeout only if we have run select() at least once,
1168 * to avoid any issues if a short timeout is reached before
1169 * select() is even run.
1171 if (timeout_ms && started) {
1172 gettimeofday(&now, NULL);
1173 if (timercmp(&now, &end, >))
1174 /* Timeout has expired. */
1176 timersub(&end, &now, &delta);
1178 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1181 if (errno == EINTR) {
1182 DEBUG("select() call was interrupted, repeating");
1185 RETURN_FAIL("select() failed");
1187 } else if (result == 0) {
1188 /* Timeout has expired. */
1193 result = read(port->fd, buf, count);
1196 if (errno == EAGAIN)
1197 /* This shouldn't happen because we did a select() first, but handle anyway. */
1200 /* This is an actual failure. */
1201 RETURN_FAIL("read() failed");
1204 bytes_read = result;
1207 if (bytes_read == 0)
1208 DEBUG("Read timed out");
1210 RETURN_INT(bytes_read);
1214 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1217 TRACE("%p, %p, %d", port, buf, count);
1222 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1224 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1230 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1231 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1232 port->timeouts.ReadTotalTimeoutConstant != 0) {
1233 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1234 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1235 port->timeouts.ReadTotalTimeoutConstant = 0;
1236 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1237 RETURN_FAIL("SetCommTimeouts() failed");
1241 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1242 if (GetLastError() != ERROR_IO_PENDING)
1243 RETURN_FAIL("ReadFile() failed");
1245 /* Get number of bytes read. */
1246 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1247 RETURN_FAIL("GetOverlappedResult() failed");
1249 TRY(restart_wait_if_needed(port, bytes_read));
1251 RETURN_INT(bytes_read);
1255 /* Returns the number of bytes read, or -1 upon failure. */
1256 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1257 if (errno == EAGAIN)
1258 /* No bytes available. */
1261 /* This is an actual failure. */
1262 RETURN_FAIL("read() failed");
1264 RETURN_INT(bytes_read);
1268 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1274 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1280 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1281 RETURN_FAIL("ClearCommError() failed");
1282 RETURN_INT(comstat.cbInQue);
1285 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1286 RETURN_FAIL("TIOCINQ ioctl failed");
1287 RETURN_INT(bytes_waiting);
1291 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1297 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1303 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1304 RETURN_FAIL("ClearCommError() failed");
1305 RETURN_INT(comstat.cbOutQue);
1308 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1309 RETURN_FAIL("TIOCOUTQ ioctl failed");
1310 RETURN_INT(bytes_waiting);
1314 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1316 struct sp_event_set *result;
1318 TRACE("%p", result_ptr);
1321 RETURN_ERROR(SP_ERR_ARG, "Null result");
1325 if (!(result = malloc(sizeof(struct sp_event_set))))
1326 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1328 memset(result, 0, sizeof(struct sp_event_set));
1330 *result_ptr = result;
1335 static enum sp_return add_handle(struct sp_event_set *event_set,
1336 event_handle handle, enum sp_event mask)
1339 enum sp_event *new_masks;
1341 TRACE("%p, %d, %d", event_set, handle, mask);
1343 if (!(new_handles = realloc(event_set->handles,
1344 sizeof(event_handle) * (event_set->count + 1))))
1345 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1347 event_set->handles = new_handles;
1349 if (!(new_masks = realloc(event_set->masks,
1350 sizeof(enum sp_event) * (event_set->count + 1))))
1351 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1353 event_set->masks = new_masks;
1355 ((event_handle *) event_set->handles)[event_set->count] = handle;
1356 event_set->masks[event_set->count] = mask;
1363 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1364 const struct sp_port *port, enum sp_event mask)
1366 TRACE("%p, %p, %d", event_set, port, mask);
1369 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1372 RETURN_ERROR(SP_ERR_ARG, "Null port");
1374 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1375 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1381 enum sp_event handle_mask;
1382 if ((handle_mask = mask & SP_EVENT_TX_READY))
1383 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1384 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1385 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1387 TRY(add_handle(event_set, port->fd, mask));
1393 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1395 TRACE("%p", event_set);
1398 DEBUG("Null event set");
1402 DEBUG("Freeing event set");
1404 if (event_set->handles)
1405 free(event_set->handles);
1406 if (event_set->masks)
1407 free(event_set->masks);
1414 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1415 unsigned int timeout_ms)
1417 TRACE("%p, %d", event_set, timeout_ms);
1420 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1423 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1424 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1425 RETURN_FAIL("WaitForMultipleObjects() failed");
1429 struct timeval start, delta, now, end = {0, 0};
1430 const struct timeval max_delta = {
1431 (INT_MAX / 1000), (INT_MAX % 1000) * 1000};
1432 int started = 0, timeout_overflow = 0;
1433 int result, timeout_remaining_ms;
1434 struct pollfd *pollfds;
1437 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1438 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1440 for (i = 0; i < event_set->count; i++) {
1441 pollfds[i].fd = ((int *) event_set->handles)[i];
1442 pollfds[i].events = 0;
1443 pollfds[i].revents = 0;
1444 if (event_set->masks[i] & SP_EVENT_RX_READY)
1445 pollfds[i].events |= POLLIN;
1446 if (event_set->masks[i] & SP_EVENT_TX_READY)
1447 pollfds[i].events |= POLLOUT;
1448 if (event_set->masks[i] & SP_EVENT_ERROR)
1449 pollfds[i].events |= POLLERR;
1453 /* Get time at start of operation. */
1454 gettimeofday(&start, NULL);
1455 /* Define duration of timeout. */
1456 delta.tv_sec = timeout_ms / 1000;
1457 delta.tv_usec = (timeout_ms % 1000) * 1000;
1458 /* Calculate time at which we should give up. */
1459 timeradd(&start, &delta, &end);
1462 /* Loop until an event occurs. */
1465 * Check timeout only if we have run poll() at least once,
1466 * to avoid any issues if a short timeout is reached before
1467 * poll() is even run.
1470 timeout_remaining_ms = -1;
1471 } else if (!started) {
1472 timeout_overflow = (timeout_ms > INT_MAX);
1473 timeout_remaining_ms = timeout_overflow ? INT_MAX : timeout_ms;
1475 gettimeofday(&now, NULL);
1476 if (timercmp(&now, &end, >)) {
1477 DEBUG("Wait timed out");
1480 timersub(&end, &now, &delta);
1481 if ((timeout_overflow = timercmp(&delta, &max_delta, >)))
1483 timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1486 result = poll(pollfds, event_set->count, timeout_remaining_ms);
1490 if (errno == EINTR) {
1491 DEBUG("poll() call was interrupted, repeating");
1495 RETURN_FAIL("poll() failed");
1497 } else if (result == 0) {
1498 DEBUG("poll() timed out");
1499 if (!timeout_overflow)
1502 DEBUG("poll() completed");
1512 #ifdef USE_TERMIOS_SPEED
1513 static enum sp_return get_baudrate(int fd, int *baudrate)
1517 TRACE("%d, %p", fd, baudrate);
1519 DEBUG("Getting baud rate");
1521 if (!(data = malloc(get_termios_size())))
1522 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1524 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1526 RETURN_FAIL("Getting termios failed");
1529 *baudrate = get_termios_speed(data);
1536 static enum sp_return set_baudrate(int fd, int baudrate)
1540 TRACE("%d, %d", fd, baudrate);
1542 DEBUG("Getting baud rate");
1544 if (!(data = malloc(get_termios_size())))
1545 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1547 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1549 RETURN_FAIL("Getting termios failed");
1552 DEBUG("Setting baud rate");
1554 set_termios_speed(data, baudrate);
1556 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1558 RETURN_FAIL("Setting termios failed");
1565 #endif /* USE_TERMIOS_SPEED */
1568 static enum sp_return get_flow(int fd, struct port_data *data)
1572 TRACE("%d, %p", fd, data);
1574 DEBUG("Getting advanced flow control");
1576 if (!(termx = malloc(get_termiox_size())))
1577 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1579 if (ioctl(fd, TCGETX, termx) < 0) {
1581 RETURN_FAIL("Getting termiox failed");
1584 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1585 &data->dtr_flow, &data->dsr_flow);
1592 static enum sp_return set_flow(int fd, struct port_data *data)
1596 TRACE("%d, %p", fd, data);
1598 DEBUG("Getting advanced flow control");
1600 if (!(termx = malloc(get_termiox_size())))
1601 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1603 if (ioctl(fd, TCGETX, termx) < 0) {
1605 RETURN_FAIL("Getting termiox failed");
1608 DEBUG("Setting advanced flow control");
1610 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1611 data->dtr_flow, data->dsr_flow);
1613 if (ioctl(fd, TCSETX, termx) < 0) {
1615 RETURN_FAIL("Setting termiox failed");
1622 #endif /* USE_TERMIOX */
1624 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1625 struct sp_port_config *config)
1629 TRACE("%p, %p, %p", port, data, config);
1631 DEBUG_FMT("Getting configuration for port %s", port->name);
1634 if (!GetCommState(port->hdl, &data->dcb))
1635 RETURN_FAIL("GetCommState() failed");
1637 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1638 if (data->dcb.BaudRate == std_baudrates[i].index) {
1639 config->baudrate = std_baudrates[i].value;
1644 if (i == NUM_STD_BAUDRATES)
1645 /* BaudRate field can be either an index or a custom baud rate. */
1646 config->baudrate = data->dcb.BaudRate;
1648 config->bits = data->dcb.ByteSize;
1650 if (data->dcb.fParity)
1651 switch (data->dcb.Parity) {
1653 config->parity = SP_PARITY_NONE;
1656 config->parity = SP_PARITY_ODD;
1659 config->parity = SP_PARITY_EVEN;
1662 config->parity = SP_PARITY_MARK;
1665 config->parity = SP_PARITY_SPACE;
1668 config->parity = -1;
1671 config->parity = SP_PARITY_NONE;
1673 switch (data->dcb.StopBits) {
1675 config->stopbits = 1;
1678 config->stopbits = 2;
1681 config->stopbits = -1;
1684 switch (data->dcb.fRtsControl) {
1685 case RTS_CONTROL_DISABLE:
1686 config->rts = SP_RTS_OFF;
1688 case RTS_CONTROL_ENABLE:
1689 config->rts = SP_RTS_ON;
1691 case RTS_CONTROL_HANDSHAKE:
1692 config->rts = SP_RTS_FLOW_CONTROL;
1698 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1700 switch (data->dcb.fDtrControl) {
1701 case DTR_CONTROL_DISABLE:
1702 config->dtr = SP_DTR_OFF;
1704 case DTR_CONTROL_ENABLE:
1705 config->dtr = SP_DTR_ON;
1707 case DTR_CONTROL_HANDSHAKE:
1708 config->dtr = SP_DTR_FLOW_CONTROL;
1714 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1716 if (data->dcb.fInX) {
1717 if (data->dcb.fOutX)
1718 config->xon_xoff = SP_XONXOFF_INOUT;
1720 config->xon_xoff = SP_XONXOFF_IN;
1722 if (data->dcb.fOutX)
1723 config->xon_xoff = SP_XONXOFF_OUT;
1725 config->xon_xoff = SP_XONXOFF_DISABLED;
1730 if (tcgetattr(port->fd, &data->term) < 0)
1731 RETURN_FAIL("tcgetattr() failed");
1733 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1734 RETURN_FAIL("TIOCMGET ioctl failed");
1737 int ret = get_flow(port->fd, data);
1739 if (ret == SP_ERR_FAIL && errno == EINVAL)
1740 data->termiox_supported = 0;
1742 RETURN_CODEVAL(ret);
1744 data->termiox_supported = 1;
1746 data->termiox_supported = 0;
1749 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1750 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1751 config->baudrate = std_baudrates[i].value;
1756 if (i == NUM_STD_BAUDRATES) {
1758 config->baudrate = (int)data->term.c_ispeed;
1759 #elif defined(USE_TERMIOS_SPEED)
1760 TRY(get_baudrate(port->fd, &config->baudrate));
1762 config->baudrate = -1;
1766 switch (data->term.c_cflag & CSIZE) {
1783 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1784 config->parity = SP_PARITY_NONE;
1785 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1786 config->parity = -1;
1788 else if (data->term.c_cflag & CMSPAR)
1789 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1792 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1794 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1796 if (data->term.c_cflag & CRTSCTS) {
1797 config->rts = SP_RTS_FLOW_CONTROL;
1798 config->cts = SP_CTS_FLOW_CONTROL;
1800 if (data->termiox_supported && data->rts_flow)
1801 config->rts = SP_RTS_FLOW_CONTROL;
1803 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1805 config->cts = (data->termiox_supported && data->cts_flow) ?
1806 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1809 if (data->termiox_supported && data->dtr_flow)
1810 config->dtr = SP_DTR_FLOW_CONTROL;
1812 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1814 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1815 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1817 if (data->term.c_iflag & IXOFF) {
1818 if (data->term.c_iflag & IXON)
1819 config->xon_xoff = SP_XONXOFF_INOUT;
1821 config->xon_xoff = SP_XONXOFF_IN;
1823 if (data->term.c_iflag & IXON)
1824 config->xon_xoff = SP_XONXOFF_OUT;
1826 config->xon_xoff = SP_XONXOFF_DISABLED;
1833 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1834 const struct sp_port_config *config)
1838 BAUD_TYPE baud_nonstd;
1842 #ifdef USE_TERMIOS_SPEED
1843 int baud_nonstd = 0;
1846 TRACE("%p, %p, %p", port, data, config);
1848 DEBUG_FMT("Setting configuration for port %s", port->name);
1851 if (config->baudrate >= 0) {
1852 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1853 if (config->baudrate == std_baudrates[i].value) {
1854 data->dcb.BaudRate = std_baudrates[i].index;
1859 if (i == NUM_STD_BAUDRATES)
1860 data->dcb.BaudRate = config->baudrate;
1863 if (config->bits >= 0)
1864 data->dcb.ByteSize = config->bits;
1866 if (config->parity >= 0) {
1867 switch (config->parity) {
1868 case SP_PARITY_NONE:
1869 data->dcb.Parity = NOPARITY;
1872 data->dcb.Parity = ODDPARITY;
1874 case SP_PARITY_EVEN:
1875 data->dcb.Parity = EVENPARITY;
1877 case SP_PARITY_MARK:
1878 data->dcb.Parity = MARKPARITY;
1880 case SP_PARITY_SPACE:
1881 data->dcb.Parity = SPACEPARITY;
1884 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1888 if (config->stopbits >= 0) {
1889 switch (config->stopbits) {
1890 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1892 data->dcb.StopBits = ONESTOPBIT;
1895 data->dcb.StopBits = TWOSTOPBITS;
1898 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1902 if (config->rts >= 0) {
1903 switch (config->rts) {
1905 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1908 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1910 case SP_RTS_FLOW_CONTROL:
1911 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1914 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1918 if (config->cts >= 0) {
1919 switch (config->cts) {
1921 data->dcb.fOutxCtsFlow = FALSE;
1923 case SP_CTS_FLOW_CONTROL:
1924 data->dcb.fOutxCtsFlow = TRUE;
1927 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1931 if (config->dtr >= 0) {
1932 switch (config->dtr) {
1934 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1937 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1939 case SP_DTR_FLOW_CONTROL:
1940 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1943 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1947 if (config->dsr >= 0) {
1948 switch (config->dsr) {
1950 data->dcb.fOutxDsrFlow = FALSE;
1952 case SP_DSR_FLOW_CONTROL:
1953 data->dcb.fOutxDsrFlow = TRUE;
1956 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1960 if (config->xon_xoff >= 0) {
1961 switch (config->xon_xoff) {
1962 case SP_XONXOFF_DISABLED:
1963 data->dcb.fInX = FALSE;
1964 data->dcb.fOutX = FALSE;
1967 data->dcb.fInX = TRUE;
1968 data->dcb.fOutX = FALSE;
1970 case SP_XONXOFF_OUT:
1971 data->dcb.fInX = FALSE;
1972 data->dcb.fOutX = TRUE;
1974 case SP_XONXOFF_INOUT:
1975 data->dcb.fInX = TRUE;
1976 data->dcb.fOutX = TRUE;
1979 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1983 if (!SetCommState(port->hdl, &data->dcb))
1984 RETURN_FAIL("SetCommState() failed");
1990 if (config->baudrate >= 0) {
1991 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1992 if (config->baudrate == std_baudrates[i].value) {
1993 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1994 RETURN_FAIL("cfsetospeed() failed");
1996 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1997 RETURN_FAIL("cfsetispeed() failed");
2002 /* Non-standard baud rate */
2003 if (i == NUM_STD_BAUDRATES) {
2005 /* Set "dummy" baud rate. */
2006 if (cfsetspeed(&data->term, B9600) < 0)
2007 RETURN_FAIL("cfsetspeed() failed");
2008 baud_nonstd = config->baudrate;
2009 #elif defined(USE_TERMIOS_SPEED)
2012 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2017 if (config->bits >= 0) {
2018 data->term.c_cflag &= ~CSIZE;
2019 switch (config->bits) {
2021 data->term.c_cflag |= CS8;
2024 data->term.c_cflag |= CS7;
2027 data->term.c_cflag |= CS6;
2030 data->term.c_cflag |= CS5;
2033 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2037 if (config->parity >= 0) {
2038 data->term.c_iflag &= ~IGNPAR;
2039 data->term.c_cflag &= ~(PARENB | PARODD);
2041 data->term.c_cflag &= ~CMSPAR;
2043 switch (config->parity) {
2044 case SP_PARITY_NONE:
2045 data->term.c_iflag |= IGNPAR;
2047 case SP_PARITY_EVEN:
2048 data->term.c_cflag |= PARENB;
2051 data->term.c_cflag |= PARENB | PARODD;
2054 case SP_PARITY_MARK:
2055 data->term.c_cflag |= PARENB | PARODD;
2056 data->term.c_cflag |= CMSPAR;
2058 case SP_PARITY_SPACE:
2059 data->term.c_cflag |= PARENB;
2060 data->term.c_cflag |= CMSPAR;
2063 case SP_PARITY_MARK:
2064 case SP_PARITY_SPACE:
2065 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2068 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2072 if (config->stopbits >= 0) {
2073 data->term.c_cflag &= ~CSTOPB;
2074 switch (config->stopbits) {
2076 data->term.c_cflag &= ~CSTOPB;
2079 data->term.c_cflag |= CSTOPB;
2082 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2086 if (config->rts >= 0 || config->cts >= 0) {
2087 if (data->termiox_supported) {
2088 data->rts_flow = data->cts_flow = 0;
2089 switch (config->rts) {
2092 controlbits = TIOCM_RTS;
2093 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2094 RETURN_FAIL("Setting RTS signal level failed");
2096 case SP_RTS_FLOW_CONTROL:
2102 if (config->cts == SP_CTS_FLOW_CONTROL)
2105 if (data->rts_flow && data->cts_flow)
2106 data->term.c_iflag |= CRTSCTS;
2108 data->term.c_iflag &= ~CRTSCTS;
2110 /* Asymmetric use of RTS/CTS not supported. */
2111 if (data->term.c_iflag & CRTSCTS) {
2112 /* Flow control can only be disabled for both RTS & CTS together. */
2113 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2114 if (config->cts != SP_CTS_IGNORE)
2115 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2117 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2118 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2119 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2122 /* Flow control can only be enabled for both RTS & CTS together. */
2123 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2124 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2125 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2128 if (config->rts >= 0) {
2129 if (config->rts == SP_RTS_FLOW_CONTROL) {
2130 data->term.c_iflag |= CRTSCTS;
2132 controlbits = TIOCM_RTS;
2133 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2135 RETURN_FAIL("Setting RTS signal level failed");
2141 if (config->dtr >= 0 || config->dsr >= 0) {
2142 if (data->termiox_supported) {
2143 data->dtr_flow = data->dsr_flow = 0;
2144 switch (config->dtr) {
2147 controlbits = TIOCM_DTR;
2148 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2149 RETURN_FAIL("Setting DTR signal level failed");
2151 case SP_DTR_FLOW_CONTROL:
2157 if (config->dsr == SP_DSR_FLOW_CONTROL)
2160 /* DTR/DSR flow control not supported. */
2161 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2162 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2164 if (config->dtr >= 0) {
2165 controlbits = TIOCM_DTR;
2166 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2168 RETURN_FAIL("Setting DTR signal level failed");
2173 if (config->xon_xoff >= 0) {
2174 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2175 switch (config->xon_xoff) {
2176 case SP_XONXOFF_DISABLED:
2179 data->term.c_iflag |= IXOFF;
2181 case SP_XONXOFF_OUT:
2182 data->term.c_iflag |= IXON | IXANY;
2184 case SP_XONXOFF_INOUT:
2185 data->term.c_iflag |= IXON | IXOFF | IXANY;
2188 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2192 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2193 RETURN_FAIL("tcsetattr() failed");
2196 if (baud_nonstd != B0) {
2197 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2198 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2200 * Set baud rates in data->term to correct, but incompatible
2201 * with tcsetattr() value, same as delivered by tcgetattr().
2203 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2204 RETURN_FAIL("cfsetspeed() failed");
2206 #elif defined(__linux__)
2207 #ifdef USE_TERMIOS_SPEED
2209 TRY(set_baudrate(port->fd, config->baudrate));
2212 if (data->termiox_supported)
2213 TRY(set_flow(port->fd, data));
2217 #endif /* !_WIN32 */
2222 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2224 struct sp_port_config *config;
2226 TRACE("%p", config_ptr);
2229 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2233 if (!(config = malloc(sizeof(struct sp_port_config))))
2234 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2236 config->baudrate = -1;
2238 config->parity = -1;
2239 config->stopbits = -1;
2245 *config_ptr = config;
2250 SP_API void sp_free_config(struct sp_port_config *config)
2252 TRACE("%p", config);
2255 DEBUG("Null config");
2262 SP_API enum sp_return sp_get_config(struct sp_port *port,
2263 struct sp_port_config *config)
2265 struct port_data data;
2267 TRACE("%p, %p", port, config);
2272 RETURN_ERROR(SP_ERR_ARG, "Null config");
2274 TRY(get_config(port, &data, config));
2279 SP_API enum sp_return sp_set_config(struct sp_port *port,
2280 const struct sp_port_config *config)
2282 struct port_data data;
2283 struct sp_port_config prev_config;
2285 TRACE("%p, %p", port, config);
2290 RETURN_ERROR(SP_ERR_ARG, "Null config");
2292 TRY(get_config(port, &data, &prev_config));
2293 TRY(set_config(port, &data, config));
2298 #define CREATE_ACCESSORS(x, type) \
2299 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2300 struct port_data data; \
2301 struct sp_port_config config; \
2302 TRACE("%p, %d", port, x); \
2303 CHECK_OPEN_PORT(); \
2304 TRY(get_config(port, &data, &config)); \
2306 TRY(set_config(port, &data, &config)); \
2309 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2311 TRACE("%p, %p", config, x); \
2313 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2315 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2319 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2321 TRACE("%p, %d", config, x); \
2323 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2328 CREATE_ACCESSORS(baudrate, int)
2329 CREATE_ACCESSORS(bits, int)
2330 CREATE_ACCESSORS(parity, enum sp_parity)
2331 CREATE_ACCESSORS(stopbits, int)
2332 CREATE_ACCESSORS(rts, enum sp_rts)
2333 CREATE_ACCESSORS(cts, enum sp_cts)
2334 CREATE_ACCESSORS(dtr, enum sp_dtr)
2335 CREATE_ACCESSORS(dsr, enum sp_dsr)
2336 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2338 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2339 enum sp_flowcontrol flowcontrol)
2342 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2344 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2345 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2347 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2348 config->xon_xoff = SP_XONXOFF_INOUT;
2350 config->xon_xoff = SP_XONXOFF_DISABLED;
2352 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2353 config->rts = SP_RTS_FLOW_CONTROL;
2354 config->cts = SP_CTS_FLOW_CONTROL;
2356 if (config->rts == SP_RTS_FLOW_CONTROL)
2357 config->rts = SP_RTS_ON;
2358 config->cts = SP_CTS_IGNORE;
2361 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2362 config->dtr = SP_DTR_FLOW_CONTROL;
2363 config->dsr = SP_DSR_FLOW_CONTROL;
2365 if (config->dtr == SP_DTR_FLOW_CONTROL)
2366 config->dtr = SP_DTR_ON;
2367 config->dsr = SP_DSR_IGNORE;
2373 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2374 enum sp_flowcontrol flowcontrol)
2376 struct port_data data;
2377 struct sp_port_config config;
2379 TRACE("%p, %d", port, flowcontrol);
2383 TRY(get_config(port, &data, &config));
2385 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2387 TRY(set_config(port, &data, &config));
2392 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2393 enum sp_signal *signals)
2395 TRACE("%p, %p", port, signals);
2400 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2402 DEBUG_FMT("Getting control signals for port %s", port->name);
2407 if (GetCommModemStatus(port->hdl, &bits) == 0)
2408 RETURN_FAIL("GetCommModemStatus() failed");
2409 if (bits & MS_CTS_ON)
2410 *signals |= SP_SIG_CTS;
2411 if (bits & MS_DSR_ON)
2412 *signals |= SP_SIG_DSR;
2413 if (bits & MS_RLSD_ON)
2414 *signals |= SP_SIG_DCD;
2415 if (bits & MS_RING_ON)
2416 *signals |= SP_SIG_RI;
2419 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2420 RETURN_FAIL("TIOCMGET ioctl failed");
2421 if (bits & TIOCM_CTS)
2422 *signals |= SP_SIG_CTS;
2423 if (bits & TIOCM_DSR)
2424 *signals |= SP_SIG_DSR;
2425 if (bits & TIOCM_CAR)
2426 *signals |= SP_SIG_DCD;
2427 if (bits & TIOCM_RNG)
2428 *signals |= SP_SIG_RI;
2433 SP_API enum sp_return sp_start_break(struct sp_port *port)
2439 if (SetCommBreak(port->hdl) == 0)
2440 RETURN_FAIL("SetCommBreak() failed");
2442 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2443 RETURN_FAIL("TIOCSBRK ioctl failed");
2449 SP_API enum sp_return sp_end_break(struct sp_port *port)
2455 if (ClearCommBreak(port->hdl) == 0)
2456 RETURN_FAIL("ClearCommBreak() failed");
2458 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2459 RETURN_FAIL("TIOCCBRK ioctl failed");
2465 SP_API int sp_last_error_code(void)
2469 RETURN_INT(GetLastError());
2475 SP_API char *sp_last_error_message(void)
2481 DWORD error = GetLastError();
2483 DWORD length = FormatMessage(
2484 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2485 FORMAT_MESSAGE_FROM_SYSTEM |
2486 FORMAT_MESSAGE_IGNORE_INSERTS,
2489 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2493 if (length >= 2 && message[length - 2] == '\r')
2494 message[length - 2] = '\0';
2496 RETURN_STRING(message);
2498 RETURN_STRING(strerror(errno));
2502 SP_API void sp_free_error_message(char *message)
2504 TRACE("%s", message);
2515 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2517 TRACE("%p", handler);
2519 sp_debug_handler = handler;
2524 SP_API void sp_default_debug_handler(const char *format, ...)
2527 va_start(args, format);
2528 if (getenv("LIBSERIALPORT_DEBUG")) {
2529 fputs("sp: ", stderr);
2530 vfprintf(stderr, format, args);
2535 SP_API int sp_get_major_package_version(void)
2537 return SP_PACKAGE_VERSION_MAJOR;
2540 SP_API int sp_get_minor_package_version(void)
2542 return SP_PACKAGE_VERSION_MINOR;
2545 SP_API int sp_get_micro_package_version(void)
2547 return SP_PACKAGE_VERSION_MICRO;
2550 SP_API const char *sp_get_package_version_string(void)
2552 return SP_PACKAGE_VERSION_STRING;
2555 SP_API int sp_get_current_lib_version(void)
2557 return SP_LIB_VERSION_CURRENT;
2560 SP_API int sp_get_revision_lib_version(void)
2562 return SP_LIB_VERSION_REVISION;
2565 SP_API int sp_get_age_lib_version(void)
2567 return SP_LIB_VERSION_AGE;
2570 SP_API const char *sp_get_lib_version_string(void)
2572 return SP_LIB_VERSION_STRING;