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;
67 #elif defined(__APPLE__)
68 mach_timebase_info_data_t info;
69 mach_timebase_info(&info);
70 uint64_t ticks = mach_absolute_time();
71 uint64_t ns = (ticks * info.numer) / info.denom;
72 time->tv_sec = ns / 1000000000;
73 time->tv_usec = (ns % 1000000000) / 1000;
75 gettimeofday(time, NULL);
79 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
82 #ifndef NO_PORT_METADATA
87 TRACE("%s, %p", portname, port_ptr);
90 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
95 RETURN_ERROR(SP_ERR_ARG, "Null port name");
97 DEBUG_FMT("Building structure for port %s", portname);
99 #if !defined(_WIN32) && defined(HAVE_REALPATH)
101 * get_port_details() below tries to be too smart and figure out
102 * some transport properties from the port name which breaks with
103 * symlinks. Therefore we canonicalize the portname first.
105 char pathbuf[PATH_MAX + 1];
106 char *res = realpath(portname, pathbuf);
108 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
113 if (!(port = malloc(sizeof(struct sp_port))))
114 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
116 len = strlen(portname) + 1;
118 if (!(port->name = malloc(len))) {
120 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
123 memcpy(port->name, portname, len);
126 port->usb_path = NULL;
127 port->hdl = INVALID_HANDLE_VALUE;
128 port->write_buf = NULL;
129 port->write_buf_size = 0;
134 port->description = NULL;
135 port->transport = SP_TRANSPORT_NATIVE;
137 port->usb_address = -1;
140 port->usb_manufacturer = NULL;
141 port->usb_product = NULL;
142 port->usb_serial = NULL;
143 port->bluetooth_address = NULL;
145 #ifndef NO_PORT_METADATA
146 if ((ret = get_port_details(port)) != SP_OK) {
157 SP_API char *sp_get_port_name(const struct sp_port *port)
164 RETURN_STRING(port->name);
167 SP_API char *sp_get_port_description(const struct sp_port *port)
171 if (!port || !port->description)
174 RETURN_STRING(port->description);
177 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
182 RETURN_ERROR(SP_ERR_ARG, "Null port");
184 RETURN_INT(port->transport);
187 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
188 int *usb_bus,int *usb_address)
193 RETURN_ERROR(SP_ERR_ARG, "Null port");
194 if (port->transport != SP_TRANSPORT_USB)
195 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
196 if (port->usb_bus < 0 || port->usb_address < 0)
197 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
200 *usb_bus = port->usb_bus;
202 *usb_address = port->usb_address;
207 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
208 int *usb_vid, int *usb_pid)
213 RETURN_ERROR(SP_ERR_ARG, "Null port");
214 if (port->transport != SP_TRANSPORT_USB)
215 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
216 if (port->usb_vid < 0 || port->usb_pid < 0)
217 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
220 *usb_vid = port->usb_vid;
222 *usb_pid = port->usb_pid;
227 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
231 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
234 RETURN_STRING(port->usb_manufacturer);
237 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
241 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
244 RETURN_STRING(port->usb_product);
247 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
251 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
254 RETURN_STRING(port->usb_serial);
257 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
261 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
262 || !port->bluetooth_address)
265 RETURN_STRING(port->bluetooth_address);
268 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
271 TRACE("%p, %p", port, result_ptr);
274 RETURN_ERROR(SP_ERR_ARG, "Null port");
276 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
279 HANDLE *handle_ptr = result_ptr;
280 *handle_ptr = port->hdl;
282 int *fd_ptr = result_ptr;
289 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
290 struct sp_port **copy_ptr)
292 TRACE("%p, %p", port, copy_ptr);
295 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
300 RETURN_ERROR(SP_ERR_ARG, "Null port");
303 RETURN_ERROR(SP_ERR_ARG, "Null port name");
305 DEBUG("Copying port structure");
307 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
310 SP_API void sp_free_port(struct sp_port *port)
319 DEBUG("Freeing port structure");
323 if (port->description)
324 free(port->description);
325 if (port->usb_manufacturer)
326 free(port->usb_manufacturer);
327 if (port->usb_product)
328 free(port->usb_product);
329 if (port->usb_serial)
330 free(port->usb_serial);
331 if (port->bluetooth_address)
332 free(port->bluetooth_address);
335 free(port->usb_path);
337 free(port->write_buf);
345 SP_PRIV struct sp_port **list_append(struct sp_port **list,
346 const char *portname)
351 for (count = 0; list[count]; count++)
353 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
356 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
358 list[count + 1] = NULL;
362 sp_free_port_list(list);
366 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
368 #ifndef NO_ENUMERATION
369 struct sp_port **list;
373 TRACE("%p", list_ptr);
376 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
380 #ifdef NO_ENUMERATION
381 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
383 DEBUG("Enumerating ports");
385 if (!(list = malloc(sizeof(struct sp_port *))))
386 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
390 ret = list_ports(&list);
395 sp_free_port_list(list);
403 SP_API void sp_free_port_list(struct sp_port **list)
414 DEBUG("Freeing port list");
416 for (i = 0; list[i]; i++)
417 sp_free_port(list[i]);
423 #define CHECK_PORT() do { \
425 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
427 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
430 #define CHECK_PORT_HANDLE() do { \
431 if (port->hdl == INVALID_HANDLE_VALUE) \
432 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
435 #define CHECK_PORT_HANDLE() do { \
437 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
440 #define CHECK_OPEN_PORT() do { \
442 CHECK_PORT_HANDLE(); \
446 /** To be called after port receive buffer is emptied. */
447 static enum sp_return restart_wait(struct sp_port *port)
451 if (port->wait_running) {
452 /* Check status of running wait operation. */
453 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
454 &wait_result, FALSE)) {
455 DEBUG("Previous wait completed");
456 port->wait_running = FALSE;
457 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
458 DEBUG("Previous wait still running");
461 RETURN_FAIL("GetOverlappedResult() failed");
465 if (!port->wait_running) {
466 /* Start new wait operation. */
467 if (WaitCommEvent(port->hdl, &port->events,
469 DEBUG("New wait returned, events already pending");
470 } else if (GetLastError() == ERROR_IO_PENDING) {
471 DEBUG("New wait running in background");
472 port->wait_running = TRUE;
474 RETURN_FAIL("WaitCommEvent() failed");
482 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
484 struct port_data data;
485 struct sp_port_config config;
488 TRACE("%p, 0x%x", port, flags);
492 if (flags > SP_MODE_READ_WRITE)
493 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
495 DEBUG_FMT("Opening port %s", port->name);
498 DWORD desired_access = 0, flags_and_attributes = 0, errors;
499 char *escaped_port_name;
502 /* Prefix port name with '\\.\' to work with ports above COM9. */
503 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
504 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
505 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
507 /* Map 'flags' to the OS-specific settings. */
508 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
509 if (flags & SP_MODE_READ)
510 desired_access |= GENERIC_READ;
511 if (flags & SP_MODE_WRITE)
512 desired_access |= GENERIC_WRITE;
514 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
515 OPEN_EXISTING, flags_and_attributes, 0);
517 free(escaped_port_name);
519 if (port->hdl == INVALID_HANDLE_VALUE)
520 RETURN_FAIL("Port CreateFile() failed");
522 /* All timeouts initially disabled. */
523 port->timeouts.ReadIntervalTimeout = 0;
524 port->timeouts.ReadTotalTimeoutMultiplier = 0;
525 port->timeouts.ReadTotalTimeoutConstant = 0;
526 port->timeouts.WriteTotalTimeoutMultiplier = 0;
527 port->timeouts.WriteTotalTimeoutConstant = 0;
529 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
531 RETURN_FAIL("SetCommTimeouts() failed");
534 /* Prepare OVERLAPPED structures. */
535 #define INIT_OVERLAPPED(ovl) do { \
536 memset(&port->ovl, 0, sizeof(port->ovl)); \
537 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
538 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
539 == INVALID_HANDLE_VALUE) { \
541 RETURN_FAIL(#ovl "CreateEvent() failed"); \
545 INIT_OVERLAPPED(read_ovl);
546 INIT_OVERLAPPED(write_ovl);
547 INIT_OVERLAPPED(wait_ovl);
549 /* Set event mask for RX and error events. */
550 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
552 RETURN_FAIL("SetCommMask() failed");
555 port->writing = FALSE;
556 port->wait_running = FALSE;
558 ret = restart_wait(port);
565 int flags_local = O_NONBLOCK | O_NOCTTY;
567 /* Map 'flags' to the OS-specific settings. */
568 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
569 flags_local |= O_RDWR;
570 else if (flags & SP_MODE_READ)
571 flags_local |= O_RDONLY;
572 else if (flags & SP_MODE_WRITE)
573 flags_local |= O_WRONLY;
575 if ((port->fd = open(port->name, flags_local)) < 0)
576 RETURN_FAIL("open() failed");
579 ret = get_config(port, &data, &config);
586 /* Set sane port settings. */
588 data.dcb.fBinary = TRUE;
589 data.dcb.fDsrSensitivity = FALSE;
590 data.dcb.fErrorChar = FALSE;
591 data.dcb.fNull = FALSE;
592 data.dcb.fAbortOnError = FALSE;
594 /* Turn off all fancy termios tricks, give us a raw channel. */
595 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
597 data.term.c_iflag &= ~IUCLC;
599 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
601 data.term.c_oflag &= ~OLCUC;
604 data.term.c_oflag &= ~NLDLY;
607 data.term.c_oflag &= ~CRDLY;
610 data.term.c_oflag &= ~TABDLY;
613 data.term.c_oflag &= ~BSDLY;
616 data.term.c_oflag &= ~VTDLY;
619 data.term.c_oflag &= ~FFDLY;
622 data.term.c_oflag &= ~OFILL;
624 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
625 data.term.c_cc[VMIN] = 0;
626 data.term.c_cc[VTIME] = 0;
628 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
629 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
633 if (ClearCommError(port->hdl, &errors, &status) == 0)
634 RETURN_FAIL("ClearCommError() failed");
637 ret = set_config(port, &data, &config);
647 SP_API enum sp_return sp_close(struct sp_port *port)
653 DEBUG_FMT("Closing port %s", port->name);
656 /* Returns non-zero upon success, 0 upon failure. */
657 if (CloseHandle(port->hdl) == 0)
658 RETURN_FAIL("Port CloseHandle() failed");
659 port->hdl = INVALID_HANDLE_VALUE;
661 /* Close event handles for overlapped structures. */
662 #define CLOSE_OVERLAPPED(ovl) do { \
663 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
664 CloseHandle(port->ovl.hEvent) == 0) \
665 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
667 CLOSE_OVERLAPPED(read_ovl);
668 CLOSE_OVERLAPPED(write_ovl);
669 CLOSE_OVERLAPPED(wait_ovl);
671 if (port->write_buf) {
672 free(port->write_buf);
673 port->write_buf = NULL;
676 /* Returns 0 upon success, -1 upon failure. */
677 if (close(port->fd) == -1)
678 RETURN_FAIL("close() failed");
685 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
687 TRACE("%p, 0x%x", port, buffers);
691 if (buffers > SP_BUF_BOTH)
692 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
694 const char *buffer_names[] = {"no", "input", "output", "both"};
696 DEBUG_FMT("Flushing %s buffers on port %s",
697 buffer_names[buffers], port->name);
701 if (buffers & SP_BUF_INPUT)
702 flags |= PURGE_RXCLEAR;
703 if (buffers & SP_BUF_OUTPUT)
704 flags |= PURGE_TXCLEAR;
706 /* Returns non-zero upon success, 0 upon failure. */
707 if (PurgeComm(port->hdl, flags) == 0)
708 RETURN_FAIL("PurgeComm() failed");
710 if (buffers & SP_BUF_INPUT)
711 TRY(restart_wait(port));
714 if (buffers == SP_BUF_BOTH)
716 else if (buffers == SP_BUF_INPUT)
718 else if (buffers == SP_BUF_OUTPUT)
721 /* Returns 0 upon success, -1 upon failure. */
722 if (tcflush(port->fd, flags) < 0)
723 RETURN_FAIL("tcflush() failed");
728 SP_API enum sp_return sp_drain(struct sp_port *port)
734 DEBUG_FMT("Draining port %s", port->name);
737 /* Returns non-zero upon success, 0 upon failure. */
738 if (FlushFileBuffers(port->hdl) == 0)
739 RETURN_FAIL("FlushFileBuffers() failed");
746 result = ioctl(port->fd, TCSBRK, &arg);
748 result = tcdrain(port->fd);
751 if (errno == EINTR) {
752 DEBUG("tcdrain() was interrupted");
755 RETURN_FAIL("tcdrain() failed");
765 static enum sp_return await_write_completion(struct sp_port *port)
771 /* Wait for previous non-blocking write to complete, if any. */
773 DEBUG("Waiting for previous write to complete");
774 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
777 RETURN_FAIL("Previous write failed to complete");
778 DEBUG("Previous write completed");
785 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
786 size_t count, unsigned int timeout_ms)
788 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
793 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
796 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
797 count, port->name, timeout_ms);
799 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
806 DWORD bytes_written = 0;
808 TRY(await_write_completion(port));
811 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
812 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
813 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
814 RETURN_FAIL("SetCommTimeouts() failed");
817 /* Reduce count if it exceeds the WriteFile limit. */
818 if (count > WRITEFILE_MAX_SIZE)
819 count = WRITEFILE_MAX_SIZE;
822 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
823 DEBUG("Write completed immediately");
825 } else if (GetLastError() == ERROR_IO_PENDING) {
826 DEBUG("Waiting for write to complete");
827 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
828 if (GetLastError() == ERROR_SEM_TIMEOUT) {
829 DEBUG("Write timed out");
832 RETURN_FAIL("GetOverlappedResult() failed");
835 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
836 RETURN_INT(bytes_written);
838 RETURN_FAIL("WriteFile() failed");
841 size_t bytes_written = 0;
842 unsigned char *ptr = (unsigned char *) buf;
843 struct timeval start, delta, now, end = {0, 0};
849 /* Get time at start of operation. */
851 /* Define duration of timeout. */
852 delta.tv_sec = timeout_ms / 1000;
853 delta.tv_usec = (timeout_ms % 1000) * 1000;
854 /* Calculate time at which we should give up. */
855 timeradd(&start, &delta, &end);
859 FD_SET(port->fd, &fds);
861 /* Loop until we have written the requested number of bytes. */
862 while (bytes_written < count) {
864 * Check timeout only if we have run select() at least once,
865 * to avoid any issues if a short timeout is reached before
866 * select() is even run.
868 if (timeout_ms && started) {
870 if (timercmp(&now, &end, >))
871 /* Timeout has expired. */
873 timersub(&end, &now, &delta);
875 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
878 if (errno == EINTR) {
879 DEBUG("select() call was interrupted, repeating");
882 RETURN_FAIL("select() failed");
884 } else if (result == 0) {
885 /* Timeout has expired. */
890 result = write(port->fd, ptr, count - bytes_written);
894 /* This shouldn't happen because we did a select() first, but handle anyway. */
897 /* This is an actual failure. */
898 RETURN_FAIL("write() failed");
901 bytes_written += result;
905 if (bytes_written < count)
906 DEBUG("Write timed out");
908 RETURN_INT(bytes_written);
912 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
913 const void *buf, size_t count)
915 TRACE("%p, %p, %d", port, buf, count);
920 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
922 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
930 /* Check whether previous write is complete. */
932 if (HasOverlappedIoCompleted(&port->write_ovl)) {
933 DEBUG("Previous write completed");
936 DEBUG("Previous write not complete");
937 /* Can't take a new write until the previous one finishes. */
943 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
944 port->timeouts.WriteTotalTimeoutConstant = 0;
945 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
946 RETURN_FAIL("SetCommTimeouts() failed");
949 /* Reduce count if it exceeds the WriteFile limit. */
950 if (count > WRITEFILE_MAX_SIZE)
951 count = WRITEFILE_MAX_SIZE;
953 /* Copy data to our write buffer. */
954 buf_bytes = min(port->write_buf_size, count);
955 memcpy(port->write_buf, buf, buf_bytes);
957 /* Start asynchronous write. */
958 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
959 if (GetLastError() == ERROR_IO_PENDING) {
960 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
961 DEBUG("Asynchronous write completed immediately");
963 DEBUG("Asynchronous write running");
965 /* Actual failure of some kind. */
966 RETURN_FAIL("WriteFile() failed");
970 DEBUG("All bytes written immediately");
972 RETURN_INT(buf_bytes);
974 /* Returns the number of bytes written, or -1 upon failure. */
975 ssize_t written = write(port->fd, buf, count);
979 // Buffer is full, no bytes written.
982 RETURN_FAIL("write() failed");
990 /* Restart wait operation if buffer was emptied. */
991 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
999 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1000 RETURN_FAIL("ClearCommError() failed");
1002 if (comstat.cbInQue == 0)
1003 TRY(restart_wait(port));
1009 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1010 size_t count, unsigned int timeout_ms)
1012 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1017 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1020 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1021 count, port->name, timeout_ms);
1023 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1030 DWORD bytes_read = 0;
1033 if (port->timeouts.ReadIntervalTimeout != 0 ||
1034 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1035 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1036 port->timeouts.ReadIntervalTimeout = 0;
1037 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1038 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1039 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1040 RETURN_FAIL("SetCommTimeouts() failed");
1044 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1045 DEBUG("Read completed immediately");
1047 } else if (GetLastError() == ERROR_IO_PENDING) {
1048 DEBUG("Waiting for read to complete");
1049 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1050 RETURN_FAIL("GetOverlappedResult() failed");
1051 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1053 RETURN_FAIL("ReadFile() failed");
1056 TRY(restart_wait_if_needed(port, bytes_read));
1058 RETURN_INT(bytes_read);
1061 size_t bytes_read = 0;
1062 unsigned char *ptr = (unsigned char *)buf;
1063 struct timeval start, delta, now, end = {0, 0};
1069 /* Get time at start of operation. */
1071 /* Define duration of timeout. */
1072 delta.tv_sec = timeout_ms / 1000;
1073 delta.tv_usec = (timeout_ms % 1000) * 1000;
1074 /* Calculate time at which we should give up. */
1075 timeradd(&start, &delta, &end);
1079 FD_SET(port->fd, &fds);
1081 /* Loop until we have the requested number of bytes. */
1082 while (bytes_read < count) {
1084 * Check timeout only if we have run select() at least once,
1085 * to avoid any issues if a short timeout is reached before
1086 * select() is even run.
1088 if (timeout_ms && started) {
1090 if (timercmp(&now, &end, >))
1091 /* Timeout has expired. */
1093 timersub(&end, &now, &delta);
1095 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1098 if (errno == EINTR) {
1099 DEBUG("select() call was interrupted, repeating");
1102 RETURN_FAIL("select() failed");
1104 } else if (result == 0) {
1105 /* Timeout has expired. */
1110 result = read(port->fd, ptr, count - bytes_read);
1113 if (errno == EAGAIN)
1115 * This shouldn't happen because we did a
1116 * select() first, but handle anyway.
1120 /* This is an actual failure. */
1121 RETURN_FAIL("read() failed");
1124 bytes_read += result;
1128 if (bytes_read < count)
1129 DEBUG("Read timed out");
1131 RETURN_INT(bytes_read);
1135 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1136 size_t count, unsigned int timeout_ms)
1138 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1143 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1146 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1149 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1150 count, port->name, timeout_ms);
1152 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1156 DWORD bytes_read = 0;
1158 /* If timeout_ms == 0, set maximum timeout. */
1159 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1162 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1163 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1164 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1165 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1166 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1167 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1168 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1169 RETURN_FAIL("SetCommTimeouts() failed");
1172 /* Loop until we have at least one byte, or timeout is reached. */
1173 while (bytes_read == 0) {
1175 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1176 DEBUG("Read completed immediately");
1177 } else if (GetLastError() == ERROR_IO_PENDING) {
1178 DEBUG("Waiting for read to complete");
1179 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1180 RETURN_FAIL("GetOverlappedResult() failed");
1181 if (bytes_read > 0) {
1182 DEBUG("Read completed");
1183 } else if (timeout_ms > 0) {
1184 DEBUG("Read timed out");
1187 DEBUG("Restarting read");
1190 RETURN_FAIL("ReadFile() failed");
1194 TRY(restart_wait_if_needed(port, bytes_read));
1196 RETURN_INT(bytes_read);
1199 size_t bytes_read = 0;
1200 struct timeval start, delta, now, end = {0, 0};
1206 /* Get time at start of operation. */
1208 /* Define duration of timeout. */
1209 delta.tv_sec = timeout_ms / 1000;
1210 delta.tv_usec = (timeout_ms % 1000) * 1000;
1211 /* Calculate time at which we should give up. */
1212 timeradd(&start, &delta, &end);
1216 FD_SET(port->fd, &fds);
1218 /* Loop until we have at least one byte, or timeout is reached. */
1219 while (bytes_read == 0) {
1221 * Check timeout only if we have run select() at least once,
1222 * to avoid any issues if a short timeout is reached before
1223 * select() is even run.
1225 if (timeout_ms && started) {
1227 if (timercmp(&now, &end, >))
1228 /* Timeout has expired. */
1230 timersub(&end, &now, &delta);
1232 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1235 if (errno == EINTR) {
1236 DEBUG("select() call was interrupted, repeating");
1239 RETURN_FAIL("select() failed");
1241 } else if (result == 0) {
1242 /* Timeout has expired. */
1247 result = read(port->fd, buf, count);
1250 if (errno == EAGAIN)
1251 /* This shouldn't happen because we did a select() first, but handle anyway. */
1254 /* This is an actual failure. */
1255 RETURN_FAIL("read() failed");
1258 bytes_read = result;
1261 if (bytes_read == 0)
1262 DEBUG("Read timed out");
1264 RETURN_INT(bytes_read);
1268 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1271 TRACE("%p, %p, %d", port, buf, count);
1276 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1278 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1284 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1285 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1286 port->timeouts.ReadTotalTimeoutConstant != 0) {
1287 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1288 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1289 port->timeouts.ReadTotalTimeoutConstant = 0;
1290 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1291 RETURN_FAIL("SetCommTimeouts() failed");
1295 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1296 if (GetLastError() != ERROR_IO_PENDING)
1297 RETURN_FAIL("ReadFile() failed");
1299 /* Get number of bytes read. */
1300 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1301 RETURN_FAIL("GetOverlappedResult() failed");
1303 TRY(restart_wait_if_needed(port, bytes_read));
1305 RETURN_INT(bytes_read);
1309 /* Returns the number of bytes read, or -1 upon failure. */
1310 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1311 if (errno == EAGAIN)
1312 /* No bytes available. */
1315 /* This is an actual failure. */
1316 RETURN_FAIL("read() failed");
1318 RETURN_INT(bytes_read);
1322 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1328 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1334 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1335 RETURN_FAIL("ClearCommError() failed");
1336 RETURN_INT(comstat.cbInQue);
1339 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1340 RETURN_FAIL("TIOCINQ ioctl failed");
1341 RETURN_INT(bytes_waiting);
1345 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1351 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1357 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1358 RETURN_FAIL("ClearCommError() failed");
1359 RETURN_INT(comstat.cbOutQue);
1362 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1363 RETURN_FAIL("TIOCOUTQ ioctl failed");
1364 RETURN_INT(bytes_waiting);
1368 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1370 struct sp_event_set *result;
1372 TRACE("%p", result_ptr);
1375 RETURN_ERROR(SP_ERR_ARG, "Null result");
1379 if (!(result = malloc(sizeof(struct sp_event_set))))
1380 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1382 memset(result, 0, sizeof(struct sp_event_set));
1384 *result_ptr = result;
1389 static enum sp_return add_handle(struct sp_event_set *event_set,
1390 event_handle handle, enum sp_event mask)
1393 enum sp_event *new_masks;
1395 TRACE("%p, %d, %d", event_set, handle, mask);
1397 if (!(new_handles = realloc(event_set->handles,
1398 sizeof(event_handle) * (event_set->count + 1))))
1399 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1401 event_set->handles = new_handles;
1403 if (!(new_masks = realloc(event_set->masks,
1404 sizeof(enum sp_event) * (event_set->count + 1))))
1405 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1407 event_set->masks = new_masks;
1409 ((event_handle *) event_set->handles)[event_set->count] = handle;
1410 event_set->masks[event_set->count] = mask;
1417 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1418 const struct sp_port *port, enum sp_event mask)
1420 TRACE("%p, %p, %d", event_set, port, mask);
1423 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1426 RETURN_ERROR(SP_ERR_ARG, "Null port");
1428 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1429 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1435 enum sp_event handle_mask;
1436 if ((handle_mask = mask & SP_EVENT_TX_READY))
1437 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1438 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1439 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1441 TRY(add_handle(event_set, port->fd, mask));
1447 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1449 TRACE("%p", event_set);
1452 DEBUG("Null event set");
1456 DEBUG("Freeing event set");
1458 if (event_set->handles)
1459 free(event_set->handles);
1460 if (event_set->masks)
1461 free(event_set->masks);
1468 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1469 unsigned int timeout_ms)
1471 TRACE("%p, %d", event_set, timeout_ms);
1474 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1477 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1478 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1479 RETURN_FAIL("WaitForMultipleObjects() failed");
1483 struct timeval start, delta, now, end = {0, 0};
1484 const struct timeval max_delta = {
1485 (INT_MAX / 1000), (INT_MAX % 1000) * 1000
1487 int started = 0, timeout_overflow = 0;
1488 int result, timeout_remaining_ms;
1489 struct pollfd *pollfds;
1492 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1493 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1495 for (i = 0; i < event_set->count; i++) {
1496 pollfds[i].fd = ((int *)event_set->handles)[i];
1497 pollfds[i].events = 0;
1498 pollfds[i].revents = 0;
1499 if (event_set->masks[i] & SP_EVENT_RX_READY)
1500 pollfds[i].events |= POLLIN;
1501 if (event_set->masks[i] & SP_EVENT_TX_READY)
1502 pollfds[i].events |= POLLOUT;
1503 if (event_set->masks[i] & SP_EVENT_ERROR)
1504 pollfds[i].events |= POLLERR;
1508 /* Get time at start of operation. */
1510 /* Define duration of timeout. */
1511 delta.tv_sec = timeout_ms / 1000;
1512 delta.tv_usec = (timeout_ms % 1000) * 1000;
1513 /* Calculate time at which we should give up. */
1514 timeradd(&start, &delta, &end);
1517 /* Loop until an event occurs. */
1520 * Check timeout only if we have run poll() at least once,
1521 * to avoid any issues if a short timeout is reached before
1522 * poll() is even run.
1525 timeout_remaining_ms = -1;
1526 } else if (!started) {
1527 timeout_overflow = (timeout_ms > INT_MAX);
1528 timeout_remaining_ms = timeout_overflow ? INT_MAX : timeout_ms;
1531 if (timercmp(&now, &end, >)) {
1532 DEBUG("Wait timed out");
1535 timersub(&end, &now, &delta);
1536 if ((timeout_overflow = timercmp(&delta, &max_delta, >)))
1538 timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1541 result = poll(pollfds, event_set->count, timeout_remaining_ms);
1545 if (errno == EINTR) {
1546 DEBUG("poll() call was interrupted, repeating");
1550 RETURN_FAIL("poll() failed");
1552 } else if (result == 0) {
1553 DEBUG("poll() timed out");
1554 if (!timeout_overflow)
1557 DEBUG("poll() completed");
1567 #ifdef USE_TERMIOS_SPEED
1568 static enum sp_return get_baudrate(int fd, int *baudrate)
1572 TRACE("%d, %p", fd, baudrate);
1574 DEBUG("Getting baud rate");
1576 if (!(data = malloc(get_termios_size())))
1577 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1579 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1581 RETURN_FAIL("Getting termios failed");
1584 *baudrate = get_termios_speed(data);
1591 static enum sp_return set_baudrate(int fd, int baudrate)
1595 TRACE("%d, %d", fd, baudrate);
1597 DEBUG("Getting baud rate");
1599 if (!(data = malloc(get_termios_size())))
1600 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1602 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1604 RETURN_FAIL("Getting termios failed");
1607 DEBUG("Setting baud rate");
1609 set_termios_speed(data, baudrate);
1611 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1613 RETURN_FAIL("Setting termios failed");
1620 #endif /* USE_TERMIOS_SPEED */
1623 static enum sp_return get_flow(int fd, struct port_data *data)
1627 TRACE("%d, %p", fd, data);
1629 DEBUG("Getting advanced flow control");
1631 if (!(termx = malloc(get_termiox_size())))
1632 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1634 if (ioctl(fd, TCGETX, termx) < 0) {
1636 RETURN_FAIL("Getting termiox failed");
1639 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1640 &data->dtr_flow, &data->dsr_flow);
1647 static enum sp_return set_flow(int fd, struct port_data *data)
1651 TRACE("%d, %p", fd, data);
1653 DEBUG("Getting advanced flow control");
1655 if (!(termx = malloc(get_termiox_size())))
1656 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1658 if (ioctl(fd, TCGETX, termx) < 0) {
1660 RETURN_FAIL("Getting termiox failed");
1663 DEBUG("Setting advanced flow control");
1665 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1666 data->dtr_flow, data->dsr_flow);
1668 if (ioctl(fd, TCSETX, termx) < 0) {
1670 RETURN_FAIL("Setting termiox failed");
1677 #endif /* USE_TERMIOX */
1679 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1680 struct sp_port_config *config)
1684 TRACE("%p, %p, %p", port, data, config);
1686 DEBUG_FMT("Getting configuration for port %s", port->name);
1689 if (!GetCommState(port->hdl, &data->dcb))
1690 RETURN_FAIL("GetCommState() failed");
1692 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1693 if (data->dcb.BaudRate == std_baudrates[i].index) {
1694 config->baudrate = std_baudrates[i].value;
1699 if (i == NUM_STD_BAUDRATES)
1700 /* BaudRate field can be either an index or a custom baud rate. */
1701 config->baudrate = data->dcb.BaudRate;
1703 config->bits = data->dcb.ByteSize;
1705 if (data->dcb.fParity)
1706 switch (data->dcb.Parity) {
1708 config->parity = SP_PARITY_NONE;
1711 config->parity = SP_PARITY_ODD;
1714 config->parity = SP_PARITY_EVEN;
1717 config->parity = SP_PARITY_MARK;
1720 config->parity = SP_PARITY_SPACE;
1723 config->parity = -1;
1726 config->parity = SP_PARITY_NONE;
1728 switch (data->dcb.StopBits) {
1730 config->stopbits = 1;
1733 config->stopbits = 2;
1736 config->stopbits = -1;
1739 switch (data->dcb.fRtsControl) {
1740 case RTS_CONTROL_DISABLE:
1741 config->rts = SP_RTS_OFF;
1743 case RTS_CONTROL_ENABLE:
1744 config->rts = SP_RTS_ON;
1746 case RTS_CONTROL_HANDSHAKE:
1747 config->rts = SP_RTS_FLOW_CONTROL;
1753 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1755 switch (data->dcb.fDtrControl) {
1756 case DTR_CONTROL_DISABLE:
1757 config->dtr = SP_DTR_OFF;
1759 case DTR_CONTROL_ENABLE:
1760 config->dtr = SP_DTR_ON;
1762 case DTR_CONTROL_HANDSHAKE:
1763 config->dtr = SP_DTR_FLOW_CONTROL;
1769 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1771 if (data->dcb.fInX) {
1772 if (data->dcb.fOutX)
1773 config->xon_xoff = SP_XONXOFF_INOUT;
1775 config->xon_xoff = SP_XONXOFF_IN;
1777 if (data->dcb.fOutX)
1778 config->xon_xoff = SP_XONXOFF_OUT;
1780 config->xon_xoff = SP_XONXOFF_DISABLED;
1785 if (tcgetattr(port->fd, &data->term) < 0)
1786 RETURN_FAIL("tcgetattr() failed");
1788 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1789 RETURN_FAIL("TIOCMGET ioctl failed");
1792 int ret = get_flow(port->fd, data);
1794 if (ret == SP_ERR_FAIL && errno == EINVAL)
1795 data->termiox_supported = 0;
1797 RETURN_CODEVAL(ret);
1799 data->termiox_supported = 1;
1801 data->termiox_supported = 0;
1804 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1805 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1806 config->baudrate = std_baudrates[i].value;
1811 if (i == NUM_STD_BAUDRATES) {
1813 config->baudrate = (int)data->term.c_ispeed;
1814 #elif defined(USE_TERMIOS_SPEED)
1815 TRY(get_baudrate(port->fd, &config->baudrate));
1817 config->baudrate = -1;
1821 switch (data->term.c_cflag & CSIZE) {
1838 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1839 config->parity = SP_PARITY_NONE;
1840 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1841 config->parity = -1;
1843 else if (data->term.c_cflag & CMSPAR)
1844 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1847 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1849 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1851 if (data->term.c_cflag & CRTSCTS) {
1852 config->rts = SP_RTS_FLOW_CONTROL;
1853 config->cts = SP_CTS_FLOW_CONTROL;
1855 if (data->termiox_supported && data->rts_flow)
1856 config->rts = SP_RTS_FLOW_CONTROL;
1858 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1860 config->cts = (data->termiox_supported && data->cts_flow) ?
1861 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1864 if (data->termiox_supported && data->dtr_flow)
1865 config->dtr = SP_DTR_FLOW_CONTROL;
1867 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1869 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1870 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1872 if (data->term.c_iflag & IXOFF) {
1873 if (data->term.c_iflag & IXON)
1874 config->xon_xoff = SP_XONXOFF_INOUT;
1876 config->xon_xoff = SP_XONXOFF_IN;
1878 if (data->term.c_iflag & IXON)
1879 config->xon_xoff = SP_XONXOFF_OUT;
1881 config->xon_xoff = SP_XONXOFF_DISABLED;
1888 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1889 const struct sp_port_config *config)
1893 BAUD_TYPE baud_nonstd;
1897 #ifdef USE_TERMIOS_SPEED
1898 int baud_nonstd = 0;
1901 TRACE("%p, %p, %p", port, data, config);
1903 DEBUG_FMT("Setting configuration for port %s", port->name);
1907 TRY(await_write_completion(port));
1909 if (config->baudrate >= 0) {
1910 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1911 if (config->baudrate == std_baudrates[i].value) {
1912 data->dcb.BaudRate = std_baudrates[i].index;
1917 if (i == NUM_STD_BAUDRATES)
1918 data->dcb.BaudRate = config->baudrate;
1920 /* Allocate write buffer for 50ms of data at baud rate. */
1921 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1922 port->write_buf = realloc(port->write_buf,
1923 port->write_buf_size);
1925 if (!port->write_buf)
1926 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1929 if (config->bits >= 0)
1930 data->dcb.ByteSize = config->bits;
1932 if (config->parity >= 0) {
1933 switch (config->parity) {
1934 case SP_PARITY_NONE:
1935 data->dcb.Parity = NOPARITY;
1938 data->dcb.Parity = ODDPARITY;
1940 case SP_PARITY_EVEN:
1941 data->dcb.Parity = EVENPARITY;
1943 case SP_PARITY_MARK:
1944 data->dcb.Parity = MARKPARITY;
1946 case SP_PARITY_SPACE:
1947 data->dcb.Parity = SPACEPARITY;
1950 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1954 if (config->stopbits >= 0) {
1955 switch (config->stopbits) {
1956 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1958 data->dcb.StopBits = ONESTOPBIT;
1961 data->dcb.StopBits = TWOSTOPBITS;
1964 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1968 if (config->rts >= 0) {
1969 switch (config->rts) {
1971 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1974 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1976 case SP_RTS_FLOW_CONTROL:
1977 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1980 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1984 if (config->cts >= 0) {
1985 switch (config->cts) {
1987 data->dcb.fOutxCtsFlow = FALSE;
1989 case SP_CTS_FLOW_CONTROL:
1990 data->dcb.fOutxCtsFlow = TRUE;
1993 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1997 if (config->dtr >= 0) {
1998 switch (config->dtr) {
2000 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
2003 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
2005 case SP_DTR_FLOW_CONTROL:
2006 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
2009 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
2013 if (config->dsr >= 0) {
2014 switch (config->dsr) {
2016 data->dcb.fOutxDsrFlow = FALSE;
2018 case SP_DSR_FLOW_CONTROL:
2019 data->dcb.fOutxDsrFlow = TRUE;
2022 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2026 if (config->xon_xoff >= 0) {
2027 switch (config->xon_xoff) {
2028 case SP_XONXOFF_DISABLED:
2029 data->dcb.fInX = FALSE;
2030 data->dcb.fOutX = FALSE;
2033 data->dcb.fInX = TRUE;
2034 data->dcb.fOutX = FALSE;
2036 case SP_XONXOFF_OUT:
2037 data->dcb.fInX = FALSE;
2038 data->dcb.fOutX = TRUE;
2040 case SP_XONXOFF_INOUT:
2041 data->dcb.fInX = TRUE;
2042 data->dcb.fOutX = TRUE;
2045 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2049 if (!SetCommState(port->hdl, &data->dcb))
2050 RETURN_FAIL("SetCommState() failed");
2056 if (config->baudrate >= 0) {
2057 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2058 if (config->baudrate == std_baudrates[i].value) {
2059 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2060 RETURN_FAIL("cfsetospeed() failed");
2062 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2063 RETURN_FAIL("cfsetispeed() failed");
2068 /* Non-standard baud rate */
2069 if (i == NUM_STD_BAUDRATES) {
2071 /* Set "dummy" baud rate. */
2072 if (cfsetspeed(&data->term, B9600) < 0)
2073 RETURN_FAIL("cfsetspeed() failed");
2074 baud_nonstd = config->baudrate;
2075 #elif defined(USE_TERMIOS_SPEED)
2078 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2083 if (config->bits >= 0) {
2084 data->term.c_cflag &= ~CSIZE;
2085 switch (config->bits) {
2087 data->term.c_cflag |= CS8;
2090 data->term.c_cflag |= CS7;
2093 data->term.c_cflag |= CS6;
2096 data->term.c_cflag |= CS5;
2099 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2103 if (config->parity >= 0) {
2104 data->term.c_iflag &= ~IGNPAR;
2105 data->term.c_cflag &= ~(PARENB | PARODD);
2107 data->term.c_cflag &= ~CMSPAR;
2109 switch (config->parity) {
2110 case SP_PARITY_NONE:
2111 data->term.c_iflag |= IGNPAR;
2113 case SP_PARITY_EVEN:
2114 data->term.c_cflag |= PARENB;
2117 data->term.c_cflag |= PARENB | PARODD;
2120 case SP_PARITY_MARK:
2121 data->term.c_cflag |= PARENB | PARODD;
2122 data->term.c_cflag |= CMSPAR;
2124 case SP_PARITY_SPACE:
2125 data->term.c_cflag |= PARENB;
2126 data->term.c_cflag |= CMSPAR;
2129 case SP_PARITY_MARK:
2130 case SP_PARITY_SPACE:
2131 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2134 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2138 if (config->stopbits >= 0) {
2139 data->term.c_cflag &= ~CSTOPB;
2140 switch (config->stopbits) {
2142 data->term.c_cflag &= ~CSTOPB;
2145 data->term.c_cflag |= CSTOPB;
2148 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2152 if (config->rts >= 0 || config->cts >= 0) {
2153 if (data->termiox_supported) {
2154 data->rts_flow = data->cts_flow = 0;
2155 switch (config->rts) {
2158 controlbits = TIOCM_RTS;
2159 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2160 RETURN_FAIL("Setting RTS signal level failed");
2162 case SP_RTS_FLOW_CONTROL:
2168 if (config->cts == SP_CTS_FLOW_CONTROL)
2171 if (data->rts_flow && data->cts_flow)
2172 data->term.c_iflag |= CRTSCTS;
2174 data->term.c_iflag &= ~CRTSCTS;
2176 /* Asymmetric use of RTS/CTS not supported. */
2177 if (data->term.c_iflag & CRTSCTS) {
2178 /* Flow control can only be disabled for both RTS & CTS together. */
2179 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2180 if (config->cts != SP_CTS_IGNORE)
2181 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2183 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2184 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2185 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2188 /* Flow control can only be enabled for both RTS & CTS together. */
2189 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2190 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2191 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2194 if (config->rts >= 0) {
2195 if (config->rts == SP_RTS_FLOW_CONTROL) {
2196 data->term.c_iflag |= CRTSCTS;
2198 controlbits = TIOCM_RTS;
2199 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2201 RETURN_FAIL("Setting RTS signal level failed");
2207 if (config->dtr >= 0 || config->dsr >= 0) {
2208 if (data->termiox_supported) {
2209 data->dtr_flow = data->dsr_flow = 0;
2210 switch (config->dtr) {
2213 controlbits = TIOCM_DTR;
2214 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2215 RETURN_FAIL("Setting DTR signal level failed");
2217 case SP_DTR_FLOW_CONTROL:
2223 if (config->dsr == SP_DSR_FLOW_CONTROL)
2226 /* DTR/DSR flow control not supported. */
2227 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2228 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2230 if (config->dtr >= 0) {
2231 controlbits = TIOCM_DTR;
2232 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2234 RETURN_FAIL("Setting DTR signal level failed");
2239 if (config->xon_xoff >= 0) {
2240 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2241 switch (config->xon_xoff) {
2242 case SP_XONXOFF_DISABLED:
2245 data->term.c_iflag |= IXOFF;
2247 case SP_XONXOFF_OUT:
2248 data->term.c_iflag |= IXON | IXANY;
2250 case SP_XONXOFF_INOUT:
2251 data->term.c_iflag |= IXON | IXOFF | IXANY;
2254 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2258 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2259 RETURN_FAIL("tcsetattr() failed");
2262 if (baud_nonstd != B0) {
2263 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2264 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2266 * Set baud rates in data->term to correct, but incompatible
2267 * with tcsetattr() value, same as delivered by tcgetattr().
2269 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2270 RETURN_FAIL("cfsetspeed() failed");
2272 #elif defined(__linux__)
2273 #ifdef USE_TERMIOS_SPEED
2275 TRY(set_baudrate(port->fd, config->baudrate));
2278 if (data->termiox_supported)
2279 TRY(set_flow(port->fd, data));
2283 #endif /* !_WIN32 */
2288 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2290 struct sp_port_config *config;
2292 TRACE("%p", config_ptr);
2295 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2299 if (!(config = malloc(sizeof(struct sp_port_config))))
2300 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2302 config->baudrate = -1;
2304 config->parity = -1;
2305 config->stopbits = -1;
2311 *config_ptr = config;
2316 SP_API void sp_free_config(struct sp_port_config *config)
2318 TRACE("%p", config);
2321 DEBUG("Null config");
2328 SP_API enum sp_return sp_get_config(struct sp_port *port,
2329 struct sp_port_config *config)
2331 struct port_data data;
2333 TRACE("%p, %p", port, config);
2338 RETURN_ERROR(SP_ERR_ARG, "Null config");
2340 TRY(get_config(port, &data, config));
2345 SP_API enum sp_return sp_set_config(struct sp_port *port,
2346 const struct sp_port_config *config)
2348 struct port_data data;
2349 struct sp_port_config prev_config;
2351 TRACE("%p, %p", port, config);
2356 RETURN_ERROR(SP_ERR_ARG, "Null config");
2358 TRY(get_config(port, &data, &prev_config));
2359 TRY(set_config(port, &data, config));
2364 #define CREATE_ACCESSORS(x, type) \
2365 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2366 struct port_data data; \
2367 struct sp_port_config config; \
2368 TRACE("%p, %d", port, x); \
2369 CHECK_OPEN_PORT(); \
2370 TRY(get_config(port, &data, &config)); \
2372 TRY(set_config(port, &data, &config)); \
2375 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2377 TRACE("%p, %p", config, x); \
2379 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2381 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2385 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2387 TRACE("%p, %d", config, x); \
2389 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2394 CREATE_ACCESSORS(baudrate, int)
2395 CREATE_ACCESSORS(bits, int)
2396 CREATE_ACCESSORS(parity, enum sp_parity)
2397 CREATE_ACCESSORS(stopbits, int)
2398 CREATE_ACCESSORS(rts, enum sp_rts)
2399 CREATE_ACCESSORS(cts, enum sp_cts)
2400 CREATE_ACCESSORS(dtr, enum sp_dtr)
2401 CREATE_ACCESSORS(dsr, enum sp_dsr)
2402 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2404 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2405 enum sp_flowcontrol flowcontrol)
2408 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2410 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2411 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2413 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2414 config->xon_xoff = SP_XONXOFF_INOUT;
2416 config->xon_xoff = SP_XONXOFF_DISABLED;
2418 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2419 config->rts = SP_RTS_FLOW_CONTROL;
2420 config->cts = SP_CTS_FLOW_CONTROL;
2422 if (config->rts == SP_RTS_FLOW_CONTROL)
2423 config->rts = SP_RTS_ON;
2424 config->cts = SP_CTS_IGNORE;
2427 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2428 config->dtr = SP_DTR_FLOW_CONTROL;
2429 config->dsr = SP_DSR_FLOW_CONTROL;
2431 if (config->dtr == SP_DTR_FLOW_CONTROL)
2432 config->dtr = SP_DTR_ON;
2433 config->dsr = SP_DSR_IGNORE;
2439 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2440 enum sp_flowcontrol flowcontrol)
2442 struct port_data data;
2443 struct sp_port_config config;
2445 TRACE("%p, %d", port, flowcontrol);
2449 TRY(get_config(port, &data, &config));
2451 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2453 TRY(set_config(port, &data, &config));
2458 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2459 enum sp_signal *signals)
2461 TRACE("%p, %p", port, signals);
2466 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2468 DEBUG_FMT("Getting control signals for port %s", port->name);
2473 if (GetCommModemStatus(port->hdl, &bits) == 0)
2474 RETURN_FAIL("GetCommModemStatus() failed");
2475 if (bits & MS_CTS_ON)
2476 *signals |= SP_SIG_CTS;
2477 if (bits & MS_DSR_ON)
2478 *signals |= SP_SIG_DSR;
2479 if (bits & MS_RLSD_ON)
2480 *signals |= SP_SIG_DCD;
2481 if (bits & MS_RING_ON)
2482 *signals |= SP_SIG_RI;
2485 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2486 RETURN_FAIL("TIOCMGET ioctl failed");
2487 if (bits & TIOCM_CTS)
2488 *signals |= SP_SIG_CTS;
2489 if (bits & TIOCM_DSR)
2490 *signals |= SP_SIG_DSR;
2491 if (bits & TIOCM_CAR)
2492 *signals |= SP_SIG_DCD;
2493 if (bits & TIOCM_RNG)
2494 *signals |= SP_SIG_RI;
2499 SP_API enum sp_return sp_start_break(struct sp_port *port)
2505 if (SetCommBreak(port->hdl) == 0)
2506 RETURN_FAIL("SetCommBreak() failed");
2508 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2509 RETURN_FAIL("TIOCSBRK ioctl failed");
2515 SP_API enum sp_return sp_end_break(struct sp_port *port)
2521 if (ClearCommBreak(port->hdl) == 0)
2522 RETURN_FAIL("ClearCommBreak() failed");
2524 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2525 RETURN_FAIL("TIOCCBRK ioctl failed");
2531 SP_API int sp_last_error_code(void)
2535 RETURN_INT(GetLastError());
2541 SP_API char *sp_last_error_message(void)
2547 DWORD error = GetLastError();
2549 DWORD length = FormatMessage(
2550 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2551 FORMAT_MESSAGE_FROM_SYSTEM |
2552 FORMAT_MESSAGE_IGNORE_INSERTS,
2555 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2559 if (length >= 2 && message[length - 2] == '\r')
2560 message[length - 2] = '\0';
2562 RETURN_STRING(message);
2564 RETURN_STRING(strerror(errno));
2568 SP_API void sp_free_error_message(char *message)
2570 TRACE("%s", message);
2581 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2583 TRACE("%p", handler);
2585 sp_debug_handler = handler;
2590 SP_API void sp_default_debug_handler(const char *format, ...)
2593 va_start(args, format);
2594 if (getenv("LIBSERIALPORT_DEBUG")) {
2595 fputs("sp: ", stderr);
2596 vfprintf(stderr, format, args);
2601 SP_API int sp_get_major_package_version(void)
2603 return SP_PACKAGE_VERSION_MAJOR;
2606 SP_API int sp_get_minor_package_version(void)
2608 return SP_PACKAGE_VERSION_MINOR;
2611 SP_API int sp_get_micro_package_version(void)
2613 return SP_PACKAGE_VERSION_MICRO;
2616 SP_API const char *sp_get_package_version_string(void)
2618 return SP_PACKAGE_VERSION_STRING;
2621 SP_API int sp_get_current_lib_version(void)
2623 return SP_LIB_VERSION_CURRENT;
2626 SP_API int sp_get_revision_lib_version(void)
2628 return SP_LIB_VERSION_REVISION;
2631 SP_API int sp_get_age_lib_version(void)
2633 return SP_LIB_VERSION_AGE;
2636 SP_API const char *sp_get_lib_version_string(void)
2638 return SP_LIB_VERSION_STRING;