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 static 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 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
49 void (*sp_debug_handler
)(const char *format
, ...) = sp_default_debug_handler
;
51 static enum sp_return
get_config(struct sp_port
*port
, struct port_data
*data
,
52 struct sp_port_config
*config
);
54 static enum sp_return
set_config(struct sp_port
*port
, struct port_data
*data
,
55 const struct sp_port_config
*config
);
57 SP_API
enum sp_return
sp_get_port_by_name(const char *portname
, struct sp_port
**port_ptr
)
60 #ifndef NO_PORT_METADATA
65 TRACE("%s, %p", portname
, port_ptr
);
68 RETURN_ERROR(SP_ERR_ARG
, "Null result pointer");
73 RETURN_ERROR(SP_ERR_ARG
, "Null port name");
75 DEBUG_FMT("Building structure for port %s", portname
);
77 if (!(port
= malloc(sizeof(struct sp_port
))))
78 RETURN_ERROR(SP_ERR_MEM
, "Port structure malloc failed");
80 len
= strlen(portname
) + 1;
82 if (!(port
->name
= malloc(len
))) {
84 RETURN_ERROR(SP_ERR_MEM
, "Port name malloc failed");
87 memcpy(port
->name
, portname
, len
);
90 port
->usb_path
= NULL
;
91 port
->hdl
= INVALID_HANDLE_VALUE
;
96 port
->description
= NULL
;
97 port
->transport
= SP_TRANSPORT_NATIVE
;
99 port
->usb_address
= -1;
102 port
->usb_manufacturer
= NULL
;
103 port
->usb_product
= NULL
;
104 port
->usb_serial
= NULL
;
105 port
->bluetooth_address
= NULL
;
107 #ifndef NO_PORT_METADATA
108 if ((ret
= get_port_details(port
)) != SP_OK
) {
119 SP_API
char *sp_get_port_name(const struct sp_port
*port
)
126 RETURN_STRING(port
->name
);
129 SP_API
char *sp_get_port_description(struct sp_port
*port
)
133 if (!port
|| !port
->description
)
136 RETURN_STRING(port
->description
);
139 SP_API
enum sp_transport
sp_get_port_transport(struct sp_port
*port
)
144 RETURN_ERROR(SP_ERR_ARG
, "Null port");
146 RETURN_INT(port
->transport
);
149 SP_API
enum sp_return
sp_get_port_usb_bus_address(const struct sp_port
*port
,
150 int *usb_bus
,int *usb_address
)
155 RETURN_ERROR(SP_ERR_ARG
, "Null port");
156 if (port
->transport
!= SP_TRANSPORT_USB
)
157 RETURN_ERROR(SP_ERR_ARG
, "Port does not use USB transport");
158 if (port
->usb_bus
< 0 || port
->usb_address
< 0)
159 RETURN_ERROR(SP_ERR_SUPP
, "Bus and address values are not available");
162 *usb_bus
= port
->usb_bus
;
164 *usb_address
= port
->usb_address
;
169 SP_API
enum sp_return
sp_get_port_usb_vid_pid(const struct sp_port
*port
,
170 int *usb_vid
, int *usb_pid
)
175 RETURN_ERROR(SP_ERR_ARG
, "Null port");
176 if (port
->transport
!= SP_TRANSPORT_USB
)
177 RETURN_ERROR(SP_ERR_ARG
, "Port does not use USB transport");
178 if (port
->usb_vid
< 0 || port
->usb_pid
< 0)
179 RETURN_ERROR(SP_ERR_SUPP
, "VID:PID values are not available");
182 *usb_vid
= port
->usb_vid
;
184 *usb_pid
= port
->usb_pid
;
189 SP_API
char *sp_get_port_usb_manufacturer(const struct sp_port
*port
)
193 if (!port
|| port
->transport
!= SP_TRANSPORT_USB
|| !port
->usb_manufacturer
)
196 RETURN_STRING(port
->usb_manufacturer
);
199 SP_API
char *sp_get_port_usb_product(const struct sp_port
*port
)
203 if (!port
|| port
->transport
!= SP_TRANSPORT_USB
|| !port
->usb_product
)
206 RETURN_STRING(port
->usb_product
);
209 SP_API
char *sp_get_port_usb_serial(const struct sp_port
*port
)
213 if (!port
|| port
->transport
!= SP_TRANSPORT_USB
|| !port
->usb_serial
)
216 RETURN_STRING(port
->usb_serial
);
219 SP_API
char *sp_get_port_bluetooth_address(const struct sp_port
*port
)
223 if (!port
|| port
->transport
!= SP_TRANSPORT_BLUETOOTH
224 || !port
->bluetooth_address
)
227 RETURN_STRING(port
->bluetooth_address
);
230 SP_API
enum sp_return
sp_get_port_handle(const struct sp_port
*port
,
233 TRACE("%p, %p", port
, result_ptr
);
236 RETURN_ERROR(SP_ERR_ARG
, "Null port");
239 HANDLE
*handle_ptr
= result_ptr
;
240 *handle_ptr
= port
->hdl
;
242 int *fd_ptr
= result_ptr
;
249 SP_API
enum sp_return
sp_copy_port(const struct sp_port
*port
,
250 struct sp_port
**copy_ptr
)
252 TRACE("%p, %p", port
, copy_ptr
);
255 RETURN_ERROR(SP_ERR_ARG
, "Null result pointer");
260 RETURN_ERROR(SP_ERR_ARG
, "Null port");
263 RETURN_ERROR(SP_ERR_ARG
, "Null port name");
265 DEBUG("Copying port structure");
267 RETURN_INT(sp_get_port_by_name(port
->name
, copy_ptr
));
270 SP_API
void sp_free_port(struct sp_port
*port
)
279 DEBUG("Freeing port structure");
283 if (port
->description
)
284 free(port
->description
);
285 if (port
->usb_manufacturer
)
286 free(port
->usb_manufacturer
);
287 if (port
->usb_product
)
288 free(port
->usb_product
);
289 if (port
->usb_serial
)
290 free(port
->usb_serial
);
291 if (port
->bluetooth_address
)
292 free(port
->bluetooth_address
);
295 free(port
->usb_path
);
303 SP_PRIV
struct sp_port
**list_append(struct sp_port
**list
,
304 const char *portname
)
309 for (count
= 0; list
[count
]; count
++);
310 if (!(tmp
= realloc(list
, sizeof(struct sp_port
*) * (count
+ 2))))
313 if (sp_get_port_by_name(portname
, &list
[count
]) != SP_OK
)
315 list
[count
+ 1] = NULL
;
319 sp_free_port_list(list
);
323 SP_API
enum sp_return
sp_list_ports(struct sp_port
***list_ptr
)
325 struct sp_port
**list
;
328 TRACE("%p", list_ptr
);
331 RETURN_ERROR(SP_ERR_ARG
, "Null result pointer");
333 #ifdef NO_ENUMERATION
334 RETURN_ERROR(SP_ERR_SUPP
, "Enumeration not supported on this platform");
336 DEBUG("Enumerating ports");
338 if (!(list
= malloc(sizeof(struct sp_port
*))))
339 RETURN_ERROR(SP_ERR_MEM
, "Port list malloc failed");
343 ret
= list_ports(&list
);
348 sp_free_port_list(list
);
356 SP_API
void sp_free_port_list(struct sp_port
**list
)
367 DEBUG("Freeing port list");
369 for (i
= 0; list
[i
]; i
++)
370 sp_free_port(list
[i
]);
376 #define CHECK_PORT() do { \
378 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
380 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
383 #define CHECK_PORT_HANDLE() do { \
384 if (port->hdl == INVALID_HANDLE_VALUE) \
385 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
388 #define CHECK_PORT_HANDLE() do { \
390 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
393 #define CHECK_OPEN_PORT() do { \
395 CHECK_PORT_HANDLE(); \
399 /** To be called after port receive buffer is emptied. */
400 static enum sp_return
restart_wait(struct sp_port
*port
)
404 if (port
->wait_running
) {
405 /* Check status of running wait operation. */
406 if (GetOverlappedResult(port
->hdl
, &port
->wait_ovl
,
407 &wait_result
, FALSE
)) {
408 DEBUG("Previous wait completed");
409 port
->wait_running
= FALSE
;
410 } else if (GetLastError() == ERROR_IO_INCOMPLETE
) {
411 DEBUG("Previous wait still running");
414 RETURN_FAIL("GetOverlappedResult() failed");
418 if (!port
->wait_running
) {
419 /* Start new wait operation. */
420 if (WaitCommEvent(port
->hdl
, &port
->events
,
422 DEBUG("New wait returned, events already pending");
423 } else if (GetLastError() == ERROR_IO_PENDING
) {
424 DEBUG("New wait running in background");
425 port
->wait_running
= TRUE
;
427 RETURN_FAIL("WaitCommEvent() failed");
435 SP_API
enum sp_return
sp_open(struct sp_port
*port
, enum sp_mode flags
)
437 struct port_data data
;
438 struct sp_port_config config
;
441 TRACE("%p, 0x%x", port
, flags
);
445 if (flags
> SP_MODE_READ_WRITE
)
446 RETURN_ERROR(SP_ERR_ARG
, "Invalid flags");
448 DEBUG_FMT("Opening port %s", port
->name
);
451 DWORD desired_access
= 0, flags_and_attributes
= 0, errors
;
452 char *escaped_port_name
;
455 /* Prefix port name with '\\.\' to work with ports above COM9. */
456 if (!(escaped_port_name
= malloc(strlen(port
->name
) + 5)))
457 RETURN_ERROR(SP_ERR_MEM
, "Escaped port name malloc failed");
458 sprintf(escaped_port_name
, "\\\\.\\%s", port
->name
);
460 /* Map 'flags' to the OS-specific settings. */
461 flags_and_attributes
= FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_OVERLAPPED
;
462 if (flags
& SP_MODE_READ
)
463 desired_access
|= GENERIC_READ
;
464 if (flags
& SP_MODE_WRITE
)
465 desired_access
|= GENERIC_WRITE
;
467 port
->hdl
= CreateFile(escaped_port_name
, desired_access
, 0, 0,
468 OPEN_EXISTING
, flags_and_attributes
, 0);
470 free(escaped_port_name
);
472 if (port
->hdl
== INVALID_HANDLE_VALUE
)
473 RETURN_FAIL("Port CreateFile() failed");
475 /* All timeouts initially disabled. */
476 port
->timeouts
.ReadIntervalTimeout
= 0;
477 port
->timeouts
.ReadTotalTimeoutMultiplier
= 0;
478 port
->timeouts
.ReadTotalTimeoutConstant
= 0;
479 port
->timeouts
.WriteTotalTimeoutMultiplier
= 0;
480 port
->timeouts
.WriteTotalTimeoutConstant
= 0;
482 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0) {
484 RETURN_FAIL("SetCommTimeouts() failed");
487 /* Prepare OVERLAPPED structures. */
488 #define INIT_OVERLAPPED(ovl) do { \
489 memset(&port->ovl, 0, sizeof(port->ovl)); \
490 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
491 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
492 == INVALID_HANDLE_VALUE) { \
494 RETURN_FAIL(#ovl "CreateEvent() failed"); \
498 INIT_OVERLAPPED(read_ovl
);
499 INIT_OVERLAPPED(write_ovl
);
500 INIT_OVERLAPPED(wait_ovl
);
502 /* Set event mask for RX and error events. */
503 if (SetCommMask(port
->hdl
, EV_RXCHAR
| EV_ERR
) == 0) {
505 RETURN_FAIL("SetCommMask() failed");
508 port
->writing
= FALSE
;
509 port
->wait_running
= FALSE
;
511 ret
= restart_wait(port
);
518 int flags_local
= O_NONBLOCK
| O_NOCTTY
;
520 /* Map 'flags' to the OS-specific settings. */
521 if ((flags
& SP_MODE_READ_WRITE
) == SP_MODE_READ_WRITE
)
522 flags_local
|= O_RDWR
;
523 else if (flags
& SP_MODE_READ
)
524 flags_local
|= O_RDONLY
;
525 else if (flags
& SP_MODE_WRITE
)
526 flags_local
|= O_WRONLY
;
528 if ((port
->fd
= open(port
->name
, flags_local
)) < 0)
529 RETURN_FAIL("open() failed");
532 ret
= get_config(port
, &data
, &config
);
539 /* Set sane port settings. */
541 data
.dcb
.fBinary
= TRUE
;
542 data
.dcb
.fDsrSensitivity
= FALSE
;
543 data
.dcb
.fErrorChar
= FALSE
;
544 data
.dcb
.fNull
= FALSE
;
545 data
.dcb
.fAbortOnError
= FALSE
;
547 /* Turn off all fancy termios tricks, give us a raw channel. */
548 data
.term
.c_iflag
&= ~(IGNBRK
| BRKINT
| PARMRK
| ISTRIP
| INLCR
| IGNCR
| ICRNL
| IMAXBEL
);
550 data
.term
.c_iflag
&= ~IUCLC
;
552 data
.term
.c_oflag
&= ~(OPOST
| ONLCR
| OCRNL
| ONOCR
| ONLRET
);
554 data
.term
.c_oflag
&= ~OLCUC
;
557 data
.term
.c_oflag
&= ~NLDLY
;
560 data
.term
.c_oflag
&= ~CRDLY
;
563 data
.term
.c_oflag
&= ~TABDLY
;
566 data
.term
.c_oflag
&= ~BSDLY
;
569 data
.term
.c_oflag
&= ~VTDLY
;
572 data
.term
.c_oflag
&= ~FFDLY
;
575 data
.term
.c_oflag
&= ~OFILL
;
577 data
.term
.c_lflag
&= ~(ISIG
| ICANON
| ECHO
| IEXTEN
);
578 data
.term
.c_cc
[VMIN
] = 0;
579 data
.term
.c_cc
[VTIME
] = 0;
581 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
582 data
.term
.c_cflag
|= (CLOCAL
| CREAD
| HUPCL
);
586 if (ClearCommError(port
->hdl
, &errors
, &status
) == 0)
587 RETURN_FAIL("ClearCommError() failed");
590 ret
= set_config(port
, &data
, &config
);
600 SP_API
enum sp_return
sp_close(struct sp_port
*port
)
606 DEBUG_FMT("Closing port %s", port
->name
);
609 /* Returns non-zero upon success, 0 upon failure. */
610 if (CloseHandle(port
->hdl
) == 0)
611 RETURN_FAIL("Port CloseHandle() failed");
612 port
->hdl
= INVALID_HANDLE_VALUE
;
614 /* Close event handles for overlapped structures. */
615 #define CLOSE_OVERLAPPED(ovl) do { \
616 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
617 CloseHandle(port->ovl.hEvent) == 0) \
618 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
620 CLOSE_OVERLAPPED(read_ovl
);
621 CLOSE_OVERLAPPED(write_ovl
);
622 CLOSE_OVERLAPPED(wait_ovl
);
625 /* Returns 0 upon success, -1 upon failure. */
626 if (close(port
->fd
) == -1)
627 RETURN_FAIL("close() failed");
634 SP_API
enum sp_return
sp_flush(struct sp_port
*port
, enum sp_buffer buffers
)
636 TRACE("%p, 0x%x", port
, buffers
);
640 if (buffers
> SP_BUF_BOTH
)
641 RETURN_ERROR(SP_ERR_ARG
, "Invalid buffer selection");
643 const char *buffer_names
[] = {"no", "input", "output", "both"};
645 DEBUG_FMT("Flushing %s buffers on port %s",
646 buffer_names
[buffers
], port
->name
);
650 if (buffers
& SP_BUF_INPUT
)
651 flags
|= PURGE_RXCLEAR
;
652 if (buffers
& SP_BUF_OUTPUT
)
653 flags
|= PURGE_TXCLEAR
;
655 /* Returns non-zero upon success, 0 upon failure. */
656 if (PurgeComm(port
->hdl
, flags
) == 0)
657 RETURN_FAIL("PurgeComm() failed");
659 if (buffers
& SP_BUF_INPUT
)
660 TRY(restart_wait(port
));
663 if (buffers
== SP_BUF_BOTH
)
665 else if (buffers
== SP_BUF_INPUT
)
667 else if (buffers
== SP_BUF_OUTPUT
)
670 /* Returns 0 upon success, -1 upon failure. */
671 if (tcflush(port
->fd
, flags
) < 0)
672 RETURN_FAIL("tcflush() failed");
677 SP_API
enum sp_return
sp_drain(struct sp_port
*port
)
683 DEBUG_FMT("Draining port %s", port
->name
);
686 /* Returns non-zero upon success, 0 upon failure. */
687 if (FlushFileBuffers(port
->hdl
) == 0)
688 RETURN_FAIL("FlushFileBuffers() failed");
695 result
= ioctl(port
->fd
, TCSBRK
, &arg
);
697 result
= tcdrain(port
->fd
);
700 if (errno
== EINTR
) {
701 DEBUG("tcdrain() was interrupted");
704 RETURN_FAIL("tcdrain() failed");
713 SP_API
enum sp_return
sp_blocking_write(struct sp_port
*port
, const void *buf
,
714 size_t count
, unsigned int timeout
)
716 TRACE("%p, %p, %d, %d", port
, buf
, count
, timeout
);
721 RETURN_ERROR(SP_ERR_ARG
, "Null buffer");
724 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
725 count
, port
->name
, timeout
);
727 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
734 DWORD bytes_written
= 0;
737 /* Wait for previous non-blocking write to complete, if any. */
739 DEBUG("Waiting for previous write to complete");
740 result
= GetOverlappedResult(port
->hdl
, &port
->write_ovl
, &bytes_written
, TRUE
);
743 RETURN_FAIL("Previous write failed to complete");
744 DEBUG("Previous write completed");
748 port
->timeouts
.WriteTotalTimeoutConstant
= timeout
;
749 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0)
750 RETURN_FAIL("SetCommTimeouts() failed");
753 if (WriteFile(port
->hdl
, buf
, count
, NULL
, &port
->write_ovl
) == 0) {
754 if (GetLastError() == ERROR_IO_PENDING
) {
755 DEBUG("Waiting for write to complete");
756 GetOverlappedResult(port
->hdl
, &port
->write_ovl
, &bytes_written
, TRUE
);
757 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written
, count
);
758 RETURN_INT(bytes_written
);
760 RETURN_FAIL("WriteFile() failed");
763 DEBUG("Write completed immediately");
767 size_t bytes_written
= 0;
768 unsigned char *ptr
= (unsigned char *) buf
;
769 struct timeval start
, delta
, now
, end
= {0, 0};
774 /* Get time at start of operation. */
775 gettimeofday(&start
, NULL
);
776 /* Define duration of timeout. */
777 delta
.tv_sec
= timeout
/ 1000;
778 delta
.tv_usec
= (timeout
% 1000) * 1000;
779 /* Calculate time at which we should give up. */
780 timeradd(&start
, &delta
, &end
);
783 /* Loop until we have written the requested number of bytes. */
784 while (bytes_written
< count
) {
785 /* Wait until space is available. */
787 FD_SET(port
->fd
, &fds
);
789 gettimeofday(&now
, NULL
);
790 if (timercmp(&now
, &end
, >)) {
791 DEBUG("Write timed out");
792 RETURN_INT(bytes_written
);
794 timersub(&end
, &now
, &delta
);
796 result
= select(port
->fd
+ 1, NULL
, &fds
, NULL
, timeout
? &delta
: NULL
);
798 if (errno
== EINTR
) {
799 DEBUG("select() call was interrupted, repeating");
802 RETURN_FAIL("select() failed");
804 } else if (result
== 0) {
805 DEBUG("Write timed out");
806 RETURN_INT(bytes_written
);
810 result
= write(port
->fd
, ptr
, count
- bytes_written
);
814 /* This shouldn't happen because we did a select() first, but handle anyway. */
817 /* This is an actual failure. */
818 RETURN_FAIL("write() failed");
821 bytes_written
+= result
;
825 RETURN_INT(bytes_written
);
829 SP_API
enum sp_return
sp_nonblocking_write(struct sp_port
*port
,
830 const void *buf
, size_t count
)
832 TRACE("%p, %p, %d", port
, buf
, count
);
837 RETURN_ERROR(SP_ERR_ARG
, "Null buffer");
839 DEBUG_FMT("Writing up to %d bytes to port %s", count
, port
->name
);
846 BYTE
*ptr
= (BYTE
*) buf
;
848 /* Check whether previous write is complete. */
850 if (HasOverlappedIoCompleted(&port
->write_ovl
)) {
851 DEBUG("Previous write completed");
854 DEBUG("Previous write not complete");
855 /* Can't take a new write until the previous one finishes. */
861 port
->timeouts
.WriteTotalTimeoutConstant
= 0;
862 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0)
863 RETURN_FAIL("SetCommTimeouts() failed");
866 * Keep writing data until the OS has to actually start an async IO
867 * for it. At that point we know the buffer is full.
869 while (written
< count
) {
870 /* Copy first byte of user buffer. */
871 port
->pending_byte
= *ptr
++;
873 /* Start asynchronous write. */
874 if (WriteFile(port
->hdl
, &port
->pending_byte
, 1, NULL
, &port
->write_ovl
) == 0) {
875 if (GetLastError() == ERROR_IO_PENDING
) {
876 if (HasOverlappedIoCompleted(&port
->write_ovl
)) {
877 DEBUG("Asynchronous write completed immediately");
882 DEBUG("Asynchronous write running");
884 RETURN_INT(++written
);
887 /* Actual failure of some kind. */
888 RETURN_FAIL("WriteFile() failed");
891 DEBUG("Single byte written immediately");
896 DEBUG("All bytes written immediately");
900 /* Returns the number of bytes written, or -1 upon failure. */
901 ssize_t written
= write(port
->fd
, buf
, count
);
904 RETURN_FAIL("write() failed");
910 SP_API
enum sp_return
sp_blocking_read(struct sp_port
*port
, void *buf
,
911 size_t count
, unsigned int timeout
)
913 TRACE("%p, %p, %d, %d", port
, buf
, count
, timeout
);
918 RETURN_ERROR(SP_ERR_ARG
, "Null buffer");
921 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
922 count
, port
->name
, timeout
);
924 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
931 DWORD bytes_read
= 0;
932 DWORD bytes_remaining
;
936 port
->timeouts
.ReadIntervalTimeout
= 0;
937 port
->timeouts
.ReadTotalTimeoutConstant
= timeout
;
938 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0)
939 RETURN_FAIL("SetCommTimeouts() failed");
942 if (ReadFile(port
->hdl
, buf
, count
, NULL
, &port
->read_ovl
) == 0) {
943 if (GetLastError() == ERROR_IO_PENDING
) {
944 DEBUG("Waiting for read to complete");
945 GetOverlappedResult(port
->hdl
, &port
->read_ovl
, &bytes_read
, TRUE
);
946 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read
, count
);
948 RETURN_FAIL("ReadFile() failed");
951 DEBUG("Read completed immediately");
955 ret
= sp_input_waiting(port
);
960 bytes_remaining
= ret
;
962 /* Restart wait operation if buffer was emptied. */
963 if (bytes_read
> 0 && bytes_remaining
== 0)
964 TRY(restart_wait(port
));
966 RETURN_INT(bytes_read
);
969 size_t bytes_read
= 0;
970 unsigned char *ptr
= (unsigned char *) buf
;
971 struct timeval start
, delta
, now
, end
= {0, 0};
976 /* Get time at start of operation. */
977 gettimeofday(&start
, NULL
);
978 /* Define duration of timeout. */
979 delta
.tv_sec
= timeout
/ 1000;
980 delta
.tv_usec
= (timeout
% 1000) * 1000;
981 /* Calculate time at which we should give up. */
982 timeradd(&start
, &delta
, &end
);
985 /* Loop until we have the requested number of bytes. */
986 while (bytes_read
< count
) {
987 /* Wait until data is available. */
989 FD_SET(port
->fd
, &fds
);
991 gettimeofday(&now
, NULL
);
992 if (timercmp(&now
, &end
, >))
993 /* Timeout has expired. */
994 RETURN_INT(bytes_read
);
995 timersub(&end
, &now
, &delta
);
997 result
= select(port
->fd
+ 1, &fds
, NULL
, NULL
, timeout
? &delta
: NULL
);
999 if (errno
== EINTR
) {
1000 DEBUG("select() call was interrupted, repeating");
1003 RETURN_FAIL("select() failed");
1005 } else if (result
== 0) {
1006 DEBUG("Read timed out");
1007 RETURN_INT(bytes_read
);
1011 result
= read(port
->fd
, ptr
, count
- bytes_read
);
1014 if (errno
== EAGAIN
)
1015 /* This shouldn't happen because we did a select() first, but handle anyway. */
1018 /* This is an actual failure. */
1019 RETURN_FAIL("read() failed");
1022 bytes_read
+= result
;
1026 RETURN_INT(bytes_read
);
1030 SP_API
enum sp_return
sp_nonblocking_read(struct sp_port
*port
, void *buf
,
1033 TRACE("%p, %p, %d", port
, buf
, count
);
1038 RETURN_ERROR(SP_ERR_ARG
, "Null buffer");
1040 DEBUG_FMT("Reading up to %d bytes from port %s", count
, port
->name
);
1044 DWORD bytes_remaining
;
1048 port
->timeouts
.ReadIntervalTimeout
= MAXDWORD
;
1049 port
->timeouts
.ReadTotalTimeoutConstant
= 0;
1050 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0)
1051 RETURN_FAIL("SetCommTimeouts() failed");
1054 if (ReadFile(port
->hdl
, buf
, count
, NULL
, &port
->read_ovl
) == 0)
1055 RETURN_FAIL("ReadFile() failed");
1057 /* Get number of bytes read. */
1058 if (GetOverlappedResult(port
->hdl
, &port
->read_ovl
, &bytes_read
, TRUE
) == 0)
1059 RETURN_FAIL("GetOverlappedResult() failed");
1061 ret
= sp_input_waiting(port
);
1064 RETURN_CODEVAL(ret
);
1066 bytes_remaining
= ret
;
1068 /* Restart wait operation if buffer was emptied. */
1069 if (bytes_read
> 0 && bytes_remaining
== 0)
1070 TRY(restart_wait(port
));
1072 RETURN_INT(bytes_read
);
1076 /* Returns the number of bytes read, or -1 upon failure. */
1077 if ((bytes_read
= read(port
->fd
, buf
, count
)) < 0) {
1078 if (errno
== EAGAIN
)
1079 /* No bytes available. */
1082 /* This is an actual failure. */
1083 RETURN_FAIL("read() failed");
1085 RETURN_INT(bytes_read
);
1089 SP_API
enum sp_return
sp_input_waiting(struct sp_port
*port
)
1095 DEBUG_FMT("Checking input bytes waiting on port %s", port
->name
);
1101 if (ClearCommError(port
->hdl
, &errors
, &comstat
) == 0)
1102 RETURN_FAIL("ClearCommError() failed");
1103 RETURN_INT(comstat
.cbInQue
);
1106 if (ioctl(port
->fd
, TIOCINQ
, &bytes_waiting
) < 0)
1107 RETURN_FAIL("TIOCINQ ioctl failed");
1108 RETURN_INT(bytes_waiting
);
1112 SP_API
enum sp_return
sp_output_waiting(struct sp_port
*port
)
1118 DEBUG_FMT("Checking output bytes waiting on port %s", port
->name
);
1124 if (ClearCommError(port
->hdl
, &errors
, &comstat
) == 0)
1125 RETURN_FAIL("ClearCommError() failed");
1126 RETURN_INT(comstat
.cbOutQue
);
1129 if (ioctl(port
->fd
, TIOCOUTQ
, &bytes_waiting
) < 0)
1130 RETURN_FAIL("TIOCOUTQ ioctl failed");
1131 RETURN_INT(bytes_waiting
);
1135 SP_API
enum sp_return
sp_new_event_set(struct sp_event_set
**result_ptr
)
1137 struct sp_event_set
*result
;
1139 TRACE("%p", result_ptr
);
1142 RETURN_ERROR(SP_ERR_ARG
, "Null result");
1146 if (!(result
= malloc(sizeof(struct sp_event_set
))))
1147 RETURN_ERROR(SP_ERR_MEM
, "sp_event_set malloc() failed");
1149 memset(result
, 0, sizeof(struct sp_event_set
));
1151 *result_ptr
= result
;
1156 static enum sp_return
add_handle(struct sp_event_set
*event_set
,
1157 event_handle handle
, enum sp_event mask
)
1160 enum sp_event
*new_masks
;
1162 TRACE("%p, %d, %d", event_set
, handle
, mask
);
1164 if (!(new_handles
= realloc(event_set
->handles
,
1165 sizeof(event_handle
) * (event_set
->count
+ 1))))
1166 RETURN_ERROR(SP_ERR_MEM
, "Handle array realloc() failed");
1168 if (!(new_masks
= realloc(event_set
->masks
,
1169 sizeof(enum sp_event
) * (event_set
->count
+ 1))))
1170 RETURN_ERROR(SP_ERR_MEM
, "Mask array realloc() failed");
1172 event_set
->handles
= new_handles
;
1173 event_set
->masks
= new_masks
;
1175 ((event_handle
*) event_set
->handles
)[event_set
->count
] = handle
;
1176 event_set
->masks
[event_set
->count
] = mask
;
1183 SP_API
enum sp_return
sp_add_port_events(struct sp_event_set
*event_set
,
1184 const struct sp_port
*port
, enum sp_event mask
)
1186 TRACE("%p, %p, %d", event_set
, port
, mask
);
1189 RETURN_ERROR(SP_ERR_ARG
, "Null event set");
1192 RETURN_ERROR(SP_ERR_ARG
, "Null port");
1194 if (mask
> (SP_EVENT_RX_READY
| SP_EVENT_TX_READY
| SP_EVENT_ERROR
))
1195 RETURN_ERROR(SP_ERR_ARG
, "Invalid event mask");
1201 enum sp_event handle_mask
;
1202 if ((handle_mask
= mask
& SP_EVENT_TX_READY
))
1203 TRY(add_handle(event_set
, port
->write_ovl
.hEvent
, handle_mask
));
1204 if ((handle_mask
= mask
& (SP_EVENT_RX_READY
| SP_EVENT_ERROR
)))
1205 TRY(add_handle(event_set
, port
->wait_ovl
.hEvent
, handle_mask
));
1207 TRY(add_handle(event_set
, port
->fd
, mask
));
1213 SP_API
void sp_free_event_set(struct sp_event_set
*event_set
)
1215 TRACE("%p", event_set
);
1218 DEBUG("Null event set");
1222 DEBUG("Freeing event set");
1224 if (event_set
->handles
)
1225 free(event_set
->handles
);
1226 if (event_set
->masks
)
1227 free(event_set
->masks
);
1234 SP_API
enum sp_return
sp_wait(struct sp_event_set
*event_set
,
1235 unsigned int timeout
)
1237 TRACE("%p, %d", event_set
, timeout
);
1240 RETURN_ERROR(SP_ERR_ARG
, "Null event set");
1243 if (WaitForMultipleObjects(event_set
->count
, event_set
->handles
, FALSE
,
1244 timeout
? timeout
: INFINITE
) == WAIT_FAILED
)
1245 RETURN_FAIL("WaitForMultipleObjects() failed");
1249 struct timeval start
, delta
, now
, end
= {0, 0};
1250 int result
, timeout_remaining
;
1251 struct pollfd
*pollfds
;
1254 if (!(pollfds
= malloc(sizeof(struct pollfd
) * event_set
->count
)))
1255 RETURN_ERROR(SP_ERR_MEM
, "pollfds malloc() failed");
1257 for (i
= 0; i
< event_set
->count
; i
++) {
1258 pollfds
[i
].fd
= ((int *) event_set
->handles
)[i
];
1259 pollfds
[i
].events
= 0;
1260 pollfds
[i
].revents
= 0;
1261 if (event_set
->masks
[i
] & SP_EVENT_RX_READY
)
1262 pollfds
[i
].events
|= POLLIN
;
1263 if (event_set
->masks
[i
] & SP_EVENT_TX_READY
)
1264 pollfds
[i
].events
|= POLLOUT
;
1265 if (event_set
->masks
[i
] & SP_EVENT_ERROR
)
1266 pollfds
[i
].events
|= POLLERR
;
1270 /* Get time at start of operation. */
1271 gettimeofday(&start
, NULL
);
1272 /* Define duration of timeout. */
1273 delta
.tv_sec
= timeout
/ 1000;
1274 delta
.tv_usec
= (timeout
% 1000) * 1000;
1275 /* Calculate time at which we should give up. */
1276 timeradd(&start
, &delta
, &end
);
1279 /* Loop until an event occurs. */
1282 gettimeofday(&now
, NULL
);
1283 if (timercmp(&now
, &end
, >)) {
1284 DEBUG("Wait timed out");
1287 timersub(&end
, &now
, &delta
);
1288 timeout_remaining
= delta
.tv_sec
* 1000 + delta
.tv_usec
/ 1000;
1291 result
= poll(pollfds
, event_set
->count
, timeout
? timeout_remaining
: -1);
1294 if (errno
== EINTR
) {
1295 DEBUG("poll() call was interrupted, repeating");
1299 RETURN_FAIL("poll() failed");
1301 } else if (result
== 0) {
1302 DEBUG("poll() timed out");
1305 DEBUG("poll() completed");
1315 #ifdef USE_TERMIOS_SPEED
1316 static enum sp_return
get_baudrate(int fd
, int *baudrate
)
1320 TRACE("%d, %p", fd
, baudrate
);
1322 DEBUG("Getting baud rate");
1324 if (!(data
= malloc(get_termios_size())))
1325 RETURN_ERROR(SP_ERR_MEM
, "termios malloc failed");
1327 if (ioctl(fd
, get_termios_get_ioctl(), data
) < 0) {
1329 RETURN_FAIL("Getting termios failed");
1332 *baudrate
= get_termios_speed(data
);
1339 static enum sp_return
set_baudrate(int fd
, int baudrate
)
1343 TRACE("%d, %d", fd
, baudrate
);
1345 DEBUG("Getting baud rate");
1347 if (!(data
= malloc(get_termios_size())))
1348 RETURN_ERROR(SP_ERR_MEM
, "termios malloc failed");
1350 if (ioctl(fd
, get_termios_get_ioctl(), data
) < 0) {
1352 RETURN_FAIL("Getting termios failed");
1355 DEBUG("Setting baud rate");
1357 set_termios_speed(data
, baudrate
);
1359 if (ioctl(fd
, get_termios_set_ioctl(), data
) < 0) {
1361 RETURN_FAIL("Setting termios failed");
1368 #endif /* USE_TERMIOS_SPEED */
1371 static enum sp_return
get_flow(int fd
, struct port_data
*data
)
1375 TRACE("%d, %p", fd
, data
);
1377 DEBUG("Getting advanced flow control");
1379 if (!(termx
= malloc(get_termiox_size())))
1380 RETURN_ERROR(SP_ERR_MEM
, "termiox malloc failed");
1382 if (ioctl(fd
, TCGETX
, termx
) < 0) {
1384 RETURN_FAIL("Getting termiox failed");
1387 get_termiox_flow(termx
, &data
->rts_flow
, &data
->cts_flow
,
1388 &data
->dtr_flow
, &data
->dsr_flow
);
1395 static enum sp_return
set_flow(int fd
, struct port_data
*data
)
1399 TRACE("%d, %p", fd
, data
);
1401 DEBUG("Getting advanced flow control");
1403 if (!(termx
= malloc(get_termiox_size())))
1404 RETURN_ERROR(SP_ERR_MEM
, "termiox malloc failed");
1406 if (ioctl(fd
, TCGETX
, termx
) < 0) {
1408 RETURN_FAIL("Getting termiox failed");
1411 DEBUG("Setting advanced flow control");
1413 set_termiox_flow(termx
, data
->rts_flow
, data
->cts_flow
,
1414 data
->dtr_flow
, data
->dsr_flow
);
1416 if (ioctl(fd
, TCSETX
, termx
) < 0) {
1418 RETURN_FAIL("Setting termiox failed");
1425 #endif /* USE_TERMIOX */
1427 static enum sp_return
get_config(struct sp_port
*port
, struct port_data
*data
,
1428 struct sp_port_config
*config
)
1432 TRACE("%p, %p, %p", port
, data
, config
);
1434 DEBUG_FMT("Getting configuration for port %s", port
->name
);
1437 if (!GetCommState(port
->hdl
, &data
->dcb
))
1438 RETURN_FAIL("GetCommState() failed");
1440 for (i
= 0; i
< NUM_STD_BAUDRATES
; i
++) {
1441 if (data
->dcb
.BaudRate
== std_baudrates
[i
].index
) {
1442 config
->baudrate
= std_baudrates
[i
].value
;
1447 if (i
== NUM_STD_BAUDRATES
)
1448 /* BaudRate field can be either an index or a custom baud rate. */
1449 config
->baudrate
= data
->dcb
.BaudRate
;
1451 config
->bits
= data
->dcb
.ByteSize
;
1453 if (data
->dcb
.fParity
)
1454 switch (data
->dcb
.Parity
) {
1456 config
->parity
= SP_PARITY_NONE
;
1459 config
->parity
= SP_PARITY_ODD
;
1462 config
->parity
= SP_PARITY_EVEN
;
1465 config
->parity
= SP_PARITY_MARK
;
1468 config
->parity
= SP_PARITY_SPACE
;
1471 config
->parity
= -1;
1474 config
->parity
= SP_PARITY_NONE
;
1476 switch (data
->dcb
.StopBits
) {
1478 config
->stopbits
= 1;
1481 config
->stopbits
= 2;
1484 config
->stopbits
= -1;
1487 switch (data
->dcb
.fRtsControl
) {
1488 case RTS_CONTROL_DISABLE
:
1489 config
->rts
= SP_RTS_OFF
;
1491 case RTS_CONTROL_ENABLE
:
1492 config
->rts
= SP_RTS_ON
;
1494 case RTS_CONTROL_HANDSHAKE
:
1495 config
->rts
= SP_RTS_FLOW_CONTROL
;
1501 config
->cts
= data
->dcb
.fOutxCtsFlow
? SP_CTS_FLOW_CONTROL
: SP_CTS_IGNORE
;
1503 switch (data
->dcb
.fDtrControl
) {
1504 case DTR_CONTROL_DISABLE
:
1505 config
->dtr
= SP_DTR_OFF
;
1507 case DTR_CONTROL_ENABLE
:
1508 config
->dtr
= SP_DTR_ON
;
1510 case DTR_CONTROL_HANDSHAKE
:
1511 config
->dtr
= SP_DTR_FLOW_CONTROL
;
1517 config
->dsr
= data
->dcb
.fOutxDsrFlow
? SP_DSR_FLOW_CONTROL
: SP_DSR_IGNORE
;
1519 if (data
->dcb
.fInX
) {
1520 if (data
->dcb
.fOutX
)
1521 config
->xon_xoff
= SP_XONXOFF_INOUT
;
1523 config
->xon_xoff
= SP_XONXOFF_IN
;
1525 if (data
->dcb
.fOutX
)
1526 config
->xon_xoff
= SP_XONXOFF_OUT
;
1528 config
->xon_xoff
= SP_XONXOFF_DISABLED
;
1533 if (tcgetattr(port
->fd
, &data
->term
) < 0)
1534 RETURN_FAIL("tcgetattr() failed");
1536 if (ioctl(port
->fd
, TIOCMGET
, &data
->controlbits
) < 0)
1537 RETURN_FAIL("TIOCMGET ioctl failed");
1540 int ret
= get_flow(port
->fd
, data
);
1542 if (ret
== SP_ERR_FAIL
&& errno
== EINVAL
)
1543 data
->termiox_supported
= 0;
1545 RETURN_CODEVAL(ret
);
1547 data
->termiox_supported
= 1;
1549 data
->termiox_supported
= 0;
1552 for (i
= 0; i
< NUM_STD_BAUDRATES
; i
++) {
1553 if (cfgetispeed(&data
->term
) == std_baudrates
[i
].index
) {
1554 config
->baudrate
= std_baudrates
[i
].value
;
1559 if (i
== NUM_STD_BAUDRATES
) {
1561 config
->baudrate
= (int)data
->term
.c_ispeed
;
1562 #elif defined(USE_TERMIOS_SPEED)
1563 TRY(get_baudrate(port
->fd
, &config
->baudrate
));
1565 config
->baudrate
= -1;
1569 switch (data
->term
.c_cflag
& CSIZE
) {
1586 if (!(data
->term
.c_cflag
& PARENB
) && (data
->term
.c_iflag
& IGNPAR
))
1587 config
->parity
= SP_PARITY_NONE
;
1588 else if (!(data
->term
.c_cflag
& PARENB
) || (data
->term
.c_iflag
& IGNPAR
))
1589 config
->parity
= -1;
1591 else if (data
->term
.c_cflag
& CMSPAR
)
1592 config
->parity
= (data
->term
.c_cflag
& PARODD
) ? SP_PARITY_MARK
: SP_PARITY_SPACE
;
1595 config
->parity
= (data
->term
.c_cflag
& PARODD
) ? SP_PARITY_ODD
: SP_PARITY_EVEN
;
1597 config
->stopbits
= (data
->term
.c_cflag
& CSTOPB
) ? 2 : 1;
1599 if (data
->term
.c_cflag
& CRTSCTS
) {
1600 config
->rts
= SP_RTS_FLOW_CONTROL
;
1601 config
->cts
= SP_CTS_FLOW_CONTROL
;
1603 if (data
->termiox_supported
&& data
->rts_flow
)
1604 config
->rts
= SP_RTS_FLOW_CONTROL
;
1606 config
->rts
= (data
->controlbits
& TIOCM_RTS
) ? SP_RTS_ON
: SP_RTS_OFF
;
1608 config
->cts
= (data
->termiox_supported
&& data
->cts_flow
) ?
1609 SP_CTS_FLOW_CONTROL
: SP_CTS_IGNORE
;
1612 if (data
->termiox_supported
&& data
->dtr_flow
)
1613 config
->dtr
= SP_DTR_FLOW_CONTROL
;
1615 config
->dtr
= (data
->controlbits
& TIOCM_DTR
) ? SP_DTR_ON
: SP_DTR_OFF
;
1617 config
->dsr
= (data
->termiox_supported
&& data
->dsr_flow
) ?
1618 SP_DSR_FLOW_CONTROL
: SP_DSR_IGNORE
;
1620 if (data
->term
.c_iflag
& IXOFF
) {
1621 if (data
->term
.c_iflag
& IXON
)
1622 config
->xon_xoff
= SP_XONXOFF_INOUT
;
1624 config
->xon_xoff
= SP_XONXOFF_IN
;
1626 if (data
->term
.c_iflag
& IXON
)
1627 config
->xon_xoff
= SP_XONXOFF_OUT
;
1629 config
->xon_xoff
= SP_XONXOFF_DISABLED
;
1636 static enum sp_return
set_config(struct sp_port
*port
, struct port_data
*data
,
1637 const struct sp_port_config
*config
)
1641 BAUD_TYPE baud_nonstd
;
1645 #ifdef USE_TERMIOS_SPEED
1646 int baud_nonstd
= 0;
1649 TRACE("%p, %p, %p", port
, data
, config
);
1651 DEBUG_FMT("Setting configuration for port %s", port
->name
);
1654 if (config
->baudrate
>= 0) {
1655 for (i
= 0; i
< NUM_STD_BAUDRATES
; i
++) {
1656 if (config
->baudrate
== std_baudrates
[i
].value
) {
1657 data
->dcb
.BaudRate
= std_baudrates
[i
].index
;
1662 if (i
== NUM_STD_BAUDRATES
)
1663 data
->dcb
.BaudRate
= config
->baudrate
;
1666 if (config
->bits
>= 0)
1667 data
->dcb
.ByteSize
= config
->bits
;
1669 if (config
->parity
>= 0) {
1670 switch (config
->parity
) {
1671 case SP_PARITY_NONE
:
1672 data
->dcb
.Parity
= NOPARITY
;
1675 data
->dcb
.Parity
= ODDPARITY
;
1677 case SP_PARITY_EVEN
:
1678 data
->dcb
.Parity
= EVENPARITY
;
1680 case SP_PARITY_MARK
:
1681 data
->dcb
.Parity
= MARKPARITY
;
1683 case SP_PARITY_SPACE
:
1684 data
->dcb
.Parity
= SPACEPARITY
;
1687 RETURN_ERROR(SP_ERR_ARG
, "Invalid parity setting");
1691 if (config
->stopbits
>= 0) {
1692 switch (config
->stopbits
) {
1693 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1695 data
->dcb
.StopBits
= ONESTOPBIT
;
1698 data
->dcb
.StopBits
= TWOSTOPBITS
;
1701 RETURN_ERROR(SP_ERR_ARG
, "Invalid stop bit setting");
1705 if (config
->rts
>= 0) {
1706 switch (config
->rts
) {
1708 data
->dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
1711 data
->dcb
.fRtsControl
= RTS_CONTROL_ENABLE
;
1713 case SP_RTS_FLOW_CONTROL
:
1714 data
->dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
1717 RETURN_ERROR(SP_ERR_ARG
, "Invalid RTS setting");
1721 if (config
->cts
>= 0) {
1722 switch (config
->cts
) {
1724 data
->dcb
.fOutxCtsFlow
= FALSE
;
1726 case SP_CTS_FLOW_CONTROL
:
1727 data
->dcb
.fOutxCtsFlow
= TRUE
;
1730 RETURN_ERROR(SP_ERR_ARG
, "Invalid CTS setting");
1734 if (config
->dtr
>= 0) {
1735 switch (config
->dtr
) {
1737 data
->dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
1740 data
->dcb
.fDtrControl
= DTR_CONTROL_ENABLE
;
1742 case SP_DTR_FLOW_CONTROL
:
1743 data
->dcb
.fDtrControl
= DTR_CONTROL_HANDSHAKE
;
1746 RETURN_ERROR(SP_ERR_ARG
, "Invalid DTR setting");
1750 if (config
->dsr
>= 0) {
1751 switch (config
->dsr
) {
1753 data
->dcb
.fOutxDsrFlow
= FALSE
;
1755 case SP_DSR_FLOW_CONTROL
:
1756 data
->dcb
.fOutxDsrFlow
= TRUE
;
1759 RETURN_ERROR(SP_ERR_ARG
, "Invalid DSR setting");
1763 if (config
->xon_xoff
>= 0) {
1764 switch (config
->xon_xoff
) {
1765 case SP_XONXOFF_DISABLED
:
1766 data
->dcb
.fInX
= FALSE
;
1767 data
->dcb
.fOutX
= FALSE
;
1770 data
->dcb
.fInX
= TRUE
;
1771 data
->dcb
.fOutX
= FALSE
;
1773 case SP_XONXOFF_OUT
:
1774 data
->dcb
.fInX
= FALSE
;
1775 data
->dcb
.fOutX
= TRUE
;
1777 case SP_XONXOFF_INOUT
:
1778 data
->dcb
.fInX
= TRUE
;
1779 data
->dcb
.fOutX
= TRUE
;
1782 RETURN_ERROR(SP_ERR_ARG
, "Invalid XON/XOFF setting");
1786 if (!SetCommState(port
->hdl
, &data
->dcb
))
1787 RETURN_FAIL("SetCommState() failed");
1793 if (config
->baudrate
>= 0) {
1794 for (i
= 0; i
< NUM_STD_BAUDRATES
; i
++) {
1795 if (config
->baudrate
== std_baudrates
[i
].value
) {
1796 if (cfsetospeed(&data
->term
, std_baudrates
[i
].index
) < 0)
1797 RETURN_FAIL("cfsetospeed() failed");
1799 if (cfsetispeed(&data
->term
, std_baudrates
[i
].index
) < 0)
1800 RETURN_FAIL("cfsetispeed() failed");
1805 /* Non-standard baud rate */
1806 if (i
== NUM_STD_BAUDRATES
) {
1808 /* Set "dummy" baud rate. */
1809 if (cfsetspeed(&data
->term
, B9600
) < 0)
1810 RETURN_FAIL("cfsetspeed() failed");
1811 baud_nonstd
= config
->baudrate
;
1812 #elif defined(USE_TERMIOS_SPEED)
1815 RETURN_ERROR(SP_ERR_SUPP
, "Non-standard baudrate not supported");
1820 if (config
->bits
>= 0) {
1821 data
->term
.c_cflag
&= ~CSIZE
;
1822 switch (config
->bits
) {
1824 data
->term
.c_cflag
|= CS8
;
1827 data
->term
.c_cflag
|= CS7
;
1830 data
->term
.c_cflag
|= CS6
;
1833 data
->term
.c_cflag
|= CS5
;
1836 RETURN_ERROR(SP_ERR_ARG
, "Invalid data bits setting");
1840 if (config
->parity
>= 0) {
1841 data
->term
.c_iflag
&= ~IGNPAR
;
1842 data
->term
.c_cflag
&= ~(PARENB
| PARODD
);
1844 data
->term
.c_cflag
&= ~CMSPAR
;
1846 switch (config
->parity
) {
1847 case SP_PARITY_NONE
:
1848 data
->term
.c_iflag
|= IGNPAR
;
1850 case SP_PARITY_EVEN
:
1851 data
->term
.c_cflag
|= PARENB
;
1854 data
->term
.c_cflag
|= PARENB
| PARODD
;
1857 case SP_PARITY_MARK
:
1858 data
->term
.c_cflag
|= PARENB
| PARODD
;
1859 data
->term
.c_cflag
|= CMSPAR
;
1861 case SP_PARITY_SPACE
:
1862 data
->term
.c_cflag
|= PARENB
;
1863 data
->term
.c_cflag
|= CMSPAR
;
1866 case SP_PARITY_MARK
:
1867 case SP_PARITY_SPACE
:
1868 RETURN_ERROR(SP_ERR_SUPP
, "Mark/space parity not supported");
1871 RETURN_ERROR(SP_ERR_ARG
, "Invalid parity setting");
1875 if (config
->stopbits
>= 0) {
1876 data
->term
.c_cflag
&= ~CSTOPB
;
1877 switch (config
->stopbits
) {
1879 data
->term
.c_cflag
&= ~CSTOPB
;
1882 data
->term
.c_cflag
|= CSTOPB
;
1885 RETURN_ERROR(SP_ERR_ARG
, "Invalid stop bits setting");
1889 if (config
->rts
>= 0 || config
->cts
>= 0) {
1890 if (data
->termiox_supported
) {
1891 data
->rts_flow
= data
->cts_flow
= 0;
1892 switch (config
->rts
) {
1895 controlbits
= TIOCM_RTS
;
1896 if (ioctl(port
->fd
, config
->rts
== SP_RTS_ON
? TIOCMBIS
: TIOCMBIC
, &controlbits
) < 0)
1897 RETURN_FAIL("Setting RTS signal level failed");
1899 case SP_RTS_FLOW_CONTROL
:
1905 if (config
->cts
== SP_CTS_FLOW_CONTROL
)
1908 if (data
->rts_flow
&& data
->cts_flow
)
1909 data
->term
.c_iflag
|= CRTSCTS
;
1911 data
->term
.c_iflag
&= ~CRTSCTS
;
1913 /* Asymmetric use of RTS/CTS not supported. */
1914 if (data
->term
.c_iflag
& CRTSCTS
) {
1915 /* Flow control can only be disabled for both RTS & CTS together. */
1916 if (config
->rts
>= 0 && config
->rts
!= SP_RTS_FLOW_CONTROL
) {
1917 if (config
->cts
!= SP_CTS_IGNORE
)
1918 RETURN_ERROR(SP_ERR_SUPP
, "RTS & CTS flow control must be disabled together");
1920 if (config
->cts
>= 0 && config
->cts
!= SP_CTS_FLOW_CONTROL
) {
1921 if (config
->rts
<= 0 || config
->rts
== SP_RTS_FLOW_CONTROL
)
1922 RETURN_ERROR(SP_ERR_SUPP
, "RTS & CTS flow control must be disabled together");
1925 /* Flow control can only be enabled for both RTS & CTS together. */
1926 if (((config
->rts
== SP_RTS_FLOW_CONTROL
) && (config
->cts
!= SP_CTS_FLOW_CONTROL
)) ||
1927 ((config
->cts
== SP_CTS_FLOW_CONTROL
) && (config
->rts
!= SP_RTS_FLOW_CONTROL
)))
1928 RETURN_ERROR(SP_ERR_SUPP
, "RTS & CTS flow control must be enabled together");
1931 if (config
->rts
>= 0) {
1932 if (config
->rts
== SP_RTS_FLOW_CONTROL
) {
1933 data
->term
.c_iflag
|= CRTSCTS
;
1935 controlbits
= TIOCM_RTS
;
1936 if (ioctl(port
->fd
, config
->rts
== SP_RTS_ON
? TIOCMBIS
: TIOCMBIC
,
1938 RETURN_FAIL("Setting RTS signal level failed");
1944 if (config
->dtr
>= 0 || config
->dsr
>= 0) {
1945 if (data
->termiox_supported
) {
1946 data
->dtr_flow
= data
->dsr_flow
= 0;
1947 switch (config
->dtr
) {
1950 controlbits
= TIOCM_DTR
;
1951 if (ioctl(port
->fd
, config
->dtr
== SP_DTR_ON
? TIOCMBIS
: TIOCMBIC
, &controlbits
) < 0)
1952 RETURN_FAIL("Setting DTR signal level failed");
1954 case SP_DTR_FLOW_CONTROL
:
1960 if (config
->dsr
== SP_DSR_FLOW_CONTROL
)
1963 /* DTR/DSR flow control not supported. */
1964 if (config
->dtr
== SP_DTR_FLOW_CONTROL
|| config
->dsr
== SP_DSR_FLOW_CONTROL
)
1965 RETURN_ERROR(SP_ERR_SUPP
, "DTR/DSR flow control not supported");
1967 if (config
->dtr
>= 0) {
1968 controlbits
= TIOCM_DTR
;
1969 if (ioctl(port
->fd
, config
->dtr
== SP_DTR_ON
? TIOCMBIS
: TIOCMBIC
,
1971 RETURN_FAIL("Setting DTR signal level failed");
1976 if (config
->xon_xoff
>= 0) {
1977 data
->term
.c_iflag
&= ~(IXON
| IXOFF
| IXANY
);
1978 switch (config
->xon_xoff
) {
1979 case SP_XONXOFF_DISABLED
:
1982 data
->term
.c_iflag
|= IXOFF
;
1984 case SP_XONXOFF_OUT
:
1985 data
->term
.c_iflag
|= IXON
| IXANY
;
1987 case SP_XONXOFF_INOUT
:
1988 data
->term
.c_iflag
|= IXON
| IXOFF
| IXANY
;
1991 RETURN_ERROR(SP_ERR_ARG
, "Invalid XON/XOFF setting");
1995 if (tcsetattr(port
->fd
, TCSANOW
, &data
->term
) < 0)
1996 RETURN_FAIL("tcsetattr() failed");
1999 if (baud_nonstd
!= B0
) {
2000 if (ioctl(port
->fd
, IOSSIOSPEED
, &baud_nonstd
) == -1)
2001 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2003 * Set baud rates in data->term to correct, but incompatible
2004 * with tcsetattr() value, same as delivered by tcgetattr().
2006 if (cfsetspeed(&data
->term
, baud_nonstd
) < 0)
2007 RETURN_FAIL("cfsetspeed() failed");
2009 #elif defined(__linux__)
2010 #ifdef USE_TERMIOS_SPEED
2012 TRY(set_baudrate(port
->fd
, config
->baudrate
));
2015 if (data
->termiox_supported
)
2016 TRY(set_flow(port
->fd
, data
));
2020 #endif /* !_WIN32 */
2025 SP_API
enum sp_return
sp_new_config(struct sp_port_config
**config_ptr
)
2027 struct sp_port_config
*config
;
2029 TRACE("%p", config_ptr
);
2032 RETURN_ERROR(SP_ERR_ARG
, "Null result pointer");
2036 if (!(config
= malloc(sizeof(struct sp_port_config
))))
2037 RETURN_ERROR(SP_ERR_MEM
, "Config malloc failed");
2039 config
->baudrate
= -1;
2041 config
->parity
= -1;
2042 config
->stopbits
= -1;
2048 *config_ptr
= config
;
2053 SP_API
void sp_free_config(struct sp_port_config
*config
)
2055 TRACE("%p", config
);
2058 DEBUG("Null config");
2065 SP_API
enum sp_return
sp_get_config(struct sp_port
*port
,
2066 struct sp_port_config
*config
)
2068 struct port_data data
;
2070 TRACE("%p, %p", port
, config
);
2075 RETURN_ERROR(SP_ERR_ARG
, "Null config");
2077 TRY(get_config(port
, &data
, config
));
2082 SP_API
enum sp_return
sp_set_config(struct sp_port
*port
,
2083 const struct sp_port_config
*config
)
2085 struct port_data data
;
2086 struct sp_port_config prev_config
;
2088 TRACE("%p, %p", port
, config
);
2093 RETURN_ERROR(SP_ERR_ARG
, "Null config");
2095 TRY(get_config(port
, &data
, &prev_config
));
2096 TRY(set_config(port
, &data
, config
));
2101 #define CREATE_ACCESSORS(x, type) \
2102 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2103 struct port_data data; \
2104 struct sp_port_config config; \
2105 TRACE("%p, %d", port, x); \
2106 CHECK_OPEN_PORT(); \
2107 TRY(get_config(port, &data, &config)); \
2109 TRY(set_config(port, &data, &config)); \
2112 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2114 TRACE("%p, %p", config, x); \
2116 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2120 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2122 TRACE("%p, %d", config, x); \
2124 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2129 CREATE_ACCESSORS(baudrate
, int)
2130 CREATE_ACCESSORS(bits
, int)
2131 CREATE_ACCESSORS(parity
, enum sp_parity
)
2132 CREATE_ACCESSORS(stopbits
, int)
2133 CREATE_ACCESSORS(rts
, enum sp_rts
)
2134 CREATE_ACCESSORS(cts
, enum sp_cts
)
2135 CREATE_ACCESSORS(dtr
, enum sp_dtr
)
2136 CREATE_ACCESSORS(dsr
, enum sp_dsr
)
2137 CREATE_ACCESSORS(xon_xoff
, enum sp_xonxoff
)
2139 SP_API
enum sp_return
sp_set_config_flowcontrol(struct sp_port_config
*config
,
2140 enum sp_flowcontrol flowcontrol
)
2143 RETURN_ERROR(SP_ERR_ARG
, "Null configuration");
2145 if (flowcontrol
> SP_FLOWCONTROL_DTRDSR
)
2146 RETURN_ERROR(SP_ERR_ARG
, "Invalid flow control setting");
2148 if (flowcontrol
== SP_FLOWCONTROL_XONXOFF
)
2149 config
->xon_xoff
= SP_XONXOFF_INOUT
;
2151 config
->xon_xoff
= SP_XONXOFF_DISABLED
;
2153 if (flowcontrol
== SP_FLOWCONTROL_RTSCTS
) {
2154 config
->rts
= SP_RTS_FLOW_CONTROL
;
2155 config
->cts
= SP_CTS_FLOW_CONTROL
;
2157 if (config
->rts
== SP_RTS_FLOW_CONTROL
)
2158 config
->rts
= SP_RTS_ON
;
2159 config
->cts
= SP_CTS_IGNORE
;
2162 if (flowcontrol
== SP_FLOWCONTROL_DTRDSR
) {
2163 config
->dtr
= SP_DTR_FLOW_CONTROL
;
2164 config
->dsr
= SP_DSR_FLOW_CONTROL
;
2166 if (config
->dtr
== SP_DTR_FLOW_CONTROL
)
2167 config
->dtr
= SP_DTR_ON
;
2168 config
->dsr
= SP_DSR_IGNORE
;
2174 SP_API
enum sp_return
sp_set_flowcontrol(struct sp_port
*port
,
2175 enum sp_flowcontrol flowcontrol
)
2177 struct port_data data
;
2178 struct sp_port_config config
;
2180 TRACE("%p, %d", port
, flowcontrol
);
2184 TRY(get_config(port
, &data
, &config
));
2186 TRY(sp_set_config_flowcontrol(&config
, flowcontrol
));
2188 TRY(set_config(port
, &data
, &config
));
2193 SP_API
enum sp_return
sp_get_signals(struct sp_port
*port
,
2194 enum sp_signal
*signals
)
2196 TRACE("%p, %p", port
, signals
);
2201 RETURN_ERROR(SP_ERR_ARG
, "Null result pointer");
2203 DEBUG_FMT("Getting control signals for port %s", port
->name
);
2208 if (GetCommModemStatus(port
->hdl
, &bits
) == 0)
2209 RETURN_FAIL("GetCommModemStatus() failed");
2210 if (bits
& MS_CTS_ON
)
2211 *signals
|= SP_SIG_CTS
;
2212 if (bits
& MS_DSR_ON
)
2213 *signals
|= SP_SIG_DSR
;
2214 if (bits
& MS_RLSD_ON
)
2215 *signals
|= SP_SIG_DCD
;
2216 if (bits
& MS_RING_ON
)
2217 *signals
|= SP_SIG_RI
;
2220 if (ioctl(port
->fd
, TIOCMGET
, &bits
) < 0)
2221 RETURN_FAIL("TIOCMGET ioctl failed");
2222 if (bits
& TIOCM_CTS
)
2223 *signals
|= SP_SIG_CTS
;
2224 if (bits
& TIOCM_DSR
)
2225 *signals
|= SP_SIG_DSR
;
2226 if (bits
& TIOCM_CAR
)
2227 *signals
|= SP_SIG_DCD
;
2228 if (bits
& TIOCM_RNG
)
2229 *signals
|= SP_SIG_RI
;
2234 SP_API
enum sp_return
sp_start_break(struct sp_port
*port
)
2240 if (SetCommBreak(port
->hdl
) == 0)
2241 RETURN_FAIL("SetCommBreak() failed");
2243 if (ioctl(port
->fd
, TIOCSBRK
, 1) < 0)
2244 RETURN_FAIL("TIOCSBRK ioctl failed");
2250 SP_API
enum sp_return
sp_end_break(struct sp_port
*port
)
2256 if (ClearCommBreak(port
->hdl
) == 0)
2257 RETURN_FAIL("ClearCommBreak() failed");
2259 if (ioctl(port
->fd
, TIOCCBRK
, 1) < 0)
2260 RETURN_FAIL("TIOCCBRK ioctl failed");
2266 SP_API
int sp_last_error_code(void)
2270 RETURN_INT(GetLastError());
2276 SP_API
char *sp_last_error_message(void)
2282 DWORD error
= GetLastError();
2285 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
2286 FORMAT_MESSAGE_FROM_SYSTEM
|
2287 FORMAT_MESSAGE_IGNORE_INSERTS
,
2290 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
2294 RETURN_STRING(message
);
2296 RETURN_STRING(strerror(errno
));
2300 SP_API
void sp_free_error_message(char *message
)
2302 TRACE("%s", message
);
2313 SP_API
void sp_set_debug_handler(void (*handler
)(const char *format
, ...))
2315 TRACE("%p", handler
);
2317 sp_debug_handler
= handler
;
2322 SP_API
void sp_default_debug_handler(const char *format
, ...)
2325 va_start(args
, format
);
2326 if (getenv("LIBSERIALPORT_DEBUG")) {
2327 fputs("sp: ", stderr
);
2328 vfprintf(stderr
, format
, args
);
2333 SP_API
int sp_get_major_package_version(void)
2335 return SP_PACKAGE_VERSION_MAJOR
;
2338 SP_API
int sp_get_minor_package_version(void)
2340 return SP_PACKAGE_VERSION_MINOR
;
2343 SP_API
int sp_get_micro_package_version(void)
2345 return SP_PACKAGE_VERSION_MICRO
;
2348 SP_API
const char *sp_get_package_version_string(void)
2350 return SP_PACKAGE_VERSION_STRING
;
2353 SP_API
int sp_get_current_lib_version(void)
2355 return SP_LIB_VERSION_CURRENT
;
2358 SP_API
int sp_get_revision_lib_version(void)
2360 return SP_LIB_VERSION_REVISION
;
2363 SP_API
int sp_get_age_lib_version(void)
2365 return SP_LIB_VERSION_AGE
;
2368 SP_API
const char *sp_get_lib_version_string(void)
2370 return SP_LIB_VERSION_STRING
;