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(const struct sp_port
*port
)
133 if (!port
|| !port
->description
)
136 RETURN_STRING(port
->description
);
139 SP_API
enum sp_transport
sp_get_port_transport(const 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 #ifndef NO_ENUMERATION
326 struct sp_port
**list
;
330 TRACE("%p", list_ptr
);
333 RETURN_ERROR(SP_ERR_ARG
, "Null result pointer");
335 #ifdef NO_ENUMERATION
336 RETURN_ERROR(SP_ERR_SUPP
, "Enumeration not supported on this platform");
338 DEBUG("Enumerating ports");
340 if (!(list
= malloc(sizeof(struct sp_port
*))))
341 RETURN_ERROR(SP_ERR_MEM
, "Port list malloc failed");
345 ret
= list_ports(&list
);
350 sp_free_port_list(list
);
358 SP_API
void sp_free_port_list(struct sp_port
**list
)
369 DEBUG("Freeing port list");
371 for (i
= 0; list
[i
]; i
++)
372 sp_free_port(list
[i
]);
378 #define CHECK_PORT() do { \
380 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
382 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
385 #define CHECK_PORT_HANDLE() do { \
386 if (port->hdl == INVALID_HANDLE_VALUE) \
387 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
390 #define CHECK_PORT_HANDLE() do { \
392 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
395 #define CHECK_OPEN_PORT() do { \
397 CHECK_PORT_HANDLE(); \
401 /** To be called after port receive buffer is emptied. */
402 static enum sp_return
restart_wait(struct sp_port
*port
)
406 if (port
->wait_running
) {
407 /* Check status of running wait operation. */
408 if (GetOverlappedResult(port
->hdl
, &port
->wait_ovl
,
409 &wait_result
, FALSE
)) {
410 DEBUG("Previous wait completed");
411 port
->wait_running
= FALSE
;
412 } else if (GetLastError() == ERROR_IO_INCOMPLETE
) {
413 DEBUG("Previous wait still running");
416 RETURN_FAIL("GetOverlappedResult() failed");
420 if (!port
->wait_running
) {
421 /* Start new wait operation. */
422 if (WaitCommEvent(port
->hdl
, &port
->events
,
424 DEBUG("New wait returned, events already pending");
425 } else if (GetLastError() == ERROR_IO_PENDING
) {
426 DEBUG("New wait running in background");
427 port
->wait_running
= TRUE
;
429 RETURN_FAIL("WaitCommEvent() failed");
437 SP_API
enum sp_return
sp_open(struct sp_port
*port
, enum sp_mode flags
)
439 struct port_data data
;
440 struct sp_port_config config
;
443 TRACE("%p, 0x%x", port
, flags
);
447 if (flags
> SP_MODE_READ_WRITE
)
448 RETURN_ERROR(SP_ERR_ARG
, "Invalid flags");
450 DEBUG_FMT("Opening port %s", port
->name
);
453 DWORD desired_access
= 0, flags_and_attributes
= 0, errors
;
454 char *escaped_port_name
;
457 /* Prefix port name with '\\.\' to work with ports above COM9. */
458 if (!(escaped_port_name
= malloc(strlen(port
->name
) + 5)))
459 RETURN_ERROR(SP_ERR_MEM
, "Escaped port name malloc failed");
460 sprintf(escaped_port_name
, "\\\\.\\%s", port
->name
);
462 /* Map 'flags' to the OS-specific settings. */
463 flags_and_attributes
= FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_OVERLAPPED
;
464 if (flags
& SP_MODE_READ
)
465 desired_access
|= GENERIC_READ
;
466 if (flags
& SP_MODE_WRITE
)
467 desired_access
|= GENERIC_WRITE
;
469 port
->hdl
= CreateFile(escaped_port_name
, desired_access
, 0, 0,
470 OPEN_EXISTING
, flags_and_attributes
, 0);
472 free(escaped_port_name
);
474 if (port
->hdl
== INVALID_HANDLE_VALUE
)
475 RETURN_FAIL("Port CreateFile() failed");
477 /* All timeouts initially disabled. */
478 port
->timeouts
.ReadIntervalTimeout
= 0;
479 port
->timeouts
.ReadTotalTimeoutMultiplier
= 0;
480 port
->timeouts
.ReadTotalTimeoutConstant
= 0;
481 port
->timeouts
.WriteTotalTimeoutMultiplier
= 0;
482 port
->timeouts
.WriteTotalTimeoutConstant
= 0;
484 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0) {
486 RETURN_FAIL("SetCommTimeouts() failed");
489 /* Prepare OVERLAPPED structures. */
490 #define INIT_OVERLAPPED(ovl) do { \
491 memset(&port->ovl, 0, sizeof(port->ovl)); \
492 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
493 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
494 == INVALID_HANDLE_VALUE) { \
496 RETURN_FAIL(#ovl "CreateEvent() failed"); \
500 INIT_OVERLAPPED(read_ovl
);
501 INIT_OVERLAPPED(write_ovl
);
502 INIT_OVERLAPPED(wait_ovl
);
504 /* Set event mask for RX and error events. */
505 if (SetCommMask(port
->hdl
, EV_RXCHAR
| EV_ERR
) == 0) {
507 RETURN_FAIL("SetCommMask() failed");
510 port
->writing
= FALSE
;
511 port
->wait_running
= FALSE
;
513 ret
= restart_wait(port
);
520 int flags_local
= O_NONBLOCK
| O_NOCTTY
;
522 /* Map 'flags' to the OS-specific settings. */
523 if ((flags
& SP_MODE_READ_WRITE
) == SP_MODE_READ_WRITE
)
524 flags_local
|= O_RDWR
;
525 else if (flags
& SP_MODE_READ
)
526 flags_local
|= O_RDONLY
;
527 else if (flags
& SP_MODE_WRITE
)
528 flags_local
|= O_WRONLY
;
530 if ((port
->fd
= open(port
->name
, flags_local
)) < 0)
531 RETURN_FAIL("open() failed");
534 ret
= get_config(port
, &data
, &config
);
541 /* Set sane port settings. */
543 data
.dcb
.fBinary
= TRUE
;
544 data
.dcb
.fDsrSensitivity
= FALSE
;
545 data
.dcb
.fErrorChar
= FALSE
;
546 data
.dcb
.fNull
= FALSE
;
547 data
.dcb
.fAbortOnError
= FALSE
;
549 /* Turn off all fancy termios tricks, give us a raw channel. */
550 data
.term
.c_iflag
&= ~(IGNBRK
| BRKINT
| PARMRK
| ISTRIP
| INLCR
| IGNCR
| ICRNL
| IMAXBEL
);
552 data
.term
.c_iflag
&= ~IUCLC
;
554 data
.term
.c_oflag
&= ~(OPOST
| ONLCR
| OCRNL
| ONOCR
| ONLRET
);
556 data
.term
.c_oflag
&= ~OLCUC
;
559 data
.term
.c_oflag
&= ~NLDLY
;
562 data
.term
.c_oflag
&= ~CRDLY
;
565 data
.term
.c_oflag
&= ~TABDLY
;
568 data
.term
.c_oflag
&= ~BSDLY
;
571 data
.term
.c_oflag
&= ~VTDLY
;
574 data
.term
.c_oflag
&= ~FFDLY
;
577 data
.term
.c_oflag
&= ~OFILL
;
579 data
.term
.c_lflag
&= ~(ISIG
| ICANON
| ECHO
| IEXTEN
);
580 data
.term
.c_cc
[VMIN
] = 0;
581 data
.term
.c_cc
[VTIME
] = 0;
583 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
584 data
.term
.c_cflag
|= (CLOCAL
| CREAD
| HUPCL
);
588 if (ClearCommError(port
->hdl
, &errors
, &status
) == 0)
589 RETURN_FAIL("ClearCommError() failed");
592 ret
= set_config(port
, &data
, &config
);
602 SP_API
enum sp_return
sp_close(struct sp_port
*port
)
608 DEBUG_FMT("Closing port %s", port
->name
);
611 /* Returns non-zero upon success, 0 upon failure. */
612 if (CloseHandle(port
->hdl
) == 0)
613 RETURN_FAIL("Port CloseHandle() failed");
614 port
->hdl
= INVALID_HANDLE_VALUE
;
616 /* Close event handles for overlapped structures. */
617 #define CLOSE_OVERLAPPED(ovl) do { \
618 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
619 CloseHandle(port->ovl.hEvent) == 0) \
620 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
622 CLOSE_OVERLAPPED(read_ovl
);
623 CLOSE_OVERLAPPED(write_ovl
);
624 CLOSE_OVERLAPPED(wait_ovl
);
627 /* Returns 0 upon success, -1 upon failure. */
628 if (close(port
->fd
) == -1)
629 RETURN_FAIL("close() failed");
636 SP_API
enum sp_return
sp_flush(struct sp_port
*port
, enum sp_buffer buffers
)
638 TRACE("%p, 0x%x", port
, buffers
);
642 if (buffers
> SP_BUF_BOTH
)
643 RETURN_ERROR(SP_ERR_ARG
, "Invalid buffer selection");
645 const char *buffer_names
[] = {"no", "input", "output", "both"};
647 DEBUG_FMT("Flushing %s buffers on port %s",
648 buffer_names
[buffers
], port
->name
);
652 if (buffers
& SP_BUF_INPUT
)
653 flags
|= PURGE_RXCLEAR
;
654 if (buffers
& SP_BUF_OUTPUT
)
655 flags
|= PURGE_TXCLEAR
;
657 /* Returns non-zero upon success, 0 upon failure. */
658 if (PurgeComm(port
->hdl
, flags
) == 0)
659 RETURN_FAIL("PurgeComm() failed");
661 if (buffers
& SP_BUF_INPUT
)
662 TRY(restart_wait(port
));
665 if (buffers
== SP_BUF_BOTH
)
667 else if (buffers
== SP_BUF_INPUT
)
669 else if (buffers
== SP_BUF_OUTPUT
)
672 /* Returns 0 upon success, -1 upon failure. */
673 if (tcflush(port
->fd
, flags
) < 0)
674 RETURN_FAIL("tcflush() failed");
679 SP_API
enum sp_return
sp_drain(struct sp_port
*port
)
685 DEBUG_FMT("Draining port %s", port
->name
);
688 /* Returns non-zero upon success, 0 upon failure. */
689 if (FlushFileBuffers(port
->hdl
) == 0)
690 RETURN_FAIL("FlushFileBuffers() failed");
697 result
= ioctl(port
->fd
, TCSBRK
, &arg
);
699 result
= tcdrain(port
->fd
);
702 if (errno
== EINTR
) {
703 DEBUG("tcdrain() was interrupted");
706 RETURN_FAIL("tcdrain() failed");
715 SP_API
enum sp_return
sp_blocking_write(struct sp_port
*port
, const void *buf
,
716 size_t count
, unsigned int timeout
)
718 TRACE("%p, %p, %d, %d", port
, buf
, count
, timeout
);
723 RETURN_ERROR(SP_ERR_ARG
, "Null buffer");
726 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
727 count
, port
->name
, timeout
);
729 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
736 DWORD bytes_written
= 0;
739 /* Wait for previous non-blocking write to complete, if any. */
741 DEBUG("Waiting for previous write to complete");
742 result
= GetOverlappedResult(port
->hdl
, &port
->write_ovl
, &bytes_written
, TRUE
);
745 RETURN_FAIL("Previous write failed to complete");
746 DEBUG("Previous write completed");
750 port
->timeouts
.WriteTotalTimeoutConstant
= timeout
;
751 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0)
752 RETURN_FAIL("SetCommTimeouts() failed");
755 if (WriteFile(port
->hdl
, buf
, count
, NULL
, &port
->write_ovl
) == 0) {
756 if (GetLastError() == ERROR_IO_PENDING
) {
757 DEBUG("Waiting for write to complete");
758 GetOverlappedResult(port
->hdl
, &port
->write_ovl
, &bytes_written
, TRUE
);
759 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written
, count
);
760 RETURN_INT(bytes_written
);
762 RETURN_FAIL("WriteFile() failed");
765 DEBUG("Write completed immediately");
769 size_t bytes_written
= 0;
770 unsigned char *ptr
= (unsigned char *) buf
;
771 struct timeval start
, delta
, now
, end
= {0, 0};
776 /* Get time at start of operation. */
777 gettimeofday(&start
, NULL
);
778 /* Define duration of timeout. */
779 delta
.tv_sec
= timeout
/ 1000;
780 delta
.tv_usec
= (timeout
% 1000) * 1000;
781 /* Calculate time at which we should give up. */
782 timeradd(&start
, &delta
, &end
);
785 /* Loop until we have written the requested number of bytes. */
786 while (bytes_written
< count
) {
787 /* Wait until space is available. */
789 FD_SET(port
->fd
, &fds
);
791 gettimeofday(&now
, NULL
);
792 if (timercmp(&now
, &end
, >)) {
793 DEBUG("Write timed out");
794 RETURN_INT(bytes_written
);
796 timersub(&end
, &now
, &delta
);
798 result
= select(port
->fd
+ 1, NULL
, &fds
, NULL
, timeout
? &delta
: NULL
);
800 if (errno
== EINTR
) {
801 DEBUG("select() call was interrupted, repeating");
804 RETURN_FAIL("select() failed");
806 } else if (result
== 0) {
807 DEBUG("Write timed out");
808 RETURN_INT(bytes_written
);
812 result
= write(port
->fd
, ptr
, count
- bytes_written
);
816 /* This shouldn't happen because we did a select() first, but handle anyway. */
819 /* This is an actual failure. */
820 RETURN_FAIL("write() failed");
823 bytes_written
+= result
;
827 RETURN_INT(bytes_written
);
831 SP_API
enum sp_return
sp_nonblocking_write(struct sp_port
*port
,
832 const void *buf
, size_t count
)
834 TRACE("%p, %p, %d", port
, buf
, count
);
839 RETURN_ERROR(SP_ERR_ARG
, "Null buffer");
841 DEBUG_FMT("Writing up to %d bytes to port %s", count
, port
->name
);
848 BYTE
*ptr
= (BYTE
*) buf
;
850 /* Check whether previous write is complete. */
852 if (HasOverlappedIoCompleted(&port
->write_ovl
)) {
853 DEBUG("Previous write completed");
856 DEBUG("Previous write not complete");
857 /* Can't take a new write until the previous one finishes. */
863 port
->timeouts
.WriteTotalTimeoutConstant
= 0;
864 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0)
865 RETURN_FAIL("SetCommTimeouts() failed");
868 * Keep writing data until the OS has to actually start an async IO
869 * for it. At that point we know the buffer is full.
871 while (written
< count
) {
872 /* Copy first byte of user buffer. */
873 port
->pending_byte
= *ptr
++;
875 /* Start asynchronous write. */
876 if (WriteFile(port
->hdl
, &port
->pending_byte
, 1, NULL
, &port
->write_ovl
) == 0) {
877 if (GetLastError() == ERROR_IO_PENDING
) {
878 if (HasOverlappedIoCompleted(&port
->write_ovl
)) {
879 DEBUG("Asynchronous write completed immediately");
884 DEBUG("Asynchronous write running");
886 RETURN_INT(++written
);
889 /* Actual failure of some kind. */
890 RETURN_FAIL("WriteFile() failed");
893 DEBUG("Single byte written immediately");
898 DEBUG("All bytes written immediately");
902 /* Returns the number of bytes written, or -1 upon failure. */
903 ssize_t written
= write(port
->fd
, buf
, count
);
906 RETURN_FAIL("write() failed");
912 SP_API
enum sp_return
sp_blocking_read(struct sp_port
*port
, void *buf
,
913 size_t count
, unsigned int timeout
)
915 TRACE("%p, %p, %d, %d", port
, buf
, count
, timeout
);
920 RETURN_ERROR(SP_ERR_ARG
, "Null buffer");
923 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
924 count
, port
->name
, timeout
);
926 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
933 DWORD bytes_read
= 0;
934 DWORD bytes_remaining
;
938 port
->timeouts
.ReadIntervalTimeout
= 0;
939 port
->timeouts
.ReadTotalTimeoutConstant
= timeout
;
940 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0)
941 RETURN_FAIL("SetCommTimeouts() failed");
944 if (ReadFile(port
->hdl
, buf
, count
, NULL
, &port
->read_ovl
) == 0) {
945 if (GetLastError() == ERROR_IO_PENDING
) {
946 DEBUG("Waiting for read to complete");
947 GetOverlappedResult(port
->hdl
, &port
->read_ovl
, &bytes_read
, TRUE
);
948 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read
, count
);
950 RETURN_FAIL("ReadFile() failed");
953 DEBUG("Read completed immediately");
957 ret
= sp_input_waiting(port
);
962 bytes_remaining
= ret
;
964 /* Restart wait operation if buffer was emptied. */
965 if (bytes_read
> 0 && bytes_remaining
== 0)
966 TRY(restart_wait(port
));
968 RETURN_INT(bytes_read
);
971 size_t bytes_read
= 0;
972 unsigned char *ptr
= (unsigned char *) buf
;
973 struct timeval start
, delta
, now
, end
= {0, 0};
978 /* Get time at start of operation. */
979 gettimeofday(&start
, NULL
);
980 /* Define duration of timeout. */
981 delta
.tv_sec
= timeout
/ 1000;
982 delta
.tv_usec
= (timeout
% 1000) * 1000;
983 /* Calculate time at which we should give up. */
984 timeradd(&start
, &delta
, &end
);
987 /* Loop until we have the requested number of bytes. */
988 while (bytes_read
< count
) {
989 /* Wait until data is available. */
991 FD_SET(port
->fd
, &fds
);
993 gettimeofday(&now
, NULL
);
994 if (timercmp(&now
, &end
, >))
995 /* Timeout has expired. */
996 RETURN_INT(bytes_read
);
997 timersub(&end
, &now
, &delta
);
999 result
= select(port
->fd
+ 1, &fds
, NULL
, NULL
, timeout
? &delta
: NULL
);
1001 if (errno
== EINTR
) {
1002 DEBUG("select() call was interrupted, repeating");
1005 RETURN_FAIL("select() failed");
1007 } else if (result
== 0) {
1008 DEBUG("Read timed out");
1009 RETURN_INT(bytes_read
);
1013 result
= read(port
->fd
, ptr
, count
- bytes_read
);
1016 if (errno
== EAGAIN
)
1017 /* This shouldn't happen because we did a select() first, but handle anyway. */
1020 /* This is an actual failure. */
1021 RETURN_FAIL("read() failed");
1024 bytes_read
+= result
;
1028 RETURN_INT(bytes_read
);
1032 SP_API
enum sp_return
sp_nonblocking_read(struct sp_port
*port
, void *buf
,
1035 TRACE("%p, %p, %d", port
, buf
, count
);
1040 RETURN_ERROR(SP_ERR_ARG
, "Null buffer");
1042 DEBUG_FMT("Reading up to %d bytes from port %s", count
, port
->name
);
1046 DWORD bytes_remaining
;
1050 port
->timeouts
.ReadIntervalTimeout
= MAXDWORD
;
1051 port
->timeouts
.ReadTotalTimeoutConstant
= 0;
1052 if (SetCommTimeouts(port
->hdl
, &port
->timeouts
) == 0)
1053 RETURN_FAIL("SetCommTimeouts() failed");
1056 if (ReadFile(port
->hdl
, buf
, count
, NULL
, &port
->read_ovl
) == 0)
1057 RETURN_FAIL("ReadFile() failed");
1059 /* Get number of bytes read. */
1060 if (GetOverlappedResult(port
->hdl
, &port
->read_ovl
, &bytes_read
, TRUE
) == 0)
1061 RETURN_FAIL("GetOverlappedResult() failed");
1063 ret
= sp_input_waiting(port
);
1066 RETURN_CODEVAL(ret
);
1068 bytes_remaining
= ret
;
1070 /* Restart wait operation if buffer was emptied. */
1071 if (bytes_read
> 0 && bytes_remaining
== 0)
1072 TRY(restart_wait(port
));
1074 RETURN_INT(bytes_read
);
1078 /* Returns the number of bytes read, or -1 upon failure. */
1079 if ((bytes_read
= read(port
->fd
, buf
, count
)) < 0) {
1080 if (errno
== EAGAIN
)
1081 /* No bytes available. */
1084 /* This is an actual failure. */
1085 RETURN_FAIL("read() failed");
1087 RETURN_INT(bytes_read
);
1091 SP_API
enum sp_return
sp_input_waiting(struct sp_port
*port
)
1097 DEBUG_FMT("Checking input bytes waiting on port %s", port
->name
);
1103 if (ClearCommError(port
->hdl
, &errors
, &comstat
) == 0)
1104 RETURN_FAIL("ClearCommError() failed");
1105 RETURN_INT(comstat
.cbInQue
);
1108 if (ioctl(port
->fd
, TIOCINQ
, &bytes_waiting
) < 0)
1109 RETURN_FAIL("TIOCINQ ioctl failed");
1110 RETURN_INT(bytes_waiting
);
1114 SP_API
enum sp_return
sp_output_waiting(struct sp_port
*port
)
1120 DEBUG_FMT("Checking output bytes waiting on port %s", port
->name
);
1126 if (ClearCommError(port
->hdl
, &errors
, &comstat
) == 0)
1127 RETURN_FAIL("ClearCommError() failed");
1128 RETURN_INT(comstat
.cbOutQue
);
1131 if (ioctl(port
->fd
, TIOCOUTQ
, &bytes_waiting
) < 0)
1132 RETURN_FAIL("TIOCOUTQ ioctl failed");
1133 RETURN_INT(bytes_waiting
);
1137 SP_API
enum sp_return
sp_new_event_set(struct sp_event_set
**result_ptr
)
1139 struct sp_event_set
*result
;
1141 TRACE("%p", result_ptr
);
1144 RETURN_ERROR(SP_ERR_ARG
, "Null result");
1148 if (!(result
= malloc(sizeof(struct sp_event_set
))))
1149 RETURN_ERROR(SP_ERR_MEM
, "sp_event_set malloc() failed");
1151 memset(result
, 0, sizeof(struct sp_event_set
));
1153 *result_ptr
= result
;
1158 static enum sp_return
add_handle(struct sp_event_set
*event_set
,
1159 event_handle handle
, enum sp_event mask
)
1162 enum sp_event
*new_masks
;
1164 TRACE("%p, %d, %d", event_set
, handle
, mask
);
1166 if (!(new_handles
= realloc(event_set
->handles
,
1167 sizeof(event_handle
) * (event_set
->count
+ 1))))
1168 RETURN_ERROR(SP_ERR_MEM
, "Handle array realloc() failed");
1170 event_set
->handles
= new_handles
;
1172 if (!(new_masks
= realloc(event_set
->masks
,
1173 sizeof(enum sp_event
) * (event_set
->count
+ 1))))
1174 RETURN_ERROR(SP_ERR_MEM
, "Mask array realloc() failed");
1176 event_set
->masks
= new_masks
;
1178 ((event_handle
*) event_set
->handles
)[event_set
->count
] = handle
;
1179 event_set
->masks
[event_set
->count
] = mask
;
1186 SP_API
enum sp_return
sp_add_port_events(struct sp_event_set
*event_set
,
1187 const struct sp_port
*port
, enum sp_event mask
)
1189 TRACE("%p, %p, %d", event_set
, port
, mask
);
1192 RETURN_ERROR(SP_ERR_ARG
, "Null event set");
1195 RETURN_ERROR(SP_ERR_ARG
, "Null port");
1197 if (mask
> (SP_EVENT_RX_READY
| SP_EVENT_TX_READY
| SP_EVENT_ERROR
))
1198 RETURN_ERROR(SP_ERR_ARG
, "Invalid event mask");
1204 enum sp_event handle_mask
;
1205 if ((handle_mask
= mask
& SP_EVENT_TX_READY
))
1206 TRY(add_handle(event_set
, port
->write_ovl
.hEvent
, handle_mask
));
1207 if ((handle_mask
= mask
& (SP_EVENT_RX_READY
| SP_EVENT_ERROR
)))
1208 TRY(add_handle(event_set
, port
->wait_ovl
.hEvent
, handle_mask
));
1210 TRY(add_handle(event_set
, port
->fd
, mask
));
1216 SP_API
void sp_free_event_set(struct sp_event_set
*event_set
)
1218 TRACE("%p", event_set
);
1221 DEBUG("Null event set");
1225 DEBUG("Freeing event set");
1227 if (event_set
->handles
)
1228 free(event_set
->handles
);
1229 if (event_set
->masks
)
1230 free(event_set
->masks
);
1237 SP_API
enum sp_return
sp_wait(struct sp_event_set
*event_set
,
1238 unsigned int timeout
)
1240 TRACE("%p, %d", event_set
, timeout
);
1243 RETURN_ERROR(SP_ERR_ARG
, "Null event set");
1246 if (WaitForMultipleObjects(event_set
->count
, event_set
->handles
, FALSE
,
1247 timeout
? timeout
: INFINITE
) == WAIT_FAILED
)
1248 RETURN_FAIL("WaitForMultipleObjects() failed");
1252 struct timeval start
, delta
, now
, end
= {0, 0};
1253 int result
, timeout_remaining
;
1254 struct pollfd
*pollfds
;
1257 if (!(pollfds
= malloc(sizeof(struct pollfd
) * event_set
->count
)))
1258 RETURN_ERROR(SP_ERR_MEM
, "pollfds malloc() failed");
1260 for (i
= 0; i
< event_set
->count
; i
++) {
1261 pollfds
[i
].fd
= ((int *) event_set
->handles
)[i
];
1262 pollfds
[i
].events
= 0;
1263 pollfds
[i
].revents
= 0;
1264 if (event_set
->masks
[i
] & SP_EVENT_RX_READY
)
1265 pollfds
[i
].events
|= POLLIN
;
1266 if (event_set
->masks
[i
] & SP_EVENT_TX_READY
)
1267 pollfds
[i
].events
|= POLLOUT
;
1268 if (event_set
->masks
[i
] & SP_EVENT_ERROR
)
1269 pollfds
[i
].events
|= POLLERR
;
1273 /* Get time at start of operation. */
1274 gettimeofday(&start
, NULL
);
1275 /* Define duration of timeout. */
1276 delta
.tv_sec
= timeout
/ 1000;
1277 delta
.tv_usec
= (timeout
% 1000) * 1000;
1278 /* Calculate time at which we should give up. */
1279 timeradd(&start
, &delta
, &end
);
1282 /* Loop until an event occurs. */
1285 gettimeofday(&now
, NULL
);
1286 if (timercmp(&now
, &end
, >)) {
1287 DEBUG("Wait timed out");
1290 timersub(&end
, &now
, &delta
);
1291 timeout_remaining
= delta
.tv_sec
* 1000 + delta
.tv_usec
/ 1000;
1294 result
= poll(pollfds
, event_set
->count
, timeout
? timeout_remaining
: -1);
1297 if (errno
== EINTR
) {
1298 DEBUG("poll() call was interrupted, repeating");
1302 RETURN_FAIL("poll() failed");
1304 } else if (result
== 0) {
1305 DEBUG("poll() timed out");
1308 DEBUG("poll() completed");
1318 #ifdef USE_TERMIOS_SPEED
1319 static enum sp_return
get_baudrate(int fd
, int *baudrate
)
1323 TRACE("%d, %p", fd
, baudrate
);
1325 DEBUG("Getting baud rate");
1327 if (!(data
= malloc(get_termios_size())))
1328 RETURN_ERROR(SP_ERR_MEM
, "termios malloc failed");
1330 if (ioctl(fd
, get_termios_get_ioctl(), data
) < 0) {
1332 RETURN_FAIL("Getting termios failed");
1335 *baudrate
= get_termios_speed(data
);
1342 static enum sp_return
set_baudrate(int fd
, int baudrate
)
1346 TRACE("%d, %d", fd
, baudrate
);
1348 DEBUG("Getting baud rate");
1350 if (!(data
= malloc(get_termios_size())))
1351 RETURN_ERROR(SP_ERR_MEM
, "termios malloc failed");
1353 if (ioctl(fd
, get_termios_get_ioctl(), data
) < 0) {
1355 RETURN_FAIL("Getting termios failed");
1358 DEBUG("Setting baud rate");
1360 set_termios_speed(data
, baudrate
);
1362 if (ioctl(fd
, get_termios_set_ioctl(), data
) < 0) {
1364 RETURN_FAIL("Setting termios failed");
1371 #endif /* USE_TERMIOS_SPEED */
1374 static enum sp_return
get_flow(int fd
, struct port_data
*data
)
1378 TRACE("%d, %p", fd
, data
);
1380 DEBUG("Getting advanced flow control");
1382 if (!(termx
= malloc(get_termiox_size())))
1383 RETURN_ERROR(SP_ERR_MEM
, "termiox malloc failed");
1385 if (ioctl(fd
, TCGETX
, termx
) < 0) {
1387 RETURN_FAIL("Getting termiox failed");
1390 get_termiox_flow(termx
, &data
->rts_flow
, &data
->cts_flow
,
1391 &data
->dtr_flow
, &data
->dsr_flow
);
1398 static enum sp_return
set_flow(int fd
, struct port_data
*data
)
1402 TRACE("%d, %p", fd
, data
);
1404 DEBUG("Getting advanced flow control");
1406 if (!(termx
= malloc(get_termiox_size())))
1407 RETURN_ERROR(SP_ERR_MEM
, "termiox malloc failed");
1409 if (ioctl(fd
, TCGETX
, termx
) < 0) {
1411 RETURN_FAIL("Getting termiox failed");
1414 DEBUG("Setting advanced flow control");
1416 set_termiox_flow(termx
, data
->rts_flow
, data
->cts_flow
,
1417 data
->dtr_flow
, data
->dsr_flow
);
1419 if (ioctl(fd
, TCSETX
, termx
) < 0) {
1421 RETURN_FAIL("Setting termiox failed");
1428 #endif /* USE_TERMIOX */
1430 static enum sp_return
get_config(struct sp_port
*port
, struct port_data
*data
,
1431 struct sp_port_config
*config
)
1435 TRACE("%p, %p, %p", port
, data
, config
);
1437 DEBUG_FMT("Getting configuration for port %s", port
->name
);
1440 if (!GetCommState(port
->hdl
, &data
->dcb
))
1441 RETURN_FAIL("GetCommState() failed");
1443 for (i
= 0; i
< NUM_STD_BAUDRATES
; i
++) {
1444 if (data
->dcb
.BaudRate
== std_baudrates
[i
].index
) {
1445 config
->baudrate
= std_baudrates
[i
].value
;
1450 if (i
== NUM_STD_BAUDRATES
)
1451 /* BaudRate field can be either an index or a custom baud rate. */
1452 config
->baudrate
= data
->dcb
.BaudRate
;
1454 config
->bits
= data
->dcb
.ByteSize
;
1456 if (data
->dcb
.fParity
)
1457 switch (data
->dcb
.Parity
) {
1459 config
->parity
= SP_PARITY_NONE
;
1462 config
->parity
= SP_PARITY_ODD
;
1465 config
->parity
= SP_PARITY_EVEN
;
1468 config
->parity
= SP_PARITY_MARK
;
1471 config
->parity
= SP_PARITY_SPACE
;
1474 config
->parity
= -1;
1477 config
->parity
= SP_PARITY_NONE
;
1479 switch (data
->dcb
.StopBits
) {
1481 config
->stopbits
= 1;
1484 config
->stopbits
= 2;
1487 config
->stopbits
= -1;
1490 switch (data
->dcb
.fRtsControl
) {
1491 case RTS_CONTROL_DISABLE
:
1492 config
->rts
= SP_RTS_OFF
;
1494 case RTS_CONTROL_ENABLE
:
1495 config
->rts
= SP_RTS_ON
;
1497 case RTS_CONTROL_HANDSHAKE
:
1498 config
->rts
= SP_RTS_FLOW_CONTROL
;
1504 config
->cts
= data
->dcb
.fOutxCtsFlow
? SP_CTS_FLOW_CONTROL
: SP_CTS_IGNORE
;
1506 switch (data
->dcb
.fDtrControl
) {
1507 case DTR_CONTROL_DISABLE
:
1508 config
->dtr
= SP_DTR_OFF
;
1510 case DTR_CONTROL_ENABLE
:
1511 config
->dtr
= SP_DTR_ON
;
1513 case DTR_CONTROL_HANDSHAKE
:
1514 config
->dtr
= SP_DTR_FLOW_CONTROL
;
1520 config
->dsr
= data
->dcb
.fOutxDsrFlow
? SP_DSR_FLOW_CONTROL
: SP_DSR_IGNORE
;
1522 if (data
->dcb
.fInX
) {
1523 if (data
->dcb
.fOutX
)
1524 config
->xon_xoff
= SP_XONXOFF_INOUT
;
1526 config
->xon_xoff
= SP_XONXOFF_IN
;
1528 if (data
->dcb
.fOutX
)
1529 config
->xon_xoff
= SP_XONXOFF_OUT
;
1531 config
->xon_xoff
= SP_XONXOFF_DISABLED
;
1536 if (tcgetattr(port
->fd
, &data
->term
) < 0)
1537 RETURN_FAIL("tcgetattr() failed");
1539 if (ioctl(port
->fd
, TIOCMGET
, &data
->controlbits
) < 0)
1540 RETURN_FAIL("TIOCMGET ioctl failed");
1543 int ret
= get_flow(port
->fd
, data
);
1545 if (ret
== SP_ERR_FAIL
&& errno
== EINVAL
)
1546 data
->termiox_supported
= 0;
1548 RETURN_CODEVAL(ret
);
1550 data
->termiox_supported
= 1;
1552 data
->termiox_supported
= 0;
1555 for (i
= 0; i
< NUM_STD_BAUDRATES
; i
++) {
1556 if (cfgetispeed(&data
->term
) == std_baudrates
[i
].index
) {
1557 config
->baudrate
= std_baudrates
[i
].value
;
1562 if (i
== NUM_STD_BAUDRATES
) {
1564 config
->baudrate
= (int)data
->term
.c_ispeed
;
1565 #elif defined(USE_TERMIOS_SPEED)
1566 TRY(get_baudrate(port
->fd
, &config
->baudrate
));
1568 config
->baudrate
= -1;
1572 switch (data
->term
.c_cflag
& CSIZE
) {
1589 if (!(data
->term
.c_cflag
& PARENB
) && (data
->term
.c_iflag
& IGNPAR
))
1590 config
->parity
= SP_PARITY_NONE
;
1591 else if (!(data
->term
.c_cflag
& PARENB
) || (data
->term
.c_iflag
& IGNPAR
))
1592 config
->parity
= -1;
1594 else if (data
->term
.c_cflag
& CMSPAR
)
1595 config
->parity
= (data
->term
.c_cflag
& PARODD
) ? SP_PARITY_MARK
: SP_PARITY_SPACE
;
1598 config
->parity
= (data
->term
.c_cflag
& PARODD
) ? SP_PARITY_ODD
: SP_PARITY_EVEN
;
1600 config
->stopbits
= (data
->term
.c_cflag
& CSTOPB
) ? 2 : 1;
1602 if (data
->term
.c_cflag
& CRTSCTS
) {
1603 config
->rts
= SP_RTS_FLOW_CONTROL
;
1604 config
->cts
= SP_CTS_FLOW_CONTROL
;
1606 if (data
->termiox_supported
&& data
->rts_flow
)
1607 config
->rts
= SP_RTS_FLOW_CONTROL
;
1609 config
->rts
= (data
->controlbits
& TIOCM_RTS
) ? SP_RTS_ON
: SP_RTS_OFF
;
1611 config
->cts
= (data
->termiox_supported
&& data
->cts_flow
) ?
1612 SP_CTS_FLOW_CONTROL
: SP_CTS_IGNORE
;
1615 if (data
->termiox_supported
&& data
->dtr_flow
)
1616 config
->dtr
= SP_DTR_FLOW_CONTROL
;
1618 config
->dtr
= (data
->controlbits
& TIOCM_DTR
) ? SP_DTR_ON
: SP_DTR_OFF
;
1620 config
->dsr
= (data
->termiox_supported
&& data
->dsr_flow
) ?
1621 SP_DSR_FLOW_CONTROL
: SP_DSR_IGNORE
;
1623 if (data
->term
.c_iflag
& IXOFF
) {
1624 if (data
->term
.c_iflag
& IXON
)
1625 config
->xon_xoff
= SP_XONXOFF_INOUT
;
1627 config
->xon_xoff
= SP_XONXOFF_IN
;
1629 if (data
->term
.c_iflag
& IXON
)
1630 config
->xon_xoff
= SP_XONXOFF_OUT
;
1632 config
->xon_xoff
= SP_XONXOFF_DISABLED
;
1639 static enum sp_return
set_config(struct sp_port
*port
, struct port_data
*data
,
1640 const struct sp_port_config
*config
)
1644 BAUD_TYPE baud_nonstd
;
1648 #ifdef USE_TERMIOS_SPEED
1649 int baud_nonstd
= 0;
1652 TRACE("%p, %p, %p", port
, data
, config
);
1654 DEBUG_FMT("Setting configuration for port %s", port
->name
);
1657 if (config
->baudrate
>= 0) {
1658 for (i
= 0; i
< NUM_STD_BAUDRATES
; i
++) {
1659 if (config
->baudrate
== std_baudrates
[i
].value
) {
1660 data
->dcb
.BaudRate
= std_baudrates
[i
].index
;
1665 if (i
== NUM_STD_BAUDRATES
)
1666 data
->dcb
.BaudRate
= config
->baudrate
;
1669 if (config
->bits
>= 0)
1670 data
->dcb
.ByteSize
= config
->bits
;
1672 if (config
->parity
>= 0) {
1673 switch (config
->parity
) {
1674 case SP_PARITY_NONE
:
1675 data
->dcb
.Parity
= NOPARITY
;
1678 data
->dcb
.Parity
= ODDPARITY
;
1680 case SP_PARITY_EVEN
:
1681 data
->dcb
.Parity
= EVENPARITY
;
1683 case SP_PARITY_MARK
:
1684 data
->dcb
.Parity
= MARKPARITY
;
1686 case SP_PARITY_SPACE
:
1687 data
->dcb
.Parity
= SPACEPARITY
;
1690 RETURN_ERROR(SP_ERR_ARG
, "Invalid parity setting");
1694 if (config
->stopbits
>= 0) {
1695 switch (config
->stopbits
) {
1696 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1698 data
->dcb
.StopBits
= ONESTOPBIT
;
1701 data
->dcb
.StopBits
= TWOSTOPBITS
;
1704 RETURN_ERROR(SP_ERR_ARG
, "Invalid stop bit setting");
1708 if (config
->rts
>= 0) {
1709 switch (config
->rts
) {
1711 data
->dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
1714 data
->dcb
.fRtsControl
= RTS_CONTROL_ENABLE
;
1716 case SP_RTS_FLOW_CONTROL
:
1717 data
->dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
1720 RETURN_ERROR(SP_ERR_ARG
, "Invalid RTS setting");
1724 if (config
->cts
>= 0) {
1725 switch (config
->cts
) {
1727 data
->dcb
.fOutxCtsFlow
= FALSE
;
1729 case SP_CTS_FLOW_CONTROL
:
1730 data
->dcb
.fOutxCtsFlow
= TRUE
;
1733 RETURN_ERROR(SP_ERR_ARG
, "Invalid CTS setting");
1737 if (config
->dtr
>= 0) {
1738 switch (config
->dtr
) {
1740 data
->dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
1743 data
->dcb
.fDtrControl
= DTR_CONTROL_ENABLE
;
1745 case SP_DTR_FLOW_CONTROL
:
1746 data
->dcb
.fDtrControl
= DTR_CONTROL_HANDSHAKE
;
1749 RETURN_ERROR(SP_ERR_ARG
, "Invalid DTR setting");
1753 if (config
->dsr
>= 0) {
1754 switch (config
->dsr
) {
1756 data
->dcb
.fOutxDsrFlow
= FALSE
;
1758 case SP_DSR_FLOW_CONTROL
:
1759 data
->dcb
.fOutxDsrFlow
= TRUE
;
1762 RETURN_ERROR(SP_ERR_ARG
, "Invalid DSR setting");
1766 if (config
->xon_xoff
>= 0) {
1767 switch (config
->xon_xoff
) {
1768 case SP_XONXOFF_DISABLED
:
1769 data
->dcb
.fInX
= FALSE
;
1770 data
->dcb
.fOutX
= FALSE
;
1773 data
->dcb
.fInX
= TRUE
;
1774 data
->dcb
.fOutX
= FALSE
;
1776 case SP_XONXOFF_OUT
:
1777 data
->dcb
.fInX
= FALSE
;
1778 data
->dcb
.fOutX
= TRUE
;
1780 case SP_XONXOFF_INOUT
:
1781 data
->dcb
.fInX
= TRUE
;
1782 data
->dcb
.fOutX
= TRUE
;
1785 RETURN_ERROR(SP_ERR_ARG
, "Invalid XON/XOFF setting");
1789 if (!SetCommState(port
->hdl
, &data
->dcb
))
1790 RETURN_FAIL("SetCommState() failed");
1796 if (config
->baudrate
>= 0) {
1797 for (i
= 0; i
< NUM_STD_BAUDRATES
; i
++) {
1798 if (config
->baudrate
== std_baudrates
[i
].value
) {
1799 if (cfsetospeed(&data
->term
, std_baudrates
[i
].index
) < 0)
1800 RETURN_FAIL("cfsetospeed() failed");
1802 if (cfsetispeed(&data
->term
, std_baudrates
[i
].index
) < 0)
1803 RETURN_FAIL("cfsetispeed() failed");
1808 /* Non-standard baud rate */
1809 if (i
== NUM_STD_BAUDRATES
) {
1811 /* Set "dummy" baud rate. */
1812 if (cfsetspeed(&data
->term
, B9600
) < 0)
1813 RETURN_FAIL("cfsetspeed() failed");
1814 baud_nonstd
= config
->baudrate
;
1815 #elif defined(USE_TERMIOS_SPEED)
1818 RETURN_ERROR(SP_ERR_SUPP
, "Non-standard baudrate not supported");
1823 if (config
->bits
>= 0) {
1824 data
->term
.c_cflag
&= ~CSIZE
;
1825 switch (config
->bits
) {
1827 data
->term
.c_cflag
|= CS8
;
1830 data
->term
.c_cflag
|= CS7
;
1833 data
->term
.c_cflag
|= CS6
;
1836 data
->term
.c_cflag
|= CS5
;
1839 RETURN_ERROR(SP_ERR_ARG
, "Invalid data bits setting");
1843 if (config
->parity
>= 0) {
1844 data
->term
.c_iflag
&= ~IGNPAR
;
1845 data
->term
.c_cflag
&= ~(PARENB
| PARODD
);
1847 data
->term
.c_cflag
&= ~CMSPAR
;
1849 switch (config
->parity
) {
1850 case SP_PARITY_NONE
:
1851 data
->term
.c_iflag
|= IGNPAR
;
1853 case SP_PARITY_EVEN
:
1854 data
->term
.c_cflag
|= PARENB
;
1857 data
->term
.c_cflag
|= PARENB
| PARODD
;
1860 case SP_PARITY_MARK
:
1861 data
->term
.c_cflag
|= PARENB
| PARODD
;
1862 data
->term
.c_cflag
|= CMSPAR
;
1864 case SP_PARITY_SPACE
:
1865 data
->term
.c_cflag
|= PARENB
;
1866 data
->term
.c_cflag
|= CMSPAR
;
1869 case SP_PARITY_MARK
:
1870 case SP_PARITY_SPACE
:
1871 RETURN_ERROR(SP_ERR_SUPP
, "Mark/space parity not supported");
1874 RETURN_ERROR(SP_ERR_ARG
, "Invalid parity setting");
1878 if (config
->stopbits
>= 0) {
1879 data
->term
.c_cflag
&= ~CSTOPB
;
1880 switch (config
->stopbits
) {
1882 data
->term
.c_cflag
&= ~CSTOPB
;
1885 data
->term
.c_cflag
|= CSTOPB
;
1888 RETURN_ERROR(SP_ERR_ARG
, "Invalid stop bits setting");
1892 if (config
->rts
>= 0 || config
->cts
>= 0) {
1893 if (data
->termiox_supported
) {
1894 data
->rts_flow
= data
->cts_flow
= 0;
1895 switch (config
->rts
) {
1898 controlbits
= TIOCM_RTS
;
1899 if (ioctl(port
->fd
, config
->rts
== SP_RTS_ON
? TIOCMBIS
: TIOCMBIC
, &controlbits
) < 0)
1900 RETURN_FAIL("Setting RTS signal level failed");
1902 case SP_RTS_FLOW_CONTROL
:
1908 if (config
->cts
== SP_CTS_FLOW_CONTROL
)
1911 if (data
->rts_flow
&& data
->cts_flow
)
1912 data
->term
.c_iflag
|= CRTSCTS
;
1914 data
->term
.c_iflag
&= ~CRTSCTS
;
1916 /* Asymmetric use of RTS/CTS not supported. */
1917 if (data
->term
.c_iflag
& CRTSCTS
) {
1918 /* Flow control can only be disabled for both RTS & CTS together. */
1919 if (config
->rts
>= 0 && config
->rts
!= SP_RTS_FLOW_CONTROL
) {
1920 if (config
->cts
!= SP_CTS_IGNORE
)
1921 RETURN_ERROR(SP_ERR_SUPP
, "RTS & CTS flow control must be disabled together");
1923 if (config
->cts
>= 0 && config
->cts
!= SP_CTS_FLOW_CONTROL
) {
1924 if (config
->rts
<= 0 || config
->rts
== SP_RTS_FLOW_CONTROL
)
1925 RETURN_ERROR(SP_ERR_SUPP
, "RTS & CTS flow control must be disabled together");
1928 /* Flow control can only be enabled for both RTS & CTS together. */
1929 if (((config
->rts
== SP_RTS_FLOW_CONTROL
) && (config
->cts
!= SP_CTS_FLOW_CONTROL
)) ||
1930 ((config
->cts
== SP_CTS_FLOW_CONTROL
) && (config
->rts
!= SP_RTS_FLOW_CONTROL
)))
1931 RETURN_ERROR(SP_ERR_SUPP
, "RTS & CTS flow control must be enabled together");
1934 if (config
->rts
>= 0) {
1935 if (config
->rts
== SP_RTS_FLOW_CONTROL
) {
1936 data
->term
.c_iflag
|= CRTSCTS
;
1938 controlbits
= TIOCM_RTS
;
1939 if (ioctl(port
->fd
, config
->rts
== SP_RTS_ON
? TIOCMBIS
: TIOCMBIC
,
1941 RETURN_FAIL("Setting RTS signal level failed");
1947 if (config
->dtr
>= 0 || config
->dsr
>= 0) {
1948 if (data
->termiox_supported
) {
1949 data
->dtr_flow
= data
->dsr_flow
= 0;
1950 switch (config
->dtr
) {
1953 controlbits
= TIOCM_DTR
;
1954 if (ioctl(port
->fd
, config
->dtr
== SP_DTR_ON
? TIOCMBIS
: TIOCMBIC
, &controlbits
) < 0)
1955 RETURN_FAIL("Setting DTR signal level failed");
1957 case SP_DTR_FLOW_CONTROL
:
1963 if (config
->dsr
== SP_DSR_FLOW_CONTROL
)
1966 /* DTR/DSR flow control not supported. */
1967 if (config
->dtr
== SP_DTR_FLOW_CONTROL
|| config
->dsr
== SP_DSR_FLOW_CONTROL
)
1968 RETURN_ERROR(SP_ERR_SUPP
, "DTR/DSR flow control not supported");
1970 if (config
->dtr
>= 0) {
1971 controlbits
= TIOCM_DTR
;
1972 if (ioctl(port
->fd
, config
->dtr
== SP_DTR_ON
? TIOCMBIS
: TIOCMBIC
,
1974 RETURN_FAIL("Setting DTR signal level failed");
1979 if (config
->xon_xoff
>= 0) {
1980 data
->term
.c_iflag
&= ~(IXON
| IXOFF
| IXANY
);
1981 switch (config
->xon_xoff
) {
1982 case SP_XONXOFF_DISABLED
:
1985 data
->term
.c_iflag
|= IXOFF
;
1987 case SP_XONXOFF_OUT
:
1988 data
->term
.c_iflag
|= IXON
| IXANY
;
1990 case SP_XONXOFF_INOUT
:
1991 data
->term
.c_iflag
|= IXON
| IXOFF
| IXANY
;
1994 RETURN_ERROR(SP_ERR_ARG
, "Invalid XON/XOFF setting");
1998 if (tcsetattr(port
->fd
, TCSANOW
, &data
->term
) < 0)
1999 RETURN_FAIL("tcsetattr() failed");
2002 if (baud_nonstd
!= B0
) {
2003 if (ioctl(port
->fd
, IOSSIOSPEED
, &baud_nonstd
) == -1)
2004 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2006 * Set baud rates in data->term to correct, but incompatible
2007 * with tcsetattr() value, same as delivered by tcgetattr().
2009 if (cfsetspeed(&data
->term
, baud_nonstd
) < 0)
2010 RETURN_FAIL("cfsetspeed() failed");
2012 #elif defined(__linux__)
2013 #ifdef USE_TERMIOS_SPEED
2015 TRY(set_baudrate(port
->fd
, config
->baudrate
));
2018 if (data
->termiox_supported
)
2019 TRY(set_flow(port
->fd
, data
));
2023 #endif /* !_WIN32 */
2028 SP_API
enum sp_return
sp_new_config(struct sp_port_config
**config_ptr
)
2030 struct sp_port_config
*config
;
2032 TRACE("%p", config_ptr
);
2035 RETURN_ERROR(SP_ERR_ARG
, "Null result pointer");
2039 if (!(config
= malloc(sizeof(struct sp_port_config
))))
2040 RETURN_ERROR(SP_ERR_MEM
, "Config malloc failed");
2042 config
->baudrate
= -1;
2044 config
->parity
= -1;
2045 config
->stopbits
= -1;
2051 *config_ptr
= config
;
2056 SP_API
void sp_free_config(struct sp_port_config
*config
)
2058 TRACE("%p", config
);
2061 DEBUG("Null config");
2068 SP_API
enum sp_return
sp_get_config(struct sp_port
*port
,
2069 struct sp_port_config
*config
)
2071 struct port_data data
;
2073 TRACE("%p, %p", port
, config
);
2078 RETURN_ERROR(SP_ERR_ARG
, "Null config");
2080 TRY(get_config(port
, &data
, config
));
2085 SP_API
enum sp_return
sp_set_config(struct sp_port
*port
,
2086 const struct sp_port_config
*config
)
2088 struct port_data data
;
2089 struct sp_port_config prev_config
;
2091 TRACE("%p, %p", port
, config
);
2096 RETURN_ERROR(SP_ERR_ARG
, "Null config");
2098 TRY(get_config(port
, &data
, &prev_config
));
2099 TRY(set_config(port
, &data
, config
));
2104 #define CREATE_ACCESSORS(x, type) \
2105 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2106 struct port_data data; \
2107 struct sp_port_config config; \
2108 TRACE("%p, %d", port, x); \
2109 CHECK_OPEN_PORT(); \
2110 TRY(get_config(port, &data, &config)); \
2112 TRY(set_config(port, &data, &config)); \
2115 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2117 TRACE("%p, %p", config, x); \
2119 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2123 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2125 TRACE("%p, %d", config, x); \
2127 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2132 CREATE_ACCESSORS(baudrate
, int)
2133 CREATE_ACCESSORS(bits
, int)
2134 CREATE_ACCESSORS(parity
, enum sp_parity
)
2135 CREATE_ACCESSORS(stopbits
, int)
2136 CREATE_ACCESSORS(rts
, enum sp_rts
)
2137 CREATE_ACCESSORS(cts
, enum sp_cts
)
2138 CREATE_ACCESSORS(dtr
, enum sp_dtr
)
2139 CREATE_ACCESSORS(dsr
, enum sp_dsr
)
2140 CREATE_ACCESSORS(xon_xoff
, enum sp_xonxoff
)
2142 SP_API
enum sp_return
sp_set_config_flowcontrol(struct sp_port_config
*config
,
2143 enum sp_flowcontrol flowcontrol
)
2146 RETURN_ERROR(SP_ERR_ARG
, "Null configuration");
2148 if (flowcontrol
> SP_FLOWCONTROL_DTRDSR
)
2149 RETURN_ERROR(SP_ERR_ARG
, "Invalid flow control setting");
2151 if (flowcontrol
== SP_FLOWCONTROL_XONXOFF
)
2152 config
->xon_xoff
= SP_XONXOFF_INOUT
;
2154 config
->xon_xoff
= SP_XONXOFF_DISABLED
;
2156 if (flowcontrol
== SP_FLOWCONTROL_RTSCTS
) {
2157 config
->rts
= SP_RTS_FLOW_CONTROL
;
2158 config
->cts
= SP_CTS_FLOW_CONTROL
;
2160 if (config
->rts
== SP_RTS_FLOW_CONTROL
)
2161 config
->rts
= SP_RTS_ON
;
2162 config
->cts
= SP_CTS_IGNORE
;
2165 if (flowcontrol
== SP_FLOWCONTROL_DTRDSR
) {
2166 config
->dtr
= SP_DTR_FLOW_CONTROL
;
2167 config
->dsr
= SP_DSR_FLOW_CONTROL
;
2169 if (config
->dtr
== SP_DTR_FLOW_CONTROL
)
2170 config
->dtr
= SP_DTR_ON
;
2171 config
->dsr
= SP_DSR_IGNORE
;
2177 SP_API
enum sp_return
sp_set_flowcontrol(struct sp_port
*port
,
2178 enum sp_flowcontrol flowcontrol
)
2180 struct port_data data
;
2181 struct sp_port_config config
;
2183 TRACE("%p, %d", port
, flowcontrol
);
2187 TRY(get_config(port
, &data
, &config
));
2189 TRY(sp_set_config_flowcontrol(&config
, flowcontrol
));
2191 TRY(set_config(port
, &data
, &config
));
2196 SP_API
enum sp_return
sp_get_signals(struct sp_port
*port
,
2197 enum sp_signal
*signals
)
2199 TRACE("%p, %p", port
, signals
);
2204 RETURN_ERROR(SP_ERR_ARG
, "Null result pointer");
2206 DEBUG_FMT("Getting control signals for port %s", port
->name
);
2211 if (GetCommModemStatus(port
->hdl
, &bits
) == 0)
2212 RETURN_FAIL("GetCommModemStatus() failed");
2213 if (bits
& MS_CTS_ON
)
2214 *signals
|= SP_SIG_CTS
;
2215 if (bits
& MS_DSR_ON
)
2216 *signals
|= SP_SIG_DSR
;
2217 if (bits
& MS_RLSD_ON
)
2218 *signals
|= SP_SIG_DCD
;
2219 if (bits
& MS_RING_ON
)
2220 *signals
|= SP_SIG_RI
;
2223 if (ioctl(port
->fd
, TIOCMGET
, &bits
) < 0)
2224 RETURN_FAIL("TIOCMGET ioctl failed");
2225 if (bits
& TIOCM_CTS
)
2226 *signals
|= SP_SIG_CTS
;
2227 if (bits
& TIOCM_DSR
)
2228 *signals
|= SP_SIG_DSR
;
2229 if (bits
& TIOCM_CAR
)
2230 *signals
|= SP_SIG_DCD
;
2231 if (bits
& TIOCM_RNG
)
2232 *signals
|= SP_SIG_RI
;
2237 SP_API
enum sp_return
sp_start_break(struct sp_port
*port
)
2243 if (SetCommBreak(port
->hdl
) == 0)
2244 RETURN_FAIL("SetCommBreak() failed");
2246 if (ioctl(port
->fd
, TIOCSBRK
, 1) < 0)
2247 RETURN_FAIL("TIOCSBRK ioctl failed");
2253 SP_API
enum sp_return
sp_end_break(struct sp_port
*port
)
2259 if (ClearCommBreak(port
->hdl
) == 0)
2260 RETURN_FAIL("ClearCommBreak() failed");
2262 if (ioctl(port
->fd
, TIOCCBRK
, 1) < 0)
2263 RETURN_FAIL("TIOCCBRK ioctl failed");
2269 SP_API
int sp_last_error_code(void)
2273 RETURN_INT(GetLastError());
2279 SP_API
char *sp_last_error_message(void)
2285 DWORD error
= GetLastError();
2288 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
2289 FORMAT_MESSAGE_FROM_SYSTEM
|
2290 FORMAT_MESSAGE_IGNORE_INSERTS
,
2293 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
2297 RETURN_STRING(message
);
2299 RETURN_STRING(strerror(errno
));
2303 SP_API
void sp_free_error_message(char *message
)
2305 TRACE("%s", message
);
2316 SP_API
void sp_set_debug_handler(void (*handler
)(const char *format
, ...))
2318 TRACE("%p", handler
);
2320 sp_debug_handler
= handler
;
2325 SP_API
void sp_default_debug_handler(const char *format
, ...)
2328 va_start(args
, format
);
2329 if (getenv("LIBSERIALPORT_DEBUG")) {
2330 fputs("sp: ", stderr
);
2331 vfprintf(stderr
, format
, args
);
2336 SP_API
int sp_get_major_package_version(void)
2338 return SP_PACKAGE_VERSION_MAJOR
;
2341 SP_API
int sp_get_minor_package_version(void)
2343 return SP_PACKAGE_VERSION_MINOR
;
2346 SP_API
int sp_get_micro_package_version(void)
2348 return SP_PACKAGE_VERSION_MICRO
;
2351 SP_API
const char *sp_get_package_version_string(void)
2353 return SP_PACKAGE_VERSION_STRING
;
2356 SP_API
int sp_get_current_lib_version(void)
2358 return SP_LIB_VERSION_CURRENT
;
2361 SP_API
int sp_get_revision_lib_version(void)
2363 return SP_LIB_VERSION_REVISION
;
2366 SP_API
int sp_get_age_lib_version(void)
2368 return SP_LIB_VERSION_AGE
;
2371 SP_API
const char *sp_get_lib_version_string(void)
2373 return SP_LIB_VERSION_STRING
;