2 * This file is part of the libserialport project.
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2015 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2013-2015 Martin Ling <martin-libserialport@earth.li>
7 * Copyright (C) 2013 Matthias Heidbrink <m-sigrok@heidbrink.biz>
8 * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation, either version 3 of the
13 * License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "libserialport.h"
26 #include "libserialport_internal.h"
28 static const struct std_baudrate std_baudrates[] = {
31 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
32 * have documented CBR_* macros.
34 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
35 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
36 BAUD(115200), BAUD(128000), BAUD(256000),
38 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
39 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
40 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
42 #if !defined(__APPLE__) && !defined(__OpenBSD__)
48 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
50 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
52 static void get_time(struct timeval *time);
54 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
55 struct sp_port_config *config);
57 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
58 const struct sp_port_config *config);
60 static void get_time(struct timeval *time)
62 #ifdef HAVE_CLOCK_GETTIME
64 clock_gettime(CLOCK_MONOTONIC, &ts);
65 time->tv_sec = ts.tv_sec;
66 time->tv_usec = ts.tv_nsec / 1000;
68 gettimeofday(time, NULL);
72 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
75 #ifndef NO_PORT_METADATA
80 TRACE("%s, %p", portname, port_ptr);
83 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
88 RETURN_ERROR(SP_ERR_ARG, "Null port name");
90 DEBUG_FMT("Building structure for port %s", portname);
92 #if !defined(_WIN32) && defined(HAVE_REALPATH)
94 * get_port_details() below tries to be too smart and figure out
95 * some transport properties from the port name which breaks with
96 * symlinks. Therefore we canonicalize the portname first.
98 char pathbuf[PATH_MAX + 1];
99 char *res = realpath(portname, pathbuf);
101 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
106 if (!(port = malloc(sizeof(struct sp_port))))
107 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
109 len = strlen(portname) + 1;
111 if (!(port->name = malloc(len))) {
113 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
116 memcpy(port->name, portname, len);
119 port->usb_path = NULL;
120 port->hdl = INVALID_HANDLE_VALUE;
121 port->write_buf = NULL;
122 port->write_buf_size = 0;
127 port->description = NULL;
128 port->transport = SP_TRANSPORT_NATIVE;
130 port->usb_address = -1;
133 port->usb_manufacturer = NULL;
134 port->usb_product = NULL;
135 port->usb_serial = NULL;
136 port->bluetooth_address = NULL;
138 #ifndef NO_PORT_METADATA
139 if ((ret = get_port_details(port)) != SP_OK) {
150 SP_API char *sp_get_port_name(const struct sp_port *port)
157 RETURN_STRING(port->name);
160 SP_API char *sp_get_port_description(const struct sp_port *port)
164 if (!port || !port->description)
167 RETURN_STRING(port->description);
170 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
175 RETURN_ERROR(SP_ERR_ARG, "Null port");
177 RETURN_INT(port->transport);
180 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
181 int *usb_bus,int *usb_address)
186 RETURN_ERROR(SP_ERR_ARG, "Null port");
187 if (port->transport != SP_TRANSPORT_USB)
188 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
189 if (port->usb_bus < 0 || port->usb_address < 0)
190 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
193 *usb_bus = port->usb_bus;
195 *usb_address = port->usb_address;
200 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
201 int *usb_vid, int *usb_pid)
206 RETURN_ERROR(SP_ERR_ARG, "Null port");
207 if (port->transport != SP_TRANSPORT_USB)
208 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
209 if (port->usb_vid < 0 || port->usb_pid < 0)
210 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
213 *usb_vid = port->usb_vid;
215 *usb_pid = port->usb_pid;
220 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
224 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
227 RETURN_STRING(port->usb_manufacturer);
230 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
234 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
237 RETURN_STRING(port->usb_product);
240 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
244 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
247 RETURN_STRING(port->usb_serial);
250 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
254 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
255 || !port->bluetooth_address)
258 RETURN_STRING(port->bluetooth_address);
261 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
264 TRACE("%p, %p", port, result_ptr);
267 RETURN_ERROR(SP_ERR_ARG, "Null port");
269 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
272 HANDLE *handle_ptr = result_ptr;
273 *handle_ptr = port->hdl;
275 int *fd_ptr = result_ptr;
282 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
283 struct sp_port **copy_ptr)
285 TRACE("%p, %p", port, copy_ptr);
288 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
293 RETURN_ERROR(SP_ERR_ARG, "Null port");
296 RETURN_ERROR(SP_ERR_ARG, "Null port name");
298 DEBUG("Copying port structure");
300 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
303 SP_API void sp_free_port(struct sp_port *port)
312 DEBUG("Freeing port structure");
316 if (port->description)
317 free(port->description);
318 if (port->usb_manufacturer)
319 free(port->usb_manufacturer);
320 if (port->usb_product)
321 free(port->usb_product);
322 if (port->usb_serial)
323 free(port->usb_serial);
324 if (port->bluetooth_address)
325 free(port->bluetooth_address);
328 free(port->usb_path);
330 free(port->write_buf);
338 SP_PRIV struct sp_port **list_append(struct sp_port **list,
339 const char *portname)
344 for (count = 0; list[count]; count++)
346 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
349 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
351 list[count + 1] = NULL;
355 sp_free_port_list(list);
359 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
361 #ifndef NO_ENUMERATION
362 struct sp_port **list;
366 TRACE("%p", list_ptr);
369 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
373 #ifdef NO_ENUMERATION
374 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
376 DEBUG("Enumerating ports");
378 if (!(list = malloc(sizeof(struct sp_port *))))
379 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
383 ret = list_ports(&list);
388 sp_free_port_list(list);
396 SP_API void sp_free_port_list(struct sp_port **list)
407 DEBUG("Freeing port list");
409 for (i = 0; list[i]; i++)
410 sp_free_port(list[i]);
416 #define CHECK_PORT() do { \
418 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
420 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
423 #define CHECK_PORT_HANDLE() do { \
424 if (port->hdl == INVALID_HANDLE_VALUE) \
425 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
428 #define CHECK_PORT_HANDLE() do { \
430 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
433 #define CHECK_OPEN_PORT() do { \
435 CHECK_PORT_HANDLE(); \
439 /** To be called after port receive buffer is emptied. */
440 static enum sp_return restart_wait(struct sp_port *port)
444 if (port->wait_running) {
445 /* Check status of running wait operation. */
446 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
447 &wait_result, FALSE)) {
448 DEBUG("Previous wait completed");
449 port->wait_running = FALSE;
450 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
451 DEBUG("Previous wait still running");
454 RETURN_FAIL("GetOverlappedResult() failed");
458 if (!port->wait_running) {
459 /* Start new wait operation. */
460 if (WaitCommEvent(port->hdl, &port->events,
462 DEBUG("New wait returned, events already pending");
463 } else if (GetLastError() == ERROR_IO_PENDING) {
464 DEBUG("New wait running in background");
465 port->wait_running = TRUE;
467 RETURN_FAIL("WaitCommEvent() failed");
475 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
477 struct port_data data;
478 struct sp_port_config config;
481 TRACE("%p, 0x%x", port, flags);
485 if (flags > SP_MODE_READ_WRITE)
486 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
488 DEBUG_FMT("Opening port %s", port->name);
491 DWORD desired_access = 0, flags_and_attributes = 0, errors;
492 char *escaped_port_name;
495 /* Prefix port name with '\\.\' to work with ports above COM9. */
496 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
497 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
498 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
500 /* Map 'flags' to the OS-specific settings. */
501 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
502 if (flags & SP_MODE_READ)
503 desired_access |= GENERIC_READ;
504 if (flags & SP_MODE_WRITE)
505 desired_access |= GENERIC_WRITE;
507 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
508 OPEN_EXISTING, flags_and_attributes, 0);
510 free(escaped_port_name);
512 if (port->hdl == INVALID_HANDLE_VALUE)
513 RETURN_FAIL("Port CreateFile() failed");
515 /* All timeouts initially disabled. */
516 port->timeouts.ReadIntervalTimeout = 0;
517 port->timeouts.ReadTotalTimeoutMultiplier = 0;
518 port->timeouts.ReadTotalTimeoutConstant = 0;
519 port->timeouts.WriteTotalTimeoutMultiplier = 0;
520 port->timeouts.WriteTotalTimeoutConstant = 0;
522 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
524 RETURN_FAIL("SetCommTimeouts() failed");
527 /* Prepare OVERLAPPED structures. */
528 #define INIT_OVERLAPPED(ovl) do { \
529 memset(&port->ovl, 0, sizeof(port->ovl)); \
530 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
531 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
532 == INVALID_HANDLE_VALUE) { \
534 RETURN_FAIL(#ovl "CreateEvent() failed"); \
538 INIT_OVERLAPPED(read_ovl);
539 INIT_OVERLAPPED(write_ovl);
540 INIT_OVERLAPPED(wait_ovl);
542 /* Set event mask for RX and error events. */
543 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
545 RETURN_FAIL("SetCommMask() failed");
548 port->writing = FALSE;
549 port->wait_running = FALSE;
551 ret = restart_wait(port);
558 int flags_local = O_NONBLOCK | O_NOCTTY;
560 /* Map 'flags' to the OS-specific settings. */
561 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
562 flags_local |= O_RDWR;
563 else if (flags & SP_MODE_READ)
564 flags_local |= O_RDONLY;
565 else if (flags & SP_MODE_WRITE)
566 flags_local |= O_WRONLY;
568 if ((port->fd = open(port->name, flags_local)) < 0)
569 RETURN_FAIL("open() failed");
572 ret = get_config(port, &data, &config);
579 /* Set sane port settings. */
581 data.dcb.fBinary = TRUE;
582 data.dcb.fDsrSensitivity = FALSE;
583 data.dcb.fErrorChar = FALSE;
584 data.dcb.fNull = FALSE;
585 data.dcb.fAbortOnError = FALSE;
587 /* Turn off all fancy termios tricks, give us a raw channel. */
588 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
590 data.term.c_iflag &= ~IUCLC;
592 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
594 data.term.c_oflag &= ~OLCUC;
597 data.term.c_oflag &= ~NLDLY;
600 data.term.c_oflag &= ~CRDLY;
603 data.term.c_oflag &= ~TABDLY;
606 data.term.c_oflag &= ~BSDLY;
609 data.term.c_oflag &= ~VTDLY;
612 data.term.c_oflag &= ~FFDLY;
615 data.term.c_oflag &= ~OFILL;
617 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
618 data.term.c_cc[VMIN] = 0;
619 data.term.c_cc[VTIME] = 0;
621 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
622 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
626 if (ClearCommError(port->hdl, &errors, &status) == 0)
627 RETURN_FAIL("ClearCommError() failed");
630 ret = set_config(port, &data, &config);
640 SP_API enum sp_return sp_close(struct sp_port *port)
646 DEBUG_FMT("Closing port %s", port->name);
649 /* Returns non-zero upon success, 0 upon failure. */
650 if (CloseHandle(port->hdl) == 0)
651 RETURN_FAIL("Port CloseHandle() failed");
652 port->hdl = INVALID_HANDLE_VALUE;
654 /* Close event handles for overlapped structures. */
655 #define CLOSE_OVERLAPPED(ovl) do { \
656 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
657 CloseHandle(port->ovl.hEvent) == 0) \
658 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
660 CLOSE_OVERLAPPED(read_ovl);
661 CLOSE_OVERLAPPED(write_ovl);
662 CLOSE_OVERLAPPED(wait_ovl);
664 if (port->write_buf) {
665 free(port->write_buf);
666 port->write_buf = NULL;
669 /* Returns 0 upon success, -1 upon failure. */
670 if (close(port->fd) == -1)
671 RETURN_FAIL("close() failed");
678 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
680 TRACE("%p, 0x%x", port, buffers);
684 if (buffers > SP_BUF_BOTH)
685 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
687 const char *buffer_names[] = {"no", "input", "output", "both"};
689 DEBUG_FMT("Flushing %s buffers on port %s",
690 buffer_names[buffers], port->name);
694 if (buffers & SP_BUF_INPUT)
695 flags |= PURGE_RXCLEAR;
696 if (buffers & SP_BUF_OUTPUT)
697 flags |= PURGE_TXCLEAR;
699 /* Returns non-zero upon success, 0 upon failure. */
700 if (PurgeComm(port->hdl, flags) == 0)
701 RETURN_FAIL("PurgeComm() failed");
703 if (buffers & SP_BUF_INPUT)
704 TRY(restart_wait(port));
707 if (buffers == SP_BUF_BOTH)
709 else if (buffers == SP_BUF_INPUT)
711 else if (buffers == SP_BUF_OUTPUT)
714 /* Returns 0 upon success, -1 upon failure. */
715 if (tcflush(port->fd, flags) < 0)
716 RETURN_FAIL("tcflush() failed");
721 SP_API enum sp_return sp_drain(struct sp_port *port)
727 DEBUG_FMT("Draining port %s", port->name);
730 /* Returns non-zero upon success, 0 upon failure. */
731 if (FlushFileBuffers(port->hdl) == 0)
732 RETURN_FAIL("FlushFileBuffers() failed");
739 result = ioctl(port->fd, TCSBRK, &arg);
741 result = tcdrain(port->fd);
744 if (errno == EINTR) {
745 DEBUG("tcdrain() was interrupted");
748 RETURN_FAIL("tcdrain() failed");
758 static enum sp_return await_write_completion(struct sp_port *port)
764 /* Wait for previous non-blocking write to complete, if any. */
766 DEBUG("Waiting for previous write to complete");
767 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
770 RETURN_FAIL("Previous write failed to complete");
771 DEBUG("Previous write completed");
778 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
779 size_t count, unsigned int timeout_ms)
781 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
786 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
789 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
790 count, port->name, timeout_ms);
792 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
799 DWORD bytes_written = 0;
801 TRY(await_write_completion(port));
804 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
805 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
806 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
807 RETURN_FAIL("SetCommTimeouts() failed");
810 /* Reduce count if it exceeds the WriteFile limit. */
811 if (count > WRITEFILE_MAX_SIZE)
812 count = WRITEFILE_MAX_SIZE;
815 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
816 DEBUG("Write completed immediately");
818 } else if (GetLastError() == ERROR_IO_PENDING) {
819 DEBUG("Waiting for write to complete");
820 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
821 if (GetLastError() == ERROR_SEM_TIMEOUT) {
822 DEBUG("Write timed out");
825 RETURN_FAIL("GetOverlappedResult() failed");
828 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
829 RETURN_INT(bytes_written);
831 RETURN_FAIL("WriteFile() failed");
834 size_t bytes_written = 0;
835 unsigned char *ptr = (unsigned char *) buf;
836 struct timeval start, delta, now, end = {0, 0};
842 /* Get time at start of operation. */
844 /* Define duration of timeout. */
845 delta.tv_sec = timeout_ms / 1000;
846 delta.tv_usec = (timeout_ms % 1000) * 1000;
847 /* Calculate time at which we should give up. */
848 timeradd(&start, &delta, &end);
852 FD_SET(port->fd, &fds);
854 /* Loop until we have written the requested number of bytes. */
855 while (bytes_written < count) {
857 * Check timeout only if we have run select() at least once,
858 * to avoid any issues if a short timeout is reached before
859 * select() is even run.
861 if (timeout_ms && started) {
863 if (timercmp(&now, &end, >))
864 /* Timeout has expired. */
866 timersub(&end, &now, &delta);
868 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
871 if (errno == EINTR) {
872 DEBUG("select() call was interrupted, repeating");
875 RETURN_FAIL("select() failed");
877 } else if (result == 0) {
878 /* Timeout has expired. */
883 result = write(port->fd, ptr, count - bytes_written);
887 /* This shouldn't happen because we did a select() first, but handle anyway. */
890 /* This is an actual failure. */
891 RETURN_FAIL("write() failed");
894 bytes_written += result;
898 if (bytes_written < count)
899 DEBUG("Write timed out");
901 RETURN_INT(bytes_written);
905 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
906 const void *buf, size_t count)
908 TRACE("%p, %p, %d", port, buf, count);
913 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
915 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
923 /* Check whether previous write is complete. */
925 if (HasOverlappedIoCompleted(&port->write_ovl)) {
926 DEBUG("Previous write completed");
929 DEBUG("Previous write not complete");
930 /* Can't take a new write until the previous one finishes. */
936 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
937 port->timeouts.WriteTotalTimeoutConstant = 0;
938 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
939 RETURN_FAIL("SetCommTimeouts() failed");
942 /* Reduce count if it exceeds the WriteFile limit. */
943 if (count > WRITEFILE_MAX_SIZE)
944 count = WRITEFILE_MAX_SIZE;
946 /* Copy data to our write buffer. */
947 buf_bytes = min(port->write_buf_size, count);
948 memcpy(port->write_buf, buf, buf_bytes);
950 /* Start asynchronous write. */
951 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
952 if (GetLastError() == ERROR_IO_PENDING) {
953 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
954 DEBUG("Asynchronous write completed immediately");
956 DEBUG("Asynchronous write running");
958 /* Actual failure of some kind. */
959 RETURN_FAIL("WriteFile() failed");
963 DEBUG("All bytes written immediately");
965 RETURN_INT(buf_bytes);
967 /* Returns the number of bytes written, or -1 upon failure. */
968 ssize_t written = write(port->fd, buf, count);
972 // Buffer is full, no bytes written.
975 RETURN_FAIL("write() failed");
983 /* Restart wait operation if buffer was emptied. */
984 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
992 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
993 RETURN_FAIL("ClearCommError() failed");
995 if (comstat.cbInQue == 0)
996 TRY(restart_wait(port));
1002 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1003 size_t count, unsigned int timeout_ms)
1005 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1010 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1013 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1014 count, port->name, timeout_ms);
1016 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1023 DWORD bytes_read = 0;
1026 if (port->timeouts.ReadIntervalTimeout != 0 ||
1027 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1028 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1029 port->timeouts.ReadIntervalTimeout = 0;
1030 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1031 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1032 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1033 RETURN_FAIL("SetCommTimeouts() failed");
1037 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1038 DEBUG("Read completed immediately");
1040 } else if (GetLastError() == ERROR_IO_PENDING) {
1041 DEBUG("Waiting for read to complete");
1042 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1043 RETURN_FAIL("GetOverlappedResult() failed");
1044 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1046 RETURN_FAIL("ReadFile() failed");
1049 TRY(restart_wait_if_needed(port, bytes_read));
1051 RETURN_INT(bytes_read);
1054 size_t bytes_read = 0;
1055 unsigned char *ptr = (unsigned char *)buf;
1056 struct timeval start, delta, now, end = {0, 0};
1062 /* Get time at start of operation. */
1064 /* Define duration of timeout. */
1065 delta.tv_sec = timeout_ms / 1000;
1066 delta.tv_usec = (timeout_ms % 1000) * 1000;
1067 /* Calculate time at which we should give up. */
1068 timeradd(&start, &delta, &end);
1072 FD_SET(port->fd, &fds);
1074 /* Loop until we have the requested number of bytes. */
1075 while (bytes_read < count) {
1077 * Check timeout only if we have run select() at least once,
1078 * to avoid any issues if a short timeout is reached before
1079 * select() is even run.
1081 if (timeout_ms && started) {
1083 if (timercmp(&now, &end, >))
1084 /* Timeout has expired. */
1086 timersub(&end, &now, &delta);
1088 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1091 if (errno == EINTR) {
1092 DEBUG("select() call was interrupted, repeating");
1095 RETURN_FAIL("select() failed");
1097 } else if (result == 0) {
1098 /* Timeout has expired. */
1103 result = read(port->fd, ptr, count - bytes_read);
1106 if (errno == EAGAIN)
1108 * This shouldn't happen because we did a
1109 * select() first, but handle anyway.
1113 /* This is an actual failure. */
1114 RETURN_FAIL("read() failed");
1117 bytes_read += result;
1121 if (bytes_read < count)
1122 DEBUG("Read timed out");
1124 RETURN_INT(bytes_read);
1128 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1129 size_t count, unsigned int timeout_ms)
1131 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1136 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1139 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1142 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1143 count, port->name, timeout_ms);
1145 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1149 DWORD bytes_read = 0;
1151 /* If timeout_ms == 0, set maximum timeout. */
1152 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1155 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1156 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1157 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1158 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1159 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1160 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1161 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1162 RETURN_FAIL("SetCommTimeouts() failed");
1165 /* Loop until we have at least one byte, or timeout is reached. */
1166 while (bytes_read == 0) {
1168 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1169 DEBUG("Read completed immediately");
1170 } else if (GetLastError() == ERROR_IO_PENDING) {
1171 DEBUG("Waiting for read to complete");
1172 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1173 RETURN_FAIL("GetOverlappedResult() failed");
1174 if (bytes_read > 0) {
1175 DEBUG("Read completed");
1176 } else if (timeout_ms > 0) {
1177 DEBUG("Read timed out");
1180 DEBUG("Restarting read");
1183 RETURN_FAIL("ReadFile() failed");
1187 TRY(restart_wait_if_needed(port, bytes_read));
1189 RETURN_INT(bytes_read);
1192 size_t bytes_read = 0;
1193 struct timeval start, delta, now, end = {0, 0};
1199 /* Get time at start of operation. */
1201 /* Define duration of timeout. */
1202 delta.tv_sec = timeout_ms / 1000;
1203 delta.tv_usec = (timeout_ms % 1000) * 1000;
1204 /* Calculate time at which we should give up. */
1205 timeradd(&start, &delta, &end);
1209 FD_SET(port->fd, &fds);
1211 /* Loop until we have at least one byte, or timeout is reached. */
1212 while (bytes_read == 0) {
1214 * Check timeout only if we have run select() at least once,
1215 * to avoid any issues if a short timeout is reached before
1216 * select() is even run.
1218 if (timeout_ms && started) {
1220 if (timercmp(&now, &end, >))
1221 /* Timeout has expired. */
1223 timersub(&end, &now, &delta);
1225 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1228 if (errno == EINTR) {
1229 DEBUG("select() call was interrupted, repeating");
1232 RETURN_FAIL("select() failed");
1234 } else if (result == 0) {
1235 /* Timeout has expired. */
1240 result = read(port->fd, buf, count);
1243 if (errno == EAGAIN)
1244 /* This shouldn't happen because we did a select() first, but handle anyway. */
1247 /* This is an actual failure. */
1248 RETURN_FAIL("read() failed");
1251 bytes_read = result;
1254 if (bytes_read == 0)
1255 DEBUG("Read timed out");
1257 RETURN_INT(bytes_read);
1261 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1264 TRACE("%p, %p, %d", port, buf, count);
1269 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1271 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1277 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1278 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1279 port->timeouts.ReadTotalTimeoutConstant != 0) {
1280 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1281 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1282 port->timeouts.ReadTotalTimeoutConstant = 0;
1283 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1284 RETURN_FAIL("SetCommTimeouts() failed");
1288 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1289 if (GetLastError() != ERROR_IO_PENDING)
1290 RETURN_FAIL("ReadFile() failed");
1292 /* Get number of bytes read. */
1293 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1294 RETURN_FAIL("GetOverlappedResult() failed");
1296 TRY(restart_wait_if_needed(port, bytes_read));
1298 RETURN_INT(bytes_read);
1302 /* Returns the number of bytes read, or -1 upon failure. */
1303 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1304 if (errno == EAGAIN)
1305 /* No bytes available. */
1308 /* This is an actual failure. */
1309 RETURN_FAIL("read() failed");
1311 RETURN_INT(bytes_read);
1315 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1321 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1327 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1328 RETURN_FAIL("ClearCommError() failed");
1329 RETURN_INT(comstat.cbInQue);
1332 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1333 RETURN_FAIL("TIOCINQ ioctl failed");
1334 RETURN_INT(bytes_waiting);
1338 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1344 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1350 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1351 RETURN_FAIL("ClearCommError() failed");
1352 RETURN_INT(comstat.cbOutQue);
1355 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1356 RETURN_FAIL("TIOCOUTQ ioctl failed");
1357 RETURN_INT(bytes_waiting);
1361 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1363 struct sp_event_set *result;
1365 TRACE("%p", result_ptr);
1368 RETURN_ERROR(SP_ERR_ARG, "Null result");
1372 if (!(result = malloc(sizeof(struct sp_event_set))))
1373 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1375 memset(result, 0, sizeof(struct sp_event_set));
1377 *result_ptr = result;
1382 static enum sp_return add_handle(struct sp_event_set *event_set,
1383 event_handle handle, enum sp_event mask)
1386 enum sp_event *new_masks;
1388 TRACE("%p, %d, %d", event_set, handle, mask);
1390 if (!(new_handles = realloc(event_set->handles,
1391 sizeof(event_handle) * (event_set->count + 1))))
1392 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1394 event_set->handles = new_handles;
1396 if (!(new_masks = realloc(event_set->masks,
1397 sizeof(enum sp_event) * (event_set->count + 1))))
1398 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1400 event_set->masks = new_masks;
1402 ((event_handle *) event_set->handles)[event_set->count] = handle;
1403 event_set->masks[event_set->count] = mask;
1410 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1411 const struct sp_port *port, enum sp_event mask)
1413 TRACE("%p, %p, %d", event_set, port, mask);
1416 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1419 RETURN_ERROR(SP_ERR_ARG, "Null port");
1421 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1422 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1428 enum sp_event handle_mask;
1429 if ((handle_mask = mask & SP_EVENT_TX_READY))
1430 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1431 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1432 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1434 TRY(add_handle(event_set, port->fd, mask));
1440 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1442 TRACE("%p", event_set);
1445 DEBUG("Null event set");
1449 DEBUG("Freeing event set");
1451 if (event_set->handles)
1452 free(event_set->handles);
1453 if (event_set->masks)
1454 free(event_set->masks);
1461 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1462 unsigned int timeout_ms)
1464 TRACE("%p, %d", event_set, timeout_ms);
1467 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1470 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1471 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1472 RETURN_FAIL("WaitForMultipleObjects() failed");
1476 struct timeval start, delta, now, end = {0, 0};
1477 const struct timeval max_delta = {
1478 (INT_MAX / 1000), (INT_MAX % 1000) * 1000
1480 int started = 0, timeout_overflow = 0;
1481 int result, timeout_remaining_ms;
1482 struct pollfd *pollfds;
1485 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1486 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1488 for (i = 0; i < event_set->count; i++) {
1489 pollfds[i].fd = ((int *)event_set->handles)[i];
1490 pollfds[i].events = 0;
1491 pollfds[i].revents = 0;
1492 if (event_set->masks[i] & SP_EVENT_RX_READY)
1493 pollfds[i].events |= POLLIN;
1494 if (event_set->masks[i] & SP_EVENT_TX_READY)
1495 pollfds[i].events |= POLLOUT;
1496 if (event_set->masks[i] & SP_EVENT_ERROR)
1497 pollfds[i].events |= POLLERR;
1501 /* Get time at start of operation. */
1503 /* Define duration of timeout. */
1504 delta.tv_sec = timeout_ms / 1000;
1505 delta.tv_usec = (timeout_ms % 1000) * 1000;
1506 /* Calculate time at which we should give up. */
1507 timeradd(&start, &delta, &end);
1510 /* Loop until an event occurs. */
1513 * Check timeout only if we have run poll() at least once,
1514 * to avoid any issues if a short timeout is reached before
1515 * poll() is even run.
1518 timeout_remaining_ms = -1;
1519 } else if (!started) {
1520 timeout_overflow = (timeout_ms > INT_MAX);
1521 timeout_remaining_ms = timeout_overflow ? INT_MAX : timeout_ms;
1524 if (timercmp(&now, &end, >)) {
1525 DEBUG("Wait timed out");
1528 timersub(&end, &now, &delta);
1529 if ((timeout_overflow = timercmp(&delta, &max_delta, >)))
1531 timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1534 result = poll(pollfds, event_set->count, timeout_remaining_ms);
1538 if (errno == EINTR) {
1539 DEBUG("poll() call was interrupted, repeating");
1543 RETURN_FAIL("poll() failed");
1545 } else if (result == 0) {
1546 DEBUG("poll() timed out");
1547 if (!timeout_overflow)
1550 DEBUG("poll() completed");
1560 #ifdef USE_TERMIOS_SPEED
1561 static enum sp_return get_baudrate(int fd, int *baudrate)
1565 TRACE("%d, %p", fd, baudrate);
1567 DEBUG("Getting baud rate");
1569 if (!(data = malloc(get_termios_size())))
1570 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1572 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1574 RETURN_FAIL("Getting termios failed");
1577 *baudrate = get_termios_speed(data);
1584 static enum sp_return set_baudrate(int fd, int baudrate)
1588 TRACE("%d, %d", fd, baudrate);
1590 DEBUG("Getting baud rate");
1592 if (!(data = malloc(get_termios_size())))
1593 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1595 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1597 RETURN_FAIL("Getting termios failed");
1600 DEBUG("Setting baud rate");
1602 set_termios_speed(data, baudrate);
1604 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1606 RETURN_FAIL("Setting termios failed");
1613 #endif /* USE_TERMIOS_SPEED */
1616 static enum sp_return get_flow(int fd, struct port_data *data)
1620 TRACE("%d, %p", fd, data);
1622 DEBUG("Getting advanced flow control");
1624 if (!(termx = malloc(get_termiox_size())))
1625 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1627 if (ioctl(fd, TCGETX, termx) < 0) {
1629 RETURN_FAIL("Getting termiox failed");
1632 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1633 &data->dtr_flow, &data->dsr_flow);
1640 static enum sp_return set_flow(int fd, struct port_data *data)
1644 TRACE("%d, %p", fd, data);
1646 DEBUG("Getting advanced flow control");
1648 if (!(termx = malloc(get_termiox_size())))
1649 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1651 if (ioctl(fd, TCGETX, termx) < 0) {
1653 RETURN_FAIL("Getting termiox failed");
1656 DEBUG("Setting advanced flow control");
1658 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1659 data->dtr_flow, data->dsr_flow);
1661 if (ioctl(fd, TCSETX, termx) < 0) {
1663 RETURN_FAIL("Setting termiox failed");
1670 #endif /* USE_TERMIOX */
1672 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1673 struct sp_port_config *config)
1677 TRACE("%p, %p, %p", port, data, config);
1679 DEBUG_FMT("Getting configuration for port %s", port->name);
1682 if (!GetCommState(port->hdl, &data->dcb))
1683 RETURN_FAIL("GetCommState() failed");
1685 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1686 if (data->dcb.BaudRate == std_baudrates[i].index) {
1687 config->baudrate = std_baudrates[i].value;
1692 if (i == NUM_STD_BAUDRATES)
1693 /* BaudRate field can be either an index or a custom baud rate. */
1694 config->baudrate = data->dcb.BaudRate;
1696 config->bits = data->dcb.ByteSize;
1698 if (data->dcb.fParity)
1699 switch (data->dcb.Parity) {
1701 config->parity = SP_PARITY_NONE;
1704 config->parity = SP_PARITY_ODD;
1707 config->parity = SP_PARITY_EVEN;
1710 config->parity = SP_PARITY_MARK;
1713 config->parity = SP_PARITY_SPACE;
1716 config->parity = -1;
1719 config->parity = SP_PARITY_NONE;
1721 switch (data->dcb.StopBits) {
1723 config->stopbits = 1;
1726 config->stopbits = 2;
1729 config->stopbits = -1;
1732 switch (data->dcb.fRtsControl) {
1733 case RTS_CONTROL_DISABLE:
1734 config->rts = SP_RTS_OFF;
1736 case RTS_CONTROL_ENABLE:
1737 config->rts = SP_RTS_ON;
1739 case RTS_CONTROL_HANDSHAKE:
1740 config->rts = SP_RTS_FLOW_CONTROL;
1746 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1748 switch (data->dcb.fDtrControl) {
1749 case DTR_CONTROL_DISABLE:
1750 config->dtr = SP_DTR_OFF;
1752 case DTR_CONTROL_ENABLE:
1753 config->dtr = SP_DTR_ON;
1755 case DTR_CONTROL_HANDSHAKE:
1756 config->dtr = SP_DTR_FLOW_CONTROL;
1762 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1764 if (data->dcb.fInX) {
1765 if (data->dcb.fOutX)
1766 config->xon_xoff = SP_XONXOFF_INOUT;
1768 config->xon_xoff = SP_XONXOFF_IN;
1770 if (data->dcb.fOutX)
1771 config->xon_xoff = SP_XONXOFF_OUT;
1773 config->xon_xoff = SP_XONXOFF_DISABLED;
1778 if (tcgetattr(port->fd, &data->term) < 0)
1779 RETURN_FAIL("tcgetattr() failed");
1781 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1782 RETURN_FAIL("TIOCMGET ioctl failed");
1785 int ret = get_flow(port->fd, data);
1787 if (ret == SP_ERR_FAIL && errno == EINVAL)
1788 data->termiox_supported = 0;
1790 RETURN_CODEVAL(ret);
1792 data->termiox_supported = 1;
1794 data->termiox_supported = 0;
1797 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1798 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1799 config->baudrate = std_baudrates[i].value;
1804 if (i == NUM_STD_BAUDRATES) {
1806 config->baudrate = (int)data->term.c_ispeed;
1807 #elif defined(USE_TERMIOS_SPEED)
1808 TRY(get_baudrate(port->fd, &config->baudrate));
1810 config->baudrate = -1;
1814 switch (data->term.c_cflag & CSIZE) {
1831 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1832 config->parity = SP_PARITY_NONE;
1833 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1834 config->parity = -1;
1836 else if (data->term.c_cflag & CMSPAR)
1837 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1840 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1842 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1844 if (data->term.c_cflag & CRTSCTS) {
1845 config->rts = SP_RTS_FLOW_CONTROL;
1846 config->cts = SP_CTS_FLOW_CONTROL;
1848 if (data->termiox_supported && data->rts_flow)
1849 config->rts = SP_RTS_FLOW_CONTROL;
1851 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1853 config->cts = (data->termiox_supported && data->cts_flow) ?
1854 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1857 if (data->termiox_supported && data->dtr_flow)
1858 config->dtr = SP_DTR_FLOW_CONTROL;
1860 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1862 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1863 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1865 if (data->term.c_iflag & IXOFF) {
1866 if (data->term.c_iflag & IXON)
1867 config->xon_xoff = SP_XONXOFF_INOUT;
1869 config->xon_xoff = SP_XONXOFF_IN;
1871 if (data->term.c_iflag & IXON)
1872 config->xon_xoff = SP_XONXOFF_OUT;
1874 config->xon_xoff = SP_XONXOFF_DISABLED;
1881 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1882 const struct sp_port_config *config)
1886 BAUD_TYPE baud_nonstd;
1890 #ifdef USE_TERMIOS_SPEED
1891 int baud_nonstd = 0;
1894 TRACE("%p, %p, %p", port, data, config);
1896 DEBUG_FMT("Setting configuration for port %s", port->name);
1900 TRY(await_write_completion(port));
1902 if (config->baudrate >= 0) {
1903 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1904 if (config->baudrate == std_baudrates[i].value) {
1905 data->dcb.BaudRate = std_baudrates[i].index;
1910 if (i == NUM_STD_BAUDRATES)
1911 data->dcb.BaudRate = config->baudrate;
1913 /* Allocate write buffer for 50ms of data at baud rate. */
1914 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1915 port->write_buf = realloc(port->write_buf,
1916 port->write_buf_size);
1918 if (!port->write_buf)
1919 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1922 if (config->bits >= 0)
1923 data->dcb.ByteSize = config->bits;
1925 if (config->parity >= 0) {
1926 switch (config->parity) {
1927 case SP_PARITY_NONE:
1928 data->dcb.Parity = NOPARITY;
1931 data->dcb.Parity = ODDPARITY;
1933 case SP_PARITY_EVEN:
1934 data->dcb.Parity = EVENPARITY;
1936 case SP_PARITY_MARK:
1937 data->dcb.Parity = MARKPARITY;
1939 case SP_PARITY_SPACE:
1940 data->dcb.Parity = SPACEPARITY;
1943 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1947 if (config->stopbits >= 0) {
1948 switch (config->stopbits) {
1949 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1951 data->dcb.StopBits = ONESTOPBIT;
1954 data->dcb.StopBits = TWOSTOPBITS;
1957 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1961 if (config->rts >= 0) {
1962 switch (config->rts) {
1964 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1967 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1969 case SP_RTS_FLOW_CONTROL:
1970 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1973 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1977 if (config->cts >= 0) {
1978 switch (config->cts) {
1980 data->dcb.fOutxCtsFlow = FALSE;
1982 case SP_CTS_FLOW_CONTROL:
1983 data->dcb.fOutxCtsFlow = TRUE;
1986 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1990 if (config->dtr >= 0) {
1991 switch (config->dtr) {
1993 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1996 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1998 case SP_DTR_FLOW_CONTROL:
1999 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
2002 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
2006 if (config->dsr >= 0) {
2007 switch (config->dsr) {
2009 data->dcb.fOutxDsrFlow = FALSE;
2011 case SP_DSR_FLOW_CONTROL:
2012 data->dcb.fOutxDsrFlow = TRUE;
2015 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2019 if (config->xon_xoff >= 0) {
2020 switch (config->xon_xoff) {
2021 case SP_XONXOFF_DISABLED:
2022 data->dcb.fInX = FALSE;
2023 data->dcb.fOutX = FALSE;
2026 data->dcb.fInX = TRUE;
2027 data->dcb.fOutX = FALSE;
2029 case SP_XONXOFF_OUT:
2030 data->dcb.fInX = FALSE;
2031 data->dcb.fOutX = TRUE;
2033 case SP_XONXOFF_INOUT:
2034 data->dcb.fInX = TRUE;
2035 data->dcb.fOutX = TRUE;
2038 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2042 if (!SetCommState(port->hdl, &data->dcb))
2043 RETURN_FAIL("SetCommState() failed");
2049 if (config->baudrate >= 0) {
2050 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2051 if (config->baudrate == std_baudrates[i].value) {
2052 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2053 RETURN_FAIL("cfsetospeed() failed");
2055 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2056 RETURN_FAIL("cfsetispeed() failed");
2061 /* Non-standard baud rate */
2062 if (i == NUM_STD_BAUDRATES) {
2064 /* Set "dummy" baud rate. */
2065 if (cfsetspeed(&data->term, B9600) < 0)
2066 RETURN_FAIL("cfsetspeed() failed");
2067 baud_nonstd = config->baudrate;
2068 #elif defined(USE_TERMIOS_SPEED)
2071 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2076 if (config->bits >= 0) {
2077 data->term.c_cflag &= ~CSIZE;
2078 switch (config->bits) {
2080 data->term.c_cflag |= CS8;
2083 data->term.c_cflag |= CS7;
2086 data->term.c_cflag |= CS6;
2089 data->term.c_cflag |= CS5;
2092 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2096 if (config->parity >= 0) {
2097 data->term.c_iflag &= ~IGNPAR;
2098 data->term.c_cflag &= ~(PARENB | PARODD);
2100 data->term.c_cflag &= ~CMSPAR;
2102 switch (config->parity) {
2103 case SP_PARITY_NONE:
2104 data->term.c_iflag |= IGNPAR;
2106 case SP_PARITY_EVEN:
2107 data->term.c_cflag |= PARENB;
2110 data->term.c_cflag |= PARENB | PARODD;
2113 case SP_PARITY_MARK:
2114 data->term.c_cflag |= PARENB | PARODD;
2115 data->term.c_cflag |= CMSPAR;
2117 case SP_PARITY_SPACE:
2118 data->term.c_cflag |= PARENB;
2119 data->term.c_cflag |= CMSPAR;
2122 case SP_PARITY_MARK:
2123 case SP_PARITY_SPACE:
2124 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2127 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2131 if (config->stopbits >= 0) {
2132 data->term.c_cflag &= ~CSTOPB;
2133 switch (config->stopbits) {
2135 data->term.c_cflag &= ~CSTOPB;
2138 data->term.c_cflag |= CSTOPB;
2141 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2145 if (config->rts >= 0 || config->cts >= 0) {
2146 if (data->termiox_supported) {
2147 data->rts_flow = data->cts_flow = 0;
2148 switch (config->rts) {
2151 controlbits = TIOCM_RTS;
2152 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2153 RETURN_FAIL("Setting RTS signal level failed");
2155 case SP_RTS_FLOW_CONTROL:
2161 if (config->cts == SP_CTS_FLOW_CONTROL)
2164 if (data->rts_flow && data->cts_flow)
2165 data->term.c_iflag |= CRTSCTS;
2167 data->term.c_iflag &= ~CRTSCTS;
2169 /* Asymmetric use of RTS/CTS not supported. */
2170 if (data->term.c_iflag & CRTSCTS) {
2171 /* Flow control can only be disabled for both RTS & CTS together. */
2172 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2173 if (config->cts != SP_CTS_IGNORE)
2174 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2176 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2177 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2178 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2181 /* Flow control can only be enabled for both RTS & CTS together. */
2182 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2183 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2184 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2187 if (config->rts >= 0) {
2188 if (config->rts == SP_RTS_FLOW_CONTROL) {
2189 data->term.c_iflag |= CRTSCTS;
2191 controlbits = TIOCM_RTS;
2192 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2194 RETURN_FAIL("Setting RTS signal level failed");
2200 if (config->dtr >= 0 || config->dsr >= 0) {
2201 if (data->termiox_supported) {
2202 data->dtr_flow = data->dsr_flow = 0;
2203 switch (config->dtr) {
2206 controlbits = TIOCM_DTR;
2207 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2208 RETURN_FAIL("Setting DTR signal level failed");
2210 case SP_DTR_FLOW_CONTROL:
2216 if (config->dsr == SP_DSR_FLOW_CONTROL)
2219 /* DTR/DSR flow control not supported. */
2220 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2221 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2223 if (config->dtr >= 0) {
2224 controlbits = TIOCM_DTR;
2225 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2227 RETURN_FAIL("Setting DTR signal level failed");
2232 if (config->xon_xoff >= 0) {
2233 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2234 switch (config->xon_xoff) {
2235 case SP_XONXOFF_DISABLED:
2238 data->term.c_iflag |= IXOFF;
2240 case SP_XONXOFF_OUT:
2241 data->term.c_iflag |= IXON | IXANY;
2243 case SP_XONXOFF_INOUT:
2244 data->term.c_iflag |= IXON | IXOFF | IXANY;
2247 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2251 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2252 RETURN_FAIL("tcsetattr() failed");
2255 if (baud_nonstd != B0) {
2256 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2257 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2259 * Set baud rates in data->term to correct, but incompatible
2260 * with tcsetattr() value, same as delivered by tcgetattr().
2262 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2263 RETURN_FAIL("cfsetspeed() failed");
2265 #elif defined(__linux__)
2266 #ifdef USE_TERMIOS_SPEED
2268 TRY(set_baudrate(port->fd, config->baudrate));
2271 if (data->termiox_supported)
2272 TRY(set_flow(port->fd, data));
2276 #endif /* !_WIN32 */
2281 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2283 struct sp_port_config *config;
2285 TRACE("%p", config_ptr);
2288 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2292 if (!(config = malloc(sizeof(struct sp_port_config))))
2293 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2295 config->baudrate = -1;
2297 config->parity = -1;
2298 config->stopbits = -1;
2304 *config_ptr = config;
2309 SP_API void sp_free_config(struct sp_port_config *config)
2311 TRACE("%p", config);
2314 DEBUG("Null config");
2321 SP_API enum sp_return sp_get_config(struct sp_port *port,
2322 struct sp_port_config *config)
2324 struct port_data data;
2326 TRACE("%p, %p", port, config);
2331 RETURN_ERROR(SP_ERR_ARG, "Null config");
2333 TRY(get_config(port, &data, config));
2338 SP_API enum sp_return sp_set_config(struct sp_port *port,
2339 const struct sp_port_config *config)
2341 struct port_data data;
2342 struct sp_port_config prev_config;
2344 TRACE("%p, %p", port, config);
2349 RETURN_ERROR(SP_ERR_ARG, "Null config");
2351 TRY(get_config(port, &data, &prev_config));
2352 TRY(set_config(port, &data, config));
2357 #define CREATE_ACCESSORS(x, type) \
2358 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2359 struct port_data data; \
2360 struct sp_port_config config; \
2361 TRACE("%p, %d", port, x); \
2362 CHECK_OPEN_PORT(); \
2363 TRY(get_config(port, &data, &config)); \
2365 TRY(set_config(port, &data, &config)); \
2368 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2370 TRACE("%p, %p", config, x); \
2372 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2374 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2378 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2380 TRACE("%p, %d", config, x); \
2382 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2387 CREATE_ACCESSORS(baudrate, int)
2388 CREATE_ACCESSORS(bits, int)
2389 CREATE_ACCESSORS(parity, enum sp_parity)
2390 CREATE_ACCESSORS(stopbits, int)
2391 CREATE_ACCESSORS(rts, enum sp_rts)
2392 CREATE_ACCESSORS(cts, enum sp_cts)
2393 CREATE_ACCESSORS(dtr, enum sp_dtr)
2394 CREATE_ACCESSORS(dsr, enum sp_dsr)
2395 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2397 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2398 enum sp_flowcontrol flowcontrol)
2401 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2403 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2404 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2406 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2407 config->xon_xoff = SP_XONXOFF_INOUT;
2409 config->xon_xoff = SP_XONXOFF_DISABLED;
2411 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2412 config->rts = SP_RTS_FLOW_CONTROL;
2413 config->cts = SP_CTS_FLOW_CONTROL;
2415 if (config->rts == SP_RTS_FLOW_CONTROL)
2416 config->rts = SP_RTS_ON;
2417 config->cts = SP_CTS_IGNORE;
2420 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2421 config->dtr = SP_DTR_FLOW_CONTROL;
2422 config->dsr = SP_DSR_FLOW_CONTROL;
2424 if (config->dtr == SP_DTR_FLOW_CONTROL)
2425 config->dtr = SP_DTR_ON;
2426 config->dsr = SP_DSR_IGNORE;
2432 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2433 enum sp_flowcontrol flowcontrol)
2435 struct port_data data;
2436 struct sp_port_config config;
2438 TRACE("%p, %d", port, flowcontrol);
2442 TRY(get_config(port, &data, &config));
2444 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2446 TRY(set_config(port, &data, &config));
2451 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2452 enum sp_signal *signals)
2454 TRACE("%p, %p", port, signals);
2459 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2461 DEBUG_FMT("Getting control signals for port %s", port->name);
2466 if (GetCommModemStatus(port->hdl, &bits) == 0)
2467 RETURN_FAIL("GetCommModemStatus() failed");
2468 if (bits & MS_CTS_ON)
2469 *signals |= SP_SIG_CTS;
2470 if (bits & MS_DSR_ON)
2471 *signals |= SP_SIG_DSR;
2472 if (bits & MS_RLSD_ON)
2473 *signals |= SP_SIG_DCD;
2474 if (bits & MS_RING_ON)
2475 *signals |= SP_SIG_RI;
2478 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2479 RETURN_FAIL("TIOCMGET ioctl failed");
2480 if (bits & TIOCM_CTS)
2481 *signals |= SP_SIG_CTS;
2482 if (bits & TIOCM_DSR)
2483 *signals |= SP_SIG_DSR;
2484 if (bits & TIOCM_CAR)
2485 *signals |= SP_SIG_DCD;
2486 if (bits & TIOCM_RNG)
2487 *signals |= SP_SIG_RI;
2492 SP_API enum sp_return sp_start_break(struct sp_port *port)
2498 if (SetCommBreak(port->hdl) == 0)
2499 RETURN_FAIL("SetCommBreak() failed");
2501 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2502 RETURN_FAIL("TIOCSBRK ioctl failed");
2508 SP_API enum sp_return sp_end_break(struct sp_port *port)
2514 if (ClearCommBreak(port->hdl) == 0)
2515 RETURN_FAIL("ClearCommBreak() failed");
2517 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2518 RETURN_FAIL("TIOCCBRK ioctl failed");
2524 SP_API int sp_last_error_code(void)
2528 RETURN_INT(GetLastError());
2534 SP_API char *sp_last_error_message(void)
2540 DWORD error = GetLastError();
2542 DWORD length = FormatMessage(
2543 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2544 FORMAT_MESSAGE_FROM_SYSTEM |
2545 FORMAT_MESSAGE_IGNORE_INSERTS,
2548 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2552 if (length >= 2 && message[length - 2] == '\r')
2553 message[length - 2] = '\0';
2555 RETURN_STRING(message);
2557 RETURN_STRING(strerror(errno));
2561 SP_API void sp_free_error_message(char *message)
2563 TRACE("%s", message);
2574 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2576 TRACE("%p", handler);
2578 sp_debug_handler = handler;
2583 SP_API void sp_default_debug_handler(const char *format, ...)
2586 va_start(args, format);
2587 if (getenv("LIBSERIALPORT_DEBUG")) {
2588 fputs("sp: ", stderr);
2589 vfprintf(stderr, format, args);
2594 SP_API int sp_get_major_package_version(void)
2596 return SP_PACKAGE_VERSION_MAJOR;
2599 SP_API int sp_get_minor_package_version(void)
2601 return SP_PACKAGE_VERSION_MINOR;
2604 SP_API int sp_get_micro_package_version(void)
2606 return SP_PACKAGE_VERSION_MICRO;
2609 SP_API const char *sp_get_package_version_string(void)
2611 return SP_PACKAGE_VERSION_STRING;
2614 SP_API int sp_get_current_lib_version(void)
2616 return SP_LIB_VERSION_CURRENT;
2619 SP_API int sp_get_revision_lib_version(void)
2621 return SP_LIB_VERSION_REVISION;
2624 SP_API int sp_get_age_lib_version(void)
2626 return SP_LIB_VERSION_AGE;
2629 SP_API const char *sp_get_lib_version_string(void)
2631 return SP_LIB_VERSION_STRING;