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)
58 #ifndef NO_PORT_METADATA
63 TRACE("%s, %p", portname, port_ptr);
66 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
71 RETURN_ERROR(SP_ERR_ARG, "Null port name");
73 DEBUG("Building structure for port %s", portname);
75 if (!(port = malloc(sizeof(struct sp_port))))
76 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
78 len = strlen(portname) + 1;
80 if (!(port->name = malloc(len))) {
82 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
85 memcpy(port->name, portname, len);
88 port->hdl = INVALID_HANDLE_VALUE;
93 port->description = NULL;
94 port->transport = SP_TRANSPORT_NATIVE;
96 port->usb_address = -1;
99 port->usb_manufacturer = NULL;
100 port->usb_product = NULL;
101 port->usb_serial = NULL;
102 port->bluetooth_address = NULL;
104 #ifndef NO_PORT_METADATA
105 if ((ret = get_port_details(port)) != SP_OK) {
116 SP_API char *sp_get_port_name(const struct sp_port *port)
123 RETURN_STRING(port->name);
126 SP_API char *sp_get_port_description(struct sp_port *port)
130 if (!port || !port->description)
133 RETURN_STRING(port->description);
136 SP_API enum sp_transport sp_get_port_transport(struct sp_port *port)
141 RETURN_ERROR(SP_ERR_ARG, "Null port");
143 RETURN_INT(port->transport);
146 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
147 int *usb_bus,int *usb_address)
152 RETURN_ERROR(SP_ERR_ARG, "Null port");
153 if (port->transport != SP_TRANSPORT_USB)
154 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
155 if (port->usb_bus < 0 || port->usb_address < 0)
156 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
158 if (usb_bus) *usb_bus = port->usb_bus;
159 if (usb_address) *usb_address = port->usb_address;
164 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
165 int *usb_vid, int *usb_pid)
170 RETURN_ERROR(SP_ERR_ARG, "Null port");
171 if (port->transport != SP_TRANSPORT_USB)
172 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
173 if (port->usb_vid < 0 || port->usb_pid < 0)
174 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
176 if (usb_vid) *usb_vid = port->usb_vid;
177 if (usb_pid) *usb_pid = port->usb_pid;
182 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
186 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
189 RETURN_STRING(port->usb_manufacturer);
192 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
196 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
199 RETURN_STRING(port->usb_product);
202 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
206 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
209 RETURN_STRING(port->usb_serial);
212 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
216 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
217 || !port->bluetooth_address)
220 RETURN_STRING(port->bluetooth_address);
223 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
226 TRACE("%p, %p", port, result_ptr);
229 RETURN_ERROR(SP_ERR_ARG, "Null port");
232 HANDLE *handle_ptr = result_ptr;
233 *handle_ptr = port->hdl;
235 int *fd_ptr = result_ptr;
242 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
243 struct sp_port **copy_ptr)
245 TRACE("%p, %p", port, copy_ptr);
248 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
253 RETURN_ERROR(SP_ERR_ARG, "Null port");
256 RETURN_ERROR(SP_ERR_ARG, "Null port name");
258 DEBUG("Copying port structure");
260 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
263 SP_API void sp_free_port(struct sp_port *port)
272 DEBUG("Freeing port structure");
276 if (port->description)
277 free(port->description);
278 if (port->usb_manufacturer)
279 free(port->usb_manufacturer);
280 if (port->usb_product)
281 free(port->usb_product);
282 if (port->usb_serial)
283 free(port->usb_serial);
284 if (port->bluetooth_address)
285 free(port->bluetooth_address);
288 free(port->usb_path);
296 SP_PRIV struct sp_port **list_append(struct sp_port **list,
297 const char *portname)
302 for (count = 0; list[count]; count++);
303 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
306 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
308 list[count + 1] = NULL;
312 sp_free_port_list(list);
316 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
318 struct sp_port **list;
321 TRACE("%p", list_ptr);
324 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
326 DEBUG("Enumerating ports");
328 if (!(list = malloc(sizeof(struct sp_port **))))
329 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
333 #ifdef NO_ENUMERATION
336 ret = list_ports(&list);
344 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
347 sp_free_port_list(list);
353 SP_API void sp_free_port_list(struct sp_port **list)
364 DEBUG("Freeing port list");
366 for (i = 0; list[i]; i++)
367 sp_free_port(list[i]);
373 #define CHECK_PORT() do { \
375 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
376 if (port->name == NULL) \
377 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
380 #define CHECK_PORT_HANDLE() do { \
381 if (port->hdl == INVALID_HANDLE_VALUE) \
382 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
385 #define CHECK_PORT_HANDLE() do { \
387 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
390 #define CHECK_OPEN_PORT() do { \
392 CHECK_PORT_HANDLE(); \
395 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
397 struct port_data data;
398 struct sp_port_config config;
401 TRACE("%p, 0x%x", port, flags);
405 if (flags > (SP_MODE_READ | SP_MODE_WRITE))
406 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
408 DEBUG("Opening port %s", port->name);
411 DWORD desired_access = 0, flags_and_attributes = 0, errors;
412 char *escaped_port_name;
415 /* Prefix port name with '\\.\' to work with ports above COM9. */
416 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
417 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
418 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
420 /* Map 'flags' to the OS-specific settings. */
421 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
422 if (flags & SP_MODE_READ)
423 desired_access |= GENERIC_READ;
424 if (flags & SP_MODE_WRITE)
425 desired_access |= GENERIC_WRITE;
427 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
428 OPEN_EXISTING, flags_and_attributes, 0);
430 free(escaped_port_name);
432 if (port->hdl == INVALID_HANDLE_VALUE)
433 RETURN_FAIL("port CreateFile() failed");
435 /* All timeouts initially disabled. */
436 port->timeouts.ReadIntervalTimeout = 0;
437 port->timeouts.ReadTotalTimeoutMultiplier = 0;
438 port->timeouts.ReadTotalTimeoutConstant = 0;
439 port->timeouts.WriteTotalTimeoutMultiplier = 0;
440 port->timeouts.WriteTotalTimeoutConstant = 0;
442 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
444 RETURN_FAIL("SetCommTimeouts() failed");
447 /* Prepare OVERLAPPED structures. */
448 #define INIT_OVERLAPPED(ovl) do { \
449 memset(&port->ovl, 0, sizeof(port->ovl)); \
450 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
451 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
452 == INVALID_HANDLE_VALUE) { \
454 RETURN_FAIL(#ovl "CreateEvent() failed"); \
458 INIT_OVERLAPPED(read_ovl);
459 INIT_OVERLAPPED(write_ovl);
460 INIT_OVERLAPPED(wait_ovl);
462 /* Set event mask for RX and error events. */
463 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
465 RETURN_FAIL("SetCommMask() failed");
468 /* Start background operation for RX and error events. */
469 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
470 if (GetLastError() != ERROR_IO_PENDING) {
472 RETURN_FAIL("WaitCommEvent() failed");
476 port->writing = FALSE;
479 int flags_local = O_NONBLOCK | O_NOCTTY;
481 /* Map 'flags' to the OS-specific settings. */
482 if (flags & (SP_MODE_READ | SP_MODE_WRITE))
483 flags_local |= O_RDWR;
484 else if (flags & SP_MODE_READ)
485 flags_local |= O_RDONLY;
486 else if (flags & SP_MODE_WRITE)
487 flags_local |= O_WRONLY;
489 if ((port->fd = open(port->name, flags_local)) < 0)
490 RETURN_FAIL("open() failed");
493 ret = get_config(port, &data, &config);
500 /* Set sane port settings. */
502 data.dcb.fBinary = TRUE;
503 data.dcb.fDsrSensitivity = FALSE;
504 data.dcb.fErrorChar = FALSE;
505 data.dcb.fNull = FALSE;
506 data.dcb.fAbortOnError = TRUE;
508 /* Turn off all fancy termios tricks, give us a raw channel. */
509 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
511 data.term.c_iflag &= ~IUCLC;
513 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
515 data.term.c_oflag &= ~OLCUC;
518 data.term.c_oflag &= ~NLDLY;
521 data.term.c_oflag &= ~CRDLY;
524 data.term.c_oflag &= ~TABDLY;
527 data.term.c_oflag &= ~BSDLY;
530 data.term.c_oflag &= ~VTDLY;
533 data.term.c_oflag &= ~FFDLY;
536 data.term.c_oflag &= ~OFILL;
538 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
539 data.term.c_cc[VMIN] = 0;
540 data.term.c_cc[VTIME] = 0;
542 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
543 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
547 if (ClearCommError(port->hdl, &errors, &status) == 0)
548 RETURN_FAIL("ClearCommError() failed");
551 ret = set_config(port, &data, &config);
561 SP_API enum sp_return sp_close(struct sp_port *port)
567 DEBUG("Closing port %s", port->name);
570 /* Returns non-zero upon success, 0 upon failure. */
571 if (CloseHandle(port->hdl) == 0)
572 RETURN_FAIL("port CloseHandle() failed");
573 port->hdl = INVALID_HANDLE_VALUE;
575 /* Close event handles for overlapped structures. */
576 #define CLOSE_OVERLAPPED(ovl) do { \
577 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
578 CloseHandle(port->ovl.hEvent) == 0) \
579 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
581 CLOSE_OVERLAPPED(read_ovl);
582 CLOSE_OVERLAPPED(write_ovl);
583 CLOSE_OVERLAPPED(wait_ovl);
586 /* Returns 0 upon success, -1 upon failure. */
587 if (close(port->fd) == -1)
588 RETURN_FAIL("close() failed");
595 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
597 TRACE("%p, 0x%x", port, buffers);
601 if (buffers > SP_BUF_BOTH)
602 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
604 const char *buffer_names[] = {"no", "input", "output", "both"};
606 DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
610 if (buffers & SP_BUF_INPUT)
611 flags |= PURGE_RXCLEAR;
612 if (buffers & SP_BUF_OUTPUT)
613 flags |= PURGE_TXCLEAR;
615 /* Returns non-zero upon success, 0 upon failure. */
616 if (PurgeComm(port->hdl, flags) == 0)
617 RETURN_FAIL("PurgeComm() failed");
620 if (buffers & SP_BUF_BOTH)
622 else if (buffers & SP_BUF_INPUT)
624 else if (buffers & SP_BUF_OUTPUT)
627 /* Returns 0 upon success, -1 upon failure. */
628 if (tcflush(port->fd, flags) < 0)
629 RETURN_FAIL("tcflush() failed");
634 SP_API enum sp_return sp_drain(struct sp_port *port)
640 DEBUG("Draining port %s", port->name);
643 /* Returns non-zero upon success, 0 upon failure. */
644 if (FlushFileBuffers(port->hdl) == 0)
645 RETURN_FAIL("FlushFileBuffers() failed");
652 result = ioctl(port->fd, TCSBRK, &arg);
654 result = tcdrain(port->fd);
657 if (errno == EINTR) {
658 DEBUG("tcdrain() was interrupted");
661 RETURN_FAIL("tcdrain() failed");
670 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
671 size_t count, unsigned int timeout)
673 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
678 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
681 DEBUG("Writing %d bytes to port %s, timeout %d ms", count, port->name, timeout);
683 DEBUG("Writing %d bytes to port %s, no timeout", count, port->name);
689 DWORD bytes_written = 0;
692 /* Wait for previous non-blocking write to complete, if any. */
694 DEBUG("Waiting for previous write to complete");
695 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
698 RETURN_FAIL("Previous write failed to complete");
699 DEBUG("Previous write completed");
703 port->timeouts.WriteTotalTimeoutConstant = timeout;
704 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
705 RETURN_FAIL("SetCommTimeouts() failed");
708 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) {
709 if (GetLastError() == ERROR_IO_PENDING) {
710 DEBUG("Waiting for write to complete");
711 GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
712 DEBUG("Write completed, %d/%d bytes written", bytes_written, count);
713 RETURN_INT(bytes_written);
715 RETURN_FAIL("WriteFile() failed");
718 DEBUG("Write completed immediately");
722 size_t bytes_written = 0;
723 unsigned char *ptr = (unsigned char *) buf;
724 struct timeval start, delta, now, end = {0, 0};
729 /* Get time at start of operation. */
730 gettimeofday(&start, NULL);
731 /* Define duration of timeout. */
732 delta.tv_sec = timeout / 1000;
733 delta.tv_usec = (timeout % 1000) * 1000;
734 /* Calculate time at which we should give up. */
735 timeradd(&start, &delta, &end);
738 /* Loop until we have written the requested number of bytes. */
739 while (bytes_written < count)
741 /* Wait until space is available. */
743 FD_SET(port->fd, &fds);
745 gettimeofday(&now, NULL);
746 if (timercmp(&now, &end, >)) {
747 DEBUG("write timed out");
748 RETURN_INT(bytes_written);
750 timersub(&end, &now, &delta);
752 result = select(port->fd + 1, NULL, &fds, NULL, timeout ? &delta : NULL);
754 if (errno == EINTR) {
755 DEBUG("select() call was interrupted, repeating");
758 RETURN_FAIL("select() failed");
760 } else if (result == 0) {
761 DEBUG("write timed out");
762 RETURN_INT(bytes_written);
766 result = write(port->fd, ptr, count - bytes_written);
770 /* This shouldn't happen because we did a select() first, but handle anyway. */
773 /* This is an actual failure. */
774 RETURN_FAIL("write() failed");
777 bytes_written += result;
781 RETURN_INT(bytes_written);
785 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
786 const void *buf, size_t count)
788 TRACE("%p, %p, %d", port, buf, count);
793 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
795 DEBUG("Writing up to %d bytes to port %s", count, port->name);
802 BYTE *ptr = (BYTE *) buf;
804 /* Check whether previous write is complete. */
806 if (HasOverlappedIoCompleted(&port->write_ovl)) {
807 DEBUG("Previous write completed");
810 DEBUG("Previous write not complete");
811 /* Can't take a new write until the previous one finishes. */
817 port->timeouts.WriteTotalTimeoutConstant = 0;
818 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
819 RETURN_FAIL("SetCommTimeouts() failed");
821 /* Keep writing data until the OS has to actually start an async IO for it.
822 * At that point we know the buffer is full. */
823 while (written < count)
825 /* Copy first byte of user buffer. */
826 port->pending_byte = *ptr++;
828 /* Start asynchronous write. */
829 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
830 if (GetLastError() == ERROR_IO_PENDING) {
831 if (HasOverlappedIoCompleted(&port->write_ovl)) {
832 DEBUG("Asynchronous write completed immediately");
837 DEBUG("Asynchronous write running");
839 RETURN_INT(++written);
842 /* Actual failure of some kind. */
843 RETURN_FAIL("WriteFile() failed");
846 DEBUG("Single byte written immediately");
851 DEBUG("All bytes written immediately");
855 /* Returns the number of bytes written, or -1 upon failure. */
856 ssize_t written = write(port->fd, buf, count);
859 RETURN_FAIL("write() failed");
865 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
866 size_t count, unsigned int timeout)
868 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
873 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
876 DEBUG("Reading %d bytes from port %s, timeout %d ms", count, port->name, timeout);
878 DEBUG("Reading %d bytes from port %s, no timeout", count, port->name);
884 DWORD bytes_read = 0;
887 port->timeouts.ReadIntervalTimeout = 0;
888 port->timeouts.ReadTotalTimeoutConstant = timeout;
889 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
890 RETURN_FAIL("SetCommTimeouts() failed");
893 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) {
894 if (GetLastError() == ERROR_IO_PENDING) {
895 DEBUG("Waiting for read to complete");
896 GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
897 DEBUG("Read completed, %d/%d bytes read", bytes_read, count);
899 RETURN_FAIL("ReadFile() failed");
902 DEBUG("Read completed immediately");
906 /* Start background operation for subsequent events. */
907 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
908 if (GetLastError() != ERROR_IO_PENDING)
909 RETURN_FAIL("WaitCommEvent() failed");
912 RETURN_INT(bytes_read);
915 size_t bytes_read = 0;
916 unsigned char *ptr = (unsigned char *) buf;
917 struct timeval start, delta, now, end = {0, 0};
922 /* Get time at start of operation. */
923 gettimeofday(&start, NULL);
924 /* Define duration of timeout. */
925 delta.tv_sec = timeout / 1000;
926 delta.tv_usec = (timeout % 1000) * 1000;
927 /* Calculate time at which we should give up. */
928 timeradd(&start, &delta, &end);
931 /* Loop until we have the requested number of bytes. */
932 while (bytes_read < count)
934 /* Wait until data is available. */
936 FD_SET(port->fd, &fds);
938 gettimeofday(&now, NULL);
939 if (timercmp(&now, &end, >))
940 /* Timeout has expired. */
941 RETURN_INT(bytes_read);
942 timersub(&end, &now, &delta);
944 result = select(port->fd + 1, &fds, NULL, NULL, timeout ? &delta : NULL);
946 if (errno == EINTR) {
947 DEBUG("select() call was interrupted, repeating");
950 RETURN_FAIL("select() failed");
952 } else if (result == 0) {
953 DEBUG("read timed out");
954 RETURN_INT(bytes_read);
958 result = read(port->fd, ptr, count - bytes_read);
962 /* This shouldn't happen because we did a select() first, but handle anyway. */
965 /* This is an actual failure. */
966 RETURN_FAIL("read() failed");
969 bytes_read += result;
973 RETURN_INT(bytes_read);
977 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
980 TRACE("%p, %p, %d", port, buf, count);
985 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
987 DEBUG("Reading up to %d bytes from port %s", count, port->name);
993 port->timeouts.ReadIntervalTimeout = MAXDWORD;
994 port->timeouts.ReadTotalTimeoutConstant = 0;
995 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
996 RETURN_FAIL("SetCommTimeouts() failed");
999 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1000 RETURN_FAIL("ReadFile() failed");
1002 /* Get number of bytes read. */
1003 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1004 RETURN_FAIL("GetOverlappedResult() failed");
1006 if (bytes_read > 0) {
1007 /* Start background operation for subsequent events. */
1008 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
1009 if (GetLastError() != ERROR_IO_PENDING)
1010 RETURN_FAIL("WaitCommEvent() failed");
1014 RETURN_INT(bytes_read);
1018 /* Returns the number of bytes read, or -1 upon failure. */
1019 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1020 if (errno == EAGAIN)
1021 /* No bytes available. */
1024 /* This is an actual failure. */
1025 RETURN_FAIL("read() failed");
1027 RETURN_INT(bytes_read);
1031 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1037 DEBUG("Checking input bytes waiting on port %s", port->name);
1043 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1044 RETURN_FAIL("ClearCommError() failed");
1045 RETURN_INT(comstat.cbInQue);
1048 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1049 RETURN_FAIL("TIOCINQ ioctl failed");
1050 RETURN_INT(bytes_waiting);
1054 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1060 DEBUG("Checking output bytes waiting on port %s", port->name);
1066 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1067 RETURN_FAIL("ClearCommError() failed");
1068 RETURN_INT(comstat.cbOutQue);
1071 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1072 RETURN_FAIL("TIOCOUTQ ioctl failed");
1073 RETURN_INT(bytes_waiting);
1077 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1079 struct sp_event_set *result;
1081 TRACE("%p", result_ptr);
1084 RETURN_ERROR(SP_ERR_ARG, "Null result");
1088 if (!(result = malloc(sizeof(struct sp_event_set))))
1089 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1091 memset(result, 0, sizeof(struct sp_event_set));
1093 *result_ptr = result;
1098 static enum sp_return add_handle(struct sp_event_set *event_set,
1099 event_handle handle, enum sp_event mask)
1102 enum sp_event *new_masks;
1104 TRACE("%p, %d, %d", event_set, handle, mask);
1106 if (!(new_handles = realloc(event_set->handles,
1107 sizeof(event_handle) * (event_set->count + 1))))
1108 RETURN_ERROR(SP_ERR_MEM, "handle array realloc() failed");
1110 if (!(new_masks = realloc(event_set->masks,
1111 sizeof(enum sp_event) * (event_set->count + 1))))
1112 RETURN_ERROR(SP_ERR_MEM, "mask array realloc() failed");
1114 event_set->handles = new_handles;
1115 event_set->masks = new_masks;
1117 ((event_handle *) event_set->handles)[event_set->count] = handle;
1118 event_set->masks[event_set->count] = mask;
1125 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1126 const struct sp_port *port, enum sp_event mask)
1128 TRACE("%p, %p, %d", event_set, port, mask);
1131 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1134 RETURN_ERROR(SP_ERR_ARG, "Null port");
1136 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1137 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1143 enum sp_event handle_mask;
1144 if ((handle_mask = mask & SP_EVENT_TX_READY))
1145 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1146 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1147 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1149 TRY(add_handle(event_set, port->fd, mask));
1155 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1157 TRACE("%p", event_set);
1160 DEBUG("Null event set");
1164 DEBUG("Freeing event set");
1166 if (event_set->handles)
1167 free(event_set->handles);
1168 if (event_set->masks)
1169 free(event_set->masks);
1176 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1177 unsigned int timeout)
1179 TRACE("%p, %d", event_set, timeout);
1182 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1185 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1186 timeout ? timeout : INFINITE) == WAIT_FAILED)
1187 RETURN_FAIL("WaitForMultipleObjects() failed");
1191 struct timeval start, delta, now, end = {0, 0};
1192 int result, timeout_remaining;
1193 struct pollfd *pollfds;
1196 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1197 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1199 for (i = 0; i < event_set->count; i++) {
1200 pollfds[i].fd = ((int *) event_set->handles)[i];
1201 pollfds[i].events = 0;
1202 pollfds[i].revents = 0;
1203 if (event_set->masks[i] & SP_EVENT_RX_READY)
1204 pollfds[i].events |= POLLIN;
1205 if (event_set->masks[i] & SP_EVENT_TX_READY)
1206 pollfds[i].events |= POLLOUT;
1207 if (event_set->masks[i] & SP_EVENT_ERROR)
1208 pollfds[i].events |= POLLERR;
1212 /* Get time at start of operation. */
1213 gettimeofday(&start, NULL);
1214 /* Define duration of timeout. */
1215 delta.tv_sec = timeout / 1000;
1216 delta.tv_usec = (timeout % 1000) * 1000;
1217 /* Calculate time at which we should give up. */
1218 timeradd(&start, &delta, &end);
1221 /* Loop until an event occurs. */
1225 gettimeofday(&now, NULL);
1226 if (timercmp(&now, &end, >)) {
1227 DEBUG("wait timed out");
1230 timersub(&end, &now, &delta);
1231 timeout_remaining = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1234 result = poll(pollfds, event_set->count, timeout ? timeout_remaining : -1);
1237 if (errno == EINTR) {
1238 DEBUG("poll() call was interrupted, repeating");
1242 RETURN_FAIL("poll() failed");
1244 } else if (result == 0) {
1245 DEBUG("poll() timed out");
1248 DEBUG("poll() completed");
1258 #ifdef USE_TERMIOS_SPEED
1259 static enum sp_return get_baudrate(int fd, int *baudrate)
1263 TRACE("%d, %p", fd, baudrate);
1265 DEBUG("Getting baud rate");
1267 if (!(data = malloc(get_termios_size())))
1268 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1270 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1272 RETURN_FAIL("getting termios failed");
1275 *baudrate = get_termios_speed(data);
1282 static enum sp_return set_baudrate(int fd, int baudrate)
1286 TRACE("%d, %d", fd, baudrate);
1288 DEBUG("Getting baud rate");
1290 if (!(data = malloc(get_termios_size())))
1291 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1293 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1295 RETURN_FAIL("getting termios failed");
1298 DEBUG("Setting baud rate");
1300 set_termios_speed(data, baudrate);
1302 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1304 RETURN_FAIL("setting termios failed");
1311 #endif /* USE_TERMIOS_SPEED */
1314 static enum sp_return get_flow(int fd, struct port_data *data)
1318 TRACE("%d, %p", fd, data);
1320 DEBUG("Getting advanced flow control");
1322 if (!(termx = malloc(get_termiox_size())))
1323 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1325 if (ioctl(fd, TCGETX, termx) < 0) {
1327 RETURN_FAIL("getting termiox failed");
1330 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1331 &data->dtr_flow, &data->dsr_flow);
1338 static enum sp_return set_flow(int fd, struct port_data *data)
1342 TRACE("%d, %p", fd, data);
1344 DEBUG("Getting advanced flow control");
1346 if (!(termx = malloc(get_termiox_size())))
1347 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1349 if (ioctl(fd, TCGETX, termx) < 0) {
1351 RETURN_FAIL("getting termiox failed");
1354 DEBUG("Setting advanced flow control");
1356 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1357 data->dtr_flow, data->dsr_flow);
1359 if (ioctl(fd, TCSETX, termx) < 0) {
1361 RETURN_FAIL("setting termiox failed");
1368 #endif /* USE_TERMIOX */
1370 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1371 struct sp_port_config *config)
1375 TRACE("%p, %p, %p", port, data, config);
1377 DEBUG("Getting configuration for port %s", port->name);
1380 if (!GetCommState(port->hdl, &data->dcb))
1381 RETURN_FAIL("GetCommState() failed");
1383 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1384 if (data->dcb.BaudRate == std_baudrates[i].index) {
1385 config->baudrate = std_baudrates[i].value;
1390 if (i == NUM_STD_BAUDRATES)
1391 /* BaudRate field can be either an index or a custom baud rate. */
1392 config->baudrate = data->dcb.BaudRate;
1394 config->bits = data->dcb.ByteSize;
1396 if (data->dcb.fParity)
1397 switch (data->dcb.Parity) {
1399 config->parity = SP_PARITY_NONE;
1402 config->parity = SP_PARITY_ODD;
1405 config->parity = SP_PARITY_EVEN;
1408 config->parity = SP_PARITY_MARK;
1411 config->parity = SP_PARITY_SPACE;
1414 config->parity = -1;
1417 config->parity = SP_PARITY_NONE;
1419 switch (data->dcb.StopBits) {
1421 config->stopbits = 1;
1424 config->stopbits = 2;
1427 config->stopbits = -1;
1430 switch (data->dcb.fRtsControl) {
1431 case RTS_CONTROL_DISABLE:
1432 config->rts = SP_RTS_OFF;
1434 case RTS_CONTROL_ENABLE:
1435 config->rts = SP_RTS_ON;
1437 case RTS_CONTROL_HANDSHAKE:
1438 config->rts = SP_RTS_FLOW_CONTROL;
1444 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1446 switch (data->dcb.fDtrControl) {
1447 case DTR_CONTROL_DISABLE:
1448 config->dtr = SP_DTR_OFF;
1450 case DTR_CONTROL_ENABLE:
1451 config->dtr = SP_DTR_ON;
1453 case DTR_CONTROL_HANDSHAKE:
1454 config->dtr = SP_DTR_FLOW_CONTROL;
1460 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1462 if (data->dcb.fInX) {
1463 if (data->dcb.fOutX)
1464 config->xon_xoff = SP_XONXOFF_INOUT;
1466 config->xon_xoff = SP_XONXOFF_IN;
1468 if (data->dcb.fOutX)
1469 config->xon_xoff = SP_XONXOFF_OUT;
1471 config->xon_xoff = SP_XONXOFF_DISABLED;
1476 if (tcgetattr(port->fd, &data->term) < 0)
1477 RETURN_FAIL("tcgetattr() failed");
1479 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1480 RETURN_FAIL("TIOCMGET ioctl failed");
1483 int ret = get_flow(port->fd, data);
1485 if (ret == SP_ERR_FAIL && errno == EINVAL)
1486 data->termiox_supported = 0;
1488 RETURN_CODEVAL(ret);
1490 data->termiox_supported = 1;
1492 data->termiox_supported = 0;
1495 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1496 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1497 config->baudrate = std_baudrates[i].value;
1502 if (i == NUM_STD_BAUDRATES) {
1504 config->baudrate = (int)data->term.c_ispeed;
1505 #elif defined(USE_TERMIOS_SPEED)
1506 TRY(get_baudrate(port->fd, &config->baudrate));
1508 config->baudrate = -1;
1512 switch (data->term.c_cflag & CSIZE) {
1529 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1530 config->parity = SP_PARITY_NONE;
1531 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1532 config->parity = -1;
1534 else if (data->term.c_cflag & CMSPAR)
1535 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1538 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1540 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1542 if (data->term.c_cflag & CRTSCTS) {
1543 config->rts = SP_RTS_FLOW_CONTROL;
1544 config->cts = SP_CTS_FLOW_CONTROL;
1546 if (data->termiox_supported && data->rts_flow)
1547 config->rts = SP_RTS_FLOW_CONTROL;
1549 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1551 config->cts = (data->termiox_supported && data->cts_flow) ?
1552 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1555 if (data->termiox_supported && data->dtr_flow)
1556 config->dtr = SP_DTR_FLOW_CONTROL;
1558 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1560 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1561 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1563 if (data->term.c_iflag & IXOFF) {
1564 if (data->term.c_iflag & IXON)
1565 config->xon_xoff = SP_XONXOFF_INOUT;
1567 config->xon_xoff = SP_XONXOFF_IN;
1569 if (data->term.c_iflag & IXON)
1570 config->xon_xoff = SP_XONXOFF_OUT;
1572 config->xon_xoff = SP_XONXOFF_DISABLED;
1579 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1580 const struct sp_port_config *config)
1584 BAUD_TYPE baud_nonstd;
1588 #ifdef USE_TERMIOS_SPEED
1589 int baud_nonstd = 0;
1592 TRACE("%p, %p, %p", port, data, config);
1594 DEBUG("Setting configuration for port %s", port->name);
1597 if (config->baudrate >= 0) {
1598 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1599 if (config->baudrate == std_baudrates[i].value) {
1600 data->dcb.BaudRate = std_baudrates[i].index;
1605 if (i == NUM_STD_BAUDRATES)
1606 data->dcb.BaudRate = config->baudrate;
1609 if (config->bits >= 0)
1610 data->dcb.ByteSize = config->bits;
1612 if (config->parity >= 0) {
1613 switch (config->parity) {
1614 case SP_PARITY_NONE:
1615 data->dcb.Parity = NOPARITY;
1618 data->dcb.Parity = ODDPARITY;
1620 case SP_PARITY_EVEN:
1621 data->dcb.Parity = EVENPARITY;
1623 case SP_PARITY_MARK:
1624 data->dcb.Parity = MARKPARITY;
1626 case SP_PARITY_SPACE:
1627 data->dcb.Parity = SPACEPARITY;
1630 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1634 if (config->stopbits >= 0) {
1635 switch (config->stopbits) {
1636 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1638 data->dcb.StopBits = ONESTOPBIT;
1641 data->dcb.StopBits = TWOSTOPBITS;
1644 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1648 if (config->rts >= 0) {
1649 switch (config->rts) {
1651 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1654 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1656 case SP_RTS_FLOW_CONTROL:
1657 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1660 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1664 if (config->cts >= 0) {
1665 switch (config->cts) {
1667 data->dcb.fOutxCtsFlow = FALSE;
1669 case SP_CTS_FLOW_CONTROL:
1670 data->dcb.fOutxCtsFlow = TRUE;
1673 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1677 if (config->dtr >= 0) {
1678 switch (config->dtr) {
1680 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1683 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1685 case SP_DTR_FLOW_CONTROL:
1686 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1689 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1693 if (config->dsr >= 0) {
1694 switch (config->dsr) {
1696 data->dcb.fOutxDsrFlow = FALSE;
1698 case SP_DSR_FLOW_CONTROL:
1699 data->dcb.fOutxDsrFlow = TRUE;
1702 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1706 if (config->xon_xoff >= 0) {
1707 switch (config->xon_xoff) {
1708 case SP_XONXOFF_DISABLED:
1709 data->dcb.fInX = FALSE;
1710 data->dcb.fOutX = FALSE;
1713 data->dcb.fInX = TRUE;
1714 data->dcb.fOutX = FALSE;
1716 case SP_XONXOFF_OUT:
1717 data->dcb.fInX = FALSE;
1718 data->dcb.fOutX = TRUE;
1720 case SP_XONXOFF_INOUT:
1721 data->dcb.fInX = TRUE;
1722 data->dcb.fOutX = TRUE;
1725 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1729 if (!SetCommState(port->hdl, &data->dcb))
1730 RETURN_FAIL("SetCommState() failed");
1736 if (config->baudrate >= 0) {
1737 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1738 if (config->baudrate == std_baudrates[i].value) {
1739 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1740 RETURN_FAIL("cfsetospeed() failed");
1742 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1743 RETURN_FAIL("cfsetispeed() failed");
1748 /* Non-standard baud rate */
1749 if (i == NUM_STD_BAUDRATES) {
1751 /* Set "dummy" baud rate. */
1752 if (cfsetspeed(&data->term, B9600) < 0)
1753 RETURN_FAIL("cfsetspeed() failed");
1754 baud_nonstd = config->baudrate;
1755 #elif defined(USE_TERMIOS_SPEED)
1758 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1763 if (config->bits >= 0) {
1764 data->term.c_cflag &= ~CSIZE;
1765 switch (config->bits) {
1767 data->term.c_cflag |= CS8;
1770 data->term.c_cflag |= CS7;
1773 data->term.c_cflag |= CS6;
1776 data->term.c_cflag |= CS5;
1779 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1783 if (config->parity >= 0) {
1784 data->term.c_iflag &= ~IGNPAR;
1785 data->term.c_cflag &= ~(PARENB | PARODD);
1787 data->term.c_cflag &= ~CMSPAR;
1789 switch (config->parity) {
1790 case SP_PARITY_NONE:
1791 data->term.c_iflag |= IGNPAR;
1793 case SP_PARITY_EVEN:
1794 data->term.c_cflag |= PARENB;
1797 data->term.c_cflag |= PARENB | PARODD;
1800 case SP_PARITY_MARK:
1801 data->term.c_cflag |= PARENB | PARODD;
1802 data->term.c_cflag |= CMSPAR;
1804 case SP_PARITY_SPACE:
1805 data->term.c_cflag |= PARENB;
1806 data->term.c_cflag |= CMSPAR;
1809 case SP_PARITY_MARK:
1810 case SP_PARITY_SPACE:
1811 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1814 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1818 if (config->stopbits >= 0) {
1819 data->term.c_cflag &= ~CSTOPB;
1820 switch (config->stopbits) {
1822 data->term.c_cflag &= ~CSTOPB;
1825 data->term.c_cflag |= CSTOPB;
1828 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1832 if (config->rts >= 0 || config->cts >= 0) {
1833 if (data->termiox_supported) {
1834 data->rts_flow = data->cts_flow = 0;
1835 switch (config->rts) {
1838 controlbits = TIOCM_RTS;
1839 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1840 RETURN_FAIL("Setting RTS signal level failed");
1842 case SP_RTS_FLOW_CONTROL:
1848 if (config->cts == SP_CTS_FLOW_CONTROL)
1851 if (data->rts_flow && data->cts_flow)
1852 data->term.c_iflag |= CRTSCTS;
1854 data->term.c_iflag &= ~CRTSCTS;
1856 /* Asymmetric use of RTS/CTS not supported. */
1857 if (data->term.c_iflag & CRTSCTS) {
1858 /* Flow control can only be disabled for both RTS & CTS together. */
1859 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1860 if (config->cts != SP_CTS_IGNORE)
1861 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1863 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1864 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1865 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1868 /* Flow control can only be enabled for both RTS & CTS together. */
1869 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1870 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1871 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1874 if (config->rts >= 0) {
1875 if (config->rts == SP_RTS_FLOW_CONTROL) {
1876 data->term.c_iflag |= CRTSCTS;
1878 controlbits = TIOCM_RTS;
1879 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1881 RETURN_FAIL("Setting RTS signal level failed");
1887 if (config->dtr >= 0 || config->dsr >= 0) {
1888 if (data->termiox_supported) {
1889 data->dtr_flow = data->dsr_flow = 0;
1890 switch (config->dtr) {
1893 controlbits = TIOCM_DTR;
1894 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1895 RETURN_FAIL("Setting DTR signal level failed");
1897 case SP_DTR_FLOW_CONTROL:
1903 if (config->dsr == SP_DSR_FLOW_CONTROL)
1906 /* DTR/DSR flow control not supported. */
1907 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1908 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1910 if (config->dtr >= 0) {
1911 controlbits = TIOCM_DTR;
1912 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1914 RETURN_FAIL("Setting DTR signal level failed");
1919 if (config->xon_xoff >= 0) {
1920 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1921 switch (config->xon_xoff) {
1922 case SP_XONXOFF_DISABLED:
1925 data->term.c_iflag |= IXOFF;
1927 case SP_XONXOFF_OUT:
1928 data->term.c_iflag |= IXON | IXANY;
1930 case SP_XONXOFF_INOUT:
1931 data->term.c_iflag |= IXON | IXOFF | IXANY;
1934 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1938 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
1939 RETURN_FAIL("tcsetattr() failed");
1942 if (baud_nonstd != B0) {
1943 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1944 RETURN_FAIL("IOSSIOSPEED ioctl failed");
1945 /* Set baud rates in data->term to correct, but incompatible
1946 * with tcsetattr() value, same as delivered by tcgetattr(). */
1947 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1948 RETURN_FAIL("cfsetspeed() failed");
1950 #elif defined(__linux__)
1951 #ifdef USE_TERMIOS_SPEED
1953 TRY(set_baudrate(port->fd, config->baudrate));
1956 if (data->termiox_supported)
1957 TRY(set_flow(port->fd, data));
1961 #endif /* !_WIN32 */
1966 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
1968 struct sp_port_config *config;
1970 TRACE("%p", config_ptr);
1973 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1977 if (!(config = malloc(sizeof(struct sp_port_config))))
1978 RETURN_ERROR(SP_ERR_MEM, "config malloc failed");
1980 config->baudrate = -1;
1982 config->parity = -1;
1983 config->stopbits = -1;
1989 *config_ptr = config;
1994 SP_API void sp_free_config(struct sp_port_config *config)
1996 TRACE("%p", config);
1999 DEBUG("Null config");
2006 SP_API enum sp_return sp_get_config(struct sp_port *port,
2007 struct sp_port_config *config)
2009 struct port_data data;
2011 TRACE("%p, %p", port, config);
2016 RETURN_ERROR(SP_ERR_ARG, "Null config");
2018 TRY(get_config(port, &data, config));
2023 SP_API enum sp_return sp_set_config(struct sp_port *port,
2024 const struct sp_port_config *config)
2026 struct port_data data;
2027 struct sp_port_config prev_config;
2029 TRACE("%p, %p", port, config);
2034 RETURN_ERROR(SP_ERR_ARG, "Null config");
2036 TRY(get_config(port, &data, &prev_config));
2037 TRY(set_config(port, &data, config));
2042 #define CREATE_ACCESSORS(x, type) \
2043 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2044 struct port_data data; \
2045 struct sp_port_config config; \
2046 TRACE("%p, %d", port, x); \
2047 CHECK_OPEN_PORT(); \
2048 TRY(get_config(port, &data, &config)); \
2050 TRY(set_config(port, &data, &config)); \
2053 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2055 TRACE("%p, %p", config, x); \
2057 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2061 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2063 TRACE("%p, %d", config, x); \
2065 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2070 CREATE_ACCESSORS(baudrate, int)
2071 CREATE_ACCESSORS(bits, int)
2072 CREATE_ACCESSORS(parity, enum sp_parity)
2073 CREATE_ACCESSORS(stopbits, int)
2074 CREATE_ACCESSORS(rts, enum sp_rts)
2075 CREATE_ACCESSORS(cts, enum sp_cts)
2076 CREATE_ACCESSORS(dtr, enum sp_dtr)
2077 CREATE_ACCESSORS(dsr, enum sp_dsr)
2078 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2080 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2081 enum sp_flowcontrol flowcontrol)
2084 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2086 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2087 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2089 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2090 config->xon_xoff = SP_XONXOFF_INOUT;
2092 config->xon_xoff = SP_XONXOFF_DISABLED;
2094 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2095 config->rts = SP_RTS_FLOW_CONTROL;
2096 config->cts = SP_CTS_FLOW_CONTROL;
2098 if (config->rts == SP_RTS_FLOW_CONTROL)
2099 config->rts = SP_RTS_ON;
2100 config->cts = SP_CTS_IGNORE;
2103 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2104 config->dtr = SP_DTR_FLOW_CONTROL;
2105 config->dsr = SP_DSR_FLOW_CONTROL;
2107 if (config->dtr == SP_DTR_FLOW_CONTROL)
2108 config->dtr = SP_DTR_ON;
2109 config->dsr = SP_DSR_IGNORE;
2115 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2116 enum sp_flowcontrol flowcontrol)
2118 struct port_data data;
2119 struct sp_port_config config;
2121 TRACE("%p, %d", port, flowcontrol);
2125 TRY(get_config(port, &data, &config));
2127 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2129 TRY(set_config(port, &data, &config));
2134 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2135 enum sp_signal *signals)
2137 TRACE("%p, %p", port, signals);
2142 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2144 DEBUG("Getting control signals for port %s", port->name);
2149 if (GetCommModemStatus(port->hdl, &bits) == 0)
2150 RETURN_FAIL("GetCommModemStatus() failed");
2151 if (bits & MS_CTS_ON)
2152 *signals |= SP_SIG_CTS;
2153 if (bits & MS_DSR_ON)
2154 *signals |= SP_SIG_DSR;
2155 if (bits & MS_RLSD_ON)
2156 *signals |= SP_SIG_DCD;
2157 if (bits & MS_RING_ON)
2158 *signals |= SP_SIG_RI;
2161 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2162 RETURN_FAIL("TIOCMGET ioctl failed");
2163 if (bits & TIOCM_CTS)
2164 *signals |= SP_SIG_CTS;
2165 if (bits & TIOCM_DSR)
2166 *signals |= SP_SIG_DSR;
2167 if (bits & TIOCM_CAR)
2168 *signals |= SP_SIG_DCD;
2169 if (bits & TIOCM_RNG)
2170 *signals |= SP_SIG_RI;
2175 SP_API enum sp_return sp_start_break(struct sp_port *port)
2181 if (SetCommBreak(port->hdl) == 0)
2182 RETURN_FAIL("SetCommBreak() failed");
2184 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2185 RETURN_FAIL("TIOCSBRK ioctl failed");
2191 SP_API enum sp_return sp_end_break(struct sp_port *port)
2197 if (ClearCommBreak(port->hdl) == 0)
2198 RETURN_FAIL("ClearCommBreak() failed");
2200 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2201 RETURN_FAIL("TIOCCBRK ioctl failed");
2207 SP_API int sp_last_error_code(void)
2211 RETURN_INT(GetLastError());
2217 SP_API char *sp_last_error_message(void)
2223 DWORD error = GetLastError();
2226 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2227 FORMAT_MESSAGE_FROM_SYSTEM |
2228 FORMAT_MESSAGE_IGNORE_INSERTS,
2231 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2235 RETURN_STRING(message);
2237 RETURN_STRING(strerror(errno));
2241 SP_API void sp_free_error_message(char *message)
2243 TRACE("%s", message);
2254 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2256 TRACE("%p", handler);
2258 sp_debug_handler = handler;
2263 SP_API void sp_default_debug_handler(const char *format, ...)
2266 va_start(args, format);
2267 if (getenv("LIBSERIALPORT_DEBUG")) {
2268 fputs("sp: ", stderr);
2269 vfprintf(stderr, format, args);
2274 SP_API int sp_get_major_package_version(void)
2276 return SP_PACKAGE_VERSION_MAJOR;
2279 SP_API int sp_get_minor_package_version(void)
2281 return SP_PACKAGE_VERSION_MINOR;
2284 SP_API int sp_get_micro_package_version(void)
2286 return SP_PACKAGE_VERSION_MICRO;
2289 SP_API const char *sp_get_package_version_string(void)
2291 return SP_PACKAGE_VERSION_STRING;
2294 SP_API int sp_get_current_lib_version(void)
2296 return SP_LIB_VERSION_CURRENT;
2299 SP_API int sp_get_revision_lib_version(void)
2301 return SP_LIB_VERSION_REVISION;
2304 SP_API int sp_get_age_lib_version(void)
2306 return SP_LIB_VERSION_AGE;
2309 SP_API const char *sp_get_lib_version_string(void)
2311 return SP_LIB_VERSION_STRING;