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