]> sigrok.org Git - libserialport.git/blame - serialport.c
Add project files for Visual Studio 2019.
[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
5919c913 62 int 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;
326 unsigned int 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
99945a1f 491 port->hdl = CreateFile(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
060d1d8a
ML
785 DWORD remaining_ms, write_size, bytes_written, total_bytes_written = 0;
786 const uint8_t *write_ptr = (uint8_t *) buf;
787 bool result;
788 struct timeout timeout;
789
790 timeout_start(&timeout, timeout_ms);
e3dcf906 791
62ed9f80 792 TRY(await_write_completion(port));
e3dcf906 793
060d1d8a 794 while (total_bytes_written < count) {
e3dcf906 795
060d1d8a
ML
796 if (timeout_check(&timeout))
797 break;
798
799 remaining_ms = timeout_remaining_ms(&timeout);
800
801 if (port->timeouts.WriteTotalTimeoutConstant != remaining_ms) {
802 port->timeouts.WriteTotalTimeoutConstant = remaining_ms;
803 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
804 RETURN_FAIL("SetCommTimeouts() failed");
805 }
806
807 /* Reduce write size if it exceeds the WriteFile limit. */
808 write_size = count - total_bytes_written;
809 if (write_size > WRITEFILE_MAX_SIZE)
810 write_size = WRITEFILE_MAX_SIZE;
811
812 /* Start write. */
813
814 result = WriteFile(port->hdl, write_ptr, write_size, NULL, &port->write_ovl);
815
816 timeout_update(&timeout);
817
818 if (result) {
819 DEBUG("Write completed immediately");
820 bytes_written = write_size;
821 } else if (GetLastError() == ERROR_IO_PENDING) {
822 DEBUG("Waiting for write to complete");
823 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
824 if (GetLastError() == ERROR_SEM_TIMEOUT) {
825 DEBUG("Write timed out");
826 break;
827 } else {
828 RETURN_FAIL("GetOverlappedResult() failed");
829 }
aee7d691 830 }
060d1d8a
ML
831 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, write_size);
832 } else {
833 RETURN_FAIL("WriteFile() failed");
aee7d691 834 }
060d1d8a
ML
835
836 write_ptr += bytes_written;
837 total_bytes_written += bytes_written;
e3dcf906 838 }
060d1d8a
ML
839
840 RETURN_INT(total_bytes_written);
e3dcf906
ML
841#else
842 size_t bytes_written = 0;
843 unsigned char *ptr = (unsigned char *) buf;
32dbe2d2 844 struct timeout timeout;
e3dcf906
ML
845 fd_set fds;
846 int result;
847
32dbe2d2 848 timeout_start(&timeout, timeout_ms);
e3dcf906 849
772c5861
ML
850 FD_ZERO(&fds);
851 FD_SET(port->fd, &fds);
852
e3dcf906 853 /* Loop until we have written the requested number of bytes. */
dc422c04 854 while (bytes_written < count) {
bd72614f
ML
855
856 if (timeout_check(&timeout))
32dbe2d2
ML
857 break;
858
859 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
bd72614f
ML
860
861 timeout_update(&timeout);
862
63a17c64
ML
863 if (result < 0) {
864 if (errno == EINTR) {
865 DEBUG("select() call was interrupted, repeating");
866 continue;
867 } else {
868 RETURN_FAIL("select() failed");
869 }
870 } else if (result == 0) {
c3cee38c
ML
871 /* Timeout has expired. */
872 break;
e3dcf906
ML
873 }
874
875 /* Do write. */
876 result = write(port->fd, ptr, count - bytes_written);
877
878 if (result < 0) {
879 if (errno == EAGAIN)
880 /* This shouldn't happen because we did a select() first, but handle anyway. */
881 continue;
882 else
883 /* This is an actual failure. */
884 RETURN_FAIL("write() failed");
885 }
886
887 bytes_written += result;
888 ptr += result;
889 }
890
c3cee38c
ML
891 if (bytes_written < count)
892 DEBUG("Write timed out");
893
9caa2e86 894 RETURN_INT(bytes_written);
e3dcf906
ML
895#endif
896}
897
970f279a
AJ
898SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
899 const void *buf, size_t count)
74510d4b 900{
c33efc48
ML
901 TRACE("%p, %p, %d", port, buf, count);
902
dec10e31 903 CHECK_OPEN_PORT();
74510d4b
ML
904
905 if (!buf)
c33efc48 906 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
74510d4b 907
7890cef6 908 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
ea667be7 909
a3cb91f5 910 if (count == 0)
9caa2e86 911 RETURN_INT(0);
a3cb91f5 912
74510d4b 913#ifdef _WIN32
39df7833 914 DWORD buf_bytes;
f92f1f0c 915
e3dcf906
ML
916 /* Check whether previous write is complete. */
917 if (port->writing) {
918 if (HasOverlappedIoCompleted(&port->write_ovl)) {
919 DEBUG("Previous write completed");
920 port->writing = 0;
921 } else {
922 DEBUG("Previous write not complete");
923 /* Can't take a new write until the previous one finishes. */
9caa2e86 924 RETURN_INT(0);
a3cb91f5 925 }
e3dcf906 926 }
a3cb91f5 927
e3dcf906 928 /* Set timeout. */
27a58c05
ML
929 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
930 port->timeouts.WriteTotalTimeoutConstant = 0;
931 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
932 RETURN_FAIL("SetCommTimeouts() failed");
933 }
e3dcf906 934
b457865b
ML
935 /* Reduce count if it exceeds the WriteFile limit. */
936 if (count > WRITEFILE_MAX_SIZE)
937 count = WRITEFILE_MAX_SIZE;
938
39df7833
ML
939 /* Copy data to our write buffer. */
940 buf_bytes = min(port->write_buf_size, count);
941 memcpy(port->write_buf, buf, buf_bytes);
942
943 /* Start asynchronous write. */
944 if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
945 if (GetLastError() == ERROR_IO_PENDING) {
946 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
947 DEBUG("Asynchronous write completed immediately");
948 else
949 DEBUG("Asynchronous write running");
e3dcf906 950 } else {
39df7833
ML
951 /* Actual failure of some kind. */
952 RETURN_FAIL("WriteFile() failed");
a3cb91f5
ML
953 }
954 }
955
9af8cff3 956 DEBUG("All bytes written immediately");
e3dcf906 957
39df7833 958 RETURN_INT(buf_bytes);
74510d4b
ML
959#else
960 /* Returns the number of bytes written, or -1 upon failure. */
961 ssize_t written = write(port->fd, buf, count);
f92f1f0c 962
55ab7e0b
ML
963 if (written < 0) {
964 if (errno == EAGAIN)
965 // Buffer is full, no bytes written.
966 RETURN_INT(0);
967 else
968 RETURN_FAIL("write() failed");
969 } else {
9caa2e86 970 RETURN_INT(written);
55ab7e0b 971 }
74510d4b
ML
972#endif
973}
974
94a314a8
ML
975#ifdef _WIN32
976/* Restart wait operation if buffer was emptied. */
977static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
978{
8ebfaf89
ML
979 DWORD errors;
980 COMSTAT comstat;
94a314a8 981
21ae5ce1
ML
982 if (bytes_read == 0)
983 RETURN_OK();
984
8ebfaf89
ML
985 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
986 RETURN_FAIL("ClearCommError() failed");
94a314a8 987
8ebfaf89 988 if (comstat.cbInQue == 0)
94a314a8
ML
989 TRY(restart_wait(port));
990
991 RETURN_OK();
992}
993#endif
994
970f279a 995SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1b91c6ea 996 size_t count, unsigned int timeout_ms)
e3dcf906 997{
1b91c6ea 998 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
e3dcf906
ML
999
1000 CHECK_OPEN_PORT();
1001
1002 if (!buf)
1003 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1004
1b91c6ea 1005 if (timeout_ms)
7890cef6 1006 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1b91c6ea 1007 count, port->name, timeout_ms);
e3dcf906 1008 else
7890cef6
ML
1009 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1010 count, port->name);
e3dcf906
ML
1011
1012 if (count == 0)
9caa2e86 1013 RETURN_INT(0);
e3dcf906
ML
1014
1015#ifdef _WIN32
1016 DWORD bytes_read = 0;
1017
1018 /* Set timeout. */
27a58c05 1019 if (port->timeouts.ReadIntervalTimeout != 0 ||
0188a545 1020 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
27a58c05
ML
1021 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1022 port->timeouts.ReadIntervalTimeout = 0;
0188a545 1023 port->timeouts.ReadTotalTimeoutMultiplier = 0;
27a58c05
ML
1024 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1025 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1026 RETURN_FAIL("SetCommTimeouts() failed");
1027 }
e3dcf906
ML
1028
1029 /* Start read. */
bbe566fe 1030 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
e3dcf906 1031 DEBUG("Read completed immediately");
6f1186aa 1032 bytes_read = count;
bbe566fe
ML
1033 } else if (GetLastError() == ERROR_IO_PENDING) {
1034 DEBUG("Waiting for read to complete");
27911925
ML
1035 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1036 RETURN_FAIL("GetOverlappedResult() failed");
bbe566fe
ML
1037 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1038 } else {
1039 RETURN_FAIL("ReadFile() failed");
6f1186aa
ML
1040 }
1041
94a314a8 1042 TRY(restart_wait_if_needed(port, bytes_read));
6f1186aa 1043
9caa2e86 1044 RETURN_INT(bytes_read);
6f1186aa 1045
e3dcf906
ML
1046#else
1047 size_t bytes_read = 0;
9a7945af 1048 unsigned char *ptr = (unsigned char *) buf;
32dbe2d2 1049 struct timeout timeout;
e3dcf906
ML
1050 fd_set fds;
1051 int result;
1052
32dbe2d2 1053 timeout_start(&timeout, timeout_ms);
e3dcf906 1054
772c5861
ML
1055 FD_ZERO(&fds);
1056 FD_SET(port->fd, &fds);
1057
e3dcf906 1058 /* Loop until we have the requested number of bytes. */
dc422c04 1059 while (bytes_read < count) {
bd72614f
ML
1060
1061 if (timeout_check(&timeout))
32dbe2d2
ML
1062 /* Timeout has expired. */
1063 break;
1064
1065 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
bd72614f
ML
1066
1067 timeout_update(&timeout);
1068
63a17c64
ML
1069 if (result < 0) {
1070 if (errno == EINTR) {
1071 DEBUG("select() call was interrupted, repeating");
1072 continue;
1073 } else {
1074 RETURN_FAIL("select() failed");
1075 }
1076 } else if (result == 0) {
c3cee38c
ML
1077 /* Timeout has expired. */
1078 break;
e3dcf906
ML
1079 }
1080
1081 /* Do read. */
1082 result = read(port->fd, ptr, count - bytes_read);
1083
1084 if (result < 0) {
1085 if (errno == EAGAIN)
76222ee5
ML
1086 /*
1087 * This shouldn't happen because we did a
1088 * select() first, but handle anyway.
1089 */
e3dcf906
ML
1090 continue;
1091 else
1092 /* This is an actual failure. */
1093 RETURN_FAIL("read() failed");
1094 }
1095
1096 bytes_read += result;
1097 ptr += result;
1098 }
1099
c3cee38c
ML
1100 if (bytes_read < count)
1101 DEBUG("Read timed out");
1102
9caa2e86 1103 RETURN_INT(bytes_read);
e3dcf906
ML
1104#endif
1105}
1106
e5c2630e
ML
1107SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1108 size_t count, unsigned int timeout_ms)
1109{
1110 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1111
1112 CHECK_OPEN_PORT();
1113
1114 if (!buf)
1115 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1116
1117 if (count == 0)
1118 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1119
1120 if (timeout_ms)
1121 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1122 count, port->name, timeout_ms);
1123 else
1124 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1125 count, port->name);
1126
1127#ifdef _WIN32
1128 DWORD bytes_read = 0;
1129
1130 /* If timeout_ms == 0, set maximum timeout. */
1131 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1132
1133 /* Set timeout. */
1134 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1135 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1136 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1137 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1138 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1139 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1140 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1141 RETURN_FAIL("SetCommTimeouts() failed");
1142 }
1143
1144 /* Loop until we have at least one byte, or timeout is reached. */
1145 while (bytes_read == 0) {
1146 /* Start read. */
888fb45d 1147 if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
e5c2630e 1148 DEBUG("Read completed immediately");
e5c2630e
ML
1149 } else if (GetLastError() == ERROR_IO_PENDING) {
1150 DEBUG("Waiting for read to complete");
1151 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1152 RETURN_FAIL("GetOverlappedResult() failed");
1153 if (bytes_read > 0) {
1154 DEBUG("Read completed");
1155 } else if (timeout_ms > 0) {
1156 DEBUG("Read timed out");
1157 break;
1158 } else {
1159 DEBUG("Restarting read");
1160 }
1161 } else {
1162 RETURN_FAIL("ReadFile() failed");
1163 }
1164 }
1165
1166 TRY(restart_wait_if_needed(port, bytes_read));
1167
1168 RETURN_INT(bytes_read);
1169
1170#else
1171 size_t bytes_read = 0;
32dbe2d2 1172 struct timeout timeout;
e5c2630e
ML
1173 fd_set fds;
1174 int result;
1175
32dbe2d2 1176 timeout_start(&timeout, timeout_ms);
e5c2630e
ML
1177
1178 FD_ZERO(&fds);
1179 FD_SET(port->fd, &fds);
1180
1181 /* Loop until we have at least one byte, or timeout is reached. */
1182 while (bytes_read == 0) {
bd72614f
ML
1183
1184 if (timeout_check(&timeout))
32dbe2d2
ML
1185 /* Timeout has expired. */
1186 break;
1187
1188 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
bd72614f
ML
1189
1190 timeout_update(&timeout);
1191
e5c2630e
ML
1192 if (result < 0) {
1193 if (errno == EINTR) {
1194 DEBUG("select() call was interrupted, repeating");
1195 continue;
1196 } else {
1197 RETURN_FAIL("select() failed");
1198 }
1199 } else if (result == 0) {
1200 /* Timeout has expired. */
1201 break;
1202 }
1203
1204 /* Do read. */
1205 result = read(port->fd, buf, count);
1206
1207 if (result < 0) {
1208 if (errno == EAGAIN)
1209 /* This shouldn't happen because we did a select() first, but handle anyway. */
1210 continue;
1211 else
1212 /* This is an actual failure. */
1213 RETURN_FAIL("read() failed");
1214 }
1215
1216 bytes_read = result;
1217 }
1218
1219 if (bytes_read == 0)
1220 DEBUG("Read timed out");
1221
1222 RETURN_INT(bytes_read);
1223#endif
1224}
1225
970f279a
AJ
1226SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1227 size_t count)
74510d4b 1228{
c33efc48
ML
1229 TRACE("%p, %p, %d", port, buf, count);
1230
dec10e31 1231 CHECK_OPEN_PORT();
74510d4b
ML
1232
1233 if (!buf)
c33efc48 1234 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
74510d4b 1235
7890cef6 1236 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
ea667be7 1237
74510d4b 1238#ifdef _WIN32
e3dcf906 1239 DWORD bytes_read;
f92f1f0c 1240
e3dcf906 1241 /* Set timeout. */
27a58c05 1242 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
0188a545 1243 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
27a58c05
ML
1244 port->timeouts.ReadTotalTimeoutConstant != 0) {
1245 port->timeouts.ReadIntervalTimeout = MAXDWORD;
0188a545 1246 port->timeouts.ReadTotalTimeoutMultiplier = 0;
27a58c05
ML
1247 port->timeouts.ReadTotalTimeoutConstant = 0;
1248 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1249 RETURN_FAIL("SetCommTimeouts() failed");
1250 }
e3dcf906
ML
1251
1252 /* Do read. */
1253 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
ae2c5825
ML
1254 if (GetLastError() != ERROR_IO_PENDING)
1255 RETURN_FAIL("ReadFile() failed");
e3dcf906
ML
1256
1257 /* Get number of bytes read. */
ae2c5825 1258 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1622ef60 1259 RETURN_FAIL("GetOverlappedResult() failed");
e3dcf906 1260
94a314a8 1261 TRY(restart_wait_if_needed(port, bytes_read));
6f1186aa 1262
9caa2e86 1263 RETURN_INT(bytes_read);
74510d4b
ML
1264#else
1265 ssize_t bytes_read;
f92f1f0c 1266
74510d4b 1267 /* Returns the number of bytes read, or -1 upon failure. */
33d5ff47 1268 if ((bytes_read = read(port->fd, buf, count)) < 0) {
e3dcf906
ML
1269 if (errno == EAGAIN)
1270 /* No bytes available. */
33d5ff47
ML
1271 bytes_read = 0;
1272 else
1273 /* This is an actual failure. */
1274 RETURN_FAIL("read() failed");
1275 }
9caa2e86 1276 RETURN_INT(bytes_read);
74510d4b
ML
1277#endif
1278}
1279
970f279a 1280SP_API enum sp_return sp_input_waiting(struct sp_port *port)
3353c22f
ML
1281{
1282 TRACE("%p", port);
1283
1284 CHECK_OPEN_PORT();
1285
7890cef6 1286 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
3353c22f
ML
1287
1288#ifdef _WIN32
1289 DWORD errors;
1290 COMSTAT comstat;
1291
1292 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1a2a1544 1293 RETURN_FAIL("ClearCommError() failed");
9caa2e86 1294 RETURN_INT(comstat.cbInQue);
3353c22f
ML
1295#else
1296 int bytes_waiting;
1297 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1298 RETURN_FAIL("TIOCINQ ioctl failed");
9caa2e86 1299 RETURN_INT(bytes_waiting);
3353c22f
ML
1300#endif
1301}
1302
970f279a 1303SP_API enum sp_return sp_output_waiting(struct sp_port *port)
3353c22f
ML
1304{
1305 TRACE("%p", port);
1306
1307 CHECK_OPEN_PORT();
1308
7890cef6 1309 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
3353c22f
ML
1310
1311#ifdef _WIN32
1312 DWORD errors;
1313 COMSTAT comstat;
1314
1315 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1a2a1544 1316 RETURN_FAIL("ClearCommError() failed");
9caa2e86 1317 RETURN_INT(comstat.cbOutQue);
3353c22f
ML
1318#else
1319 int bytes_waiting;
1320 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1321 RETURN_FAIL("TIOCOUTQ ioctl failed");
9caa2e86 1322 RETURN_INT(bytes_waiting);
3353c22f
ML
1323#endif
1324}
1325
970f279a 1326SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
6f1186aa
ML
1327{
1328 struct sp_event_set *result;
1329
1330 TRACE("%p", result_ptr);
1331
1332 if (!result_ptr)
1333 RETURN_ERROR(SP_ERR_ARG, "Null result");
1334
1335 *result_ptr = NULL;
1336
1337 if (!(result = malloc(sizeof(struct sp_event_set))))
1338 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1339
1340 memset(result, 0, sizeof(struct sp_event_set));
1341
1342 *result_ptr = result;
1343
1344 RETURN_OK();
1345}
1346
1347static enum sp_return add_handle(struct sp_event_set *event_set,
1348 event_handle handle, enum sp_event mask)
1349{
1350 void *new_handles;
1351 enum sp_event *new_masks;
1352
1353 TRACE("%p, %d, %d", event_set, handle, mask);
1354
1355 if (!(new_handles = realloc(event_set->handles,
1356 sizeof(event_handle) * (event_set->count + 1))))
dc422c04 1357 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
6f1186aa 1358
ac323d80
UH
1359 event_set->handles = new_handles;
1360
6f1186aa 1361 if (!(new_masks = realloc(event_set->masks,
ac323d80 1362 sizeof(enum sp_event) * (event_set->count + 1))))
dc422c04 1363 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
6f1186aa 1364
6f1186aa
ML
1365 event_set->masks = new_masks;
1366
1367 ((event_handle *) event_set->handles)[event_set->count] = handle;
1368 event_set->masks[event_set->count] = mask;
1369
1370 event_set->count++;
1371
1372 RETURN_OK();
1373}
1374
970f279a 1375SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
6f1186aa
ML
1376 const struct sp_port *port, enum sp_event mask)
1377{
1378 TRACE("%p, %p, %d", event_set, port, mask);
1379
1380 if (!event_set)
1381 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1382
1383 if (!port)
1384 RETURN_ERROR(SP_ERR_ARG, "Null port");
1385
1386 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1387 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1388
1389 if (!mask)
1390 RETURN_OK();
1391
1392#ifdef _WIN32
1393 enum sp_event handle_mask;
1394 if ((handle_mask = mask & SP_EVENT_TX_READY))
1395 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1396 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1397 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1398#else
1399 TRY(add_handle(event_set, port->fd, mask));
1400#endif
1401
1402 RETURN_OK();
1403}
1404
970f279a 1405SP_API void sp_free_event_set(struct sp_event_set *event_set)
6f1186aa
ML
1406{
1407 TRACE("%p", event_set);
1408
1409 if (!event_set) {
1410 DEBUG("Null event set");
1411 RETURN();
1412 }
1413
1414 DEBUG("Freeing event set");
1415
1416 if (event_set->handles)
1417 free(event_set->handles);
1418 if (event_set->masks)
1419 free(event_set->masks);
1420
1421 free(event_set);
1422
1423 RETURN();
1424}
1425
970f279a 1426SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1b91c6ea 1427 unsigned int timeout_ms)
6f1186aa 1428{
1b91c6ea 1429 TRACE("%p, %d", event_set, timeout_ms);
6f1186aa
ML
1430
1431 if (!event_set)
1432 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1433
1434#ifdef _WIN32
1435 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1b91c6ea 1436 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
6f1186aa
ML
1437 RETURN_FAIL("WaitForMultipleObjects() failed");
1438
1439 RETURN_OK();
1440#else
32dbe2d2 1441 struct timeout timeout;
bd72614f 1442 int result;
6f1186aa
ML
1443 struct pollfd *pollfds;
1444 unsigned int i;
1445
1446 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1447 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1448
1449 for (i = 0; i < event_set->count; i++) {
81243567 1450 pollfds[i].fd = ((int *)event_set->handles)[i];
6f1186aa
ML
1451 pollfds[i].events = 0;
1452 pollfds[i].revents = 0;
1453 if (event_set->masks[i] & SP_EVENT_RX_READY)
1454 pollfds[i].events |= POLLIN;
1455 if (event_set->masks[i] & SP_EVENT_TX_READY)
1456 pollfds[i].events |= POLLOUT;
1457 if (event_set->masks[i] & SP_EVENT_ERROR)
1458 pollfds[i].events |= POLLERR;
1459 }
1460
32dbe2d2 1461 timeout_start(&timeout, timeout_ms);
08eb25f5 1462 timeout_limit(&timeout, INT_MAX);
6f1186aa
ML
1463
1464 /* Loop until an event occurs. */
dc422c04 1465 while (1) {
bd72614f
ML
1466
1467 if (timeout_check(&timeout)) {
32dbe2d2
ML
1468 DEBUG("Wait timed out");
1469 break;
6f1186aa
ML
1470 }
1471
9d1ca7c8 1472 result = poll(pollfds, event_set->count, timeout_remaining_ms(&timeout) || -1);
bd72614f
ML
1473
1474 timeout_update(&timeout);
6f1186aa
ML
1475
1476 if (result < 0) {
1477 if (errno == EINTR) {
1478 DEBUG("poll() call was interrupted, repeating");
1479 continue;
1480 } else {
1481 free(pollfds);
1482 RETURN_FAIL("poll() failed");
1483 }
1484 } else if (result == 0) {
1485 DEBUG("poll() timed out");
32dbe2d2 1486 if (!timeout.overflow)
127d8d0c 1487 break;
6f1186aa
ML
1488 } else {
1489 DEBUG("poll() completed");
1490 break;
1491 }
1492 }
1493
1494 free(pollfds);
1495 RETURN_OK();
1496#endif
1497}
1498
5cea279a 1499#ifdef USE_TERMIOS_SPEED
7a6d2196
ML
1500static enum sp_return get_baudrate(int fd, int *baudrate)
1501{
1502 void *data;
1503
c33efc48
ML
1504 TRACE("%d, %p", fd, baudrate);
1505
ea667be7
ML
1506 DEBUG("Getting baud rate");
1507
7a6d2196 1508 if (!(data = malloc(get_termios_size())))
c33efc48 1509 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
7a6d2196 1510
8d43110a
ML
1511 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1512 free(data);
dc422c04 1513 RETURN_FAIL("Getting termios failed");
8d43110a 1514 }
7a6d2196
ML
1515
1516 *baudrate = get_termios_speed(data);
1517
8d43110a
ML
1518 free(data);
1519
c33efc48 1520 RETURN_OK();
7a6d2196
ML
1521}
1522
1523static enum sp_return set_baudrate(int fd, int baudrate)
1524{
1525 void *data;
1526
c33efc48
ML
1527 TRACE("%d, %d", fd, baudrate);
1528
ea667be7
ML
1529 DEBUG("Getting baud rate");
1530
7a6d2196 1531 if (!(data = malloc(get_termios_size())))
c33efc48 1532 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
7a6d2196 1533
8d43110a
ML
1534 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1535 free(data);
dc422c04 1536 RETURN_FAIL("Getting termios failed");
8d43110a 1537 }
7a6d2196 1538
ea667be7
ML
1539 DEBUG("Setting baud rate");
1540
7a6d2196
ML
1541 set_termios_speed(data, baudrate);
1542
8d43110a
ML
1543 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1544 free(data);
dc422c04 1545 RETURN_FAIL("Setting termios failed");
8d43110a
ML
1546 }
1547
1548 free(data);
7a6d2196 1549
c33efc48 1550 RETURN_OK();
7a6d2196 1551}
5cea279a 1552#endif /* USE_TERMIOS_SPEED */
40978c2b
ML
1553
1554#ifdef USE_TERMIOX
bd791fe1 1555static enum sp_return get_flow(int fd, struct port_data *data)
40978c2b 1556{
bd791fe1 1557 void *termx;
40978c2b 1558
bd791fe1 1559 TRACE("%d, %p", fd, data);
c33efc48 1560
ea667be7
ML
1561 DEBUG("Getting advanced flow control");
1562
bd791fe1 1563 if (!(termx = malloc(get_termiox_size())))
c33efc48 1564 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
40978c2b 1565
bd791fe1
ML
1566 if (ioctl(fd, TCGETX, termx) < 0) {
1567 free(termx);
dc422c04 1568 RETURN_FAIL("Getting termiox failed");
8d43110a 1569 }
40978c2b 1570
bd791fe1
ML
1571 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1572 &data->dtr_flow, &data->dsr_flow);
40978c2b 1573
bd791fe1 1574 free(termx);
8d43110a 1575
c33efc48 1576 RETURN_OK();
40978c2b
ML
1577}
1578
bd791fe1 1579static enum sp_return set_flow(int fd, struct port_data *data)
40978c2b 1580{
bd791fe1 1581 void *termx;
40978c2b 1582
bd791fe1 1583 TRACE("%d, %p", fd, data);
c33efc48 1584
ea667be7
ML
1585 DEBUG("Getting advanced flow control");
1586
bd791fe1 1587 if (!(termx = malloc(get_termiox_size())))
c33efc48 1588 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
40978c2b 1589
bd791fe1
ML
1590 if (ioctl(fd, TCGETX, termx) < 0) {
1591 free(termx);
dc422c04 1592 RETURN_FAIL("Getting termiox failed");
8d43110a 1593 }
40978c2b 1594
ea667be7
ML
1595 DEBUG("Setting advanced flow control");
1596
bd791fe1
ML
1597 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1598 data->dtr_flow, data->dsr_flow);
40978c2b 1599
bd791fe1
ML
1600 if (ioctl(fd, TCSETX, termx) < 0) {
1601 free(termx);
dc422c04 1602 RETURN_FAIL("Setting termiox failed");
8d43110a
ML
1603 }
1604
bd791fe1 1605 free(termx);
40978c2b 1606
c33efc48 1607 RETURN_OK();
40978c2b
ML
1608}
1609#endif /* USE_TERMIOX */
7a6d2196 1610
eb6ed20f
ML
1611static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1612 struct sp_port_config *config)
8094e4a0 1613{
da2748bf 1614 unsigned int i;
cbf628c7 1615
c33efc48
ML
1616 TRACE("%p, %p, %p", port, data, config);
1617
7890cef6 1618 DEBUG_FMT("Getting configuration for port %s", port->name);
ea667be7 1619
8094e4a0 1620#ifdef _WIN32
e33ab9aa 1621 if (!GetCommState(port->hdl, &data->dcb))
c33efc48 1622 RETURN_FAIL("GetCommState() failed");
8094e4a0 1623
067417af 1624 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
e33ab9aa 1625 if (data->dcb.BaudRate == std_baudrates[i].index) {
067417af
ML
1626 config->baudrate = std_baudrates[i].value;
1627 break;
1628 }
1629 }
1630
1631 if (i == NUM_STD_BAUDRATES)
1632 /* BaudRate field can be either an index or a custom baud rate. */
e33ab9aa 1633 config->baudrate = data->dcb.BaudRate;
067417af 1634
e33ab9aa 1635 config->bits = data->dcb.ByteSize;
067417af 1636
e33ab9aa
ML
1637 if (data->dcb.fParity)
1638 switch (data->dcb.Parity) {
067417af
ML
1639 case NOPARITY:
1640 config->parity = SP_PARITY_NONE;
1641 break;
e432ce60
ML
1642 case ODDPARITY:
1643 config->parity = SP_PARITY_ODD;
1644 break;
067417af
ML
1645 case EVENPARITY:
1646 config->parity = SP_PARITY_EVEN;
1647 break;
e432ce60
ML
1648 case MARKPARITY:
1649 config->parity = SP_PARITY_MARK;
1650 break;
1651 case SPACEPARITY:
1652 config->parity = SP_PARITY_SPACE;
067417af
ML
1653 break;
1654 default:
1655 config->parity = -1;
1656 }
1657 else
1658 config->parity = SP_PARITY_NONE;
1659
e33ab9aa 1660 switch (data->dcb.StopBits) {
067417af
ML
1661 case ONESTOPBIT:
1662 config->stopbits = 1;
1663 break;
1664 case TWOSTOPBITS:
1665 config->stopbits = 2;
1666 break;
1667 default:
1668 config->stopbits = -1;
1669 }
1670
e33ab9aa 1671 switch (data->dcb.fRtsControl) {
eac329d2
UH
1672 case RTS_CONTROL_DISABLE:
1673 config->rts = SP_RTS_OFF;
1674 break;
1675 case RTS_CONTROL_ENABLE:
1676 config->rts = SP_RTS_ON;
1677 break;
1678 case RTS_CONTROL_HANDSHAKE:
1679 config->rts = SP_RTS_FLOW_CONTROL;
1680 break;
1681 default:
1682 config->rts = -1;
067417af
ML
1683 }
1684
e33ab9aa 1685 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
067417af 1686
e33ab9aa 1687 switch (data->dcb.fDtrControl) {
eac329d2
UH
1688 case DTR_CONTROL_DISABLE:
1689 config->dtr = SP_DTR_OFF;
1690 break;
1691 case DTR_CONTROL_ENABLE:
1692 config->dtr = SP_DTR_ON;
1693 break;
1694 case DTR_CONTROL_HANDSHAKE:
1695 config->dtr = SP_DTR_FLOW_CONTROL;
1696 break;
1697 default:
1698 config->dtr = -1;
067417af
ML
1699 }
1700
e33ab9aa
ML
1701 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1702
c6754b45
ML
1703 if (data->dcb.fInX) {
1704 if (data->dcb.fOutX)
1705 config->xon_xoff = SP_XONXOFF_INOUT;
1706 else
1707 config->xon_xoff = SP_XONXOFF_IN;
1708 } else {
1709 if (data->dcb.fOutX)
1710 config->xon_xoff = SP_XONXOFF_OUT;
1711 else
1712 config->xon_xoff = SP_XONXOFF_DISABLED;
1713 }
1714
e33ab9aa
ML
1715#else // !_WIN32
1716
1717 if (tcgetattr(port->fd, &data->term) < 0)
c33efc48 1718 RETURN_FAIL("tcgetattr() failed");
e33ab9aa
ML
1719
1720 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
c33efc48 1721 RETURN_FAIL("TIOCMGET ioctl failed");
40978c2b
ML
1722
1723#ifdef USE_TERMIOX
bd791fe1 1724 int ret = get_flow(port->fd, data);
68ec29db
ML
1725
1726 if (ret == SP_ERR_FAIL && errno == EINVAL)
1727 data->termiox_supported = 0;
1728 else if (ret < 0)
c33efc48 1729 RETURN_CODEVAL(ret);
68ec29db
ML
1730 else
1731 data->termiox_supported = 1;
1732#else
1733 data->termiox_supported = 0;
40978c2b
ML
1734#endif
1735
067417af 1736 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
e33ab9aa 1737 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
067417af
ML
1738 config->baudrate = std_baudrates[i].value;
1739 break;
1740 }
1741 }
1742
31b3a8f5
MH
1743 if (i == NUM_STD_BAUDRATES) {
1744#ifdef __APPLE__
1745 config->baudrate = (int)data->term.c_ispeed;
5cea279a 1746#elif defined(USE_TERMIOS_SPEED)
7a6d2196 1747 TRY(get_baudrate(port->fd, &config->baudrate));
31b3a8f5 1748#else
067417af 1749 config->baudrate = -1;
31b3a8f5
MH
1750#endif
1751 }
067417af 1752
e33ab9aa 1753 switch (data->term.c_cflag & CSIZE) {
067417af
ML
1754 case CS8:
1755 config->bits = 8;
1756 break;
1757 case CS7:
1758 config->bits = 7;
1759 break;
1760 case CS6:
1761 config->bits = 6;
1762 break;
1763 case CS5:
1764 config->bits = 5;
1765 break;
1766 default:
1767 config->bits = -1;
1768 }
1769
e33ab9aa 1770 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
067417af 1771 config->parity = SP_PARITY_NONE;
e33ab9aa 1772 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
067417af 1773 config->parity = -1;
c3e05092 1774#ifdef CMSPAR
e432ce60
ML
1775 else if (data->term.c_cflag & CMSPAR)
1776 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
c3e05092 1777#endif
067417af 1778 else
e33ab9aa 1779 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
067417af 1780
e33ab9aa 1781 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
067417af 1782
e33ab9aa 1783 if (data->term.c_cflag & CRTSCTS) {
067417af
ML
1784 config->rts = SP_RTS_FLOW_CONTROL;
1785 config->cts = SP_CTS_FLOW_CONTROL;
1786 } else {
bd791fe1 1787 if (data->termiox_supported && data->rts_flow)
40978c2b
ML
1788 config->rts = SP_RTS_FLOW_CONTROL;
1789 else
1790 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1791
bd791fe1 1792 config->cts = (data->termiox_supported && data->cts_flow) ?
68ec29db 1793 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
067417af
ML
1794 }
1795
bd791fe1 1796 if (data->termiox_supported && data->dtr_flow)
40978c2b
ML
1797 config->dtr = SP_DTR_FLOW_CONTROL;
1798 else
1799 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1800
bd791fe1 1801 config->dsr = (data->termiox_supported && data->dsr_flow) ?
68ec29db 1802 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
705bdc69 1803
e29b93a5
ML
1804 if (data->term.c_iflag & IXOFF) {
1805 if (data->term.c_iflag & IXON)
1806 config->xon_xoff = SP_XONXOFF_INOUT;
1807 else
1808 config->xon_xoff = SP_XONXOFF_IN;
1809 } else {
1810 if (data->term.c_iflag & IXON)
1811 config->xon_xoff = SP_XONXOFF_OUT;
1812 else
1813 config->xon_xoff = SP_XONXOFF_DISABLED;
1814 }
067417af
ML
1815#endif
1816
c33efc48 1817 RETURN_OK();
067417af
ML
1818}
1819
7a6d2196 1820static enum sp_return set_config(struct sp_port *port, struct port_data *data,
eb6ed20f 1821 const struct sp_port_config *config)
18fc2dd1 1822{
e33ab9aa 1823 unsigned int i;
31b3a8f5
MH
1824#ifdef __APPLE__
1825 BAUD_TYPE baud_nonstd;
1826
1827 baud_nonstd = B0;
1828#endif
5cea279a 1829#ifdef USE_TERMIOS_SPEED
7a6d2196
ML
1830 int baud_nonstd = 0;
1831#endif
18fc2dd1 1832
c33efc48
ML
1833 TRACE("%p, %p, %p", port, data, config);
1834
7890cef6 1835 DEBUG_FMT("Setting configuration for port %s", port->name);
ea667be7 1836
e33ab9aa 1837#ifdef _WIN32
6bd6a8b5
ML
1838
1839 TRY(await_write_completion(port));
1840
eac329d2 1841 if (config->baudrate >= 0) {
e33ab9aa
ML
1842 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1843 if (config->baudrate == std_baudrates[i].value) {
1844 data->dcb.BaudRate = std_baudrates[i].index;
1845 break;
1846 }
1847 }
18fc2dd1 1848
e33ab9aa
ML
1849 if (i == NUM_STD_BAUDRATES)
1850 data->dcb.BaudRate = config->baudrate;
39df7833
ML
1851
1852 /* Allocate write buffer for 50ms of data at baud rate. */
1853 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
1854 port->write_buf = realloc(port->write_buf,
1855 port->write_buf_size);
1856
1857 if (!port->write_buf)
1858 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
e33ab9aa 1859 }
18fc2dd1 1860
e33ab9aa
ML
1861 if (config->bits >= 0)
1862 data->dcb.ByteSize = config->bits;
1863
1864 if (config->parity >= 0) {
1865 switch (config->parity) {
e33ab9aa
ML
1866 case SP_PARITY_NONE:
1867 data->dcb.Parity = NOPARITY;
1868 break;
e432ce60
ML
1869 case SP_PARITY_ODD:
1870 data->dcb.Parity = ODDPARITY;
1871 break;
e33ab9aa
ML
1872 case SP_PARITY_EVEN:
1873 data->dcb.Parity = EVENPARITY;
1874 break;
e432ce60
ML
1875 case SP_PARITY_MARK:
1876 data->dcb.Parity = MARKPARITY;
1877 break;
1878 case SP_PARITY_SPACE:
1879 data->dcb.Parity = SPACEPARITY;
e33ab9aa
ML
1880 break;
1881 default:
c33efc48 1882 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
e33ab9aa 1883 }
18fc2dd1
ML
1884 }
1885
e33ab9aa
ML
1886 if (config->stopbits >= 0) {
1887 switch (config->stopbits) {
1888 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1889 case 1:
1890 data->dcb.StopBits = ONESTOPBIT;
1891 break;
1892 case 2:
1893 data->dcb.StopBits = TWOSTOPBITS;
1894 break;
1895 default:
c33efc48 1896 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
e33ab9aa
ML
1897 }
1898 }
1899
1900 if (config->rts >= 0) {
1901 switch (config->rts) {
1902 case SP_RTS_OFF:
1903 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1904 break;
1905 case SP_RTS_ON:
1906 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1907 break;
1908 case SP_RTS_FLOW_CONTROL:
1909 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1910 break;
1911 default:
c33efc48 1912 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
e33ab9aa
ML
1913 }
1914 }
1915
1916 if (config->cts >= 0) {
1917 switch (config->cts) {
1918 case SP_CTS_IGNORE:
1919 data->dcb.fOutxCtsFlow = FALSE;
1920 break;
1921 case SP_CTS_FLOW_CONTROL:
1922 data->dcb.fOutxCtsFlow = TRUE;
1923 break;
1924 default:
c33efc48 1925 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
e33ab9aa
ML
1926 }
1927 }
1928
1929 if (config->dtr >= 0) {
1930 switch (config->dtr) {
1931 case SP_DTR_OFF:
1932 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1933 break;
1934 case SP_DTR_ON:
1935 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1936 break;
1937 case SP_DTR_FLOW_CONTROL:
1938 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1939 break;
1940 default:
c33efc48 1941 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
e33ab9aa
ML
1942 }
1943 }
1944
1945 if (config->dsr >= 0) {
1946 switch (config->dsr) {
1947 case SP_DSR_IGNORE:
1948 data->dcb.fOutxDsrFlow = FALSE;
1949 break;
1950 case SP_DSR_FLOW_CONTROL:
1951 data->dcb.fOutxDsrFlow = TRUE;
1952 break;
1953 default:
c33efc48 1954 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
e33ab9aa 1955 }
18fc2dd1
ML
1956 }
1957
e33ab9aa
ML
1958 if (config->xon_xoff >= 0) {
1959 switch (config->xon_xoff) {
1960 case SP_XONXOFF_DISABLED:
1961 data->dcb.fInX = FALSE;
1962 data->dcb.fOutX = FALSE;
1963 break;
1964 case SP_XONXOFF_IN:
1965 data->dcb.fInX = TRUE;
1966 data->dcb.fOutX = FALSE;
1967 break;
1968 case SP_XONXOFF_OUT:
1969 data->dcb.fInX = FALSE;
1970 data->dcb.fOutX = TRUE;
1971 break;
1972 case SP_XONXOFF_INOUT:
1973 data->dcb.fInX = TRUE;
1974 data->dcb.fOutX = TRUE;
1975 break;
1976 default:
c33efc48 1977 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
e33ab9aa
ML
1978 }
1979 }
1980
1981 if (!SetCommState(port->hdl, &data->dcb))
c33efc48 1982 RETURN_FAIL("SetCommState() failed");
e33ab9aa 1983
31b3a8f5 1984#else /* !_WIN32 */
e33ab9aa 1985
7a6d2196
ML
1986 int controlbits;
1987
eac329d2 1988 if (config->baudrate >= 0) {
e33ab9aa
ML
1989 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1990 if (config->baudrate == std_baudrates[i].value) {
1991 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
c33efc48 1992 RETURN_FAIL("cfsetospeed() failed");
e33ab9aa
ML
1993
1994 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
c33efc48 1995 RETURN_FAIL("cfsetispeed() failed");
e33ab9aa
ML
1996 break;
1997 }
1998 }
1999
31b3a8f5
MH
2000 /* Non-standard baud rate */
2001 if (i == NUM_STD_BAUDRATES) {
2002#ifdef __APPLE__
24abdb68 2003 /* Set "dummy" baud rate. */
31b3a8f5 2004 if (cfsetspeed(&data->term, B9600) < 0)
c33efc48 2005 RETURN_FAIL("cfsetspeed() failed");
31b3a8f5 2006 baud_nonstd = config->baudrate;
5cea279a 2007#elif defined(USE_TERMIOS_SPEED)
7a6d2196 2008 baud_nonstd = 1;
31b3a8f5 2009#else
c33efc48 2010 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
31b3a8f5
MH
2011#endif
2012 }
e33ab9aa
ML
2013 }
2014
2015 if (config->bits >= 0) {
2016 data->term.c_cflag &= ~CSIZE;
2017 switch (config->bits) {
2018 case 8:
2019 data->term.c_cflag |= CS8;
2020 break;
2021 case 7:
2022 data->term.c_cflag |= CS7;
2023 break;
2024 case 6:
2025 data->term.c_cflag |= CS6;
2026 break;
23922313
UH
2027 case 5:
2028 data->term.c_cflag |= CS5;
2029 break;
e33ab9aa 2030 default:
c33efc48 2031 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
e33ab9aa
ML
2032 }
2033 }
2034
2035 if (config->parity >= 0) {
2036 data->term.c_iflag &= ~IGNPAR;
c3e05092
UH
2037 data->term.c_cflag &= ~(PARENB | PARODD);
2038#ifdef CMSPAR
2039 data->term.c_cflag &= ~CMSPAR;
2040#endif
e33ab9aa
ML
2041 switch (config->parity) {
2042 case SP_PARITY_NONE:
2043 data->term.c_iflag |= IGNPAR;
2044 break;
2045 case SP_PARITY_EVEN:
2046 data->term.c_cflag |= PARENB;
2047 break;
2048 case SP_PARITY_ODD:
2049 data->term.c_cflag |= PARENB | PARODD;
2050 break;
afb518f0 2051#ifdef CMSPAR
e432ce60 2052 case SP_PARITY_MARK:
c3e05092 2053 data->term.c_cflag |= PARENB | PARODD;
c3e05092 2054 data->term.c_cflag |= CMSPAR;
e432ce60
ML
2055 break;
2056 case SP_PARITY_SPACE:
c3e05092 2057 data->term.c_cflag |= PARENB;
c3e05092 2058 data->term.c_cflag |= CMSPAR;
e432ce60 2059 break;
afb518f0
ML
2060#else
2061 case SP_PARITY_MARK:
2062 case SP_PARITY_SPACE:
2063 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2064#endif
e33ab9aa 2065 default:
c33efc48 2066 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
e33ab9aa
ML
2067 }
2068 }
2069
2070 if (config->stopbits >= 0) {
2071 data->term.c_cflag &= ~CSTOPB;
2072 switch (config->stopbits) {
2073 case 1:
2074 data->term.c_cflag &= ~CSTOPB;
2075 break;
2076 case 2:
2077 data->term.c_cflag |= CSTOPB;
2078 break;
2079 default:
c33efc48 2080 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
e33ab9aa
ML
2081 }
2082 }
2083
eac329d2 2084 if (config->rts >= 0 || config->cts >= 0) {
68ec29db 2085 if (data->termiox_supported) {
bd791fe1 2086 data->rts_flow = data->cts_flow = 0;
68ec29db
ML
2087 switch (config->rts) {
2088 case SP_RTS_OFF:
2089 case SP_RTS_ON:
2090 controlbits = TIOCM_RTS;
2091 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
c33efc48 2092 RETURN_FAIL("Setting RTS signal level failed");
68ec29db
ML
2093 break;
2094 case SP_RTS_FLOW_CONTROL:
bd791fe1 2095 data->rts_flow = 1;
68ec29db
ML
2096 break;
2097 default:
2098 break;
e33ab9aa 2099 }
68ec29db 2100 if (config->cts == SP_CTS_FLOW_CONTROL)
bd791fe1 2101 data->cts_flow = 1;
e33ab9aa 2102
bd791fe1 2103 if (data->rts_flow && data->cts_flow)
e33ab9aa 2104 data->term.c_iflag |= CRTSCTS;
68ec29db
ML
2105 else
2106 data->term.c_iflag &= ~CRTSCTS;
2107 } else {
2108 /* Asymmetric use of RTS/CTS not supported. */
2109 if (data->term.c_iflag & CRTSCTS) {
2110 /* Flow control can only be disabled for both RTS & CTS together. */
2111 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2112 if (config->cts != SP_CTS_IGNORE)
c33efc48 2113 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
68ec29db
ML
2114 }
2115 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2116 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
c33efc48 2117 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
68ec29db 2118 }
e33ab9aa 2119 } else {
68ec29db
ML
2120 /* Flow control can only be enabled for both RTS & CTS together. */
2121 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2122 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
c33efc48 2123 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
68ec29db
ML
2124 }
2125
2126 if (config->rts >= 0) {
2127 if (config->rts == SP_RTS_FLOW_CONTROL) {
2128 data->term.c_iflag |= CRTSCTS;
2129 } else {
2130 controlbits = TIOCM_RTS;
2131 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2132 &controlbits) < 0)
c33efc48 2133 RETURN_FAIL("Setting RTS signal level failed");
68ec29db 2134 }
e33ab9aa
ML
2135 }
2136 }
2137 }
2138
eac329d2 2139 if (config->dtr >= 0 || config->dsr >= 0) {
68ec29db 2140 if (data->termiox_supported) {
bd791fe1 2141 data->dtr_flow = data->dsr_flow = 0;
68ec29db
ML
2142 switch (config->dtr) {
2143 case SP_DTR_OFF:
2144 case SP_DTR_ON:
2145 controlbits = TIOCM_DTR;
2146 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
c33efc48 2147 RETURN_FAIL("Setting DTR signal level failed");
68ec29db
ML
2148 break;
2149 case SP_DTR_FLOW_CONTROL:
bd791fe1 2150 data->dtr_flow = 1;
68ec29db
ML
2151 break;
2152 default:
2153 break;
2154 }
2155 if (config->dsr == SP_DSR_FLOW_CONTROL)
bd791fe1 2156 data->dsr_flow = 1;
68ec29db
ML
2157 } else {
2158 /* DTR/DSR flow control not supported. */
2159 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
c33efc48 2160 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
e33ab9aa 2161
68ec29db
ML
2162 if (config->dtr >= 0) {
2163 controlbits = TIOCM_DTR;
2164 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2165 &controlbits) < 0)
c33efc48 2166 RETURN_FAIL("Setting DTR signal level failed");
68ec29db 2167 }
e33ab9aa
ML
2168 }
2169 }
2170
2171 if (config->xon_xoff >= 0) {
2172 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2173 switch (config->xon_xoff) {
2174 case SP_XONXOFF_DISABLED:
2175 break;
2176 case SP_XONXOFF_IN:
2177 data->term.c_iflag |= IXOFF;
2178 break;
2179 case SP_XONXOFF_OUT:
2180 data->term.c_iflag |= IXON | IXANY;
2181 break;
2182 case SP_XONXOFF_INOUT:
2183 data->term.c_iflag |= IXON | IXOFF | IXANY;
2184 break;
2185 default:
c33efc48 2186 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
e33ab9aa
ML
2187 }
2188 }
2189
3f5c06d0 2190 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
c33efc48 2191 RETURN_FAIL("tcsetattr() failed");
31b3a8f5
MH
2192
2193#ifdef __APPLE__
2194 if (baud_nonstd != B0) {
2195 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
c33efc48 2196 RETURN_FAIL("IOSSIOSPEED ioctl failed");
dc422c04
UH
2197 /*
2198 * Set baud rates in data->term to correct, but incompatible
2199 * with tcsetattr() value, same as delivered by tcgetattr().
2200 */
31b3a8f5 2201 if (cfsetspeed(&data->term, baud_nonstd) < 0)
c33efc48 2202 RETURN_FAIL("cfsetspeed() failed");
31b3a8f5 2203 }
7a6d2196 2204#elif defined(__linux__)
5cea279a 2205#ifdef USE_TERMIOS_SPEED
7a6d2196
ML
2206 if (baud_nonstd)
2207 TRY(set_baudrate(port->fd, config->baudrate));
5cea279a 2208#endif
40978c2b 2209#ifdef USE_TERMIOX
68ec29db 2210 if (data->termiox_supported)
bd791fe1 2211 TRY(set_flow(port->fd, data));
40978c2b 2212#endif
7a6d2196 2213#endif
31b3a8f5
MH
2214
2215#endif /* !_WIN32 */
e33ab9aa 2216
c33efc48 2217 RETURN_OK();
e33ab9aa
ML
2218}
2219
970f279a 2220SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
9b1502ef 2221{
59131d60 2222 struct sp_port_config *config;
9b1502ef 2223
00d8c56d
UH
2224 TRACE("%p", config_ptr);
2225
9b1502ef
ML
2226 if (!config_ptr)
2227 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2228
59131d60
ML
2229 *config_ptr = NULL;
2230
2231 if (!(config = malloc(sizeof(struct sp_port_config))))
dc422c04 2232 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
9b1502ef 2233
59131d60
ML
2234 config->baudrate = -1;
2235 config->bits = -1;
2236 config->parity = -1;
2237 config->stopbits = -1;
2238 config->rts = -1;
2239 config->cts = -1;
2240 config->dtr = -1;
2241 config->dsr = -1;
2242
2243 *config_ptr = config;
2244
9b1502ef
ML
2245 RETURN_OK();
2246}
2247
970f279a 2248SP_API void sp_free_config(struct sp_port_config *config)
9b1502ef
ML
2249{
2250 TRACE("%p", config);
2251
2252 if (!config)
2253 DEBUG("Null config");
2254 else
2255 free(config);
2256
2257 RETURN();
2258}
2259
970f279a
AJ
2260SP_API enum sp_return sp_get_config(struct sp_port *port,
2261 struct sp_port_config *config)
70cd37de
ML
2262{
2263 struct port_data data;
2264
2265 TRACE("%p, %p", port, config);
2266
2267 CHECK_OPEN_PORT();
2268
2269 if (!config)
9b1502ef 2270 RETURN_ERROR(SP_ERR_ARG, "Null config");
70cd37de
ML
2271
2272 TRY(get_config(port, &data, config));
2273
2274 RETURN_OK();
2275}
2276
970f279a
AJ
2277SP_API enum sp_return sp_set_config(struct sp_port *port,
2278 const struct sp_port_config *config)
e33ab9aa 2279{
8f189c4c 2280 struct port_data data;
e33ab9aa
ML
2281 struct sp_port_config prev_config;
2282
c33efc48
ML
2283 TRACE("%p, %p", port, config);
2284
dec10e31 2285 CHECK_OPEN_PORT();
823690ae
ML
2286
2287 if (!config)
c33efc48 2288 RETURN_ERROR(SP_ERR_ARG, "Null config");
823690ae 2289
e33ab9aa
ML
2290 TRY(get_config(port, &data, &prev_config));
2291 TRY(set_config(port, &data, config));
74510d4b 2292
c33efc48 2293 RETURN_OK();
74510d4b
ML
2294}
2295
9b1502ef 2296#define CREATE_ACCESSORS(x, type) \
970f279a 2297SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
8f189c4c 2298 struct port_data data; \
e33ab9aa 2299 struct sp_port_config config; \
c33efc48 2300 TRACE("%p, %d", port, x); \
dec10e31 2301 CHECK_OPEN_PORT(); \
e33ab9aa
ML
2302 TRY(get_config(port, &data, &config)); \
2303 config.x = x; \
2304 TRY(set_config(port, &data, &config)); \
c33efc48 2305 RETURN_OK(); \
9b1502ef 2306} \
970f279a
AJ
2307SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2308 type *x) { \
00d8c56d 2309 TRACE("%p, %p", config, x); \
6aad5bdd
UH
2310 if (!x) \
2311 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
9b1502ef
ML
2312 if (!config) \
2313 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2314 *x = config->x; \
2315 RETURN_OK(); \
2316} \
970f279a
AJ
2317SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2318 type x) { \
9b1502ef
ML
2319 TRACE("%p, %d", config, x); \
2320 if (!config) \
2321 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2322 config->x = x; \
2323 RETURN_OK(); \
9069c2fb
ML
2324}
2325
9b1502ef
ML
2326CREATE_ACCESSORS(baudrate, int)
2327CREATE_ACCESSORS(bits, int)
2328CREATE_ACCESSORS(parity, enum sp_parity)
2329CREATE_ACCESSORS(stopbits, int)
2330CREATE_ACCESSORS(rts, enum sp_rts)
2331CREATE_ACCESSORS(cts, enum sp_cts)
2332CREATE_ACCESSORS(dtr, enum sp_dtr)
2333CREATE_ACCESSORS(dsr, enum sp_dsr)
2334CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2335
970f279a
AJ
2336SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2337 enum sp_flowcontrol flowcontrol)
e33ab9aa 2338{
9b1502ef
ML
2339 if (!config)
2340 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
dec10e31
ML
2341
2342 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2343 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
823690ae 2344
e33ab9aa 2345 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
9b1502ef 2346 config->xon_xoff = SP_XONXOFF_INOUT;
e33ab9aa 2347 else
9b1502ef 2348 config->xon_xoff = SP_XONXOFF_DISABLED;
e33ab9aa
ML
2349
2350 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
9b1502ef
ML
2351 config->rts = SP_RTS_FLOW_CONTROL;
2352 config->cts = SP_CTS_FLOW_CONTROL;
e33ab9aa 2353 } else {
9b1502ef
ML
2354 if (config->rts == SP_RTS_FLOW_CONTROL)
2355 config->rts = SP_RTS_ON;
2356 config->cts = SP_CTS_IGNORE;
e33ab9aa
ML
2357 }
2358
2359 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
9b1502ef
ML
2360 config->dtr = SP_DTR_FLOW_CONTROL;
2361 config->dsr = SP_DSR_FLOW_CONTROL;
e33ab9aa 2362 } else {
9b1502ef
ML
2363 if (config->dtr == SP_DTR_FLOW_CONTROL)
2364 config->dtr = SP_DTR_ON;
2365 config->dsr = SP_DSR_IGNORE;
e33ab9aa
ML
2366 }
2367
9b1502ef
ML
2368 RETURN_OK();
2369}
2370
970f279a
AJ
2371SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2372 enum sp_flowcontrol flowcontrol)
9b1502ef
ML
2373{
2374 struct port_data data;
2375 struct sp_port_config config;
2376
2377 TRACE("%p, %d", port, flowcontrol);
2378
2379 CHECK_OPEN_PORT();
2380
2381 TRY(get_config(port, &data, &config));
2382
2383 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2384
e33ab9aa
ML
2385 TRY(set_config(port, &data, &config));
2386
c33efc48 2387 RETURN_OK();
e33ab9aa
ML
2388}
2389
970f279a
AJ
2390SP_API enum sp_return sp_get_signals(struct sp_port *port,
2391 enum sp_signal *signals)
8cf7c697 2392{
c33efc48
ML
2393 TRACE("%p, %p", port, signals);
2394
dec10e31 2395 CHECK_OPEN_PORT();
8cf7c697
ML
2396
2397 if (!signals)
c33efc48 2398 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
8cf7c697 2399
7890cef6 2400 DEBUG_FMT("Getting control signals for port %s", port->name);
ea667be7 2401
8cf7c697
ML
2402 *signals = 0;
2403#ifdef _WIN32
2404 DWORD bits;
2405 if (GetCommModemStatus(port->hdl, &bits) == 0)
c33efc48 2406 RETURN_FAIL("GetCommModemStatus() failed");
8cf7c697
ML
2407 if (bits & MS_CTS_ON)
2408 *signals |= SP_SIG_CTS;
2409 if (bits & MS_DSR_ON)
2410 *signals |= SP_SIG_DSR;
8cf7c697 2411 if (bits & MS_RLSD_ON)
a6cda1e8
ML
2412 *signals |= SP_SIG_DCD;
2413 if (bits & MS_RING_ON)
8cf7c697
ML
2414 *signals |= SP_SIG_RI;
2415#else
2416 int bits;
2417 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
c33efc48 2418 RETURN_FAIL("TIOCMGET ioctl failed");
8cf7c697
ML
2419 if (bits & TIOCM_CTS)
2420 *signals |= SP_SIG_CTS;
2421 if (bits & TIOCM_DSR)
2422 *signals |= SP_SIG_DSR;
2423 if (bits & TIOCM_CAR)
2424 *signals |= SP_SIG_DCD;
2425 if (bits & TIOCM_RNG)
2426 *signals |= SP_SIG_RI;
2427#endif
c33efc48 2428 RETURN_OK();
8cf7c697
ML
2429}
2430
970f279a 2431SP_API enum sp_return sp_start_break(struct sp_port *port)
90cc3ee6 2432{
c33efc48
ML
2433 TRACE("%p", port);
2434
dec10e31 2435 CHECK_OPEN_PORT();
90cc3ee6
ML
2436#ifdef _WIN32
2437 if (SetCommBreak(port->hdl) == 0)
c33efc48 2438 RETURN_FAIL("SetCommBreak() failed");
90cc3ee6
ML
2439#else
2440 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
c33efc48 2441 RETURN_FAIL("TIOCSBRK ioctl failed");
90cc3ee6
ML
2442#endif
2443
c33efc48 2444 RETURN_OK();
90cc3ee6
ML
2445}
2446
970f279a 2447SP_API enum sp_return sp_end_break(struct sp_port *port)
90cc3ee6 2448{
c33efc48
ML
2449 TRACE("%p", port);
2450
dec10e31 2451 CHECK_OPEN_PORT();
90cc3ee6
ML
2452#ifdef _WIN32
2453 if (ClearCommBreak(port->hdl) == 0)
c33efc48 2454 RETURN_FAIL("ClearCommBreak() failed");
90cc3ee6
ML
2455#else
2456 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
c33efc48 2457 RETURN_FAIL("TIOCCBRK ioctl failed");
90cc3ee6
ML
2458#endif
2459
c33efc48 2460 RETURN_OK();
90cc3ee6
ML
2461}
2462
970f279a 2463SP_API int sp_last_error_code(void)
74510d4b 2464{
7890cef6 2465 TRACE_VOID();
74510d4b 2466#ifdef _WIN32
9caa2e86 2467 RETURN_INT(GetLastError());
74510d4b 2468#else
9caa2e86 2469 RETURN_INT(errno);
74510d4b
ML
2470#endif
2471}
2472
970f279a 2473SP_API char *sp_last_error_message(void)
74510d4b 2474{
7890cef6 2475 TRACE_VOID();
c33efc48 2476
74510d4b 2477#ifdef _WIN32
9a0c4bbd 2478 TCHAR *message;
74510d4b
ML
2479 DWORD error = GetLastError();
2480
9a0c4bbd 2481 DWORD length = FormatMessage(
74510d4b
ML
2482 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2483 FORMAT_MESSAGE_FROM_SYSTEM |
2484 FORMAT_MESSAGE_IGNORE_INSERTS,
2485 NULL,
2486 error,
2487 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2488 (LPTSTR) &message,
2489 0, NULL );
2490
9a0c4bbd
ML
2491 if (length >= 2 && message[length - 2] == '\r')
2492 message[length - 2] = '\0';
2493
9caa2e86 2494 RETURN_STRING(message);
74510d4b 2495#else
9caa2e86 2496 RETURN_STRING(strerror(errno));
74510d4b
ML
2497#endif
2498}
2499
970f279a 2500SP_API void sp_free_error_message(char *message)
74510d4b 2501{
c33efc48
ML
2502 TRACE("%s", message);
2503
74510d4b
ML
2504#ifdef _WIN32
2505 LocalFree(message);
64eec30d
ML
2506#else
2507 (void)message;
74510d4b 2508#endif
c33efc48
ML
2509
2510 RETURN();
74510d4b 2511}
863b35e6 2512
970f279a 2513SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
863b35e6 2514{
c33efc48
ML
2515 TRACE("%p", handler);
2516
863b35e6 2517 sp_debug_handler = handler;
c33efc48
ML
2518
2519 RETURN();
863b35e6
ML
2520}
2521
970f279a 2522SP_API void sp_default_debug_handler(const char *format, ...)
863b35e6
ML
2523{
2524 va_list args;
2525 va_start(args, format);
2526 if (getenv("LIBSERIALPORT_DEBUG")) {
dd7742fb 2527 fputs("sp: ", stderr);
863b35e6
ML
2528 vfprintf(stderr, format, args);
2529 }
2530 va_end(args);
2531}
524b0e14 2532
970f279a 2533SP_API int sp_get_major_package_version(void)
524b0e14
UH
2534{
2535 return SP_PACKAGE_VERSION_MAJOR;
2536}
2537
970f279a 2538SP_API int sp_get_minor_package_version(void)
524b0e14
UH
2539{
2540 return SP_PACKAGE_VERSION_MINOR;
2541}
2542
970f279a 2543SP_API int sp_get_micro_package_version(void)
524b0e14
UH
2544{
2545 return SP_PACKAGE_VERSION_MICRO;
2546}
2547
970f279a 2548SP_API const char *sp_get_package_version_string(void)
524b0e14
UH
2549{
2550 return SP_PACKAGE_VERSION_STRING;
2551}
2552
970f279a 2553SP_API int sp_get_current_lib_version(void)
524b0e14
UH
2554{
2555 return SP_LIB_VERSION_CURRENT;
2556}
2557
970f279a 2558SP_API int sp_get_revision_lib_version(void)
524b0e14
UH
2559{
2560 return SP_LIB_VERSION_REVISION;
2561}
2562
970f279a 2563SP_API int sp_get_age_lib_version(void)
524b0e14
UH
2564{
2565 return SP_LIB_VERSION_AGE;
2566}
2567
970f279a 2568SP_API const char *sp_get_lib_version_string(void)
524b0e14
UH
2569{
2570 return SP_LIB_VERSION_STRING;
2571}
2572
2573/** @} */