]> sigrok.org Git - libserialport.git/blame_incremental - serialport.c
Move repetitive timeout code into helper functions.
[libserialport.git] / serialport.c
... / ...
CommitLineData
1/*
2 * This file is part of the libserialport project.
3 *
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>
9 *
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.
14 *
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.
19 *
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/>.
22 */
23
24#include <config.h>
25#include "libserialport.h"
26#include "libserialport_internal.h"
27
28static const struct std_baudrate std_baudrates[] = {
29#ifdef _WIN32
30 /*
31 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
32 * have documented CBR_* macros.
33 */
34 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
35 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
36 BAUD(115200), BAUD(128000), BAUD(256000),
37#else
38 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
39 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
40 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
41 BAUD(230400),
42#if !defined(__APPLE__) && !defined(__OpenBSD__)
43 BAUD(460800),
44#endif
45#endif
46};
47
48#define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
49
50void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
51
52static enum sp_return get_config(struct sp_port *port, struct port_data *data,
53 struct sp_port_config *config);
54
55static enum sp_return set_config(struct sp_port *port, struct port_data *data,
56 const struct sp_port_config *config);
57
58#ifndef _WIN32
59
60/* Timing abstraction */
61
62struct time {
63 struct timeval tv;
64};
65
66struct timeout {
67 unsigned int ms;
68 struct time start, delta, now, end;
69 struct timeval delta_tv;
70 bool overflow;
71};
72
73#define TIME_ZERO {.tv = {0, 0}}
74#define TIME_MS(ms) {.tv = {ms / 1000, (ms % 1000) * 1000}}
75
76const struct time max_delta = TIME_MS(INT_MAX);
77
78static void time_get(struct time *time)
79{
80#ifdef HAVE_CLOCK_GETTIME
81 struct timespec ts;
82 if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
83 clock_gettime(CLOCK_REALTIME, &ts);
84 time->tv.tv_sec = ts.tv_sec;
85 time->tv.tv_usec = ts.tv_nsec / 1000;
86#elif defined(__APPLE__)
87 mach_timebase_info_data_t info;
88 mach_timebase_info(&info);
89 uint64_t ticks = mach_absolute_time();
90 uint64_t ns = (ticks * info.numer) / info.denom;
91 time->tv.tv_sec = ns / 1000000000;
92 time->tv.tv_usec = (ns % 1000000000) / 1000;
93#else
94 gettimeofday(&time->tv, NULL);
95#endif
96}
97
98static void time_set_ms(struct time *time, unsigned int ms)
99{
100 time->tv.tv_sec = ms / 1000;
101 time->tv.tv_usec = (ms % 1000) * 1000;
102}
103
104static void time_add(const struct time *a,
105 const struct time *b, struct time *result)
106{
107 timeradd(&a->tv, &b->tv, &result->tv);
108}
109
110static void time_sub(const struct time *a,
111 const struct time *b, struct time *result)
112{
113 timersub(&a->tv, &b->tv, &result->tv);
114}
115
116static bool time_greater(const struct time *a, const struct time *b)
117{
118 return timercmp(&a->tv, &b->tv, >);
119}
120
121static void time_as_timeval(const struct time *time, struct timeval *tv)
122{
123 *tv = time->tv;
124}
125
126static unsigned int time_as_ms(const struct time *time)
127{
128 return time->tv.tv_sec * 1000 + time->tv.tv_usec / 1000;
129}
130
131static void timeout_start(struct timeout *timeout, unsigned int timeout_ms)
132{
133 timeout->ms = timeout_ms;
134
135 timeout->overflow = (timeout->ms > INT_MAX);
136
137 /* Get time at start of operation. */
138 time_get(&timeout->start);
139 /* Define duration of timeout. */
140 time_set_ms(&timeout->delta, timeout_ms);
141 /* Calculate time at which we should give up. */
142 time_add(&timeout->start, &timeout->delta, &timeout->end);
143}
144
145static bool timeout_check(struct timeout *timeout)
146{
147 if (timeout->ms == 0)
148 return false;
149
150 time_get(&timeout->now);
151 time_sub(&timeout->end, &timeout->now, &timeout->delta);
152 if ((timeout->overflow = time_greater(&timeout->delta, &max_delta)))
153 timeout->delta = max_delta;
154
155 return time_greater(&timeout->now, &timeout->end);
156}
157
158static struct timeval *timeout_timeval(struct timeout *timeout)
159{
160 if (timeout->ms == 0)
161 return NULL;
162
163 time_as_timeval(&timeout->delta, &timeout->delta_tv);
164
165 return &timeout->delta_tv;
166}
167
168static unsigned int timeout_remaining_ms(struct timeout *timeout)
169{
170 if (timeout->ms == 0)
171 return -1;
172 else if (timeout->overflow)
173 return INT_MAX;
174 else
175 return time_as_ms(&timeout->delta);
176}
177
178#endif
179
180SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
181{
182 struct sp_port *port;
183#ifndef NO_PORT_METADATA
184 enum sp_return ret;
185#endif
186 int len;
187
188 TRACE("%s, %p", portname, port_ptr);
189
190 if (!port_ptr)
191 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
192
193 *port_ptr = NULL;
194
195 if (!portname)
196 RETURN_ERROR(SP_ERR_ARG, "Null port name");
197
198 DEBUG_FMT("Building structure for port %s", portname);
199
200#if !defined(_WIN32) && defined(HAVE_REALPATH)
201 /*
202 * get_port_details() below tries to be too smart and figure out
203 * some transport properties from the port name which breaks with
204 * symlinks. Therefore we canonicalize the portname first.
205 */
206 char pathbuf[PATH_MAX + 1];
207 char *res = realpath(portname, pathbuf);
208 if (!res)
209 RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
210
211 portname = pathbuf;
212#endif
213
214 if (!(port = malloc(sizeof(struct sp_port))))
215 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
216
217 len = strlen(portname) + 1;
218
219 if (!(port->name = malloc(len))) {
220 free(port);
221 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
222 }
223
224 memcpy(port->name, portname, len);
225
226#ifdef _WIN32
227 port->usb_path = NULL;
228 port->hdl = INVALID_HANDLE_VALUE;
229 port->write_buf = NULL;
230 port->write_buf_size = 0;
231#else
232 port->fd = -1;
233#endif
234
235 port->description = NULL;
236 port->transport = SP_TRANSPORT_NATIVE;
237 port->usb_bus = -1;
238 port->usb_address = -1;
239 port->usb_vid = -1;
240 port->usb_pid = -1;
241 port->usb_manufacturer = NULL;
242 port->usb_product = NULL;
243 port->usb_serial = NULL;
244 port->bluetooth_address = NULL;
245
246#ifndef NO_PORT_METADATA
247 if ((ret = get_port_details(port)) != SP_OK) {
248 sp_free_port(port);
249 return ret;
250 }
251#endif
252
253 *port_ptr = port;
254
255 RETURN_OK();
256}
257
258SP_API char *sp_get_port_name(const struct sp_port *port)
259{
260 TRACE("%p", port);
261
262 if (!port)
263 return NULL;
264
265 RETURN_STRING(port->name);
266}
267
268SP_API char *sp_get_port_description(const struct sp_port *port)
269{
270 TRACE("%p", port);
271
272 if (!port || !port->description)
273 return NULL;
274
275 RETURN_STRING(port->description);
276}
277
278SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
279{
280 TRACE("%p", port);
281
282 if (!port)
283 RETURN_ERROR(SP_ERR_ARG, "Null port");
284
285 RETURN_INT(port->transport);
286}
287
288SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
289 int *usb_bus,int *usb_address)
290{
291 TRACE("%p", port);
292
293 if (!port)
294 RETURN_ERROR(SP_ERR_ARG, "Null port");
295 if (port->transport != SP_TRANSPORT_USB)
296 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
297 if (port->usb_bus < 0 || port->usb_address < 0)
298 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
299
300 if (usb_bus)
301 *usb_bus = port->usb_bus;
302 if (usb_address)
303 *usb_address = port->usb_address;
304
305 RETURN_OK();
306}
307
308SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
309 int *usb_vid, int *usb_pid)
310{
311 TRACE("%p", port);
312
313 if (!port)
314 RETURN_ERROR(SP_ERR_ARG, "Null port");
315 if (port->transport != SP_TRANSPORT_USB)
316 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
317 if (port->usb_vid < 0 || port->usb_pid < 0)
318 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
319
320 if (usb_vid)
321 *usb_vid = port->usb_vid;
322 if (usb_pid)
323 *usb_pid = port->usb_pid;
324
325 RETURN_OK();
326}
327
328SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
329{
330 TRACE("%p", port);
331
332 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
333 return NULL;
334
335 RETURN_STRING(port->usb_manufacturer);
336}
337
338SP_API char *sp_get_port_usb_product(const struct sp_port *port)
339{
340 TRACE("%p", port);
341
342 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
343 return NULL;
344
345 RETURN_STRING(port->usb_product);
346}
347
348SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
349{
350 TRACE("%p", port);
351
352 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
353 return NULL;
354
355 RETURN_STRING(port->usb_serial);
356}
357
358SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
359{
360 TRACE("%p", port);
361
362 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
363 || !port->bluetooth_address)
364 return NULL;
365
366 RETURN_STRING(port->bluetooth_address);
367}
368
369SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
370 void *result_ptr)
371{
372 TRACE("%p, %p", port, result_ptr);
373
374 if (!port)
375 RETURN_ERROR(SP_ERR_ARG, "Null port");
376 if (!result_ptr)
377 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
378
379#ifdef _WIN32
380 HANDLE *handle_ptr = result_ptr;
381 *handle_ptr = port->hdl;
382#else
383 int *fd_ptr = result_ptr;
384 *fd_ptr = port->fd;
385#endif
386
387 RETURN_OK();
388}
389
390SP_API enum sp_return sp_copy_port(const struct sp_port *port,
391 struct sp_port **copy_ptr)
392{
393 TRACE("%p, %p", port, copy_ptr);
394
395 if (!copy_ptr)
396 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
397
398 *copy_ptr = NULL;
399
400 if (!port)
401 RETURN_ERROR(SP_ERR_ARG, "Null port");
402
403 if (!port->name)
404 RETURN_ERROR(SP_ERR_ARG, "Null port name");
405
406 DEBUG("Copying port structure");
407
408 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
409}
410
411SP_API void sp_free_port(struct sp_port *port)
412{
413 TRACE("%p", port);
414
415 if (!port) {
416 DEBUG("Null port");
417 RETURN();
418 }
419
420 DEBUG("Freeing port structure");
421
422 if (port->name)
423 free(port->name);
424 if (port->description)
425 free(port->description);
426 if (port->usb_manufacturer)
427 free(port->usb_manufacturer);
428 if (port->usb_product)
429 free(port->usb_product);
430 if (port->usb_serial)
431 free(port->usb_serial);
432 if (port->bluetooth_address)
433 free(port->bluetooth_address);
434#ifdef _WIN32
435 if (port->usb_path)
436 free(port->usb_path);
437 if (port->write_buf)
438 free(port->write_buf);
439#endif
440
441 free(port);
442
443 RETURN();
444}
445
446SP_PRIV struct sp_port **list_append(struct sp_port **list,
447 const char *portname)
448{
449 void *tmp;
450 unsigned int count;
451
452 for (count = 0; list[count]; count++)
453 ;
454 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
455 goto fail;
456 list = tmp;
457 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
458 goto fail;
459 list[count + 1] = NULL;
460 return list;
461
462fail:
463 sp_free_port_list(list);
464 return NULL;
465}
466
467SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
468{
469#ifndef NO_ENUMERATION
470 struct sp_port **list;
471 int ret;
472#endif
473
474 TRACE("%p", list_ptr);
475
476 if (!list_ptr)
477 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
478
479 *list_ptr = NULL;
480
481#ifdef NO_ENUMERATION
482 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
483#else
484 DEBUG("Enumerating ports");
485
486 if (!(list = malloc(sizeof(struct sp_port *))))
487 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
488
489 list[0] = NULL;
490
491 ret = list_ports(&list);
492
493 if (ret == SP_OK) {
494 *list_ptr = list;
495 } else {
496 sp_free_port_list(list);
497 *list_ptr = NULL;
498 }
499
500 RETURN_CODEVAL(ret);
501#endif
502}
503
504SP_API void sp_free_port_list(struct sp_port **list)
505{
506 unsigned int i;
507
508 TRACE("%p", list);
509
510 if (!list) {
511 DEBUG("Null list");
512 RETURN();
513 }
514
515 DEBUG("Freeing port list");
516
517 for (i = 0; list[i]; i++)
518 sp_free_port(list[i]);
519 free(list);
520
521 RETURN();
522}
523
524#define CHECK_PORT() do { \
525 if (!port) \
526 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
527 if (!port->name) \
528 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
529} while (0)
530#ifdef _WIN32
531#define CHECK_PORT_HANDLE() do { \
532 if (port->hdl == INVALID_HANDLE_VALUE) \
533 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
534} while (0)
535#else
536#define CHECK_PORT_HANDLE() do { \
537 if (port->fd < 0) \
538 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
539} while (0)
540#endif
541#define CHECK_OPEN_PORT() do { \
542 CHECK_PORT(); \
543 CHECK_PORT_HANDLE(); \
544} while (0)
545
546#ifdef WIN32
547/** To be called after port receive buffer is emptied. */
548static enum sp_return restart_wait(struct sp_port *port)
549{
550 DWORD wait_result;
551
552 if (port->wait_running) {
553 /* Check status of running wait operation. */
554 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
555 &wait_result, FALSE)) {
556 DEBUG("Previous wait completed");
557 port->wait_running = FALSE;
558 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
559 DEBUG("Previous wait still running");
560 RETURN_OK();
561 } else {
562 RETURN_FAIL("GetOverlappedResult() failed");
563 }
564 }
565
566 if (!port->wait_running) {
567 /* Start new wait operation. */
568 if (WaitCommEvent(port->hdl, &port->events,
569 &port->wait_ovl)) {
570 DEBUG("New wait returned, events already pending");
571 } else if (GetLastError() == ERROR_IO_PENDING) {
572 DEBUG("New wait running in background");
573 port->wait_running = TRUE;
574 } else {
575 RETURN_FAIL("WaitCommEvent() failed");
576 }
577 }
578
579 RETURN_OK();
580}
581#endif
582
583SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
584{
585 struct port_data data;
586 struct sp_port_config config;
587 enum sp_return ret;
588
589 TRACE("%p, 0x%x", port, flags);
590
591 CHECK_PORT();
592
593 if (flags > SP_MODE_READ_WRITE)
594 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
595
596 DEBUG_FMT("Opening port %s", port->name);
597
598#ifdef _WIN32
599 DWORD desired_access = 0, flags_and_attributes = 0, errors;
600 char *escaped_port_name;
601 COMSTAT status;
602
603 /* Prefix port name with '\\.\' to work with ports above COM9. */
604 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
605 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
606 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
607
608 /* Map 'flags' to the OS-specific settings. */
609 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
610 if (flags & SP_MODE_READ)
611 desired_access |= GENERIC_READ;
612 if (flags & SP_MODE_WRITE)
613 desired_access |= GENERIC_WRITE;
614
615 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
616 OPEN_EXISTING, flags_and_attributes, 0);
617
618 free(escaped_port_name);
619
620 if (port->hdl == INVALID_HANDLE_VALUE)
621 RETURN_FAIL("Port CreateFile() failed");
622
623 /* All timeouts initially disabled. */
624 port->timeouts.ReadIntervalTimeout = 0;
625 port->timeouts.ReadTotalTimeoutMultiplier = 0;
626 port->timeouts.ReadTotalTimeoutConstant = 0;
627 port->timeouts.WriteTotalTimeoutMultiplier = 0;
628 port->timeouts.WriteTotalTimeoutConstant = 0;
629
630 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
631 sp_close(port);
632 RETURN_FAIL("SetCommTimeouts() failed");
633 }
634
635 /* Prepare OVERLAPPED structures. */
636#define INIT_OVERLAPPED(ovl) do { \
637 memset(&port->ovl, 0, sizeof(port->ovl)); \
638 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
639 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
640 == INVALID_HANDLE_VALUE) { \
641 sp_close(port); \
642 RETURN_FAIL(#ovl "CreateEvent() failed"); \
643 } \
644} while (0)
645
646 INIT_OVERLAPPED(read_ovl);
647 INIT_OVERLAPPED(write_ovl);
648 INIT_OVERLAPPED(wait_ovl);
649
650 /* Set event mask for RX and error events. */
651 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
652 sp_close(port);
653 RETURN_FAIL("SetCommMask() failed");
654 }
655
656 port->writing = FALSE;
657 port->wait_running = FALSE;
658
659 ret = restart_wait(port);
660
661 if (ret < 0) {
662 sp_close(port);
663 RETURN_CODEVAL(ret);
664 }
665#else
666 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
667
668 /* Map 'flags' to the OS-specific settings. */
669 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
670 flags_local |= O_RDWR;
671 else if (flags & SP_MODE_READ)
672 flags_local |= O_RDONLY;
673 else if (flags & SP_MODE_WRITE)
674 flags_local |= O_WRONLY;
675
676 if ((port->fd = open(port->name, flags_local)) < 0)
677 RETURN_FAIL("open() failed");
678#endif
679
680 ret = get_config(port, &data, &config);
681
682 if (ret < 0) {
683 sp_close(port);
684 RETURN_CODEVAL(ret);
685 }
686
687 /* Set sane port settings. */
688#ifdef _WIN32
689 data.dcb.fBinary = TRUE;
690 data.dcb.fDsrSensitivity = FALSE;
691 data.dcb.fErrorChar = FALSE;
692 data.dcb.fNull = FALSE;
693 data.dcb.fAbortOnError = FALSE;
694#else
695 /* Turn off all fancy termios tricks, give us a raw channel. */
696 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
697#ifdef IUCLC
698 data.term.c_iflag &= ~IUCLC;
699#endif
700 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
701#ifdef OLCUC
702 data.term.c_oflag &= ~OLCUC;
703#endif
704#ifdef NLDLY
705 data.term.c_oflag &= ~NLDLY;
706#endif
707#ifdef CRDLY
708 data.term.c_oflag &= ~CRDLY;
709#endif
710#ifdef TABDLY
711 data.term.c_oflag &= ~TABDLY;
712#endif
713#ifdef BSDLY
714 data.term.c_oflag &= ~BSDLY;
715#endif
716#ifdef VTDLY
717 data.term.c_oflag &= ~VTDLY;
718#endif
719#ifdef FFDLY
720 data.term.c_oflag &= ~FFDLY;
721#endif
722#ifdef OFILL
723 data.term.c_oflag &= ~OFILL;
724#endif
725 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
726 data.term.c_cc[VMIN] = 0;
727 data.term.c_cc[VTIME] = 0;
728
729 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
730 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
731#endif
732
733#ifdef _WIN32
734 if (ClearCommError(port->hdl, &errors, &status) == 0)
735 RETURN_FAIL("ClearCommError() failed");
736#endif
737
738 ret = set_config(port, &data, &config);
739
740 if (ret < 0) {
741 sp_close(port);
742 RETURN_CODEVAL(ret);
743 }
744
745 RETURN_OK();
746}
747
748SP_API enum sp_return sp_close(struct sp_port *port)
749{
750 TRACE("%p", port);
751
752 CHECK_OPEN_PORT();
753
754 DEBUG_FMT("Closing port %s", port->name);
755
756#ifdef _WIN32
757 /* Returns non-zero upon success, 0 upon failure. */
758 if (CloseHandle(port->hdl) == 0)
759 RETURN_FAIL("Port CloseHandle() failed");
760 port->hdl = INVALID_HANDLE_VALUE;
761
762 /* Close event handles for overlapped structures. */
763#define CLOSE_OVERLAPPED(ovl) do { \
764 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
765 CloseHandle(port->ovl.hEvent) == 0) \
766 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
767} while (0)
768 CLOSE_OVERLAPPED(read_ovl);
769 CLOSE_OVERLAPPED(write_ovl);
770 CLOSE_OVERLAPPED(wait_ovl);
771
772 if (port->write_buf) {
773 free(port->write_buf);
774 port->write_buf = NULL;
775 }
776#else
777 /* Returns 0 upon success, -1 upon failure. */
778 if (close(port->fd) == -1)
779 RETURN_FAIL("close() failed");
780 port->fd = -1;
781#endif
782
783 RETURN_OK();
784}
785
786SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
787{
788 TRACE("%p, 0x%x", port, buffers);
789
790 CHECK_OPEN_PORT();
791
792 if (buffers > SP_BUF_BOTH)
793 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
794
795 const char *buffer_names[] = {"no", "input", "output", "both"};
796
797 DEBUG_FMT("Flushing %s buffers on port %s",
798 buffer_names[buffers], port->name);
799
800#ifdef _WIN32
801 DWORD flags = 0;
802 if (buffers & SP_BUF_INPUT)
803 flags |= PURGE_RXCLEAR;
804 if (buffers & SP_BUF_OUTPUT)
805 flags |= PURGE_TXCLEAR;
806
807 /* Returns non-zero upon success, 0 upon failure. */
808 if (PurgeComm(port->hdl, flags) == 0)
809 RETURN_FAIL("PurgeComm() failed");
810
811 if (buffers & SP_BUF_INPUT)
812 TRY(restart_wait(port));
813#else
814 int flags = 0;
815 if (buffers == SP_BUF_BOTH)
816 flags = TCIOFLUSH;
817 else if (buffers == SP_BUF_INPUT)
818 flags = TCIFLUSH;
819 else if (buffers == SP_BUF_OUTPUT)
820 flags = TCOFLUSH;
821
822 /* Returns 0 upon success, -1 upon failure. */
823 if (tcflush(port->fd, flags) < 0)
824 RETURN_FAIL("tcflush() failed");
825#endif
826 RETURN_OK();
827}
828
829SP_API enum sp_return sp_drain(struct sp_port *port)
830{
831 TRACE("%p", port);
832
833 CHECK_OPEN_PORT();
834
835 DEBUG_FMT("Draining port %s", port->name);
836
837#ifdef _WIN32
838 /* Returns non-zero upon success, 0 upon failure. */
839 if (FlushFileBuffers(port->hdl) == 0)
840 RETURN_FAIL("FlushFileBuffers() failed");
841 RETURN_OK();
842#else
843 int result;
844 while (1) {
845#if defined(__ANDROID__) && (__ANDROID_API__ < 21)
846 /* Android only has tcdrain from platform 21 onwards.
847 * On previous API versions, use the ioctl directly. */
848 int arg = 1;
849 result = ioctl(port->fd, TCSBRK, &arg);
850#else
851 result = tcdrain(port->fd);
852#endif
853 if (result < 0) {
854 if (errno == EINTR) {
855 DEBUG("tcdrain() was interrupted");
856 continue;
857 } else {
858 RETURN_FAIL("tcdrain() failed");
859 }
860 } else {
861 RETURN_OK();
862 }
863 }
864#endif
865}
866
867#ifdef _WIN32
868static enum sp_return await_write_completion(struct sp_port *port)
869{
870 TRACE("%p", port);
871 DWORD bytes_written;
872 BOOL result;
873
874 /* Wait for previous non-blocking write to complete, if any. */
875 if (port->writing) {
876 DEBUG("Waiting for previous write to complete");
877 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
878 port->writing = 0;
879 if (!result)
880 RETURN_FAIL("Previous write failed to complete");
881 DEBUG("Previous write completed");
882 }
883
884 RETURN_OK();
885}
886#endif
887
888SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
889 size_t count, unsigned int timeout_ms)
890{
891 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
892
893 CHECK_OPEN_PORT();
894
895 if (!buf)
896 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
897
898 if (timeout_ms)
899 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
900 count, port->name, timeout_ms);
901 else
902 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
903 count, port->name);
904
905 if (count == 0)
906 RETURN_INT(0);
907
908#ifdef _WIN32
909 DWORD bytes_written = 0;
910
911 TRY(await_write_completion(port));
912
913 /* Set timeout. */
914 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
915 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
916 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
917 RETURN_FAIL("SetCommTimeouts() failed");
918 }
919
920 /* Reduce count if it exceeds the WriteFile limit. */
921 if (count > WRITEFILE_MAX_SIZE)
922 count = WRITEFILE_MAX_SIZE;
923
924 /* Start write. */
925 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
926 DEBUG("Write completed immediately");
927 RETURN_INT(count);
928 } else if (GetLastError() == ERROR_IO_PENDING) {
929 DEBUG("Waiting for write to complete");
930 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
931 if (GetLastError() == ERROR_SEM_TIMEOUT) {
932 DEBUG("Write timed out");
933 RETURN_INT(0);
934 } else {
935 RETURN_FAIL("GetOverlappedResult() failed");
936 }
937 }
938 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
939 RETURN_INT(bytes_written);
940 } else {
941 RETURN_FAIL("WriteFile() failed");
942 }
943#else
944 size_t bytes_written = 0;
945 unsigned char *ptr = (unsigned char *) buf;
946 struct timeout timeout;
947 int started = 0;
948 fd_set fds;
949 int result;
950
951 timeout_start(&timeout, timeout_ms);
952
953 FD_ZERO(&fds);
954 FD_SET(port->fd, &fds);
955
956 /* Loop until we have written the requested number of bytes. */
957 while (bytes_written < count) {
958 /*
959 * Check timeout only if we have run select() at least once,
960 * to avoid any issues if a short timeout is reached before
961 * select() is even run.
962 */
963 if (started && timeout_check(&timeout))
964 break;
965
966 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
967 started = 1;
968 if (result < 0) {
969 if (errno == EINTR) {
970 DEBUG("select() call was interrupted, repeating");
971 continue;
972 } else {
973 RETURN_FAIL("select() failed");
974 }
975 } else if (result == 0) {
976 /* Timeout has expired. */
977 break;
978 }
979
980 /* Do write. */
981 result = write(port->fd, ptr, count - bytes_written);
982
983 if (result < 0) {
984 if (errno == EAGAIN)
985 /* This shouldn't happen because we did a select() first, but handle anyway. */
986 continue;
987 else
988 /* This is an actual failure. */
989 RETURN_FAIL("write() failed");
990 }
991
992 bytes_written += result;
993 ptr += result;
994 }
995
996 if (bytes_written < count)
997 DEBUG("Write timed out");
998
999 RETURN_INT(bytes_written);
1000#endif
1001}
1002
1003SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
1004 const void *buf, size_t count)
1005{
1006 TRACE("%p, %p, %d", port, buf, count);
1007
1008 CHECK_OPEN_PORT();
1009
1010 if (!buf)
1011 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1012
1013 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
1014
1015 if (count == 0)
1016 RETURN_INT(0);
1017
1018#ifdef _WIN32
1019 DWORD buf_bytes;
1020
1021 /* Check whether previous write is complete. */
1022 if (port->writing) {
1023 if (HasOverlappedIoCompleted(&port->write_ovl)) {
1024 DEBUG("Previous write completed");
1025 port->writing = 0;
1026 } else {
1027 DEBUG("Previous write not complete");
1028 /* Can't take a new write until the previous one finishes. */
1029 RETURN_INT(0);
1030 }
1031 }
1032
1033 /* Set timeout. */
1034 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
1035 port->timeouts.WriteTotalTimeoutConstant = 0;
1036 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1037 RETURN_FAIL("SetCommTimeouts() failed");
1038 }
1039
1040 /* Reduce count if it exceeds the WriteFile limit. */
1041 if (count > WRITEFILE_MAX_SIZE)
1042 count = WRITEFILE_MAX_SIZE;
1043
1044 /* Copy data to our write buffer. */
1045 buf_bytes = min(port->write_buf_size, count);
1046 memcpy(port->write_buf, buf, buf_bytes);
1047
1048 /* Start asynchronous write. */
1049 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
1050 if (GetLastError() == ERROR_IO_PENDING) {
1051 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
1052 DEBUG("Asynchronous write completed immediately");
1053 else
1054 DEBUG("Asynchronous write running");
1055 } else {
1056 /* Actual failure of some kind. */
1057 RETURN_FAIL("WriteFile() failed");
1058 }
1059 }
1060
1061 DEBUG("All bytes written immediately");
1062
1063 RETURN_INT(buf_bytes);
1064#else
1065 /* Returns the number of bytes written, or -1 upon failure. */
1066 ssize_t written = write(port->fd, buf, count);
1067
1068 if (written < 0) {
1069 if (errno == EAGAIN)
1070 // Buffer is full, no bytes written.
1071 RETURN_INT(0);
1072 else
1073 RETURN_FAIL("write() failed");
1074 } else {
1075 RETURN_INT(written);
1076 }
1077#endif
1078}
1079
1080#ifdef _WIN32
1081/* Restart wait operation if buffer was emptied. */
1082static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1083{
1084 DWORD errors;
1085 COMSTAT comstat;
1086
1087 if (bytes_read == 0)
1088 RETURN_OK();
1089
1090 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1091 RETURN_FAIL("ClearCommError() failed");
1092
1093 if (comstat.cbInQue == 0)
1094 TRY(restart_wait(port));
1095
1096 RETURN_OK();
1097}
1098#endif
1099
1100SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1101 size_t count, unsigned int timeout_ms)
1102{
1103 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1104
1105 CHECK_OPEN_PORT();
1106
1107 if (!buf)
1108 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1109
1110 if (timeout_ms)
1111 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1112 count, port->name, timeout_ms);
1113 else
1114 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1115 count, port->name);
1116
1117 if (count == 0)
1118 RETURN_INT(0);
1119
1120#ifdef _WIN32
1121 DWORD bytes_read = 0;
1122
1123 /* Set timeout. */
1124 if (port->timeouts.ReadIntervalTimeout != 0 ||
1125 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1126 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1127 port->timeouts.ReadIntervalTimeout = 0;
1128 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1129 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1130 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1131 RETURN_FAIL("SetCommTimeouts() failed");
1132 }
1133
1134 /* Start read. */
1135 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1136 DEBUG("Read completed immediately");
1137 bytes_read = count;
1138 } else if (GetLastError() == ERROR_IO_PENDING) {
1139 DEBUG("Waiting for read to complete");
1140 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1141 RETURN_FAIL("GetOverlappedResult() failed");
1142 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1143 } else {
1144 RETURN_FAIL("ReadFile() failed");
1145 }
1146
1147 TRY(restart_wait_if_needed(port, bytes_read));
1148
1149 RETURN_INT(bytes_read);
1150
1151#else
1152 size_t bytes_read = 0;
1153 unsigned char *ptr = (unsigned char *) buf;
1154 struct timeout timeout;
1155 int started = 0;
1156 fd_set fds;
1157 int result;
1158
1159 timeout_start(&timeout, timeout_ms);
1160
1161 FD_ZERO(&fds);
1162 FD_SET(port->fd, &fds);
1163
1164 /* Loop until we have the requested number of bytes. */
1165 while (bytes_read < count) {
1166 /*
1167 * Check timeout only if we have run select() at least once,
1168 * to avoid any issues if a short timeout is reached before
1169 * select() is even run.
1170 */
1171 if (started && timeout_check(&timeout))
1172 /* Timeout has expired. */
1173 break;
1174
1175 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1176 started = 1;
1177 if (result < 0) {
1178 if (errno == EINTR) {
1179 DEBUG("select() call was interrupted, repeating");
1180 continue;
1181 } else {
1182 RETURN_FAIL("select() failed");
1183 }
1184 } else if (result == 0) {
1185 /* Timeout has expired. */
1186 break;
1187 }
1188
1189 /* Do read. */
1190 result = read(port->fd, ptr, count - bytes_read);
1191
1192 if (result < 0) {
1193 if (errno == EAGAIN)
1194 /*
1195 * This shouldn't happen because we did a
1196 * select() first, but handle anyway.
1197 */
1198 continue;
1199 else
1200 /* This is an actual failure. */
1201 RETURN_FAIL("read() failed");
1202 }
1203
1204 bytes_read += result;
1205 ptr += result;
1206 }
1207
1208 if (bytes_read < count)
1209 DEBUG("Read timed out");
1210
1211 RETURN_INT(bytes_read);
1212#endif
1213}
1214
1215SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1216 size_t count, unsigned int timeout_ms)
1217{
1218 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1219
1220 CHECK_OPEN_PORT();
1221
1222 if (!buf)
1223 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1224
1225 if (count == 0)
1226 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1227
1228 if (timeout_ms)
1229 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1230 count, port->name, timeout_ms);
1231 else
1232 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1233 count, port->name);
1234
1235#ifdef _WIN32
1236 DWORD bytes_read = 0;
1237
1238 /* If timeout_ms == 0, set maximum timeout. */
1239 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1240
1241 /* Set timeout. */
1242 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1243 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1244 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1245 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1246 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1247 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1248 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1249 RETURN_FAIL("SetCommTimeouts() failed");
1250 }
1251
1252 /* Loop until we have at least one byte, or timeout is reached. */
1253 while (bytes_read == 0) {
1254 /* Start read. */
1255 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
1256 DEBUG("Read completed immediately");
1257 } else if (GetLastError() == ERROR_IO_PENDING) {
1258 DEBUG("Waiting for read to complete");
1259 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1260 RETURN_FAIL("GetOverlappedResult() failed");
1261 if (bytes_read > 0) {
1262 DEBUG("Read completed");
1263 } else if (timeout_ms > 0) {
1264 DEBUG("Read timed out");
1265 break;
1266 } else {
1267 DEBUG("Restarting read");
1268 }
1269 } else {
1270 RETURN_FAIL("ReadFile() failed");
1271 }
1272 }
1273
1274 TRY(restart_wait_if_needed(port, bytes_read));
1275
1276 RETURN_INT(bytes_read);
1277
1278#else
1279 size_t bytes_read = 0;
1280 struct timeout timeout;
1281 int started = 0;
1282 fd_set fds;
1283 int result;
1284
1285 timeout_start(&timeout, timeout_ms);
1286
1287 FD_ZERO(&fds);
1288 FD_SET(port->fd, &fds);
1289
1290 /* Loop until we have at least one byte, or timeout is reached. */
1291 while (bytes_read == 0) {
1292 /*
1293 * Check timeout only if we have run select() at least once,
1294 * to avoid any issues if a short timeout is reached before
1295 * select() is even run.
1296 */
1297 if (started && timeout_check(&timeout))
1298 /* Timeout has expired. */
1299 break;
1300
1301 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
1302 started = 1;
1303 if (result < 0) {
1304 if (errno == EINTR) {
1305 DEBUG("select() call was interrupted, repeating");
1306 continue;
1307 } else {
1308 RETURN_FAIL("select() failed");
1309 }
1310 } else if (result == 0) {
1311 /* Timeout has expired. */
1312 break;
1313 }
1314
1315 /* Do read. */
1316 result = read(port->fd, buf, count);
1317
1318 if (result < 0) {
1319 if (errno == EAGAIN)
1320 /* This shouldn't happen because we did a select() first, but handle anyway. */
1321 continue;
1322 else
1323 /* This is an actual failure. */
1324 RETURN_FAIL("read() failed");
1325 }
1326
1327 bytes_read = result;
1328 }
1329
1330 if (bytes_read == 0)
1331 DEBUG("Read timed out");
1332
1333 RETURN_INT(bytes_read);
1334#endif
1335}
1336
1337SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1338 size_t count)
1339{
1340 TRACE("%p, %p, %d", port, buf, count);
1341
1342 CHECK_OPEN_PORT();
1343
1344 if (!buf)
1345 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1346
1347 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1348
1349#ifdef _WIN32
1350 DWORD bytes_read;
1351
1352 /* Set timeout. */
1353 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1354 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1355 port->timeouts.ReadTotalTimeoutConstant != 0) {
1356 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1357 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1358 port->timeouts.ReadTotalTimeoutConstant = 0;
1359 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1360 RETURN_FAIL("SetCommTimeouts() failed");
1361 }
1362
1363 /* Do read. */
1364 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1365 if (GetLastError() != ERROR_IO_PENDING)
1366 RETURN_FAIL("ReadFile() failed");
1367
1368 /* Get number of bytes read. */
1369 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1370 RETURN_FAIL("GetOverlappedResult() failed");
1371
1372 TRY(restart_wait_if_needed(port, bytes_read));
1373
1374 RETURN_INT(bytes_read);
1375#else
1376 ssize_t bytes_read;
1377
1378 /* Returns the number of bytes read, or -1 upon failure. */
1379 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1380 if (errno == EAGAIN)
1381 /* No bytes available. */
1382 bytes_read = 0;
1383 else
1384 /* This is an actual failure. */
1385 RETURN_FAIL("read() failed");
1386 }
1387 RETURN_INT(bytes_read);
1388#endif
1389}
1390
1391SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1392{
1393 TRACE("%p", port);
1394
1395 CHECK_OPEN_PORT();
1396
1397 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1398
1399#ifdef _WIN32
1400 DWORD errors;
1401 COMSTAT comstat;
1402
1403 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1404 RETURN_FAIL("ClearCommError() failed");
1405 RETURN_INT(comstat.cbInQue);
1406#else
1407 int bytes_waiting;
1408 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1409 RETURN_FAIL("TIOCINQ ioctl failed");
1410 RETURN_INT(bytes_waiting);
1411#endif
1412}
1413
1414SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1415{
1416 TRACE("%p", port);
1417
1418 CHECK_OPEN_PORT();
1419
1420 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1421
1422#ifdef _WIN32
1423 DWORD errors;
1424 COMSTAT comstat;
1425
1426 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1427 RETURN_FAIL("ClearCommError() failed");
1428 RETURN_INT(comstat.cbOutQue);
1429#else
1430 int bytes_waiting;
1431 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1432 RETURN_FAIL("TIOCOUTQ ioctl failed");
1433 RETURN_INT(bytes_waiting);
1434#endif
1435}
1436
1437SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1438{
1439 struct sp_event_set *result;
1440
1441 TRACE("%p", result_ptr);
1442
1443 if (!result_ptr)
1444 RETURN_ERROR(SP_ERR_ARG, "Null result");
1445
1446 *result_ptr = NULL;
1447
1448 if (!(result = malloc(sizeof(struct sp_event_set))))
1449 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1450
1451 memset(result, 0, sizeof(struct sp_event_set));
1452
1453 *result_ptr = result;
1454
1455 RETURN_OK();
1456}
1457
1458static enum sp_return add_handle(struct sp_event_set *event_set,
1459 event_handle handle, enum sp_event mask)
1460{
1461 void *new_handles;
1462 enum sp_event *new_masks;
1463
1464 TRACE("%p, %d, %d", event_set, handle, mask);
1465
1466 if (!(new_handles = realloc(event_set->handles,
1467 sizeof(event_handle) * (event_set->count + 1))))
1468 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1469
1470 event_set->handles = new_handles;
1471
1472 if (!(new_masks = realloc(event_set->masks,
1473 sizeof(enum sp_event) * (event_set->count + 1))))
1474 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1475
1476 event_set->masks = new_masks;
1477
1478 ((event_handle *) event_set->handles)[event_set->count] = handle;
1479 event_set->masks[event_set->count] = mask;
1480
1481 event_set->count++;
1482
1483 RETURN_OK();
1484}
1485
1486SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1487 const struct sp_port *port, enum sp_event mask)
1488{
1489 TRACE("%p, %p, %d", event_set, port, mask);
1490
1491 if (!event_set)
1492 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1493
1494 if (!port)
1495 RETURN_ERROR(SP_ERR_ARG, "Null port");
1496
1497 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1498 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1499
1500 if (!mask)
1501 RETURN_OK();
1502
1503#ifdef _WIN32
1504 enum sp_event handle_mask;
1505 if ((handle_mask = mask & SP_EVENT_TX_READY))
1506 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1507 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1508 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1509#else
1510 TRY(add_handle(event_set, port->fd, mask));
1511#endif
1512
1513 RETURN_OK();
1514}
1515
1516SP_API void sp_free_event_set(struct sp_event_set *event_set)
1517{
1518 TRACE("%p", event_set);
1519
1520 if (!event_set) {
1521 DEBUG("Null event set");
1522 RETURN();
1523 }
1524
1525 DEBUG("Freeing event set");
1526
1527 if (event_set->handles)
1528 free(event_set->handles);
1529 if (event_set->masks)
1530 free(event_set->masks);
1531
1532 free(event_set);
1533
1534 RETURN();
1535}
1536
1537SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1538 unsigned int timeout_ms)
1539{
1540 TRACE("%p, %d", event_set, timeout_ms);
1541
1542 if (!event_set)
1543 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1544
1545#ifdef _WIN32
1546 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1547 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1548 RETURN_FAIL("WaitForMultipleObjects() failed");
1549
1550 RETURN_OK();
1551#else
1552 struct timeout timeout;
1553 int started = 0, result;
1554 struct pollfd *pollfds;
1555 unsigned int i;
1556
1557 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1558 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1559
1560 for (i = 0; i < event_set->count; i++) {
1561 pollfds[i].fd = ((int *)event_set->handles)[i];
1562 pollfds[i].events = 0;
1563 pollfds[i].revents = 0;
1564 if (event_set->masks[i] & SP_EVENT_RX_READY)
1565 pollfds[i].events |= POLLIN;
1566 if (event_set->masks[i] & SP_EVENT_TX_READY)
1567 pollfds[i].events |= POLLOUT;
1568 if (event_set->masks[i] & SP_EVENT_ERROR)
1569 pollfds[i].events |= POLLERR;
1570 }
1571
1572 timeout_start(&timeout, timeout_ms);
1573
1574 /* Loop until an event occurs. */
1575 while (1) {
1576 /*
1577 * Check timeout only if we have run poll() at least once,
1578 * to avoid any issues if a short timeout is reached before
1579 * poll() is even run.
1580 */
1581 if (started && timeout_check(&timeout)) {
1582 DEBUG("Wait timed out");
1583 break;
1584 }
1585
1586 result = poll(pollfds, event_set->count, timeout_remaining_ms(&timeout));
1587 started = 1;
1588
1589 if (result < 0) {
1590 if (errno == EINTR) {
1591 DEBUG("poll() call was interrupted, repeating");
1592 continue;
1593 } else {
1594 free(pollfds);
1595 RETURN_FAIL("poll() failed");
1596 }
1597 } else if (result == 0) {
1598 DEBUG("poll() timed out");
1599 if (!timeout.overflow)
1600 break;
1601 } else {
1602 DEBUG("poll() completed");
1603 break;
1604 }
1605 }
1606
1607 free(pollfds);
1608 RETURN_OK();
1609#endif
1610}
1611
1612#ifdef USE_TERMIOS_SPEED
1613static enum sp_return get_baudrate(int fd, int *baudrate)
1614{
1615 void *data;
1616
1617 TRACE("%d, %p", fd, baudrate);
1618
1619 DEBUG("Getting baud rate");
1620
1621 if (!(data = malloc(get_termios_size())))
1622 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1623
1624 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1625 free(data);
1626 RETURN_FAIL("Getting termios failed");
1627 }
1628
1629 *baudrate = get_termios_speed(data);
1630
1631 free(data);
1632
1633 RETURN_OK();
1634}
1635
1636static enum sp_return set_baudrate(int fd, int baudrate)
1637{
1638 void *data;
1639
1640 TRACE("%d, %d", fd, baudrate);
1641
1642 DEBUG("Getting baud rate");
1643
1644 if (!(data = malloc(get_termios_size())))
1645 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1646
1647 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1648 free(data);
1649 RETURN_FAIL("Getting termios failed");
1650 }
1651
1652 DEBUG("Setting baud rate");
1653
1654 set_termios_speed(data, baudrate);
1655
1656 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1657 free(data);
1658 RETURN_FAIL("Setting termios failed");
1659 }
1660
1661 free(data);
1662
1663 RETURN_OK();
1664}
1665#endif /* USE_TERMIOS_SPEED */
1666
1667#ifdef USE_TERMIOX
1668static enum sp_return get_flow(int fd, struct port_data *data)
1669{
1670 void *termx;
1671
1672 TRACE("%d, %p", fd, data);
1673
1674 DEBUG("Getting advanced flow control");
1675
1676 if (!(termx = malloc(get_termiox_size())))
1677 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1678
1679 if (ioctl(fd, TCGETX, termx) < 0) {
1680 free(termx);
1681 RETURN_FAIL("Getting termiox failed");
1682 }
1683
1684 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1685 &data->dtr_flow, &data->dsr_flow);
1686
1687 free(termx);
1688
1689 RETURN_OK();
1690}
1691
1692static enum sp_return set_flow(int fd, struct port_data *data)
1693{
1694 void *termx;
1695
1696 TRACE("%d, %p", fd, data);
1697
1698 DEBUG("Getting advanced flow control");
1699
1700 if (!(termx = malloc(get_termiox_size())))
1701 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1702
1703 if (ioctl(fd, TCGETX, termx) < 0) {
1704 free(termx);
1705 RETURN_FAIL("Getting termiox failed");
1706 }
1707
1708 DEBUG("Setting advanced flow control");
1709
1710 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1711 data->dtr_flow, data->dsr_flow);
1712
1713 if (ioctl(fd, TCSETX, termx) < 0) {
1714 free(termx);
1715 RETURN_FAIL("Setting termiox failed");
1716 }
1717
1718 free(termx);
1719
1720 RETURN_OK();
1721}
1722#endif /* USE_TERMIOX */
1723
1724static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1725 struct sp_port_config *config)
1726{
1727 unsigned int i;
1728
1729 TRACE("%p, %p, %p", port, data, config);
1730
1731 DEBUG_FMT("Getting configuration for port %s", port->name);
1732
1733#ifdef _WIN32
1734 if (!GetCommState(port->hdl, &data->dcb))
1735 RETURN_FAIL("GetCommState() failed");
1736
1737 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1738 if (data->dcb.BaudRate == std_baudrates[i].index) {
1739 config->baudrate = std_baudrates[i].value;
1740 break;
1741 }
1742 }
1743
1744 if (i == NUM_STD_BAUDRATES)
1745 /* BaudRate field can be either an index or a custom baud rate. */
1746 config->baudrate = data->dcb.BaudRate;
1747
1748 config->bits = data->dcb.ByteSize;
1749
1750 if (data->dcb.fParity)
1751 switch (data->dcb.Parity) {
1752 case NOPARITY:
1753 config->parity = SP_PARITY_NONE;
1754 break;
1755 case ODDPARITY:
1756 config->parity = SP_PARITY_ODD;
1757 break;
1758 case EVENPARITY:
1759 config->parity = SP_PARITY_EVEN;
1760 break;
1761 case MARKPARITY:
1762 config->parity = SP_PARITY_MARK;
1763 break;
1764 case SPACEPARITY:
1765 config->parity = SP_PARITY_SPACE;
1766 break;
1767 default:
1768 config->parity = -1;
1769 }
1770 else
1771 config->parity = SP_PARITY_NONE;
1772
1773 switch (data->dcb.StopBits) {
1774 case ONESTOPBIT:
1775 config->stopbits = 1;
1776 break;
1777 case TWOSTOPBITS:
1778 config->stopbits = 2;
1779 break;
1780 default:
1781 config->stopbits = -1;
1782 }
1783
1784 switch (data->dcb.fRtsControl) {
1785 case RTS_CONTROL_DISABLE:
1786 config->rts = SP_RTS_OFF;
1787 break;
1788 case RTS_CONTROL_ENABLE:
1789 config->rts = SP_RTS_ON;
1790 break;
1791 case RTS_CONTROL_HANDSHAKE:
1792 config->rts = SP_RTS_FLOW_CONTROL;
1793 break;
1794 default:
1795 config->rts = -1;
1796 }
1797
1798 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1799
1800 switch (data->dcb.fDtrControl) {
1801 case DTR_CONTROL_DISABLE:
1802 config->dtr = SP_DTR_OFF;
1803 break;
1804 case DTR_CONTROL_ENABLE:
1805 config->dtr = SP_DTR_ON;
1806 break;
1807 case DTR_CONTROL_HANDSHAKE:
1808 config->dtr = SP_DTR_FLOW_CONTROL;
1809 break;
1810 default:
1811 config->dtr = -1;
1812 }
1813
1814 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1815
1816 if (data->dcb.fInX) {
1817 if (data->dcb.fOutX)
1818 config->xon_xoff = SP_XONXOFF_INOUT;
1819 else
1820 config->xon_xoff = SP_XONXOFF_IN;
1821 } else {
1822 if (data->dcb.fOutX)
1823 config->xon_xoff = SP_XONXOFF_OUT;
1824 else
1825 config->xon_xoff = SP_XONXOFF_DISABLED;
1826 }
1827
1828#else // !_WIN32
1829
1830 if (tcgetattr(port->fd, &data->term) < 0)
1831 RETURN_FAIL("tcgetattr() failed");
1832
1833 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1834 RETURN_FAIL("TIOCMGET ioctl failed");
1835
1836#ifdef USE_TERMIOX
1837 int ret = get_flow(port->fd, data);
1838
1839 if (ret == SP_ERR_FAIL && errno == EINVAL)
1840 data->termiox_supported = 0;
1841 else if (ret < 0)
1842 RETURN_CODEVAL(ret);
1843 else
1844 data->termiox_supported = 1;
1845#else
1846 data->termiox_supported = 0;
1847#endif
1848
1849 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1850 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1851 config->baudrate = std_baudrates[i].value;
1852 break;
1853 }
1854 }
1855
1856 if (i == NUM_STD_BAUDRATES) {
1857#ifdef __APPLE__
1858 config->baudrate = (int)data->term.c_ispeed;
1859#elif defined(USE_TERMIOS_SPEED)
1860 TRY(get_baudrate(port->fd, &config->baudrate));
1861#else
1862 config->baudrate = -1;
1863#endif
1864 }
1865
1866 switch (data->term.c_cflag & CSIZE) {
1867 case CS8:
1868 config->bits = 8;
1869 break;
1870 case CS7:
1871 config->bits = 7;
1872 break;
1873 case CS6:
1874 config->bits = 6;
1875 break;
1876 case CS5:
1877 config->bits = 5;
1878 break;
1879 default:
1880 config->bits = -1;
1881 }
1882
1883 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1884 config->parity = SP_PARITY_NONE;
1885 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1886 config->parity = -1;
1887#ifdef CMSPAR
1888 else if (data->term.c_cflag & CMSPAR)
1889 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1890#endif
1891 else
1892 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1893
1894 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1895
1896 if (data->term.c_cflag & CRTSCTS) {
1897 config->rts = SP_RTS_FLOW_CONTROL;
1898 config->cts = SP_CTS_FLOW_CONTROL;
1899 } else {
1900 if (data->termiox_supported && data->rts_flow)
1901 config->rts = SP_RTS_FLOW_CONTROL;
1902 else
1903 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1904
1905 config->cts = (data->termiox_supported && data->cts_flow) ?
1906 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1907 }
1908
1909 if (data->termiox_supported && data->dtr_flow)
1910 config->dtr = SP_DTR_FLOW_CONTROL;
1911 else
1912 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1913
1914 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1915 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1916
1917 if (data->term.c_iflag & IXOFF) {
1918 if (data->term.c_iflag & IXON)
1919 config->xon_xoff = SP_XONXOFF_INOUT;
1920 else
1921 config->xon_xoff = SP_XONXOFF_IN;
1922 } else {
1923 if (data->term.c_iflag & IXON)
1924 config->xon_xoff = SP_XONXOFF_OUT;
1925 else
1926 config->xon_xoff = SP_XONXOFF_DISABLED;
1927 }
1928#endif
1929
1930 RETURN_OK();
1931}
1932
1933static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1934 const struct sp_port_config *config)
1935{
1936 unsigned int i;
1937#ifdef __APPLE__
1938 BAUD_TYPE baud_nonstd;
1939
1940 baud_nonstd = B0;
1941#endif
1942#ifdef USE_TERMIOS_SPEED
1943 int baud_nonstd = 0;
1944#endif
1945
1946 TRACE("%p, %p, %p", port, data, config);
1947
1948 DEBUG_FMT("Setting configuration for port %s", port->name);
1949
1950#ifdef _WIN32
1951
1952 TRY(await_write_completion(port));
1953
1954 if (config->baudrate >= 0) {
1955 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1956 if (config->baudrate == std_baudrates[i].value) {
1957 data->dcb.BaudRate = std_baudrates[i].index;
1958 break;
1959 }
1960 }
1961
1962 if (i == NUM_STD_BAUDRATES)
1963 data->dcb.BaudRate = config->baudrate;
1964
1965 /* Allocate write buffer for 50ms of data at baud rate. */
1966 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1967 port->write_buf = realloc(port->write_buf,
1968 port->write_buf_size);
1969
1970 if (!port->write_buf)
1971 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
1972 }
1973
1974 if (config->bits >= 0)
1975 data->dcb.ByteSize = config->bits;
1976
1977 if (config->parity >= 0) {
1978 switch (config->parity) {
1979 case SP_PARITY_NONE:
1980 data->dcb.Parity = NOPARITY;
1981 break;
1982 case SP_PARITY_ODD:
1983 data->dcb.Parity = ODDPARITY;
1984 break;
1985 case SP_PARITY_EVEN:
1986 data->dcb.Parity = EVENPARITY;
1987 break;
1988 case SP_PARITY_MARK:
1989 data->dcb.Parity = MARKPARITY;
1990 break;
1991 case SP_PARITY_SPACE:
1992 data->dcb.Parity = SPACEPARITY;
1993 break;
1994 default:
1995 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1996 }
1997 }
1998
1999 if (config->stopbits >= 0) {
2000 switch (config->stopbits) {
2001 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
2002 case 1:
2003 data->dcb.StopBits = ONESTOPBIT;
2004 break;
2005 case 2:
2006 data->dcb.StopBits = TWOSTOPBITS;
2007 break;
2008 default:
2009 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
2010 }
2011 }
2012
2013 if (config->rts >= 0) {
2014 switch (config->rts) {
2015 case SP_RTS_OFF:
2016 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
2017 break;
2018 case SP_RTS_ON:
2019 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
2020 break;
2021 case SP_RTS_FLOW_CONTROL:
2022 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
2023 break;
2024 default:
2025 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
2026 }
2027 }
2028
2029 if (config->cts >= 0) {
2030 switch (config->cts) {
2031 case SP_CTS_IGNORE:
2032 data->dcb.fOutxCtsFlow = FALSE;
2033 break;
2034 case SP_CTS_FLOW_CONTROL:
2035 data->dcb.fOutxCtsFlow = TRUE;
2036 break;
2037 default:
2038 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
2039 }
2040 }
2041
2042 if (config->dtr >= 0) {
2043 switch (config->dtr) {
2044 case SP_DTR_OFF:
2045 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
2046 break;
2047 case SP_DTR_ON:
2048 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
2049 break;
2050 case SP_DTR_FLOW_CONTROL:
2051 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
2052 break;
2053 default:
2054 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
2055 }
2056 }
2057
2058 if (config->dsr >= 0) {
2059 switch (config->dsr) {
2060 case SP_DSR_IGNORE:
2061 data->dcb.fOutxDsrFlow = FALSE;
2062 break;
2063 case SP_DSR_FLOW_CONTROL:
2064 data->dcb.fOutxDsrFlow = TRUE;
2065 break;
2066 default:
2067 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
2068 }
2069 }
2070
2071 if (config->xon_xoff >= 0) {
2072 switch (config->xon_xoff) {
2073 case SP_XONXOFF_DISABLED:
2074 data->dcb.fInX = FALSE;
2075 data->dcb.fOutX = FALSE;
2076 break;
2077 case SP_XONXOFF_IN:
2078 data->dcb.fInX = TRUE;
2079 data->dcb.fOutX = FALSE;
2080 break;
2081 case SP_XONXOFF_OUT:
2082 data->dcb.fInX = FALSE;
2083 data->dcb.fOutX = TRUE;
2084 break;
2085 case SP_XONXOFF_INOUT:
2086 data->dcb.fInX = TRUE;
2087 data->dcb.fOutX = TRUE;
2088 break;
2089 default:
2090 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2091 }
2092 }
2093
2094 if (!SetCommState(port->hdl, &data->dcb))
2095 RETURN_FAIL("SetCommState() failed");
2096
2097#else /* !_WIN32 */
2098
2099 int controlbits;
2100
2101 if (config->baudrate >= 0) {
2102 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2103 if (config->baudrate == std_baudrates[i].value) {
2104 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
2105 RETURN_FAIL("cfsetospeed() failed");
2106
2107 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
2108 RETURN_FAIL("cfsetispeed() failed");
2109 break;
2110 }
2111 }
2112
2113 /* Non-standard baud rate */
2114 if (i == NUM_STD_BAUDRATES) {
2115#ifdef __APPLE__
2116 /* Set "dummy" baud rate. */
2117 if (cfsetspeed(&data->term, B9600) < 0)
2118 RETURN_FAIL("cfsetspeed() failed");
2119 baud_nonstd = config->baudrate;
2120#elif defined(USE_TERMIOS_SPEED)
2121 baud_nonstd = 1;
2122#else
2123 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2124#endif
2125 }
2126 }
2127
2128 if (config->bits >= 0) {
2129 data->term.c_cflag &= ~CSIZE;
2130 switch (config->bits) {
2131 case 8:
2132 data->term.c_cflag |= CS8;
2133 break;
2134 case 7:
2135 data->term.c_cflag |= CS7;
2136 break;
2137 case 6:
2138 data->term.c_cflag |= CS6;
2139 break;
2140 case 5:
2141 data->term.c_cflag |= CS5;
2142 break;
2143 default:
2144 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2145 }
2146 }
2147
2148 if (config->parity >= 0) {
2149 data->term.c_iflag &= ~IGNPAR;
2150 data->term.c_cflag &= ~(PARENB | PARODD);
2151#ifdef CMSPAR
2152 data->term.c_cflag &= ~CMSPAR;
2153#endif
2154 switch (config->parity) {
2155 case SP_PARITY_NONE:
2156 data->term.c_iflag |= IGNPAR;
2157 break;
2158 case SP_PARITY_EVEN:
2159 data->term.c_cflag |= PARENB;
2160 break;
2161 case SP_PARITY_ODD:
2162 data->term.c_cflag |= PARENB | PARODD;
2163 break;
2164#ifdef CMSPAR
2165 case SP_PARITY_MARK:
2166 data->term.c_cflag |= PARENB | PARODD;
2167 data->term.c_cflag |= CMSPAR;
2168 break;
2169 case SP_PARITY_SPACE:
2170 data->term.c_cflag |= PARENB;
2171 data->term.c_cflag |= CMSPAR;
2172 break;
2173#else
2174 case SP_PARITY_MARK:
2175 case SP_PARITY_SPACE:
2176 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2177#endif
2178 default:
2179 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2180 }
2181 }
2182
2183 if (config->stopbits >= 0) {
2184 data->term.c_cflag &= ~CSTOPB;
2185 switch (config->stopbits) {
2186 case 1:
2187 data->term.c_cflag &= ~CSTOPB;
2188 break;
2189 case 2:
2190 data->term.c_cflag |= CSTOPB;
2191 break;
2192 default:
2193 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2194 }
2195 }
2196
2197 if (config->rts >= 0 || config->cts >= 0) {
2198 if (data->termiox_supported) {
2199 data->rts_flow = data->cts_flow = 0;
2200 switch (config->rts) {
2201 case SP_RTS_OFF:
2202 case SP_RTS_ON:
2203 controlbits = TIOCM_RTS;
2204 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2205 RETURN_FAIL("Setting RTS signal level failed");
2206 break;
2207 case SP_RTS_FLOW_CONTROL:
2208 data->rts_flow = 1;
2209 break;
2210 default:
2211 break;
2212 }
2213 if (config->cts == SP_CTS_FLOW_CONTROL)
2214 data->cts_flow = 1;
2215
2216 if (data->rts_flow && data->cts_flow)
2217 data->term.c_iflag |= CRTSCTS;
2218 else
2219 data->term.c_iflag &= ~CRTSCTS;
2220 } else {
2221 /* Asymmetric use of RTS/CTS not supported. */
2222 if (data->term.c_iflag & CRTSCTS) {
2223 /* Flow control can only be disabled for both RTS & CTS together. */
2224 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2225 if (config->cts != SP_CTS_IGNORE)
2226 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2227 }
2228 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2229 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2230 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2231 }
2232 } else {
2233 /* Flow control can only be enabled for both RTS & CTS together. */
2234 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2235 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2236 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2237 }
2238
2239 if (config->rts >= 0) {
2240 if (config->rts == SP_RTS_FLOW_CONTROL) {
2241 data->term.c_iflag |= CRTSCTS;
2242 } else {
2243 controlbits = TIOCM_RTS;
2244 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2245 &controlbits) < 0)
2246 RETURN_FAIL("Setting RTS signal level failed");
2247 }
2248 }
2249 }
2250 }
2251
2252 if (config->dtr >= 0 || config->dsr >= 0) {
2253 if (data->termiox_supported) {
2254 data->dtr_flow = data->dsr_flow = 0;
2255 switch (config->dtr) {
2256 case SP_DTR_OFF:
2257 case SP_DTR_ON:
2258 controlbits = TIOCM_DTR;
2259 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2260 RETURN_FAIL("Setting DTR signal level failed");
2261 break;
2262 case SP_DTR_FLOW_CONTROL:
2263 data->dtr_flow = 1;
2264 break;
2265 default:
2266 break;
2267 }
2268 if (config->dsr == SP_DSR_FLOW_CONTROL)
2269 data->dsr_flow = 1;
2270 } else {
2271 /* DTR/DSR flow control not supported. */
2272 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2273 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2274
2275 if (config->dtr >= 0) {
2276 controlbits = TIOCM_DTR;
2277 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2278 &controlbits) < 0)
2279 RETURN_FAIL("Setting DTR signal level failed");
2280 }
2281 }
2282 }
2283
2284 if (config->xon_xoff >= 0) {
2285 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2286 switch (config->xon_xoff) {
2287 case SP_XONXOFF_DISABLED:
2288 break;
2289 case SP_XONXOFF_IN:
2290 data->term.c_iflag |= IXOFF;
2291 break;
2292 case SP_XONXOFF_OUT:
2293 data->term.c_iflag |= IXON | IXANY;
2294 break;
2295 case SP_XONXOFF_INOUT:
2296 data->term.c_iflag |= IXON | IXOFF | IXANY;
2297 break;
2298 default:
2299 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2300 }
2301 }
2302
2303 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2304 RETURN_FAIL("tcsetattr() failed");
2305
2306#ifdef __APPLE__
2307 if (baud_nonstd != B0) {
2308 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2309 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2310 /*
2311 * Set baud rates in data->term to correct, but incompatible
2312 * with tcsetattr() value, same as delivered by tcgetattr().
2313 */
2314 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2315 RETURN_FAIL("cfsetspeed() failed");
2316 }
2317#elif defined(__linux__)
2318#ifdef USE_TERMIOS_SPEED
2319 if (baud_nonstd)
2320 TRY(set_baudrate(port->fd, config->baudrate));
2321#endif
2322#ifdef USE_TERMIOX
2323 if (data->termiox_supported)
2324 TRY(set_flow(port->fd, data));
2325#endif
2326#endif
2327
2328#endif /* !_WIN32 */
2329
2330 RETURN_OK();
2331}
2332
2333SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2334{
2335 struct sp_port_config *config;
2336
2337 TRACE("%p", config_ptr);
2338
2339 if (!config_ptr)
2340 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2341
2342 *config_ptr = NULL;
2343
2344 if (!(config = malloc(sizeof(struct sp_port_config))))
2345 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2346
2347 config->baudrate = -1;
2348 config->bits = -1;
2349 config->parity = -1;
2350 config->stopbits = -1;
2351 config->rts = -1;
2352 config->cts = -1;
2353 config->dtr = -1;
2354 config->dsr = -1;
2355
2356 *config_ptr = config;
2357
2358 RETURN_OK();
2359}
2360
2361SP_API void sp_free_config(struct sp_port_config *config)
2362{
2363 TRACE("%p", config);
2364
2365 if (!config)
2366 DEBUG("Null config");
2367 else
2368 free(config);
2369
2370 RETURN();
2371}
2372
2373SP_API enum sp_return sp_get_config(struct sp_port *port,
2374 struct sp_port_config *config)
2375{
2376 struct port_data data;
2377
2378 TRACE("%p, %p", port, config);
2379
2380 CHECK_OPEN_PORT();
2381
2382 if (!config)
2383 RETURN_ERROR(SP_ERR_ARG, "Null config");
2384
2385 TRY(get_config(port, &data, config));
2386
2387 RETURN_OK();
2388}
2389
2390SP_API enum sp_return sp_set_config(struct sp_port *port,
2391 const struct sp_port_config *config)
2392{
2393 struct port_data data;
2394 struct sp_port_config prev_config;
2395
2396 TRACE("%p, %p", port, config);
2397
2398 CHECK_OPEN_PORT();
2399
2400 if (!config)
2401 RETURN_ERROR(SP_ERR_ARG, "Null config");
2402
2403 TRY(get_config(port, &data, &prev_config));
2404 TRY(set_config(port, &data, config));
2405
2406 RETURN_OK();
2407}
2408
2409#define CREATE_ACCESSORS(x, type) \
2410SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2411 struct port_data data; \
2412 struct sp_port_config config; \
2413 TRACE("%p, %d", port, x); \
2414 CHECK_OPEN_PORT(); \
2415 TRY(get_config(port, &data, &config)); \
2416 config.x = x; \
2417 TRY(set_config(port, &data, &config)); \
2418 RETURN_OK(); \
2419} \
2420SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2421 type *x) { \
2422 TRACE("%p, %p", config, x); \
2423 if (!x) \
2424 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2425 if (!config) \
2426 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2427 *x = config->x; \
2428 RETURN_OK(); \
2429} \
2430SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2431 type x) { \
2432 TRACE("%p, %d", config, x); \
2433 if (!config) \
2434 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2435 config->x = x; \
2436 RETURN_OK(); \
2437}
2438
2439CREATE_ACCESSORS(baudrate, int)
2440CREATE_ACCESSORS(bits, int)
2441CREATE_ACCESSORS(parity, enum sp_parity)
2442CREATE_ACCESSORS(stopbits, int)
2443CREATE_ACCESSORS(rts, enum sp_rts)
2444CREATE_ACCESSORS(cts, enum sp_cts)
2445CREATE_ACCESSORS(dtr, enum sp_dtr)
2446CREATE_ACCESSORS(dsr, enum sp_dsr)
2447CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2448
2449SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2450 enum sp_flowcontrol flowcontrol)
2451{
2452 if (!config)
2453 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2454
2455 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2456 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2457
2458 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2459 config->xon_xoff = SP_XONXOFF_INOUT;
2460 else
2461 config->xon_xoff = SP_XONXOFF_DISABLED;
2462
2463 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2464 config->rts = SP_RTS_FLOW_CONTROL;
2465 config->cts = SP_CTS_FLOW_CONTROL;
2466 } else {
2467 if (config->rts == SP_RTS_FLOW_CONTROL)
2468 config->rts = SP_RTS_ON;
2469 config->cts = SP_CTS_IGNORE;
2470 }
2471
2472 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2473 config->dtr = SP_DTR_FLOW_CONTROL;
2474 config->dsr = SP_DSR_FLOW_CONTROL;
2475 } else {
2476 if (config->dtr == SP_DTR_FLOW_CONTROL)
2477 config->dtr = SP_DTR_ON;
2478 config->dsr = SP_DSR_IGNORE;
2479 }
2480
2481 RETURN_OK();
2482}
2483
2484SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2485 enum sp_flowcontrol flowcontrol)
2486{
2487 struct port_data data;
2488 struct sp_port_config config;
2489
2490 TRACE("%p, %d", port, flowcontrol);
2491
2492 CHECK_OPEN_PORT();
2493
2494 TRY(get_config(port, &data, &config));
2495
2496 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2497
2498 TRY(set_config(port, &data, &config));
2499
2500 RETURN_OK();
2501}
2502
2503SP_API enum sp_return sp_get_signals(struct sp_port *port,
2504 enum sp_signal *signals)
2505{
2506 TRACE("%p, %p", port, signals);
2507
2508 CHECK_OPEN_PORT();
2509
2510 if (!signals)
2511 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2512
2513 DEBUG_FMT("Getting control signals for port %s", port->name);
2514
2515 *signals = 0;
2516#ifdef _WIN32
2517 DWORD bits;
2518 if (GetCommModemStatus(port->hdl, &bits) == 0)
2519 RETURN_FAIL("GetCommModemStatus() failed");
2520 if (bits & MS_CTS_ON)
2521 *signals |= SP_SIG_CTS;
2522 if (bits & MS_DSR_ON)
2523 *signals |= SP_SIG_DSR;
2524 if (bits & MS_RLSD_ON)
2525 *signals |= SP_SIG_DCD;
2526 if (bits & MS_RING_ON)
2527 *signals |= SP_SIG_RI;
2528#else
2529 int bits;
2530 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2531 RETURN_FAIL("TIOCMGET ioctl failed");
2532 if (bits & TIOCM_CTS)
2533 *signals |= SP_SIG_CTS;
2534 if (bits & TIOCM_DSR)
2535 *signals |= SP_SIG_DSR;
2536 if (bits & TIOCM_CAR)
2537 *signals |= SP_SIG_DCD;
2538 if (bits & TIOCM_RNG)
2539 *signals |= SP_SIG_RI;
2540#endif
2541 RETURN_OK();
2542}
2543
2544SP_API enum sp_return sp_start_break(struct sp_port *port)
2545{
2546 TRACE("%p", port);
2547
2548 CHECK_OPEN_PORT();
2549#ifdef _WIN32
2550 if (SetCommBreak(port->hdl) == 0)
2551 RETURN_FAIL("SetCommBreak() failed");
2552#else
2553 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2554 RETURN_FAIL("TIOCSBRK ioctl failed");
2555#endif
2556
2557 RETURN_OK();
2558}
2559
2560SP_API enum sp_return sp_end_break(struct sp_port *port)
2561{
2562 TRACE("%p", port);
2563
2564 CHECK_OPEN_PORT();
2565#ifdef _WIN32
2566 if (ClearCommBreak(port->hdl) == 0)
2567 RETURN_FAIL("ClearCommBreak() failed");
2568#else
2569 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2570 RETURN_FAIL("TIOCCBRK ioctl failed");
2571#endif
2572
2573 RETURN_OK();
2574}
2575
2576SP_API int sp_last_error_code(void)
2577{
2578 TRACE_VOID();
2579#ifdef _WIN32
2580 RETURN_INT(GetLastError());
2581#else
2582 RETURN_INT(errno);
2583#endif
2584}
2585
2586SP_API char *sp_last_error_message(void)
2587{
2588 TRACE_VOID();
2589
2590#ifdef _WIN32
2591 TCHAR *message;
2592 DWORD error = GetLastError();
2593
2594 DWORD length = FormatMessage(
2595 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2596 FORMAT_MESSAGE_FROM_SYSTEM |
2597 FORMAT_MESSAGE_IGNORE_INSERTS,
2598 NULL,
2599 error,
2600 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2601 (LPTSTR) &message,
2602 0, NULL );
2603
2604 if (length >= 2 && message[length - 2] == '\r')
2605 message[length - 2] = '\0';
2606
2607 RETURN_STRING(message);
2608#else
2609 RETURN_STRING(strerror(errno));
2610#endif
2611}
2612
2613SP_API void sp_free_error_message(char *message)
2614{
2615 TRACE("%s", message);
2616
2617#ifdef _WIN32
2618 LocalFree(message);
2619#else
2620 (void)message;
2621#endif
2622
2623 RETURN();
2624}
2625
2626SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2627{
2628 TRACE("%p", handler);
2629
2630 sp_debug_handler = handler;
2631
2632 RETURN();
2633}
2634
2635SP_API void sp_default_debug_handler(const char *format, ...)
2636{
2637 va_list args;
2638 va_start(args, format);
2639 if (getenv("LIBSERIALPORT_DEBUG")) {
2640 fputs("sp: ", stderr);
2641 vfprintf(stderr, format, args);
2642 }
2643 va_end(args);
2644}
2645
2646SP_API int sp_get_major_package_version(void)
2647{
2648 return SP_PACKAGE_VERSION_MAJOR;
2649}
2650
2651SP_API int sp_get_minor_package_version(void)
2652{
2653 return SP_PACKAGE_VERSION_MINOR;
2654}
2655
2656SP_API int sp_get_micro_package_version(void)
2657{
2658 return SP_PACKAGE_VERSION_MICRO;
2659}
2660
2661SP_API const char *sp_get_package_version_string(void)
2662{
2663 return SP_PACKAGE_VERSION_STRING;
2664}
2665
2666SP_API int sp_get_current_lib_version(void)
2667{
2668 return SP_LIB_VERSION_CURRENT;
2669}
2670
2671SP_API int sp_get_revision_lib_version(void)
2672{
2673 return SP_LIB_VERSION_REVISION;
2674}
2675
2676SP_API int sp_get_age_lib_version(void)
2677{
2678 return SP_LIB_VERSION_AGE;
2679}
2680
2681SP_API const char *sp_get_lib_version_string(void)
2682{
2683 return SP_LIB_VERSION_STRING;
2684}
2685
2686/** @} */