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