2 * This file is part of the libserialport project.
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2013 Martin Ling <martin-libserialport@earth.li>
7 * Copyright (C) 2013 Matthias Heidbrink <m-sigrok@heidbrink.biz>
8 * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation, either version 3 of the
13 * License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "libserialport.h"
25 #include "libserialport_internal.h"
27 static const struct std_baudrate std_baudrates[] = {
30 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
31 * have documented CBR_* macros.
33 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
34 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
35 BAUD(115200), BAUD(128000), BAUD(256000),
37 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
38 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
39 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
41 #if !defined(__APPLE__) && !defined(__OpenBSD__)
47 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
49 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
51 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
52 struct sp_port_config *config);
54 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
55 const struct sp_port_config *config);
57 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
60 #ifndef NO_PORT_METADATA
65 TRACE("%s, %p", portname, port_ptr);
68 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
73 RETURN_ERROR(SP_ERR_ARG, "Null port name");
75 DEBUG_FMT("Building structure for port %s", portname);
77 if (!(port = malloc(sizeof(struct sp_port))))
78 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
80 len = strlen(portname) + 1;
82 if (!(port->name = malloc(len))) {
84 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
87 memcpy(port->name, portname, len);
90 port->usb_path = NULL;
91 port->hdl = INVALID_HANDLE_VALUE;
96 port->description = NULL;
97 port->transport = SP_TRANSPORT_NATIVE;
99 port->usb_address = -1;
102 port->usb_manufacturer = NULL;
103 port->usb_product = NULL;
104 port->usb_serial = NULL;
105 port->bluetooth_address = NULL;
107 #ifndef NO_PORT_METADATA
108 if ((ret = get_port_details(port)) != SP_OK) {
119 SP_API char *sp_get_port_name(const struct sp_port *port)
126 RETURN_STRING(port->name);
129 SP_API char *sp_get_port_description(struct sp_port *port)
133 if (!port || !port->description)
136 RETURN_STRING(port->description);
139 SP_API enum sp_transport sp_get_port_transport(struct sp_port *port)
144 RETURN_ERROR(SP_ERR_ARG, "Null port");
146 RETURN_INT(port->transport);
149 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
150 int *usb_bus,int *usb_address)
155 RETURN_ERROR(SP_ERR_ARG, "Null port");
156 if (port->transport != SP_TRANSPORT_USB)
157 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
158 if (port->usb_bus < 0 || port->usb_address < 0)
159 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
162 *usb_bus = port->usb_bus;
164 *usb_address = port->usb_address;
169 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
170 int *usb_vid, int *usb_pid)
175 RETURN_ERROR(SP_ERR_ARG, "Null port");
176 if (port->transport != SP_TRANSPORT_USB)
177 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
178 if (port->usb_vid < 0 || port->usb_pid < 0)
179 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
182 *usb_vid = port->usb_vid;
184 *usb_pid = port->usb_pid;
189 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
193 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
196 RETURN_STRING(port->usb_manufacturer);
199 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
203 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
206 RETURN_STRING(port->usb_product);
209 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
213 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
216 RETURN_STRING(port->usb_serial);
219 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
223 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
224 || !port->bluetooth_address)
227 RETURN_STRING(port->bluetooth_address);
230 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
233 TRACE("%p, %p", port, result_ptr);
236 RETURN_ERROR(SP_ERR_ARG, "Null port");
239 HANDLE *handle_ptr = result_ptr;
240 *handle_ptr = port->hdl;
242 int *fd_ptr = result_ptr;
249 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
250 struct sp_port **copy_ptr)
252 TRACE("%p, %p", port, copy_ptr);
255 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
260 RETURN_ERROR(SP_ERR_ARG, "Null port");
263 RETURN_ERROR(SP_ERR_ARG, "Null port name");
265 DEBUG("Copying port structure");
267 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
270 SP_API void sp_free_port(struct sp_port *port)
279 DEBUG("Freeing port structure");
283 if (port->description)
284 free(port->description);
285 if (port->usb_manufacturer)
286 free(port->usb_manufacturer);
287 if (port->usb_product)
288 free(port->usb_product);
289 if (port->usb_serial)
290 free(port->usb_serial);
291 if (port->bluetooth_address)
292 free(port->bluetooth_address);
295 free(port->usb_path);
303 SP_PRIV struct sp_port **list_append(struct sp_port **list,
304 const char *portname)
309 for (count = 0; list[count]; count++);
310 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
313 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
315 list[count + 1] = NULL;
319 sp_free_port_list(list);
323 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
325 struct sp_port **list;
328 TRACE("%p", list_ptr);
331 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
333 DEBUG("Enumerating ports");
335 if (!(list = malloc(sizeof(struct sp_port **))))
336 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
340 #ifdef NO_ENUMERATION
343 ret = list_ports(&list);
351 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
354 sp_free_port_list(list);
360 SP_API void sp_free_port_list(struct sp_port **list)
371 DEBUG("Freeing port list");
373 for (i = 0; list[i]; i++)
374 sp_free_port(list[i]);
380 #define CHECK_PORT() do { \
382 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
384 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
387 #define CHECK_PORT_HANDLE() do { \
388 if (port->hdl == INVALID_HANDLE_VALUE) \
389 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
392 #define CHECK_PORT_HANDLE() do { \
394 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
397 #define CHECK_OPEN_PORT() do { \
399 CHECK_PORT_HANDLE(); \
403 /** To be called after port receive buffer is emptied. */
404 static enum sp_return restart_wait(struct sp_port *port)
408 if (port->wait_running) {
409 /* Check status of running wait operation. */
410 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
411 &wait_result, FALSE)) {
412 DEBUG("Previous wait completed");
413 port->wait_running = FALSE;
414 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
415 DEBUG("Previous wait still running");
418 RETURN_FAIL("GetOverlappedResult() failed");
422 if (!port->wait_running) {
423 /* Start new wait operation. */
424 if (WaitCommEvent(port->hdl, &port->events,
426 DEBUG("New wait returned, events already pending");
427 } else if (GetLastError() == ERROR_IO_PENDING) {
428 DEBUG("New wait running in background");
429 port->wait_running = TRUE;
431 RETURN_FAIL("WaitCommEvent() failed");
439 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
441 struct port_data data;
442 struct sp_port_config config;
445 TRACE("%p, 0x%x", port, flags);
449 if (flags > SP_MODE_READ_WRITE)
450 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
452 DEBUG_FMT("Opening port %s", port->name);
455 DWORD desired_access = 0, flags_and_attributes = 0, errors;
456 char *escaped_port_name;
459 /* Prefix port name with '\\.\' to work with ports above COM9. */
460 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
461 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
462 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
464 /* Map 'flags' to the OS-specific settings. */
465 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
466 if (flags & SP_MODE_READ)
467 desired_access |= GENERIC_READ;
468 if (flags & SP_MODE_WRITE)
469 desired_access |= GENERIC_WRITE;
471 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
472 OPEN_EXISTING, flags_and_attributes, 0);
474 free(escaped_port_name);
476 if (port->hdl == INVALID_HANDLE_VALUE)
477 RETURN_FAIL("Port CreateFile() failed");
479 /* All timeouts initially disabled. */
480 port->timeouts.ReadIntervalTimeout = 0;
481 port->timeouts.ReadTotalTimeoutMultiplier = 0;
482 port->timeouts.ReadTotalTimeoutConstant = 0;
483 port->timeouts.WriteTotalTimeoutMultiplier = 0;
484 port->timeouts.WriteTotalTimeoutConstant = 0;
486 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
488 RETURN_FAIL("SetCommTimeouts() failed");
491 /* Prepare OVERLAPPED structures. */
492 #define INIT_OVERLAPPED(ovl) do { \
493 memset(&port->ovl, 0, sizeof(port->ovl)); \
494 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
495 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
496 == INVALID_HANDLE_VALUE) { \
498 RETURN_FAIL(#ovl "CreateEvent() failed"); \
502 INIT_OVERLAPPED(read_ovl);
503 INIT_OVERLAPPED(write_ovl);
504 INIT_OVERLAPPED(wait_ovl);
506 /* Set event mask for RX and error events. */
507 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
509 RETURN_FAIL("SetCommMask() failed");
512 port->writing = FALSE;
513 port->wait_running = FALSE;
515 ret = restart_wait(port);
522 int flags_local = O_NONBLOCK | O_NOCTTY;
524 /* Map 'flags' to the OS-specific settings. */
525 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
526 flags_local |= O_RDWR;
527 else if (flags & SP_MODE_READ)
528 flags_local |= O_RDONLY;
529 else if (flags & SP_MODE_WRITE)
530 flags_local |= O_WRONLY;
532 if ((port->fd = open(port->name, flags_local)) < 0)
533 RETURN_FAIL("open() failed");
536 ret = get_config(port, &data, &config);
543 /* Set sane port settings. */
545 data.dcb.fBinary = TRUE;
546 data.dcb.fDsrSensitivity = FALSE;
547 data.dcb.fErrorChar = FALSE;
548 data.dcb.fNull = FALSE;
549 data.dcb.fAbortOnError = FALSE;
551 /* Turn off all fancy termios tricks, give us a raw channel. */
552 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
554 data.term.c_iflag &= ~IUCLC;
556 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
558 data.term.c_oflag &= ~OLCUC;
561 data.term.c_oflag &= ~NLDLY;
564 data.term.c_oflag &= ~CRDLY;
567 data.term.c_oflag &= ~TABDLY;
570 data.term.c_oflag &= ~BSDLY;
573 data.term.c_oflag &= ~VTDLY;
576 data.term.c_oflag &= ~FFDLY;
579 data.term.c_oflag &= ~OFILL;
581 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
582 data.term.c_cc[VMIN] = 0;
583 data.term.c_cc[VTIME] = 0;
585 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
586 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
590 if (ClearCommError(port->hdl, &errors, &status) == 0)
591 RETURN_FAIL("ClearCommError() failed");
594 ret = set_config(port, &data, &config);
604 SP_API enum sp_return sp_close(struct sp_port *port)
610 DEBUG_FMT("Closing port %s", port->name);
613 /* Returns non-zero upon success, 0 upon failure. */
614 if (CloseHandle(port->hdl) == 0)
615 RETURN_FAIL("Port CloseHandle() failed");
616 port->hdl = INVALID_HANDLE_VALUE;
618 /* Close event handles for overlapped structures. */
619 #define CLOSE_OVERLAPPED(ovl) do { \
620 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
621 CloseHandle(port->ovl.hEvent) == 0) \
622 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
624 CLOSE_OVERLAPPED(read_ovl);
625 CLOSE_OVERLAPPED(write_ovl);
626 CLOSE_OVERLAPPED(wait_ovl);
629 /* Returns 0 upon success, -1 upon failure. */
630 if (close(port->fd) == -1)
631 RETURN_FAIL("close() failed");
638 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
640 TRACE("%p, 0x%x", port, buffers);
644 if (buffers > SP_BUF_BOTH)
645 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
647 const char *buffer_names[] = {"no", "input", "output", "both"};
649 DEBUG_FMT("Flushing %s buffers on port %s",
650 buffer_names[buffers], port->name);
654 if (buffers & SP_BUF_INPUT)
655 flags |= PURGE_RXCLEAR;
656 if (buffers & SP_BUF_OUTPUT)
657 flags |= PURGE_TXCLEAR;
659 /* Returns non-zero upon success, 0 upon failure. */
660 if (PurgeComm(port->hdl, flags) == 0)
661 RETURN_FAIL("PurgeComm() failed");
663 if (buffers & SP_BUF_INPUT)
664 TRY(restart_wait(port));
667 if (buffers == SP_BUF_BOTH)
669 else if (buffers == SP_BUF_INPUT)
671 else if (buffers == SP_BUF_OUTPUT)
674 /* Returns 0 upon success, -1 upon failure. */
675 if (tcflush(port->fd, flags) < 0)
676 RETURN_FAIL("tcflush() failed");
681 SP_API enum sp_return sp_drain(struct sp_port *port)
687 DEBUG_FMT("Draining port %s", port->name);
690 /* Returns non-zero upon success, 0 upon failure. */
691 if (FlushFileBuffers(port->hdl) == 0)
692 RETURN_FAIL("FlushFileBuffers() failed");
699 result = ioctl(port->fd, TCSBRK, &arg);
701 result = tcdrain(port->fd);
704 if (errno == EINTR) {
705 DEBUG("tcdrain() was interrupted");
708 RETURN_FAIL("tcdrain() failed");
717 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
718 size_t count, unsigned int timeout)
720 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
725 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
728 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
729 count, port->name, timeout);
731 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
738 DWORD bytes_written = 0;
741 /* Wait for previous non-blocking write to complete, if any. */
743 DEBUG("Waiting for previous write to complete");
744 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
747 RETURN_FAIL("Previous write failed to complete");
748 DEBUG("Previous write completed");
752 port->timeouts.WriteTotalTimeoutConstant = timeout;
753 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
754 RETURN_FAIL("SetCommTimeouts() failed");
757 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) {
758 if (GetLastError() == ERROR_IO_PENDING) {
759 DEBUG("Waiting for write to complete");
760 GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
761 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
762 RETURN_INT(bytes_written);
764 RETURN_FAIL("WriteFile() failed");
767 DEBUG("Write completed immediately");
771 size_t bytes_written = 0;
772 unsigned char *ptr = (unsigned char *) buf;
773 struct timeval start, delta, now, end = {0, 0};
778 /* Get time at start of operation. */
779 gettimeofday(&start, NULL);
780 /* Define duration of timeout. */
781 delta.tv_sec = timeout / 1000;
782 delta.tv_usec = (timeout % 1000) * 1000;
783 /* Calculate time at which we should give up. */
784 timeradd(&start, &delta, &end);
787 /* Loop until we have written the requested number of bytes. */
788 while (bytes_written < count) {
789 /* Wait until space is available. */
791 FD_SET(port->fd, &fds);
793 gettimeofday(&now, NULL);
794 if (timercmp(&now, &end, >)) {
795 DEBUG("Write timed out");
796 RETURN_INT(bytes_written);
798 timersub(&end, &now, &delta);
800 result = select(port->fd + 1, NULL, &fds, NULL, timeout ? &delta : NULL);
802 if (errno == EINTR) {
803 DEBUG("select() call was interrupted, repeating");
806 RETURN_FAIL("select() failed");
808 } else if (result == 0) {
809 DEBUG("Write timed out");
810 RETURN_INT(bytes_written);
814 result = write(port->fd, ptr, count - bytes_written);
818 /* This shouldn't happen because we did a select() first, but handle anyway. */
821 /* This is an actual failure. */
822 RETURN_FAIL("write() failed");
825 bytes_written += result;
829 RETURN_INT(bytes_written);
833 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
834 const void *buf, size_t count)
836 TRACE("%p, %p, %d", port, buf, count);
841 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
843 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
850 BYTE *ptr = (BYTE *) buf;
852 /* Check whether previous write is complete. */
854 if (HasOverlappedIoCompleted(&port->write_ovl)) {
855 DEBUG("Previous write completed");
858 DEBUG("Previous write not complete");
859 /* Can't take a new write until the previous one finishes. */
865 port->timeouts.WriteTotalTimeoutConstant = 0;
866 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
867 RETURN_FAIL("SetCommTimeouts() failed");
870 * Keep writing data until the OS has to actually start an async IO
871 * for it. At that point we know the buffer is full.
873 while (written < count) {
874 /* Copy first byte of user buffer. */
875 port->pending_byte = *ptr++;
877 /* Start asynchronous write. */
878 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
879 if (GetLastError() == ERROR_IO_PENDING) {
880 if (HasOverlappedIoCompleted(&port->write_ovl)) {
881 DEBUG("Asynchronous write completed immediately");
886 DEBUG("Asynchronous write running");
888 RETURN_INT(++written);
891 /* Actual failure of some kind. */
892 RETURN_FAIL("WriteFile() failed");
895 DEBUG("Single byte written immediately");
900 DEBUG("All bytes written immediately");
904 /* Returns the number of bytes written, or -1 upon failure. */
905 ssize_t written = write(port->fd, buf, count);
908 RETURN_FAIL("write() failed");
914 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
915 size_t count, unsigned int timeout)
917 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
922 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
925 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
926 count, port->name, timeout);
928 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
935 DWORD bytes_read = 0;
936 DWORD bytes_remaining;
940 port->timeouts.ReadIntervalTimeout = 0;
941 port->timeouts.ReadTotalTimeoutConstant = timeout;
942 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
943 RETURN_FAIL("SetCommTimeouts() failed");
946 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) {
947 if (GetLastError() == ERROR_IO_PENDING) {
948 DEBUG("Waiting for read to complete");
949 GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
950 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
952 RETURN_FAIL("ReadFile() failed");
955 DEBUG("Read completed immediately");
959 ret = sp_input_waiting(port);
964 bytes_remaining = ret;
966 /* Restart wait operation if buffer was emptied. */
967 if (bytes_read > 0 && bytes_remaining == 0)
968 TRY(restart_wait(port));
970 RETURN_INT(bytes_read);
973 size_t bytes_read = 0;
974 unsigned char *ptr = (unsigned char *) buf;
975 struct timeval start, delta, now, end = {0, 0};
980 /* Get time at start of operation. */
981 gettimeofday(&start, NULL);
982 /* Define duration of timeout. */
983 delta.tv_sec = timeout / 1000;
984 delta.tv_usec = (timeout % 1000) * 1000;
985 /* Calculate time at which we should give up. */
986 timeradd(&start, &delta, &end);
989 /* Loop until we have the requested number of bytes. */
990 while (bytes_read < count) {
991 /* Wait until data is available. */
993 FD_SET(port->fd, &fds);
995 gettimeofday(&now, NULL);
996 if (timercmp(&now, &end, >))
997 /* Timeout has expired. */
998 RETURN_INT(bytes_read);
999 timersub(&end, &now, &delta);
1001 result = select(port->fd + 1, &fds, NULL, NULL, timeout ? &delta : NULL);
1003 if (errno == EINTR) {
1004 DEBUG("select() call was interrupted, repeating");
1007 RETURN_FAIL("select() failed");
1009 } else if (result == 0) {
1010 DEBUG("Read timed out");
1011 RETURN_INT(bytes_read);
1015 result = read(port->fd, ptr, count - bytes_read);
1018 if (errno == EAGAIN)
1019 /* This shouldn't happen because we did a select() first, but handle anyway. */
1022 /* This is an actual failure. */
1023 RETURN_FAIL("read() failed");
1026 bytes_read += result;
1030 RETURN_INT(bytes_read);
1034 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1037 TRACE("%p, %p, %d", port, buf, count);
1042 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1044 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1048 DWORD bytes_remaining;
1052 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1053 port->timeouts.ReadTotalTimeoutConstant = 0;
1054 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1055 RETURN_FAIL("SetCommTimeouts() failed");
1058 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1059 RETURN_FAIL("ReadFile() failed");
1061 /* Get number of bytes read. */
1062 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1063 RETURN_FAIL("GetOverlappedResult() failed");
1065 ret = sp_input_waiting(port);
1068 RETURN_CODEVAL(ret);
1070 bytes_remaining = ret;
1072 /* Restart wait operation if buffer was emptied. */
1073 if (bytes_read > 0 && bytes_remaining == 0)
1074 TRY(restart_wait(port));
1076 RETURN_INT(bytes_read);
1080 /* Returns the number of bytes read, or -1 upon failure. */
1081 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1082 if (errno == EAGAIN)
1083 /* No bytes available. */
1086 /* This is an actual failure. */
1087 RETURN_FAIL("read() failed");
1089 RETURN_INT(bytes_read);
1093 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1099 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1105 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1106 RETURN_FAIL("ClearCommError() failed");
1107 RETURN_INT(comstat.cbInQue);
1110 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1111 RETURN_FAIL("TIOCINQ ioctl failed");
1112 RETURN_INT(bytes_waiting);
1116 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1122 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1128 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1129 RETURN_FAIL("ClearCommError() failed");
1130 RETURN_INT(comstat.cbOutQue);
1133 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1134 RETURN_FAIL("TIOCOUTQ ioctl failed");
1135 RETURN_INT(bytes_waiting);
1139 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1141 struct sp_event_set *result;
1143 TRACE("%p", result_ptr);
1146 RETURN_ERROR(SP_ERR_ARG, "Null result");
1150 if (!(result = malloc(sizeof(struct sp_event_set))))
1151 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1153 memset(result, 0, sizeof(struct sp_event_set));
1155 *result_ptr = result;
1160 static enum sp_return add_handle(struct sp_event_set *event_set,
1161 event_handle handle, enum sp_event mask)
1164 enum sp_event *new_masks;
1166 TRACE("%p, %d, %d", event_set, handle, mask);
1168 if (!(new_handles = realloc(event_set->handles,
1169 sizeof(event_handle) * (event_set->count + 1))))
1170 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1172 if (!(new_masks = realloc(event_set->masks,
1173 sizeof(enum sp_event) * (event_set->count + 1))))
1174 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1176 event_set->handles = new_handles;
1177 event_set->masks = new_masks;
1179 ((event_handle *) event_set->handles)[event_set->count] = handle;
1180 event_set->masks[event_set->count] = mask;
1187 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1188 const struct sp_port *port, enum sp_event mask)
1190 TRACE("%p, %p, %d", event_set, port, mask);
1193 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1196 RETURN_ERROR(SP_ERR_ARG, "Null port");
1198 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1199 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1205 enum sp_event handle_mask;
1206 if ((handle_mask = mask & SP_EVENT_TX_READY))
1207 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1208 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1209 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1211 TRY(add_handle(event_set, port->fd, mask));
1217 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1219 TRACE("%p", event_set);
1222 DEBUG("Null event set");
1226 DEBUG("Freeing event set");
1228 if (event_set->handles)
1229 free(event_set->handles);
1230 if (event_set->masks)
1231 free(event_set->masks);
1238 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1239 unsigned int timeout)
1241 TRACE("%p, %d", event_set, timeout);
1244 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1247 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1248 timeout ? timeout : INFINITE) == WAIT_FAILED)
1249 RETURN_FAIL("WaitForMultipleObjects() failed");
1253 struct timeval start, delta, now, end = {0, 0};
1254 int result, timeout_remaining;
1255 struct pollfd *pollfds;
1258 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1259 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1261 for (i = 0; i < event_set->count; i++) {
1262 pollfds[i].fd = ((int *) event_set->handles)[i];
1263 pollfds[i].events = 0;
1264 pollfds[i].revents = 0;
1265 if (event_set->masks[i] & SP_EVENT_RX_READY)
1266 pollfds[i].events |= POLLIN;
1267 if (event_set->masks[i] & SP_EVENT_TX_READY)
1268 pollfds[i].events |= POLLOUT;
1269 if (event_set->masks[i] & SP_EVENT_ERROR)
1270 pollfds[i].events |= POLLERR;
1274 /* Get time at start of operation. */
1275 gettimeofday(&start, NULL);
1276 /* Define duration of timeout. */
1277 delta.tv_sec = timeout / 1000;
1278 delta.tv_usec = (timeout % 1000) * 1000;
1279 /* Calculate time at which we should give up. */
1280 timeradd(&start, &delta, &end);
1283 /* Loop until an event occurs. */
1286 gettimeofday(&now, NULL);
1287 if (timercmp(&now, &end, >)) {
1288 DEBUG("Wait timed out");
1291 timersub(&end, &now, &delta);
1292 timeout_remaining = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1295 result = poll(pollfds, event_set->count, timeout ? timeout_remaining : -1);
1298 if (errno == EINTR) {
1299 DEBUG("poll() call was interrupted, repeating");
1303 RETURN_FAIL("poll() failed");
1305 } else if (result == 0) {
1306 DEBUG("poll() timed out");
1309 DEBUG("poll() completed");
1319 #ifdef USE_TERMIOS_SPEED
1320 static enum sp_return get_baudrate(int fd, int *baudrate)
1324 TRACE("%d, %p", fd, baudrate);
1326 DEBUG("Getting baud rate");
1328 if (!(data = malloc(get_termios_size())))
1329 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1331 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1333 RETURN_FAIL("Getting termios failed");
1336 *baudrate = get_termios_speed(data);
1343 static enum sp_return set_baudrate(int fd, int baudrate)
1347 TRACE("%d, %d", fd, baudrate);
1349 DEBUG("Getting baud rate");
1351 if (!(data = malloc(get_termios_size())))
1352 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1354 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1356 RETURN_FAIL("Getting termios failed");
1359 DEBUG("Setting baud rate");
1361 set_termios_speed(data, baudrate);
1363 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1365 RETURN_FAIL("Setting termios failed");
1372 #endif /* USE_TERMIOS_SPEED */
1375 static enum sp_return get_flow(int fd, struct port_data *data)
1379 TRACE("%d, %p", fd, data);
1381 DEBUG("Getting advanced flow control");
1383 if (!(termx = malloc(get_termiox_size())))
1384 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1386 if (ioctl(fd, TCGETX, termx) < 0) {
1388 RETURN_FAIL("Getting termiox failed");
1391 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1392 &data->dtr_flow, &data->dsr_flow);
1399 static enum sp_return set_flow(int fd, struct port_data *data)
1403 TRACE("%d, %p", fd, data);
1405 DEBUG("Getting advanced flow control");
1407 if (!(termx = malloc(get_termiox_size())))
1408 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1410 if (ioctl(fd, TCGETX, termx) < 0) {
1412 RETURN_FAIL("Getting termiox failed");
1415 DEBUG("Setting advanced flow control");
1417 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1418 data->dtr_flow, data->dsr_flow);
1420 if (ioctl(fd, TCSETX, termx) < 0) {
1422 RETURN_FAIL("Setting termiox failed");
1429 #endif /* USE_TERMIOX */
1431 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1432 struct sp_port_config *config)
1436 TRACE("%p, %p, %p", port, data, config);
1438 DEBUG_FMT("Getting configuration for port %s", port->name);
1441 if (!GetCommState(port->hdl, &data->dcb))
1442 RETURN_FAIL("GetCommState() failed");
1444 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1445 if (data->dcb.BaudRate == std_baudrates[i].index) {
1446 config->baudrate = std_baudrates[i].value;
1451 if (i == NUM_STD_BAUDRATES)
1452 /* BaudRate field can be either an index or a custom baud rate. */
1453 config->baudrate = data->dcb.BaudRate;
1455 config->bits = data->dcb.ByteSize;
1457 if (data->dcb.fParity)
1458 switch (data->dcb.Parity) {
1460 config->parity = SP_PARITY_NONE;
1463 config->parity = SP_PARITY_ODD;
1466 config->parity = SP_PARITY_EVEN;
1469 config->parity = SP_PARITY_MARK;
1472 config->parity = SP_PARITY_SPACE;
1475 config->parity = -1;
1478 config->parity = SP_PARITY_NONE;
1480 switch (data->dcb.StopBits) {
1482 config->stopbits = 1;
1485 config->stopbits = 2;
1488 config->stopbits = -1;
1491 switch (data->dcb.fRtsControl) {
1492 case RTS_CONTROL_DISABLE:
1493 config->rts = SP_RTS_OFF;
1495 case RTS_CONTROL_ENABLE:
1496 config->rts = SP_RTS_ON;
1498 case RTS_CONTROL_HANDSHAKE:
1499 config->rts = SP_RTS_FLOW_CONTROL;
1505 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1507 switch (data->dcb.fDtrControl) {
1508 case DTR_CONTROL_DISABLE:
1509 config->dtr = SP_DTR_OFF;
1511 case DTR_CONTROL_ENABLE:
1512 config->dtr = SP_DTR_ON;
1514 case DTR_CONTROL_HANDSHAKE:
1515 config->dtr = SP_DTR_FLOW_CONTROL;
1521 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1523 if (data->dcb.fInX) {
1524 if (data->dcb.fOutX)
1525 config->xon_xoff = SP_XONXOFF_INOUT;
1527 config->xon_xoff = SP_XONXOFF_IN;
1529 if (data->dcb.fOutX)
1530 config->xon_xoff = SP_XONXOFF_OUT;
1532 config->xon_xoff = SP_XONXOFF_DISABLED;
1537 if (tcgetattr(port->fd, &data->term) < 0)
1538 RETURN_FAIL("tcgetattr() failed");
1540 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1541 RETURN_FAIL("TIOCMGET ioctl failed");
1544 int ret = get_flow(port->fd, data);
1546 if (ret == SP_ERR_FAIL && errno == EINVAL)
1547 data->termiox_supported = 0;
1549 RETURN_CODEVAL(ret);
1551 data->termiox_supported = 1;
1553 data->termiox_supported = 0;
1556 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1557 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1558 config->baudrate = std_baudrates[i].value;
1563 if (i == NUM_STD_BAUDRATES) {
1565 config->baudrate = (int)data->term.c_ispeed;
1566 #elif defined(USE_TERMIOS_SPEED)
1567 TRY(get_baudrate(port->fd, &config->baudrate));
1569 config->baudrate = -1;
1573 switch (data->term.c_cflag & CSIZE) {
1590 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1591 config->parity = SP_PARITY_NONE;
1592 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1593 config->parity = -1;
1595 else if (data->term.c_cflag & CMSPAR)
1596 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1599 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1601 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1603 if (data->term.c_cflag & CRTSCTS) {
1604 config->rts = SP_RTS_FLOW_CONTROL;
1605 config->cts = SP_CTS_FLOW_CONTROL;
1607 if (data->termiox_supported && data->rts_flow)
1608 config->rts = SP_RTS_FLOW_CONTROL;
1610 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1612 config->cts = (data->termiox_supported && data->cts_flow) ?
1613 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1616 if (data->termiox_supported && data->dtr_flow)
1617 config->dtr = SP_DTR_FLOW_CONTROL;
1619 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1621 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1622 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1624 if (data->term.c_iflag & IXOFF) {
1625 if (data->term.c_iflag & IXON)
1626 config->xon_xoff = SP_XONXOFF_INOUT;
1628 config->xon_xoff = SP_XONXOFF_IN;
1630 if (data->term.c_iflag & IXON)
1631 config->xon_xoff = SP_XONXOFF_OUT;
1633 config->xon_xoff = SP_XONXOFF_DISABLED;
1640 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1641 const struct sp_port_config *config)
1645 BAUD_TYPE baud_nonstd;
1649 #ifdef USE_TERMIOS_SPEED
1650 int baud_nonstd = 0;
1653 TRACE("%p, %p, %p", port, data, config);
1655 DEBUG_FMT("Setting configuration for port %s", port->name);
1658 if (config->baudrate >= 0) {
1659 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1660 if (config->baudrate == std_baudrates[i].value) {
1661 data->dcb.BaudRate = std_baudrates[i].index;
1666 if (i == NUM_STD_BAUDRATES)
1667 data->dcb.BaudRate = config->baudrate;
1670 if (config->bits >= 0)
1671 data->dcb.ByteSize = config->bits;
1673 if (config->parity >= 0) {
1674 switch (config->parity) {
1675 case SP_PARITY_NONE:
1676 data->dcb.Parity = NOPARITY;
1679 data->dcb.Parity = ODDPARITY;
1681 case SP_PARITY_EVEN:
1682 data->dcb.Parity = EVENPARITY;
1684 case SP_PARITY_MARK:
1685 data->dcb.Parity = MARKPARITY;
1687 case SP_PARITY_SPACE:
1688 data->dcb.Parity = SPACEPARITY;
1691 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1695 if (config->stopbits >= 0) {
1696 switch (config->stopbits) {
1697 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1699 data->dcb.StopBits = ONESTOPBIT;
1702 data->dcb.StopBits = TWOSTOPBITS;
1705 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1709 if (config->rts >= 0) {
1710 switch (config->rts) {
1712 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1715 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1717 case SP_RTS_FLOW_CONTROL:
1718 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1721 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1725 if (config->cts >= 0) {
1726 switch (config->cts) {
1728 data->dcb.fOutxCtsFlow = FALSE;
1730 case SP_CTS_FLOW_CONTROL:
1731 data->dcb.fOutxCtsFlow = TRUE;
1734 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1738 if (config->dtr >= 0) {
1739 switch (config->dtr) {
1741 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1744 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1746 case SP_DTR_FLOW_CONTROL:
1747 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1750 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1754 if (config->dsr >= 0) {
1755 switch (config->dsr) {
1757 data->dcb.fOutxDsrFlow = FALSE;
1759 case SP_DSR_FLOW_CONTROL:
1760 data->dcb.fOutxDsrFlow = TRUE;
1763 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1767 if (config->xon_xoff >= 0) {
1768 switch (config->xon_xoff) {
1769 case SP_XONXOFF_DISABLED:
1770 data->dcb.fInX = FALSE;
1771 data->dcb.fOutX = FALSE;
1774 data->dcb.fInX = TRUE;
1775 data->dcb.fOutX = FALSE;
1777 case SP_XONXOFF_OUT:
1778 data->dcb.fInX = FALSE;
1779 data->dcb.fOutX = TRUE;
1781 case SP_XONXOFF_INOUT:
1782 data->dcb.fInX = TRUE;
1783 data->dcb.fOutX = TRUE;
1786 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1790 if (!SetCommState(port->hdl, &data->dcb))
1791 RETURN_FAIL("SetCommState() failed");
1797 if (config->baudrate >= 0) {
1798 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1799 if (config->baudrate == std_baudrates[i].value) {
1800 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1801 RETURN_FAIL("cfsetospeed() failed");
1803 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1804 RETURN_FAIL("cfsetispeed() failed");
1809 /* Non-standard baud rate */
1810 if (i == NUM_STD_BAUDRATES) {
1812 /* Set "dummy" baud rate. */
1813 if (cfsetspeed(&data->term, B9600) < 0)
1814 RETURN_FAIL("cfsetspeed() failed");
1815 baud_nonstd = config->baudrate;
1816 #elif defined(USE_TERMIOS_SPEED)
1819 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1824 if (config->bits >= 0) {
1825 data->term.c_cflag &= ~CSIZE;
1826 switch (config->bits) {
1828 data->term.c_cflag |= CS8;
1831 data->term.c_cflag |= CS7;
1834 data->term.c_cflag |= CS6;
1837 data->term.c_cflag |= CS5;
1840 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1844 if (config->parity >= 0) {
1845 data->term.c_iflag &= ~IGNPAR;
1846 data->term.c_cflag &= ~(PARENB | PARODD);
1848 data->term.c_cflag &= ~CMSPAR;
1850 switch (config->parity) {
1851 case SP_PARITY_NONE:
1852 data->term.c_iflag |= IGNPAR;
1854 case SP_PARITY_EVEN:
1855 data->term.c_cflag |= PARENB;
1858 data->term.c_cflag |= PARENB | PARODD;
1861 case SP_PARITY_MARK:
1862 data->term.c_cflag |= PARENB | PARODD;
1863 data->term.c_cflag |= CMSPAR;
1865 case SP_PARITY_SPACE:
1866 data->term.c_cflag |= PARENB;
1867 data->term.c_cflag |= CMSPAR;
1870 case SP_PARITY_MARK:
1871 case SP_PARITY_SPACE:
1872 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1875 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1879 if (config->stopbits >= 0) {
1880 data->term.c_cflag &= ~CSTOPB;
1881 switch (config->stopbits) {
1883 data->term.c_cflag &= ~CSTOPB;
1886 data->term.c_cflag |= CSTOPB;
1889 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1893 if (config->rts >= 0 || config->cts >= 0) {
1894 if (data->termiox_supported) {
1895 data->rts_flow = data->cts_flow = 0;
1896 switch (config->rts) {
1899 controlbits = TIOCM_RTS;
1900 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1901 RETURN_FAIL("Setting RTS signal level failed");
1903 case SP_RTS_FLOW_CONTROL:
1909 if (config->cts == SP_CTS_FLOW_CONTROL)
1912 if (data->rts_flow && data->cts_flow)
1913 data->term.c_iflag |= CRTSCTS;
1915 data->term.c_iflag &= ~CRTSCTS;
1917 /* Asymmetric use of RTS/CTS not supported. */
1918 if (data->term.c_iflag & CRTSCTS) {
1919 /* Flow control can only be disabled for both RTS & CTS together. */
1920 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1921 if (config->cts != SP_CTS_IGNORE)
1922 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1924 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1925 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1926 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1929 /* Flow control can only be enabled for both RTS & CTS together. */
1930 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1931 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1932 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1935 if (config->rts >= 0) {
1936 if (config->rts == SP_RTS_FLOW_CONTROL) {
1937 data->term.c_iflag |= CRTSCTS;
1939 controlbits = TIOCM_RTS;
1940 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1942 RETURN_FAIL("Setting RTS signal level failed");
1948 if (config->dtr >= 0 || config->dsr >= 0) {
1949 if (data->termiox_supported) {
1950 data->dtr_flow = data->dsr_flow = 0;
1951 switch (config->dtr) {
1954 controlbits = TIOCM_DTR;
1955 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1956 RETURN_FAIL("Setting DTR signal level failed");
1958 case SP_DTR_FLOW_CONTROL:
1964 if (config->dsr == SP_DSR_FLOW_CONTROL)
1967 /* DTR/DSR flow control not supported. */
1968 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1969 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1971 if (config->dtr >= 0) {
1972 controlbits = TIOCM_DTR;
1973 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1975 RETURN_FAIL("Setting DTR signal level failed");
1980 if (config->xon_xoff >= 0) {
1981 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1982 switch (config->xon_xoff) {
1983 case SP_XONXOFF_DISABLED:
1986 data->term.c_iflag |= IXOFF;
1988 case SP_XONXOFF_OUT:
1989 data->term.c_iflag |= IXON | IXANY;
1991 case SP_XONXOFF_INOUT:
1992 data->term.c_iflag |= IXON | IXOFF | IXANY;
1995 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1999 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2000 RETURN_FAIL("tcsetattr() failed");
2003 if (baud_nonstd != B0) {
2004 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2005 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2007 * Set baud rates in data->term to correct, but incompatible
2008 * with tcsetattr() value, same as delivered by tcgetattr().
2010 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2011 RETURN_FAIL("cfsetspeed() failed");
2013 #elif defined(__linux__)
2014 #ifdef USE_TERMIOS_SPEED
2016 TRY(set_baudrate(port->fd, config->baudrate));
2019 if (data->termiox_supported)
2020 TRY(set_flow(port->fd, data));
2024 #endif /* !_WIN32 */
2029 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2031 struct sp_port_config *config;
2033 TRACE("%p", config_ptr);
2036 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2040 if (!(config = malloc(sizeof(struct sp_port_config))))
2041 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2043 config->baudrate = -1;
2045 config->parity = -1;
2046 config->stopbits = -1;
2052 *config_ptr = config;
2057 SP_API void sp_free_config(struct sp_port_config *config)
2059 TRACE("%p", config);
2062 DEBUG("Null config");
2069 SP_API enum sp_return sp_get_config(struct sp_port *port,
2070 struct sp_port_config *config)
2072 struct port_data data;
2074 TRACE("%p, %p", port, config);
2079 RETURN_ERROR(SP_ERR_ARG, "Null config");
2081 TRY(get_config(port, &data, config));
2086 SP_API enum sp_return sp_set_config(struct sp_port *port,
2087 const struct sp_port_config *config)
2089 struct port_data data;
2090 struct sp_port_config prev_config;
2092 TRACE("%p, %p", port, config);
2097 RETURN_ERROR(SP_ERR_ARG, "Null config");
2099 TRY(get_config(port, &data, &prev_config));
2100 TRY(set_config(port, &data, config));
2105 #define CREATE_ACCESSORS(x, type) \
2106 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2107 struct port_data data; \
2108 struct sp_port_config config; \
2109 TRACE("%p, %d", port, x); \
2110 CHECK_OPEN_PORT(); \
2111 TRY(get_config(port, &data, &config)); \
2113 TRY(set_config(port, &data, &config)); \
2116 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2118 TRACE("%p, %p", config, x); \
2120 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2124 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2126 TRACE("%p, %d", config, x); \
2128 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2133 CREATE_ACCESSORS(baudrate, int)
2134 CREATE_ACCESSORS(bits, int)
2135 CREATE_ACCESSORS(parity, enum sp_parity)
2136 CREATE_ACCESSORS(stopbits, int)
2137 CREATE_ACCESSORS(rts, enum sp_rts)
2138 CREATE_ACCESSORS(cts, enum sp_cts)
2139 CREATE_ACCESSORS(dtr, enum sp_dtr)
2140 CREATE_ACCESSORS(dsr, enum sp_dsr)
2141 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2143 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2144 enum sp_flowcontrol flowcontrol)
2147 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2149 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2150 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2152 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2153 config->xon_xoff = SP_XONXOFF_INOUT;
2155 config->xon_xoff = SP_XONXOFF_DISABLED;
2157 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2158 config->rts = SP_RTS_FLOW_CONTROL;
2159 config->cts = SP_CTS_FLOW_CONTROL;
2161 if (config->rts == SP_RTS_FLOW_CONTROL)
2162 config->rts = SP_RTS_ON;
2163 config->cts = SP_CTS_IGNORE;
2166 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2167 config->dtr = SP_DTR_FLOW_CONTROL;
2168 config->dsr = SP_DSR_FLOW_CONTROL;
2170 if (config->dtr == SP_DTR_FLOW_CONTROL)
2171 config->dtr = SP_DTR_ON;
2172 config->dsr = SP_DSR_IGNORE;
2178 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2179 enum sp_flowcontrol flowcontrol)
2181 struct port_data data;
2182 struct sp_port_config config;
2184 TRACE("%p, %d", port, flowcontrol);
2188 TRY(get_config(port, &data, &config));
2190 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2192 TRY(set_config(port, &data, &config));
2197 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2198 enum sp_signal *signals)
2200 TRACE("%p, %p", port, signals);
2205 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2207 DEBUG_FMT("Getting control signals for port %s", port->name);
2212 if (GetCommModemStatus(port->hdl, &bits) == 0)
2213 RETURN_FAIL("GetCommModemStatus() failed");
2214 if (bits & MS_CTS_ON)
2215 *signals |= SP_SIG_CTS;
2216 if (bits & MS_DSR_ON)
2217 *signals |= SP_SIG_DSR;
2218 if (bits & MS_RLSD_ON)
2219 *signals |= SP_SIG_DCD;
2220 if (bits & MS_RING_ON)
2221 *signals |= SP_SIG_RI;
2224 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2225 RETURN_FAIL("TIOCMGET ioctl failed");
2226 if (bits & TIOCM_CTS)
2227 *signals |= SP_SIG_CTS;
2228 if (bits & TIOCM_DSR)
2229 *signals |= SP_SIG_DSR;
2230 if (bits & TIOCM_CAR)
2231 *signals |= SP_SIG_DCD;
2232 if (bits & TIOCM_RNG)
2233 *signals |= SP_SIG_RI;
2238 SP_API enum sp_return sp_start_break(struct sp_port *port)
2244 if (SetCommBreak(port->hdl) == 0)
2245 RETURN_FAIL("SetCommBreak() failed");
2247 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2248 RETURN_FAIL("TIOCSBRK ioctl failed");
2254 SP_API enum sp_return sp_end_break(struct sp_port *port)
2260 if (ClearCommBreak(port->hdl) == 0)
2261 RETURN_FAIL("ClearCommBreak() failed");
2263 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2264 RETURN_FAIL("TIOCCBRK ioctl failed");
2270 SP_API int sp_last_error_code(void)
2274 RETURN_INT(GetLastError());
2280 SP_API char *sp_last_error_message(void)
2286 DWORD error = GetLastError();
2289 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2290 FORMAT_MESSAGE_FROM_SYSTEM |
2291 FORMAT_MESSAGE_IGNORE_INSERTS,
2294 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2298 RETURN_STRING(message);
2300 RETURN_STRING(strerror(errno));
2304 SP_API void sp_free_error_message(char *message)
2306 TRACE("%s", message);
2317 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2319 TRACE("%p", handler);
2321 sp_debug_handler = handler;
2326 SP_API void sp_default_debug_handler(const char *format, ...)
2329 va_start(args, format);
2330 if (getenv("LIBSERIALPORT_DEBUG")) {
2331 fputs("sp: ", stderr);
2332 vfprintf(stderr, format, args);
2337 SP_API int sp_get_major_package_version(void)
2339 return SP_PACKAGE_VERSION_MAJOR;
2342 SP_API int sp_get_minor_package_version(void)
2344 return SP_PACKAGE_VERSION_MINOR;
2347 SP_API int sp_get_micro_package_version(void)
2349 return SP_PACKAGE_VERSION_MICRO;
2352 SP_API const char *sp_get_package_version_string(void)
2354 return SP_PACKAGE_VERSION_STRING;
2357 SP_API int sp_get_current_lib_version(void)
2359 return SP_LIB_VERSION_CURRENT;
2362 SP_API int sp_get_revision_lib_version(void)
2364 return SP_LIB_VERSION_REVISION;
2367 SP_API int sp_get_age_lib_version(void)
2369 return SP_LIB_VERSION_AGE;
2372 SP_API const char *sp_get_lib_version_string(void)
2374 return SP_LIB_VERSION_STRING;