2 * This file is part of the libserialport project.
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2013 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/>.
24 #include "libserialport.h"
25 #include "libserialport_internal.h"
27 static const struct std_baudrate std_baudrates[] = {
30 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
31 * have documented CBR_* macros.
33 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
34 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
35 BAUD(115200), BAUD(128000), BAUD(256000),
37 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
38 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
39 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
41 #if !defined(__APPLE__) && !defined(__OpenBSD__)
47 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
49 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
51 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
52 struct sp_port_config *config);
54 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
55 const struct sp_port_config *config);
57 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
60 #ifndef NO_PORT_METADATA
65 TRACE("%s, %p", portname, port_ptr);
68 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
73 RETURN_ERROR(SP_ERR_ARG, "Null port name");
75 DEBUG_FMT("Building structure for port %s", portname);
77 if (!(port = malloc(sizeof(struct sp_port))))
78 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
80 len = strlen(portname) + 1;
82 if (!(port->name = malloc(len))) {
84 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
87 memcpy(port->name, portname, len);
90 port->usb_path = NULL;
91 port->hdl = INVALID_HANDLE_VALUE;
96 port->description = NULL;
97 port->transport = SP_TRANSPORT_NATIVE;
99 port->usb_address = -1;
102 port->usb_manufacturer = NULL;
103 port->usb_product = NULL;
104 port->usb_serial = NULL;
105 port->bluetooth_address = NULL;
107 #ifndef NO_PORT_METADATA
108 if ((ret = get_port_details(port)) != SP_OK) {
119 SP_API char *sp_get_port_name(const struct sp_port *port)
126 RETURN_STRING(port->name);
129 SP_API char *sp_get_port_description(struct sp_port *port)
133 if (!port || !port->description)
136 RETURN_STRING(port->description);
139 SP_API enum sp_transport sp_get_port_transport(struct sp_port *port)
144 RETURN_ERROR(SP_ERR_ARG, "Null port");
146 RETURN_INT(port->transport);
149 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
150 int *usb_bus,int *usb_address)
155 RETURN_ERROR(SP_ERR_ARG, "Null port");
156 if (port->transport != SP_TRANSPORT_USB)
157 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
158 if (port->usb_bus < 0 || port->usb_address < 0)
159 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
162 *usb_bus = port->usb_bus;
164 *usb_address = port->usb_address;
169 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
170 int *usb_vid, int *usb_pid)
175 RETURN_ERROR(SP_ERR_ARG, "Null port");
176 if (port->transport != SP_TRANSPORT_USB)
177 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
178 if (port->usb_vid < 0 || port->usb_pid < 0)
179 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
182 *usb_vid = port->usb_vid;
184 *usb_pid = port->usb_pid;
189 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
193 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
196 RETURN_STRING(port->usb_manufacturer);
199 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
203 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
206 RETURN_STRING(port->usb_product);
209 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
213 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
216 RETURN_STRING(port->usb_serial);
219 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
223 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
224 || !port->bluetooth_address)
227 RETURN_STRING(port->bluetooth_address);
230 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
233 TRACE("%p, %p", port, result_ptr);
236 RETURN_ERROR(SP_ERR_ARG, "Null port");
239 HANDLE *handle_ptr = result_ptr;
240 *handle_ptr = port->hdl;
242 int *fd_ptr = result_ptr;
249 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
250 struct sp_port **copy_ptr)
252 TRACE("%p, %p", port, copy_ptr);
255 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
260 RETURN_ERROR(SP_ERR_ARG, "Null port");
263 RETURN_ERROR(SP_ERR_ARG, "Null port name");
265 DEBUG("Copying port structure");
267 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
270 SP_API void sp_free_port(struct sp_port *port)
279 DEBUG("Freeing port structure");
283 if (port->description)
284 free(port->description);
285 if (port->usb_manufacturer)
286 free(port->usb_manufacturer);
287 if (port->usb_product)
288 free(port->usb_product);
289 if (port->usb_serial)
290 free(port->usb_serial);
291 if (port->bluetooth_address)
292 free(port->bluetooth_address);
295 free(port->usb_path);
303 SP_PRIV struct sp_port **list_append(struct sp_port **list,
304 const char *portname)
309 for (count = 0; list[count]; count++);
310 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
313 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
315 list[count + 1] = NULL;
319 sp_free_port_list(list);
323 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
325 struct sp_port **list;
328 TRACE("%p", list_ptr);
331 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
333 DEBUG("Enumerating ports");
335 if (!(list = malloc(sizeof(struct sp_port **))))
336 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
340 #ifdef NO_ENUMERATION
343 ret = list_ports(&list);
351 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
354 sp_free_port_list(list);
360 SP_API void sp_free_port_list(struct sp_port **list)
371 DEBUG("Freeing port list");
373 for (i = 0; list[i]; i++)
374 sp_free_port(list[i]);
380 #define CHECK_PORT() do { \
382 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
384 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
387 #define CHECK_PORT_HANDLE() do { \
388 if (port->hdl == INVALID_HANDLE_VALUE) \
389 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
392 #define CHECK_PORT_HANDLE() do { \
394 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
397 #define CHECK_OPEN_PORT() do { \
399 CHECK_PORT_HANDLE(); \
402 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
404 struct port_data data;
405 struct sp_port_config config;
408 TRACE("%p, 0x%x", port, flags);
412 if (flags > SP_MODE_READ_WRITE)
413 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
415 DEBUG_FMT("Opening port %s", port->name);
418 DWORD desired_access = 0, flags_and_attributes = 0, errors;
419 char *escaped_port_name;
422 /* Prefix port name with '\\.\' to work with ports above COM9. */
423 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
424 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
425 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
427 /* Map 'flags' to the OS-specific settings. */
428 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
429 if (flags & SP_MODE_READ)
430 desired_access |= GENERIC_READ;
431 if (flags & SP_MODE_WRITE)
432 desired_access |= GENERIC_WRITE;
434 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
435 OPEN_EXISTING, flags_and_attributes, 0);
437 free(escaped_port_name);
439 if (port->hdl == INVALID_HANDLE_VALUE)
440 RETURN_FAIL("Port CreateFile() failed");
442 /* All timeouts initially disabled. */
443 port->timeouts.ReadIntervalTimeout = 0;
444 port->timeouts.ReadTotalTimeoutMultiplier = 0;
445 port->timeouts.ReadTotalTimeoutConstant = 0;
446 port->timeouts.WriteTotalTimeoutMultiplier = 0;
447 port->timeouts.WriteTotalTimeoutConstant = 0;
449 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
451 RETURN_FAIL("SetCommTimeouts() failed");
454 /* Prepare OVERLAPPED structures. */
455 #define INIT_OVERLAPPED(ovl) do { \
456 memset(&port->ovl, 0, sizeof(port->ovl)); \
457 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
458 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
459 == INVALID_HANDLE_VALUE) { \
461 RETURN_FAIL(#ovl "CreateEvent() failed"); \
465 INIT_OVERLAPPED(read_ovl);
466 INIT_OVERLAPPED(write_ovl);
467 INIT_OVERLAPPED(wait_ovl);
469 /* Set event mask for RX and error events. */
470 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
472 RETURN_FAIL("SetCommMask() failed");
475 /* Start background operation for RX and error events. */
476 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
477 if (GetLastError() != ERROR_IO_PENDING) {
479 RETURN_FAIL("WaitCommEvent() failed");
483 port->writing = FALSE;
486 int flags_local = O_NONBLOCK | O_NOCTTY;
488 /* Map 'flags' to the OS-specific settings. */
489 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
490 flags_local |= O_RDWR;
491 else if (flags & SP_MODE_READ)
492 flags_local |= O_RDONLY;
493 else if (flags & SP_MODE_WRITE)
494 flags_local |= O_WRONLY;
496 if ((port->fd = open(port->name, flags_local)) < 0)
497 RETURN_FAIL("open() failed");
500 ret = get_config(port, &data, &config);
507 /* Set sane port settings. */
509 data.dcb.fBinary = TRUE;
510 data.dcb.fDsrSensitivity = FALSE;
511 data.dcb.fErrorChar = FALSE;
512 data.dcb.fNull = FALSE;
513 data.dcb.fAbortOnError = TRUE;
515 /* Turn off all fancy termios tricks, give us a raw channel. */
516 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
518 data.term.c_iflag &= ~IUCLC;
520 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
522 data.term.c_oflag &= ~OLCUC;
525 data.term.c_oflag &= ~NLDLY;
528 data.term.c_oflag &= ~CRDLY;
531 data.term.c_oflag &= ~TABDLY;
534 data.term.c_oflag &= ~BSDLY;
537 data.term.c_oflag &= ~VTDLY;
540 data.term.c_oflag &= ~FFDLY;
543 data.term.c_oflag &= ~OFILL;
545 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
546 data.term.c_cc[VMIN] = 0;
547 data.term.c_cc[VTIME] = 0;
549 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
550 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
554 if (ClearCommError(port->hdl, &errors, &status) == 0)
555 RETURN_FAIL("ClearCommError() failed");
558 ret = set_config(port, &data, &config);
568 SP_API enum sp_return sp_close(struct sp_port *port)
574 DEBUG_FMT("Closing port %s", port->name);
577 /* Returns non-zero upon success, 0 upon failure. */
578 if (CloseHandle(port->hdl) == 0)
579 RETURN_FAIL("Port CloseHandle() failed");
580 port->hdl = INVALID_HANDLE_VALUE;
582 /* Close event handles for overlapped structures. */
583 #define CLOSE_OVERLAPPED(ovl) do { \
584 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
585 CloseHandle(port->ovl.hEvent) == 0) \
586 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
588 CLOSE_OVERLAPPED(read_ovl);
589 CLOSE_OVERLAPPED(write_ovl);
590 CLOSE_OVERLAPPED(wait_ovl);
593 /* Returns 0 upon success, -1 upon failure. */
594 if (close(port->fd) == -1)
595 RETURN_FAIL("close() failed");
602 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
604 TRACE("%p, 0x%x", port, buffers);
608 if (buffers > SP_BUF_BOTH)
609 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
611 const char *buffer_names[] = {"no", "input", "output", "both"};
613 DEBUG_FMT("Flushing %s buffers on port %s",
614 buffer_names[buffers], port->name);
618 if (buffers & SP_BUF_INPUT)
619 flags |= PURGE_RXCLEAR;
620 if (buffers & SP_BUF_OUTPUT)
621 flags |= PURGE_TXCLEAR;
623 /* Returns non-zero upon success, 0 upon failure. */
624 if (PurgeComm(port->hdl, flags) == 0)
625 RETURN_FAIL("PurgeComm() failed");
628 if (buffers == SP_BUF_BOTH)
630 else if (buffers == SP_BUF_INPUT)
632 else if (buffers == SP_BUF_OUTPUT)
635 /* Returns 0 upon success, -1 upon failure. */
636 if (tcflush(port->fd, flags) < 0)
637 RETURN_FAIL("tcflush() failed");
642 SP_API enum sp_return sp_drain(struct sp_port *port)
648 DEBUG_FMT("Draining port %s", port->name);
651 /* Returns non-zero upon success, 0 upon failure. */
652 if (FlushFileBuffers(port->hdl) == 0)
653 RETURN_FAIL("FlushFileBuffers() failed");
660 result = ioctl(port->fd, TCSBRK, &arg);
662 result = tcdrain(port->fd);
665 if (errno == EINTR) {
666 DEBUG("tcdrain() was interrupted");
669 RETURN_FAIL("tcdrain() failed");
678 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
679 size_t count, unsigned int timeout)
681 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
686 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
689 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
690 count, port->name, timeout);
692 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
699 DWORD bytes_written = 0;
702 /* Wait for previous non-blocking write to complete, if any. */
704 DEBUG("Waiting for previous write to complete");
705 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
708 RETURN_FAIL("Previous write failed to complete");
709 DEBUG("Previous write completed");
713 port->timeouts.WriteTotalTimeoutConstant = timeout;
714 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
715 RETURN_FAIL("SetCommTimeouts() failed");
718 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) {
719 if (GetLastError() == ERROR_IO_PENDING) {
720 DEBUG("Waiting for write to complete");
721 GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
722 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
723 RETURN_INT(bytes_written);
725 RETURN_FAIL("WriteFile() failed");
728 DEBUG("Write completed immediately");
732 size_t bytes_written = 0;
733 unsigned char *ptr = (unsigned char *) buf;
734 struct timeval start, delta, now, end = {0, 0};
739 /* Get time at start of operation. */
740 gettimeofday(&start, NULL);
741 /* Define duration of timeout. */
742 delta.tv_sec = timeout / 1000;
743 delta.tv_usec = (timeout % 1000) * 1000;
744 /* Calculate time at which we should give up. */
745 timeradd(&start, &delta, &end);
748 /* Loop until we have written the requested number of bytes. */
749 while (bytes_written < count) {
750 /* Wait until space is available. */
752 FD_SET(port->fd, &fds);
754 gettimeofday(&now, NULL);
755 if (timercmp(&now, &end, >)) {
756 DEBUG("Write timed out");
757 RETURN_INT(bytes_written);
759 timersub(&end, &now, &delta);
761 result = select(port->fd + 1, NULL, &fds, NULL, timeout ? &delta : NULL);
763 if (errno == EINTR) {
764 DEBUG("select() call was interrupted, repeating");
767 RETURN_FAIL("select() failed");
769 } else if (result == 0) {
770 DEBUG("Write timed out");
771 RETURN_INT(bytes_written);
775 result = write(port->fd, ptr, count - bytes_written);
779 /* This shouldn't happen because we did a select() first, but handle anyway. */
782 /* This is an actual failure. */
783 RETURN_FAIL("write() failed");
786 bytes_written += result;
790 RETURN_INT(bytes_written);
794 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
795 const void *buf, size_t count)
797 TRACE("%p, %p, %d", port, buf, count);
802 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
804 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
811 BYTE *ptr = (BYTE *) buf;
813 /* Check whether previous write is complete. */
815 if (HasOverlappedIoCompleted(&port->write_ovl)) {
816 DEBUG("Previous write completed");
819 DEBUG("Previous write not complete");
820 /* Can't take a new write until the previous one finishes. */
826 port->timeouts.WriteTotalTimeoutConstant = 0;
827 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
828 RETURN_FAIL("SetCommTimeouts() failed");
831 * Keep writing data until the OS has to actually start an async IO
832 * for it. At that point we know the buffer is full.
834 while (written < count) {
835 /* Copy first byte of user buffer. */
836 port->pending_byte = *ptr++;
838 /* Start asynchronous write. */
839 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
840 if (GetLastError() == ERROR_IO_PENDING) {
841 if (HasOverlappedIoCompleted(&port->write_ovl)) {
842 DEBUG("Asynchronous write completed immediately");
847 DEBUG("Asynchronous write running");
849 RETURN_INT(++written);
852 /* Actual failure of some kind. */
853 RETURN_FAIL("WriteFile() failed");
856 DEBUG("Single byte written immediately");
861 DEBUG("All bytes written immediately");
865 /* Returns the number of bytes written, or -1 upon failure. */
866 ssize_t written = write(port->fd, buf, count);
869 RETURN_FAIL("write() failed");
875 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
876 size_t count, unsigned int timeout)
878 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
883 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
886 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
887 count, port->name, timeout);
889 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
896 DWORD bytes_read = 0;
897 DWORD wait_result = 0;
900 port->timeouts.ReadIntervalTimeout = 0;
901 port->timeouts.ReadTotalTimeoutConstant = timeout;
902 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
903 RETURN_FAIL("SetCommTimeouts() failed");
906 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) {
907 if (GetLastError() == ERROR_IO_PENDING) {
908 DEBUG("Waiting for read to complete");
909 GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
910 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
912 RETURN_FAIL("ReadFile() failed");
915 DEBUG("Read completed immediately");
919 /* Restart wait operation if needed. */
920 if (GetOverlappedResult(port->hdl, &port->wait_ovl, &wait_result, FALSE)) {
921 /* Previous wait completed, start a new one. */
922 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
923 if (GetLastError() != ERROR_IO_PENDING)
924 RETURN_FAIL("WaitCommEvent() failed");
926 } else if (GetLastError() != ERROR_IO_INCOMPLETE) {
927 RETURN_FAIL("GetOverlappedResult() failed");
930 RETURN_INT(bytes_read);
933 size_t bytes_read = 0;
934 unsigned char *ptr = (unsigned char *) buf;
935 struct timeval start, delta, now, end = {0, 0};
940 /* Get time at start of operation. */
941 gettimeofday(&start, NULL);
942 /* Define duration of timeout. */
943 delta.tv_sec = timeout / 1000;
944 delta.tv_usec = (timeout % 1000) * 1000;
945 /* Calculate time at which we should give up. */
946 timeradd(&start, &delta, &end);
949 /* Loop until we have the requested number of bytes. */
950 while (bytes_read < count) {
951 /* Wait until data is available. */
953 FD_SET(port->fd, &fds);
955 gettimeofday(&now, NULL);
956 if (timercmp(&now, &end, >))
957 /* Timeout has expired. */
958 RETURN_INT(bytes_read);
959 timersub(&end, &now, &delta);
961 result = select(port->fd + 1, &fds, NULL, NULL, timeout ? &delta : NULL);
963 if (errno == EINTR) {
964 DEBUG("select() call was interrupted, repeating");
967 RETURN_FAIL("select() failed");
969 } else if (result == 0) {
970 DEBUG("Read timed out");
971 RETURN_INT(bytes_read);
975 result = read(port->fd, ptr, count - bytes_read);
979 /* This shouldn't happen because we did a select() first, but handle anyway. */
982 /* This is an actual failure. */
983 RETURN_FAIL("read() failed");
986 bytes_read += result;
990 RETURN_INT(bytes_read);
994 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
997 TRACE("%p, %p, %d", port, buf, count);
1002 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1004 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1011 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1012 port->timeouts.ReadTotalTimeoutConstant = 0;
1013 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1014 RETURN_FAIL("SetCommTimeouts() failed");
1017 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1018 RETURN_FAIL("ReadFile() failed");
1020 /* Get number of bytes read. */
1021 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1022 RETURN_FAIL("GetOverlappedResult() failed");
1024 /* Restart wait operation if needed. */
1025 if (GetOverlappedResult(port->hdl, &port->wait_ovl, &wait_result, FALSE)) {
1026 /* Previous wait completed, start a new one. */
1027 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
1028 if (GetLastError() != ERROR_IO_PENDING)
1029 RETURN_FAIL("WaitCommEvent() failed");
1031 } else if (GetLastError() != ERROR_IO_INCOMPLETE) {
1032 RETURN_FAIL("GetOverlappedResult() failed");
1035 RETURN_INT(bytes_read);
1039 /* Returns the number of bytes read, or -1 upon failure. */
1040 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1041 if (errno == EAGAIN)
1042 /* No bytes available. */
1045 /* This is an actual failure. */
1046 RETURN_FAIL("read() failed");
1048 RETURN_INT(bytes_read);
1052 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1058 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1064 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1065 RETURN_FAIL("ClearCommError() failed");
1066 RETURN_INT(comstat.cbInQue);
1069 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1070 RETURN_FAIL("TIOCINQ ioctl failed");
1071 RETURN_INT(bytes_waiting);
1075 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1081 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1087 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1088 RETURN_FAIL("ClearCommError() failed");
1089 RETURN_INT(comstat.cbOutQue);
1092 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1093 RETURN_FAIL("TIOCOUTQ ioctl failed");
1094 RETURN_INT(bytes_waiting);
1098 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1100 struct sp_event_set *result;
1102 TRACE("%p", result_ptr);
1105 RETURN_ERROR(SP_ERR_ARG, "Null result");
1109 if (!(result = malloc(sizeof(struct sp_event_set))))
1110 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1112 memset(result, 0, sizeof(struct sp_event_set));
1114 *result_ptr = result;
1119 static enum sp_return add_handle(struct sp_event_set *event_set,
1120 event_handle handle, enum sp_event mask)
1123 enum sp_event *new_masks;
1125 TRACE("%p, %d, %d", event_set, handle, mask);
1127 if (!(new_handles = realloc(event_set->handles,
1128 sizeof(event_handle) * (event_set->count + 1))))
1129 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1131 if (!(new_masks = realloc(event_set->masks,
1132 sizeof(enum sp_event) * (event_set->count + 1))))
1133 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1135 event_set->handles = new_handles;
1136 event_set->masks = new_masks;
1138 ((event_handle *) event_set->handles)[event_set->count] = handle;
1139 event_set->masks[event_set->count] = mask;
1146 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1147 const struct sp_port *port, enum sp_event mask)
1149 TRACE("%p, %p, %d", event_set, port, mask);
1152 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1155 RETURN_ERROR(SP_ERR_ARG, "Null port");
1157 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1158 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1164 enum sp_event handle_mask;
1165 if ((handle_mask = mask & SP_EVENT_TX_READY))
1166 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1167 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1168 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1170 TRY(add_handle(event_set, port->fd, mask));
1176 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1178 TRACE("%p", event_set);
1181 DEBUG("Null event set");
1185 DEBUG("Freeing event set");
1187 if (event_set->handles)
1188 free(event_set->handles);
1189 if (event_set->masks)
1190 free(event_set->masks);
1197 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1198 unsigned int timeout)
1200 TRACE("%p, %d", event_set, timeout);
1203 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1206 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1207 timeout ? timeout : INFINITE) == WAIT_FAILED)
1208 RETURN_FAIL("WaitForMultipleObjects() failed");
1212 struct timeval start, delta, now, end = {0, 0};
1213 int result, timeout_remaining;
1214 struct pollfd *pollfds;
1217 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1218 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1220 for (i = 0; i < event_set->count; i++) {
1221 pollfds[i].fd = ((int *) event_set->handles)[i];
1222 pollfds[i].events = 0;
1223 pollfds[i].revents = 0;
1224 if (event_set->masks[i] & SP_EVENT_RX_READY)
1225 pollfds[i].events |= POLLIN;
1226 if (event_set->masks[i] & SP_EVENT_TX_READY)
1227 pollfds[i].events |= POLLOUT;
1228 if (event_set->masks[i] & SP_EVENT_ERROR)
1229 pollfds[i].events |= POLLERR;
1233 /* Get time at start of operation. */
1234 gettimeofday(&start, NULL);
1235 /* Define duration of timeout. */
1236 delta.tv_sec = timeout / 1000;
1237 delta.tv_usec = (timeout % 1000) * 1000;
1238 /* Calculate time at which we should give up. */
1239 timeradd(&start, &delta, &end);
1242 /* Loop until an event occurs. */
1245 gettimeofday(&now, NULL);
1246 if (timercmp(&now, &end, >)) {
1247 DEBUG("Wait timed out");
1250 timersub(&end, &now, &delta);
1251 timeout_remaining = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1254 result = poll(pollfds, event_set->count, timeout ? timeout_remaining : -1);
1257 if (errno == EINTR) {
1258 DEBUG("poll() call was interrupted, repeating");
1262 RETURN_FAIL("poll() failed");
1264 } else if (result == 0) {
1265 DEBUG("poll() timed out");
1268 DEBUG("poll() completed");
1278 #ifdef USE_TERMIOS_SPEED
1279 static enum sp_return get_baudrate(int fd, int *baudrate)
1283 TRACE("%d, %p", fd, baudrate);
1285 DEBUG("Getting baud rate");
1287 if (!(data = malloc(get_termios_size())))
1288 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1290 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1292 RETURN_FAIL("Getting termios failed");
1295 *baudrate = get_termios_speed(data);
1302 static enum sp_return set_baudrate(int fd, int baudrate)
1306 TRACE("%d, %d", fd, baudrate);
1308 DEBUG("Getting baud rate");
1310 if (!(data = malloc(get_termios_size())))
1311 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1313 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1315 RETURN_FAIL("Getting termios failed");
1318 DEBUG("Setting baud rate");
1320 set_termios_speed(data, baudrate);
1322 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1324 RETURN_FAIL("Setting termios failed");
1331 #endif /* USE_TERMIOS_SPEED */
1334 static enum sp_return get_flow(int fd, struct port_data *data)
1338 TRACE("%d, %p", fd, data);
1340 DEBUG("Getting advanced flow control");
1342 if (!(termx = malloc(get_termiox_size())))
1343 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1345 if (ioctl(fd, TCGETX, termx) < 0) {
1347 RETURN_FAIL("Getting termiox failed");
1350 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1351 &data->dtr_flow, &data->dsr_flow);
1358 static enum sp_return set_flow(int fd, struct port_data *data)
1362 TRACE("%d, %p", fd, data);
1364 DEBUG("Getting advanced flow control");
1366 if (!(termx = malloc(get_termiox_size())))
1367 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1369 if (ioctl(fd, TCGETX, termx) < 0) {
1371 RETURN_FAIL("Getting termiox failed");
1374 DEBUG("Setting advanced flow control");
1376 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1377 data->dtr_flow, data->dsr_flow);
1379 if (ioctl(fd, TCSETX, termx) < 0) {
1381 RETURN_FAIL("Setting termiox failed");
1388 #endif /* USE_TERMIOX */
1390 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1391 struct sp_port_config *config)
1395 TRACE("%p, %p, %p", port, data, config);
1397 DEBUG_FMT("Getting configuration for port %s", port->name);
1400 if (!GetCommState(port->hdl, &data->dcb))
1401 RETURN_FAIL("GetCommState() failed");
1403 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1404 if (data->dcb.BaudRate == std_baudrates[i].index) {
1405 config->baudrate = std_baudrates[i].value;
1410 if (i == NUM_STD_BAUDRATES)
1411 /* BaudRate field can be either an index or a custom baud rate. */
1412 config->baudrate = data->dcb.BaudRate;
1414 config->bits = data->dcb.ByteSize;
1416 if (data->dcb.fParity)
1417 switch (data->dcb.Parity) {
1419 config->parity = SP_PARITY_NONE;
1422 config->parity = SP_PARITY_ODD;
1425 config->parity = SP_PARITY_EVEN;
1428 config->parity = SP_PARITY_MARK;
1431 config->parity = SP_PARITY_SPACE;
1434 config->parity = -1;
1437 config->parity = SP_PARITY_NONE;
1439 switch (data->dcb.StopBits) {
1441 config->stopbits = 1;
1444 config->stopbits = 2;
1447 config->stopbits = -1;
1450 switch (data->dcb.fRtsControl) {
1451 case RTS_CONTROL_DISABLE:
1452 config->rts = SP_RTS_OFF;
1454 case RTS_CONTROL_ENABLE:
1455 config->rts = SP_RTS_ON;
1457 case RTS_CONTROL_HANDSHAKE:
1458 config->rts = SP_RTS_FLOW_CONTROL;
1464 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1466 switch (data->dcb.fDtrControl) {
1467 case DTR_CONTROL_DISABLE:
1468 config->dtr = SP_DTR_OFF;
1470 case DTR_CONTROL_ENABLE:
1471 config->dtr = SP_DTR_ON;
1473 case DTR_CONTROL_HANDSHAKE:
1474 config->dtr = SP_DTR_FLOW_CONTROL;
1480 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1482 if (data->dcb.fInX) {
1483 if (data->dcb.fOutX)
1484 config->xon_xoff = SP_XONXOFF_INOUT;
1486 config->xon_xoff = SP_XONXOFF_IN;
1488 if (data->dcb.fOutX)
1489 config->xon_xoff = SP_XONXOFF_OUT;
1491 config->xon_xoff = SP_XONXOFF_DISABLED;
1496 if (tcgetattr(port->fd, &data->term) < 0)
1497 RETURN_FAIL("tcgetattr() failed");
1499 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1500 RETURN_FAIL("TIOCMGET ioctl failed");
1503 int ret = get_flow(port->fd, data);
1505 if (ret == SP_ERR_FAIL && errno == EINVAL)
1506 data->termiox_supported = 0;
1508 RETURN_CODEVAL(ret);
1510 data->termiox_supported = 1;
1512 data->termiox_supported = 0;
1515 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1516 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1517 config->baudrate = std_baudrates[i].value;
1522 if (i == NUM_STD_BAUDRATES) {
1524 config->baudrate = (int)data->term.c_ispeed;
1525 #elif defined(USE_TERMIOS_SPEED)
1526 TRY(get_baudrate(port->fd, &config->baudrate));
1528 config->baudrate = -1;
1532 switch (data->term.c_cflag & CSIZE) {
1549 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1550 config->parity = SP_PARITY_NONE;
1551 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1552 config->parity = -1;
1554 else if (data->term.c_cflag & CMSPAR)
1555 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1558 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1560 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1562 if (data->term.c_cflag & CRTSCTS) {
1563 config->rts = SP_RTS_FLOW_CONTROL;
1564 config->cts = SP_CTS_FLOW_CONTROL;
1566 if (data->termiox_supported && data->rts_flow)
1567 config->rts = SP_RTS_FLOW_CONTROL;
1569 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1571 config->cts = (data->termiox_supported && data->cts_flow) ?
1572 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1575 if (data->termiox_supported && data->dtr_flow)
1576 config->dtr = SP_DTR_FLOW_CONTROL;
1578 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1580 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1581 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1583 if (data->term.c_iflag & IXOFF) {
1584 if (data->term.c_iflag & IXON)
1585 config->xon_xoff = SP_XONXOFF_INOUT;
1587 config->xon_xoff = SP_XONXOFF_IN;
1589 if (data->term.c_iflag & IXON)
1590 config->xon_xoff = SP_XONXOFF_OUT;
1592 config->xon_xoff = SP_XONXOFF_DISABLED;
1599 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1600 const struct sp_port_config *config)
1604 BAUD_TYPE baud_nonstd;
1608 #ifdef USE_TERMIOS_SPEED
1609 int baud_nonstd = 0;
1612 TRACE("%p, %p, %p", port, data, config);
1614 DEBUG_FMT("Setting configuration for port %s", port->name);
1617 if (config->baudrate >= 0) {
1618 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1619 if (config->baudrate == std_baudrates[i].value) {
1620 data->dcb.BaudRate = std_baudrates[i].index;
1625 if (i == NUM_STD_BAUDRATES)
1626 data->dcb.BaudRate = config->baudrate;
1629 if (config->bits >= 0)
1630 data->dcb.ByteSize = config->bits;
1632 if (config->parity >= 0) {
1633 switch (config->parity) {
1634 case SP_PARITY_NONE:
1635 data->dcb.Parity = NOPARITY;
1638 data->dcb.Parity = ODDPARITY;
1640 case SP_PARITY_EVEN:
1641 data->dcb.Parity = EVENPARITY;
1643 case SP_PARITY_MARK:
1644 data->dcb.Parity = MARKPARITY;
1646 case SP_PARITY_SPACE:
1647 data->dcb.Parity = SPACEPARITY;
1650 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1654 if (config->stopbits >= 0) {
1655 switch (config->stopbits) {
1656 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1658 data->dcb.StopBits = ONESTOPBIT;
1661 data->dcb.StopBits = TWOSTOPBITS;
1664 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1668 if (config->rts >= 0) {
1669 switch (config->rts) {
1671 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1674 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1676 case SP_RTS_FLOW_CONTROL:
1677 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1680 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1684 if (config->cts >= 0) {
1685 switch (config->cts) {
1687 data->dcb.fOutxCtsFlow = FALSE;
1689 case SP_CTS_FLOW_CONTROL:
1690 data->dcb.fOutxCtsFlow = TRUE;
1693 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1697 if (config->dtr >= 0) {
1698 switch (config->dtr) {
1700 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1703 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1705 case SP_DTR_FLOW_CONTROL:
1706 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1709 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1713 if (config->dsr >= 0) {
1714 switch (config->dsr) {
1716 data->dcb.fOutxDsrFlow = FALSE;
1718 case SP_DSR_FLOW_CONTROL:
1719 data->dcb.fOutxDsrFlow = TRUE;
1722 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1726 if (config->xon_xoff >= 0) {
1727 switch (config->xon_xoff) {
1728 case SP_XONXOFF_DISABLED:
1729 data->dcb.fInX = FALSE;
1730 data->dcb.fOutX = FALSE;
1733 data->dcb.fInX = TRUE;
1734 data->dcb.fOutX = FALSE;
1736 case SP_XONXOFF_OUT:
1737 data->dcb.fInX = FALSE;
1738 data->dcb.fOutX = TRUE;
1740 case SP_XONXOFF_INOUT:
1741 data->dcb.fInX = TRUE;
1742 data->dcb.fOutX = TRUE;
1745 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1749 if (!SetCommState(port->hdl, &data->dcb))
1750 RETURN_FAIL("SetCommState() failed");
1756 if (config->baudrate >= 0) {
1757 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1758 if (config->baudrate == std_baudrates[i].value) {
1759 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1760 RETURN_FAIL("cfsetospeed() failed");
1762 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1763 RETURN_FAIL("cfsetispeed() failed");
1768 /* Non-standard baud rate */
1769 if (i == NUM_STD_BAUDRATES) {
1771 /* Set "dummy" baud rate. */
1772 if (cfsetspeed(&data->term, B9600) < 0)
1773 RETURN_FAIL("cfsetspeed() failed");
1774 baud_nonstd = config->baudrate;
1775 #elif defined(USE_TERMIOS_SPEED)
1778 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1783 if (config->bits >= 0) {
1784 data->term.c_cflag &= ~CSIZE;
1785 switch (config->bits) {
1787 data->term.c_cflag |= CS8;
1790 data->term.c_cflag |= CS7;
1793 data->term.c_cflag |= CS6;
1796 data->term.c_cflag |= CS5;
1799 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1803 if (config->parity >= 0) {
1804 data->term.c_iflag &= ~IGNPAR;
1805 data->term.c_cflag &= ~(PARENB | PARODD);
1807 data->term.c_cflag &= ~CMSPAR;
1809 switch (config->parity) {
1810 case SP_PARITY_NONE:
1811 data->term.c_iflag |= IGNPAR;
1813 case SP_PARITY_EVEN:
1814 data->term.c_cflag |= PARENB;
1817 data->term.c_cflag |= PARENB | PARODD;
1820 case SP_PARITY_MARK:
1821 data->term.c_cflag |= PARENB | PARODD;
1822 data->term.c_cflag |= CMSPAR;
1824 case SP_PARITY_SPACE:
1825 data->term.c_cflag |= PARENB;
1826 data->term.c_cflag |= CMSPAR;
1829 case SP_PARITY_MARK:
1830 case SP_PARITY_SPACE:
1831 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1834 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1838 if (config->stopbits >= 0) {
1839 data->term.c_cflag &= ~CSTOPB;
1840 switch (config->stopbits) {
1842 data->term.c_cflag &= ~CSTOPB;
1845 data->term.c_cflag |= CSTOPB;
1848 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1852 if (config->rts >= 0 || config->cts >= 0) {
1853 if (data->termiox_supported) {
1854 data->rts_flow = data->cts_flow = 0;
1855 switch (config->rts) {
1858 controlbits = TIOCM_RTS;
1859 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1860 RETURN_FAIL("Setting RTS signal level failed");
1862 case SP_RTS_FLOW_CONTROL:
1868 if (config->cts == SP_CTS_FLOW_CONTROL)
1871 if (data->rts_flow && data->cts_flow)
1872 data->term.c_iflag |= CRTSCTS;
1874 data->term.c_iflag &= ~CRTSCTS;
1876 /* Asymmetric use of RTS/CTS not supported. */
1877 if (data->term.c_iflag & CRTSCTS) {
1878 /* Flow control can only be disabled for both RTS & CTS together. */
1879 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1880 if (config->cts != SP_CTS_IGNORE)
1881 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1883 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1884 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1885 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1888 /* Flow control can only be enabled for both RTS & CTS together. */
1889 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1890 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1891 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1894 if (config->rts >= 0) {
1895 if (config->rts == SP_RTS_FLOW_CONTROL) {
1896 data->term.c_iflag |= CRTSCTS;
1898 controlbits = TIOCM_RTS;
1899 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1901 RETURN_FAIL("Setting RTS signal level failed");
1907 if (config->dtr >= 0 || config->dsr >= 0) {
1908 if (data->termiox_supported) {
1909 data->dtr_flow = data->dsr_flow = 0;
1910 switch (config->dtr) {
1913 controlbits = TIOCM_DTR;
1914 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1915 RETURN_FAIL("Setting DTR signal level failed");
1917 case SP_DTR_FLOW_CONTROL:
1923 if (config->dsr == SP_DSR_FLOW_CONTROL)
1926 /* DTR/DSR flow control not supported. */
1927 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1928 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1930 if (config->dtr >= 0) {
1931 controlbits = TIOCM_DTR;
1932 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1934 RETURN_FAIL("Setting DTR signal level failed");
1939 if (config->xon_xoff >= 0) {
1940 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1941 switch (config->xon_xoff) {
1942 case SP_XONXOFF_DISABLED:
1945 data->term.c_iflag |= IXOFF;
1947 case SP_XONXOFF_OUT:
1948 data->term.c_iflag |= IXON | IXANY;
1950 case SP_XONXOFF_INOUT:
1951 data->term.c_iflag |= IXON | IXOFF | IXANY;
1954 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1958 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
1959 RETURN_FAIL("tcsetattr() failed");
1962 if (baud_nonstd != B0) {
1963 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1964 RETURN_FAIL("IOSSIOSPEED ioctl failed");
1966 * Set baud rates in data->term to correct, but incompatible
1967 * with tcsetattr() value, same as delivered by tcgetattr().
1969 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1970 RETURN_FAIL("cfsetspeed() failed");
1972 #elif defined(__linux__)
1973 #ifdef USE_TERMIOS_SPEED
1975 TRY(set_baudrate(port->fd, config->baudrate));
1978 if (data->termiox_supported)
1979 TRY(set_flow(port->fd, data));
1983 #endif /* !_WIN32 */
1988 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
1990 struct sp_port_config *config;
1992 TRACE("%p", config_ptr);
1995 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1999 if (!(config = malloc(sizeof(struct sp_port_config))))
2000 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2002 config->baudrate = -1;
2004 config->parity = -1;
2005 config->stopbits = -1;
2011 *config_ptr = config;
2016 SP_API void sp_free_config(struct sp_port_config *config)
2018 TRACE("%p", config);
2021 DEBUG("Null config");
2028 SP_API enum sp_return sp_get_config(struct sp_port *port,
2029 struct sp_port_config *config)
2031 struct port_data data;
2033 TRACE("%p, %p", port, config);
2038 RETURN_ERROR(SP_ERR_ARG, "Null config");
2040 TRY(get_config(port, &data, config));
2045 SP_API enum sp_return sp_set_config(struct sp_port *port,
2046 const struct sp_port_config *config)
2048 struct port_data data;
2049 struct sp_port_config prev_config;
2051 TRACE("%p, %p", port, config);
2056 RETURN_ERROR(SP_ERR_ARG, "Null config");
2058 TRY(get_config(port, &data, &prev_config));
2059 TRY(set_config(port, &data, config));
2064 #define CREATE_ACCESSORS(x, type) \
2065 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2066 struct port_data data; \
2067 struct sp_port_config config; \
2068 TRACE("%p, %d", port, x); \
2069 CHECK_OPEN_PORT(); \
2070 TRY(get_config(port, &data, &config)); \
2072 TRY(set_config(port, &data, &config)); \
2075 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2077 TRACE("%p, %p", config, x); \
2079 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2083 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2085 TRACE("%p, %d", config, x); \
2087 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2092 CREATE_ACCESSORS(baudrate, int)
2093 CREATE_ACCESSORS(bits, int)
2094 CREATE_ACCESSORS(parity, enum sp_parity)
2095 CREATE_ACCESSORS(stopbits, int)
2096 CREATE_ACCESSORS(rts, enum sp_rts)
2097 CREATE_ACCESSORS(cts, enum sp_cts)
2098 CREATE_ACCESSORS(dtr, enum sp_dtr)
2099 CREATE_ACCESSORS(dsr, enum sp_dsr)
2100 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2102 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2103 enum sp_flowcontrol flowcontrol)
2106 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2108 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2109 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2111 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2112 config->xon_xoff = SP_XONXOFF_INOUT;
2114 config->xon_xoff = SP_XONXOFF_DISABLED;
2116 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2117 config->rts = SP_RTS_FLOW_CONTROL;
2118 config->cts = SP_CTS_FLOW_CONTROL;
2120 if (config->rts == SP_RTS_FLOW_CONTROL)
2121 config->rts = SP_RTS_ON;
2122 config->cts = SP_CTS_IGNORE;
2125 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2126 config->dtr = SP_DTR_FLOW_CONTROL;
2127 config->dsr = SP_DSR_FLOW_CONTROL;
2129 if (config->dtr == SP_DTR_FLOW_CONTROL)
2130 config->dtr = SP_DTR_ON;
2131 config->dsr = SP_DSR_IGNORE;
2137 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2138 enum sp_flowcontrol flowcontrol)
2140 struct port_data data;
2141 struct sp_port_config config;
2143 TRACE("%p, %d", port, flowcontrol);
2147 TRY(get_config(port, &data, &config));
2149 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2151 TRY(set_config(port, &data, &config));
2156 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2157 enum sp_signal *signals)
2159 TRACE("%p, %p", port, signals);
2164 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2166 DEBUG_FMT("Getting control signals for port %s", port->name);
2171 if (GetCommModemStatus(port->hdl, &bits) == 0)
2172 RETURN_FAIL("GetCommModemStatus() failed");
2173 if (bits & MS_CTS_ON)
2174 *signals |= SP_SIG_CTS;
2175 if (bits & MS_DSR_ON)
2176 *signals |= SP_SIG_DSR;
2177 if (bits & MS_RLSD_ON)
2178 *signals |= SP_SIG_DCD;
2179 if (bits & MS_RING_ON)
2180 *signals |= SP_SIG_RI;
2183 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2184 RETURN_FAIL("TIOCMGET ioctl failed");
2185 if (bits & TIOCM_CTS)
2186 *signals |= SP_SIG_CTS;
2187 if (bits & TIOCM_DSR)
2188 *signals |= SP_SIG_DSR;
2189 if (bits & TIOCM_CAR)
2190 *signals |= SP_SIG_DCD;
2191 if (bits & TIOCM_RNG)
2192 *signals |= SP_SIG_RI;
2197 SP_API enum sp_return sp_start_break(struct sp_port *port)
2203 if (SetCommBreak(port->hdl) == 0)
2204 RETURN_FAIL("SetCommBreak() failed");
2206 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2207 RETURN_FAIL("TIOCSBRK ioctl failed");
2213 SP_API enum sp_return sp_end_break(struct sp_port *port)
2219 if (ClearCommBreak(port->hdl) == 0)
2220 RETURN_FAIL("ClearCommBreak() failed");
2222 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2223 RETURN_FAIL("TIOCCBRK ioctl failed");
2229 SP_API int sp_last_error_code(void)
2233 RETURN_INT(GetLastError());
2239 SP_API char *sp_last_error_message(void)
2245 DWORD error = GetLastError();
2248 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2249 FORMAT_MESSAGE_FROM_SYSTEM |
2250 FORMAT_MESSAGE_IGNORE_INSERTS,
2253 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2257 RETURN_STRING(message);
2259 RETURN_STRING(strerror(errno));
2263 SP_API void sp_free_error_message(char *message)
2265 TRACE("%s", message);
2276 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2278 TRACE("%p", handler);
2280 sp_debug_handler = handler;
2285 SP_API void sp_default_debug_handler(const char *format, ...)
2288 va_start(args, format);
2289 if (getenv("LIBSERIALPORT_DEBUG")) {
2290 fputs("sp: ", stderr);
2291 vfprintf(stderr, format, args);
2296 SP_API int sp_get_major_package_version(void)
2298 return SP_PACKAGE_VERSION_MAJOR;
2301 SP_API int sp_get_minor_package_version(void)
2303 return SP_PACKAGE_VERSION_MINOR;
2306 SP_API int sp_get_micro_package_version(void)
2308 return SP_PACKAGE_VERSION_MICRO;
2311 SP_API const char *sp_get_package_version_string(void)
2313 return SP_PACKAGE_VERSION_STRING;
2316 SP_API int sp_get_current_lib_version(void)
2318 return SP_LIB_VERSION_CURRENT;
2321 SP_API int sp_get_revision_lib_version(void)
2323 return SP_LIB_VERSION_REVISION;
2326 SP_API int sp_get_age_lib_version(void)
2328 return SP_LIB_VERSION_AGE;
2331 SP_API const char *sp_get_lib_version_string(void)
2333 return SP_LIB_VERSION_STRING;