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