Open the file descriptor of a serial port on POSIX systems exclusively
[libserialport/gsi.git] / serialport.c
blob51fe0788fc4abd015adc9768d63c9288ac9e0593
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 "libserialport_internal.h"
26 static const struct std_baudrate std_baudrates[] = {
27 #ifdef _WIN32
29 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
30 * have documented CBR_* macros.
32 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
33 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
34 BAUD(115200), BAUD(128000), BAUD(256000),
35 #else
36 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
37 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
38 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
39 BAUD(230400),
40 #if !defined(__APPLE__) && !defined(__OpenBSD__)
41 BAUD(460800),
42 #endif
43 #endif
46 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
48 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
50 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
51 struct sp_port_config *config);
53 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
54 const struct sp_port_config *config);
56 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
58 struct sp_port *port;
59 #ifndef NO_PORT_METADATA
60 enum sp_return ret;
61 #endif
62 size_t len;
64 TRACE("%s, %p", portname, port_ptr);
66 if (!port_ptr)
67 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
69 *port_ptr = NULL;
71 if (!portname)
72 RETURN_ERROR(SP_ERR_ARG, "Null port name");
74 DEBUG_FMT("Building structure for port %s", portname);
76 #if !defined(_WIN32) && defined(HAVE_REALPATH)
78 * get_port_details() below tries to be too smart and figure out
79 * some transport properties from the port name which breaks with
80 * symlinks. Therefore we canonicalize the portname first.
82 char pathbuf[PATH_MAX + 1];
83 char *res = realpath(portname, pathbuf);
84 if (!res)
85 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
87 portname = pathbuf;
88 #endif
90 if (!(port = malloc(sizeof(struct sp_port))))
91 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
93 len = strlen(portname) + 1;
95 if (!(port->name = malloc(len))) {
96 free(port);
97 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
100 memcpy(port->name, portname, len);
102 #ifdef _WIN32
103 port->usb_path = NULL;
104 port->hdl = INVALID_HANDLE_VALUE;
105 port->write_buf = NULL;
106 port->write_buf_size = 0;
107 #else
108 port->fd = -1;
109 #endif
111 port->description = NULL;
112 port->transport = SP_TRANSPORT_NATIVE;
113 port->usb_bus = -1;
114 port->usb_address = -1;
115 port->usb_vid = -1;
116 port->usb_pid = -1;
117 port->usb_manufacturer = NULL;
118 port->usb_product = NULL;
119 port->usb_serial = NULL;
120 port->bluetooth_address = NULL;
122 #ifndef NO_PORT_METADATA
123 if ((ret = get_port_details(port)) != SP_OK) {
124 sp_free_port(port);
125 return ret;
127 #endif
129 *port_ptr = port;
131 RETURN_OK();
134 SP_API char *sp_get_port_name(const struct sp_port *port)
136 TRACE("%p", port);
138 if (!port)
139 return NULL;
141 RETURN_STRING(port->name);
144 SP_API char *sp_get_port_description(const struct sp_port *port)
146 TRACE("%p", port);
148 if (!port || !port->description)
149 return NULL;
151 RETURN_STRING(port->description);
154 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
156 TRACE("%p", port);
158 if (!port)
159 RETURN_ERROR(SP_ERR_ARG, "Null port");
161 RETURN_INT(port->transport);
164 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
165 int *usb_bus,int *usb_address)
167 TRACE("%p", port);
169 if (!port)
170 RETURN_ERROR(SP_ERR_ARG, "Null port");
171 if (port->transport != SP_TRANSPORT_USB)
172 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
173 if (port->usb_bus < 0 || port->usb_address < 0)
174 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
176 if (usb_bus)
177 *usb_bus = port->usb_bus;
178 if (usb_address)
179 *usb_address = port->usb_address;
181 RETURN_OK();
184 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
185 int *usb_vid, int *usb_pid)
187 TRACE("%p", port);
189 if (!port)
190 RETURN_ERROR(SP_ERR_ARG, "Null port");
191 if (port->transport != SP_TRANSPORT_USB)
192 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
193 if (port->usb_vid < 0 || port->usb_pid < 0)
194 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
196 if (usb_vid)
197 *usb_vid = port->usb_vid;
198 if (usb_pid)
199 *usb_pid = port->usb_pid;
201 RETURN_OK();
204 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
206 TRACE("%p", port);
208 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
209 return NULL;
211 RETURN_STRING(port->usb_manufacturer);
214 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
216 TRACE("%p", port);
218 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
219 return NULL;
221 RETURN_STRING(port->usb_product);
224 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
226 TRACE("%p", port);
228 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
229 return NULL;
231 RETURN_STRING(port->usb_serial);
234 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
236 TRACE("%p", port);
238 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
239 || !port->bluetooth_address)
240 return NULL;
242 RETURN_STRING(port->bluetooth_address);
245 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
246 void *result_ptr)
248 TRACE("%p, %p", port, result_ptr);
250 if (!port)
251 RETURN_ERROR(SP_ERR_ARG, "Null port");
252 if (!result_ptr)
253 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
255 #ifdef _WIN32
256 HANDLE *handle_ptr = result_ptr;
257 *handle_ptr = port->hdl;
258 #else
259 int *fd_ptr = result_ptr;
260 *fd_ptr = port->fd;
261 #endif
263 RETURN_OK();
266 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
267 struct sp_port **copy_ptr)
269 TRACE("%p, %p", port, copy_ptr);
271 if (!copy_ptr)
272 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
274 *copy_ptr = NULL;
276 if (!port)
277 RETURN_ERROR(SP_ERR_ARG, "Null port");
279 if (!port->name)
280 RETURN_ERROR(SP_ERR_ARG, "Null port name");
282 DEBUG("Copying port structure");
284 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
287 SP_API void sp_free_port(struct sp_port *port)
289 TRACE("%p", port);
291 if (!port) {
292 DEBUG("Null port");
293 RETURN();
296 DEBUG("Freeing port structure");
298 if (port->name)
299 free(port->name);
300 if (port->description)
301 free(port->description);
302 if (port->usb_manufacturer)
303 free(port->usb_manufacturer);
304 if (port->usb_product)
305 free(port->usb_product);
306 if (port->usb_serial)
307 free(port->usb_serial);
308 if (port->bluetooth_address)
309 free(port->bluetooth_address);
310 #ifdef _WIN32
311 if (port->usb_path)
312 free(port->usb_path);
313 if (port->write_buf)
314 free(port->write_buf);
315 #endif
317 free(port);
319 RETURN();
322 SP_PRIV struct sp_port **list_append(struct sp_port **list,
323 const char *portname)
325 void *tmp;
326 size_t count;
328 for (count = 0; list[count]; count++)
330 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
331 goto fail;
332 list = tmp;
333 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
334 goto fail;
335 list[count + 1] = NULL;
336 return list;
338 fail:
339 sp_free_port_list(list);
340 return NULL;
343 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
345 #ifndef NO_ENUMERATION
346 struct sp_port **list;
347 int ret;
348 #endif
350 TRACE("%p", list_ptr);
352 if (!list_ptr)
353 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
355 *list_ptr = NULL;
357 #ifdef NO_ENUMERATION
358 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
359 #else
360 DEBUG("Enumerating ports");
362 if (!(list = malloc(sizeof(struct sp_port *))))
363 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
365 list[0] = NULL;
367 ret = list_ports(&list);
369 if (ret == SP_OK) {
370 *list_ptr = list;
371 } else {
372 sp_free_port_list(list);
373 *list_ptr = NULL;
376 RETURN_CODEVAL(ret);
377 #endif
380 SP_API void sp_free_port_list(struct sp_port **list)
382 unsigned int i;
384 TRACE("%p", list);
386 if (!list) {
387 DEBUG("Null list");
388 RETURN();
391 DEBUG("Freeing port list");
393 for (i = 0; list[i]; i++)
394 sp_free_port(list[i]);
395 free(list);
397 RETURN();
400 #define CHECK_PORT() do { \
401 if (!port) \
402 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
403 if (!port->name) \
404 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
405 } while (0)
406 #ifdef _WIN32
407 #define CHECK_PORT_HANDLE() do { \
408 if (port->hdl == INVALID_HANDLE_VALUE) \
409 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
410 } while (0)
411 #else
412 #define CHECK_PORT_HANDLE() do { \
413 if (port->fd < 0) \
414 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
415 } while (0)
416 #endif
417 #define CHECK_OPEN_PORT() do { \
418 CHECK_PORT(); \
419 CHECK_PORT_HANDLE(); \
420 } while (0)
422 #ifdef WIN32
423 /** To be called after port receive buffer is emptied. */
424 static enum sp_return restart_wait(struct sp_port *port)
426 DWORD wait_result;
428 if (port->wait_running) {
429 /* Check status of running wait operation. */
430 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
431 &wait_result, FALSE)) {
432 DEBUG("Previous wait completed");
433 port->wait_running = FALSE;
434 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
435 DEBUG("Previous wait still running");
436 RETURN_OK();
437 } else {
438 RETURN_FAIL("GetOverlappedResult() failed");
442 if (!port->wait_running) {
443 /* Start new wait operation. */
444 if (WaitCommEvent(port->hdl, &port->events,
445 &port->wait_ovl)) {
446 DEBUG("New wait returned, events already pending");
447 } else if (GetLastError() == ERROR_IO_PENDING) {
448 DEBUG("New wait running in background");
449 port->wait_running = TRUE;
450 } else {
451 RETURN_FAIL("WaitCommEvent() failed");
455 RETURN_OK();
457 #endif
459 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
461 struct port_data data;
462 struct sp_port_config config;
463 enum sp_return ret;
465 TRACE("%p, 0x%x", port, flags);
467 CHECK_PORT();
469 if (flags > SP_MODE_READ_WRITE)
470 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
472 DEBUG_FMT("Opening port %s", port->name);
474 #ifdef _WIN32
475 DWORD desired_access = 0, flags_and_attributes = 0, errors;
476 char *escaped_port_name;
477 COMSTAT status;
479 /* Prefix port name with '\\.\' to work with ports above COM9. */
480 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
481 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
482 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
484 /* Map 'flags' to the OS-specific settings. */
485 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
486 if (flags & SP_MODE_READ)
487 desired_access |= GENERIC_READ;
488 if (flags & SP_MODE_WRITE)
489 desired_access |= GENERIC_WRITE;
491 port->hdl = CreateFileA(escaped_port_name, desired_access, 0, 0,
492 OPEN_EXISTING, flags_and_attributes, 0);
494 free(escaped_port_name);
496 if (port->hdl == INVALID_HANDLE_VALUE)
497 RETURN_FAIL("Port CreateFile() failed");
499 /* All timeouts initially disabled. */
500 port->timeouts.ReadIntervalTimeout = 0;
501 port->timeouts.ReadTotalTimeoutMultiplier = 0;
502 port->timeouts.ReadTotalTimeoutConstant = 0;
503 port->timeouts.WriteTotalTimeoutMultiplier = 0;
504 port->timeouts.WriteTotalTimeoutConstant = 0;
506 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
507 sp_close(port);
508 RETURN_FAIL("SetCommTimeouts() failed");
511 /* Prepare OVERLAPPED structures. */
512 #define INIT_OVERLAPPED(ovl) do { \
513 memset(&port->ovl, 0, sizeof(port->ovl)); \
514 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
515 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
516 == INVALID_HANDLE_VALUE) { \
517 sp_close(port); \
518 RETURN_FAIL(#ovl "CreateEvent() failed"); \
520 } while (0)
522 INIT_OVERLAPPED(read_ovl);
523 INIT_OVERLAPPED(write_ovl);
524 INIT_OVERLAPPED(wait_ovl);
526 /* Set event mask for RX and error events. */
527 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
528 sp_close(port);
529 RETURN_FAIL("SetCommMask() failed");
532 port->writing = FALSE;
533 port->wait_running = FALSE;
535 ret = restart_wait(port);
537 if (ret < 0) {
538 sp_close(port);
539 RETURN_CODEVAL(ret);
541 #else
542 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
544 /* Map 'flags' to the OS-specific settings. */
545 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
546 flags_local |= O_RDWR;
547 else if (flags & SP_MODE_READ)
548 flags_local |= O_RDONLY;
549 else if (flags & SP_MODE_WRITE)
550 flags_local |= O_WRONLY;
552 if ((port->fd = open(port->name, flags_local)) < 0)
553 RETURN_FAIL("open() failed");
556 * On POSIX in the default case the file descriptor of a serial port
557 * is not opened exclusively. Therefore the settings of a port are
558 * overwritten if the serial port is opened a second time. Windows
559 * opens all serial ports exclusively.
560 * So the idea is to open the serial ports alike in the exclusive mode.
562 * ioctl(*, TIOCEXCL) defines the file descriptor as exclusive. So all
563 * further open calls on the serial port will fail.
565 * There is a race condition if two processes open the same serial
566 * port. None of the processes will notice the exclusive ownership of
567 * the other process because ioctl() doesn't return an error code if
568 * the file descriptor is already marked as exclusive.
569 * This can be solved with flock(). It returns an error if the file
570 * descriptor is already locked by another process.
572 #ifdef HAVE_FLOCK
573 if (flock(port->fd, LOCK_EX | LOCK_NB) < 0)
574 RETURN_FAIL("flock() failed");
575 #endif
577 #ifdef TIOCEXCL
579 * Before Linux 3.8 ioctl(*, TIOCEXCL) was not implemented and could
580 * lead to EINVAL or ENOTTY.
581 * These errors aren't fatal and can be ignored.
583 if (ioctl(port->fd, TIOCEXCL) < 0 && errno != EINVAL && errno != ENOTTY)
584 RETURN_FAIL("ioctl() failed");
585 #endif
587 #endif
589 ret = get_config(port, &data, &config);
591 if (ret < 0) {
592 sp_close(port);
593 RETURN_CODEVAL(ret);
596 /* Set sane port settings. */
597 #ifdef _WIN32
598 data.dcb.fBinary = TRUE;
599 data.dcb.fDsrSensitivity = FALSE;
600 data.dcb.fErrorChar = FALSE;
601 data.dcb.fNull = FALSE;
602 data.dcb.fAbortOnError = FALSE;
603 #else
604 /* Turn off all fancy termios tricks, give us a raw channel. */
605 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
606 #ifdef IUCLC
607 data.term.c_iflag &= ~IUCLC;
608 #endif
609 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
610 #ifdef OLCUC
611 data.term.c_oflag &= ~OLCUC;
612 #endif
613 #ifdef NLDLY
614 data.term.c_oflag &= ~NLDLY;
615 #endif
616 #ifdef CRDLY
617 data.term.c_oflag &= ~CRDLY;
618 #endif
619 #ifdef TABDLY
620 data.term.c_oflag &= ~TABDLY;
621 #endif
622 #ifdef BSDLY
623 data.term.c_oflag &= ~BSDLY;
624 #endif
625 #ifdef VTDLY
626 data.term.c_oflag &= ~VTDLY;
627 #endif
628 #ifdef FFDLY
629 data.term.c_oflag &= ~FFDLY;
630 #endif
631 #ifdef OFILL
632 data.term.c_oflag &= ~OFILL;
633 #endif
634 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
635 data.term.c_cc[VMIN] = 0;
636 data.term.c_cc[VTIME] = 0;
638 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
639 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
640 #endif
642 #ifdef _WIN32
643 if (ClearCommError(port->hdl, &errors, &status) == 0)
644 RETURN_FAIL("ClearCommError() failed");
645 #endif
647 ret = set_config(port, &data, &config);
649 if (ret < 0) {
650 sp_close(port);
651 RETURN_CODEVAL(ret);
654 RETURN_OK();
657 SP_API enum sp_return sp_close(struct sp_port *port)
659 TRACE("%p", port);
661 CHECK_OPEN_PORT();
663 DEBUG_FMT("Closing port %s", port->name);
665 #ifdef _WIN32
666 /* Returns non-zero upon success, 0 upon failure. */
667 if (CloseHandle(port->hdl) == 0)
668 RETURN_FAIL("Port CloseHandle() failed");
669 port->hdl = INVALID_HANDLE_VALUE;
671 /* Close event handles for overlapped structures. */
672 #define CLOSE_OVERLAPPED(ovl) do { \
673 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
674 CloseHandle(port->ovl.hEvent) == 0) \
675 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
676 } while (0)
677 CLOSE_OVERLAPPED(read_ovl);
678 CLOSE_OVERLAPPED(write_ovl);
679 CLOSE_OVERLAPPED(wait_ovl);
681 if (port->write_buf) {
682 free(port->write_buf);
683 port->write_buf = NULL;
685 #else
686 /* Returns 0 upon success, -1 upon failure. */
687 if (close(port->fd) == -1)
688 RETURN_FAIL("close() failed");
689 port->fd = -1;
690 #endif
692 RETURN_OK();
695 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
697 TRACE("%p, 0x%x", port, buffers);
699 CHECK_OPEN_PORT();
701 if (buffers > SP_BUF_BOTH)
702 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
704 const char *buffer_names[] = {"no", "input", "output", "both"};
706 DEBUG_FMT("Flushing %s buffers on port %s",
707 buffer_names[buffers], port->name);
709 #ifdef _WIN32
710 DWORD flags = 0;
711 if (buffers & SP_BUF_INPUT)
712 flags |= PURGE_RXCLEAR;
713 if (buffers & SP_BUF_OUTPUT)
714 flags |= PURGE_TXCLEAR;
716 /* Returns non-zero upon success, 0 upon failure. */
717 if (PurgeComm(port->hdl, flags) == 0)
718 RETURN_FAIL("PurgeComm() failed");
720 if (buffers & SP_BUF_INPUT)
721 TRY(restart_wait(port));
722 #else
723 int flags = 0;
724 if (buffers == SP_BUF_BOTH)
725 flags = TCIOFLUSH;
726 else if (buffers == SP_BUF_INPUT)
727 flags = TCIFLUSH;
728 else if (buffers == SP_BUF_OUTPUT)
729 flags = TCOFLUSH;
731 /* Returns 0 upon success, -1 upon failure. */
732 if (tcflush(port->fd, flags) < 0)
733 RETURN_FAIL("tcflush() failed");
734 #endif
735 RETURN_OK();
738 SP_API enum sp_return sp_drain(struct sp_port *port)
740 TRACE("%p", port);
742 CHECK_OPEN_PORT();
744 DEBUG_FMT("Draining port %s", port->name);
746 #ifdef _WIN32
747 /* Returns non-zero upon success, 0 upon failure. */
748 if (FlushFileBuffers(port->hdl) == 0)
749 RETURN_FAIL("FlushFileBuffers() failed");
750 RETURN_OK();
751 #else
752 int result;
753 while (1) {
754 #if defined(__ANDROID__) && (__ANDROID_API__ < 21)
755 /* Android only has tcdrain from platform 21 onwards.
756 * On previous API versions, use the ioctl directly. */
757 int arg = 1;
758 result = ioctl(port->fd, TCSBRK, &arg);
759 #else
760 result = tcdrain(port->fd);
761 #endif
762 if (result < 0) {
763 if (errno == EINTR) {
764 DEBUG("tcdrain() was interrupted");
765 continue;
766 } else {
767 RETURN_FAIL("tcdrain() failed");
769 } else {
770 RETURN_OK();
773 #endif
776 #ifdef _WIN32
777 static enum sp_return await_write_completion(struct sp_port *port)
779 TRACE("%p", port);
780 DWORD bytes_written;
781 BOOL result;
783 /* Wait for previous non-blocking write to complete, if any. */
784 if (port->writing) {
785 DEBUG("Waiting for previous write to complete");
786 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
787 port->writing = 0;
788 if (!result)
789 RETURN_FAIL("Previous write failed to complete");
790 DEBUG("Previous write completed");
793 RETURN_OK();
795 #endif
797 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
798 size_t count, unsigned int timeout_ms)
800 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
802 CHECK_OPEN_PORT();
804 if (!buf)
805 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
807 if (timeout_ms)
808 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
809 count, port->name, timeout_ms);
810 else
811 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
812 count, port->name);
814 if (count == 0)
815 RETURN_INT(0);
817 #ifdef _WIN32
818 DWORD remaining_ms, write_size, bytes_written;
819 size_t remaining_bytes, total_bytes_written = 0;
820 const uint8_t *write_ptr = (uint8_t *) buf;
821 bool result;
822 struct timeout timeout;
824 timeout_start(&timeout, timeout_ms);
826 TRY(await_write_completion(port));
828 while (total_bytes_written < count) {
830 if (timeout_check(&timeout))
831 break;
833 remaining_ms = timeout_remaining_ms(&timeout);
835 if (port->timeouts.WriteTotalTimeoutConstant != remaining_ms) {
836 port->timeouts.WriteTotalTimeoutConstant = remaining_ms;
837 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
838 RETURN_FAIL("SetCommTimeouts() failed");
841 /* Reduce write size if it exceeds the WriteFile limit. */
842 remaining_bytes = count - total_bytes_written;
843 if (remaining_bytes > WRITEFILE_MAX_SIZE)
844 write_size = WRITEFILE_MAX_SIZE;
845 else
846 write_size = (DWORD) remaining_bytes;
848 /* Start write. */
850 result = WriteFile(port->hdl, write_ptr, write_size, NULL, &port->write_ovl);
852 timeout_update(&timeout);
854 if (result) {
855 DEBUG("Write completed immediately");
856 bytes_written = write_size;
857 } else if (GetLastError() == ERROR_IO_PENDING) {
858 DEBUG("Waiting for write to complete");
859 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
860 if (GetLastError() == ERROR_SEM_TIMEOUT) {
861 DEBUG("Write timed out");
862 break;
863 } else {
864 RETURN_FAIL("GetOverlappedResult() failed");
867 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, write_size);
868 } else {
869 RETURN_FAIL("WriteFile() failed");
872 write_ptr += bytes_written;
873 total_bytes_written += bytes_written;
876 RETURN_INT((int) total_bytes_written);
877 #else
878 size_t bytes_written = 0;
879 unsigned char *ptr = (unsigned char *) buf;
880 struct timeout timeout;
881 fd_set fds;
882 int result;
884 timeout_start(&timeout, timeout_ms);
886 FD_ZERO(&fds);
887 FD_SET(port->fd, &fds);
889 /* Loop until we have written the requested number of bytes. */
890 while (bytes_written < count) {
892 if (timeout_check(&timeout))
893 break;
895 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
897 timeout_update(&timeout);
899 if (result < 0) {
900 if (errno == EINTR) {
901 DEBUG("select() call was interrupted, repeating");
902 continue;
903 } else {
904 RETURN_FAIL("select() failed");
906 } else if (result == 0) {
907 /* Timeout has expired. */
908 break;
911 /* Do write. */
912 result = write(port->fd, ptr, count - bytes_written);
914 if (result < 0) {
915 if (errno == EAGAIN)
916 /* This shouldn't happen because we did a select() first, but handle anyway. */
917 continue;
918 else
919 /* This is an actual failure. */
920 RETURN_FAIL("write() failed");
923 bytes_written += result;
924 ptr += result;
927 if (bytes_written < count)
928 DEBUG("Write timed out");
930 RETURN_INT(bytes_written);
931 #endif
934 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
935 const void *buf, size_t count)
937 TRACE("%p, %p, %d", port, buf, count);
939 CHECK_OPEN_PORT();
941 if (!buf)
942 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
944 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
946 if (count == 0)
947 RETURN_INT(0);
949 #ifdef _WIN32
950 size_t buf_bytes;
952 /* Check whether previous write is complete. */
953 if (port->writing) {
954 if (HasOverlappedIoCompleted(&port->write_ovl)) {
955 DEBUG("Previous write completed");
956 port->writing = 0;
957 } else {
958 DEBUG("Previous write not complete");
959 /* Can't take a new write until the previous one finishes. */
960 RETURN_INT(0);
964 /* Set timeout. */
965 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
966 port->timeouts.WriteTotalTimeoutConstant = 0;
967 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
968 RETURN_FAIL("SetCommTimeouts() failed");
971 /* Reduce count if it exceeds the WriteFile limit. */
972 if (count > WRITEFILE_MAX_SIZE)
973 count = WRITEFILE_MAX_SIZE;
975 /* Copy data to our write buffer. */
976 buf_bytes = min(port->write_buf_size, count);
977 memcpy(port->write_buf, buf, buf_bytes);
979 /* Start asynchronous write. */
980 if (WriteFile(port->hdl, port->write_buf, (DWORD) buf_bytes, NULL, &port->write_ovl) == 0) {
981 if (GetLastError() == ERROR_IO_PENDING) {
982 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
983 DEBUG("Asynchronous write completed immediately");
984 else
985 DEBUG("Asynchronous write running");
986 } else {
987 /* Actual failure of some kind. */
988 RETURN_FAIL("WriteFile() failed");
992 DEBUG("All bytes written immediately");
994 RETURN_INT((int) buf_bytes);
995 #else
996 /* Returns the number of bytes written, or -1 upon failure. */
997 ssize_t written = write(port->fd, buf, count);
999 if (written < 0) {
1000 if (errno == EAGAIN)
1001 // Buffer is full, no bytes written.
1002 RETURN_INT(0);
1003 else
1004 RETURN_FAIL("write() failed");
1005 } else {
1006 RETURN_INT(written);
1008 #endif
1011 #ifdef _WIN32
1012 /* Restart wait operation if buffer was emptied. */
1013 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1015 DWORD errors;
1016 COMSTAT comstat;
1018 if (bytes_read == 0)
1019 RETURN_OK();
1021 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1022 RETURN_FAIL("ClearCommError() failed");
1024 if (comstat.cbInQue == 0)
1025 TRY(restart_wait(port));
1027 RETURN_OK();
1029 #endif
1031 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1032 size_t count, unsigned int timeout_ms)
1034 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1036 CHECK_OPEN_PORT();
1038 if (!buf)
1039 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1041 if (timeout_ms)
1042 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1043 count, port->name, timeout_ms);
1044 else
1045 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1046 count, port->name);
1048 if (count == 0)
1049 RETURN_INT(0);
1051 #ifdef _WIN32
1052 DWORD bytes_read;
1054 /* Set timeout. */
1055 if (port->timeouts.ReadIntervalTimeout != 0 ||
1056 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1057 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1058 port->timeouts.ReadIntervalTimeout = 0;
1059 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1060 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1061 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1062 RETURN_FAIL("SetCommTimeouts() failed");
1065 /* Start read. */
1066 if (ReadFile(port->hdl, buf, (DWORD) count, NULL, &port->read_ovl)) {
1067 DEBUG("Read completed immediately");
1068 bytes_read = (DWORD) count;
1069 } else if (GetLastError() == ERROR_IO_PENDING) {
1070 DEBUG("Waiting for read to complete");
1071 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1072 RETURN_FAIL("GetOverlappedResult() failed");
1073 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1074 } else {
1075 RETURN_FAIL("ReadFile() failed");
1078 TRY(restart_wait_if_needed(port, bytes_read));
1080 RETURN_INT((int) bytes_read);
1082 #else
1083 size_t bytes_read = 0;
1084 unsigned char *ptr = (unsigned char *) buf;
1085 struct timeout timeout;
1086 fd_set fds;
1087 int result;
1089 timeout_start(&timeout, timeout_ms);
1091 FD_ZERO(&fds);
1092 FD_SET(port->fd, &fds);
1094 /* Loop until we have the requested number of bytes. */
1095 while (bytes_read < count) {
1097 if (timeout_check(&timeout))
1098 /* Timeout has expired. */
1099 break;
1101 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1103 timeout_update(&timeout);
1105 if (result < 0) {
1106 if (errno == EINTR) {
1107 DEBUG("select() call was interrupted, repeating");
1108 continue;
1109 } else {
1110 RETURN_FAIL("select() failed");
1112 } else if (result == 0) {
1113 /* Timeout has expired. */
1114 break;
1117 /* Do read. */
1118 result = read(port->fd, ptr, count - bytes_read);
1120 if (result < 0) {
1121 if (errno == EAGAIN)
1123 * This shouldn't happen because we did a
1124 * select() first, but handle anyway.
1126 continue;
1127 else
1128 /* This is an actual failure. */
1129 RETURN_FAIL("read() failed");
1132 bytes_read += result;
1133 ptr += result;
1136 if (bytes_read < count)
1137 DEBUG("Read timed out");
1139 RETURN_INT(bytes_read);
1140 #endif
1143 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1144 size_t count, unsigned int timeout_ms)
1146 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1148 CHECK_OPEN_PORT();
1150 if (!buf)
1151 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1153 if (count == 0)
1154 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1156 if (timeout_ms)
1157 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1158 count, port->name, timeout_ms);
1159 else
1160 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1161 count, port->name);
1163 #ifdef _WIN32
1164 DWORD bytes_read = 0;
1166 /* If timeout_ms == 0, set maximum timeout. */
1167 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1169 /* Set timeout. */
1170 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1171 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1172 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1173 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1174 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1175 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1176 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1177 RETURN_FAIL("SetCommTimeouts() failed");
1180 /* Loop until we have at least one byte, or timeout is reached. */
1181 while (bytes_read == 0) {
1182 /* Start read. */
1183 if (ReadFile(port->hdl, buf, (DWORD) count, &bytes_read, &port->read_ovl)) {
1184 DEBUG("Read completed immediately");
1185 } else if (GetLastError() == ERROR_IO_PENDING) {
1186 DEBUG("Waiting for read to complete");
1187 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1188 RETURN_FAIL("GetOverlappedResult() failed");
1189 if (bytes_read > 0) {
1190 DEBUG("Read completed");
1191 } else if (timeout_ms > 0) {
1192 DEBUG("Read timed out");
1193 break;
1194 } else {
1195 DEBUG("Restarting read");
1197 } else {
1198 RETURN_FAIL("ReadFile() failed");
1202 TRY(restart_wait_if_needed(port, bytes_read));
1204 RETURN_INT(bytes_read);
1206 #else
1207 size_t bytes_read = 0;
1208 struct timeout timeout;
1209 fd_set fds;
1210 int result;
1212 timeout_start(&timeout, timeout_ms);
1214 FD_ZERO(&fds);
1215 FD_SET(port->fd, &fds);
1217 /* Loop until we have at least one byte, or timeout is reached. */
1218 while (bytes_read == 0) {
1220 if (timeout_check(&timeout))
1221 /* Timeout has expired. */
1222 break;
1224 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1226 timeout_update(&timeout);
1228 if (result < 0) {
1229 if (errno == EINTR) {
1230 DEBUG("select() call was interrupted, repeating");
1231 continue;
1232 } else {
1233 RETURN_FAIL("select() failed");
1235 } else if (result == 0) {
1236 /* Timeout has expired. */
1237 break;
1240 /* Do read. */
1241 result = read(port->fd, buf, count);
1243 if (result < 0) {
1244 if (errno == EAGAIN)
1245 /* This shouldn't happen because we did a select() first, but handle anyway. */
1246 continue;
1247 else
1248 /* This is an actual failure. */
1249 RETURN_FAIL("read() failed");
1252 bytes_read = result;
1255 if (bytes_read == 0)
1256 DEBUG("Read timed out");
1258 RETURN_INT(bytes_read);
1259 #endif
1262 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1263 size_t count)
1265 TRACE("%p, %p, %d", port, buf, count);
1267 CHECK_OPEN_PORT();
1269 if (!buf)
1270 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1272 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1274 #ifdef _WIN32
1275 DWORD bytes_read;
1277 /* Set timeout. */
1278 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1279 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1280 port->timeouts.ReadTotalTimeoutConstant != 0) {
1281 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1282 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1283 port->timeouts.ReadTotalTimeoutConstant = 0;
1284 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1285 RETURN_FAIL("SetCommTimeouts() failed");
1288 /* Do read. */
1289 if (ReadFile(port->hdl, buf, (DWORD) count, NULL, &port->read_ovl) == 0)
1290 if (GetLastError() != ERROR_IO_PENDING)
1291 RETURN_FAIL("ReadFile() failed");
1293 /* Get number of bytes read. */
1294 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1295 RETURN_FAIL("GetOverlappedResult() failed");
1297 TRY(restart_wait_if_needed(port, bytes_read));
1299 RETURN_INT(bytes_read);
1300 #else
1301 ssize_t bytes_read;
1303 /* Returns the number of bytes read, or -1 upon failure. */
1304 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1305 if (errno == EAGAIN)
1306 /* No bytes available. */
1307 bytes_read = 0;
1308 else
1309 /* This is an actual failure. */
1310 RETURN_FAIL("read() failed");
1312 RETURN_INT(bytes_read);
1313 #endif
1316 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1318 TRACE("%p", port);
1320 CHECK_OPEN_PORT();
1322 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1324 #ifdef _WIN32
1325 DWORD errors;
1326 COMSTAT comstat;
1328 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1329 RETURN_FAIL("ClearCommError() failed");
1330 RETURN_INT(comstat.cbInQue);
1331 #else
1332 int bytes_waiting;
1333 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1334 RETURN_FAIL("TIOCINQ ioctl failed");
1335 RETURN_INT(bytes_waiting);
1336 #endif
1339 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1341 TRACE("%p", port);
1343 #ifdef __CYGWIN__
1344 /* TIOCOUTQ is not defined in Cygwin headers */
1345 RETURN_ERROR(SP_ERR_SUPP,
1346 "Getting output bytes waiting is not supported on Cygwin");
1347 #else
1348 CHECK_OPEN_PORT();
1350 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1352 #ifdef _WIN32
1353 DWORD errors;
1354 COMSTAT comstat;
1356 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1357 RETURN_FAIL("ClearCommError() failed");
1358 RETURN_INT(comstat.cbOutQue);
1359 #else
1360 int bytes_waiting;
1361 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1362 RETURN_FAIL("TIOCOUTQ ioctl failed");
1363 RETURN_INT(bytes_waiting);
1364 #endif
1365 #endif
1368 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1370 struct sp_event_set *result;
1372 TRACE("%p", result_ptr);
1374 if (!result_ptr)
1375 RETURN_ERROR(SP_ERR_ARG, "Null result");
1377 *result_ptr = NULL;
1379 if (!(result = malloc(sizeof(struct sp_event_set))))
1380 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1382 memset(result, 0, sizeof(struct sp_event_set));
1384 *result_ptr = result;
1386 RETURN_OK();
1389 static enum sp_return add_handle(struct sp_event_set *event_set,
1390 event_handle handle, enum sp_event mask)
1392 void *new_handles;
1393 enum sp_event *new_masks;
1395 TRACE("%p, %d, %d", event_set, handle, mask);
1397 if (!(new_handles = realloc(event_set->handles,
1398 sizeof(event_handle) * (event_set->count + 1))))
1399 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1401 event_set->handles = new_handles;
1403 if (!(new_masks = realloc(event_set->masks,
1404 sizeof(enum sp_event) * (event_set->count + 1))))
1405 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1407 event_set->masks = new_masks;
1409 ((event_handle *) event_set->handles)[event_set->count] = handle;
1410 event_set->masks[event_set->count] = mask;
1412 event_set->count++;
1414 RETURN_OK();
1417 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1418 const struct sp_port *port, enum sp_event mask)
1420 TRACE("%p, %p, %d", event_set, port, mask);
1422 if (!event_set)
1423 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1425 if (!port)
1426 RETURN_ERROR(SP_ERR_ARG, "Null port");
1428 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1429 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1431 if (!mask)
1432 RETURN_OK();
1434 #ifdef _WIN32
1435 enum sp_event handle_mask;
1436 if ((handle_mask = mask & SP_EVENT_TX_READY))
1437 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1438 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1439 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1440 #else
1441 TRY(add_handle(event_set, port->fd, mask));
1442 #endif
1444 RETURN_OK();
1447 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1449 TRACE("%p", event_set);
1451 if (!event_set) {
1452 DEBUG("Null event set");
1453 RETURN();
1456 DEBUG("Freeing event set");
1458 if (event_set->handles)
1459 free(event_set->handles);
1460 if (event_set->masks)
1461 free(event_set->masks);
1463 free(event_set);
1465 RETURN();
1468 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1469 unsigned int timeout_ms)
1471 TRACE("%p, %d", event_set, timeout_ms);
1473 if (!event_set)
1474 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1476 #ifdef _WIN32
1477 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1478 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1479 RETURN_FAIL("WaitForMultipleObjects() failed");
1481 RETURN_OK();
1482 #else
1483 struct timeout timeout;
1484 int poll_timeout;
1485 int result;
1486 struct pollfd *pollfds;
1487 unsigned int i;
1489 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1490 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1492 for (i = 0; i < event_set->count; i++) {
1493 pollfds[i].fd = ((int *)event_set->handles)[i];
1494 pollfds[i].events = 0;
1495 pollfds[i].revents = 0;
1496 if (event_set->masks[i] & SP_EVENT_RX_READY)
1497 pollfds[i].events |= POLLIN;
1498 if (event_set->masks[i] & SP_EVENT_TX_READY)
1499 pollfds[i].events |= POLLOUT;
1500 if (event_set->masks[i] & SP_EVENT_ERROR)
1501 pollfds[i].events |= POLLERR;
1504 timeout_start(&timeout, timeout_ms);
1505 timeout_limit(&timeout, INT_MAX);
1507 /* Loop until an event occurs. */
1508 while (1) {
1510 if (timeout_check(&timeout)) {
1511 DEBUG("Wait timed out");
1512 break;
1515 poll_timeout = (int) timeout_remaining_ms(&timeout);
1516 if (poll_timeout == 0)
1517 poll_timeout = -1;
1519 result = poll(pollfds, event_set->count, poll_timeout);
1521 timeout_update(&timeout);
1523 if (result < 0) {
1524 if (errno == EINTR) {
1525 DEBUG("poll() call was interrupted, repeating");
1526 continue;
1527 } else {
1528 free(pollfds);
1529 RETURN_FAIL("poll() failed");
1531 } else if (result == 0) {
1532 DEBUG("poll() timed out");
1533 if (!timeout.overflow)
1534 break;
1535 } else {
1536 DEBUG("poll() completed");
1537 break;
1541 free(pollfds);
1542 RETURN_OK();
1543 #endif
1546 #ifdef USE_TERMIOS_SPEED
1547 static enum sp_return get_baudrate(int fd, int *baudrate)
1549 void *data;
1551 TRACE("%d, %p", fd, baudrate);
1553 DEBUG("Getting baud rate");
1555 if (!(data = malloc(get_termios_size())))
1556 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1558 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1559 free(data);
1560 RETURN_FAIL("Getting termios failed");
1563 *baudrate = get_termios_speed(data);
1565 free(data);
1567 RETURN_OK();
1570 static enum sp_return set_baudrate(int fd, int baudrate)
1572 void *data;
1574 TRACE("%d, %d", fd, baudrate);
1576 DEBUG("Getting baud rate");
1578 if (!(data = malloc(get_termios_size())))
1579 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1581 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1582 free(data);
1583 RETURN_FAIL("Getting termios failed");
1586 DEBUG("Setting baud rate");
1588 set_termios_speed(data, baudrate);
1590 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1591 free(data);
1592 RETURN_FAIL("Setting termios failed");
1595 free(data);
1597 RETURN_OK();
1599 #endif /* USE_TERMIOS_SPEED */
1601 #ifdef USE_TERMIOX
1602 static enum sp_return get_flow(int fd, struct port_data *data)
1604 void *termx;
1606 TRACE("%d, %p", fd, data);
1608 DEBUG("Getting advanced flow control");
1610 if (!(termx = malloc(get_termiox_size())))
1611 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1613 if (ioctl(fd, TCGETX, termx) < 0) {
1614 free(termx);
1615 RETURN_FAIL("Getting termiox failed");
1618 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1619 &data->dtr_flow, &data->dsr_flow);
1621 free(termx);
1623 RETURN_OK();
1626 static enum sp_return set_flow(int fd, struct port_data *data)
1628 void *termx;
1630 TRACE("%d, %p", fd, data);
1632 DEBUG("Getting advanced flow control");
1634 if (!(termx = malloc(get_termiox_size())))
1635 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1637 if (ioctl(fd, TCGETX, termx) < 0) {
1638 free(termx);
1639 RETURN_FAIL("Getting termiox failed");
1642 DEBUG("Setting advanced flow control");
1644 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1645 data->dtr_flow, data->dsr_flow);
1647 if (ioctl(fd, TCSETX, termx) < 0) {
1648 free(termx);
1649 RETURN_FAIL("Setting termiox failed");
1652 free(termx);
1654 RETURN_OK();
1656 #endif /* USE_TERMIOX */
1658 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1659 struct sp_port_config *config)
1661 unsigned int i;
1663 TRACE("%p, %p, %p", port, data, config);
1665 DEBUG_FMT("Getting configuration for port %s", port->name);
1667 #ifdef _WIN32
1668 if (!GetCommState(port->hdl, &data->dcb))
1669 RETURN_FAIL("GetCommState() failed");
1671 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1672 if (data->dcb.BaudRate == std_baudrates[i].index) {
1673 config->baudrate = std_baudrates[i].value;
1674 break;
1678 if (i == NUM_STD_BAUDRATES)
1679 /* BaudRate field can be either an index or a custom baud rate. */
1680 config->baudrate = data->dcb.BaudRate;
1682 config->bits = data->dcb.ByteSize;
1684 switch (data->dcb.Parity) {
1685 case NOPARITY:
1686 config->parity = SP_PARITY_NONE;
1687 break;
1688 case ODDPARITY:
1689 config->parity = SP_PARITY_ODD;
1690 break;
1691 case EVENPARITY:
1692 config->parity = SP_PARITY_EVEN;
1693 break;
1694 case MARKPARITY:
1695 config->parity = SP_PARITY_MARK;
1696 break;
1697 case SPACEPARITY:
1698 config->parity = SP_PARITY_SPACE;
1699 break;
1700 default:
1701 config->parity = -1;
1704 switch (data->dcb.StopBits) {
1705 case ONESTOPBIT:
1706 config->stopbits = 1;
1707 break;
1708 case TWOSTOPBITS:
1709 config->stopbits = 2;
1710 break;
1711 default:
1712 config->stopbits = -1;
1715 switch (data->dcb.fRtsControl) {
1716 case RTS_CONTROL_DISABLE:
1717 config->rts = SP_RTS_OFF;
1718 break;
1719 case RTS_CONTROL_ENABLE:
1720 config->rts = SP_RTS_ON;
1721 break;
1722 case RTS_CONTROL_HANDSHAKE:
1723 config->rts = SP_RTS_FLOW_CONTROL;
1724 break;
1725 default:
1726 config->rts = -1;
1729 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1731 switch (data->dcb.fDtrControl) {
1732 case DTR_CONTROL_DISABLE:
1733 config->dtr = SP_DTR_OFF;
1734 break;
1735 case DTR_CONTROL_ENABLE:
1736 config->dtr = SP_DTR_ON;
1737 break;
1738 case DTR_CONTROL_HANDSHAKE:
1739 config->dtr = SP_DTR_FLOW_CONTROL;
1740 break;
1741 default:
1742 config->dtr = -1;
1745 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1747 if (data->dcb.fInX) {
1748 if (data->dcb.fOutX)
1749 config->xon_xoff = SP_XONXOFF_INOUT;
1750 else
1751 config->xon_xoff = SP_XONXOFF_IN;
1752 } else {
1753 if (data->dcb.fOutX)
1754 config->xon_xoff = SP_XONXOFF_OUT;
1755 else
1756 config->xon_xoff = SP_XONXOFF_DISABLED;
1759 #else // !_WIN32
1761 if (tcgetattr(port->fd, &data->term) < 0)
1762 RETURN_FAIL("tcgetattr() failed");
1764 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1765 RETURN_FAIL("TIOCMGET ioctl failed");
1767 #ifdef USE_TERMIOX
1768 int ret = get_flow(port->fd, data);
1770 if (ret == SP_ERR_FAIL && errno == EINVAL)
1771 data->termiox_supported = 0;
1772 else if (ret < 0)
1773 RETURN_CODEVAL(ret);
1774 else
1775 data->termiox_supported = 1;
1776 #else
1777 data->termiox_supported = 0;
1778 #endif
1780 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1781 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1782 config->baudrate = std_baudrates[i].value;
1783 break;
1787 if (i == NUM_STD_BAUDRATES) {
1788 #ifdef __APPLE__
1789 config->baudrate = (int)data->term.c_ispeed;
1790 #elif defined(USE_TERMIOS_SPEED)
1791 TRY(get_baudrate(port->fd, &config->baudrate));
1792 #else
1793 config->baudrate = -1;
1794 #endif
1797 switch (data->term.c_cflag & CSIZE) {
1798 case CS8:
1799 config->bits = 8;
1800 break;
1801 case CS7:
1802 config->bits = 7;
1803 break;
1804 case CS6:
1805 config->bits = 6;
1806 break;
1807 case CS5:
1808 config->bits = 5;
1809 break;
1810 default:
1811 config->bits = -1;
1814 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1815 config->parity = SP_PARITY_NONE;
1816 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1817 config->parity = -1;
1818 #ifdef CMSPAR
1819 else if (data->term.c_cflag & CMSPAR)
1820 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1821 #endif
1822 else
1823 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1825 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1827 if (data->term.c_cflag & CRTSCTS) {
1828 config->rts = SP_RTS_FLOW_CONTROL;
1829 config->cts = SP_CTS_FLOW_CONTROL;
1830 } else {
1831 if (data->termiox_supported && data->rts_flow)
1832 config->rts = SP_RTS_FLOW_CONTROL;
1833 else
1834 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1836 config->cts = (data->termiox_supported && data->cts_flow) ?
1837 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1840 if (data->termiox_supported && data->dtr_flow)
1841 config->dtr = SP_DTR_FLOW_CONTROL;
1842 else
1843 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1845 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1846 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1848 if (data->term.c_iflag & IXOFF) {
1849 if (data->term.c_iflag & IXON)
1850 config->xon_xoff = SP_XONXOFF_INOUT;
1851 else
1852 config->xon_xoff = SP_XONXOFF_IN;
1853 } else {
1854 if (data->term.c_iflag & IXON)
1855 config->xon_xoff = SP_XONXOFF_OUT;
1856 else
1857 config->xon_xoff = SP_XONXOFF_DISABLED;
1859 #endif
1861 RETURN_OK();
1864 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1865 const struct sp_port_config *config)
1867 unsigned int i;
1868 #ifdef __APPLE__
1869 BAUD_TYPE baud_nonstd;
1871 baud_nonstd = B0;
1872 #endif
1873 #ifdef USE_TERMIOS_SPEED
1874 int baud_nonstd = 0;
1875 #endif
1877 TRACE("%p, %p, %p", port, data, config);
1879 DEBUG_FMT("Setting configuration for port %s", port->name);
1881 #ifdef _WIN32
1882 BYTE* new_buf;
1884 TRY(await_write_completion(port));
1886 if (config->baudrate >= 0) {
1887 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1888 if (config->baudrate == std_baudrates[i].value) {
1889 data->dcb.BaudRate = std_baudrates[i].index;
1890 break;
1894 if (i == NUM_STD_BAUDRATES)
1895 data->dcb.BaudRate = config->baudrate;
1897 /* Allocate write buffer for 50ms of data at baud rate. */
1898 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1899 new_buf = realloc(port->write_buf, port->write_buf_size);
1900 if (!new_buf)
1901 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1902 port->write_buf = new_buf;
1905 if (config->bits >= 0)
1906 data->dcb.ByteSize = config->bits;
1908 if (config->parity >= 0) {
1909 switch (config->parity) {
1910 case SP_PARITY_NONE:
1911 data->dcb.Parity = NOPARITY;
1912 break;
1913 case SP_PARITY_ODD:
1914 data->dcb.Parity = ODDPARITY;
1915 break;
1916 case SP_PARITY_EVEN:
1917 data->dcb.Parity = EVENPARITY;
1918 break;
1919 case SP_PARITY_MARK:
1920 data->dcb.Parity = MARKPARITY;
1921 break;
1922 case SP_PARITY_SPACE:
1923 data->dcb.Parity = SPACEPARITY;
1924 break;
1925 default:
1926 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1930 if (config->stopbits >= 0) {
1931 switch (config->stopbits) {
1932 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1933 case 1:
1934 data->dcb.StopBits = ONESTOPBIT;
1935 break;
1936 case 2:
1937 data->dcb.StopBits = TWOSTOPBITS;
1938 break;
1939 default:
1940 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1944 if (config->rts >= 0) {
1945 switch (config->rts) {
1946 case SP_RTS_OFF:
1947 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1948 break;
1949 case SP_RTS_ON:
1950 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1951 break;
1952 case SP_RTS_FLOW_CONTROL:
1953 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1954 break;
1955 default:
1956 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1960 if (config->cts >= 0) {
1961 switch (config->cts) {
1962 case SP_CTS_IGNORE:
1963 data->dcb.fOutxCtsFlow = FALSE;
1964 break;
1965 case SP_CTS_FLOW_CONTROL:
1966 data->dcb.fOutxCtsFlow = TRUE;
1967 break;
1968 default:
1969 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1973 if (config->dtr >= 0) {
1974 switch (config->dtr) {
1975 case SP_DTR_OFF:
1976 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1977 break;
1978 case SP_DTR_ON:
1979 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1980 break;
1981 case SP_DTR_FLOW_CONTROL:
1982 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1983 break;
1984 default:
1985 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1989 if (config->dsr >= 0) {
1990 switch (config->dsr) {
1991 case SP_DSR_IGNORE:
1992 data->dcb.fOutxDsrFlow = FALSE;
1993 break;
1994 case SP_DSR_FLOW_CONTROL:
1995 data->dcb.fOutxDsrFlow = TRUE;
1996 break;
1997 default:
1998 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2002 if (config->xon_xoff >= 0) {
2003 switch (config->xon_xoff) {
2004 case SP_XONXOFF_DISABLED:
2005 data->dcb.fInX = FALSE;
2006 data->dcb.fOutX = FALSE;
2007 break;
2008 case SP_XONXOFF_IN:
2009 data->dcb.fInX = TRUE;
2010 data->dcb.fOutX = FALSE;
2011 break;
2012 case SP_XONXOFF_OUT:
2013 data->dcb.fInX = FALSE;
2014 data->dcb.fOutX = TRUE;
2015 break;
2016 case SP_XONXOFF_INOUT:
2017 data->dcb.fInX = TRUE;
2018 data->dcb.fOutX = TRUE;
2019 break;
2020 default:
2021 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2025 if (!SetCommState(port->hdl, &data->dcb))
2026 RETURN_FAIL("SetCommState() failed");
2028 #else /* !_WIN32 */
2030 int controlbits;
2032 if (config->baudrate >= 0) {
2033 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2034 if (config->baudrate == std_baudrates[i].value) {
2035 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2036 RETURN_FAIL("cfsetospeed() failed");
2038 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2039 RETURN_FAIL("cfsetispeed() failed");
2040 break;
2044 /* Non-standard baud rate */
2045 if (i == NUM_STD_BAUDRATES) {
2046 #ifdef __APPLE__
2047 /* Set "dummy" baud rate. */
2048 if (cfsetspeed(&data->term, B9600) < 0)
2049 RETURN_FAIL("cfsetspeed() failed");
2050 baud_nonstd = config->baudrate;
2051 #elif defined(USE_TERMIOS_SPEED)
2052 baud_nonstd = 1;
2053 #else
2054 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2055 #endif
2059 if (config->bits >= 0) {
2060 data->term.c_cflag &= ~CSIZE;
2061 switch (config->bits) {
2062 case 8:
2063 data->term.c_cflag |= CS8;
2064 break;
2065 case 7:
2066 data->term.c_cflag |= CS7;
2067 break;
2068 case 6:
2069 data->term.c_cflag |= CS6;
2070 break;
2071 case 5:
2072 data->term.c_cflag |= CS5;
2073 break;
2074 default:
2075 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2079 if (config->parity >= 0) {
2080 data->term.c_iflag &= ~IGNPAR;
2081 data->term.c_cflag &= ~(PARENB | PARODD);
2082 #ifdef CMSPAR
2083 data->term.c_cflag &= ~CMSPAR;
2084 #endif
2085 switch (config->parity) {
2086 case SP_PARITY_NONE:
2087 data->term.c_iflag |= IGNPAR;
2088 break;
2089 case SP_PARITY_EVEN:
2090 data->term.c_cflag |= PARENB;
2091 break;
2092 case SP_PARITY_ODD:
2093 data->term.c_cflag |= PARENB | PARODD;
2094 break;
2095 #ifdef CMSPAR
2096 case SP_PARITY_MARK:
2097 data->term.c_cflag |= PARENB | PARODD;
2098 data->term.c_cflag |= CMSPAR;
2099 break;
2100 case SP_PARITY_SPACE:
2101 data->term.c_cflag |= PARENB;
2102 data->term.c_cflag |= CMSPAR;
2103 break;
2104 #else
2105 case SP_PARITY_MARK:
2106 case SP_PARITY_SPACE:
2107 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2108 #endif
2109 default:
2110 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2114 if (config->stopbits >= 0) {
2115 data->term.c_cflag &= ~CSTOPB;
2116 switch (config->stopbits) {
2117 case 1:
2118 data->term.c_cflag &= ~CSTOPB;
2119 break;
2120 case 2:
2121 data->term.c_cflag |= CSTOPB;
2122 break;
2123 default:
2124 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2128 if (config->rts >= 0 || config->cts >= 0) {
2129 if (data->termiox_supported) {
2130 data->rts_flow = data->cts_flow = 0;
2131 switch (config->rts) {
2132 case SP_RTS_OFF:
2133 case SP_RTS_ON:
2134 controlbits = TIOCM_RTS;
2135 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2136 RETURN_FAIL("Setting RTS signal level failed");
2137 break;
2138 case SP_RTS_FLOW_CONTROL:
2139 data->rts_flow = 1;
2140 break;
2141 default:
2142 break;
2144 if (config->cts == SP_CTS_FLOW_CONTROL)
2145 data->cts_flow = 1;
2147 if (data->rts_flow && data->cts_flow)
2148 data->term.c_iflag |= CRTSCTS;
2149 else
2150 data->term.c_iflag &= ~CRTSCTS;
2151 } else {
2152 /* Asymmetric use of RTS/CTS not supported. */
2153 if (data->term.c_iflag & CRTSCTS) {
2154 /* Flow control can only be disabled for both RTS & CTS together. */
2155 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2156 if (config->cts != SP_CTS_IGNORE)
2157 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2159 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2160 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2161 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2163 } else {
2164 /* Flow control can only be enabled for both RTS & CTS together. */
2165 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2166 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2167 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2170 if (config->rts >= 0) {
2171 if (config->rts == SP_RTS_FLOW_CONTROL) {
2172 data->term.c_iflag |= CRTSCTS;
2173 } else {
2174 controlbits = TIOCM_RTS;
2175 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2176 &controlbits) < 0)
2177 RETURN_FAIL("Setting RTS signal level failed");
2183 if (config->dtr >= 0 || config->dsr >= 0) {
2184 if (data->termiox_supported) {
2185 data->dtr_flow = data->dsr_flow = 0;
2186 switch (config->dtr) {
2187 case SP_DTR_OFF:
2188 case SP_DTR_ON:
2189 controlbits = TIOCM_DTR;
2190 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2191 RETURN_FAIL("Setting DTR signal level failed");
2192 break;
2193 case SP_DTR_FLOW_CONTROL:
2194 data->dtr_flow = 1;
2195 break;
2196 default:
2197 break;
2199 if (config->dsr == SP_DSR_FLOW_CONTROL)
2200 data->dsr_flow = 1;
2201 } else {
2202 /* DTR/DSR flow control not supported. */
2203 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2204 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2206 if (config->dtr >= 0) {
2207 controlbits = TIOCM_DTR;
2208 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2209 &controlbits) < 0)
2210 RETURN_FAIL("Setting DTR signal level failed");
2215 if (config->xon_xoff >= 0) {
2216 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2217 switch (config->xon_xoff) {
2218 case SP_XONXOFF_DISABLED:
2219 break;
2220 case SP_XONXOFF_IN:
2221 data->term.c_iflag |= IXOFF;
2222 break;
2223 case SP_XONXOFF_OUT:
2224 data->term.c_iflag |= IXON | IXANY;
2225 break;
2226 case SP_XONXOFF_INOUT:
2227 data->term.c_iflag |= IXON | IXOFF | IXANY;
2228 break;
2229 default:
2230 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2234 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2235 RETURN_FAIL("tcsetattr() failed");
2237 #ifdef __APPLE__
2238 if (baud_nonstd != B0) {
2239 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2240 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2242 * Set baud rates in data->term to correct, but incompatible
2243 * with tcsetattr() value, same as delivered by tcgetattr().
2245 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2246 RETURN_FAIL("cfsetspeed() failed");
2248 #elif defined(__linux__)
2249 #ifdef USE_TERMIOS_SPEED
2250 if (baud_nonstd)
2251 TRY(set_baudrate(port->fd, config->baudrate));
2252 #endif
2253 #ifdef USE_TERMIOX
2254 if (data->termiox_supported)
2255 TRY(set_flow(port->fd, data));
2256 #endif
2257 #endif
2259 #endif /* !_WIN32 */
2261 RETURN_OK();
2264 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2266 struct sp_port_config *config;
2268 TRACE("%p", config_ptr);
2270 if (!config_ptr)
2271 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2273 *config_ptr = NULL;
2275 if (!(config = malloc(sizeof(struct sp_port_config))))
2276 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2278 config->baudrate = -1;
2279 config->bits = -1;
2280 config->parity = -1;
2281 config->stopbits = -1;
2282 config->rts = -1;
2283 config->cts = -1;
2284 config->dtr = -1;
2285 config->dsr = -1;
2287 *config_ptr = config;
2289 RETURN_OK();
2292 SP_API void sp_free_config(struct sp_port_config *config)
2294 TRACE("%p", config);
2296 if (!config)
2297 DEBUG("Null config");
2298 else
2299 free(config);
2301 RETURN();
2304 SP_API enum sp_return sp_get_config(struct sp_port *port,
2305 struct sp_port_config *config)
2307 struct port_data data;
2309 TRACE("%p, %p", port, config);
2311 CHECK_OPEN_PORT();
2313 if (!config)
2314 RETURN_ERROR(SP_ERR_ARG, "Null config");
2316 TRY(get_config(port, &data, config));
2318 RETURN_OK();
2321 SP_API enum sp_return sp_set_config(struct sp_port *port,
2322 const struct sp_port_config *config)
2324 struct port_data data;
2325 struct sp_port_config prev_config;
2327 TRACE("%p, %p", port, config);
2329 CHECK_OPEN_PORT();
2331 if (!config)
2332 RETURN_ERROR(SP_ERR_ARG, "Null config");
2334 TRY(get_config(port, &data, &prev_config));
2335 TRY(set_config(port, &data, config));
2337 RETURN_OK();
2340 #define CREATE_ACCESSORS(x, type) \
2341 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2342 struct port_data data; \
2343 struct sp_port_config config; \
2344 TRACE("%p, %d", port, x); \
2345 CHECK_OPEN_PORT(); \
2346 TRY(get_config(port, &data, &config)); \
2347 config.x = x; \
2348 TRY(set_config(port, &data, &config)); \
2349 RETURN_OK(); \
2351 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2352 type *x) { \
2353 TRACE("%p, %p", config, x); \
2354 if (!x) \
2355 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2356 if (!config) \
2357 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2358 *x = config->x; \
2359 RETURN_OK(); \
2361 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2362 type x) { \
2363 TRACE("%p, %d", config, x); \
2364 if (!config) \
2365 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2366 config->x = x; \
2367 RETURN_OK(); \
2370 CREATE_ACCESSORS(baudrate, int)
2371 CREATE_ACCESSORS(bits, int)
2372 CREATE_ACCESSORS(parity, enum sp_parity)
2373 CREATE_ACCESSORS(stopbits, int)
2374 CREATE_ACCESSORS(rts, enum sp_rts)
2375 CREATE_ACCESSORS(cts, enum sp_cts)
2376 CREATE_ACCESSORS(dtr, enum sp_dtr)
2377 CREATE_ACCESSORS(dsr, enum sp_dsr)
2378 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2380 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2381 enum sp_flowcontrol flowcontrol)
2383 if (!config)
2384 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2386 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2387 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2389 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2390 config->xon_xoff = SP_XONXOFF_INOUT;
2391 else
2392 config->xon_xoff = SP_XONXOFF_DISABLED;
2394 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2395 config->rts = SP_RTS_FLOW_CONTROL;
2396 config->cts = SP_CTS_FLOW_CONTROL;
2397 } else {
2398 if (config->rts == SP_RTS_FLOW_CONTROL)
2399 config->rts = SP_RTS_ON;
2400 config->cts = SP_CTS_IGNORE;
2403 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2404 config->dtr = SP_DTR_FLOW_CONTROL;
2405 config->dsr = SP_DSR_FLOW_CONTROL;
2406 } else {
2407 if (config->dtr == SP_DTR_FLOW_CONTROL)
2408 config->dtr = SP_DTR_ON;
2409 config->dsr = SP_DSR_IGNORE;
2412 RETURN_OK();
2415 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2416 enum sp_flowcontrol flowcontrol)
2418 struct port_data data;
2419 struct sp_port_config config;
2421 TRACE("%p, %d", port, flowcontrol);
2423 CHECK_OPEN_PORT();
2425 TRY(get_config(port, &data, &config));
2427 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2429 TRY(set_config(port, &data, &config));
2431 RETURN_OK();
2434 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2435 enum sp_signal *signals)
2437 TRACE("%p, %p", port, signals);
2439 CHECK_OPEN_PORT();
2441 if (!signals)
2442 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2444 DEBUG_FMT("Getting control signals for port %s", port->name);
2446 *signals = 0;
2447 #ifdef _WIN32
2448 DWORD bits;
2449 if (GetCommModemStatus(port->hdl, &bits) == 0)
2450 RETURN_FAIL("GetCommModemStatus() failed");
2451 if (bits & MS_CTS_ON)
2452 *signals |= SP_SIG_CTS;
2453 if (bits & MS_DSR_ON)
2454 *signals |= SP_SIG_DSR;
2455 if (bits & MS_RLSD_ON)
2456 *signals |= SP_SIG_DCD;
2457 if (bits & MS_RING_ON)
2458 *signals |= SP_SIG_RI;
2459 #else
2460 int bits;
2461 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2462 RETURN_FAIL("TIOCMGET ioctl failed");
2463 if (bits & TIOCM_CTS)
2464 *signals |= SP_SIG_CTS;
2465 if (bits & TIOCM_DSR)
2466 *signals |= SP_SIG_DSR;
2467 if (bits & TIOCM_CAR)
2468 *signals |= SP_SIG_DCD;
2469 if (bits & TIOCM_RNG)
2470 *signals |= SP_SIG_RI;
2471 #endif
2472 RETURN_OK();
2475 SP_API enum sp_return sp_start_break(struct sp_port *port)
2477 TRACE("%p", port);
2479 CHECK_OPEN_PORT();
2480 #ifdef _WIN32
2481 if (SetCommBreak(port->hdl) == 0)
2482 RETURN_FAIL("SetCommBreak() failed");
2483 #else
2484 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2485 RETURN_FAIL("TIOCSBRK ioctl failed");
2486 #endif
2488 RETURN_OK();
2491 SP_API enum sp_return sp_end_break(struct sp_port *port)
2493 TRACE("%p", port);
2495 CHECK_OPEN_PORT();
2496 #ifdef _WIN32
2497 if (ClearCommBreak(port->hdl) == 0)
2498 RETURN_FAIL("ClearCommBreak() failed");
2499 #else
2500 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2501 RETURN_FAIL("TIOCCBRK ioctl failed");
2502 #endif
2504 RETURN_OK();
2507 SP_API int sp_last_error_code(void)
2509 TRACE_VOID();
2510 #ifdef _WIN32
2511 RETURN_INT(GetLastError());
2512 #else
2513 RETURN_INT(errno);
2514 #endif
2517 SP_API char *sp_last_error_message(void)
2519 TRACE_VOID();
2521 #ifdef _WIN32
2522 char *message;
2523 DWORD error = GetLastError();
2525 DWORD length = FormatMessageA(
2526 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2527 FORMAT_MESSAGE_FROM_SYSTEM |
2528 FORMAT_MESSAGE_IGNORE_INSERTS,
2529 NULL,
2530 error,
2531 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2532 (LPSTR) &message,
2533 0, NULL );
2535 if (length >= 2 && message[length - 2] == '\r')
2536 message[length - 2] = '\0';
2538 RETURN_STRING(message);
2539 #else
2540 RETURN_STRING(strerror(errno));
2541 #endif
2544 SP_API void sp_free_error_message(char *message)
2546 TRACE("%s", message);
2548 #ifdef _WIN32
2549 LocalFree(message);
2550 #else
2551 (void)message;
2552 #endif
2554 RETURN();
2557 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2559 TRACE("%p", handler);
2561 sp_debug_handler = handler;
2563 RETURN();
2566 SP_API void sp_default_debug_handler(const char *format, ...)
2568 va_list args;
2569 va_start(args, format);
2570 if (getenv("LIBSERIALPORT_DEBUG")) {
2571 fputs("sp: ", stderr);
2572 vfprintf(stderr, format, args);
2574 va_end(args);
2577 SP_API int sp_get_major_package_version(void)
2579 return SP_PACKAGE_VERSION_MAJOR;
2582 SP_API int sp_get_minor_package_version(void)
2584 return SP_PACKAGE_VERSION_MINOR;
2587 SP_API int sp_get_micro_package_version(void)
2589 return SP_PACKAGE_VERSION_MICRO;
2592 SP_API const char *sp_get_package_version_string(void)
2594 return SP_PACKAGE_VERSION_STRING;
2597 SP_API int sp_get_current_lib_version(void)
2599 return SP_LIB_VERSION_CURRENT;
2602 SP_API int sp_get_revision_lib_version(void)
2604 return SP_LIB_VERSION_REVISION;
2607 SP_API int sp_get_age_lib_version(void)
2609 return SP_LIB_VERSION_AGE;
2612 SP_API const char *sp_get_lib_version_string(void)
2614 return SP_LIB_VERSION_STRING;
2617 /** @} */