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