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