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