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 gettimeofday(time, NULL);
65 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
68 #ifndef NO_PORT_METADATA
73 TRACE("%s, %p", portname, port_ptr);
76 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
81 RETURN_ERROR(SP_ERR_ARG, "Null port name");
83 DEBUG_FMT("Building structure for port %s", portname);
85 #if !defined(_WIN32) && defined(HAVE_REALPATH)
87 * get_port_details() below tries to be too smart and figure out
88 * some transport properties from the port name which breaks with
89 * symlinks. Therefore we canonicalize the portname first.
91 char pathbuf[PATH_MAX + 1];
92 char *res = realpath(portname, pathbuf);
94 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
99 if (!(port = malloc(sizeof(struct sp_port))))
100 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
102 len = strlen(portname) + 1;
104 if (!(port->name = malloc(len))) {
106 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
109 memcpy(port->name, portname, len);
112 port->usb_path = NULL;
113 port->hdl = INVALID_HANDLE_VALUE;
114 port->write_buf = NULL;
115 port->write_buf_size = 0;
120 port->description = NULL;
121 port->transport = SP_TRANSPORT_NATIVE;
123 port->usb_address = -1;
126 port->usb_manufacturer = NULL;
127 port->usb_product = NULL;
128 port->usb_serial = NULL;
129 port->bluetooth_address = NULL;
131 #ifndef NO_PORT_METADATA
132 if ((ret = get_port_details(port)) != SP_OK) {
143 SP_API char *sp_get_port_name(const struct sp_port *port)
150 RETURN_STRING(port->name);
153 SP_API char *sp_get_port_description(const struct sp_port *port)
157 if (!port || !port->description)
160 RETURN_STRING(port->description);
163 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
168 RETURN_ERROR(SP_ERR_ARG, "Null port");
170 RETURN_INT(port->transport);
173 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
174 int *usb_bus,int *usb_address)
179 RETURN_ERROR(SP_ERR_ARG, "Null port");
180 if (port->transport != SP_TRANSPORT_USB)
181 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
182 if (port->usb_bus < 0 || port->usb_address < 0)
183 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
186 *usb_bus = port->usb_bus;
188 *usb_address = port->usb_address;
193 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
194 int *usb_vid, int *usb_pid)
199 RETURN_ERROR(SP_ERR_ARG, "Null port");
200 if (port->transport != SP_TRANSPORT_USB)
201 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
202 if (port->usb_vid < 0 || port->usb_pid < 0)
203 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
206 *usb_vid = port->usb_vid;
208 *usb_pid = port->usb_pid;
213 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
217 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
220 RETURN_STRING(port->usb_manufacturer);
223 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
227 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
230 RETURN_STRING(port->usb_product);
233 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
237 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
240 RETURN_STRING(port->usb_serial);
243 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
247 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
248 || !port->bluetooth_address)
251 RETURN_STRING(port->bluetooth_address);
254 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
257 TRACE("%p, %p", port, result_ptr);
260 RETURN_ERROR(SP_ERR_ARG, "Null port");
262 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
265 HANDLE *handle_ptr = result_ptr;
266 *handle_ptr = port->hdl;
268 int *fd_ptr = result_ptr;
275 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
276 struct sp_port **copy_ptr)
278 TRACE("%p, %p", port, copy_ptr);
281 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
286 RETURN_ERROR(SP_ERR_ARG, "Null port");
289 RETURN_ERROR(SP_ERR_ARG, "Null port name");
291 DEBUG("Copying port structure");
293 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
296 SP_API void sp_free_port(struct sp_port *port)
305 DEBUG("Freeing port structure");
309 if (port->description)
310 free(port->description);
311 if (port->usb_manufacturer)
312 free(port->usb_manufacturer);
313 if (port->usb_product)
314 free(port->usb_product);
315 if (port->usb_serial)
316 free(port->usb_serial);
317 if (port->bluetooth_address)
318 free(port->bluetooth_address);
321 free(port->usb_path);
323 free(port->write_buf);
331 SP_PRIV struct sp_port **list_append(struct sp_port **list,
332 const char *portname)
337 for (count = 0; list[count]; count++)
339 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
342 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
344 list[count + 1] = NULL;
348 sp_free_port_list(list);
352 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
354 #ifndef NO_ENUMERATION
355 struct sp_port **list;
359 TRACE("%p", list_ptr);
362 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
366 #ifdef NO_ENUMERATION
367 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
369 DEBUG("Enumerating ports");
371 if (!(list = malloc(sizeof(struct sp_port *))))
372 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
376 ret = list_ports(&list);
381 sp_free_port_list(list);
389 SP_API void sp_free_port_list(struct sp_port **list)
400 DEBUG("Freeing port list");
402 for (i = 0; list[i]; i++)
403 sp_free_port(list[i]);
409 #define CHECK_PORT() do { \
411 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
413 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
416 #define CHECK_PORT_HANDLE() do { \
417 if (port->hdl == INVALID_HANDLE_VALUE) \
418 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
421 #define CHECK_PORT_HANDLE() do { \
423 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
426 #define CHECK_OPEN_PORT() do { \
428 CHECK_PORT_HANDLE(); \
432 /** To be called after port receive buffer is emptied. */
433 static enum sp_return restart_wait(struct sp_port *port)
437 if (port->wait_running) {
438 /* Check status of running wait operation. */
439 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
440 &wait_result, FALSE)) {
441 DEBUG("Previous wait completed");
442 port->wait_running = FALSE;
443 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
444 DEBUG("Previous wait still running");
447 RETURN_FAIL("GetOverlappedResult() failed");
451 if (!port->wait_running) {
452 /* Start new wait operation. */
453 if (WaitCommEvent(port->hdl, &port->events,
455 DEBUG("New wait returned, events already pending");
456 } else if (GetLastError() == ERROR_IO_PENDING) {
457 DEBUG("New wait running in background");
458 port->wait_running = TRUE;
460 RETURN_FAIL("WaitCommEvent() failed");
468 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
470 struct port_data data;
471 struct sp_port_config config;
474 TRACE("%p, 0x%x", port, flags);
478 if (flags > SP_MODE_READ_WRITE)
479 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
481 DEBUG_FMT("Opening port %s", port->name);
484 DWORD desired_access = 0, flags_and_attributes = 0, errors;
485 char *escaped_port_name;
488 /* Prefix port name with '\\.\' to work with ports above COM9. */
489 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
490 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
491 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
493 /* Map 'flags' to the OS-specific settings. */
494 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
495 if (flags & SP_MODE_READ)
496 desired_access |= GENERIC_READ;
497 if (flags & SP_MODE_WRITE)
498 desired_access |= GENERIC_WRITE;
500 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
501 OPEN_EXISTING, flags_and_attributes, 0);
503 free(escaped_port_name);
505 if (port->hdl == INVALID_HANDLE_VALUE)
506 RETURN_FAIL("Port CreateFile() failed");
508 /* All timeouts initially disabled. */
509 port->timeouts.ReadIntervalTimeout = 0;
510 port->timeouts.ReadTotalTimeoutMultiplier = 0;
511 port->timeouts.ReadTotalTimeoutConstant = 0;
512 port->timeouts.WriteTotalTimeoutMultiplier = 0;
513 port->timeouts.WriteTotalTimeoutConstant = 0;
515 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
517 RETURN_FAIL("SetCommTimeouts() failed");
520 /* Prepare OVERLAPPED structures. */
521 #define INIT_OVERLAPPED(ovl) do { \
522 memset(&port->ovl, 0, sizeof(port->ovl)); \
523 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
524 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
525 == INVALID_HANDLE_VALUE) { \
527 RETURN_FAIL(#ovl "CreateEvent() failed"); \
531 INIT_OVERLAPPED(read_ovl);
532 INIT_OVERLAPPED(write_ovl);
533 INIT_OVERLAPPED(wait_ovl);
535 /* Set event mask for RX and error events. */
536 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
538 RETURN_FAIL("SetCommMask() failed");
541 port->writing = FALSE;
542 port->wait_running = FALSE;
544 ret = restart_wait(port);
551 int flags_local = O_NONBLOCK | O_NOCTTY;
553 /* Map 'flags' to the OS-specific settings. */
554 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
555 flags_local |= O_RDWR;
556 else if (flags & SP_MODE_READ)
557 flags_local |= O_RDONLY;
558 else if (flags & SP_MODE_WRITE)
559 flags_local |= O_WRONLY;
561 if ((port->fd = open(port->name, flags_local)) < 0)
562 RETURN_FAIL("open() failed");
565 ret = get_config(port, &data, &config);
572 /* Set sane port settings. */
574 data.dcb.fBinary = TRUE;
575 data.dcb.fDsrSensitivity = FALSE;
576 data.dcb.fErrorChar = FALSE;
577 data.dcb.fNull = FALSE;
578 data.dcb.fAbortOnError = FALSE;
580 /* Turn off all fancy termios tricks, give us a raw channel. */
581 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
583 data.term.c_iflag &= ~IUCLC;
585 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
587 data.term.c_oflag &= ~OLCUC;
590 data.term.c_oflag &= ~NLDLY;
593 data.term.c_oflag &= ~CRDLY;
596 data.term.c_oflag &= ~TABDLY;
599 data.term.c_oflag &= ~BSDLY;
602 data.term.c_oflag &= ~VTDLY;
605 data.term.c_oflag &= ~FFDLY;
608 data.term.c_oflag &= ~OFILL;
610 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
611 data.term.c_cc[VMIN] = 0;
612 data.term.c_cc[VTIME] = 0;
614 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
615 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
619 if (ClearCommError(port->hdl, &errors, &status) == 0)
620 RETURN_FAIL("ClearCommError() failed");
623 ret = set_config(port, &data, &config);
633 SP_API enum sp_return sp_close(struct sp_port *port)
639 DEBUG_FMT("Closing port %s", port->name);
642 /* Returns non-zero upon success, 0 upon failure. */
643 if (CloseHandle(port->hdl) == 0)
644 RETURN_FAIL("Port CloseHandle() failed");
645 port->hdl = INVALID_HANDLE_VALUE;
647 /* Close event handles for overlapped structures. */
648 #define CLOSE_OVERLAPPED(ovl) do { \
649 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
650 CloseHandle(port->ovl.hEvent) == 0) \
651 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
653 CLOSE_OVERLAPPED(read_ovl);
654 CLOSE_OVERLAPPED(write_ovl);
655 CLOSE_OVERLAPPED(wait_ovl);
657 if (port->write_buf) {
658 free(port->write_buf);
659 port->write_buf = NULL;
662 /* Returns 0 upon success, -1 upon failure. */
663 if (close(port->fd) == -1)
664 RETURN_FAIL("close() failed");
671 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
673 TRACE("%p, 0x%x", port, buffers);
677 if (buffers > SP_BUF_BOTH)
678 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
680 const char *buffer_names[] = {"no", "input", "output", "both"};
682 DEBUG_FMT("Flushing %s buffers on port %s",
683 buffer_names[buffers], port->name);
687 if (buffers & SP_BUF_INPUT)
688 flags |= PURGE_RXCLEAR;
689 if (buffers & SP_BUF_OUTPUT)
690 flags |= PURGE_TXCLEAR;
692 /* Returns non-zero upon success, 0 upon failure. */
693 if (PurgeComm(port->hdl, flags) == 0)
694 RETURN_FAIL("PurgeComm() failed");
696 if (buffers & SP_BUF_INPUT)
697 TRY(restart_wait(port));
700 if (buffers == SP_BUF_BOTH)
702 else if (buffers == SP_BUF_INPUT)
704 else if (buffers == SP_BUF_OUTPUT)
707 /* Returns 0 upon success, -1 upon failure. */
708 if (tcflush(port->fd, flags) < 0)
709 RETURN_FAIL("tcflush() failed");
714 SP_API enum sp_return sp_drain(struct sp_port *port)
720 DEBUG_FMT("Draining port %s", port->name);
723 /* Returns non-zero upon success, 0 upon failure. */
724 if (FlushFileBuffers(port->hdl) == 0)
725 RETURN_FAIL("FlushFileBuffers() failed");
732 result = ioctl(port->fd, TCSBRK, &arg);
734 result = tcdrain(port->fd);
737 if (errno == EINTR) {
738 DEBUG("tcdrain() was interrupted");
741 RETURN_FAIL("tcdrain() failed");
751 static enum sp_return await_write_completion(struct sp_port *port)
757 /* Wait for previous non-blocking write to complete, if any. */
759 DEBUG("Waiting for previous write to complete");
760 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
763 RETURN_FAIL("Previous write failed to complete");
764 DEBUG("Previous write completed");
771 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
772 size_t count, unsigned int timeout_ms)
774 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
779 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
782 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
783 count, port->name, timeout_ms);
785 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
792 DWORD bytes_written = 0;
794 TRY(await_write_completion(port));
797 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
798 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
799 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
800 RETURN_FAIL("SetCommTimeouts() failed");
803 /* Reduce count if it exceeds the WriteFile limit. */
804 if (count > WRITEFILE_MAX_SIZE)
805 count = WRITEFILE_MAX_SIZE;
808 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
809 DEBUG("Write completed immediately");
811 } else if (GetLastError() == ERROR_IO_PENDING) {
812 DEBUG("Waiting for write to complete");
813 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
814 if (GetLastError() == ERROR_SEM_TIMEOUT) {
815 DEBUG("Write timed out");
818 RETURN_FAIL("GetOverlappedResult() failed");
821 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
822 RETURN_INT(bytes_written);
824 RETURN_FAIL("WriteFile() failed");
827 size_t bytes_written = 0;
828 unsigned char *ptr = (unsigned char *) buf;
829 struct timeval start, delta, now, end = {0, 0};
835 /* Get time at start of operation. */
837 /* Define duration of timeout. */
838 delta.tv_sec = timeout_ms / 1000;
839 delta.tv_usec = (timeout_ms % 1000) * 1000;
840 /* Calculate time at which we should give up. */
841 timeradd(&start, &delta, &end);
845 FD_SET(port->fd, &fds);
847 /* Loop until we have written the requested number of bytes. */
848 while (bytes_written < count) {
850 * Check timeout only if we have run select() at least once,
851 * to avoid any issues if a short timeout is reached before
852 * select() is even run.
854 if (timeout_ms && started) {
856 if (timercmp(&now, &end, >))
857 /* Timeout has expired. */
859 timersub(&end, &now, &delta);
861 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
864 if (errno == EINTR) {
865 DEBUG("select() call was interrupted, repeating");
868 RETURN_FAIL("select() failed");
870 } else if (result == 0) {
871 /* Timeout has expired. */
876 result = write(port->fd, ptr, count - bytes_written);
880 /* This shouldn't happen because we did a select() first, but handle anyway. */
883 /* This is an actual failure. */
884 RETURN_FAIL("write() failed");
887 bytes_written += result;
891 if (bytes_written < count)
892 DEBUG("Write timed out");
894 RETURN_INT(bytes_written);
898 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
899 const void *buf, size_t count)
901 TRACE("%p, %p, %d", port, buf, count);
906 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
908 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
916 /* Check whether previous write is complete. */
918 if (HasOverlappedIoCompleted(&port->write_ovl)) {
919 DEBUG("Previous write completed");
922 DEBUG("Previous write not complete");
923 /* Can't take a new write until the previous one finishes. */
929 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
930 port->timeouts.WriteTotalTimeoutConstant = 0;
931 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
932 RETURN_FAIL("SetCommTimeouts() failed");
935 /* Reduce count if it exceeds the WriteFile limit. */
936 if (count > WRITEFILE_MAX_SIZE)
937 count = WRITEFILE_MAX_SIZE;
939 /* Copy data to our write buffer. */
940 buf_bytes = min(port->write_buf_size, count);
941 memcpy(port->write_buf, buf, buf_bytes);
943 /* Start asynchronous write. */
944 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
945 if (GetLastError() == ERROR_IO_PENDING) {
946 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
947 DEBUG("Asynchronous write completed immediately");
949 DEBUG("Asynchronous write running");
951 /* Actual failure of some kind. */
952 RETURN_FAIL("WriteFile() failed");
956 DEBUG("All bytes written immediately");
958 RETURN_INT(buf_bytes);
960 /* Returns the number of bytes written, or -1 upon failure. */
961 ssize_t written = write(port->fd, buf, count);
965 // Buffer is full, no bytes written.
968 RETURN_FAIL("write() failed");
976 /* Restart wait operation if buffer was emptied. */
977 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
985 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
986 RETURN_FAIL("ClearCommError() failed");
988 if (comstat.cbInQue == 0)
989 TRY(restart_wait(port));
995 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
996 size_t count, unsigned int timeout_ms)
998 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1003 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1006 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1007 count, port->name, timeout_ms);
1009 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1016 DWORD bytes_read = 0;
1019 if (port->timeouts.ReadIntervalTimeout != 0 ||
1020 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1021 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1022 port->timeouts.ReadIntervalTimeout = 0;
1023 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1024 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1025 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1026 RETURN_FAIL("SetCommTimeouts() failed");
1030 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1031 DEBUG("Read completed immediately");
1033 } else if (GetLastError() == ERROR_IO_PENDING) {
1034 DEBUG("Waiting for read to complete");
1035 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1036 RETURN_FAIL("GetOverlappedResult() failed");
1037 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1039 RETURN_FAIL("ReadFile() failed");
1042 TRY(restart_wait_if_needed(port, bytes_read));
1044 RETURN_INT(bytes_read);
1047 size_t bytes_read = 0;
1048 unsigned char *ptr = (unsigned char *)buf;
1049 struct timeval start, delta, now, end = {0, 0};
1055 /* Get time at start of operation. */
1057 /* Define duration of timeout. */
1058 delta.tv_sec = timeout_ms / 1000;
1059 delta.tv_usec = (timeout_ms % 1000) * 1000;
1060 /* Calculate time at which we should give up. */
1061 timeradd(&start, &delta, &end);
1065 FD_SET(port->fd, &fds);
1067 /* Loop until we have the requested number of bytes. */
1068 while (bytes_read < count) {
1070 * Check timeout only if we have run select() at least once,
1071 * to avoid any issues if a short timeout is reached before
1072 * select() is even run.
1074 if (timeout_ms && started) {
1076 if (timercmp(&now, &end, >))
1077 /* Timeout has expired. */
1079 timersub(&end, &now, &delta);
1081 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1084 if (errno == EINTR) {
1085 DEBUG("select() call was interrupted, repeating");
1088 RETURN_FAIL("select() failed");
1090 } else if (result == 0) {
1091 /* Timeout has expired. */
1096 result = read(port->fd, ptr, count - bytes_read);
1099 if (errno == EAGAIN)
1101 * This shouldn't happen because we did a
1102 * select() first, but handle anyway.
1106 /* This is an actual failure. */
1107 RETURN_FAIL("read() failed");
1110 bytes_read += result;
1114 if (bytes_read < count)
1115 DEBUG("Read timed out");
1117 RETURN_INT(bytes_read);
1121 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1122 size_t count, unsigned int timeout_ms)
1124 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1129 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1132 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1135 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1136 count, port->name, timeout_ms);
1138 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1142 DWORD bytes_read = 0;
1144 /* If timeout_ms == 0, set maximum timeout. */
1145 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1148 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1149 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1150 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1151 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1152 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1153 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1154 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1155 RETURN_FAIL("SetCommTimeouts() failed");
1158 /* Loop until we have at least one byte, or timeout is reached. */
1159 while (bytes_read == 0) {
1161 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1162 DEBUG("Read completed immediately");
1163 } else if (GetLastError() == ERROR_IO_PENDING) {
1164 DEBUG("Waiting for read to complete");
1165 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1166 RETURN_FAIL("GetOverlappedResult() failed");
1167 if (bytes_read > 0) {
1168 DEBUG("Read completed");
1169 } else if (timeout_ms > 0) {
1170 DEBUG("Read timed out");
1173 DEBUG("Restarting read");
1176 RETURN_FAIL("ReadFile() failed");
1180 TRY(restart_wait_if_needed(port, bytes_read));
1182 RETURN_INT(bytes_read);
1185 size_t bytes_read = 0;
1186 struct timeval start, delta, now, end = {0, 0};
1192 /* Get time at start of operation. */
1194 /* Define duration of timeout. */
1195 delta.tv_sec = timeout_ms / 1000;
1196 delta.tv_usec = (timeout_ms % 1000) * 1000;
1197 /* Calculate time at which we should give up. */
1198 timeradd(&start, &delta, &end);
1202 FD_SET(port->fd, &fds);
1204 /* Loop until we have at least one byte, or timeout is reached. */
1205 while (bytes_read == 0) {
1207 * Check timeout only if we have run select() at least once,
1208 * to avoid any issues if a short timeout is reached before
1209 * select() is even run.
1211 if (timeout_ms && started) {
1213 if (timercmp(&now, &end, >))
1214 /* Timeout has expired. */
1216 timersub(&end, &now, &delta);
1218 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1221 if (errno == EINTR) {
1222 DEBUG("select() call was interrupted, repeating");
1225 RETURN_FAIL("select() failed");
1227 } else if (result == 0) {
1228 /* Timeout has expired. */
1233 result = read(port->fd, buf, count);
1236 if (errno == EAGAIN)
1237 /* This shouldn't happen because we did a select() first, but handle anyway. */
1240 /* This is an actual failure. */
1241 RETURN_FAIL("read() failed");
1244 bytes_read = result;
1247 if (bytes_read == 0)
1248 DEBUG("Read timed out");
1250 RETURN_INT(bytes_read);
1254 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1257 TRACE("%p, %p, %d", port, buf, count);
1262 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1264 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1270 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1271 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1272 port->timeouts.ReadTotalTimeoutConstant != 0) {
1273 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1274 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1275 port->timeouts.ReadTotalTimeoutConstant = 0;
1276 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1277 RETURN_FAIL("SetCommTimeouts() failed");
1281 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1282 if (GetLastError() != ERROR_IO_PENDING)
1283 RETURN_FAIL("ReadFile() failed");
1285 /* Get number of bytes read. */
1286 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1287 RETURN_FAIL("GetOverlappedResult() failed");
1289 TRY(restart_wait_if_needed(port, bytes_read));
1291 RETURN_INT(bytes_read);
1295 /* Returns the number of bytes read, or -1 upon failure. */
1296 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1297 if (errno == EAGAIN)
1298 /* No bytes available. */
1301 /* This is an actual failure. */
1302 RETURN_FAIL("read() failed");
1304 RETURN_INT(bytes_read);
1308 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1314 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1320 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1321 RETURN_FAIL("ClearCommError() failed");
1322 RETURN_INT(comstat.cbInQue);
1325 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1326 RETURN_FAIL("TIOCINQ ioctl failed");
1327 RETURN_INT(bytes_waiting);
1331 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1337 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1343 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1344 RETURN_FAIL("ClearCommError() failed");
1345 RETURN_INT(comstat.cbOutQue);
1348 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1349 RETURN_FAIL("TIOCOUTQ ioctl failed");
1350 RETURN_INT(bytes_waiting);
1354 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1356 struct sp_event_set *result;
1358 TRACE("%p", result_ptr);
1361 RETURN_ERROR(SP_ERR_ARG, "Null result");
1365 if (!(result = malloc(sizeof(struct sp_event_set))))
1366 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1368 memset(result, 0, sizeof(struct sp_event_set));
1370 *result_ptr = result;
1375 static enum sp_return add_handle(struct sp_event_set *event_set,
1376 event_handle handle, enum sp_event mask)
1379 enum sp_event *new_masks;
1381 TRACE("%p, %d, %d", event_set, handle, mask);
1383 if (!(new_handles = realloc(event_set->handles,
1384 sizeof(event_handle) * (event_set->count + 1))))
1385 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1387 event_set->handles = new_handles;
1389 if (!(new_masks = realloc(event_set->masks,
1390 sizeof(enum sp_event) * (event_set->count + 1))))
1391 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1393 event_set->masks = new_masks;
1395 ((event_handle *) event_set->handles)[event_set->count] = handle;
1396 event_set->masks[event_set->count] = mask;
1403 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1404 const struct sp_port *port, enum sp_event mask)
1406 TRACE("%p, %p, %d", event_set, port, mask);
1409 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1412 RETURN_ERROR(SP_ERR_ARG, "Null port");
1414 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1415 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1421 enum sp_event handle_mask;
1422 if ((handle_mask = mask & SP_EVENT_TX_READY))
1423 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1424 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1425 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1427 TRY(add_handle(event_set, port->fd, mask));
1433 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1435 TRACE("%p", event_set);
1438 DEBUG("Null event set");
1442 DEBUG("Freeing event set");
1444 if (event_set->handles)
1445 free(event_set->handles);
1446 if (event_set->masks)
1447 free(event_set->masks);
1454 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1455 unsigned int timeout_ms)
1457 TRACE("%p, %d", event_set, timeout_ms);
1460 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1463 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1464 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1465 RETURN_FAIL("WaitForMultipleObjects() failed");
1469 struct timeval start, delta, now, end = {0, 0};
1470 const struct timeval max_delta = {
1471 (INT_MAX / 1000), (INT_MAX % 1000) * 1000
1473 int started = 0, timeout_overflow = 0;
1474 int result, timeout_remaining_ms;
1475 struct pollfd *pollfds;
1478 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1479 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1481 for (i = 0; i < event_set->count; i++) {
1482 pollfds[i].fd = ((int *)event_set->handles)[i];
1483 pollfds[i].events = 0;
1484 pollfds[i].revents = 0;
1485 if (event_set->masks[i] & SP_EVENT_RX_READY)
1486 pollfds[i].events |= POLLIN;
1487 if (event_set->masks[i] & SP_EVENT_TX_READY)
1488 pollfds[i].events |= POLLOUT;
1489 if (event_set->masks[i] & SP_EVENT_ERROR)
1490 pollfds[i].events |= POLLERR;
1494 /* Get time at start of operation. */
1496 /* Define duration of timeout. */
1497 delta.tv_sec = timeout_ms / 1000;
1498 delta.tv_usec = (timeout_ms % 1000) * 1000;
1499 /* Calculate time at which we should give up. */
1500 timeradd(&start, &delta, &end);
1503 /* Loop until an event occurs. */
1506 * Check timeout only if we have run poll() at least once,
1507 * to avoid any issues if a short timeout is reached before
1508 * poll() is even run.
1511 timeout_remaining_ms = -1;
1512 } else if (!started) {
1513 timeout_overflow = (timeout_ms > INT_MAX);
1514 timeout_remaining_ms = timeout_overflow ? INT_MAX : timeout_ms;
1517 if (timercmp(&now, &end, >)) {
1518 DEBUG("Wait timed out");
1521 timersub(&end, &now, &delta);
1522 if ((timeout_overflow = timercmp(&delta, &max_delta, >)))
1524 timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1527 result = poll(pollfds, event_set->count, timeout_remaining_ms);
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 if (data->dcb.fParity)
1692 switch (data->dcb.Parity) {
1694 config->parity = SP_PARITY_NONE;
1697 config->parity = SP_PARITY_ODD;
1700 config->parity = SP_PARITY_EVEN;
1703 config->parity = SP_PARITY_MARK;
1706 config->parity = SP_PARITY_SPACE;
1709 config->parity = -1;
1712 config->parity = SP_PARITY_NONE;
1714 switch (data->dcb.StopBits) {
1716 config->stopbits = 1;
1719 config->stopbits = 2;
1722 config->stopbits = -1;
1725 switch (data->dcb.fRtsControl) {
1726 case RTS_CONTROL_DISABLE:
1727 config->rts = SP_RTS_OFF;
1729 case RTS_CONTROL_ENABLE:
1730 config->rts = SP_RTS_ON;
1732 case RTS_CONTROL_HANDSHAKE:
1733 config->rts = SP_RTS_FLOW_CONTROL;
1739 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1741 switch (data->dcb.fDtrControl) {
1742 case DTR_CONTROL_DISABLE:
1743 config->dtr = SP_DTR_OFF;
1745 case DTR_CONTROL_ENABLE:
1746 config->dtr = SP_DTR_ON;
1748 case DTR_CONTROL_HANDSHAKE:
1749 config->dtr = SP_DTR_FLOW_CONTROL;
1755 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1757 if (data->dcb.fInX) {
1758 if (data->dcb.fOutX)
1759 config->xon_xoff = SP_XONXOFF_INOUT;
1761 config->xon_xoff = SP_XONXOFF_IN;
1763 if (data->dcb.fOutX)
1764 config->xon_xoff = SP_XONXOFF_OUT;
1766 config->xon_xoff = SP_XONXOFF_DISABLED;
1771 if (tcgetattr(port->fd, &data->term) < 0)
1772 RETURN_FAIL("tcgetattr() failed");
1774 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1775 RETURN_FAIL("TIOCMGET ioctl failed");
1778 int ret = get_flow(port->fd, data);
1780 if (ret == SP_ERR_FAIL && errno == EINVAL)
1781 data->termiox_supported = 0;
1783 RETURN_CODEVAL(ret);
1785 data->termiox_supported = 1;
1787 data->termiox_supported = 0;
1790 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1791 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1792 config->baudrate = std_baudrates[i].value;
1797 if (i == NUM_STD_BAUDRATES) {
1799 config->baudrate = (int)data->term.c_ispeed;
1800 #elif defined(USE_TERMIOS_SPEED)
1801 TRY(get_baudrate(port->fd, &config->baudrate));
1803 config->baudrate = -1;
1807 switch (data->term.c_cflag & CSIZE) {
1824 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1825 config->parity = SP_PARITY_NONE;
1826 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1827 config->parity = -1;
1829 else if (data->term.c_cflag & CMSPAR)
1830 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1833 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1835 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1837 if (data->term.c_cflag & CRTSCTS) {
1838 config->rts = SP_RTS_FLOW_CONTROL;
1839 config->cts = SP_CTS_FLOW_CONTROL;
1841 if (data->termiox_supported && data->rts_flow)
1842 config->rts = SP_RTS_FLOW_CONTROL;
1844 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1846 config->cts = (data->termiox_supported && data->cts_flow) ?
1847 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1850 if (data->termiox_supported && data->dtr_flow)
1851 config->dtr = SP_DTR_FLOW_CONTROL;
1853 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1855 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1856 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1858 if (data->term.c_iflag & IXOFF) {
1859 if (data->term.c_iflag & IXON)
1860 config->xon_xoff = SP_XONXOFF_INOUT;
1862 config->xon_xoff = SP_XONXOFF_IN;
1864 if (data->term.c_iflag & IXON)
1865 config->xon_xoff = SP_XONXOFF_OUT;
1867 config->xon_xoff = SP_XONXOFF_DISABLED;
1874 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1875 const struct sp_port_config *config)
1879 BAUD_TYPE baud_nonstd;
1883 #ifdef USE_TERMIOS_SPEED
1884 int baud_nonstd = 0;
1887 TRACE("%p, %p, %p", port, data, config);
1889 DEBUG_FMT("Setting configuration for port %s", port->name);
1893 TRY(await_write_completion(port));
1895 if (config->baudrate >= 0) {
1896 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1897 if (config->baudrate == std_baudrates[i].value) {
1898 data->dcb.BaudRate = std_baudrates[i].index;
1903 if (i == NUM_STD_BAUDRATES)
1904 data->dcb.BaudRate = config->baudrate;
1906 /* Allocate write buffer for 50ms of data at baud rate. */
1907 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1908 port->write_buf = realloc(port->write_buf,
1909 port->write_buf_size);
1911 if (!port->write_buf)
1912 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1915 if (config->bits >= 0)
1916 data->dcb.ByteSize = config->bits;
1918 if (config->parity >= 0) {
1919 switch (config->parity) {
1920 case SP_PARITY_NONE:
1921 data->dcb.Parity = NOPARITY;
1924 data->dcb.Parity = ODDPARITY;
1926 case SP_PARITY_EVEN:
1927 data->dcb.Parity = EVENPARITY;
1929 case SP_PARITY_MARK:
1930 data->dcb.Parity = MARKPARITY;
1932 case SP_PARITY_SPACE:
1933 data->dcb.Parity = SPACEPARITY;
1936 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1940 if (config->stopbits >= 0) {
1941 switch (config->stopbits) {
1942 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1944 data->dcb.StopBits = ONESTOPBIT;
1947 data->dcb.StopBits = TWOSTOPBITS;
1950 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1954 if (config->rts >= 0) {
1955 switch (config->rts) {
1957 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1960 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1962 case SP_RTS_FLOW_CONTROL:
1963 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1966 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1970 if (config->cts >= 0) {
1971 switch (config->cts) {
1973 data->dcb.fOutxCtsFlow = FALSE;
1975 case SP_CTS_FLOW_CONTROL:
1976 data->dcb.fOutxCtsFlow = TRUE;
1979 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1983 if (config->dtr >= 0) {
1984 switch (config->dtr) {
1986 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1989 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1991 case SP_DTR_FLOW_CONTROL:
1992 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1995 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1999 if (config->dsr >= 0) {
2000 switch (config->dsr) {
2002 data->dcb.fOutxDsrFlow = FALSE;
2004 case SP_DSR_FLOW_CONTROL:
2005 data->dcb.fOutxDsrFlow = TRUE;
2008 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2012 if (config->xon_xoff >= 0) {
2013 switch (config->xon_xoff) {
2014 case SP_XONXOFF_DISABLED:
2015 data->dcb.fInX = FALSE;
2016 data->dcb.fOutX = FALSE;
2019 data->dcb.fInX = TRUE;
2020 data->dcb.fOutX = FALSE;
2022 case SP_XONXOFF_OUT:
2023 data->dcb.fInX = FALSE;
2024 data->dcb.fOutX = TRUE;
2026 case SP_XONXOFF_INOUT:
2027 data->dcb.fInX = TRUE;
2028 data->dcb.fOutX = TRUE;
2031 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2035 if (!SetCommState(port->hdl, &data->dcb))
2036 RETURN_FAIL("SetCommState() failed");
2042 if (config->baudrate >= 0) {
2043 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2044 if (config->baudrate == std_baudrates[i].value) {
2045 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2046 RETURN_FAIL("cfsetospeed() failed");
2048 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2049 RETURN_FAIL("cfsetispeed() failed");
2054 /* Non-standard baud rate */
2055 if (i == NUM_STD_BAUDRATES) {
2057 /* Set "dummy" baud rate. */
2058 if (cfsetspeed(&data->term, B9600) < 0)
2059 RETURN_FAIL("cfsetspeed() failed");
2060 baud_nonstd = config->baudrate;
2061 #elif defined(USE_TERMIOS_SPEED)
2064 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2069 if (config->bits >= 0) {
2070 data->term.c_cflag &= ~CSIZE;
2071 switch (config->bits) {
2073 data->term.c_cflag |= CS8;
2076 data->term.c_cflag |= CS7;
2079 data->term.c_cflag |= CS6;
2082 data->term.c_cflag |= CS5;
2085 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2089 if (config->parity >= 0) {
2090 data->term.c_iflag &= ~IGNPAR;
2091 data->term.c_cflag &= ~(PARENB | PARODD);
2093 data->term.c_cflag &= ~CMSPAR;
2095 switch (config->parity) {
2096 case SP_PARITY_NONE:
2097 data->term.c_iflag |= IGNPAR;
2099 case SP_PARITY_EVEN:
2100 data->term.c_cflag |= PARENB;
2103 data->term.c_cflag |= PARENB | PARODD;
2106 case SP_PARITY_MARK:
2107 data->term.c_cflag |= PARENB | PARODD;
2108 data->term.c_cflag |= CMSPAR;
2110 case SP_PARITY_SPACE:
2111 data->term.c_cflag |= PARENB;
2112 data->term.c_cflag |= CMSPAR;
2115 case SP_PARITY_MARK:
2116 case SP_PARITY_SPACE:
2117 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2120 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2124 if (config->stopbits >= 0) {
2125 data->term.c_cflag &= ~CSTOPB;
2126 switch (config->stopbits) {
2128 data->term.c_cflag &= ~CSTOPB;
2131 data->term.c_cflag |= CSTOPB;
2134 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2138 if (config->rts >= 0 || config->cts >= 0) {
2139 if (data->termiox_supported) {
2140 data->rts_flow = data->cts_flow = 0;
2141 switch (config->rts) {
2144 controlbits = TIOCM_RTS;
2145 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2146 RETURN_FAIL("Setting RTS signal level failed");
2148 case SP_RTS_FLOW_CONTROL:
2154 if (config->cts == SP_CTS_FLOW_CONTROL)
2157 if (data->rts_flow && data->cts_flow)
2158 data->term.c_iflag |= CRTSCTS;
2160 data->term.c_iflag &= ~CRTSCTS;
2162 /* Asymmetric use of RTS/CTS not supported. */
2163 if (data->term.c_iflag & CRTSCTS) {
2164 /* Flow control can only be disabled for both RTS & CTS together. */
2165 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2166 if (config->cts != SP_CTS_IGNORE)
2167 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2169 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2170 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2171 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2174 /* Flow control can only be enabled for both RTS & CTS together. */
2175 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2176 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2177 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2180 if (config->rts >= 0) {
2181 if (config->rts == SP_RTS_FLOW_CONTROL) {
2182 data->term.c_iflag |= CRTSCTS;
2184 controlbits = TIOCM_RTS;
2185 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2187 RETURN_FAIL("Setting RTS signal level failed");
2193 if (config->dtr >= 0 || config->dsr >= 0) {
2194 if (data->termiox_supported) {
2195 data->dtr_flow = data->dsr_flow = 0;
2196 switch (config->dtr) {
2199 controlbits = TIOCM_DTR;
2200 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2201 RETURN_FAIL("Setting DTR signal level failed");
2203 case SP_DTR_FLOW_CONTROL:
2209 if (config->dsr == SP_DSR_FLOW_CONTROL)
2212 /* DTR/DSR flow control not supported. */
2213 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2214 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2216 if (config->dtr >= 0) {
2217 controlbits = TIOCM_DTR;
2218 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2220 RETURN_FAIL("Setting DTR signal level failed");
2225 if (config->xon_xoff >= 0) {
2226 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2227 switch (config->xon_xoff) {
2228 case SP_XONXOFF_DISABLED:
2231 data->term.c_iflag |= IXOFF;
2233 case SP_XONXOFF_OUT:
2234 data->term.c_iflag |= IXON | IXANY;
2236 case SP_XONXOFF_INOUT:
2237 data->term.c_iflag |= IXON | IXOFF | IXANY;
2240 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2244 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2245 RETURN_FAIL("tcsetattr() failed");
2248 if (baud_nonstd != B0) {
2249 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2250 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2252 * Set baud rates in data->term to correct, but incompatible
2253 * with tcsetattr() value, same as delivered by tcgetattr().
2255 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2256 RETURN_FAIL("cfsetspeed() failed");
2258 #elif defined(__linux__)
2259 #ifdef USE_TERMIOS_SPEED
2261 TRY(set_baudrate(port->fd, config->baudrate));
2264 if (data->termiox_supported)
2265 TRY(set_flow(port->fd, data));
2269 #endif /* !_WIN32 */
2274 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2276 struct sp_port_config *config;
2278 TRACE("%p", config_ptr);
2281 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2285 if (!(config = malloc(sizeof(struct sp_port_config))))
2286 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2288 config->baudrate = -1;
2290 config->parity = -1;
2291 config->stopbits = -1;
2297 *config_ptr = config;
2302 SP_API void sp_free_config(struct sp_port_config *config)
2304 TRACE("%p", config);
2307 DEBUG("Null config");
2314 SP_API enum sp_return sp_get_config(struct sp_port *port,
2315 struct sp_port_config *config)
2317 struct port_data data;
2319 TRACE("%p, %p", port, config);
2324 RETURN_ERROR(SP_ERR_ARG, "Null config");
2326 TRY(get_config(port, &data, config));
2331 SP_API enum sp_return sp_set_config(struct sp_port *port,
2332 const struct sp_port_config *config)
2334 struct port_data data;
2335 struct sp_port_config prev_config;
2337 TRACE("%p, %p", port, config);
2342 RETURN_ERROR(SP_ERR_ARG, "Null config");
2344 TRY(get_config(port, &data, &prev_config));
2345 TRY(set_config(port, &data, config));
2350 #define CREATE_ACCESSORS(x, type) \
2351 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2352 struct port_data data; \
2353 struct sp_port_config config; \
2354 TRACE("%p, %d", port, x); \
2355 CHECK_OPEN_PORT(); \
2356 TRY(get_config(port, &data, &config)); \
2358 TRY(set_config(port, &data, &config)); \
2361 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2363 TRACE("%p, %p", config, x); \
2365 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2367 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2371 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2373 TRACE("%p, %d", config, x); \
2375 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2380 CREATE_ACCESSORS(baudrate, int)
2381 CREATE_ACCESSORS(bits, int)
2382 CREATE_ACCESSORS(parity, enum sp_parity)
2383 CREATE_ACCESSORS(stopbits, int)
2384 CREATE_ACCESSORS(rts, enum sp_rts)
2385 CREATE_ACCESSORS(cts, enum sp_cts)
2386 CREATE_ACCESSORS(dtr, enum sp_dtr)
2387 CREATE_ACCESSORS(dsr, enum sp_dsr)
2388 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2390 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2391 enum sp_flowcontrol flowcontrol)
2394 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2396 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2397 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2399 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2400 config->xon_xoff = SP_XONXOFF_INOUT;
2402 config->xon_xoff = SP_XONXOFF_DISABLED;
2404 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2405 config->rts = SP_RTS_FLOW_CONTROL;
2406 config->cts = SP_CTS_FLOW_CONTROL;
2408 if (config->rts == SP_RTS_FLOW_CONTROL)
2409 config->rts = SP_RTS_ON;
2410 config->cts = SP_CTS_IGNORE;
2413 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2414 config->dtr = SP_DTR_FLOW_CONTROL;
2415 config->dsr = SP_DSR_FLOW_CONTROL;
2417 if (config->dtr == SP_DTR_FLOW_CONTROL)
2418 config->dtr = SP_DTR_ON;
2419 config->dsr = SP_DSR_IGNORE;
2425 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2426 enum sp_flowcontrol flowcontrol)
2428 struct port_data data;
2429 struct sp_port_config config;
2431 TRACE("%p, %d", port, flowcontrol);
2435 TRY(get_config(port, &data, &config));
2437 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2439 TRY(set_config(port, &data, &config));
2444 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2445 enum sp_signal *signals)
2447 TRACE("%p, %p", port, signals);
2452 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2454 DEBUG_FMT("Getting control signals for port %s", port->name);
2459 if (GetCommModemStatus(port->hdl, &bits) == 0)
2460 RETURN_FAIL("GetCommModemStatus() failed");
2461 if (bits & MS_CTS_ON)
2462 *signals |= SP_SIG_CTS;
2463 if (bits & MS_DSR_ON)
2464 *signals |= SP_SIG_DSR;
2465 if (bits & MS_RLSD_ON)
2466 *signals |= SP_SIG_DCD;
2467 if (bits & MS_RING_ON)
2468 *signals |= SP_SIG_RI;
2471 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2472 RETURN_FAIL("TIOCMGET ioctl failed");
2473 if (bits & TIOCM_CTS)
2474 *signals |= SP_SIG_CTS;
2475 if (bits & TIOCM_DSR)
2476 *signals |= SP_SIG_DSR;
2477 if (bits & TIOCM_CAR)
2478 *signals |= SP_SIG_DCD;
2479 if (bits & TIOCM_RNG)
2480 *signals |= SP_SIG_RI;
2485 SP_API enum sp_return sp_start_break(struct sp_port *port)
2491 if (SetCommBreak(port->hdl) == 0)
2492 RETURN_FAIL("SetCommBreak() failed");
2494 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2495 RETURN_FAIL("TIOCSBRK ioctl failed");
2501 SP_API enum sp_return sp_end_break(struct sp_port *port)
2507 if (ClearCommBreak(port->hdl) == 0)
2508 RETURN_FAIL("ClearCommBreak() failed");
2510 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2511 RETURN_FAIL("TIOCCBRK ioctl failed");
2517 SP_API int sp_last_error_code(void)
2521 RETURN_INT(GetLastError());
2527 SP_API char *sp_last_error_message(void)
2533 DWORD error = GetLastError();
2535 DWORD length = FormatMessage(
2536 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2537 FORMAT_MESSAGE_FROM_SYSTEM |
2538 FORMAT_MESSAGE_IGNORE_INSERTS,
2541 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2545 if (length >= 2 && message[length - 2] == '\r')
2546 message[length - 2] = '\0';
2548 RETURN_STRING(message);
2550 RETURN_STRING(strerror(errno));
2554 SP_API void sp_free_error_message(char *message)
2556 TRACE("%s", message);
2567 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2569 TRACE("%p", handler);
2571 sp_debug_handler = handler;
2576 SP_API void sp_default_debug_handler(const char *format, ...)
2579 va_start(args, format);
2580 if (getenv("LIBSERIALPORT_DEBUG")) {
2581 fputs("sp: ", stderr);
2582 vfprintf(stderr, format, args);
2587 SP_API int sp_get_major_package_version(void)
2589 return SP_PACKAGE_VERSION_MAJOR;
2592 SP_API int sp_get_minor_package_version(void)
2594 return SP_PACKAGE_VERSION_MINOR;
2597 SP_API int sp_get_micro_package_version(void)
2599 return SP_PACKAGE_VERSION_MICRO;
2602 SP_API const char *sp_get_package_version_string(void)
2604 return SP_PACKAGE_VERSION_STRING;
2607 SP_API int sp_get_current_lib_version(void)
2609 return SP_LIB_VERSION_CURRENT;
2612 SP_API int sp_get_revision_lib_version(void)
2614 return SP_LIB_VERSION_REVISION;
2617 SP_API int sp_get_age_lib_version(void)
2619 return SP_LIB_VERSION_AGE;
2622 SP_API const char *sp_get_lib_version_string(void)
2624 return SP_LIB_VERSION_STRING;