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 enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
61 TRACE("%s, %p", portname, port_ptr);
64 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
69 RETURN_ERROR(SP_ERR_ARG, "Null port name");
71 DEBUG("Building structure for port %s", portname);
73 if (!(port = malloc(sizeof(struct sp_port))))
74 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
76 len = strlen(portname) + 1;
78 if (!(port->name = malloc(len))) {
80 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
83 memcpy(port->name, portname, len);
86 port->hdl = INVALID_HANDLE_VALUE;
91 port->description = NULL;
92 port->transport = SP_TRANSPORT_NATIVE;
94 port->usb_address = -1;
97 port->usb_manufacturer = NULL;
98 port->usb_product = NULL;
99 port->usb_serial = NULL;
100 port->bluetooth_address = NULL;
102 #ifndef NO_PORT_METADATA
103 if ((ret = get_port_details(port)) != SP_OK) {
114 char *sp_get_port_name(const struct sp_port *port)
121 RETURN_VALUE("%s", port->name);
124 char *sp_get_port_description(struct sp_port *port)
128 if (!port || !port->description)
131 RETURN_VALUE("%s", port->description);
134 enum sp_transport sp_get_port_transport(struct sp_port *port)
139 RETURN_ERROR(SP_ERR_ARG, "Null port");
141 RETURN_VALUE("%d", port->transport);
144 enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
145 int *usb_bus, int *usb_address)
150 RETURN_ERROR(SP_ERR_ARG, "Null port");
151 if (port->transport != SP_TRANSPORT_USB)
152 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
153 if (port->usb_bus < 0 || port->usb_address < 0)
154 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
156 if (usb_bus) *usb_bus = port->usb_bus;
157 if (usb_address) *usb_address = port->usb_address;
162 enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
163 int *usb_vid, int *usb_pid)
168 RETURN_ERROR(SP_ERR_ARG, "Null port");
169 if (port->transport != SP_TRANSPORT_USB)
170 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
171 if (port->usb_vid < 0 || port->usb_pid < 0)
172 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
174 if (usb_vid) *usb_vid = port->usb_vid;
175 if (usb_pid) *usb_pid = port->usb_pid;
180 char *sp_get_port_usb_manufacturer(const struct sp_port *port)
184 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
187 RETURN_VALUE("%s", port->usb_manufacturer);
190 char *sp_get_port_usb_product(const struct sp_port *port)
194 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
197 RETURN_VALUE("%s", port->usb_product);
200 char *sp_get_port_usb_serial(const struct sp_port *port)
204 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
207 RETURN_VALUE("%s", port->usb_serial);
210 char *sp_get_port_bluetooth_address(const struct sp_port *port)
214 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
215 || !port->bluetooth_address)
218 RETURN_VALUE("%s", port->bluetooth_address);
221 enum sp_return sp_get_port_handle(const struct sp_port *port, void *result_ptr)
223 TRACE("%p, %p", port, result_ptr);
226 RETURN_ERROR(SP_ERR_ARG, "Null port");
229 HANDLE *handle_ptr = result_ptr;
230 *handle_ptr = port->hdl;
232 int *fd_ptr = result_ptr;
239 enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
241 TRACE("%p, %p", port, copy_ptr);
244 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
249 RETURN_ERROR(SP_ERR_ARG, "Null port");
252 RETURN_ERROR(SP_ERR_ARG, "Null port name");
254 DEBUG("Copying port structure");
256 RETURN_VALUE("%p", sp_get_port_by_name(port->name, copy_ptr));
259 void sp_free_port(struct sp_port *port)
268 DEBUG("Freeing port structure");
272 if (port->description)
273 free(port->description);
274 if (port->usb_manufacturer)
275 free(port->usb_manufacturer);
276 if (port->usb_product)
277 free(port->usb_product);
278 if (port->usb_serial)
279 free(port->usb_serial);
280 if (port->bluetooth_address)
281 free(port->bluetooth_address);
284 free(port->usb_path);
292 struct sp_port **list_append(struct sp_port **list, const char *portname)
297 for (count = 0; list[count]; count++);
298 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
301 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
303 list[count + 1] = NULL;
307 sp_free_port_list(list);
311 enum sp_return sp_list_ports(struct sp_port ***list_ptr)
313 struct sp_port **list;
316 TRACE("%p", list_ptr);
319 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
321 DEBUG("Enumerating ports");
323 if (!(list = malloc(sizeof(struct sp_port **))))
324 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
328 #ifdef NO_ENUMERATION
331 ret = list_ports(&list);
339 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
342 sp_free_port_list(list);
348 void sp_free_port_list(struct sp_port **list)
359 DEBUG("Freeing port list");
361 for (i = 0; list[i]; i++)
362 sp_free_port(list[i]);
368 #define CHECK_PORT() do { \
370 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
371 if (port->name == NULL) \
372 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
375 #define CHECK_PORT_HANDLE() do { \
376 if (port->hdl == INVALID_HANDLE_VALUE) \
377 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
380 #define CHECK_PORT_HANDLE() do { \
382 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
385 #define CHECK_OPEN_PORT() do { \
387 CHECK_PORT_HANDLE(); \
390 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
392 struct port_data data;
393 struct sp_port_config config;
396 TRACE("%p, 0x%x", port, flags);
400 if (flags > (SP_MODE_READ | SP_MODE_WRITE))
401 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
403 DEBUG("Opening port %s", port->name);
406 DWORD desired_access = 0, flags_and_attributes = 0, errors;
407 char *escaped_port_name;
410 /* Prefix port name with '\\.\' to work with ports above COM9. */
411 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
412 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
413 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
415 /* Map 'flags' to the OS-specific settings. */
416 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
417 if (flags & SP_MODE_READ)
418 desired_access |= GENERIC_READ;
419 if (flags & SP_MODE_WRITE)
420 desired_access |= GENERIC_WRITE;
422 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
423 OPEN_EXISTING, flags_and_attributes, 0);
425 free(escaped_port_name);
427 if (port->hdl == INVALID_HANDLE_VALUE)
428 RETURN_FAIL("port CreateFile() failed");
430 /* All timeouts initially disabled. */
431 port->timeouts.ReadIntervalTimeout = 0;
432 port->timeouts.ReadTotalTimeoutMultiplier = 0;
433 port->timeouts.ReadTotalTimeoutConstant = 0;
434 port->timeouts.WriteTotalTimeoutMultiplier = 0;
435 port->timeouts.WriteTotalTimeoutConstant = 0;
437 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
439 RETURN_FAIL("SetCommTimeouts() failed");
442 /* Prepare OVERLAPPED structures. */
443 #define INIT_OVERLAPPED(ovl) do { \
444 memset(&port->ovl, 0, sizeof(port->ovl)); \
445 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
446 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
447 == INVALID_HANDLE_VALUE) { \
449 RETURN_FAIL(#ovl "CreateEvent() failed"); \
453 INIT_OVERLAPPED(read_ovl);
454 INIT_OVERLAPPED(write_ovl);
455 INIT_OVERLAPPED(wait_ovl);
457 /* Set event mask for RX and error events. */
458 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
460 RETURN_FAIL("SetCommMask() failed");
463 /* Start background operation for RX and error events. */
464 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
465 if (GetLastError() != ERROR_IO_PENDING) {
467 RETURN_FAIL("WaitCommEvent() failed");
471 port->writing = FALSE;
474 int flags_local = O_NONBLOCK | O_NOCTTY;
476 /* Map 'flags' to the OS-specific settings. */
477 if (flags & (SP_MODE_READ | SP_MODE_WRITE))
478 flags_local |= O_RDWR;
479 else if (flags & SP_MODE_READ)
480 flags_local |= O_RDONLY;
481 else if (flags & SP_MODE_WRITE)
482 flags_local |= O_WRONLY;
484 if ((port->fd = open(port->name, flags_local)) < 0)
485 RETURN_FAIL("open() failed");
488 ret = get_config(port, &data, &config);
495 /* Set sane port settings. */
497 data.dcb.fBinary = TRUE;
498 data.dcb.fDsrSensitivity = FALSE;
499 data.dcb.fErrorChar = FALSE;
500 data.dcb.fNull = FALSE;
501 data.dcb.fAbortOnError = TRUE;
503 /* Turn off all fancy termios tricks, give us a raw channel. */
504 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
506 data.term.c_iflag &= ~IUCLC;
508 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
510 data.term.c_oflag &= ~OLCUC;
513 data.term.c_oflag &= ~NLDLY;
516 data.term.c_oflag &= ~CRDLY;
519 data.term.c_oflag &= ~TABDLY;
522 data.term.c_oflag &= ~BSDLY;
525 data.term.c_oflag &= ~VTDLY;
528 data.term.c_oflag &= ~FFDLY;
531 data.term.c_oflag &= ~OFILL;
533 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
534 data.term.c_cc[VMIN] = 0;
535 data.term.c_cc[VTIME] = 0;
537 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
538 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
542 if (ClearCommError(port->hdl, &errors, &status) == 0)
543 RETURN_FAIL("ClearCommError() failed");
546 ret = set_config(port, &data, &config);
556 enum sp_return sp_close(struct sp_port *port)
562 DEBUG("Closing port %s", port->name);
565 /* Returns non-zero upon success, 0 upon failure. */
566 if (CloseHandle(port->hdl) == 0)
567 RETURN_FAIL("port CloseHandle() failed");
568 port->hdl = INVALID_HANDLE_VALUE;
570 /* Close event handles for overlapped structures. */
571 #define CLOSE_OVERLAPPED(ovl) do { \
572 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
573 CloseHandle(port->ovl.hEvent) == 0) \
574 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
576 CLOSE_OVERLAPPED(read_ovl);
577 CLOSE_OVERLAPPED(write_ovl);
578 CLOSE_OVERLAPPED(wait_ovl);
581 /* Returns 0 upon success, -1 upon failure. */
582 if (close(port->fd) == -1)
583 RETURN_FAIL("close() failed");
590 enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
592 TRACE("%p, 0x%x", port, buffers);
596 if (buffers > SP_BUF_BOTH)
597 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
599 const char *buffer_names[] = {"no", "input", "output", "both"};
601 DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
605 if (buffers & SP_BUF_INPUT)
606 flags |= PURGE_RXCLEAR;
607 if (buffers & SP_BUF_OUTPUT)
608 flags |= PURGE_TXCLEAR;
610 /* Returns non-zero upon success, 0 upon failure. */
611 if (PurgeComm(port->hdl, flags) == 0)
612 RETURN_FAIL("PurgeComm() failed");
615 if (buffers & SP_BUF_BOTH)
617 else if (buffers & SP_BUF_INPUT)
619 else if (buffers & SP_BUF_OUTPUT)
622 /* Returns 0 upon success, -1 upon failure. */
623 if (tcflush(port->fd, flags) < 0)
624 RETURN_FAIL("tcflush() failed");
629 enum sp_return sp_drain(struct sp_port *port)
635 DEBUG("Draining port %s", port->name);
638 /* Returns non-zero upon success, 0 upon failure. */
639 if (FlushFileBuffers(port->hdl) == 0)
640 RETURN_FAIL("FlushFileBuffers() failed");
647 result = ioctl(port->fd, TCSBRK, &arg);
649 result = tcdrain(port->fd);
652 if (errno == EINTR) {
653 DEBUG("tcdrain() was interrupted");
656 RETURN_FAIL("tcdrain() failed");
665 enum sp_return sp_blocking_write(struct sp_port *port, const void *buf, size_t count, unsigned int timeout)
667 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
672 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
675 DEBUG("Writing %d bytes to port %s, timeout %d ms", count, port->name, timeout);
677 DEBUG("Writing %d bytes to port %s, no timeout", count, port->name);
680 RETURN_VALUE("0", 0);
683 DWORD bytes_written = 0;
686 /* Wait for previous non-blocking write to complete, if any. */
688 DEBUG("Waiting for previous write to complete");
689 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
692 RETURN_FAIL("Previous write failed to complete");
693 DEBUG("Previous write completed");
697 port->timeouts.WriteTotalTimeoutConstant = timeout;
698 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
699 RETURN_FAIL("SetCommTimeouts() failed");
702 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) {
703 if (GetLastError() == ERROR_IO_PENDING) {
704 DEBUG("Waiting for write to complete");
705 GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
706 DEBUG("Write completed, %d/%d bytes written", bytes_written, count);
707 RETURN_VALUE("%d", bytes_written);
709 RETURN_FAIL("WriteFile() failed");
712 DEBUG("Write completed immediately");
713 RETURN_VALUE("%d", count);
716 size_t bytes_written = 0;
717 unsigned char *ptr = (unsigned char *) buf;
718 struct timeval start, delta, now, end = {0, 0};
723 /* Get time at start of operation. */
724 gettimeofday(&start, NULL);
725 /* Define duration of timeout. */
726 delta.tv_sec = timeout / 1000;
727 delta.tv_usec = (timeout % 1000) * 1000;
728 /* Calculate time at which we should give up. */
729 timeradd(&start, &delta, &end);
732 /* Loop until we have written the requested number of bytes. */
733 while (bytes_written < count)
735 /* Wait until space is available. */
737 FD_SET(port->fd, &fds);
739 gettimeofday(&now, NULL);
740 if (timercmp(&now, &end, >)) {
741 DEBUG("write timed out");
742 RETURN_VALUE("%d", bytes_written);
744 timersub(&end, &now, &delta);
746 result = select(port->fd + 1, NULL, &fds, NULL, timeout ? &delta : NULL);
748 if (errno == EINTR) {
749 DEBUG("select() call was interrupted, repeating");
752 RETURN_FAIL("select() failed");
754 } else if (result == 0) {
755 DEBUG("write timed out");
756 RETURN_VALUE("%d", bytes_written);
760 result = write(port->fd, ptr, count - bytes_written);
764 /* This shouldn't happen because we did a select() first, but handle anyway. */
767 /* This is an actual failure. */
768 RETURN_FAIL("write() failed");
771 bytes_written += result;
775 RETURN_VALUE("%d", bytes_written);
779 enum sp_return sp_nonblocking_write(struct sp_port *port, const void *buf, size_t count)
781 TRACE("%p, %p, %d", port, buf, count);
786 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
788 DEBUG("Writing up to %d bytes to port %s", count, port->name);
791 RETURN_VALUE("0", 0);
795 BYTE *ptr = (BYTE *) buf;
797 /* Check whether previous write is complete. */
799 if (HasOverlappedIoCompleted(&port->write_ovl)) {
800 DEBUG("Previous write completed");
803 DEBUG("Previous write not complete");
804 /* Can't take a new write until the previous one finishes. */
805 RETURN_VALUE("0", 0);
810 port->timeouts.WriteTotalTimeoutConstant = 0;
811 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
812 RETURN_FAIL("SetCommTimeouts() failed");
814 /* Keep writing data until the OS has to actually start an async IO for it.
815 * At that point we know the buffer is full. */
816 while (written < count)
818 /* Copy first byte of user buffer. */
819 port->pending_byte = *ptr++;
821 /* Start asynchronous write. */
822 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
823 if (GetLastError() == ERROR_IO_PENDING) {
824 if (HasOverlappedIoCompleted(&port->write_ovl)) {
825 DEBUG("Asynchronous write completed immediately");
830 DEBUG("Asynchronous write running");
832 RETURN_VALUE("%d", ++written);
835 /* Actual failure of some kind. */
836 RETURN_FAIL("WriteFile() failed");
839 DEBUG("Single byte written immediately");
844 DEBUG("All bytes written immediately");
846 RETURN_VALUE("%d", written);
848 /* Returns the number of bytes written, or -1 upon failure. */
849 ssize_t written = write(port->fd, buf, count);
852 RETURN_FAIL("write() failed");
854 RETURN_VALUE("%d", written);
858 enum sp_return sp_blocking_read(struct sp_port *port, void *buf, size_t count, unsigned int timeout)
860 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
865 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
868 DEBUG("Reading %d bytes from port %s, timeout %d ms", count, port->name, timeout);
870 DEBUG("Reading %d bytes from port %s, no timeout", count, port->name);
873 RETURN_VALUE("0", 0);
876 DWORD bytes_read = 0;
879 port->timeouts.ReadIntervalTimeout = 0;
880 port->timeouts.ReadTotalTimeoutConstant = timeout;
881 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
882 RETURN_FAIL("SetCommTimeouts() failed");
885 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) {
886 if (GetLastError() == ERROR_IO_PENDING) {
887 DEBUG("Waiting for read to complete");
888 GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
889 DEBUG("Read completed, %d/%d bytes read", bytes_read, count);
891 RETURN_FAIL("ReadFile() failed");
894 DEBUG("Read completed immediately");
898 /* Start background operation for subsequent events. */
899 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
900 if (GetLastError() != ERROR_IO_PENDING)
901 RETURN_FAIL("WaitCommEvent() failed");
904 RETURN_VALUE("%d", bytes_read);
907 size_t bytes_read = 0;
908 unsigned char *ptr = (unsigned char *) buf;
909 struct timeval start, delta, now, end = {0, 0};
914 /* Get time at start of operation. */
915 gettimeofday(&start, NULL);
916 /* Define duration of timeout. */
917 delta.tv_sec = timeout / 1000;
918 delta.tv_usec = (timeout % 1000) * 1000;
919 /* Calculate time at which we should give up. */
920 timeradd(&start, &delta, &end);
923 /* Loop until we have the requested number of bytes. */
924 while (bytes_read < count)
926 /* Wait until data is available. */
928 FD_SET(port->fd, &fds);
930 gettimeofday(&now, NULL);
931 if (timercmp(&now, &end, >))
932 /* Timeout has expired. */
933 RETURN_VALUE("%d", bytes_read);
934 timersub(&end, &now, &delta);
936 result = select(port->fd + 1, &fds, NULL, NULL, timeout ? &delta : NULL);
938 if (errno == EINTR) {
939 DEBUG("select() call was interrupted, repeating");
942 RETURN_FAIL("select() failed");
944 } else if (result == 0) {
945 DEBUG("read timed out");
946 RETURN_VALUE("%d", bytes_read);
950 result = read(port->fd, ptr, count - bytes_read);
954 /* This shouldn't happen because we did a select() first, but handle anyway. */
957 /* This is an actual failure. */
958 RETURN_FAIL("read() failed");
961 bytes_read += result;
965 RETURN_VALUE("%d", bytes_read);
969 enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf, size_t count)
971 TRACE("%p, %p, %d", port, buf, count);
976 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
978 DEBUG("Reading up to %d bytes from port %s", count, port->name);
984 port->timeouts.ReadIntervalTimeout = MAXDWORD;
985 port->timeouts.ReadTotalTimeoutConstant = 0;
986 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
987 RETURN_FAIL("SetCommTimeouts() failed");
990 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
991 RETURN_FAIL("ReadFile() failed");
993 /* Get number of bytes read. */
994 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
995 RETURN_FAIL("GetOverlappedResult() failed");
997 if (bytes_read > 0) {
998 /* Start background operation for subsequent events. */
999 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
1000 if (GetLastError() != ERROR_IO_PENDING)
1001 RETURN_FAIL("WaitCommEvent() failed");
1005 RETURN_VALUE("%d", bytes_read);
1009 /* Returns the number of bytes read, or -1 upon failure. */
1010 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1011 if (errno == EAGAIN)
1012 /* No bytes available. */
1015 /* This is an actual failure. */
1016 RETURN_FAIL("read() failed");
1018 RETURN_VALUE("%d", bytes_read);
1022 enum sp_return sp_input_waiting(struct sp_port *port)
1028 DEBUG("Checking input bytes waiting on port %s", port->name);
1034 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1035 RETURN_FAIL("ClearCommError() failed");
1036 RETURN_VALUE("%d", comstat.cbInQue);
1039 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1040 RETURN_FAIL("TIOCINQ ioctl failed");
1041 RETURN_VALUE("%d", bytes_waiting);
1045 enum sp_return sp_output_waiting(struct sp_port *port)
1051 DEBUG("Checking output bytes waiting on port %s", port->name);
1057 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1058 RETURN_FAIL("ClearCommError() failed");
1059 RETURN_VALUE("%d", comstat.cbOutQue);
1062 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1063 RETURN_FAIL("TIOCOUTQ ioctl failed");
1064 RETURN_VALUE("%d", bytes_waiting);
1068 enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1070 struct sp_event_set *result;
1072 TRACE("%p", result_ptr);
1075 RETURN_ERROR(SP_ERR_ARG, "Null result");
1079 if (!(result = malloc(sizeof(struct sp_event_set))))
1080 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1082 memset(result, 0, sizeof(struct sp_event_set));
1084 *result_ptr = result;
1089 static enum sp_return add_handle(struct sp_event_set *event_set,
1090 event_handle handle, enum sp_event mask)
1093 enum sp_event *new_masks;
1095 TRACE("%p, %d, %d", event_set, handle, mask);
1097 if (!(new_handles = realloc(event_set->handles,
1098 sizeof(event_handle) * (event_set->count + 1))))
1099 RETURN_ERROR(SP_ERR_MEM, "handle array realloc() failed");
1101 if (!(new_masks = realloc(event_set->masks,
1102 sizeof(enum sp_event) * (event_set->count + 1))))
1103 RETURN_ERROR(SP_ERR_MEM, "mask array realloc() failed");
1105 event_set->handles = new_handles;
1106 event_set->masks = new_masks;
1108 ((event_handle *) event_set->handles)[event_set->count] = handle;
1109 event_set->masks[event_set->count] = mask;
1116 enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1117 const struct sp_port *port, enum sp_event mask)
1119 TRACE("%p, %p, %d", event_set, port, mask);
1122 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1125 RETURN_ERROR(SP_ERR_ARG, "Null port");
1127 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1128 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1134 enum sp_event handle_mask;
1135 if ((handle_mask = mask & SP_EVENT_TX_READY))
1136 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1137 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1138 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1140 TRY(add_handle(event_set, port->fd, mask));
1146 void sp_free_event_set(struct sp_event_set *event_set)
1148 TRACE("%p", event_set);
1151 DEBUG("Null event set");
1155 DEBUG("Freeing event set");
1157 if (event_set->handles)
1158 free(event_set->handles);
1159 if (event_set->masks)
1160 free(event_set->masks);
1167 enum sp_return sp_wait(struct sp_event_set *event_set, unsigned int timeout)
1169 TRACE("%p, %d", event_set, timeout);
1172 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1175 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1176 timeout ? timeout : INFINITE) == WAIT_FAILED)
1177 RETURN_FAIL("WaitForMultipleObjects() failed");
1181 struct timeval start, delta, now, end = {0, 0};
1182 int result, timeout_remaining;
1183 struct pollfd *pollfds;
1186 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1187 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1189 for (i = 0; i < event_set->count; i++) {
1190 pollfds[i].fd = ((int *) event_set->handles)[i];
1191 pollfds[i].events = 0;
1192 pollfds[i].revents = 0;
1193 if (event_set->masks[i] & SP_EVENT_RX_READY)
1194 pollfds[i].events |= POLLIN;
1195 if (event_set->masks[i] & SP_EVENT_TX_READY)
1196 pollfds[i].events |= POLLOUT;
1197 if (event_set->masks[i] & SP_EVENT_ERROR)
1198 pollfds[i].events |= POLLERR;
1202 /* Get time at start of operation. */
1203 gettimeofday(&start, NULL);
1204 /* Define duration of timeout. */
1205 delta.tv_sec = timeout / 1000;
1206 delta.tv_usec = (timeout % 1000) * 1000;
1207 /* Calculate time at which we should give up. */
1208 timeradd(&start, &delta, &end);
1211 /* Loop until an event occurs. */
1215 gettimeofday(&now, NULL);
1216 if (timercmp(&now, &end, >)) {
1217 DEBUG("wait timed out");
1220 timersub(&end, &now, &delta);
1221 timeout_remaining = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1224 result = poll(pollfds, event_set->count, timeout ? timeout_remaining : -1);
1227 if (errno == EINTR) {
1228 DEBUG("poll() call was interrupted, repeating");
1232 RETURN_FAIL("poll() failed");
1234 } else if (result == 0) {
1235 DEBUG("poll() timed out");
1238 DEBUG("poll() completed");
1248 #ifdef USE_TERMIOS_SPEED
1249 static enum sp_return get_baudrate(int fd, int *baudrate)
1253 TRACE("%d, %p", fd, baudrate);
1255 DEBUG("Getting baud rate");
1257 if (!(data = malloc(get_termios_size())))
1258 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1260 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1262 RETURN_FAIL("getting termios failed");
1265 *baudrate = get_termios_speed(data);
1272 static enum sp_return set_baudrate(int fd, int baudrate)
1276 TRACE("%d, %d", fd, baudrate);
1278 DEBUG("Getting baud rate");
1280 if (!(data = malloc(get_termios_size())))
1281 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1283 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1285 RETURN_FAIL("getting termios failed");
1288 DEBUG("Setting baud rate");
1290 set_termios_speed(data, baudrate);
1292 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1294 RETURN_FAIL("setting termios failed");
1301 #endif /* USE_TERMIOS_SPEED */
1304 static enum sp_return get_flow(int fd, struct port_data *data)
1308 TRACE("%d, %p", fd, data);
1310 DEBUG("Getting advanced flow control");
1312 if (!(termx = malloc(get_termiox_size())))
1313 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1315 if (ioctl(fd, TCGETX, termx) < 0) {
1317 RETURN_FAIL("getting termiox failed");
1320 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1321 &data->dtr_flow, &data->dsr_flow);
1328 static enum sp_return set_flow(int fd, struct port_data *data)
1332 TRACE("%d, %p", fd, data);
1334 DEBUG("Getting advanced flow control");
1336 if (!(termx = malloc(get_termiox_size())))
1337 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1339 if (ioctl(fd, TCGETX, termx) < 0) {
1341 RETURN_FAIL("getting termiox failed");
1344 DEBUG("Setting advanced flow control");
1346 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1347 data->dtr_flow, data->dsr_flow);
1349 if (ioctl(fd, TCSETX, termx) < 0) {
1351 RETURN_FAIL("setting termiox failed");
1358 #endif /* USE_TERMIOX */
1360 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1361 struct sp_port_config *config)
1365 TRACE("%p, %p, %p", port, data, config);
1367 DEBUG("Getting configuration for port %s", port->name);
1370 if (!GetCommState(port->hdl, &data->dcb))
1371 RETURN_FAIL("GetCommState() failed");
1373 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1374 if (data->dcb.BaudRate == std_baudrates[i].index) {
1375 config->baudrate = std_baudrates[i].value;
1380 if (i == NUM_STD_BAUDRATES)
1381 /* BaudRate field can be either an index or a custom baud rate. */
1382 config->baudrate = data->dcb.BaudRate;
1384 config->bits = data->dcb.ByteSize;
1386 if (data->dcb.fParity)
1387 switch (data->dcb.Parity) {
1389 config->parity = SP_PARITY_NONE;
1392 config->parity = SP_PARITY_ODD;
1395 config->parity = SP_PARITY_EVEN;
1398 config->parity = SP_PARITY_MARK;
1401 config->parity = SP_PARITY_SPACE;
1404 config->parity = -1;
1407 config->parity = SP_PARITY_NONE;
1409 switch (data->dcb.StopBits) {
1411 config->stopbits = 1;
1414 config->stopbits = 2;
1417 config->stopbits = -1;
1420 switch (data->dcb.fRtsControl) {
1421 case RTS_CONTROL_DISABLE:
1422 config->rts = SP_RTS_OFF;
1424 case RTS_CONTROL_ENABLE:
1425 config->rts = SP_RTS_ON;
1427 case RTS_CONTROL_HANDSHAKE:
1428 config->rts = SP_RTS_FLOW_CONTROL;
1434 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1436 switch (data->dcb.fDtrControl) {
1437 case DTR_CONTROL_DISABLE:
1438 config->dtr = SP_DTR_OFF;
1440 case DTR_CONTROL_ENABLE:
1441 config->dtr = SP_DTR_ON;
1443 case DTR_CONTROL_HANDSHAKE:
1444 config->dtr = SP_DTR_FLOW_CONTROL;
1450 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1452 if (data->dcb.fInX) {
1453 if (data->dcb.fOutX)
1454 config->xon_xoff = SP_XONXOFF_INOUT;
1456 config->xon_xoff = SP_XONXOFF_IN;
1458 if (data->dcb.fOutX)
1459 config->xon_xoff = SP_XONXOFF_OUT;
1461 config->xon_xoff = SP_XONXOFF_DISABLED;
1466 if (tcgetattr(port->fd, &data->term) < 0)
1467 RETURN_FAIL("tcgetattr() failed");
1469 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1470 RETURN_FAIL("TIOCMGET ioctl failed");
1473 int ret = get_flow(port->fd, data);
1475 if (ret == SP_ERR_FAIL && errno == EINVAL)
1476 data->termiox_supported = 0;
1478 RETURN_CODEVAL(ret);
1480 data->termiox_supported = 1;
1482 data->termiox_supported = 0;
1485 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1486 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1487 config->baudrate = std_baudrates[i].value;
1492 if (i == NUM_STD_BAUDRATES) {
1494 config->baudrate = (int)data->term.c_ispeed;
1495 #elif defined(USE_TERMIOS_SPEED)
1496 TRY(get_baudrate(port->fd, &config->baudrate));
1498 config->baudrate = -1;
1502 switch (data->term.c_cflag & CSIZE) {
1519 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1520 config->parity = SP_PARITY_NONE;
1521 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1522 config->parity = -1;
1524 else if (data->term.c_cflag & CMSPAR)
1525 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1528 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1530 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1532 if (data->term.c_cflag & CRTSCTS) {
1533 config->rts = SP_RTS_FLOW_CONTROL;
1534 config->cts = SP_CTS_FLOW_CONTROL;
1536 if (data->termiox_supported && data->rts_flow)
1537 config->rts = SP_RTS_FLOW_CONTROL;
1539 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1541 config->cts = (data->termiox_supported && data->cts_flow) ?
1542 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1545 if (data->termiox_supported && data->dtr_flow)
1546 config->dtr = SP_DTR_FLOW_CONTROL;
1548 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1550 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1551 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1553 if (data->term.c_iflag & IXOFF) {
1554 if (data->term.c_iflag & IXON)
1555 config->xon_xoff = SP_XONXOFF_INOUT;
1557 config->xon_xoff = SP_XONXOFF_IN;
1559 if (data->term.c_iflag & IXON)
1560 config->xon_xoff = SP_XONXOFF_OUT;
1562 config->xon_xoff = SP_XONXOFF_DISABLED;
1569 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1570 const struct sp_port_config *config)
1574 BAUD_TYPE baud_nonstd;
1578 #ifdef USE_TERMIOS_SPEED
1579 int baud_nonstd = 0;
1582 TRACE("%p, %p, %p", port, data, config);
1584 DEBUG("Setting configuration for port %s", port->name);
1587 if (config->baudrate >= 0) {
1588 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1589 if (config->baudrate == std_baudrates[i].value) {
1590 data->dcb.BaudRate = std_baudrates[i].index;
1595 if (i == NUM_STD_BAUDRATES)
1596 data->dcb.BaudRate = config->baudrate;
1599 if (config->bits >= 0)
1600 data->dcb.ByteSize = config->bits;
1602 if (config->parity >= 0) {
1603 switch (config->parity) {
1604 case SP_PARITY_NONE:
1605 data->dcb.Parity = NOPARITY;
1608 data->dcb.Parity = ODDPARITY;
1610 case SP_PARITY_EVEN:
1611 data->dcb.Parity = EVENPARITY;
1613 case SP_PARITY_MARK:
1614 data->dcb.Parity = MARKPARITY;
1616 case SP_PARITY_SPACE:
1617 data->dcb.Parity = SPACEPARITY;
1620 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1624 if (config->stopbits >= 0) {
1625 switch (config->stopbits) {
1626 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1628 data->dcb.StopBits = ONESTOPBIT;
1631 data->dcb.StopBits = TWOSTOPBITS;
1634 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1638 if (config->rts >= 0) {
1639 switch (config->rts) {
1641 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1644 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1646 case SP_RTS_FLOW_CONTROL:
1647 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1650 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1654 if (config->cts >= 0) {
1655 switch (config->cts) {
1657 data->dcb.fOutxCtsFlow = FALSE;
1659 case SP_CTS_FLOW_CONTROL:
1660 data->dcb.fOutxCtsFlow = TRUE;
1663 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1667 if (config->dtr >= 0) {
1668 switch (config->dtr) {
1670 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1673 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1675 case SP_DTR_FLOW_CONTROL:
1676 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1679 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1683 if (config->dsr >= 0) {
1684 switch (config->dsr) {
1686 data->dcb.fOutxDsrFlow = FALSE;
1688 case SP_DSR_FLOW_CONTROL:
1689 data->dcb.fOutxDsrFlow = TRUE;
1692 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1696 if (config->xon_xoff >= 0) {
1697 switch (config->xon_xoff) {
1698 case SP_XONXOFF_DISABLED:
1699 data->dcb.fInX = FALSE;
1700 data->dcb.fOutX = FALSE;
1703 data->dcb.fInX = TRUE;
1704 data->dcb.fOutX = FALSE;
1706 case SP_XONXOFF_OUT:
1707 data->dcb.fInX = FALSE;
1708 data->dcb.fOutX = TRUE;
1710 case SP_XONXOFF_INOUT:
1711 data->dcb.fInX = TRUE;
1712 data->dcb.fOutX = TRUE;
1715 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1719 if (!SetCommState(port->hdl, &data->dcb))
1720 RETURN_FAIL("SetCommState() failed");
1726 if (config->baudrate >= 0) {
1727 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1728 if (config->baudrate == std_baudrates[i].value) {
1729 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1730 RETURN_FAIL("cfsetospeed() failed");
1732 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1733 RETURN_FAIL("cfsetispeed() failed");
1738 /* Non-standard baud rate */
1739 if (i == NUM_STD_BAUDRATES) {
1741 /* Set "dummy" baud rate. */
1742 if (cfsetspeed(&data->term, B9600) < 0)
1743 RETURN_FAIL("cfsetspeed() failed");
1744 baud_nonstd = config->baudrate;
1745 #elif defined(USE_TERMIOS_SPEED)
1748 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1753 if (config->bits >= 0) {
1754 data->term.c_cflag &= ~CSIZE;
1755 switch (config->bits) {
1757 data->term.c_cflag |= CS8;
1760 data->term.c_cflag |= CS7;
1763 data->term.c_cflag |= CS6;
1766 data->term.c_cflag |= CS5;
1769 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1773 if (config->parity >= 0) {
1774 data->term.c_iflag &= ~IGNPAR;
1775 data->term.c_cflag &= ~(PARENB | PARODD);
1777 data->term.c_cflag &= ~CMSPAR;
1779 switch (config->parity) {
1780 case SP_PARITY_NONE:
1781 data->term.c_iflag |= IGNPAR;
1783 case SP_PARITY_EVEN:
1784 data->term.c_cflag |= PARENB;
1787 data->term.c_cflag |= PARENB | PARODD;
1790 case SP_PARITY_MARK:
1791 data->term.c_cflag |= PARENB | PARODD;
1792 data->term.c_cflag |= CMSPAR;
1794 case SP_PARITY_SPACE:
1795 data->term.c_cflag |= PARENB;
1796 data->term.c_cflag |= CMSPAR;
1799 case SP_PARITY_MARK:
1800 case SP_PARITY_SPACE:
1801 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1804 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1808 if (config->stopbits >= 0) {
1809 data->term.c_cflag &= ~CSTOPB;
1810 switch (config->stopbits) {
1812 data->term.c_cflag &= ~CSTOPB;
1815 data->term.c_cflag |= CSTOPB;
1818 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1822 if (config->rts >= 0 || config->cts >= 0) {
1823 if (data->termiox_supported) {
1824 data->rts_flow = data->cts_flow = 0;
1825 switch (config->rts) {
1828 controlbits = TIOCM_RTS;
1829 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1830 RETURN_FAIL("Setting RTS signal level failed");
1832 case SP_RTS_FLOW_CONTROL:
1838 if (config->cts == SP_CTS_FLOW_CONTROL)
1841 if (data->rts_flow && data->cts_flow)
1842 data->term.c_iflag |= CRTSCTS;
1844 data->term.c_iflag &= ~CRTSCTS;
1846 /* Asymmetric use of RTS/CTS not supported. */
1847 if (data->term.c_iflag & CRTSCTS) {
1848 /* Flow control can only be disabled for both RTS & CTS together. */
1849 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1850 if (config->cts != SP_CTS_IGNORE)
1851 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1853 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1854 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1855 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1858 /* Flow control can only be enabled for both RTS & CTS together. */
1859 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1860 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1861 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1864 if (config->rts >= 0) {
1865 if (config->rts == SP_RTS_FLOW_CONTROL) {
1866 data->term.c_iflag |= CRTSCTS;
1868 controlbits = TIOCM_RTS;
1869 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1871 RETURN_FAIL("Setting RTS signal level failed");
1877 if (config->dtr >= 0 || config->dsr >= 0) {
1878 if (data->termiox_supported) {
1879 data->dtr_flow = data->dsr_flow = 0;
1880 switch (config->dtr) {
1883 controlbits = TIOCM_DTR;
1884 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1885 RETURN_FAIL("Setting DTR signal level failed");
1887 case SP_DTR_FLOW_CONTROL:
1893 if (config->dsr == SP_DSR_FLOW_CONTROL)
1896 /* DTR/DSR flow control not supported. */
1897 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1898 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1900 if (config->dtr >= 0) {
1901 controlbits = TIOCM_DTR;
1902 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1904 RETURN_FAIL("Setting DTR signal level failed");
1909 if (config->xon_xoff >= 0) {
1910 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1911 switch (config->xon_xoff) {
1912 case SP_XONXOFF_DISABLED:
1915 data->term.c_iflag |= IXOFF;
1917 case SP_XONXOFF_OUT:
1918 data->term.c_iflag |= IXON | IXANY;
1920 case SP_XONXOFF_INOUT:
1921 data->term.c_iflag |= IXON | IXOFF | IXANY;
1924 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1928 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
1929 RETURN_FAIL("tcsetattr() failed");
1932 if (baud_nonstd != B0) {
1933 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1934 RETURN_FAIL("IOSSIOSPEED ioctl failed");
1935 /* Set baud rates in data->term to correct, but incompatible
1936 * with tcsetattr() value, same as delivered by tcgetattr(). */
1937 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1938 RETURN_FAIL("cfsetspeed() failed");
1940 #elif defined(__linux__)
1941 #ifdef USE_TERMIOS_SPEED
1943 TRY(set_baudrate(port->fd, config->baudrate));
1946 if (data->termiox_supported)
1947 TRY(set_flow(port->fd, data));
1951 #endif /* !_WIN32 */
1956 enum sp_return sp_new_config(struct sp_port_config **config_ptr)
1958 struct sp_port_config *config;
1960 TRACE("%p", config_ptr);
1963 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1967 if (!(config = malloc(sizeof(struct sp_port_config))))
1968 RETURN_ERROR(SP_ERR_MEM, "config malloc failed");
1970 config->baudrate = -1;
1972 config->parity = -1;
1973 config->stopbits = -1;
1979 *config_ptr = config;
1984 void sp_free_config(struct sp_port_config *config)
1986 TRACE("%p", config);
1989 DEBUG("Null config");
1996 enum sp_return sp_get_config(struct sp_port *port, struct sp_port_config *config)
1998 struct port_data data;
2000 TRACE("%p, %p", port, config);
2005 RETURN_ERROR(SP_ERR_ARG, "Null config");
2007 TRY(get_config(port, &data, config));
2012 enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
2014 struct port_data data;
2015 struct sp_port_config prev_config;
2017 TRACE("%p, %p", port, config);
2022 RETURN_ERROR(SP_ERR_ARG, "Null config");
2024 TRY(get_config(port, &data, &prev_config));
2025 TRY(set_config(port, &data, config));
2030 #define CREATE_ACCESSORS(x, type) \
2031 enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2032 struct port_data data; \
2033 struct sp_port_config config; \
2034 TRACE("%p, %d", port, x); \
2035 CHECK_OPEN_PORT(); \
2036 TRY(get_config(port, &data, &config)); \
2038 TRY(set_config(port, &data, &config)); \
2041 enum sp_return sp_get_config_##x(const struct sp_port_config *config, type *x) { \
2042 TRACE("%p, %p", config, x); \
2044 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2048 enum sp_return sp_set_config_##x(struct sp_port_config *config, type x) { \
2049 TRACE("%p, %d", config, x); \
2051 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2056 CREATE_ACCESSORS(baudrate, int)
2057 CREATE_ACCESSORS(bits, int)
2058 CREATE_ACCESSORS(parity, enum sp_parity)
2059 CREATE_ACCESSORS(stopbits, int)
2060 CREATE_ACCESSORS(rts, enum sp_rts)
2061 CREATE_ACCESSORS(cts, enum sp_cts)
2062 CREATE_ACCESSORS(dtr, enum sp_dtr)
2063 CREATE_ACCESSORS(dsr, enum sp_dsr)
2064 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2066 enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config, enum sp_flowcontrol flowcontrol)
2069 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2071 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2072 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2074 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2075 config->xon_xoff = SP_XONXOFF_INOUT;
2077 config->xon_xoff = SP_XONXOFF_DISABLED;
2079 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2080 config->rts = SP_RTS_FLOW_CONTROL;
2081 config->cts = SP_CTS_FLOW_CONTROL;
2083 if (config->rts == SP_RTS_FLOW_CONTROL)
2084 config->rts = SP_RTS_ON;
2085 config->cts = SP_CTS_IGNORE;
2088 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2089 config->dtr = SP_DTR_FLOW_CONTROL;
2090 config->dsr = SP_DSR_FLOW_CONTROL;
2092 if (config->dtr == SP_DTR_FLOW_CONTROL)
2093 config->dtr = SP_DTR_ON;
2094 config->dsr = SP_DSR_IGNORE;
2100 enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
2102 struct port_data data;
2103 struct sp_port_config config;
2105 TRACE("%p, %d", port, flowcontrol);
2109 TRY(get_config(port, &data, &config));
2111 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2113 TRY(set_config(port, &data, &config));
2118 enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
2120 TRACE("%p, %p", port, signals);
2125 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2127 DEBUG("Getting control signals for port %s", port->name);
2132 if (GetCommModemStatus(port->hdl, &bits) == 0)
2133 RETURN_FAIL("GetCommModemStatus() failed");
2134 if (bits & MS_CTS_ON)
2135 *signals |= SP_SIG_CTS;
2136 if (bits & MS_DSR_ON)
2137 *signals |= SP_SIG_DSR;
2138 if (bits & MS_RLSD_ON)
2139 *signals |= SP_SIG_DCD;
2140 if (bits & MS_RING_ON)
2141 *signals |= SP_SIG_RI;
2144 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2145 RETURN_FAIL("TIOCMGET ioctl failed");
2146 if (bits & TIOCM_CTS)
2147 *signals |= SP_SIG_CTS;
2148 if (bits & TIOCM_DSR)
2149 *signals |= SP_SIG_DSR;
2150 if (bits & TIOCM_CAR)
2151 *signals |= SP_SIG_DCD;
2152 if (bits & TIOCM_RNG)
2153 *signals |= SP_SIG_RI;
2158 enum sp_return sp_start_break(struct sp_port *port)
2164 if (SetCommBreak(port->hdl) == 0)
2165 RETURN_FAIL("SetCommBreak() failed");
2167 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2168 RETURN_FAIL("TIOCSBRK ioctl failed");
2174 enum sp_return sp_end_break(struct sp_port *port)
2180 if (ClearCommBreak(port->hdl) == 0)
2181 RETURN_FAIL("ClearCommBreak() failed");
2183 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2184 RETURN_FAIL("TIOCCBRK ioctl failed");
2190 int sp_last_error_code(void)
2194 RETURN_VALUE("%d", GetLastError());
2196 RETURN_VALUE("%d", errno);
2200 char *sp_last_error_message(void)
2206 DWORD error = GetLastError();
2209 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2210 FORMAT_MESSAGE_FROM_SYSTEM |
2211 FORMAT_MESSAGE_IGNORE_INSERTS,
2214 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2218 RETURN_VALUE("%s", message);
2220 RETURN_VALUE("%s", strerror(errno));
2224 void sp_free_error_message(char *message)
2226 TRACE("%s", message);
2237 void sp_set_debug_handler(void (*handler)(const char *format, ...))
2239 TRACE("%p", handler);
2241 sp_debug_handler = handler;
2246 void sp_default_debug_handler(const char *format, ...)
2249 va_start(args, format);
2250 if (getenv("LIBSERIALPORT_DEBUG")) {
2251 fputs("sp: ", stderr);
2252 vfprintf(stderr, format, args);
2257 int sp_get_major_package_version(void)
2259 return SP_PACKAGE_VERSION_MAJOR;
2262 int sp_get_minor_package_version(void)
2264 return SP_PACKAGE_VERSION_MINOR;
2267 int sp_get_micro_package_version(void)
2269 return SP_PACKAGE_VERSION_MICRO;
2272 const char *sp_get_package_version_string(void)
2274 return SP_PACKAGE_VERSION_STRING;
2277 int sp_get_current_lib_version(void)
2279 return SP_LIB_VERSION_CURRENT;
2282 int sp_get_revision_lib_version(void)
2284 return SP_LIB_VERSION_REVISION;
2287 int sp_get_age_lib_version(void)
2289 return SP_LIB_VERSION_AGE;
2292 const char *sp_get_lib_version_string(void)
2294 return SP_LIB_VERSION_STRING;