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_FMT("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
->usb_path
= NULL
;
89 port
->hdl
= INVALID_HANDLE_VALUE
;
94 port
->description
= NULL
;
95 port
->transport
= SP_TRANSPORT_NATIVE
;
97 port
->usb_address
= -1;
100 port
->usb_manufacturer
= NULL
;
101 port
->usb_product
= NULL
;
102 port
->usb_serial
= NULL
;
103 port
->bluetooth_address
= NULL
;
105 #ifndef NO_PORT_METADATA
106 if ((ret
= get_port_details(port
)) != SP_OK
) {
117 SP_API
char *sp_get_port_name(const struct sp_port
*port
)
124 RETURN_STRING(port
->name
);
127 SP_API
char *sp_get_port_description(struct sp_port
*port
)
131 if (!port
|| !port
->description
)
134 RETURN_STRING(port
->description
);
137 SP_API
enum sp_transport
sp_get_port_transport(struct sp_port
*port
)
142 RETURN_ERROR(SP_ERR_ARG
, "Null port");
144 RETURN_INT(port
->transport
);
147 SP_API
enum sp_return
sp_get_port_usb_bus_address(const struct sp_port
*port
,
148 int *usb_bus
,int *usb_address
)
153 RETURN_ERROR(SP_ERR_ARG
, "Null port");
154 if (port
->transport
!= SP_TRANSPORT_USB
)
155 RETURN_ERROR(SP_ERR_ARG
, "Port does not use USB transport");
156 if (port
->usb_bus
< 0 || port
->usb_address
< 0)
157 RETURN_ERROR(SP_ERR_SUPP
, "Bus and address values are not available");
159 if (usb_bus
) *usb_bus
= port
->usb_bus
;
160 if (usb_address
) *usb_address
= port
->usb_address
;
165 SP_API
enum sp_return
sp_get_port_usb_vid_pid(const struct sp_port
*port
,
166 int *usb_vid
, int *usb_pid
)
171 RETURN_ERROR(SP_ERR_ARG
, "Null port");
172 if (port
->transport
!= SP_TRANSPORT_USB
)
173 RETURN_ERROR(SP_ERR_ARG
, "Port does not use USB transport");
174 if (port
->usb_vid
< 0 || port
->usb_pid
< 0)
175 RETURN_ERROR(SP_ERR_SUPP
, "VID:PID values are not available");
177 if (usb_vid
) *usb_vid
= port
->usb_vid
;
178 if (usb_pid
) *usb_pid
= port
->usb_pid
;
183 SP_API
char *sp_get_port_usb_manufacturer(const struct sp_port
*port
)
187 if (!port
|| port
->transport
!= SP_TRANSPORT_USB
|| !port
->usb_manufacturer
)
190 RETURN_STRING(port
->usb_manufacturer
);
193 SP_API
char *sp_get_port_usb_product(const struct sp_port
*port
)
197 if (!port
|| port
->transport
!= SP_TRANSPORT_USB
|| !port
->usb_product
)
200 RETURN_STRING(port
->usb_product
);
203 SP_API
char *sp_get_port_usb_serial(const struct sp_port
*port
)
207 if (!port
|| port
->transport
!= SP_TRANSPORT_USB
|| !port
->usb_serial
)
210 RETURN_STRING(port
->usb_serial
);
213 SP_API
char *sp_get_port_bluetooth_address(const struct sp_port
*port
)
217 if (!port
|| port
->transport
!= SP_TRANSPORT_BLUETOOTH
218 || !port
->bluetooth_address
)
221 RETURN_STRING(port
->bluetooth_address
);
224 SP_API
enum sp_return
sp_get_port_handle(const struct sp_port
*port
,
227 TRACE("%p, %p", port
, result_ptr
);
230 RETURN_ERROR(SP_ERR_ARG
, "Null port");
233 HANDLE
*handle_ptr
= result_ptr
;
234 *handle_ptr
= port
->hdl
;
236 int *fd_ptr
= result_ptr
;
243 SP_API
enum sp_return
sp_copy_port(const struct sp_port
*port
,
244 struct sp_port
**copy_ptr
)
246 TRACE("%p, %p", port
, copy_ptr
);
249 RETURN_ERROR(SP_ERR_ARG
, "Null result pointer");
254 RETURN_ERROR(SP_ERR_ARG
, "Null port");
257 RETURN_ERROR(SP_ERR_ARG
, "Null port name");
259 DEBUG("Copying port structure");
261 RETURN_INT(sp_get_port_by_name(port
->name
, copy_ptr
));
264 SP_API
void sp_free_port(struct sp_port
*port
)
273 DEBUG("Freeing port structure");
277 if (port
->description
)
278 free(port
->description
);
279 if (port
->usb_manufacturer
)
280 free(port
->usb_manufacturer
);
281 if (port
->usb_product
)
282 free(port
->usb_product
);
283 if (port
->usb_serial
)
284 free(port
->usb_serial
);
285 if (port
->bluetooth_address
)
286 free(port
->bluetooth_address
);
289 free(port
->usb_path
);
297 SP_PRIV
struct sp_port
**list_append(struct sp_port
**list
,
298 const char *portname
)
303 for (count
= 0; list
[count
]; count
++);
304 if (!(tmp
= realloc(list
, sizeof(struct sp_port
*) * (count
+ 2))))
307 if (sp_get_port_by_name(portname
, &list
[count
]) != SP_OK
)
309 list
[count
+ 1] = NULL
;
313 sp_free_port_list(list
);
317 SP_API
enum sp_return
sp_list_ports(struct sp_port
***list_ptr
)
319 struct sp_port
**list
;
322 TRACE("%p", list_ptr
);
325 RETURN_ERROR(SP_ERR_ARG
, "Null result pointer");
327 DEBUG("Enumerating ports");
329 if (!(list
= malloc(sizeof(struct sp_port
**))))
330 RETURN_ERROR(SP_ERR_MEM
, "Port list malloc failed");
334 #ifdef NO_ENUMERATION
337 ret
= list_ports(&list
);
345 DEBUG_ERROR(SP_ERR_SUPP
, "Enumeration not supported on this platform");
348 sp_free_port_list(list
);
354 SP_API
void sp_free_port_list(struct sp_port
**list
)
365 DEBUG("Freeing port list");
367 for (i
= 0; list
[i
]; i
++)
368 sp_free_port(list
[i
]);
374 #define CHECK_PORT() do { \
376 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
377 if (port->name == NULL) \
378 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
381 #define CHECK_PORT_HANDLE() do { \
382 if (port->hdl == INVALID_HANDLE_VALUE) \
383 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
386 #define CHECK_PORT_HANDLE() do { \
388 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
391 #define CHECK_OPEN_PORT() do { \
393 CHECK_PORT_HANDLE(); \
396 SP_API
enum sp_return
sp_open(struct sp_port
*port
, enum sp_mode flags
)
398 struct port_data data
;
399 struct sp_port_config config
;
402 TRACE("%p, 0x%x", port
, flags
);
406 if (flags
> SP_MODE_READ_WRITE
)
407 RETURN_ERROR(SP_ERR_ARG
, "Invalid flags");
409 DEBUG_FMT("Opening port %s", port
->name
);
412 DWORD desired_access
= 0, flags_and_attributes
= 0, errors
;
413 char *escaped_port_name
;
416 /* Prefix port name with '\\.\' to work with ports above COM9. */
417 if (!(escaped_port_name
= malloc(strlen(port
->name
) + 5)))
418 RETURN_ERROR(SP_ERR_MEM
, "Escaped port name malloc failed");
419 sprintf(escaped_port_name
, "\\\\.\\%s", port
->name
);
421 /* Map 'flags' to the OS-specific settings. */
422 flags_and_attributes
= FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_OVERLAPPED
;
423 if (flags
& SP_MODE_READ
)
424 desired_access
|= GENERIC_READ
;
425 if (flags
& SP_MODE_WRITE
)
426 desired_access
|= GENERIC_WRITE
;
428 port
->hdl
= CreateFile(escaped_port_name
, desired_access
, 0, 0,
429 OPEN_EXISTING
, flags_and_attributes
, 0);
431 free(escaped_port_name
);
433 if (port
->hdl
== INVALID_HANDLE_VALUE
)
434 RETURN_FAIL("port CreateFile() failed");
436 /* All timeouts initially disabled. */
437 port
->timeouts
.ReadIntervalTimeout
= 0;
438 port
->timeouts
.ReadTotalTimeoutMultiplier
= 0;
439 port
->timeouts
.ReadTotalTimeoutConstant
= 0;
440 port
->timeouts
.WriteTotalTimeoutMultiplier
= 0;
441 port
->timeouts
.WriteTotalTimeoutConstant
= 0;
443 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0) {
445 RETURN_FAIL("SetCommTimeouts() failed");
448 /* Prepare OVERLAPPED structures. */
449 #define INIT_OVERLAPPED(ovl) do { \
450 memset(&port->ovl, 0, sizeof(port->ovl)); \
451 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
452 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
453 == INVALID_HANDLE_VALUE) { \
455 RETURN_FAIL(#ovl "CreateEvent() failed"); \
459 INIT_OVERLAPPED(read_ovl
);
460 INIT_OVERLAPPED(write_ovl
);
461 INIT_OVERLAPPED(wait_ovl
);
463 /* Set event mask for RX and error events. */
464 if (SetCommMask(port
->hdl
, EV_RXCHAR
| EV_ERR
) == 0) {
466 RETURN_FAIL("SetCommMask() failed");
469 /* Start background operation for RX and error events. */
470 if (WaitCommEvent(port
->hdl
, &port
->events
, &port
->wait_ovl
) == 0) {
471 if (GetLastError() != ERROR_IO_PENDING
) {
473 RETURN_FAIL("WaitCommEvent() failed");
477 port
->writing
= FALSE
;
480 int flags_local
= O_NONBLOCK
| O_NOCTTY
;
482 /* Map 'flags' to the OS-specific settings. */
483 if ((flags
& SP_MODE_READ_WRITE
) == SP_MODE_READ_WRITE
)
484 flags_local
|= O_RDWR
;
485 else if (flags
& SP_MODE_READ
)
486 flags_local
|= O_RDONLY
;
487 else if (flags
& SP_MODE_WRITE
)
488 flags_local
|= O_WRONLY
;
490 if ((port
->fd
= open(port
->name
, flags_local
)) < 0)
491 RETURN_FAIL("open() failed");
494 ret
= get_config(port
, &data
, &config
);
501 /* Set sane port settings. */
503 data
.dcb
.fBinary
= TRUE
;
504 data
.dcb
.fDsrSensitivity
= FALSE
;
505 data
.dcb
.fErrorChar
= FALSE
;
506 data
.dcb
.fNull
= FALSE
;
507 data
.dcb
.fAbortOnError
= TRUE
;
509 /* Turn off all fancy termios tricks, give us a raw channel. */
510 data
.term
.c_iflag
&= ~(IGNBRK
| BRKINT
| PARMRK
| ISTRIP
| INLCR
| IGNCR
| ICRNL
| IMAXBEL
);
512 data
.term
.c_iflag
&= ~IUCLC
;
514 data
.term
.c_oflag
&= ~(OPOST
| ONLCR
| OCRNL
| ONOCR
| ONLRET
);
516 data
.term
.c_oflag
&= ~OLCUC
;
519 data
.term
.c_oflag
&= ~NLDLY
;
522 data
.term
.c_oflag
&= ~CRDLY
;
525 data
.term
.c_oflag
&= ~TABDLY
;
528 data
.term
.c_oflag
&= ~BSDLY
;
531 data
.term
.c_oflag
&= ~VTDLY
;
534 data
.term
.c_oflag
&= ~FFDLY
;
537 data
.term
.c_oflag
&= ~OFILL
;
539 data
.term
.c_lflag
&= ~(ISIG
| ICANON
| ECHO
| IEXTEN
);
540 data
.term
.c_cc
[VMIN
] = 0;
541 data
.term
.c_cc
[VTIME
] = 0;
543 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
544 data
.term
.c_cflag
|= (CLOCAL
| CREAD
| HUPCL
);
548 if (ClearCommError(port
->hdl
, &errors
, &status
) == 0)
549 RETURN_FAIL("ClearCommError() failed");
552 ret
= set_config(port
, &data
, &config
);
562 SP_API
enum sp_return
sp_close(struct sp_port
*port
)
568 DEBUG_FMT("Closing port %s", port
->name
);
571 /* Returns non-zero upon success, 0 upon failure. */
572 if (CloseHandle(port
->hdl
) == 0)
573 RETURN_FAIL("port CloseHandle() failed");
574 port
->hdl
= INVALID_HANDLE_VALUE
;
576 /* Close event handles for overlapped structures. */
577 #define CLOSE_OVERLAPPED(ovl) do { \
578 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
579 CloseHandle(port->ovl.hEvent) == 0) \
580 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
582 CLOSE_OVERLAPPED(read_ovl
);
583 CLOSE_OVERLAPPED(write_ovl
);
584 CLOSE_OVERLAPPED(wait_ovl
);
587 /* Returns 0 upon success, -1 upon failure. */
588 if (close(port
->fd
) == -1)
589 RETURN_FAIL("close() failed");
596 SP_API
enum sp_return
sp_flush(struct sp_port
*port
, enum sp_buffer buffers
)
598 TRACE("%p, 0x%x", port
, buffers
);
602 if (buffers
> SP_BUF_BOTH
)
603 RETURN_ERROR(SP_ERR_ARG
, "Invalid buffer selection");
605 const char *buffer_names
[] = {"no", "input", "output", "both"};
607 DEBUG_FMT("Flushing %s buffers on port %s",
608 buffer_names
[buffers
], port
->name
);
612 if (buffers
& SP_BUF_INPUT
)
613 flags
|= PURGE_RXCLEAR
;
614 if (buffers
& SP_BUF_OUTPUT
)
615 flags
|= PURGE_TXCLEAR
;
617 /* Returns non-zero upon success, 0 upon failure. */
618 if (PurgeComm(port
->hdl
, flags
) == 0)
619 RETURN_FAIL("PurgeComm() failed");
622 if (buffers
== SP_BUF_BOTH
)
624 else if (buffers
== SP_BUF_INPUT
)
626 else if (buffers
== SP_BUF_OUTPUT
)
629 /* Returns 0 upon success, -1 upon failure. */
630 if (tcflush(port
->fd
, flags
) < 0)
631 RETURN_FAIL("tcflush() failed");
636 SP_API
enum sp_return
sp_drain(struct sp_port
*port
)
642 DEBUG_FMT("Draining port %s", port
->name
);
645 /* Returns non-zero upon success, 0 upon failure. */
646 if (FlushFileBuffers(port
->hdl
) == 0)
647 RETURN_FAIL("FlushFileBuffers() failed");
654 result
= ioctl(port
->fd
, TCSBRK
, &arg
);
656 result
= tcdrain(port
->fd
);
659 if (errno
== EINTR
) {
660 DEBUG("tcdrain() was interrupted");
663 RETURN_FAIL("tcdrain() failed");
672 SP_API
enum sp_return
sp_blocking_write(struct sp_port
*port
, const void *buf
,
673 size_t count
, unsigned int timeout
)
675 TRACE("%p, %p, %d, %d", port
, buf
, count
, timeout
);
680 RETURN_ERROR(SP_ERR_ARG
, "Null buffer");
683 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
684 count
, port
->name
, timeout
);
686 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
693 DWORD bytes_written
= 0;
696 /* Wait for previous non-blocking write to complete, if any. */
698 DEBUG("Waiting for previous write to complete");
699 result
= GetOverlappedResult(port
->hdl
, &port
->write_ovl
, &bytes_written
, TRUE
);
702 RETURN_FAIL("Previous write failed to complete");
703 DEBUG("Previous write completed");
707 port
->timeouts
.WriteTotalTimeoutConstant
= timeout
;
708 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0)
709 RETURN_FAIL("SetCommTimeouts() failed");
712 if (WriteFile(port
->hdl
, buf
, count
, NULL
, &port
->write_ovl
) == 0) {
713 if (GetLastError() == ERROR_IO_PENDING
) {
714 DEBUG("Waiting for write to complete");
715 GetOverlappedResult(port
->hdl
, &port
->write_ovl
, &bytes_written
, TRUE
);
716 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written
, count
);
717 RETURN_INT(bytes_written
);
719 RETURN_FAIL("WriteFile() failed");
722 DEBUG("Write completed immediately");
726 size_t bytes_written
= 0;
727 unsigned char *ptr
= (unsigned char *) buf
;
728 struct timeval start
, delta
, now
, end
= {0, 0};
733 /* Get time at start of operation. */
734 gettimeofday(&start
, NULL
);
735 /* Define duration of timeout. */
736 delta
.tv_sec
= timeout
/ 1000;
737 delta
.tv_usec
= (timeout
% 1000) * 1000;
738 /* Calculate time at which we should give up. */
739 timeradd(&start
, &delta
, &end
);
742 /* Loop until we have written the requested number of bytes. */
743 while (bytes_written
< count
)
745 /* Wait until space is available. */
747 FD_SET(port
->fd
, &fds
);
749 gettimeofday(&now
, NULL
);
750 if (timercmp(&now
, &end
, >)) {
751 DEBUG("write timed out");
752 RETURN_INT(bytes_written
);
754 timersub(&end
, &now
, &delta
);
756 result
= select(port
->fd
+ 1, NULL
, &fds
, NULL
, timeout
? &delta
: NULL
);
758 if (errno
== EINTR
) {
759 DEBUG("select() call was interrupted, repeating");
762 RETURN_FAIL("select() failed");
764 } else if (result
== 0) {
765 DEBUG("write timed out");
766 RETURN_INT(bytes_written
);
770 result
= write(port
->fd
, ptr
, count
- bytes_written
);
774 /* This shouldn't happen because we did a select() first, but handle anyway. */
777 /* This is an actual failure. */
778 RETURN_FAIL("write() failed");
781 bytes_written
+= result
;
785 RETURN_INT(bytes_written
);
789 SP_API
enum sp_return
sp_nonblocking_write(struct sp_port
*port
,
790 const void *buf
, size_t count
)
792 TRACE("%p, %p, %d", port
, buf
, count
);
797 RETURN_ERROR(SP_ERR_ARG
, "Null buffer");
799 DEBUG_FMT("Writing up to %d bytes to port %s", count
, port
->name
);
806 BYTE
*ptr
= (BYTE
*) buf
;
808 /* Check whether previous write is complete. */
810 if (HasOverlappedIoCompleted(&port
->write_ovl
)) {
811 DEBUG("Previous write completed");
814 DEBUG("Previous write not complete");
815 /* Can't take a new write until the previous one finishes. */
821 port
->timeouts
.WriteTotalTimeoutConstant
= 0;
822 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0)
823 RETURN_FAIL("SetCommTimeouts() failed");
825 /* Keep writing data until the OS has to actually start an async IO for it.
826 * At that point we know the buffer is full. */
827 while (written
< count
)
829 /* Copy first byte of user buffer. */
830 port
->pending_byte
= *ptr
++;
832 /* Start asynchronous write. */
833 if (WriteFile(port
->hdl
, &port
->pending_byte
, 1, NULL
, &port
->write_ovl
) == 0) {
834 if (GetLastError() == ERROR_IO_PENDING
) {
835 if (HasOverlappedIoCompleted(&port
->write_ovl
)) {
836 DEBUG("Asynchronous write completed immediately");
841 DEBUG("Asynchronous write running");
843 RETURN_INT(++written
);
846 /* Actual failure of some kind. */
847 RETURN_FAIL("WriteFile() failed");
850 DEBUG("Single byte written immediately");
855 DEBUG("All bytes written immediately");
859 /* Returns the number of bytes written, or -1 upon failure. */
860 ssize_t written
= write(port
->fd
, buf
, count
);
863 RETURN_FAIL("write() failed");
869 SP_API
enum sp_return
sp_blocking_read(struct sp_port
*port
, void *buf
,
870 size_t count
, unsigned int timeout
)
872 TRACE("%p, %p, %d, %d", port
, buf
, count
, timeout
);
877 RETURN_ERROR(SP_ERR_ARG
, "Null buffer");
880 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
881 count
, port
->name
, timeout
);
883 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
890 DWORD bytes_read
= 0;
891 DWORD wait_result
= 0;
894 port
->timeouts
.ReadIntervalTimeout
= 0;
895 port
->timeouts
.ReadTotalTimeoutConstant
= timeout
;
896 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0)
897 RETURN_FAIL("SetCommTimeouts() failed");
900 if (ReadFile(port
->hdl
, buf
, count
, NULL
, &port
->read_ovl
) == 0) {
901 if (GetLastError() == ERROR_IO_PENDING
) {
902 DEBUG("Waiting for read to complete");
903 GetOverlappedResult(port
->hdl
, &port
->read_ovl
, &bytes_read
, TRUE
);
904 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read
, count
);
906 RETURN_FAIL("ReadFile() failed");
909 DEBUG("Read completed immediately");
913 /* Restart wait operation if needed. */
914 if (GetOverlappedResult(port
->hdl
, &port
->wait_ovl
, &wait_result
, FALSE
)) {
915 /* Previous wait completed, start a new one. */
916 if (WaitCommEvent(port
->hdl
, &port
->events
, &port
->wait_ovl
) == 0) {
917 if (GetLastError() != ERROR_IO_PENDING
)
918 RETURN_FAIL("WaitCommEvent() failed");
920 } else if (GetLastError() != ERROR_IO_INCOMPLETE
) {
921 RETURN_FAIL("GetOverlappedResult() failed");
924 RETURN_INT(bytes_read
);
927 size_t bytes_read
= 0;
928 unsigned char *ptr
= (unsigned char *) buf
;
929 struct timeval start
, delta
, now
, end
= {0, 0};
934 /* Get time at start of operation. */
935 gettimeofday(&start
, NULL
);
936 /* Define duration of timeout. */
937 delta
.tv_sec
= timeout
/ 1000;
938 delta
.tv_usec
= (timeout
% 1000) * 1000;
939 /* Calculate time at which we should give up. */
940 timeradd(&start
, &delta
, &end
);
943 /* Loop until we have the requested number of bytes. */
944 while (bytes_read
< count
)
946 /* Wait until data is available. */
948 FD_SET(port
->fd
, &fds
);
950 gettimeofday(&now
, NULL
);
951 if (timercmp(&now
, &end
, >))
952 /* Timeout has expired. */
953 RETURN_INT(bytes_read
);
954 timersub(&end
, &now
, &delta
);
956 result
= select(port
->fd
+ 1, &fds
, NULL
, NULL
, timeout
? &delta
: NULL
);
958 if (errno
== EINTR
) {
959 DEBUG("select() call was interrupted, repeating");
962 RETURN_FAIL("select() failed");
964 } else if (result
== 0) {
965 DEBUG("read timed out");
966 RETURN_INT(bytes_read
);
970 result
= read(port
->fd
, ptr
, count
- bytes_read
);
974 /* This shouldn't happen because we did a select() first, but handle anyway. */
977 /* This is an actual failure. */
978 RETURN_FAIL("read() failed");
981 bytes_read
+= result
;
985 RETURN_INT(bytes_read
);
989 SP_API
enum sp_return
sp_nonblocking_read(struct sp_port
*port
, void *buf
,
992 TRACE("%p, %p, %d", port
, buf
, count
);
997 RETURN_ERROR(SP_ERR_ARG
, "Null buffer");
999 DEBUG_FMT("Reading up to %d bytes from port %s", count
, port
->name
);
1006 port
->timeouts
.ReadIntervalTimeout
= MAXDWORD
;
1007 port
->timeouts
.ReadTotalTimeoutConstant
= 0;
1008 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0)
1009 RETURN_FAIL("SetCommTimeouts() failed");
1012 if (ReadFile(port
->hdl
, buf
, count
, NULL
, &port
->read_ovl
) == 0)
1013 RETURN_FAIL("ReadFile() failed");
1015 /* Get number of bytes read. */
1016 if (GetOverlappedResult(port
->hdl
, &port
->read_ovl
, &bytes_read
, TRUE
) == 0)
1017 RETURN_FAIL("GetOverlappedResult() failed");
1019 /* Restart wait operation if needed. */
1020 if (GetOverlappedResult(port
->hdl
, &port
->wait_ovl
, &wait_result
, FALSE
)) {
1021 /* Previous wait completed, start a new one. */
1022 if (WaitCommEvent(port
->hdl
, &port
->events
, &port
->wait_ovl
) == 0) {
1023 if (GetLastError() != ERROR_IO_PENDING
)
1024 RETURN_FAIL("WaitCommEvent() failed");
1026 } else if (GetLastError() != ERROR_IO_INCOMPLETE
) {
1027 RETURN_FAIL("GetOverlappedResult() failed");
1030 RETURN_INT(bytes_read
);
1034 /* Returns the number of bytes read, or -1 upon failure. */
1035 if ((bytes_read
= read(port
->fd
, buf
, count
)) < 0) {
1036 if (errno
== EAGAIN
)
1037 /* No bytes available. */
1040 /* This is an actual failure. */
1041 RETURN_FAIL("read() failed");
1043 RETURN_INT(bytes_read
);
1047 SP_API
enum sp_return
sp_input_waiting(struct sp_port
*port
)
1053 DEBUG_FMT("Checking input bytes waiting on port %s", port
->name
);
1059 if (ClearCommError(port
->hdl
, &errors
, &comstat
) == 0)
1060 RETURN_FAIL("ClearCommError() failed");
1061 RETURN_INT(comstat
.cbInQue
);
1064 if (ioctl(port
->fd
, TIOCINQ
, &bytes_waiting
) < 0)
1065 RETURN_FAIL("TIOCINQ ioctl failed");
1066 RETURN_INT(bytes_waiting
);
1070 SP_API
enum sp_return
sp_output_waiting(struct sp_port
*port
)
1076 DEBUG_FMT("Checking output bytes waiting on port %s", port
->name
);
1082 if (ClearCommError(port
->hdl
, &errors
, &comstat
) == 0)
1083 RETURN_FAIL("ClearCommError() failed");
1084 RETURN_INT(comstat
.cbOutQue
);
1087 if (ioctl(port
->fd
, TIOCOUTQ
, &bytes_waiting
) < 0)
1088 RETURN_FAIL("TIOCOUTQ ioctl failed");
1089 RETURN_INT(bytes_waiting
);
1093 SP_API
enum sp_return
sp_new_event_set(struct sp_event_set
**result_ptr
)
1095 struct sp_event_set
*result
;
1097 TRACE("%p", result_ptr
);
1100 RETURN_ERROR(SP_ERR_ARG
, "Null result");
1104 if (!(result
= malloc(sizeof(struct sp_event_set
))))
1105 RETURN_ERROR(SP_ERR_MEM
, "sp_event_set malloc() failed");
1107 memset(result
, 0, sizeof(struct sp_event_set
));
1109 *result_ptr
= result
;
1114 static enum sp_return
add_handle(struct sp_event_set
*event_set
,
1115 event_handle handle
, enum sp_event mask
)
1118 enum sp_event
*new_masks
;
1120 TRACE("%p, %d, %d", event_set
, handle
, mask
);
1122 if (!(new_handles
= realloc(event_set
->handles
,
1123 sizeof(event_handle
) * (event_set
->count
+ 1))))
1124 RETURN_ERROR(SP_ERR_MEM
, "handle array realloc() failed");
1126 if (!(new_masks
= realloc(event_set
->masks
,
1127 sizeof(enum sp_event
) * (event_set
->count
+ 1))))
1128 RETURN_ERROR(SP_ERR_MEM
, "mask array realloc() failed");
1130 event_set
->handles
= new_handles
;
1131 event_set
->masks
= new_masks
;
1133 ((event_handle
*) event_set
->handles
)[event_set
->count
] = handle
;
1134 event_set
->masks
[event_set
->count
] = mask
;
1141 SP_API
enum sp_return
sp_add_port_events(struct sp_event_set
*event_set
,
1142 const struct sp_port
*port
, enum sp_event mask
)
1144 TRACE("%p, %p, %d", event_set
, port
, mask
);
1147 RETURN_ERROR(SP_ERR_ARG
, "Null event set");
1150 RETURN_ERROR(SP_ERR_ARG
, "Null port");
1152 if (mask
> (SP_EVENT_RX_READY
| SP_EVENT_TX_READY
| SP_EVENT_ERROR
))
1153 RETURN_ERROR(SP_ERR_ARG
, "Invalid event mask");
1159 enum sp_event handle_mask
;
1160 if ((handle_mask
= mask
& SP_EVENT_TX_READY
))
1161 TRY(add_handle(event_set
, port
->write_ovl
.hEvent
, handle_mask
));
1162 if ((handle_mask
= mask
& (SP_EVENT_RX_READY
| SP_EVENT_ERROR
)))
1163 TRY(add_handle(event_set
, port
->wait_ovl
.hEvent
, handle_mask
));
1165 TRY(add_handle(event_set
, port
->fd
, mask
));
1171 SP_API
void sp_free_event_set(struct sp_event_set
*event_set
)
1173 TRACE("%p", event_set
);
1176 DEBUG("Null event set");
1180 DEBUG("Freeing event set");
1182 if (event_set
->handles
)
1183 free(event_set
->handles
);
1184 if (event_set
->masks
)
1185 free(event_set
->masks
);
1192 SP_API
enum sp_return
sp_wait(struct sp_event_set
*event_set
,
1193 unsigned int timeout
)
1195 TRACE("%p, %d", event_set
, timeout
);
1198 RETURN_ERROR(SP_ERR_ARG
, "Null event set");
1201 if (WaitForMultipleObjects(event_set
->count
, event_set
->handles
, FALSE
,
1202 timeout
? timeout
: INFINITE
) == WAIT_FAILED
)
1203 RETURN_FAIL("WaitForMultipleObjects() failed");
1207 struct timeval start
, delta
, now
, end
= {0, 0};
1208 int result
, timeout_remaining
;
1209 struct pollfd
*pollfds
;
1212 if (!(pollfds
= malloc(sizeof(struct pollfd
) * event_set
->count
)))
1213 RETURN_ERROR(SP_ERR_MEM
, "pollfds malloc() failed");
1215 for (i
= 0; i
< event_set
->count
; i
++) {
1216 pollfds
[i
].fd
= ((int *) event_set
->handles
)[i
];
1217 pollfds
[i
].events
= 0;
1218 pollfds
[i
].revents
= 0;
1219 if (event_set
->masks
[i
] & SP_EVENT_RX_READY
)
1220 pollfds
[i
].events
|= POLLIN
;
1221 if (event_set
->masks
[i
] & SP_EVENT_TX_READY
)
1222 pollfds
[i
].events
|= POLLOUT
;
1223 if (event_set
->masks
[i
] & SP_EVENT_ERROR
)
1224 pollfds
[i
].events
|= POLLERR
;
1228 /* Get time at start of operation. */
1229 gettimeofday(&start
, NULL
);
1230 /* Define duration of timeout. */
1231 delta
.tv_sec
= timeout
/ 1000;
1232 delta
.tv_usec
= (timeout
% 1000) * 1000;
1233 /* Calculate time at which we should give up. */
1234 timeradd(&start
, &delta
, &end
);
1237 /* Loop until an event occurs. */
1241 gettimeofday(&now
, NULL
);
1242 if (timercmp(&now
, &end
, >)) {
1243 DEBUG("wait timed out");
1246 timersub(&end
, &now
, &delta
);
1247 timeout_remaining
= delta
.tv_sec
* 1000 + delta
.tv_usec
/ 1000;
1250 result
= poll(pollfds
, event_set
->count
, timeout
? timeout_remaining
: -1);
1253 if (errno
== EINTR
) {
1254 DEBUG("poll() call was interrupted, repeating");
1258 RETURN_FAIL("poll() failed");
1260 } else if (result
== 0) {
1261 DEBUG("poll() timed out");
1264 DEBUG("poll() completed");
1274 #ifdef USE_TERMIOS_SPEED
1275 static enum sp_return
get_baudrate(int fd
, int *baudrate
)
1279 TRACE("%d, %p", fd
, baudrate
);
1281 DEBUG("Getting baud rate");
1283 if (!(data
= malloc(get_termios_size())))
1284 RETURN_ERROR(SP_ERR_MEM
, "termios malloc failed");
1286 if (ioctl(fd
, get_termios_get_ioctl(), data
) < 0) {
1288 RETURN_FAIL("getting termios failed");
1291 *baudrate
= get_termios_speed(data
);
1298 static enum sp_return
set_baudrate(int fd
, int baudrate
)
1302 TRACE("%d, %d", fd
, baudrate
);
1304 DEBUG("Getting baud rate");
1306 if (!(data
= malloc(get_termios_size())))
1307 RETURN_ERROR(SP_ERR_MEM
, "termios malloc failed");
1309 if (ioctl(fd
, get_termios_get_ioctl(), data
) < 0) {
1311 RETURN_FAIL("getting termios failed");
1314 DEBUG("Setting baud rate");
1316 set_termios_speed(data
, baudrate
);
1318 if (ioctl(fd
, get_termios_set_ioctl(), data
) < 0) {
1320 RETURN_FAIL("setting termios failed");
1327 #endif /* USE_TERMIOS_SPEED */
1330 static enum sp_return
get_flow(int fd
, struct port_data
*data
)
1334 TRACE("%d, %p", fd
, data
);
1336 DEBUG("Getting advanced flow control");
1338 if (!(termx
= malloc(get_termiox_size())))
1339 RETURN_ERROR(SP_ERR_MEM
, "termiox malloc failed");
1341 if (ioctl(fd
, TCGETX
, termx
) < 0) {
1343 RETURN_FAIL("getting termiox failed");
1346 get_termiox_flow(termx
, &data
->rts_flow
, &data
->cts_flow
,
1347 &data
->dtr_flow
, &data
->dsr_flow
);
1354 static enum sp_return
set_flow(int fd
, struct port_data
*data
)
1358 TRACE("%d, %p", fd
, data
);
1360 DEBUG("Getting advanced flow control");
1362 if (!(termx
= malloc(get_termiox_size())))
1363 RETURN_ERROR(SP_ERR_MEM
, "termiox malloc failed");
1365 if (ioctl(fd
, TCGETX
, termx
) < 0) {
1367 RETURN_FAIL("getting termiox failed");
1370 DEBUG("Setting advanced flow control");
1372 set_termiox_flow(termx
, data
->rts_flow
, data
->cts_flow
,
1373 data
->dtr_flow
, data
->dsr_flow
);
1375 if (ioctl(fd
, TCSETX
, termx
) < 0) {
1377 RETURN_FAIL("setting termiox failed");
1384 #endif /* USE_TERMIOX */
1386 static enum sp_return
get_config(struct sp_port
*port
, struct port_data
*data
,
1387 struct sp_port_config
*config
)
1391 TRACE("%p, %p, %p", port
, data
, config
);
1393 DEBUG_FMT("Getting configuration for port %s", port
->name
);
1396 if (!GetCommState(port
->hdl
, &data
->dcb
))
1397 RETURN_FAIL("GetCommState() failed");
1399 for (i
= 0; i
< NUM_STD_BAUDRATES
; i
++) {
1400 if (data
->dcb
.BaudRate
== std_baudrates
[i
].index
) {
1401 config
->baudrate
= std_baudrates
[i
].value
;
1406 if (i
== NUM_STD_BAUDRATES
)
1407 /* BaudRate field can be either an index or a custom baud rate. */
1408 config
->baudrate
= data
->dcb
.BaudRate
;
1410 config
->bits
= data
->dcb
.ByteSize
;
1412 if (data
->dcb
.fParity
)
1413 switch (data
->dcb
.Parity
) {
1415 config
->parity
= SP_PARITY_NONE
;
1418 config
->parity
= SP_PARITY_ODD
;
1421 config
->parity
= SP_PARITY_EVEN
;
1424 config
->parity
= SP_PARITY_MARK
;
1427 config
->parity
= SP_PARITY_SPACE
;
1430 config
->parity
= -1;
1433 config
->parity
= SP_PARITY_NONE
;
1435 switch (data
->dcb
.StopBits
) {
1437 config
->stopbits
= 1;
1440 config
->stopbits
= 2;
1443 config
->stopbits
= -1;
1446 switch (data
->dcb
.fRtsControl
) {
1447 case RTS_CONTROL_DISABLE
:
1448 config
->rts
= SP_RTS_OFF
;
1450 case RTS_CONTROL_ENABLE
:
1451 config
->rts
= SP_RTS_ON
;
1453 case RTS_CONTROL_HANDSHAKE
:
1454 config
->rts
= SP_RTS_FLOW_CONTROL
;
1460 config
->cts
= data
->dcb
.fOutxCtsFlow
? SP_CTS_FLOW_CONTROL
: SP_CTS_IGNORE
;
1462 switch (data
->dcb
.fDtrControl
) {
1463 case DTR_CONTROL_DISABLE
:
1464 config
->dtr
= SP_DTR_OFF
;
1466 case DTR_CONTROL_ENABLE
:
1467 config
->dtr
= SP_DTR_ON
;
1469 case DTR_CONTROL_HANDSHAKE
:
1470 config
->dtr
= SP_DTR_FLOW_CONTROL
;
1476 config
->dsr
= data
->dcb
.fOutxDsrFlow
? SP_DSR_FLOW_CONTROL
: SP_DSR_IGNORE
;
1478 if (data
->dcb
.fInX
) {
1479 if (data
->dcb
.fOutX
)
1480 config
->xon_xoff
= SP_XONXOFF_INOUT
;
1482 config
->xon_xoff
= SP_XONXOFF_IN
;
1484 if (data
->dcb
.fOutX
)
1485 config
->xon_xoff
= SP_XONXOFF_OUT
;
1487 config
->xon_xoff
= SP_XONXOFF_DISABLED
;
1492 if (tcgetattr(port
->fd
, &data
->term
) < 0)
1493 RETURN_FAIL("tcgetattr() failed");
1495 if (ioctl(port
->fd
, TIOCMGET
, &data
->controlbits
) < 0)
1496 RETURN_FAIL("TIOCMGET ioctl failed");
1499 int ret
= get_flow(port
->fd
, data
);
1501 if (ret
== SP_ERR_FAIL
&& errno
== EINVAL
)
1502 data
->termiox_supported
= 0;
1504 RETURN_CODEVAL(ret
);
1506 data
->termiox_supported
= 1;
1508 data
->termiox_supported
= 0;
1511 for (i
= 0; i
< NUM_STD_BAUDRATES
; i
++) {
1512 if (cfgetispeed(&data
->term
) == std_baudrates
[i
].index
) {
1513 config
->baudrate
= std_baudrates
[i
].value
;
1518 if (i
== NUM_STD_BAUDRATES
) {
1520 config
->baudrate
= (int)data
->term
.c_ispeed
;
1521 #elif defined(USE_TERMIOS_SPEED)
1522 TRY(get_baudrate(port
->fd
, &config
->baudrate
));
1524 config
->baudrate
= -1;
1528 switch (data
->term
.c_cflag
& CSIZE
) {
1545 if (!(data
->term
.c_cflag
& PARENB
) && (data
->term
.c_iflag
& IGNPAR
))
1546 config
->parity
= SP_PARITY_NONE
;
1547 else if (!(data
->term
.c_cflag
& PARENB
) || (data
->term
.c_iflag
& IGNPAR
))
1548 config
->parity
= -1;
1550 else if (data
->term
.c_cflag
& CMSPAR
)
1551 config
->parity
= (data
->term
.c_cflag
& PARODD
) ? SP_PARITY_MARK
: SP_PARITY_SPACE
;
1554 config
->parity
= (data
->term
.c_cflag
& PARODD
) ? SP_PARITY_ODD
: SP_PARITY_EVEN
;
1556 config
->stopbits
= (data
->term
.c_cflag
& CSTOPB
) ? 2 : 1;
1558 if (data
->term
.c_cflag
& CRTSCTS
) {
1559 config
->rts
= SP_RTS_FLOW_CONTROL
;
1560 config
->cts
= SP_CTS_FLOW_CONTROL
;
1562 if (data
->termiox_supported
&& data
->rts_flow
)
1563 config
->rts
= SP_RTS_FLOW_CONTROL
;
1565 config
->rts
= (data
->controlbits
& TIOCM_RTS
) ? SP_RTS_ON
: SP_RTS_OFF
;
1567 config
->cts
= (data
->termiox_supported
&& data
->cts_flow
) ?
1568 SP_CTS_FLOW_CONTROL
: SP_CTS_IGNORE
;
1571 if (data
->termiox_supported
&& data
->dtr_flow
)
1572 config
->dtr
= SP_DTR_FLOW_CONTROL
;
1574 config
->dtr
= (data
->controlbits
& TIOCM_DTR
) ? SP_DTR_ON
: SP_DTR_OFF
;
1576 config
->dsr
= (data
->termiox_supported
&& data
->dsr_flow
) ?
1577 SP_DSR_FLOW_CONTROL
: SP_DSR_IGNORE
;
1579 if (data
->term
.c_iflag
& IXOFF
) {
1580 if (data
->term
.c_iflag
& IXON
)
1581 config
->xon_xoff
= SP_XONXOFF_INOUT
;
1583 config
->xon_xoff
= SP_XONXOFF_IN
;
1585 if (data
->term
.c_iflag
& IXON
)
1586 config
->xon_xoff
= SP_XONXOFF_OUT
;
1588 config
->xon_xoff
= SP_XONXOFF_DISABLED
;
1595 static enum sp_return
set_config(struct sp_port
*port
, struct port_data
*data
,
1596 const struct sp_port_config
*config
)
1600 BAUD_TYPE baud_nonstd
;
1604 #ifdef USE_TERMIOS_SPEED
1605 int baud_nonstd
= 0;
1608 TRACE("%p, %p, %p", port
, data
, config
);
1610 DEBUG_FMT("Setting configuration for port %s", port
->name
);
1613 if (config
->baudrate
>= 0) {
1614 for (i
= 0; i
< NUM_STD_BAUDRATES
; i
++) {
1615 if (config
->baudrate
== std_baudrates
[i
].value
) {
1616 data
->dcb
.BaudRate
= std_baudrates
[i
].index
;
1621 if (i
== NUM_STD_BAUDRATES
)
1622 data
->dcb
.BaudRate
= config
->baudrate
;
1625 if (config
->bits
>= 0)
1626 data
->dcb
.ByteSize
= config
->bits
;
1628 if (config
->parity
>= 0) {
1629 switch (config
->parity
) {
1630 case SP_PARITY_NONE
:
1631 data
->dcb
.Parity
= NOPARITY
;
1634 data
->dcb
.Parity
= ODDPARITY
;
1636 case SP_PARITY_EVEN
:
1637 data
->dcb
.Parity
= EVENPARITY
;
1639 case SP_PARITY_MARK
:
1640 data
->dcb
.Parity
= MARKPARITY
;
1642 case SP_PARITY_SPACE
:
1643 data
->dcb
.Parity
= SPACEPARITY
;
1646 RETURN_ERROR(SP_ERR_ARG
, "Invalid parity setting");
1650 if (config
->stopbits
>= 0) {
1651 switch (config
->stopbits
) {
1652 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1654 data
->dcb
.StopBits
= ONESTOPBIT
;
1657 data
->dcb
.StopBits
= TWOSTOPBITS
;
1660 RETURN_ERROR(SP_ERR_ARG
, "Invalid stop bit setting");
1664 if (config
->rts
>= 0) {
1665 switch (config
->rts
) {
1667 data
->dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
1670 data
->dcb
.fRtsControl
= RTS_CONTROL_ENABLE
;
1672 case SP_RTS_FLOW_CONTROL
:
1673 data
->dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
1676 RETURN_ERROR(SP_ERR_ARG
, "Invalid RTS setting");
1680 if (config
->cts
>= 0) {
1681 switch (config
->cts
) {
1683 data
->dcb
.fOutxCtsFlow
= FALSE
;
1685 case SP_CTS_FLOW_CONTROL
:
1686 data
->dcb
.fOutxCtsFlow
= TRUE
;
1689 RETURN_ERROR(SP_ERR_ARG
, "Invalid CTS setting");
1693 if (config
->dtr
>= 0) {
1694 switch (config
->dtr
) {
1696 data
->dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
1699 data
->dcb
.fDtrControl
= DTR_CONTROL_ENABLE
;
1701 case SP_DTR_FLOW_CONTROL
:
1702 data
->dcb
.fDtrControl
= DTR_CONTROL_HANDSHAKE
;
1705 RETURN_ERROR(SP_ERR_ARG
, "Invalid DTR setting");
1709 if (config
->dsr
>= 0) {
1710 switch (config
->dsr
) {
1712 data
->dcb
.fOutxDsrFlow
= FALSE
;
1714 case SP_DSR_FLOW_CONTROL
:
1715 data
->dcb
.fOutxDsrFlow
= TRUE
;
1718 RETURN_ERROR(SP_ERR_ARG
, "Invalid DSR setting");
1722 if (config
->xon_xoff
>= 0) {
1723 switch (config
->xon_xoff
) {
1724 case SP_XONXOFF_DISABLED
:
1725 data
->dcb
.fInX
= FALSE
;
1726 data
->dcb
.fOutX
= FALSE
;
1729 data
->dcb
.fInX
= TRUE
;
1730 data
->dcb
.fOutX
= FALSE
;
1732 case SP_XONXOFF_OUT
:
1733 data
->dcb
.fInX
= FALSE
;
1734 data
->dcb
.fOutX
= TRUE
;
1736 case SP_XONXOFF_INOUT
:
1737 data
->dcb
.fInX
= TRUE
;
1738 data
->dcb
.fOutX
= TRUE
;
1741 RETURN_ERROR(SP_ERR_ARG
, "Invalid XON/XOFF setting");
1745 if (!SetCommState(port
->hdl
, &data
->dcb
))
1746 RETURN_FAIL("SetCommState() failed");
1752 if (config
->baudrate
>= 0) {
1753 for (i
= 0; i
< NUM_STD_BAUDRATES
; i
++) {
1754 if (config
->baudrate
== std_baudrates
[i
].value
) {
1755 if (cfsetospeed(&data
->term
, std_baudrates
[i
].index
) < 0)
1756 RETURN_FAIL("cfsetospeed() failed");
1758 if (cfsetispeed(&data
->term
, std_baudrates
[i
].index
) < 0)
1759 RETURN_FAIL("cfsetispeed() failed");
1764 /* Non-standard baud rate */
1765 if (i
== NUM_STD_BAUDRATES
) {
1767 /* Set "dummy" baud rate. */
1768 if (cfsetspeed(&data
->term
, B9600
) < 0)
1769 RETURN_FAIL("cfsetspeed() failed");
1770 baud_nonstd
= config
->baudrate
;
1771 #elif defined(USE_TERMIOS_SPEED)
1774 RETURN_ERROR(SP_ERR_SUPP
, "Non-standard baudrate not supported");
1779 if (config
->bits
>= 0) {
1780 data
->term
.c_cflag
&= ~CSIZE
;
1781 switch (config
->bits
) {
1783 data
->term
.c_cflag
|= CS8
;
1786 data
->term
.c_cflag
|= CS7
;
1789 data
->term
.c_cflag
|= CS6
;
1792 data
->term
.c_cflag
|= CS5
;
1795 RETURN_ERROR(SP_ERR_ARG
, "Invalid data bits setting");
1799 if (config
->parity
>= 0) {
1800 data
->term
.c_iflag
&= ~IGNPAR
;
1801 data
->term
.c_cflag
&= ~(PARENB
| PARODD
);
1803 data
->term
.c_cflag
&= ~CMSPAR
;
1805 switch (config
->parity
) {
1806 case SP_PARITY_NONE
:
1807 data
->term
.c_iflag
|= IGNPAR
;
1809 case SP_PARITY_EVEN
:
1810 data
->term
.c_cflag
|= PARENB
;
1813 data
->term
.c_cflag
|= PARENB
| PARODD
;
1816 case SP_PARITY_MARK
:
1817 data
->term
.c_cflag
|= PARENB
| PARODD
;
1818 data
->term
.c_cflag
|= CMSPAR
;
1820 case SP_PARITY_SPACE
:
1821 data
->term
.c_cflag
|= PARENB
;
1822 data
->term
.c_cflag
|= CMSPAR
;
1825 case SP_PARITY_MARK
:
1826 case SP_PARITY_SPACE
:
1827 RETURN_ERROR(SP_ERR_SUPP
, "Mark/space parity not supported");
1830 RETURN_ERROR(SP_ERR_ARG
, "Invalid parity setting");
1834 if (config
->stopbits
>= 0) {
1835 data
->term
.c_cflag
&= ~CSTOPB
;
1836 switch (config
->stopbits
) {
1838 data
->term
.c_cflag
&= ~CSTOPB
;
1841 data
->term
.c_cflag
|= CSTOPB
;
1844 RETURN_ERROR(SP_ERR_ARG
, "Invalid stop bits setting");
1848 if (config
->rts
>= 0 || config
->cts
>= 0) {
1849 if (data
->termiox_supported
) {
1850 data
->rts_flow
= data
->cts_flow
= 0;
1851 switch (config
->rts
) {
1854 controlbits
= TIOCM_RTS
;
1855 if (ioctl(port
->fd
, config
->rts
== SP_RTS_ON
? TIOCMBIS
: TIOCMBIC
, &controlbits
) < 0)
1856 RETURN_FAIL("Setting RTS signal level failed");
1858 case SP_RTS_FLOW_CONTROL
:
1864 if (config
->cts
== SP_CTS_FLOW_CONTROL
)
1867 if (data
->rts_flow
&& data
->cts_flow
)
1868 data
->term
.c_iflag
|= CRTSCTS
;
1870 data
->term
.c_iflag
&= ~CRTSCTS
;
1872 /* Asymmetric use of RTS/CTS not supported. */
1873 if (data
->term
.c_iflag
& CRTSCTS
) {
1874 /* Flow control can only be disabled for both RTS & CTS together. */
1875 if (config
->rts
>= 0 && config
->rts
!= SP_RTS_FLOW_CONTROL
) {
1876 if (config
->cts
!= SP_CTS_IGNORE
)
1877 RETURN_ERROR(SP_ERR_SUPP
, "RTS & CTS flow control must be disabled together");
1879 if (config
->cts
>= 0 && config
->cts
!= SP_CTS_FLOW_CONTROL
) {
1880 if (config
->rts
<= 0 || config
->rts
== SP_RTS_FLOW_CONTROL
)
1881 RETURN_ERROR(SP_ERR_SUPP
, "RTS & CTS flow control must be disabled together");
1884 /* Flow control can only be enabled for both RTS & CTS together. */
1885 if (((config
->rts
== SP_RTS_FLOW_CONTROL
) && (config
->cts
!= SP_CTS_FLOW_CONTROL
)) ||
1886 ((config
->cts
== SP_CTS_FLOW_CONTROL
) && (config
->rts
!= SP_RTS_FLOW_CONTROL
)))
1887 RETURN_ERROR(SP_ERR_SUPP
, "RTS & CTS flow control must be enabled together");
1890 if (config
->rts
>= 0) {
1891 if (config
->rts
== SP_RTS_FLOW_CONTROL
) {
1892 data
->term
.c_iflag
|= CRTSCTS
;
1894 controlbits
= TIOCM_RTS
;
1895 if (ioctl(port
->fd
, config
->rts
== SP_RTS_ON
? TIOCMBIS
: TIOCMBIC
,
1897 RETURN_FAIL("Setting RTS signal level failed");
1903 if (config
->dtr
>= 0 || config
->dsr
>= 0) {
1904 if (data
->termiox_supported
) {
1905 data
->dtr_flow
= data
->dsr_flow
= 0;
1906 switch (config
->dtr
) {
1909 controlbits
= TIOCM_DTR
;
1910 if (ioctl(port
->fd
, config
->dtr
== SP_DTR_ON
? TIOCMBIS
: TIOCMBIC
, &controlbits
) < 0)
1911 RETURN_FAIL("Setting DTR signal level failed");
1913 case SP_DTR_FLOW_CONTROL
:
1919 if (config
->dsr
== SP_DSR_FLOW_CONTROL
)
1922 /* DTR/DSR flow control not supported. */
1923 if (config
->dtr
== SP_DTR_FLOW_CONTROL
|| config
->dsr
== SP_DSR_FLOW_CONTROL
)
1924 RETURN_ERROR(SP_ERR_SUPP
, "DTR/DSR flow control not supported");
1926 if (config
->dtr
>= 0) {
1927 controlbits
= TIOCM_DTR
;
1928 if (ioctl(port
->fd
, config
->dtr
== SP_DTR_ON
? TIOCMBIS
: TIOCMBIC
,
1930 RETURN_FAIL("Setting DTR signal level failed");
1935 if (config
->xon_xoff
>= 0) {
1936 data
->term
.c_iflag
&= ~(IXON
| IXOFF
| IXANY
);
1937 switch (config
->xon_xoff
) {
1938 case SP_XONXOFF_DISABLED
:
1941 data
->term
.c_iflag
|= IXOFF
;
1943 case SP_XONXOFF_OUT
:
1944 data
->term
.c_iflag
|= IXON
| IXANY
;
1946 case SP_XONXOFF_INOUT
:
1947 data
->term
.c_iflag
|= IXON
| IXOFF
| IXANY
;
1950 RETURN_ERROR(SP_ERR_ARG
, "Invalid XON/XOFF setting");
1954 if (tcsetattr(port
->fd
, TCSANOW
, &data
->term
) < 0)
1955 RETURN_FAIL("tcsetattr() failed");
1958 if (baud_nonstd
!= B0
) {
1959 if (ioctl(port
->fd
, IOSSIOSPEED
, &baud_nonstd
) == -1)
1960 RETURN_FAIL("IOSSIOSPEED ioctl failed");
1961 /* Set baud rates in data->term to correct, but incompatible
1962 * with tcsetattr() value, same as delivered by tcgetattr(). */
1963 if (cfsetspeed(&data
->term
, baud_nonstd
) < 0)
1964 RETURN_FAIL("cfsetspeed() failed");
1966 #elif defined(__linux__)
1967 #ifdef USE_TERMIOS_SPEED
1969 TRY(set_baudrate(port
->fd
, config
->baudrate
));
1972 if (data
->termiox_supported
)
1973 TRY(set_flow(port
->fd
, data
));
1977 #endif /* !_WIN32 */
1982 SP_API
enum sp_return
sp_new_config(struct sp_port_config
**config_ptr
)
1984 struct sp_port_config
*config
;
1986 TRACE("%p", config_ptr
);
1989 RETURN_ERROR(SP_ERR_ARG
, "Null result pointer");
1993 if (!(config
= malloc(sizeof(struct sp_port_config
))))
1994 RETURN_ERROR(SP_ERR_MEM
, "config malloc failed");
1996 config
->baudrate
= -1;
1998 config
->parity
= -1;
1999 config
->stopbits
= -1;
2005 *config_ptr
= config
;
2010 SP_API
void sp_free_config(struct sp_port_config
*config
)
2012 TRACE("%p", config
);
2015 DEBUG("Null config");
2022 SP_API
enum sp_return
sp_get_config(struct sp_port
*port
,
2023 struct sp_port_config
*config
)
2025 struct port_data data
;
2027 TRACE("%p, %p", port
, config
);
2032 RETURN_ERROR(SP_ERR_ARG
, "Null config");
2034 TRY(get_config(port
, &data
, config
));
2039 SP_API
enum sp_return
sp_set_config(struct sp_port
*port
,
2040 const struct sp_port_config
*config
)
2042 struct port_data data
;
2043 struct sp_port_config prev_config
;
2045 TRACE("%p, %p", port
, config
);
2050 RETURN_ERROR(SP_ERR_ARG
, "Null config");
2052 TRY(get_config(port
, &data
, &prev_config
));
2053 TRY(set_config(port
, &data
, config
));
2058 #define CREATE_ACCESSORS(x, type) \
2059 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2060 struct port_data data; \
2061 struct sp_port_config config; \
2062 TRACE("%p, %d", port, x); \
2063 CHECK_OPEN_PORT(); \
2064 TRY(get_config(port, &data, &config)); \
2066 TRY(set_config(port, &data, &config)); \
2069 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2071 TRACE("%p, %p", config, x); \
2073 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2077 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2079 TRACE("%p, %d", config, x); \
2081 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2086 CREATE_ACCESSORS(baudrate
, int)
2087 CREATE_ACCESSORS(bits
, int)
2088 CREATE_ACCESSORS(parity
, enum sp_parity
)
2089 CREATE_ACCESSORS(stopbits
, int)
2090 CREATE_ACCESSORS(rts
, enum sp_rts
)
2091 CREATE_ACCESSORS(cts
, enum sp_cts
)
2092 CREATE_ACCESSORS(dtr
, enum sp_dtr
)
2093 CREATE_ACCESSORS(dsr
, enum sp_dsr
)
2094 CREATE_ACCESSORS(xon_xoff
, enum sp_xonxoff
)
2096 SP_API
enum sp_return
sp_set_config_flowcontrol(struct sp_port_config
*config
,
2097 enum sp_flowcontrol flowcontrol
)
2100 RETURN_ERROR(SP_ERR_ARG
, "Null configuration");
2102 if (flowcontrol
> SP_FLOWCONTROL_DTRDSR
)
2103 RETURN_ERROR(SP_ERR_ARG
, "Invalid flow control setting");
2105 if (flowcontrol
== SP_FLOWCONTROL_XONXOFF
)
2106 config
->xon_xoff
= SP_XONXOFF_INOUT
;
2108 config
->xon_xoff
= SP_XONXOFF_DISABLED
;
2110 if (flowcontrol
== SP_FLOWCONTROL_RTSCTS
) {
2111 config
->rts
= SP_RTS_FLOW_CONTROL
;
2112 config
->cts
= SP_CTS_FLOW_CONTROL
;
2114 if (config
->rts
== SP_RTS_FLOW_CONTROL
)
2115 config
->rts
= SP_RTS_ON
;
2116 config
->cts
= SP_CTS_IGNORE
;
2119 if (flowcontrol
== SP_FLOWCONTROL_DTRDSR
) {
2120 config
->dtr
= SP_DTR_FLOW_CONTROL
;
2121 config
->dsr
= SP_DSR_FLOW_CONTROL
;
2123 if (config
->dtr
== SP_DTR_FLOW_CONTROL
)
2124 config
->dtr
= SP_DTR_ON
;
2125 config
->dsr
= SP_DSR_IGNORE
;
2131 SP_API
enum sp_return
sp_set_flowcontrol(struct sp_port
*port
,
2132 enum sp_flowcontrol flowcontrol
)
2134 struct port_data data
;
2135 struct sp_port_config config
;
2137 TRACE("%p, %d", port
, flowcontrol
);
2141 TRY(get_config(port
, &data
, &config
));
2143 TRY(sp_set_config_flowcontrol(&config
, flowcontrol
));
2145 TRY(set_config(port
, &data
, &config
));
2150 SP_API
enum sp_return
sp_get_signals(struct sp_port
*port
,
2151 enum sp_signal
*signals
)
2153 TRACE("%p, %p", port
, signals
);
2158 RETURN_ERROR(SP_ERR_ARG
, "Null result pointer");
2160 DEBUG_FMT("Getting control signals for port %s", port
->name
);
2165 if (GetCommModemStatus(port
->hdl
, &bits
) == 0)
2166 RETURN_FAIL("GetCommModemStatus() failed");
2167 if (bits
& MS_CTS_ON
)
2168 *signals
|= SP_SIG_CTS
;
2169 if (bits
& MS_DSR_ON
)
2170 *signals
|= SP_SIG_DSR
;
2171 if (bits
& MS_RLSD_ON
)
2172 *signals
|= SP_SIG_DCD
;
2173 if (bits
& MS_RING_ON
)
2174 *signals
|= SP_SIG_RI
;
2177 if (ioctl(port
->fd
, TIOCMGET
, &bits
) < 0)
2178 RETURN_FAIL("TIOCMGET ioctl failed");
2179 if (bits
& TIOCM_CTS
)
2180 *signals
|= SP_SIG_CTS
;
2181 if (bits
& TIOCM_DSR
)
2182 *signals
|= SP_SIG_DSR
;
2183 if (bits
& TIOCM_CAR
)
2184 *signals
|= SP_SIG_DCD
;
2185 if (bits
& TIOCM_RNG
)
2186 *signals
|= SP_SIG_RI
;
2191 SP_API
enum sp_return
sp_start_break(struct sp_port
*port
)
2197 if (SetCommBreak(port
->hdl
) == 0)
2198 RETURN_FAIL("SetCommBreak() failed");
2200 if (ioctl(port
->fd
, TIOCSBRK
, 1) < 0)
2201 RETURN_FAIL("TIOCSBRK ioctl failed");
2207 SP_API
enum sp_return
sp_end_break(struct sp_port
*port
)
2213 if (ClearCommBreak(port
->hdl
) == 0)
2214 RETURN_FAIL("ClearCommBreak() failed");
2216 if (ioctl(port
->fd
, TIOCCBRK
, 1) < 0)
2217 RETURN_FAIL("TIOCCBRK ioctl failed");
2223 SP_API
int sp_last_error_code(void)
2227 RETURN_INT(GetLastError());
2233 SP_API
char *sp_last_error_message(void)
2239 DWORD error
= GetLastError();
2242 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
2243 FORMAT_MESSAGE_FROM_SYSTEM
|
2244 FORMAT_MESSAGE_IGNORE_INSERTS
,
2247 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
2251 RETURN_STRING(message
);
2253 RETURN_STRING(strerror(errno
));
2257 SP_API
void sp_free_error_message(char *message
)
2259 TRACE("%s", message
);
2270 SP_API
void sp_set_debug_handler(void (*handler
)(const char *format
, ...))
2272 TRACE("%p", handler
);
2274 sp_debug_handler
= handler
;
2279 SP_API
void sp_default_debug_handler(const char *format
, ...)
2282 va_start(args
, format
);
2283 if (getenv("LIBSERIALPORT_DEBUG")) {
2284 fputs("sp: ", stderr
);
2285 vfprintf(stderr
, format
, args
);
2290 SP_API
int sp_get_major_package_version(void)
2292 return SP_PACKAGE_VERSION_MAJOR
;
2295 SP_API
int sp_get_minor_package_version(void)
2297 return SP_PACKAGE_VERSION_MINOR
;
2300 SP_API
int sp_get_micro_package_version(void)
2302 return SP_PACKAGE_VERSION_MICRO
;
2305 SP_API
const char *sp_get_package_version_string(void)
2307 return SP_PACKAGE_VERSION_STRING
;
2310 SP_API
int sp_get_current_lib_version(void)
2312 return SP_LIB_VERSION_CURRENT
;
2315 SP_API
int sp_get_revision_lib_version(void)
2317 return SP_LIB_VERSION_REVISION
;
2320 SP_API
int sp_get_age_lib_version(void)
2322 return SP_LIB_VERSION_AGE
;
2325 SP_API
const char *sp_get_lib_version_string(void)
2327 return SP_LIB_VERSION_STRING
;