]> sigrok.org Git - libserialport.git/blame - serialport.c
Move repetitive timeout code into helper functions.
[libserialport.git] / serialport.c
CommitLineData
74510d4b
ML
1/*
2 * This file is part of the libserialport project.
3 *
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
f77bb46d
ML
5 * Copyright (C) 2010-2015 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2013-2015 Martin Ling <martin-libserialport@earth.li>
31b3a8f5 7 * Copyright (C) 2013 Matthias Heidbrink <m-sigrok@heidbrink.biz>
a93fb468 8 * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
74510d4b
ML
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
1a584c45 24#include <config.h>
f6a1fb65 25#include "libserialport.h"
e33dcf90 26#include "libserialport_internal.h"
da2748bf 27
6c6aebe7 28static const struct std_baudrate std_baudrates[] = {
da2748bf
ML
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),
eac329d2 36 BAUD(115200), BAUD(128000), BAUD(256000),
da2748bf 37#else
eac329d2
UH
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),
da2748bf 42#if !defined(__APPLE__) && !defined(__OpenBSD__)
eac329d2 43 BAUD(460800),
da2748bf
ML
44#endif
45#endif
46};
47
6c6aebe7
UH
48#define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
49
863b35e6
ML
50void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
51
eb6ed20f
ML
52static enum sp_return get_config(struct sp_port *port, struct port_data *data,
53 struct sp_port_config *config);
e33dcf90 54
eb6ed20f
ML
55static enum sp_return set_config(struct sp_port *port, struct port_data *data,
56 const struct sp_port_config *config);
80186526 57
bd0fb609 58#ifndef _WIN32
9a7945af
ML
59
60/* Timing abstraction */
61
62struct time {
63 struct timeval tv;
64};
65
32dbe2d2
ML
66struct timeout {
67 unsigned int ms;
68 struct time start, delta, now, end;
69 struct timeval delta_tv;
70 bool overflow;
71};
72
9a7945af
ML
73#define TIME_ZERO {.tv = {0, 0}}
74#define TIME_MS(ms) {.tv = {ms / 1000, (ms % 1000) * 1000}}
75
32dbe2d2
ML
76const struct time max_delta = TIME_MS(INT_MAX);
77
9a7945af 78static void time_get(struct time *time)
573feabc 79{
f40ea9d4
ML
80#ifdef HAVE_CLOCK_GETTIME
81 struct timespec ts;
7fb9a7b0
ML
82 if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
83 clock_gettime(CLOCK_REALTIME, &ts);
9a7945af
ML
84 time->tv.tv_sec = ts.tv_sec;
85 time->tv.tv_usec = ts.tv_nsec / 1000;
192e7749
ML
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;
9a7945af
ML
91 time->tv.tv_sec = ns / 1000000000;
92 time->tv.tv_usec = (ns % 1000000000) / 1000;
f40ea9d4 93#else
9a7945af 94 gettimeofday(&time->tv, NULL);
f40ea9d4 95#endif
573feabc 96}
9a7945af
ML
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
32dbe2d2
ML
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
bd0fb609 178#endif
573feabc 179
970f279a 180SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
d54e9004
ML
181{
182 struct sp_port *port;
5a8810e2 183#ifndef NO_PORT_METADATA
a93fb468 184 enum sp_return ret;
5a8810e2 185#endif
5919c913 186 int len;
d54e9004 187
c33efc48
ML
188 TRACE("%s, %p", portname, port_ptr);
189
32b5ac05 190 if (!port_ptr)
c33efc48 191 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
32b5ac05 192
77f262c4
ML
193 *port_ptr = NULL;
194
d4babed2 195 if (!portname)
c33efc48 196 RETURN_ERROR(SP_ERR_ARG, "Null port name");
d4babed2 197
7890cef6 198 DEBUG_FMT("Building structure for port %s", portname);
ea667be7 199
95bad38c
ST
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
d54e9004 214 if (!(port = malloc(sizeof(struct sp_port))))
c33efc48 215 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
d54e9004 216
5919c913
ML
217 len = strlen(portname) + 1;
218
eac329d2 219 if (!(port->name = malloc(len))) {
d54e9004 220 free(port);
c33efc48 221 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
d54e9004
ML
222 }
223
224 memcpy(port->name, portname, len);
225
8f471c66 226#ifdef _WIN32
e31f2c6b 227 port->usb_path = NULL;
8f471c66 228 port->hdl = INVALID_HANDLE_VALUE;
39df7833
ML
229 port->write_buf = NULL;
230 port->write_buf_size = 0;
8f471c66
ML
231#else
232 port->fd = -1;
233#endif
234
e33dcf90
ML
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
e4ce975a 246#ifndef NO_PORT_METADATA
e33dcf90 247 if ((ret = get_port_details(port)) != SP_OK) {
a93fb468
AJ
248 sp_free_port(port);
249 return ret;
250 }
e4ce975a 251#endif
a93fb468 252
77f262c4
ML
253 *port_ptr = port;
254
c33efc48 255 RETURN_OK();
d54e9004
ML
256}
257
970f279a 258SP_API char *sp_get_port_name(const struct sp_port *port)
1c5aae9d
ML
259{
260 TRACE("%p", port);
261
262 if (!port)
263 return NULL;
264
9caa2e86 265 RETURN_STRING(port->name);
1c5aae9d
ML
266}
267
f1480939 268SP_API char *sp_get_port_description(const struct sp_port *port)
a93fb468
AJ
269{
270 TRACE("%p", port);
271
272 if (!port || !port->description)
273 return NULL;
274
9caa2e86 275 RETURN_STRING(port->description);
a93fb468
AJ
276}
277
ad036cc8 278SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
a93fb468
AJ
279{
280 TRACE("%p", port);
281
282 if (!port)
283 RETURN_ERROR(SP_ERR_ARG, "Null port");
284
9caa2e86 285 RETURN_INT(port->transport);
a93fb468
AJ
286}
287
970f279a
AJ
288SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
289 int *usb_bus,int *usb_address)
a93fb468
AJ
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");
65172bef
AJ
297 if (port->usb_bus < 0 || port->usb_address < 0)
298 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
a93fb468 299
dc422c04
UH
300 if (usb_bus)
301 *usb_bus = port->usb_bus;
302 if (usb_address)
303 *usb_address = port->usb_address;
a93fb468
AJ
304
305 RETURN_OK();
306}
307
970f279a
AJ
308SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
309 int *usb_vid, int *usb_pid)
a93fb468
AJ
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");
65172bef
AJ
317 if (port->usb_vid < 0 || port->usb_pid < 0)
318 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
a93fb468 319
dc422c04
UH
320 if (usb_vid)
321 *usb_vid = port->usb_vid;
322 if (usb_pid)
323 *usb_pid = port->usb_pid;
a93fb468
AJ
324
325 RETURN_OK();
326}
327
970f279a 328SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
a93fb468
AJ
329{
330 TRACE("%p", port);
331
332 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
333 return NULL;
334
9caa2e86 335 RETURN_STRING(port->usb_manufacturer);
a93fb468
AJ
336}
337
970f279a 338SP_API char *sp_get_port_usb_product(const struct sp_port *port)
a93fb468
AJ
339{
340 TRACE("%p", port);
341
342 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
343 return NULL;
344
9caa2e86 345 RETURN_STRING(port->usb_product);
a93fb468
AJ
346}
347
970f279a 348SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
a93fb468
AJ
349{
350 TRACE("%p", port);
351
352 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
353 return NULL;
354
9caa2e86 355 RETURN_STRING(port->usb_serial);
a93fb468
AJ
356}
357
970f279a 358SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
a93fb468
AJ
359{
360 TRACE("%p", port);
361
362 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
363 || !port->bluetooth_address)
364 return NULL;
365
9caa2e86 366 RETURN_STRING(port->bluetooth_address);
a93fb468
AJ
367}
368
970f279a
AJ
369SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
370 void *result_ptr)
3c126654 371{
00d8c56d 372 TRACE("%p, %p", port, result_ptr);
3c126654
ML
373
374 if (!port)
375 RETURN_ERROR(SP_ERR_ARG, "Null port");
5f64c285
UH
376 if (!result_ptr)
377 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
3c126654
ML
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
970f279a
AJ
390SP_API enum sp_return sp_copy_port(const struct sp_port *port,
391 struct sp_port **copy_ptr)
32b5ac05 392{
c33efc48
ML
393 TRACE("%p, %p", port, copy_ptr);
394
32b5ac05 395 if (!copy_ptr)
c33efc48 396 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
32b5ac05
ML
397
398 *copy_ptr = NULL;
399
c33efc48
ML
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");
32b5ac05 405
ea667be7
ML
406 DEBUG("Copying port structure");
407
9caa2e86 408 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
32b5ac05
ML
409}
410
970f279a 411SP_API void sp_free_port(struct sp_port *port)
e3b2f7a4 412{
c33efc48
ML
413 TRACE("%p", port);
414
00d8c56d 415 if (!port) {
c33efc48
ML
416 DEBUG("Null port");
417 RETURN();
418 }
e3b2f7a4 419
ea667be7
ML
420 DEBUG("Freeing port structure");
421
e3b2f7a4
ML
422 if (port->name)
423 free(port->name);
a93fb468
AJ
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);
39df7833
ML
437 if (port->write_buf)
438 free(port->write_buf);
a93fb468 439#endif
e3b2f7a4
ML
440
441 free(port);
c33efc48
ML
442
443 RETURN();
e3b2f7a4
ML
444}
445
970f279a
AJ
446SP_PRIV struct sp_port **list_append(struct sp_port **list,
447 const char *portname)
3b63f34d
ML
448{
449 void *tmp;
450 unsigned int count;
f92f1f0c 451
81243567
UH
452 for (count = 0; list[count]; count++)
453 ;
d54e9004 454 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
3b63f34d
ML
455 goto fail;
456 list = tmp;
77f262c4 457 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
3b63f34d 458 goto fail;
db2794ce 459 list[count + 1] = NULL;
3b63f34d 460 return list;
f92f1f0c 461
3b63f34d
ML
462fail:
463 sp_free_port_list(list);
464 return NULL;
465}
466
970f279a 467SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
3b63f34d 468{
23e7fa37 469#ifndef NO_ENUMERATION
d54e9004 470 struct sp_port **list;
48a4076f 471 int ret;
23e7fa37 472#endif
24c1a4bb 473
c33efc48
ML
474 TRACE("%p", list_ptr);
475
dec10e31
ML
476 if (!list_ptr)
477 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
478
63926415
UH
479 *list_ptr = NULL;
480
8d12e620
ML
481#ifdef NO_ENUMERATION
482 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
483#else
ea667be7
ML
484 DEBUG("Enumerating ports");
485
8d12e620 486 if (!(list = malloc(sizeof(struct sp_port *))))
c33efc48 487 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
24c1a4bb
ML
488
489 list[0] = NULL;
3b63f34d 490
48a4076f 491 ret = list_ports(&list);
77f262c4 492
8d12e620 493 if (ret == SP_OK) {
77f262c4 494 *list_ptr = list;
8d12e620
ML
495 } else {
496 sp_free_port_list(list);
77f262c4
ML
497 *list_ptr = NULL;
498 }
8d12e620
ML
499
500 RETURN_CODEVAL(ret);
501#endif
3b63f34d
ML
502}
503
970f279a 504SP_API void sp_free_port_list(struct sp_port **list)
3b63f34d
ML
505{
506 unsigned int i;
f92f1f0c 507
c33efc48
ML
508 TRACE("%p", list);
509
dec10e31
ML
510 if (!list) {
511 DEBUG("Null list");
512 RETURN();
513 }
514
ea667be7
ML
515 DEBUG("Freeing port list");
516
3b63f34d 517 for (i = 0; list[i]; i++)
e3b2f7a4 518 sp_free_port(list[i]);
3b63f34d 519 free(list);
c33efc48
ML
520
521 RETURN();
3b63f34d
ML
522}
523
c33efc48 524#define CHECK_PORT() do { \
dc422c04 525 if (!port) \
c33efc48 526 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
dc422c04 527 if (!port->name) \
dec10e31
ML
528 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
529} while (0)
530#ifdef _WIN32
531#define CHECK_PORT_HANDLE() do { \
c33efc48 532 if (port->hdl == INVALID_HANDLE_VALUE) \
8062087a 533 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
dec10e31 534} while (0)
74510d4b 535#else
dec10e31 536#define CHECK_PORT_HANDLE() do { \
c33efc48 537 if (port->fd < 0) \
8062087a 538 RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
dec10e31 539} while (0)
74510d4b 540#endif
dec10e31
ML
541#define CHECK_OPEN_PORT() do { \
542 CHECK_PORT(); \
543 CHECK_PORT_HANDLE(); \
544} while (0)
74510d4b 545
47fcf8ec
ML
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
970f279a 583SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
74510d4b 584{
bccc7c9f
ML
585 struct port_data data;
586 struct sp_port_config config;
587 enum sp_return ret;
588
00d8c56d 589 TRACE("%p, 0x%x", port, flags);
c33efc48 590
dec10e31
ML
591 CHECK_PORT();
592
276ef1b9 593 if (flags > SP_MODE_READ_WRITE)
dec10e31 594 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
74510d4b 595
7890cef6 596 DEBUG_FMT("Opening port %s", port->name);
ea667be7 597
74510d4b 598#ifdef _WIN32
537942c9 599 DWORD desired_access = 0, flags_and_attributes = 0, errors;
99945a1f 600 char *escaped_port_name;
537942c9 601 COMSTAT status;
99945a1f
ML
602
603 /* Prefix port name with '\\.\' to work with ports above COM9. */
e48f0ece 604 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
c33efc48 605 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
99945a1f
ML
606 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
607
74510d4b 608 /* Map 'flags' to the OS-specific settings. */
e3dcf906 609 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
a036341b
ML
610 if (flags & SP_MODE_READ)
611 desired_access |= GENERIC_READ;
612 if (flags & SP_MODE_WRITE)
74510d4b 613 desired_access |= GENERIC_WRITE;
74510d4b 614
99945a1f 615 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
74510d4b 616 OPEN_EXISTING, flags_and_attributes, 0);
99945a1f
ML
617
618 free(escaped_port_name);
619
74510d4b 620 if (port->hdl == INVALID_HANDLE_VALUE)
dc422c04 621 RETURN_FAIL("Port CreateFile() failed");
e3dcf906
ML
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;
a3cb91f5 629
e3dcf906 630 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
a3cb91f5
ML
631 sp_close(port);
632 RETURN_FAIL("SetCommTimeouts() failed");
633 }
e3dcf906
ML
634
635 /* Prepare OVERLAPPED structures. */
6f1186aa
ML
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) {
e3dcf906 652 sp_close(port);
6f1186aa 653 RETURN_FAIL("SetCommMask() failed");
e3dcf906 654 }
6f1186aa 655
e3dcf906 656 port->writing = FALSE;
47fcf8ec 657 port->wait_running = FALSE;
e3dcf906 658
47fcf8ec
ML
659 ret = restart_wait(port);
660
661 if (ret < 0) {
662 sp_close(port);
663 RETURN_CODEVAL(ret);
664 }
74510d4b 665#else
fa106ef1 666 int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
f92f1f0c 667
74510d4b 668 /* Map 'flags' to the OS-specific settings. */
276ef1b9 669 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
74510d4b 670 flags_local |= O_RDWR;
a036341b 671 else if (flags & SP_MODE_READ)
74510d4b 672 flags_local |= O_RDONLY;
a036341b
ML
673 else if (flags & SP_MODE_WRITE)
674 flags_local |= O_WRONLY;
74510d4b
ML
675
676 if ((port->fd = open(port->name, flags_local)) < 0)
c33efc48 677 RETURN_FAIL("open() failed");
bccc7c9f 678#endif
9cb98459 679
e33ab9aa
ML
680 ret = get_config(port, &data, &config);
681
eac329d2 682 if (ret < 0) {
e33ab9aa 683 sp_close(port);
c33efc48 684 RETURN_CODEVAL(ret);
e33ab9aa 685 }
9cb98459 686
bccc7c9f
ML
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;
34442106 693 data.dcb.fAbortOnError = FALSE;
bccc7c9f 694#else
b251be4b 695 /* Turn off all fancy termios tricks, give us a raw channel. */
c3e05092
UH
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
b251be4b 722#ifdef OFILL
9cb98459
ML
723 data.term.c_oflag &= ~OFILL;
724#endif
c3e05092 725 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
e3dcf906 726 data.term.c_cc[VMIN] = 0;
b251be4b 727 data.term.c_cc[VTIME] = 0;
9cb98459 728
b251be4b
ML
729 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
730 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
bccc7c9f 731#endif
9cb98459 732
537942c9 733#ifdef _WIN32
1a2a1544
UH
734 if (ClearCommError(port->hdl, &errors, &status) == 0)
735 RETURN_FAIL("ClearCommError() failed");
537942c9
ML
736#endif
737
e33ab9aa
ML
738 ret = set_config(port, &data, &config);
739
eac329d2 740 if (ret < 0) {
e33ab9aa 741 sp_close(port);
c33efc48 742 RETURN_CODEVAL(ret);
e33ab9aa 743 }
74510d4b 744
c33efc48 745 RETURN_OK();
74510d4b
ML
746}
747
970f279a 748SP_API enum sp_return sp_close(struct sp_port *port)
74510d4b 749{
c33efc48
ML
750 TRACE("%p", port);
751
dec10e31 752 CHECK_OPEN_PORT();
74510d4b 753
7890cef6 754 DEBUG_FMT("Closing port %s", port->name);
ea667be7 755
74510d4b
ML
756#ifdef _WIN32
757 /* Returns non-zero upon success, 0 upon failure. */
758 if (CloseHandle(port->hdl) == 0)
dc422c04 759 RETURN_FAIL("Port CloseHandle() failed");
8f471c66 760 port->hdl = INVALID_HANDLE_VALUE;
6f1186aa
ML
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
39df7833
ML
772 if (port->write_buf) {
773 free(port->write_buf);
774 port->write_buf = NULL;
775 }
74510d4b
ML
776#else
777 /* Returns 0 upon success, -1 upon failure. */
778 if (close(port->fd) == -1)
c33efc48 779 RETURN_FAIL("close() failed");
8f471c66 780 port->fd = -1;
74510d4b
ML
781#endif
782
c33efc48 783 RETURN_OK();
74510d4b
ML
784}
785
970f279a 786SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
74510d4b 787{
00d8c56d 788 TRACE("%p, 0x%x", port, buffers);
c33efc48 789
dec10e31
ML
790 CHECK_OPEN_PORT();
791
792 if (buffers > SP_BUF_BOTH)
793 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
74510d4b 794
0ba3e49b 795 const char *buffer_names[] = {"no", "input", "output", "both"};
ea667be7 796
7890cef6
ML
797 DEBUG_FMT("Flushing %s buffers on port %s",
798 buffer_names[buffers], port->name);
ea667be7 799
74510d4b 800#ifdef _WIN32
fd8fd11a
ML
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
74510d4b 807 /* Returns non-zero upon success, 0 upon failure. */
fd8fd11a 808 if (PurgeComm(port->hdl, flags) == 0)
c33efc48 809 RETURN_FAIL("PurgeComm() failed");
47fcf8ec
ML
810
811 if (buffers & SP_BUF_INPUT)
812 TRY(restart_wait(port));
74510d4b 813#else
fd8fd11a 814 int flags = 0;
ad749855 815 if (buffers == SP_BUF_BOTH)
fd8fd11a 816 flags = TCIOFLUSH;
ad749855 817 else if (buffers == SP_BUF_INPUT)
fd8fd11a 818 flags = TCIFLUSH;
ad749855 819 else if (buffers == SP_BUF_OUTPUT)
fd8fd11a
ML
820 flags = TCOFLUSH;
821
74510d4b 822 /* Returns 0 upon success, -1 upon failure. */
fd8fd11a 823 if (tcflush(port->fd, flags) < 0)
c33efc48 824 RETURN_FAIL("tcflush() failed");
74510d4b 825#endif
c33efc48 826 RETURN_OK();
74510d4b
ML
827}
828
970f279a 829SP_API enum sp_return sp_drain(struct sp_port *port)
69a3739c 830{
c33efc48
ML
831 TRACE("%p", port);
832
dec10e31 833 CHECK_OPEN_PORT();
69a3739c 834
7890cef6 835 DEBUG_FMT("Draining port %s", port->name);
ea667be7 836
69a3739c
ML
837#ifdef _WIN32
838 /* Returns non-zero upon success, 0 upon failure. */
839 if (FlushFileBuffers(port->hdl) == 0)
c33efc48 840 RETURN_FAIL("FlushFileBuffers() failed");
2c827b21 841 RETURN_OK();
69a3739c 842#else
2c827b21
ML
843 int result;
844 while (1) {
abd31fd9
ML
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. */
33fd8804
ML
848 int arg = 1;
849 result = ioctl(port->fd, TCSBRK, &arg);
850#else
2c827b21 851 result = tcdrain(port->fd);
33fd8804 852#endif
2c827b21
ML
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 }
69a3739c 864#endif
69a3739c
ML
865}
866
62ed9f80
ML
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
970f279a 888SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
1b91c6ea 889 size_t count, unsigned int timeout_ms)
e3dcf906 890{
1b91c6ea 891 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
e3dcf906
ML
892
893 CHECK_OPEN_PORT();
894
895 if (!buf)
896 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
897
1b91c6ea 898 if (timeout_ms)
7890cef6 899 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
1b91c6ea 900 count, port->name, timeout_ms);
e3dcf906 901 else
7890cef6
ML
902 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
903 count, port->name);
e3dcf906
ML
904
905 if (count == 0)
9caa2e86 906 RETURN_INT(0);
e3dcf906
ML
907
908#ifdef _WIN32
909 DWORD bytes_written = 0;
e3dcf906 910
62ed9f80 911 TRY(await_write_completion(port));
e3dcf906
ML
912
913 /* Set timeout. */
27a58c05
ML
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 }
e3dcf906 919
b457865b
ML
920 /* Reduce count if it exceeds the WriteFile limit. */
921 if (count > WRITEFILE_MAX_SIZE)
922 count = WRITEFILE_MAX_SIZE;
923
e3dcf906 924 /* Start write. */
bbe566fe 925 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
e3dcf906 926 DEBUG("Write completed immediately");
9caa2e86 927 RETURN_INT(count);
bbe566fe
ML
928 } else if (GetLastError() == ERROR_IO_PENDING) {
929 DEBUG("Waiting for write to complete");
aee7d691
UH
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 }
bbe566fe
ML
938 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
939 RETURN_INT(bytes_written);
940 } else {
941 RETURN_FAIL("WriteFile() failed");
e3dcf906
ML
942 }
943#else
944 size_t bytes_written = 0;
945 unsigned char *ptr = (unsigned char *) buf;
32dbe2d2 946 struct timeout timeout;
76222ee5 947 int started = 0;
e3dcf906
ML
948 fd_set fds;
949 int result;
950
32dbe2d2 951 timeout_start(&timeout, timeout_ms);
e3dcf906 952
772c5861
ML
953 FD_ZERO(&fds);
954 FD_SET(port->fd, &fds);
955
e3dcf906 956 /* Loop until we have written the requested number of bytes. */
dc422c04 957 while (bytes_written < count) {
76222ee5
ML
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 */
32dbe2d2
ML
963 if (started && timeout_check(&timeout))
964 break;
965
966 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
76222ee5 967 started = 1;
63a17c64
ML
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) {
c3cee38c
ML
976 /* Timeout has expired. */
977 break;
e3dcf906
ML
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
c3cee38c
ML
996 if (bytes_written < count)
997 DEBUG("Write timed out");
998
9caa2e86 999 RETURN_INT(bytes_written);
e3dcf906
ML
1000#endif
1001}
1002
970f279a
AJ
1003SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
1004 const void *buf, size_t count)
74510d4b 1005{
c33efc48
ML
1006 TRACE("%p, %p, %d", port, buf, count);
1007
dec10e31 1008 CHECK_OPEN_PORT();
74510d4b
ML
1009
1010 if (!buf)
c33efc48 1011 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
74510d4b 1012
7890cef6 1013 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
ea667be7 1014
a3cb91f5 1015 if (count == 0)
9caa2e86 1016 RETURN_INT(0);
a3cb91f5 1017
74510d4b 1018#ifdef _WIN32
39df7833 1019 DWORD buf_bytes;
f92f1f0c 1020
e3dcf906
ML
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. */
9caa2e86 1029 RETURN_INT(0);
a3cb91f5 1030 }
e3dcf906 1031 }
a3cb91f5 1032
e3dcf906 1033 /* Set timeout. */
27a58c05
ML
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 }
e3dcf906 1039
b457865b
ML
1040 /* Reduce count if it exceeds the WriteFile limit. */
1041 if (count > WRITEFILE_MAX_SIZE)
1042 count = WRITEFILE_MAX_SIZE;
1043
39df7833
ML
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");
e3dcf906 1055 } else {
39df7833
ML
1056 /* Actual failure of some kind. */
1057 RETURN_FAIL("WriteFile() failed");
a3cb91f5
ML
1058 }
1059 }
1060
9af8cff3 1061 DEBUG("All bytes written immediately");
e3dcf906 1062
39df7833 1063 RETURN_INT(buf_bytes);
74510d4b
ML
1064#else
1065 /* Returns the number of bytes written, or -1 upon failure. */
1066 ssize_t written = write(port->fd, buf, count);
f92f1f0c 1067
55ab7e0b
ML
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 {
9caa2e86 1075 RETURN_INT(written);
55ab7e0b 1076 }
74510d4b
ML
1077#endif
1078}
1079
94a314a8
ML
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{
8ebfaf89
ML
1084 DWORD errors;
1085 COMSTAT comstat;
94a314a8 1086
21ae5ce1
ML
1087 if (bytes_read == 0)
1088 RETURN_OK();
1089
8ebfaf89
ML
1090 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1091 RETURN_FAIL("ClearCommError() failed");
94a314a8 1092
8ebfaf89 1093 if (comstat.cbInQue == 0)
94a314a8
ML
1094 TRY(restart_wait(port));
1095
1096 RETURN_OK();
1097}
1098#endif
1099
970f279a 1100SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1b91c6ea 1101 size_t count, unsigned int timeout_ms)
e3dcf906 1102{
1b91c6ea 1103 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
e3dcf906
ML
1104
1105 CHECK_OPEN_PORT();
1106
1107 if (!buf)
1108 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1109
1b91c6ea 1110 if (timeout_ms)
7890cef6 1111 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1b91c6ea 1112 count, port->name, timeout_ms);
e3dcf906 1113 else
7890cef6
ML
1114 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1115 count, port->name);
e3dcf906
ML
1116
1117 if (count == 0)
9caa2e86 1118 RETURN_INT(0);
e3dcf906
ML
1119
1120#ifdef _WIN32
1121 DWORD bytes_read = 0;
1122
1123 /* Set timeout. */
27a58c05 1124 if (port->timeouts.ReadIntervalTimeout != 0 ||
0188a545 1125 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
27a58c05
ML
1126 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1127 port->timeouts.ReadIntervalTimeout = 0;
0188a545 1128 port->timeouts.ReadTotalTimeoutMultiplier = 0;
27a58c05
ML
1129 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1130 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1131 RETURN_FAIL("SetCommTimeouts() failed");
1132 }
e3dcf906
ML
1133
1134 /* Start read. */
bbe566fe 1135 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
e3dcf906 1136 DEBUG("Read completed immediately");
6f1186aa 1137 bytes_read = count;
bbe566fe
ML
1138 } else if (GetLastError() == ERROR_IO_PENDING) {
1139 DEBUG("Waiting for read to complete");
27911925
ML
1140 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1141 RETURN_FAIL("GetOverlappedResult() failed");
bbe566fe
ML
1142 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1143 } else {
1144 RETURN_FAIL("ReadFile() failed");
6f1186aa
ML
1145 }
1146
94a314a8 1147 TRY(restart_wait_if_needed(port, bytes_read));
6f1186aa 1148
9caa2e86 1149 RETURN_INT(bytes_read);
6f1186aa 1150
e3dcf906
ML
1151#else
1152 size_t bytes_read = 0;
9a7945af 1153 unsigned char *ptr = (unsigned char *) buf;
32dbe2d2 1154 struct timeout timeout;
76222ee5 1155 int started = 0;
e3dcf906
ML
1156 fd_set fds;
1157 int result;
1158
32dbe2d2 1159 timeout_start(&timeout, timeout_ms);
e3dcf906 1160
772c5861
ML
1161 FD_ZERO(&fds);
1162 FD_SET(port->fd, &fds);
1163
e3dcf906 1164 /* Loop until we have the requested number of bytes. */
dc422c04 1165 while (bytes_read < count) {
76222ee5
ML
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 */
32dbe2d2
ML
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));
76222ee5 1176 started = 1;
63a17c64
ML
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) {
c3cee38c
ML
1185 /* Timeout has expired. */
1186 break;
e3dcf906
ML
1187 }
1188
1189 /* Do read. */
1190 result = read(port->fd, ptr, count - bytes_read);
1191
1192 if (result < 0) {
1193 if (errno == EAGAIN)
76222ee5
ML
1194 /*
1195 * This shouldn't happen because we did a
1196 * select() first, but handle anyway.
1197 */
e3dcf906
ML
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
c3cee38c
ML
1208 if (bytes_read < count)
1209 DEBUG("Read timed out");
1210
9caa2e86 1211 RETURN_INT(bytes_read);
e3dcf906
ML
1212#endif
1213}
1214
e5c2630e
ML
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. */
888fb45d 1255 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
e5c2630e 1256 DEBUG("Read completed immediately");
e5c2630e
ML
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;
32dbe2d2 1280 struct timeout timeout;
e5c2630e
ML
1281 int started = 0;
1282 fd_set fds;
1283 int result;
1284
32dbe2d2 1285 timeout_start(&timeout, timeout_ms);
e5c2630e
ML
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 */
32dbe2d2
ML
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));
e5c2630e
ML
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
970f279a
AJ
1337SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1338 size_t count)
74510d4b 1339{
c33efc48
ML
1340 TRACE("%p, %p, %d", port, buf, count);
1341
dec10e31 1342 CHECK_OPEN_PORT();
74510d4b
ML
1343
1344 if (!buf)
c33efc48 1345 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
74510d4b 1346
7890cef6 1347 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
ea667be7 1348
74510d4b 1349#ifdef _WIN32
e3dcf906 1350 DWORD bytes_read;
f92f1f0c 1351
e3dcf906 1352 /* Set timeout. */
27a58c05 1353 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
0188a545 1354 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
27a58c05
ML
1355 port->timeouts.ReadTotalTimeoutConstant != 0) {
1356 port->timeouts.ReadIntervalTimeout = MAXDWORD;
0188a545 1357 port->timeouts.ReadTotalTimeoutMultiplier = 0;
27a58c05
ML
1358 port->timeouts.ReadTotalTimeoutConstant = 0;
1359 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1360 RETURN_FAIL("SetCommTimeouts() failed");
1361 }
e3dcf906
ML
1362
1363 /* Do read. */
1364 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
ae2c5825
ML
1365 if (GetLastError() != ERROR_IO_PENDING)
1366 RETURN_FAIL("ReadFile() failed");
e3dcf906
ML
1367
1368 /* Get number of bytes read. */
ae2c5825 1369 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1622ef60 1370 RETURN_FAIL("GetOverlappedResult() failed");
e3dcf906 1371
94a314a8 1372 TRY(restart_wait_if_needed(port, bytes_read));
6f1186aa 1373
9caa2e86 1374 RETURN_INT(bytes_read);
74510d4b
ML
1375#else
1376 ssize_t bytes_read;
f92f1f0c 1377
74510d4b 1378 /* Returns the number of bytes read, or -1 upon failure. */
33d5ff47 1379 if ((bytes_read = read(port->fd, buf, count)) < 0) {
e3dcf906
ML
1380 if (errno == EAGAIN)
1381 /* No bytes available. */
33d5ff47
ML
1382 bytes_read = 0;
1383 else
1384 /* This is an actual failure. */
1385 RETURN_FAIL("read() failed");
1386 }
9caa2e86 1387 RETURN_INT(bytes_read);
74510d4b
ML
1388#endif
1389}
1390
970f279a 1391SP_API enum sp_return sp_input_waiting(struct sp_port *port)
3353c22f
ML
1392{
1393 TRACE("%p", port);
1394
1395 CHECK_OPEN_PORT();
1396
7890cef6 1397 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
3353c22f
ML
1398
1399#ifdef _WIN32
1400 DWORD errors;
1401 COMSTAT comstat;
1402
1403 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1a2a1544 1404 RETURN_FAIL("ClearCommError() failed");
9caa2e86 1405 RETURN_INT(comstat.cbInQue);
3353c22f
ML
1406#else
1407 int bytes_waiting;
1408 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1409 RETURN_FAIL("TIOCINQ ioctl failed");
9caa2e86 1410 RETURN_INT(bytes_waiting);
3353c22f
ML
1411#endif
1412}
1413
970f279a 1414SP_API enum sp_return sp_output_waiting(struct sp_port *port)
3353c22f
ML
1415{
1416 TRACE("%p", port);
1417
1418 CHECK_OPEN_PORT();
1419
7890cef6 1420 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
3353c22f
ML
1421
1422#ifdef _WIN32
1423 DWORD errors;
1424 COMSTAT comstat;
1425
1426 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1a2a1544 1427 RETURN_FAIL("ClearCommError() failed");
9caa2e86 1428 RETURN_INT(comstat.cbOutQue);
3353c22f
ML
1429#else
1430 int bytes_waiting;
1431 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1432 RETURN_FAIL("TIOCOUTQ ioctl failed");
9caa2e86 1433 RETURN_INT(bytes_waiting);
3353c22f
ML
1434#endif
1435}
1436
970f279a 1437SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
6f1186aa
ML
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))))
dc422c04 1468 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
6f1186aa 1469
ac323d80
UH
1470 event_set->handles = new_handles;
1471
6f1186aa 1472 if (!(new_masks = realloc(event_set->masks,
ac323d80 1473 sizeof(enum sp_event) * (event_set->count + 1))))
dc422c04 1474 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
6f1186aa 1475
6f1186aa
ML
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
970f279a 1486SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
6f1186aa
ML
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
970f279a 1516SP_API void sp_free_event_set(struct sp_event_set *event_set)
6f1186aa
ML
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
970f279a 1537SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1b91c6ea 1538 unsigned int timeout_ms)
6f1186aa 1539{
1b91c6ea 1540 TRACE("%p, %d", event_set, timeout_ms);
6f1186aa
ML
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,
1b91c6ea 1547 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
6f1186aa
ML
1548 RETURN_FAIL("WaitForMultipleObjects() failed");
1549
1550 RETURN_OK();
1551#else
32dbe2d2
ML
1552 struct timeout timeout;
1553 int started = 0, result;
6f1186aa
ML
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++) {
81243567 1561 pollfds[i].fd = ((int *)event_set->handles)[i];
6f1186aa
ML
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
32dbe2d2 1572 timeout_start(&timeout, timeout_ms);
6f1186aa
ML
1573
1574 /* Loop until an event occurs. */
dc422c04 1575 while (1) {
76222ee5
ML
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 */
32dbe2d2
ML
1581 if (started && timeout_check(&timeout)) {
1582 DEBUG("Wait timed out");
1583 break;
6f1186aa
ML
1584 }
1585
32dbe2d2 1586 result = poll(pollfds, event_set->count, timeout_remaining_ms(&timeout));
76222ee5 1587 started = 1;
6f1186aa
ML
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");
32dbe2d2 1599 if (!timeout.overflow)
127d8d0c 1600 break;
6f1186aa
ML
1601 } else {
1602 DEBUG("poll() completed");
1603 break;
1604 }
1605 }
1606
1607 free(pollfds);
1608 RETURN_OK();
1609#endif
1610}
1611
5cea279a 1612#ifdef USE_TERMIOS_SPEED
7a6d2196
ML
1613static enum sp_return get_baudrate(int fd, int *baudrate)
1614{
1615 void *data;
1616
c33efc48
ML
1617 TRACE("%d, %p", fd, baudrate);
1618
ea667be7
ML
1619 DEBUG("Getting baud rate");
1620
7a6d2196 1621 if (!(data = malloc(get_termios_size())))
c33efc48 1622 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
7a6d2196 1623
8d43110a
ML
1624 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1625 free(data);
dc422c04 1626 RETURN_FAIL("Getting termios failed");
8d43110a 1627 }
7a6d2196
ML
1628
1629 *baudrate = get_termios_speed(data);
1630
8d43110a
ML
1631 free(data);
1632
c33efc48 1633 RETURN_OK();
7a6d2196
ML
1634}
1635
1636static enum sp_return set_baudrate(int fd, int baudrate)
1637{
1638 void *data;
1639
c33efc48
ML
1640 TRACE("%d, %d", fd, baudrate);
1641
ea667be7
ML
1642 DEBUG("Getting baud rate");
1643
7a6d2196 1644 if (!(data = malloc(get_termios_size())))
c33efc48 1645 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
7a6d2196 1646
8d43110a
ML
1647 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1648 free(data);
dc422c04 1649 RETURN_FAIL("Getting termios failed");
8d43110a 1650 }
7a6d2196 1651
ea667be7
ML
1652 DEBUG("Setting baud rate");
1653
7a6d2196
ML
1654 set_termios_speed(data, baudrate);
1655
8d43110a
ML
1656 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1657 free(data);
dc422c04 1658 RETURN_FAIL("Setting termios failed");
8d43110a
ML
1659 }
1660
1661 free(data);
7a6d2196 1662
c33efc48 1663 RETURN_OK();
7a6d2196 1664}
5cea279a 1665#endif /* USE_TERMIOS_SPEED */
40978c2b
ML
1666
1667#ifdef USE_TERMIOX
bd791fe1 1668static enum sp_return get_flow(int fd, struct port_data *data)
40978c2b 1669{
bd791fe1 1670 void *termx;
40978c2b 1671
bd791fe1 1672 TRACE("%d, %p", fd, data);
c33efc48 1673
ea667be7
ML
1674 DEBUG("Getting advanced flow control");
1675
bd791fe1 1676 if (!(termx = malloc(get_termiox_size())))
c33efc48 1677 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
40978c2b 1678
bd791fe1
ML
1679 if (ioctl(fd, TCGETX, termx) < 0) {
1680 free(termx);
dc422c04 1681 RETURN_FAIL("Getting termiox failed");
8d43110a 1682 }
40978c2b 1683
bd791fe1
ML
1684 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1685 &data->dtr_flow, &data->dsr_flow);
40978c2b 1686
bd791fe1 1687 free(termx);
8d43110a 1688
c33efc48 1689 RETURN_OK();
40978c2b
ML
1690}
1691
bd791fe1 1692static enum sp_return set_flow(int fd, struct port_data *data)
40978c2b 1693{
bd791fe1 1694 void *termx;
40978c2b 1695
bd791fe1 1696 TRACE("%d, %p", fd, data);
c33efc48 1697
ea667be7
ML
1698 DEBUG("Getting advanced flow control");
1699
bd791fe1 1700 if (!(termx = malloc(get_termiox_size())))
c33efc48 1701 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
40978c2b 1702
bd791fe1
ML
1703 if (ioctl(fd, TCGETX, termx) < 0) {
1704 free(termx);
dc422c04 1705 RETURN_FAIL("Getting termiox failed");
8d43110a 1706 }
40978c2b 1707
ea667be7
ML
1708 DEBUG("Setting advanced flow control");
1709
bd791fe1
ML
1710 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1711 data->dtr_flow, data->dsr_flow);
40978c2b 1712
bd791fe1
ML
1713 if (ioctl(fd, TCSETX, termx) < 0) {
1714 free(termx);
dc422c04 1715 RETURN_FAIL("Setting termiox failed");
8d43110a
ML
1716 }
1717
bd791fe1 1718 free(termx);
40978c2b 1719
c33efc48 1720 RETURN_OK();
40978c2b
ML
1721}
1722#endif /* USE_TERMIOX */
7a6d2196 1723
eb6ed20f
ML
1724static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1725 struct sp_port_config *config)
8094e4a0 1726{
da2748bf 1727 unsigned int i;
cbf628c7 1728
c33efc48
ML
1729 TRACE("%p, %p, %p", port, data, config);
1730
7890cef6 1731 DEBUG_FMT("Getting configuration for port %s", port->name);
ea667be7 1732
8094e4a0 1733#ifdef _WIN32
e33ab9aa 1734 if (!GetCommState(port->hdl, &data->dcb))
c33efc48 1735 RETURN_FAIL("GetCommState() failed");
8094e4a0 1736
067417af 1737 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
e33ab9aa 1738 if (data->dcb.BaudRate == std_baudrates[i].index) {
067417af
ML
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. */
e33ab9aa 1746 config->baudrate = data->dcb.BaudRate;
067417af 1747
e33ab9aa 1748 config->bits = data->dcb.ByteSize;
067417af 1749
e33ab9aa
ML
1750 if (data->dcb.fParity)
1751 switch (data->dcb.Parity) {
067417af
ML
1752 case NOPARITY:
1753 config->parity = SP_PARITY_NONE;
1754 break;
e432ce60
ML
1755 case ODDPARITY:
1756 config->parity = SP_PARITY_ODD;
1757 break;
067417af
ML
1758 case EVENPARITY:
1759 config->parity = SP_PARITY_EVEN;
1760 break;
e432ce60
ML
1761 case MARKPARITY:
1762 config->parity = SP_PARITY_MARK;
1763 break;
1764 case SPACEPARITY:
1765 config->parity = SP_PARITY_SPACE;
067417af
ML
1766 break;
1767 default:
1768 config->parity = -1;
1769 }
1770 else
1771 config->parity = SP_PARITY_NONE;
1772
e33ab9aa 1773 switch (data->dcb.StopBits) {
067417af
ML
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
e33ab9aa 1784 switch (data->dcb.fRtsControl) {
eac329d2
UH
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;
067417af
ML
1796 }
1797
e33ab9aa 1798 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
067417af 1799
e33ab9aa 1800 switch (data->dcb.fDtrControl) {
eac329d2
UH
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;
067417af
ML
1812 }
1813
e33ab9aa
ML
1814 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1815
c6754b45
ML
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
e33ab9aa
ML
1828#else // !_WIN32
1829
1830 if (tcgetattr(port->fd, &data->term) < 0)
c33efc48 1831 RETURN_FAIL("tcgetattr() failed");
e33ab9aa
ML
1832
1833 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
c33efc48 1834 RETURN_FAIL("TIOCMGET ioctl failed");
40978c2b
ML
1835
1836#ifdef USE_TERMIOX
bd791fe1 1837 int ret = get_flow(port->fd, data);
68ec29db
ML
1838
1839 if (ret == SP_ERR_FAIL && errno == EINVAL)
1840 data->termiox_supported = 0;
1841 else if (ret < 0)
c33efc48 1842 RETURN_CODEVAL(ret);
68ec29db
ML
1843 else
1844 data->termiox_supported = 1;
1845#else
1846 data->termiox_supported = 0;
40978c2b
ML
1847#endif
1848
067417af 1849 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
e33ab9aa 1850 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
067417af
ML
1851 config->baudrate = std_baudrates[i].value;
1852 break;
1853 }
1854 }
1855
31b3a8f5
MH
1856 if (i == NUM_STD_BAUDRATES) {
1857#ifdef __APPLE__
1858 config->baudrate = (int)data->term.c_ispeed;
5cea279a 1859#elif defined(USE_TERMIOS_SPEED)
7a6d2196 1860 TRY(get_baudrate(port->fd, &config->baudrate));
31b3a8f5 1861#else
067417af 1862 config->baudrate = -1;
31b3a8f5
MH
1863#endif
1864 }
067417af 1865
e33ab9aa 1866 switch (data->term.c_cflag & CSIZE) {
067417af
ML
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
e33ab9aa 1883 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
067417af 1884 config->parity = SP_PARITY_NONE;
e33ab9aa 1885 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
067417af 1886 config->parity = -1;
c3e05092 1887#ifdef CMSPAR
e432ce60
ML
1888 else if (data->term.c_cflag & CMSPAR)
1889 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
c3e05092 1890#endif
067417af 1891 else
e33ab9aa 1892 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
067417af 1893
e33ab9aa 1894 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
067417af 1895
e33ab9aa 1896 if (data->term.c_cflag & CRTSCTS) {
067417af
ML
1897 config->rts = SP_RTS_FLOW_CONTROL;
1898 config->cts = SP_CTS_FLOW_CONTROL;
1899 } else {
bd791fe1 1900 if (data->termiox_supported && data->rts_flow)
40978c2b
ML
1901 config->rts = SP_RTS_FLOW_CONTROL;
1902 else
1903 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1904
bd791fe1 1905 config->cts = (data->termiox_supported && data->cts_flow) ?
68ec29db 1906 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
067417af
ML
1907 }
1908
bd791fe1 1909 if (data->termiox_supported && data->dtr_flow)
40978c2b
ML
1910 config->dtr = SP_DTR_FLOW_CONTROL;
1911 else
1912 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1913
bd791fe1 1914 config->dsr = (data->termiox_supported && data->dsr_flow) ?
68ec29db 1915 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
705bdc69 1916
e29b93a5
ML
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 }
067417af
ML
1928#endif
1929
c33efc48 1930 RETURN_OK();
067417af
ML
1931}
1932
7a6d2196 1933static enum sp_return set_config(struct sp_port *port, struct port_data *data,
eb6ed20f 1934 const struct sp_port_config *config)
18fc2dd1 1935{
e33ab9aa 1936 unsigned int i;
31b3a8f5
MH
1937#ifdef __APPLE__
1938 BAUD_TYPE baud_nonstd;
1939
1940 baud_nonstd = B0;
1941#endif
5cea279a 1942#ifdef USE_TERMIOS_SPEED
7a6d2196
ML
1943 int baud_nonstd = 0;
1944#endif
18fc2dd1 1945
c33efc48
ML
1946 TRACE("%p, %p, %p", port, data, config);
1947
7890cef6 1948 DEBUG_FMT("Setting configuration for port %s", port->name);
ea667be7 1949
e33ab9aa 1950#ifdef _WIN32
6bd6a8b5
ML
1951
1952 TRY(await_write_completion(port));
1953
eac329d2 1954 if (config->baudrate >= 0) {
e33ab9aa
ML
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 }
18fc2dd1 1961
e33ab9aa
ML
1962 if (i == NUM_STD_BAUDRATES)
1963 data->dcb.BaudRate = config->baudrate;
39df7833
ML
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");
e33ab9aa 1972 }
18fc2dd1 1973
e33ab9aa
ML
1974 if (config->bits >= 0)
1975 data->dcb.ByteSize = config->bits;
1976
1977 if (config->parity >= 0) {
1978 switch (config->parity) {
e33ab9aa
ML
1979 case SP_PARITY_NONE:
1980 data->dcb.Parity = NOPARITY;
1981 break;
e432ce60
ML
1982 case SP_PARITY_ODD:
1983 data->dcb.Parity = ODDPARITY;
1984 break;
e33ab9aa
ML
1985 case SP_PARITY_EVEN:
1986 data->dcb.Parity = EVENPARITY;
1987 break;
e432ce60
ML
1988 case SP_PARITY_MARK:
1989 data->dcb.Parity = MARKPARITY;
1990 break;
1991 case SP_PARITY_SPACE:
1992 data->dcb.Parity = SPACEPARITY;
e33ab9aa
ML
1993 break;
1994 default:
c33efc48 1995 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
e33ab9aa 1996 }
18fc2dd1
ML
1997 }
1998
e33ab9aa
ML
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:
c33efc48 2009 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
e33ab9aa
ML
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:
c33efc48 2025 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
e33ab9aa
ML
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:
c33efc48 2038 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
e33ab9aa
ML
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:
c33efc48 2054 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
e33ab9aa
ML
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:
c33efc48 2067 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
e33ab9aa 2068 }
18fc2dd1
ML
2069 }
2070
e33ab9aa
ML
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:
c33efc48 2090 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
e33ab9aa
ML
2091 }
2092 }
2093
2094 if (!SetCommState(port->hdl, &data->dcb))
c33efc48 2095 RETURN_FAIL("SetCommState() failed");
e33ab9aa 2096
31b3a8f5 2097#else /* !_WIN32 */
e33ab9aa 2098
7a6d2196
ML
2099 int controlbits;
2100
eac329d2 2101 if (config->baudrate >= 0) {
e33ab9aa
ML
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)
c33efc48 2105 RETURN_FAIL("cfsetospeed() failed");
e33ab9aa
ML
2106
2107 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
c33efc48 2108 RETURN_FAIL("cfsetispeed() failed");
e33ab9aa
ML
2109 break;
2110 }
2111 }
2112
31b3a8f5
MH
2113 /* Non-standard baud rate */
2114 if (i == NUM_STD_BAUDRATES) {
2115#ifdef __APPLE__
24abdb68 2116 /* Set "dummy" baud rate. */
31b3a8f5 2117 if (cfsetspeed(&data->term, B9600) < 0)
c33efc48 2118 RETURN_FAIL("cfsetspeed() failed");
31b3a8f5 2119 baud_nonstd = config->baudrate;
5cea279a 2120#elif defined(USE_TERMIOS_SPEED)
7a6d2196 2121 baud_nonstd = 1;
31b3a8f5 2122#else
c33efc48 2123 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
31b3a8f5
MH
2124#endif
2125 }
e33ab9aa
ML
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;
23922313
UH
2140 case 5:
2141 data->term.c_cflag |= CS5;
2142 break;
e33ab9aa 2143 default:
c33efc48 2144 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
e33ab9aa
ML
2145 }
2146 }
2147
2148 if (config->parity >= 0) {
2149 data->term.c_iflag &= ~IGNPAR;
c3e05092
UH
2150 data->term.c_cflag &= ~(PARENB | PARODD);
2151#ifdef CMSPAR
2152 data->term.c_cflag &= ~CMSPAR;
2153#endif
e33ab9aa
ML
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;
afb518f0 2164#ifdef CMSPAR
e432ce60 2165 case SP_PARITY_MARK:
c3e05092 2166 data->term.c_cflag |= PARENB | PARODD;
c3e05092 2167 data->term.c_cflag |= CMSPAR;
e432ce60
ML
2168 break;
2169 case SP_PARITY_SPACE:
c3e05092 2170 data->term.c_cflag |= PARENB;
c3e05092 2171 data->term.c_cflag |= CMSPAR;
e432ce60 2172 break;
afb518f0
ML
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
e33ab9aa 2178 default:
c33efc48 2179 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
e33ab9aa
ML
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:
c33efc48 2193 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
e33ab9aa
ML
2194 }
2195 }
2196
eac329d2 2197 if (config->rts >= 0 || config->cts >= 0) {
68ec29db 2198 if (data->termiox_supported) {
bd791fe1 2199 data->rts_flow = data->cts_flow = 0;
68ec29db
ML
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)
c33efc48 2205 RETURN_FAIL("Setting RTS signal level failed");
68ec29db
ML
2206 break;
2207 case SP_RTS_FLOW_CONTROL:
bd791fe1 2208 data->rts_flow = 1;
68ec29db
ML
2209 break;
2210 default:
2211 break;
e33ab9aa 2212 }
68ec29db 2213 if (config->cts == SP_CTS_FLOW_CONTROL)
bd791fe1 2214 data->cts_flow = 1;
e33ab9aa 2215
bd791fe1 2216 if (data->rts_flow && data->cts_flow)
e33ab9aa 2217 data->term.c_iflag |= CRTSCTS;
68ec29db
ML
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)
c33efc48 2226 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
68ec29db
ML
2227 }
2228 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2229 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
c33efc48 2230 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
68ec29db 2231 }
e33ab9aa 2232 } else {
68ec29db
ML
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)))
c33efc48 2236 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
68ec29db
ML
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)
c33efc48 2246 RETURN_FAIL("Setting RTS signal level failed");
68ec29db 2247 }
e33ab9aa
ML
2248 }
2249 }
2250 }
2251
eac329d2 2252 if (config->dtr >= 0 || config->dsr >= 0) {
68ec29db 2253 if (data->termiox_supported) {
bd791fe1 2254 data->dtr_flow = data->dsr_flow = 0;
68ec29db
ML
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)
c33efc48 2260 RETURN_FAIL("Setting DTR signal level failed");
68ec29db
ML
2261 break;
2262 case SP_DTR_FLOW_CONTROL:
bd791fe1 2263 data->dtr_flow = 1;
68ec29db
ML
2264 break;
2265 default:
2266 break;
2267 }
2268 if (config->dsr == SP_DSR_FLOW_CONTROL)
bd791fe1 2269 data->dsr_flow = 1;
68ec29db
ML
2270 } else {
2271 /* DTR/DSR flow control not supported. */
2272 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
c33efc48 2273 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
e33ab9aa 2274
68ec29db
ML
2275 if (config->dtr >= 0) {
2276 controlbits = TIOCM_DTR;
2277 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2278 &controlbits) < 0)
c33efc48 2279 RETURN_FAIL("Setting DTR signal level failed");
68ec29db 2280 }
e33ab9aa
ML
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:
c33efc48 2299 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
e33ab9aa
ML
2300 }
2301 }
2302
3f5c06d0 2303 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
c33efc48 2304 RETURN_FAIL("tcsetattr() failed");
31b3a8f5
MH
2305
2306#ifdef __APPLE__
2307 if (baud_nonstd != B0) {
2308 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
c33efc48 2309 RETURN_FAIL("IOSSIOSPEED ioctl failed");
dc422c04
UH
2310 /*
2311 * Set baud rates in data->term to correct, but incompatible
2312 * with tcsetattr() value, same as delivered by tcgetattr().
2313 */
31b3a8f5 2314 if (cfsetspeed(&data->term, baud_nonstd) < 0)
c33efc48 2315 RETURN_FAIL("cfsetspeed() failed");
31b3a8f5 2316 }
7a6d2196 2317#elif defined(__linux__)
5cea279a 2318#ifdef USE_TERMIOS_SPEED
7a6d2196
ML
2319 if (baud_nonstd)
2320 TRY(set_baudrate(port->fd, config->baudrate));
5cea279a 2321#endif
40978c2b 2322#ifdef USE_TERMIOX
68ec29db 2323 if (data->termiox_supported)
bd791fe1 2324 TRY(set_flow(port->fd, data));
40978c2b 2325#endif
7a6d2196 2326#endif
31b3a8f5
MH
2327
2328#endif /* !_WIN32 */
e33ab9aa 2329
c33efc48 2330 RETURN_OK();
e33ab9aa
ML
2331}
2332
970f279a 2333SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
9b1502ef 2334{
59131d60 2335 struct sp_port_config *config;
9b1502ef 2336
00d8c56d
UH
2337 TRACE("%p", config_ptr);
2338
9b1502ef
ML
2339 if (!config_ptr)
2340 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2341
59131d60
ML
2342 *config_ptr = NULL;
2343
2344 if (!(config = malloc(sizeof(struct sp_port_config))))
dc422c04 2345 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
9b1502ef 2346
59131d60
ML
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
9b1502ef
ML
2358 RETURN_OK();
2359}
2360
970f279a 2361SP_API void sp_free_config(struct sp_port_config *config)
9b1502ef
ML
2362{
2363 TRACE("%p", config);
2364
2365 if (!config)
2366 DEBUG("Null config");
2367 else
2368 free(config);
2369
2370 RETURN();
2371}
2372
970f279a
AJ
2373SP_API enum sp_return sp_get_config(struct sp_port *port,
2374 struct sp_port_config *config)
70cd37de
ML
2375{
2376 struct port_data data;
2377
2378 TRACE("%p, %p", port, config);
2379
2380 CHECK_OPEN_PORT();
2381
2382 if (!config)
9b1502ef 2383 RETURN_ERROR(SP_ERR_ARG, "Null config");
70cd37de
ML
2384
2385 TRY(get_config(port, &data, config));
2386
2387 RETURN_OK();
2388}
2389
970f279a
AJ
2390SP_API enum sp_return sp_set_config(struct sp_port *port,
2391 const struct sp_port_config *config)
e33ab9aa 2392{
8f189c4c 2393 struct port_data data;
e33ab9aa
ML
2394 struct sp_port_config prev_config;
2395
c33efc48
ML
2396 TRACE("%p, %p", port, config);
2397
dec10e31 2398 CHECK_OPEN_PORT();
823690ae
ML
2399
2400 if (!config)
c33efc48 2401 RETURN_ERROR(SP_ERR_ARG, "Null config");
823690ae 2402
e33ab9aa
ML
2403 TRY(get_config(port, &data, &prev_config));
2404 TRY(set_config(port, &data, config));
74510d4b 2405
c33efc48 2406 RETURN_OK();
74510d4b
ML
2407}
2408
9b1502ef 2409#define CREATE_ACCESSORS(x, type) \
970f279a 2410SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
8f189c4c 2411 struct port_data data; \
e33ab9aa 2412 struct sp_port_config config; \
c33efc48 2413 TRACE("%p, %d", port, x); \
dec10e31 2414 CHECK_OPEN_PORT(); \
e33ab9aa
ML
2415 TRY(get_config(port, &data, &config)); \
2416 config.x = x; \
2417 TRY(set_config(port, &data, &config)); \
c33efc48 2418 RETURN_OK(); \
9b1502ef 2419} \
970f279a
AJ
2420SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2421 type *x) { \
00d8c56d 2422 TRACE("%p, %p", config, x); \
6aad5bdd
UH
2423 if (!x) \
2424 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
9b1502ef
ML
2425 if (!config) \
2426 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2427 *x = config->x; \
2428 RETURN_OK(); \
2429} \
970f279a
AJ
2430SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2431 type x) { \
9b1502ef
ML
2432 TRACE("%p, %d", config, x); \
2433 if (!config) \
2434 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2435 config->x = x; \
2436 RETURN_OK(); \
9069c2fb
ML
2437}
2438
9b1502ef
ML
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
970f279a
AJ
2449SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2450 enum sp_flowcontrol flowcontrol)
e33ab9aa 2451{
9b1502ef
ML
2452 if (!config)
2453 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
dec10e31
ML
2454
2455 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2456 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
823690ae 2457
e33ab9aa 2458 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
9b1502ef 2459 config->xon_xoff = SP_XONXOFF_INOUT;
e33ab9aa 2460 else
9b1502ef 2461 config->xon_xoff = SP_XONXOFF_DISABLED;
e33ab9aa
ML
2462
2463 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
9b1502ef
ML
2464 config->rts = SP_RTS_FLOW_CONTROL;
2465 config->cts = SP_CTS_FLOW_CONTROL;
e33ab9aa 2466 } else {
9b1502ef
ML
2467 if (config->rts == SP_RTS_FLOW_CONTROL)
2468 config->rts = SP_RTS_ON;
2469 config->cts = SP_CTS_IGNORE;
e33ab9aa
ML
2470 }
2471
2472 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
9b1502ef
ML
2473 config->dtr = SP_DTR_FLOW_CONTROL;
2474 config->dsr = SP_DSR_FLOW_CONTROL;
e33ab9aa 2475 } else {
9b1502ef
ML
2476 if (config->dtr == SP_DTR_FLOW_CONTROL)
2477 config->dtr = SP_DTR_ON;
2478 config->dsr = SP_DSR_IGNORE;
e33ab9aa
ML
2479 }
2480
9b1502ef
ML
2481 RETURN_OK();
2482}
2483
970f279a
AJ
2484SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2485 enum sp_flowcontrol flowcontrol)
9b1502ef
ML
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
e33ab9aa
ML
2498 TRY(set_config(port, &data, &config));
2499
c33efc48 2500 RETURN_OK();
e33ab9aa
ML
2501}
2502
970f279a
AJ
2503SP_API enum sp_return sp_get_signals(struct sp_port *port,
2504 enum sp_signal *signals)
8cf7c697 2505{
c33efc48
ML
2506 TRACE("%p, %p", port, signals);
2507
dec10e31 2508 CHECK_OPEN_PORT();
8cf7c697
ML
2509
2510 if (!signals)
c33efc48 2511 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
8cf7c697 2512
7890cef6 2513 DEBUG_FMT("Getting control signals for port %s", port->name);
ea667be7 2514
8cf7c697
ML
2515 *signals = 0;
2516#ifdef _WIN32
2517 DWORD bits;
2518 if (GetCommModemStatus(port->hdl, &bits) == 0)
c33efc48 2519 RETURN_FAIL("GetCommModemStatus() failed");
8cf7c697
ML
2520 if (bits & MS_CTS_ON)
2521 *signals |= SP_SIG_CTS;
2522 if (bits & MS_DSR_ON)
2523 *signals |= SP_SIG_DSR;
8cf7c697 2524 if (bits & MS_RLSD_ON)
a6cda1e8
ML
2525 *signals |= SP_SIG_DCD;
2526 if (bits & MS_RING_ON)
8cf7c697
ML
2527 *signals |= SP_SIG_RI;
2528#else
2529 int bits;
2530 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
c33efc48 2531 RETURN_FAIL("TIOCMGET ioctl failed");
8cf7c697
ML
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
c33efc48 2541 RETURN_OK();
8cf7c697
ML
2542}
2543
970f279a 2544SP_API enum sp_return sp_start_break(struct sp_port *port)
90cc3ee6 2545{
c33efc48
ML
2546 TRACE("%p", port);
2547
dec10e31 2548 CHECK_OPEN_PORT();
90cc3ee6
ML
2549#ifdef _WIN32
2550 if (SetCommBreak(port->hdl) == 0)
c33efc48 2551 RETURN_FAIL("SetCommBreak() failed");
90cc3ee6
ML
2552#else
2553 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
c33efc48 2554 RETURN_FAIL("TIOCSBRK ioctl failed");
90cc3ee6
ML
2555#endif
2556
c33efc48 2557 RETURN_OK();
90cc3ee6
ML
2558}
2559
970f279a 2560SP_API enum sp_return sp_end_break(struct sp_port *port)
90cc3ee6 2561{
c33efc48
ML
2562 TRACE("%p", port);
2563
dec10e31 2564 CHECK_OPEN_PORT();
90cc3ee6
ML
2565#ifdef _WIN32
2566 if (ClearCommBreak(port->hdl) == 0)
c33efc48 2567 RETURN_FAIL("ClearCommBreak() failed");
90cc3ee6
ML
2568#else
2569 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
c33efc48 2570 RETURN_FAIL("TIOCCBRK ioctl failed");
90cc3ee6
ML
2571#endif
2572
c33efc48 2573 RETURN_OK();
90cc3ee6
ML
2574}
2575
970f279a 2576SP_API int sp_last_error_code(void)
74510d4b 2577{
7890cef6 2578 TRACE_VOID();
74510d4b 2579#ifdef _WIN32
9caa2e86 2580 RETURN_INT(GetLastError());
74510d4b 2581#else
9caa2e86 2582 RETURN_INT(errno);
74510d4b
ML
2583#endif
2584}
2585
970f279a 2586SP_API char *sp_last_error_message(void)
74510d4b 2587{
7890cef6 2588 TRACE_VOID();
c33efc48 2589
74510d4b 2590#ifdef _WIN32
9a0c4bbd 2591 TCHAR *message;
74510d4b
ML
2592 DWORD error = GetLastError();
2593
9a0c4bbd 2594 DWORD length = FormatMessage(
74510d4b
ML
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
9a0c4bbd
ML
2604 if (length >= 2 && message[length - 2] == '\r')
2605 message[length - 2] = '\0';
2606
9caa2e86 2607 RETURN_STRING(message);
74510d4b 2608#else
9caa2e86 2609 RETURN_STRING(strerror(errno));
74510d4b
ML
2610#endif
2611}
2612
970f279a 2613SP_API void sp_free_error_message(char *message)
74510d4b 2614{
c33efc48
ML
2615 TRACE("%s", message);
2616
74510d4b
ML
2617#ifdef _WIN32
2618 LocalFree(message);
64eec30d
ML
2619#else
2620 (void)message;
74510d4b 2621#endif
c33efc48
ML
2622
2623 RETURN();
74510d4b 2624}
863b35e6 2625
970f279a 2626SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
863b35e6 2627{
c33efc48
ML
2628 TRACE("%p", handler);
2629
863b35e6 2630 sp_debug_handler = handler;
c33efc48
ML
2631
2632 RETURN();
863b35e6
ML
2633}
2634
970f279a 2635SP_API void sp_default_debug_handler(const char *format, ...)
863b35e6
ML
2636{
2637 va_list args;
2638 va_start(args, format);
2639 if (getenv("LIBSERIALPORT_DEBUG")) {
dd7742fb 2640 fputs("sp: ", stderr);
863b35e6
ML
2641 vfprintf(stderr, format, args);
2642 }
2643 va_end(args);
2644}
524b0e14 2645
970f279a 2646SP_API int sp_get_major_package_version(void)
524b0e14
UH
2647{
2648 return SP_PACKAGE_VERSION_MAJOR;
2649}
2650
970f279a 2651SP_API int sp_get_minor_package_version(void)
524b0e14
UH
2652{
2653 return SP_PACKAGE_VERSION_MINOR;
2654}
2655
970f279a 2656SP_API int sp_get_micro_package_version(void)
524b0e14
UH
2657{
2658 return SP_PACKAGE_VERSION_MICRO;
2659}
2660
970f279a 2661SP_API const char *sp_get_package_version_string(void)
524b0e14
UH
2662{
2663 return SP_PACKAGE_VERSION_STRING;
2664}
2665
970f279a 2666SP_API int sp_get_current_lib_version(void)
524b0e14
UH
2667{
2668 return SP_LIB_VERSION_CURRENT;
2669}
2670
970f279a 2671SP_API int sp_get_revision_lib_version(void)
524b0e14
UH
2672{
2673 return SP_LIB_VERSION_REVISION;
2674}
2675
970f279a 2676SP_API int sp_get_age_lib_version(void)
524b0e14
UH
2677{
2678 return SP_LIB_VERSION_AGE;
2679}
2680
970f279a 2681SP_API const char *sp_get_lib_version_string(void)
524b0e14
UH
2682{
2683 return SP_LIB_VERSION_STRING;
2684}
2685
2686/** @} */