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/>.
24 #include "libserialport_internal.h"
26 static const struct std_baudrate std_baudrates[] = {
29 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
30 * have documented CBR_* macros.
32 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
33 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
34 BAUD(115200), BAUD(128000), BAUD(256000),
36 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
37 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
38 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
40 #if !defined(__APPLE__) && !defined(__OpenBSD__)
46 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
48 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
50 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
51 struct sp_port_config *config);
53 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
54 const struct sp_port_config *config);
56 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
59 #ifndef NO_PORT_METADATA
64 TRACE("%s, %p", portname, port_ptr);
67 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
72 RETURN_ERROR(SP_ERR_ARG, "Null port name");
74 DEBUG_FMT("Building structure for port %s", portname);
76 #if !defined(_WIN32) && defined(HAVE_REALPATH)
78 * get_port_details() below tries to be too smart and figure out
79 * some transport properties from the port name which breaks with
80 * symlinks. Therefore we canonicalize the portname first.
82 char pathbuf[PATH_MAX + 1];
83 char *res = realpath(portname, pathbuf);
85 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
90 if (!(port = malloc(sizeof(struct sp_port))))
91 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
93 len = strlen(portname) + 1;
95 if (!(port->name = malloc(len))) {
97 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
100 memcpy(port->name, portname, len);
103 port->usb_path = NULL;
104 port->hdl = INVALID_HANDLE_VALUE;
105 port->write_buf = NULL;
106 port->write_buf_size = 0;
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)
158 RETURN_INT(port ? port->transport : SP_TRANSPORT_NATIVE);
161 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
162 int *usb_bus,int *usb_address)
167 RETURN_ERROR(SP_ERR_ARG, "Null port");
168 if (port->transport != SP_TRANSPORT_USB)
169 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
170 if (port->usb_bus < 0 || port->usb_address < 0)
171 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
174 *usb_bus = port->usb_bus;
176 *usb_address = port->usb_address;
181 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
182 int *usb_vid, int *usb_pid)
187 RETURN_ERROR(SP_ERR_ARG, "Null port");
188 if (port->transport != SP_TRANSPORT_USB)
189 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
190 if (port->usb_vid < 0 || port->usb_pid < 0)
191 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
194 *usb_vid = port->usb_vid;
196 *usb_pid = port->usb_pid;
201 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
205 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
208 RETURN_STRING(port->usb_manufacturer);
211 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
215 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
218 RETURN_STRING(port->usb_product);
221 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
225 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
228 RETURN_STRING(port->usb_serial);
231 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
235 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
236 || !port->bluetooth_address)
239 RETURN_STRING(port->bluetooth_address);
242 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
245 TRACE("%p, %p", port, result_ptr);
248 RETURN_ERROR(SP_ERR_ARG, "Null port");
250 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
253 HANDLE *handle_ptr = result_ptr;
254 *handle_ptr = port->hdl;
256 int *fd_ptr = result_ptr;
263 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
264 struct sp_port **copy_ptr)
266 TRACE("%p, %p", port, copy_ptr);
269 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
274 RETURN_ERROR(SP_ERR_ARG, "Null port");
277 RETURN_ERROR(SP_ERR_ARG, "Null port name");
279 DEBUG("Copying port structure");
281 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
284 SP_API void sp_free_port(struct sp_port *port)
293 DEBUG("Freeing port structure");
297 if (port->description)
298 free(port->description);
299 if (port->usb_manufacturer)
300 free(port->usb_manufacturer);
301 if (port->usb_product)
302 free(port->usb_product);
303 if (port->usb_serial)
304 free(port->usb_serial);
305 if (port->bluetooth_address)
306 free(port->bluetooth_address);
309 free(port->usb_path);
311 free(port->write_buf);
319 SP_PRIV struct sp_port **list_append(struct sp_port **list,
320 const char *portname)
325 for (count = 0; list[count]; count++)
327 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
330 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
332 list[count + 1] = NULL;
336 sp_free_port_list(list);
340 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
342 #ifndef NO_ENUMERATION
343 struct sp_port **list;
347 TRACE("%p", list_ptr);
350 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
354 #ifdef NO_ENUMERATION
355 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
357 DEBUG("Enumerating ports");
359 if (!(list = malloc(sizeof(struct sp_port *))))
360 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
364 ret = list_ports(&list);
369 sp_free_port_list(list);
377 SP_API void sp_free_port_list(struct sp_port **list)
388 DEBUG("Freeing port list");
390 for (i = 0; list[i]; i++)
391 sp_free_port(list[i]);
397 #define CHECK_PORT() do { \
399 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
401 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
404 #define CHECK_PORT_HANDLE() do { \
405 if (port->hdl == INVALID_HANDLE_VALUE) \
406 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
409 #define CHECK_PORT_HANDLE() do { \
411 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
414 #define CHECK_OPEN_PORT() do { \
416 CHECK_PORT_HANDLE(); \
420 /** To be called after port receive buffer is emptied. */
421 static enum sp_return restart_wait(struct sp_port *port)
425 if (port->wait_running) {
426 /* Check status of running wait operation. */
427 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
428 &wait_result, FALSE)) {
429 DEBUG("Previous wait completed");
430 port->wait_running = FALSE;
431 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
432 DEBUG("Previous wait still running");
435 RETURN_FAIL("GetOverlappedResult() failed");
439 if (!port->wait_running) {
440 /* Start new wait operation. */
441 if (WaitCommEvent(port->hdl, &port->events,
443 DEBUG("New wait returned, events already pending");
444 } else if (GetLastError() == ERROR_IO_PENDING) {
445 DEBUG("New wait running in background");
446 port->wait_running = TRUE;
448 RETURN_FAIL("WaitCommEvent() failed");
456 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
458 struct port_data data;
459 struct sp_port_config config;
462 TRACE("%p, 0x%x", port, flags);
466 if (flags > SP_MODE_READ_WRITE)
467 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
469 DEBUG_FMT("Opening port %s", port->name);
472 DWORD desired_access = 0, flags_and_attributes = 0, errors;
473 char *escaped_port_name;
476 /* Prefix port name with '\\.\' to work with ports above COM9. */
477 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
478 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
479 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
481 /* Map 'flags' to the OS-specific settings. */
482 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
483 if (flags & SP_MODE_READ)
484 desired_access |= GENERIC_READ;
485 if (flags & SP_MODE_WRITE)
486 desired_access |= GENERIC_WRITE;
488 port->hdl = CreateFileA(escaped_port_name, desired_access, 0, 0,
489 OPEN_EXISTING, flags_and_attributes, 0);
491 free(escaped_port_name);
493 if (port->hdl == INVALID_HANDLE_VALUE)
494 RETURN_FAIL("Port CreateFile() failed");
496 /* All timeouts initially disabled. */
497 port->timeouts.ReadIntervalTimeout = 0;
498 port->timeouts.ReadTotalTimeoutMultiplier = 0;
499 port->timeouts.ReadTotalTimeoutConstant = 0;
500 port->timeouts.WriteTotalTimeoutMultiplier = 0;
501 port->timeouts.WriteTotalTimeoutConstant = 0;
503 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
505 RETURN_FAIL("SetCommTimeouts() failed");
508 /* Prepare OVERLAPPED structures. */
509 #define INIT_OVERLAPPED(ovl) do { \
510 memset(&port->ovl, 0, sizeof(port->ovl)); \
511 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
512 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
513 == INVALID_HANDLE_VALUE) { \
515 RETURN_FAIL(#ovl "CreateEvent() failed"); \
519 INIT_OVERLAPPED(read_ovl);
520 INIT_OVERLAPPED(write_ovl);
521 INIT_OVERLAPPED(wait_ovl);
523 /* Set event mask for RX and error events. */
524 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
526 RETURN_FAIL("SetCommMask() failed");
529 port->writing = FALSE;
530 port->wait_running = FALSE;
532 ret = restart_wait(port);
539 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
541 /* Map 'flags' to the OS-specific settings. */
542 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
543 flags_local |= O_RDWR;
544 else if (flags & SP_MODE_READ)
545 flags_local |= O_RDONLY;
546 else if (flags & SP_MODE_WRITE)
547 flags_local |= O_WRONLY;
549 if ((port->fd = open(port->name, flags_local)) < 0)
550 RETURN_FAIL("open() failed");
553 * On POSIX in the default case the file descriptor of a serial port
554 * is not opened exclusively. Therefore the settings of a port are
555 * overwritten if the serial port is opened a second time. Windows
556 * opens all serial ports exclusively.
557 * So the idea is to open the serial ports alike in the exclusive mode.
559 * ioctl(*, TIOCEXCL) defines the file descriptor as exclusive. So all
560 * further open calls on the serial port will fail.
562 * There is a race condition if two processes open the same serial
563 * port. None of the processes will notice the exclusive ownership of
564 * the other process because ioctl() doesn't return an error code if
565 * the file descriptor is already marked as exclusive.
566 * This can be solved with flock(). It returns an error if the file
567 * descriptor is already locked by another process.
570 if (flock(port->fd, LOCK_EX | LOCK_NB) < 0)
571 RETURN_FAIL("flock() failed");
576 * Before Linux 3.8 ioctl(*, TIOCEXCL) was not implemented and could
577 * lead to EINVAL or ENOTTY.
578 * These errors aren't fatal and can be ignored.
580 if (ioctl(port->fd, TIOCEXCL) < 0 && errno != EINVAL && errno != ENOTTY)
581 RETURN_FAIL("ioctl() failed");
586 ret = get_config(port, &data, &config);
593 /* Set sane port settings. */
595 data.dcb.fBinary = TRUE;
596 data.dcb.fDsrSensitivity = FALSE;
597 data.dcb.fErrorChar = FALSE;
598 data.dcb.fNull = FALSE;
599 data.dcb.fAbortOnError = FALSE;
601 /* Turn off all fancy termios tricks, give us a raw channel. */
602 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
604 data.term.c_iflag &= ~IUCLC;
606 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
608 data.term.c_oflag &= ~OLCUC;
611 data.term.c_oflag &= ~NLDLY;
614 data.term.c_oflag &= ~CRDLY;
617 data.term.c_oflag &= ~TABDLY;
620 data.term.c_oflag &= ~BSDLY;
623 data.term.c_oflag &= ~VTDLY;
626 data.term.c_oflag &= ~FFDLY;
629 data.term.c_oflag &= ~OFILL;
631 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
632 data.term.c_cc[VMIN] = 0;
633 data.term.c_cc[VTIME] = 0;
635 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
636 data.term.c_cflag |= (CLOCAL | CREAD);
637 data.term.c_cflag &= ~(HUPCL);
641 if (ClearCommError(port->hdl, &errors, &status) == 0)
642 RETURN_FAIL("ClearCommError() failed");
645 ret = set_config(port, &data, &config);
655 SP_API enum sp_return sp_close(struct sp_port *port)
661 DEBUG_FMT("Closing port %s", port->name);
664 /* Returns non-zero upon success, 0 upon failure. */
665 if (CloseHandle(port->hdl) == 0)
666 RETURN_FAIL("Port CloseHandle() failed");
667 port->hdl = INVALID_HANDLE_VALUE;
669 /* Close event handles for overlapped structures. */
670 #define CLOSE_OVERLAPPED(ovl) do { \
671 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
672 CloseHandle(port->ovl.hEvent) == 0) \
673 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
675 CLOSE_OVERLAPPED(read_ovl);
676 CLOSE_OVERLAPPED(write_ovl);
677 CLOSE_OVERLAPPED(wait_ovl);
679 if (port->write_buf) {
680 free(port->write_buf);
681 port->write_buf = NULL;
684 /* Returns 0 upon success, -1 upon failure. */
685 if (close(port->fd) == -1)
686 RETURN_FAIL("close() failed");
693 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
695 TRACE("%p, 0x%x", port, buffers);
699 if (buffers > SP_BUF_BOTH)
700 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
702 const char *buffer_names[] = {"no", "input", "output", "both"};
704 DEBUG_FMT("Flushing %s buffers on port %s",
705 buffer_names[buffers], port->name);
709 if (buffers & SP_BUF_INPUT)
710 flags |= PURGE_RXCLEAR;
711 if (buffers & SP_BUF_OUTPUT)
712 flags |= PURGE_TXCLEAR;
714 /* Returns non-zero upon success, 0 upon failure. */
715 if (PurgeComm(port->hdl, flags) == 0)
716 RETURN_FAIL("PurgeComm() failed");
718 if (buffers & SP_BUF_INPUT)
719 TRY(restart_wait(port));
722 if (buffers == SP_BUF_BOTH)
724 else if (buffers == SP_BUF_INPUT)
726 else if (buffers == SP_BUF_OUTPUT)
729 /* Returns 0 upon success, -1 upon failure. */
730 if (tcflush(port->fd, flags) < 0)
731 RETURN_FAIL("tcflush() failed");
736 SP_API enum sp_return sp_drain(struct sp_port *port)
742 DEBUG_FMT("Draining port %s", port->name);
745 /* Returns non-zero upon success, 0 upon failure. */
746 if (FlushFileBuffers(port->hdl) == 0)
747 RETURN_FAIL("FlushFileBuffers() failed");
752 #if defined(__ANDROID__) && (__ANDROID_API__ < 21)
753 /* Android only has tcdrain from platform 21 onwards.
754 * On previous API versions, use the ioctl directly. */
756 result = ioctl(port->fd, TCSBRK, &arg);
758 result = tcdrain(port->fd);
761 if (errno == EINTR) {
762 DEBUG("tcdrain() was interrupted");
765 RETURN_FAIL("tcdrain() failed");
775 static enum sp_return await_write_completion(struct sp_port *port)
781 /* Wait for previous non-blocking write to complete, if any. */
783 DEBUG("Waiting for previous write to complete");
784 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
787 RETURN_FAIL("Previous write failed to complete");
788 DEBUG("Previous write completed");
795 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
796 size_t count, unsigned int timeout_ms)
798 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
803 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
806 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
807 count, port->name, timeout_ms);
809 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
816 DWORD remaining_ms, write_size, bytes_written;
817 size_t remaining_bytes, total_bytes_written = 0;
818 const uint8_t *write_ptr = (uint8_t *) buf;
820 struct timeout timeout;
822 timeout_start(&timeout, timeout_ms);
824 TRY(await_write_completion(port));
826 while (total_bytes_written < count) {
828 if (timeout_check(&timeout))
831 remaining_ms = timeout_remaining_ms(&timeout);
833 if (port->timeouts.WriteTotalTimeoutConstant != remaining_ms) {
834 port->timeouts.WriteTotalTimeoutConstant = remaining_ms;
835 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
836 RETURN_FAIL("SetCommTimeouts() failed");
839 /* Reduce write size if it exceeds the WriteFile limit. */
840 remaining_bytes = count - total_bytes_written;
841 if (remaining_bytes > WRITEFILE_MAX_SIZE)
842 write_size = WRITEFILE_MAX_SIZE;
844 write_size = (DWORD) remaining_bytes;
848 result = WriteFile(port->hdl, write_ptr, write_size, NULL, &port->write_ovl);
850 timeout_update(&timeout);
853 DEBUG("Write completed immediately");
854 bytes_written = write_size;
855 } else if (GetLastError() == ERROR_IO_PENDING) {
856 DEBUG("Waiting for write to complete");
857 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
858 if (GetLastError() == ERROR_SEM_TIMEOUT) {
859 DEBUG("Write timed out");
862 RETURN_FAIL("GetOverlappedResult() failed");
865 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, write_size);
867 RETURN_FAIL("WriteFile() failed");
870 write_ptr += bytes_written;
871 total_bytes_written += bytes_written;
874 RETURN_INT((int) total_bytes_written);
876 size_t bytes_written = 0;
877 unsigned char *ptr = (unsigned char *) buf;
878 struct timeout timeout;
882 timeout_start(&timeout, timeout_ms);
885 FD_SET(port->fd, &fds);
887 /* Loop until we have written the requested number of bytes. */
888 while (bytes_written < count) {
890 if (timeout_check(&timeout))
893 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
895 timeout_update(&timeout);
898 if (errno == EINTR) {
899 DEBUG("select() call was interrupted, repeating");
902 RETURN_FAIL("select() failed");
904 } else if (result == 0) {
905 /* Timeout has expired. */
910 result = write(port->fd, ptr, count - bytes_written);
914 /* This shouldn't happen because we did a select() first, but handle anyway. */
917 /* This is an actual failure. */
918 RETURN_FAIL("write() failed");
921 bytes_written += result;
925 if (bytes_written < count)
926 DEBUG("Write timed out");
928 RETURN_INT(bytes_written);
932 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
933 const void *buf, size_t count)
935 TRACE("%p, %p, %d", port, buf, count);
940 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
942 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
950 /* Check whether previous write is complete. */
952 if (HasOverlappedIoCompleted(&port->write_ovl)) {
953 DEBUG("Previous write completed");
956 DEBUG("Previous write not complete");
957 /* Can't take a new write until the previous one finishes. */
963 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
964 port->timeouts.WriteTotalTimeoutConstant = 0;
965 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
966 RETURN_FAIL("SetCommTimeouts() failed");
969 /* Reduce count if it exceeds the WriteFile limit. */
970 if (count > WRITEFILE_MAX_SIZE)
971 count = WRITEFILE_MAX_SIZE;
973 /* Copy data to our write buffer. */
974 buf_bytes = min(port->write_buf_size, count);
975 memcpy(port->write_buf, buf, buf_bytes);
977 /* Start asynchronous write. */
978 if (WriteFile(port->hdl, port->write_buf, (DWORD) buf_bytes, NULL, &port->write_ovl) == 0) {
979 if (GetLastError() == ERROR_IO_PENDING) {
980 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
981 DEBUG("Asynchronous write completed immediately");
983 DEBUG("Asynchronous write running");
985 /* Actual failure of some kind. */
986 RETURN_FAIL("WriteFile() failed");
990 DEBUG("All bytes written immediately");
992 RETURN_INT((int) buf_bytes);
994 /* Returns the number of bytes written, or -1 upon failure. */
995 ssize_t written = write(port->fd, buf, count);
999 // Buffer is full, no bytes written.
1002 RETURN_FAIL("write() failed");
1004 RETURN_INT(written);
1010 /* Restart wait operation if buffer was emptied. */
1011 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1016 if (bytes_read == 0)
1019 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1020 RETURN_FAIL("ClearCommError() failed");
1022 if (comstat.cbInQue == 0)
1023 TRY(restart_wait(port));
1029 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1030 size_t count, unsigned int timeout_ms)
1032 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1037 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1040 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1041 count, port->name, timeout_ms);
1043 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1053 if (port->timeouts.ReadIntervalTimeout != 0 ||
1054 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1055 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1056 port->timeouts.ReadIntervalTimeout = 0;
1057 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1058 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1059 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1060 RETURN_FAIL("SetCommTimeouts() failed");
1064 if (ReadFile(port->hdl, buf, (DWORD) count, NULL, &port->read_ovl)) {
1065 DEBUG("Read completed immediately");
1066 bytes_read = (DWORD) count;
1067 } else if (GetLastError() == ERROR_IO_PENDING) {
1068 DEBUG("Waiting for read to complete");
1069 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1070 RETURN_FAIL("GetOverlappedResult() failed");
1071 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1073 RETURN_FAIL("ReadFile() failed");
1076 TRY(restart_wait_if_needed(port, bytes_read));
1078 RETURN_INT((int) bytes_read);
1081 size_t bytes_read = 0;
1082 unsigned char *ptr = (unsigned char *) buf;
1083 struct timeout timeout;
1087 timeout_start(&timeout, timeout_ms);
1090 FD_SET(port->fd, &fds);
1092 /* Loop until we have the requested number of bytes. */
1093 while (bytes_read < count) {
1095 if (timeout_check(&timeout))
1096 /* Timeout has expired. */
1099 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1101 timeout_update(&timeout);
1104 if (errno == EINTR) {
1105 DEBUG("select() call was interrupted, repeating");
1108 RETURN_FAIL("select() failed");
1110 } else if (result == 0) {
1111 /* Timeout has expired. */
1116 result = read(port->fd, ptr, count - bytes_read);
1119 if (errno == EAGAIN)
1121 * This shouldn't happen because we did a
1122 * select() first, but handle anyway.
1126 /* This is an actual failure. */
1127 RETURN_FAIL("read() failed");
1130 bytes_read += result;
1134 if (bytes_read < count)
1135 DEBUG("Read timed out");
1137 RETURN_INT(bytes_read);
1141 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1142 size_t count, unsigned int timeout_ms)
1144 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1149 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1152 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1155 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1156 count, port->name, timeout_ms);
1158 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1162 DWORD bytes_read = 0;
1164 /* If timeout_ms == 0, set maximum timeout. */
1165 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1168 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1169 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1170 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1171 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1172 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1173 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1174 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1175 RETURN_FAIL("SetCommTimeouts() failed");
1178 /* Loop until we have at least one byte, or timeout is reached. */
1179 while (bytes_read == 0) {
1181 if (ReadFile(port->hdl, buf, (DWORD) count, &bytes_read, &port->read_ovl)) {
1182 DEBUG("Read completed immediately");
1183 } else if (GetLastError() == ERROR_IO_PENDING) {
1184 DEBUG("Waiting for read to complete");
1185 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1186 RETURN_FAIL("GetOverlappedResult() failed");
1187 if (bytes_read > 0) {
1188 DEBUG("Read completed");
1189 } else if (timeout_ms > 0) {
1190 DEBUG("Read timed out");
1193 DEBUG("Restarting read");
1196 RETURN_FAIL("ReadFile() failed");
1200 TRY(restart_wait_if_needed(port, bytes_read));
1202 RETURN_INT(bytes_read);
1205 size_t bytes_read = 0;
1206 struct timeout timeout;
1210 timeout_start(&timeout, timeout_ms);
1213 FD_SET(port->fd, &fds);
1215 /* Loop until we have at least one byte, or timeout is reached. */
1216 while (bytes_read == 0) {
1218 if (timeout_check(&timeout))
1219 /* Timeout has expired. */
1222 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1224 timeout_update(&timeout);
1227 if (errno == EINTR) {
1228 DEBUG("select() call was interrupted, repeating");
1231 RETURN_FAIL("select() failed");
1233 } else if (result == 0) {
1234 /* Timeout has expired. */
1239 result = read(port->fd, buf, count);
1242 if (errno == EAGAIN)
1243 /* This shouldn't happen because we did a select() first, but handle anyway. */
1246 /* This is an actual failure. */
1247 RETURN_FAIL("read() failed");
1250 bytes_read = result;
1253 if (bytes_read == 0)
1254 DEBUG("Read timed out");
1256 RETURN_INT(bytes_read);
1260 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1263 TRACE("%p, %p, %d", port, buf, count);
1268 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1270 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1276 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1277 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1278 port->timeouts.ReadTotalTimeoutConstant != 0) {
1279 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1280 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1281 port->timeouts.ReadTotalTimeoutConstant = 0;
1282 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1283 RETURN_FAIL("SetCommTimeouts() failed");
1287 if (ReadFile(port->hdl, buf, (DWORD) count, NULL, &port->read_ovl) == 0)
1288 if (GetLastError() != ERROR_IO_PENDING)
1289 RETURN_FAIL("ReadFile() failed");
1291 /* Get number of bytes read. */
1292 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1293 RETURN_FAIL("GetOverlappedResult() failed");
1295 TRY(restart_wait_if_needed(port, bytes_read));
1297 RETURN_INT(bytes_read);
1301 /* Returns the number of bytes read, or -1 upon failure. */
1302 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1303 if (errno == EAGAIN)
1304 /* No bytes available. */
1307 /* This is an actual failure. */
1308 RETURN_FAIL("read() failed");
1310 RETURN_INT(bytes_read);
1314 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1320 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1326 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1327 RETURN_FAIL("ClearCommError() failed");
1328 RETURN_INT(comstat.cbInQue);
1331 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1332 RETURN_FAIL("TIOCINQ ioctl failed");
1333 RETURN_INT(bytes_waiting);
1337 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1342 /* TIOCOUTQ is not defined in Cygwin headers */
1343 RETURN_ERROR(SP_ERR_SUPP,
1344 "Getting output bytes waiting is not supported on Cygwin");
1348 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1354 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1355 RETURN_FAIL("ClearCommError() failed");
1356 RETURN_INT(comstat.cbOutQue);
1359 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1360 RETURN_FAIL("TIOCOUTQ ioctl failed");
1361 RETURN_INT(bytes_waiting);
1366 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1368 struct sp_event_set *result;
1370 TRACE("%p", result_ptr);
1373 RETURN_ERROR(SP_ERR_ARG, "Null result");
1377 if (!(result = malloc(sizeof(struct sp_event_set))))
1378 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1380 memset(result, 0, sizeof(struct sp_event_set));
1382 *result_ptr = result;
1387 static enum sp_return add_handle(struct sp_event_set *event_set,
1388 event_handle handle, enum sp_event mask)
1391 enum sp_event *new_masks;
1393 TRACE("%p, %d, %d", event_set, handle, mask);
1395 if (!(new_handles = realloc(event_set->handles,
1396 sizeof(event_handle) * (event_set->count + 1))))
1397 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1399 event_set->handles = new_handles;
1401 if (!(new_masks = realloc(event_set->masks,
1402 sizeof(enum sp_event) * (event_set->count + 1))))
1403 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1405 event_set->masks = new_masks;
1407 ((event_handle *) event_set->handles)[event_set->count] = handle;
1408 event_set->masks[event_set->count] = mask;
1415 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1416 const struct sp_port *port, enum sp_event mask)
1418 TRACE("%p, %p, %d", event_set, port, mask);
1421 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1424 RETURN_ERROR(SP_ERR_ARG, "Null port");
1426 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1427 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1433 enum sp_event handle_mask;
1434 if ((handle_mask = mask & SP_EVENT_TX_READY))
1435 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1436 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1437 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1439 TRY(add_handle(event_set, port->fd, mask));
1445 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1447 TRACE("%p", event_set);
1450 DEBUG("Null event set");
1454 DEBUG("Freeing event set");
1456 if (event_set->handles)
1457 free(event_set->handles);
1458 if (event_set->masks)
1459 free(event_set->masks);
1466 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1467 unsigned int timeout_ms)
1469 TRACE("%p, %d", event_set, timeout_ms);
1472 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1475 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1476 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1477 RETURN_FAIL("WaitForMultipleObjects() failed");
1481 struct timeout timeout;
1484 struct pollfd *pollfds;
1487 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1488 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1490 for (i = 0; i < event_set->count; i++) {
1491 pollfds[i].fd = ((int *)event_set->handles)[i];
1492 pollfds[i].events = 0;
1493 pollfds[i].revents = 0;
1494 if (event_set->masks[i] & SP_EVENT_RX_READY)
1495 pollfds[i].events |= POLLIN;
1496 if (event_set->masks[i] & SP_EVENT_TX_READY)
1497 pollfds[i].events |= POLLOUT;
1498 if (event_set->masks[i] & SP_EVENT_ERROR)
1499 pollfds[i].events |= POLLERR;
1502 timeout_start(&timeout, timeout_ms);
1503 timeout_limit(&timeout, INT_MAX);
1505 /* Loop until an event occurs. */
1508 if (timeout_check(&timeout)) {
1509 DEBUG("Wait timed out");
1513 poll_timeout = (int) timeout_remaining_ms(&timeout);
1514 if (poll_timeout == 0)
1517 result = poll(pollfds, event_set->count, poll_timeout);
1519 timeout_update(&timeout);
1522 if (errno == EINTR) {
1523 DEBUG("poll() call was interrupted, repeating");
1527 RETURN_FAIL("poll() failed");
1529 } else if (result == 0) {
1530 DEBUG("poll() timed out");
1531 if (!timeout.overflow)
1534 DEBUG("poll() completed");
1544 #ifdef USE_TERMIOS_SPEED
1545 static enum sp_return get_baudrate(int fd, int *baudrate)
1549 TRACE("%d, %p", fd, baudrate);
1551 DEBUG("Getting baud rate");
1553 if (!(data = malloc(get_termios_size())))
1554 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1556 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1558 RETURN_FAIL("Getting termios failed");
1561 *baudrate = get_termios_speed(data);
1568 static enum sp_return set_baudrate(int fd, int baudrate)
1572 TRACE("%d, %d", fd, baudrate);
1574 DEBUG("Getting baud rate");
1576 if (!(data = malloc(get_termios_size())))
1577 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1579 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1581 RETURN_FAIL("Getting termios failed");
1584 DEBUG("Setting baud rate");
1586 set_termios_speed(data, baudrate);
1588 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1590 RETURN_FAIL("Setting termios failed");
1597 #endif /* USE_TERMIOS_SPEED */
1600 static enum sp_return get_flow(int fd, struct port_data *data)
1604 TRACE("%d, %p", fd, data);
1606 DEBUG("Getting advanced flow control");
1608 if (!(termx = malloc(get_termiox_size())))
1609 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1611 if (ioctl(fd, TCGETX, termx) < 0) {
1613 RETURN_FAIL("Getting termiox failed");
1616 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1617 &data->dtr_flow, &data->dsr_flow);
1624 static enum sp_return set_flow(int fd, struct port_data *data)
1628 TRACE("%d, %p", fd, data);
1630 DEBUG("Getting advanced flow control");
1632 if (!(termx = malloc(get_termiox_size())))
1633 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1635 if (ioctl(fd, TCGETX, termx) < 0) {
1637 RETURN_FAIL("Getting termiox failed");
1640 DEBUG("Setting advanced flow control");
1642 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1643 data->dtr_flow, data->dsr_flow);
1645 if (ioctl(fd, TCSETX, termx) < 0) {
1647 RETURN_FAIL("Setting termiox failed");
1654 #endif /* USE_TERMIOX */
1656 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1657 struct sp_port_config *config)
1661 TRACE("%p, %p, %p", port, data, config);
1663 DEBUG_FMT("Getting configuration for port %s", port->name);
1666 if (!GetCommState(port->hdl, &data->dcb))
1667 RETURN_FAIL("GetCommState() failed");
1669 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1670 if (data->dcb.BaudRate == std_baudrates[i].index) {
1671 config->baudrate = std_baudrates[i].value;
1676 if (i == NUM_STD_BAUDRATES)
1677 /* BaudRate field can be either an index or a custom baud rate. */
1678 config->baudrate = data->dcb.BaudRate;
1680 config->bits = data->dcb.ByteSize;
1682 switch (data->dcb.Parity) {
1684 config->parity = SP_PARITY_NONE;
1687 config->parity = SP_PARITY_ODD;
1690 config->parity = SP_PARITY_EVEN;
1693 config->parity = SP_PARITY_MARK;
1696 config->parity = SP_PARITY_SPACE;
1699 config->parity = -1;
1702 switch (data->dcb.StopBits) {
1704 config->stopbits = 1;
1707 config->stopbits = 2;
1710 config->stopbits = -1;
1713 switch (data->dcb.fRtsControl) {
1714 case RTS_CONTROL_DISABLE:
1715 config->rts = SP_RTS_OFF;
1717 case RTS_CONTROL_ENABLE:
1718 config->rts = SP_RTS_ON;
1720 case RTS_CONTROL_HANDSHAKE:
1721 config->rts = SP_RTS_FLOW_CONTROL;
1727 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1729 switch (data->dcb.fDtrControl) {
1730 case DTR_CONTROL_DISABLE:
1731 config->dtr = SP_DTR_OFF;
1733 case DTR_CONTROL_ENABLE:
1734 config->dtr = SP_DTR_ON;
1736 case DTR_CONTROL_HANDSHAKE:
1737 config->dtr = SP_DTR_FLOW_CONTROL;
1743 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1745 if (data->dcb.fInX) {
1746 if (data->dcb.fOutX)
1747 config->xon_xoff = SP_XONXOFF_INOUT;
1749 config->xon_xoff = SP_XONXOFF_IN;
1751 if (data->dcb.fOutX)
1752 config->xon_xoff = SP_XONXOFF_OUT;
1754 config->xon_xoff = SP_XONXOFF_DISABLED;
1759 if (tcgetattr(port->fd, &data->term) < 0)
1760 RETURN_FAIL("tcgetattr() failed");
1762 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1763 RETURN_FAIL("TIOCMGET ioctl failed");
1766 int ret = get_flow(port->fd, data);
1768 if (ret == SP_ERR_FAIL && errno == EINVAL)
1769 data->termiox_supported = 0;
1771 RETURN_CODEVAL(ret);
1773 data->termiox_supported = 1;
1775 data->termiox_supported = 0;
1778 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1779 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1780 config->baudrate = std_baudrates[i].value;
1785 if (i == NUM_STD_BAUDRATES) {
1787 config->baudrate = (int)data->term.c_ispeed;
1788 #elif defined(USE_TERMIOS_SPEED)
1789 TRY(get_baudrate(port->fd, &config->baudrate));
1791 config->baudrate = -1;
1795 switch (data->term.c_cflag & CSIZE) {
1812 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1813 config->parity = SP_PARITY_NONE;
1814 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1815 config->parity = -1;
1817 else if (data->term.c_cflag & CMSPAR)
1818 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1821 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1823 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1825 if (data->term.c_cflag & CRTSCTS) {
1826 config->rts = SP_RTS_FLOW_CONTROL;
1827 config->cts = SP_CTS_FLOW_CONTROL;
1829 if (data->termiox_supported && data->rts_flow)
1830 config->rts = SP_RTS_FLOW_CONTROL;
1832 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1834 config->cts = (data->termiox_supported && data->cts_flow) ?
1835 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1838 if (data->termiox_supported && data->dtr_flow)
1839 config->dtr = SP_DTR_FLOW_CONTROL;
1841 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1843 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1844 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1846 if (data->term.c_iflag & IXOFF) {
1847 if (data->term.c_iflag & IXON)
1848 config->xon_xoff = SP_XONXOFF_INOUT;
1850 config->xon_xoff = SP_XONXOFF_IN;
1852 if (data->term.c_iflag & IXON)
1853 config->xon_xoff = SP_XONXOFF_OUT;
1855 config->xon_xoff = SP_XONXOFF_DISABLED;
1862 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1863 const struct sp_port_config *config)
1867 BAUD_TYPE baud_nonstd;
1871 #ifdef USE_TERMIOS_SPEED
1872 int baud_nonstd = 0;
1875 TRACE("%p, %p, %p", port, data, config);
1877 DEBUG_FMT("Setting configuration for port %s", port->name);
1882 TRY(await_write_completion(port));
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;
1895 /* Allocate write buffer for 50ms of data at baud rate. */
1896 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1897 new_buf = realloc(port->write_buf, port->write_buf_size);
1899 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1900 port->write_buf = new_buf;
1903 if (config->bits >= 0)
1904 data->dcb.ByteSize = config->bits;
1906 if (config->parity >= 0) {
1907 switch (config->parity) {
1908 case SP_PARITY_NONE:
1909 data->dcb.Parity = NOPARITY;
1912 data->dcb.Parity = ODDPARITY;
1914 case SP_PARITY_EVEN:
1915 data->dcb.Parity = EVENPARITY;
1917 case SP_PARITY_MARK:
1918 data->dcb.Parity = MARKPARITY;
1920 case SP_PARITY_SPACE:
1921 data->dcb.Parity = SPACEPARITY;
1924 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1928 if (config->stopbits >= 0) {
1929 switch (config->stopbits) {
1930 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1932 data->dcb.StopBits = ONESTOPBIT;
1935 data->dcb.StopBits = TWOSTOPBITS;
1938 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1942 if (config->rts >= 0) {
1943 switch (config->rts) {
1945 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1948 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1950 case SP_RTS_FLOW_CONTROL:
1951 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1954 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1958 if (config->cts >= 0) {
1959 switch (config->cts) {
1961 data->dcb.fOutxCtsFlow = FALSE;
1963 case SP_CTS_FLOW_CONTROL:
1964 data->dcb.fOutxCtsFlow = TRUE;
1967 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1971 if (config->dtr >= 0) {
1972 switch (config->dtr) {
1974 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1977 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1979 case SP_DTR_FLOW_CONTROL:
1980 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1983 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1987 if (config->dsr >= 0) {
1988 switch (config->dsr) {
1990 data->dcb.fOutxDsrFlow = FALSE;
1992 case SP_DSR_FLOW_CONTROL:
1993 data->dcb.fOutxDsrFlow = TRUE;
1996 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2000 if (config->xon_xoff >= 0) {
2001 switch (config->xon_xoff) {
2002 case SP_XONXOFF_DISABLED:
2003 data->dcb.fInX = FALSE;
2004 data->dcb.fOutX = FALSE;
2007 data->dcb.fInX = TRUE;
2008 data->dcb.fOutX = FALSE;
2010 case SP_XONXOFF_OUT:
2011 data->dcb.fInX = FALSE;
2012 data->dcb.fOutX = TRUE;
2014 case SP_XONXOFF_INOUT:
2015 data->dcb.fInX = TRUE;
2016 data->dcb.fOutX = TRUE;
2019 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2023 if (!SetCommState(port->hdl, &data->dcb))
2024 RETURN_FAIL("SetCommState() failed");
2030 if (config->baudrate >= 0) {
2031 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2032 if (config->baudrate == std_baudrates[i].value) {
2033 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2034 RETURN_FAIL("cfsetospeed() failed");
2036 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2037 RETURN_FAIL("cfsetispeed() failed");
2042 /* Non-standard baud rate */
2043 if (i == NUM_STD_BAUDRATES) {
2045 /* Set "dummy" baud rate. */
2046 if (cfsetspeed(&data->term, B9600) < 0)
2047 RETURN_FAIL("cfsetspeed() failed");
2048 baud_nonstd = config->baudrate;
2049 #elif defined(USE_TERMIOS_SPEED)
2052 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2057 if (config->bits >= 0) {
2058 data->term.c_cflag &= ~CSIZE;
2059 switch (config->bits) {
2061 data->term.c_cflag |= CS8;
2064 data->term.c_cflag |= CS7;
2067 data->term.c_cflag |= CS6;
2070 data->term.c_cflag |= CS5;
2073 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2077 if (config->parity >= 0) {
2078 data->term.c_iflag &= ~IGNPAR;
2079 data->term.c_cflag &= ~(PARENB | PARODD);
2081 data->term.c_cflag &= ~CMSPAR;
2083 switch (config->parity) {
2084 case SP_PARITY_NONE:
2085 data->term.c_iflag |= IGNPAR;
2087 case SP_PARITY_EVEN:
2088 data->term.c_cflag |= PARENB;
2091 data->term.c_cflag |= PARENB | PARODD;
2094 case SP_PARITY_MARK:
2095 data->term.c_cflag |= PARENB | PARODD;
2096 data->term.c_cflag |= CMSPAR;
2098 case SP_PARITY_SPACE:
2099 data->term.c_cflag |= PARENB;
2100 data->term.c_cflag |= CMSPAR;
2103 case SP_PARITY_MARK:
2104 case SP_PARITY_SPACE:
2105 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2108 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2112 if (config->stopbits >= 0) {
2113 data->term.c_cflag &= ~CSTOPB;
2114 switch (config->stopbits) {
2116 data->term.c_cflag &= ~CSTOPB;
2119 data->term.c_cflag |= CSTOPB;
2122 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2126 if (config->rts >= 0 || config->cts >= 0) {
2127 if (data->termiox_supported) {
2128 data->rts_flow = data->cts_flow = 0;
2129 switch (config->rts) {
2132 controlbits = TIOCM_RTS;
2133 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2134 RETURN_FAIL("Setting RTS signal level failed");
2136 case SP_RTS_FLOW_CONTROL:
2142 if (config->cts == SP_CTS_FLOW_CONTROL)
2145 if (data->rts_flow && data->cts_flow)
2146 data->term.c_iflag |= CRTSCTS;
2148 data->term.c_iflag &= ~CRTSCTS;
2150 /* Asymmetric use of RTS/CTS not supported. */
2151 if (data->term.c_iflag & CRTSCTS) {
2152 /* Flow control can only be disabled for both RTS & CTS together. */
2153 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2154 if (config->cts != SP_CTS_IGNORE)
2155 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2157 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2158 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2159 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2162 /* Flow control can only be enabled for both RTS & CTS together. */
2163 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2164 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2165 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2168 if (config->rts >= 0) {
2169 if (config->rts == SP_RTS_FLOW_CONTROL) {
2170 data->term.c_iflag |= CRTSCTS;
2172 controlbits = TIOCM_RTS;
2173 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2175 RETURN_FAIL("Setting RTS signal level failed");
2181 if (config->dtr >= 0 || config->dsr >= 0) {
2182 if (data->termiox_supported) {
2183 data->dtr_flow = data->dsr_flow = 0;
2184 switch (config->dtr) {
2187 controlbits = TIOCM_DTR;
2188 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2189 RETURN_FAIL("Setting DTR signal level failed");
2191 case SP_DTR_FLOW_CONTROL:
2197 if (config->dsr == SP_DSR_FLOW_CONTROL)
2200 /* DTR/DSR flow control not supported. */
2201 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2202 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2204 if (config->dtr >= 0) {
2205 controlbits = TIOCM_DTR;
2206 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2208 RETURN_FAIL("Setting DTR signal level failed");
2213 if (config->xon_xoff >= 0) {
2214 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2215 switch (config->xon_xoff) {
2216 case SP_XONXOFF_DISABLED:
2219 data->term.c_iflag |= IXOFF;
2221 case SP_XONXOFF_OUT:
2222 data->term.c_iflag |= IXON | IXANY;
2224 case SP_XONXOFF_INOUT:
2225 data->term.c_iflag |= IXON | IXOFF | IXANY;
2228 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2232 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2233 RETURN_FAIL("tcsetattr() failed");
2236 if (baud_nonstd != B0) {
2237 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2238 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2240 * Set baud rates in data->term to correct, but incompatible
2241 * with tcsetattr() value, same as delivered by tcgetattr().
2243 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2244 RETURN_FAIL("cfsetspeed() failed");
2246 #elif defined(__linux__)
2247 #ifdef USE_TERMIOS_SPEED
2249 TRY(set_baudrate(port->fd, config->baudrate));
2252 if (data->termiox_supported)
2253 TRY(set_flow(port->fd, data));
2257 #endif /* !_WIN32 */
2262 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2264 struct sp_port_config *config;
2266 TRACE("%p", config_ptr);
2269 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2273 if (!(config = malloc(sizeof(struct sp_port_config))))
2274 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2276 config->baudrate = -1;
2278 config->parity = -1;
2279 config->stopbits = -1;
2285 *config_ptr = config;
2290 SP_API void sp_free_config(struct sp_port_config *config)
2292 TRACE("%p", config);
2295 DEBUG("Null config");
2302 SP_API enum sp_return sp_get_config(struct sp_port *port,
2303 struct sp_port_config *config)
2305 struct port_data data;
2307 TRACE("%p, %p", port, config);
2312 RETURN_ERROR(SP_ERR_ARG, "Null config");
2314 TRY(get_config(port, &data, config));
2319 SP_API enum sp_return sp_set_config(struct sp_port *port,
2320 const struct sp_port_config *config)
2322 struct port_data data;
2323 struct sp_port_config prev_config;
2325 TRACE("%p, %p", port, config);
2330 RETURN_ERROR(SP_ERR_ARG, "Null config");
2332 TRY(get_config(port, &data, &prev_config));
2333 TRY(set_config(port, &data, config));
2338 #define CREATE_ACCESSORS(x, type) \
2339 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2340 struct port_data data; \
2341 struct sp_port_config config; \
2342 TRACE("%p, %d", port, x); \
2343 CHECK_OPEN_PORT(); \
2344 TRY(get_config(port, &data, &config)); \
2346 TRY(set_config(port, &data, &config)); \
2349 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2351 TRACE("%p, %p", config, x); \
2353 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2355 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2359 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2361 TRACE("%p, %d", config, x); \
2363 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2368 CREATE_ACCESSORS(baudrate, int)
2369 CREATE_ACCESSORS(bits, int)
2370 CREATE_ACCESSORS(parity, enum sp_parity)
2371 CREATE_ACCESSORS(stopbits, int)
2372 CREATE_ACCESSORS(rts, enum sp_rts)
2373 CREATE_ACCESSORS(cts, enum sp_cts)
2374 CREATE_ACCESSORS(dtr, enum sp_dtr)
2375 CREATE_ACCESSORS(dsr, enum sp_dsr)
2376 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2378 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2379 enum sp_flowcontrol flowcontrol)
2382 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2384 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2385 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2387 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2388 config->xon_xoff = SP_XONXOFF_INOUT;
2390 config->xon_xoff = SP_XONXOFF_DISABLED;
2392 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2393 config->rts = SP_RTS_FLOW_CONTROL;
2394 config->cts = SP_CTS_FLOW_CONTROL;
2396 if (config->rts == SP_RTS_FLOW_CONTROL)
2397 config->rts = SP_RTS_ON;
2398 config->cts = SP_CTS_IGNORE;
2401 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2402 config->dtr = SP_DTR_FLOW_CONTROL;
2403 config->dsr = SP_DSR_FLOW_CONTROL;
2405 if (config->dtr == SP_DTR_FLOW_CONTROL)
2406 config->dtr = SP_DTR_ON;
2407 config->dsr = SP_DSR_IGNORE;
2413 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2414 enum sp_flowcontrol flowcontrol)
2416 struct port_data data;
2417 struct sp_port_config config;
2419 TRACE("%p, %d", port, flowcontrol);
2423 TRY(get_config(port, &data, &config));
2425 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2427 TRY(set_config(port, &data, &config));
2432 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2433 enum sp_signal *signals)
2435 TRACE("%p, %p", port, signals);
2440 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2442 DEBUG_FMT("Getting control signals for port %s", port->name);
2447 if (GetCommModemStatus(port->hdl, &bits) == 0)
2448 RETURN_FAIL("GetCommModemStatus() failed");
2449 if (bits & MS_CTS_ON)
2450 *signals |= SP_SIG_CTS;
2451 if (bits & MS_DSR_ON)
2452 *signals |= SP_SIG_DSR;
2453 if (bits & MS_RLSD_ON)
2454 *signals |= SP_SIG_DCD;
2455 if (bits & MS_RING_ON)
2456 *signals |= SP_SIG_RI;
2459 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2460 RETURN_FAIL("TIOCMGET ioctl failed");
2461 if (bits & TIOCM_CTS)
2462 *signals |= SP_SIG_CTS;
2463 if (bits & TIOCM_DSR)
2464 *signals |= SP_SIG_DSR;
2465 if (bits & TIOCM_CAR)
2466 *signals |= SP_SIG_DCD;
2467 if (bits & TIOCM_RNG)
2468 *signals |= SP_SIG_RI;
2473 SP_API enum sp_return sp_start_break(struct sp_port *port)
2479 if (SetCommBreak(port->hdl) == 0)
2480 RETURN_FAIL("SetCommBreak() failed");
2482 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2483 RETURN_FAIL("TIOCSBRK ioctl failed");
2489 SP_API enum sp_return sp_end_break(struct sp_port *port)
2495 if (ClearCommBreak(port->hdl) == 0)
2496 RETURN_FAIL("ClearCommBreak() failed");
2498 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2499 RETURN_FAIL("TIOCCBRK ioctl failed");
2505 SP_API int sp_last_error_code(void)
2509 RETURN_INT(GetLastError());
2515 SP_API char *sp_last_error_message(void)
2521 DWORD error = GetLastError();
2523 DWORD length = FormatMessageA(
2524 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2525 FORMAT_MESSAGE_FROM_SYSTEM |
2526 FORMAT_MESSAGE_IGNORE_INSERTS,
2529 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2533 if (length >= 2 && message[length - 2] == '\r')
2534 message[length - 2] = '\0';
2536 RETURN_STRING(message);
2538 RETURN_STRING(strerror(errno));
2542 SP_API void sp_free_error_message(char *message)
2544 TRACE("%s", message);
2555 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2557 TRACE("%p", handler);
2559 sp_debug_handler = handler;
2564 SP_API void sp_default_debug_handler(const char *format, ...)
2567 va_start(args, format);
2568 if (getenv("LIBSERIALPORT_DEBUG")) {
2569 fputs("sp: ", stderr);
2570 vfprintf(stderr, format, args);
2575 SP_API int sp_get_major_package_version(void)
2577 return SP_PACKAGE_VERSION_MAJOR;
2580 SP_API int sp_get_minor_package_version(void)
2582 return SP_PACKAGE_VERSION_MINOR;
2585 SP_API int sp_get_micro_package_version(void)
2587 return SP_PACKAGE_VERSION_MICRO;
2590 SP_API const char *sp_get_package_version_string(void)
2592 return SP_PACKAGE_VERSION_STRING;
2595 SP_API int sp_get_current_lib_version(void)
2597 return SP_LIB_VERSION_CURRENT;
2600 SP_API int sp_get_revision_lib_version(void)
2602 return SP_LIB_VERSION_REVISION;
2605 SP_API int sp_get_age_lib_version(void)
2607 return SP_LIB_VERSION_AGE;
2610 SP_API const char *sp_get_lib_version_string(void)
2612 return SP_LIB_VERSION_STRING;