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