NEWS: Last updates for the upcoming 0.1.2 release.
[libserialport.git] / serialport.c
blobb3b9249a37c70b70ce3d75be0bd92ec355a2d21c
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 RETURN_INT(port ? port->transport : SP_TRANSPORT_NATIVE);
161 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
162 int *usb_bus,int *usb_address)
164 TRACE("%p", port);
166 if (!port)
167 RETURN_ERROR(SP_ERR_ARG, "Null port");
168 if (port->transport != SP_TRANSPORT_USB)
169 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
170 if (port->usb_bus < 0 || port->usb_address < 0)
171 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
173 if (usb_bus)
174 *usb_bus = port->usb_bus;
175 if (usb_address)
176 *usb_address = port->usb_address;
178 RETURN_OK();
181 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
182 int *usb_vid, int *usb_pid)
184 TRACE("%p", port);
186 if (!port)
187 RETURN_ERROR(SP_ERR_ARG, "Null port");
188 if (port->transport != SP_TRANSPORT_USB)
189 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
190 if (port->usb_vid < 0 || port->usb_pid < 0)
191 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
193 if (usb_vid)
194 *usb_vid = port->usb_vid;
195 if (usb_pid)
196 *usb_pid = port->usb_pid;
198 RETURN_OK();
201 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
203 TRACE("%p", port);
205 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
206 return NULL;
208 RETURN_STRING(port->usb_manufacturer);
211 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
213 TRACE("%p", port);
215 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
216 return NULL;
218 RETURN_STRING(port->usb_product);
221 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
223 TRACE("%p", port);
225 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
226 return NULL;
228 RETURN_STRING(port->usb_serial);
231 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
233 TRACE("%p", port);
235 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
236 || !port->bluetooth_address)
237 return NULL;
239 RETURN_STRING(port->bluetooth_address);
242 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
243 void *result_ptr)
245 TRACE("%p, %p", port, result_ptr);
247 if (!port)
248 RETURN_ERROR(SP_ERR_ARG, "Null port");
249 if (!result_ptr)
250 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
252 #ifdef _WIN32
253 HANDLE *handle_ptr = result_ptr;
254 *handle_ptr = port->hdl;
255 #else
256 int *fd_ptr = result_ptr;
257 *fd_ptr = port->fd;
258 #endif
260 RETURN_OK();
263 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
264 struct sp_port **copy_ptr)
266 TRACE("%p, %p", port, copy_ptr);
268 if (!copy_ptr)
269 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
271 *copy_ptr = NULL;
273 if (!port)
274 RETURN_ERROR(SP_ERR_ARG, "Null port");
276 if (!port->name)
277 RETURN_ERROR(SP_ERR_ARG, "Null port name");
279 DEBUG("Copying port structure");
281 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
284 SP_API void sp_free_port(struct sp_port *port)
286 TRACE("%p", port);
288 if (!port) {
289 DEBUG("Null port");
290 RETURN();
293 DEBUG("Freeing port structure");
295 if (port->name)
296 free(port->name);
297 if (port->description)
298 free(port->description);
299 if (port->usb_manufacturer)
300 free(port->usb_manufacturer);
301 if (port->usb_product)
302 free(port->usb_product);
303 if (port->usb_serial)
304 free(port->usb_serial);
305 if (port->bluetooth_address)
306 free(port->bluetooth_address);
307 #ifdef _WIN32
308 if (port->usb_path)
309 free(port->usb_path);
310 if (port->write_buf)
311 free(port->write_buf);
312 #endif
314 free(port);
316 RETURN();
319 SP_PRIV struct sp_port **list_append(struct sp_port **list,
320 const char *portname)
322 void *tmp;
323 size_t count;
325 for (count = 0; list[count]; count++)
327 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
328 goto fail;
329 list = tmp;
330 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
331 goto fail;
332 list[count + 1] = NULL;
333 return list;
335 fail:
336 sp_free_port_list(list);
337 return NULL;
340 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
342 #ifndef NO_ENUMERATION
343 struct sp_port **list;
344 int ret;
345 #endif
347 TRACE("%p", list_ptr);
349 if (!list_ptr)
350 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
352 *list_ptr = NULL;
354 #ifdef NO_ENUMERATION
355 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
356 #else
357 DEBUG("Enumerating ports");
359 if (!(list = malloc(sizeof(struct sp_port *))))
360 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
362 list[0] = NULL;
364 ret = list_ports(&list);
366 if (ret == SP_OK) {
367 *list_ptr = list;
368 } else {
369 sp_free_port_list(list);
370 *list_ptr = NULL;
373 RETURN_CODEVAL(ret);
374 #endif
377 SP_API void sp_free_port_list(struct sp_port **list)
379 unsigned int i;
381 TRACE("%p", list);
383 if (!list) {
384 DEBUG("Null list");
385 RETURN();
388 DEBUG("Freeing port list");
390 for (i = 0; list[i]; i++)
391 sp_free_port(list[i]);
392 free(list);
394 RETURN();
397 #define CHECK_PORT() do { \
398 if (!port) \
399 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
400 if (!port->name) \
401 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
402 } while (0)
403 #ifdef _WIN32
404 #define CHECK_PORT_HANDLE() do { \
405 if (port->hdl == INVALID_HANDLE_VALUE) \
406 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
407 } while (0)
408 #else
409 #define CHECK_PORT_HANDLE() do { \
410 if (port->fd < 0) \
411 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
412 } while (0)
413 #endif
414 #define CHECK_OPEN_PORT() do { \
415 CHECK_PORT(); \
416 CHECK_PORT_HANDLE(); \
417 } while (0)
419 #ifdef WIN32
420 /** To be called after port receive buffer is emptied. */
421 static enum sp_return restart_wait(struct sp_port *port)
423 DWORD wait_result;
425 if (port->wait_running) {
426 /* Check status of running wait operation. */
427 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
428 &wait_result, FALSE)) {
429 DEBUG("Previous wait completed");
430 port->last_wait_thread_exited = FALSE;
431 port->wait_running = FALSE;
432 } else if (GetLastError() == ERROR_OPERATION_ABORTED) {
433 /* This error is returned if the last thread that called
434 * restart_wait() has exited while WaitCommEvent() was
435 * still active. In that case we don't consider that to
436 * be an error. Just restart the wait procedure instead.
438 DEBUG("Previous wait ended due to previous thread exiting");
439 /* We need to record that the wait thread exited before
440 * we called WaitCommEvent(). This is because the exit of
441 * the previous thread always generates a spurious wakeup,
442 * and if no data has been received in the mean time, the
443 * WaitCommEvent() wouldn't be restarted a second time by
444 * restart_wait_if_needed() after a read call after the
445 * spurious wakeup.
447 port->last_wait_thread_exited = TRUE;
448 port->wait_running = FALSE;
449 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
450 DEBUG("Previous wait still running");
451 port->last_wait_thread_exited = FALSE;
452 RETURN_OK();
453 } else {
454 RETURN_FAIL("GetOverlappedResult() failed");
458 if (!port->wait_running) {
459 /* Start new wait operation. */
460 if (WaitCommEvent(port->hdl, &port->events,
461 &port->wait_ovl)) {
462 DEBUG("New wait returned, events already pending");
463 } else if (GetLastError() == ERROR_IO_PENDING) {
464 DEBUG("New wait running in background");
465 port->wait_running = TRUE;
466 } else {
467 RETURN_FAIL("WaitCommEvent() failed");
471 RETURN_OK();
473 #endif
475 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
477 struct port_data data;
478 struct sp_port_config config;
479 enum sp_return ret;
481 TRACE("%p, 0x%x", port, flags);
483 CHECK_PORT();
485 if (flags > SP_MODE_READ_WRITE)
486 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
488 DEBUG_FMT("Opening port %s", port->name);
490 #ifdef _WIN32
491 DWORD desired_access = 0, flags_and_attributes = 0, errors;
492 char *escaped_port_name;
493 COMSTAT status;
495 /* Prefix port name with '\\.\' to work with ports above COM9. */
496 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
497 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
498 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
500 /* Map 'flags' to the OS-specific settings. */
501 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
502 if (flags & SP_MODE_READ)
503 desired_access |= GENERIC_READ;
504 if (flags & SP_MODE_WRITE)
505 desired_access |= GENERIC_WRITE;
507 port->hdl = CreateFileA(escaped_port_name, desired_access, 0, 0,
508 OPEN_EXISTING, flags_and_attributes, 0);
510 free(escaped_port_name);
512 if (port->hdl == INVALID_HANDLE_VALUE)
513 RETURN_FAIL("Port CreateFile() failed");
515 /* All timeouts initially disabled. */
516 port->timeouts.ReadIntervalTimeout = 0;
517 port->timeouts.ReadTotalTimeoutMultiplier = 0;
518 port->timeouts.ReadTotalTimeoutConstant = 0;
519 port->timeouts.WriteTotalTimeoutMultiplier = 0;
520 port->timeouts.WriteTotalTimeoutConstant = 0;
522 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
523 sp_close(port);
524 RETURN_FAIL("SetCommTimeouts() failed");
527 /* Prepare OVERLAPPED structures. */
528 #define INIT_OVERLAPPED(ovl) do { \
529 memset(&port->ovl, 0, sizeof(port->ovl)); \
530 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
531 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
532 == INVALID_HANDLE_VALUE) { \
533 sp_close(port); \
534 RETURN_FAIL(#ovl "CreateEvent() failed"); \
536 } while (0)
538 INIT_OVERLAPPED(read_ovl);
539 INIT_OVERLAPPED(write_ovl);
540 INIT_OVERLAPPED(wait_ovl);
542 /* Set event mask for RX and error events. */
543 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
544 sp_close(port);
545 RETURN_FAIL("SetCommMask() failed");
548 port->writing = FALSE;
549 port->wait_running = FALSE;
551 ret = restart_wait(port);
553 if (ret < 0) {
554 sp_close(port);
555 RETURN_CODEVAL(ret);
557 #else
558 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
560 /* Map 'flags' to the OS-specific settings. */
561 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
562 flags_local |= O_RDWR;
563 else if (flags & SP_MODE_READ)
564 flags_local |= O_RDONLY;
565 else if (flags & SP_MODE_WRITE)
566 flags_local |= O_WRONLY;
568 if ((port->fd = open(port->name, flags_local)) < 0)
569 RETURN_FAIL("open() failed");
572 * On POSIX in the default case the file descriptor of a serial port
573 * is not opened exclusively. Therefore the settings of a port are
574 * overwritten if the serial port is opened a second time. Windows
575 * opens all serial ports exclusively.
576 * So the idea is to open the serial ports alike in the exclusive mode.
578 * ioctl(*, TIOCEXCL) defines the file descriptor as exclusive. So all
579 * further open calls on the serial port will fail.
581 * There is a race condition if two processes open the same serial
582 * port. None of the processes will notice the exclusive ownership of
583 * the other process because ioctl() doesn't return an error code if
584 * the file descriptor is already marked as exclusive.
585 * This can be solved with flock(). It returns an error if the file
586 * descriptor is already locked by another process.
588 #ifdef HAVE_FLOCK
589 if (flock(port->fd, LOCK_EX | LOCK_NB) < 0)
590 RETURN_FAIL("flock() failed");
591 #endif
593 #ifdef TIOCEXCL
595 * Before Linux 3.8 ioctl(*, TIOCEXCL) was not implemented and could
596 * lead to EINVAL or ENOTTY.
597 * These errors aren't fatal and can be ignored.
599 if (ioctl(port->fd, TIOCEXCL) < 0 && errno != EINVAL && errno != ENOTTY)
600 RETURN_FAIL("ioctl() failed");
601 #endif
603 #endif
605 ret = get_config(port, &data, &config);
607 if (ret < 0) {
608 sp_close(port);
609 RETURN_CODEVAL(ret);
613 * Assume a default baudrate if the OS does not provide one.
614 * Cannot assign -1 here since Windows holds the baudrate in
615 * the DCB and does not configure the rate individually.
617 if (config.baudrate == 0) {
618 config.baudrate = 9600;
621 /* Set sane port settings. */
622 #ifdef _WIN32
623 data.dcb.fBinary = TRUE;
624 data.dcb.fDsrSensitivity = FALSE;
625 data.dcb.fErrorChar = FALSE;
626 data.dcb.fNull = FALSE;
627 data.dcb.fAbortOnError = FALSE;
628 #else
629 /* Turn off all fancy termios tricks, give us a raw channel. */
630 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
631 #ifdef IUCLC
632 data.term.c_iflag &= ~IUCLC;
633 #endif
634 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
635 #ifdef OLCUC
636 data.term.c_oflag &= ~OLCUC;
637 #endif
638 #ifdef NLDLY
639 data.term.c_oflag &= ~NLDLY;
640 #endif
641 #ifdef CRDLY
642 data.term.c_oflag &= ~CRDLY;
643 #endif
644 #ifdef TABDLY
645 data.term.c_oflag &= ~TABDLY;
646 #endif
647 #ifdef BSDLY
648 data.term.c_oflag &= ~BSDLY;
649 #endif
650 #ifdef VTDLY
651 data.term.c_oflag &= ~VTDLY;
652 #endif
653 #ifdef FFDLY
654 data.term.c_oflag &= ~FFDLY;
655 #endif
656 #ifdef OFILL
657 data.term.c_oflag &= ~OFILL;
658 #endif
659 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
660 data.term.c_cc[VMIN] = 0;
661 data.term.c_cc[VTIME] = 0;
663 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
664 data.term.c_cflag |= (CLOCAL | CREAD);
665 data.term.c_cflag &= ~(HUPCL);
666 #endif
668 #ifdef _WIN32
669 if (ClearCommError(port->hdl, &errors, &status) == 0)
670 RETURN_FAIL("ClearCommError() failed");
671 #endif
673 ret = set_config(port, &data, &config);
675 if (ret < 0) {
676 sp_close(port);
677 RETURN_CODEVAL(ret);
680 RETURN_OK();
683 SP_API enum sp_return sp_close(struct sp_port *port)
685 TRACE("%p", port);
687 CHECK_OPEN_PORT();
689 DEBUG_FMT("Closing port %s", port->name);
691 #ifdef _WIN32
692 /* Returns non-zero upon success, 0 upon failure. */
693 if (CloseHandle(port->hdl) == 0)
694 RETURN_FAIL("Port CloseHandle() failed");
695 port->hdl = INVALID_HANDLE_VALUE;
697 /* Close event handles for overlapped structures. */
698 #define CLOSE_OVERLAPPED(ovl) do { \
699 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
700 CloseHandle(port->ovl.hEvent) == 0) \
701 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
702 } while (0)
703 CLOSE_OVERLAPPED(read_ovl);
704 CLOSE_OVERLAPPED(write_ovl);
705 CLOSE_OVERLAPPED(wait_ovl);
707 if (port->write_buf) {
708 free(port->write_buf);
709 port->write_buf = NULL;
711 #else
712 #ifdef TIOCNXCL
713 ioctl(port->fd, TIOCNXCL);
714 #endif
716 /* Returns 0 upon success, -1 upon failure. */
717 if (close(port->fd) == -1)
718 RETURN_FAIL("close() failed");
719 port->fd = -1;
720 #endif
722 RETURN_OK();
725 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
727 TRACE("%p, 0x%x", port, buffers);
729 CHECK_OPEN_PORT();
731 if (buffers > SP_BUF_BOTH)
732 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
734 const char *buffer_names[] = {"no", "input", "output", "both"};
736 DEBUG_FMT("Flushing %s buffers on port %s",
737 buffer_names[buffers], port->name);
739 #ifdef _WIN32
740 DWORD flags = 0;
741 if (buffers & SP_BUF_INPUT)
742 flags |= PURGE_RXCLEAR;
743 if (buffers & SP_BUF_OUTPUT)
744 flags |= PURGE_TXCLEAR;
746 /* Returns non-zero upon success, 0 upon failure. */
747 if (PurgeComm(port->hdl, flags) == 0)
748 RETURN_FAIL("PurgeComm() failed");
750 if (buffers & SP_BUF_INPUT)
751 TRY(restart_wait(port));
752 #else
753 int flags = 0;
754 if (buffers == SP_BUF_BOTH)
755 flags = TCIOFLUSH;
756 else if (buffers == SP_BUF_INPUT)
757 flags = TCIFLUSH;
758 else if (buffers == SP_BUF_OUTPUT)
759 flags = TCOFLUSH;
761 /* Returns 0 upon success, -1 upon failure. */
762 if (tcflush(port->fd, flags) < 0)
763 RETURN_FAIL("tcflush() failed");
764 #endif
765 RETURN_OK();
768 SP_API enum sp_return sp_drain(struct sp_port *port)
770 TRACE("%p", port);
772 CHECK_OPEN_PORT();
774 DEBUG_FMT("Draining port %s", port->name);
776 #ifdef _WIN32
777 /* Returns non-zero upon success, 0 upon failure. */
778 if (FlushFileBuffers(port->hdl) == 0)
779 RETURN_FAIL("FlushFileBuffers() failed");
780 RETURN_OK();
781 #else
782 int result;
783 while (1) {
784 #if defined(__ANDROID__) && (__ANDROID_API__ < 21)
785 /* Android only has tcdrain from platform 21 onwards.
786 * On previous API versions, use the ioctl directly. */
787 int arg = 1;
788 result = ioctl(port->fd, TCSBRK, &arg);
789 #else
790 result = tcdrain(port->fd);
791 #endif
792 if (result < 0) {
793 if (errno == EINTR) {
794 DEBUG("tcdrain() was interrupted");
795 continue;
796 } else {
797 RETURN_FAIL("tcdrain() failed");
799 } else {
800 RETURN_OK();
803 #endif
806 #ifdef _WIN32
807 static enum sp_return await_write_completion(struct sp_port *port)
809 TRACE("%p", port);
810 DWORD bytes_written;
811 BOOL result;
813 /* Wait for previous non-blocking write to complete, if any. */
814 if (port->writing) {
815 DEBUG("Waiting for previous write to complete");
816 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
817 port->writing = 0;
818 if (!result)
819 RETURN_FAIL("Previous write failed to complete");
820 DEBUG("Previous write completed");
823 RETURN_OK();
825 #endif
827 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
828 size_t count, unsigned int timeout_ms)
830 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
832 CHECK_OPEN_PORT();
834 if (!buf)
835 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
837 if (timeout_ms)
838 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
839 count, port->name, timeout_ms);
840 else
841 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
842 count, port->name);
844 if (count == 0)
845 RETURN_INT(0);
847 #ifdef _WIN32
848 DWORD remaining_ms, write_size, bytes_written;
849 size_t remaining_bytes, total_bytes_written = 0;
850 const uint8_t *write_ptr = (uint8_t *) buf;
851 bool result;
852 struct timeout timeout;
854 timeout_start(&timeout, timeout_ms);
856 TRY(await_write_completion(port));
858 while (total_bytes_written < count) {
860 if (timeout_check(&timeout))
861 break;
863 remaining_ms = timeout_remaining_ms(&timeout);
865 if (port->timeouts.WriteTotalTimeoutConstant != remaining_ms) {
866 port->timeouts.WriteTotalTimeoutConstant = remaining_ms;
867 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
868 RETURN_FAIL("SetCommTimeouts() failed");
871 /* Reduce write size if it exceeds the WriteFile limit. */
872 remaining_bytes = count - total_bytes_written;
873 if (remaining_bytes > WRITEFILE_MAX_SIZE)
874 write_size = WRITEFILE_MAX_SIZE;
875 else
876 write_size = (DWORD) remaining_bytes;
878 /* Start write. */
880 result = WriteFile(port->hdl, write_ptr, write_size, NULL, &port->write_ovl);
882 timeout_update(&timeout);
884 if (result) {
885 DEBUG("Write completed immediately");
886 bytes_written = write_size;
887 } else if (GetLastError() == ERROR_IO_PENDING) {
888 DEBUG("Waiting for write to complete");
889 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
890 if (GetLastError() == ERROR_SEM_TIMEOUT) {
891 DEBUG("Write timed out");
892 break;
893 } else {
894 RETURN_FAIL("GetOverlappedResult() failed");
897 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, write_size);
898 } else {
899 RETURN_FAIL("WriteFile() failed");
902 write_ptr += bytes_written;
903 total_bytes_written += bytes_written;
906 RETURN_INT((int) total_bytes_written);
907 #else
908 size_t bytes_written = 0;
909 unsigned char *ptr = (unsigned char *) buf;
910 struct timeout timeout;
911 fd_set fds;
912 ssize_t result;
914 timeout_start(&timeout, timeout_ms);
916 FD_ZERO(&fds);
917 FD_SET(port->fd, &fds);
919 /* Loop until we have written the requested number of bytes. */
920 while (bytes_written < count) {
922 if (timeout_check(&timeout))
923 break;
925 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
927 timeout_update(&timeout);
929 if (result < 0) {
930 if (errno == EINTR) {
931 DEBUG("select() call was interrupted, repeating");
932 continue;
933 } else {
934 RETURN_FAIL("select() failed");
936 } else if (result == 0) {
937 /* Timeout has expired. */
938 break;
941 /* Do write. */
942 result = write(port->fd, ptr, count - bytes_written);
944 if (result < 0) {
945 if (errno == EAGAIN)
946 /* This shouldn't happen because we did a select() first, but handle anyway. */
947 continue;
948 else
949 /* This is an actual failure. */
950 RETURN_FAIL("write() failed");
953 bytes_written += result;
954 ptr += result;
957 if (bytes_written < count)
958 DEBUG("Write timed out");
960 RETURN_INT(bytes_written);
961 #endif
964 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
965 const void *buf, size_t count)
967 TRACE("%p, %p, %d", port, buf, count);
969 CHECK_OPEN_PORT();
971 if (!buf)
972 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
974 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
976 if (count == 0)
977 RETURN_INT(0);
979 #ifdef _WIN32
980 size_t buf_bytes;
982 /* Check whether previous write is complete. */
983 if (port->writing) {
984 if (HasOverlappedIoCompleted(&port->write_ovl)) {
985 DEBUG("Previous write completed");
986 port->writing = 0;
987 } else {
988 DEBUG("Previous write not complete");
989 /* Can't take a new write until the previous one finishes. */
990 RETURN_INT(0);
994 /* Set timeout. */
995 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
996 port->timeouts.WriteTotalTimeoutConstant = 0;
997 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
998 RETURN_FAIL("SetCommTimeouts() failed");
1001 /* Reduce count if it exceeds the WriteFile limit. */
1002 if (count > WRITEFILE_MAX_SIZE)
1003 count = WRITEFILE_MAX_SIZE;
1005 /* Copy data to our write buffer. */
1006 buf_bytes = min(port->write_buf_size, count);
1007 memcpy(port->write_buf, buf, buf_bytes);
1009 /* Start asynchronous write. */
1010 if (WriteFile(port->hdl, port->write_buf, (DWORD) buf_bytes, NULL, &port->write_ovl) == 0) {
1011 if (GetLastError() == ERROR_IO_PENDING) {
1012 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
1013 DEBUG("Asynchronous write completed immediately");
1014 else
1015 DEBUG("Asynchronous write running");
1016 } else {
1017 /* Actual failure of some kind. */
1018 RETURN_FAIL("WriteFile() failed");
1022 DEBUG("All bytes written immediately");
1024 RETURN_INT((int) buf_bytes);
1025 #else
1026 /* Returns the number of bytes written, or -1 upon failure. */
1027 ssize_t written = write(port->fd, buf, count);
1029 if (written < 0) {
1030 if (errno == EAGAIN)
1031 // Buffer is full, no bytes written.
1032 RETURN_INT(0);
1033 else
1034 RETURN_FAIL("write() failed");
1035 } else {
1036 RETURN_INT(written);
1038 #endif
1041 #ifdef _WIN32
1042 /* Restart wait operation if buffer was emptied. */
1043 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1045 DWORD errors;
1046 COMSTAT comstat;
1048 /* Only skip restarting the wait operation if we didn't have a
1049 * wakeup immediately following the exit of the last thread that
1050 * re-initiated the wait loop.
1052 if (!port->last_wait_thread_exited && bytes_read == 0)
1053 RETURN_OK();
1055 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1056 RETURN_FAIL("ClearCommError() failed");
1058 if (comstat.cbInQue == 0)
1059 TRY(restart_wait(port));
1061 RETURN_OK();
1063 #endif
1065 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1066 size_t count, unsigned int timeout_ms)
1068 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1070 CHECK_OPEN_PORT();
1072 if (!buf)
1073 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1075 if (timeout_ms)
1076 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1077 count, port->name, timeout_ms);
1078 else
1079 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1080 count, port->name);
1082 if (count == 0)
1083 RETURN_INT(0);
1085 #ifdef _WIN32
1086 DWORD bytes_read;
1088 /* Set timeout. */
1089 if (port->timeouts.ReadIntervalTimeout != 0 ||
1090 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1091 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1092 port->timeouts.ReadIntervalTimeout = 0;
1093 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1094 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1095 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1096 RETURN_FAIL("SetCommTimeouts() failed");
1099 /* Start read. */
1100 if (ReadFile(port->hdl, buf, (DWORD) count, NULL, &port->read_ovl)) {
1101 DEBUG("Read completed immediately");
1102 bytes_read = (DWORD) count;
1103 } else if (GetLastError() == ERROR_IO_PENDING) {
1104 DEBUG("Waiting for read to complete");
1105 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1106 RETURN_FAIL("GetOverlappedResult() failed");
1107 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1108 } else {
1109 RETURN_FAIL("ReadFile() failed");
1112 TRY(restart_wait_if_needed(port, bytes_read));
1114 RETURN_INT((int) bytes_read);
1116 #else
1117 size_t bytes_read = 0;
1118 unsigned char *ptr = (unsigned char *) buf;
1119 struct timeout timeout;
1120 fd_set fds;
1121 ssize_t result;
1123 timeout_start(&timeout, timeout_ms);
1125 FD_ZERO(&fds);
1126 FD_SET(port->fd, &fds);
1128 /* Loop until we have the requested number of bytes. */
1129 while (bytes_read < count) {
1131 if (timeout_check(&timeout))
1132 /* Timeout has expired. */
1133 break;
1135 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1137 timeout_update(&timeout);
1139 if (result < 0) {
1140 if (errno == EINTR) {
1141 DEBUG("select() call was interrupted, repeating");
1142 continue;
1143 } else {
1144 RETURN_FAIL("select() failed");
1146 } else if (result == 0) {
1147 /* Timeout has expired. */
1148 break;
1151 /* Do read. */
1152 result = read(port->fd, ptr, count - bytes_read);
1154 if (result < 0) {
1155 if (errno == EAGAIN)
1157 * This shouldn't happen because we did a
1158 * select() first, but handle anyway.
1160 continue;
1161 else
1162 /* This is an actual failure. */
1163 RETURN_FAIL("read() failed");
1166 bytes_read += result;
1167 ptr += result;
1170 if (bytes_read < count)
1171 DEBUG("Read timed out");
1173 RETURN_INT(bytes_read);
1174 #endif
1177 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1178 size_t count, unsigned int timeout_ms)
1180 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1182 CHECK_OPEN_PORT();
1184 if (!buf)
1185 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1187 if (count == 0)
1188 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1190 if (timeout_ms)
1191 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1192 count, port->name, timeout_ms);
1193 else
1194 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1195 count, port->name);
1197 #ifdef _WIN32
1198 DWORD bytes_read = 0;
1200 /* If timeout_ms == 0, set maximum timeout. */
1201 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1203 /* Set timeout. */
1204 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1205 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1206 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1207 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1208 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1209 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1210 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1211 RETURN_FAIL("SetCommTimeouts() failed");
1214 /* Loop until we have at least one byte, or timeout is reached. */
1215 while (bytes_read == 0) {
1216 /* Start read. */
1217 if (ReadFile(port->hdl, buf, (DWORD) count, &bytes_read, &port->read_ovl)) {
1218 DEBUG("Read completed immediately");
1219 } else if (GetLastError() == ERROR_IO_PENDING) {
1220 DEBUG("Waiting for read to complete");
1221 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1222 RETURN_FAIL("GetOverlappedResult() failed");
1223 if (bytes_read > 0) {
1224 DEBUG("Read completed");
1225 } else if (timeout_ms > 0) {
1226 DEBUG("Read timed out");
1227 break;
1228 } else {
1229 DEBUG("Restarting read");
1231 } else {
1232 RETURN_FAIL("ReadFile() failed");
1236 TRY(restart_wait_if_needed(port, bytes_read));
1238 RETURN_INT(bytes_read);
1240 #else
1241 size_t bytes_read = 0;
1242 struct timeout timeout;
1243 fd_set fds;
1244 ssize_t result;
1246 timeout_start(&timeout, timeout_ms);
1248 FD_ZERO(&fds);
1249 FD_SET(port->fd, &fds);
1251 /* Loop until we have at least one byte, or timeout is reached. */
1252 while (bytes_read == 0) {
1254 if (timeout_check(&timeout))
1255 /* Timeout has expired. */
1256 break;
1258 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1260 timeout_update(&timeout);
1262 if (result < 0) {
1263 if (errno == EINTR) {
1264 DEBUG("select() call was interrupted, repeating");
1265 continue;
1266 } else {
1267 RETURN_FAIL("select() failed");
1269 } else if (result == 0) {
1270 /* Timeout has expired. */
1271 break;
1274 /* Do read. */
1275 result = read(port->fd, buf, count);
1277 if (result < 0) {
1278 if (errno == EAGAIN)
1279 /* This shouldn't happen because we did a select() first, but handle anyway. */
1280 continue;
1281 else
1282 /* This is an actual failure. */
1283 RETURN_FAIL("read() failed");
1286 bytes_read = result;
1289 if (bytes_read == 0)
1290 DEBUG("Read timed out");
1292 RETURN_INT(bytes_read);
1293 #endif
1296 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1297 size_t count)
1299 TRACE("%p, %p, %d", port, buf, count);
1301 CHECK_OPEN_PORT();
1303 if (!buf)
1304 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1306 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1308 #ifdef _WIN32
1309 DWORD bytes_read;
1311 /* Set timeout. */
1312 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1313 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1314 port->timeouts.ReadTotalTimeoutConstant != 0) {
1315 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1316 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1317 port->timeouts.ReadTotalTimeoutConstant = 0;
1318 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1319 RETURN_FAIL("SetCommTimeouts() failed");
1322 /* Do read. */
1323 if (ReadFile(port->hdl, buf, (DWORD) count, NULL, &port->read_ovl) == 0)
1324 if (GetLastError() != ERROR_IO_PENDING)
1325 RETURN_FAIL("ReadFile() failed");
1327 /* Get number of bytes read. */
1328 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1329 RETURN_FAIL("GetOverlappedResult() failed");
1331 TRY(restart_wait_if_needed(port, bytes_read));
1333 RETURN_INT(bytes_read);
1334 #else
1335 ssize_t bytes_read;
1337 /* Returns the number of bytes read, or -1 upon failure. */
1338 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1339 if (errno == EAGAIN)
1340 /* No bytes available. */
1341 bytes_read = 0;
1342 else
1343 /* This is an actual failure. */
1344 RETURN_FAIL("read() failed");
1346 RETURN_INT(bytes_read);
1347 #endif
1350 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1352 TRACE("%p", port);
1354 CHECK_OPEN_PORT();
1356 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1358 #ifdef _WIN32
1359 DWORD errors;
1360 COMSTAT comstat;
1362 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1363 RETURN_FAIL("ClearCommError() failed");
1364 RETURN_INT(comstat.cbInQue);
1365 #else
1366 int bytes_waiting;
1367 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1368 RETURN_FAIL("TIOCINQ ioctl failed");
1369 RETURN_INT(bytes_waiting);
1370 #endif
1373 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1375 TRACE("%p", port);
1377 #ifdef __CYGWIN__
1378 /* TIOCOUTQ is not defined in Cygwin headers */
1379 RETURN_ERROR(SP_ERR_SUPP,
1380 "Getting output bytes waiting is not supported on Cygwin");
1381 #else
1382 CHECK_OPEN_PORT();
1384 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1386 #ifdef _WIN32
1387 DWORD errors;
1388 COMSTAT comstat;
1390 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1391 RETURN_FAIL("ClearCommError() failed");
1392 RETURN_INT(comstat.cbOutQue);
1393 #else
1394 int bytes_waiting;
1395 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1396 RETURN_FAIL("TIOCOUTQ ioctl failed");
1397 RETURN_INT(bytes_waiting);
1398 #endif
1399 #endif
1402 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1404 struct sp_event_set *result;
1406 TRACE("%p", result_ptr);
1408 if (!result_ptr)
1409 RETURN_ERROR(SP_ERR_ARG, "Null result");
1411 *result_ptr = NULL;
1413 if (!(result = malloc(sizeof(struct sp_event_set))))
1414 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1416 memset(result, 0, sizeof(struct sp_event_set));
1418 *result_ptr = result;
1420 RETURN_OK();
1423 static enum sp_return add_handle(struct sp_event_set *event_set,
1424 event_handle handle, enum sp_event mask)
1426 void *new_handles;
1427 enum sp_event *new_masks;
1429 TRACE("%p, %d, %d", event_set, handle, mask);
1431 if (!(new_handles = realloc(event_set->handles,
1432 sizeof(event_handle) * (event_set->count + 1))))
1433 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1435 event_set->handles = new_handles;
1437 if (!(new_masks = realloc(event_set->masks,
1438 sizeof(enum sp_event) * (event_set->count + 1))))
1439 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1441 event_set->masks = new_masks;
1443 ((event_handle *) event_set->handles)[event_set->count] = handle;
1444 event_set->masks[event_set->count] = mask;
1446 event_set->count++;
1448 RETURN_OK();
1451 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1452 const struct sp_port *port, enum sp_event mask)
1454 TRACE("%p, %p, %d", event_set, port, mask);
1456 if (!event_set)
1457 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1459 if (!port)
1460 RETURN_ERROR(SP_ERR_ARG, "Null port");
1462 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1463 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1465 if (!mask)
1466 RETURN_OK();
1468 #ifdef _WIN32
1469 enum sp_event handle_mask;
1470 if ((handle_mask = mask & SP_EVENT_TX_READY))
1471 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1472 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1473 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1474 #else
1475 TRY(add_handle(event_set, port->fd, mask));
1476 #endif
1478 RETURN_OK();
1481 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1483 TRACE("%p", event_set);
1485 if (!event_set) {
1486 DEBUG("Null event set");
1487 RETURN();
1490 DEBUG("Freeing event set");
1492 if (event_set->handles)
1493 free(event_set->handles);
1494 if (event_set->masks)
1495 free(event_set->masks);
1497 free(event_set);
1499 RETURN();
1502 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1503 unsigned int timeout_ms)
1505 TRACE("%p, %d", event_set, timeout_ms);
1507 if (!event_set)
1508 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1510 #ifdef _WIN32
1511 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1512 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1513 RETURN_FAIL("WaitForMultipleObjects() failed");
1515 RETURN_OK();
1516 #else
1517 struct timeout timeout;
1518 int poll_timeout;
1519 int result;
1520 struct pollfd *pollfds;
1521 unsigned int i;
1523 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1524 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1526 for (i = 0; i < event_set->count; i++) {
1527 pollfds[i].fd = ((int *)event_set->handles)[i];
1528 pollfds[i].events = 0;
1529 pollfds[i].revents = 0;
1530 if (event_set->masks[i] & SP_EVENT_RX_READY)
1531 pollfds[i].events |= POLLIN;
1532 if (event_set->masks[i] & SP_EVENT_TX_READY)
1533 pollfds[i].events |= POLLOUT;
1534 if (event_set->masks[i] & SP_EVENT_ERROR)
1535 pollfds[i].events |= POLLERR;
1538 timeout_start(&timeout, timeout_ms);
1539 timeout_limit(&timeout, INT_MAX);
1541 /* Loop until an event occurs. */
1542 while (1) {
1544 if (timeout_check(&timeout)) {
1545 DEBUG("Wait timed out");
1546 break;
1549 poll_timeout = (int) timeout_remaining_ms(&timeout);
1550 if (poll_timeout == 0)
1551 poll_timeout = -1;
1553 result = poll(pollfds, event_set->count, poll_timeout);
1555 timeout_update(&timeout);
1557 if (result < 0) {
1558 if (errno == EINTR) {
1559 DEBUG("poll() call was interrupted, repeating");
1560 continue;
1561 } else {
1562 free(pollfds);
1563 RETURN_FAIL("poll() failed");
1565 } else if (result == 0) {
1566 DEBUG("poll() timed out");
1567 if (!timeout.overflow)
1568 break;
1569 } else {
1570 DEBUG("poll() completed");
1571 break;
1575 free(pollfds);
1576 RETURN_OK();
1577 #endif
1580 #ifdef USE_TERMIOS_SPEED
1581 static enum sp_return get_baudrate(int fd, int *baudrate)
1583 void *data;
1585 TRACE("%d, %p", fd, baudrate);
1587 DEBUG("Getting baud rate");
1589 if (!(data = malloc(get_termios_size())))
1590 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1592 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1593 free(data);
1594 RETURN_FAIL("Getting termios failed");
1597 *baudrate = get_termios_speed(data);
1599 free(data);
1601 RETURN_OK();
1604 static enum sp_return set_baudrate(int fd, int baudrate)
1606 void *data;
1608 TRACE("%d, %d", fd, baudrate);
1610 DEBUG("Getting baud rate");
1612 if (!(data = malloc(get_termios_size())))
1613 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1615 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1616 free(data);
1617 RETURN_FAIL("Getting termios failed");
1620 DEBUG("Setting baud rate");
1622 set_termios_speed(data, baudrate);
1624 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1625 free(data);
1626 RETURN_FAIL("Setting termios failed");
1629 free(data);
1631 RETURN_OK();
1633 #endif /* USE_TERMIOS_SPEED */
1635 #ifdef USE_TERMIOX
1636 static enum sp_return get_flow(int fd, struct port_data *data)
1638 void *termx;
1640 TRACE("%d, %p", fd, data);
1642 DEBUG("Getting advanced flow control");
1644 if (!(termx = malloc(get_termiox_size())))
1645 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1647 if (ioctl(fd, TCGETX, termx) < 0) {
1648 free(termx);
1649 RETURN_FAIL("Getting termiox failed");
1652 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1653 &data->dtr_flow, &data->dsr_flow);
1655 free(termx);
1657 RETURN_OK();
1660 static enum sp_return set_flow(int fd, struct port_data *data)
1662 void *termx;
1664 TRACE("%d, %p", fd, data);
1666 DEBUG("Getting advanced flow control");
1668 if (!(termx = malloc(get_termiox_size())))
1669 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1671 if (ioctl(fd, TCGETX, termx) < 0) {
1672 free(termx);
1673 RETURN_FAIL("Getting termiox failed");
1676 DEBUG("Setting advanced flow control");
1678 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1679 data->dtr_flow, data->dsr_flow);
1681 if (ioctl(fd, TCSETX, termx) < 0) {
1682 free(termx);
1683 RETURN_FAIL("Setting termiox failed");
1686 free(termx);
1688 RETURN_OK();
1690 #endif /* USE_TERMIOX */
1692 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1693 struct sp_port_config *config)
1695 unsigned int i;
1697 TRACE("%p, %p, %p", port, data, config);
1699 DEBUG_FMT("Getting configuration for port %s", port->name);
1701 #ifdef _WIN32
1702 if (!GetCommState(port->hdl, &data->dcb))
1703 RETURN_FAIL("GetCommState() failed");
1705 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1706 if (data->dcb.BaudRate == std_baudrates[i].index) {
1707 config->baudrate = std_baudrates[i].value;
1708 break;
1712 if (i == NUM_STD_BAUDRATES)
1713 /* BaudRate field can be either an index or a custom baud rate. */
1714 config->baudrate = data->dcb.BaudRate;
1716 config->bits = data->dcb.ByteSize;
1718 switch (data->dcb.Parity) {
1719 case NOPARITY:
1720 config->parity = SP_PARITY_NONE;
1721 break;
1722 case ODDPARITY:
1723 config->parity = SP_PARITY_ODD;
1724 break;
1725 case EVENPARITY:
1726 config->parity = SP_PARITY_EVEN;
1727 break;
1728 case MARKPARITY:
1729 config->parity = SP_PARITY_MARK;
1730 break;
1731 case SPACEPARITY:
1732 config->parity = SP_PARITY_SPACE;
1733 break;
1734 default:
1735 config->parity = -1;
1738 switch (data->dcb.StopBits) {
1739 case ONESTOPBIT:
1740 config->stopbits = 1;
1741 break;
1742 case TWOSTOPBITS:
1743 config->stopbits = 2;
1744 break;
1745 default:
1746 config->stopbits = -1;
1749 switch (data->dcb.fRtsControl) {
1750 case RTS_CONTROL_DISABLE:
1751 config->rts = SP_RTS_OFF;
1752 break;
1753 case RTS_CONTROL_ENABLE:
1754 config->rts = SP_RTS_ON;
1755 break;
1756 case RTS_CONTROL_HANDSHAKE:
1757 config->rts = SP_RTS_FLOW_CONTROL;
1758 break;
1759 default:
1760 config->rts = -1;
1763 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1765 switch (data->dcb.fDtrControl) {
1766 case DTR_CONTROL_DISABLE:
1767 config->dtr = SP_DTR_OFF;
1768 break;
1769 case DTR_CONTROL_ENABLE:
1770 config->dtr = SP_DTR_ON;
1771 break;
1772 case DTR_CONTROL_HANDSHAKE:
1773 config->dtr = SP_DTR_FLOW_CONTROL;
1774 break;
1775 default:
1776 config->dtr = -1;
1779 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1781 if (data->dcb.fInX) {
1782 if (data->dcb.fOutX)
1783 config->xon_xoff = SP_XONXOFF_INOUT;
1784 else
1785 config->xon_xoff = SP_XONXOFF_IN;
1786 } else {
1787 if (data->dcb.fOutX)
1788 config->xon_xoff = SP_XONXOFF_OUT;
1789 else
1790 config->xon_xoff = SP_XONXOFF_DISABLED;
1793 #else // !_WIN32
1795 if (tcgetattr(port->fd, &data->term) < 0)
1796 RETURN_FAIL("tcgetattr() failed");
1798 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1799 RETURN_FAIL("TIOCMGET ioctl failed");
1801 #ifdef USE_TERMIOX
1802 int ret = get_flow(port->fd, data);
1804 if (ret == SP_ERR_FAIL && errno == EINVAL)
1805 data->termiox_supported = 0;
1806 else if (ret < 0)
1807 RETURN_CODEVAL(ret);
1808 else
1809 data->termiox_supported = 1;
1810 #else
1811 data->termiox_supported = 0;
1812 #endif
1814 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1815 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1816 config->baudrate = std_baudrates[i].value;
1817 break;
1821 if (i == NUM_STD_BAUDRATES) {
1822 #ifdef __APPLE__
1823 config->baudrate = (int)data->term.c_ispeed;
1824 #elif defined(USE_TERMIOS_SPEED)
1825 TRY(get_baudrate(port->fd, &config->baudrate));
1826 #else
1827 config->baudrate = -1;
1828 #endif
1831 switch (data->term.c_cflag & CSIZE) {
1832 case CS8:
1833 config->bits = 8;
1834 break;
1835 case CS7:
1836 config->bits = 7;
1837 break;
1838 case CS6:
1839 config->bits = 6;
1840 break;
1841 case CS5:
1842 config->bits = 5;
1843 break;
1844 default:
1845 config->bits = -1;
1848 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1849 config->parity = SP_PARITY_NONE;
1850 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1851 config->parity = -1;
1852 #ifdef CMSPAR
1853 else if (data->term.c_cflag & CMSPAR)
1854 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1855 #endif
1856 else
1857 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1859 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1861 if (data->term.c_cflag & CRTSCTS) {
1862 config->rts = SP_RTS_FLOW_CONTROL;
1863 config->cts = SP_CTS_FLOW_CONTROL;
1864 } else {
1865 if (data->termiox_supported && data->rts_flow)
1866 config->rts = SP_RTS_FLOW_CONTROL;
1867 else
1868 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1870 config->cts = (data->termiox_supported && data->cts_flow) ?
1871 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1874 if (data->termiox_supported && data->dtr_flow)
1875 config->dtr = SP_DTR_FLOW_CONTROL;
1876 else
1877 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1879 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1880 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1882 if (data->term.c_iflag & IXOFF) {
1883 if (data->term.c_iflag & IXON)
1884 config->xon_xoff = SP_XONXOFF_INOUT;
1885 else
1886 config->xon_xoff = SP_XONXOFF_IN;
1887 } else {
1888 if (data->term.c_iflag & IXON)
1889 config->xon_xoff = SP_XONXOFF_OUT;
1890 else
1891 config->xon_xoff = SP_XONXOFF_DISABLED;
1893 #endif
1895 RETURN_OK();
1898 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1899 const struct sp_port_config *config)
1901 unsigned int i;
1902 #ifdef __APPLE__
1903 BAUD_TYPE baud_nonstd;
1905 baud_nonstd = B0;
1906 #endif
1907 #ifdef USE_TERMIOS_SPEED
1908 int baud_nonstd = 0;
1909 #endif
1911 TRACE("%p, %p, %p", port, data, config);
1913 DEBUG_FMT("Setting configuration for port %s", port->name);
1915 #ifdef _WIN32
1916 BYTE* new_buf;
1918 TRY(await_write_completion(port));
1920 if (config->baudrate >= 0) {
1921 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1922 if (config->baudrate == std_baudrates[i].value) {
1923 data->dcb.BaudRate = std_baudrates[i].index;
1924 break;
1928 if (i == NUM_STD_BAUDRATES)
1929 data->dcb.BaudRate = config->baudrate;
1931 /* Allocate write buffer for 50ms of data at baud rate. */
1932 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1933 new_buf = realloc(port->write_buf, port->write_buf_size);
1934 if (!new_buf)
1935 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1936 port->write_buf = new_buf;
1939 if (config->bits >= 0)
1940 data->dcb.ByteSize = config->bits;
1942 if (config->parity >= 0) {
1943 switch (config->parity) {
1944 case SP_PARITY_NONE:
1945 data->dcb.Parity = NOPARITY;
1946 break;
1947 case SP_PARITY_ODD:
1948 data->dcb.Parity = ODDPARITY;
1949 break;
1950 case SP_PARITY_EVEN:
1951 data->dcb.Parity = EVENPARITY;
1952 break;
1953 case SP_PARITY_MARK:
1954 data->dcb.Parity = MARKPARITY;
1955 break;
1956 case SP_PARITY_SPACE:
1957 data->dcb.Parity = SPACEPARITY;
1958 break;
1959 default:
1960 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1964 if (config->stopbits >= 0) {
1965 switch (config->stopbits) {
1966 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1967 case 1:
1968 data->dcb.StopBits = ONESTOPBIT;
1969 break;
1970 case 2:
1971 data->dcb.StopBits = TWOSTOPBITS;
1972 break;
1973 default:
1974 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1978 if (config->rts >= 0) {
1979 switch (config->rts) {
1980 case SP_RTS_OFF:
1981 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1982 break;
1983 case SP_RTS_ON:
1984 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1985 break;
1986 case SP_RTS_FLOW_CONTROL:
1987 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1988 break;
1989 default:
1990 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1994 if (config->cts >= 0) {
1995 switch (config->cts) {
1996 case SP_CTS_IGNORE:
1997 data->dcb.fOutxCtsFlow = FALSE;
1998 break;
1999 case SP_CTS_FLOW_CONTROL:
2000 data->dcb.fOutxCtsFlow = TRUE;
2001 break;
2002 default:
2003 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
2007 if (config->dtr >= 0) {
2008 switch (config->dtr) {
2009 case SP_DTR_OFF:
2010 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
2011 break;
2012 case SP_DTR_ON:
2013 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
2014 break;
2015 case SP_DTR_FLOW_CONTROL:
2016 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
2017 break;
2018 default:
2019 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
2023 if (config->dsr >= 0) {
2024 switch (config->dsr) {
2025 case SP_DSR_IGNORE:
2026 data->dcb.fOutxDsrFlow = FALSE;
2027 break;
2028 case SP_DSR_FLOW_CONTROL:
2029 data->dcb.fOutxDsrFlow = TRUE;
2030 break;
2031 default:
2032 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2036 if (config->xon_xoff >= 0) {
2037 switch (config->xon_xoff) {
2038 case SP_XONXOFF_DISABLED:
2039 data->dcb.fInX = FALSE;
2040 data->dcb.fOutX = FALSE;
2041 break;
2042 case SP_XONXOFF_IN:
2043 data->dcb.fInX = TRUE;
2044 data->dcb.fOutX = FALSE;
2045 break;
2046 case SP_XONXOFF_OUT:
2047 data->dcb.fInX = FALSE;
2048 data->dcb.fOutX = TRUE;
2049 break;
2050 case SP_XONXOFF_INOUT:
2051 data->dcb.fInX = TRUE;
2052 data->dcb.fOutX = TRUE;
2053 break;
2054 default:
2055 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2059 if (!SetCommState(port->hdl, &data->dcb))
2060 RETURN_FAIL("SetCommState() failed");
2062 #else /* !_WIN32 */
2064 int controlbits;
2066 if (config->baudrate >= 0) {
2067 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2068 if (config->baudrate == std_baudrates[i].value) {
2069 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2070 RETURN_FAIL("cfsetospeed() failed");
2072 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2073 RETURN_FAIL("cfsetispeed() failed");
2074 break;
2078 /* Non-standard baud rate */
2079 if (i == NUM_STD_BAUDRATES) {
2080 #ifdef __APPLE__
2081 /* Set "dummy" baud rate. */
2082 if (cfsetspeed(&data->term, B9600) < 0)
2083 RETURN_FAIL("cfsetspeed() failed");
2084 baud_nonstd = config->baudrate;
2085 #elif defined(USE_TERMIOS_SPEED)
2086 baud_nonstd = 1;
2087 #else
2088 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2089 #endif
2093 if (config->bits >= 0) {
2094 data->term.c_cflag &= ~CSIZE;
2095 switch (config->bits) {
2096 case 8:
2097 data->term.c_cflag |= CS8;
2098 break;
2099 case 7:
2100 data->term.c_cflag |= CS7;
2101 break;
2102 case 6:
2103 data->term.c_cflag |= CS6;
2104 break;
2105 case 5:
2106 data->term.c_cflag |= CS5;
2107 break;
2108 default:
2109 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2113 if (config->parity >= 0) {
2114 data->term.c_iflag &= ~IGNPAR;
2115 data->term.c_cflag &= ~(PARENB | PARODD);
2116 #ifdef CMSPAR
2117 data->term.c_cflag &= ~CMSPAR;
2118 #endif
2119 switch (config->parity) {
2120 case SP_PARITY_NONE:
2121 data->term.c_iflag |= IGNPAR;
2122 break;
2123 case SP_PARITY_EVEN:
2124 data->term.c_cflag |= PARENB;
2125 break;
2126 case SP_PARITY_ODD:
2127 data->term.c_cflag |= PARENB | PARODD;
2128 break;
2129 #ifdef CMSPAR
2130 case SP_PARITY_MARK:
2131 data->term.c_cflag |= PARENB | PARODD;
2132 data->term.c_cflag |= CMSPAR;
2133 break;
2134 case SP_PARITY_SPACE:
2135 data->term.c_cflag |= PARENB;
2136 data->term.c_cflag |= CMSPAR;
2137 break;
2138 #else
2139 case SP_PARITY_MARK:
2140 case SP_PARITY_SPACE:
2141 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2142 #endif
2143 default:
2144 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2148 if (config->stopbits >= 0) {
2149 data->term.c_cflag &= ~CSTOPB;
2150 switch (config->stopbits) {
2151 case 1:
2152 data->term.c_cflag &= ~CSTOPB;
2153 break;
2154 case 2:
2155 data->term.c_cflag |= CSTOPB;
2156 break;
2157 default:
2158 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2162 if (config->rts >= 0 || config->cts >= 0) {
2163 if (data->termiox_supported) {
2164 data->rts_flow = data->cts_flow = 0;
2165 switch (config->rts) {
2166 case SP_RTS_OFF:
2167 case SP_RTS_ON:
2168 controlbits = TIOCM_RTS;
2169 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2170 RETURN_FAIL("Setting RTS signal level failed");
2171 break;
2172 case SP_RTS_FLOW_CONTROL:
2173 data->rts_flow = 1;
2174 break;
2175 default:
2176 break;
2178 if (config->cts == SP_CTS_FLOW_CONTROL)
2179 data->cts_flow = 1;
2181 if (data->rts_flow && data->cts_flow)
2182 data->term.c_iflag |= CRTSCTS;
2183 else
2184 data->term.c_iflag &= ~CRTSCTS;
2185 } else {
2186 /* Asymmetric use of RTS/CTS not supported. */
2187 if (data->term.c_iflag & CRTSCTS) {
2188 /* Flow control can only be disabled for both RTS & CTS together. */
2189 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2190 if (config->cts != SP_CTS_IGNORE)
2191 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2193 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2194 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2195 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2197 } else {
2198 /* Flow control can only be enabled for both RTS & CTS together. */
2199 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2200 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2201 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2204 if (config->rts >= 0) {
2205 if (config->rts == SP_RTS_FLOW_CONTROL) {
2206 data->term.c_iflag |= CRTSCTS;
2207 } else {
2208 controlbits = TIOCM_RTS;
2209 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2210 &controlbits) < 0)
2211 RETURN_FAIL("Setting RTS signal level failed");
2217 if (config->dtr >= 0 || config->dsr >= 0) {
2218 if (data->termiox_supported) {
2219 data->dtr_flow = data->dsr_flow = 0;
2220 switch (config->dtr) {
2221 case SP_DTR_OFF:
2222 case SP_DTR_ON:
2223 controlbits = TIOCM_DTR;
2224 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2225 RETURN_FAIL("Setting DTR signal level failed");
2226 break;
2227 case SP_DTR_FLOW_CONTROL:
2228 data->dtr_flow = 1;
2229 break;
2230 default:
2231 break;
2233 if (config->dsr == SP_DSR_FLOW_CONTROL)
2234 data->dsr_flow = 1;
2235 } else {
2236 /* DTR/DSR flow control not supported. */
2237 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2238 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2240 if (config->dtr >= 0) {
2241 controlbits = TIOCM_DTR;
2242 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2243 &controlbits) < 0)
2244 RETURN_FAIL("Setting DTR signal level failed");
2249 if (config->xon_xoff >= 0) {
2250 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2251 switch (config->xon_xoff) {
2252 case SP_XONXOFF_DISABLED:
2253 break;
2254 case SP_XONXOFF_IN:
2255 data->term.c_iflag |= IXOFF;
2256 break;
2257 case SP_XONXOFF_OUT:
2258 data->term.c_iflag |= IXON | IXANY;
2259 break;
2260 case SP_XONXOFF_INOUT:
2261 data->term.c_iflag |= IXON | IXOFF | IXANY;
2262 break;
2263 default:
2264 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2268 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2269 RETURN_FAIL("tcsetattr() failed");
2271 #ifdef __APPLE__
2272 if (baud_nonstd != B0) {
2273 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2274 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2276 * Set baud rates in data->term to correct, but incompatible
2277 * with tcsetattr() value, same as delivered by tcgetattr().
2279 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2280 RETURN_FAIL("cfsetspeed() failed");
2282 #elif defined(__linux__)
2283 #ifdef USE_TERMIOS_SPEED
2284 if (baud_nonstd)
2285 TRY(set_baudrate(port->fd, config->baudrate));
2286 #endif
2287 #ifdef USE_TERMIOX
2288 if (data->termiox_supported)
2289 TRY(set_flow(port->fd, data));
2290 #endif
2291 #endif
2293 #endif /* !_WIN32 */
2295 RETURN_OK();
2298 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2300 struct sp_port_config *config;
2302 TRACE("%p", config_ptr);
2304 if (!config_ptr)
2305 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2307 *config_ptr = NULL;
2309 if (!(config = malloc(sizeof(struct sp_port_config))))
2310 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2312 config->baudrate = -1;
2313 config->bits = -1;
2314 config->parity = -1;
2315 config->stopbits = -1;
2316 config->rts = -1;
2317 config->cts = -1;
2318 config->dtr = -1;
2319 config->dsr = -1;
2320 config->xon_xoff = -1;
2322 *config_ptr = config;
2324 RETURN_OK();
2327 SP_API void sp_free_config(struct sp_port_config *config)
2329 TRACE("%p", config);
2331 if (!config)
2332 DEBUG("Null config");
2333 else
2334 free(config);
2336 RETURN();
2339 SP_API enum sp_return sp_get_config(struct sp_port *port,
2340 struct sp_port_config *config)
2342 struct port_data data;
2344 TRACE("%p, %p", port, config);
2346 CHECK_OPEN_PORT();
2348 if (!config)
2349 RETURN_ERROR(SP_ERR_ARG, "Null config");
2351 TRY(get_config(port, &data, config));
2353 RETURN_OK();
2356 SP_API enum sp_return sp_set_config(struct sp_port *port,
2357 const struct sp_port_config *config)
2359 struct port_data data;
2360 struct sp_port_config prev_config;
2362 TRACE("%p, %p", port, config);
2364 CHECK_OPEN_PORT();
2366 if (!config)
2367 RETURN_ERROR(SP_ERR_ARG, "Null config");
2369 TRY(get_config(port, &data, &prev_config));
2370 TRY(set_config(port, &data, config));
2372 RETURN_OK();
2375 #define CREATE_ACCESSORS(x, type) \
2376 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2377 struct port_data data; \
2378 struct sp_port_config config; \
2379 TRACE("%p, %d", port, x); \
2380 CHECK_OPEN_PORT(); \
2381 TRY(get_config(port, &data, &config)); \
2382 config.x = x; \
2383 TRY(set_config(port, &data, &config)); \
2384 RETURN_OK(); \
2386 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2387 type *x) { \
2388 TRACE("%p, %p", config, x); \
2389 if (!x) \
2390 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2391 if (!config) \
2392 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2393 *x = config->x; \
2394 RETURN_OK(); \
2396 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2397 type x) { \
2398 TRACE("%p, %d", config, x); \
2399 if (!config) \
2400 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2401 config->x = x; \
2402 RETURN_OK(); \
2405 CREATE_ACCESSORS(baudrate, int)
2406 CREATE_ACCESSORS(bits, int)
2407 CREATE_ACCESSORS(parity, enum sp_parity)
2408 CREATE_ACCESSORS(stopbits, int)
2409 CREATE_ACCESSORS(rts, enum sp_rts)
2410 CREATE_ACCESSORS(cts, enum sp_cts)
2411 CREATE_ACCESSORS(dtr, enum sp_dtr)
2412 CREATE_ACCESSORS(dsr, enum sp_dsr)
2413 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2415 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2416 enum sp_flowcontrol flowcontrol)
2418 if (!config)
2419 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2421 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2422 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2424 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2425 config->xon_xoff = SP_XONXOFF_INOUT;
2426 else
2427 config->xon_xoff = SP_XONXOFF_DISABLED;
2429 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2430 config->rts = SP_RTS_FLOW_CONTROL;
2431 config->cts = SP_CTS_FLOW_CONTROL;
2432 } else {
2433 if (config->rts == SP_RTS_FLOW_CONTROL)
2434 config->rts = SP_RTS_ON;
2435 config->cts = SP_CTS_IGNORE;
2438 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2439 config->dtr = SP_DTR_FLOW_CONTROL;
2440 config->dsr = SP_DSR_FLOW_CONTROL;
2441 } else {
2442 if (config->dtr == SP_DTR_FLOW_CONTROL)
2443 config->dtr = SP_DTR_ON;
2444 config->dsr = SP_DSR_IGNORE;
2447 RETURN_OK();
2450 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2451 enum sp_flowcontrol flowcontrol)
2453 struct port_data data;
2454 struct sp_port_config config;
2456 TRACE("%p, %d", port, flowcontrol);
2458 CHECK_OPEN_PORT();
2460 TRY(get_config(port, &data, &config));
2462 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2464 TRY(set_config(port, &data, &config));
2466 RETURN_OK();
2469 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2470 enum sp_signal *signals)
2472 TRACE("%p, %p", port, signals);
2474 CHECK_OPEN_PORT();
2476 if (!signals)
2477 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2479 DEBUG_FMT("Getting control signals for port %s", port->name);
2481 *signals = 0;
2482 #ifdef _WIN32
2483 DWORD bits;
2484 if (GetCommModemStatus(port->hdl, &bits) == 0)
2485 RETURN_FAIL("GetCommModemStatus() failed");
2486 if (bits & MS_CTS_ON)
2487 *signals |= SP_SIG_CTS;
2488 if (bits & MS_DSR_ON)
2489 *signals |= SP_SIG_DSR;
2490 if (bits & MS_RLSD_ON)
2491 *signals |= SP_SIG_DCD;
2492 if (bits & MS_RING_ON)
2493 *signals |= SP_SIG_RI;
2494 #else
2495 int bits;
2496 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2497 RETURN_FAIL("TIOCMGET ioctl failed");
2498 if (bits & TIOCM_CTS)
2499 *signals |= SP_SIG_CTS;
2500 if (bits & TIOCM_DSR)
2501 *signals |= SP_SIG_DSR;
2502 if (bits & TIOCM_CAR)
2503 *signals |= SP_SIG_DCD;
2504 if (bits & TIOCM_RNG)
2505 *signals |= SP_SIG_RI;
2506 #endif
2507 RETURN_OK();
2510 SP_API enum sp_return sp_start_break(struct sp_port *port)
2512 TRACE("%p", port);
2514 CHECK_OPEN_PORT();
2515 #ifdef _WIN32
2516 if (SetCommBreak(port->hdl) == 0)
2517 RETURN_FAIL("SetCommBreak() failed");
2518 #else
2519 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2520 RETURN_FAIL("TIOCSBRK ioctl failed");
2521 #endif
2523 RETURN_OK();
2526 SP_API enum sp_return sp_end_break(struct sp_port *port)
2528 TRACE("%p", port);
2530 CHECK_OPEN_PORT();
2531 #ifdef _WIN32
2532 if (ClearCommBreak(port->hdl) == 0)
2533 RETURN_FAIL("ClearCommBreak() failed");
2534 #else
2535 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2536 RETURN_FAIL("TIOCCBRK ioctl failed");
2537 #endif
2539 RETURN_OK();
2542 SP_API int sp_last_error_code(void)
2544 TRACE_VOID();
2545 #ifdef _WIN32
2546 RETURN_INT(GetLastError());
2547 #else
2548 RETURN_INT(errno);
2549 #endif
2552 SP_API char *sp_last_error_message(void)
2554 TRACE_VOID();
2556 #ifdef _WIN32
2557 char *message;
2558 DWORD error = GetLastError();
2560 DWORD length = FormatMessageA(
2561 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2562 FORMAT_MESSAGE_FROM_SYSTEM |
2563 FORMAT_MESSAGE_IGNORE_INSERTS,
2564 NULL,
2565 error,
2566 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2567 (LPSTR) &message,
2568 0, NULL );
2570 if (length >= 2 && message[length - 2] == '\r')
2571 message[length - 2] = '\0';
2573 RETURN_STRING(message);
2574 #else
2575 RETURN_STRING(strerror(errno));
2576 #endif
2579 SP_API void sp_free_error_message(char *message)
2581 TRACE("%s", message);
2583 #ifdef _WIN32
2584 LocalFree(message);
2585 #else
2586 (void)message;
2587 #endif
2589 RETURN();
2592 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2594 TRACE("%p", handler);
2596 sp_debug_handler = handler;
2598 RETURN();
2601 SP_API void sp_default_debug_handler(const char *format, ...)
2603 va_list args;
2604 va_start(args, format);
2605 if (getenv("LIBSERIALPORT_DEBUG")) {
2606 fputs("sp: ", stderr);
2607 vfprintf(stderr, format, args);
2609 va_end(args);
2612 SP_API int sp_get_major_package_version(void)
2614 return SP_PACKAGE_VERSION_MAJOR;
2617 SP_API int sp_get_minor_package_version(void)
2619 return SP_PACKAGE_VERSION_MINOR;
2622 SP_API int sp_get_micro_package_version(void)
2624 return SP_PACKAGE_VERSION_MICRO;
2627 SP_API const char *sp_get_package_version_string(void)
2629 return SP_PACKAGE_VERSION_STRING;
2632 SP_API int sp_get_current_lib_version(void)
2634 return SP_LIB_VERSION_CURRENT;
2637 SP_API int sp_get_revision_lib_version(void)
2639 return SP_LIB_VERSION_REVISION;
2642 SP_API int sp_get_age_lib_version(void)
2644 return SP_LIB_VERSION_AGE;
2647 SP_API const char *sp_get_lib_version_string(void)
2649 return SP_LIB_VERSION_STRING;
2652 /** @} */