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