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