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);
58 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
61 #ifndef NO_PORT_METADATA
66 TRACE("%s, %p", portname, port_ptr);
69 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
74 RETURN_ERROR(SP_ERR_ARG, "Null port name");
76 DEBUG_FMT("Building structure for port %s", portname);
78 #if !defined(_WIN32) && defined(HAVE_REALPATH)
80 * get_port_details() below tries to be too smart and figure out
81 * some transport properties from the port name which breaks with
82 * symlinks. Therefore we canonicalize the portname first.
84 char pathbuf[PATH_MAX + 1];
85 char *res = realpath(portname, pathbuf);
87 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
92 if (!(port = malloc(sizeof(struct sp_port))))
93 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
95 len = strlen(portname) + 1;
97 if (!(port->name = malloc(len))) {
99 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
102 memcpy(port->name, portname, len);
105 port->usb_path = NULL;
106 port->hdl = INVALID_HANDLE_VALUE;
107 port->write_buf = NULL;
108 port->write_buf_size = 0;
113 port->description = NULL;
114 port->transport = SP_TRANSPORT_NATIVE;
116 port->usb_address = -1;
119 port->usb_manufacturer = NULL;
120 port->usb_product = NULL;
121 port->usb_serial = NULL;
122 port->bluetooth_address = NULL;
124 #ifndef NO_PORT_METADATA
125 if ((ret = get_port_details(port)) != SP_OK) {
136 SP_API char *sp_get_port_name(const struct sp_port *port)
143 RETURN_STRING(port->name);
146 SP_API char *sp_get_port_description(const struct sp_port *port)
150 if (!port || !port->description)
153 RETURN_STRING(port->description);
156 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
161 RETURN_ERROR(SP_ERR_ARG, "Null port");
163 RETURN_INT(port->transport);
166 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
167 int *usb_bus,int *usb_address)
172 RETURN_ERROR(SP_ERR_ARG, "Null port");
173 if (port->transport != SP_TRANSPORT_USB)
174 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
175 if (port->usb_bus < 0 || port->usb_address < 0)
176 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
179 *usb_bus = port->usb_bus;
181 *usb_address = port->usb_address;
186 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
187 int *usb_vid, int *usb_pid)
192 RETURN_ERROR(SP_ERR_ARG, "Null port");
193 if (port->transport != SP_TRANSPORT_USB)
194 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
195 if (port->usb_vid < 0 || port->usb_pid < 0)
196 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
199 *usb_vid = port->usb_vid;
201 *usb_pid = port->usb_pid;
206 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
210 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
213 RETURN_STRING(port->usb_manufacturer);
216 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
220 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
223 RETURN_STRING(port->usb_product);
226 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
230 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
233 RETURN_STRING(port->usb_serial);
236 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
240 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
241 || !port->bluetooth_address)
244 RETURN_STRING(port->bluetooth_address);
247 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
250 TRACE("%p, %p", port, result_ptr);
253 RETURN_ERROR(SP_ERR_ARG, "Null port");
255 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
258 HANDLE *handle_ptr = result_ptr;
259 *handle_ptr = port->hdl;
261 int *fd_ptr = result_ptr;
268 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
269 struct sp_port **copy_ptr)
271 TRACE("%p, %p", port, copy_ptr);
274 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
279 RETURN_ERROR(SP_ERR_ARG, "Null port");
282 RETURN_ERROR(SP_ERR_ARG, "Null port name");
284 DEBUG("Copying port structure");
286 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
289 SP_API void sp_free_port(struct sp_port *port)
298 DEBUG("Freeing port structure");
302 if (port->description)
303 free(port->description);
304 if (port->usb_manufacturer)
305 free(port->usb_manufacturer);
306 if (port->usb_product)
307 free(port->usb_product);
308 if (port->usb_serial)
309 free(port->usb_serial);
310 if (port->bluetooth_address)
311 free(port->bluetooth_address);
314 free(port->usb_path);
316 free(port->write_buf);
324 SP_PRIV struct sp_port **list_append(struct sp_port **list,
325 const char *portname)
330 for (count = 0; list[count]; count++)
332 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
335 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
337 list[count + 1] = NULL;
341 sp_free_port_list(list);
345 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
347 #ifndef NO_ENUMERATION
348 struct sp_port **list;
352 TRACE("%p", list_ptr);
355 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
359 #ifdef NO_ENUMERATION
360 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
362 DEBUG("Enumerating ports");
364 if (!(list = malloc(sizeof(struct sp_port *))))
365 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
369 ret = list_ports(&list);
374 sp_free_port_list(list);
382 SP_API void sp_free_port_list(struct sp_port **list)
393 DEBUG("Freeing port list");
395 for (i = 0; list[i]; i++)
396 sp_free_port(list[i]);
402 #define CHECK_PORT() do { \
404 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
406 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
409 #define CHECK_PORT_HANDLE() do { \
410 if (port->hdl == INVALID_HANDLE_VALUE) \
411 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
414 #define CHECK_PORT_HANDLE() do { \
416 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
419 #define CHECK_OPEN_PORT() do { \
421 CHECK_PORT_HANDLE(); \
425 /** To be called after port receive buffer is emptied. */
426 static enum sp_return restart_wait(struct sp_port *port)
430 if (port->wait_running) {
431 /* Check status of running wait operation. */
432 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
433 &wait_result, FALSE)) {
434 DEBUG("Previous wait completed");
435 port->wait_running = FALSE;
436 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
437 DEBUG("Previous wait still running");
440 RETURN_FAIL("GetOverlappedResult() failed");
444 if (!port->wait_running) {
445 /* Start new wait operation. */
446 if (WaitCommEvent(port->hdl, &port->events,
448 DEBUG("New wait returned, events already pending");
449 } else if (GetLastError() == ERROR_IO_PENDING) {
450 DEBUG("New wait running in background");
451 port->wait_running = TRUE;
453 RETURN_FAIL("WaitCommEvent() failed");
461 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
463 struct port_data data;
464 struct sp_port_config config;
467 TRACE("%p, 0x%x", port, flags);
471 if (flags > SP_MODE_READ_WRITE)
472 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
474 DEBUG_FMT("Opening port %s", port->name);
477 DWORD desired_access = 0, flags_and_attributes = 0, errors;
478 char *escaped_port_name;
481 /* Prefix port name with '\\.\' to work with ports above COM9. */
482 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
483 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
484 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
486 /* Map 'flags' to the OS-specific settings. */
487 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
488 if (flags & SP_MODE_READ)
489 desired_access |= GENERIC_READ;
490 if (flags & SP_MODE_WRITE)
491 desired_access |= GENERIC_WRITE;
493 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
494 OPEN_EXISTING, flags_and_attributes, 0);
496 free(escaped_port_name);
498 if (port->hdl == INVALID_HANDLE_VALUE)
499 RETURN_FAIL("Port CreateFile() failed");
501 /* All timeouts initially disabled. */
502 port->timeouts.ReadIntervalTimeout = 0;
503 port->timeouts.ReadTotalTimeoutMultiplier = 0;
504 port->timeouts.ReadTotalTimeoutConstant = 0;
505 port->timeouts.WriteTotalTimeoutMultiplier = 0;
506 port->timeouts.WriteTotalTimeoutConstant = 0;
508 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
510 RETURN_FAIL("SetCommTimeouts() failed");
513 /* Prepare OVERLAPPED structures. */
514 #define INIT_OVERLAPPED(ovl) do { \
515 memset(&port->ovl, 0, sizeof(port->ovl)); \
516 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
517 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
518 == INVALID_HANDLE_VALUE) { \
520 RETURN_FAIL(#ovl "CreateEvent() failed"); \
524 INIT_OVERLAPPED(read_ovl);
525 INIT_OVERLAPPED(write_ovl);
526 INIT_OVERLAPPED(wait_ovl);
528 /* Set event mask for RX and error events. */
529 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
531 RETURN_FAIL("SetCommMask() failed");
534 port->writing = FALSE;
535 port->wait_running = FALSE;
537 ret = restart_wait(port);
544 int flags_local = O_NONBLOCK | O_NOCTTY;
546 /* Map 'flags' to the OS-specific settings. */
547 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
548 flags_local |= O_RDWR;
549 else if (flags & SP_MODE_READ)
550 flags_local |= O_RDONLY;
551 else if (flags & SP_MODE_WRITE)
552 flags_local |= O_WRONLY;
554 if ((port->fd = open(port->name, flags_local)) < 0)
555 RETURN_FAIL("open() failed");
558 ret = get_config(port, &data, &config);
565 /* Set sane port settings. */
567 data.dcb.fBinary = TRUE;
568 data.dcb.fDsrSensitivity = FALSE;
569 data.dcb.fErrorChar = FALSE;
570 data.dcb.fNull = FALSE;
571 data.dcb.fAbortOnError = FALSE;
573 /* Turn off all fancy termios tricks, give us a raw channel. */
574 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
576 data.term.c_iflag &= ~IUCLC;
578 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
580 data.term.c_oflag &= ~OLCUC;
583 data.term.c_oflag &= ~NLDLY;
586 data.term.c_oflag &= ~CRDLY;
589 data.term.c_oflag &= ~TABDLY;
592 data.term.c_oflag &= ~BSDLY;
595 data.term.c_oflag &= ~VTDLY;
598 data.term.c_oflag &= ~FFDLY;
601 data.term.c_oflag &= ~OFILL;
603 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
604 data.term.c_cc[VMIN] = 0;
605 data.term.c_cc[VTIME] = 0;
607 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
608 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
612 if (ClearCommError(port->hdl, &errors, &status) == 0)
613 RETURN_FAIL("ClearCommError() failed");
616 ret = set_config(port, &data, &config);
626 SP_API enum sp_return sp_close(struct sp_port *port)
632 DEBUG_FMT("Closing port %s", port->name);
635 /* Returns non-zero upon success, 0 upon failure. */
636 if (CloseHandle(port->hdl) == 0)
637 RETURN_FAIL("Port CloseHandle() failed");
638 port->hdl = INVALID_HANDLE_VALUE;
640 /* Close event handles for overlapped structures. */
641 #define CLOSE_OVERLAPPED(ovl) do { \
642 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
643 CloseHandle(port->ovl.hEvent) == 0) \
644 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
646 CLOSE_OVERLAPPED(read_ovl);
647 CLOSE_OVERLAPPED(write_ovl);
648 CLOSE_OVERLAPPED(wait_ovl);
650 if (port->write_buf) {
651 free(port->write_buf);
652 port->write_buf = NULL;
655 /* Returns 0 upon success, -1 upon failure. */
656 if (close(port->fd) == -1)
657 RETURN_FAIL("close() failed");
664 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
666 TRACE("%p, 0x%x", port, buffers);
670 if (buffers > SP_BUF_BOTH)
671 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
673 const char *buffer_names[] = {"no", "input", "output", "both"};
675 DEBUG_FMT("Flushing %s buffers on port %s",
676 buffer_names[buffers], port->name);
680 if (buffers & SP_BUF_INPUT)
681 flags |= PURGE_RXCLEAR;
682 if (buffers & SP_BUF_OUTPUT)
683 flags |= PURGE_TXCLEAR;
685 /* Returns non-zero upon success, 0 upon failure. */
686 if (PurgeComm(port->hdl, flags) == 0)
687 RETURN_FAIL("PurgeComm() failed");
689 if (buffers & SP_BUF_INPUT)
690 TRY(restart_wait(port));
693 if (buffers == SP_BUF_BOTH)
695 else if (buffers == SP_BUF_INPUT)
697 else if (buffers == SP_BUF_OUTPUT)
700 /* Returns 0 upon success, -1 upon failure. */
701 if (tcflush(port->fd, flags) < 0)
702 RETURN_FAIL("tcflush() failed");
707 SP_API enum sp_return sp_drain(struct sp_port *port)
713 DEBUG_FMT("Draining port %s", port->name);
716 /* Returns non-zero upon success, 0 upon failure. */
717 if (FlushFileBuffers(port->hdl) == 0)
718 RETURN_FAIL("FlushFileBuffers() failed");
725 result = ioctl(port->fd, TCSBRK, &arg);
727 result = tcdrain(port->fd);
730 if (errno == EINTR) {
731 DEBUG("tcdrain() was interrupted");
734 RETURN_FAIL("tcdrain() failed");
744 static enum sp_return await_write_completion(struct sp_port *port)
750 /* Wait for previous non-blocking write to complete, if any. */
752 DEBUG("Waiting for previous write to complete");
753 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
756 RETURN_FAIL("Previous write failed to complete");
757 DEBUG("Previous write completed");
764 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
765 size_t count, unsigned int timeout_ms)
767 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
772 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
775 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
776 count, port->name, timeout_ms);
778 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
785 DWORD bytes_written = 0;
787 TRY(await_write_completion(port));
790 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
791 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
792 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
793 RETURN_FAIL("SetCommTimeouts() failed");
797 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
798 DEBUG("Write completed immediately");
800 } else if (GetLastError() == ERROR_IO_PENDING) {
801 DEBUG("Waiting for write to complete");
802 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
803 if (GetLastError() == ERROR_SEM_TIMEOUT) {
804 DEBUG("Write timed out");
807 RETURN_FAIL("GetOverlappedResult() failed");
810 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
811 RETURN_INT(bytes_written);
813 RETURN_FAIL("WriteFile() failed");
816 size_t bytes_written = 0;
817 unsigned char *ptr = (unsigned char *) buf;
818 struct timeval start, delta, now, end = {0, 0};
824 /* Get time at start of operation. */
825 gettimeofday(&start, NULL);
826 /* Define duration of timeout. */
827 delta.tv_sec = timeout_ms / 1000;
828 delta.tv_usec = (timeout_ms % 1000) * 1000;
829 /* Calculate time at which we should give up. */
830 timeradd(&start, &delta, &end);
834 FD_SET(port->fd, &fds);
836 /* Loop until we have written the requested number of bytes. */
837 while (bytes_written < count) {
839 * Check timeout only if we have run select() at least once,
840 * to avoid any issues if a short timeout is reached before
841 * select() is even run.
843 if (timeout_ms && started) {
844 gettimeofday(&now, NULL);
845 if (timercmp(&now, &end, >))
846 /* Timeout has expired. */
848 timersub(&end, &now, &delta);
850 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
853 if (errno == EINTR) {
854 DEBUG("select() call was interrupted, repeating");
857 RETURN_FAIL("select() failed");
859 } else if (result == 0) {
860 /* Timeout has expired. */
865 result = write(port->fd, ptr, count - bytes_written);
869 /* This shouldn't happen because we did a select() first, but handle anyway. */
872 /* This is an actual failure. */
873 RETURN_FAIL("write() failed");
876 bytes_written += result;
880 if (bytes_written < count)
881 DEBUG("Write timed out");
883 RETURN_INT(bytes_written);
887 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
888 const void *buf, size_t count)
890 TRACE("%p, %p, %d", port, buf, count);
895 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
897 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
905 /* Check whether previous write is complete. */
907 if (HasOverlappedIoCompleted(&port->write_ovl)) {
908 DEBUG("Previous write completed");
911 DEBUG("Previous write not complete");
912 /* Can't take a new write until the previous one finishes. */
918 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
919 port->timeouts.WriteTotalTimeoutConstant = 0;
920 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
921 RETURN_FAIL("SetCommTimeouts() failed");
924 /* Copy data to our write buffer. */
925 buf_bytes = min(port->write_buf_size, count);
926 memcpy(port->write_buf, buf, buf_bytes);
928 /* Start asynchronous write. */
929 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
930 if (GetLastError() == ERROR_IO_PENDING) {
931 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
932 DEBUG("Asynchronous write completed immediately");
934 DEBUG("Asynchronous write running");
936 /* Actual failure of some kind. */
937 RETURN_FAIL("WriteFile() failed");
941 DEBUG("All bytes written immediately");
943 RETURN_INT(buf_bytes);
945 /* Returns the number of bytes written, or -1 upon failure. */
946 ssize_t written = write(port->fd, buf, count);
950 // Buffer is full, no bytes written.
953 RETURN_FAIL("write() failed");
961 /* Restart wait operation if buffer was emptied. */
962 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
970 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
971 RETURN_FAIL("ClearCommError() failed");
973 if (comstat.cbInQue == 0)
974 TRY(restart_wait(port));
980 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
981 size_t count, unsigned int timeout_ms)
983 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
988 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
991 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
992 count, port->name, timeout_ms);
994 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1001 DWORD bytes_read = 0;
1004 if (port->timeouts.ReadIntervalTimeout != 0 ||
1005 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1006 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1007 port->timeouts.ReadIntervalTimeout = 0;
1008 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1009 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1010 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1011 RETURN_FAIL("SetCommTimeouts() failed");
1015 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1016 DEBUG("Read completed immediately");
1018 } else if (GetLastError() == ERROR_IO_PENDING) {
1019 DEBUG("Waiting for read to complete");
1020 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1021 RETURN_FAIL("GetOverlappedResult() failed");
1022 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1024 RETURN_FAIL("ReadFile() failed");
1027 TRY(restart_wait_if_needed(port, bytes_read));
1029 RETURN_INT(bytes_read);
1032 size_t bytes_read = 0;
1033 unsigned char *ptr = (unsigned char *)buf;
1034 struct timeval start, delta, now, end = {0, 0};
1040 /* Get time at start of operation. */
1041 gettimeofday(&start, NULL);
1042 /* Define duration of timeout. */
1043 delta.tv_sec = timeout_ms / 1000;
1044 delta.tv_usec = (timeout_ms % 1000) * 1000;
1045 /* Calculate time at which we should give up. */
1046 timeradd(&start, &delta, &end);
1050 FD_SET(port->fd, &fds);
1052 /* Loop until we have the requested number of bytes. */
1053 while (bytes_read < count) {
1055 * Check timeout only if we have run select() at least once,
1056 * to avoid any issues if a short timeout is reached before
1057 * select() is even run.
1059 if (timeout_ms && started) {
1060 gettimeofday(&now, NULL);
1061 if (timercmp(&now, &end, >))
1062 /* Timeout has expired. */
1064 timersub(&end, &now, &delta);
1066 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1069 if (errno == EINTR) {
1070 DEBUG("select() call was interrupted, repeating");
1073 RETURN_FAIL("select() failed");
1075 } else if (result == 0) {
1076 /* Timeout has expired. */
1081 result = read(port->fd, ptr, count - bytes_read);
1084 if (errno == EAGAIN)
1086 * This shouldn't happen because we did a
1087 * select() first, but handle anyway.
1091 /* This is an actual failure. */
1092 RETURN_FAIL("read() failed");
1095 bytes_read += result;
1099 if (bytes_read < count)
1100 DEBUG("Read timed out");
1102 RETURN_INT(bytes_read);
1106 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1107 size_t count, unsigned int timeout_ms)
1109 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1114 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1117 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1120 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1121 count, port->name, timeout_ms);
1123 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1127 DWORD bytes_read = 0;
1129 /* If timeout_ms == 0, set maximum timeout. */
1130 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1133 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1134 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1135 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1136 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1137 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1138 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1139 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1140 RETURN_FAIL("SetCommTimeouts() failed");
1143 /* Loop until we have at least one byte, or timeout is reached. */
1144 while (bytes_read == 0) {
1146 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1147 DEBUG("Read completed immediately");
1148 } else if (GetLastError() == ERROR_IO_PENDING) {
1149 DEBUG("Waiting for read to complete");
1150 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1151 RETURN_FAIL("GetOverlappedResult() failed");
1152 if (bytes_read > 0) {
1153 DEBUG("Read completed");
1154 } else if (timeout_ms > 0) {
1155 DEBUG("Read timed out");
1158 DEBUG("Restarting read");
1161 RETURN_FAIL("ReadFile() failed");
1165 TRY(restart_wait_if_needed(port, bytes_read));
1167 RETURN_INT(bytes_read);
1170 size_t bytes_read = 0;
1171 struct timeval start, delta, now, end = {0, 0};
1177 /* Get time at start of operation. */
1178 gettimeofday(&start, NULL);
1179 /* Define duration of timeout. */
1180 delta.tv_sec = timeout_ms / 1000;
1181 delta.tv_usec = (timeout_ms % 1000) * 1000;
1182 /* Calculate time at which we should give up. */
1183 timeradd(&start, &delta, &end);
1187 FD_SET(port->fd, &fds);
1189 /* Loop until we have at least one byte, or timeout is reached. */
1190 while (bytes_read == 0) {
1192 * Check timeout only if we have run select() at least once,
1193 * to avoid any issues if a short timeout is reached before
1194 * select() is even run.
1196 if (timeout_ms && started) {
1197 gettimeofday(&now, NULL);
1198 if (timercmp(&now, &end, >))
1199 /* Timeout has expired. */
1201 timersub(&end, &now, &delta);
1203 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1206 if (errno == EINTR) {
1207 DEBUG("select() call was interrupted, repeating");
1210 RETURN_FAIL("select() failed");
1212 } else if (result == 0) {
1213 /* Timeout has expired. */
1218 result = read(port->fd, buf, count);
1221 if (errno == EAGAIN)
1222 /* This shouldn't happen because we did a select() first, but handle anyway. */
1225 /* This is an actual failure. */
1226 RETURN_FAIL("read() failed");
1229 bytes_read = result;
1232 if (bytes_read == 0)
1233 DEBUG("Read timed out");
1235 RETURN_INT(bytes_read);
1239 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1242 TRACE("%p, %p, %d", port, buf, count);
1247 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1249 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1255 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1256 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1257 port->timeouts.ReadTotalTimeoutConstant != 0) {
1258 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1259 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1260 port->timeouts.ReadTotalTimeoutConstant = 0;
1261 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1262 RETURN_FAIL("SetCommTimeouts() failed");
1266 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1267 if (GetLastError() != ERROR_IO_PENDING)
1268 RETURN_FAIL("ReadFile() failed");
1270 /* Get number of bytes read. */
1271 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1272 RETURN_FAIL("GetOverlappedResult() failed");
1274 TRY(restart_wait_if_needed(port, bytes_read));
1276 RETURN_INT(bytes_read);
1280 /* Returns the number of bytes read, or -1 upon failure. */
1281 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1282 if (errno == EAGAIN)
1283 /* No bytes available. */
1286 /* This is an actual failure. */
1287 RETURN_FAIL("read() failed");
1289 RETURN_INT(bytes_read);
1293 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1299 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1305 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1306 RETURN_FAIL("ClearCommError() failed");
1307 RETURN_INT(comstat.cbInQue);
1310 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1311 RETURN_FAIL("TIOCINQ ioctl failed");
1312 RETURN_INT(bytes_waiting);
1316 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1322 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1328 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1329 RETURN_FAIL("ClearCommError() failed");
1330 RETURN_INT(comstat.cbOutQue);
1333 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1334 RETURN_FAIL("TIOCOUTQ ioctl failed");
1335 RETURN_INT(bytes_waiting);
1339 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1341 struct sp_event_set *result;
1343 TRACE("%p", result_ptr);
1346 RETURN_ERROR(SP_ERR_ARG, "Null result");
1350 if (!(result = malloc(sizeof(struct sp_event_set))))
1351 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1353 memset(result, 0, sizeof(struct sp_event_set));
1355 *result_ptr = result;
1360 static enum sp_return add_handle(struct sp_event_set *event_set,
1361 event_handle handle, enum sp_event mask)
1364 enum sp_event *new_masks;
1366 TRACE("%p, %d, %d", event_set, handle, mask);
1368 if (!(new_handles = realloc(event_set->handles,
1369 sizeof(event_handle) * (event_set->count + 1))))
1370 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1372 event_set->handles = new_handles;
1374 if (!(new_masks = realloc(event_set->masks,
1375 sizeof(enum sp_event) * (event_set->count + 1))))
1376 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1378 event_set->masks = new_masks;
1380 ((event_handle *) event_set->handles)[event_set->count] = handle;
1381 event_set->masks[event_set->count] = mask;
1388 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1389 const struct sp_port *port, enum sp_event mask)
1391 TRACE("%p, %p, %d", event_set, port, mask);
1394 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1397 RETURN_ERROR(SP_ERR_ARG, "Null port");
1399 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1400 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1406 enum sp_event handle_mask;
1407 if ((handle_mask = mask & SP_EVENT_TX_READY))
1408 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1409 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1410 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1412 TRY(add_handle(event_set, port->fd, mask));
1418 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1420 TRACE("%p", event_set);
1423 DEBUG("Null event set");
1427 DEBUG("Freeing event set");
1429 if (event_set->handles)
1430 free(event_set->handles);
1431 if (event_set->masks)
1432 free(event_set->masks);
1439 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1440 unsigned int timeout_ms)
1442 TRACE("%p, %d", event_set, timeout_ms);
1445 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1448 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1449 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1450 RETURN_FAIL("WaitForMultipleObjects() failed");
1454 struct timeval start, delta, now, end = {0, 0};
1455 const struct timeval max_delta = {
1456 (INT_MAX / 1000), (INT_MAX % 1000) * 1000
1458 int started = 0, timeout_overflow = 0;
1459 int result, timeout_remaining_ms;
1460 struct pollfd *pollfds;
1463 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1464 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1466 for (i = 0; i < event_set->count; i++) {
1467 pollfds[i].fd = ((int *)event_set->handles)[i];
1468 pollfds[i].events = 0;
1469 pollfds[i].revents = 0;
1470 if (event_set->masks[i] & SP_EVENT_RX_READY)
1471 pollfds[i].events |= POLLIN;
1472 if (event_set->masks[i] & SP_EVENT_TX_READY)
1473 pollfds[i].events |= POLLOUT;
1474 if (event_set->masks[i] & SP_EVENT_ERROR)
1475 pollfds[i].events |= POLLERR;
1479 /* Get time at start of operation. */
1480 gettimeofday(&start, NULL);
1481 /* Define duration of timeout. */
1482 delta.tv_sec = timeout_ms / 1000;
1483 delta.tv_usec = (timeout_ms % 1000) * 1000;
1484 /* Calculate time at which we should give up. */
1485 timeradd(&start, &delta, &end);
1488 /* Loop until an event occurs. */
1491 * Check timeout only if we have run poll() at least once,
1492 * to avoid any issues if a short timeout is reached before
1493 * poll() is even run.
1496 timeout_remaining_ms = -1;
1497 } else if (!started) {
1498 timeout_overflow = (timeout_ms > INT_MAX);
1499 timeout_remaining_ms = timeout_overflow ? INT_MAX : timeout_ms;
1501 gettimeofday(&now, NULL);
1502 if (timercmp(&now, &end, >)) {
1503 DEBUG("Wait timed out");
1506 timersub(&end, &now, &delta);
1507 if ((timeout_overflow = timercmp(&delta, &max_delta, >)))
1509 timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1512 result = poll(pollfds, event_set->count, timeout_remaining_ms);
1516 if (errno == EINTR) {
1517 DEBUG("poll() call was interrupted, repeating");
1521 RETURN_FAIL("poll() failed");
1523 } else if (result == 0) {
1524 DEBUG("poll() timed out");
1525 if (!timeout_overflow)
1528 DEBUG("poll() completed");
1538 #ifdef USE_TERMIOS_SPEED
1539 static enum sp_return get_baudrate(int fd, int *baudrate)
1543 TRACE("%d, %p", fd, baudrate);
1545 DEBUG("Getting baud rate");
1547 if (!(data = malloc(get_termios_size())))
1548 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1550 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1552 RETURN_FAIL("Getting termios failed");
1555 *baudrate = get_termios_speed(data);
1562 static enum sp_return set_baudrate(int fd, int baudrate)
1566 TRACE("%d, %d", fd, baudrate);
1568 DEBUG("Getting baud rate");
1570 if (!(data = malloc(get_termios_size())))
1571 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1573 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1575 RETURN_FAIL("Getting termios failed");
1578 DEBUG("Setting baud rate");
1580 set_termios_speed(data, baudrate);
1582 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1584 RETURN_FAIL("Setting termios failed");
1591 #endif /* USE_TERMIOS_SPEED */
1594 static enum sp_return get_flow(int fd, struct port_data *data)
1598 TRACE("%d, %p", fd, data);
1600 DEBUG("Getting advanced flow control");
1602 if (!(termx = malloc(get_termiox_size())))
1603 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1605 if (ioctl(fd, TCGETX, termx) < 0) {
1607 RETURN_FAIL("Getting termiox failed");
1610 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1611 &data->dtr_flow, &data->dsr_flow);
1618 static enum sp_return set_flow(int fd, struct port_data *data)
1622 TRACE("%d, %p", fd, data);
1624 DEBUG("Getting advanced flow control");
1626 if (!(termx = malloc(get_termiox_size())))
1627 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1629 if (ioctl(fd, TCGETX, termx) < 0) {
1631 RETURN_FAIL("Getting termiox failed");
1634 DEBUG("Setting advanced flow control");
1636 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1637 data->dtr_flow, data->dsr_flow);
1639 if (ioctl(fd, TCSETX, termx) < 0) {
1641 RETURN_FAIL("Setting termiox failed");
1648 #endif /* USE_TERMIOX */
1650 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1651 struct sp_port_config *config)
1655 TRACE("%p, %p, %p", port, data, config);
1657 DEBUG_FMT("Getting configuration for port %s", port->name);
1660 if (!GetCommState(port->hdl, &data->dcb))
1661 RETURN_FAIL("GetCommState() failed");
1663 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1664 if (data->dcb.BaudRate == std_baudrates[i].index) {
1665 config->baudrate = std_baudrates[i].value;
1670 if (i == NUM_STD_BAUDRATES)
1671 /* BaudRate field can be either an index or a custom baud rate. */
1672 config->baudrate = data->dcb.BaudRate;
1674 config->bits = data->dcb.ByteSize;
1676 if (data->dcb.fParity)
1677 switch (data->dcb.Parity) {
1679 config->parity = SP_PARITY_NONE;
1682 config->parity = SP_PARITY_ODD;
1685 config->parity = SP_PARITY_EVEN;
1688 config->parity = SP_PARITY_MARK;
1691 config->parity = SP_PARITY_SPACE;
1694 config->parity = -1;
1697 config->parity = SP_PARITY_NONE;
1699 switch (data->dcb.StopBits) {
1701 config->stopbits = 1;
1704 config->stopbits = 2;
1707 config->stopbits = -1;
1710 switch (data->dcb.fRtsControl) {
1711 case RTS_CONTROL_DISABLE:
1712 config->rts = SP_RTS_OFF;
1714 case RTS_CONTROL_ENABLE:
1715 config->rts = SP_RTS_ON;
1717 case RTS_CONTROL_HANDSHAKE:
1718 config->rts = SP_RTS_FLOW_CONTROL;
1724 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1726 switch (data->dcb.fDtrControl) {
1727 case DTR_CONTROL_DISABLE:
1728 config->dtr = SP_DTR_OFF;
1730 case DTR_CONTROL_ENABLE:
1731 config->dtr = SP_DTR_ON;
1733 case DTR_CONTROL_HANDSHAKE:
1734 config->dtr = SP_DTR_FLOW_CONTROL;
1740 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1742 if (data->dcb.fInX) {
1743 if (data->dcb.fOutX)
1744 config->xon_xoff = SP_XONXOFF_INOUT;
1746 config->xon_xoff = SP_XONXOFF_IN;
1748 if (data->dcb.fOutX)
1749 config->xon_xoff = SP_XONXOFF_OUT;
1751 config->xon_xoff = SP_XONXOFF_DISABLED;
1756 if (tcgetattr(port->fd, &data->term) < 0)
1757 RETURN_FAIL("tcgetattr() failed");
1759 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1760 RETURN_FAIL("TIOCMGET ioctl failed");
1763 int ret = get_flow(port->fd, data);
1765 if (ret == SP_ERR_FAIL && errno == EINVAL)
1766 data->termiox_supported = 0;
1768 RETURN_CODEVAL(ret);
1770 data->termiox_supported = 1;
1772 data->termiox_supported = 0;
1775 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1776 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1777 config->baudrate = std_baudrates[i].value;
1782 if (i == NUM_STD_BAUDRATES) {
1784 config->baudrate = (int)data->term.c_ispeed;
1785 #elif defined(USE_TERMIOS_SPEED)
1786 TRY(get_baudrate(port->fd, &config->baudrate));
1788 config->baudrate = -1;
1792 switch (data->term.c_cflag & CSIZE) {
1809 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1810 config->parity = SP_PARITY_NONE;
1811 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1812 config->parity = -1;
1814 else if (data->term.c_cflag & CMSPAR)
1815 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1818 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1820 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1822 if (data->term.c_cflag & CRTSCTS) {
1823 config->rts = SP_RTS_FLOW_CONTROL;
1824 config->cts = SP_CTS_FLOW_CONTROL;
1826 if (data->termiox_supported && data->rts_flow)
1827 config->rts = SP_RTS_FLOW_CONTROL;
1829 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1831 config->cts = (data->termiox_supported && data->cts_flow) ?
1832 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1835 if (data->termiox_supported && data->dtr_flow)
1836 config->dtr = SP_DTR_FLOW_CONTROL;
1838 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1840 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1841 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1843 if (data->term.c_iflag & IXOFF) {
1844 if (data->term.c_iflag & IXON)
1845 config->xon_xoff = SP_XONXOFF_INOUT;
1847 config->xon_xoff = SP_XONXOFF_IN;
1849 if (data->term.c_iflag & IXON)
1850 config->xon_xoff = SP_XONXOFF_OUT;
1852 config->xon_xoff = SP_XONXOFF_DISABLED;
1859 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1860 const struct sp_port_config *config)
1864 BAUD_TYPE baud_nonstd;
1868 #ifdef USE_TERMIOS_SPEED
1869 int baud_nonstd = 0;
1872 TRACE("%p, %p, %p", port, data, config);
1874 DEBUG_FMT("Setting configuration for port %s", port->name);
1878 TRY(await_write_completion(port));
1880 if (config->baudrate >= 0) {
1881 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1882 if (config->baudrate == std_baudrates[i].value) {
1883 data->dcb.BaudRate = std_baudrates[i].index;
1888 if (i == NUM_STD_BAUDRATES)
1889 data->dcb.BaudRate = config->baudrate;
1891 /* Allocate write buffer for 50ms of data at baud rate. */
1892 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1893 port->write_buf = realloc(port->write_buf,
1894 port->write_buf_size);
1896 if (!port->write_buf)
1897 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1900 if (config->bits >= 0)
1901 data->dcb.ByteSize = config->bits;
1903 if (config->parity >= 0) {
1904 switch (config->parity) {
1905 case SP_PARITY_NONE:
1906 data->dcb.Parity = NOPARITY;
1909 data->dcb.Parity = ODDPARITY;
1911 case SP_PARITY_EVEN:
1912 data->dcb.Parity = EVENPARITY;
1914 case SP_PARITY_MARK:
1915 data->dcb.Parity = MARKPARITY;
1917 case SP_PARITY_SPACE:
1918 data->dcb.Parity = SPACEPARITY;
1921 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1925 if (config->stopbits >= 0) {
1926 switch (config->stopbits) {
1927 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1929 data->dcb.StopBits = ONESTOPBIT;
1932 data->dcb.StopBits = TWOSTOPBITS;
1935 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1939 if (config->rts >= 0) {
1940 switch (config->rts) {
1942 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1945 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1947 case SP_RTS_FLOW_CONTROL:
1948 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1951 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1955 if (config->cts >= 0) {
1956 switch (config->cts) {
1958 data->dcb.fOutxCtsFlow = FALSE;
1960 case SP_CTS_FLOW_CONTROL:
1961 data->dcb.fOutxCtsFlow = TRUE;
1964 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1968 if (config->dtr >= 0) {
1969 switch (config->dtr) {
1971 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1974 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1976 case SP_DTR_FLOW_CONTROL:
1977 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1980 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1984 if (config->dsr >= 0) {
1985 switch (config->dsr) {
1987 data->dcb.fOutxDsrFlow = FALSE;
1989 case SP_DSR_FLOW_CONTROL:
1990 data->dcb.fOutxDsrFlow = TRUE;
1993 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1997 if (config->xon_xoff >= 0) {
1998 switch (config->xon_xoff) {
1999 case SP_XONXOFF_DISABLED:
2000 data->dcb.fInX = FALSE;
2001 data->dcb.fOutX = FALSE;
2004 data->dcb.fInX = TRUE;
2005 data->dcb.fOutX = FALSE;
2007 case SP_XONXOFF_OUT:
2008 data->dcb.fInX = FALSE;
2009 data->dcb.fOutX = TRUE;
2011 case SP_XONXOFF_INOUT:
2012 data->dcb.fInX = TRUE;
2013 data->dcb.fOutX = TRUE;
2016 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2020 if (!SetCommState(port->hdl, &data->dcb))
2021 RETURN_FAIL("SetCommState() failed");
2027 if (config->baudrate >= 0) {
2028 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2029 if (config->baudrate == std_baudrates[i].value) {
2030 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2031 RETURN_FAIL("cfsetospeed() failed");
2033 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2034 RETURN_FAIL("cfsetispeed() failed");
2039 /* Non-standard baud rate */
2040 if (i == NUM_STD_BAUDRATES) {
2042 /* Set "dummy" baud rate. */
2043 if (cfsetspeed(&data->term, B9600) < 0)
2044 RETURN_FAIL("cfsetspeed() failed");
2045 baud_nonstd = config->baudrate;
2046 #elif defined(USE_TERMIOS_SPEED)
2049 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2054 if (config->bits >= 0) {
2055 data->term.c_cflag &= ~CSIZE;
2056 switch (config->bits) {
2058 data->term.c_cflag |= CS8;
2061 data->term.c_cflag |= CS7;
2064 data->term.c_cflag |= CS6;
2067 data->term.c_cflag |= CS5;
2070 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2074 if (config->parity >= 0) {
2075 data->term.c_iflag &= ~IGNPAR;
2076 data->term.c_cflag &= ~(PARENB | PARODD);
2078 data->term.c_cflag &= ~CMSPAR;
2080 switch (config->parity) {
2081 case SP_PARITY_NONE:
2082 data->term.c_iflag |= IGNPAR;
2084 case SP_PARITY_EVEN:
2085 data->term.c_cflag |= PARENB;
2088 data->term.c_cflag |= PARENB | PARODD;
2091 case SP_PARITY_MARK:
2092 data->term.c_cflag |= PARENB | PARODD;
2093 data->term.c_cflag |= CMSPAR;
2095 case SP_PARITY_SPACE:
2096 data->term.c_cflag |= PARENB;
2097 data->term.c_cflag |= CMSPAR;
2100 case SP_PARITY_MARK:
2101 case SP_PARITY_SPACE:
2102 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2105 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2109 if (config->stopbits >= 0) {
2110 data->term.c_cflag &= ~CSTOPB;
2111 switch (config->stopbits) {
2113 data->term.c_cflag &= ~CSTOPB;
2116 data->term.c_cflag |= CSTOPB;
2119 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2123 if (config->rts >= 0 || config->cts >= 0) {
2124 if (data->termiox_supported) {
2125 data->rts_flow = data->cts_flow = 0;
2126 switch (config->rts) {
2129 controlbits = TIOCM_RTS;
2130 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2131 RETURN_FAIL("Setting RTS signal level failed");
2133 case SP_RTS_FLOW_CONTROL:
2139 if (config->cts == SP_CTS_FLOW_CONTROL)
2142 if (data->rts_flow && data->cts_flow)
2143 data->term.c_iflag |= CRTSCTS;
2145 data->term.c_iflag &= ~CRTSCTS;
2147 /* Asymmetric use of RTS/CTS not supported. */
2148 if (data->term.c_iflag & CRTSCTS) {
2149 /* Flow control can only be disabled for both RTS & CTS together. */
2150 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2151 if (config->cts != SP_CTS_IGNORE)
2152 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2154 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2155 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2156 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2159 /* Flow control can only be enabled for both RTS & CTS together. */
2160 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2161 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2162 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2165 if (config->rts >= 0) {
2166 if (config->rts == SP_RTS_FLOW_CONTROL) {
2167 data->term.c_iflag |= CRTSCTS;
2169 controlbits = TIOCM_RTS;
2170 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2172 RETURN_FAIL("Setting RTS signal level failed");
2178 if (config->dtr >= 0 || config->dsr >= 0) {
2179 if (data->termiox_supported) {
2180 data->dtr_flow = data->dsr_flow = 0;
2181 switch (config->dtr) {
2184 controlbits = TIOCM_DTR;
2185 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2186 RETURN_FAIL("Setting DTR signal level failed");
2188 case SP_DTR_FLOW_CONTROL:
2194 if (config->dsr == SP_DSR_FLOW_CONTROL)
2197 /* DTR/DSR flow control not supported. */
2198 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2199 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2201 if (config->dtr >= 0) {
2202 controlbits = TIOCM_DTR;
2203 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2205 RETURN_FAIL("Setting DTR signal level failed");
2210 if (config->xon_xoff >= 0) {
2211 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2212 switch (config->xon_xoff) {
2213 case SP_XONXOFF_DISABLED:
2216 data->term.c_iflag |= IXOFF;
2218 case SP_XONXOFF_OUT:
2219 data->term.c_iflag |= IXON | IXANY;
2221 case SP_XONXOFF_INOUT:
2222 data->term.c_iflag |= IXON | IXOFF | IXANY;
2225 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2229 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2230 RETURN_FAIL("tcsetattr() failed");
2233 if (baud_nonstd != B0) {
2234 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2235 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2237 * Set baud rates in data->term to correct, but incompatible
2238 * with tcsetattr() value, same as delivered by tcgetattr().
2240 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2241 RETURN_FAIL("cfsetspeed() failed");
2243 #elif defined(__linux__)
2244 #ifdef USE_TERMIOS_SPEED
2246 TRY(set_baudrate(port->fd, config->baudrate));
2249 if (data->termiox_supported)
2250 TRY(set_flow(port->fd, data));
2254 #endif /* !_WIN32 */
2259 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2261 struct sp_port_config *config;
2263 TRACE("%p", config_ptr);
2266 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2270 if (!(config = malloc(sizeof(struct sp_port_config))))
2271 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2273 config->baudrate = -1;
2275 config->parity = -1;
2276 config->stopbits = -1;
2282 *config_ptr = config;
2287 SP_API void sp_free_config(struct sp_port_config *config)
2289 TRACE("%p", config);
2292 DEBUG("Null config");
2299 SP_API enum sp_return sp_get_config(struct sp_port *port,
2300 struct sp_port_config *config)
2302 struct port_data data;
2304 TRACE("%p, %p", port, config);
2309 RETURN_ERROR(SP_ERR_ARG, "Null config");
2311 TRY(get_config(port, &data, config));
2316 SP_API enum sp_return sp_set_config(struct sp_port *port,
2317 const struct sp_port_config *config)
2319 struct port_data data;
2320 struct sp_port_config prev_config;
2322 TRACE("%p, %p", port, config);
2327 RETURN_ERROR(SP_ERR_ARG, "Null config");
2329 TRY(get_config(port, &data, &prev_config));
2330 TRY(set_config(port, &data, config));
2335 #define CREATE_ACCESSORS(x, type) \
2336 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2337 struct port_data data; \
2338 struct sp_port_config config; \
2339 TRACE("%p, %d", port, x); \
2340 CHECK_OPEN_PORT(); \
2341 TRY(get_config(port, &data, &config)); \
2343 TRY(set_config(port, &data, &config)); \
2346 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2348 TRACE("%p, %p", config, x); \
2350 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2352 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2356 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2358 TRACE("%p, %d", config, x); \
2360 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2365 CREATE_ACCESSORS(baudrate, int)
2366 CREATE_ACCESSORS(bits, int)
2367 CREATE_ACCESSORS(parity, enum sp_parity)
2368 CREATE_ACCESSORS(stopbits, int)
2369 CREATE_ACCESSORS(rts, enum sp_rts)
2370 CREATE_ACCESSORS(cts, enum sp_cts)
2371 CREATE_ACCESSORS(dtr, enum sp_dtr)
2372 CREATE_ACCESSORS(dsr, enum sp_dsr)
2373 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2375 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2376 enum sp_flowcontrol flowcontrol)
2379 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2381 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2382 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2384 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2385 config->xon_xoff = SP_XONXOFF_INOUT;
2387 config->xon_xoff = SP_XONXOFF_DISABLED;
2389 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2390 config->rts = SP_RTS_FLOW_CONTROL;
2391 config->cts = SP_CTS_FLOW_CONTROL;
2393 if (config->rts == SP_RTS_FLOW_CONTROL)
2394 config->rts = SP_RTS_ON;
2395 config->cts = SP_CTS_IGNORE;
2398 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2399 config->dtr = SP_DTR_FLOW_CONTROL;
2400 config->dsr = SP_DSR_FLOW_CONTROL;
2402 if (config->dtr == SP_DTR_FLOW_CONTROL)
2403 config->dtr = SP_DTR_ON;
2404 config->dsr = SP_DSR_IGNORE;
2410 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2411 enum sp_flowcontrol flowcontrol)
2413 struct port_data data;
2414 struct sp_port_config config;
2416 TRACE("%p, %d", port, flowcontrol);
2420 TRY(get_config(port, &data, &config));
2422 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2424 TRY(set_config(port, &data, &config));
2429 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2430 enum sp_signal *signals)
2432 TRACE("%p, %p", port, signals);
2437 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2439 DEBUG_FMT("Getting control signals for port %s", port->name);
2444 if (GetCommModemStatus(port->hdl, &bits) == 0)
2445 RETURN_FAIL("GetCommModemStatus() failed");
2446 if (bits & MS_CTS_ON)
2447 *signals |= SP_SIG_CTS;
2448 if (bits & MS_DSR_ON)
2449 *signals |= SP_SIG_DSR;
2450 if (bits & MS_RLSD_ON)
2451 *signals |= SP_SIG_DCD;
2452 if (bits & MS_RING_ON)
2453 *signals |= SP_SIG_RI;
2456 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2457 RETURN_FAIL("TIOCMGET ioctl failed");
2458 if (bits & TIOCM_CTS)
2459 *signals |= SP_SIG_CTS;
2460 if (bits & TIOCM_DSR)
2461 *signals |= SP_SIG_DSR;
2462 if (bits & TIOCM_CAR)
2463 *signals |= SP_SIG_DCD;
2464 if (bits & TIOCM_RNG)
2465 *signals |= SP_SIG_RI;
2470 SP_API enum sp_return sp_start_break(struct sp_port *port)
2476 if (SetCommBreak(port->hdl) == 0)
2477 RETURN_FAIL("SetCommBreak() failed");
2479 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2480 RETURN_FAIL("TIOCSBRK ioctl failed");
2486 SP_API enum sp_return sp_end_break(struct sp_port *port)
2492 if (ClearCommBreak(port->hdl) == 0)
2493 RETURN_FAIL("ClearCommBreak() failed");
2495 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2496 RETURN_FAIL("TIOCCBRK ioctl failed");
2502 SP_API int sp_last_error_code(void)
2506 RETURN_INT(GetLastError());
2512 SP_API char *sp_last_error_message(void)
2518 DWORD error = GetLastError();
2520 DWORD length = FormatMessage(
2521 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2522 FORMAT_MESSAGE_FROM_SYSTEM |
2523 FORMAT_MESSAGE_IGNORE_INSERTS,
2526 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2530 if (length >= 2 && message[length - 2] == '\r')
2531 message[length - 2] = '\0';
2533 RETURN_STRING(message);
2535 RETURN_STRING(strerror(errno));
2539 SP_API void sp_free_error_message(char *message)
2541 TRACE("%s", message);
2552 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2554 TRACE("%p", handler);
2556 sp_debug_handler = handler;
2561 SP_API void sp_default_debug_handler(const char *format, ...)
2564 va_start(args, format);
2565 if (getenv("LIBSERIALPORT_DEBUG")) {
2566 fputs("sp: ", stderr);
2567 vfprintf(stderr, format, args);
2572 SP_API int sp_get_major_package_version(void)
2574 return SP_PACKAGE_VERSION_MAJOR;
2577 SP_API int sp_get_minor_package_version(void)
2579 return SP_PACKAGE_VERSION_MINOR;
2582 SP_API int sp_get_micro_package_version(void)
2584 return SP_PACKAGE_VERSION_MICRO;
2587 SP_API const char *sp_get_package_version_string(void)
2589 return SP_PACKAGE_VERSION_STRING;
2592 SP_API int sp_get_current_lib_version(void)
2594 return SP_LIB_VERSION_CURRENT;
2597 SP_API int sp_get_revision_lib_version(void)
2599 return SP_LIB_VERSION_REVISION;
2602 SP_API int sp_get_age_lib_version(void)
2604 return SP_LIB_VERSION_AGE;
2607 SP_API const char *sp_get_lib_version_string(void)
2609 return SP_LIB_VERSION_STRING;