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 if ((ret = get_port_details(port)) != SP_OK) {
112 char *sp_get_port_name(const struct sp_port *port)
119 RETURN_VALUE("%s", port->name);
122 char *sp_get_port_description(struct sp_port *port)
126 if (!port || !port->description)
129 RETURN_VALUE("%s", port->description);
132 enum sp_transport sp_get_port_transport(struct sp_port *port)
137 RETURN_ERROR(SP_ERR_ARG, "Null port");
139 RETURN_VALUE("%d", port->transport);
142 enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
143 int *usb_bus, int *usb_address)
148 RETURN_ERROR(SP_ERR_ARG, "Null port");
149 if (port->transport != SP_TRANSPORT_USB)
150 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
151 if (port->usb_bus < 0 || port->usb_address < 0)
152 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
154 if (usb_bus) *usb_bus = port->usb_bus;
155 if (usb_address) *usb_address = port->usb_address;
160 enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
161 int *usb_vid, int *usb_pid)
166 RETURN_ERROR(SP_ERR_ARG, "Null port");
167 if (port->transport != SP_TRANSPORT_USB)
168 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
169 if (port->usb_vid < 0 || port->usb_pid < 0)
170 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
172 if (usb_vid) *usb_vid = port->usb_vid;
173 if (usb_pid) *usb_pid = port->usb_pid;
178 char *sp_get_port_usb_manufacturer(const struct sp_port *port)
182 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
185 RETURN_VALUE("%s", port->usb_manufacturer);
188 char *sp_get_port_usb_product(const struct sp_port *port)
192 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
195 RETURN_VALUE("%s", port->usb_product);
198 char *sp_get_port_usb_serial(const struct sp_port *port)
202 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
205 RETURN_VALUE("%s", port->usb_serial);
208 char *sp_get_port_bluetooth_address(const struct sp_port *port)
212 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
213 || !port->bluetooth_address)
216 RETURN_VALUE("%s", port->bluetooth_address);
219 enum sp_return sp_get_port_handle(const struct sp_port *port, void *result_ptr)
221 TRACE("%p, %p", port, result_ptr);
224 RETURN_ERROR(SP_ERR_ARG, "Null port");
227 HANDLE *handle_ptr = result_ptr;
228 *handle_ptr = port->hdl;
230 int *fd_ptr = result_ptr;
237 enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
239 TRACE("%p, %p", port, copy_ptr);
242 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
247 RETURN_ERROR(SP_ERR_ARG, "Null port");
250 RETURN_ERROR(SP_ERR_ARG, "Null port name");
252 DEBUG("Copying port structure");
254 RETURN_VALUE("%p", sp_get_port_by_name(port->name, copy_ptr));
257 void sp_free_port(struct sp_port *port)
266 DEBUG("Freeing port structure");
270 if (port->description)
271 free(port->description);
272 if (port->usb_manufacturer)
273 free(port->usb_manufacturer);
274 if (port->usb_product)
275 free(port->usb_product);
276 if (port->usb_serial)
277 free(port->usb_serial);
278 if (port->bluetooth_address)
279 free(port->bluetooth_address);
282 free(port->usb_path);
290 struct sp_port **list_append(struct sp_port **list, const char *portname)
295 for (count = 0; list[count]; count++);
296 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
299 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
301 list[count + 1] = NULL;
305 sp_free_port_list(list);
309 enum sp_return sp_list_ports(struct sp_port ***list_ptr)
311 struct sp_port **list;
314 TRACE("%p", list_ptr);
317 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
319 DEBUG("Enumerating ports");
321 if (!(list = malloc(sizeof(struct sp_port **))))
322 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
326 ret = list_ports(&list);
333 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
336 sp_free_port_list(list);
342 void sp_free_port_list(struct sp_port **list)
353 DEBUG("Freeing port list");
355 for (i = 0; list[i]; i++)
356 sp_free_port(list[i]);
362 #define CHECK_PORT() do { \
364 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
365 if (port->name == NULL) \
366 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
369 #define CHECK_PORT_HANDLE() do { \
370 if (port->hdl == INVALID_HANDLE_VALUE) \
371 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
374 #define CHECK_PORT_HANDLE() do { \
376 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
379 #define CHECK_OPEN_PORT() do { \
381 CHECK_PORT_HANDLE(); \
384 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
386 struct port_data data;
387 struct sp_port_config config;
390 TRACE("%p, 0x%x", port, flags);
394 if (flags > (SP_MODE_READ | SP_MODE_WRITE))
395 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
397 DEBUG("Opening port %s", port->name);
400 DWORD desired_access = 0, flags_and_attributes = 0, errors;
401 char *escaped_port_name;
404 /* Prefix port name with '\\.\' to work with ports above COM9. */
405 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
406 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
407 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
409 /* Map 'flags' to the OS-specific settings. */
410 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
411 if (flags & SP_MODE_READ)
412 desired_access |= GENERIC_READ;
413 if (flags & SP_MODE_WRITE)
414 desired_access |= GENERIC_WRITE;
416 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
417 OPEN_EXISTING, flags_and_attributes, 0);
419 free(escaped_port_name);
421 if (port->hdl == INVALID_HANDLE_VALUE)
422 RETURN_FAIL("port CreateFile() failed");
424 /* All timeouts initially disabled. */
425 port->timeouts.ReadIntervalTimeout = 0;
426 port->timeouts.ReadTotalTimeoutMultiplier = 0;
427 port->timeouts.ReadTotalTimeoutConstant = 0;
428 port->timeouts.WriteTotalTimeoutMultiplier = 0;
429 port->timeouts.WriteTotalTimeoutConstant = 0;
431 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
433 RETURN_FAIL("SetCommTimeouts() failed");
436 /* Prepare OVERLAPPED structures. */
437 #define INIT_OVERLAPPED(ovl) do { \
438 memset(&port->ovl, 0, sizeof(port->ovl)); \
439 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
440 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
441 == INVALID_HANDLE_VALUE) { \
443 RETURN_FAIL(#ovl "CreateEvent() failed"); \
447 INIT_OVERLAPPED(read_ovl);
448 INIT_OVERLAPPED(write_ovl);
449 INIT_OVERLAPPED(wait_ovl);
451 /* Set event mask for RX and error events. */
452 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
454 RETURN_FAIL("SetCommMask() failed");
457 /* Start background operation for RX and error events. */
458 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
459 if (GetLastError() != ERROR_IO_PENDING) {
461 RETURN_FAIL("WaitCommEvent() failed");
465 port->writing = FALSE;
468 int flags_local = O_NONBLOCK | O_NOCTTY;
470 /* Map 'flags' to the OS-specific settings. */
471 if (flags & (SP_MODE_READ | SP_MODE_WRITE))
472 flags_local |= O_RDWR;
473 else if (flags & SP_MODE_READ)
474 flags_local |= O_RDONLY;
475 else if (flags & SP_MODE_WRITE)
476 flags_local |= O_WRONLY;
478 if ((port->fd = open(port->name, flags_local)) < 0)
479 RETURN_FAIL("open() failed");
482 ret = get_config(port, &data, &config);
489 /* Set sane port settings. */
491 data.dcb.fBinary = TRUE;
492 data.dcb.fDsrSensitivity = FALSE;
493 data.dcb.fErrorChar = FALSE;
494 data.dcb.fNull = FALSE;
495 data.dcb.fAbortOnError = TRUE;
497 /* Turn off all fancy termios tricks, give us a raw channel. */
498 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
500 data.term.c_iflag &= ~IUCLC;
502 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
504 data.term.c_oflag &= ~OLCUC;
507 data.term.c_oflag &= ~NLDLY;
510 data.term.c_oflag &= ~CRDLY;
513 data.term.c_oflag &= ~TABDLY;
516 data.term.c_oflag &= ~BSDLY;
519 data.term.c_oflag &= ~VTDLY;
522 data.term.c_oflag &= ~FFDLY;
525 data.term.c_oflag &= ~OFILL;
527 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
528 data.term.c_cc[VMIN] = 0;
529 data.term.c_cc[VTIME] = 0;
531 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
532 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
536 if (ClearCommError(port->hdl, &errors, &status) == 0)
537 RETURN_FAIL("ClearCommError() failed");
540 ret = set_config(port, &data, &config);
550 enum sp_return sp_close(struct sp_port *port)
556 DEBUG("Closing port %s", port->name);
559 /* Returns non-zero upon success, 0 upon failure. */
560 if (CloseHandle(port->hdl) == 0)
561 RETURN_FAIL("port CloseHandle() failed");
562 port->hdl = INVALID_HANDLE_VALUE;
564 /* Close event handles for overlapped structures. */
565 #define CLOSE_OVERLAPPED(ovl) do { \
566 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
567 CloseHandle(port->ovl.hEvent) == 0) \
568 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
570 CLOSE_OVERLAPPED(read_ovl);
571 CLOSE_OVERLAPPED(write_ovl);
572 CLOSE_OVERLAPPED(wait_ovl);
575 /* Returns 0 upon success, -1 upon failure. */
576 if (close(port->fd) == -1)
577 RETURN_FAIL("close() failed");
584 enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
586 TRACE("%p, 0x%x", port, buffers);
590 if (buffers > SP_BUF_BOTH)
591 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
593 const char *buffer_names[] = {"no", "input", "output", "both"};
595 DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
599 if (buffers & SP_BUF_INPUT)
600 flags |= PURGE_RXCLEAR;
601 if (buffers & SP_BUF_OUTPUT)
602 flags |= PURGE_TXCLEAR;
604 /* Returns non-zero upon success, 0 upon failure. */
605 if (PurgeComm(port->hdl, flags) == 0)
606 RETURN_FAIL("PurgeComm() failed");
609 if (buffers & SP_BUF_BOTH)
611 else if (buffers & SP_BUF_INPUT)
613 else if (buffers & SP_BUF_OUTPUT)
616 /* Returns 0 upon success, -1 upon failure. */
617 if (tcflush(port->fd, flags) < 0)
618 RETURN_FAIL("tcflush() failed");
623 enum sp_return sp_drain(struct sp_port *port)
629 DEBUG("Draining port %s", port->name);
632 /* Returns non-zero upon success, 0 upon failure. */
633 if (FlushFileBuffers(port->hdl) == 0)
634 RETURN_FAIL("FlushFileBuffers() failed");
641 result = ioctl(port->fd, TCSBRK, &arg);
643 result = tcdrain(port->fd);
646 if (errno == EINTR) {
647 DEBUG("tcdrain() was interrupted");
650 RETURN_FAIL("tcdrain() failed");
659 enum sp_return sp_blocking_write(struct sp_port *port, const void *buf, size_t count, unsigned int timeout)
661 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
666 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
669 DEBUG("Writing %d bytes to port %s, timeout %d ms", count, port->name, timeout);
671 DEBUG("Writing %d bytes to port %s, no timeout", count, port->name);
674 RETURN_VALUE("0", 0);
677 DWORD bytes_written = 0;
680 /* Wait for previous non-blocking write to complete, if any. */
682 DEBUG("Waiting for previous write to complete");
683 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
686 RETURN_FAIL("Previous write failed to complete");
687 DEBUG("Previous write completed");
691 port->timeouts.WriteTotalTimeoutConstant = timeout;
692 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
693 RETURN_FAIL("SetCommTimeouts() failed");
696 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) {
697 if (GetLastError() == ERROR_IO_PENDING) {
698 DEBUG("Waiting for write to complete");
699 GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
700 DEBUG("Write completed, %d/%d bytes written", bytes_written, count);
701 RETURN_VALUE("%d", bytes_written);
703 RETURN_FAIL("WriteFile() failed");
706 DEBUG("Write completed immediately");
707 RETURN_VALUE("%d", count);
710 size_t bytes_written = 0;
711 unsigned char *ptr = (unsigned char *) buf;
712 struct timeval start, delta, now, end = {0, 0};
717 /* Get time at start of operation. */
718 gettimeofday(&start, NULL);
719 /* Define duration of timeout. */
720 delta.tv_sec = timeout / 1000;
721 delta.tv_usec = (timeout % 1000) * 1000;
722 /* Calculate time at which we should give up. */
723 timeradd(&start, &delta, &end);
726 /* Loop until we have written the requested number of bytes. */
727 while (bytes_written < count)
729 /* Wait until space is available. */
731 FD_SET(port->fd, &fds);
733 gettimeofday(&now, NULL);
734 if (timercmp(&now, &end, >)) {
735 DEBUG("write timed out");
736 RETURN_VALUE("%d", bytes_written);
738 timersub(&end, &now, &delta);
740 result = select(port->fd + 1, NULL, &fds, NULL, timeout ? &delta : NULL);
742 if (errno == EINTR) {
743 DEBUG("select() call was interrupted, repeating");
746 RETURN_FAIL("select() failed");
748 } else if (result == 0) {
749 DEBUG("write timed out");
750 RETURN_VALUE("%d", bytes_written);
754 result = write(port->fd, ptr, count - bytes_written);
758 /* This shouldn't happen because we did a select() first, but handle anyway. */
761 /* This is an actual failure. */
762 RETURN_FAIL("write() failed");
765 bytes_written += result;
769 RETURN_VALUE("%d", bytes_written);
773 enum sp_return sp_nonblocking_write(struct sp_port *port, const void *buf, size_t count)
775 TRACE("%p, %p, %d", port, buf, count);
780 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
782 DEBUG("Writing up to %d bytes to port %s", count, port->name);
785 RETURN_VALUE("0", 0);
789 BYTE *ptr = (BYTE *) buf;
791 /* Check whether previous write is complete. */
793 if (HasOverlappedIoCompleted(&port->write_ovl)) {
794 DEBUG("Previous write completed");
797 DEBUG("Previous write not complete");
798 /* Can't take a new write until the previous one finishes. */
799 RETURN_VALUE("0", 0);
804 port->timeouts.WriteTotalTimeoutConstant = 0;
805 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
806 RETURN_FAIL("SetCommTimeouts() failed");
808 /* Keep writing data until the OS has to actually start an async IO for it.
809 * At that point we know the buffer is full. */
810 while (written < count)
812 /* Copy first byte of user buffer. */
813 port->pending_byte = *ptr++;
815 /* Start asynchronous write. */
816 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
817 if (GetLastError() == ERROR_IO_PENDING) {
818 if (HasOverlappedIoCompleted(&port->write_ovl)) {
819 DEBUG("Asynchronous write completed immediately");
824 DEBUG("Asynchronous write running");
826 RETURN_VALUE("%d", ++written);
829 /* Actual failure of some kind. */
830 RETURN_FAIL("WriteFile() failed");
833 DEBUG("Single byte written immediately");
838 DEBUG("All bytes written immediately");
840 RETURN_VALUE("%d", written);
842 /* Returns the number of bytes written, or -1 upon failure. */
843 ssize_t written = write(port->fd, buf, count);
846 RETURN_FAIL("write() failed");
848 RETURN_VALUE("%d", written);
852 enum sp_return sp_blocking_read(struct sp_port *port, void *buf, size_t count, unsigned int timeout)
854 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
859 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
862 DEBUG("Reading %d bytes from port %s, timeout %d ms", count, port->name, timeout);
864 DEBUG("Reading %d bytes from port %s, no timeout", count, port->name);
867 RETURN_VALUE("0", 0);
870 DWORD bytes_read = 0;
873 port->timeouts.ReadIntervalTimeout = 0;
874 port->timeouts.ReadTotalTimeoutConstant = timeout;
875 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
876 RETURN_FAIL("SetCommTimeouts() failed");
879 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) {
880 if (GetLastError() == ERROR_IO_PENDING) {
881 DEBUG("Waiting for read to complete");
882 GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
883 DEBUG("Read completed, %d/%d bytes read", bytes_read, count);
885 RETURN_FAIL("ReadFile() failed");
888 DEBUG("Read completed immediately");
892 /* Start background operation for subsequent events. */
893 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
894 if (GetLastError() != ERROR_IO_PENDING)
895 RETURN_FAIL("WaitCommEvent() failed");
898 RETURN_VALUE("%d", bytes_read);
901 size_t bytes_read = 0;
902 unsigned char *ptr = (unsigned char *) buf;
903 struct timeval start, delta, now, end = {0, 0};
908 /* Get time at start of operation. */
909 gettimeofday(&start, NULL);
910 /* Define duration of timeout. */
911 delta.tv_sec = timeout / 1000;
912 delta.tv_usec = (timeout % 1000) * 1000;
913 /* Calculate time at which we should give up. */
914 timeradd(&start, &delta, &end);
917 /* Loop until we have the requested number of bytes. */
918 while (bytes_read < count)
920 /* Wait until data is available. */
922 FD_SET(port->fd, &fds);
924 gettimeofday(&now, NULL);
925 if (timercmp(&now, &end, >))
926 /* Timeout has expired. */
927 RETURN_VALUE("%d", bytes_read);
928 timersub(&end, &now, &delta);
930 result = select(port->fd + 1, &fds, NULL, NULL, timeout ? &delta : NULL);
932 if (errno == EINTR) {
933 DEBUG("select() call was interrupted, repeating");
936 RETURN_FAIL("select() failed");
938 } else if (result == 0) {
939 DEBUG("read timed out");
940 RETURN_VALUE("%d", bytes_read);
944 result = read(port->fd, ptr, count - bytes_read);
948 /* This shouldn't happen because we did a select() first, but handle anyway. */
951 /* This is an actual failure. */
952 RETURN_FAIL("read() failed");
955 bytes_read += result;
959 RETURN_VALUE("%d", bytes_read);
963 enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf, size_t count)
965 TRACE("%p, %p, %d", port, buf, count);
970 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
972 DEBUG("Reading up to %d bytes from port %s", count, port->name);
978 port->timeouts.ReadIntervalTimeout = MAXDWORD;
979 port->timeouts.ReadTotalTimeoutConstant = 0;
980 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
981 RETURN_FAIL("SetCommTimeouts() failed");
984 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
985 RETURN_FAIL("ReadFile() failed");
987 /* Get number of bytes read. */
988 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
989 RETURN_FAIL("GetOverlappedResult() failed");
991 if (bytes_read > 0) {
992 /* Start background operation for subsequent events. */
993 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
994 if (GetLastError() != ERROR_IO_PENDING)
995 RETURN_FAIL("WaitCommEvent() failed");
999 RETURN_VALUE("%d", bytes_read);
1003 /* Returns the number of bytes read, or -1 upon failure. */
1004 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1005 if (errno == EAGAIN)
1006 /* No bytes available. */
1009 /* This is an actual failure. */
1010 RETURN_FAIL("read() failed");
1012 RETURN_VALUE("%d", bytes_read);
1016 enum sp_return sp_input_waiting(struct sp_port *port)
1022 DEBUG("Checking input bytes waiting on port %s", port->name);
1028 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1029 RETURN_FAIL("ClearCommError() failed");
1030 RETURN_VALUE("%d", comstat.cbInQue);
1033 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1034 RETURN_FAIL("TIOCINQ ioctl failed");
1035 RETURN_VALUE("%d", bytes_waiting);
1039 enum sp_return sp_output_waiting(struct sp_port *port)
1045 DEBUG("Checking output bytes waiting on port %s", port->name);
1051 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1052 RETURN_FAIL("ClearCommError() failed");
1053 RETURN_VALUE("%d", comstat.cbOutQue);
1056 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1057 RETURN_FAIL("TIOCOUTQ ioctl failed");
1058 RETURN_VALUE("%d", bytes_waiting);
1062 enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1064 struct sp_event_set *result;
1066 TRACE("%p", result_ptr);
1069 RETURN_ERROR(SP_ERR_ARG, "Null result");
1073 if (!(result = malloc(sizeof(struct sp_event_set))))
1074 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1076 memset(result, 0, sizeof(struct sp_event_set));
1078 *result_ptr = result;
1083 static enum sp_return add_handle(struct sp_event_set *event_set,
1084 event_handle handle, enum sp_event mask)
1087 enum sp_event *new_masks;
1089 TRACE("%p, %d, %d", event_set, handle, mask);
1091 if (!(new_handles = realloc(event_set->handles,
1092 sizeof(event_handle) * (event_set->count + 1))))
1093 RETURN_ERROR(SP_ERR_MEM, "handle array realloc() failed");
1095 if (!(new_masks = realloc(event_set->masks,
1096 sizeof(enum sp_event) * (event_set->count + 1))))
1097 RETURN_ERROR(SP_ERR_MEM, "mask array realloc() failed");
1099 event_set->handles = new_handles;
1100 event_set->masks = new_masks;
1102 ((event_handle *) event_set->handles)[event_set->count] = handle;
1103 event_set->masks[event_set->count] = mask;
1110 enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1111 const struct sp_port *port, enum sp_event mask)
1113 TRACE("%p, %p, %d", event_set, port, mask);
1116 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1119 RETURN_ERROR(SP_ERR_ARG, "Null port");
1121 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1122 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1128 enum sp_event handle_mask;
1129 if ((handle_mask = mask & SP_EVENT_TX_READY))
1130 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1131 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1132 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1134 TRY(add_handle(event_set, port->fd, mask));
1140 void sp_free_event_set(struct sp_event_set *event_set)
1142 TRACE("%p", event_set);
1145 DEBUG("Null event set");
1149 DEBUG("Freeing event set");
1151 if (event_set->handles)
1152 free(event_set->handles);
1153 if (event_set->masks)
1154 free(event_set->masks);
1161 enum sp_return sp_wait(struct sp_event_set *event_set, unsigned int timeout)
1163 TRACE("%p, %d", event_set, timeout);
1166 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1169 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1170 timeout ? timeout : INFINITE) == WAIT_FAILED)
1171 RETURN_FAIL("WaitForMultipleObjects() failed");
1175 struct timeval start, delta, now, end = {0, 0};
1176 int result, timeout_remaining;
1177 struct pollfd *pollfds;
1180 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1181 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1183 for (i = 0; i < event_set->count; i++) {
1184 pollfds[i].fd = ((int *) event_set->handles)[i];
1185 pollfds[i].events = 0;
1186 pollfds[i].revents = 0;
1187 if (event_set->masks[i] & SP_EVENT_RX_READY)
1188 pollfds[i].events |= POLLIN;
1189 if (event_set->masks[i] & SP_EVENT_TX_READY)
1190 pollfds[i].events |= POLLOUT;
1191 if (event_set->masks[i] & SP_EVENT_ERROR)
1192 pollfds[i].events |= POLLERR;
1196 /* Get time at start of operation. */
1197 gettimeofday(&start, NULL);
1198 /* Define duration of timeout. */
1199 delta.tv_sec = timeout / 1000;
1200 delta.tv_usec = (timeout % 1000) * 1000;
1201 /* Calculate time at which we should give up. */
1202 timeradd(&start, &delta, &end);
1205 /* Loop until an event occurs. */
1209 gettimeofday(&now, NULL);
1210 if (timercmp(&now, &end, >)) {
1211 DEBUG("wait timed out");
1214 timersub(&end, &now, &delta);
1215 timeout_remaining = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1218 result = poll(pollfds, event_set->count, timeout ? timeout_remaining : -1);
1221 if (errno == EINTR) {
1222 DEBUG("poll() call was interrupted, repeating");
1226 RETURN_FAIL("poll() failed");
1228 } else if (result == 0) {
1229 DEBUG("poll() timed out");
1232 DEBUG("poll() completed");
1242 #ifdef USE_TERMIOS_SPEED
1243 static enum sp_return get_baudrate(int fd, int *baudrate)
1247 TRACE("%d, %p", fd, baudrate);
1249 DEBUG("Getting baud rate");
1251 if (!(data = malloc(get_termios_size())))
1252 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1254 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1256 RETURN_FAIL("getting termios failed");
1259 *baudrate = get_termios_speed(data);
1266 static enum sp_return set_baudrate(int fd, int baudrate)
1270 TRACE("%d, %d", fd, baudrate);
1272 DEBUG("Getting baud rate");
1274 if (!(data = malloc(get_termios_size())))
1275 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1277 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1279 RETURN_FAIL("getting termios failed");
1282 DEBUG("Setting baud rate");
1284 set_termios_speed(data, baudrate);
1286 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1288 RETURN_FAIL("setting termios failed");
1295 #endif /* USE_TERMIOS_SPEED */
1298 static enum sp_return get_flow(int fd, struct port_data *data)
1302 TRACE("%d, %p", fd, data);
1304 DEBUG("Getting advanced flow control");
1306 if (!(termx = malloc(get_termiox_size())))
1307 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1309 if (ioctl(fd, TCGETX, termx) < 0) {
1311 RETURN_FAIL("getting termiox failed");
1314 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1315 &data->dtr_flow, &data->dsr_flow);
1322 static enum sp_return set_flow(int fd, struct port_data *data)
1326 TRACE("%d, %p", fd, data);
1328 DEBUG("Getting advanced flow control");
1330 if (!(termx = malloc(get_termiox_size())))
1331 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1333 if (ioctl(fd, TCGETX, termx) < 0) {
1335 RETURN_FAIL("getting termiox failed");
1338 DEBUG("Setting advanced flow control");
1340 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1341 data->dtr_flow, data->dsr_flow);
1343 if (ioctl(fd, TCSETX, termx) < 0) {
1345 RETURN_FAIL("setting termiox failed");
1352 #endif /* USE_TERMIOX */
1354 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1355 struct sp_port_config *config)
1359 TRACE("%p, %p, %p", port, data, config);
1361 DEBUG("Getting configuration for port %s", port->name);
1364 if (!GetCommState(port->hdl, &data->dcb))
1365 RETURN_FAIL("GetCommState() failed");
1367 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1368 if (data->dcb.BaudRate == std_baudrates[i].index) {
1369 config->baudrate = std_baudrates[i].value;
1374 if (i == NUM_STD_BAUDRATES)
1375 /* BaudRate field can be either an index or a custom baud rate. */
1376 config->baudrate = data->dcb.BaudRate;
1378 config->bits = data->dcb.ByteSize;
1380 if (data->dcb.fParity)
1381 switch (data->dcb.Parity) {
1383 config->parity = SP_PARITY_NONE;
1386 config->parity = SP_PARITY_ODD;
1389 config->parity = SP_PARITY_EVEN;
1392 config->parity = SP_PARITY_MARK;
1395 config->parity = SP_PARITY_SPACE;
1398 config->parity = -1;
1401 config->parity = SP_PARITY_NONE;
1403 switch (data->dcb.StopBits) {
1405 config->stopbits = 1;
1408 config->stopbits = 2;
1411 config->stopbits = -1;
1414 switch (data->dcb.fRtsControl) {
1415 case RTS_CONTROL_DISABLE:
1416 config->rts = SP_RTS_OFF;
1418 case RTS_CONTROL_ENABLE:
1419 config->rts = SP_RTS_ON;
1421 case RTS_CONTROL_HANDSHAKE:
1422 config->rts = SP_RTS_FLOW_CONTROL;
1428 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1430 switch (data->dcb.fDtrControl) {
1431 case DTR_CONTROL_DISABLE:
1432 config->dtr = SP_DTR_OFF;
1434 case DTR_CONTROL_ENABLE:
1435 config->dtr = SP_DTR_ON;
1437 case DTR_CONTROL_HANDSHAKE:
1438 config->dtr = SP_DTR_FLOW_CONTROL;
1444 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1446 if (data->dcb.fInX) {
1447 if (data->dcb.fOutX)
1448 config->xon_xoff = SP_XONXOFF_INOUT;
1450 config->xon_xoff = SP_XONXOFF_IN;
1452 if (data->dcb.fOutX)
1453 config->xon_xoff = SP_XONXOFF_OUT;
1455 config->xon_xoff = SP_XONXOFF_DISABLED;
1460 if (tcgetattr(port->fd, &data->term) < 0)
1461 RETURN_FAIL("tcgetattr() failed");
1463 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1464 RETURN_FAIL("TIOCMGET ioctl failed");
1467 int ret = get_flow(port->fd, data);
1469 if (ret == SP_ERR_FAIL && errno == EINVAL)
1470 data->termiox_supported = 0;
1472 RETURN_CODEVAL(ret);
1474 data->termiox_supported = 1;
1476 data->termiox_supported = 0;
1479 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1480 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1481 config->baudrate = std_baudrates[i].value;
1486 if (i == NUM_STD_BAUDRATES) {
1488 config->baudrate = (int)data->term.c_ispeed;
1489 #elif defined(USE_TERMIOS_SPEED)
1490 TRY(get_baudrate(port->fd, &config->baudrate));
1492 config->baudrate = -1;
1496 switch (data->term.c_cflag & CSIZE) {
1513 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1514 config->parity = SP_PARITY_NONE;
1515 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1516 config->parity = -1;
1518 else if (data->term.c_cflag & CMSPAR)
1519 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1522 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1524 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1526 if (data->term.c_cflag & CRTSCTS) {
1527 config->rts = SP_RTS_FLOW_CONTROL;
1528 config->cts = SP_CTS_FLOW_CONTROL;
1530 if (data->termiox_supported && data->rts_flow)
1531 config->rts = SP_RTS_FLOW_CONTROL;
1533 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1535 config->cts = (data->termiox_supported && data->cts_flow) ?
1536 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1539 if (data->termiox_supported && data->dtr_flow)
1540 config->dtr = SP_DTR_FLOW_CONTROL;
1542 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1544 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1545 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1547 if (data->term.c_iflag & IXOFF) {
1548 if (data->term.c_iflag & IXON)
1549 config->xon_xoff = SP_XONXOFF_INOUT;
1551 config->xon_xoff = SP_XONXOFF_IN;
1553 if (data->term.c_iflag & IXON)
1554 config->xon_xoff = SP_XONXOFF_OUT;
1556 config->xon_xoff = SP_XONXOFF_DISABLED;
1563 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1564 const struct sp_port_config *config)
1568 BAUD_TYPE baud_nonstd;
1572 #ifdef USE_TERMIOS_SPEED
1573 int baud_nonstd = 0;
1576 TRACE("%p, %p, %p", port, data, config);
1578 DEBUG("Setting configuration for port %s", port->name);
1581 if (config->baudrate >= 0) {
1582 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1583 if (config->baudrate == std_baudrates[i].value) {
1584 data->dcb.BaudRate = std_baudrates[i].index;
1589 if (i == NUM_STD_BAUDRATES)
1590 data->dcb.BaudRate = config->baudrate;
1593 if (config->bits >= 0)
1594 data->dcb.ByteSize = config->bits;
1596 if (config->parity >= 0) {
1597 switch (config->parity) {
1598 case SP_PARITY_NONE:
1599 data->dcb.Parity = NOPARITY;
1602 data->dcb.Parity = ODDPARITY;
1604 case SP_PARITY_EVEN:
1605 data->dcb.Parity = EVENPARITY;
1607 case SP_PARITY_MARK:
1608 data->dcb.Parity = MARKPARITY;
1610 case SP_PARITY_SPACE:
1611 data->dcb.Parity = SPACEPARITY;
1614 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1618 if (config->stopbits >= 0) {
1619 switch (config->stopbits) {
1620 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1622 data->dcb.StopBits = ONESTOPBIT;
1625 data->dcb.StopBits = TWOSTOPBITS;
1628 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1632 if (config->rts >= 0) {
1633 switch (config->rts) {
1635 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1638 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1640 case SP_RTS_FLOW_CONTROL:
1641 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1644 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1648 if (config->cts >= 0) {
1649 switch (config->cts) {
1651 data->dcb.fOutxCtsFlow = FALSE;
1653 case SP_CTS_FLOW_CONTROL:
1654 data->dcb.fOutxCtsFlow = TRUE;
1657 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1661 if (config->dtr >= 0) {
1662 switch (config->dtr) {
1664 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1667 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1669 case SP_DTR_FLOW_CONTROL:
1670 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1673 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1677 if (config->dsr >= 0) {
1678 switch (config->dsr) {
1680 data->dcb.fOutxDsrFlow = FALSE;
1682 case SP_DSR_FLOW_CONTROL:
1683 data->dcb.fOutxDsrFlow = TRUE;
1686 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1690 if (config->xon_xoff >= 0) {
1691 switch (config->xon_xoff) {
1692 case SP_XONXOFF_DISABLED:
1693 data->dcb.fInX = FALSE;
1694 data->dcb.fOutX = FALSE;
1697 data->dcb.fInX = TRUE;
1698 data->dcb.fOutX = FALSE;
1700 case SP_XONXOFF_OUT:
1701 data->dcb.fInX = FALSE;
1702 data->dcb.fOutX = TRUE;
1704 case SP_XONXOFF_INOUT:
1705 data->dcb.fInX = TRUE;
1706 data->dcb.fOutX = TRUE;
1709 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1713 if (!SetCommState(port->hdl, &data->dcb))
1714 RETURN_FAIL("SetCommState() failed");
1720 if (config->baudrate >= 0) {
1721 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1722 if (config->baudrate == std_baudrates[i].value) {
1723 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1724 RETURN_FAIL("cfsetospeed() failed");
1726 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1727 RETURN_FAIL("cfsetispeed() failed");
1732 /* Non-standard baud rate */
1733 if (i == NUM_STD_BAUDRATES) {
1735 /* Set "dummy" baud rate. */
1736 if (cfsetspeed(&data->term, B9600) < 0)
1737 RETURN_FAIL("cfsetspeed() failed");
1738 baud_nonstd = config->baudrate;
1739 #elif defined(USE_TERMIOS_SPEED)
1742 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1747 if (config->bits >= 0) {
1748 data->term.c_cflag &= ~CSIZE;
1749 switch (config->bits) {
1751 data->term.c_cflag |= CS8;
1754 data->term.c_cflag |= CS7;
1757 data->term.c_cflag |= CS6;
1760 data->term.c_cflag |= CS5;
1763 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1767 if (config->parity >= 0) {
1768 data->term.c_iflag &= ~IGNPAR;
1769 data->term.c_cflag &= ~(PARENB | PARODD);
1771 data->term.c_cflag &= ~CMSPAR;
1773 switch (config->parity) {
1774 case SP_PARITY_NONE:
1775 data->term.c_iflag |= IGNPAR;
1777 case SP_PARITY_EVEN:
1778 data->term.c_cflag |= PARENB;
1781 data->term.c_cflag |= PARENB | PARODD;
1784 case SP_PARITY_MARK:
1785 data->term.c_cflag |= PARENB | PARODD;
1786 data->term.c_cflag |= CMSPAR;
1788 case SP_PARITY_SPACE:
1789 data->term.c_cflag |= PARENB;
1790 data->term.c_cflag |= CMSPAR;
1793 case SP_PARITY_MARK:
1794 case SP_PARITY_SPACE:
1795 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1798 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1802 if (config->stopbits >= 0) {
1803 data->term.c_cflag &= ~CSTOPB;
1804 switch (config->stopbits) {
1806 data->term.c_cflag &= ~CSTOPB;
1809 data->term.c_cflag |= CSTOPB;
1812 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1816 if (config->rts >= 0 || config->cts >= 0) {
1817 if (data->termiox_supported) {
1818 data->rts_flow = data->cts_flow = 0;
1819 switch (config->rts) {
1822 controlbits = TIOCM_RTS;
1823 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1824 RETURN_FAIL("Setting RTS signal level failed");
1826 case SP_RTS_FLOW_CONTROL:
1832 if (config->cts == SP_CTS_FLOW_CONTROL)
1835 if (data->rts_flow && data->cts_flow)
1836 data->term.c_iflag |= CRTSCTS;
1838 data->term.c_iflag &= ~CRTSCTS;
1840 /* Asymmetric use of RTS/CTS not supported. */
1841 if (data->term.c_iflag & CRTSCTS) {
1842 /* Flow control can only be disabled for both RTS & CTS together. */
1843 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1844 if (config->cts != SP_CTS_IGNORE)
1845 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1847 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1848 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1849 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1852 /* Flow control can only be enabled for both RTS & CTS together. */
1853 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1854 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1855 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1858 if (config->rts >= 0) {
1859 if (config->rts == SP_RTS_FLOW_CONTROL) {
1860 data->term.c_iflag |= CRTSCTS;
1862 controlbits = TIOCM_RTS;
1863 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1865 RETURN_FAIL("Setting RTS signal level failed");
1871 if (config->dtr >= 0 || config->dsr >= 0) {
1872 if (data->termiox_supported) {
1873 data->dtr_flow = data->dsr_flow = 0;
1874 switch (config->dtr) {
1877 controlbits = TIOCM_DTR;
1878 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1879 RETURN_FAIL("Setting DTR signal level failed");
1881 case SP_DTR_FLOW_CONTROL:
1887 if (config->dsr == SP_DSR_FLOW_CONTROL)
1890 /* DTR/DSR flow control not supported. */
1891 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1892 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1894 if (config->dtr >= 0) {
1895 controlbits = TIOCM_DTR;
1896 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1898 RETURN_FAIL("Setting DTR signal level failed");
1903 if (config->xon_xoff >= 0) {
1904 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1905 switch (config->xon_xoff) {
1906 case SP_XONXOFF_DISABLED:
1909 data->term.c_iflag |= IXOFF;
1911 case SP_XONXOFF_OUT:
1912 data->term.c_iflag |= IXON | IXANY;
1914 case SP_XONXOFF_INOUT:
1915 data->term.c_iflag |= IXON | IXOFF | IXANY;
1918 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1922 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
1923 RETURN_FAIL("tcsetattr() failed");
1926 if (baud_nonstd != B0) {
1927 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1928 RETURN_FAIL("IOSSIOSPEED ioctl failed");
1929 /* Set baud rates in data->term to correct, but incompatible
1930 * with tcsetattr() value, same as delivered by tcgetattr(). */
1931 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1932 RETURN_FAIL("cfsetspeed() failed");
1934 #elif defined(__linux__)
1935 #ifdef USE_TERMIOS_SPEED
1937 TRY(set_baudrate(port->fd, config->baudrate));
1940 if (data->termiox_supported)
1941 TRY(set_flow(port->fd, data));
1945 #endif /* !_WIN32 */
1950 enum sp_return sp_new_config(struct sp_port_config **config_ptr)
1952 struct sp_port_config *config;
1954 TRACE("%p", config_ptr);
1957 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1961 if (!(config = malloc(sizeof(struct sp_port_config))))
1962 RETURN_ERROR(SP_ERR_MEM, "config malloc failed");
1964 config->baudrate = -1;
1966 config->parity = -1;
1967 config->stopbits = -1;
1973 *config_ptr = config;
1978 void sp_free_config(struct sp_port_config *config)
1980 TRACE("%p", config);
1983 DEBUG("Null config");
1990 enum sp_return sp_get_config(struct sp_port *port, struct sp_port_config *config)
1992 struct port_data data;
1994 TRACE("%p, %p", port, config);
1999 RETURN_ERROR(SP_ERR_ARG, "Null config");
2001 TRY(get_config(port, &data, config));
2006 enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
2008 struct port_data data;
2009 struct sp_port_config prev_config;
2011 TRACE("%p, %p", port, config);
2016 RETURN_ERROR(SP_ERR_ARG, "Null config");
2018 TRY(get_config(port, &data, &prev_config));
2019 TRY(set_config(port, &data, config));
2024 #define CREATE_ACCESSORS(x, type) \
2025 enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2026 struct port_data data; \
2027 struct sp_port_config config; \
2028 TRACE("%p, %d", port, x); \
2029 CHECK_OPEN_PORT(); \
2030 TRY(get_config(port, &data, &config)); \
2032 TRY(set_config(port, &data, &config)); \
2035 enum sp_return sp_get_config_##x(const struct sp_port_config *config, type *x) { \
2036 TRACE("%p, %p", config, x); \
2038 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2042 enum sp_return sp_set_config_##x(struct sp_port_config *config, type x) { \
2043 TRACE("%p, %d", config, x); \
2045 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2050 CREATE_ACCESSORS(baudrate, int)
2051 CREATE_ACCESSORS(bits, int)
2052 CREATE_ACCESSORS(parity, enum sp_parity)
2053 CREATE_ACCESSORS(stopbits, int)
2054 CREATE_ACCESSORS(rts, enum sp_rts)
2055 CREATE_ACCESSORS(cts, enum sp_cts)
2056 CREATE_ACCESSORS(dtr, enum sp_dtr)
2057 CREATE_ACCESSORS(dsr, enum sp_dsr)
2058 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2060 enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config, enum sp_flowcontrol flowcontrol)
2063 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2065 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2066 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2068 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2069 config->xon_xoff = SP_XONXOFF_INOUT;
2071 config->xon_xoff = SP_XONXOFF_DISABLED;
2073 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2074 config->rts = SP_RTS_FLOW_CONTROL;
2075 config->cts = SP_CTS_FLOW_CONTROL;
2077 if (config->rts == SP_RTS_FLOW_CONTROL)
2078 config->rts = SP_RTS_ON;
2079 config->cts = SP_CTS_IGNORE;
2082 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2083 config->dtr = SP_DTR_FLOW_CONTROL;
2084 config->dsr = SP_DSR_FLOW_CONTROL;
2086 if (config->dtr == SP_DTR_FLOW_CONTROL)
2087 config->dtr = SP_DTR_ON;
2088 config->dsr = SP_DSR_IGNORE;
2094 enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
2096 struct port_data data;
2097 struct sp_port_config config;
2099 TRACE("%p, %d", port, flowcontrol);
2103 TRY(get_config(port, &data, &config));
2105 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2107 TRY(set_config(port, &data, &config));
2112 enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
2114 TRACE("%p, %p", port, signals);
2119 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2121 DEBUG("Getting control signals for port %s", port->name);
2126 if (GetCommModemStatus(port->hdl, &bits) == 0)
2127 RETURN_FAIL("GetCommModemStatus() failed");
2128 if (bits & MS_CTS_ON)
2129 *signals |= SP_SIG_CTS;
2130 if (bits & MS_DSR_ON)
2131 *signals |= SP_SIG_DSR;
2132 if (bits & MS_RLSD_ON)
2133 *signals |= SP_SIG_DCD;
2134 if (bits & MS_RING_ON)
2135 *signals |= SP_SIG_RI;
2138 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2139 RETURN_FAIL("TIOCMGET ioctl failed");
2140 if (bits & TIOCM_CTS)
2141 *signals |= SP_SIG_CTS;
2142 if (bits & TIOCM_DSR)
2143 *signals |= SP_SIG_DSR;
2144 if (bits & TIOCM_CAR)
2145 *signals |= SP_SIG_DCD;
2146 if (bits & TIOCM_RNG)
2147 *signals |= SP_SIG_RI;
2152 enum sp_return sp_start_break(struct sp_port *port)
2158 if (SetCommBreak(port->hdl) == 0)
2159 RETURN_FAIL("SetCommBreak() failed");
2161 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2162 RETURN_FAIL("TIOCSBRK ioctl failed");
2168 enum sp_return sp_end_break(struct sp_port *port)
2174 if (ClearCommBreak(port->hdl) == 0)
2175 RETURN_FAIL("ClearCommBreak() failed");
2177 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2178 RETURN_FAIL("TIOCCBRK ioctl failed");
2184 int sp_last_error_code(void)
2188 RETURN_VALUE("%d", GetLastError());
2190 RETURN_VALUE("%d", errno);
2194 char *sp_last_error_message(void)
2200 DWORD error = GetLastError();
2203 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2204 FORMAT_MESSAGE_FROM_SYSTEM |
2205 FORMAT_MESSAGE_IGNORE_INSERTS,
2208 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2212 RETURN_VALUE("%s", message);
2214 RETURN_VALUE("%s", strerror(errno));
2218 void sp_free_error_message(char *message)
2220 TRACE("%s", message);
2231 void sp_set_debug_handler(void (*handler)(const char *format, ...))
2233 TRACE("%p", handler);
2235 sp_debug_handler = handler;
2240 void sp_default_debug_handler(const char *format, ...)
2243 va_start(args, format);
2244 if (getenv("LIBSERIALPORT_DEBUG")) {
2245 fputs("sp: ", stderr);
2246 vfprintf(stderr, format, args);
2251 int sp_get_major_package_version(void)
2253 return SP_PACKAGE_VERSION_MAJOR;
2256 int sp_get_minor_package_version(void)
2258 return SP_PACKAGE_VERSION_MINOR;
2261 int sp_get_micro_package_version(void)
2263 return SP_PACKAGE_VERSION_MICRO;
2266 const char *sp_get_package_version_string(void)
2268 return SP_PACKAGE_VERSION_STRING;
2271 int sp_get_current_lib_version(void)
2273 return SP_LIB_VERSION_CURRENT;
2276 int sp_get_revision_lib_version(void)
2278 return SP_LIB_VERSION_REVISION;
2281 int sp_get_age_lib_version(void)
2283 return SP_LIB_VERSION_AGE;
2286 const char *sp_get_lib_version_string(void)
2288 return SP_LIB_VERSION_STRING;