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(const struct sp_port *port)
133 if (!port || !port->description)
136 RETURN_STRING(port->description);
139 SP_API enum sp_transport sp_get_port_transport(const 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");
238 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
241 HANDLE *handle_ptr = result_ptr;
242 *handle_ptr = port->hdl;
244 int *fd_ptr = result_ptr;
251 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
252 struct sp_port **copy_ptr)
254 TRACE("%p, %p", port, copy_ptr);
257 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
262 RETURN_ERROR(SP_ERR_ARG, "Null port");
265 RETURN_ERROR(SP_ERR_ARG, "Null port name");
267 DEBUG("Copying port structure");
269 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
272 SP_API void sp_free_port(struct sp_port *port)
281 DEBUG("Freeing port structure");
285 if (port->description)
286 free(port->description);
287 if (port->usb_manufacturer)
288 free(port->usb_manufacturer);
289 if (port->usb_product)
290 free(port->usb_product);
291 if (port->usb_serial)
292 free(port->usb_serial);
293 if (port->bluetooth_address)
294 free(port->bluetooth_address);
297 free(port->usb_path);
305 SP_PRIV struct sp_port **list_append(struct sp_port **list,
306 const char *portname)
311 for (count = 0; list[count]; count++);
312 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
315 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
317 list[count + 1] = NULL;
321 sp_free_port_list(list);
325 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
327 #ifndef NO_ENUMERATION
328 struct sp_port **list;
332 TRACE("%p", list_ptr);
335 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
339 #ifdef NO_ENUMERATION
340 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
342 DEBUG("Enumerating ports");
344 if (!(list = malloc(sizeof(struct sp_port *))))
345 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
349 ret = list_ports(&list);
354 sp_free_port_list(list);
362 SP_API void sp_free_port_list(struct sp_port **list)
373 DEBUG("Freeing port list");
375 for (i = 0; list[i]; i++)
376 sp_free_port(list[i]);
382 #define CHECK_PORT() do { \
384 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
386 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
389 #define CHECK_PORT_HANDLE() do { \
390 if (port->hdl == INVALID_HANDLE_VALUE) \
391 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
394 #define CHECK_PORT_HANDLE() do { \
396 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
399 #define CHECK_OPEN_PORT() do { \
401 CHECK_PORT_HANDLE(); \
405 /** To be called after port receive buffer is emptied. */
406 static enum sp_return restart_wait(struct sp_port *port)
410 if (port->wait_running) {
411 /* Check status of running wait operation. */
412 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
413 &wait_result, FALSE)) {
414 DEBUG("Previous wait completed");
415 port->wait_running = FALSE;
416 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
417 DEBUG("Previous wait still running");
420 RETURN_FAIL("GetOverlappedResult() failed");
424 if (!port->wait_running) {
425 /* Start new wait operation. */
426 if (WaitCommEvent(port->hdl, &port->events,
428 DEBUG("New wait returned, events already pending");
429 } else if (GetLastError() == ERROR_IO_PENDING) {
430 DEBUG("New wait running in background");
431 port->wait_running = TRUE;
433 RETURN_FAIL("WaitCommEvent() failed");
441 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
443 struct port_data data;
444 struct sp_port_config config;
447 TRACE("%p, 0x%x", port, flags);
451 if (flags > SP_MODE_READ_WRITE)
452 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
454 DEBUG_FMT("Opening port %s", port->name);
457 DWORD desired_access = 0, flags_and_attributes = 0, errors;
458 char *escaped_port_name;
461 /* Prefix port name with '\\.\' to work with ports above COM9. */
462 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
463 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
464 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
466 /* Map 'flags' to the OS-specific settings. */
467 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
468 if (flags & SP_MODE_READ)
469 desired_access |= GENERIC_READ;
470 if (flags & SP_MODE_WRITE)
471 desired_access |= GENERIC_WRITE;
473 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
474 OPEN_EXISTING, flags_and_attributes, 0);
476 free(escaped_port_name);
478 if (port->hdl == INVALID_HANDLE_VALUE)
479 RETURN_FAIL("Port CreateFile() failed");
481 /* All timeouts initially disabled. */
482 port->timeouts.ReadIntervalTimeout = 0;
483 port->timeouts.ReadTotalTimeoutMultiplier = 0;
484 port->timeouts.ReadTotalTimeoutConstant = 0;
485 port->timeouts.WriteTotalTimeoutMultiplier = 0;
486 port->timeouts.WriteTotalTimeoutConstant = 0;
488 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
490 RETURN_FAIL("SetCommTimeouts() failed");
493 /* Prepare OVERLAPPED structures. */
494 #define INIT_OVERLAPPED(ovl) do { \
495 memset(&port->ovl, 0, sizeof(port->ovl)); \
496 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
497 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
498 == INVALID_HANDLE_VALUE) { \
500 RETURN_FAIL(#ovl "CreateEvent() failed"); \
504 INIT_OVERLAPPED(read_ovl);
505 INIT_OVERLAPPED(write_ovl);
506 INIT_OVERLAPPED(wait_ovl);
508 /* Set event mask for RX and error events. */
509 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
511 RETURN_FAIL("SetCommMask() failed");
514 port->writing = FALSE;
515 port->wait_running = FALSE;
517 ret = restart_wait(port);
524 int flags_local = O_NONBLOCK | O_NOCTTY;
526 /* Map 'flags' to the OS-specific settings. */
527 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
528 flags_local |= O_RDWR;
529 else if (flags & SP_MODE_READ)
530 flags_local |= O_RDONLY;
531 else if (flags & SP_MODE_WRITE)
532 flags_local |= O_WRONLY;
534 if ((port->fd = open(port->name, flags_local)) < 0)
535 RETURN_FAIL("open() failed");
538 ret = get_config(port, &data, &config);
545 /* Set sane port settings. */
547 data.dcb.fBinary = TRUE;
548 data.dcb.fDsrSensitivity = FALSE;
549 data.dcb.fErrorChar = FALSE;
550 data.dcb.fNull = FALSE;
551 data.dcb.fAbortOnError = FALSE;
553 /* Turn off all fancy termios tricks, give us a raw channel. */
554 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
556 data.term.c_iflag &= ~IUCLC;
558 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
560 data.term.c_oflag &= ~OLCUC;
563 data.term.c_oflag &= ~NLDLY;
566 data.term.c_oflag &= ~CRDLY;
569 data.term.c_oflag &= ~TABDLY;
572 data.term.c_oflag &= ~BSDLY;
575 data.term.c_oflag &= ~VTDLY;
578 data.term.c_oflag &= ~FFDLY;
581 data.term.c_oflag &= ~OFILL;
583 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
584 data.term.c_cc[VMIN] = 0;
585 data.term.c_cc[VTIME] = 0;
587 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
588 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
592 if (ClearCommError(port->hdl, &errors, &status) == 0)
593 RETURN_FAIL("ClearCommError() failed");
596 ret = set_config(port, &data, &config);
606 SP_API enum sp_return sp_close(struct sp_port *port)
612 DEBUG_FMT("Closing port %s", port->name);
615 /* Returns non-zero upon success, 0 upon failure. */
616 if (CloseHandle(port->hdl) == 0)
617 RETURN_FAIL("Port CloseHandle() failed");
618 port->hdl = INVALID_HANDLE_VALUE;
620 /* Close event handles for overlapped structures. */
621 #define CLOSE_OVERLAPPED(ovl) do { \
622 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
623 CloseHandle(port->ovl.hEvent) == 0) \
624 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
626 CLOSE_OVERLAPPED(read_ovl);
627 CLOSE_OVERLAPPED(write_ovl);
628 CLOSE_OVERLAPPED(wait_ovl);
631 /* Returns 0 upon success, -1 upon failure. */
632 if (close(port->fd) == -1)
633 RETURN_FAIL("close() failed");
640 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
642 TRACE("%p, 0x%x", port, buffers);
646 if (buffers > SP_BUF_BOTH)
647 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
649 const char *buffer_names[] = {"no", "input", "output", "both"};
651 DEBUG_FMT("Flushing %s buffers on port %s",
652 buffer_names[buffers], port->name);
656 if (buffers & SP_BUF_INPUT)
657 flags |= PURGE_RXCLEAR;
658 if (buffers & SP_BUF_OUTPUT)
659 flags |= PURGE_TXCLEAR;
661 /* Returns non-zero upon success, 0 upon failure. */
662 if (PurgeComm(port->hdl, flags) == 0)
663 RETURN_FAIL("PurgeComm() failed");
665 if (buffers & SP_BUF_INPUT)
666 TRY(restart_wait(port));
669 if (buffers == SP_BUF_BOTH)
671 else if (buffers == SP_BUF_INPUT)
673 else if (buffers == SP_BUF_OUTPUT)
676 /* Returns 0 upon success, -1 upon failure. */
677 if (tcflush(port->fd, flags) < 0)
678 RETURN_FAIL("tcflush() failed");
683 SP_API enum sp_return sp_drain(struct sp_port *port)
689 DEBUG_FMT("Draining port %s", port->name);
692 /* Returns non-zero upon success, 0 upon failure. */
693 if (FlushFileBuffers(port->hdl) == 0)
694 RETURN_FAIL("FlushFileBuffers() failed");
701 result = ioctl(port->fd, TCSBRK, &arg);
703 result = tcdrain(port->fd);
706 if (errno == EINTR) {
707 DEBUG("tcdrain() was interrupted");
710 RETURN_FAIL("tcdrain() failed");
719 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
720 size_t count, unsigned int timeout_ms)
722 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
727 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
730 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
731 count, port->name, timeout_ms);
733 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
740 DWORD bytes_written = 0;
743 /* Wait for previous non-blocking write to complete, if any. */
745 DEBUG("Waiting for previous write to complete");
746 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
749 RETURN_FAIL("Previous write failed to complete");
750 DEBUG("Previous write completed");
754 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
755 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
756 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
757 RETURN_FAIL("SetCommTimeouts() failed");
761 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
762 DEBUG("Write completed immediately");
764 } else if (GetLastError() == ERROR_IO_PENDING) {
765 DEBUG("Waiting for write to complete");
766 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0)
767 RETURN_FAIL("GetOverlappedResult() failed");
768 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
769 RETURN_INT(bytes_written);
771 RETURN_FAIL("WriteFile() failed");
774 size_t bytes_written = 0;
775 unsigned char *ptr = (unsigned char *) buf;
776 struct timeval start, delta, now, end = {0, 0};
782 /* Get time at start of operation. */
783 gettimeofday(&start, NULL);
784 /* Define duration of timeout. */
785 delta.tv_sec = timeout_ms / 1000;
786 delta.tv_usec = (timeout_ms % 1000) * 1000;
787 /* Calculate time at which we should give up. */
788 timeradd(&start, &delta, &end);
792 FD_SET(port->fd, &fds);
794 /* Loop until we have written the requested number of bytes. */
795 while (bytes_written < count) {
797 * Check timeout only if we have run select() at least once,
798 * to avoid any issues if a short timeout is reached before
799 * select() is even run.
801 if (timeout_ms && started) {
802 gettimeofday(&now, NULL);
803 if (timercmp(&now, &end, >))
804 /* Timeout has expired. */
806 timersub(&end, &now, &delta);
808 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
811 if (errno == EINTR) {
812 DEBUG("select() call was interrupted, repeating");
815 RETURN_FAIL("select() failed");
817 } else if (result == 0) {
818 /* Timeout has expired. */
823 result = write(port->fd, ptr, count - bytes_written);
827 /* This shouldn't happen because we did a select() first, but handle anyway. */
830 /* This is an actual failure. */
831 RETURN_FAIL("write() failed");
834 bytes_written += result;
838 if (bytes_written < count)
839 DEBUG("Write timed out");
841 RETURN_INT(bytes_written);
845 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
846 const void *buf, size_t count)
848 TRACE("%p, %p, %d", port, buf, count);
853 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
855 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
862 BYTE *ptr = (BYTE *) buf;
864 /* Check whether previous write is complete. */
866 if (HasOverlappedIoCompleted(&port->write_ovl)) {
867 DEBUG("Previous write completed");
870 DEBUG("Previous write not complete");
871 /* Can't take a new write until the previous one finishes. */
877 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
878 port->timeouts.WriteTotalTimeoutConstant = 0;
879 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
880 RETURN_FAIL("SetCommTimeouts() failed");
884 * Keep writing data until the OS has to actually start an async IO
885 * for it. At that point we know the buffer is full.
887 while (written < count) {
888 /* Copy first byte of user buffer. */
889 port->pending_byte = *ptr++;
891 /* Start asynchronous write. */
892 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
893 if (GetLastError() == ERROR_IO_PENDING) {
894 if (HasOverlappedIoCompleted(&port->write_ovl)) {
895 DEBUG("Asynchronous write completed immediately");
900 DEBUG("Asynchronous write running");
902 RETURN_INT(++written);
905 /* Actual failure of some kind. */
906 RETURN_FAIL("WriteFile() failed");
909 DEBUG("Single byte written immediately");
914 DEBUG("All bytes written immediately");
918 /* Returns the number of bytes written, or -1 upon failure. */
919 ssize_t written = write(port->fd, buf, count);
922 RETURN_FAIL("write() failed");
929 /* Restart wait operation if buffer was emptied. */
930 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
938 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
939 RETURN_FAIL("ClearCommError() failed");
941 if (comstat.cbInQue == 0)
942 TRY(restart_wait(port));
948 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
949 size_t count, unsigned int timeout_ms)
951 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
956 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
959 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
960 count, port->name, timeout_ms);
962 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
969 DWORD bytes_read = 0;
972 if (port->timeouts.ReadIntervalTimeout != 0 ||
973 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
974 port->timeouts.ReadIntervalTimeout = 0;
975 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
976 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
977 RETURN_FAIL("SetCommTimeouts() failed");
981 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
982 DEBUG("Read completed immediately");
984 } else if (GetLastError() == ERROR_IO_PENDING) {
985 DEBUG("Waiting for read to complete");
986 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
987 RETURN_FAIL("GetOverlappedResult() failed");
988 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
990 RETURN_FAIL("ReadFile() failed");
993 TRY(restart_wait_if_needed(port, bytes_read));
995 RETURN_INT(bytes_read);
998 size_t bytes_read = 0;
999 unsigned char *ptr = (unsigned char *) buf;
1000 struct timeval start, delta, now, end = {0, 0};
1006 /* Get time at start of operation. */
1007 gettimeofday(&start, NULL);
1008 /* Define duration of timeout. */
1009 delta.tv_sec = timeout_ms / 1000;
1010 delta.tv_usec = (timeout_ms % 1000) * 1000;
1011 /* Calculate time at which we should give up. */
1012 timeradd(&start, &delta, &end);
1016 FD_SET(port->fd, &fds);
1018 /* Loop until we have the requested number of bytes. */
1019 while (bytes_read < count) {
1021 * Check timeout only if we have run select() at least once,
1022 * to avoid any issues if a short timeout is reached before
1023 * select() is even run.
1025 if (timeout_ms && started) {
1026 gettimeofday(&now, NULL);
1027 if (timercmp(&now, &end, >))
1028 /* Timeout has expired. */
1030 timersub(&end, &now, &delta);
1032 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1035 if (errno == EINTR) {
1036 DEBUG("select() call was interrupted, repeating");
1039 RETURN_FAIL("select() failed");
1041 } else if (result == 0) {
1042 /* Timeout has expired. */
1047 result = read(port->fd, ptr, count - bytes_read);
1050 if (errno == EAGAIN)
1052 * This shouldn't happen because we did a
1053 * select() first, but handle anyway.
1057 /* This is an actual failure. */
1058 RETURN_FAIL("read() failed");
1061 bytes_read += result;
1065 if (bytes_read < count)
1066 DEBUG("Read timed out");
1068 RETURN_INT(bytes_read);
1072 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1075 TRACE("%p, %p, %d", port, buf, count);
1080 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1082 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1088 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1089 port->timeouts.ReadTotalTimeoutConstant != 0) {
1090 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1091 port->timeouts.ReadTotalTimeoutConstant = 0;
1092 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1093 RETURN_FAIL("SetCommTimeouts() failed");
1097 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1098 RETURN_FAIL("ReadFile() failed");
1100 /* Get number of bytes read. */
1101 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1102 RETURN_FAIL("GetOverlappedResult() failed");
1104 TRY(restart_wait_if_needed(port, bytes_read));
1106 RETURN_INT(bytes_read);
1110 /* Returns the number of bytes read, or -1 upon failure. */
1111 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1112 if (errno == EAGAIN)
1113 /* No bytes available. */
1116 /* This is an actual failure. */
1117 RETURN_FAIL("read() failed");
1119 RETURN_INT(bytes_read);
1123 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1129 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1135 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1136 RETURN_FAIL("ClearCommError() failed");
1137 RETURN_INT(comstat.cbInQue);
1140 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1141 RETURN_FAIL("TIOCINQ ioctl failed");
1142 RETURN_INT(bytes_waiting);
1146 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1152 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1158 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1159 RETURN_FAIL("ClearCommError() failed");
1160 RETURN_INT(comstat.cbOutQue);
1163 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1164 RETURN_FAIL("TIOCOUTQ ioctl failed");
1165 RETURN_INT(bytes_waiting);
1169 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1171 struct sp_event_set *result;
1173 TRACE("%p", result_ptr);
1176 RETURN_ERROR(SP_ERR_ARG, "Null result");
1180 if (!(result = malloc(sizeof(struct sp_event_set))))
1181 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1183 memset(result, 0, sizeof(struct sp_event_set));
1185 *result_ptr = result;
1190 static enum sp_return add_handle(struct sp_event_set *event_set,
1191 event_handle handle, enum sp_event mask)
1194 enum sp_event *new_masks;
1196 TRACE("%p, %d, %d", event_set, handle, mask);
1198 if (!(new_handles = realloc(event_set->handles,
1199 sizeof(event_handle) * (event_set->count + 1))))
1200 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1202 event_set->handles = new_handles;
1204 if (!(new_masks = realloc(event_set->masks,
1205 sizeof(enum sp_event) * (event_set->count + 1))))
1206 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1208 event_set->masks = new_masks;
1210 ((event_handle *) event_set->handles)[event_set->count] = handle;
1211 event_set->masks[event_set->count] = mask;
1218 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1219 const struct sp_port *port, enum sp_event mask)
1221 TRACE("%p, %p, %d", event_set, port, mask);
1224 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1227 RETURN_ERROR(SP_ERR_ARG, "Null port");
1229 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1230 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1236 enum sp_event handle_mask;
1237 if ((handle_mask = mask & SP_EVENT_TX_READY))
1238 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1239 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1240 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1242 TRY(add_handle(event_set, port->fd, mask));
1248 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1250 TRACE("%p", event_set);
1253 DEBUG("Null event set");
1257 DEBUG("Freeing event set");
1259 if (event_set->handles)
1260 free(event_set->handles);
1261 if (event_set->masks)
1262 free(event_set->masks);
1269 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1270 unsigned int timeout_ms)
1272 TRACE("%p, %d", event_set, timeout_ms);
1275 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1278 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1279 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1280 RETURN_FAIL("WaitForMultipleObjects() failed");
1284 struct timeval start, delta, now, end = {0, 0};
1286 int result, timeout_remaining_ms;
1287 struct pollfd *pollfds;
1290 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1291 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1293 for (i = 0; i < event_set->count; i++) {
1294 pollfds[i].fd = ((int *) event_set->handles)[i];
1295 pollfds[i].events = 0;
1296 pollfds[i].revents = 0;
1297 if (event_set->masks[i] & SP_EVENT_RX_READY)
1298 pollfds[i].events |= POLLIN;
1299 if (event_set->masks[i] & SP_EVENT_TX_READY)
1300 pollfds[i].events |= POLLOUT;
1301 if (event_set->masks[i] & SP_EVENT_ERROR)
1302 pollfds[i].events |= POLLERR;
1306 /* Get time at start of operation. */
1307 gettimeofday(&start, NULL);
1308 /* Define duration of timeout. */
1309 delta.tv_sec = timeout_ms / 1000;
1310 delta.tv_usec = (timeout_ms % 1000) * 1000;
1311 /* Calculate time at which we should give up. */
1312 timeradd(&start, &delta, &end);
1315 /* Loop until an event occurs. */
1318 * Check timeout only if we have run poll() at least once,
1319 * to avoid any issues if a short timeout is reached before
1320 * poll() is even run.
1322 if (timeout_ms && started) {
1323 gettimeofday(&now, NULL);
1324 if (timercmp(&now, &end, >)) {
1325 DEBUG("Wait timed out");
1328 timersub(&end, &now, &delta);
1329 timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1332 result = poll(pollfds, event_set->count, timeout_ms ? timeout_remaining_ms : -1);
1336 if (errno == EINTR) {
1337 DEBUG("poll() call was interrupted, repeating");
1341 RETURN_FAIL("poll() failed");
1343 } else if (result == 0) {
1344 DEBUG("poll() timed out");
1347 DEBUG("poll() completed");
1357 #ifdef USE_TERMIOS_SPEED
1358 static enum sp_return get_baudrate(int fd, int *baudrate)
1362 TRACE("%d, %p", fd, baudrate);
1364 DEBUG("Getting baud rate");
1366 if (!(data = malloc(get_termios_size())))
1367 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1369 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1371 RETURN_FAIL("Getting termios failed");
1374 *baudrate = get_termios_speed(data);
1381 static enum sp_return set_baudrate(int fd, int baudrate)
1385 TRACE("%d, %d", fd, baudrate);
1387 DEBUG("Getting baud rate");
1389 if (!(data = malloc(get_termios_size())))
1390 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1392 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1394 RETURN_FAIL("Getting termios failed");
1397 DEBUG("Setting baud rate");
1399 set_termios_speed(data, baudrate);
1401 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1403 RETURN_FAIL("Setting termios failed");
1410 #endif /* USE_TERMIOS_SPEED */
1413 static enum sp_return get_flow(int fd, struct port_data *data)
1417 TRACE("%d, %p", fd, data);
1419 DEBUG("Getting advanced flow control");
1421 if (!(termx = malloc(get_termiox_size())))
1422 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1424 if (ioctl(fd, TCGETX, termx) < 0) {
1426 RETURN_FAIL("Getting termiox failed");
1429 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1430 &data->dtr_flow, &data->dsr_flow);
1437 static enum sp_return set_flow(int fd, struct port_data *data)
1441 TRACE("%d, %p", fd, data);
1443 DEBUG("Getting advanced flow control");
1445 if (!(termx = malloc(get_termiox_size())))
1446 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1448 if (ioctl(fd, TCGETX, termx) < 0) {
1450 RETURN_FAIL("Getting termiox failed");
1453 DEBUG("Setting advanced flow control");
1455 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1456 data->dtr_flow, data->dsr_flow);
1458 if (ioctl(fd, TCSETX, termx) < 0) {
1460 RETURN_FAIL("Setting termiox failed");
1467 #endif /* USE_TERMIOX */
1469 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1470 struct sp_port_config *config)
1474 TRACE("%p, %p, %p", port, data, config);
1476 DEBUG_FMT("Getting configuration for port %s", port->name);
1479 if (!GetCommState(port->hdl, &data->dcb))
1480 RETURN_FAIL("GetCommState() failed");
1482 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1483 if (data->dcb.BaudRate == std_baudrates[i].index) {
1484 config->baudrate = std_baudrates[i].value;
1489 if (i == NUM_STD_BAUDRATES)
1490 /* BaudRate field can be either an index or a custom baud rate. */
1491 config->baudrate = data->dcb.BaudRate;
1493 config->bits = data->dcb.ByteSize;
1495 if (data->dcb.fParity)
1496 switch (data->dcb.Parity) {
1498 config->parity = SP_PARITY_NONE;
1501 config->parity = SP_PARITY_ODD;
1504 config->parity = SP_PARITY_EVEN;
1507 config->parity = SP_PARITY_MARK;
1510 config->parity = SP_PARITY_SPACE;
1513 config->parity = -1;
1516 config->parity = SP_PARITY_NONE;
1518 switch (data->dcb.StopBits) {
1520 config->stopbits = 1;
1523 config->stopbits = 2;
1526 config->stopbits = -1;
1529 switch (data->dcb.fRtsControl) {
1530 case RTS_CONTROL_DISABLE:
1531 config->rts = SP_RTS_OFF;
1533 case RTS_CONTROL_ENABLE:
1534 config->rts = SP_RTS_ON;
1536 case RTS_CONTROL_HANDSHAKE:
1537 config->rts = SP_RTS_FLOW_CONTROL;
1543 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1545 switch (data->dcb.fDtrControl) {
1546 case DTR_CONTROL_DISABLE:
1547 config->dtr = SP_DTR_OFF;
1549 case DTR_CONTROL_ENABLE:
1550 config->dtr = SP_DTR_ON;
1552 case DTR_CONTROL_HANDSHAKE:
1553 config->dtr = SP_DTR_FLOW_CONTROL;
1559 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1561 if (data->dcb.fInX) {
1562 if (data->dcb.fOutX)
1563 config->xon_xoff = SP_XONXOFF_INOUT;
1565 config->xon_xoff = SP_XONXOFF_IN;
1567 if (data->dcb.fOutX)
1568 config->xon_xoff = SP_XONXOFF_OUT;
1570 config->xon_xoff = SP_XONXOFF_DISABLED;
1575 if (tcgetattr(port->fd, &data->term) < 0)
1576 RETURN_FAIL("tcgetattr() failed");
1578 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1579 RETURN_FAIL("TIOCMGET ioctl failed");
1582 int ret = get_flow(port->fd, data);
1584 if (ret == SP_ERR_FAIL && errno == EINVAL)
1585 data->termiox_supported = 0;
1587 RETURN_CODEVAL(ret);
1589 data->termiox_supported = 1;
1591 data->termiox_supported = 0;
1594 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1595 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1596 config->baudrate = std_baudrates[i].value;
1601 if (i == NUM_STD_BAUDRATES) {
1603 config->baudrate = (int)data->term.c_ispeed;
1604 #elif defined(USE_TERMIOS_SPEED)
1605 TRY(get_baudrate(port->fd, &config->baudrate));
1607 config->baudrate = -1;
1611 switch (data->term.c_cflag & CSIZE) {
1628 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1629 config->parity = SP_PARITY_NONE;
1630 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1631 config->parity = -1;
1633 else if (data->term.c_cflag & CMSPAR)
1634 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1637 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1639 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1641 if (data->term.c_cflag & CRTSCTS) {
1642 config->rts = SP_RTS_FLOW_CONTROL;
1643 config->cts = SP_CTS_FLOW_CONTROL;
1645 if (data->termiox_supported && data->rts_flow)
1646 config->rts = SP_RTS_FLOW_CONTROL;
1648 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1650 config->cts = (data->termiox_supported && data->cts_flow) ?
1651 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1654 if (data->termiox_supported && data->dtr_flow)
1655 config->dtr = SP_DTR_FLOW_CONTROL;
1657 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1659 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1660 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1662 if (data->term.c_iflag & IXOFF) {
1663 if (data->term.c_iflag & IXON)
1664 config->xon_xoff = SP_XONXOFF_INOUT;
1666 config->xon_xoff = SP_XONXOFF_IN;
1668 if (data->term.c_iflag & IXON)
1669 config->xon_xoff = SP_XONXOFF_OUT;
1671 config->xon_xoff = SP_XONXOFF_DISABLED;
1678 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1679 const struct sp_port_config *config)
1683 BAUD_TYPE baud_nonstd;
1687 #ifdef USE_TERMIOS_SPEED
1688 int baud_nonstd = 0;
1691 TRACE("%p, %p, %p", port, data, config);
1693 DEBUG_FMT("Setting configuration for port %s", port->name);
1696 if (config->baudrate >= 0) {
1697 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1698 if (config->baudrate == std_baudrates[i].value) {
1699 data->dcb.BaudRate = std_baudrates[i].index;
1704 if (i == NUM_STD_BAUDRATES)
1705 data->dcb.BaudRate = config->baudrate;
1708 if (config->bits >= 0)
1709 data->dcb.ByteSize = config->bits;
1711 if (config->parity >= 0) {
1712 switch (config->parity) {
1713 case SP_PARITY_NONE:
1714 data->dcb.Parity = NOPARITY;
1717 data->dcb.Parity = ODDPARITY;
1719 case SP_PARITY_EVEN:
1720 data->dcb.Parity = EVENPARITY;
1722 case SP_PARITY_MARK:
1723 data->dcb.Parity = MARKPARITY;
1725 case SP_PARITY_SPACE:
1726 data->dcb.Parity = SPACEPARITY;
1729 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1733 if (config->stopbits >= 0) {
1734 switch (config->stopbits) {
1735 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1737 data->dcb.StopBits = ONESTOPBIT;
1740 data->dcb.StopBits = TWOSTOPBITS;
1743 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1747 if (config->rts >= 0) {
1748 switch (config->rts) {
1750 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1753 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1755 case SP_RTS_FLOW_CONTROL:
1756 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1759 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1763 if (config->cts >= 0) {
1764 switch (config->cts) {
1766 data->dcb.fOutxCtsFlow = FALSE;
1768 case SP_CTS_FLOW_CONTROL:
1769 data->dcb.fOutxCtsFlow = TRUE;
1772 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1776 if (config->dtr >= 0) {
1777 switch (config->dtr) {
1779 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1782 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1784 case SP_DTR_FLOW_CONTROL:
1785 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1788 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1792 if (config->dsr >= 0) {
1793 switch (config->dsr) {
1795 data->dcb.fOutxDsrFlow = FALSE;
1797 case SP_DSR_FLOW_CONTROL:
1798 data->dcb.fOutxDsrFlow = TRUE;
1801 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1805 if (config->xon_xoff >= 0) {
1806 switch (config->xon_xoff) {
1807 case SP_XONXOFF_DISABLED:
1808 data->dcb.fInX = FALSE;
1809 data->dcb.fOutX = FALSE;
1812 data->dcb.fInX = TRUE;
1813 data->dcb.fOutX = FALSE;
1815 case SP_XONXOFF_OUT:
1816 data->dcb.fInX = FALSE;
1817 data->dcb.fOutX = TRUE;
1819 case SP_XONXOFF_INOUT:
1820 data->dcb.fInX = TRUE;
1821 data->dcb.fOutX = TRUE;
1824 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1828 if (!SetCommState(port->hdl, &data->dcb))
1829 RETURN_FAIL("SetCommState() failed");
1835 if (config->baudrate >= 0) {
1836 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1837 if (config->baudrate == std_baudrates[i].value) {
1838 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1839 RETURN_FAIL("cfsetospeed() failed");
1841 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1842 RETURN_FAIL("cfsetispeed() failed");
1847 /* Non-standard baud rate */
1848 if (i == NUM_STD_BAUDRATES) {
1850 /* Set "dummy" baud rate. */
1851 if (cfsetspeed(&data->term, B9600) < 0)
1852 RETURN_FAIL("cfsetspeed() failed");
1853 baud_nonstd = config->baudrate;
1854 #elif defined(USE_TERMIOS_SPEED)
1857 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1862 if (config->bits >= 0) {
1863 data->term.c_cflag &= ~CSIZE;
1864 switch (config->bits) {
1866 data->term.c_cflag |= CS8;
1869 data->term.c_cflag |= CS7;
1872 data->term.c_cflag |= CS6;
1875 data->term.c_cflag |= CS5;
1878 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1882 if (config->parity >= 0) {
1883 data->term.c_iflag &= ~IGNPAR;
1884 data->term.c_cflag &= ~(PARENB | PARODD);
1886 data->term.c_cflag &= ~CMSPAR;
1888 switch (config->parity) {
1889 case SP_PARITY_NONE:
1890 data->term.c_iflag |= IGNPAR;
1892 case SP_PARITY_EVEN:
1893 data->term.c_cflag |= PARENB;
1896 data->term.c_cflag |= PARENB | PARODD;
1899 case SP_PARITY_MARK:
1900 data->term.c_cflag |= PARENB | PARODD;
1901 data->term.c_cflag |= CMSPAR;
1903 case SP_PARITY_SPACE:
1904 data->term.c_cflag |= PARENB;
1905 data->term.c_cflag |= CMSPAR;
1908 case SP_PARITY_MARK:
1909 case SP_PARITY_SPACE:
1910 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1913 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1917 if (config->stopbits >= 0) {
1918 data->term.c_cflag &= ~CSTOPB;
1919 switch (config->stopbits) {
1921 data->term.c_cflag &= ~CSTOPB;
1924 data->term.c_cflag |= CSTOPB;
1927 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1931 if (config->rts >= 0 || config->cts >= 0) {
1932 if (data->termiox_supported) {
1933 data->rts_flow = data->cts_flow = 0;
1934 switch (config->rts) {
1937 controlbits = TIOCM_RTS;
1938 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1939 RETURN_FAIL("Setting RTS signal level failed");
1941 case SP_RTS_FLOW_CONTROL:
1947 if (config->cts == SP_CTS_FLOW_CONTROL)
1950 if (data->rts_flow && data->cts_flow)
1951 data->term.c_iflag |= CRTSCTS;
1953 data->term.c_iflag &= ~CRTSCTS;
1955 /* Asymmetric use of RTS/CTS not supported. */
1956 if (data->term.c_iflag & CRTSCTS) {
1957 /* Flow control can only be disabled for both RTS & CTS together. */
1958 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1959 if (config->cts != SP_CTS_IGNORE)
1960 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1962 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1963 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1964 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1967 /* Flow control can only be enabled for both RTS & CTS together. */
1968 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1969 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1970 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1973 if (config->rts >= 0) {
1974 if (config->rts == SP_RTS_FLOW_CONTROL) {
1975 data->term.c_iflag |= CRTSCTS;
1977 controlbits = TIOCM_RTS;
1978 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1980 RETURN_FAIL("Setting RTS signal level failed");
1986 if (config->dtr >= 0 || config->dsr >= 0) {
1987 if (data->termiox_supported) {
1988 data->dtr_flow = data->dsr_flow = 0;
1989 switch (config->dtr) {
1992 controlbits = TIOCM_DTR;
1993 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1994 RETURN_FAIL("Setting DTR signal level failed");
1996 case SP_DTR_FLOW_CONTROL:
2002 if (config->dsr == SP_DSR_FLOW_CONTROL)
2005 /* DTR/DSR flow control not supported. */
2006 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2007 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2009 if (config->dtr >= 0) {
2010 controlbits = TIOCM_DTR;
2011 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2013 RETURN_FAIL("Setting DTR signal level failed");
2018 if (config->xon_xoff >= 0) {
2019 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2020 switch (config->xon_xoff) {
2021 case SP_XONXOFF_DISABLED:
2024 data->term.c_iflag |= IXOFF;
2026 case SP_XONXOFF_OUT:
2027 data->term.c_iflag |= IXON | IXANY;
2029 case SP_XONXOFF_INOUT:
2030 data->term.c_iflag |= IXON | IXOFF | IXANY;
2033 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2037 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2038 RETURN_FAIL("tcsetattr() failed");
2041 if (baud_nonstd != B0) {
2042 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2043 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2045 * Set baud rates in data->term to correct, but incompatible
2046 * with tcsetattr() value, same as delivered by tcgetattr().
2048 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2049 RETURN_FAIL("cfsetspeed() failed");
2051 #elif defined(__linux__)
2052 #ifdef USE_TERMIOS_SPEED
2054 TRY(set_baudrate(port->fd, config->baudrate));
2057 if (data->termiox_supported)
2058 TRY(set_flow(port->fd, data));
2062 #endif /* !_WIN32 */
2067 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2069 struct sp_port_config *config;
2071 TRACE("%p", config_ptr);
2074 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2078 if (!(config = malloc(sizeof(struct sp_port_config))))
2079 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2081 config->baudrate = -1;
2083 config->parity = -1;
2084 config->stopbits = -1;
2090 *config_ptr = config;
2095 SP_API void sp_free_config(struct sp_port_config *config)
2097 TRACE("%p", config);
2100 DEBUG("Null config");
2107 SP_API enum sp_return sp_get_config(struct sp_port *port,
2108 struct sp_port_config *config)
2110 struct port_data data;
2112 TRACE("%p, %p", port, config);
2117 RETURN_ERROR(SP_ERR_ARG, "Null config");
2119 TRY(get_config(port, &data, config));
2124 SP_API enum sp_return sp_set_config(struct sp_port *port,
2125 const struct sp_port_config *config)
2127 struct port_data data;
2128 struct sp_port_config prev_config;
2130 TRACE("%p, %p", port, config);
2135 RETURN_ERROR(SP_ERR_ARG, "Null config");
2137 TRY(get_config(port, &data, &prev_config));
2138 TRY(set_config(port, &data, config));
2143 #define CREATE_ACCESSORS(x, type) \
2144 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2145 struct port_data data; \
2146 struct sp_port_config config; \
2147 TRACE("%p, %d", port, x); \
2148 CHECK_OPEN_PORT(); \
2149 TRY(get_config(port, &data, &config)); \
2151 TRY(set_config(port, &data, &config)); \
2154 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2156 TRACE("%p, %p", config, x); \
2158 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2160 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2164 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2166 TRACE("%p, %d", config, x); \
2168 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2173 CREATE_ACCESSORS(baudrate, int)
2174 CREATE_ACCESSORS(bits, int)
2175 CREATE_ACCESSORS(parity, enum sp_parity)
2176 CREATE_ACCESSORS(stopbits, int)
2177 CREATE_ACCESSORS(rts, enum sp_rts)
2178 CREATE_ACCESSORS(cts, enum sp_cts)
2179 CREATE_ACCESSORS(dtr, enum sp_dtr)
2180 CREATE_ACCESSORS(dsr, enum sp_dsr)
2181 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2183 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2184 enum sp_flowcontrol flowcontrol)
2187 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2189 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2190 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2192 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2193 config->xon_xoff = SP_XONXOFF_INOUT;
2195 config->xon_xoff = SP_XONXOFF_DISABLED;
2197 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2198 config->rts = SP_RTS_FLOW_CONTROL;
2199 config->cts = SP_CTS_FLOW_CONTROL;
2201 if (config->rts == SP_RTS_FLOW_CONTROL)
2202 config->rts = SP_RTS_ON;
2203 config->cts = SP_CTS_IGNORE;
2206 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2207 config->dtr = SP_DTR_FLOW_CONTROL;
2208 config->dsr = SP_DSR_FLOW_CONTROL;
2210 if (config->dtr == SP_DTR_FLOW_CONTROL)
2211 config->dtr = SP_DTR_ON;
2212 config->dsr = SP_DSR_IGNORE;
2218 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2219 enum sp_flowcontrol flowcontrol)
2221 struct port_data data;
2222 struct sp_port_config config;
2224 TRACE("%p, %d", port, flowcontrol);
2228 TRY(get_config(port, &data, &config));
2230 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2232 TRY(set_config(port, &data, &config));
2237 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2238 enum sp_signal *signals)
2240 TRACE("%p, %p", port, signals);
2245 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2247 DEBUG_FMT("Getting control signals for port %s", port->name);
2252 if (GetCommModemStatus(port->hdl, &bits) == 0)
2253 RETURN_FAIL("GetCommModemStatus() failed");
2254 if (bits & MS_CTS_ON)
2255 *signals |= SP_SIG_CTS;
2256 if (bits & MS_DSR_ON)
2257 *signals |= SP_SIG_DSR;
2258 if (bits & MS_RLSD_ON)
2259 *signals |= SP_SIG_DCD;
2260 if (bits & MS_RING_ON)
2261 *signals |= SP_SIG_RI;
2264 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2265 RETURN_FAIL("TIOCMGET ioctl failed");
2266 if (bits & TIOCM_CTS)
2267 *signals |= SP_SIG_CTS;
2268 if (bits & TIOCM_DSR)
2269 *signals |= SP_SIG_DSR;
2270 if (bits & TIOCM_CAR)
2271 *signals |= SP_SIG_DCD;
2272 if (bits & TIOCM_RNG)
2273 *signals |= SP_SIG_RI;
2278 SP_API enum sp_return sp_start_break(struct sp_port *port)
2284 if (SetCommBreak(port->hdl) == 0)
2285 RETURN_FAIL("SetCommBreak() failed");
2287 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2288 RETURN_FAIL("TIOCSBRK ioctl failed");
2294 SP_API enum sp_return sp_end_break(struct sp_port *port)
2300 if (ClearCommBreak(port->hdl) == 0)
2301 RETURN_FAIL("ClearCommBreak() failed");
2303 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2304 RETURN_FAIL("TIOCCBRK ioctl failed");
2310 SP_API int sp_last_error_code(void)
2314 RETURN_INT(GetLastError());
2320 SP_API char *sp_last_error_message(void)
2326 DWORD error = GetLastError();
2328 DWORD length = FormatMessage(
2329 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2330 FORMAT_MESSAGE_FROM_SYSTEM |
2331 FORMAT_MESSAGE_IGNORE_INSERTS,
2334 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2338 if (length >= 2 && message[length - 2] == '\r')
2339 message[length - 2] = '\0';
2341 RETURN_STRING(message);
2343 RETURN_STRING(strerror(errno));
2347 SP_API void sp_free_error_message(char *message)
2349 TRACE("%s", message);
2360 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2362 TRACE("%p", handler);
2364 sp_debug_handler = handler;
2369 SP_API void sp_default_debug_handler(const char *format, ...)
2372 va_start(args, format);
2373 if (getenv("LIBSERIALPORT_DEBUG")) {
2374 fputs("sp: ", stderr);
2375 vfprintf(stderr, format, args);
2380 SP_API int sp_get_major_package_version(void)
2382 return SP_PACKAGE_VERSION_MAJOR;
2385 SP_API int sp_get_minor_package_version(void)
2387 return SP_PACKAGE_VERSION_MINOR;
2390 SP_API int sp_get_micro_package_version(void)
2392 return SP_PACKAGE_VERSION_MICRO;
2395 SP_API const char *sp_get_package_version_string(void)
2397 return SP_PACKAGE_VERSION_STRING;
2400 SP_API int sp_get_current_lib_version(void)
2402 return SP_LIB_VERSION_CURRENT;
2405 SP_API int sp_get_revision_lib_version(void)
2407 return SP_LIB_VERSION_REVISION;
2410 SP_API int sp_get_age_lib_version(void)
2412 return SP_LIB_VERSION_AGE;
2415 SP_API const char *sp_get_lib_version_string(void)
2417 return SP_LIB_VERSION_STRING;