2 * This file is part of the libserialport project.
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2015 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2013-2015 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/>.
25 #include "libserialport.h"
26 #include "libserialport_internal.h"
28 static const struct std_baudrate std_baudrates[] = {
31 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
32 * have documented CBR_* macros.
34 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
35 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
36 BAUD(115200), BAUD(128000), BAUD(256000),
38 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
39 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
40 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
42 #if !defined(__APPLE__) && !defined(__OpenBSD__)
48 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
50 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
52 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
53 struct sp_port_config *config);
55 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
56 const struct sp_port_config *config);
58 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
61 #ifndef NO_PORT_METADATA
66 TRACE("%s, %p", portname, port_ptr);
69 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
74 RETURN_ERROR(SP_ERR_ARG, "Null port name");
76 DEBUG_FMT("Building structure for port %s", portname);
78 #if !defined(_WIN32) && defined(HAVE_REALPATH)
80 * get_port_details() below tries to be too smart and figure out
81 * some transport properties from the port name which breaks with
82 * symlinks. Therefore we canonicalize the portname first.
84 char pathbuf[PATH_MAX + 1];
85 char *res = realpath(portname, pathbuf);
87 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
92 if (!(port = malloc(sizeof(struct sp_port))))
93 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
95 len = strlen(portname) + 1;
97 if (!(port->name = malloc(len))) {
99 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
102 memcpy(port->name, portname, len);
105 port->usb_path = NULL;
106 port->hdl = INVALID_HANDLE_VALUE;
111 port->description = NULL;
112 port->transport = SP_TRANSPORT_NATIVE;
114 port->usb_address = -1;
117 port->usb_manufacturer = NULL;
118 port->usb_product = NULL;
119 port->usb_serial = NULL;
120 port->bluetooth_address = NULL;
122 #ifndef NO_PORT_METADATA
123 if ((ret = get_port_details(port)) != SP_OK) {
134 SP_API char *sp_get_port_name(const struct sp_port *port)
141 RETURN_STRING(port->name);
144 SP_API char *sp_get_port_description(const struct sp_port *port)
148 if (!port || !port->description)
151 RETURN_STRING(port->description);
154 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
159 RETURN_ERROR(SP_ERR_ARG, "Null port");
161 RETURN_INT(port->transport);
164 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
165 int *usb_bus,int *usb_address)
170 RETURN_ERROR(SP_ERR_ARG, "Null port");
171 if (port->transport != SP_TRANSPORT_USB)
172 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
173 if (port->usb_bus < 0 || port->usb_address < 0)
174 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
177 *usb_bus = port->usb_bus;
179 *usb_address = port->usb_address;
184 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
185 int *usb_vid, int *usb_pid)
190 RETURN_ERROR(SP_ERR_ARG, "Null port");
191 if (port->transport != SP_TRANSPORT_USB)
192 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
193 if (port->usb_vid < 0 || port->usb_pid < 0)
194 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
197 *usb_vid = port->usb_vid;
199 *usb_pid = port->usb_pid;
204 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
208 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
211 RETURN_STRING(port->usb_manufacturer);
214 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
218 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
221 RETURN_STRING(port->usb_product);
224 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
228 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
231 RETURN_STRING(port->usb_serial);
234 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
238 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
239 || !port->bluetooth_address)
242 RETURN_STRING(port->bluetooth_address);
245 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
248 TRACE("%p, %p", port, result_ptr);
251 RETURN_ERROR(SP_ERR_ARG, "Null port");
253 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
256 HANDLE *handle_ptr = result_ptr;
257 *handle_ptr = port->hdl;
259 int *fd_ptr = result_ptr;
266 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
267 struct sp_port **copy_ptr)
269 TRACE("%p, %p", port, copy_ptr);
272 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
277 RETURN_ERROR(SP_ERR_ARG, "Null port");
280 RETURN_ERROR(SP_ERR_ARG, "Null port name");
282 DEBUG("Copying port structure");
284 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
287 SP_API void sp_free_port(struct sp_port *port)
296 DEBUG("Freeing port structure");
300 if (port->description)
301 free(port->description);
302 if (port->usb_manufacturer)
303 free(port->usb_manufacturer);
304 if (port->usb_product)
305 free(port->usb_product);
306 if (port->usb_serial)
307 free(port->usb_serial);
308 if (port->bluetooth_address)
309 free(port->bluetooth_address);
312 free(port->usb_path);
320 SP_PRIV struct sp_port **list_append(struct sp_port **list,
321 const char *portname)
326 for (count = 0; list[count]; count++)
328 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
331 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
333 list[count + 1] = NULL;
337 sp_free_port_list(list);
341 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
343 #ifndef NO_ENUMERATION
344 struct sp_port **list;
348 TRACE("%p", list_ptr);
351 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
355 #ifdef NO_ENUMERATION
356 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
358 DEBUG("Enumerating ports");
360 if (!(list = malloc(sizeof(struct sp_port *))))
361 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
365 ret = list_ports(&list);
370 sp_free_port_list(list);
378 SP_API void sp_free_port_list(struct sp_port **list)
389 DEBUG("Freeing port list");
391 for (i = 0; list[i]; i++)
392 sp_free_port(list[i]);
398 #define CHECK_PORT() do { \
400 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
402 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
405 #define CHECK_PORT_HANDLE() do { \
406 if (port->hdl == INVALID_HANDLE_VALUE) \
407 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
410 #define CHECK_PORT_HANDLE() do { \
412 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
415 #define CHECK_OPEN_PORT() do { \
417 CHECK_PORT_HANDLE(); \
421 /** To be called after port receive buffer is emptied. */
422 static enum sp_return restart_wait(struct sp_port *port)
426 if (port->wait_running) {
427 /* Check status of running wait operation. */
428 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
429 &wait_result, FALSE)) {
430 DEBUG("Previous wait completed");
431 port->wait_running = FALSE;
432 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
433 DEBUG("Previous wait still running");
436 RETURN_FAIL("GetOverlappedResult() failed");
440 if (!port->wait_running) {
441 /* Start new wait operation. */
442 if (WaitCommEvent(port->hdl, &port->events,
444 DEBUG("New wait returned, events already pending");
445 } else if (GetLastError() == ERROR_IO_PENDING) {
446 DEBUG("New wait running in background");
447 port->wait_running = TRUE;
449 RETURN_FAIL("WaitCommEvent() failed");
457 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
459 struct port_data data;
460 struct sp_port_config config;
463 TRACE("%p, 0x%x", port, flags);
467 if (flags > SP_MODE_READ_WRITE)
468 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
470 DEBUG_FMT("Opening port %s", port->name);
473 DWORD desired_access = 0, flags_and_attributes = 0, errors;
474 char *escaped_port_name;
477 /* Prefix port name with '\\.\' to work with ports above COM9. */
478 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
479 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
480 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
482 /* Map 'flags' to the OS-specific settings. */
483 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
484 if (flags & SP_MODE_READ)
485 desired_access |= GENERIC_READ;
486 if (flags & SP_MODE_WRITE)
487 desired_access |= GENERIC_WRITE;
489 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
490 OPEN_EXISTING, flags_and_attributes, 0);
492 free(escaped_port_name);
494 if (port->hdl == INVALID_HANDLE_VALUE)
495 RETURN_FAIL("Port CreateFile() failed");
497 /* All timeouts initially disabled. */
498 port->timeouts.ReadIntervalTimeout = 0;
499 port->timeouts.ReadTotalTimeoutMultiplier = 0;
500 port->timeouts.ReadTotalTimeoutConstant = 0;
501 port->timeouts.WriteTotalTimeoutMultiplier = 0;
502 port->timeouts.WriteTotalTimeoutConstant = 0;
504 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
506 RETURN_FAIL("SetCommTimeouts() failed");
509 /* Prepare OVERLAPPED structures. */
510 #define INIT_OVERLAPPED(ovl) do { \
511 memset(&port->ovl, 0, sizeof(port->ovl)); \
512 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
513 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
514 == INVALID_HANDLE_VALUE) { \
516 RETURN_FAIL(#ovl "CreateEvent() failed"); \
520 INIT_OVERLAPPED(read_ovl);
521 INIT_OVERLAPPED(write_ovl);
522 INIT_OVERLAPPED(wait_ovl);
524 /* Set event mask for RX and error events. */
525 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
527 RETURN_FAIL("SetCommMask() failed");
530 port->writing = FALSE;
531 port->wait_running = FALSE;
533 ret = restart_wait(port);
540 int flags_local = O_NONBLOCK | O_NOCTTY;
542 /* Map 'flags' to the OS-specific settings. */
543 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
544 flags_local |= O_RDWR;
545 else if (flags & SP_MODE_READ)
546 flags_local |= O_RDONLY;
547 else if (flags & SP_MODE_WRITE)
548 flags_local |= O_WRONLY;
550 if ((port->fd = open(port->name, flags_local)) < 0)
551 RETURN_FAIL("open() failed");
554 ret = get_config(port, &data, &config);
561 /* Set sane port settings. */
563 data.dcb.fBinary = TRUE;
564 data.dcb.fDsrSensitivity = FALSE;
565 data.dcb.fErrorChar = FALSE;
566 data.dcb.fNull = FALSE;
567 data.dcb.fAbortOnError = FALSE;
569 /* Turn off all fancy termios tricks, give us a raw channel. */
570 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
572 data.term.c_iflag &= ~IUCLC;
574 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
576 data.term.c_oflag &= ~OLCUC;
579 data.term.c_oflag &= ~NLDLY;
582 data.term.c_oflag &= ~CRDLY;
585 data.term.c_oflag &= ~TABDLY;
588 data.term.c_oflag &= ~BSDLY;
591 data.term.c_oflag &= ~VTDLY;
594 data.term.c_oflag &= ~FFDLY;
597 data.term.c_oflag &= ~OFILL;
599 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
600 data.term.c_cc[VMIN] = 0;
601 data.term.c_cc[VTIME] = 0;
603 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
604 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
608 if (ClearCommError(port->hdl, &errors, &status) == 0)
609 RETURN_FAIL("ClearCommError() failed");
612 ret = set_config(port, &data, &config);
622 SP_API enum sp_return sp_close(struct sp_port *port)
628 DEBUG_FMT("Closing port %s", port->name);
631 /* Returns non-zero upon success, 0 upon failure. */
632 if (CloseHandle(port->hdl) == 0)
633 RETURN_FAIL("Port CloseHandle() failed");
634 port->hdl = INVALID_HANDLE_VALUE;
636 /* Close event handles for overlapped structures. */
637 #define CLOSE_OVERLAPPED(ovl) do { \
638 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
639 CloseHandle(port->ovl.hEvent) == 0) \
640 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
642 CLOSE_OVERLAPPED(read_ovl);
643 CLOSE_OVERLAPPED(write_ovl);
644 CLOSE_OVERLAPPED(wait_ovl);
647 /* Returns 0 upon success, -1 upon failure. */
648 if (close(port->fd) == -1)
649 RETURN_FAIL("close() failed");
656 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
658 TRACE("%p, 0x%x", port, buffers);
662 if (buffers > SP_BUF_BOTH)
663 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
665 const char *buffer_names[] = {"no", "input", "output", "both"};
667 DEBUG_FMT("Flushing %s buffers on port %s",
668 buffer_names[buffers], port->name);
672 if (buffers & SP_BUF_INPUT)
673 flags |= PURGE_RXCLEAR;
674 if (buffers & SP_BUF_OUTPUT)
675 flags |= PURGE_TXCLEAR;
677 /* Returns non-zero upon success, 0 upon failure. */
678 if (PurgeComm(port->hdl, flags) == 0)
679 RETURN_FAIL("PurgeComm() failed");
681 if (buffers & SP_BUF_INPUT)
682 TRY(restart_wait(port));
685 if (buffers == SP_BUF_BOTH)
687 else if (buffers == SP_BUF_INPUT)
689 else if (buffers == SP_BUF_OUTPUT)
692 /* Returns 0 upon success, -1 upon failure. */
693 if (tcflush(port->fd, flags) < 0)
694 RETURN_FAIL("tcflush() failed");
699 SP_API enum sp_return sp_drain(struct sp_port *port)
705 DEBUG_FMT("Draining port %s", port->name);
708 /* Returns non-zero upon success, 0 upon failure. */
709 if (FlushFileBuffers(port->hdl) == 0)
710 RETURN_FAIL("FlushFileBuffers() failed");
717 result = ioctl(port->fd, TCSBRK, &arg);
719 result = tcdrain(port->fd);
722 if (errno == EINTR) {
723 DEBUG("tcdrain() was interrupted");
726 RETURN_FAIL("tcdrain() failed");
736 static enum sp_return await_write_completion(struct sp_port *port)
742 /* Wait for previous non-blocking write to complete, if any. */
744 DEBUG("Waiting for previous write to complete");
745 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
748 RETURN_FAIL("Previous write failed to complete");
749 DEBUG("Previous write completed");
756 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
757 size_t count, unsigned int timeout_ms)
759 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
764 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
767 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
768 count, port->name, timeout_ms);
770 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
777 DWORD bytes_written = 0;
779 TRY(await_write_completion(port));
782 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
783 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
784 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
785 RETURN_FAIL("SetCommTimeouts() failed");
789 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
790 DEBUG("Write completed immediately");
792 } else if (GetLastError() == ERROR_IO_PENDING) {
793 DEBUG("Waiting for write to complete");
794 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
795 if (GetLastError() == ERROR_SEM_TIMEOUT) {
796 DEBUG("Write timed out");
799 RETURN_FAIL("GetOverlappedResult() failed");
802 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
803 RETURN_INT(bytes_written);
805 RETURN_FAIL("WriteFile() failed");
808 size_t bytes_written = 0;
809 unsigned char *ptr = (unsigned char *) buf;
810 struct timeval start, delta, now, end = {0, 0};
816 /* Get time at start of operation. */
817 gettimeofday(&start, NULL);
818 /* Define duration of timeout. */
819 delta.tv_sec = timeout_ms / 1000;
820 delta.tv_usec = (timeout_ms % 1000) * 1000;
821 /* Calculate time at which we should give up. */
822 timeradd(&start, &delta, &end);
826 FD_SET(port->fd, &fds);
828 /* Loop until we have written the requested number of bytes. */
829 while (bytes_written < count) {
831 * Check timeout only if we have run select() at least once,
832 * to avoid any issues if a short timeout is reached before
833 * select() is even run.
835 if (timeout_ms && started) {
836 gettimeofday(&now, NULL);
837 if (timercmp(&now, &end, >))
838 /* Timeout has expired. */
840 timersub(&end, &now, &delta);
842 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
845 if (errno == EINTR) {
846 DEBUG("select() call was interrupted, repeating");
849 RETURN_FAIL("select() failed");
851 } else if (result == 0) {
852 /* Timeout has expired. */
857 result = write(port->fd, ptr, count - bytes_written);
861 /* This shouldn't happen because we did a select() first, but handle anyway. */
864 /* This is an actual failure. */
865 RETURN_FAIL("write() failed");
868 bytes_written += result;
872 if (bytes_written < count)
873 DEBUG("Write timed out");
875 RETURN_INT(bytes_written);
879 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
880 const void *buf, size_t count)
882 TRACE("%p, %p, %d", port, buf, count);
887 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
889 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
896 BYTE *ptr = (BYTE *) buf;
898 /* Check whether previous write is complete. */
900 if (HasOverlappedIoCompleted(&port->write_ovl)) {
901 DEBUG("Previous write completed");
904 DEBUG("Previous write not complete");
905 /* Can't take a new write until the previous one finishes. */
911 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
912 port->timeouts.WriteTotalTimeoutConstant = 0;
913 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
914 RETURN_FAIL("SetCommTimeouts() failed");
918 * Keep writing data until the OS has to actually start an async IO
919 * for it. At that point we know the buffer is full.
921 while (written < count) {
922 /* Copy first byte of user buffer. */
923 port->pending_byte = *ptr++;
925 /* Start asynchronous write. */
926 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
927 if (GetLastError() == ERROR_IO_PENDING) {
928 if (HasOverlappedIoCompleted(&port->write_ovl)) {
929 DEBUG("Asynchronous write completed immediately");
934 DEBUG("Asynchronous write running");
936 RETURN_INT(++written);
939 /* Actual failure of some kind. */
940 RETURN_FAIL("WriteFile() failed");
943 DEBUG("Single byte written immediately");
948 DEBUG("All bytes written immediately");
952 /* Returns the number of bytes written, or -1 upon failure. */
953 ssize_t written = write(port->fd, buf, count);
957 // Buffer is full, no bytes written.
960 RETURN_FAIL("write() failed");
968 /* Restart wait operation if buffer was emptied. */
969 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
977 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
978 RETURN_FAIL("ClearCommError() failed");
980 if (comstat.cbInQue == 0)
981 TRY(restart_wait(port));
987 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
988 size_t count, unsigned int timeout_ms)
990 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
995 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
998 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
999 count, port->name, timeout_ms);
1001 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1008 DWORD bytes_read = 0;
1011 if (port->timeouts.ReadIntervalTimeout != 0 ||
1012 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1013 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1014 port->timeouts.ReadIntervalTimeout = 0;
1015 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1016 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1017 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1018 RETURN_FAIL("SetCommTimeouts() failed");
1022 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1023 DEBUG("Read completed immediately");
1025 } else if (GetLastError() == ERROR_IO_PENDING) {
1026 DEBUG("Waiting for read to complete");
1027 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1028 RETURN_FAIL("GetOverlappedResult() failed");
1029 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1031 RETURN_FAIL("ReadFile() failed");
1034 TRY(restart_wait_if_needed(port, bytes_read));
1036 RETURN_INT(bytes_read);
1039 size_t bytes_read = 0;
1040 unsigned char *ptr = (unsigned char *)buf;
1041 struct timeval start, delta, now, end = {0, 0};
1047 /* Get time at start of operation. */
1048 gettimeofday(&start, NULL);
1049 /* Define duration of timeout. */
1050 delta.tv_sec = timeout_ms / 1000;
1051 delta.tv_usec = (timeout_ms % 1000) * 1000;
1052 /* Calculate time at which we should give up. */
1053 timeradd(&start, &delta, &end);
1057 FD_SET(port->fd, &fds);
1059 /* Loop until we have the requested number of bytes. */
1060 while (bytes_read < count) {
1062 * Check timeout only if we have run select() at least once,
1063 * to avoid any issues if a short timeout is reached before
1064 * select() is even run.
1066 if (timeout_ms && started) {
1067 gettimeofday(&now, NULL);
1068 if (timercmp(&now, &end, >))
1069 /* Timeout has expired. */
1071 timersub(&end, &now, &delta);
1073 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1076 if (errno == EINTR) {
1077 DEBUG("select() call was interrupted, repeating");
1080 RETURN_FAIL("select() failed");
1082 } else if (result == 0) {
1083 /* Timeout has expired. */
1088 result = read(port->fd, ptr, count - bytes_read);
1091 if (errno == EAGAIN)
1093 * This shouldn't happen because we did a
1094 * select() first, but handle anyway.
1098 /* This is an actual failure. */
1099 RETURN_FAIL("read() failed");
1102 bytes_read += result;
1106 if (bytes_read < count)
1107 DEBUG("Read timed out");
1109 RETURN_INT(bytes_read);
1113 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1114 size_t count, unsigned int timeout_ms)
1116 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1121 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1124 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1127 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1128 count, port->name, timeout_ms);
1130 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1134 DWORD bytes_read = 0;
1136 /* If timeout_ms == 0, set maximum timeout. */
1137 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1140 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1141 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1142 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1143 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1144 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1145 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1146 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1147 RETURN_FAIL("SetCommTimeouts() failed");
1150 /* Loop until we have at least one byte, or timeout is reached. */
1151 while (bytes_read == 0) {
1153 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1154 DEBUG("Read completed immediately");
1155 } else if (GetLastError() == ERROR_IO_PENDING) {
1156 DEBUG("Waiting for read to complete");
1157 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1158 RETURN_FAIL("GetOverlappedResult() failed");
1159 if (bytes_read > 0) {
1160 DEBUG("Read completed");
1161 } else if (timeout_ms > 0) {
1162 DEBUG("Read timed out");
1165 DEBUG("Restarting read");
1168 RETURN_FAIL("ReadFile() failed");
1172 TRY(restart_wait_if_needed(port, bytes_read));
1174 RETURN_INT(bytes_read);
1177 size_t bytes_read = 0;
1178 struct timeval start, delta, now, end = {0, 0};
1184 /* Get time at start of operation. */
1185 gettimeofday(&start, NULL);
1186 /* Define duration of timeout. */
1187 delta.tv_sec = timeout_ms / 1000;
1188 delta.tv_usec = (timeout_ms % 1000) * 1000;
1189 /* Calculate time at which we should give up. */
1190 timeradd(&start, &delta, &end);
1194 FD_SET(port->fd, &fds);
1196 /* Loop until we have at least one byte, or timeout is reached. */
1197 while (bytes_read == 0) {
1199 * Check timeout only if we have run select() at least once,
1200 * to avoid any issues if a short timeout is reached before
1201 * select() is even run.
1203 if (timeout_ms && started) {
1204 gettimeofday(&now, NULL);
1205 if (timercmp(&now, &end, >))
1206 /* Timeout has expired. */
1208 timersub(&end, &now, &delta);
1210 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1213 if (errno == EINTR) {
1214 DEBUG("select() call was interrupted, repeating");
1217 RETURN_FAIL("select() failed");
1219 } else if (result == 0) {
1220 /* Timeout has expired. */
1225 result = read(port->fd, buf, count);
1228 if (errno == EAGAIN)
1229 /* This shouldn't happen because we did a select() first, but handle anyway. */
1232 /* This is an actual failure. */
1233 RETURN_FAIL("read() failed");
1236 bytes_read = result;
1239 if (bytes_read == 0)
1240 DEBUG("Read timed out");
1242 RETURN_INT(bytes_read);
1246 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1249 TRACE("%p, %p, %d", port, buf, count);
1254 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1256 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1262 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1263 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1264 port->timeouts.ReadTotalTimeoutConstant != 0) {
1265 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1266 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1267 port->timeouts.ReadTotalTimeoutConstant = 0;
1268 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1269 RETURN_FAIL("SetCommTimeouts() failed");
1273 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1274 if (GetLastError() != ERROR_IO_PENDING)
1275 RETURN_FAIL("ReadFile() failed");
1277 /* Get number of bytes read. */
1278 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1279 RETURN_FAIL("GetOverlappedResult() failed");
1281 TRY(restart_wait_if_needed(port, bytes_read));
1283 RETURN_INT(bytes_read);
1287 /* Returns the number of bytes read, or -1 upon failure. */
1288 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1289 if (errno == EAGAIN)
1290 /* No bytes available. */
1293 /* This is an actual failure. */
1294 RETURN_FAIL("read() failed");
1296 RETURN_INT(bytes_read);
1300 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1306 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1312 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1313 RETURN_FAIL("ClearCommError() failed");
1314 RETURN_INT(comstat.cbInQue);
1317 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1318 RETURN_FAIL("TIOCINQ ioctl failed");
1319 RETURN_INT(bytes_waiting);
1323 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1329 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1335 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1336 RETURN_FAIL("ClearCommError() failed");
1337 RETURN_INT(comstat.cbOutQue);
1340 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1341 RETURN_FAIL("TIOCOUTQ ioctl failed");
1342 RETURN_INT(bytes_waiting);
1346 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1348 struct sp_event_set *result;
1350 TRACE("%p", result_ptr);
1353 RETURN_ERROR(SP_ERR_ARG, "Null result");
1357 if (!(result = malloc(sizeof(struct sp_event_set))))
1358 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1360 memset(result, 0, sizeof(struct sp_event_set));
1362 *result_ptr = result;
1367 static enum sp_return add_handle(struct sp_event_set *event_set,
1368 event_handle handle, enum sp_event mask)
1371 enum sp_event *new_masks;
1373 TRACE("%p, %d, %d", event_set, handle, mask);
1375 if (!(new_handles = realloc(event_set->handles,
1376 sizeof(event_handle) * (event_set->count + 1))))
1377 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1379 event_set->handles = new_handles;
1381 if (!(new_masks = realloc(event_set->masks,
1382 sizeof(enum sp_event) * (event_set->count + 1))))
1383 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1385 event_set->masks = new_masks;
1387 ((event_handle *) event_set->handles)[event_set->count] = handle;
1388 event_set->masks[event_set->count] = mask;
1395 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1396 const struct sp_port *port, enum sp_event mask)
1398 TRACE("%p, %p, %d", event_set, port, mask);
1401 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1404 RETURN_ERROR(SP_ERR_ARG, "Null port");
1406 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1407 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1413 enum sp_event handle_mask;
1414 if ((handle_mask = mask & SP_EVENT_TX_READY))
1415 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1416 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1417 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1419 TRY(add_handle(event_set, port->fd, mask));
1425 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1427 TRACE("%p", event_set);
1430 DEBUG("Null event set");
1434 DEBUG("Freeing event set");
1436 if (event_set->handles)
1437 free(event_set->handles);
1438 if (event_set->masks)
1439 free(event_set->masks);
1446 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1447 unsigned int timeout_ms)
1449 TRACE("%p, %d", event_set, timeout_ms);
1452 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1455 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1456 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1457 RETURN_FAIL("WaitForMultipleObjects() failed");
1461 struct timeval start, delta, now, end = {0, 0};
1462 const struct timeval max_delta = {
1463 (INT_MAX / 1000), (INT_MAX % 1000) * 1000
1465 int started = 0, timeout_overflow = 0;
1466 int result, timeout_remaining_ms;
1467 struct pollfd *pollfds;
1470 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1471 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1473 for (i = 0; i < event_set->count; i++) {
1474 pollfds[i].fd = ((int *)event_set->handles)[i];
1475 pollfds[i].events = 0;
1476 pollfds[i].revents = 0;
1477 if (event_set->masks[i] & SP_EVENT_RX_READY)
1478 pollfds[i].events |= POLLIN;
1479 if (event_set->masks[i] & SP_EVENT_TX_READY)
1480 pollfds[i].events |= POLLOUT;
1481 if (event_set->masks[i] & SP_EVENT_ERROR)
1482 pollfds[i].events |= POLLERR;
1486 /* Get time at start of operation. */
1487 gettimeofday(&start, NULL);
1488 /* Define duration of timeout. */
1489 delta.tv_sec = timeout_ms / 1000;
1490 delta.tv_usec = (timeout_ms % 1000) * 1000;
1491 /* Calculate time at which we should give up. */
1492 timeradd(&start, &delta, &end);
1495 /* Loop until an event occurs. */
1498 * Check timeout only if we have run poll() at least once,
1499 * to avoid any issues if a short timeout is reached before
1500 * poll() is even run.
1503 timeout_remaining_ms = -1;
1504 } else if (!started) {
1505 timeout_overflow = (timeout_ms > INT_MAX);
1506 timeout_remaining_ms = timeout_overflow ? INT_MAX : timeout_ms;
1508 gettimeofday(&now, NULL);
1509 if (timercmp(&now, &end, >)) {
1510 DEBUG("Wait timed out");
1513 timersub(&end, &now, &delta);
1514 if ((timeout_overflow = timercmp(&delta, &max_delta, >)))
1516 timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1519 result = poll(pollfds, event_set->count, timeout_remaining_ms);
1523 if (errno == EINTR) {
1524 DEBUG("poll() call was interrupted, repeating");
1528 RETURN_FAIL("poll() failed");
1530 } else if (result == 0) {
1531 DEBUG("poll() timed out");
1532 if (!timeout_overflow)
1535 DEBUG("poll() completed");
1545 #ifdef USE_TERMIOS_SPEED
1546 static enum sp_return get_baudrate(int fd, int *baudrate)
1550 TRACE("%d, %p", fd, baudrate);
1552 DEBUG("Getting baud rate");
1554 if (!(data = malloc(get_termios_size())))
1555 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1557 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1559 RETURN_FAIL("Getting termios failed");
1562 *baudrate = get_termios_speed(data);
1569 static enum sp_return set_baudrate(int fd, int baudrate)
1573 TRACE("%d, %d", fd, baudrate);
1575 DEBUG("Getting baud rate");
1577 if (!(data = malloc(get_termios_size())))
1578 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1580 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1582 RETURN_FAIL("Getting termios failed");
1585 DEBUG("Setting baud rate");
1587 set_termios_speed(data, baudrate);
1589 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1591 RETURN_FAIL("Setting termios failed");
1598 #endif /* USE_TERMIOS_SPEED */
1601 static enum sp_return get_flow(int fd, struct port_data *data)
1605 TRACE("%d, %p", fd, data);
1607 DEBUG("Getting advanced flow control");
1609 if (!(termx = malloc(get_termiox_size())))
1610 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1612 if (ioctl(fd, TCGETX, termx) < 0) {
1614 RETURN_FAIL("Getting termiox failed");
1617 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1618 &data->dtr_flow, &data->dsr_flow);
1625 static enum sp_return set_flow(int fd, struct port_data *data)
1629 TRACE("%d, %p", fd, data);
1631 DEBUG("Getting advanced flow control");
1633 if (!(termx = malloc(get_termiox_size())))
1634 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1636 if (ioctl(fd, TCGETX, termx) < 0) {
1638 RETURN_FAIL("Getting termiox failed");
1641 DEBUG("Setting advanced flow control");
1643 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1644 data->dtr_flow, data->dsr_flow);
1646 if (ioctl(fd, TCSETX, termx) < 0) {
1648 RETURN_FAIL("Setting termiox failed");
1655 #endif /* USE_TERMIOX */
1657 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1658 struct sp_port_config *config)
1662 TRACE("%p, %p, %p", port, data, config);
1664 DEBUG_FMT("Getting configuration for port %s", port->name);
1667 if (!GetCommState(port->hdl, &data->dcb))
1668 RETURN_FAIL("GetCommState() failed");
1670 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1671 if (data->dcb.BaudRate == std_baudrates[i].index) {
1672 config->baudrate = std_baudrates[i].value;
1677 if (i == NUM_STD_BAUDRATES)
1678 /* BaudRate field can be either an index or a custom baud rate. */
1679 config->baudrate = data->dcb.BaudRate;
1681 config->bits = data->dcb.ByteSize;
1683 if (data->dcb.fParity)
1684 switch (data->dcb.Parity) {
1686 config->parity = SP_PARITY_NONE;
1689 config->parity = SP_PARITY_ODD;
1692 config->parity = SP_PARITY_EVEN;
1695 config->parity = SP_PARITY_MARK;
1698 config->parity = SP_PARITY_SPACE;
1701 config->parity = -1;
1704 config->parity = SP_PARITY_NONE;
1706 switch (data->dcb.StopBits) {
1708 config->stopbits = 1;
1711 config->stopbits = 2;
1714 config->stopbits = -1;
1717 switch (data->dcb.fRtsControl) {
1718 case RTS_CONTROL_DISABLE:
1719 config->rts = SP_RTS_OFF;
1721 case RTS_CONTROL_ENABLE:
1722 config->rts = SP_RTS_ON;
1724 case RTS_CONTROL_HANDSHAKE:
1725 config->rts = SP_RTS_FLOW_CONTROL;
1731 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1733 switch (data->dcb.fDtrControl) {
1734 case DTR_CONTROL_DISABLE:
1735 config->dtr = SP_DTR_OFF;
1737 case DTR_CONTROL_ENABLE:
1738 config->dtr = SP_DTR_ON;
1740 case DTR_CONTROL_HANDSHAKE:
1741 config->dtr = SP_DTR_FLOW_CONTROL;
1747 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1749 if (data->dcb.fInX) {
1750 if (data->dcb.fOutX)
1751 config->xon_xoff = SP_XONXOFF_INOUT;
1753 config->xon_xoff = SP_XONXOFF_IN;
1755 if (data->dcb.fOutX)
1756 config->xon_xoff = SP_XONXOFF_OUT;
1758 config->xon_xoff = SP_XONXOFF_DISABLED;
1763 if (tcgetattr(port->fd, &data->term) < 0)
1764 RETURN_FAIL("tcgetattr() failed");
1766 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1767 RETURN_FAIL("TIOCMGET ioctl failed");
1770 int ret = get_flow(port->fd, data);
1772 if (ret == SP_ERR_FAIL && errno == EINVAL)
1773 data->termiox_supported = 0;
1775 RETURN_CODEVAL(ret);
1777 data->termiox_supported = 1;
1779 data->termiox_supported = 0;
1782 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1783 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1784 config->baudrate = std_baudrates[i].value;
1789 if (i == NUM_STD_BAUDRATES) {
1791 config->baudrate = (int)data->term.c_ispeed;
1792 #elif defined(USE_TERMIOS_SPEED)
1793 TRY(get_baudrate(port->fd, &config->baudrate));
1795 config->baudrate = -1;
1799 switch (data->term.c_cflag & CSIZE) {
1816 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1817 config->parity = SP_PARITY_NONE;
1818 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1819 config->parity = -1;
1821 else if (data->term.c_cflag & CMSPAR)
1822 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1825 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1827 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1829 if (data->term.c_cflag & CRTSCTS) {
1830 config->rts = SP_RTS_FLOW_CONTROL;
1831 config->cts = SP_CTS_FLOW_CONTROL;
1833 if (data->termiox_supported && data->rts_flow)
1834 config->rts = SP_RTS_FLOW_CONTROL;
1836 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1838 config->cts = (data->termiox_supported && data->cts_flow) ?
1839 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1842 if (data->termiox_supported && data->dtr_flow)
1843 config->dtr = SP_DTR_FLOW_CONTROL;
1845 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1847 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1848 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1850 if (data->term.c_iflag & IXOFF) {
1851 if (data->term.c_iflag & IXON)
1852 config->xon_xoff = SP_XONXOFF_INOUT;
1854 config->xon_xoff = SP_XONXOFF_IN;
1856 if (data->term.c_iflag & IXON)
1857 config->xon_xoff = SP_XONXOFF_OUT;
1859 config->xon_xoff = SP_XONXOFF_DISABLED;
1866 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1867 const struct sp_port_config *config)
1871 BAUD_TYPE baud_nonstd;
1875 #ifdef USE_TERMIOS_SPEED
1876 int baud_nonstd = 0;
1879 TRACE("%p, %p, %p", port, data, config);
1881 DEBUG_FMT("Setting configuration for port %s", port->name);
1884 if (config->baudrate >= 0) {
1885 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1886 if (config->baudrate == std_baudrates[i].value) {
1887 data->dcb.BaudRate = std_baudrates[i].index;
1892 if (i == NUM_STD_BAUDRATES)
1893 data->dcb.BaudRate = config->baudrate;
1896 if (config->bits >= 0)
1897 data->dcb.ByteSize = config->bits;
1899 if (config->parity >= 0) {
1900 switch (config->parity) {
1901 case SP_PARITY_NONE:
1902 data->dcb.Parity = NOPARITY;
1905 data->dcb.Parity = ODDPARITY;
1907 case SP_PARITY_EVEN:
1908 data->dcb.Parity = EVENPARITY;
1910 case SP_PARITY_MARK:
1911 data->dcb.Parity = MARKPARITY;
1913 case SP_PARITY_SPACE:
1914 data->dcb.Parity = SPACEPARITY;
1917 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1921 if (config->stopbits >= 0) {
1922 switch (config->stopbits) {
1923 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1925 data->dcb.StopBits = ONESTOPBIT;
1928 data->dcb.StopBits = TWOSTOPBITS;
1931 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1935 if (config->rts >= 0) {
1936 switch (config->rts) {
1938 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1941 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1943 case SP_RTS_FLOW_CONTROL:
1944 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1947 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1951 if (config->cts >= 0) {
1952 switch (config->cts) {
1954 data->dcb.fOutxCtsFlow = FALSE;
1956 case SP_CTS_FLOW_CONTROL:
1957 data->dcb.fOutxCtsFlow = TRUE;
1960 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1964 if (config->dtr >= 0) {
1965 switch (config->dtr) {
1967 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1970 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1972 case SP_DTR_FLOW_CONTROL:
1973 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1976 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1980 if (config->dsr >= 0) {
1981 switch (config->dsr) {
1983 data->dcb.fOutxDsrFlow = FALSE;
1985 case SP_DSR_FLOW_CONTROL:
1986 data->dcb.fOutxDsrFlow = TRUE;
1989 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1993 if (config->xon_xoff >= 0) {
1994 switch (config->xon_xoff) {
1995 case SP_XONXOFF_DISABLED:
1996 data->dcb.fInX = FALSE;
1997 data->dcb.fOutX = FALSE;
2000 data->dcb.fInX = TRUE;
2001 data->dcb.fOutX = FALSE;
2003 case SP_XONXOFF_OUT:
2004 data->dcb.fInX = FALSE;
2005 data->dcb.fOutX = TRUE;
2007 case SP_XONXOFF_INOUT:
2008 data->dcb.fInX = TRUE;
2009 data->dcb.fOutX = TRUE;
2012 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2016 if (!SetCommState(port->hdl, &data->dcb))
2017 RETURN_FAIL("SetCommState() failed");
2023 if (config->baudrate >= 0) {
2024 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2025 if (config->baudrate == std_baudrates[i].value) {
2026 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2027 RETURN_FAIL("cfsetospeed() failed");
2029 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2030 RETURN_FAIL("cfsetispeed() failed");
2035 /* Non-standard baud rate */
2036 if (i == NUM_STD_BAUDRATES) {
2038 /* Set "dummy" baud rate. */
2039 if (cfsetspeed(&data->term, B9600) < 0)
2040 RETURN_FAIL("cfsetspeed() failed");
2041 baud_nonstd = config->baudrate;
2042 #elif defined(USE_TERMIOS_SPEED)
2045 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2050 if (config->bits >= 0) {
2051 data->term.c_cflag &= ~CSIZE;
2052 switch (config->bits) {
2054 data->term.c_cflag |= CS8;
2057 data->term.c_cflag |= CS7;
2060 data->term.c_cflag |= CS6;
2063 data->term.c_cflag |= CS5;
2066 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2070 if (config->parity >= 0) {
2071 data->term.c_iflag &= ~IGNPAR;
2072 data->term.c_cflag &= ~(PARENB | PARODD);
2074 data->term.c_cflag &= ~CMSPAR;
2076 switch (config->parity) {
2077 case SP_PARITY_NONE:
2078 data->term.c_iflag |= IGNPAR;
2080 case SP_PARITY_EVEN:
2081 data->term.c_cflag |= PARENB;
2084 data->term.c_cflag |= PARENB | PARODD;
2087 case SP_PARITY_MARK:
2088 data->term.c_cflag |= PARENB | PARODD;
2089 data->term.c_cflag |= CMSPAR;
2091 case SP_PARITY_SPACE:
2092 data->term.c_cflag |= PARENB;
2093 data->term.c_cflag |= CMSPAR;
2096 case SP_PARITY_MARK:
2097 case SP_PARITY_SPACE:
2098 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2101 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2105 if (config->stopbits >= 0) {
2106 data->term.c_cflag &= ~CSTOPB;
2107 switch (config->stopbits) {
2109 data->term.c_cflag &= ~CSTOPB;
2112 data->term.c_cflag |= CSTOPB;
2115 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2119 if (config->rts >= 0 || config->cts >= 0) {
2120 if (data->termiox_supported) {
2121 data->rts_flow = data->cts_flow = 0;
2122 switch (config->rts) {
2125 controlbits = TIOCM_RTS;
2126 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2127 RETURN_FAIL("Setting RTS signal level failed");
2129 case SP_RTS_FLOW_CONTROL:
2135 if (config->cts == SP_CTS_FLOW_CONTROL)
2138 if (data->rts_flow && data->cts_flow)
2139 data->term.c_iflag |= CRTSCTS;
2141 data->term.c_iflag &= ~CRTSCTS;
2143 /* Asymmetric use of RTS/CTS not supported. */
2144 if (data->term.c_iflag & CRTSCTS) {
2145 /* Flow control can only be disabled for both RTS & CTS together. */
2146 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2147 if (config->cts != SP_CTS_IGNORE)
2148 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2150 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2151 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2152 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2155 /* Flow control can only be enabled for both RTS & CTS together. */
2156 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2157 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2158 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2161 if (config->rts >= 0) {
2162 if (config->rts == SP_RTS_FLOW_CONTROL) {
2163 data->term.c_iflag |= CRTSCTS;
2165 controlbits = TIOCM_RTS;
2166 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2168 RETURN_FAIL("Setting RTS signal level failed");
2174 if (config->dtr >= 0 || config->dsr >= 0) {
2175 if (data->termiox_supported) {
2176 data->dtr_flow = data->dsr_flow = 0;
2177 switch (config->dtr) {
2180 controlbits = TIOCM_DTR;
2181 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2182 RETURN_FAIL("Setting DTR signal level failed");
2184 case SP_DTR_FLOW_CONTROL:
2190 if (config->dsr == SP_DSR_FLOW_CONTROL)
2193 /* DTR/DSR flow control not supported. */
2194 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2195 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2197 if (config->dtr >= 0) {
2198 controlbits = TIOCM_DTR;
2199 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2201 RETURN_FAIL("Setting DTR signal level failed");
2206 if (config->xon_xoff >= 0) {
2207 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2208 switch (config->xon_xoff) {
2209 case SP_XONXOFF_DISABLED:
2212 data->term.c_iflag |= IXOFF;
2214 case SP_XONXOFF_OUT:
2215 data->term.c_iflag |= IXON | IXANY;
2217 case SP_XONXOFF_INOUT:
2218 data->term.c_iflag |= IXON | IXOFF | IXANY;
2221 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2225 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2226 RETURN_FAIL("tcsetattr() failed");
2229 if (baud_nonstd != B0) {
2230 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2231 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2233 * Set baud rates in data->term to correct, but incompatible
2234 * with tcsetattr() value, same as delivered by tcgetattr().
2236 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2237 RETURN_FAIL("cfsetspeed() failed");
2239 #elif defined(__linux__)
2240 #ifdef USE_TERMIOS_SPEED
2242 TRY(set_baudrate(port->fd, config->baudrate));
2245 if (data->termiox_supported)
2246 TRY(set_flow(port->fd, data));
2250 #endif /* !_WIN32 */
2255 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2257 struct sp_port_config *config;
2259 TRACE("%p", config_ptr);
2262 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2266 if (!(config = malloc(sizeof(struct sp_port_config))))
2267 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2269 config->baudrate = -1;
2271 config->parity = -1;
2272 config->stopbits = -1;
2278 *config_ptr = config;
2283 SP_API void sp_free_config(struct sp_port_config *config)
2285 TRACE("%p", config);
2288 DEBUG("Null config");
2295 SP_API enum sp_return sp_get_config(struct sp_port *port,
2296 struct sp_port_config *config)
2298 struct port_data data;
2300 TRACE("%p, %p", port, config);
2305 RETURN_ERROR(SP_ERR_ARG, "Null config");
2307 TRY(get_config(port, &data, config));
2312 SP_API enum sp_return sp_set_config(struct sp_port *port,
2313 const struct sp_port_config *config)
2315 struct port_data data;
2316 struct sp_port_config prev_config;
2318 TRACE("%p, %p", port, config);
2323 RETURN_ERROR(SP_ERR_ARG, "Null config");
2325 TRY(get_config(port, &data, &prev_config));
2326 TRY(set_config(port, &data, config));
2331 #define CREATE_ACCESSORS(x, type) \
2332 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2333 struct port_data data; \
2334 struct sp_port_config config; \
2335 TRACE("%p, %d", port, x); \
2336 CHECK_OPEN_PORT(); \
2337 TRY(get_config(port, &data, &config)); \
2339 TRY(set_config(port, &data, &config)); \
2342 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2344 TRACE("%p, %p", config, x); \
2346 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2348 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2352 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2354 TRACE("%p, %d", config, x); \
2356 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2361 CREATE_ACCESSORS(baudrate, int)
2362 CREATE_ACCESSORS(bits, int)
2363 CREATE_ACCESSORS(parity, enum sp_parity)
2364 CREATE_ACCESSORS(stopbits, int)
2365 CREATE_ACCESSORS(rts, enum sp_rts)
2366 CREATE_ACCESSORS(cts, enum sp_cts)
2367 CREATE_ACCESSORS(dtr, enum sp_dtr)
2368 CREATE_ACCESSORS(dsr, enum sp_dsr)
2369 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2371 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2372 enum sp_flowcontrol flowcontrol)
2375 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2377 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2378 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2380 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2381 config->xon_xoff = SP_XONXOFF_INOUT;
2383 config->xon_xoff = SP_XONXOFF_DISABLED;
2385 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2386 config->rts = SP_RTS_FLOW_CONTROL;
2387 config->cts = SP_CTS_FLOW_CONTROL;
2389 if (config->rts == SP_RTS_FLOW_CONTROL)
2390 config->rts = SP_RTS_ON;
2391 config->cts = SP_CTS_IGNORE;
2394 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2395 config->dtr = SP_DTR_FLOW_CONTROL;
2396 config->dsr = SP_DSR_FLOW_CONTROL;
2398 if (config->dtr == SP_DTR_FLOW_CONTROL)
2399 config->dtr = SP_DTR_ON;
2400 config->dsr = SP_DSR_IGNORE;
2406 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2407 enum sp_flowcontrol flowcontrol)
2409 struct port_data data;
2410 struct sp_port_config config;
2412 TRACE("%p, %d", port, flowcontrol);
2416 TRY(get_config(port, &data, &config));
2418 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2420 TRY(set_config(port, &data, &config));
2425 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2426 enum sp_signal *signals)
2428 TRACE("%p, %p", port, signals);
2433 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2435 DEBUG_FMT("Getting control signals for port %s", port->name);
2440 if (GetCommModemStatus(port->hdl, &bits) == 0)
2441 RETURN_FAIL("GetCommModemStatus() failed");
2442 if (bits & MS_CTS_ON)
2443 *signals |= SP_SIG_CTS;
2444 if (bits & MS_DSR_ON)
2445 *signals |= SP_SIG_DSR;
2446 if (bits & MS_RLSD_ON)
2447 *signals |= SP_SIG_DCD;
2448 if (bits & MS_RING_ON)
2449 *signals |= SP_SIG_RI;
2452 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2453 RETURN_FAIL("TIOCMGET ioctl failed");
2454 if (bits & TIOCM_CTS)
2455 *signals |= SP_SIG_CTS;
2456 if (bits & TIOCM_DSR)
2457 *signals |= SP_SIG_DSR;
2458 if (bits & TIOCM_CAR)
2459 *signals |= SP_SIG_DCD;
2460 if (bits & TIOCM_RNG)
2461 *signals |= SP_SIG_RI;
2466 SP_API enum sp_return sp_start_break(struct sp_port *port)
2472 if (SetCommBreak(port->hdl) == 0)
2473 RETURN_FAIL("SetCommBreak() failed");
2475 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2476 RETURN_FAIL("TIOCSBRK ioctl failed");
2482 SP_API enum sp_return sp_end_break(struct sp_port *port)
2488 if (ClearCommBreak(port->hdl) == 0)
2489 RETURN_FAIL("ClearCommBreak() failed");
2491 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2492 RETURN_FAIL("TIOCCBRK ioctl failed");
2498 SP_API int sp_last_error_code(void)
2502 RETURN_INT(GetLastError());
2508 SP_API char *sp_last_error_message(void)
2514 DWORD error = GetLastError();
2516 DWORD length = FormatMessage(
2517 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2518 FORMAT_MESSAGE_FROM_SYSTEM |
2519 FORMAT_MESSAGE_IGNORE_INSERTS,
2522 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2526 if (length >= 2 && message[length - 2] == '\r')
2527 message[length - 2] = '\0';
2529 RETURN_STRING(message);
2531 RETURN_STRING(strerror(errno));
2535 SP_API void sp_free_error_message(char *message)
2537 TRACE("%s", message);
2548 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2550 TRACE("%p", handler);
2552 sp_debug_handler = handler;
2557 SP_API void sp_default_debug_handler(const char *format, ...)
2560 va_start(args, format);
2561 if (getenv("LIBSERIALPORT_DEBUG")) {
2562 fputs("sp: ", stderr);
2563 vfprintf(stderr, format, args);
2568 SP_API int sp_get_major_package_version(void)
2570 return SP_PACKAGE_VERSION_MAJOR;
2573 SP_API int sp_get_minor_package_version(void)
2575 return SP_PACKAGE_VERSION_MINOR;
2578 SP_API int sp_get_micro_package_version(void)
2580 return SP_PACKAGE_VERSION_MICRO;
2583 SP_API const char *sp_get_package_version_string(void)
2585 return SP_PACKAGE_VERSION_STRING;
2588 SP_API int sp_get_current_lib_version(void)
2590 return SP_LIB_VERSION_CURRENT;
2593 SP_API int sp_get_revision_lib_version(void)
2595 return SP_LIB_VERSION_REVISION;
2598 SP_API int sp_get_age_lib_version(void)
2600 return SP_LIB_VERSION_AGE;
2603 SP_API const char *sp_get_lib_version_string(void)
2605 return SP_LIB_VERSION_STRING;