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