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