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)
158 RETURN_INT(port ? port->transport : SP_TRANSPORT_NATIVE);
161 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
162 int *usb_bus,int *usb_address)
167 RETURN_ERROR(SP_ERR_ARG, "Null port");
168 if (port->transport != SP_TRANSPORT_USB)
169 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
170 if (port->usb_bus < 0 || port->usb_address < 0)
171 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
174 *usb_bus = port->usb_bus;
176 *usb_address = port->usb_address;
181 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
182 int *usb_vid, int *usb_pid)
187 RETURN_ERROR(SP_ERR_ARG, "Null port");
188 if (port->transport != SP_TRANSPORT_USB)
189 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
190 if (port->usb_vid < 0 || port->usb_pid < 0)
191 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
194 *usb_vid = port->usb_vid;
196 *usb_pid = port->usb_pid;
201 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
205 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
208 RETURN_STRING(port->usb_manufacturer);
211 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
215 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
218 RETURN_STRING(port->usb_product);
221 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
225 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
228 RETURN_STRING(port->usb_serial);
231 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
235 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
236 || !port->bluetooth_address)
239 RETURN_STRING(port->bluetooth_address);
242 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
245 TRACE("%p, %p", port, result_ptr);
248 RETURN_ERROR(SP_ERR_ARG, "Null port");
250 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
253 HANDLE *handle_ptr = result_ptr;
254 *handle_ptr = port->hdl;
256 int *fd_ptr = result_ptr;
263 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
264 struct sp_port **copy_ptr)
266 TRACE("%p, %p", port, copy_ptr);
269 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
274 RETURN_ERROR(SP_ERR_ARG, "Null port");
277 RETURN_ERROR(SP_ERR_ARG, "Null port name");
279 DEBUG("Copying port structure");
281 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
284 SP_API void sp_free_port(struct sp_port *port)
293 DEBUG("Freeing port structure");
297 if (port->description)
298 free(port->description);
299 if (port->usb_manufacturer)
300 free(port->usb_manufacturer);
301 if (port->usb_product)
302 free(port->usb_product);
303 if (port->usb_serial)
304 free(port->usb_serial);
305 if (port->bluetooth_address)
306 free(port->bluetooth_address);
309 free(port->usb_path);
311 free(port->write_buf);
319 SP_PRIV struct sp_port **list_append(struct sp_port **list,
320 const char *portname)
325 for (count = 0; list[count]; count++)
327 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
330 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
332 list[count + 1] = NULL;
336 sp_free_port_list(list);
340 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
342 #ifndef NO_ENUMERATION
343 struct sp_port **list;
347 TRACE("%p", list_ptr);
350 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
354 #ifdef NO_ENUMERATION
355 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
357 DEBUG("Enumerating ports");
359 if (!(list = malloc(sizeof(struct sp_port *))))
360 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
364 ret = list_ports(&list);
369 sp_free_port_list(list);
377 SP_API void sp_free_port_list(struct sp_port **list)
388 DEBUG("Freeing port list");
390 for (i = 0; list[i]; i++)
391 sp_free_port(list[i]);
397 #define CHECK_PORT() do { \
399 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
401 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
404 #define CHECK_PORT_HANDLE() do { \
405 if (port->hdl == INVALID_HANDLE_VALUE) \
406 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
409 #define CHECK_PORT_HANDLE() do { \
411 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
414 #define CHECK_OPEN_PORT() do { \
416 CHECK_PORT_HANDLE(); \
420 /** To be called after port receive buffer is emptied. */
421 static enum sp_return restart_wait(struct sp_port *port)
425 if (port->wait_running) {
426 /* Check status of running wait operation. */
427 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
428 &wait_result, FALSE)) {
429 DEBUG("Previous wait completed");
430 port->wait_running = FALSE;
431 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
432 DEBUG("Previous wait still running");
435 RETURN_FAIL("GetOverlappedResult() failed");
439 if (!port->wait_running) {
440 /* Start new wait operation. */
441 if (WaitCommEvent(port->hdl, &port->events,
443 DEBUG("New wait returned, events already pending");
444 } else if (GetLastError() == ERROR_IO_PENDING) {
445 DEBUG("New wait running in background");
446 port->wait_running = TRUE;
448 RETURN_FAIL("WaitCommEvent() failed");
456 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
458 struct port_data data;
459 struct sp_port_config config;
462 TRACE("%p, 0x%x", port, flags);
466 if (flags > SP_MODE_READ_WRITE)
467 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
469 DEBUG_FMT("Opening port %s", port->name);
472 DWORD desired_access = 0, flags_and_attributes = 0, errors;
473 char *escaped_port_name;
476 /* Prefix port name with '\\.\' to work with ports above COM9. */
477 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
478 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
479 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
481 /* Map 'flags' to the OS-specific settings. */
482 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
483 if (flags & SP_MODE_READ)
484 desired_access |= GENERIC_READ;
485 if (flags & SP_MODE_WRITE)
486 desired_access |= GENERIC_WRITE;
488 port->hdl = CreateFileA(escaped_port_name, desired_access, 0, 0,
489 OPEN_EXISTING, flags_and_attributes, 0);
491 free(escaped_port_name);
493 if (port->hdl == INVALID_HANDLE_VALUE)
494 RETURN_FAIL("Port CreateFile() failed");
496 /* All timeouts initially disabled. */
497 port->timeouts.ReadIntervalTimeout = 0;
498 port->timeouts.ReadTotalTimeoutMultiplier = 0;
499 port->timeouts.ReadTotalTimeoutConstant = 0;
500 port->timeouts.WriteTotalTimeoutMultiplier = 0;
501 port->timeouts.WriteTotalTimeoutConstant = 0;
503 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
505 RETURN_FAIL("SetCommTimeouts() failed");
508 /* Prepare OVERLAPPED structures. */
509 #define INIT_OVERLAPPED(ovl) do { \
510 memset(&port->ovl, 0, sizeof(port->ovl)); \
511 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
512 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
513 == INVALID_HANDLE_VALUE) { \
515 RETURN_FAIL(#ovl "CreateEvent() failed"); \
519 INIT_OVERLAPPED(read_ovl);
520 INIT_OVERLAPPED(write_ovl);
521 INIT_OVERLAPPED(wait_ovl);
523 /* Set event mask for RX and error events. */
524 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
526 RETURN_FAIL("SetCommMask() failed");
529 port->writing = FALSE;
530 port->wait_running = FALSE;
532 ret = restart_wait(port);
539 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
541 /* Map 'flags' to the OS-specific settings. */
542 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
543 flags_local |= O_RDWR;
544 else if (flags & SP_MODE_READ)
545 flags_local |= O_RDONLY;
546 else if (flags & SP_MODE_WRITE)
547 flags_local |= O_WRONLY;
549 if ((port->fd = open(port->name, flags_local)) < 0)
550 RETURN_FAIL("open() failed");
553 * On POSIX in the default case the file descriptor of a serial port
554 * is not opened exclusively. Therefore the settings of a port are
555 * overwritten if the serial port is opened a second time. Windows
556 * opens all serial ports exclusively.
557 * So the idea is to open the serial ports alike in the exclusive mode.
559 * ioctl(*, TIOCEXCL) defines the file descriptor as exclusive. So all
560 * further open calls on the serial port will fail.
562 * There is a race condition if two processes open the same serial
563 * port. None of the processes will notice the exclusive ownership of
564 * the other process because ioctl() doesn't return an error code if
565 * the file descriptor is already marked as exclusive.
566 * This can be solved with flock(). It returns an error if the file
567 * descriptor is already locked by another process.
570 if (flock(port->fd, LOCK_EX | LOCK_NB) < 0)
571 RETURN_FAIL("flock() failed");
576 * Before Linux 3.8 ioctl(*, TIOCEXCL) was not implemented and could
577 * lead to EINVAL or ENOTTY.
578 * These errors aren't fatal and can be ignored.
580 if (ioctl(port->fd, TIOCEXCL) < 0 && errno != EINVAL && errno != ENOTTY)
581 RETURN_FAIL("ioctl() failed");
586 ret = get_config(port, &data, &config);
594 * Assume a default baudrate if the OS does not provide one.
595 * Cannot assign -1 here since Windows holds the baudrate in
596 * the DCB and does not configure the rate individually.
598 if (config.baudrate == 0) {
599 config.baudrate = 9600;
602 /* Set sane port settings. */
604 data.dcb.fBinary = TRUE;
605 data.dcb.fDsrSensitivity = FALSE;
606 data.dcb.fErrorChar = FALSE;
607 data.dcb.fNull = FALSE;
608 data.dcb.fAbortOnError = FALSE;
610 /* Turn off all fancy termios tricks, give us a raw channel. */
611 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
613 data.term.c_iflag &= ~IUCLC;
615 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
617 data.term.c_oflag &= ~OLCUC;
620 data.term.c_oflag &= ~NLDLY;
623 data.term.c_oflag &= ~CRDLY;
626 data.term.c_oflag &= ~TABDLY;
629 data.term.c_oflag &= ~BSDLY;
632 data.term.c_oflag &= ~VTDLY;
635 data.term.c_oflag &= ~FFDLY;
638 data.term.c_oflag &= ~OFILL;
640 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
641 data.term.c_cc[VMIN] = 0;
642 data.term.c_cc[VTIME] = 0;
644 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
645 data.term.c_cflag |= (CLOCAL | CREAD);
646 data.term.c_cflag &= ~(HUPCL);
650 if (ClearCommError(port->hdl, &errors, &status) == 0)
651 RETURN_FAIL("ClearCommError() failed");
654 ret = set_config(port, &data, &config);
664 SP_API enum sp_return sp_close(struct sp_port *port)
670 DEBUG_FMT("Closing port %s", port->name);
673 /* Returns non-zero upon success, 0 upon failure. */
674 if (CloseHandle(port->hdl) == 0)
675 RETURN_FAIL("Port CloseHandle() failed");
676 port->hdl = INVALID_HANDLE_VALUE;
678 /* Close event handles for overlapped structures. */
679 #define CLOSE_OVERLAPPED(ovl) do { \
680 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
681 CloseHandle(port->ovl.hEvent) == 0) \
682 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
684 CLOSE_OVERLAPPED(read_ovl);
685 CLOSE_OVERLAPPED(write_ovl);
686 CLOSE_OVERLAPPED(wait_ovl);
688 if (port->write_buf) {
689 free(port->write_buf);
690 port->write_buf = NULL;
693 /* Returns 0 upon success, -1 upon failure. */
694 if (close(port->fd) == -1)
695 RETURN_FAIL("close() failed");
702 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
704 TRACE("%p, 0x%x", port, buffers);
708 if (buffers > SP_BUF_BOTH)
709 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
711 const char *buffer_names[] = {"no", "input", "output", "both"};
713 DEBUG_FMT("Flushing %s buffers on port %s",
714 buffer_names[buffers], port->name);
718 if (buffers & SP_BUF_INPUT)
719 flags |= PURGE_RXCLEAR;
720 if (buffers & SP_BUF_OUTPUT)
721 flags |= PURGE_TXCLEAR;
723 /* Returns non-zero upon success, 0 upon failure. */
724 if (PurgeComm(port->hdl, flags) == 0)
725 RETURN_FAIL("PurgeComm() failed");
727 if (buffers & SP_BUF_INPUT)
728 TRY(restart_wait(port));
731 if (buffers == SP_BUF_BOTH)
733 else if (buffers == SP_BUF_INPUT)
735 else if (buffers == SP_BUF_OUTPUT)
738 /* Returns 0 upon success, -1 upon failure. */
739 if (tcflush(port->fd, flags) < 0)
740 RETURN_FAIL("tcflush() failed");
745 SP_API enum sp_return sp_drain(struct sp_port *port)
751 DEBUG_FMT("Draining port %s", port->name);
754 /* Returns non-zero upon success, 0 upon failure. */
755 if (FlushFileBuffers(port->hdl) == 0)
756 RETURN_FAIL("FlushFileBuffers() failed");
761 #if defined(__ANDROID__) && (__ANDROID_API__ < 21)
762 /* Android only has tcdrain from platform 21 onwards.
763 * On previous API versions, use the ioctl directly. */
765 result = ioctl(port->fd, TCSBRK, &arg);
767 result = tcdrain(port->fd);
770 if (errno == EINTR) {
771 DEBUG("tcdrain() was interrupted");
774 RETURN_FAIL("tcdrain() failed");
784 static enum sp_return await_write_completion(struct sp_port *port)
790 /* Wait for previous non-blocking write to complete, if any. */
792 DEBUG("Waiting for previous write to complete");
793 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
796 RETURN_FAIL("Previous write failed to complete");
797 DEBUG("Previous write completed");
804 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
805 size_t count, unsigned int timeout_ms)
807 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
812 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
815 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
816 count, port->name, timeout_ms);
818 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
825 DWORD remaining_ms, write_size, bytes_written;
826 size_t remaining_bytes, total_bytes_written = 0;
827 const uint8_t *write_ptr = (uint8_t *) buf;
829 struct timeout timeout;
831 timeout_start(&timeout, timeout_ms);
833 TRY(await_write_completion(port));
835 while (total_bytes_written < count) {
837 if (timeout_check(&timeout))
840 remaining_ms = timeout_remaining_ms(&timeout);
842 if (port->timeouts.WriteTotalTimeoutConstant != remaining_ms) {
843 port->timeouts.WriteTotalTimeoutConstant = remaining_ms;
844 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
845 RETURN_FAIL("SetCommTimeouts() failed");
848 /* Reduce write size if it exceeds the WriteFile limit. */
849 remaining_bytes = count - total_bytes_written;
850 if (remaining_bytes > WRITEFILE_MAX_SIZE)
851 write_size = WRITEFILE_MAX_SIZE;
853 write_size = (DWORD) remaining_bytes;
857 result = WriteFile(port->hdl, write_ptr, write_size, NULL, &port->write_ovl);
859 timeout_update(&timeout);
862 DEBUG("Write completed immediately");
863 bytes_written = write_size;
864 } else if (GetLastError() == ERROR_IO_PENDING) {
865 DEBUG("Waiting for write to complete");
866 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
867 if (GetLastError() == ERROR_SEM_TIMEOUT) {
868 DEBUG("Write timed out");
871 RETURN_FAIL("GetOverlappedResult() failed");
874 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, write_size);
876 RETURN_FAIL("WriteFile() failed");
879 write_ptr += bytes_written;
880 total_bytes_written += bytes_written;
883 RETURN_INT((int) total_bytes_written);
885 size_t bytes_written = 0;
886 unsigned char *ptr = (unsigned char *) buf;
887 struct timeout timeout;
891 timeout_start(&timeout, timeout_ms);
894 FD_SET(port->fd, &fds);
896 /* Loop until we have written the requested number of bytes. */
897 while (bytes_written < count) {
899 if (timeout_check(&timeout))
902 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
904 timeout_update(&timeout);
907 if (errno == EINTR) {
908 DEBUG("select() call was interrupted, repeating");
911 RETURN_FAIL("select() failed");
913 } else if (result == 0) {
914 /* Timeout has expired. */
919 result = write(port->fd, ptr, count - bytes_written);
923 /* This shouldn't happen because we did a select() first, but handle anyway. */
926 /* This is an actual failure. */
927 RETURN_FAIL("write() failed");
930 bytes_written += result;
934 if (bytes_written < count)
935 DEBUG("Write timed out");
937 RETURN_INT(bytes_written);
941 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
942 const void *buf, size_t count)
944 TRACE("%p, %p, %d", port, buf, count);
949 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
951 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
959 /* Check whether previous write is complete. */
961 if (HasOverlappedIoCompleted(&port->write_ovl)) {
962 DEBUG("Previous write completed");
965 DEBUG("Previous write not complete");
966 /* Can't take a new write until the previous one finishes. */
972 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
973 port->timeouts.WriteTotalTimeoutConstant = 0;
974 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
975 RETURN_FAIL("SetCommTimeouts() failed");
978 /* Reduce count if it exceeds the WriteFile limit. */
979 if (count > WRITEFILE_MAX_SIZE)
980 count = WRITEFILE_MAX_SIZE;
982 /* Copy data to our write buffer. */
983 buf_bytes = min(port->write_buf_size, count);
984 memcpy(port->write_buf, buf, buf_bytes);
986 /* Start asynchronous write. */
987 if (WriteFile(port->hdl, port->write_buf, (DWORD) buf_bytes, NULL, &port->write_ovl) == 0) {
988 if (GetLastError() == ERROR_IO_PENDING) {
989 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
990 DEBUG("Asynchronous write completed immediately");
992 DEBUG("Asynchronous write running");
994 /* Actual failure of some kind. */
995 RETURN_FAIL("WriteFile() failed");
999 DEBUG("All bytes written immediately");
1001 RETURN_INT((int) buf_bytes);
1003 /* Returns the number of bytes written, or -1 upon failure. */
1004 ssize_t written = write(port->fd, buf, count);
1007 if (errno == EAGAIN)
1008 // Buffer is full, no bytes written.
1011 RETURN_FAIL("write() failed");
1013 RETURN_INT(written);
1019 /* Restart wait operation if buffer was emptied. */
1020 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1025 if (bytes_read == 0)
1028 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1029 RETURN_FAIL("ClearCommError() failed");
1031 if (comstat.cbInQue == 0)
1032 TRY(restart_wait(port));
1038 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1039 size_t count, unsigned int timeout_ms)
1041 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1046 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1049 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1050 count, port->name, timeout_ms);
1052 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1062 if (port->timeouts.ReadIntervalTimeout != 0 ||
1063 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1064 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1065 port->timeouts.ReadIntervalTimeout = 0;
1066 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1067 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1068 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1069 RETURN_FAIL("SetCommTimeouts() failed");
1073 if (ReadFile(port->hdl, buf, (DWORD) count, NULL, &port->read_ovl)) {
1074 DEBUG("Read completed immediately");
1075 bytes_read = (DWORD) count;
1076 } else if (GetLastError() == ERROR_IO_PENDING) {
1077 DEBUG("Waiting for read to complete");
1078 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1079 RETURN_FAIL("GetOverlappedResult() failed");
1080 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1082 RETURN_FAIL("ReadFile() failed");
1085 TRY(restart_wait_if_needed(port, bytes_read));
1087 RETURN_INT((int) bytes_read);
1090 size_t bytes_read = 0;
1091 unsigned char *ptr = (unsigned char *) buf;
1092 struct timeout timeout;
1096 timeout_start(&timeout, timeout_ms);
1099 FD_SET(port->fd, &fds);
1101 /* Loop until we have the requested number of bytes. */
1102 while (bytes_read < count) {
1104 if (timeout_check(&timeout))
1105 /* Timeout has expired. */
1108 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1110 timeout_update(&timeout);
1113 if (errno == EINTR) {
1114 DEBUG("select() call was interrupted, repeating");
1117 RETURN_FAIL("select() failed");
1119 } else if (result == 0) {
1120 /* Timeout has expired. */
1125 result = read(port->fd, ptr, count - bytes_read);
1128 if (errno == EAGAIN)
1130 * This shouldn't happen because we did a
1131 * select() first, but handle anyway.
1135 /* This is an actual failure. */
1136 RETURN_FAIL("read() failed");
1139 bytes_read += result;
1143 if (bytes_read < count)
1144 DEBUG("Read timed out");
1146 RETURN_INT(bytes_read);
1150 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1151 size_t count, unsigned int timeout_ms)
1153 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1158 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1161 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1164 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1165 count, port->name, timeout_ms);
1167 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1171 DWORD bytes_read = 0;
1173 /* If timeout_ms == 0, set maximum timeout. */
1174 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1177 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1178 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1179 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1180 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1181 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1182 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1183 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1184 RETURN_FAIL("SetCommTimeouts() failed");
1187 /* Loop until we have at least one byte, or timeout is reached. */
1188 while (bytes_read == 0) {
1190 if (ReadFile(port->hdl, buf, (DWORD) count, &bytes_read, &port->read_ovl)) {
1191 DEBUG("Read completed immediately");
1192 } else if (GetLastError() == ERROR_IO_PENDING) {
1193 DEBUG("Waiting for read to complete");
1194 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1195 RETURN_FAIL("GetOverlappedResult() failed");
1196 if (bytes_read > 0) {
1197 DEBUG("Read completed");
1198 } else if (timeout_ms > 0) {
1199 DEBUG("Read timed out");
1202 DEBUG("Restarting read");
1205 RETURN_FAIL("ReadFile() failed");
1209 TRY(restart_wait_if_needed(port, bytes_read));
1211 RETURN_INT(bytes_read);
1214 size_t bytes_read = 0;
1215 struct timeout timeout;
1219 timeout_start(&timeout, timeout_ms);
1222 FD_SET(port->fd, &fds);
1224 /* Loop until we have at least one byte, or timeout is reached. */
1225 while (bytes_read == 0) {
1227 if (timeout_check(&timeout))
1228 /* Timeout has expired. */
1231 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1233 timeout_update(&timeout);
1236 if (errno == EINTR) {
1237 DEBUG("select() call was interrupted, repeating");
1240 RETURN_FAIL("select() failed");
1242 } else if (result == 0) {
1243 /* Timeout has expired. */
1248 result = read(port->fd, buf, count);
1251 if (errno == EAGAIN)
1252 /* This shouldn't happen because we did a select() first, but handle anyway. */
1255 /* This is an actual failure. */
1256 RETURN_FAIL("read() failed");
1259 bytes_read = result;
1262 if (bytes_read == 0)
1263 DEBUG("Read timed out");
1265 RETURN_INT(bytes_read);
1269 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1272 TRACE("%p, %p, %d", port, buf, count);
1277 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1279 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1285 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1286 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1287 port->timeouts.ReadTotalTimeoutConstant != 0) {
1288 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1289 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1290 port->timeouts.ReadTotalTimeoutConstant = 0;
1291 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1292 RETURN_FAIL("SetCommTimeouts() failed");
1296 if (ReadFile(port->hdl, buf, (DWORD) count, NULL, &port->read_ovl) == 0)
1297 if (GetLastError() != ERROR_IO_PENDING)
1298 RETURN_FAIL("ReadFile() failed");
1300 /* Get number of bytes read. */
1301 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1302 RETURN_FAIL("GetOverlappedResult() failed");
1304 TRY(restart_wait_if_needed(port, bytes_read));
1306 RETURN_INT(bytes_read);
1310 /* Returns the number of bytes read, or -1 upon failure. */
1311 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1312 if (errno == EAGAIN)
1313 /* No bytes available. */
1316 /* This is an actual failure. */
1317 RETURN_FAIL("read() failed");
1319 RETURN_INT(bytes_read);
1323 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1329 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1335 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1336 RETURN_FAIL("ClearCommError() failed");
1337 RETURN_INT(comstat.cbInQue);
1340 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1341 RETURN_FAIL("TIOCINQ ioctl failed");
1342 RETURN_INT(bytes_waiting);
1346 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1351 /* TIOCOUTQ is not defined in Cygwin headers */
1352 RETURN_ERROR(SP_ERR_SUPP,
1353 "Getting output bytes waiting is not supported on Cygwin");
1357 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1363 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1364 RETURN_FAIL("ClearCommError() failed");
1365 RETURN_INT(comstat.cbOutQue);
1368 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1369 RETURN_FAIL("TIOCOUTQ ioctl failed");
1370 RETURN_INT(bytes_waiting);
1375 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1377 struct sp_event_set *result;
1379 TRACE("%p", result_ptr);
1382 RETURN_ERROR(SP_ERR_ARG, "Null result");
1386 if (!(result = malloc(sizeof(struct sp_event_set))))
1387 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1389 memset(result, 0, sizeof(struct sp_event_set));
1391 *result_ptr = result;
1396 static enum sp_return add_handle(struct sp_event_set *event_set,
1397 event_handle handle, enum sp_event mask)
1400 enum sp_event *new_masks;
1402 TRACE("%p, %d, %d", event_set, handle, mask);
1404 if (!(new_handles = realloc(event_set->handles,
1405 sizeof(event_handle) * (event_set->count + 1))))
1406 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1408 event_set->handles = new_handles;
1410 if (!(new_masks = realloc(event_set->masks,
1411 sizeof(enum sp_event) * (event_set->count + 1))))
1412 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1414 event_set->masks = new_masks;
1416 ((event_handle *) event_set->handles)[event_set->count] = handle;
1417 event_set->masks[event_set->count] = mask;
1424 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1425 const struct sp_port *port, enum sp_event mask)
1427 TRACE("%p, %p, %d", event_set, port, mask);
1430 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1433 RETURN_ERROR(SP_ERR_ARG, "Null port");
1435 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1436 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1442 enum sp_event handle_mask;
1443 if ((handle_mask = mask & SP_EVENT_TX_READY))
1444 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1445 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1446 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1448 TRY(add_handle(event_set, port->fd, mask));
1454 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1456 TRACE("%p", event_set);
1459 DEBUG("Null event set");
1463 DEBUG("Freeing event set");
1465 if (event_set->handles)
1466 free(event_set->handles);
1467 if (event_set->masks)
1468 free(event_set->masks);
1475 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1476 unsigned int timeout_ms)
1478 TRACE("%p, %d", event_set, timeout_ms);
1481 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1484 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1485 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1486 RETURN_FAIL("WaitForMultipleObjects() failed");
1490 struct timeout timeout;
1493 struct pollfd *pollfds;
1496 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1497 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1499 for (i = 0; i < event_set->count; i++) {
1500 pollfds[i].fd = ((int *)event_set->handles)[i];
1501 pollfds[i].events = 0;
1502 pollfds[i].revents = 0;
1503 if (event_set->masks[i] & SP_EVENT_RX_READY)
1504 pollfds[i].events |= POLLIN;
1505 if (event_set->masks[i] & SP_EVENT_TX_READY)
1506 pollfds[i].events |= POLLOUT;
1507 if (event_set->masks[i] & SP_EVENT_ERROR)
1508 pollfds[i].events |= POLLERR;
1511 timeout_start(&timeout, timeout_ms);
1512 timeout_limit(&timeout, INT_MAX);
1514 /* Loop until an event occurs. */
1517 if (timeout_check(&timeout)) {
1518 DEBUG("Wait timed out");
1522 poll_timeout = (int) timeout_remaining_ms(&timeout);
1523 if (poll_timeout == 0)
1526 result = poll(pollfds, event_set->count, poll_timeout);
1528 timeout_update(&timeout);
1531 if (errno == EINTR) {
1532 DEBUG("poll() call was interrupted, repeating");
1536 RETURN_FAIL("poll() failed");
1538 } else if (result == 0) {
1539 DEBUG("poll() timed out");
1540 if (!timeout.overflow)
1543 DEBUG("poll() completed");
1553 #ifdef USE_TERMIOS_SPEED
1554 static enum sp_return get_baudrate(int fd, int *baudrate)
1558 TRACE("%d, %p", fd, baudrate);
1560 DEBUG("Getting baud rate");
1562 if (!(data = malloc(get_termios_size())))
1563 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1565 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1567 RETURN_FAIL("Getting termios failed");
1570 *baudrate = get_termios_speed(data);
1577 static enum sp_return set_baudrate(int fd, int baudrate)
1581 TRACE("%d, %d", fd, baudrate);
1583 DEBUG("Getting baud rate");
1585 if (!(data = malloc(get_termios_size())))
1586 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1588 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1590 RETURN_FAIL("Getting termios failed");
1593 DEBUG("Setting baud rate");
1595 set_termios_speed(data, baudrate);
1597 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1599 RETURN_FAIL("Setting termios failed");
1606 #endif /* USE_TERMIOS_SPEED */
1609 static enum sp_return get_flow(int fd, struct port_data *data)
1613 TRACE("%d, %p", fd, data);
1615 DEBUG("Getting advanced flow control");
1617 if (!(termx = malloc(get_termiox_size())))
1618 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1620 if (ioctl(fd, TCGETX, termx) < 0) {
1622 RETURN_FAIL("Getting termiox failed");
1625 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1626 &data->dtr_flow, &data->dsr_flow);
1633 static enum sp_return set_flow(int fd, struct port_data *data)
1637 TRACE("%d, %p", fd, data);
1639 DEBUG("Getting advanced flow control");
1641 if (!(termx = malloc(get_termiox_size())))
1642 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1644 if (ioctl(fd, TCGETX, termx) < 0) {
1646 RETURN_FAIL("Getting termiox failed");
1649 DEBUG("Setting advanced flow control");
1651 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1652 data->dtr_flow, data->dsr_flow);
1654 if (ioctl(fd, TCSETX, termx) < 0) {
1656 RETURN_FAIL("Setting termiox failed");
1663 #endif /* USE_TERMIOX */
1665 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1666 struct sp_port_config *config)
1670 TRACE("%p, %p, %p", port, data, config);
1672 DEBUG_FMT("Getting configuration for port %s", port->name);
1675 if (!GetCommState(port->hdl, &data->dcb))
1676 RETURN_FAIL("GetCommState() failed");
1678 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1679 if (data->dcb.BaudRate == std_baudrates[i].index) {
1680 config->baudrate = std_baudrates[i].value;
1685 if (i == NUM_STD_BAUDRATES)
1686 /* BaudRate field can be either an index or a custom baud rate. */
1687 config->baudrate = data->dcb.BaudRate;
1689 config->bits = data->dcb.ByteSize;
1691 switch (data->dcb.Parity) {
1693 config->parity = SP_PARITY_NONE;
1696 config->parity = SP_PARITY_ODD;
1699 config->parity = SP_PARITY_EVEN;
1702 config->parity = SP_PARITY_MARK;
1705 config->parity = SP_PARITY_SPACE;
1708 config->parity = -1;
1711 switch (data->dcb.StopBits) {
1713 config->stopbits = 1;
1716 config->stopbits = 2;
1719 config->stopbits = -1;
1722 switch (data->dcb.fRtsControl) {
1723 case RTS_CONTROL_DISABLE:
1724 config->rts = SP_RTS_OFF;
1726 case RTS_CONTROL_ENABLE:
1727 config->rts = SP_RTS_ON;
1729 case RTS_CONTROL_HANDSHAKE:
1730 config->rts = SP_RTS_FLOW_CONTROL;
1736 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1738 switch (data->dcb.fDtrControl) {
1739 case DTR_CONTROL_DISABLE:
1740 config->dtr = SP_DTR_OFF;
1742 case DTR_CONTROL_ENABLE:
1743 config->dtr = SP_DTR_ON;
1745 case DTR_CONTROL_HANDSHAKE:
1746 config->dtr = SP_DTR_FLOW_CONTROL;
1752 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1754 if (data->dcb.fInX) {
1755 if (data->dcb.fOutX)
1756 config->xon_xoff = SP_XONXOFF_INOUT;
1758 config->xon_xoff = SP_XONXOFF_IN;
1760 if (data->dcb.fOutX)
1761 config->xon_xoff = SP_XONXOFF_OUT;
1763 config->xon_xoff = SP_XONXOFF_DISABLED;
1768 if (tcgetattr(port->fd, &data->term) < 0)
1769 RETURN_FAIL("tcgetattr() failed");
1771 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1772 RETURN_FAIL("TIOCMGET ioctl failed");
1775 int ret = get_flow(port->fd, data);
1777 if (ret == SP_ERR_FAIL && errno == EINVAL)
1778 data->termiox_supported = 0;
1780 RETURN_CODEVAL(ret);
1782 data->termiox_supported = 1;
1784 data->termiox_supported = 0;
1787 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1788 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1789 config->baudrate = std_baudrates[i].value;
1794 if (i == NUM_STD_BAUDRATES) {
1796 config->baudrate = (int)data->term.c_ispeed;
1797 #elif defined(USE_TERMIOS_SPEED)
1798 TRY(get_baudrate(port->fd, &config->baudrate));
1800 config->baudrate = -1;
1804 switch (data->term.c_cflag & CSIZE) {
1821 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1822 config->parity = SP_PARITY_NONE;
1823 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1824 config->parity = -1;
1826 else if (data->term.c_cflag & CMSPAR)
1827 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1830 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1832 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1834 if (data->term.c_cflag & CRTSCTS) {
1835 config->rts = SP_RTS_FLOW_CONTROL;
1836 config->cts = SP_CTS_FLOW_CONTROL;
1838 if (data->termiox_supported && data->rts_flow)
1839 config->rts = SP_RTS_FLOW_CONTROL;
1841 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1843 config->cts = (data->termiox_supported && data->cts_flow) ?
1844 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1847 if (data->termiox_supported && data->dtr_flow)
1848 config->dtr = SP_DTR_FLOW_CONTROL;
1850 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1852 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1853 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1855 if (data->term.c_iflag & IXOFF) {
1856 if (data->term.c_iflag & IXON)
1857 config->xon_xoff = SP_XONXOFF_INOUT;
1859 config->xon_xoff = SP_XONXOFF_IN;
1861 if (data->term.c_iflag & IXON)
1862 config->xon_xoff = SP_XONXOFF_OUT;
1864 config->xon_xoff = SP_XONXOFF_DISABLED;
1871 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1872 const struct sp_port_config *config)
1876 BAUD_TYPE baud_nonstd;
1880 #ifdef USE_TERMIOS_SPEED
1881 int baud_nonstd = 0;
1884 TRACE("%p, %p, %p", port, data, config);
1886 DEBUG_FMT("Setting configuration for port %s", port->name);
1891 TRY(await_write_completion(port));
1893 if (config->baudrate >= 0) {
1894 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1895 if (config->baudrate == std_baudrates[i].value) {
1896 data->dcb.BaudRate = std_baudrates[i].index;
1901 if (i == NUM_STD_BAUDRATES)
1902 data->dcb.BaudRate = config->baudrate;
1904 /* Allocate write buffer for 50ms of data at baud rate. */
1905 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1906 new_buf = realloc(port->write_buf, port->write_buf_size);
1908 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1909 port->write_buf = new_buf;
1912 if (config->bits >= 0)
1913 data->dcb.ByteSize = config->bits;
1915 if (config->parity >= 0) {
1916 switch (config->parity) {
1917 case SP_PARITY_NONE:
1918 data->dcb.Parity = NOPARITY;
1921 data->dcb.Parity = ODDPARITY;
1923 case SP_PARITY_EVEN:
1924 data->dcb.Parity = EVENPARITY;
1926 case SP_PARITY_MARK:
1927 data->dcb.Parity = MARKPARITY;
1929 case SP_PARITY_SPACE:
1930 data->dcb.Parity = SPACEPARITY;
1933 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1937 if (config->stopbits >= 0) {
1938 switch (config->stopbits) {
1939 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1941 data->dcb.StopBits = ONESTOPBIT;
1944 data->dcb.StopBits = TWOSTOPBITS;
1947 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1951 if (config->rts >= 0) {
1952 switch (config->rts) {
1954 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1957 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1959 case SP_RTS_FLOW_CONTROL:
1960 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1963 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1967 if (config->cts >= 0) {
1968 switch (config->cts) {
1970 data->dcb.fOutxCtsFlow = FALSE;
1972 case SP_CTS_FLOW_CONTROL:
1973 data->dcb.fOutxCtsFlow = TRUE;
1976 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1980 if (config->dtr >= 0) {
1981 switch (config->dtr) {
1983 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1986 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1988 case SP_DTR_FLOW_CONTROL:
1989 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1992 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1996 if (config->dsr >= 0) {
1997 switch (config->dsr) {
1999 data->dcb.fOutxDsrFlow = FALSE;
2001 case SP_DSR_FLOW_CONTROL:
2002 data->dcb.fOutxDsrFlow = TRUE;
2005 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2009 if (config->xon_xoff >= 0) {
2010 switch (config->xon_xoff) {
2011 case SP_XONXOFF_DISABLED:
2012 data->dcb.fInX = FALSE;
2013 data->dcb.fOutX = FALSE;
2016 data->dcb.fInX = TRUE;
2017 data->dcb.fOutX = FALSE;
2019 case SP_XONXOFF_OUT:
2020 data->dcb.fInX = FALSE;
2021 data->dcb.fOutX = TRUE;
2023 case SP_XONXOFF_INOUT:
2024 data->dcb.fInX = TRUE;
2025 data->dcb.fOutX = TRUE;
2028 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2032 if (!SetCommState(port->hdl, &data->dcb))
2033 RETURN_FAIL("SetCommState() failed");
2039 if (config->baudrate >= 0) {
2040 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2041 if (config->baudrate == std_baudrates[i].value) {
2042 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2043 RETURN_FAIL("cfsetospeed() failed");
2045 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2046 RETURN_FAIL("cfsetispeed() failed");
2051 /* Non-standard baud rate */
2052 if (i == NUM_STD_BAUDRATES) {
2054 /* Set "dummy" baud rate. */
2055 if (cfsetspeed(&data->term, B9600) < 0)
2056 RETURN_FAIL("cfsetspeed() failed");
2057 baud_nonstd = config->baudrate;
2058 #elif defined(USE_TERMIOS_SPEED)
2061 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2066 if (config->bits >= 0) {
2067 data->term.c_cflag &= ~CSIZE;
2068 switch (config->bits) {
2070 data->term.c_cflag |= CS8;
2073 data->term.c_cflag |= CS7;
2076 data->term.c_cflag |= CS6;
2079 data->term.c_cflag |= CS5;
2082 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2086 if (config->parity >= 0) {
2087 data->term.c_iflag &= ~IGNPAR;
2088 data->term.c_cflag &= ~(PARENB | PARODD);
2090 data->term.c_cflag &= ~CMSPAR;
2092 switch (config->parity) {
2093 case SP_PARITY_NONE:
2094 data->term.c_iflag |= IGNPAR;
2096 case SP_PARITY_EVEN:
2097 data->term.c_cflag |= PARENB;
2100 data->term.c_cflag |= PARENB | PARODD;
2103 case SP_PARITY_MARK:
2104 data->term.c_cflag |= PARENB | PARODD;
2105 data->term.c_cflag |= CMSPAR;
2107 case SP_PARITY_SPACE:
2108 data->term.c_cflag |= PARENB;
2109 data->term.c_cflag |= CMSPAR;
2112 case SP_PARITY_MARK:
2113 case SP_PARITY_SPACE:
2114 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2117 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2121 if (config->stopbits >= 0) {
2122 data->term.c_cflag &= ~CSTOPB;
2123 switch (config->stopbits) {
2125 data->term.c_cflag &= ~CSTOPB;
2128 data->term.c_cflag |= CSTOPB;
2131 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2135 if (config->rts >= 0 || config->cts >= 0) {
2136 if (data->termiox_supported) {
2137 data->rts_flow = data->cts_flow = 0;
2138 switch (config->rts) {
2141 controlbits = TIOCM_RTS;
2142 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2143 RETURN_FAIL("Setting RTS signal level failed");
2145 case SP_RTS_FLOW_CONTROL:
2151 if (config->cts == SP_CTS_FLOW_CONTROL)
2154 if (data->rts_flow && data->cts_flow)
2155 data->term.c_iflag |= CRTSCTS;
2157 data->term.c_iflag &= ~CRTSCTS;
2159 /* Asymmetric use of RTS/CTS not supported. */
2160 if (data->term.c_iflag & CRTSCTS) {
2161 /* Flow control can only be disabled for both RTS & CTS together. */
2162 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2163 if (config->cts != SP_CTS_IGNORE)
2164 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2166 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2167 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2168 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2171 /* Flow control can only be enabled for both RTS & CTS together. */
2172 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2173 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2174 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2177 if (config->rts >= 0) {
2178 if (config->rts == SP_RTS_FLOW_CONTROL) {
2179 data->term.c_iflag |= CRTSCTS;
2181 controlbits = TIOCM_RTS;
2182 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2184 RETURN_FAIL("Setting RTS signal level failed");
2190 if (config->dtr >= 0 || config->dsr >= 0) {
2191 if (data->termiox_supported) {
2192 data->dtr_flow = data->dsr_flow = 0;
2193 switch (config->dtr) {
2196 controlbits = TIOCM_DTR;
2197 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2198 RETURN_FAIL("Setting DTR signal level failed");
2200 case SP_DTR_FLOW_CONTROL:
2206 if (config->dsr == SP_DSR_FLOW_CONTROL)
2209 /* DTR/DSR flow control not supported. */
2210 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2211 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2213 if (config->dtr >= 0) {
2214 controlbits = TIOCM_DTR;
2215 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2217 RETURN_FAIL("Setting DTR signal level failed");
2222 if (config->xon_xoff >= 0) {
2223 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2224 switch (config->xon_xoff) {
2225 case SP_XONXOFF_DISABLED:
2228 data->term.c_iflag |= IXOFF;
2230 case SP_XONXOFF_OUT:
2231 data->term.c_iflag |= IXON | IXANY;
2233 case SP_XONXOFF_INOUT:
2234 data->term.c_iflag |= IXON | IXOFF | IXANY;
2237 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2241 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2242 RETURN_FAIL("tcsetattr() failed");
2245 if (baud_nonstd != B0) {
2246 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2247 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2249 * Set baud rates in data->term to correct, but incompatible
2250 * with tcsetattr() value, same as delivered by tcgetattr().
2252 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2253 RETURN_FAIL("cfsetspeed() failed");
2255 #elif defined(__linux__)
2256 #ifdef USE_TERMIOS_SPEED
2258 TRY(set_baudrate(port->fd, config->baudrate));
2261 if (data->termiox_supported)
2262 TRY(set_flow(port->fd, data));
2266 #endif /* !_WIN32 */
2271 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2273 struct sp_port_config *config;
2275 TRACE("%p", config_ptr);
2278 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2282 if (!(config = malloc(sizeof(struct sp_port_config))))
2283 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2285 config->baudrate = -1;
2287 config->parity = -1;
2288 config->stopbits = -1;
2294 *config_ptr = config;
2299 SP_API void sp_free_config(struct sp_port_config *config)
2301 TRACE("%p", config);
2304 DEBUG("Null config");
2311 SP_API enum sp_return sp_get_config(struct sp_port *port,
2312 struct sp_port_config *config)
2314 struct port_data data;
2316 TRACE("%p, %p", port, config);
2321 RETURN_ERROR(SP_ERR_ARG, "Null config");
2323 TRY(get_config(port, &data, config));
2328 SP_API enum sp_return sp_set_config(struct sp_port *port,
2329 const struct sp_port_config *config)
2331 struct port_data data;
2332 struct sp_port_config prev_config;
2334 TRACE("%p, %p", port, config);
2339 RETURN_ERROR(SP_ERR_ARG, "Null config");
2341 TRY(get_config(port, &data, &prev_config));
2342 TRY(set_config(port, &data, config));
2347 #define CREATE_ACCESSORS(x, type) \
2348 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2349 struct port_data data; \
2350 struct sp_port_config config; \
2351 TRACE("%p, %d", port, x); \
2352 CHECK_OPEN_PORT(); \
2353 TRY(get_config(port, &data, &config)); \
2355 TRY(set_config(port, &data, &config)); \
2358 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2360 TRACE("%p, %p", config, x); \
2362 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2364 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2368 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2370 TRACE("%p, %d", config, x); \
2372 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2377 CREATE_ACCESSORS(baudrate, int)
2378 CREATE_ACCESSORS(bits, int)
2379 CREATE_ACCESSORS(parity, enum sp_parity)
2380 CREATE_ACCESSORS(stopbits, int)
2381 CREATE_ACCESSORS(rts, enum sp_rts)
2382 CREATE_ACCESSORS(cts, enum sp_cts)
2383 CREATE_ACCESSORS(dtr, enum sp_dtr)
2384 CREATE_ACCESSORS(dsr, enum sp_dsr)
2385 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2387 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2388 enum sp_flowcontrol flowcontrol)
2391 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2393 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2394 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2396 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2397 config->xon_xoff = SP_XONXOFF_INOUT;
2399 config->xon_xoff = SP_XONXOFF_DISABLED;
2401 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2402 config->rts = SP_RTS_FLOW_CONTROL;
2403 config->cts = SP_CTS_FLOW_CONTROL;
2405 if (config->rts == SP_RTS_FLOW_CONTROL)
2406 config->rts = SP_RTS_ON;
2407 config->cts = SP_CTS_IGNORE;
2410 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2411 config->dtr = SP_DTR_FLOW_CONTROL;
2412 config->dsr = SP_DSR_FLOW_CONTROL;
2414 if (config->dtr == SP_DTR_FLOW_CONTROL)
2415 config->dtr = SP_DTR_ON;
2416 config->dsr = SP_DSR_IGNORE;
2422 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2423 enum sp_flowcontrol flowcontrol)
2425 struct port_data data;
2426 struct sp_port_config config;
2428 TRACE("%p, %d", port, flowcontrol);
2432 TRY(get_config(port, &data, &config));
2434 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2436 TRY(set_config(port, &data, &config));
2441 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2442 enum sp_signal *signals)
2444 TRACE("%p, %p", port, signals);
2449 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2451 DEBUG_FMT("Getting control signals for port %s", port->name);
2456 if (GetCommModemStatus(port->hdl, &bits) == 0)
2457 RETURN_FAIL("GetCommModemStatus() failed");
2458 if (bits & MS_CTS_ON)
2459 *signals |= SP_SIG_CTS;
2460 if (bits & MS_DSR_ON)
2461 *signals |= SP_SIG_DSR;
2462 if (bits & MS_RLSD_ON)
2463 *signals |= SP_SIG_DCD;
2464 if (bits & MS_RING_ON)
2465 *signals |= SP_SIG_RI;
2468 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2469 RETURN_FAIL("TIOCMGET ioctl failed");
2470 if (bits & TIOCM_CTS)
2471 *signals |= SP_SIG_CTS;
2472 if (bits & TIOCM_DSR)
2473 *signals |= SP_SIG_DSR;
2474 if (bits & TIOCM_CAR)
2475 *signals |= SP_SIG_DCD;
2476 if (bits & TIOCM_RNG)
2477 *signals |= SP_SIG_RI;
2482 SP_API enum sp_return sp_start_break(struct sp_port *port)
2488 if (SetCommBreak(port->hdl) == 0)
2489 RETURN_FAIL("SetCommBreak() failed");
2491 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2492 RETURN_FAIL("TIOCSBRK ioctl failed");
2498 SP_API enum sp_return sp_end_break(struct sp_port *port)
2504 if (ClearCommBreak(port->hdl) == 0)
2505 RETURN_FAIL("ClearCommBreak() failed");
2507 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2508 RETURN_FAIL("TIOCCBRK ioctl failed");
2514 SP_API int sp_last_error_code(void)
2518 RETURN_INT(GetLastError());
2524 SP_API char *sp_last_error_message(void)
2530 DWORD error = GetLastError();
2532 DWORD length = FormatMessageA(
2533 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2534 FORMAT_MESSAGE_FROM_SYSTEM |
2535 FORMAT_MESSAGE_IGNORE_INSERTS,
2538 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2542 if (length >= 2 && message[length - 2] == '\r')
2543 message[length - 2] = '\0';
2545 RETURN_STRING(message);
2547 RETURN_STRING(strerror(errno));
2551 SP_API void sp_free_error_message(char *message)
2553 TRACE("%s", message);
2564 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2566 TRACE("%p", handler);
2568 sp_debug_handler = handler;
2573 SP_API void sp_default_debug_handler(const char *format, ...)
2576 va_start(args, format);
2577 if (getenv("LIBSERIALPORT_DEBUG")) {
2578 fputs("sp: ", stderr);
2579 vfprintf(stderr, format, args);
2584 SP_API int sp_get_major_package_version(void)
2586 return SP_PACKAGE_VERSION_MAJOR;
2589 SP_API int sp_get_minor_package_version(void)
2591 return SP_PACKAGE_VERSION_MINOR;
2594 SP_API int sp_get_micro_package_version(void)
2596 return SP_PACKAGE_VERSION_MICRO;
2599 SP_API const char *sp_get_package_version_string(void)
2601 return SP_PACKAGE_VERSION_STRING;
2604 SP_API int sp_get_current_lib_version(void)
2606 return SP_LIB_VERSION_CURRENT;
2609 SP_API int sp_get_revision_lib_version(void)
2611 return SP_LIB_VERSION_REVISION;
2614 SP_API int sp_get_age_lib_version(void)
2616 return SP_LIB_VERSION_AGE;
2619 SP_API const char *sp_get_lib_version_string(void)
2621 return SP_LIB_VERSION_STRING;