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/>.
24 #include "libserialport_internal.h"
26 static const struct std_baudrate std_baudrates[] = {
29 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
30 * have documented CBR_* macros.
32 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
33 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
34 BAUD(115200), BAUD(128000), BAUD(256000),
36 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
37 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
38 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
40 #if !defined(__APPLE__) && !defined(__OpenBSD__)
46 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
48 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
50 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
51 struct sp_port_config *config);
53 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
54 const struct sp_port_config *config);
56 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
59 #ifndef NO_PORT_METADATA
64 TRACE("%s, %p", portname, port_ptr);
67 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
72 RETURN_ERROR(SP_ERR_ARG, "Null port name");
74 DEBUG_FMT("Building structure for port %s", portname);
76 #if !defined(_WIN32) && defined(HAVE_REALPATH)
78 * get_port_details() below tries to be too smart and figure out
79 * some transport properties from the port name which breaks with
80 * symlinks. Therefore we canonicalize the portname first.
82 char pathbuf[PATH_MAX + 1];
83 char *res = realpath(portname, pathbuf);
85 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
90 if (!(port = malloc(sizeof(struct sp_port))))
91 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
93 len = strlen(portname) + 1;
95 if (!(port->name = malloc(len))) {
97 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
100 memcpy(port->name, portname, len);
103 port->usb_path = NULL;
104 port->hdl = INVALID_HANDLE_VALUE;
105 port->write_buf = NULL;
106 port->write_buf_size = 0;
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);
314 free(port->write_buf);
322 SP_PRIV struct sp_port **list_append(struct sp_port **list,
323 const char *portname)
328 for (count = 0; list[count]; count++)
330 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
333 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
335 list[count + 1] = NULL;
339 sp_free_port_list(list);
343 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
345 #ifndef NO_ENUMERATION
346 struct sp_port **list;
350 TRACE("%p", list_ptr);
353 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
357 #ifdef NO_ENUMERATION
358 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
360 DEBUG("Enumerating ports");
362 if (!(list = malloc(sizeof(struct sp_port *))))
363 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
367 ret = list_ports(&list);
372 sp_free_port_list(list);
380 SP_API void sp_free_port_list(struct sp_port **list)
391 DEBUG("Freeing port list");
393 for (i = 0; list[i]; i++)
394 sp_free_port(list[i]);
400 #define CHECK_PORT() do { \
402 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
404 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
407 #define CHECK_PORT_HANDLE() do { \
408 if (port->hdl == INVALID_HANDLE_VALUE) \
409 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
412 #define CHECK_PORT_HANDLE() do { \
414 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
417 #define CHECK_OPEN_PORT() do { \
419 CHECK_PORT_HANDLE(); \
423 /** To be called after port receive buffer is emptied. */
424 static enum sp_return restart_wait(struct sp_port *port)
428 if (port->wait_running) {
429 /* Check status of running wait operation. */
430 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
431 &wait_result, FALSE)) {
432 DEBUG("Previous wait completed");
433 port->wait_running = FALSE;
434 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
435 DEBUG("Previous wait still running");
438 RETURN_FAIL("GetOverlappedResult() failed");
442 if (!port->wait_running) {
443 /* Start new wait operation. */
444 if (WaitCommEvent(port->hdl, &port->events,
446 DEBUG("New wait returned, events already pending");
447 } else if (GetLastError() == ERROR_IO_PENDING) {
448 DEBUG("New wait running in background");
449 port->wait_running = TRUE;
451 RETURN_FAIL("WaitCommEvent() failed");
459 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
461 struct port_data data;
462 struct sp_port_config config;
465 TRACE("%p, 0x%x", port, flags);
469 if (flags > SP_MODE_READ_WRITE)
470 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
472 DEBUG_FMT("Opening port %s", port->name);
475 DWORD desired_access = 0, flags_and_attributes = 0, errors;
476 char *escaped_port_name;
479 /* Prefix port name with '\\.\' to work with ports above COM9. */
480 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
481 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
482 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
484 /* Map 'flags' to the OS-specific settings. */
485 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
486 if (flags & SP_MODE_READ)
487 desired_access |= GENERIC_READ;
488 if (flags & SP_MODE_WRITE)
489 desired_access |= GENERIC_WRITE;
491 port->hdl = CreateFileA(escaped_port_name, desired_access, 0, 0,
492 OPEN_EXISTING, flags_and_attributes, 0);
494 free(escaped_port_name);
496 if (port->hdl == INVALID_HANDLE_VALUE)
497 RETURN_FAIL("Port CreateFile() failed");
499 /* All timeouts initially disabled. */
500 port->timeouts.ReadIntervalTimeout = 0;
501 port->timeouts.ReadTotalTimeoutMultiplier = 0;
502 port->timeouts.ReadTotalTimeoutConstant = 0;
503 port->timeouts.WriteTotalTimeoutMultiplier = 0;
504 port->timeouts.WriteTotalTimeoutConstant = 0;
506 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
508 RETURN_FAIL("SetCommTimeouts() failed");
511 /* Prepare OVERLAPPED structures. */
512 #define INIT_OVERLAPPED(ovl) do { \
513 memset(&port->ovl, 0, sizeof(port->ovl)); \
514 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
515 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
516 == INVALID_HANDLE_VALUE) { \
518 RETURN_FAIL(#ovl "CreateEvent() failed"); \
522 INIT_OVERLAPPED(read_ovl);
523 INIT_OVERLAPPED(write_ovl);
524 INIT_OVERLAPPED(wait_ovl);
526 /* Set event mask for RX and error events. */
527 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
529 RETURN_FAIL("SetCommMask() failed");
532 port->writing = FALSE;
533 port->wait_running = FALSE;
535 ret = restart_wait(port);
542 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
544 /* Map 'flags' to the OS-specific settings. */
545 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
546 flags_local |= O_RDWR;
547 else if (flags & SP_MODE_READ)
548 flags_local |= O_RDONLY;
549 else if (flags & SP_MODE_WRITE)
550 flags_local |= O_WRONLY;
552 if ((port->fd = open(port->name, flags_local)) < 0)
553 RETURN_FAIL("open() failed");
556 * On POSIX in the default case the file descriptor of a serial port
557 * is not opened exclusively. Therefore the settings of a port are
558 * overwritten if the serial port is opened a second time. Windows
559 * opens all serial ports exclusively.
560 * So the idea is to open the serial ports alike in the exclusive mode.
562 * ioctl(*, TIOCEXCL) defines the file descriptor as exclusive. So all
563 * further open calls on the serial port will fail.
565 * There is a race condition if two processes open the same serial
566 * port. None of the processes will notice the exclusive ownership of
567 * the other process because ioctl() doesn't return an error code if
568 * the file descriptor is already marked as exclusive.
569 * This can be solved with flock(). It returns an error if the file
570 * descriptor is already locked by another process.
573 if (flock(port->fd, LOCK_EX | LOCK_NB) < 0)
574 RETURN_FAIL("flock() failed");
579 * Before Linux 3.8 ioctl(*, TIOCEXCL) was not implemented and could
580 * lead to EINVAL or ENOTTY.
581 * These errors aren't fatal and can be ignored.
583 if (ioctl(port->fd, TIOCEXCL) < 0 && errno != EINVAL && errno != ENOTTY)
584 RETURN_FAIL("ioctl() failed");
589 ret = get_config(port, &data, &config);
596 /* Set sane port settings. */
598 data.dcb.fBinary = TRUE;
599 data.dcb.fDsrSensitivity = FALSE;
600 data.dcb.fErrorChar = FALSE;
601 data.dcb.fNull = FALSE;
602 data.dcb.fAbortOnError = FALSE;
604 /* Turn off all fancy termios tricks, give us a raw channel. */
605 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
607 data.term.c_iflag &= ~IUCLC;
609 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
611 data.term.c_oflag &= ~OLCUC;
614 data.term.c_oflag &= ~NLDLY;
617 data.term.c_oflag &= ~CRDLY;
620 data.term.c_oflag &= ~TABDLY;
623 data.term.c_oflag &= ~BSDLY;
626 data.term.c_oflag &= ~VTDLY;
629 data.term.c_oflag &= ~FFDLY;
632 data.term.c_oflag &= ~OFILL;
634 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
635 data.term.c_cc[VMIN] = 0;
636 data.term.c_cc[VTIME] = 0;
638 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
639 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
643 if (ClearCommError(port->hdl, &errors, &status) == 0)
644 RETURN_FAIL("ClearCommError() failed");
647 ret = set_config(port, &data, &config);
657 SP_API enum sp_return sp_close(struct sp_port *port)
663 DEBUG_FMT("Closing port %s", port->name);
666 /* Returns non-zero upon success, 0 upon failure. */
667 if (CloseHandle(port->hdl) == 0)
668 RETURN_FAIL("Port CloseHandle() failed");
669 port->hdl = INVALID_HANDLE_VALUE;
671 /* Close event handles for overlapped structures. */
672 #define CLOSE_OVERLAPPED(ovl) do { \
673 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
674 CloseHandle(port->ovl.hEvent) == 0) \
675 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
677 CLOSE_OVERLAPPED(read_ovl);
678 CLOSE_OVERLAPPED(write_ovl);
679 CLOSE_OVERLAPPED(wait_ovl);
681 if (port->write_buf) {
682 free(port->write_buf);
683 port->write_buf = NULL;
686 /* Returns 0 upon success, -1 upon failure. */
687 if (close(port->fd) == -1)
688 RETURN_FAIL("close() failed");
695 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
697 TRACE("%p, 0x%x", port, buffers);
701 if (buffers > SP_BUF_BOTH)
702 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
704 const char *buffer_names[] = {"no", "input", "output", "both"};
706 DEBUG_FMT("Flushing %s buffers on port %s",
707 buffer_names[buffers], port->name);
711 if (buffers & SP_BUF_INPUT)
712 flags |= PURGE_RXCLEAR;
713 if (buffers & SP_BUF_OUTPUT)
714 flags |= PURGE_TXCLEAR;
716 /* Returns non-zero upon success, 0 upon failure. */
717 if (PurgeComm(port->hdl, flags) == 0)
718 RETURN_FAIL("PurgeComm() failed");
720 if (buffers & SP_BUF_INPUT)
721 TRY(restart_wait(port));
724 if (buffers == SP_BUF_BOTH)
726 else if (buffers == SP_BUF_INPUT)
728 else if (buffers == SP_BUF_OUTPUT)
731 /* Returns 0 upon success, -1 upon failure. */
732 if (tcflush(port->fd, flags) < 0)
733 RETURN_FAIL("tcflush() failed");
738 SP_API enum sp_return sp_drain(struct sp_port *port)
744 DEBUG_FMT("Draining port %s", port->name);
747 /* Returns non-zero upon success, 0 upon failure. */
748 if (FlushFileBuffers(port->hdl) == 0)
749 RETURN_FAIL("FlushFileBuffers() failed");
754 #if defined(__ANDROID__) && (__ANDROID_API__ < 21)
755 /* Android only has tcdrain from platform 21 onwards.
756 * On previous API versions, use the ioctl directly. */
758 result = ioctl(port->fd, TCSBRK, &arg);
760 result = tcdrain(port->fd);
763 if (errno == EINTR) {
764 DEBUG("tcdrain() was interrupted");
767 RETURN_FAIL("tcdrain() failed");
777 static enum sp_return await_write_completion(struct sp_port *port)
783 /* Wait for previous non-blocking write to complete, if any. */
785 DEBUG("Waiting for previous write to complete");
786 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
789 RETURN_FAIL("Previous write failed to complete");
790 DEBUG("Previous write completed");
797 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
798 size_t count, unsigned int timeout_ms)
800 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
805 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
808 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
809 count, port->name, timeout_ms);
811 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
818 DWORD remaining_ms, write_size, bytes_written;
819 size_t remaining_bytes, total_bytes_written = 0;
820 const uint8_t *write_ptr = (uint8_t *) buf;
822 struct timeout timeout;
824 timeout_start(&timeout, timeout_ms);
826 TRY(await_write_completion(port));
828 while (total_bytes_written < count) {
830 if (timeout_check(&timeout))
833 remaining_ms = timeout_remaining_ms(&timeout);
835 if (port->timeouts.WriteTotalTimeoutConstant != remaining_ms) {
836 port->timeouts.WriteTotalTimeoutConstant = remaining_ms;
837 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
838 RETURN_FAIL("SetCommTimeouts() failed");
841 /* Reduce write size if it exceeds the WriteFile limit. */
842 remaining_bytes = count - total_bytes_written;
843 if (remaining_bytes > WRITEFILE_MAX_SIZE)
844 write_size = WRITEFILE_MAX_SIZE;
846 write_size = (DWORD) remaining_bytes;
850 result = WriteFile(port->hdl, write_ptr, write_size, NULL, &port->write_ovl);
852 timeout_update(&timeout);
855 DEBUG("Write completed immediately");
856 bytes_written = write_size;
857 } else if (GetLastError() == ERROR_IO_PENDING) {
858 DEBUG("Waiting for write to complete");
859 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
860 if (GetLastError() == ERROR_SEM_TIMEOUT) {
861 DEBUG("Write timed out");
864 RETURN_FAIL("GetOverlappedResult() failed");
867 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, write_size);
869 RETURN_FAIL("WriteFile() failed");
872 write_ptr += bytes_written;
873 total_bytes_written += bytes_written;
876 RETURN_INT((int) total_bytes_written);
878 size_t bytes_written = 0;
879 unsigned char *ptr = (unsigned char *) buf;
880 struct timeout timeout;
884 timeout_start(&timeout, timeout_ms);
887 FD_SET(port->fd, &fds);
889 /* Loop until we have written the requested number of bytes. */
890 while (bytes_written < count) {
892 if (timeout_check(&timeout))
895 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
897 timeout_update(&timeout);
900 if (errno == EINTR) {
901 DEBUG("select() call was interrupted, repeating");
904 RETURN_FAIL("select() failed");
906 } else if (result == 0) {
907 /* Timeout has expired. */
912 result = write(port->fd, ptr, count - bytes_written);
916 /* This shouldn't happen because we did a select() first, but handle anyway. */
919 /* This is an actual failure. */
920 RETURN_FAIL("write() failed");
923 bytes_written += result;
927 if (bytes_written < count)
928 DEBUG("Write timed out");
930 RETURN_INT(bytes_written);
934 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
935 const void *buf, size_t count)
937 TRACE("%p, %p, %d", port, buf, count);
942 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
944 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
952 /* Check whether previous write is complete. */
954 if (HasOverlappedIoCompleted(&port->write_ovl)) {
955 DEBUG("Previous write completed");
958 DEBUG("Previous write not complete");
959 /* Can't take a new write until the previous one finishes. */
965 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
966 port->timeouts.WriteTotalTimeoutConstant = 0;
967 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
968 RETURN_FAIL("SetCommTimeouts() failed");
971 /* Reduce count if it exceeds the WriteFile limit. */
972 if (count > WRITEFILE_MAX_SIZE)
973 count = WRITEFILE_MAX_SIZE;
975 /* Copy data to our write buffer. */
976 buf_bytes = min(port->write_buf_size, count);
977 memcpy(port->write_buf, buf, buf_bytes);
979 /* Start asynchronous write. */
980 if (WriteFile(port->hdl, port->write_buf, (DWORD) buf_bytes, NULL, &port->write_ovl) == 0) {
981 if (GetLastError() == ERROR_IO_PENDING) {
982 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
983 DEBUG("Asynchronous write completed immediately");
985 DEBUG("Asynchronous write running");
987 /* Actual failure of some kind. */
988 RETURN_FAIL("WriteFile() failed");
992 DEBUG("All bytes written immediately");
994 RETURN_INT((int) buf_bytes);
996 /* Returns the number of bytes written, or -1 upon failure. */
997 ssize_t written = write(port->fd, buf, count);
1000 if (errno == EAGAIN)
1001 // Buffer is full, no bytes written.
1004 RETURN_FAIL("write() failed");
1006 RETURN_INT(written);
1012 /* Restart wait operation if buffer was emptied. */
1013 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1018 if (bytes_read == 0)
1021 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1022 RETURN_FAIL("ClearCommError() failed");
1024 if (comstat.cbInQue == 0)
1025 TRY(restart_wait(port));
1031 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1032 size_t count, unsigned int timeout_ms)
1034 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1039 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1042 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1043 count, port->name, timeout_ms);
1045 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1055 if (port->timeouts.ReadIntervalTimeout != 0 ||
1056 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1057 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1058 port->timeouts.ReadIntervalTimeout = 0;
1059 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1060 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1061 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1062 RETURN_FAIL("SetCommTimeouts() failed");
1066 if (ReadFile(port->hdl, buf, (DWORD) count, NULL, &port->read_ovl)) {
1067 DEBUG("Read completed immediately");
1068 bytes_read = (DWORD) count;
1069 } else if (GetLastError() == ERROR_IO_PENDING) {
1070 DEBUG("Waiting for read to complete");
1071 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1072 RETURN_FAIL("GetOverlappedResult() failed");
1073 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1075 RETURN_FAIL("ReadFile() failed");
1078 TRY(restart_wait_if_needed(port, bytes_read));
1080 RETURN_INT((int) bytes_read);
1083 size_t bytes_read = 0;
1084 unsigned char *ptr = (unsigned char *) buf;
1085 struct timeout timeout;
1089 timeout_start(&timeout, timeout_ms);
1092 FD_SET(port->fd, &fds);
1094 /* Loop until we have the requested number of bytes. */
1095 while (bytes_read < count) {
1097 if (timeout_check(&timeout))
1098 /* Timeout has expired. */
1101 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1103 timeout_update(&timeout);
1106 if (errno == EINTR) {
1107 DEBUG("select() call was interrupted, repeating");
1110 RETURN_FAIL("select() failed");
1112 } else if (result == 0) {
1113 /* Timeout has expired. */
1118 result = read(port->fd, ptr, count - bytes_read);
1121 if (errno == EAGAIN)
1123 * This shouldn't happen because we did a
1124 * select() first, but handle anyway.
1128 /* This is an actual failure. */
1129 RETURN_FAIL("read() failed");
1132 bytes_read += result;
1136 if (bytes_read < count)
1137 DEBUG("Read timed out");
1139 RETURN_INT(bytes_read);
1143 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1144 size_t count, unsigned int timeout_ms)
1146 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1151 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1154 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1157 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1158 count, port->name, timeout_ms);
1160 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1164 DWORD bytes_read = 0;
1166 /* If timeout_ms == 0, set maximum timeout. */
1167 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1170 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1171 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1172 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1173 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1174 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1175 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1176 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1177 RETURN_FAIL("SetCommTimeouts() failed");
1180 /* Loop until we have at least one byte, or timeout is reached. */
1181 while (bytes_read == 0) {
1183 if (ReadFile(port->hdl, buf, (DWORD) count, &bytes_read, &port->read_ovl)) {
1184 DEBUG("Read completed immediately");
1185 } else if (GetLastError() == ERROR_IO_PENDING) {
1186 DEBUG("Waiting for read to complete");
1187 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1188 RETURN_FAIL("GetOverlappedResult() failed");
1189 if (bytes_read > 0) {
1190 DEBUG("Read completed");
1191 } else if (timeout_ms > 0) {
1192 DEBUG("Read timed out");
1195 DEBUG("Restarting read");
1198 RETURN_FAIL("ReadFile() failed");
1202 TRY(restart_wait_if_needed(port, bytes_read));
1204 RETURN_INT(bytes_read);
1207 size_t bytes_read = 0;
1208 struct timeout timeout;
1212 timeout_start(&timeout, timeout_ms);
1215 FD_SET(port->fd, &fds);
1217 /* Loop until we have at least one byte, or timeout is reached. */
1218 while (bytes_read == 0) {
1220 if (timeout_check(&timeout))
1221 /* Timeout has expired. */
1224 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1226 timeout_update(&timeout);
1229 if (errno == EINTR) {
1230 DEBUG("select() call was interrupted, repeating");
1233 RETURN_FAIL("select() failed");
1235 } else if (result == 0) {
1236 /* Timeout has expired. */
1241 result = read(port->fd, buf, count);
1244 if (errno == EAGAIN)
1245 /* This shouldn't happen because we did a select() first, but handle anyway. */
1248 /* This is an actual failure. */
1249 RETURN_FAIL("read() failed");
1252 bytes_read = result;
1255 if (bytes_read == 0)
1256 DEBUG("Read timed out");
1258 RETURN_INT(bytes_read);
1262 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1265 TRACE("%p, %p, %d", port, buf, count);
1270 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1272 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1278 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1279 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1280 port->timeouts.ReadTotalTimeoutConstant != 0) {
1281 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1282 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1283 port->timeouts.ReadTotalTimeoutConstant = 0;
1284 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1285 RETURN_FAIL("SetCommTimeouts() failed");
1289 if (ReadFile(port->hdl, buf, (DWORD) count, NULL, &port->read_ovl) == 0)
1290 if (GetLastError() != ERROR_IO_PENDING)
1291 RETURN_FAIL("ReadFile() failed");
1293 /* Get number of bytes read. */
1294 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1295 RETURN_FAIL("GetOverlappedResult() failed");
1297 TRY(restart_wait_if_needed(port, bytes_read));
1299 RETURN_INT(bytes_read);
1303 /* Returns the number of bytes read, or -1 upon failure. */
1304 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1305 if (errno == EAGAIN)
1306 /* No bytes available. */
1309 /* This is an actual failure. */
1310 RETURN_FAIL("read() failed");
1312 RETURN_INT(bytes_read);
1316 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1322 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1328 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1329 RETURN_FAIL("ClearCommError() failed");
1330 RETURN_INT(comstat.cbInQue);
1333 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1334 RETURN_FAIL("TIOCINQ ioctl failed");
1335 RETURN_INT(bytes_waiting);
1339 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1344 /* TIOCOUTQ is not defined in Cygwin headers */
1345 RETURN_ERROR(SP_ERR_SUPP,
1346 "Getting output bytes waiting is not supported on Cygwin");
1350 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1356 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1357 RETURN_FAIL("ClearCommError() failed");
1358 RETURN_INT(comstat.cbOutQue);
1361 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1362 RETURN_FAIL("TIOCOUTQ ioctl failed");
1363 RETURN_INT(bytes_waiting);
1368 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1370 struct sp_event_set *result;
1372 TRACE("%p", result_ptr);
1375 RETURN_ERROR(SP_ERR_ARG, "Null result");
1379 if (!(result = malloc(sizeof(struct sp_event_set))))
1380 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1382 memset(result, 0, sizeof(struct sp_event_set));
1384 *result_ptr = result;
1389 static enum sp_return add_handle(struct sp_event_set *event_set,
1390 event_handle handle, enum sp_event mask)
1393 enum sp_event *new_masks;
1395 TRACE("%p, %d, %d", event_set, handle, mask);
1397 if (!(new_handles = realloc(event_set->handles,
1398 sizeof(event_handle) * (event_set->count + 1))))
1399 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1401 event_set->handles = new_handles;
1403 if (!(new_masks = realloc(event_set->masks,
1404 sizeof(enum sp_event) * (event_set->count + 1))))
1405 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1407 event_set->masks = new_masks;
1409 ((event_handle *) event_set->handles)[event_set->count] = handle;
1410 event_set->masks[event_set->count] = mask;
1417 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1418 const struct sp_port *port, enum sp_event mask)
1420 TRACE("%p, %p, %d", event_set, port, mask);
1423 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1426 RETURN_ERROR(SP_ERR_ARG, "Null port");
1428 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1429 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1435 enum sp_event handle_mask;
1436 if ((handle_mask = mask & SP_EVENT_TX_READY))
1437 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1438 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1439 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1441 TRY(add_handle(event_set, port->fd, mask));
1447 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1449 TRACE("%p", event_set);
1452 DEBUG("Null event set");
1456 DEBUG("Freeing event set");
1458 if (event_set->handles)
1459 free(event_set->handles);
1460 if (event_set->masks)
1461 free(event_set->masks);
1468 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1469 unsigned int timeout_ms)
1471 TRACE("%p, %d", event_set, timeout_ms);
1474 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1477 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1478 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1479 RETURN_FAIL("WaitForMultipleObjects() failed");
1483 struct timeout timeout;
1486 struct pollfd *pollfds;
1489 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1490 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1492 for (i = 0; i < event_set->count; i++) {
1493 pollfds[i].fd = ((int *)event_set->handles)[i];
1494 pollfds[i].events = 0;
1495 pollfds[i].revents = 0;
1496 if (event_set->masks[i] & SP_EVENT_RX_READY)
1497 pollfds[i].events |= POLLIN;
1498 if (event_set->masks[i] & SP_EVENT_TX_READY)
1499 pollfds[i].events |= POLLOUT;
1500 if (event_set->masks[i] & SP_EVENT_ERROR)
1501 pollfds[i].events |= POLLERR;
1504 timeout_start(&timeout, timeout_ms);
1505 timeout_limit(&timeout, INT_MAX);
1507 /* Loop until an event occurs. */
1510 if (timeout_check(&timeout)) {
1511 DEBUG("Wait timed out");
1515 poll_timeout = (int) timeout_remaining_ms(&timeout);
1516 if (poll_timeout == 0)
1519 result = poll(pollfds, event_set->count, poll_timeout);
1521 timeout_update(&timeout);
1524 if (errno == EINTR) {
1525 DEBUG("poll() call was interrupted, repeating");
1529 RETURN_FAIL("poll() failed");
1531 } else if (result == 0) {
1532 DEBUG("poll() timed out");
1533 if (!timeout.overflow)
1536 DEBUG("poll() completed");
1546 #ifdef USE_TERMIOS_SPEED
1547 static enum sp_return get_baudrate(int fd, int *baudrate)
1551 TRACE("%d, %p", fd, baudrate);
1553 DEBUG("Getting baud rate");
1555 if (!(data = malloc(get_termios_size())))
1556 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1558 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1560 RETURN_FAIL("Getting termios failed");
1563 *baudrate = get_termios_speed(data);
1570 static enum sp_return set_baudrate(int fd, int baudrate)
1574 TRACE("%d, %d", fd, baudrate);
1576 DEBUG("Getting baud rate");
1578 if (!(data = malloc(get_termios_size())))
1579 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1581 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1583 RETURN_FAIL("Getting termios failed");
1586 DEBUG("Setting baud rate");
1588 set_termios_speed(data, baudrate);
1590 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1592 RETURN_FAIL("Setting termios failed");
1599 #endif /* USE_TERMIOS_SPEED */
1602 static enum sp_return get_flow(int fd, struct port_data *data)
1606 TRACE("%d, %p", fd, data);
1608 DEBUG("Getting advanced flow control");
1610 if (!(termx = malloc(get_termiox_size())))
1611 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1613 if (ioctl(fd, TCGETX, termx) < 0) {
1615 RETURN_FAIL("Getting termiox failed");
1618 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1619 &data->dtr_flow, &data->dsr_flow);
1626 static enum sp_return set_flow(int fd, struct port_data *data)
1630 TRACE("%d, %p", fd, data);
1632 DEBUG("Getting advanced flow control");
1634 if (!(termx = malloc(get_termiox_size())))
1635 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1637 if (ioctl(fd, TCGETX, termx) < 0) {
1639 RETURN_FAIL("Getting termiox failed");
1642 DEBUG("Setting advanced flow control");
1644 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1645 data->dtr_flow, data->dsr_flow);
1647 if (ioctl(fd, TCSETX, termx) < 0) {
1649 RETURN_FAIL("Setting termiox failed");
1656 #endif /* USE_TERMIOX */
1658 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1659 struct sp_port_config *config)
1663 TRACE("%p, %p, %p", port, data, config);
1665 DEBUG_FMT("Getting configuration for port %s", port->name);
1668 if (!GetCommState(port->hdl, &data->dcb))
1669 RETURN_FAIL("GetCommState() failed");
1671 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1672 if (data->dcb.BaudRate == std_baudrates[i].index) {
1673 config->baudrate = std_baudrates[i].value;
1678 if (i == NUM_STD_BAUDRATES)
1679 /* BaudRate field can be either an index or a custom baud rate. */
1680 config->baudrate = data->dcb.BaudRate;
1682 config->bits = data->dcb.ByteSize;
1684 switch (data->dcb.Parity) {
1686 config->parity = SP_PARITY_NONE;
1689 config->parity = SP_PARITY_ODD;
1692 config->parity = SP_PARITY_EVEN;
1695 config->parity = SP_PARITY_MARK;
1698 config->parity = SP_PARITY_SPACE;
1701 config->parity = -1;
1704 switch (data->dcb.StopBits) {
1706 config->stopbits = 1;
1709 config->stopbits = 2;
1712 config->stopbits = -1;
1715 switch (data->dcb.fRtsControl) {
1716 case RTS_CONTROL_DISABLE:
1717 config->rts = SP_RTS_OFF;
1719 case RTS_CONTROL_ENABLE:
1720 config->rts = SP_RTS_ON;
1722 case RTS_CONTROL_HANDSHAKE:
1723 config->rts = SP_RTS_FLOW_CONTROL;
1729 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1731 switch (data->dcb.fDtrControl) {
1732 case DTR_CONTROL_DISABLE:
1733 config->dtr = SP_DTR_OFF;
1735 case DTR_CONTROL_ENABLE:
1736 config->dtr = SP_DTR_ON;
1738 case DTR_CONTROL_HANDSHAKE:
1739 config->dtr = SP_DTR_FLOW_CONTROL;
1745 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1747 if (data->dcb.fInX) {
1748 if (data->dcb.fOutX)
1749 config->xon_xoff = SP_XONXOFF_INOUT;
1751 config->xon_xoff = SP_XONXOFF_IN;
1753 if (data->dcb.fOutX)
1754 config->xon_xoff = SP_XONXOFF_OUT;
1756 config->xon_xoff = SP_XONXOFF_DISABLED;
1761 if (tcgetattr(port->fd, &data->term) < 0)
1762 RETURN_FAIL("tcgetattr() failed");
1764 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1765 RETURN_FAIL("TIOCMGET ioctl failed");
1768 int ret = get_flow(port->fd, data);
1770 if (ret == SP_ERR_FAIL && errno == EINVAL)
1771 data->termiox_supported = 0;
1773 RETURN_CODEVAL(ret);
1775 data->termiox_supported = 1;
1777 data->termiox_supported = 0;
1780 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1781 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1782 config->baudrate = std_baudrates[i].value;
1787 if (i == NUM_STD_BAUDRATES) {
1789 config->baudrate = (int)data->term.c_ispeed;
1790 #elif defined(USE_TERMIOS_SPEED)
1791 TRY(get_baudrate(port->fd, &config->baudrate));
1793 config->baudrate = -1;
1797 switch (data->term.c_cflag & CSIZE) {
1814 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1815 config->parity = SP_PARITY_NONE;
1816 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1817 config->parity = -1;
1819 else if (data->term.c_cflag & CMSPAR)
1820 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1823 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1825 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1827 if (data->term.c_cflag & CRTSCTS) {
1828 config->rts = SP_RTS_FLOW_CONTROL;
1829 config->cts = SP_CTS_FLOW_CONTROL;
1831 if (data->termiox_supported && data->rts_flow)
1832 config->rts = SP_RTS_FLOW_CONTROL;
1834 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1836 config->cts = (data->termiox_supported && data->cts_flow) ?
1837 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1840 if (data->termiox_supported && data->dtr_flow)
1841 config->dtr = SP_DTR_FLOW_CONTROL;
1843 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1845 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1846 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1848 if (data->term.c_iflag & IXOFF) {
1849 if (data->term.c_iflag & IXON)
1850 config->xon_xoff = SP_XONXOFF_INOUT;
1852 config->xon_xoff = SP_XONXOFF_IN;
1854 if (data->term.c_iflag & IXON)
1855 config->xon_xoff = SP_XONXOFF_OUT;
1857 config->xon_xoff = SP_XONXOFF_DISABLED;
1864 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1865 const struct sp_port_config *config)
1869 BAUD_TYPE baud_nonstd;
1873 #ifdef USE_TERMIOS_SPEED
1874 int baud_nonstd = 0;
1877 TRACE("%p, %p, %p", port, data, config);
1879 DEBUG_FMT("Setting configuration for port %s", port->name);
1884 TRY(await_write_completion(port));
1886 if (config->baudrate >= 0) {
1887 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1888 if (config->baudrate == std_baudrates[i].value) {
1889 data->dcb.BaudRate = std_baudrates[i].index;
1894 if (i == NUM_STD_BAUDRATES)
1895 data->dcb.BaudRate = config->baudrate;
1897 /* Allocate write buffer for 50ms of data at baud rate. */
1898 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1899 new_buf = realloc(port->write_buf, port->write_buf_size);
1901 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1902 port->write_buf = new_buf;
1905 if (config->bits >= 0)
1906 data->dcb.ByteSize = config->bits;
1908 if (config->parity >= 0) {
1909 switch (config->parity) {
1910 case SP_PARITY_NONE:
1911 data->dcb.Parity = NOPARITY;
1914 data->dcb.Parity = ODDPARITY;
1916 case SP_PARITY_EVEN:
1917 data->dcb.Parity = EVENPARITY;
1919 case SP_PARITY_MARK:
1920 data->dcb.Parity = MARKPARITY;
1922 case SP_PARITY_SPACE:
1923 data->dcb.Parity = SPACEPARITY;
1926 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1930 if (config->stopbits >= 0) {
1931 switch (config->stopbits) {
1932 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1934 data->dcb.StopBits = ONESTOPBIT;
1937 data->dcb.StopBits = TWOSTOPBITS;
1940 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1944 if (config->rts >= 0) {
1945 switch (config->rts) {
1947 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1950 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1952 case SP_RTS_FLOW_CONTROL:
1953 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1956 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1960 if (config->cts >= 0) {
1961 switch (config->cts) {
1963 data->dcb.fOutxCtsFlow = FALSE;
1965 case SP_CTS_FLOW_CONTROL:
1966 data->dcb.fOutxCtsFlow = TRUE;
1969 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1973 if (config->dtr >= 0) {
1974 switch (config->dtr) {
1976 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1979 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1981 case SP_DTR_FLOW_CONTROL:
1982 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1985 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1989 if (config->dsr >= 0) {
1990 switch (config->dsr) {
1992 data->dcb.fOutxDsrFlow = FALSE;
1994 case SP_DSR_FLOW_CONTROL:
1995 data->dcb.fOutxDsrFlow = TRUE;
1998 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2002 if (config->xon_xoff >= 0) {
2003 switch (config->xon_xoff) {
2004 case SP_XONXOFF_DISABLED:
2005 data->dcb.fInX = FALSE;
2006 data->dcb.fOutX = FALSE;
2009 data->dcb.fInX = TRUE;
2010 data->dcb.fOutX = FALSE;
2012 case SP_XONXOFF_OUT:
2013 data->dcb.fInX = FALSE;
2014 data->dcb.fOutX = TRUE;
2016 case SP_XONXOFF_INOUT:
2017 data->dcb.fInX = TRUE;
2018 data->dcb.fOutX = TRUE;
2021 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2025 if (!SetCommState(port->hdl, &data->dcb))
2026 RETURN_FAIL("SetCommState() failed");
2032 if (config->baudrate >= 0) {
2033 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2034 if (config->baudrate == std_baudrates[i].value) {
2035 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2036 RETURN_FAIL("cfsetospeed() failed");
2038 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2039 RETURN_FAIL("cfsetispeed() failed");
2044 /* Non-standard baud rate */
2045 if (i == NUM_STD_BAUDRATES) {
2047 /* Set "dummy" baud rate. */
2048 if (cfsetspeed(&data->term, B9600) < 0)
2049 RETURN_FAIL("cfsetspeed() failed");
2050 baud_nonstd = config->baudrate;
2051 #elif defined(USE_TERMIOS_SPEED)
2054 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2059 if (config->bits >= 0) {
2060 data->term.c_cflag &= ~CSIZE;
2061 switch (config->bits) {
2063 data->term.c_cflag |= CS8;
2066 data->term.c_cflag |= CS7;
2069 data->term.c_cflag |= CS6;
2072 data->term.c_cflag |= CS5;
2075 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2079 if (config->parity >= 0) {
2080 data->term.c_iflag &= ~IGNPAR;
2081 data->term.c_cflag &= ~(PARENB | PARODD);
2083 data->term.c_cflag &= ~CMSPAR;
2085 switch (config->parity) {
2086 case SP_PARITY_NONE:
2087 data->term.c_iflag |= IGNPAR;
2089 case SP_PARITY_EVEN:
2090 data->term.c_cflag |= PARENB;
2093 data->term.c_cflag |= PARENB | PARODD;
2096 case SP_PARITY_MARK:
2097 data->term.c_cflag |= PARENB | PARODD;
2098 data->term.c_cflag |= CMSPAR;
2100 case SP_PARITY_SPACE:
2101 data->term.c_cflag |= PARENB;
2102 data->term.c_cflag |= CMSPAR;
2105 case SP_PARITY_MARK:
2106 case SP_PARITY_SPACE:
2107 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2110 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2114 if (config->stopbits >= 0) {
2115 data->term.c_cflag &= ~CSTOPB;
2116 switch (config->stopbits) {
2118 data->term.c_cflag &= ~CSTOPB;
2121 data->term.c_cflag |= CSTOPB;
2124 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2128 if (config->rts >= 0 || config->cts >= 0) {
2129 if (data->termiox_supported) {
2130 data->rts_flow = data->cts_flow = 0;
2131 switch (config->rts) {
2134 controlbits = TIOCM_RTS;
2135 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2136 RETURN_FAIL("Setting RTS signal level failed");
2138 case SP_RTS_FLOW_CONTROL:
2144 if (config->cts == SP_CTS_FLOW_CONTROL)
2147 if (data->rts_flow && data->cts_flow)
2148 data->term.c_iflag |= CRTSCTS;
2150 data->term.c_iflag &= ~CRTSCTS;
2152 /* Asymmetric use of RTS/CTS not supported. */
2153 if (data->term.c_iflag & CRTSCTS) {
2154 /* Flow control can only be disabled for both RTS & CTS together. */
2155 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2156 if (config->cts != SP_CTS_IGNORE)
2157 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2159 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2160 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2161 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2164 /* Flow control can only be enabled for both RTS & CTS together. */
2165 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2166 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2167 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2170 if (config->rts >= 0) {
2171 if (config->rts == SP_RTS_FLOW_CONTROL) {
2172 data->term.c_iflag |= CRTSCTS;
2174 controlbits = TIOCM_RTS;
2175 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2177 RETURN_FAIL("Setting RTS signal level failed");
2183 if (config->dtr >= 0 || config->dsr >= 0) {
2184 if (data->termiox_supported) {
2185 data->dtr_flow = data->dsr_flow = 0;
2186 switch (config->dtr) {
2189 controlbits = TIOCM_DTR;
2190 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2191 RETURN_FAIL("Setting DTR signal level failed");
2193 case SP_DTR_FLOW_CONTROL:
2199 if (config->dsr == SP_DSR_FLOW_CONTROL)
2202 /* DTR/DSR flow control not supported. */
2203 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2204 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2206 if (config->dtr >= 0) {
2207 controlbits = TIOCM_DTR;
2208 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2210 RETURN_FAIL("Setting DTR signal level failed");
2215 if (config->xon_xoff >= 0) {
2216 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2217 switch (config->xon_xoff) {
2218 case SP_XONXOFF_DISABLED:
2221 data->term.c_iflag |= IXOFF;
2223 case SP_XONXOFF_OUT:
2224 data->term.c_iflag |= IXON | IXANY;
2226 case SP_XONXOFF_INOUT:
2227 data->term.c_iflag |= IXON | IXOFF | IXANY;
2230 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2234 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2235 RETURN_FAIL("tcsetattr() failed");
2238 if (baud_nonstd != B0) {
2239 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2240 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2242 * Set baud rates in data->term to correct, but incompatible
2243 * with tcsetattr() value, same as delivered by tcgetattr().
2245 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2246 RETURN_FAIL("cfsetspeed() failed");
2248 #elif defined(__linux__)
2249 #ifdef USE_TERMIOS_SPEED
2251 TRY(set_baudrate(port->fd, config->baudrate));
2254 if (data->termiox_supported)
2255 TRY(set_flow(port->fd, data));
2259 #endif /* !_WIN32 */
2264 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2266 struct sp_port_config *config;
2268 TRACE("%p", config_ptr);
2271 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2275 if (!(config = malloc(sizeof(struct sp_port_config))))
2276 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2278 config->baudrate = -1;
2280 config->parity = -1;
2281 config->stopbits = -1;
2287 *config_ptr = config;
2292 SP_API void sp_free_config(struct sp_port_config *config)
2294 TRACE("%p", config);
2297 DEBUG("Null config");
2304 SP_API enum sp_return sp_get_config(struct sp_port *port,
2305 struct sp_port_config *config)
2307 struct port_data data;
2309 TRACE("%p, %p", port, config);
2314 RETURN_ERROR(SP_ERR_ARG, "Null config");
2316 TRY(get_config(port, &data, config));
2321 SP_API enum sp_return sp_set_config(struct sp_port *port,
2322 const struct sp_port_config *config)
2324 struct port_data data;
2325 struct sp_port_config prev_config;
2327 TRACE("%p, %p", port, config);
2332 RETURN_ERROR(SP_ERR_ARG, "Null config");
2334 TRY(get_config(port, &data, &prev_config));
2335 TRY(set_config(port, &data, config));
2340 #define CREATE_ACCESSORS(x, type) \
2341 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2342 struct port_data data; \
2343 struct sp_port_config config; \
2344 TRACE("%p, %d", port, x); \
2345 CHECK_OPEN_PORT(); \
2346 TRY(get_config(port, &data, &config)); \
2348 TRY(set_config(port, &data, &config)); \
2351 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2353 TRACE("%p, %p", config, x); \
2355 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2357 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2361 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2363 TRACE("%p, %d", config, x); \
2365 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2370 CREATE_ACCESSORS(baudrate, int)
2371 CREATE_ACCESSORS(bits, int)
2372 CREATE_ACCESSORS(parity, enum sp_parity)
2373 CREATE_ACCESSORS(stopbits, int)
2374 CREATE_ACCESSORS(rts, enum sp_rts)
2375 CREATE_ACCESSORS(cts, enum sp_cts)
2376 CREATE_ACCESSORS(dtr, enum sp_dtr)
2377 CREATE_ACCESSORS(dsr, enum sp_dsr)
2378 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2380 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2381 enum sp_flowcontrol flowcontrol)
2384 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2386 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2387 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2389 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2390 config->xon_xoff = SP_XONXOFF_INOUT;
2392 config->xon_xoff = SP_XONXOFF_DISABLED;
2394 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2395 config->rts = SP_RTS_FLOW_CONTROL;
2396 config->cts = SP_CTS_FLOW_CONTROL;
2398 if (config->rts == SP_RTS_FLOW_CONTROL)
2399 config->rts = SP_RTS_ON;
2400 config->cts = SP_CTS_IGNORE;
2403 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2404 config->dtr = SP_DTR_FLOW_CONTROL;
2405 config->dsr = SP_DSR_FLOW_CONTROL;
2407 if (config->dtr == SP_DTR_FLOW_CONTROL)
2408 config->dtr = SP_DTR_ON;
2409 config->dsr = SP_DSR_IGNORE;
2415 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2416 enum sp_flowcontrol flowcontrol)
2418 struct port_data data;
2419 struct sp_port_config config;
2421 TRACE("%p, %d", port, flowcontrol);
2425 TRY(get_config(port, &data, &config));
2427 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2429 TRY(set_config(port, &data, &config));
2434 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2435 enum sp_signal *signals)
2437 TRACE("%p, %p", port, signals);
2442 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2444 DEBUG_FMT("Getting control signals for port %s", port->name);
2449 if (GetCommModemStatus(port->hdl, &bits) == 0)
2450 RETURN_FAIL("GetCommModemStatus() failed");
2451 if (bits & MS_CTS_ON)
2452 *signals |= SP_SIG_CTS;
2453 if (bits & MS_DSR_ON)
2454 *signals |= SP_SIG_DSR;
2455 if (bits & MS_RLSD_ON)
2456 *signals |= SP_SIG_DCD;
2457 if (bits & MS_RING_ON)
2458 *signals |= SP_SIG_RI;
2461 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2462 RETURN_FAIL("TIOCMGET ioctl failed");
2463 if (bits & TIOCM_CTS)
2464 *signals |= SP_SIG_CTS;
2465 if (bits & TIOCM_DSR)
2466 *signals |= SP_SIG_DSR;
2467 if (bits & TIOCM_CAR)
2468 *signals |= SP_SIG_DCD;
2469 if (bits & TIOCM_RNG)
2470 *signals |= SP_SIG_RI;
2475 SP_API enum sp_return sp_start_break(struct sp_port *port)
2481 if (SetCommBreak(port->hdl) == 0)
2482 RETURN_FAIL("SetCommBreak() failed");
2484 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2485 RETURN_FAIL("TIOCSBRK ioctl failed");
2491 SP_API enum sp_return sp_end_break(struct sp_port *port)
2497 if (ClearCommBreak(port->hdl) == 0)
2498 RETURN_FAIL("ClearCommBreak() failed");
2500 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2501 RETURN_FAIL("TIOCCBRK ioctl failed");
2507 SP_API int sp_last_error_code(void)
2511 RETURN_INT(GetLastError());
2517 SP_API char *sp_last_error_message(void)
2523 DWORD error = GetLastError();
2525 DWORD length = FormatMessageA(
2526 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2527 FORMAT_MESSAGE_FROM_SYSTEM |
2528 FORMAT_MESSAGE_IGNORE_INSERTS,
2531 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2535 if (length >= 2 && message[length - 2] == '\r')
2536 message[length - 2] = '\0';
2538 RETURN_STRING(message);
2540 RETURN_STRING(strerror(errno));
2544 SP_API void sp_free_error_message(char *message)
2546 TRACE("%s", message);
2557 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2559 TRACE("%p", handler);
2561 sp_debug_handler = handler;
2566 SP_API void sp_default_debug_handler(const char *format, ...)
2569 va_start(args, format);
2570 if (getenv("LIBSERIALPORT_DEBUG")) {
2571 fputs("sp: ", stderr);
2572 vfprintf(stderr, format, args);
2577 SP_API int sp_get_major_package_version(void)
2579 return SP_PACKAGE_VERSION_MAJOR;
2582 SP_API int sp_get_minor_package_version(void)
2584 return SP_PACKAGE_VERSION_MINOR;
2587 SP_API int sp_get_micro_package_version(void)
2589 return SP_PACKAGE_VERSION_MICRO;
2592 SP_API const char *sp_get_package_version_string(void)
2594 return SP_PACKAGE_VERSION_STRING;
2597 SP_API int sp_get_current_lib_version(void)
2599 return SP_LIB_VERSION_CURRENT;
2602 SP_API int sp_get_revision_lib_version(void)
2604 return SP_LIB_VERSION_REVISION;
2607 SP_API int sp_get_age_lib_version(void)
2609 return SP_LIB_VERSION_AGE;
2612 SP_API const char *sp_get_lib_version_string(void)
2614 return SP_LIB_VERSION_STRING;