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 enum sp_return get_config(struct sp_port *port, struct port_data *data,
53 struct sp_port_config *config);
55 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
56 const struct sp_port_config *config);
59 static void get_time(struct timeval *time)
61 #ifdef HAVE_CLOCK_GETTIME
63 if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
64 clock_gettime(CLOCK_REALTIME, &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);
80 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
83 #ifndef NO_PORT_METADATA
88 TRACE("%s, %p", portname, port_ptr);
91 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
96 RETURN_ERROR(SP_ERR_ARG, "Null port name");
98 DEBUG_FMT("Building structure for port %s", portname);
100 #if !defined(_WIN32) && defined(HAVE_REALPATH)
102 * get_port_details() below tries to be too smart and figure out
103 * some transport properties from the port name which breaks with
104 * symlinks. Therefore we canonicalize the portname first.
106 char pathbuf[PATH_MAX + 1];
107 char *res = realpath(portname, pathbuf);
109 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
114 if (!(port = malloc(sizeof(struct sp_port))))
115 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
117 len = strlen(portname) + 1;
119 if (!(port->name = malloc(len))) {
121 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
124 memcpy(port->name, portname, len);
127 port->usb_path = NULL;
128 port->hdl = INVALID_HANDLE_VALUE;
129 port->write_buf = NULL;
130 port->write_buf_size = 0;
135 port->description = NULL;
136 port->transport = SP_TRANSPORT_NATIVE;
138 port->usb_address = -1;
141 port->usb_manufacturer = NULL;
142 port->usb_product = NULL;
143 port->usb_serial = NULL;
144 port->bluetooth_address = NULL;
146 #ifndef NO_PORT_METADATA
147 if ((ret = get_port_details(port)) != SP_OK) {
158 SP_API char *sp_get_port_name(const struct sp_port *port)
165 RETURN_STRING(port->name);
168 SP_API char *sp_get_port_description(const struct sp_port *port)
172 if (!port || !port->description)
175 RETURN_STRING(port->description);
178 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
183 RETURN_ERROR(SP_ERR_ARG, "Null port");
185 RETURN_INT(port->transport);
188 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
189 int *usb_bus,int *usb_address)
194 RETURN_ERROR(SP_ERR_ARG, "Null port");
195 if (port->transport != SP_TRANSPORT_USB)
196 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
197 if (port->usb_bus < 0 || port->usb_address < 0)
198 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
201 *usb_bus = port->usb_bus;
203 *usb_address = port->usb_address;
208 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
209 int *usb_vid, int *usb_pid)
214 RETURN_ERROR(SP_ERR_ARG, "Null port");
215 if (port->transport != SP_TRANSPORT_USB)
216 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
217 if (port->usb_vid < 0 || port->usb_pid < 0)
218 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
221 *usb_vid = port->usb_vid;
223 *usb_pid = port->usb_pid;
228 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
232 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
235 RETURN_STRING(port->usb_manufacturer);
238 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
242 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
245 RETURN_STRING(port->usb_product);
248 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
252 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
255 RETURN_STRING(port->usb_serial);
258 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
262 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
263 || !port->bluetooth_address)
266 RETURN_STRING(port->bluetooth_address);
269 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
272 TRACE("%p, %p", port, result_ptr);
275 RETURN_ERROR(SP_ERR_ARG, "Null port");
277 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
280 HANDLE *handle_ptr = result_ptr;
281 *handle_ptr = port->hdl;
283 int *fd_ptr = result_ptr;
290 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
291 struct sp_port **copy_ptr)
293 TRACE("%p, %p", port, copy_ptr);
296 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
301 RETURN_ERROR(SP_ERR_ARG, "Null port");
304 RETURN_ERROR(SP_ERR_ARG, "Null port name");
306 DEBUG("Copying port structure");
308 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
311 SP_API void sp_free_port(struct sp_port *port)
320 DEBUG("Freeing port structure");
324 if (port->description)
325 free(port->description);
326 if (port->usb_manufacturer)
327 free(port->usb_manufacturer);
328 if (port->usb_product)
329 free(port->usb_product);
330 if (port->usb_serial)
331 free(port->usb_serial);
332 if (port->bluetooth_address)
333 free(port->bluetooth_address);
336 free(port->usb_path);
338 free(port->write_buf);
346 SP_PRIV struct sp_port **list_append(struct sp_port **list,
347 const char *portname)
352 for (count = 0; list[count]; count++)
354 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
357 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
359 list[count + 1] = NULL;
363 sp_free_port_list(list);
367 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
369 #ifndef NO_ENUMERATION
370 struct sp_port **list;
374 TRACE("%p", list_ptr);
377 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
381 #ifdef NO_ENUMERATION
382 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
384 DEBUG("Enumerating ports");
386 if (!(list = malloc(sizeof(struct sp_port *))))
387 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
391 ret = list_ports(&list);
396 sp_free_port_list(list);
404 SP_API void sp_free_port_list(struct sp_port **list)
415 DEBUG("Freeing port list");
417 for (i = 0; list[i]; i++)
418 sp_free_port(list[i]);
424 #define CHECK_PORT() do { \
426 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
428 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
431 #define CHECK_PORT_HANDLE() do { \
432 if (port->hdl == INVALID_HANDLE_VALUE) \
433 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
436 #define CHECK_PORT_HANDLE() do { \
438 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
441 #define CHECK_OPEN_PORT() do { \
443 CHECK_PORT_HANDLE(); \
447 /** To be called after port receive buffer is emptied. */
448 static enum sp_return restart_wait(struct sp_port *port)
452 if (port->wait_running) {
453 /* Check status of running wait operation. */
454 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
455 &wait_result, FALSE)) {
456 DEBUG("Previous wait completed");
457 port->wait_running = FALSE;
458 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
459 DEBUG("Previous wait still running");
462 RETURN_FAIL("GetOverlappedResult() failed");
466 if (!port->wait_running) {
467 /* Start new wait operation. */
468 if (WaitCommEvent(port->hdl, &port->events,
470 DEBUG("New wait returned, events already pending");
471 } else if (GetLastError() == ERROR_IO_PENDING) {
472 DEBUG("New wait running in background");
473 port->wait_running = TRUE;
475 RETURN_FAIL("WaitCommEvent() failed");
483 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
485 struct port_data data;
486 struct sp_port_config config;
489 TRACE("%p, 0x%x", port, flags);
493 if (flags > SP_MODE_READ_WRITE)
494 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
496 DEBUG_FMT("Opening port %s", port->name);
499 DWORD desired_access = 0, flags_and_attributes = 0, errors;
500 char *escaped_port_name;
503 /* Prefix port name with '\\.\' to work with ports above COM9. */
504 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
505 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
506 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
508 /* Map 'flags' to the OS-specific settings. */
509 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
510 if (flags & SP_MODE_READ)
511 desired_access |= GENERIC_READ;
512 if (flags & SP_MODE_WRITE)
513 desired_access |= GENERIC_WRITE;
515 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
516 OPEN_EXISTING, flags_and_attributes, 0);
518 free(escaped_port_name);
520 if (port->hdl == INVALID_HANDLE_VALUE)
521 RETURN_FAIL("Port CreateFile() failed");
523 /* All timeouts initially disabled. */
524 port->timeouts.ReadIntervalTimeout = 0;
525 port->timeouts.ReadTotalTimeoutMultiplier = 0;
526 port->timeouts.ReadTotalTimeoutConstant = 0;
527 port->timeouts.WriteTotalTimeoutMultiplier = 0;
528 port->timeouts.WriteTotalTimeoutConstant = 0;
530 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
532 RETURN_FAIL("SetCommTimeouts() failed");
535 /* Prepare OVERLAPPED structures. */
536 #define INIT_OVERLAPPED(ovl) do { \
537 memset(&port->ovl, 0, sizeof(port->ovl)); \
538 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
539 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
540 == INVALID_HANDLE_VALUE) { \
542 RETURN_FAIL(#ovl "CreateEvent() failed"); \
546 INIT_OVERLAPPED(read_ovl);
547 INIT_OVERLAPPED(write_ovl);
548 INIT_OVERLAPPED(wait_ovl);
550 /* Set event mask for RX and error events. */
551 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
553 RETURN_FAIL("SetCommMask() failed");
556 port->writing = FALSE;
557 port->wait_running = FALSE;
559 ret = restart_wait(port);
566 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
568 /* Map 'flags' to the OS-specific settings. */
569 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
570 flags_local |= O_RDWR;
571 else if (flags & SP_MODE_READ)
572 flags_local |= O_RDONLY;
573 else if (flags & SP_MODE_WRITE)
574 flags_local |= O_WRONLY;
576 if ((port->fd = open(port->name, flags_local)) < 0)
577 RETURN_FAIL("open() failed");
580 ret = get_config(port, &data, &config);
587 /* Set sane port settings. */
589 data.dcb.fBinary = TRUE;
590 data.dcb.fDsrSensitivity = FALSE;
591 data.dcb.fErrorChar = FALSE;
592 data.dcb.fNull = FALSE;
593 data.dcb.fAbortOnError = FALSE;
595 /* Turn off all fancy termios tricks, give us a raw channel. */
596 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
598 data.term.c_iflag &= ~IUCLC;
600 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
602 data.term.c_oflag &= ~OLCUC;
605 data.term.c_oflag &= ~NLDLY;
608 data.term.c_oflag &= ~CRDLY;
611 data.term.c_oflag &= ~TABDLY;
614 data.term.c_oflag &= ~BSDLY;
617 data.term.c_oflag &= ~VTDLY;
620 data.term.c_oflag &= ~FFDLY;
623 data.term.c_oflag &= ~OFILL;
625 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
626 data.term.c_cc[VMIN] = 0;
627 data.term.c_cc[VTIME] = 0;
629 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
630 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
634 if (ClearCommError(port->hdl, &errors, &status) == 0)
635 RETURN_FAIL("ClearCommError() failed");
638 ret = set_config(port, &data, &config);
648 SP_API enum sp_return sp_close(struct sp_port *port)
654 DEBUG_FMT("Closing port %s", port->name);
657 /* Returns non-zero upon success, 0 upon failure. */
658 if (CloseHandle(port->hdl) == 0)
659 RETURN_FAIL("Port CloseHandle() failed");
660 port->hdl = INVALID_HANDLE_VALUE;
662 /* Close event handles for overlapped structures. */
663 #define CLOSE_OVERLAPPED(ovl) do { \
664 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
665 CloseHandle(port->ovl.hEvent) == 0) \
666 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
668 CLOSE_OVERLAPPED(read_ovl);
669 CLOSE_OVERLAPPED(write_ovl);
670 CLOSE_OVERLAPPED(wait_ovl);
672 if (port->write_buf) {
673 free(port->write_buf);
674 port->write_buf = NULL;
677 /* Returns 0 upon success, -1 upon failure. */
678 if (close(port->fd) == -1)
679 RETURN_FAIL("close() failed");
686 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
688 TRACE("%p, 0x%x", port, buffers);
692 if (buffers > SP_BUF_BOTH)
693 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
695 const char *buffer_names[] = {"no", "input", "output", "both"};
697 DEBUG_FMT("Flushing %s buffers on port %s",
698 buffer_names[buffers], port->name);
702 if (buffers & SP_BUF_INPUT)
703 flags |= PURGE_RXCLEAR;
704 if (buffers & SP_BUF_OUTPUT)
705 flags |= PURGE_TXCLEAR;
707 /* Returns non-zero upon success, 0 upon failure. */
708 if (PurgeComm(port->hdl, flags) == 0)
709 RETURN_FAIL("PurgeComm() failed");
711 if (buffers & SP_BUF_INPUT)
712 TRY(restart_wait(port));
715 if (buffers == SP_BUF_BOTH)
717 else if (buffers == SP_BUF_INPUT)
719 else if (buffers == SP_BUF_OUTPUT)
722 /* Returns 0 upon success, -1 upon failure. */
723 if (tcflush(port->fd, flags) < 0)
724 RETURN_FAIL("tcflush() failed");
729 SP_API enum sp_return sp_drain(struct sp_port *port)
735 DEBUG_FMT("Draining port %s", port->name);
738 /* Returns non-zero upon success, 0 upon failure. */
739 if (FlushFileBuffers(port->hdl) == 0)
740 RETURN_FAIL("FlushFileBuffers() failed");
745 #if defined(__ANDROID__) && (__ANDROID_API__ < 21)
746 /* Android only has tcdrain from platform 21 onwards.
747 * On previous API versions, use the ioctl directly. */
749 result = ioctl(port->fd, TCSBRK, &arg);
751 result = tcdrain(port->fd);
754 if (errno == EINTR) {
755 DEBUG("tcdrain() was interrupted");
758 RETURN_FAIL("tcdrain() failed");
768 static enum sp_return await_write_completion(struct sp_port *port)
774 /* Wait for previous non-blocking write to complete, if any. */
776 DEBUG("Waiting for previous write to complete");
777 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
780 RETURN_FAIL("Previous write failed to complete");
781 DEBUG("Previous write completed");
788 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
789 size_t count, unsigned int timeout_ms)
791 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
796 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
799 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
800 count, port->name, timeout_ms);
802 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
809 DWORD bytes_written = 0;
811 TRY(await_write_completion(port));
814 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
815 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
816 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
817 RETURN_FAIL("SetCommTimeouts() failed");
820 /* Reduce count if it exceeds the WriteFile limit. */
821 if (count > WRITEFILE_MAX_SIZE)
822 count = WRITEFILE_MAX_SIZE;
825 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
826 DEBUG("Write completed immediately");
828 } else if (GetLastError() == ERROR_IO_PENDING) {
829 DEBUG("Waiting for write to complete");
830 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
831 if (GetLastError() == ERROR_SEM_TIMEOUT) {
832 DEBUG("Write timed out");
835 RETURN_FAIL("GetOverlappedResult() failed");
838 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
839 RETURN_INT(bytes_written);
841 RETURN_FAIL("WriteFile() failed");
844 size_t bytes_written = 0;
845 unsigned char *ptr = (unsigned char *) buf;
846 struct timeval start, delta, now, end = {0, 0};
852 /* Get time at start of operation. */
854 /* Define duration of timeout. */
855 delta.tv_sec = timeout_ms / 1000;
856 delta.tv_usec = (timeout_ms % 1000) * 1000;
857 /* Calculate time at which we should give up. */
858 timeradd(&start, &delta, &end);
862 FD_SET(port->fd, &fds);
864 /* Loop until we have written the requested number of bytes. */
865 while (bytes_written < count) {
867 * Check timeout only if we have run select() at least once,
868 * to avoid any issues if a short timeout is reached before
869 * select() is even run.
871 if (timeout_ms && started) {
873 if (timercmp(&now, &end, >))
874 /* Timeout has expired. */
876 timersub(&end, &now, &delta);
878 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
881 if (errno == EINTR) {
882 DEBUG("select() call was interrupted, repeating");
885 RETURN_FAIL("select() failed");
887 } else if (result == 0) {
888 /* Timeout has expired. */
893 result = write(port->fd, ptr, count - bytes_written);
897 /* This shouldn't happen because we did a select() first, but handle anyway. */
900 /* This is an actual failure. */
901 RETURN_FAIL("write() failed");
904 bytes_written += result;
908 if (bytes_written < count)
909 DEBUG("Write timed out");
911 RETURN_INT(bytes_written);
915 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
916 const void *buf, size_t count)
918 TRACE("%p, %p, %d", port, buf, count);
923 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
925 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
933 /* Check whether previous write is complete. */
935 if (HasOverlappedIoCompleted(&port->write_ovl)) {
936 DEBUG("Previous write completed");
939 DEBUG("Previous write not complete");
940 /* Can't take a new write until the previous one finishes. */
946 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
947 port->timeouts.WriteTotalTimeoutConstant = 0;
948 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
949 RETURN_FAIL("SetCommTimeouts() failed");
952 /* Reduce count if it exceeds the WriteFile limit. */
953 if (count > WRITEFILE_MAX_SIZE)
954 count = WRITEFILE_MAX_SIZE;
956 /* Copy data to our write buffer. */
957 buf_bytes = min(port->write_buf_size, count);
958 memcpy(port->write_buf, buf, buf_bytes);
960 /* Start asynchronous write. */
961 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
962 if (GetLastError() == ERROR_IO_PENDING) {
963 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
964 DEBUG("Asynchronous write completed immediately");
966 DEBUG("Asynchronous write running");
968 /* Actual failure of some kind. */
969 RETURN_FAIL("WriteFile() failed");
973 DEBUG("All bytes written immediately");
975 RETURN_INT(buf_bytes);
977 /* Returns the number of bytes written, or -1 upon failure. */
978 ssize_t written = write(port->fd, buf, count);
982 // Buffer is full, no bytes written.
985 RETURN_FAIL("write() failed");
993 /* Restart wait operation if buffer was emptied. */
994 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1002 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1003 RETURN_FAIL("ClearCommError() failed");
1005 if (comstat.cbInQue == 0)
1006 TRY(restart_wait(port));
1012 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1013 size_t count, unsigned int timeout_ms)
1015 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1020 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1023 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1024 count, port->name, timeout_ms);
1026 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1033 DWORD bytes_read = 0;
1036 if (port->timeouts.ReadIntervalTimeout != 0 ||
1037 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1038 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1039 port->timeouts.ReadIntervalTimeout = 0;
1040 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1041 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1042 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1043 RETURN_FAIL("SetCommTimeouts() failed");
1047 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1048 DEBUG("Read completed immediately");
1050 } else if (GetLastError() == ERROR_IO_PENDING) {
1051 DEBUG("Waiting for read to complete");
1052 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1053 RETURN_FAIL("GetOverlappedResult() failed");
1054 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1056 RETURN_FAIL("ReadFile() failed");
1059 TRY(restart_wait_if_needed(port, bytes_read));
1061 RETURN_INT(bytes_read);
1064 size_t bytes_read = 0;
1065 unsigned char *ptr = (unsigned char *)buf;
1066 struct timeval start, delta, now, end = {0, 0};
1072 /* Get time at start of operation. */
1074 /* Define duration of timeout. */
1075 delta.tv_sec = timeout_ms / 1000;
1076 delta.tv_usec = (timeout_ms % 1000) * 1000;
1077 /* Calculate time at which we should give up. */
1078 timeradd(&start, &delta, &end);
1082 FD_SET(port->fd, &fds);
1084 /* Loop until we have the requested number of bytes. */
1085 while (bytes_read < count) {
1087 * Check timeout only if we have run select() at least once,
1088 * to avoid any issues if a short timeout is reached before
1089 * select() is even run.
1091 if (timeout_ms && started) {
1093 if (timercmp(&now, &end, >))
1094 /* Timeout has expired. */
1096 timersub(&end, &now, &delta);
1098 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1101 if (errno == EINTR) {
1102 DEBUG("select() call was interrupted, repeating");
1105 RETURN_FAIL("select() failed");
1107 } else if (result == 0) {
1108 /* Timeout has expired. */
1113 result = read(port->fd, ptr, count - bytes_read);
1116 if (errno == EAGAIN)
1118 * This shouldn't happen because we did a
1119 * select() first, but handle anyway.
1123 /* This is an actual failure. */
1124 RETURN_FAIL("read() failed");
1127 bytes_read += result;
1131 if (bytes_read < count)
1132 DEBUG("Read timed out");
1134 RETURN_INT(bytes_read);
1138 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1139 size_t count, unsigned int timeout_ms)
1141 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1146 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1149 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1152 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1153 count, port->name, timeout_ms);
1155 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1159 DWORD bytes_read = 0;
1161 /* If timeout_ms == 0, set maximum timeout. */
1162 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1165 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1166 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1167 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1168 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1169 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1170 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1171 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1172 RETURN_FAIL("SetCommTimeouts() failed");
1175 /* Loop until we have at least one byte, or timeout is reached. */
1176 while (bytes_read == 0) {
1178 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1179 DEBUG("Read completed immediately");
1180 } else if (GetLastError() == ERROR_IO_PENDING) {
1181 DEBUG("Waiting for read to complete");
1182 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1183 RETURN_FAIL("GetOverlappedResult() failed");
1184 if (bytes_read > 0) {
1185 DEBUG("Read completed");
1186 } else if (timeout_ms > 0) {
1187 DEBUG("Read timed out");
1190 DEBUG("Restarting read");
1193 RETURN_FAIL("ReadFile() failed");
1197 TRY(restart_wait_if_needed(port, bytes_read));
1199 RETURN_INT(bytes_read);
1202 size_t bytes_read = 0;
1203 struct timeval start, delta, now, end = {0, 0};
1209 /* Get time at start of operation. */
1211 /* Define duration of timeout. */
1212 delta.tv_sec = timeout_ms / 1000;
1213 delta.tv_usec = (timeout_ms % 1000) * 1000;
1214 /* Calculate time at which we should give up. */
1215 timeradd(&start, &delta, &end);
1219 FD_SET(port->fd, &fds);
1221 /* Loop until we have at least one byte, or timeout is reached. */
1222 while (bytes_read == 0) {
1224 * Check timeout only if we have run select() at least once,
1225 * to avoid any issues if a short timeout is reached before
1226 * select() is even run.
1228 if (timeout_ms && started) {
1230 if (timercmp(&now, &end, >))
1231 /* Timeout has expired. */
1233 timersub(&end, &now, &delta);
1235 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1238 if (errno == EINTR) {
1239 DEBUG("select() call was interrupted, repeating");
1242 RETURN_FAIL("select() failed");
1244 } else if (result == 0) {
1245 /* Timeout has expired. */
1250 result = read(port->fd, buf, count);
1253 if (errno == EAGAIN)
1254 /* This shouldn't happen because we did a select() first, but handle anyway. */
1257 /* This is an actual failure. */
1258 RETURN_FAIL("read() failed");
1261 bytes_read = result;
1264 if (bytes_read == 0)
1265 DEBUG("Read timed out");
1267 RETURN_INT(bytes_read);
1271 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1274 TRACE("%p, %p, %d", port, buf, count);
1279 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1281 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1287 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1288 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1289 port->timeouts.ReadTotalTimeoutConstant != 0) {
1290 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1291 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1292 port->timeouts.ReadTotalTimeoutConstant = 0;
1293 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1294 RETURN_FAIL("SetCommTimeouts() failed");
1298 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1299 if (GetLastError() != ERROR_IO_PENDING)
1300 RETURN_FAIL("ReadFile() failed");
1302 /* Get number of bytes read. */
1303 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1304 RETURN_FAIL("GetOverlappedResult() failed");
1306 TRY(restart_wait_if_needed(port, bytes_read));
1308 RETURN_INT(bytes_read);
1312 /* Returns the number of bytes read, or -1 upon failure. */
1313 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1314 if (errno == EAGAIN)
1315 /* No bytes available. */
1318 /* This is an actual failure. */
1319 RETURN_FAIL("read() failed");
1321 RETURN_INT(bytes_read);
1325 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1331 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1337 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1338 RETURN_FAIL("ClearCommError() failed");
1339 RETURN_INT(comstat.cbInQue);
1342 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1343 RETURN_FAIL("TIOCINQ ioctl failed");
1344 RETURN_INT(bytes_waiting);
1348 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1354 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1360 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1361 RETURN_FAIL("ClearCommError() failed");
1362 RETURN_INT(comstat.cbOutQue);
1365 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1366 RETURN_FAIL("TIOCOUTQ ioctl failed");
1367 RETURN_INT(bytes_waiting);
1371 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1373 struct sp_event_set *result;
1375 TRACE("%p", result_ptr);
1378 RETURN_ERROR(SP_ERR_ARG, "Null result");
1382 if (!(result = malloc(sizeof(struct sp_event_set))))
1383 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1385 memset(result, 0, sizeof(struct sp_event_set));
1387 *result_ptr = result;
1392 static enum sp_return add_handle(struct sp_event_set *event_set,
1393 event_handle handle, enum sp_event mask)
1396 enum sp_event *new_masks;
1398 TRACE("%p, %d, %d", event_set, handle, mask);
1400 if (!(new_handles = realloc(event_set->handles,
1401 sizeof(event_handle) * (event_set->count + 1))))
1402 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1404 event_set->handles = new_handles;
1406 if (!(new_masks = realloc(event_set->masks,
1407 sizeof(enum sp_event) * (event_set->count + 1))))
1408 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1410 event_set->masks = new_masks;
1412 ((event_handle *) event_set->handles)[event_set->count] = handle;
1413 event_set->masks[event_set->count] = mask;
1420 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1421 const struct sp_port *port, enum sp_event mask)
1423 TRACE("%p, %p, %d", event_set, port, mask);
1426 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1429 RETURN_ERROR(SP_ERR_ARG, "Null port");
1431 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1432 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1438 enum sp_event handle_mask;
1439 if ((handle_mask = mask & SP_EVENT_TX_READY))
1440 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1441 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1442 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1444 TRY(add_handle(event_set, port->fd, mask));
1450 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1452 TRACE("%p", event_set);
1455 DEBUG("Null event set");
1459 DEBUG("Freeing event set");
1461 if (event_set->handles)
1462 free(event_set->handles);
1463 if (event_set->masks)
1464 free(event_set->masks);
1471 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1472 unsigned int timeout_ms)
1474 TRACE("%p, %d", event_set, timeout_ms);
1477 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1480 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1481 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1482 RETURN_FAIL("WaitForMultipleObjects() failed");
1486 struct timeval start, delta, now, end = {0, 0};
1487 const struct timeval max_delta = {
1488 (INT_MAX / 1000), (INT_MAX % 1000) * 1000
1490 int started = 0, timeout_overflow = 0;
1491 int result, timeout_remaining_ms;
1492 struct pollfd *pollfds;
1495 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1496 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1498 for (i = 0; i < event_set->count; i++) {
1499 pollfds[i].fd = ((int *)event_set->handles)[i];
1500 pollfds[i].events = 0;
1501 pollfds[i].revents = 0;
1502 if (event_set->masks[i] & SP_EVENT_RX_READY)
1503 pollfds[i].events |= POLLIN;
1504 if (event_set->masks[i] & SP_EVENT_TX_READY)
1505 pollfds[i].events |= POLLOUT;
1506 if (event_set->masks[i] & SP_EVENT_ERROR)
1507 pollfds[i].events |= POLLERR;
1511 /* Get time at start of operation. */
1513 /* Define duration of timeout. */
1514 delta.tv_sec = timeout_ms / 1000;
1515 delta.tv_usec = (timeout_ms % 1000) * 1000;
1516 /* Calculate time at which we should give up. */
1517 timeradd(&start, &delta, &end);
1520 /* Loop until an event occurs. */
1523 * Check timeout only if we have run poll() at least once,
1524 * to avoid any issues if a short timeout is reached before
1525 * poll() is even run.
1528 timeout_remaining_ms = -1;
1529 } else if (!started) {
1530 timeout_overflow = (timeout_ms > INT_MAX);
1531 timeout_remaining_ms = timeout_overflow ? INT_MAX : timeout_ms;
1534 if (timercmp(&now, &end, >)) {
1535 DEBUG("Wait timed out");
1538 timersub(&end, &now, &delta);
1539 if ((timeout_overflow = timercmp(&delta, &max_delta, >)))
1541 timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1544 result = poll(pollfds, event_set->count, timeout_remaining_ms);
1548 if (errno == EINTR) {
1549 DEBUG("poll() call was interrupted, repeating");
1553 RETURN_FAIL("poll() failed");
1555 } else if (result == 0) {
1556 DEBUG("poll() timed out");
1557 if (!timeout_overflow)
1560 DEBUG("poll() completed");
1570 #ifdef USE_TERMIOS_SPEED
1571 static enum sp_return get_baudrate(int fd, int *baudrate)
1575 TRACE("%d, %p", fd, baudrate);
1577 DEBUG("Getting baud rate");
1579 if (!(data = malloc(get_termios_size())))
1580 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1582 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1584 RETURN_FAIL("Getting termios failed");
1587 *baudrate = get_termios_speed(data);
1594 static enum sp_return set_baudrate(int fd, int baudrate)
1598 TRACE("%d, %d", fd, baudrate);
1600 DEBUG("Getting baud rate");
1602 if (!(data = malloc(get_termios_size())))
1603 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1605 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1607 RETURN_FAIL("Getting termios failed");
1610 DEBUG("Setting baud rate");
1612 set_termios_speed(data, baudrate);
1614 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1616 RETURN_FAIL("Setting termios failed");
1623 #endif /* USE_TERMIOS_SPEED */
1626 static enum sp_return get_flow(int fd, struct port_data *data)
1630 TRACE("%d, %p", fd, data);
1632 DEBUG("Getting advanced flow control");
1634 if (!(termx = malloc(get_termiox_size())))
1635 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1637 if (ioctl(fd, TCGETX, termx) < 0) {
1639 RETURN_FAIL("Getting termiox failed");
1642 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1643 &data->dtr_flow, &data->dsr_flow);
1650 static enum sp_return set_flow(int fd, struct port_data *data)
1654 TRACE("%d, %p", fd, data);
1656 DEBUG("Getting advanced flow control");
1658 if (!(termx = malloc(get_termiox_size())))
1659 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1661 if (ioctl(fd, TCGETX, termx) < 0) {
1663 RETURN_FAIL("Getting termiox failed");
1666 DEBUG("Setting advanced flow control");
1668 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1669 data->dtr_flow, data->dsr_flow);
1671 if (ioctl(fd, TCSETX, termx) < 0) {
1673 RETURN_FAIL("Setting termiox failed");
1680 #endif /* USE_TERMIOX */
1682 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1683 struct sp_port_config *config)
1687 TRACE("%p, %p, %p", port, data, config);
1689 DEBUG_FMT("Getting configuration for port %s", port->name);
1692 if (!GetCommState(port->hdl, &data->dcb))
1693 RETURN_FAIL("GetCommState() failed");
1695 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1696 if (data->dcb.BaudRate == std_baudrates[i].index) {
1697 config->baudrate = std_baudrates[i].value;
1702 if (i == NUM_STD_BAUDRATES)
1703 /* BaudRate field can be either an index or a custom baud rate. */
1704 config->baudrate = data->dcb.BaudRate;
1706 config->bits = data->dcb.ByteSize;
1708 if (data->dcb.fParity)
1709 switch (data->dcb.Parity) {
1711 config->parity = SP_PARITY_NONE;
1714 config->parity = SP_PARITY_ODD;
1717 config->parity = SP_PARITY_EVEN;
1720 config->parity = SP_PARITY_MARK;
1723 config->parity = SP_PARITY_SPACE;
1726 config->parity = -1;
1729 config->parity = SP_PARITY_NONE;
1731 switch (data->dcb.StopBits) {
1733 config->stopbits = 1;
1736 config->stopbits = 2;
1739 config->stopbits = -1;
1742 switch (data->dcb.fRtsControl) {
1743 case RTS_CONTROL_DISABLE:
1744 config->rts = SP_RTS_OFF;
1746 case RTS_CONTROL_ENABLE:
1747 config->rts = SP_RTS_ON;
1749 case RTS_CONTROL_HANDSHAKE:
1750 config->rts = SP_RTS_FLOW_CONTROL;
1756 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1758 switch (data->dcb.fDtrControl) {
1759 case DTR_CONTROL_DISABLE:
1760 config->dtr = SP_DTR_OFF;
1762 case DTR_CONTROL_ENABLE:
1763 config->dtr = SP_DTR_ON;
1765 case DTR_CONTROL_HANDSHAKE:
1766 config->dtr = SP_DTR_FLOW_CONTROL;
1772 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1774 if (data->dcb.fInX) {
1775 if (data->dcb.fOutX)
1776 config->xon_xoff = SP_XONXOFF_INOUT;
1778 config->xon_xoff = SP_XONXOFF_IN;
1780 if (data->dcb.fOutX)
1781 config->xon_xoff = SP_XONXOFF_OUT;
1783 config->xon_xoff = SP_XONXOFF_DISABLED;
1788 if (tcgetattr(port->fd, &data->term) < 0)
1789 RETURN_FAIL("tcgetattr() failed");
1791 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1792 RETURN_FAIL("TIOCMGET ioctl failed");
1795 int ret = get_flow(port->fd, data);
1797 if (ret == SP_ERR_FAIL && errno == EINVAL)
1798 data->termiox_supported = 0;
1800 RETURN_CODEVAL(ret);
1802 data->termiox_supported = 1;
1804 data->termiox_supported = 0;
1807 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1808 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1809 config->baudrate = std_baudrates[i].value;
1814 if (i == NUM_STD_BAUDRATES) {
1816 config->baudrate = (int)data->term.c_ispeed;
1817 #elif defined(USE_TERMIOS_SPEED)
1818 TRY(get_baudrate(port->fd, &config->baudrate));
1820 config->baudrate = -1;
1824 switch (data->term.c_cflag & CSIZE) {
1841 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1842 config->parity = SP_PARITY_NONE;
1843 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1844 config->parity = -1;
1846 else if (data->term.c_cflag & CMSPAR)
1847 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1850 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1852 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1854 if (data->term.c_cflag & CRTSCTS) {
1855 config->rts = SP_RTS_FLOW_CONTROL;
1856 config->cts = SP_CTS_FLOW_CONTROL;
1858 if (data->termiox_supported && data->rts_flow)
1859 config->rts = SP_RTS_FLOW_CONTROL;
1861 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1863 config->cts = (data->termiox_supported && data->cts_flow) ?
1864 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1867 if (data->termiox_supported && data->dtr_flow)
1868 config->dtr = SP_DTR_FLOW_CONTROL;
1870 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1872 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1873 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1875 if (data->term.c_iflag & IXOFF) {
1876 if (data->term.c_iflag & IXON)
1877 config->xon_xoff = SP_XONXOFF_INOUT;
1879 config->xon_xoff = SP_XONXOFF_IN;
1881 if (data->term.c_iflag & IXON)
1882 config->xon_xoff = SP_XONXOFF_OUT;
1884 config->xon_xoff = SP_XONXOFF_DISABLED;
1891 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1892 const struct sp_port_config *config)
1896 BAUD_TYPE baud_nonstd;
1900 #ifdef USE_TERMIOS_SPEED
1901 int baud_nonstd = 0;
1904 TRACE("%p, %p, %p", port, data, config);
1906 DEBUG_FMT("Setting configuration for port %s", port->name);
1910 TRY(await_write_completion(port));
1912 if (config->baudrate >= 0) {
1913 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1914 if (config->baudrate == std_baudrates[i].value) {
1915 data->dcb.BaudRate = std_baudrates[i].index;
1920 if (i == NUM_STD_BAUDRATES)
1921 data->dcb.BaudRate = config->baudrate;
1923 /* Allocate write buffer for 50ms of data at baud rate. */
1924 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1925 port->write_buf = realloc(port->write_buf,
1926 port->write_buf_size);
1928 if (!port->write_buf)
1929 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1932 if (config->bits >= 0)
1933 data->dcb.ByteSize = config->bits;
1935 if (config->parity >= 0) {
1936 switch (config->parity) {
1937 case SP_PARITY_NONE:
1938 data->dcb.Parity = NOPARITY;
1941 data->dcb.Parity = ODDPARITY;
1943 case SP_PARITY_EVEN:
1944 data->dcb.Parity = EVENPARITY;
1946 case SP_PARITY_MARK:
1947 data->dcb.Parity = MARKPARITY;
1949 case SP_PARITY_SPACE:
1950 data->dcb.Parity = SPACEPARITY;
1953 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1957 if (config->stopbits >= 0) {
1958 switch (config->stopbits) {
1959 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1961 data->dcb.StopBits = ONESTOPBIT;
1964 data->dcb.StopBits = TWOSTOPBITS;
1967 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1971 if (config->rts >= 0) {
1972 switch (config->rts) {
1974 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1977 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1979 case SP_RTS_FLOW_CONTROL:
1980 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1983 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1987 if (config->cts >= 0) {
1988 switch (config->cts) {
1990 data->dcb.fOutxCtsFlow = FALSE;
1992 case SP_CTS_FLOW_CONTROL:
1993 data->dcb.fOutxCtsFlow = TRUE;
1996 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
2000 if (config->dtr >= 0) {
2001 switch (config->dtr) {
2003 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
2006 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
2008 case SP_DTR_FLOW_CONTROL:
2009 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
2012 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
2016 if (config->dsr >= 0) {
2017 switch (config->dsr) {
2019 data->dcb.fOutxDsrFlow = FALSE;
2021 case SP_DSR_FLOW_CONTROL:
2022 data->dcb.fOutxDsrFlow = TRUE;
2025 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2029 if (config->xon_xoff >= 0) {
2030 switch (config->xon_xoff) {
2031 case SP_XONXOFF_DISABLED:
2032 data->dcb.fInX = FALSE;
2033 data->dcb.fOutX = FALSE;
2036 data->dcb.fInX = TRUE;
2037 data->dcb.fOutX = FALSE;
2039 case SP_XONXOFF_OUT:
2040 data->dcb.fInX = FALSE;
2041 data->dcb.fOutX = TRUE;
2043 case SP_XONXOFF_INOUT:
2044 data->dcb.fInX = TRUE;
2045 data->dcb.fOutX = TRUE;
2048 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2052 if (!SetCommState(port->hdl, &data->dcb))
2053 RETURN_FAIL("SetCommState() failed");
2059 if (config->baudrate >= 0) {
2060 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2061 if (config->baudrate == std_baudrates[i].value) {
2062 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2063 RETURN_FAIL("cfsetospeed() failed");
2065 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2066 RETURN_FAIL("cfsetispeed() failed");
2071 /* Non-standard baud rate */
2072 if (i == NUM_STD_BAUDRATES) {
2074 /* Set "dummy" baud rate. */
2075 if (cfsetspeed(&data->term, B9600) < 0)
2076 RETURN_FAIL("cfsetspeed() failed");
2077 baud_nonstd = config->baudrate;
2078 #elif defined(USE_TERMIOS_SPEED)
2081 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2086 if (config->bits >= 0) {
2087 data->term.c_cflag &= ~CSIZE;
2088 switch (config->bits) {
2090 data->term.c_cflag |= CS8;
2093 data->term.c_cflag |= CS7;
2096 data->term.c_cflag |= CS6;
2099 data->term.c_cflag |= CS5;
2102 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2106 if (config->parity >= 0) {
2107 data->term.c_iflag &= ~IGNPAR;
2108 data->term.c_cflag &= ~(PARENB | PARODD);
2110 data->term.c_cflag &= ~CMSPAR;
2112 switch (config->parity) {
2113 case SP_PARITY_NONE:
2114 data->term.c_iflag |= IGNPAR;
2116 case SP_PARITY_EVEN:
2117 data->term.c_cflag |= PARENB;
2120 data->term.c_cflag |= PARENB | PARODD;
2123 case SP_PARITY_MARK:
2124 data->term.c_cflag |= PARENB | PARODD;
2125 data->term.c_cflag |= CMSPAR;
2127 case SP_PARITY_SPACE:
2128 data->term.c_cflag |= PARENB;
2129 data->term.c_cflag |= CMSPAR;
2132 case SP_PARITY_MARK:
2133 case SP_PARITY_SPACE:
2134 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2137 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2141 if (config->stopbits >= 0) {
2142 data->term.c_cflag &= ~CSTOPB;
2143 switch (config->stopbits) {
2145 data->term.c_cflag &= ~CSTOPB;
2148 data->term.c_cflag |= CSTOPB;
2151 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2155 if (config->rts >= 0 || config->cts >= 0) {
2156 if (data->termiox_supported) {
2157 data->rts_flow = data->cts_flow = 0;
2158 switch (config->rts) {
2161 controlbits = TIOCM_RTS;
2162 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2163 RETURN_FAIL("Setting RTS signal level failed");
2165 case SP_RTS_FLOW_CONTROL:
2171 if (config->cts == SP_CTS_FLOW_CONTROL)
2174 if (data->rts_flow && data->cts_flow)
2175 data->term.c_iflag |= CRTSCTS;
2177 data->term.c_iflag &= ~CRTSCTS;
2179 /* Asymmetric use of RTS/CTS not supported. */
2180 if (data->term.c_iflag & CRTSCTS) {
2181 /* Flow control can only be disabled for both RTS & CTS together. */
2182 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2183 if (config->cts != SP_CTS_IGNORE)
2184 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2186 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2187 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2188 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2191 /* Flow control can only be enabled for both RTS & CTS together. */
2192 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2193 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2194 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2197 if (config->rts >= 0) {
2198 if (config->rts == SP_RTS_FLOW_CONTROL) {
2199 data->term.c_iflag |= CRTSCTS;
2201 controlbits = TIOCM_RTS;
2202 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2204 RETURN_FAIL("Setting RTS signal level failed");
2210 if (config->dtr >= 0 || config->dsr >= 0) {
2211 if (data->termiox_supported) {
2212 data->dtr_flow = data->dsr_flow = 0;
2213 switch (config->dtr) {
2216 controlbits = TIOCM_DTR;
2217 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2218 RETURN_FAIL("Setting DTR signal level failed");
2220 case SP_DTR_FLOW_CONTROL:
2226 if (config->dsr == SP_DSR_FLOW_CONTROL)
2229 /* DTR/DSR flow control not supported. */
2230 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2231 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2233 if (config->dtr >= 0) {
2234 controlbits = TIOCM_DTR;
2235 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2237 RETURN_FAIL("Setting DTR signal level failed");
2242 if (config->xon_xoff >= 0) {
2243 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2244 switch (config->xon_xoff) {
2245 case SP_XONXOFF_DISABLED:
2248 data->term.c_iflag |= IXOFF;
2250 case SP_XONXOFF_OUT:
2251 data->term.c_iflag |= IXON | IXANY;
2253 case SP_XONXOFF_INOUT:
2254 data->term.c_iflag |= IXON | IXOFF | IXANY;
2257 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2261 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2262 RETURN_FAIL("tcsetattr() failed");
2265 if (baud_nonstd != B0) {
2266 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2267 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2269 * Set baud rates in data->term to correct, but incompatible
2270 * with tcsetattr() value, same as delivered by tcgetattr().
2272 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2273 RETURN_FAIL("cfsetspeed() failed");
2275 #elif defined(__linux__)
2276 #ifdef USE_TERMIOS_SPEED
2278 TRY(set_baudrate(port->fd, config->baudrate));
2281 if (data->termiox_supported)
2282 TRY(set_flow(port->fd, data));
2286 #endif /* !_WIN32 */
2291 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2293 struct sp_port_config *config;
2295 TRACE("%p", config_ptr);
2298 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2302 if (!(config = malloc(sizeof(struct sp_port_config))))
2303 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2305 config->baudrate = -1;
2307 config->parity = -1;
2308 config->stopbits = -1;
2314 *config_ptr = config;
2319 SP_API void sp_free_config(struct sp_port_config *config)
2321 TRACE("%p", config);
2324 DEBUG("Null config");
2331 SP_API enum sp_return sp_get_config(struct sp_port *port,
2332 struct sp_port_config *config)
2334 struct port_data data;
2336 TRACE("%p, %p", port, config);
2341 RETURN_ERROR(SP_ERR_ARG, "Null config");
2343 TRY(get_config(port, &data, config));
2348 SP_API enum sp_return sp_set_config(struct sp_port *port,
2349 const struct sp_port_config *config)
2351 struct port_data data;
2352 struct sp_port_config prev_config;
2354 TRACE("%p, %p", port, config);
2359 RETURN_ERROR(SP_ERR_ARG, "Null config");
2361 TRY(get_config(port, &data, &prev_config));
2362 TRY(set_config(port, &data, config));
2367 #define CREATE_ACCESSORS(x, type) \
2368 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2369 struct port_data data; \
2370 struct sp_port_config config; \
2371 TRACE("%p, %d", port, x); \
2372 CHECK_OPEN_PORT(); \
2373 TRY(get_config(port, &data, &config)); \
2375 TRY(set_config(port, &data, &config)); \
2378 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2380 TRACE("%p, %p", config, x); \
2382 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2384 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2388 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2390 TRACE("%p, %d", config, x); \
2392 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2397 CREATE_ACCESSORS(baudrate, int)
2398 CREATE_ACCESSORS(bits, int)
2399 CREATE_ACCESSORS(parity, enum sp_parity)
2400 CREATE_ACCESSORS(stopbits, int)
2401 CREATE_ACCESSORS(rts, enum sp_rts)
2402 CREATE_ACCESSORS(cts, enum sp_cts)
2403 CREATE_ACCESSORS(dtr, enum sp_dtr)
2404 CREATE_ACCESSORS(dsr, enum sp_dsr)
2405 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2407 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2408 enum sp_flowcontrol flowcontrol)
2411 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2413 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2414 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2416 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2417 config->xon_xoff = SP_XONXOFF_INOUT;
2419 config->xon_xoff = SP_XONXOFF_DISABLED;
2421 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2422 config->rts = SP_RTS_FLOW_CONTROL;
2423 config->cts = SP_CTS_FLOW_CONTROL;
2425 if (config->rts == SP_RTS_FLOW_CONTROL)
2426 config->rts = SP_RTS_ON;
2427 config->cts = SP_CTS_IGNORE;
2430 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2431 config->dtr = SP_DTR_FLOW_CONTROL;
2432 config->dsr = SP_DSR_FLOW_CONTROL;
2434 if (config->dtr == SP_DTR_FLOW_CONTROL)
2435 config->dtr = SP_DTR_ON;
2436 config->dsr = SP_DSR_IGNORE;
2442 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2443 enum sp_flowcontrol flowcontrol)
2445 struct port_data data;
2446 struct sp_port_config config;
2448 TRACE("%p, %d", port, flowcontrol);
2452 TRY(get_config(port, &data, &config));
2454 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2456 TRY(set_config(port, &data, &config));
2461 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2462 enum sp_signal *signals)
2464 TRACE("%p, %p", port, signals);
2469 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2471 DEBUG_FMT("Getting control signals for port %s", port->name);
2476 if (GetCommModemStatus(port->hdl, &bits) == 0)
2477 RETURN_FAIL("GetCommModemStatus() failed");
2478 if (bits & MS_CTS_ON)
2479 *signals |= SP_SIG_CTS;
2480 if (bits & MS_DSR_ON)
2481 *signals |= SP_SIG_DSR;
2482 if (bits & MS_RLSD_ON)
2483 *signals |= SP_SIG_DCD;
2484 if (bits & MS_RING_ON)
2485 *signals |= SP_SIG_RI;
2488 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2489 RETURN_FAIL("TIOCMGET ioctl failed");
2490 if (bits & TIOCM_CTS)
2491 *signals |= SP_SIG_CTS;
2492 if (bits & TIOCM_DSR)
2493 *signals |= SP_SIG_DSR;
2494 if (bits & TIOCM_CAR)
2495 *signals |= SP_SIG_DCD;
2496 if (bits & TIOCM_RNG)
2497 *signals |= SP_SIG_RI;
2502 SP_API enum sp_return sp_start_break(struct sp_port *port)
2508 if (SetCommBreak(port->hdl) == 0)
2509 RETURN_FAIL("SetCommBreak() failed");
2511 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2512 RETURN_FAIL("TIOCSBRK ioctl failed");
2518 SP_API enum sp_return sp_end_break(struct sp_port *port)
2524 if (ClearCommBreak(port->hdl) == 0)
2525 RETURN_FAIL("ClearCommBreak() failed");
2527 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2528 RETURN_FAIL("TIOCCBRK ioctl failed");
2534 SP_API int sp_last_error_code(void)
2538 RETURN_INT(GetLastError());
2544 SP_API char *sp_last_error_message(void)
2550 DWORD error = GetLastError();
2552 DWORD length = FormatMessage(
2553 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2554 FORMAT_MESSAGE_FROM_SYSTEM |
2555 FORMAT_MESSAGE_IGNORE_INSERTS,
2558 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2562 if (length >= 2 && message[length - 2] == '\r')
2563 message[length - 2] = '\0';
2565 RETURN_STRING(message);
2567 RETURN_STRING(strerror(errno));
2571 SP_API void sp_free_error_message(char *message)
2573 TRACE("%s", message);
2584 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2586 TRACE("%p", handler);
2588 sp_debug_handler = handler;
2593 SP_API void sp_default_debug_handler(const char *format, ...)
2596 va_start(args, format);
2597 if (getenv("LIBSERIALPORT_DEBUG")) {
2598 fputs("sp: ", stderr);
2599 vfprintf(stderr, format, args);
2604 SP_API int sp_get_major_package_version(void)
2606 return SP_PACKAGE_VERSION_MAJOR;
2609 SP_API int sp_get_minor_package_version(void)
2611 return SP_PACKAGE_VERSION_MINOR;
2614 SP_API int sp_get_micro_package_version(void)
2616 return SP_PACKAGE_VERSION_MICRO;
2619 SP_API const char *sp_get_package_version_string(void)
2621 return SP_PACKAGE_VERSION_STRING;
2624 SP_API int sp_get_current_lib_version(void)
2626 return SP_LIB_VERSION_CURRENT;
2629 SP_API int sp_get_revision_lib_version(void)
2631 return SP_LIB_VERSION_REVISION;
2634 SP_API int sp_get_age_lib_version(void)
2636 return SP_LIB_VERSION_AGE;
2639 SP_API const char *sp_get_lib_version_string(void)
2641 return SP_LIB_VERSION_STRING;