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