2 * This file is part of the libserialport project.
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2013 Martin Ling <martin-libserialport@earth.li>
7 * Copyright (C) 2013 Matthias Heidbrink <m-sigrok@heidbrink.biz>
8 * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation, either version 3 of the
13 * License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "libserialport.h"
25 #include "libserialport_internal.h"
27 const struct std_baudrate std_baudrates[] = {
30 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
31 * have documented CBR_* macros.
33 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
34 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
35 BAUD(115200), BAUD(128000), BAUD(256000),
37 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
38 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
39 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
41 #if !defined(__APPLE__) && !defined(__OpenBSD__)
47 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
49 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
50 struct sp_port_config *config);
52 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
53 const struct sp_port_config *config);
55 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
61 TRACE("%s, %p", portname, port_ptr);
64 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
69 RETURN_ERROR(SP_ERR_ARG, "Null port name");
71 DEBUG("Building structure for port %s", portname);
73 if (!(port = malloc(sizeof(struct sp_port))))
74 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
76 len = strlen(portname) + 1;
78 if (!(port->name = malloc(len))) {
80 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
83 memcpy(port->name, portname, len);
86 port->hdl = INVALID_HANDLE_VALUE;
91 port->description = NULL;
92 port->transport = SP_TRANSPORT_NATIVE;
94 port->usb_address = -1;
97 port->usb_manufacturer = NULL;
98 port->usb_product = NULL;
99 port->usb_serial = NULL;
100 port->bluetooth_address = NULL;
102 #ifndef NO_PORT_METADATA
103 if ((ret = get_port_details(port)) != SP_OK) {
114 SP_API char *sp_get_port_name(const struct sp_port *port)
121 RETURN_VALUE("%s", port->name);
124 SP_API char *sp_get_port_description(struct sp_port *port)
128 if (!port || !port->description)
131 RETURN_VALUE("%s", port->description);
134 SP_API enum sp_transport sp_get_port_transport(struct sp_port *port)
139 RETURN_ERROR(SP_ERR_ARG, "Null port");
141 RETURN_VALUE("%d", port->transport);
144 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
145 int *usb_bus,int *usb_address)
150 RETURN_ERROR(SP_ERR_ARG, "Null port");
151 if (port->transport != SP_TRANSPORT_USB)
152 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
153 if (port->usb_bus < 0 || port->usb_address < 0)
154 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
156 if (usb_bus) *usb_bus = port->usb_bus;
157 if (usb_address) *usb_address = port->usb_address;
162 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
163 int *usb_vid, int *usb_pid)
168 RETURN_ERROR(SP_ERR_ARG, "Null port");
169 if (port->transport != SP_TRANSPORT_USB)
170 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
171 if (port->usb_vid < 0 || port->usb_pid < 0)
172 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
174 if (usb_vid) *usb_vid = port->usb_vid;
175 if (usb_pid) *usb_pid = port->usb_pid;
180 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
184 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
187 RETURN_VALUE("%s", port->usb_manufacturer);
190 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
194 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
197 RETURN_VALUE("%s", port->usb_product);
200 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
204 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
207 RETURN_VALUE("%s", port->usb_serial);
210 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
214 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
215 || !port->bluetooth_address)
218 RETURN_VALUE("%s", port->bluetooth_address);
221 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
224 TRACE("%p, %p", port, result_ptr);
227 RETURN_ERROR(SP_ERR_ARG, "Null port");
230 HANDLE *handle_ptr = result_ptr;
231 *handle_ptr = port->hdl;
233 int *fd_ptr = result_ptr;
240 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
241 struct sp_port **copy_ptr)
243 TRACE("%p, %p", port, copy_ptr);
246 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
251 RETURN_ERROR(SP_ERR_ARG, "Null port");
254 RETURN_ERROR(SP_ERR_ARG, "Null port name");
256 DEBUG("Copying port structure");
258 RETURN_VALUE("%p", sp_get_port_by_name(port->name, copy_ptr));
261 SP_API void sp_free_port(struct sp_port *port)
270 DEBUG("Freeing port structure");
274 if (port->description)
275 free(port->description);
276 if (port->usb_manufacturer)
277 free(port->usb_manufacturer);
278 if (port->usb_product)
279 free(port->usb_product);
280 if (port->usb_serial)
281 free(port->usb_serial);
282 if (port->bluetooth_address)
283 free(port->bluetooth_address);
286 free(port->usb_path);
294 SP_PRIV struct sp_port **list_append(struct sp_port **list,
295 const char *portname)
300 for (count = 0; list[count]; count++);
301 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
304 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
306 list[count + 1] = NULL;
310 sp_free_port_list(list);
314 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
316 struct sp_port **list;
319 TRACE("%p", list_ptr);
322 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
324 DEBUG("Enumerating ports");
326 if (!(list = malloc(sizeof(struct sp_port **))))
327 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
331 #ifdef NO_ENUMERATION
334 ret = list_ports(&list);
342 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
345 sp_free_port_list(list);
351 SP_API void sp_free_port_list(struct sp_port **list)
362 DEBUG("Freeing port list");
364 for (i = 0; list[i]; i++)
365 sp_free_port(list[i]);
371 #define CHECK_PORT() do { \
373 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
374 if (port->name == NULL) \
375 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
378 #define CHECK_PORT_HANDLE() do { \
379 if (port->hdl == INVALID_HANDLE_VALUE) \
380 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
383 #define CHECK_PORT_HANDLE() do { \
385 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
388 #define CHECK_OPEN_PORT() do { \
390 CHECK_PORT_HANDLE(); \
393 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
395 struct port_data data;
396 struct sp_port_config config;
399 TRACE("%p, 0x%x", port, flags);
403 if (flags > (SP_MODE_READ | SP_MODE_WRITE))
404 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
406 DEBUG("Opening port %s", port->name);
409 DWORD desired_access = 0, flags_and_attributes = 0, errors;
410 char *escaped_port_name;
413 /* Prefix port name with '\\.\' to work with ports above COM9. */
414 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
415 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
416 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
418 /* Map 'flags' to the OS-specific settings. */
419 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
420 if (flags & SP_MODE_READ)
421 desired_access |= GENERIC_READ;
422 if (flags & SP_MODE_WRITE)
423 desired_access |= GENERIC_WRITE;
425 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
426 OPEN_EXISTING, flags_and_attributes, 0);
428 free(escaped_port_name);
430 if (port->hdl == INVALID_HANDLE_VALUE)
431 RETURN_FAIL("port CreateFile() failed");
433 /* All timeouts initially disabled. */
434 port->timeouts.ReadIntervalTimeout = 0;
435 port->timeouts.ReadTotalTimeoutMultiplier = 0;
436 port->timeouts.ReadTotalTimeoutConstant = 0;
437 port->timeouts.WriteTotalTimeoutMultiplier = 0;
438 port->timeouts.WriteTotalTimeoutConstant = 0;
440 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
442 RETURN_FAIL("SetCommTimeouts() failed");
445 /* Prepare OVERLAPPED structures. */
446 #define INIT_OVERLAPPED(ovl) do { \
447 memset(&port->ovl, 0, sizeof(port->ovl)); \
448 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
449 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
450 == INVALID_HANDLE_VALUE) { \
452 RETURN_FAIL(#ovl "CreateEvent() failed"); \
456 INIT_OVERLAPPED(read_ovl);
457 INIT_OVERLAPPED(write_ovl);
458 INIT_OVERLAPPED(wait_ovl);
460 /* Set event mask for RX and error events. */
461 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
463 RETURN_FAIL("SetCommMask() failed");
466 /* Start background operation for RX and error events. */
467 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
468 if (GetLastError() != ERROR_IO_PENDING) {
470 RETURN_FAIL("WaitCommEvent() failed");
474 port->writing = FALSE;
477 int flags_local = O_NONBLOCK | O_NOCTTY;
479 /* Map 'flags' to the OS-specific settings. */
480 if (flags & (SP_MODE_READ | SP_MODE_WRITE))
481 flags_local |= O_RDWR;
482 else if (flags & SP_MODE_READ)
483 flags_local |= O_RDONLY;
484 else if (flags & SP_MODE_WRITE)
485 flags_local |= O_WRONLY;
487 if ((port->fd = open(port->name, flags_local)) < 0)
488 RETURN_FAIL("open() failed");
491 ret = get_config(port, &data, &config);
498 /* Set sane port settings. */
500 data.dcb.fBinary = TRUE;
501 data.dcb.fDsrSensitivity = FALSE;
502 data.dcb.fErrorChar = FALSE;
503 data.dcb.fNull = FALSE;
504 data.dcb.fAbortOnError = TRUE;
506 /* Turn off all fancy termios tricks, give us a raw channel. */
507 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
509 data.term.c_iflag &= ~IUCLC;
511 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
513 data.term.c_oflag &= ~OLCUC;
516 data.term.c_oflag &= ~NLDLY;
519 data.term.c_oflag &= ~CRDLY;
522 data.term.c_oflag &= ~TABDLY;
525 data.term.c_oflag &= ~BSDLY;
528 data.term.c_oflag &= ~VTDLY;
531 data.term.c_oflag &= ~FFDLY;
534 data.term.c_oflag &= ~OFILL;
536 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
537 data.term.c_cc[VMIN] = 0;
538 data.term.c_cc[VTIME] = 0;
540 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
541 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
545 if (ClearCommError(port->hdl, &errors, &status) == 0)
546 RETURN_FAIL("ClearCommError() failed");
549 ret = set_config(port, &data, &config);
559 SP_API enum sp_return sp_close(struct sp_port *port)
565 DEBUG("Closing port %s", port->name);
568 /* Returns non-zero upon success, 0 upon failure. */
569 if (CloseHandle(port->hdl) == 0)
570 RETURN_FAIL("port CloseHandle() failed");
571 port->hdl = INVALID_HANDLE_VALUE;
573 /* Close event handles for overlapped structures. */
574 #define CLOSE_OVERLAPPED(ovl) do { \
575 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
576 CloseHandle(port->ovl.hEvent) == 0) \
577 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
579 CLOSE_OVERLAPPED(read_ovl);
580 CLOSE_OVERLAPPED(write_ovl);
581 CLOSE_OVERLAPPED(wait_ovl);
584 /* Returns 0 upon success, -1 upon failure. */
585 if (close(port->fd) == -1)
586 RETURN_FAIL("close() failed");
593 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
595 TRACE("%p, 0x%x", port, buffers);
599 if (buffers > SP_BUF_BOTH)
600 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
602 const char *buffer_names[] = {"no", "input", "output", "both"};
604 DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
608 if (buffers & SP_BUF_INPUT)
609 flags |= PURGE_RXCLEAR;
610 if (buffers & SP_BUF_OUTPUT)
611 flags |= PURGE_TXCLEAR;
613 /* Returns non-zero upon success, 0 upon failure. */
614 if (PurgeComm(port->hdl, flags) == 0)
615 RETURN_FAIL("PurgeComm() failed");
618 if (buffers & SP_BUF_BOTH)
620 else if (buffers & SP_BUF_INPUT)
622 else if (buffers & SP_BUF_OUTPUT)
625 /* Returns 0 upon success, -1 upon failure. */
626 if (tcflush(port->fd, flags) < 0)
627 RETURN_FAIL("tcflush() failed");
632 SP_API enum sp_return sp_drain(struct sp_port *port)
638 DEBUG("Draining port %s", port->name);
641 /* Returns non-zero upon success, 0 upon failure. */
642 if (FlushFileBuffers(port->hdl) == 0)
643 RETURN_FAIL("FlushFileBuffers() failed");
650 result = ioctl(port->fd, TCSBRK, &arg);
652 result = tcdrain(port->fd);
655 if (errno == EINTR) {
656 DEBUG("tcdrain() was interrupted");
659 RETURN_FAIL("tcdrain() failed");
668 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
669 size_t count, unsigned int timeout)
671 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
676 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
679 DEBUG("Writing %d bytes to port %s, timeout %d ms", count, port->name, timeout);
681 DEBUG("Writing %d bytes to port %s, no timeout", count, port->name);
684 RETURN_VALUE("0", 0);
687 DWORD bytes_written = 0;
690 /* Wait for previous non-blocking write to complete, if any. */
692 DEBUG("Waiting for previous write to complete");
693 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
696 RETURN_FAIL("Previous write failed to complete");
697 DEBUG("Previous write completed");
701 port->timeouts.WriteTotalTimeoutConstant = timeout;
702 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
703 RETURN_FAIL("SetCommTimeouts() failed");
706 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) {
707 if (GetLastError() == ERROR_IO_PENDING) {
708 DEBUG("Waiting for write to complete");
709 GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
710 DEBUG("Write completed, %d/%d bytes written", bytes_written, count);
711 RETURN_VALUE("%d", bytes_written);
713 RETURN_FAIL("WriteFile() failed");
716 DEBUG("Write completed immediately");
717 RETURN_VALUE("%d", count);
720 size_t bytes_written = 0;
721 unsigned char *ptr = (unsigned char *) buf;
722 struct timeval start, delta, now, end = {0, 0};
727 /* Get time at start of operation. */
728 gettimeofday(&start, NULL);
729 /* Define duration of timeout. */
730 delta.tv_sec = timeout / 1000;
731 delta.tv_usec = (timeout % 1000) * 1000;
732 /* Calculate time at which we should give up. */
733 timeradd(&start, &delta, &end);
736 /* Loop until we have written the requested number of bytes. */
737 while (bytes_written < count)
739 /* Wait until space is available. */
741 FD_SET(port->fd, &fds);
743 gettimeofday(&now, NULL);
744 if (timercmp(&now, &end, >)) {
745 DEBUG("write timed out");
746 RETURN_VALUE("%d", bytes_written);
748 timersub(&end, &now, &delta);
750 result = select(port->fd + 1, NULL, &fds, NULL, timeout ? &delta : NULL);
752 if (errno == EINTR) {
753 DEBUG("select() call was interrupted, repeating");
756 RETURN_FAIL("select() failed");
758 } else if (result == 0) {
759 DEBUG("write timed out");
760 RETURN_VALUE("%d", bytes_written);
764 result = write(port->fd, ptr, count - bytes_written);
768 /* This shouldn't happen because we did a select() first, but handle anyway. */
771 /* This is an actual failure. */
772 RETURN_FAIL("write() failed");
775 bytes_written += result;
779 RETURN_VALUE("%d", bytes_written);
783 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
784 const void *buf, size_t count)
786 TRACE("%p, %p, %d", port, buf, count);
791 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
793 DEBUG("Writing up to %d bytes to port %s", count, port->name);
796 RETURN_VALUE("0", 0);
800 BYTE *ptr = (BYTE *) buf;
802 /* Check whether previous write is complete. */
804 if (HasOverlappedIoCompleted(&port->write_ovl)) {
805 DEBUG("Previous write completed");
808 DEBUG("Previous write not complete");
809 /* Can't take a new write until the previous one finishes. */
810 RETURN_VALUE("0", 0);
815 port->timeouts.WriteTotalTimeoutConstant = 0;
816 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
817 RETURN_FAIL("SetCommTimeouts() failed");
819 /* Keep writing data until the OS has to actually start an async IO for it.
820 * At that point we know the buffer is full. */
821 while (written < count)
823 /* Copy first byte of user buffer. */
824 port->pending_byte = *ptr++;
826 /* Start asynchronous write. */
827 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
828 if (GetLastError() == ERROR_IO_PENDING) {
829 if (HasOverlappedIoCompleted(&port->write_ovl)) {
830 DEBUG("Asynchronous write completed immediately");
835 DEBUG("Asynchronous write running");
837 RETURN_VALUE("%d", ++written);
840 /* Actual failure of some kind. */
841 RETURN_FAIL("WriteFile() failed");
844 DEBUG("Single byte written immediately");
849 DEBUG("All bytes written immediately");
851 RETURN_VALUE("%d", written);
853 /* Returns the number of bytes written, or -1 upon failure. */
854 ssize_t written = write(port->fd, buf, count);
857 RETURN_FAIL("write() failed");
859 RETURN_VALUE("%d", written);
863 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
864 size_t count, unsigned int timeout)
866 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
871 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
874 DEBUG("Reading %d bytes from port %s, timeout %d ms", count, port->name, timeout);
876 DEBUG("Reading %d bytes from port %s, no timeout", count, port->name);
879 RETURN_VALUE("0", 0);
882 DWORD bytes_read = 0;
885 port->timeouts.ReadIntervalTimeout = 0;
886 port->timeouts.ReadTotalTimeoutConstant = timeout;
887 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
888 RETURN_FAIL("SetCommTimeouts() failed");
891 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) {
892 if (GetLastError() == ERROR_IO_PENDING) {
893 DEBUG("Waiting for read to complete");
894 GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
895 DEBUG("Read completed, %d/%d bytes read", bytes_read, count);
897 RETURN_FAIL("ReadFile() failed");
900 DEBUG("Read completed immediately");
904 /* Start background operation for subsequent events. */
905 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
906 if (GetLastError() != ERROR_IO_PENDING)
907 RETURN_FAIL("WaitCommEvent() failed");
910 RETURN_VALUE("%d", bytes_read);
913 size_t bytes_read = 0;
914 unsigned char *ptr = (unsigned char *) buf;
915 struct timeval start, delta, now, end = {0, 0};
920 /* Get time at start of operation. */
921 gettimeofday(&start, NULL);
922 /* Define duration of timeout. */
923 delta.tv_sec = timeout / 1000;
924 delta.tv_usec = (timeout % 1000) * 1000;
925 /* Calculate time at which we should give up. */
926 timeradd(&start, &delta, &end);
929 /* Loop until we have the requested number of bytes. */
930 while (bytes_read < count)
932 /* Wait until data is available. */
934 FD_SET(port->fd, &fds);
936 gettimeofday(&now, NULL);
937 if (timercmp(&now, &end, >))
938 /* Timeout has expired. */
939 RETURN_VALUE("%d", bytes_read);
940 timersub(&end, &now, &delta);
942 result = select(port->fd + 1, &fds, NULL, NULL, timeout ? &delta : NULL);
944 if (errno == EINTR) {
945 DEBUG("select() call was interrupted, repeating");
948 RETURN_FAIL("select() failed");
950 } else if (result == 0) {
951 DEBUG("read timed out");
952 RETURN_VALUE("%d", bytes_read);
956 result = read(port->fd, ptr, count - bytes_read);
960 /* This shouldn't happen because we did a select() first, but handle anyway. */
963 /* This is an actual failure. */
964 RETURN_FAIL("read() failed");
967 bytes_read += result;
971 RETURN_VALUE("%d", bytes_read);
975 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
978 TRACE("%p, %p, %d", port, buf, count);
983 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
985 DEBUG("Reading up to %d bytes from port %s", count, port->name);
991 port->timeouts.ReadIntervalTimeout = MAXDWORD;
992 port->timeouts.ReadTotalTimeoutConstant = 0;
993 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
994 RETURN_FAIL("SetCommTimeouts() failed");
997 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
998 RETURN_FAIL("ReadFile() failed");
1000 /* Get number of bytes read. */
1001 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1002 RETURN_FAIL("GetOverlappedResult() failed");
1004 if (bytes_read > 0) {
1005 /* Start background operation for subsequent events. */
1006 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
1007 if (GetLastError() != ERROR_IO_PENDING)
1008 RETURN_FAIL("WaitCommEvent() failed");
1012 RETURN_VALUE("%d", bytes_read);
1016 /* Returns the number of bytes read, or -1 upon failure. */
1017 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1018 if (errno == EAGAIN)
1019 /* No bytes available. */
1022 /* This is an actual failure. */
1023 RETURN_FAIL("read() failed");
1025 RETURN_VALUE("%d", bytes_read);
1029 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1035 DEBUG("Checking input bytes waiting on port %s", port->name);
1041 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1042 RETURN_FAIL("ClearCommError() failed");
1043 RETURN_VALUE("%d", comstat.cbInQue);
1046 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1047 RETURN_FAIL("TIOCINQ ioctl failed");
1048 RETURN_VALUE("%d", bytes_waiting);
1052 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1058 DEBUG("Checking output bytes waiting on port %s", port->name);
1064 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1065 RETURN_FAIL("ClearCommError() failed");
1066 RETURN_VALUE("%d", comstat.cbOutQue);
1069 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1070 RETURN_FAIL("TIOCOUTQ ioctl failed");
1071 RETURN_VALUE("%d", bytes_waiting);
1075 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1077 struct sp_event_set *result;
1079 TRACE("%p", result_ptr);
1082 RETURN_ERROR(SP_ERR_ARG, "Null result");
1086 if (!(result = malloc(sizeof(struct sp_event_set))))
1087 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1089 memset(result, 0, sizeof(struct sp_event_set));
1091 *result_ptr = result;
1096 static enum sp_return add_handle(struct sp_event_set *event_set,
1097 event_handle handle, enum sp_event mask)
1100 enum sp_event *new_masks;
1102 TRACE("%p, %d, %d", event_set, handle, mask);
1104 if (!(new_handles = realloc(event_set->handles,
1105 sizeof(event_handle) * (event_set->count + 1))))
1106 RETURN_ERROR(SP_ERR_MEM, "handle array realloc() failed");
1108 if (!(new_masks = realloc(event_set->masks,
1109 sizeof(enum sp_event) * (event_set->count + 1))))
1110 RETURN_ERROR(SP_ERR_MEM, "mask array realloc() failed");
1112 event_set->handles = new_handles;
1113 event_set->masks = new_masks;
1115 ((event_handle *) event_set->handles)[event_set->count] = handle;
1116 event_set->masks[event_set->count] = mask;
1123 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1124 const struct sp_port *port, enum sp_event mask)
1126 TRACE("%p, %p, %d", event_set, port, mask);
1129 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1132 RETURN_ERROR(SP_ERR_ARG, "Null port");
1134 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1135 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1141 enum sp_event handle_mask;
1142 if ((handle_mask = mask & SP_EVENT_TX_READY))
1143 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1144 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1145 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1147 TRY(add_handle(event_set, port->fd, mask));
1153 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1155 TRACE("%p", event_set);
1158 DEBUG("Null event set");
1162 DEBUG("Freeing event set");
1164 if (event_set->handles)
1165 free(event_set->handles);
1166 if (event_set->masks)
1167 free(event_set->masks);
1174 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1175 unsigned int timeout)
1177 TRACE("%p, %d", event_set, timeout);
1180 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1183 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1184 timeout ? timeout : INFINITE) == WAIT_FAILED)
1185 RETURN_FAIL("WaitForMultipleObjects() failed");
1189 struct timeval start, delta, now, end = {0, 0};
1190 int result, timeout_remaining;
1191 struct pollfd *pollfds;
1194 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1195 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1197 for (i = 0; i < event_set->count; i++) {
1198 pollfds[i].fd = ((int *) event_set->handles)[i];
1199 pollfds[i].events = 0;
1200 pollfds[i].revents = 0;
1201 if (event_set->masks[i] & SP_EVENT_RX_READY)
1202 pollfds[i].events |= POLLIN;
1203 if (event_set->masks[i] & SP_EVENT_TX_READY)
1204 pollfds[i].events |= POLLOUT;
1205 if (event_set->masks[i] & SP_EVENT_ERROR)
1206 pollfds[i].events |= POLLERR;
1210 /* Get time at start of operation. */
1211 gettimeofday(&start, NULL);
1212 /* Define duration of timeout. */
1213 delta.tv_sec = timeout / 1000;
1214 delta.tv_usec = (timeout % 1000) * 1000;
1215 /* Calculate time at which we should give up. */
1216 timeradd(&start, &delta, &end);
1219 /* Loop until an event occurs. */
1223 gettimeofday(&now, NULL);
1224 if (timercmp(&now, &end, >)) {
1225 DEBUG("wait timed out");
1228 timersub(&end, &now, &delta);
1229 timeout_remaining = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1232 result = poll(pollfds, event_set->count, timeout ? timeout_remaining : -1);
1235 if (errno == EINTR) {
1236 DEBUG("poll() call was interrupted, repeating");
1240 RETURN_FAIL("poll() failed");
1242 } else if (result == 0) {
1243 DEBUG("poll() timed out");
1246 DEBUG("poll() completed");
1256 #ifdef USE_TERMIOS_SPEED
1257 static enum sp_return get_baudrate(int fd, int *baudrate)
1261 TRACE("%d, %p", fd, baudrate);
1263 DEBUG("Getting baud rate");
1265 if (!(data = malloc(get_termios_size())))
1266 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1268 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1270 RETURN_FAIL("getting termios failed");
1273 *baudrate = get_termios_speed(data);
1280 static enum sp_return set_baudrate(int fd, int baudrate)
1284 TRACE("%d, %d", fd, baudrate);
1286 DEBUG("Getting baud rate");
1288 if (!(data = malloc(get_termios_size())))
1289 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1291 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1293 RETURN_FAIL("getting termios failed");
1296 DEBUG("Setting baud rate");
1298 set_termios_speed(data, baudrate);
1300 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1302 RETURN_FAIL("setting termios failed");
1309 #endif /* USE_TERMIOS_SPEED */
1312 static enum sp_return get_flow(int fd, struct port_data *data)
1316 TRACE("%d, %p", fd, data);
1318 DEBUG("Getting advanced flow control");
1320 if (!(termx = malloc(get_termiox_size())))
1321 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1323 if (ioctl(fd, TCGETX, termx) < 0) {
1325 RETURN_FAIL("getting termiox failed");
1328 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1329 &data->dtr_flow, &data->dsr_flow);
1336 static enum sp_return set_flow(int fd, struct port_data *data)
1340 TRACE("%d, %p", fd, data);
1342 DEBUG("Getting advanced flow control");
1344 if (!(termx = malloc(get_termiox_size())))
1345 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1347 if (ioctl(fd, TCGETX, termx) < 0) {
1349 RETURN_FAIL("getting termiox failed");
1352 DEBUG("Setting advanced flow control");
1354 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1355 data->dtr_flow, data->dsr_flow);
1357 if (ioctl(fd, TCSETX, termx) < 0) {
1359 RETURN_FAIL("setting termiox failed");
1366 #endif /* USE_TERMIOX */
1368 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1369 struct sp_port_config *config)
1373 TRACE("%p, %p, %p", port, data, config);
1375 DEBUG("Getting configuration for port %s", port->name);
1378 if (!GetCommState(port->hdl, &data->dcb))
1379 RETURN_FAIL("GetCommState() failed");
1381 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1382 if (data->dcb.BaudRate == std_baudrates[i].index) {
1383 config->baudrate = std_baudrates[i].value;
1388 if (i == NUM_STD_BAUDRATES)
1389 /* BaudRate field can be either an index or a custom baud rate. */
1390 config->baudrate = data->dcb.BaudRate;
1392 config->bits = data->dcb.ByteSize;
1394 if (data->dcb.fParity)
1395 switch (data->dcb.Parity) {
1397 config->parity = SP_PARITY_NONE;
1400 config->parity = SP_PARITY_ODD;
1403 config->parity = SP_PARITY_EVEN;
1406 config->parity = SP_PARITY_MARK;
1409 config->parity = SP_PARITY_SPACE;
1412 config->parity = -1;
1415 config->parity = SP_PARITY_NONE;
1417 switch (data->dcb.StopBits) {
1419 config->stopbits = 1;
1422 config->stopbits = 2;
1425 config->stopbits = -1;
1428 switch (data->dcb.fRtsControl) {
1429 case RTS_CONTROL_DISABLE:
1430 config->rts = SP_RTS_OFF;
1432 case RTS_CONTROL_ENABLE:
1433 config->rts = SP_RTS_ON;
1435 case RTS_CONTROL_HANDSHAKE:
1436 config->rts = SP_RTS_FLOW_CONTROL;
1442 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1444 switch (data->dcb.fDtrControl) {
1445 case DTR_CONTROL_DISABLE:
1446 config->dtr = SP_DTR_OFF;
1448 case DTR_CONTROL_ENABLE:
1449 config->dtr = SP_DTR_ON;
1451 case DTR_CONTROL_HANDSHAKE:
1452 config->dtr = SP_DTR_FLOW_CONTROL;
1458 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1460 if (data->dcb.fInX) {
1461 if (data->dcb.fOutX)
1462 config->xon_xoff = SP_XONXOFF_INOUT;
1464 config->xon_xoff = SP_XONXOFF_IN;
1466 if (data->dcb.fOutX)
1467 config->xon_xoff = SP_XONXOFF_OUT;
1469 config->xon_xoff = SP_XONXOFF_DISABLED;
1474 if (tcgetattr(port->fd, &data->term) < 0)
1475 RETURN_FAIL("tcgetattr() failed");
1477 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1478 RETURN_FAIL("TIOCMGET ioctl failed");
1481 int ret = get_flow(port->fd, data);
1483 if (ret == SP_ERR_FAIL && errno == EINVAL)
1484 data->termiox_supported = 0;
1486 RETURN_CODEVAL(ret);
1488 data->termiox_supported = 1;
1490 data->termiox_supported = 0;
1493 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1494 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1495 config->baudrate = std_baudrates[i].value;
1500 if (i == NUM_STD_BAUDRATES) {
1502 config->baudrate = (int)data->term.c_ispeed;
1503 #elif defined(USE_TERMIOS_SPEED)
1504 TRY(get_baudrate(port->fd, &config->baudrate));
1506 config->baudrate = -1;
1510 switch (data->term.c_cflag & CSIZE) {
1527 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1528 config->parity = SP_PARITY_NONE;
1529 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1530 config->parity = -1;
1532 else if (data->term.c_cflag & CMSPAR)
1533 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1536 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1538 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1540 if (data->term.c_cflag & CRTSCTS) {
1541 config->rts = SP_RTS_FLOW_CONTROL;
1542 config->cts = SP_CTS_FLOW_CONTROL;
1544 if (data->termiox_supported && data->rts_flow)
1545 config->rts = SP_RTS_FLOW_CONTROL;
1547 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1549 config->cts = (data->termiox_supported && data->cts_flow) ?
1550 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1553 if (data->termiox_supported && data->dtr_flow)
1554 config->dtr = SP_DTR_FLOW_CONTROL;
1556 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1558 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1559 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1561 if (data->term.c_iflag & IXOFF) {
1562 if (data->term.c_iflag & IXON)
1563 config->xon_xoff = SP_XONXOFF_INOUT;
1565 config->xon_xoff = SP_XONXOFF_IN;
1567 if (data->term.c_iflag & IXON)
1568 config->xon_xoff = SP_XONXOFF_OUT;
1570 config->xon_xoff = SP_XONXOFF_DISABLED;
1577 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1578 const struct sp_port_config *config)
1582 BAUD_TYPE baud_nonstd;
1586 #ifdef USE_TERMIOS_SPEED
1587 int baud_nonstd = 0;
1590 TRACE("%p, %p, %p", port, data, config);
1592 DEBUG("Setting configuration for port %s", port->name);
1595 if (config->baudrate >= 0) {
1596 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1597 if (config->baudrate == std_baudrates[i].value) {
1598 data->dcb.BaudRate = std_baudrates[i].index;
1603 if (i == NUM_STD_BAUDRATES)
1604 data->dcb.BaudRate = config->baudrate;
1607 if (config->bits >= 0)
1608 data->dcb.ByteSize = config->bits;
1610 if (config->parity >= 0) {
1611 switch (config->parity) {
1612 case SP_PARITY_NONE:
1613 data->dcb.Parity = NOPARITY;
1616 data->dcb.Parity = ODDPARITY;
1618 case SP_PARITY_EVEN:
1619 data->dcb.Parity = EVENPARITY;
1621 case SP_PARITY_MARK:
1622 data->dcb.Parity = MARKPARITY;
1624 case SP_PARITY_SPACE:
1625 data->dcb.Parity = SPACEPARITY;
1628 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1632 if (config->stopbits >= 0) {
1633 switch (config->stopbits) {
1634 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1636 data->dcb.StopBits = ONESTOPBIT;
1639 data->dcb.StopBits = TWOSTOPBITS;
1642 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1646 if (config->rts >= 0) {
1647 switch (config->rts) {
1649 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1652 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1654 case SP_RTS_FLOW_CONTROL:
1655 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1658 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1662 if (config->cts >= 0) {
1663 switch (config->cts) {
1665 data->dcb.fOutxCtsFlow = FALSE;
1667 case SP_CTS_FLOW_CONTROL:
1668 data->dcb.fOutxCtsFlow = TRUE;
1671 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1675 if (config->dtr >= 0) {
1676 switch (config->dtr) {
1678 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1681 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1683 case SP_DTR_FLOW_CONTROL:
1684 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1687 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1691 if (config->dsr >= 0) {
1692 switch (config->dsr) {
1694 data->dcb.fOutxDsrFlow = FALSE;
1696 case SP_DSR_FLOW_CONTROL:
1697 data->dcb.fOutxDsrFlow = TRUE;
1700 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1704 if (config->xon_xoff >= 0) {
1705 switch (config->xon_xoff) {
1706 case SP_XONXOFF_DISABLED:
1707 data->dcb.fInX = FALSE;
1708 data->dcb.fOutX = FALSE;
1711 data->dcb.fInX = TRUE;
1712 data->dcb.fOutX = FALSE;
1714 case SP_XONXOFF_OUT:
1715 data->dcb.fInX = FALSE;
1716 data->dcb.fOutX = TRUE;
1718 case SP_XONXOFF_INOUT:
1719 data->dcb.fInX = TRUE;
1720 data->dcb.fOutX = TRUE;
1723 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1727 if (!SetCommState(port->hdl, &data->dcb))
1728 RETURN_FAIL("SetCommState() failed");
1734 if (config->baudrate >= 0) {
1735 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1736 if (config->baudrate == std_baudrates[i].value) {
1737 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1738 RETURN_FAIL("cfsetospeed() failed");
1740 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1741 RETURN_FAIL("cfsetispeed() failed");
1746 /* Non-standard baud rate */
1747 if (i == NUM_STD_BAUDRATES) {
1749 /* Set "dummy" baud rate. */
1750 if (cfsetspeed(&data->term, B9600) < 0)
1751 RETURN_FAIL("cfsetspeed() failed");
1752 baud_nonstd = config->baudrate;
1753 #elif defined(USE_TERMIOS_SPEED)
1756 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1761 if (config->bits >= 0) {
1762 data->term.c_cflag &= ~CSIZE;
1763 switch (config->bits) {
1765 data->term.c_cflag |= CS8;
1768 data->term.c_cflag |= CS7;
1771 data->term.c_cflag |= CS6;
1774 data->term.c_cflag |= CS5;
1777 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1781 if (config->parity >= 0) {
1782 data->term.c_iflag &= ~IGNPAR;
1783 data->term.c_cflag &= ~(PARENB | PARODD);
1785 data->term.c_cflag &= ~CMSPAR;
1787 switch (config->parity) {
1788 case SP_PARITY_NONE:
1789 data->term.c_iflag |= IGNPAR;
1791 case SP_PARITY_EVEN:
1792 data->term.c_cflag |= PARENB;
1795 data->term.c_cflag |= PARENB | PARODD;
1798 case SP_PARITY_MARK:
1799 data->term.c_cflag |= PARENB | PARODD;
1800 data->term.c_cflag |= CMSPAR;
1802 case SP_PARITY_SPACE:
1803 data->term.c_cflag |= PARENB;
1804 data->term.c_cflag |= CMSPAR;
1807 case SP_PARITY_MARK:
1808 case SP_PARITY_SPACE:
1809 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1812 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1816 if (config->stopbits >= 0) {
1817 data->term.c_cflag &= ~CSTOPB;
1818 switch (config->stopbits) {
1820 data->term.c_cflag &= ~CSTOPB;
1823 data->term.c_cflag |= CSTOPB;
1826 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1830 if (config->rts >= 0 || config->cts >= 0) {
1831 if (data->termiox_supported) {
1832 data->rts_flow = data->cts_flow = 0;
1833 switch (config->rts) {
1836 controlbits = TIOCM_RTS;
1837 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1838 RETURN_FAIL("Setting RTS signal level failed");
1840 case SP_RTS_FLOW_CONTROL:
1846 if (config->cts == SP_CTS_FLOW_CONTROL)
1849 if (data->rts_flow && data->cts_flow)
1850 data->term.c_iflag |= CRTSCTS;
1852 data->term.c_iflag &= ~CRTSCTS;
1854 /* Asymmetric use of RTS/CTS not supported. */
1855 if (data->term.c_iflag & CRTSCTS) {
1856 /* Flow control can only be disabled for both RTS & CTS together. */
1857 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1858 if (config->cts != SP_CTS_IGNORE)
1859 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1861 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1862 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1863 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1866 /* Flow control can only be enabled for both RTS & CTS together. */
1867 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1868 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1869 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1872 if (config->rts >= 0) {
1873 if (config->rts == SP_RTS_FLOW_CONTROL) {
1874 data->term.c_iflag |= CRTSCTS;
1876 controlbits = TIOCM_RTS;
1877 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1879 RETURN_FAIL("Setting RTS signal level failed");
1885 if (config->dtr >= 0 || config->dsr >= 0) {
1886 if (data->termiox_supported) {
1887 data->dtr_flow = data->dsr_flow = 0;
1888 switch (config->dtr) {
1891 controlbits = TIOCM_DTR;
1892 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1893 RETURN_FAIL("Setting DTR signal level failed");
1895 case SP_DTR_FLOW_CONTROL:
1901 if (config->dsr == SP_DSR_FLOW_CONTROL)
1904 /* DTR/DSR flow control not supported. */
1905 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1906 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1908 if (config->dtr >= 0) {
1909 controlbits = TIOCM_DTR;
1910 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1912 RETURN_FAIL("Setting DTR signal level failed");
1917 if (config->xon_xoff >= 0) {
1918 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1919 switch (config->xon_xoff) {
1920 case SP_XONXOFF_DISABLED:
1923 data->term.c_iflag |= IXOFF;
1925 case SP_XONXOFF_OUT:
1926 data->term.c_iflag |= IXON | IXANY;
1928 case SP_XONXOFF_INOUT:
1929 data->term.c_iflag |= IXON | IXOFF | IXANY;
1932 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1936 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
1937 RETURN_FAIL("tcsetattr() failed");
1940 if (baud_nonstd != B0) {
1941 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1942 RETURN_FAIL("IOSSIOSPEED ioctl failed");
1943 /* Set baud rates in data->term to correct, but incompatible
1944 * with tcsetattr() value, same as delivered by tcgetattr(). */
1945 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1946 RETURN_FAIL("cfsetspeed() failed");
1948 #elif defined(__linux__)
1949 #ifdef USE_TERMIOS_SPEED
1951 TRY(set_baudrate(port->fd, config->baudrate));
1954 if (data->termiox_supported)
1955 TRY(set_flow(port->fd, data));
1959 #endif /* !_WIN32 */
1964 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
1966 struct sp_port_config *config;
1968 TRACE("%p", config_ptr);
1971 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1975 if (!(config = malloc(sizeof(struct sp_port_config))))
1976 RETURN_ERROR(SP_ERR_MEM, "config malloc failed");
1978 config->baudrate = -1;
1980 config->parity = -1;
1981 config->stopbits = -1;
1987 *config_ptr = config;
1992 SP_API void sp_free_config(struct sp_port_config *config)
1994 TRACE("%p", config);
1997 DEBUG("Null config");
2004 SP_API enum sp_return sp_get_config(struct sp_port *port,
2005 struct sp_port_config *config)
2007 struct port_data data;
2009 TRACE("%p, %p", port, config);
2014 RETURN_ERROR(SP_ERR_ARG, "Null config");
2016 TRY(get_config(port, &data, config));
2021 SP_API enum sp_return sp_set_config(struct sp_port *port,
2022 const struct sp_port_config *config)
2024 struct port_data data;
2025 struct sp_port_config prev_config;
2027 TRACE("%p, %p", port, config);
2032 RETURN_ERROR(SP_ERR_ARG, "Null config");
2034 TRY(get_config(port, &data, &prev_config));
2035 TRY(set_config(port, &data, config));
2040 #define CREATE_ACCESSORS(x, type) \
2041 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2042 struct port_data data; \
2043 struct sp_port_config config; \
2044 TRACE("%p, %d", port, x); \
2045 CHECK_OPEN_PORT(); \
2046 TRY(get_config(port, &data, &config)); \
2048 TRY(set_config(port, &data, &config)); \
2051 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2053 TRACE("%p, %p", config, x); \
2055 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2059 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2061 TRACE("%p, %d", config, x); \
2063 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2068 CREATE_ACCESSORS(baudrate, int)
2069 CREATE_ACCESSORS(bits, int)
2070 CREATE_ACCESSORS(parity, enum sp_parity)
2071 CREATE_ACCESSORS(stopbits, int)
2072 CREATE_ACCESSORS(rts, enum sp_rts)
2073 CREATE_ACCESSORS(cts, enum sp_cts)
2074 CREATE_ACCESSORS(dtr, enum sp_dtr)
2075 CREATE_ACCESSORS(dsr, enum sp_dsr)
2076 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2078 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2079 enum sp_flowcontrol flowcontrol)
2082 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2084 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2085 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2087 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2088 config->xon_xoff = SP_XONXOFF_INOUT;
2090 config->xon_xoff = SP_XONXOFF_DISABLED;
2092 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2093 config->rts = SP_RTS_FLOW_CONTROL;
2094 config->cts = SP_CTS_FLOW_CONTROL;
2096 if (config->rts == SP_RTS_FLOW_CONTROL)
2097 config->rts = SP_RTS_ON;
2098 config->cts = SP_CTS_IGNORE;
2101 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2102 config->dtr = SP_DTR_FLOW_CONTROL;
2103 config->dsr = SP_DSR_FLOW_CONTROL;
2105 if (config->dtr == SP_DTR_FLOW_CONTROL)
2106 config->dtr = SP_DTR_ON;
2107 config->dsr = SP_DSR_IGNORE;
2113 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2114 enum sp_flowcontrol flowcontrol)
2116 struct port_data data;
2117 struct sp_port_config config;
2119 TRACE("%p, %d", port, flowcontrol);
2123 TRY(get_config(port, &data, &config));
2125 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2127 TRY(set_config(port, &data, &config));
2132 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2133 enum sp_signal *signals)
2135 TRACE("%p, %p", port, signals);
2140 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2142 DEBUG("Getting control signals for port %s", port->name);
2147 if (GetCommModemStatus(port->hdl, &bits) == 0)
2148 RETURN_FAIL("GetCommModemStatus() failed");
2149 if (bits & MS_CTS_ON)
2150 *signals |= SP_SIG_CTS;
2151 if (bits & MS_DSR_ON)
2152 *signals |= SP_SIG_DSR;
2153 if (bits & MS_RLSD_ON)
2154 *signals |= SP_SIG_DCD;
2155 if (bits & MS_RING_ON)
2156 *signals |= SP_SIG_RI;
2159 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2160 RETURN_FAIL("TIOCMGET ioctl failed");
2161 if (bits & TIOCM_CTS)
2162 *signals |= SP_SIG_CTS;
2163 if (bits & TIOCM_DSR)
2164 *signals |= SP_SIG_DSR;
2165 if (bits & TIOCM_CAR)
2166 *signals |= SP_SIG_DCD;
2167 if (bits & TIOCM_RNG)
2168 *signals |= SP_SIG_RI;
2173 SP_API enum sp_return sp_start_break(struct sp_port *port)
2179 if (SetCommBreak(port->hdl) == 0)
2180 RETURN_FAIL("SetCommBreak() failed");
2182 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2183 RETURN_FAIL("TIOCSBRK ioctl failed");
2189 SP_API enum sp_return sp_end_break(struct sp_port *port)
2195 if (ClearCommBreak(port->hdl) == 0)
2196 RETURN_FAIL("ClearCommBreak() failed");
2198 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2199 RETURN_FAIL("TIOCCBRK ioctl failed");
2205 SP_API int sp_last_error_code(void)
2209 RETURN_VALUE("%d", GetLastError());
2211 RETURN_VALUE("%d", errno);
2215 SP_API char *sp_last_error_message(void)
2221 DWORD error = GetLastError();
2224 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2225 FORMAT_MESSAGE_FROM_SYSTEM |
2226 FORMAT_MESSAGE_IGNORE_INSERTS,
2229 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2233 RETURN_VALUE("%s", message);
2235 RETURN_VALUE("%s", strerror(errno));
2239 SP_API void sp_free_error_message(char *message)
2241 TRACE("%s", message);
2252 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2254 TRACE("%p", handler);
2256 sp_debug_handler = handler;
2261 SP_API void sp_default_debug_handler(const char *format, ...)
2264 va_start(args, format);
2265 if (getenv("LIBSERIALPORT_DEBUG")) {
2266 fputs("sp: ", stderr);
2267 vfprintf(stderr, format, args);
2272 SP_API int sp_get_major_package_version(void)
2274 return SP_PACKAGE_VERSION_MAJOR;
2277 SP_API int sp_get_minor_package_version(void)
2279 return SP_PACKAGE_VERSION_MINOR;
2282 SP_API int sp_get_micro_package_version(void)
2284 return SP_PACKAGE_VERSION_MICRO;
2287 SP_API const char *sp_get_package_version_string(void)
2289 return SP_PACKAGE_VERSION_STRING;
2292 SP_API int sp_get_current_lib_version(void)
2294 return SP_LIB_VERSION_CURRENT;
2297 SP_API int sp_get_revision_lib_version(void)
2299 return SP_LIB_VERSION_REVISION;
2302 SP_API int sp_get_age_lib_version(void)
2304 return SP_LIB_VERSION_AGE;
2307 SP_API const char *sp_get_lib_version_string(void)
2309 return SP_LIB_VERSION_STRING;