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