windows: Fix a build error.
[libserialport/gsi.git] / serialport.c
blob2c1b68217eaf0747d93761fc5af61a6accaa45c4
1 /*
2 * This file is part of the libserialport project.
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2015 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2013-2015 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 <config.h>
25 #include "libserialport.h"
26 #include "libserialport_internal.h"
28 static const struct std_baudrate std_baudrates[] = {
29 #ifdef _WIN32
31 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
32 * have documented CBR_* macros.
34 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
35 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
36 BAUD(115200), BAUD(128000), BAUD(256000),
37 #else
38 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
39 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
40 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
41 BAUD(230400),
42 #if !defined(__APPLE__) && !defined(__OpenBSD__)
43 BAUD(460800),
44 #endif
45 #endif
48 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
50 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
52 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
53 struct sp_port_config *config);
55 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
56 const struct sp_port_config *config);
58 #ifndef _WIN32
59 static void get_time(struct timeval *time)
61 #ifdef HAVE_CLOCK_GETTIME
62 struct timespec ts;
63 if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
64 clock_gettime(CLOCK_REALTIME, &ts);
65 time->tv_sec = ts.tv_sec;
66 time->tv_usec = ts.tv_nsec / 1000;
67 #elif defined(__APPLE__)
68 mach_timebase_info_data_t info;
69 mach_timebase_info(&info);
70 uint64_t ticks = mach_absolute_time();
71 uint64_t ns = (ticks * info.numer) / info.denom;
72 time->tv_sec = ns / 1000000000;
73 time->tv_usec = (ns % 1000000000) / 1000;
74 #else
75 gettimeofday(time, NULL);
76 #endif
78 #endif
80 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
82 struct sp_port *port;
83 #ifndef NO_PORT_METADATA
84 enum sp_return ret;
85 #endif
86 int len;
88 TRACE("%s, %p", portname, port_ptr);
90 if (!port_ptr)
91 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
93 *port_ptr = NULL;
95 if (!portname)
96 RETURN_ERROR(SP_ERR_ARG, "Null port name");
98 DEBUG_FMT("Building structure for port %s", portname);
100 #if !defined(_WIN32) && defined(HAVE_REALPATH)
102 * get_port_details() below tries to be too smart and figure out
103 * some transport properties from the port name which breaks with
104 * symlinks. Therefore we canonicalize the portname first.
106 char pathbuf[PATH_MAX + 1];
107 char *res = realpath(portname, pathbuf);
108 if (!res)
109 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
111 portname = pathbuf;
112 #endif
114 if (!(port = malloc(sizeof(struct sp_port))))
115 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
117 len = strlen(portname) + 1;
119 if (!(port->name = malloc(len))) {
120 free(port);
121 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
124 memcpy(port->name, portname, len);
126 #ifdef _WIN32
127 port->usb_path = NULL;
128 port->hdl = INVALID_HANDLE_VALUE;
129 port->write_buf = NULL;
130 port->write_buf_size = 0;
131 #else
132 port->fd = -1;
133 #endif
135 port->description = NULL;
136 port->transport = SP_TRANSPORT_NATIVE;
137 port->usb_bus = -1;
138 port->usb_address = -1;
139 port->usb_vid = -1;
140 port->usb_pid = -1;
141 port->usb_manufacturer = NULL;
142 port->usb_product = NULL;
143 port->usb_serial = NULL;
144 port->bluetooth_address = NULL;
146 #ifndef NO_PORT_METADATA
147 if ((ret = get_port_details(port)) != SP_OK) {
148 sp_free_port(port);
149 return ret;
151 #endif
153 *port_ptr = port;
155 RETURN_OK();
158 SP_API char *sp_get_port_name(const struct sp_port *port)
160 TRACE("%p", port);
162 if (!port)
163 return NULL;
165 RETURN_STRING(port->name);
168 SP_API char *sp_get_port_description(const struct sp_port *port)
170 TRACE("%p", port);
172 if (!port || !port->description)
173 return NULL;
175 RETURN_STRING(port->description);
178 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
180 TRACE("%p", port);
182 if (!port)
183 RETURN_ERROR(SP_ERR_ARG, "Null port");
185 RETURN_INT(port->transport);
188 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
189 int *usb_bus,int *usb_address)
191 TRACE("%p", port);
193 if (!port)
194 RETURN_ERROR(SP_ERR_ARG, "Null port");
195 if (port->transport != SP_TRANSPORT_USB)
196 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
197 if (port->usb_bus < 0 || port->usb_address < 0)
198 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
200 if (usb_bus)
201 *usb_bus = port->usb_bus;
202 if (usb_address)
203 *usb_address = port->usb_address;
205 RETURN_OK();
208 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
209 int *usb_vid, int *usb_pid)
211 TRACE("%p", port);
213 if (!port)
214 RETURN_ERROR(SP_ERR_ARG, "Null port");
215 if (port->transport != SP_TRANSPORT_USB)
216 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
217 if (port->usb_vid < 0 || port->usb_pid < 0)
218 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
220 if (usb_vid)
221 *usb_vid = port->usb_vid;
222 if (usb_pid)
223 *usb_pid = port->usb_pid;
225 RETURN_OK();
228 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
230 TRACE("%p", port);
232 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
233 return NULL;
235 RETURN_STRING(port->usb_manufacturer);
238 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
240 TRACE("%p", port);
242 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
243 return NULL;
245 RETURN_STRING(port->usb_product);
248 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
250 TRACE("%p", port);
252 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
253 return NULL;
255 RETURN_STRING(port->usb_serial);
258 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
260 TRACE("%p", port);
262 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
263 || !port->bluetooth_address)
264 return NULL;
266 RETURN_STRING(port->bluetooth_address);
269 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
270 void *result_ptr)
272 TRACE("%p, %p", port, result_ptr);
274 if (!port)
275 RETURN_ERROR(SP_ERR_ARG, "Null port");
276 if (!result_ptr)
277 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
279 #ifdef _WIN32
280 HANDLE *handle_ptr = result_ptr;
281 *handle_ptr = port->hdl;
282 #else
283 int *fd_ptr = result_ptr;
284 *fd_ptr = port->fd;
285 #endif
287 RETURN_OK();
290 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
291 struct sp_port **copy_ptr)
293 TRACE("%p, %p", port, copy_ptr);
295 if (!copy_ptr)
296 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
298 *copy_ptr = NULL;
300 if (!port)
301 RETURN_ERROR(SP_ERR_ARG, "Null port");
303 if (!port->name)
304 RETURN_ERROR(SP_ERR_ARG, "Null port name");
306 DEBUG("Copying port structure");
308 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
311 SP_API void sp_free_port(struct sp_port *port)
313 TRACE("%p", port);
315 if (!port) {
316 DEBUG("Null port");
317 RETURN();
320 DEBUG("Freeing port structure");
322 if (port->name)
323 free(port->name);
324 if (port->description)
325 free(port->description);
326 if (port->usb_manufacturer)
327 free(port->usb_manufacturer);
328 if (port->usb_product)
329 free(port->usb_product);
330 if (port->usb_serial)
331 free(port->usb_serial);
332 if (port->bluetooth_address)
333 free(port->bluetooth_address);
334 #ifdef _WIN32
335 if (port->usb_path)
336 free(port->usb_path);
337 if (port->write_buf)
338 free(port->write_buf);
339 #endif
341 free(port);
343 RETURN();
346 SP_PRIV struct sp_port **list_append(struct sp_port **list,
347 const char *portname)
349 void *tmp;
350 unsigned int count;
352 for (count = 0; list[count]; count++)
354 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
355 goto fail;
356 list = tmp;
357 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
358 goto fail;
359 list[count + 1] = NULL;
360 return list;
362 fail:
363 sp_free_port_list(list);
364 return NULL;
367 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
369 #ifndef NO_ENUMERATION
370 struct sp_port **list;
371 int ret;
372 #endif
374 TRACE("%p", list_ptr);
376 if (!list_ptr)
377 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
379 *list_ptr = NULL;
381 #ifdef NO_ENUMERATION
382 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
383 #else
384 DEBUG("Enumerating ports");
386 if (!(list = malloc(sizeof(struct sp_port *))))
387 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
389 list[0] = NULL;
391 ret = list_ports(&list);
393 if (ret == SP_OK) {
394 *list_ptr = list;
395 } else {
396 sp_free_port_list(list);
397 *list_ptr = NULL;
400 RETURN_CODEVAL(ret);
401 #endif
404 SP_API void sp_free_port_list(struct sp_port **list)
406 unsigned int i;
408 TRACE("%p", list);
410 if (!list) {
411 DEBUG("Null list");
412 RETURN();
415 DEBUG("Freeing port list");
417 for (i = 0; list[i]; i++)
418 sp_free_port(list[i]);
419 free(list);
421 RETURN();
424 #define CHECK_PORT() do { \
425 if (!port) \
426 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
427 if (!port->name) \
428 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
429 } while (0)
430 #ifdef _WIN32
431 #define CHECK_PORT_HANDLE() do { \
432 if (port->hdl == INVALID_HANDLE_VALUE) \
433 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
434 } while (0)
435 #else
436 #define CHECK_PORT_HANDLE() do { \
437 if (port->fd < 0) \
438 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
439 } while (0)
440 #endif
441 #define CHECK_OPEN_PORT() do { \
442 CHECK_PORT(); \
443 CHECK_PORT_HANDLE(); \
444 } while (0)
446 #ifdef WIN32
447 /** To be called after port receive buffer is emptied. */
448 static enum sp_return restart_wait(struct sp_port *port)
450 DWORD wait_result;
452 if (port->wait_running) {
453 /* Check status of running wait operation. */
454 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
455 &wait_result, FALSE)) {
456 DEBUG("Previous wait completed");
457 port->wait_running = FALSE;
458 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
459 DEBUG("Previous wait still running");
460 RETURN_OK();
461 } else {
462 RETURN_FAIL("GetOverlappedResult() failed");
466 if (!port->wait_running) {
467 /* Start new wait operation. */
468 if (WaitCommEvent(port->hdl, &port->events,
469 &port->wait_ovl)) {
470 DEBUG("New wait returned, events already pending");
471 } else if (GetLastError() == ERROR_IO_PENDING) {
472 DEBUG("New wait running in background");
473 port->wait_running = TRUE;
474 } else {
475 RETURN_FAIL("WaitCommEvent() failed");
479 RETURN_OK();
481 #endif
483 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
485 struct port_data data;
486 struct sp_port_config config;
487 enum sp_return ret;
489 TRACE("%p, 0x%x", port, flags);
491 CHECK_PORT();
493 if (flags > SP_MODE_READ_WRITE)
494 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
496 DEBUG_FMT("Opening port %s", port->name);
498 #ifdef _WIN32
499 DWORD desired_access = 0, flags_and_attributes = 0, errors;
500 char *escaped_port_name;
501 COMSTAT status;
503 /* Prefix port name with '\\.\' to work with ports above COM9. */
504 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
505 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
506 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
508 /* Map 'flags' to the OS-specific settings. */
509 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
510 if (flags & SP_MODE_READ)
511 desired_access |= GENERIC_READ;
512 if (flags & SP_MODE_WRITE)
513 desired_access |= GENERIC_WRITE;
515 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
516 OPEN_EXISTING, flags_and_attributes, 0);
518 free(escaped_port_name);
520 if (port->hdl == INVALID_HANDLE_VALUE)
521 RETURN_FAIL("Port CreateFile() failed");
523 /* All timeouts initially disabled. */
524 port->timeouts.ReadIntervalTimeout = 0;
525 port->timeouts.ReadTotalTimeoutMultiplier = 0;
526 port->timeouts.ReadTotalTimeoutConstant = 0;
527 port->timeouts.WriteTotalTimeoutMultiplier = 0;
528 port->timeouts.WriteTotalTimeoutConstant = 0;
530 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
531 sp_close(port);
532 RETURN_FAIL("SetCommTimeouts() failed");
535 /* Prepare OVERLAPPED structures. */
536 #define INIT_OVERLAPPED(ovl) do { \
537 memset(&port->ovl, 0, sizeof(port->ovl)); \
538 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
539 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
540 == INVALID_HANDLE_VALUE) { \
541 sp_close(port); \
542 RETURN_FAIL(#ovl "CreateEvent() failed"); \
544 } while (0)
546 INIT_OVERLAPPED(read_ovl);
547 INIT_OVERLAPPED(write_ovl);
548 INIT_OVERLAPPED(wait_ovl);
550 /* Set event mask for RX and error events. */
551 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
552 sp_close(port);
553 RETURN_FAIL("SetCommMask() failed");
556 port->writing = FALSE;
557 port->wait_running = FALSE;
559 ret = restart_wait(port);
561 if (ret < 0) {
562 sp_close(port);
563 RETURN_CODEVAL(ret);
565 #else
566 int flags_local = O_NONBLOCK | O_NOCTTY;
568 /* Map 'flags' to the OS-specific settings. */
569 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
570 flags_local |= O_RDWR;
571 else if (flags & SP_MODE_READ)
572 flags_local |= O_RDONLY;
573 else if (flags & SP_MODE_WRITE)
574 flags_local |= O_WRONLY;
576 if ((port->fd = open(port->name, flags_local)) < 0)
577 RETURN_FAIL("open() failed");
578 #endif
580 ret = get_config(port, &data, &config);
582 if (ret < 0) {
583 sp_close(port);
584 RETURN_CODEVAL(ret);
587 /* Set sane port settings. */
588 #ifdef _WIN32
589 data.dcb.fBinary = TRUE;
590 data.dcb.fDsrSensitivity = FALSE;
591 data.dcb.fErrorChar = FALSE;
592 data.dcb.fNull = FALSE;
593 data.dcb.fAbortOnError = FALSE;
594 #else
595 /* Turn off all fancy termios tricks, give us a raw channel. */
596 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
597 #ifdef IUCLC
598 data.term.c_iflag &= ~IUCLC;
599 #endif
600 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
601 #ifdef OLCUC
602 data.term.c_oflag &= ~OLCUC;
603 #endif
604 #ifdef NLDLY
605 data.term.c_oflag &= ~NLDLY;
606 #endif
607 #ifdef CRDLY
608 data.term.c_oflag &= ~CRDLY;
609 #endif
610 #ifdef TABDLY
611 data.term.c_oflag &= ~TABDLY;
612 #endif
613 #ifdef BSDLY
614 data.term.c_oflag &= ~BSDLY;
615 #endif
616 #ifdef VTDLY
617 data.term.c_oflag &= ~VTDLY;
618 #endif
619 #ifdef FFDLY
620 data.term.c_oflag &= ~FFDLY;
621 #endif
622 #ifdef OFILL
623 data.term.c_oflag &= ~OFILL;
624 #endif
625 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
626 data.term.c_cc[VMIN] = 0;
627 data.term.c_cc[VTIME] = 0;
629 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
630 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
631 #endif
633 #ifdef _WIN32
634 if (ClearCommError(port->hdl, &errors, &status) == 0)
635 RETURN_FAIL("ClearCommError() failed");
636 #endif
638 ret = set_config(port, &data, &config);
640 if (ret < 0) {
641 sp_close(port);
642 RETURN_CODEVAL(ret);
645 RETURN_OK();
648 SP_API enum sp_return sp_close(struct sp_port *port)
650 TRACE("%p", port);
652 CHECK_OPEN_PORT();
654 DEBUG_FMT("Closing port %s", port->name);
656 #ifdef _WIN32
657 /* Returns non-zero upon success, 0 upon failure. */
658 if (CloseHandle(port->hdl) == 0)
659 RETURN_FAIL("Port CloseHandle() failed");
660 port->hdl = INVALID_HANDLE_VALUE;
662 /* Close event handles for overlapped structures. */
663 #define CLOSE_OVERLAPPED(ovl) do { \
664 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
665 CloseHandle(port->ovl.hEvent) == 0) \
666 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
667 } while (0)
668 CLOSE_OVERLAPPED(read_ovl);
669 CLOSE_OVERLAPPED(write_ovl);
670 CLOSE_OVERLAPPED(wait_ovl);
672 if (port->write_buf) {
673 free(port->write_buf);
674 port->write_buf = NULL;
676 #else
677 /* Returns 0 upon success, -1 upon failure. */
678 if (close(port->fd) == -1)
679 RETURN_FAIL("close() failed");
680 port->fd = -1;
681 #endif
683 RETURN_OK();
686 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
688 TRACE("%p, 0x%x", port, buffers);
690 CHECK_OPEN_PORT();
692 if (buffers > SP_BUF_BOTH)
693 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
695 const char *buffer_names[] = {"no", "input", "output", "both"};
697 DEBUG_FMT("Flushing %s buffers on port %s",
698 buffer_names[buffers], port->name);
700 #ifdef _WIN32
701 DWORD flags = 0;
702 if (buffers & SP_BUF_INPUT)
703 flags |= PURGE_RXCLEAR;
704 if (buffers & SP_BUF_OUTPUT)
705 flags |= PURGE_TXCLEAR;
707 /* Returns non-zero upon success, 0 upon failure. */
708 if (PurgeComm(port->hdl, flags) == 0)
709 RETURN_FAIL("PurgeComm() failed");
711 if (buffers & SP_BUF_INPUT)
712 TRY(restart_wait(port));
713 #else
714 int flags = 0;
715 if (buffers == SP_BUF_BOTH)
716 flags = TCIOFLUSH;
717 else if (buffers == SP_BUF_INPUT)
718 flags = TCIFLUSH;
719 else if (buffers == SP_BUF_OUTPUT)
720 flags = TCOFLUSH;
722 /* Returns 0 upon success, -1 upon failure. */
723 if (tcflush(port->fd, flags) < 0)
724 RETURN_FAIL("tcflush() failed");
725 #endif
726 RETURN_OK();
729 SP_API enum sp_return sp_drain(struct sp_port *port)
731 TRACE("%p", port);
733 CHECK_OPEN_PORT();
735 DEBUG_FMT("Draining port %s", port->name);
737 #ifdef _WIN32
738 /* Returns non-zero upon success, 0 upon failure. */
739 if (FlushFileBuffers(port->hdl) == 0)
740 RETURN_FAIL("FlushFileBuffers() failed");
741 RETURN_OK();
742 #else
743 int result;
744 while (1) {
745 #ifdef __ANDROID__
746 int arg = 1;
747 result = ioctl(port->fd, TCSBRK, &arg);
748 #else
749 result = tcdrain(port->fd);
750 #endif
751 if (result < 0) {
752 if (errno == EINTR) {
753 DEBUG("tcdrain() was interrupted");
754 continue;
755 } else {
756 RETURN_FAIL("tcdrain() failed");
758 } else {
759 RETURN_OK();
762 #endif
765 #ifdef _WIN32
766 static enum sp_return await_write_completion(struct sp_port *port)
768 TRACE("%p", port);
769 DWORD bytes_written;
770 BOOL result;
772 /* Wait for previous non-blocking write to complete, if any. */
773 if (port->writing) {
774 DEBUG("Waiting for previous write to complete");
775 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
776 port->writing = 0;
777 if (!result)
778 RETURN_FAIL("Previous write failed to complete");
779 DEBUG("Previous write completed");
782 RETURN_OK();
784 #endif
786 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
787 size_t count, unsigned int timeout_ms)
789 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
791 CHECK_OPEN_PORT();
793 if (!buf)
794 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
796 if (timeout_ms)
797 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
798 count, port->name, timeout_ms);
799 else
800 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
801 count, port->name);
803 if (count == 0)
804 RETURN_INT(0);
806 #ifdef _WIN32
807 DWORD bytes_written = 0;
809 TRY(await_write_completion(port));
811 /* Set timeout. */
812 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
813 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
814 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
815 RETURN_FAIL("SetCommTimeouts() failed");
818 /* Reduce count if it exceeds the WriteFile limit. */
819 if (count > WRITEFILE_MAX_SIZE)
820 count = WRITEFILE_MAX_SIZE;
822 /* Start write. */
823 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
824 DEBUG("Write completed immediately");
825 RETURN_INT(count);
826 } else if (GetLastError() == ERROR_IO_PENDING) {
827 DEBUG("Waiting for write to complete");
828 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
829 if (GetLastError() == ERROR_SEM_TIMEOUT) {
830 DEBUG("Write timed out");
831 RETURN_INT(0);
832 } else {
833 RETURN_FAIL("GetOverlappedResult() failed");
836 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
837 RETURN_INT(bytes_written);
838 } else {
839 RETURN_FAIL("WriteFile() failed");
841 #else
842 size_t bytes_written = 0;
843 unsigned char *ptr = (unsigned char *) buf;
844 struct timeval start, delta, now, end = {0, 0};
845 int started = 0;
846 fd_set fds;
847 int result;
849 if (timeout_ms) {
850 /* Get time at start of operation. */
851 get_time(&start);
852 /* Define duration of timeout. */
853 delta.tv_sec = timeout_ms / 1000;
854 delta.tv_usec = (timeout_ms % 1000) * 1000;
855 /* Calculate time at which we should give up. */
856 timeradd(&start, &delta, &end);
859 FD_ZERO(&fds);
860 FD_SET(port->fd, &fds);
862 /* Loop until we have written the requested number of bytes. */
863 while (bytes_written < count) {
865 * Check timeout only if we have run select() at least once,
866 * to avoid any issues if a short timeout is reached before
867 * select() is even run.
869 if (timeout_ms && started) {
870 get_time(&now);
871 if (timercmp(&now, &end, >))
872 /* Timeout has expired. */
873 break;
874 timersub(&end, &now, &delta);
876 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
877 started = 1;
878 if (result < 0) {
879 if (errno == EINTR) {
880 DEBUG("select() call was interrupted, repeating");
881 continue;
882 } else {
883 RETURN_FAIL("select() failed");
885 } else if (result == 0) {
886 /* Timeout has expired. */
887 break;
890 /* Do write. */
891 result = write(port->fd, ptr, count - bytes_written);
893 if (result < 0) {
894 if (errno == EAGAIN)
895 /* This shouldn't happen because we did a select() first, but handle anyway. */
896 continue;
897 else
898 /* This is an actual failure. */
899 RETURN_FAIL("write() failed");
902 bytes_written += result;
903 ptr += result;
906 if (bytes_written < count)
907 DEBUG("Write timed out");
909 RETURN_INT(bytes_written);
910 #endif
913 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
914 const void *buf, size_t count)
916 TRACE("%p, %p, %d", port, buf, count);
918 CHECK_OPEN_PORT();
920 if (!buf)
921 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
923 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
925 if (count == 0)
926 RETURN_INT(0);
928 #ifdef _WIN32
929 DWORD buf_bytes;
931 /* Check whether previous write is complete. */
932 if (port->writing) {
933 if (HasOverlappedIoCompleted(&port->write_ovl)) {
934 DEBUG("Previous write completed");
935 port->writing = 0;
936 } else {
937 DEBUG("Previous write not complete");
938 /* Can't take a new write until the previous one finishes. */
939 RETURN_INT(0);
943 /* Set timeout. */
944 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
945 port->timeouts.WriteTotalTimeoutConstant = 0;
946 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
947 RETURN_FAIL("SetCommTimeouts() failed");
950 /* Reduce count if it exceeds the WriteFile limit. */
951 if (count > WRITEFILE_MAX_SIZE)
952 count = WRITEFILE_MAX_SIZE;
954 /* Copy data to our write buffer. */
955 buf_bytes = min(port->write_buf_size, count);
956 memcpy(port->write_buf, buf, buf_bytes);
958 /* Start asynchronous write. */
959 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
960 if (GetLastError() == ERROR_IO_PENDING) {
961 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
962 DEBUG("Asynchronous write completed immediately");
963 else
964 DEBUG("Asynchronous write running");
965 } else {
966 /* Actual failure of some kind. */
967 RETURN_FAIL("WriteFile() failed");
971 DEBUG("All bytes written immediately");
973 RETURN_INT(buf_bytes);
974 #else
975 /* Returns the number of bytes written, or -1 upon failure. */
976 ssize_t written = write(port->fd, buf, count);
978 if (written < 0) {
979 if (errno == EAGAIN)
980 // Buffer is full, no bytes written.
981 RETURN_INT(0);
982 else
983 RETURN_FAIL("write() failed");
984 } else {
985 RETURN_INT(written);
987 #endif
990 #ifdef _WIN32
991 /* Restart wait operation if buffer was emptied. */
992 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
994 DWORD errors;
995 COMSTAT comstat;
997 if (bytes_read == 0)
998 RETURN_OK();
1000 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1001 RETURN_FAIL("ClearCommError() failed");
1003 if (comstat.cbInQue == 0)
1004 TRY(restart_wait(port));
1006 RETURN_OK();
1008 #endif
1010 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1011 size_t count, unsigned int timeout_ms)
1013 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1015 CHECK_OPEN_PORT();
1017 if (!buf)
1018 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1020 if (timeout_ms)
1021 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1022 count, port->name, timeout_ms);
1023 else
1024 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1025 count, port->name);
1027 if (count == 0)
1028 RETURN_INT(0);
1030 #ifdef _WIN32
1031 DWORD bytes_read = 0;
1033 /* Set timeout. */
1034 if (port->timeouts.ReadIntervalTimeout != 0 ||
1035 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1036 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1037 port->timeouts.ReadIntervalTimeout = 0;
1038 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1039 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1040 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1041 RETURN_FAIL("SetCommTimeouts() failed");
1044 /* Start read. */
1045 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1046 DEBUG("Read completed immediately");
1047 bytes_read = count;
1048 } else if (GetLastError() == ERROR_IO_PENDING) {
1049 DEBUG("Waiting for read to complete");
1050 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1051 RETURN_FAIL("GetOverlappedResult() failed");
1052 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1053 } else {
1054 RETURN_FAIL("ReadFile() failed");
1057 TRY(restart_wait_if_needed(port, bytes_read));
1059 RETURN_INT(bytes_read);
1061 #else
1062 size_t bytes_read = 0;
1063 unsigned char *ptr = (unsigned char *)buf;
1064 struct timeval start, delta, now, end = {0, 0};
1065 int started = 0;
1066 fd_set fds;
1067 int result;
1069 if (timeout_ms) {
1070 /* Get time at start of operation. */
1071 get_time(&start);
1072 /* Define duration of timeout. */
1073 delta.tv_sec = timeout_ms / 1000;
1074 delta.tv_usec = (timeout_ms % 1000) * 1000;
1075 /* Calculate time at which we should give up. */
1076 timeradd(&start, &delta, &end);
1079 FD_ZERO(&fds);
1080 FD_SET(port->fd, &fds);
1082 /* Loop until we have the requested number of bytes. */
1083 while (bytes_read < count) {
1085 * Check timeout only if we have run select() at least once,
1086 * to avoid any issues if a short timeout is reached before
1087 * select() is even run.
1089 if (timeout_ms && started) {
1090 get_time(&now);
1091 if (timercmp(&now, &end, >))
1092 /* Timeout has expired. */
1093 break;
1094 timersub(&end, &now, &delta);
1096 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1097 started = 1;
1098 if (result < 0) {
1099 if (errno == EINTR) {
1100 DEBUG("select() call was interrupted, repeating");
1101 continue;
1102 } else {
1103 RETURN_FAIL("select() failed");
1105 } else if (result == 0) {
1106 /* Timeout has expired. */
1107 break;
1110 /* Do read. */
1111 result = read(port->fd, ptr, count - bytes_read);
1113 if (result < 0) {
1114 if (errno == EAGAIN)
1116 * This shouldn't happen because we did a
1117 * select() first, but handle anyway.
1119 continue;
1120 else
1121 /* This is an actual failure. */
1122 RETURN_FAIL("read() failed");
1125 bytes_read += result;
1126 ptr += result;
1129 if (bytes_read < count)
1130 DEBUG("Read timed out");
1132 RETURN_INT(bytes_read);
1133 #endif
1136 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1137 size_t count, unsigned int timeout_ms)
1139 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1141 CHECK_OPEN_PORT();
1143 if (!buf)
1144 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1146 if (count == 0)
1147 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1149 if (timeout_ms)
1150 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1151 count, port->name, timeout_ms);
1152 else
1153 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1154 count, port->name);
1156 #ifdef _WIN32
1157 DWORD bytes_read = 0;
1159 /* If timeout_ms == 0, set maximum timeout. */
1160 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1162 /* Set timeout. */
1163 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1164 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1165 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1166 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1167 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1168 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1169 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1170 RETURN_FAIL("SetCommTimeouts() failed");
1173 /* Loop until we have at least one byte, or timeout is reached. */
1174 while (bytes_read == 0) {
1175 /* Start read. */
1176 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1177 DEBUG("Read completed immediately");
1178 } else if (GetLastError() == ERROR_IO_PENDING) {
1179 DEBUG("Waiting for read to complete");
1180 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1181 RETURN_FAIL("GetOverlappedResult() failed");
1182 if (bytes_read > 0) {
1183 DEBUG("Read completed");
1184 } else if (timeout_ms > 0) {
1185 DEBUG("Read timed out");
1186 break;
1187 } else {
1188 DEBUG("Restarting read");
1190 } else {
1191 RETURN_FAIL("ReadFile() failed");
1195 TRY(restart_wait_if_needed(port, bytes_read));
1197 RETURN_INT(bytes_read);
1199 #else
1200 size_t bytes_read = 0;
1201 struct timeval start, delta, now, end = {0, 0};
1202 int started = 0;
1203 fd_set fds;
1204 int result;
1206 if (timeout_ms) {
1207 /* Get time at start of operation. */
1208 get_time(&start);
1209 /* Define duration of timeout. */
1210 delta.tv_sec = timeout_ms / 1000;
1211 delta.tv_usec = (timeout_ms % 1000) * 1000;
1212 /* Calculate time at which we should give up. */
1213 timeradd(&start, &delta, &end);
1216 FD_ZERO(&fds);
1217 FD_SET(port->fd, &fds);
1219 /* Loop until we have at least one byte, or timeout is reached. */
1220 while (bytes_read == 0) {
1222 * Check timeout only if we have run select() at least once,
1223 * to avoid any issues if a short timeout is reached before
1224 * select() is even run.
1226 if (timeout_ms && started) {
1227 get_time(&now);
1228 if (timercmp(&now, &end, >))
1229 /* Timeout has expired. */
1230 break;
1231 timersub(&end, &now, &delta);
1233 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1234 started = 1;
1235 if (result < 0) {
1236 if (errno == EINTR) {
1237 DEBUG("select() call was interrupted, repeating");
1238 continue;
1239 } else {
1240 RETURN_FAIL("select() failed");
1242 } else if (result == 0) {
1243 /* Timeout has expired. */
1244 break;
1247 /* Do read. */
1248 result = read(port->fd, buf, count);
1250 if (result < 0) {
1251 if (errno == EAGAIN)
1252 /* This shouldn't happen because we did a select() first, but handle anyway. */
1253 continue;
1254 else
1255 /* This is an actual failure. */
1256 RETURN_FAIL("read() failed");
1259 bytes_read = result;
1262 if (bytes_read == 0)
1263 DEBUG("Read timed out");
1265 RETURN_INT(bytes_read);
1266 #endif
1269 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1270 size_t count)
1272 TRACE("%p, %p, %d", port, buf, count);
1274 CHECK_OPEN_PORT();
1276 if (!buf)
1277 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1279 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1281 #ifdef _WIN32
1282 DWORD bytes_read;
1284 /* Set timeout. */
1285 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1286 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1287 port->timeouts.ReadTotalTimeoutConstant != 0) {
1288 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1289 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1290 port->timeouts.ReadTotalTimeoutConstant = 0;
1291 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1292 RETURN_FAIL("SetCommTimeouts() failed");
1295 /* Do read. */
1296 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1297 if (GetLastError() != ERROR_IO_PENDING)
1298 RETURN_FAIL("ReadFile() failed");
1300 /* Get number of bytes read. */
1301 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1302 RETURN_FAIL("GetOverlappedResult() failed");
1304 TRY(restart_wait_if_needed(port, bytes_read));
1306 RETURN_INT(bytes_read);
1307 #else
1308 ssize_t bytes_read;
1310 /* Returns the number of bytes read, or -1 upon failure. */
1311 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1312 if (errno == EAGAIN)
1313 /* No bytes available. */
1314 bytes_read = 0;
1315 else
1316 /* This is an actual failure. */
1317 RETURN_FAIL("read() failed");
1319 RETURN_INT(bytes_read);
1320 #endif
1323 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1325 TRACE("%p", port);
1327 CHECK_OPEN_PORT();
1329 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1331 #ifdef _WIN32
1332 DWORD errors;
1333 COMSTAT comstat;
1335 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1336 RETURN_FAIL("ClearCommError() failed");
1337 RETURN_INT(comstat.cbInQue);
1338 #else
1339 int bytes_waiting;
1340 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1341 RETURN_FAIL("TIOCINQ ioctl failed");
1342 RETURN_INT(bytes_waiting);
1343 #endif
1346 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1348 TRACE("%p", port);
1350 CHECK_OPEN_PORT();
1352 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1354 #ifdef _WIN32
1355 DWORD errors;
1356 COMSTAT comstat;
1358 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1359 RETURN_FAIL("ClearCommError() failed");
1360 RETURN_INT(comstat.cbOutQue);
1361 #else
1362 int bytes_waiting;
1363 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1364 RETURN_FAIL("TIOCOUTQ ioctl failed");
1365 RETURN_INT(bytes_waiting);
1366 #endif
1369 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1371 struct sp_event_set *result;
1373 TRACE("%p", result_ptr);
1375 if (!result_ptr)
1376 RETURN_ERROR(SP_ERR_ARG, "Null result");
1378 *result_ptr = NULL;
1380 if (!(result = malloc(sizeof(struct sp_event_set))))
1381 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1383 memset(result, 0, sizeof(struct sp_event_set));
1385 *result_ptr = result;
1387 RETURN_OK();
1390 static enum sp_return add_handle(struct sp_event_set *event_set,
1391 event_handle handle, enum sp_event mask)
1393 void *new_handles;
1394 enum sp_event *new_masks;
1396 TRACE("%p, %d, %d", event_set, handle, mask);
1398 if (!(new_handles = realloc(event_set->handles,
1399 sizeof(event_handle) * (event_set->count + 1))))
1400 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1402 event_set->handles = new_handles;
1404 if (!(new_masks = realloc(event_set->masks,
1405 sizeof(enum sp_event) * (event_set->count + 1))))
1406 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1408 event_set->masks = new_masks;
1410 ((event_handle *) event_set->handles)[event_set->count] = handle;
1411 event_set->masks[event_set->count] = mask;
1413 event_set->count++;
1415 RETURN_OK();
1418 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1419 const struct sp_port *port, enum sp_event mask)
1421 TRACE("%p, %p, %d", event_set, port, mask);
1423 if (!event_set)
1424 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1426 if (!port)
1427 RETURN_ERROR(SP_ERR_ARG, "Null port");
1429 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1430 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1432 if (!mask)
1433 RETURN_OK();
1435 #ifdef _WIN32
1436 enum sp_event handle_mask;
1437 if ((handle_mask = mask & SP_EVENT_TX_READY))
1438 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1439 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1440 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1441 #else
1442 TRY(add_handle(event_set, port->fd, mask));
1443 #endif
1445 RETURN_OK();
1448 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1450 TRACE("%p", event_set);
1452 if (!event_set) {
1453 DEBUG("Null event set");
1454 RETURN();
1457 DEBUG("Freeing event set");
1459 if (event_set->handles)
1460 free(event_set->handles);
1461 if (event_set->masks)
1462 free(event_set->masks);
1464 free(event_set);
1466 RETURN();
1469 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1470 unsigned int timeout_ms)
1472 TRACE("%p, %d", event_set, timeout_ms);
1474 if (!event_set)
1475 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1477 #ifdef _WIN32
1478 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1479 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1480 RETURN_FAIL("WaitForMultipleObjects() failed");
1482 RETURN_OK();
1483 #else
1484 struct timeval start, delta, now, end = {0, 0};
1485 const struct timeval max_delta = {
1486 (INT_MAX / 1000), (INT_MAX % 1000) * 1000
1488 int started = 0, timeout_overflow = 0;
1489 int result, timeout_remaining_ms;
1490 struct pollfd *pollfds;
1491 unsigned int i;
1493 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1494 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1496 for (i = 0; i < event_set->count; i++) {
1497 pollfds[i].fd = ((int *)event_set->handles)[i];
1498 pollfds[i].events = 0;
1499 pollfds[i].revents = 0;
1500 if (event_set->masks[i] & SP_EVENT_RX_READY)
1501 pollfds[i].events |= POLLIN;
1502 if (event_set->masks[i] & SP_EVENT_TX_READY)
1503 pollfds[i].events |= POLLOUT;
1504 if (event_set->masks[i] & SP_EVENT_ERROR)
1505 pollfds[i].events |= POLLERR;
1508 if (timeout_ms) {
1509 /* Get time at start of operation. */
1510 get_time(&start);
1511 /* Define duration of timeout. */
1512 delta.tv_sec = timeout_ms / 1000;
1513 delta.tv_usec = (timeout_ms % 1000) * 1000;
1514 /* Calculate time at which we should give up. */
1515 timeradd(&start, &delta, &end);
1518 /* Loop until an event occurs. */
1519 while (1) {
1521 * Check timeout only if we have run poll() at least once,
1522 * to avoid any issues if a short timeout is reached before
1523 * poll() is even run.
1525 if (!timeout_ms) {
1526 timeout_remaining_ms = -1;
1527 } else if (!started) {
1528 timeout_overflow = (timeout_ms > INT_MAX);
1529 timeout_remaining_ms = timeout_overflow ? INT_MAX : timeout_ms;
1530 } else {
1531 get_time(&now);
1532 if (timercmp(&now, &end, >)) {
1533 DEBUG("Wait timed out");
1534 break;
1536 timersub(&end, &now, &delta);
1537 if ((timeout_overflow = timercmp(&delta, &max_delta, >)))
1538 delta = max_delta;
1539 timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1542 result = poll(pollfds, event_set->count, timeout_remaining_ms);
1543 started = 1;
1545 if (result < 0) {
1546 if (errno == EINTR) {
1547 DEBUG("poll() call was interrupted, repeating");
1548 continue;
1549 } else {
1550 free(pollfds);
1551 RETURN_FAIL("poll() failed");
1553 } else if (result == 0) {
1554 DEBUG("poll() timed out");
1555 if (!timeout_overflow)
1556 break;
1557 } else {
1558 DEBUG("poll() completed");
1559 break;
1563 free(pollfds);
1564 RETURN_OK();
1565 #endif
1568 #ifdef USE_TERMIOS_SPEED
1569 static enum sp_return get_baudrate(int fd, int *baudrate)
1571 void *data;
1573 TRACE("%d, %p", fd, baudrate);
1575 DEBUG("Getting baud rate");
1577 if (!(data = malloc(get_termios_size())))
1578 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1580 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1581 free(data);
1582 RETURN_FAIL("Getting termios failed");
1585 *baudrate = get_termios_speed(data);
1587 free(data);
1589 RETURN_OK();
1592 static enum sp_return set_baudrate(int fd, int baudrate)
1594 void *data;
1596 TRACE("%d, %d", fd, baudrate);
1598 DEBUG("Getting baud rate");
1600 if (!(data = malloc(get_termios_size())))
1601 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1603 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1604 free(data);
1605 RETURN_FAIL("Getting termios failed");
1608 DEBUG("Setting baud rate");
1610 set_termios_speed(data, baudrate);
1612 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1613 free(data);
1614 RETURN_FAIL("Setting termios failed");
1617 free(data);
1619 RETURN_OK();
1621 #endif /* USE_TERMIOS_SPEED */
1623 #ifdef USE_TERMIOX
1624 static enum sp_return get_flow(int fd, struct port_data *data)
1626 void *termx;
1628 TRACE("%d, %p", fd, data);
1630 DEBUG("Getting advanced flow control");
1632 if (!(termx = malloc(get_termiox_size())))
1633 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1635 if (ioctl(fd, TCGETX, termx) < 0) {
1636 free(termx);
1637 RETURN_FAIL("Getting termiox failed");
1640 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1641 &data->dtr_flow, &data->dsr_flow);
1643 free(termx);
1645 RETURN_OK();
1648 static enum sp_return set_flow(int fd, struct port_data *data)
1650 void *termx;
1652 TRACE("%d, %p", fd, data);
1654 DEBUG("Getting advanced flow control");
1656 if (!(termx = malloc(get_termiox_size())))
1657 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1659 if (ioctl(fd, TCGETX, termx) < 0) {
1660 free(termx);
1661 RETURN_FAIL("Getting termiox failed");
1664 DEBUG("Setting advanced flow control");
1666 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1667 data->dtr_flow, data->dsr_flow);
1669 if (ioctl(fd, TCSETX, termx) < 0) {
1670 free(termx);
1671 RETURN_FAIL("Setting termiox failed");
1674 free(termx);
1676 RETURN_OK();
1678 #endif /* USE_TERMIOX */
1680 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1681 struct sp_port_config *config)
1683 unsigned int i;
1685 TRACE("%p, %p, %p", port, data, config);
1687 DEBUG_FMT("Getting configuration for port %s", port->name);
1689 #ifdef _WIN32
1690 if (!GetCommState(port->hdl, &data->dcb))
1691 RETURN_FAIL("GetCommState() failed");
1693 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1694 if (data->dcb.BaudRate == std_baudrates[i].index) {
1695 config->baudrate = std_baudrates[i].value;
1696 break;
1700 if (i == NUM_STD_BAUDRATES)
1701 /* BaudRate field can be either an index or a custom baud rate. */
1702 config->baudrate = data->dcb.BaudRate;
1704 config->bits = data->dcb.ByteSize;
1706 if (data->dcb.fParity)
1707 switch (data->dcb.Parity) {
1708 case NOPARITY:
1709 config->parity = SP_PARITY_NONE;
1710 break;
1711 case ODDPARITY:
1712 config->parity = SP_PARITY_ODD;
1713 break;
1714 case EVENPARITY:
1715 config->parity = SP_PARITY_EVEN;
1716 break;
1717 case MARKPARITY:
1718 config->parity = SP_PARITY_MARK;
1719 break;
1720 case SPACEPARITY:
1721 config->parity = SP_PARITY_SPACE;
1722 break;
1723 default:
1724 config->parity = -1;
1726 else
1727 config->parity = SP_PARITY_NONE;
1729 switch (data->dcb.StopBits) {
1730 case ONESTOPBIT:
1731 config->stopbits = 1;
1732 break;
1733 case TWOSTOPBITS:
1734 config->stopbits = 2;
1735 break;
1736 default:
1737 config->stopbits = -1;
1740 switch (data->dcb.fRtsControl) {
1741 case RTS_CONTROL_DISABLE:
1742 config->rts = SP_RTS_OFF;
1743 break;
1744 case RTS_CONTROL_ENABLE:
1745 config->rts = SP_RTS_ON;
1746 break;
1747 case RTS_CONTROL_HANDSHAKE:
1748 config->rts = SP_RTS_FLOW_CONTROL;
1749 break;
1750 default:
1751 config->rts = -1;
1754 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1756 switch (data->dcb.fDtrControl) {
1757 case DTR_CONTROL_DISABLE:
1758 config->dtr = SP_DTR_OFF;
1759 break;
1760 case DTR_CONTROL_ENABLE:
1761 config->dtr = SP_DTR_ON;
1762 break;
1763 case DTR_CONTROL_HANDSHAKE:
1764 config->dtr = SP_DTR_FLOW_CONTROL;
1765 break;
1766 default:
1767 config->dtr = -1;
1770 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1772 if (data->dcb.fInX) {
1773 if (data->dcb.fOutX)
1774 config->xon_xoff = SP_XONXOFF_INOUT;
1775 else
1776 config->xon_xoff = SP_XONXOFF_IN;
1777 } else {
1778 if (data->dcb.fOutX)
1779 config->xon_xoff = SP_XONXOFF_OUT;
1780 else
1781 config->xon_xoff = SP_XONXOFF_DISABLED;
1784 #else // !_WIN32
1786 if (tcgetattr(port->fd, &data->term) < 0)
1787 RETURN_FAIL("tcgetattr() failed");
1789 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1790 RETURN_FAIL("TIOCMGET ioctl failed");
1792 #ifdef USE_TERMIOX
1793 int ret = get_flow(port->fd, data);
1795 if (ret == SP_ERR_FAIL && errno == EINVAL)
1796 data->termiox_supported = 0;
1797 else if (ret < 0)
1798 RETURN_CODEVAL(ret);
1799 else
1800 data->termiox_supported = 1;
1801 #else
1802 data->termiox_supported = 0;
1803 #endif
1805 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1806 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1807 config->baudrate = std_baudrates[i].value;
1808 break;
1812 if (i == NUM_STD_BAUDRATES) {
1813 #ifdef __APPLE__
1814 config->baudrate = (int)data->term.c_ispeed;
1815 #elif defined(USE_TERMIOS_SPEED)
1816 TRY(get_baudrate(port->fd, &config->baudrate));
1817 #else
1818 config->baudrate = -1;
1819 #endif
1822 switch (data->term.c_cflag & CSIZE) {
1823 case CS8:
1824 config->bits = 8;
1825 break;
1826 case CS7:
1827 config->bits = 7;
1828 break;
1829 case CS6:
1830 config->bits = 6;
1831 break;
1832 case CS5:
1833 config->bits = 5;
1834 break;
1835 default:
1836 config->bits = -1;
1839 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1840 config->parity = SP_PARITY_NONE;
1841 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1842 config->parity = -1;
1843 #ifdef CMSPAR
1844 else if (data->term.c_cflag & CMSPAR)
1845 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1846 #endif
1847 else
1848 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1850 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1852 if (data->term.c_cflag & CRTSCTS) {
1853 config->rts = SP_RTS_FLOW_CONTROL;
1854 config->cts = SP_CTS_FLOW_CONTROL;
1855 } else {
1856 if (data->termiox_supported && data->rts_flow)
1857 config->rts = SP_RTS_FLOW_CONTROL;
1858 else
1859 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1861 config->cts = (data->termiox_supported && data->cts_flow) ?
1862 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1865 if (data->termiox_supported && data->dtr_flow)
1866 config->dtr = SP_DTR_FLOW_CONTROL;
1867 else
1868 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1870 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1871 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1873 if (data->term.c_iflag & IXOFF) {
1874 if (data->term.c_iflag & IXON)
1875 config->xon_xoff = SP_XONXOFF_INOUT;
1876 else
1877 config->xon_xoff = SP_XONXOFF_IN;
1878 } else {
1879 if (data->term.c_iflag & IXON)
1880 config->xon_xoff = SP_XONXOFF_OUT;
1881 else
1882 config->xon_xoff = SP_XONXOFF_DISABLED;
1884 #endif
1886 RETURN_OK();
1889 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1890 const struct sp_port_config *config)
1892 unsigned int i;
1893 #ifdef __APPLE__
1894 BAUD_TYPE baud_nonstd;
1896 baud_nonstd = B0;
1897 #endif
1898 #ifdef USE_TERMIOS_SPEED
1899 int baud_nonstd = 0;
1900 #endif
1902 TRACE("%p, %p, %p", port, data, config);
1904 DEBUG_FMT("Setting configuration for port %s", port->name);
1906 #ifdef _WIN32
1908 TRY(await_write_completion(port));
1910 if (config->baudrate >= 0) {
1911 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1912 if (config->baudrate == std_baudrates[i].value) {
1913 data->dcb.BaudRate = std_baudrates[i].index;
1914 break;
1918 if (i == NUM_STD_BAUDRATES)
1919 data->dcb.BaudRate = config->baudrate;
1921 /* Allocate write buffer for 50ms of data at baud rate. */
1922 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1923 port->write_buf = realloc(port->write_buf,
1924 port->write_buf_size);
1926 if (!port->write_buf)
1927 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1930 if (config->bits >= 0)
1931 data->dcb.ByteSize = config->bits;
1933 if (config->parity >= 0) {
1934 switch (config->parity) {
1935 case SP_PARITY_NONE:
1936 data->dcb.Parity = NOPARITY;
1937 break;
1938 case SP_PARITY_ODD:
1939 data->dcb.Parity = ODDPARITY;
1940 break;
1941 case SP_PARITY_EVEN:
1942 data->dcb.Parity = EVENPARITY;
1943 break;
1944 case SP_PARITY_MARK:
1945 data->dcb.Parity = MARKPARITY;
1946 break;
1947 case SP_PARITY_SPACE:
1948 data->dcb.Parity = SPACEPARITY;
1949 break;
1950 default:
1951 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1955 if (config->stopbits >= 0) {
1956 switch (config->stopbits) {
1957 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1958 case 1:
1959 data->dcb.StopBits = ONESTOPBIT;
1960 break;
1961 case 2:
1962 data->dcb.StopBits = TWOSTOPBITS;
1963 break;
1964 default:
1965 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1969 if (config->rts >= 0) {
1970 switch (config->rts) {
1971 case SP_RTS_OFF:
1972 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1973 break;
1974 case SP_RTS_ON:
1975 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1976 break;
1977 case SP_RTS_FLOW_CONTROL:
1978 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1979 break;
1980 default:
1981 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1985 if (config->cts >= 0) {
1986 switch (config->cts) {
1987 case SP_CTS_IGNORE:
1988 data->dcb.fOutxCtsFlow = FALSE;
1989 break;
1990 case SP_CTS_FLOW_CONTROL:
1991 data->dcb.fOutxCtsFlow = TRUE;
1992 break;
1993 default:
1994 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1998 if (config->dtr >= 0) {
1999 switch (config->dtr) {
2000 case SP_DTR_OFF:
2001 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
2002 break;
2003 case SP_DTR_ON:
2004 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
2005 break;
2006 case SP_DTR_FLOW_CONTROL:
2007 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
2008 break;
2009 default:
2010 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
2014 if (config->dsr >= 0) {
2015 switch (config->dsr) {
2016 case SP_DSR_IGNORE:
2017 data->dcb.fOutxDsrFlow = FALSE;
2018 break;
2019 case SP_DSR_FLOW_CONTROL:
2020 data->dcb.fOutxDsrFlow = TRUE;
2021 break;
2022 default:
2023 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2027 if (config->xon_xoff >= 0) {
2028 switch (config->xon_xoff) {
2029 case SP_XONXOFF_DISABLED:
2030 data->dcb.fInX = FALSE;
2031 data->dcb.fOutX = FALSE;
2032 break;
2033 case SP_XONXOFF_IN:
2034 data->dcb.fInX = TRUE;
2035 data->dcb.fOutX = FALSE;
2036 break;
2037 case SP_XONXOFF_OUT:
2038 data->dcb.fInX = FALSE;
2039 data->dcb.fOutX = TRUE;
2040 break;
2041 case SP_XONXOFF_INOUT:
2042 data->dcb.fInX = TRUE;
2043 data->dcb.fOutX = TRUE;
2044 break;
2045 default:
2046 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2050 if (!SetCommState(port->hdl, &data->dcb))
2051 RETURN_FAIL("SetCommState() failed");
2053 #else /* !_WIN32 */
2055 int controlbits;
2057 if (config->baudrate >= 0) {
2058 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2059 if (config->baudrate == std_baudrates[i].value) {
2060 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2061 RETURN_FAIL("cfsetospeed() failed");
2063 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2064 RETURN_FAIL("cfsetispeed() failed");
2065 break;
2069 /* Non-standard baud rate */
2070 if (i == NUM_STD_BAUDRATES) {
2071 #ifdef __APPLE__
2072 /* Set "dummy" baud rate. */
2073 if (cfsetspeed(&data->term, B9600) < 0)
2074 RETURN_FAIL("cfsetspeed() failed");
2075 baud_nonstd = config->baudrate;
2076 #elif defined(USE_TERMIOS_SPEED)
2077 baud_nonstd = 1;
2078 #else
2079 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2080 #endif
2084 if (config->bits >= 0) {
2085 data->term.c_cflag &= ~CSIZE;
2086 switch (config->bits) {
2087 case 8:
2088 data->term.c_cflag |= CS8;
2089 break;
2090 case 7:
2091 data->term.c_cflag |= CS7;
2092 break;
2093 case 6:
2094 data->term.c_cflag |= CS6;
2095 break;
2096 case 5:
2097 data->term.c_cflag |= CS5;
2098 break;
2099 default:
2100 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2104 if (config->parity >= 0) {
2105 data->term.c_iflag &= ~IGNPAR;
2106 data->term.c_cflag &= ~(PARENB | PARODD);
2107 #ifdef CMSPAR
2108 data->term.c_cflag &= ~CMSPAR;
2109 #endif
2110 switch (config->parity) {
2111 case SP_PARITY_NONE:
2112 data->term.c_iflag |= IGNPAR;
2113 break;
2114 case SP_PARITY_EVEN:
2115 data->term.c_cflag |= PARENB;
2116 break;
2117 case SP_PARITY_ODD:
2118 data->term.c_cflag |= PARENB | PARODD;
2119 break;
2120 #ifdef CMSPAR
2121 case SP_PARITY_MARK:
2122 data->term.c_cflag |= PARENB | PARODD;
2123 data->term.c_cflag |= CMSPAR;
2124 break;
2125 case SP_PARITY_SPACE:
2126 data->term.c_cflag |= PARENB;
2127 data->term.c_cflag |= CMSPAR;
2128 break;
2129 #else
2130 case SP_PARITY_MARK:
2131 case SP_PARITY_SPACE:
2132 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2133 #endif
2134 default:
2135 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2139 if (config->stopbits >= 0) {
2140 data->term.c_cflag &= ~CSTOPB;
2141 switch (config->stopbits) {
2142 case 1:
2143 data->term.c_cflag &= ~CSTOPB;
2144 break;
2145 case 2:
2146 data->term.c_cflag |= CSTOPB;
2147 break;
2148 default:
2149 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2153 if (config->rts >= 0 || config->cts >= 0) {
2154 if (data->termiox_supported) {
2155 data->rts_flow = data->cts_flow = 0;
2156 switch (config->rts) {
2157 case SP_RTS_OFF:
2158 case SP_RTS_ON:
2159 controlbits = TIOCM_RTS;
2160 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2161 RETURN_FAIL("Setting RTS signal level failed");
2162 break;
2163 case SP_RTS_FLOW_CONTROL:
2164 data->rts_flow = 1;
2165 break;
2166 default:
2167 break;
2169 if (config->cts == SP_CTS_FLOW_CONTROL)
2170 data->cts_flow = 1;
2172 if (data->rts_flow && data->cts_flow)
2173 data->term.c_iflag |= CRTSCTS;
2174 else
2175 data->term.c_iflag &= ~CRTSCTS;
2176 } else {
2177 /* Asymmetric use of RTS/CTS not supported. */
2178 if (data->term.c_iflag & CRTSCTS) {
2179 /* Flow control can only be disabled for both RTS & CTS together. */
2180 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2181 if (config->cts != SP_CTS_IGNORE)
2182 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2184 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2185 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2186 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2188 } else {
2189 /* Flow control can only be enabled for both RTS & CTS together. */
2190 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2191 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2192 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2195 if (config->rts >= 0) {
2196 if (config->rts == SP_RTS_FLOW_CONTROL) {
2197 data->term.c_iflag |= CRTSCTS;
2198 } else {
2199 controlbits = TIOCM_RTS;
2200 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2201 &controlbits) < 0)
2202 RETURN_FAIL("Setting RTS signal level failed");
2208 if (config->dtr >= 0 || config->dsr >= 0) {
2209 if (data->termiox_supported) {
2210 data->dtr_flow = data->dsr_flow = 0;
2211 switch (config->dtr) {
2212 case SP_DTR_OFF:
2213 case SP_DTR_ON:
2214 controlbits = TIOCM_DTR;
2215 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2216 RETURN_FAIL("Setting DTR signal level failed");
2217 break;
2218 case SP_DTR_FLOW_CONTROL:
2219 data->dtr_flow = 1;
2220 break;
2221 default:
2222 break;
2224 if (config->dsr == SP_DSR_FLOW_CONTROL)
2225 data->dsr_flow = 1;
2226 } else {
2227 /* DTR/DSR flow control not supported. */
2228 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2229 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2231 if (config->dtr >= 0) {
2232 controlbits = TIOCM_DTR;
2233 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2234 &controlbits) < 0)
2235 RETURN_FAIL("Setting DTR signal level failed");
2240 if (config->xon_xoff >= 0) {
2241 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2242 switch (config->xon_xoff) {
2243 case SP_XONXOFF_DISABLED:
2244 break;
2245 case SP_XONXOFF_IN:
2246 data->term.c_iflag |= IXOFF;
2247 break;
2248 case SP_XONXOFF_OUT:
2249 data->term.c_iflag |= IXON | IXANY;
2250 break;
2251 case SP_XONXOFF_INOUT:
2252 data->term.c_iflag |= IXON | IXOFF | IXANY;
2253 break;
2254 default:
2255 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2259 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2260 RETURN_FAIL("tcsetattr() failed");
2262 #ifdef __APPLE__
2263 if (baud_nonstd != B0) {
2264 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2265 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2267 * Set baud rates in data->term to correct, but incompatible
2268 * with tcsetattr() value, same as delivered by tcgetattr().
2270 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2271 RETURN_FAIL("cfsetspeed() failed");
2273 #elif defined(__linux__)
2274 #ifdef USE_TERMIOS_SPEED
2275 if (baud_nonstd)
2276 TRY(set_baudrate(port->fd, config->baudrate));
2277 #endif
2278 #ifdef USE_TERMIOX
2279 if (data->termiox_supported)
2280 TRY(set_flow(port->fd, data));
2281 #endif
2282 #endif
2284 #endif /* !_WIN32 */
2286 RETURN_OK();
2289 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2291 struct sp_port_config *config;
2293 TRACE("%p", config_ptr);
2295 if (!config_ptr)
2296 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2298 *config_ptr = NULL;
2300 if (!(config = malloc(sizeof(struct sp_port_config))))
2301 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2303 config->baudrate = -1;
2304 config->bits = -1;
2305 config->parity = -1;
2306 config->stopbits = -1;
2307 config->rts = -1;
2308 config->cts = -1;
2309 config->dtr = -1;
2310 config->dsr = -1;
2312 *config_ptr = config;
2314 RETURN_OK();
2317 SP_API void sp_free_config(struct sp_port_config *config)
2319 TRACE("%p", config);
2321 if (!config)
2322 DEBUG("Null config");
2323 else
2324 free(config);
2326 RETURN();
2329 SP_API enum sp_return sp_get_config(struct sp_port *port,
2330 struct sp_port_config *config)
2332 struct port_data data;
2334 TRACE("%p, %p", port, config);
2336 CHECK_OPEN_PORT();
2338 if (!config)
2339 RETURN_ERROR(SP_ERR_ARG, "Null config");
2341 TRY(get_config(port, &data, config));
2343 RETURN_OK();
2346 SP_API enum sp_return sp_set_config(struct sp_port *port,
2347 const struct sp_port_config *config)
2349 struct port_data data;
2350 struct sp_port_config prev_config;
2352 TRACE("%p, %p", port, config);
2354 CHECK_OPEN_PORT();
2356 if (!config)
2357 RETURN_ERROR(SP_ERR_ARG, "Null config");
2359 TRY(get_config(port, &data, &prev_config));
2360 TRY(set_config(port, &data, config));
2362 RETURN_OK();
2365 #define CREATE_ACCESSORS(x, type) \
2366 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2367 struct port_data data; \
2368 struct sp_port_config config; \
2369 TRACE("%p, %d", port, x); \
2370 CHECK_OPEN_PORT(); \
2371 TRY(get_config(port, &data, &config)); \
2372 config.x = x; \
2373 TRY(set_config(port, &data, &config)); \
2374 RETURN_OK(); \
2376 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2377 type *x) { \
2378 TRACE("%p, %p", config, x); \
2379 if (!x) \
2380 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2381 if (!config) \
2382 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2383 *x = config->x; \
2384 RETURN_OK(); \
2386 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2387 type x) { \
2388 TRACE("%p, %d", config, x); \
2389 if (!config) \
2390 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2391 config->x = x; \
2392 RETURN_OK(); \
2395 CREATE_ACCESSORS(baudrate, int)
2396 CREATE_ACCESSORS(bits, int)
2397 CREATE_ACCESSORS(parity, enum sp_parity)
2398 CREATE_ACCESSORS(stopbits, int)
2399 CREATE_ACCESSORS(rts, enum sp_rts)
2400 CREATE_ACCESSORS(cts, enum sp_cts)
2401 CREATE_ACCESSORS(dtr, enum sp_dtr)
2402 CREATE_ACCESSORS(dsr, enum sp_dsr)
2403 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2405 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2406 enum sp_flowcontrol flowcontrol)
2408 if (!config)
2409 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2411 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2412 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2414 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2415 config->xon_xoff = SP_XONXOFF_INOUT;
2416 else
2417 config->xon_xoff = SP_XONXOFF_DISABLED;
2419 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2420 config->rts = SP_RTS_FLOW_CONTROL;
2421 config->cts = SP_CTS_FLOW_CONTROL;
2422 } else {
2423 if (config->rts == SP_RTS_FLOW_CONTROL)
2424 config->rts = SP_RTS_ON;
2425 config->cts = SP_CTS_IGNORE;
2428 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2429 config->dtr = SP_DTR_FLOW_CONTROL;
2430 config->dsr = SP_DSR_FLOW_CONTROL;
2431 } else {
2432 if (config->dtr == SP_DTR_FLOW_CONTROL)
2433 config->dtr = SP_DTR_ON;
2434 config->dsr = SP_DSR_IGNORE;
2437 RETURN_OK();
2440 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2441 enum sp_flowcontrol flowcontrol)
2443 struct port_data data;
2444 struct sp_port_config config;
2446 TRACE("%p, %d", port, flowcontrol);
2448 CHECK_OPEN_PORT();
2450 TRY(get_config(port, &data, &config));
2452 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2454 TRY(set_config(port, &data, &config));
2456 RETURN_OK();
2459 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2460 enum sp_signal *signals)
2462 TRACE("%p, %p", port, signals);
2464 CHECK_OPEN_PORT();
2466 if (!signals)
2467 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2469 DEBUG_FMT("Getting control signals for port %s", port->name);
2471 *signals = 0;
2472 #ifdef _WIN32
2473 DWORD bits;
2474 if (GetCommModemStatus(port->hdl, &bits) == 0)
2475 RETURN_FAIL("GetCommModemStatus() failed");
2476 if (bits & MS_CTS_ON)
2477 *signals |= SP_SIG_CTS;
2478 if (bits & MS_DSR_ON)
2479 *signals |= SP_SIG_DSR;
2480 if (bits & MS_RLSD_ON)
2481 *signals |= SP_SIG_DCD;
2482 if (bits & MS_RING_ON)
2483 *signals |= SP_SIG_RI;
2484 #else
2485 int bits;
2486 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2487 RETURN_FAIL("TIOCMGET ioctl failed");
2488 if (bits & TIOCM_CTS)
2489 *signals |= SP_SIG_CTS;
2490 if (bits & TIOCM_DSR)
2491 *signals |= SP_SIG_DSR;
2492 if (bits & TIOCM_CAR)
2493 *signals |= SP_SIG_DCD;
2494 if (bits & TIOCM_RNG)
2495 *signals |= SP_SIG_RI;
2496 #endif
2497 RETURN_OK();
2500 SP_API enum sp_return sp_start_break(struct sp_port *port)
2502 TRACE("%p", port);
2504 CHECK_OPEN_PORT();
2505 #ifdef _WIN32
2506 if (SetCommBreak(port->hdl) == 0)
2507 RETURN_FAIL("SetCommBreak() failed");
2508 #else
2509 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2510 RETURN_FAIL("TIOCSBRK ioctl failed");
2511 #endif
2513 RETURN_OK();
2516 SP_API enum sp_return sp_end_break(struct sp_port *port)
2518 TRACE("%p", port);
2520 CHECK_OPEN_PORT();
2521 #ifdef _WIN32
2522 if (ClearCommBreak(port->hdl) == 0)
2523 RETURN_FAIL("ClearCommBreak() failed");
2524 #else
2525 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2526 RETURN_FAIL("TIOCCBRK ioctl failed");
2527 #endif
2529 RETURN_OK();
2532 SP_API int sp_last_error_code(void)
2534 TRACE_VOID();
2535 #ifdef _WIN32
2536 RETURN_INT(GetLastError());
2537 #else
2538 RETURN_INT(errno);
2539 #endif
2542 SP_API char *sp_last_error_message(void)
2544 TRACE_VOID();
2546 #ifdef _WIN32
2547 TCHAR *message;
2548 DWORD error = GetLastError();
2550 DWORD length = FormatMessage(
2551 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2552 FORMAT_MESSAGE_FROM_SYSTEM |
2553 FORMAT_MESSAGE_IGNORE_INSERTS,
2554 NULL,
2555 error,
2556 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2557 (LPTSTR) &message,
2558 0, NULL );
2560 if (length >= 2 && message[length - 2] == '\r')
2561 message[length - 2] = '\0';
2563 RETURN_STRING(message);
2564 #else
2565 RETURN_STRING(strerror(errno));
2566 #endif
2569 SP_API void sp_free_error_message(char *message)
2571 TRACE("%s", message);
2573 #ifdef _WIN32
2574 LocalFree(message);
2575 #else
2576 (void)message;
2577 #endif
2579 RETURN();
2582 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2584 TRACE("%p", handler);
2586 sp_debug_handler = handler;
2588 RETURN();
2591 SP_API void sp_default_debug_handler(const char *format, ...)
2593 va_list args;
2594 va_start(args, format);
2595 if (getenv("LIBSERIALPORT_DEBUG")) {
2596 fputs("sp: ", stderr);
2597 vfprintf(stderr, format, args);
2599 va_end(args);
2602 SP_API int sp_get_major_package_version(void)
2604 return SP_PACKAGE_VERSION_MAJOR;
2607 SP_API int sp_get_minor_package_version(void)
2609 return SP_PACKAGE_VERSION_MINOR;
2612 SP_API int sp_get_micro_package_version(void)
2614 return SP_PACKAGE_VERSION_MICRO;
2617 SP_API const char *sp_get_package_version_string(void)
2619 return SP_PACKAGE_VERSION_STRING;
2622 SP_API int sp_get_current_lib_version(void)
2624 return SP_LIB_VERSION_CURRENT;
2627 SP_API int sp_get_revision_lib_version(void)
2629 return SP_LIB_VERSION_REVISION;
2632 SP_API int sp_get_age_lib_version(void)
2634 return SP_LIB_VERSION_AGE;
2637 SP_API const char *sp_get_lib_version_string(void)
2639 return SP_LIB_VERSION_STRING;
2642 /** @} */