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 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 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
49 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
50 struct sp_port_config *config);
52 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
53 const struct sp_port_config *config);
55 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
58 #ifndef NO_PORT_METADATA
63 TRACE("%s, %p", portname, port_ptr);
66 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
71 RETURN_ERROR(SP_ERR_ARG, "Null port name");
73 DEBUG_FMT("Building structure for port %s", portname);
75 if (!(port = malloc(sizeof(struct sp_port))))
76 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
78 len = strlen(portname) + 1;
80 if (!(port->name = malloc(len))) {
82 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
85 memcpy(port->name, portname, len);
88 port->usb_path = NULL;
89 port->hdl = INVALID_HANDLE_VALUE;
94 port->description = NULL;
95 port->transport = SP_TRANSPORT_NATIVE;
97 port->usb_address = -1;
100 port->usb_manufacturer = NULL;
101 port->usb_product = NULL;
102 port->usb_serial = NULL;
103 port->bluetooth_address = NULL;
105 #ifndef NO_PORT_METADATA
106 if ((ret = get_port_details(port)) != SP_OK) {
117 SP_API char *sp_get_port_name(const struct sp_port *port)
124 RETURN_STRING(port->name);
127 SP_API char *sp_get_port_description(struct sp_port *port)
131 if (!port || !port->description)
134 RETURN_STRING(port->description);
137 SP_API enum sp_transport sp_get_port_transport(struct sp_port *port)
142 RETURN_ERROR(SP_ERR_ARG, "Null port");
144 RETURN_INT(port->transport);
147 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
148 int *usb_bus,int *usb_address)
153 RETURN_ERROR(SP_ERR_ARG, "Null port");
154 if (port->transport != SP_TRANSPORT_USB)
155 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
156 if (port->usb_bus < 0 || port->usb_address < 0)
157 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
160 *usb_bus = port->usb_bus;
162 *usb_address = port->usb_address;
167 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
168 int *usb_vid, int *usb_pid)
173 RETURN_ERROR(SP_ERR_ARG, "Null port");
174 if (port->transport != SP_TRANSPORT_USB)
175 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
176 if (port->usb_vid < 0 || port->usb_pid < 0)
177 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
180 *usb_vid = port->usb_vid;
182 *usb_pid = port->usb_pid;
187 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
191 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
194 RETURN_STRING(port->usb_manufacturer);
197 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
201 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
204 RETURN_STRING(port->usb_product);
207 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
211 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
214 RETURN_STRING(port->usb_serial);
217 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
221 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
222 || !port->bluetooth_address)
225 RETURN_STRING(port->bluetooth_address);
228 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
231 TRACE("%p, %p", port, result_ptr);
234 RETURN_ERROR(SP_ERR_ARG, "Null port");
237 HANDLE *handle_ptr = result_ptr;
238 *handle_ptr = port->hdl;
240 int *fd_ptr = result_ptr;
247 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
248 struct sp_port **copy_ptr)
250 TRACE("%p, %p", port, copy_ptr);
253 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
258 RETURN_ERROR(SP_ERR_ARG, "Null port");
261 RETURN_ERROR(SP_ERR_ARG, "Null port name");
263 DEBUG("Copying port structure");
265 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
268 SP_API void sp_free_port(struct sp_port *port)
277 DEBUG("Freeing port structure");
281 if (port->description)
282 free(port->description);
283 if (port->usb_manufacturer)
284 free(port->usb_manufacturer);
285 if (port->usb_product)
286 free(port->usb_product);
287 if (port->usb_serial)
288 free(port->usb_serial);
289 if (port->bluetooth_address)
290 free(port->bluetooth_address);
293 free(port->usb_path);
301 SP_PRIV struct sp_port **list_append(struct sp_port **list,
302 const char *portname)
307 for (count = 0; list[count]; count++);
308 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
311 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
313 list[count + 1] = NULL;
317 sp_free_port_list(list);
321 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
323 struct sp_port **list;
326 TRACE("%p", list_ptr);
329 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
331 DEBUG("Enumerating ports");
333 if (!(list = malloc(sizeof(struct sp_port **))))
334 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
338 #ifdef NO_ENUMERATION
341 ret = list_ports(&list);
349 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
352 sp_free_port_list(list);
358 SP_API void sp_free_port_list(struct sp_port **list)
369 DEBUG("Freeing port list");
371 for (i = 0; list[i]; i++)
372 sp_free_port(list[i]);
378 #define CHECK_PORT() do { \
380 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
382 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
385 #define CHECK_PORT_HANDLE() do { \
386 if (port->hdl == INVALID_HANDLE_VALUE) \
387 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
390 #define CHECK_PORT_HANDLE() do { \
392 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
395 #define CHECK_OPEN_PORT() do { \
397 CHECK_PORT_HANDLE(); \
400 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
402 struct port_data data;
403 struct sp_port_config config;
406 TRACE("%p, 0x%x", port, flags);
410 if (flags > SP_MODE_READ_WRITE)
411 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
413 DEBUG_FMT("Opening port %s", port->name);
416 DWORD desired_access = 0, flags_and_attributes = 0, errors;
417 char *escaped_port_name;
420 /* Prefix port name with '\\.\' to work with ports above COM9. */
421 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
422 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
423 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
425 /* Map 'flags' to the OS-specific settings. */
426 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
427 if (flags & SP_MODE_READ)
428 desired_access |= GENERIC_READ;
429 if (flags & SP_MODE_WRITE)
430 desired_access |= GENERIC_WRITE;
432 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
433 OPEN_EXISTING, flags_and_attributes, 0);
435 free(escaped_port_name);
437 if (port->hdl == INVALID_HANDLE_VALUE)
438 RETURN_FAIL("Port CreateFile() failed");
440 /* All timeouts initially disabled. */
441 port->timeouts.ReadIntervalTimeout = 0;
442 port->timeouts.ReadTotalTimeoutMultiplier = 0;
443 port->timeouts.ReadTotalTimeoutConstant = 0;
444 port->timeouts.WriteTotalTimeoutMultiplier = 0;
445 port->timeouts.WriteTotalTimeoutConstant = 0;
447 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
449 RETURN_FAIL("SetCommTimeouts() failed");
452 /* Prepare OVERLAPPED structures. */
453 #define INIT_OVERLAPPED(ovl) do { \
454 memset(&port->ovl, 0, sizeof(port->ovl)); \
455 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
456 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
457 == INVALID_HANDLE_VALUE) { \
459 RETURN_FAIL(#ovl "CreateEvent() failed"); \
463 INIT_OVERLAPPED(read_ovl);
464 INIT_OVERLAPPED(write_ovl);
465 INIT_OVERLAPPED(wait_ovl);
467 /* Set event mask for RX and error events. */
468 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
470 RETURN_FAIL("SetCommMask() failed");
473 /* Start background operation for RX and error events. */
474 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
475 if (GetLastError() != ERROR_IO_PENDING) {
477 RETURN_FAIL("WaitCommEvent() failed");
481 port->writing = FALSE;
484 int flags_local = O_NONBLOCK | O_NOCTTY;
486 /* Map 'flags' to the OS-specific settings. */
487 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
488 flags_local |= O_RDWR;
489 else if (flags & SP_MODE_READ)
490 flags_local |= O_RDONLY;
491 else if (flags & SP_MODE_WRITE)
492 flags_local |= O_WRONLY;
494 if ((port->fd = open(port->name, flags_local)) < 0)
495 RETURN_FAIL("open() failed");
498 ret = get_config(port, &data, &config);
505 /* Set sane port settings. */
507 data.dcb.fBinary = TRUE;
508 data.dcb.fDsrSensitivity = FALSE;
509 data.dcb.fErrorChar = FALSE;
510 data.dcb.fNull = FALSE;
511 data.dcb.fAbortOnError = TRUE;
513 /* Turn off all fancy termios tricks, give us a raw channel. */
514 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
516 data.term.c_iflag &= ~IUCLC;
518 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
520 data.term.c_oflag &= ~OLCUC;
523 data.term.c_oflag &= ~NLDLY;
526 data.term.c_oflag &= ~CRDLY;
529 data.term.c_oflag &= ~TABDLY;
532 data.term.c_oflag &= ~BSDLY;
535 data.term.c_oflag &= ~VTDLY;
538 data.term.c_oflag &= ~FFDLY;
541 data.term.c_oflag &= ~OFILL;
543 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
544 data.term.c_cc[VMIN] = 0;
545 data.term.c_cc[VTIME] = 0;
547 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
548 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
552 if (ClearCommError(port->hdl, &errors, &status) == 0)
553 RETURN_FAIL("ClearCommError() failed");
556 ret = set_config(port, &data, &config);
566 SP_API enum sp_return sp_close(struct sp_port *port)
572 DEBUG_FMT("Closing port %s", port->name);
575 /* Returns non-zero upon success, 0 upon failure. */
576 if (CloseHandle(port->hdl) == 0)
577 RETURN_FAIL("Port CloseHandle() failed");
578 port->hdl = INVALID_HANDLE_VALUE;
580 /* Close event handles for overlapped structures. */
581 #define CLOSE_OVERLAPPED(ovl) do { \
582 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
583 CloseHandle(port->ovl.hEvent) == 0) \
584 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
586 CLOSE_OVERLAPPED(read_ovl);
587 CLOSE_OVERLAPPED(write_ovl);
588 CLOSE_OVERLAPPED(wait_ovl);
591 /* Returns 0 upon success, -1 upon failure. */
592 if (close(port->fd) == -1)
593 RETURN_FAIL("close() failed");
600 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
602 TRACE("%p, 0x%x", port, buffers);
606 if (buffers > SP_BUF_BOTH)
607 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
609 const char *buffer_names[] = {"no", "input", "output", "both"};
611 DEBUG_FMT("Flushing %s buffers on port %s",
612 buffer_names[buffers], port->name);
616 if (buffers & SP_BUF_INPUT)
617 flags |= PURGE_RXCLEAR;
618 if (buffers & SP_BUF_OUTPUT)
619 flags |= PURGE_TXCLEAR;
621 /* Returns non-zero upon success, 0 upon failure. */
622 if (PurgeComm(port->hdl, flags) == 0)
623 RETURN_FAIL("PurgeComm() failed");
626 if (buffers == SP_BUF_BOTH)
628 else if (buffers == SP_BUF_INPUT)
630 else if (buffers == SP_BUF_OUTPUT)
633 /* Returns 0 upon success, -1 upon failure. */
634 if (tcflush(port->fd, flags) < 0)
635 RETURN_FAIL("tcflush() failed");
640 SP_API enum sp_return sp_drain(struct sp_port *port)
646 DEBUG_FMT("Draining port %s", port->name);
649 /* Returns non-zero upon success, 0 upon failure. */
650 if (FlushFileBuffers(port->hdl) == 0)
651 RETURN_FAIL("FlushFileBuffers() failed");
658 result = ioctl(port->fd, TCSBRK, &arg);
660 result = tcdrain(port->fd);
663 if (errno == EINTR) {
664 DEBUG("tcdrain() was interrupted");
667 RETURN_FAIL("tcdrain() failed");
676 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
677 size_t count, unsigned int timeout)
679 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
684 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
687 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
688 count, port->name, timeout);
690 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
697 DWORD bytes_written = 0;
700 /* Wait for previous non-blocking write to complete, if any. */
702 DEBUG("Waiting for previous write to complete");
703 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
706 RETURN_FAIL("Previous write failed to complete");
707 DEBUG("Previous write completed");
711 port->timeouts.WriteTotalTimeoutConstant = timeout;
712 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
713 RETURN_FAIL("SetCommTimeouts() failed");
716 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) {
717 if (GetLastError() == ERROR_IO_PENDING) {
718 DEBUG("Waiting for write to complete");
719 GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
720 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
721 RETURN_INT(bytes_written);
723 RETURN_FAIL("WriteFile() failed");
726 DEBUG("Write completed immediately");
730 size_t bytes_written = 0;
731 unsigned char *ptr = (unsigned char *) buf;
732 struct timeval start, delta, now, end = {0, 0};
737 /* Get time at start of operation. */
738 gettimeofday(&start, NULL);
739 /* Define duration of timeout. */
740 delta.tv_sec = timeout / 1000;
741 delta.tv_usec = (timeout % 1000) * 1000;
742 /* Calculate time at which we should give up. */
743 timeradd(&start, &delta, &end);
746 /* Loop until we have written the requested number of bytes. */
747 while (bytes_written < count) {
748 /* Wait until space is available. */
750 FD_SET(port->fd, &fds);
752 gettimeofday(&now, NULL);
753 if (timercmp(&now, &end, >)) {
754 DEBUG("Write timed out");
755 RETURN_INT(bytes_written);
757 timersub(&end, &now, &delta);
759 result = select(port->fd + 1, NULL, &fds, NULL, timeout ? &delta : NULL);
761 if (errno == EINTR) {
762 DEBUG("select() call was interrupted, repeating");
765 RETURN_FAIL("select() failed");
767 } else if (result == 0) {
768 DEBUG("Write timed out");
769 RETURN_INT(bytes_written);
773 result = write(port->fd, ptr, count - bytes_written);
777 /* This shouldn't happen because we did a select() first, but handle anyway. */
780 /* This is an actual failure. */
781 RETURN_FAIL("write() failed");
784 bytes_written += result;
788 RETURN_INT(bytes_written);
792 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
793 const void *buf, size_t count)
795 TRACE("%p, %p, %d", port, buf, count);
800 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
802 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
809 BYTE *ptr = (BYTE *) buf;
811 /* Check whether previous write is complete. */
813 if (HasOverlappedIoCompleted(&port->write_ovl)) {
814 DEBUG("Previous write completed");
817 DEBUG("Previous write not complete");
818 /* Can't take a new write until the previous one finishes. */
824 port->timeouts.WriteTotalTimeoutConstant = 0;
825 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
826 RETURN_FAIL("SetCommTimeouts() failed");
829 * Keep writing data until the OS has to actually start an async IO
830 * for it. At that point we know the buffer is full.
832 while (written < count) {
833 /* Copy first byte of user buffer. */
834 port->pending_byte = *ptr++;
836 /* Start asynchronous write. */
837 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
838 if (GetLastError() == ERROR_IO_PENDING) {
839 if (HasOverlappedIoCompleted(&port->write_ovl)) {
840 DEBUG("Asynchronous write completed immediately");
845 DEBUG("Asynchronous write running");
847 RETURN_INT(++written);
850 /* Actual failure of some kind. */
851 RETURN_FAIL("WriteFile() failed");
854 DEBUG("Single byte written immediately");
859 DEBUG("All bytes written immediately");
863 /* Returns the number of bytes written, or -1 upon failure. */
864 ssize_t written = write(port->fd, buf, count);
867 RETURN_FAIL("write() failed");
873 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
874 size_t count, unsigned int timeout)
876 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
881 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
884 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
885 count, port->name, timeout);
887 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
894 DWORD bytes_read = 0;
895 DWORD wait_result = 0;
898 port->timeouts.ReadIntervalTimeout = 0;
899 port->timeouts.ReadTotalTimeoutConstant = timeout;
900 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
901 RETURN_FAIL("SetCommTimeouts() failed");
904 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) {
905 if (GetLastError() == ERROR_IO_PENDING) {
906 DEBUG("Waiting for read to complete");
907 GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
908 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
910 RETURN_FAIL("ReadFile() failed");
913 DEBUG("Read completed immediately");
917 /* Restart wait operation if needed. */
918 if (GetOverlappedResult(port->hdl, &port->wait_ovl, &wait_result, FALSE)) {
919 /* Previous wait completed, start a new one. */
920 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
921 if (GetLastError() != ERROR_IO_PENDING)
922 RETURN_FAIL("WaitCommEvent() failed");
924 } else if (GetLastError() != ERROR_IO_INCOMPLETE) {
925 RETURN_FAIL("GetOverlappedResult() failed");
928 RETURN_INT(bytes_read);
931 size_t bytes_read = 0;
932 unsigned char *ptr = (unsigned char *) buf;
933 struct timeval start, delta, now, end = {0, 0};
938 /* Get time at start of operation. */
939 gettimeofday(&start, NULL);
940 /* Define duration of timeout. */
941 delta.tv_sec = timeout / 1000;
942 delta.tv_usec = (timeout % 1000) * 1000;
943 /* Calculate time at which we should give up. */
944 timeradd(&start, &delta, &end);
947 /* Loop until we have the requested number of bytes. */
948 while (bytes_read < count) {
949 /* Wait until data is available. */
951 FD_SET(port->fd, &fds);
953 gettimeofday(&now, NULL);
954 if (timercmp(&now, &end, >))
955 /* Timeout has expired. */
956 RETURN_INT(bytes_read);
957 timersub(&end, &now, &delta);
959 result = select(port->fd + 1, &fds, NULL, NULL, timeout ? &delta : NULL);
961 if (errno == EINTR) {
962 DEBUG("select() call was interrupted, repeating");
965 RETURN_FAIL("select() failed");
967 } else if (result == 0) {
968 DEBUG("Read timed out");
969 RETURN_INT(bytes_read);
973 result = read(port->fd, ptr, count - bytes_read);
977 /* This shouldn't happen because we did a select() first, but handle anyway. */
980 /* This is an actual failure. */
981 RETURN_FAIL("read() failed");
984 bytes_read += result;
988 RETURN_INT(bytes_read);
992 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
995 TRACE("%p, %p, %d", port, buf, count);
1000 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1002 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1009 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1010 port->timeouts.ReadTotalTimeoutConstant = 0;
1011 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1012 RETURN_FAIL("SetCommTimeouts() failed");
1015 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1016 RETURN_FAIL("ReadFile() failed");
1018 /* Get number of bytes read. */
1019 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1020 RETURN_FAIL("GetOverlappedResult() failed");
1022 /* Restart wait operation if needed. */
1023 if (GetOverlappedResult(port->hdl, &port->wait_ovl, &wait_result, FALSE)) {
1024 /* Previous wait completed, start a new one. */
1025 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
1026 if (GetLastError() != ERROR_IO_PENDING)
1027 RETURN_FAIL("WaitCommEvent() failed");
1029 } else if (GetLastError() != ERROR_IO_INCOMPLETE) {
1030 RETURN_FAIL("GetOverlappedResult() failed");
1033 RETURN_INT(bytes_read);
1037 /* Returns the number of bytes read, or -1 upon failure. */
1038 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1039 if (errno == EAGAIN)
1040 /* No bytes available. */
1043 /* This is an actual failure. */
1044 RETURN_FAIL("read() failed");
1046 RETURN_INT(bytes_read);
1050 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1056 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1062 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1063 RETURN_FAIL("ClearCommError() failed");
1064 RETURN_INT(comstat.cbInQue);
1067 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1068 RETURN_FAIL("TIOCINQ ioctl failed");
1069 RETURN_INT(bytes_waiting);
1073 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1079 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1085 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1086 RETURN_FAIL("ClearCommError() failed");
1087 RETURN_INT(comstat.cbOutQue);
1090 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1091 RETURN_FAIL("TIOCOUTQ ioctl failed");
1092 RETURN_INT(bytes_waiting);
1096 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1098 struct sp_event_set *result;
1100 TRACE("%p", result_ptr);
1103 RETURN_ERROR(SP_ERR_ARG, "Null result");
1107 if (!(result = malloc(sizeof(struct sp_event_set))))
1108 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1110 memset(result, 0, sizeof(struct sp_event_set));
1112 *result_ptr = result;
1117 static enum sp_return add_handle(struct sp_event_set *event_set,
1118 event_handle handle, enum sp_event mask)
1121 enum sp_event *new_masks;
1123 TRACE("%p, %d, %d", event_set, handle, mask);
1125 if (!(new_handles = realloc(event_set->handles,
1126 sizeof(event_handle) * (event_set->count + 1))))
1127 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1129 if (!(new_masks = realloc(event_set->masks,
1130 sizeof(enum sp_event) * (event_set->count + 1))))
1131 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1133 event_set->handles = new_handles;
1134 event_set->masks = new_masks;
1136 ((event_handle *) event_set->handles)[event_set->count] = handle;
1137 event_set->masks[event_set->count] = mask;
1144 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1145 const struct sp_port *port, enum sp_event mask)
1147 TRACE("%p, %p, %d", event_set, port, mask);
1150 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1153 RETURN_ERROR(SP_ERR_ARG, "Null port");
1155 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1156 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1162 enum sp_event handle_mask;
1163 if ((handle_mask = mask & SP_EVENT_TX_READY))
1164 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1165 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1166 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1168 TRY(add_handle(event_set, port->fd, mask));
1174 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1176 TRACE("%p", event_set);
1179 DEBUG("Null event set");
1183 DEBUG("Freeing event set");
1185 if (event_set->handles)
1186 free(event_set->handles);
1187 if (event_set->masks)
1188 free(event_set->masks);
1195 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1196 unsigned int timeout)
1198 TRACE("%p, %d", event_set, timeout);
1201 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1204 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1205 timeout ? timeout : INFINITE) == WAIT_FAILED)
1206 RETURN_FAIL("WaitForMultipleObjects() failed");
1210 struct timeval start, delta, now, end = {0, 0};
1211 int result, timeout_remaining;
1212 struct pollfd *pollfds;
1215 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1216 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1218 for (i = 0; i < event_set->count; i++) {
1219 pollfds[i].fd = ((int *) event_set->handles)[i];
1220 pollfds[i].events = 0;
1221 pollfds[i].revents = 0;
1222 if (event_set->masks[i] & SP_EVENT_RX_READY)
1223 pollfds[i].events |= POLLIN;
1224 if (event_set->masks[i] & SP_EVENT_TX_READY)
1225 pollfds[i].events |= POLLOUT;
1226 if (event_set->masks[i] & SP_EVENT_ERROR)
1227 pollfds[i].events |= POLLERR;
1231 /* Get time at start of operation. */
1232 gettimeofday(&start, NULL);
1233 /* Define duration of timeout. */
1234 delta.tv_sec = timeout / 1000;
1235 delta.tv_usec = (timeout % 1000) * 1000;
1236 /* Calculate time at which we should give up. */
1237 timeradd(&start, &delta, &end);
1240 /* Loop until an event occurs. */
1243 gettimeofday(&now, NULL);
1244 if (timercmp(&now, &end, >)) {
1245 DEBUG("Wait timed out");
1248 timersub(&end, &now, &delta);
1249 timeout_remaining = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1252 result = poll(pollfds, event_set->count, timeout ? timeout_remaining : -1);
1255 if (errno == EINTR) {
1256 DEBUG("poll() call was interrupted, repeating");
1260 RETURN_FAIL("poll() failed");
1262 } else if (result == 0) {
1263 DEBUG("poll() timed out");
1266 DEBUG("poll() completed");
1276 #ifdef USE_TERMIOS_SPEED
1277 static enum sp_return get_baudrate(int fd, int *baudrate)
1281 TRACE("%d, %p", fd, baudrate);
1283 DEBUG("Getting baud rate");
1285 if (!(data = malloc(get_termios_size())))
1286 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1288 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1290 RETURN_FAIL("Getting termios failed");
1293 *baudrate = get_termios_speed(data);
1300 static enum sp_return set_baudrate(int fd, int baudrate)
1304 TRACE("%d, %d", fd, baudrate);
1306 DEBUG("Getting baud rate");
1308 if (!(data = malloc(get_termios_size())))
1309 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1311 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1313 RETURN_FAIL("Getting termios failed");
1316 DEBUG("Setting baud rate");
1318 set_termios_speed(data, baudrate);
1320 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1322 RETURN_FAIL("Setting termios failed");
1329 #endif /* USE_TERMIOS_SPEED */
1332 static enum sp_return get_flow(int fd, struct port_data *data)
1336 TRACE("%d, %p", fd, data);
1338 DEBUG("Getting advanced flow control");
1340 if (!(termx = malloc(get_termiox_size())))
1341 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1343 if (ioctl(fd, TCGETX, termx) < 0) {
1345 RETURN_FAIL("Getting termiox failed");
1348 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1349 &data->dtr_flow, &data->dsr_flow);
1356 static enum sp_return set_flow(int fd, struct port_data *data)
1360 TRACE("%d, %p", fd, data);
1362 DEBUG("Getting advanced flow control");
1364 if (!(termx = malloc(get_termiox_size())))
1365 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1367 if (ioctl(fd, TCGETX, termx) < 0) {
1369 RETURN_FAIL("Getting termiox failed");
1372 DEBUG("Setting advanced flow control");
1374 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1375 data->dtr_flow, data->dsr_flow);
1377 if (ioctl(fd, TCSETX, termx) < 0) {
1379 RETURN_FAIL("Setting termiox failed");
1386 #endif /* USE_TERMIOX */
1388 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1389 struct sp_port_config *config)
1393 TRACE("%p, %p, %p", port, data, config);
1395 DEBUG_FMT("Getting configuration for port %s", port->name);
1398 if (!GetCommState(port->hdl, &data->dcb))
1399 RETURN_FAIL("GetCommState() failed");
1401 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1402 if (data->dcb.BaudRate == std_baudrates[i].index) {
1403 config->baudrate = std_baudrates[i].value;
1408 if (i == NUM_STD_BAUDRATES)
1409 /* BaudRate field can be either an index or a custom baud rate. */
1410 config->baudrate = data->dcb.BaudRate;
1412 config->bits = data->dcb.ByteSize;
1414 if (data->dcb.fParity)
1415 switch (data->dcb.Parity) {
1417 config->parity = SP_PARITY_NONE;
1420 config->parity = SP_PARITY_ODD;
1423 config->parity = SP_PARITY_EVEN;
1426 config->parity = SP_PARITY_MARK;
1429 config->parity = SP_PARITY_SPACE;
1432 config->parity = -1;
1435 config->parity = SP_PARITY_NONE;
1437 switch (data->dcb.StopBits) {
1439 config->stopbits = 1;
1442 config->stopbits = 2;
1445 config->stopbits = -1;
1448 switch (data->dcb.fRtsControl) {
1449 case RTS_CONTROL_DISABLE:
1450 config->rts = SP_RTS_OFF;
1452 case RTS_CONTROL_ENABLE:
1453 config->rts = SP_RTS_ON;
1455 case RTS_CONTROL_HANDSHAKE:
1456 config->rts = SP_RTS_FLOW_CONTROL;
1462 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1464 switch (data->dcb.fDtrControl) {
1465 case DTR_CONTROL_DISABLE:
1466 config->dtr = SP_DTR_OFF;
1468 case DTR_CONTROL_ENABLE:
1469 config->dtr = SP_DTR_ON;
1471 case DTR_CONTROL_HANDSHAKE:
1472 config->dtr = SP_DTR_FLOW_CONTROL;
1478 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1480 if (data->dcb.fInX) {
1481 if (data->dcb.fOutX)
1482 config->xon_xoff = SP_XONXOFF_INOUT;
1484 config->xon_xoff = SP_XONXOFF_IN;
1486 if (data->dcb.fOutX)
1487 config->xon_xoff = SP_XONXOFF_OUT;
1489 config->xon_xoff = SP_XONXOFF_DISABLED;
1494 if (tcgetattr(port->fd, &data->term) < 0)
1495 RETURN_FAIL("tcgetattr() failed");
1497 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1498 RETURN_FAIL("TIOCMGET ioctl failed");
1501 int ret = get_flow(port->fd, data);
1503 if (ret == SP_ERR_FAIL && errno == EINVAL)
1504 data->termiox_supported = 0;
1506 RETURN_CODEVAL(ret);
1508 data->termiox_supported = 1;
1510 data->termiox_supported = 0;
1513 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1514 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1515 config->baudrate = std_baudrates[i].value;
1520 if (i == NUM_STD_BAUDRATES) {
1522 config->baudrate = (int)data->term.c_ispeed;
1523 #elif defined(USE_TERMIOS_SPEED)
1524 TRY(get_baudrate(port->fd, &config->baudrate));
1526 config->baudrate = -1;
1530 switch (data->term.c_cflag & CSIZE) {
1547 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1548 config->parity = SP_PARITY_NONE;
1549 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1550 config->parity = -1;
1552 else if (data->term.c_cflag & CMSPAR)
1553 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1556 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1558 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1560 if (data->term.c_cflag & CRTSCTS) {
1561 config->rts = SP_RTS_FLOW_CONTROL;
1562 config->cts = SP_CTS_FLOW_CONTROL;
1564 if (data->termiox_supported && data->rts_flow)
1565 config->rts = SP_RTS_FLOW_CONTROL;
1567 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1569 config->cts = (data->termiox_supported && data->cts_flow) ?
1570 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1573 if (data->termiox_supported && data->dtr_flow)
1574 config->dtr = SP_DTR_FLOW_CONTROL;
1576 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1578 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1579 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1581 if (data->term.c_iflag & IXOFF) {
1582 if (data->term.c_iflag & IXON)
1583 config->xon_xoff = SP_XONXOFF_INOUT;
1585 config->xon_xoff = SP_XONXOFF_IN;
1587 if (data->term.c_iflag & IXON)
1588 config->xon_xoff = SP_XONXOFF_OUT;
1590 config->xon_xoff = SP_XONXOFF_DISABLED;
1597 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1598 const struct sp_port_config *config)
1602 BAUD_TYPE baud_nonstd;
1606 #ifdef USE_TERMIOS_SPEED
1607 int baud_nonstd = 0;
1610 TRACE("%p, %p, %p", port, data, config);
1612 DEBUG_FMT("Setting configuration for port %s", port->name);
1615 if (config->baudrate >= 0) {
1616 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1617 if (config->baudrate == std_baudrates[i].value) {
1618 data->dcb.BaudRate = std_baudrates[i].index;
1623 if (i == NUM_STD_BAUDRATES)
1624 data->dcb.BaudRate = config->baudrate;
1627 if (config->bits >= 0)
1628 data->dcb.ByteSize = config->bits;
1630 if (config->parity >= 0) {
1631 switch (config->parity) {
1632 case SP_PARITY_NONE:
1633 data->dcb.Parity = NOPARITY;
1636 data->dcb.Parity = ODDPARITY;
1638 case SP_PARITY_EVEN:
1639 data->dcb.Parity = EVENPARITY;
1641 case SP_PARITY_MARK:
1642 data->dcb.Parity = MARKPARITY;
1644 case SP_PARITY_SPACE:
1645 data->dcb.Parity = SPACEPARITY;
1648 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1652 if (config->stopbits >= 0) {
1653 switch (config->stopbits) {
1654 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1656 data->dcb.StopBits = ONESTOPBIT;
1659 data->dcb.StopBits = TWOSTOPBITS;
1662 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1666 if (config->rts >= 0) {
1667 switch (config->rts) {
1669 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1672 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1674 case SP_RTS_FLOW_CONTROL:
1675 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1678 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1682 if (config->cts >= 0) {
1683 switch (config->cts) {
1685 data->dcb.fOutxCtsFlow = FALSE;
1687 case SP_CTS_FLOW_CONTROL:
1688 data->dcb.fOutxCtsFlow = TRUE;
1691 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1695 if (config->dtr >= 0) {
1696 switch (config->dtr) {
1698 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1701 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1703 case SP_DTR_FLOW_CONTROL:
1704 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1707 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1711 if (config->dsr >= 0) {
1712 switch (config->dsr) {
1714 data->dcb.fOutxDsrFlow = FALSE;
1716 case SP_DSR_FLOW_CONTROL:
1717 data->dcb.fOutxDsrFlow = TRUE;
1720 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1724 if (config->xon_xoff >= 0) {
1725 switch (config->xon_xoff) {
1726 case SP_XONXOFF_DISABLED:
1727 data->dcb.fInX = FALSE;
1728 data->dcb.fOutX = FALSE;
1731 data->dcb.fInX = TRUE;
1732 data->dcb.fOutX = FALSE;
1734 case SP_XONXOFF_OUT:
1735 data->dcb.fInX = FALSE;
1736 data->dcb.fOutX = TRUE;
1738 case SP_XONXOFF_INOUT:
1739 data->dcb.fInX = TRUE;
1740 data->dcb.fOutX = TRUE;
1743 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1747 if (!SetCommState(port->hdl, &data->dcb))
1748 RETURN_FAIL("SetCommState() failed");
1754 if (config->baudrate >= 0) {
1755 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1756 if (config->baudrate == std_baudrates[i].value) {
1757 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1758 RETURN_FAIL("cfsetospeed() failed");
1760 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1761 RETURN_FAIL("cfsetispeed() failed");
1766 /* Non-standard baud rate */
1767 if (i == NUM_STD_BAUDRATES) {
1769 /* Set "dummy" baud rate. */
1770 if (cfsetspeed(&data->term, B9600) < 0)
1771 RETURN_FAIL("cfsetspeed() failed");
1772 baud_nonstd = config->baudrate;
1773 #elif defined(USE_TERMIOS_SPEED)
1776 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1781 if (config->bits >= 0) {
1782 data->term.c_cflag &= ~CSIZE;
1783 switch (config->bits) {
1785 data->term.c_cflag |= CS8;
1788 data->term.c_cflag |= CS7;
1791 data->term.c_cflag |= CS6;
1794 data->term.c_cflag |= CS5;
1797 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1801 if (config->parity >= 0) {
1802 data->term.c_iflag &= ~IGNPAR;
1803 data->term.c_cflag &= ~(PARENB | PARODD);
1805 data->term.c_cflag &= ~CMSPAR;
1807 switch (config->parity) {
1808 case SP_PARITY_NONE:
1809 data->term.c_iflag |= IGNPAR;
1811 case SP_PARITY_EVEN:
1812 data->term.c_cflag |= PARENB;
1815 data->term.c_cflag |= PARENB | PARODD;
1818 case SP_PARITY_MARK:
1819 data->term.c_cflag |= PARENB | PARODD;
1820 data->term.c_cflag |= CMSPAR;
1822 case SP_PARITY_SPACE:
1823 data->term.c_cflag |= PARENB;
1824 data->term.c_cflag |= CMSPAR;
1827 case SP_PARITY_MARK:
1828 case SP_PARITY_SPACE:
1829 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1832 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1836 if (config->stopbits >= 0) {
1837 data->term.c_cflag &= ~CSTOPB;
1838 switch (config->stopbits) {
1840 data->term.c_cflag &= ~CSTOPB;
1843 data->term.c_cflag |= CSTOPB;
1846 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1850 if (config->rts >= 0 || config->cts >= 0) {
1851 if (data->termiox_supported) {
1852 data->rts_flow = data->cts_flow = 0;
1853 switch (config->rts) {
1856 controlbits = TIOCM_RTS;
1857 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1858 RETURN_FAIL("Setting RTS signal level failed");
1860 case SP_RTS_FLOW_CONTROL:
1866 if (config->cts == SP_CTS_FLOW_CONTROL)
1869 if (data->rts_flow && data->cts_flow)
1870 data->term.c_iflag |= CRTSCTS;
1872 data->term.c_iflag &= ~CRTSCTS;
1874 /* Asymmetric use of RTS/CTS not supported. */
1875 if (data->term.c_iflag & CRTSCTS) {
1876 /* Flow control can only be disabled for both RTS & CTS together. */
1877 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1878 if (config->cts != SP_CTS_IGNORE)
1879 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1881 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1882 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1883 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1886 /* Flow control can only be enabled for both RTS & CTS together. */
1887 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1888 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1889 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1892 if (config->rts >= 0) {
1893 if (config->rts == SP_RTS_FLOW_CONTROL) {
1894 data->term.c_iflag |= CRTSCTS;
1896 controlbits = TIOCM_RTS;
1897 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1899 RETURN_FAIL("Setting RTS signal level failed");
1905 if (config->dtr >= 0 || config->dsr >= 0) {
1906 if (data->termiox_supported) {
1907 data->dtr_flow = data->dsr_flow = 0;
1908 switch (config->dtr) {
1911 controlbits = TIOCM_DTR;
1912 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1913 RETURN_FAIL("Setting DTR signal level failed");
1915 case SP_DTR_FLOW_CONTROL:
1921 if (config->dsr == SP_DSR_FLOW_CONTROL)
1924 /* DTR/DSR flow control not supported. */
1925 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1926 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1928 if (config->dtr >= 0) {
1929 controlbits = TIOCM_DTR;
1930 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1932 RETURN_FAIL("Setting DTR signal level failed");
1937 if (config->xon_xoff >= 0) {
1938 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1939 switch (config->xon_xoff) {
1940 case SP_XONXOFF_DISABLED:
1943 data->term.c_iflag |= IXOFF;
1945 case SP_XONXOFF_OUT:
1946 data->term.c_iflag |= IXON | IXANY;
1948 case SP_XONXOFF_INOUT:
1949 data->term.c_iflag |= IXON | IXOFF | IXANY;
1952 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1956 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
1957 RETURN_FAIL("tcsetattr() failed");
1960 if (baud_nonstd != B0) {
1961 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1962 RETURN_FAIL("IOSSIOSPEED ioctl failed");
1964 * Set baud rates in data->term to correct, but incompatible
1965 * with tcsetattr() value, same as delivered by tcgetattr().
1967 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1968 RETURN_FAIL("cfsetspeed() failed");
1970 #elif defined(__linux__)
1971 #ifdef USE_TERMIOS_SPEED
1973 TRY(set_baudrate(port->fd, config->baudrate));
1976 if (data->termiox_supported)
1977 TRY(set_flow(port->fd, data));
1981 #endif /* !_WIN32 */
1986 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
1988 struct sp_port_config *config;
1990 TRACE("%p", config_ptr);
1993 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1997 if (!(config = malloc(sizeof(struct sp_port_config))))
1998 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2000 config->baudrate = -1;
2002 config->parity = -1;
2003 config->stopbits = -1;
2009 *config_ptr = config;
2014 SP_API void sp_free_config(struct sp_port_config *config)
2016 TRACE("%p", config);
2019 DEBUG("Null config");
2026 SP_API enum sp_return sp_get_config(struct sp_port *port,
2027 struct sp_port_config *config)
2029 struct port_data data;
2031 TRACE("%p, %p", port, config);
2036 RETURN_ERROR(SP_ERR_ARG, "Null config");
2038 TRY(get_config(port, &data, config));
2043 SP_API enum sp_return sp_set_config(struct sp_port *port,
2044 const struct sp_port_config *config)
2046 struct port_data data;
2047 struct sp_port_config prev_config;
2049 TRACE("%p, %p", port, config);
2054 RETURN_ERROR(SP_ERR_ARG, "Null config");
2056 TRY(get_config(port, &data, &prev_config));
2057 TRY(set_config(port, &data, config));
2062 #define CREATE_ACCESSORS(x, type) \
2063 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2064 struct port_data data; \
2065 struct sp_port_config config; \
2066 TRACE("%p, %d", port, x); \
2067 CHECK_OPEN_PORT(); \
2068 TRY(get_config(port, &data, &config)); \
2070 TRY(set_config(port, &data, &config)); \
2073 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2075 TRACE("%p, %p", config, x); \
2077 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2081 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2083 TRACE("%p, %d", config, x); \
2085 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2090 CREATE_ACCESSORS(baudrate, int)
2091 CREATE_ACCESSORS(bits, int)
2092 CREATE_ACCESSORS(parity, enum sp_parity)
2093 CREATE_ACCESSORS(stopbits, int)
2094 CREATE_ACCESSORS(rts, enum sp_rts)
2095 CREATE_ACCESSORS(cts, enum sp_cts)
2096 CREATE_ACCESSORS(dtr, enum sp_dtr)
2097 CREATE_ACCESSORS(dsr, enum sp_dsr)
2098 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2100 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2101 enum sp_flowcontrol flowcontrol)
2104 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2106 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2107 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2109 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2110 config->xon_xoff = SP_XONXOFF_INOUT;
2112 config->xon_xoff = SP_XONXOFF_DISABLED;
2114 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2115 config->rts = SP_RTS_FLOW_CONTROL;
2116 config->cts = SP_CTS_FLOW_CONTROL;
2118 if (config->rts == SP_RTS_FLOW_CONTROL)
2119 config->rts = SP_RTS_ON;
2120 config->cts = SP_CTS_IGNORE;
2123 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2124 config->dtr = SP_DTR_FLOW_CONTROL;
2125 config->dsr = SP_DSR_FLOW_CONTROL;
2127 if (config->dtr == SP_DTR_FLOW_CONTROL)
2128 config->dtr = SP_DTR_ON;
2129 config->dsr = SP_DSR_IGNORE;
2135 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2136 enum sp_flowcontrol flowcontrol)
2138 struct port_data data;
2139 struct sp_port_config config;
2141 TRACE("%p, %d", port, flowcontrol);
2145 TRY(get_config(port, &data, &config));
2147 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2149 TRY(set_config(port, &data, &config));
2154 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2155 enum sp_signal *signals)
2157 TRACE("%p, %p", port, signals);
2162 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2164 DEBUG_FMT("Getting control signals for port %s", port->name);
2169 if (GetCommModemStatus(port->hdl, &bits) == 0)
2170 RETURN_FAIL("GetCommModemStatus() failed");
2171 if (bits & MS_CTS_ON)
2172 *signals |= SP_SIG_CTS;
2173 if (bits & MS_DSR_ON)
2174 *signals |= SP_SIG_DSR;
2175 if (bits & MS_RLSD_ON)
2176 *signals |= SP_SIG_DCD;
2177 if (bits & MS_RING_ON)
2178 *signals |= SP_SIG_RI;
2181 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2182 RETURN_FAIL("TIOCMGET ioctl failed");
2183 if (bits & TIOCM_CTS)
2184 *signals |= SP_SIG_CTS;
2185 if (bits & TIOCM_DSR)
2186 *signals |= SP_SIG_DSR;
2187 if (bits & TIOCM_CAR)
2188 *signals |= SP_SIG_DCD;
2189 if (bits & TIOCM_RNG)
2190 *signals |= SP_SIG_RI;
2195 SP_API enum sp_return sp_start_break(struct sp_port *port)
2201 if (SetCommBreak(port->hdl) == 0)
2202 RETURN_FAIL("SetCommBreak() failed");
2204 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2205 RETURN_FAIL("TIOCSBRK ioctl failed");
2211 SP_API enum sp_return sp_end_break(struct sp_port *port)
2217 if (ClearCommBreak(port->hdl) == 0)
2218 RETURN_FAIL("ClearCommBreak() failed");
2220 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2221 RETURN_FAIL("TIOCCBRK ioctl failed");
2227 SP_API int sp_last_error_code(void)
2231 RETURN_INT(GetLastError());
2237 SP_API char *sp_last_error_message(void)
2243 DWORD error = GetLastError();
2246 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2247 FORMAT_MESSAGE_FROM_SYSTEM |
2248 FORMAT_MESSAGE_IGNORE_INSERTS,
2251 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2255 RETURN_STRING(message);
2257 RETURN_STRING(strerror(errno));
2261 SP_API void sp_free_error_message(char *message)
2263 TRACE("%s", message);
2274 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2276 TRACE("%p", handler);
2278 sp_debug_handler = handler;
2283 SP_API void sp_default_debug_handler(const char *format, ...)
2286 va_start(args, format);
2287 if (getenv("LIBSERIALPORT_DEBUG")) {
2288 fputs("sp: ", stderr);
2289 vfprintf(stderr, format, args);
2294 SP_API int sp_get_major_package_version(void)
2296 return SP_PACKAGE_VERSION_MAJOR;
2299 SP_API int sp_get_minor_package_version(void)
2301 return SP_PACKAGE_VERSION_MINOR;
2304 SP_API int sp_get_micro_package_version(void)
2306 return SP_PACKAGE_VERSION_MICRO;
2309 SP_API const char *sp_get_package_version_string(void)
2311 return SP_PACKAGE_VERSION_STRING;
2314 SP_API int sp_get_current_lib_version(void)
2316 return SP_LIB_VERSION_CURRENT;
2319 SP_API int sp_get_revision_lib_version(void)
2321 return SP_LIB_VERSION_REVISION;
2324 SP_API int sp_get_age_lib_version(void)
2326 return SP_LIB_VERSION_AGE;
2329 SP_API const char *sp_get_lib_version_string(void)
2331 return SP_LIB_VERSION_STRING;