]> sigrok.org Git - libserialport.git/blame - serialport.c
change type of result variables to ssize_t
[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
1abec205
JJ
593 /*
594 * Assume a default baudrate if the OS does not provide one.
595 * Cannot assign -1 here since Windows holds the baudrate in
596 * the DCB and does not configure the rate individually.
597 */
598 if (config.baudrate == 0) {
599 config.baudrate = 9600;
600 }
601
bccc7c9f
ML
602 /* Set sane port settings. */
603#ifdef _WIN32
604 data.dcb.fBinary = TRUE;
605 data.dcb.fDsrSensitivity = FALSE;
606 data.dcb.fErrorChar = FALSE;
607 data.dcb.fNull = FALSE;
34442106 608 data.dcb.fAbortOnError = FALSE;
bccc7c9f 609#else
b251be4b 610 /* Turn off all fancy termios tricks, give us a raw channel. */
c3e05092
UH
611 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
612#ifdef IUCLC
613 data.term.c_iflag &= ~IUCLC;
614#endif
615 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
616#ifdef OLCUC
617 data.term.c_oflag &= ~OLCUC;
618#endif
619#ifdef NLDLY
620 data.term.c_oflag &= ~NLDLY;
621#endif
622#ifdef CRDLY
623 data.term.c_oflag &= ~CRDLY;
624#endif
625#ifdef TABDLY
626 data.term.c_oflag &= ~TABDLY;
627#endif
628#ifdef BSDLY
629 data.term.c_oflag &= ~BSDLY;
630#endif
631#ifdef VTDLY
632 data.term.c_oflag &= ~VTDLY;
633#endif
634#ifdef FFDLY
635 data.term.c_oflag &= ~FFDLY;
636#endif
b251be4b 637#ifdef OFILL
9cb98459
ML
638 data.term.c_oflag &= ~OFILL;
639#endif
c3e05092 640 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
e3dcf906 641 data.term.c_cc[VMIN] = 0;
b251be4b 642 data.term.c_cc[VTIME] = 0;
9cb98459 643
b251be4b 644 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
1b011060
BG
645 data.term.c_cflag |= (CLOCAL | CREAD);
646 data.term.c_cflag &= ~(HUPCL);
bccc7c9f 647#endif
9cb98459 648
537942c9 649#ifdef _WIN32
1a2a1544
UH
650 if (ClearCommError(port->hdl, &errors, &status) == 0)
651 RETURN_FAIL("ClearCommError() failed");
537942c9
ML
652#endif
653
e33ab9aa
ML
654 ret = set_config(port, &data, &config);
655
eac329d2 656 if (ret < 0) {
e33ab9aa 657 sp_close(port);
c33efc48 658 RETURN_CODEVAL(ret);
e33ab9aa 659 }
74510d4b 660
c33efc48 661 RETURN_OK();
74510d4b
ML
662}
663
970f279a 664SP_API enum sp_return sp_close(struct sp_port *port)
74510d4b 665{
c33efc48
ML
666 TRACE("%p", port);
667
dec10e31 668 CHECK_OPEN_PORT();
74510d4b 669
7890cef6 670 DEBUG_FMT("Closing port %s", port->name);
ea667be7 671
74510d4b
ML
672#ifdef _WIN32
673 /* Returns non-zero upon success, 0 upon failure. */
674 if (CloseHandle(port->hdl) == 0)
dc422c04 675 RETURN_FAIL("Port CloseHandle() failed");
8f471c66 676 port->hdl = INVALID_HANDLE_VALUE;
6f1186aa
ML
677
678 /* Close event handles for overlapped structures. */
679#define CLOSE_OVERLAPPED(ovl) do { \
680 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
681 CloseHandle(port->ovl.hEvent) == 0) \
682 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
683} while (0)
684 CLOSE_OVERLAPPED(read_ovl);
685 CLOSE_OVERLAPPED(write_ovl);
686 CLOSE_OVERLAPPED(wait_ovl);
687
39df7833
ML
688 if (port->write_buf) {
689 free(port->write_buf);
690 port->write_buf = NULL;
691 }
74510d4b
ML
692#else
693 /* Returns 0 upon success, -1 upon failure. */
694 if (close(port->fd) == -1)
c33efc48 695 RETURN_FAIL("close() failed");
8f471c66 696 port->fd = -1;
74510d4b
ML
697#endif
698
c33efc48 699 RETURN_OK();
74510d4b
ML
700}
701
970f279a 702SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
74510d4b 703{
00d8c56d 704 TRACE("%p, 0x%x", port, buffers);
c33efc48 705
dec10e31
ML
706 CHECK_OPEN_PORT();
707
708 if (buffers > SP_BUF_BOTH)
709 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
74510d4b 710
0ba3e49b 711 const char *buffer_names[] = {"no", "input", "output", "both"};
ea667be7 712
7890cef6
ML
713 DEBUG_FMT("Flushing %s buffers on port %s",
714 buffer_names[buffers], port->name);
ea667be7 715
74510d4b 716#ifdef _WIN32
fd8fd11a
ML
717 DWORD flags = 0;
718 if (buffers & SP_BUF_INPUT)
719 flags |= PURGE_RXCLEAR;
720 if (buffers & SP_BUF_OUTPUT)
721 flags |= PURGE_TXCLEAR;
722
74510d4b 723 /* Returns non-zero upon success, 0 upon failure. */
fd8fd11a 724 if (PurgeComm(port->hdl, flags) == 0)
c33efc48 725 RETURN_FAIL("PurgeComm() failed");
47fcf8ec
ML
726
727 if (buffers & SP_BUF_INPUT)
728 TRY(restart_wait(port));
74510d4b 729#else
fd8fd11a 730 int flags = 0;
ad749855 731 if (buffers == SP_BUF_BOTH)
fd8fd11a 732 flags = TCIOFLUSH;
ad749855 733 else if (buffers == SP_BUF_INPUT)
fd8fd11a 734 flags = TCIFLUSH;
ad749855 735 else if (buffers == SP_BUF_OUTPUT)
fd8fd11a
ML
736 flags = TCOFLUSH;
737
74510d4b 738 /* Returns 0 upon success, -1 upon failure. */
fd8fd11a 739 if (tcflush(port->fd, flags) < 0)
c33efc48 740 RETURN_FAIL("tcflush() failed");
74510d4b 741#endif
c33efc48 742 RETURN_OK();
74510d4b
ML
743}
744
970f279a 745SP_API enum sp_return sp_drain(struct sp_port *port)
69a3739c 746{
c33efc48
ML
747 TRACE("%p", port);
748
dec10e31 749 CHECK_OPEN_PORT();
69a3739c 750
7890cef6 751 DEBUG_FMT("Draining port %s", port->name);
ea667be7 752
69a3739c
ML
753#ifdef _WIN32
754 /* Returns non-zero upon success, 0 upon failure. */
755 if (FlushFileBuffers(port->hdl) == 0)
c33efc48 756 RETURN_FAIL("FlushFileBuffers() failed");
2c827b21 757 RETURN_OK();
69a3739c 758#else
2c827b21
ML
759 int result;
760 while (1) {
abd31fd9
ML
761#if defined(__ANDROID__) && (__ANDROID_API__ < 21)
762 /* Android only has tcdrain from platform 21 onwards.
763 * On previous API versions, use the ioctl directly. */
33fd8804
ML
764 int arg = 1;
765 result = ioctl(port->fd, TCSBRK, &arg);
766#else
2c827b21 767 result = tcdrain(port->fd);
33fd8804 768#endif
2c827b21
ML
769 if (result < 0) {
770 if (errno == EINTR) {
771 DEBUG("tcdrain() was interrupted");
772 continue;
773 } else {
774 RETURN_FAIL("tcdrain() failed");
775 }
776 } else {
777 RETURN_OK();
778 }
779 }
69a3739c 780#endif
69a3739c
ML
781}
782
62ed9f80
ML
783#ifdef _WIN32
784static enum sp_return await_write_completion(struct sp_port *port)
785{
786 TRACE("%p", port);
787 DWORD bytes_written;
788 BOOL result;
789
790 /* Wait for previous non-blocking write to complete, if any. */
791 if (port->writing) {
792 DEBUG("Waiting for previous write to complete");
793 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
794 port->writing = 0;
795 if (!result)
796 RETURN_FAIL("Previous write failed to complete");
797 DEBUG("Previous write completed");
798 }
799
800 RETURN_OK();
801}
802#endif
803
970f279a 804SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
1b91c6ea 805 size_t count, unsigned int timeout_ms)
e3dcf906 806{
1b91c6ea 807 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
e3dcf906
ML
808
809 CHECK_OPEN_PORT();
810
811 if (!buf)
812 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
813
1b91c6ea 814 if (timeout_ms)
7890cef6 815 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
1b91c6ea 816 count, port->name, timeout_ms);
e3dcf906 817 else
7890cef6
ML
818 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
819 count, port->name);
e3dcf906
ML
820
821 if (count == 0)
9caa2e86 822 RETURN_INT(0);
e3dcf906
ML
823
824#ifdef _WIN32
2149db9e
ML
825 DWORD remaining_ms, write_size, bytes_written;
826 size_t remaining_bytes, total_bytes_written = 0;
060d1d8a
ML
827 const uint8_t *write_ptr = (uint8_t *) buf;
828 bool result;
829 struct timeout timeout;
830
831 timeout_start(&timeout, timeout_ms);
e3dcf906 832
62ed9f80 833 TRY(await_write_completion(port));
e3dcf906 834
060d1d8a 835 while (total_bytes_written < count) {
e3dcf906 836
060d1d8a
ML
837 if (timeout_check(&timeout))
838 break;
839
840 remaining_ms = timeout_remaining_ms(&timeout);
841
842 if (port->timeouts.WriteTotalTimeoutConstant != remaining_ms) {
843 port->timeouts.WriteTotalTimeoutConstant = remaining_ms;
844 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
845 RETURN_FAIL("SetCommTimeouts() failed");
846 }
847
848 /* Reduce write size if it exceeds the WriteFile limit. */
2149db9e
ML
849 remaining_bytes = count - total_bytes_written;
850 if (remaining_bytes > WRITEFILE_MAX_SIZE)
060d1d8a 851 write_size = WRITEFILE_MAX_SIZE;
2149db9e
ML
852 else
853 write_size = (DWORD) remaining_bytes;
060d1d8a
ML
854
855 /* Start write. */
856
857 result = WriteFile(port->hdl, write_ptr, write_size, NULL, &port->write_ovl);
858
859 timeout_update(&timeout);
860
861 if (result) {
862 DEBUG("Write completed immediately");
863 bytes_written = write_size;
864 } else if (GetLastError() == ERROR_IO_PENDING) {
865 DEBUG("Waiting for write to complete");
866 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
867 if (GetLastError() == ERROR_SEM_TIMEOUT) {
868 DEBUG("Write timed out");
869 break;
870 } else {
871 RETURN_FAIL("GetOverlappedResult() failed");
872 }
aee7d691 873 }
060d1d8a
ML
874 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, write_size);
875 } else {
876 RETURN_FAIL("WriteFile() failed");
aee7d691 877 }
060d1d8a
ML
878
879 write_ptr += bytes_written;
880 total_bytes_written += bytes_written;
e3dcf906 881 }
060d1d8a 882
2149db9e 883 RETURN_INT((int) total_bytes_written);
e3dcf906
ML
884#else
885 size_t bytes_written = 0;
886 unsigned char *ptr = (unsigned char *) buf;
32dbe2d2 887 struct timeout timeout;
e3dcf906 888 fd_set fds;
fd20b0fc 889 ssize_t result;
e3dcf906 890
32dbe2d2 891 timeout_start(&timeout, timeout_ms);
e3dcf906 892
772c5861
ML
893 FD_ZERO(&fds);
894 FD_SET(port->fd, &fds);
895
e3dcf906 896 /* Loop until we have written the requested number of bytes. */
dc422c04 897 while (bytes_written < count) {
bd72614f
ML
898
899 if (timeout_check(&timeout))
32dbe2d2
ML
900 break;
901
902 result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
bd72614f
ML
903
904 timeout_update(&timeout);
905
63a17c64
ML
906 if (result < 0) {
907 if (errno == EINTR) {
908 DEBUG("select() call was interrupted, repeating");
909 continue;
910 } else {
911 RETURN_FAIL("select() failed");
912 }
913 } else if (result == 0) {
c3cee38c
ML
914 /* Timeout has expired. */
915 break;
e3dcf906
ML
916 }
917
918 /* Do write. */
919 result = write(port->fd, ptr, count - bytes_written);
920
921 if (result < 0) {
922 if (errno == EAGAIN)
923 /* This shouldn't happen because we did a select() first, but handle anyway. */
924 continue;
925 else
926 /* This is an actual failure. */
927 RETURN_FAIL("write() failed");
928 }
929
930 bytes_written += result;
931 ptr += result;
932 }
933
c3cee38c
ML
934 if (bytes_written < count)
935 DEBUG("Write timed out");
936
9caa2e86 937 RETURN_INT(bytes_written);
e3dcf906
ML
938#endif
939}
940
970f279a
AJ
941SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
942 const void *buf, size_t count)
74510d4b 943{
c33efc48
ML
944 TRACE("%p, %p, %d", port, buf, count);
945
dec10e31 946 CHECK_OPEN_PORT();
74510d4b
ML
947
948 if (!buf)
c33efc48 949 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
74510d4b 950
7890cef6 951 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
ea667be7 952
a3cb91f5 953 if (count == 0)
9caa2e86 954 RETURN_INT(0);
a3cb91f5 955
74510d4b 956#ifdef _WIN32
2149db9e 957 size_t buf_bytes;
f92f1f0c 958
e3dcf906
ML
959 /* Check whether previous write is complete. */
960 if (port->writing) {
961 if (HasOverlappedIoCompleted(&port->write_ovl)) {
962 DEBUG("Previous write completed");
963 port->writing = 0;
964 } else {
965 DEBUG("Previous write not complete");
966 /* Can't take a new write until the previous one finishes. */
9caa2e86 967 RETURN_INT(0);
a3cb91f5 968 }
e3dcf906 969 }
a3cb91f5 970
e3dcf906 971 /* Set timeout. */
27a58c05
ML
972 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
973 port->timeouts.WriteTotalTimeoutConstant = 0;
974 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
975 RETURN_FAIL("SetCommTimeouts() failed");
976 }
e3dcf906 977
b457865b
ML
978 /* Reduce count if it exceeds the WriteFile limit. */
979 if (count > WRITEFILE_MAX_SIZE)
980 count = WRITEFILE_MAX_SIZE;
981
39df7833
ML
982 /* Copy data to our write buffer. */
983 buf_bytes = min(port->write_buf_size, count);
984 memcpy(port->write_buf, buf, buf_bytes);
985
986 /* Start asynchronous write. */
2149db9e 987 if (WriteFile(port->hdl, port->write_buf, (DWORD) buf_bytes, NULL, &port->write_ovl) == 0) {
39df7833
ML
988 if (GetLastError() == ERROR_IO_PENDING) {
989 if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
990 DEBUG("Asynchronous write completed immediately");
991 else
992 DEBUG("Asynchronous write running");
e3dcf906 993 } else {
39df7833
ML
994 /* Actual failure of some kind. */
995 RETURN_FAIL("WriteFile() failed");
a3cb91f5
ML
996 }
997 }
998
9af8cff3 999 DEBUG("All bytes written immediately");
e3dcf906 1000
2149db9e 1001 RETURN_INT((int) buf_bytes);
74510d4b
ML
1002#else
1003 /* Returns the number of bytes written, or -1 upon failure. */
1004 ssize_t written = write(port->fd, buf, count);
f92f1f0c 1005
55ab7e0b
ML
1006 if (written < 0) {
1007 if (errno == EAGAIN)
1008 // Buffer is full, no bytes written.
1009 RETURN_INT(0);
1010 else
1011 RETURN_FAIL("write() failed");
1012 } else {
9caa2e86 1013 RETURN_INT(written);
55ab7e0b 1014 }
74510d4b
ML
1015#endif
1016}
1017
94a314a8
ML
1018#ifdef _WIN32
1019/* Restart wait operation if buffer was emptied. */
1020static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
1021{
8ebfaf89
ML
1022 DWORD errors;
1023 COMSTAT comstat;
94a314a8 1024
21ae5ce1
ML
1025 if (bytes_read == 0)
1026 RETURN_OK();
1027
8ebfaf89
ML
1028 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1029 RETURN_FAIL("ClearCommError() failed");
94a314a8 1030
8ebfaf89 1031 if (comstat.cbInQue == 0)
94a314a8
ML
1032 TRY(restart_wait(port));
1033
1034 RETURN_OK();
1035}
1036#endif
1037
970f279a 1038SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
1b91c6ea 1039 size_t count, unsigned int timeout_ms)
e3dcf906 1040{
1b91c6ea 1041 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
e3dcf906
ML
1042
1043 CHECK_OPEN_PORT();
1044
1045 if (!buf)
1046 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1047
1b91c6ea 1048 if (timeout_ms)
7890cef6 1049 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
1b91c6ea 1050 count, port->name, timeout_ms);
e3dcf906 1051 else
7890cef6
ML
1052 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
1053 count, port->name);
e3dcf906
ML
1054
1055 if (count == 0)
9caa2e86 1056 RETURN_INT(0);
e3dcf906
ML
1057
1058#ifdef _WIN32
2149db9e 1059 DWORD bytes_read;
e3dcf906
ML
1060
1061 /* Set timeout. */
27a58c05 1062 if (port->timeouts.ReadIntervalTimeout != 0 ||
0188a545 1063 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
27a58c05
ML
1064 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
1065 port->timeouts.ReadIntervalTimeout = 0;
0188a545 1066 port->timeouts.ReadTotalTimeoutMultiplier = 0;
27a58c05
ML
1067 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
1068 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1069 RETURN_FAIL("SetCommTimeouts() failed");
1070 }
e3dcf906
ML
1071
1072 /* Start read. */
2149db9e 1073 if (ReadFile(port->hdl, buf, (DWORD) count, NULL, &port->read_ovl)) {
e3dcf906 1074 DEBUG("Read completed immediately");
2149db9e 1075 bytes_read = (DWORD) count;
bbe566fe
ML
1076 } else if (GetLastError() == ERROR_IO_PENDING) {
1077 DEBUG("Waiting for read to complete");
27911925
ML
1078 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1079 RETURN_FAIL("GetOverlappedResult() failed");
bbe566fe
ML
1080 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
1081 } else {
1082 RETURN_FAIL("ReadFile() failed");
6f1186aa
ML
1083 }
1084
94a314a8 1085 TRY(restart_wait_if_needed(port, bytes_read));
6f1186aa 1086
2149db9e 1087 RETURN_INT((int) bytes_read);
6f1186aa 1088
e3dcf906
ML
1089#else
1090 size_t bytes_read = 0;
9a7945af 1091 unsigned char *ptr = (unsigned char *) buf;
32dbe2d2 1092 struct timeout timeout;
e3dcf906 1093 fd_set fds;
fd20b0fc 1094 ssize_t result;
e3dcf906 1095
32dbe2d2 1096 timeout_start(&timeout, timeout_ms);
e3dcf906 1097
772c5861
ML
1098 FD_ZERO(&fds);
1099 FD_SET(port->fd, &fds);
1100
e3dcf906 1101 /* Loop until we have the requested number of bytes. */
dc422c04 1102 while (bytes_read < count) {
bd72614f
ML
1103
1104 if (timeout_check(&timeout))
32dbe2d2
ML
1105 /* Timeout has expired. */
1106 break;
1107
1108 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
bd72614f
ML
1109
1110 timeout_update(&timeout);
1111
63a17c64
ML
1112 if (result < 0) {
1113 if (errno == EINTR) {
1114 DEBUG("select() call was interrupted, repeating");
1115 continue;
1116 } else {
1117 RETURN_FAIL("select() failed");
1118 }
1119 } else if (result == 0) {
c3cee38c
ML
1120 /* Timeout has expired. */
1121 break;
e3dcf906
ML
1122 }
1123
1124 /* Do read. */
1125 result = read(port->fd, ptr, count - bytes_read);
1126
1127 if (result < 0) {
1128 if (errno == EAGAIN)
76222ee5
ML
1129 /*
1130 * This shouldn't happen because we did a
1131 * select() first, but handle anyway.
1132 */
e3dcf906
ML
1133 continue;
1134 else
1135 /* This is an actual failure. */
1136 RETURN_FAIL("read() failed");
1137 }
1138
1139 bytes_read += result;
1140 ptr += result;
1141 }
1142
c3cee38c
ML
1143 if (bytes_read < count)
1144 DEBUG("Read timed out");
1145
9caa2e86 1146 RETURN_INT(bytes_read);
e3dcf906
ML
1147#endif
1148}
1149
e5c2630e
ML
1150SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1151 size_t count, unsigned int timeout_ms)
1152{
1153 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1154
1155 CHECK_OPEN_PORT();
1156
1157 if (!buf)
1158 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1159
1160 if (count == 0)
1161 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1162
1163 if (timeout_ms)
1164 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1165 count, port->name, timeout_ms);
1166 else
1167 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1168 count, port->name);
1169
1170#ifdef _WIN32
1171 DWORD bytes_read = 0;
1172
1173 /* If timeout_ms == 0, set maximum timeout. */
1174 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1175
1176 /* Set timeout. */
1177 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1178 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1179 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1180 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1181 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1182 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1183 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1184 RETURN_FAIL("SetCommTimeouts() failed");
1185 }
1186
1187 /* Loop until we have at least one byte, or timeout is reached. */
1188 while (bytes_read == 0) {
1189 /* Start read. */
2149db9e 1190 if (ReadFile(port->hdl, buf, (DWORD) count, &bytes_read, &port->read_ovl)) {
e5c2630e 1191 DEBUG("Read completed immediately");
e5c2630e
ML
1192 } else if (GetLastError() == ERROR_IO_PENDING) {
1193 DEBUG("Waiting for read to complete");
1194 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1195 RETURN_FAIL("GetOverlappedResult() failed");
1196 if (bytes_read > 0) {
1197 DEBUG("Read completed");
1198 } else if (timeout_ms > 0) {
1199 DEBUG("Read timed out");
1200 break;
1201 } else {
1202 DEBUG("Restarting read");
1203 }
1204 } else {
1205 RETURN_FAIL("ReadFile() failed");
1206 }
1207 }
1208
1209 TRY(restart_wait_if_needed(port, bytes_read));
1210
1211 RETURN_INT(bytes_read);
1212
1213#else
1214 size_t bytes_read = 0;
32dbe2d2 1215 struct timeout timeout;
e5c2630e 1216 fd_set fds;
fd20b0fc 1217 ssize_t result;
e5c2630e 1218
32dbe2d2 1219 timeout_start(&timeout, timeout_ms);
e5c2630e
ML
1220
1221 FD_ZERO(&fds);
1222 FD_SET(port->fd, &fds);
1223
1224 /* Loop until we have at least one byte, or timeout is reached. */
1225 while (bytes_read == 0) {
bd72614f
ML
1226
1227 if (timeout_check(&timeout))
32dbe2d2
ML
1228 /* Timeout has expired. */
1229 break;
1230
1231 result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
bd72614f
ML
1232
1233 timeout_update(&timeout);
1234
e5c2630e
ML
1235 if (result < 0) {
1236 if (errno == EINTR) {
1237 DEBUG("select() call was interrupted, repeating");
1238 continue;
1239 } else {
1240 RETURN_FAIL("select() failed");
1241 }
1242 } else if (result == 0) {
1243 /* Timeout has expired. */
1244 break;
1245 }
1246
1247 /* Do read. */
1248 result = read(port->fd, buf, count);
1249
1250 if (result < 0) {
1251 if (errno == EAGAIN)
1252 /* This shouldn't happen because we did a select() first, but handle anyway. */
1253 continue;
1254 else
1255 /* This is an actual failure. */
1256 RETURN_FAIL("read() failed");
1257 }
1258
1259 bytes_read = result;
1260 }
1261
1262 if (bytes_read == 0)
1263 DEBUG("Read timed out");
1264
1265 RETURN_INT(bytes_read);
1266#endif
1267}
1268
970f279a
AJ
1269SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1270 size_t count)
74510d4b 1271{
c33efc48
ML
1272 TRACE("%p, %p, %d", port, buf, count);
1273
dec10e31 1274 CHECK_OPEN_PORT();
74510d4b
ML
1275
1276 if (!buf)
c33efc48 1277 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
74510d4b 1278
7890cef6 1279 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
ea667be7 1280
74510d4b 1281#ifdef _WIN32
e3dcf906 1282 DWORD bytes_read;
f92f1f0c 1283
e3dcf906 1284 /* Set timeout. */
27a58c05 1285 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
0188a545 1286 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
27a58c05
ML
1287 port->timeouts.ReadTotalTimeoutConstant != 0) {
1288 port->timeouts.ReadIntervalTimeout = MAXDWORD;
0188a545 1289 port->timeouts.ReadTotalTimeoutMultiplier = 0;
27a58c05
ML
1290 port->timeouts.ReadTotalTimeoutConstant = 0;
1291 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1292 RETURN_FAIL("SetCommTimeouts() failed");
1293 }
e3dcf906
ML
1294
1295 /* Do read. */
2149db9e 1296 if (ReadFile(port->hdl, buf, (DWORD) count, NULL, &port->read_ovl) == 0)
ae2c5825
ML
1297 if (GetLastError() != ERROR_IO_PENDING)
1298 RETURN_FAIL("ReadFile() failed");
e3dcf906
ML
1299
1300 /* Get number of bytes read. */
ae2c5825 1301 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, FALSE) == 0)
1622ef60 1302 RETURN_FAIL("GetOverlappedResult() failed");
e3dcf906 1303
94a314a8 1304 TRY(restart_wait_if_needed(port, bytes_read));
6f1186aa 1305
9caa2e86 1306 RETURN_INT(bytes_read);
74510d4b
ML
1307#else
1308 ssize_t bytes_read;
f92f1f0c 1309
74510d4b 1310 /* Returns the number of bytes read, or -1 upon failure. */
33d5ff47 1311 if ((bytes_read = read(port->fd, buf, count)) < 0) {
e3dcf906
ML
1312 if (errno == EAGAIN)
1313 /* No bytes available. */
33d5ff47
ML
1314 bytes_read = 0;
1315 else
1316 /* This is an actual failure. */
1317 RETURN_FAIL("read() failed");
1318 }
9caa2e86 1319 RETURN_INT(bytes_read);
74510d4b
ML
1320#endif
1321}
1322
970f279a 1323SP_API enum sp_return sp_input_waiting(struct sp_port *port)
3353c22f
ML
1324{
1325 TRACE("%p", port);
1326
1327 CHECK_OPEN_PORT();
1328
7890cef6 1329 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
3353c22f
ML
1330
1331#ifdef _WIN32
1332 DWORD errors;
1333 COMSTAT comstat;
1334
1335 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1a2a1544 1336 RETURN_FAIL("ClearCommError() failed");
9caa2e86 1337 RETURN_INT(comstat.cbInQue);
3353c22f
ML
1338#else
1339 int bytes_waiting;
1340 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1341 RETURN_FAIL("TIOCINQ ioctl failed");
9caa2e86 1342 RETURN_INT(bytes_waiting);
3353c22f
ML
1343#endif
1344}
1345
970f279a 1346SP_API enum sp_return sp_output_waiting(struct sp_port *port)
3353c22f
ML
1347{
1348 TRACE("%p", port);
1349
2be41b12
ML
1350#ifdef __CYGWIN__
1351 /* TIOCOUTQ is not defined in Cygwin headers */
1352 RETURN_ERROR(SP_ERR_SUPP,
1353 "Getting output bytes waiting is not supported on Cygwin");
1354#else
3353c22f
ML
1355 CHECK_OPEN_PORT();
1356
7890cef6 1357 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
3353c22f
ML
1358
1359#ifdef _WIN32
1360 DWORD errors;
1361 COMSTAT comstat;
1362
1363 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1a2a1544 1364 RETURN_FAIL("ClearCommError() failed");
9caa2e86 1365 RETURN_INT(comstat.cbOutQue);
3353c22f
ML
1366#else
1367 int bytes_waiting;
1368 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1369 RETURN_FAIL("TIOCOUTQ ioctl failed");
9caa2e86 1370 RETURN_INT(bytes_waiting);
3353c22f 1371#endif
2be41b12 1372#endif
3353c22f
ML
1373}
1374
970f279a 1375SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
6f1186aa
ML
1376{
1377 struct sp_event_set *result;
1378
1379 TRACE("%p", result_ptr);
1380
1381 if (!result_ptr)
1382 RETURN_ERROR(SP_ERR_ARG, "Null result");
1383
1384 *result_ptr = NULL;
1385
1386 if (!(result = malloc(sizeof(struct sp_event_set))))
1387 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1388
1389 memset(result, 0, sizeof(struct sp_event_set));
1390
1391 *result_ptr = result;
1392
1393 RETURN_OK();
1394}
1395
1396static enum sp_return add_handle(struct sp_event_set *event_set,
1397 event_handle handle, enum sp_event mask)
1398{
1399 void *new_handles;
1400 enum sp_event *new_masks;
1401
1402 TRACE("%p, %d, %d", event_set, handle, mask);
1403
1404 if (!(new_handles = realloc(event_set->handles,
1405 sizeof(event_handle) * (event_set->count + 1))))
dc422c04 1406 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
6f1186aa 1407
ac323d80
UH
1408 event_set->handles = new_handles;
1409
6f1186aa 1410 if (!(new_masks = realloc(event_set->masks,
ac323d80 1411 sizeof(enum sp_event) * (event_set->count + 1))))
dc422c04 1412 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
6f1186aa 1413
6f1186aa
ML
1414 event_set->masks = new_masks;
1415
1416 ((event_handle *) event_set->handles)[event_set->count] = handle;
1417 event_set->masks[event_set->count] = mask;
1418
1419 event_set->count++;
1420
1421 RETURN_OK();
1422}
1423
970f279a 1424SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
6f1186aa
ML
1425 const struct sp_port *port, enum sp_event mask)
1426{
1427 TRACE("%p, %p, %d", event_set, port, mask);
1428
1429 if (!event_set)
1430 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1431
1432 if (!port)
1433 RETURN_ERROR(SP_ERR_ARG, "Null port");
1434
1435 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1436 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1437
1438 if (!mask)
1439 RETURN_OK();
1440
1441#ifdef _WIN32
1442 enum sp_event handle_mask;
1443 if ((handle_mask = mask & SP_EVENT_TX_READY))
1444 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1445 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1446 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1447#else
1448 TRY(add_handle(event_set, port->fd, mask));
1449#endif
1450
1451 RETURN_OK();
1452}
1453
970f279a 1454SP_API void sp_free_event_set(struct sp_event_set *event_set)
6f1186aa
ML
1455{
1456 TRACE("%p", event_set);
1457
1458 if (!event_set) {
1459 DEBUG("Null event set");
1460 RETURN();
1461 }
1462
1463 DEBUG("Freeing event set");
1464
1465 if (event_set->handles)
1466 free(event_set->handles);
1467 if (event_set->masks)
1468 free(event_set->masks);
1469
1470 free(event_set);
1471
1472 RETURN();
1473}
1474
970f279a 1475SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1b91c6ea 1476 unsigned int timeout_ms)
6f1186aa 1477{
1b91c6ea 1478 TRACE("%p, %d", event_set, timeout_ms);
6f1186aa
ML
1479
1480 if (!event_set)
1481 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1482
1483#ifdef _WIN32
1484 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1b91c6ea 1485 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
6f1186aa
ML
1486 RETURN_FAIL("WaitForMultipleObjects() failed");
1487
1488 RETURN_OK();
1489#else
32dbe2d2 1490 struct timeout timeout;
d81a4dfd 1491 int poll_timeout;
bd72614f 1492 int result;
6f1186aa
ML
1493 struct pollfd *pollfds;
1494 unsigned int i;
1495
1496 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1497 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1498
1499 for (i = 0; i < event_set->count; i++) {
81243567 1500 pollfds[i].fd = ((int *)event_set->handles)[i];
6f1186aa
ML
1501 pollfds[i].events = 0;
1502 pollfds[i].revents = 0;
1503 if (event_set->masks[i] & SP_EVENT_RX_READY)
1504 pollfds[i].events |= POLLIN;
1505 if (event_set->masks[i] & SP_EVENT_TX_READY)
1506 pollfds[i].events |= POLLOUT;
1507 if (event_set->masks[i] & SP_EVENT_ERROR)
1508 pollfds[i].events |= POLLERR;
1509 }
1510
32dbe2d2 1511 timeout_start(&timeout, timeout_ms);
08eb25f5 1512 timeout_limit(&timeout, INT_MAX);
6f1186aa
ML
1513
1514 /* Loop until an event occurs. */
dc422c04 1515 while (1) {
bd72614f
ML
1516
1517 if (timeout_check(&timeout)) {
32dbe2d2
ML
1518 DEBUG("Wait timed out");
1519 break;
6f1186aa
ML
1520 }
1521
d81a4dfd
ML
1522 poll_timeout = (int) timeout_remaining_ms(&timeout);
1523 if (poll_timeout == 0)
1524 poll_timeout = -1;
1525
1526 result = poll(pollfds, event_set->count, poll_timeout);
bd72614f
ML
1527
1528 timeout_update(&timeout);
6f1186aa
ML
1529
1530 if (result < 0) {
1531 if (errno == EINTR) {
1532 DEBUG("poll() call was interrupted, repeating");
1533 continue;
1534 } else {
1535 free(pollfds);
1536 RETURN_FAIL("poll() failed");
1537 }
1538 } else if (result == 0) {
1539 DEBUG("poll() timed out");
32dbe2d2 1540 if (!timeout.overflow)
127d8d0c 1541 break;
6f1186aa
ML
1542 } else {
1543 DEBUG("poll() completed");
1544 break;
1545 }
1546 }
1547
1548 free(pollfds);
1549 RETURN_OK();
1550#endif
1551}
1552
5cea279a 1553#ifdef USE_TERMIOS_SPEED
7a6d2196
ML
1554static enum sp_return get_baudrate(int fd, int *baudrate)
1555{
1556 void *data;
1557
c33efc48
ML
1558 TRACE("%d, %p", fd, baudrate);
1559
ea667be7
ML
1560 DEBUG("Getting baud rate");
1561
7a6d2196 1562 if (!(data = malloc(get_termios_size())))
c33efc48 1563 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
7a6d2196 1564
8d43110a
ML
1565 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1566 free(data);
dc422c04 1567 RETURN_FAIL("Getting termios failed");
8d43110a 1568 }
7a6d2196
ML
1569
1570 *baudrate = get_termios_speed(data);
1571
8d43110a
ML
1572 free(data);
1573
c33efc48 1574 RETURN_OK();
7a6d2196
ML
1575}
1576
1577static enum sp_return set_baudrate(int fd, int baudrate)
1578{
1579 void *data;
1580
c33efc48
ML
1581 TRACE("%d, %d", fd, baudrate);
1582
ea667be7
ML
1583 DEBUG("Getting baud rate");
1584
7a6d2196 1585 if (!(data = malloc(get_termios_size())))
c33efc48 1586 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
7a6d2196 1587
8d43110a
ML
1588 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1589 free(data);
dc422c04 1590 RETURN_FAIL("Getting termios failed");
8d43110a 1591 }
7a6d2196 1592
ea667be7
ML
1593 DEBUG("Setting baud rate");
1594
7a6d2196
ML
1595 set_termios_speed(data, baudrate);
1596
8d43110a
ML
1597 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1598 free(data);
dc422c04 1599 RETURN_FAIL("Setting termios failed");
8d43110a
ML
1600 }
1601
1602 free(data);
7a6d2196 1603
c33efc48 1604 RETURN_OK();
7a6d2196 1605}
5cea279a 1606#endif /* USE_TERMIOS_SPEED */
40978c2b
ML
1607
1608#ifdef USE_TERMIOX
bd791fe1 1609static enum sp_return get_flow(int fd, struct port_data *data)
40978c2b 1610{
bd791fe1 1611 void *termx;
40978c2b 1612
bd791fe1 1613 TRACE("%d, %p", fd, data);
c33efc48 1614
ea667be7
ML
1615 DEBUG("Getting advanced flow control");
1616
bd791fe1 1617 if (!(termx = malloc(get_termiox_size())))
c33efc48 1618 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
40978c2b 1619
bd791fe1
ML
1620 if (ioctl(fd, TCGETX, termx) < 0) {
1621 free(termx);
dc422c04 1622 RETURN_FAIL("Getting termiox failed");
8d43110a 1623 }
40978c2b 1624
bd791fe1
ML
1625 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1626 &data->dtr_flow, &data->dsr_flow);
40978c2b 1627
bd791fe1 1628 free(termx);
8d43110a 1629
c33efc48 1630 RETURN_OK();
40978c2b
ML
1631}
1632
bd791fe1 1633static enum sp_return set_flow(int fd, struct port_data *data)
40978c2b 1634{
bd791fe1 1635 void *termx;
40978c2b 1636
bd791fe1 1637 TRACE("%d, %p", fd, data);
c33efc48 1638
ea667be7
ML
1639 DEBUG("Getting advanced flow control");
1640
bd791fe1 1641 if (!(termx = malloc(get_termiox_size())))
c33efc48 1642 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
40978c2b 1643
bd791fe1
ML
1644 if (ioctl(fd, TCGETX, termx) < 0) {
1645 free(termx);
dc422c04 1646 RETURN_FAIL("Getting termiox failed");
8d43110a 1647 }
40978c2b 1648
ea667be7
ML
1649 DEBUG("Setting advanced flow control");
1650
bd791fe1
ML
1651 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1652 data->dtr_flow, data->dsr_flow);
40978c2b 1653
bd791fe1
ML
1654 if (ioctl(fd, TCSETX, termx) < 0) {
1655 free(termx);
dc422c04 1656 RETURN_FAIL("Setting termiox failed");
8d43110a
ML
1657 }
1658
bd791fe1 1659 free(termx);
40978c2b 1660
c33efc48 1661 RETURN_OK();
40978c2b
ML
1662}
1663#endif /* USE_TERMIOX */
7a6d2196 1664
eb6ed20f
ML
1665static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1666 struct sp_port_config *config)
8094e4a0 1667{
da2748bf 1668 unsigned int i;
cbf628c7 1669
c33efc48
ML
1670 TRACE("%p, %p, %p", port, data, config);
1671
7890cef6 1672 DEBUG_FMT("Getting configuration for port %s", port->name);
ea667be7 1673
8094e4a0 1674#ifdef _WIN32
e33ab9aa 1675 if (!GetCommState(port->hdl, &data->dcb))
c33efc48 1676 RETURN_FAIL("GetCommState() failed");
8094e4a0 1677
067417af 1678 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
e33ab9aa 1679 if (data->dcb.BaudRate == std_baudrates[i].index) {
067417af
ML
1680 config->baudrate = std_baudrates[i].value;
1681 break;
1682 }
1683 }
1684
1685 if (i == NUM_STD_BAUDRATES)
1686 /* BaudRate field can be either an index or a custom baud rate. */
e33ab9aa 1687 config->baudrate = data->dcb.BaudRate;
067417af 1688
e33ab9aa 1689 config->bits = data->dcb.ByteSize;
067417af 1690
2913355f
ML
1691 switch (data->dcb.Parity) {
1692 case NOPARITY:
067417af 1693 config->parity = SP_PARITY_NONE;
2913355f
ML
1694 break;
1695 case ODDPARITY:
1696 config->parity = SP_PARITY_ODD;
1697 break;
1698 case EVENPARITY:
1699 config->parity = SP_PARITY_EVEN;
1700 break;
1701 case MARKPARITY:
1702 config->parity = SP_PARITY_MARK;
1703 break;
1704 case SPACEPARITY:
1705 config->parity = SP_PARITY_SPACE;
1706 break;
1707 default:
1708 config->parity = -1;
1709 }
067417af 1710
e33ab9aa 1711 switch (data->dcb.StopBits) {
067417af
ML
1712 case ONESTOPBIT:
1713 config->stopbits = 1;
1714 break;
1715 case TWOSTOPBITS:
1716 config->stopbits = 2;
1717 break;
1718 default:
1719 config->stopbits = -1;
1720 }
1721
e33ab9aa 1722 switch (data->dcb.fRtsControl) {
eac329d2
UH
1723 case RTS_CONTROL_DISABLE:
1724 config->rts = SP_RTS_OFF;
1725 break;
1726 case RTS_CONTROL_ENABLE:
1727 config->rts = SP_RTS_ON;
1728 break;
1729 case RTS_CONTROL_HANDSHAKE:
1730 config->rts = SP_RTS_FLOW_CONTROL;
1731 break;
1732 default:
1733 config->rts = -1;
067417af
ML
1734 }
1735
e33ab9aa 1736 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
067417af 1737
e33ab9aa 1738 switch (data->dcb.fDtrControl) {
eac329d2
UH
1739 case DTR_CONTROL_DISABLE:
1740 config->dtr = SP_DTR_OFF;
1741 break;
1742 case DTR_CONTROL_ENABLE:
1743 config->dtr = SP_DTR_ON;
1744 break;
1745 case DTR_CONTROL_HANDSHAKE:
1746 config->dtr = SP_DTR_FLOW_CONTROL;
1747 break;
1748 default:
1749 config->dtr = -1;
067417af
ML
1750 }
1751
e33ab9aa
ML
1752 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1753
c6754b45
ML
1754 if (data->dcb.fInX) {
1755 if (data->dcb.fOutX)
1756 config->xon_xoff = SP_XONXOFF_INOUT;
1757 else
1758 config->xon_xoff = SP_XONXOFF_IN;
1759 } else {
1760 if (data->dcb.fOutX)
1761 config->xon_xoff = SP_XONXOFF_OUT;
1762 else
1763 config->xon_xoff = SP_XONXOFF_DISABLED;
1764 }
1765
e33ab9aa
ML
1766#else // !_WIN32
1767
1768 if (tcgetattr(port->fd, &data->term) < 0)
c33efc48 1769 RETURN_FAIL("tcgetattr() failed");
e33ab9aa
ML
1770
1771 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
c33efc48 1772 RETURN_FAIL("TIOCMGET ioctl failed");
40978c2b
ML
1773
1774#ifdef USE_TERMIOX
bd791fe1 1775 int ret = get_flow(port->fd, data);
68ec29db
ML
1776
1777 if (ret == SP_ERR_FAIL && errno == EINVAL)
1778 data->termiox_supported = 0;
1779 else if (ret < 0)
c33efc48 1780 RETURN_CODEVAL(ret);
68ec29db
ML
1781 else
1782 data->termiox_supported = 1;
1783#else
1784 data->termiox_supported = 0;
40978c2b
ML
1785#endif
1786
067417af 1787 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
e33ab9aa 1788 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
067417af
ML
1789 config->baudrate = std_baudrates[i].value;
1790 break;
1791 }
1792 }
1793
31b3a8f5
MH
1794 if (i == NUM_STD_BAUDRATES) {
1795#ifdef __APPLE__
1796 config->baudrate = (int)data->term.c_ispeed;
5cea279a 1797#elif defined(USE_TERMIOS_SPEED)
7a6d2196 1798 TRY(get_baudrate(port->fd, &config->baudrate));
31b3a8f5 1799#else
067417af 1800 config->baudrate = -1;
31b3a8f5
MH
1801#endif
1802 }
067417af 1803
e33ab9aa 1804 switch (data->term.c_cflag & CSIZE) {
067417af
ML
1805 case CS8:
1806 config->bits = 8;
1807 break;
1808 case CS7:
1809 config->bits = 7;
1810 break;
1811 case CS6:
1812 config->bits = 6;
1813 break;
1814 case CS5:
1815 config->bits = 5;
1816 break;
1817 default:
1818 config->bits = -1;
1819 }
1820
e33ab9aa 1821 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
067417af 1822 config->parity = SP_PARITY_NONE;
e33ab9aa 1823 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
067417af 1824 config->parity = -1;
c3e05092 1825#ifdef CMSPAR
e432ce60
ML
1826 else if (data->term.c_cflag & CMSPAR)
1827 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
c3e05092 1828#endif
067417af 1829 else
e33ab9aa 1830 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
067417af 1831
e33ab9aa 1832 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
067417af 1833
e33ab9aa 1834 if (data->term.c_cflag & CRTSCTS) {
067417af
ML
1835 config->rts = SP_RTS_FLOW_CONTROL;
1836 config->cts = SP_CTS_FLOW_CONTROL;
1837 } else {
bd791fe1 1838 if (data->termiox_supported && data->rts_flow)
40978c2b
ML
1839 config->rts = SP_RTS_FLOW_CONTROL;
1840 else
1841 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1842
bd791fe1 1843 config->cts = (data->termiox_supported && data->cts_flow) ?
68ec29db 1844 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
067417af
ML
1845 }
1846
bd791fe1 1847 if (data->termiox_supported && data->dtr_flow)
40978c2b
ML
1848 config->dtr = SP_DTR_FLOW_CONTROL;
1849 else
1850 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1851
bd791fe1 1852 config->dsr = (data->termiox_supported && data->dsr_flow) ?
68ec29db 1853 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
705bdc69 1854
e29b93a5
ML
1855 if (data->term.c_iflag & IXOFF) {
1856 if (data->term.c_iflag & IXON)
1857 config->xon_xoff = SP_XONXOFF_INOUT;
1858 else
1859 config->xon_xoff = SP_XONXOFF_IN;
1860 } else {
1861 if (data->term.c_iflag & IXON)
1862 config->xon_xoff = SP_XONXOFF_OUT;
1863 else
1864 config->xon_xoff = SP_XONXOFF_DISABLED;
1865 }
067417af
ML
1866#endif
1867
c33efc48 1868 RETURN_OK();
067417af
ML
1869}
1870
7a6d2196 1871static enum sp_return set_config(struct sp_port *port, struct port_data *data,
eb6ed20f 1872 const struct sp_port_config *config)
18fc2dd1 1873{
e33ab9aa 1874 unsigned int i;
31b3a8f5
MH
1875#ifdef __APPLE__
1876 BAUD_TYPE baud_nonstd;
1877
1878 baud_nonstd = B0;
1879#endif
5cea279a 1880#ifdef USE_TERMIOS_SPEED
7a6d2196
ML
1881 int baud_nonstd = 0;
1882#endif
18fc2dd1 1883
c33efc48
ML
1884 TRACE("%p, %p, %p", port, data, config);
1885
7890cef6 1886 DEBUG_FMT("Setting configuration for port %s", port->name);
ea667be7 1887
e33ab9aa 1888#ifdef _WIN32
988ace6c 1889 BYTE* new_buf;
6bd6a8b5
ML
1890
1891 TRY(await_write_completion(port));
1892
eac329d2 1893 if (config->baudrate >= 0) {
e33ab9aa
ML
1894 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1895 if (config->baudrate == std_baudrates[i].value) {
1896 data->dcb.BaudRate = std_baudrates[i].index;
1897 break;
1898 }
1899 }
18fc2dd1 1900
e33ab9aa
ML
1901 if (i == NUM_STD_BAUDRATES)
1902 data->dcb.BaudRate = config->baudrate;
39df7833
ML
1903
1904 /* Allocate write buffer for 50ms of data at baud rate. */
1905 port->write_buf_size = max(config->baudrate / (8 * 20), 1);
988ace6c
ML
1906 new_buf = realloc(port->write_buf, port->write_buf_size);
1907 if (!new_buf)
39df7833 1908 RETURN_ERROR(SP_ERR_MEM, "Allocating write buffer failed");
988ace6c 1909 port->write_buf = new_buf;
e33ab9aa 1910 }
18fc2dd1 1911
e33ab9aa
ML
1912 if (config->bits >= 0)
1913 data->dcb.ByteSize = config->bits;
1914
1915 if (config->parity >= 0) {
1916 switch (config->parity) {
e33ab9aa
ML
1917 case SP_PARITY_NONE:
1918 data->dcb.Parity = NOPARITY;
1919 break;
e432ce60
ML
1920 case SP_PARITY_ODD:
1921 data->dcb.Parity = ODDPARITY;
1922 break;
e33ab9aa
ML
1923 case SP_PARITY_EVEN:
1924 data->dcb.Parity = EVENPARITY;
1925 break;
e432ce60
ML
1926 case SP_PARITY_MARK:
1927 data->dcb.Parity = MARKPARITY;
1928 break;
1929 case SP_PARITY_SPACE:
1930 data->dcb.Parity = SPACEPARITY;
e33ab9aa
ML
1931 break;
1932 default:
c33efc48 1933 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
e33ab9aa 1934 }
18fc2dd1
ML
1935 }
1936
e33ab9aa
ML
1937 if (config->stopbits >= 0) {
1938 switch (config->stopbits) {
1939 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1940 case 1:
1941 data->dcb.StopBits = ONESTOPBIT;
1942 break;
1943 case 2:
1944 data->dcb.StopBits = TWOSTOPBITS;
1945 break;
1946 default:
c33efc48 1947 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
e33ab9aa
ML
1948 }
1949 }
1950
1951 if (config->rts >= 0) {
1952 switch (config->rts) {
1953 case SP_RTS_OFF:
1954 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1955 break;
1956 case SP_RTS_ON:
1957 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1958 break;
1959 case SP_RTS_FLOW_CONTROL:
1960 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1961 break;
1962 default:
c33efc48 1963 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
e33ab9aa
ML
1964 }
1965 }
1966
1967 if (config->cts >= 0) {
1968 switch (config->cts) {
1969 case SP_CTS_IGNORE:
1970 data->dcb.fOutxCtsFlow = FALSE;
1971 break;
1972 case SP_CTS_FLOW_CONTROL:
1973 data->dcb.fOutxCtsFlow = TRUE;
1974 break;
1975 default:
c33efc48 1976 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
e33ab9aa
ML
1977 }
1978 }
1979
1980 if (config->dtr >= 0) {
1981 switch (config->dtr) {
1982 case SP_DTR_OFF:
1983 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1984 break;
1985 case SP_DTR_ON:
1986 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1987 break;
1988 case SP_DTR_FLOW_CONTROL:
1989 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1990 break;
1991 default:
c33efc48 1992 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
e33ab9aa
ML
1993 }
1994 }
1995
1996 if (config->dsr >= 0) {
1997 switch (config->dsr) {
1998 case SP_DSR_IGNORE:
1999 data->dcb.fOutxDsrFlow = FALSE;
2000 break;
2001 case SP_DSR_FLOW_CONTROL:
2002 data->dcb.fOutxDsrFlow = TRUE;
2003 break;
2004 default:
c33efc48 2005 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
e33ab9aa 2006 }
18fc2dd1
ML
2007 }
2008
e33ab9aa
ML
2009 if (config->xon_xoff >= 0) {
2010 switch (config->xon_xoff) {
2011 case SP_XONXOFF_DISABLED:
2012 data->dcb.fInX = FALSE;
2013 data->dcb.fOutX = FALSE;
2014 break;
2015 case SP_XONXOFF_IN:
2016 data->dcb.fInX = TRUE;
2017 data->dcb.fOutX = FALSE;
2018 break;
2019 case SP_XONXOFF_OUT:
2020 data->dcb.fInX = FALSE;
2021 data->dcb.fOutX = TRUE;
2022 break;
2023 case SP_XONXOFF_INOUT:
2024 data->dcb.fInX = TRUE;
2025 data->dcb.fOutX = TRUE;
2026 break;
2027 default:
c33efc48 2028 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
e33ab9aa
ML
2029 }
2030 }
2031
2032 if (!SetCommState(port->hdl, &data->dcb))
c33efc48 2033 RETURN_FAIL("SetCommState() failed");
e33ab9aa 2034
31b3a8f5 2035#else /* !_WIN32 */
e33ab9aa 2036
7a6d2196
ML
2037 int controlbits;
2038
eac329d2 2039 if (config->baudrate >= 0) {
e33ab9aa
ML
2040 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
2041 if (config->baudrate == std_baudrates[i].value) {
2042 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
c33efc48 2043 RETURN_FAIL("cfsetospeed() failed");
e33ab9aa
ML
2044
2045 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
c33efc48 2046 RETURN_FAIL("cfsetispeed() failed");
e33ab9aa
ML
2047 break;
2048 }
2049 }
2050
31b3a8f5
MH
2051 /* Non-standard baud rate */
2052 if (i == NUM_STD_BAUDRATES) {
2053#ifdef __APPLE__
24abdb68 2054 /* Set "dummy" baud rate. */
31b3a8f5 2055 if (cfsetspeed(&data->term, B9600) < 0)
c33efc48 2056 RETURN_FAIL("cfsetspeed() failed");
31b3a8f5 2057 baud_nonstd = config->baudrate;
5cea279a 2058#elif defined(USE_TERMIOS_SPEED)
7a6d2196 2059 baud_nonstd = 1;
31b3a8f5 2060#else
c33efc48 2061 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
31b3a8f5
MH
2062#endif
2063 }
e33ab9aa
ML
2064 }
2065
2066 if (config->bits >= 0) {
2067 data->term.c_cflag &= ~CSIZE;
2068 switch (config->bits) {
2069 case 8:
2070 data->term.c_cflag |= CS8;
2071 break;
2072 case 7:
2073 data->term.c_cflag |= CS7;
2074 break;
2075 case 6:
2076 data->term.c_cflag |= CS6;
2077 break;
23922313
UH
2078 case 5:
2079 data->term.c_cflag |= CS5;
2080 break;
e33ab9aa 2081 default:
c33efc48 2082 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
e33ab9aa
ML
2083 }
2084 }
2085
2086 if (config->parity >= 0) {
2087 data->term.c_iflag &= ~IGNPAR;
c3e05092
UH
2088 data->term.c_cflag &= ~(PARENB | PARODD);
2089#ifdef CMSPAR
2090 data->term.c_cflag &= ~CMSPAR;
2091#endif
e33ab9aa
ML
2092 switch (config->parity) {
2093 case SP_PARITY_NONE:
2094 data->term.c_iflag |= IGNPAR;
2095 break;
2096 case SP_PARITY_EVEN:
2097 data->term.c_cflag |= PARENB;
2098 break;
2099 case SP_PARITY_ODD:
2100 data->term.c_cflag |= PARENB | PARODD;
2101 break;
afb518f0 2102#ifdef CMSPAR
e432ce60 2103 case SP_PARITY_MARK:
c3e05092 2104 data->term.c_cflag |= PARENB | PARODD;
c3e05092 2105 data->term.c_cflag |= CMSPAR;
e432ce60
ML
2106 break;
2107 case SP_PARITY_SPACE:
c3e05092 2108 data->term.c_cflag |= PARENB;
c3e05092 2109 data->term.c_cflag |= CMSPAR;
e432ce60 2110 break;
afb518f0
ML
2111#else
2112 case SP_PARITY_MARK:
2113 case SP_PARITY_SPACE:
2114 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2115#endif
e33ab9aa 2116 default:
c33efc48 2117 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
e33ab9aa
ML
2118 }
2119 }
2120
2121 if (config->stopbits >= 0) {
2122 data->term.c_cflag &= ~CSTOPB;
2123 switch (config->stopbits) {
2124 case 1:
2125 data->term.c_cflag &= ~CSTOPB;
2126 break;
2127 case 2:
2128 data->term.c_cflag |= CSTOPB;
2129 break;
2130 default:
c33efc48 2131 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
e33ab9aa
ML
2132 }
2133 }
2134
eac329d2 2135 if (config->rts >= 0 || config->cts >= 0) {
68ec29db 2136 if (data->termiox_supported) {
bd791fe1 2137 data->rts_flow = data->cts_flow = 0;
68ec29db
ML
2138 switch (config->rts) {
2139 case SP_RTS_OFF:
2140 case SP_RTS_ON:
2141 controlbits = TIOCM_RTS;
2142 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
c33efc48 2143 RETURN_FAIL("Setting RTS signal level failed");
68ec29db
ML
2144 break;
2145 case SP_RTS_FLOW_CONTROL:
bd791fe1 2146 data->rts_flow = 1;
68ec29db
ML
2147 break;
2148 default:
2149 break;
e33ab9aa 2150 }
68ec29db 2151 if (config->cts == SP_CTS_FLOW_CONTROL)
bd791fe1 2152 data->cts_flow = 1;
e33ab9aa 2153
bd791fe1 2154 if (data->rts_flow && data->cts_flow)
e33ab9aa 2155 data->term.c_iflag |= CRTSCTS;
68ec29db
ML
2156 else
2157 data->term.c_iflag &= ~CRTSCTS;
2158 } else {
2159 /* Asymmetric use of RTS/CTS not supported. */
2160 if (data->term.c_iflag & CRTSCTS) {
2161 /* Flow control can only be disabled for both RTS & CTS together. */
2162 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2163 if (config->cts != SP_CTS_IGNORE)
c33efc48 2164 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
68ec29db
ML
2165 }
2166 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2167 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
c33efc48 2168 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
68ec29db 2169 }
e33ab9aa 2170 } else {
68ec29db
ML
2171 /* Flow control can only be enabled for both RTS & CTS together. */
2172 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2173 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
c33efc48 2174 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
68ec29db
ML
2175 }
2176
2177 if (config->rts >= 0) {
2178 if (config->rts == SP_RTS_FLOW_CONTROL) {
2179 data->term.c_iflag |= CRTSCTS;
2180 } else {
2181 controlbits = TIOCM_RTS;
2182 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2183 &controlbits) < 0)
c33efc48 2184 RETURN_FAIL("Setting RTS signal level failed");
68ec29db 2185 }
e33ab9aa
ML
2186 }
2187 }
2188 }
2189
eac329d2 2190 if (config->dtr >= 0 || config->dsr >= 0) {
68ec29db 2191 if (data->termiox_supported) {
bd791fe1 2192 data->dtr_flow = data->dsr_flow = 0;
68ec29db
ML
2193 switch (config->dtr) {
2194 case SP_DTR_OFF:
2195 case SP_DTR_ON:
2196 controlbits = TIOCM_DTR;
2197 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
c33efc48 2198 RETURN_FAIL("Setting DTR signal level failed");
68ec29db
ML
2199 break;
2200 case SP_DTR_FLOW_CONTROL:
bd791fe1 2201 data->dtr_flow = 1;
68ec29db
ML
2202 break;
2203 default:
2204 break;
2205 }
2206 if (config->dsr == SP_DSR_FLOW_CONTROL)
bd791fe1 2207 data->dsr_flow = 1;
68ec29db
ML
2208 } else {
2209 /* DTR/DSR flow control not supported. */
2210 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
c33efc48 2211 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
e33ab9aa 2212
68ec29db
ML
2213 if (config->dtr >= 0) {
2214 controlbits = TIOCM_DTR;
2215 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2216 &controlbits) < 0)
c33efc48 2217 RETURN_FAIL("Setting DTR signal level failed");
68ec29db 2218 }
e33ab9aa
ML
2219 }
2220 }
2221
2222 if (config->xon_xoff >= 0) {
2223 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2224 switch (config->xon_xoff) {
2225 case SP_XONXOFF_DISABLED:
2226 break;
2227 case SP_XONXOFF_IN:
2228 data->term.c_iflag |= IXOFF;
2229 break;
2230 case SP_XONXOFF_OUT:
2231 data->term.c_iflag |= IXON | IXANY;
2232 break;
2233 case SP_XONXOFF_INOUT:
2234 data->term.c_iflag |= IXON | IXOFF | IXANY;
2235 break;
2236 default:
c33efc48 2237 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
e33ab9aa
ML
2238 }
2239 }
2240
3f5c06d0 2241 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
c33efc48 2242 RETURN_FAIL("tcsetattr() failed");
31b3a8f5
MH
2243
2244#ifdef __APPLE__
2245 if (baud_nonstd != B0) {
2246 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
c33efc48 2247 RETURN_FAIL("IOSSIOSPEED ioctl failed");
dc422c04
UH
2248 /*
2249 * Set baud rates in data->term to correct, but incompatible
2250 * with tcsetattr() value, same as delivered by tcgetattr().
2251 */
31b3a8f5 2252 if (cfsetspeed(&data->term, baud_nonstd) < 0)
c33efc48 2253 RETURN_FAIL("cfsetspeed() failed");
31b3a8f5 2254 }
7a6d2196 2255#elif defined(__linux__)
5cea279a 2256#ifdef USE_TERMIOS_SPEED
7a6d2196
ML
2257 if (baud_nonstd)
2258 TRY(set_baudrate(port->fd, config->baudrate));
5cea279a 2259#endif
40978c2b 2260#ifdef USE_TERMIOX
68ec29db 2261 if (data->termiox_supported)
bd791fe1 2262 TRY(set_flow(port->fd, data));
40978c2b 2263#endif
7a6d2196 2264#endif
31b3a8f5
MH
2265
2266#endif /* !_WIN32 */
e33ab9aa 2267
c33efc48 2268 RETURN_OK();
e33ab9aa
ML
2269}
2270
970f279a 2271SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
9b1502ef 2272{
59131d60 2273 struct sp_port_config *config;
9b1502ef 2274
00d8c56d
UH
2275 TRACE("%p", config_ptr);
2276
9b1502ef
ML
2277 if (!config_ptr)
2278 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2279
59131d60
ML
2280 *config_ptr = NULL;
2281
2282 if (!(config = malloc(sizeof(struct sp_port_config))))
dc422c04 2283 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
9b1502ef 2284
59131d60
ML
2285 config->baudrate = -1;
2286 config->bits = -1;
2287 config->parity = -1;
2288 config->stopbits = -1;
2289 config->rts = -1;
2290 config->cts = -1;
2291 config->dtr = -1;
2292 config->dsr = -1;
2293
2294 *config_ptr = config;
2295
9b1502ef
ML
2296 RETURN_OK();
2297}
2298
970f279a 2299SP_API void sp_free_config(struct sp_port_config *config)
9b1502ef
ML
2300{
2301 TRACE("%p", config);
2302
2303 if (!config)
2304 DEBUG("Null config");
2305 else
2306 free(config);
2307
2308 RETURN();
2309}
2310
970f279a
AJ
2311SP_API enum sp_return sp_get_config(struct sp_port *port,
2312 struct sp_port_config *config)
70cd37de
ML
2313{
2314 struct port_data data;
2315
2316 TRACE("%p, %p", port, config);
2317
2318 CHECK_OPEN_PORT();
2319
2320 if (!config)
9b1502ef 2321 RETURN_ERROR(SP_ERR_ARG, "Null config");
70cd37de
ML
2322
2323 TRY(get_config(port, &data, config));
2324
2325 RETURN_OK();
2326}
2327
970f279a
AJ
2328SP_API enum sp_return sp_set_config(struct sp_port *port,
2329 const struct sp_port_config *config)
e33ab9aa 2330{
8f189c4c 2331 struct port_data data;
e33ab9aa
ML
2332 struct sp_port_config prev_config;
2333
c33efc48
ML
2334 TRACE("%p, %p", port, config);
2335
dec10e31 2336 CHECK_OPEN_PORT();
823690ae
ML
2337
2338 if (!config)
c33efc48 2339 RETURN_ERROR(SP_ERR_ARG, "Null config");
823690ae 2340
e33ab9aa
ML
2341 TRY(get_config(port, &data, &prev_config));
2342 TRY(set_config(port, &data, config));
74510d4b 2343
c33efc48 2344 RETURN_OK();
74510d4b
ML
2345}
2346
9b1502ef 2347#define CREATE_ACCESSORS(x, type) \
970f279a 2348SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
8f189c4c 2349 struct port_data data; \
e33ab9aa 2350 struct sp_port_config config; \
c33efc48 2351 TRACE("%p, %d", port, x); \
dec10e31 2352 CHECK_OPEN_PORT(); \
e33ab9aa
ML
2353 TRY(get_config(port, &data, &config)); \
2354 config.x = x; \
2355 TRY(set_config(port, &data, &config)); \
c33efc48 2356 RETURN_OK(); \
9b1502ef 2357} \
970f279a
AJ
2358SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2359 type *x) { \
00d8c56d 2360 TRACE("%p, %p", config, x); \
6aad5bdd
UH
2361 if (!x) \
2362 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
9b1502ef
ML
2363 if (!config) \
2364 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2365 *x = config->x; \
2366 RETURN_OK(); \
2367} \
970f279a
AJ
2368SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2369 type x) { \
9b1502ef
ML
2370 TRACE("%p, %d", config, x); \
2371 if (!config) \
2372 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2373 config->x = x; \
2374 RETURN_OK(); \
9069c2fb
ML
2375}
2376
9b1502ef
ML
2377CREATE_ACCESSORS(baudrate, int)
2378CREATE_ACCESSORS(bits, int)
2379CREATE_ACCESSORS(parity, enum sp_parity)
2380CREATE_ACCESSORS(stopbits, int)
2381CREATE_ACCESSORS(rts, enum sp_rts)
2382CREATE_ACCESSORS(cts, enum sp_cts)
2383CREATE_ACCESSORS(dtr, enum sp_dtr)
2384CREATE_ACCESSORS(dsr, enum sp_dsr)
2385CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2386
970f279a
AJ
2387SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2388 enum sp_flowcontrol flowcontrol)
e33ab9aa 2389{
9b1502ef
ML
2390 if (!config)
2391 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
dec10e31
ML
2392
2393 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2394 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
823690ae 2395
e33ab9aa 2396 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
9b1502ef 2397 config->xon_xoff = SP_XONXOFF_INOUT;
e33ab9aa 2398 else
9b1502ef 2399 config->xon_xoff = SP_XONXOFF_DISABLED;
e33ab9aa
ML
2400
2401 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
9b1502ef
ML
2402 config->rts = SP_RTS_FLOW_CONTROL;
2403 config->cts = SP_CTS_FLOW_CONTROL;
e33ab9aa 2404 } else {
9b1502ef
ML
2405 if (config->rts == SP_RTS_FLOW_CONTROL)
2406 config->rts = SP_RTS_ON;
2407 config->cts = SP_CTS_IGNORE;
e33ab9aa
ML
2408 }
2409
2410 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
9b1502ef
ML
2411 config->dtr = SP_DTR_FLOW_CONTROL;
2412 config->dsr = SP_DSR_FLOW_CONTROL;
e33ab9aa 2413 } else {
9b1502ef
ML
2414 if (config->dtr == SP_DTR_FLOW_CONTROL)
2415 config->dtr = SP_DTR_ON;
2416 config->dsr = SP_DSR_IGNORE;
e33ab9aa
ML
2417 }
2418
9b1502ef
ML
2419 RETURN_OK();
2420}
2421
970f279a
AJ
2422SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2423 enum sp_flowcontrol flowcontrol)
9b1502ef
ML
2424{
2425 struct port_data data;
2426 struct sp_port_config config;
2427
2428 TRACE("%p, %d", port, flowcontrol);
2429
2430 CHECK_OPEN_PORT();
2431
2432 TRY(get_config(port, &data, &config));
2433
2434 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2435
e33ab9aa
ML
2436 TRY(set_config(port, &data, &config));
2437
c33efc48 2438 RETURN_OK();
e33ab9aa
ML
2439}
2440
970f279a
AJ
2441SP_API enum sp_return sp_get_signals(struct sp_port *port,
2442 enum sp_signal *signals)
8cf7c697 2443{
c33efc48
ML
2444 TRACE("%p, %p", port, signals);
2445
dec10e31 2446 CHECK_OPEN_PORT();
8cf7c697
ML
2447
2448 if (!signals)
c33efc48 2449 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
8cf7c697 2450
7890cef6 2451 DEBUG_FMT("Getting control signals for port %s", port->name);
ea667be7 2452
8cf7c697
ML
2453 *signals = 0;
2454#ifdef _WIN32
2455 DWORD bits;
2456 if (GetCommModemStatus(port->hdl, &bits) == 0)
c33efc48 2457 RETURN_FAIL("GetCommModemStatus() failed");
8cf7c697
ML
2458 if (bits & MS_CTS_ON)
2459 *signals |= SP_SIG_CTS;
2460 if (bits & MS_DSR_ON)
2461 *signals |= SP_SIG_DSR;
8cf7c697 2462 if (bits & MS_RLSD_ON)
a6cda1e8
ML
2463 *signals |= SP_SIG_DCD;
2464 if (bits & MS_RING_ON)
8cf7c697
ML
2465 *signals |= SP_SIG_RI;
2466#else
2467 int bits;
2468 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
c33efc48 2469 RETURN_FAIL("TIOCMGET ioctl failed");
8cf7c697
ML
2470 if (bits & TIOCM_CTS)
2471 *signals |= SP_SIG_CTS;
2472 if (bits & TIOCM_DSR)
2473 *signals |= SP_SIG_DSR;
2474 if (bits & TIOCM_CAR)
2475 *signals |= SP_SIG_DCD;
2476 if (bits & TIOCM_RNG)
2477 *signals |= SP_SIG_RI;
2478#endif
c33efc48 2479 RETURN_OK();
8cf7c697
ML
2480}
2481
970f279a 2482SP_API enum sp_return sp_start_break(struct sp_port *port)
90cc3ee6 2483{
c33efc48
ML
2484 TRACE("%p", port);
2485
dec10e31 2486 CHECK_OPEN_PORT();
90cc3ee6
ML
2487#ifdef _WIN32
2488 if (SetCommBreak(port->hdl) == 0)
c33efc48 2489 RETURN_FAIL("SetCommBreak() failed");
90cc3ee6
ML
2490#else
2491 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
c33efc48 2492 RETURN_FAIL("TIOCSBRK ioctl failed");
90cc3ee6
ML
2493#endif
2494
c33efc48 2495 RETURN_OK();
90cc3ee6
ML
2496}
2497
970f279a 2498SP_API enum sp_return sp_end_break(struct sp_port *port)
90cc3ee6 2499{
c33efc48
ML
2500 TRACE("%p", port);
2501
dec10e31 2502 CHECK_OPEN_PORT();
90cc3ee6
ML
2503#ifdef _WIN32
2504 if (ClearCommBreak(port->hdl) == 0)
c33efc48 2505 RETURN_FAIL("ClearCommBreak() failed");
90cc3ee6
ML
2506#else
2507 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
c33efc48 2508 RETURN_FAIL("TIOCCBRK ioctl failed");
90cc3ee6
ML
2509#endif
2510
c33efc48 2511 RETURN_OK();
90cc3ee6
ML
2512}
2513
970f279a 2514SP_API int sp_last_error_code(void)
74510d4b 2515{
7890cef6 2516 TRACE_VOID();
74510d4b 2517#ifdef _WIN32
9caa2e86 2518 RETURN_INT(GetLastError());
74510d4b 2519#else
9caa2e86 2520 RETURN_INT(errno);
74510d4b
ML
2521#endif
2522}
2523
970f279a 2524SP_API char *sp_last_error_message(void)
74510d4b 2525{
7890cef6 2526 TRACE_VOID();
c33efc48 2527
74510d4b 2528#ifdef _WIN32
bf40b1ce 2529 char *message;
74510d4b
ML
2530 DWORD error = GetLastError();
2531
bf40b1ce 2532 DWORD length = FormatMessageA(
74510d4b
ML
2533 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2534 FORMAT_MESSAGE_FROM_SYSTEM |
2535 FORMAT_MESSAGE_IGNORE_INSERTS,
2536 NULL,
2537 error,
2538 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
bf40b1ce 2539 (LPSTR) &message,
74510d4b
ML
2540 0, NULL );
2541
9a0c4bbd
ML
2542 if (length >= 2 && message[length - 2] == '\r')
2543 message[length - 2] = '\0';
2544
9caa2e86 2545 RETURN_STRING(message);
74510d4b 2546#else
9caa2e86 2547 RETURN_STRING(strerror(errno));
74510d4b
ML
2548#endif
2549}
2550
970f279a 2551SP_API void sp_free_error_message(char *message)
74510d4b 2552{
c33efc48
ML
2553 TRACE("%s", message);
2554
74510d4b
ML
2555#ifdef _WIN32
2556 LocalFree(message);
64eec30d
ML
2557#else
2558 (void)message;
74510d4b 2559#endif
c33efc48
ML
2560
2561 RETURN();
74510d4b 2562}
863b35e6 2563
970f279a 2564SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
863b35e6 2565{
c33efc48
ML
2566 TRACE("%p", handler);
2567
863b35e6 2568 sp_debug_handler = handler;
c33efc48
ML
2569
2570 RETURN();
863b35e6
ML
2571}
2572
970f279a 2573SP_API void sp_default_debug_handler(const char *format, ...)
863b35e6
ML
2574{
2575 va_list args;
2576 va_start(args, format);
2577 if (getenv("LIBSERIALPORT_DEBUG")) {
dd7742fb 2578 fputs("sp: ", stderr);
863b35e6
ML
2579 vfprintf(stderr, format, args);
2580 }
2581 va_end(args);
2582}
524b0e14 2583
970f279a 2584SP_API int sp_get_major_package_version(void)
524b0e14
UH
2585{
2586 return SP_PACKAGE_VERSION_MAJOR;
2587}
2588
970f279a 2589SP_API int sp_get_minor_package_version(void)
524b0e14
UH
2590{
2591 return SP_PACKAGE_VERSION_MINOR;
2592}
2593
970f279a 2594SP_API int sp_get_micro_package_version(void)
524b0e14
UH
2595{
2596 return SP_PACKAGE_VERSION_MICRO;
2597}
2598
970f279a 2599SP_API const char *sp_get_package_version_string(void)
524b0e14
UH
2600{
2601 return SP_PACKAGE_VERSION_STRING;
2602}
2603
970f279a 2604SP_API int sp_get_current_lib_version(void)
524b0e14
UH
2605{
2606 return SP_LIB_VERSION_CURRENT;
2607}
2608
970f279a 2609SP_API int sp_get_revision_lib_version(void)
524b0e14
UH
2610{
2611 return SP_LIB_VERSION_REVISION;
2612}
2613
970f279a 2614SP_API int sp_get_age_lib_version(void)
524b0e14
UH
2615{
2616 return SP_LIB_VERSION_AGE;
2617}
2618
970f279a 2619SP_API const char *sp_get_lib_version_string(void)
524b0e14
UH
2620{
2621 return SP_LIB_VERSION_STRING;
2622}
2623
2624/** @} */