]> sigrok.org Git - libserialport.git/blame - serialport.c
Minor cosmetics.
[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
74510d4b
ML
37#include <termios.h>
38#include <sys/ioctl.h>
39#endif
3b63f34d 40#ifdef __APPLE__
1ebf4347
ML
41#include <IOKit/IOKitLib.h>
42#include <IOKit/serial/IOSerialKeys.h>
31b3a8f5 43#include <IOKit/serial/ioss.h>
1ebf4347 44#include <sys/syslimits.h>
3b63f34d
ML
45#endif
46#ifdef __linux__
47#include "libudev.h"
4b97c9fc 48#include "linux/serial.h"
7a6d2196 49#include "linux_termios.h"
40978c2b 50#if defined(TCGETX) && defined(TCSETX) && defined(HAVE_TERMIOX)
68ec29db 51#define USE_TERMIOX
40978c2b 52#endif
3b63f34d 53#endif
74510d4b 54
71c8a9b9
UH
55#ifndef _WIN32
56#include "linux_termios.h"
57#endif
58
f6a1fb65 59#include "libserialport.h"
74510d4b 60
1c5aae9d
ML
61struct sp_port {
62 char *name;
33d5ff47 63 int nonblocking;
1c5aae9d
ML
64#ifdef _WIN32
65 HANDLE hdl;
a3cb91f5 66 OVERLAPPED write_ovl;
0765af56 67 BYTE pending_byte;
a3cb91f5 68 BOOL writing;
1c5aae9d
ML
69#else
70 int fd;
71#endif
72};
73
9b1502ef
ML
74struct sp_port_config {
75 int baudrate;
76 int bits;
77 enum sp_parity parity;
78 int stopbits;
79 enum sp_rts rts;
80 enum sp_cts cts;
81 enum sp_dtr dtr;
82 enum sp_dsr dsr;
83 enum sp_xonxoff xon_xoff;
84};
85
8f189c4c 86struct port_data {
8094e4a0
ML
87#ifdef _WIN32
88 DCB dcb;
89#else
90 struct termios term;
824dcb45 91 int controlbits;
68ec29db 92 int termiox_supported;
40978c2b
ML
93 int flow;
94#endif
8094e4a0
ML
95};
96
da2748bf
ML
97/* Standard baud rates. */
98#ifdef _WIN32
99#define BAUD_TYPE DWORD
100#define BAUD(n) {CBR_##n, n}
101#else
102#define BAUD_TYPE speed_t
103#define BAUD(n) {B##n, n}
104#endif
105
106struct std_baudrate {
107 BAUD_TYPE index;
108 int value;
109};
110
111const struct std_baudrate std_baudrates[] = {
112#ifdef _WIN32
113 /*
114 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
115 * have documented CBR_* macros.
116 */
117 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
118 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
eac329d2 119 BAUD(115200), BAUD(128000), BAUD(256000),
da2748bf 120#else
eac329d2
UH
121 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
122 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
123 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
124 BAUD(230400),
da2748bf 125#if !defined(__APPLE__) && !defined(__OpenBSD__)
eac329d2 126 BAUD(460800),
da2748bf
ML
127#endif
128#endif
129};
130
863b35e6
ML
131void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
132
da2748bf
ML
133#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
134#define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
135
92f756f8
ML
136/* Debug output macros. */
137#define DEBUG(fmt, ...) do { if (sp_debug_handler) sp_debug_handler(fmt ".\n", ##__VA_ARGS__); } while (0)
138#define DEBUG_ERROR(err, msg) DEBUG("%s returning " #err ": " msg, __func__)
139#define DEBUG_FAIL(msg) do { \
140 char *errmsg = sp_last_error_message(); \
141 DEBUG("%s returning SP_ERR_FAIL: " msg ": %s", __func__, errmsg); \
142 sp_free_error_message(errmsg); \
143} while (0);
144#define RETURN() do { DEBUG("%s returning", __func__); return; } while(0)
145#define RETURN_CODE(x) do { DEBUG("%s returning " #x, __func__); return x; } while (0)
146#define RETURN_CODEVAL(x) do { \
147 switch (x) { \
148 case SP_OK: RETURN_CODE(SP_OK); \
149 case SP_ERR_ARG: RETURN_CODE(SP_ERR_ARG); \
150 case SP_ERR_FAIL: RETURN_CODE(SP_ERR_FAIL); \
151 case SP_ERR_MEM: RETURN_CODE(SP_ERR_MEM); \
152 case SP_ERR_SUPP: RETURN_CODE(SP_ERR_SUPP); \
153 } \
154} while (0)
155#define RETURN_OK() RETURN_CODE(SP_OK);
156#define RETURN_ERROR(err, msg) do { DEBUG_ERROR(err, msg); return err; } while (0)
157#define RETURN_FAIL(msg) do { DEBUG_FAIL(msg); return SP_ERR_FAIL; } while (0)
158#define RETURN_VALUE(fmt, x) do { DEBUG("%s returning " fmt, __func__, x); return x; } while (0)
159#define SET_ERROR(val, err, msg) do { DEBUG_ERROR(err, msg); val = err; } while (0)
aac4d7f2 160#define SET_FAIL(val, msg) do { DEBUG_FAIL(msg); val = SP_ERR_FAIL; } while (0)
92f756f8
ML
161#define TRACE(fmt, ...) DEBUG("%s(" fmt ") called", __func__, ##__VA_ARGS__)
162
64690702
ML
163#define TRY(x) do { int ret = x; if (ret != SP_OK) RETURN_CODEVAL(ret); } while (0)
164
348e23cc 165/* Helper functions. */
348e23cc 166static struct sp_port **list_append(struct sp_port **list, const char *portname);
eb6ed20f
ML
167static enum sp_return get_config(struct sp_port *port, struct port_data *data,
168 struct sp_port_config *config);
169static enum sp_return set_config(struct sp_port *port, struct port_data *data,
170 const struct sp_port_config *config);
80186526 171
eb6ed20f 172enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
d54e9004
ML
173{
174 struct sp_port *port;
5919c913 175 int len;
d54e9004 176
c33efc48
ML
177 TRACE("%s, %p", portname, port_ptr);
178
32b5ac05 179 if (!port_ptr)
c33efc48 180 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
32b5ac05 181
77f262c4
ML
182 *port_ptr = NULL;
183
d4babed2 184 if (!portname)
c33efc48 185 RETURN_ERROR(SP_ERR_ARG, "Null port name");
d4babed2 186
ea667be7
ML
187 DEBUG("Building structure for port %s", portname);
188
d54e9004 189 if (!(port = malloc(sizeof(struct sp_port))))
c33efc48 190 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
d54e9004 191
5919c913
ML
192 len = strlen(portname) + 1;
193
eac329d2 194 if (!(port->name = malloc(len))) {
d54e9004 195 free(port);
c33efc48 196 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
d54e9004
ML
197 }
198
199 memcpy(port->name, portname, len);
200
8f471c66
ML
201#ifdef _WIN32
202 port->hdl = INVALID_HANDLE_VALUE;
203#else
204 port->fd = -1;
205#endif
206
77f262c4
ML
207 *port_ptr = port;
208
c33efc48 209 RETURN_OK();
d54e9004
ML
210}
211
1c5aae9d
ML
212char *sp_get_port_name(const struct sp_port *port)
213{
214 TRACE("%p", port);
215
216 if (!port)
217 return NULL;
218
219 RETURN_VALUE("%s", port->name);
220}
221
3c126654
ML
222enum sp_return sp_get_port_handle(const struct sp_port *port, void *result_ptr)
223{
00d8c56d 224 TRACE("%p, %p", port, result_ptr);
3c126654
ML
225
226 if (!port)
227 RETURN_ERROR(SP_ERR_ARG, "Null port");
228
229#ifdef _WIN32
230 HANDLE *handle_ptr = result_ptr;
231 *handle_ptr = port->hdl;
232#else
233 int *fd_ptr = result_ptr;
234 *fd_ptr = port->fd;
235#endif
236
237 RETURN_OK();
238}
239
eb6ed20f 240enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
32b5ac05 241{
c33efc48
ML
242 TRACE("%p, %p", port, copy_ptr);
243
32b5ac05 244 if (!copy_ptr)
c33efc48 245 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
32b5ac05
ML
246
247 *copy_ptr = NULL;
248
c33efc48
ML
249 if (!port)
250 RETURN_ERROR(SP_ERR_ARG, "Null port");
251
252 if (!port->name)
253 RETURN_ERROR(SP_ERR_ARG, "Null port name");
32b5ac05 254
ea667be7
ML
255 DEBUG("Copying port structure");
256
c33efc48 257 RETURN_VALUE("%p", sp_get_port_by_name(port->name, copy_ptr));
32b5ac05
ML
258}
259
e3b2f7a4
ML
260void sp_free_port(struct sp_port *port)
261{
c33efc48
ML
262 TRACE("%p", port);
263
00d8c56d 264 if (!port) {
c33efc48
ML
265 DEBUG("Null port");
266 RETURN();
267 }
e3b2f7a4 268
ea667be7
ML
269 DEBUG("Freeing port structure");
270
e3b2f7a4
ML
271 if (port->name)
272 free(port->name);
273
274 free(port);
c33efc48
ML
275
276 RETURN();
e3b2f7a4
ML
277}
278
348e23cc 279static struct sp_port **list_append(struct sp_port **list, const char *portname)
3b63f34d
ML
280{
281 void *tmp;
282 unsigned int count;
f92f1f0c 283
3b63f34d 284 for (count = 0; list[count]; count++);
d54e9004 285 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
3b63f34d
ML
286 goto fail;
287 list = tmp;
77f262c4 288 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
3b63f34d 289 goto fail;
db2794ce 290 list[count + 1] = NULL;
3b63f34d 291 return list;
f92f1f0c 292
3b63f34d
ML
293fail:
294 sp_free_port_list(list);
295 return NULL;
296}
297
eb6ed20f 298enum sp_return sp_list_ports(struct sp_port ***list_ptr)
3b63f34d 299{
d54e9004 300 struct sp_port **list;
6b93ede4 301 int ret = SP_ERR_SUPP;
24c1a4bb 302
c33efc48
ML
303 TRACE("%p", list_ptr);
304
dec10e31
ML
305 if (!list_ptr)
306 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
307
ea667be7
ML
308 DEBUG("Enumerating ports");
309
d54e9004 310 if (!(list = malloc(sizeof(struct sp_port **))))
c33efc48 311 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
24c1a4bb
ML
312
313 list[0] = NULL;
3b63f34d
ML
314
315#ifdef _WIN32
316 HKEY key;
bdfb5b8c
ML
317 TCHAR *value, *data;
318 DWORD max_value_len, max_data_size, max_data_len;
319 DWORD value_len, data_size, data_len;
3b63f34d 320 DWORD type, index = 0;
8b532d9c
ML
321 char *name;
322 int name_len;
3b63f34d 323
6b93ede4
ML
324 ret = SP_OK;
325
ea667be7 326 DEBUG("Opening registry key");
3b63f34d 327 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
eac329d2 328 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
c33efc48 329 SET_FAIL(ret, "RegOpenKeyEx() failed");
77f262c4
ML
330 goto out_done;
331 }
ea667be7 332 DEBUG("Querying registry key value and data sizes");
3b63f34d 333 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
eac329d2 334 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
c33efc48 335 SET_FAIL(ret, "RegQueryInfoKey() failed");
3b63f34d 336 goto out_close;
77f262c4 337 }
3b63f34d 338 max_data_len = max_data_size / sizeof(TCHAR);
eac329d2 339 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
c33efc48 340 SET_ERROR(ret, SP_ERR_MEM, "registry value malloc failed");
3b63f34d 341 goto out_close;
77f262c4 342 }
eac329d2 343 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
c33efc48 344 SET_ERROR(ret, SP_ERR_MEM, "registry data malloc failed");
bdfb5b8c 345 goto out_free_value;
77f262c4 346 }
ea667be7 347 DEBUG("Iterating over values");
3b63f34d 348 while (
d9573bad 349 value_len = max_value_len + 1,
3b63f34d 350 data_size = max_data_size,
bdfb5b8c 351 RegEnumValue(key, index, value, &value_len,
3b63f34d
ML
352 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
353 {
354 data_len = data_size / sizeof(TCHAR);
355 data[data_len] = '\0';
8b532d9c
ML
356#ifdef UNICODE
357 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
358#else
359 name_len = data_len + 1;
360#endif
eac329d2 361 if (!(name = malloc(name_len))) {
c33efc48 362 SET_ERROR(ret, SP_ERR_MEM, "registry port name malloc failed");
8b532d9c 363 goto out;
77f262c4 364 }
8b532d9c
ML
365#ifdef UNICODE
366 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
367#else
368 strcpy(name, data);
369#endif
c33efc48
ML
370 if (type == REG_SZ) {
371 DEBUG("Found port %s", name);
372 if (!(list = list_append(list, name))) {
373 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
374 goto out;
375 }
77f262c4 376 }
3b63f34d
ML
377 index++;
378 }
379out:
380 free(data);
bdfb5b8c
ML
381out_free_value:
382 free(value);
3b63f34d
ML
383out_close:
384 RegCloseKey(key);
77f262c4 385out_done:
3b63f34d
ML
386#endif
387#ifdef __APPLE__
388 mach_port_t master;
389 CFMutableDictionaryRef classes;
390 io_iterator_t iter;
391 char *path;
392 io_object_t port;
393 CFTypeRef cf_path;
394 Boolean result;
395
6b93ede4
ML
396 ret = SP_OK;
397
ea667be7 398 DEBUG("Getting IOKit master port");
eac329d2 399 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS) {
c33efc48 400 SET_FAIL(ret, "IOMasterPort() failed");
77f262c4
ML
401 goto out_done;
402 }
3b63f34d 403
ea667be7 404 DEBUG("Creating matching dictionary");
eac329d2 405 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) {
c33efc48 406 SET_FAIL(ret, "IOServiceMatching() failed");
77f262c4
ML
407 goto out_done;
408 }
3b63f34d
ML
409
410 CFDictionarySetValue(classes,
411 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
412
ea667be7 413 DEBUG("Getting matching services");
eac329d2 414 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS) {
c33efc48 415 SET_FAIL(ret, "IOServiceGetMatchingServices() failed");
77f262c4
ML
416 goto out_done;
417 }
3b63f34d 418
eac329d2 419 if (!(path = malloc(PATH_MAX))) {
c33efc48 420 SET_ERROR(ret, SP_ERR_MEM, "device path malloc failed");
3b63f34d 421 goto out_release;
77f262c4 422 }
3b63f34d 423
ea667be7 424 DEBUG("Iterating over results");
1ebf4347 425 while ((port = IOIteratorNext(iter))) {
3b63f34d
ML
426 cf_path = IORegistryEntryCreateCFProperty(port,
427 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
428 if (cf_path) {
429 result = CFStringGetCString(cf_path,
430 path, PATH_MAX, kCFStringEncodingASCII);
431 CFRelease(cf_path);
c33efc48
ML
432 if (result) {
433 DEBUG("Found port %s", path);
434 if (!(list = list_append(list, path))) {
435 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
436 IOObjectRelease(port);
437 goto out;
438 }
77f262c4 439 }
3b63f34d
ML
440 }
441 IOObjectRelease(port);
442 }
3b63f34d
ML
443out:
444 free(path);
445out_release:
446 IOObjectRelease(iter);
77f262c4 447out_done:
3b63f34d
ML
448#endif
449#ifdef __linux__
450 struct udev *ud;
451 struct udev_enumerate *ud_enumerate;
452 struct udev_list_entry *ud_list;
453 struct udev_list_entry *ud_entry;
454 const char *path;
08fe0bdb 455 struct udev_device *ud_dev, *ud_parent;
3b63f34d 456 const char *name;
4b97c9fc
ML
457 const char *driver;
458 int fd, ioctl_result;
459 struct serial_struct serial_info;
3b63f34d 460
6b93ede4
ML
461 ret = SP_OK;
462
ea667be7 463 DEBUG("Enumerating tty devices");
3b63f34d
ML
464 ud = udev_new();
465 ud_enumerate = udev_enumerate_new(ud);
466 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
467 udev_enumerate_scan_devices(ud_enumerate);
468 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
ea667be7 469 DEBUG("Iterating over results");
eac329d2 470 udev_list_entry_foreach(ud_entry, ud_list) {
3b63f34d 471 path = udev_list_entry_get_name(ud_entry);
ea667be7 472 DEBUG("Found device %s", path);
3b63f34d 473 ud_dev = udev_device_new_from_syspath(ud, path);
08fe0bdb
ML
474 /* If there is no parent device, this is a virtual tty. */
475 ud_parent = udev_device_get_parent(ud_dev);
eac329d2 476 if (ud_parent == NULL) {
ea667be7 477 DEBUG("No parent device, assuming virtual tty");
08fe0bdb
ML
478 udev_device_unref(ud_dev);
479 continue;
480 }
3b63f34d 481 name = udev_device_get_devnode(ud_dev);
4b97c9fc
ML
482 /* The serial8250 driver has a hardcoded number of ports.
483 * The only way to tell which actually exist on a given system
484 * is to try to open them and make an ioctl call. */
485 driver = udev_device_get_driver(ud_parent);
eac329d2 486 if (driver && !strcmp(driver, "serial8250")) {
ea667be7
ML
487 DEBUG("serial8250 device, attempting to open");
488 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0) {
489 DEBUG("open failed, skipping");
4b97c9fc 490 goto skip;
ea667be7 491 }
4b97c9fc
ML
492 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
493 close(fd);
ea667be7
ML
494 if (ioctl_result != 0) {
495 DEBUG("ioctl failed, skipping");
4b97c9fc 496 goto skip;
ea667be7
ML
497 }
498 if (serial_info.type == PORT_UNKNOWN) {
499 DEBUG("port type is unknown, skipping");
4b97c9fc 500 goto skip;
ea667be7 501 }
4b97c9fc 502 }
c33efc48 503 DEBUG("Found port %s", name);
348e23cc 504 list = list_append(list, name);
4b97c9fc 505skip:
3b63f34d 506 udev_device_unref(ud_dev);
eac329d2 507 if (!list) {
c33efc48 508 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
3b63f34d 509 goto out;
77f262c4 510 }
3b63f34d
ML
511 }
512out:
513 udev_enumerate_unref(ud_enumerate);
514 udev_unref(ud);
3b63f34d 515#endif
77f262c4 516
6b93ede4
ML
517 switch (ret) {
518 case SP_OK:
77f262c4 519 *list_ptr = list;
c33efc48 520 RETURN_OK();
6b93ede4
ML
521 case SP_ERR_SUPP:
522 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform.");
523 default:
77f262c4
ML
524 if (list)
525 sp_free_port_list(list);
77f262c4 526 *list_ptr = NULL;
c33efc48 527 return ret;
77f262c4 528 }
3b63f34d
ML
529}
530
d54e9004 531void sp_free_port_list(struct sp_port **list)
3b63f34d
ML
532{
533 unsigned int i;
f92f1f0c 534
c33efc48
ML
535 TRACE("%p", list);
536
dec10e31
ML
537 if (!list) {
538 DEBUG("Null list");
539 RETURN();
540 }
541
ea667be7
ML
542 DEBUG("Freeing port list");
543
3b63f34d 544 for (i = 0; list[i]; i++)
e3b2f7a4 545 sp_free_port(list[i]);
3b63f34d 546 free(list);
c33efc48
ML
547
548 RETURN();
3b63f34d
ML
549}
550
c33efc48
ML
551#define CHECK_PORT() do { \
552 if (port == NULL) \
553 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
dec10e31
ML
554 if (port->name == NULL) \
555 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
556} while (0)
557#ifdef _WIN32
558#define CHECK_PORT_HANDLE() do { \
c33efc48
ML
559 if (port->hdl == INVALID_HANDLE_VALUE) \
560 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
dec10e31 561} while (0)
74510d4b 562#else
dec10e31 563#define CHECK_PORT_HANDLE() do { \
c33efc48
ML
564 if (port->fd < 0) \
565 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
dec10e31 566} while (0)
74510d4b 567#endif
dec10e31
ML
568#define CHECK_OPEN_PORT() do { \
569 CHECK_PORT(); \
570 CHECK_PORT_HANDLE(); \
571} while (0)
74510d4b 572
eb6ed20f 573enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
74510d4b 574{
bccc7c9f
ML
575 struct port_data data;
576 struct sp_port_config config;
577 enum sp_return ret;
578
00d8c56d 579 TRACE("%p, 0x%x", port, flags);
c33efc48 580
dec10e31
ML
581 CHECK_PORT();
582
583 if (flags > (SP_MODE_READ | SP_MODE_WRITE | SP_MODE_NONBLOCK))
584 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
74510d4b 585
ea667be7
ML
586 DEBUG("Opening port %s", port->name);
587
33d5ff47
ML
588 port->nonblocking = (flags & SP_MODE_NONBLOCK) ? 1 : 0;
589
74510d4b
ML
590#ifdef _WIN32
591 DWORD desired_access = 0, flags_and_attributes = 0;
a3cb91f5 592 COMMTIMEOUTS timeouts;
99945a1f
ML
593 char *escaped_port_name;
594
595 /* Prefix port name with '\\.\' to work with ports above COM9. */
596 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
c33efc48 597 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
99945a1f
ML
598 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
599
74510d4b 600 /* Map 'flags' to the OS-specific settings. */
74510d4b 601 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
a036341b
ML
602 if (flags & SP_MODE_READ)
603 desired_access |= GENERIC_READ;
604 if (flags & SP_MODE_WRITE)
74510d4b
ML
605 desired_access |= GENERIC_WRITE;
606 if (flags & SP_MODE_NONBLOCK)
607 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
608
99945a1f 609 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
74510d4b 610 OPEN_EXISTING, flags_and_attributes, 0);
99945a1f
ML
611
612 free(escaped_port_name);
613
74510d4b 614 if (port->hdl == INVALID_HANDLE_VALUE)
c33efc48 615 RETURN_FAIL("CreateFile() failed");
a3cb91f5
ML
616
617 /* All timeouts disabled. */
618 timeouts.ReadIntervalTimeout = 0;
619 timeouts.ReadTotalTimeoutMultiplier = 0;
620 timeouts.ReadTotalTimeoutConstant = 0;
621 timeouts.WriteTotalTimeoutMultiplier = 0;
622 timeouts.WriteTotalTimeoutConstant = 0;
623
624 if (port->nonblocking) {
625 /* Set read timeout such that all reads return immediately. */
626 timeouts.ReadIntervalTimeout = MAXDWORD;
627 /* Prepare OVERLAPPED structure for non-blocking writes. */
628 memset(&port->write_ovl, 0, sizeof(port->write_ovl));
629 if (!(port->write_ovl.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) {
630 sp_close(port);
631 RETURN_FAIL("CreateEvent() failed");
632 }
a3cb91f5
ML
633 port->writing = FALSE;
634 }
635
636 if (SetCommTimeouts(port->hdl, &timeouts) == 0) {
637 sp_close(port);
638 RETURN_FAIL("SetCommTimeouts() failed");
639 }
74510d4b
ML
640#else
641 int flags_local = 0;
f92f1f0c 642
74510d4b 643 /* Map 'flags' to the OS-specific settings. */
a036341b 644 if (flags & (SP_MODE_READ | SP_MODE_WRITE))
74510d4b 645 flags_local |= O_RDWR;
a036341b 646 else if (flags & SP_MODE_READ)
74510d4b 647 flags_local |= O_RDONLY;
a036341b
ML
648 else if (flags & SP_MODE_WRITE)
649 flags_local |= O_WRONLY;
74510d4b
ML
650 if (flags & SP_MODE_NONBLOCK)
651 flags_local |= O_NONBLOCK;
652
653 if ((port->fd = open(port->name, flags_local)) < 0)
c33efc48 654 RETURN_FAIL("open() failed");
bccc7c9f 655#endif
9cb98459 656
e33ab9aa
ML
657 ret = get_config(port, &data, &config);
658
eac329d2 659 if (ret < 0) {
e33ab9aa 660 sp_close(port);
c33efc48 661 RETURN_CODEVAL(ret);
e33ab9aa 662 }
9cb98459 663
bccc7c9f
ML
664 /* Set sane port settings. */
665#ifdef _WIN32
666 data.dcb.fBinary = TRUE;
667 data.dcb.fDsrSensitivity = FALSE;
668 data.dcb.fErrorChar = FALSE;
669 data.dcb.fNull = FALSE;
670 data.dcb.fAbortOnError = TRUE;
671#else
b251be4b 672 /* Turn off all fancy termios tricks, give us a raw channel. */
c3e05092
UH
673 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
674#ifdef IUCLC
675 data.term.c_iflag &= ~IUCLC;
676#endif
677 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
678#ifdef OLCUC
679 data.term.c_oflag &= ~OLCUC;
680#endif
681#ifdef NLDLY
682 data.term.c_oflag &= ~NLDLY;
683#endif
684#ifdef CRDLY
685 data.term.c_oflag &= ~CRDLY;
686#endif
687#ifdef TABDLY
688 data.term.c_oflag &= ~TABDLY;
689#endif
690#ifdef BSDLY
691 data.term.c_oflag &= ~BSDLY;
692#endif
693#ifdef VTDLY
694 data.term.c_oflag &= ~VTDLY;
695#endif
696#ifdef FFDLY
697 data.term.c_oflag &= ~FFDLY;
698#endif
b251be4b 699#ifdef OFILL
9cb98459
ML
700 data.term.c_oflag &= ~OFILL;
701#endif
c3e05092 702 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
b251be4b
ML
703 data.term.c_cc[VMIN] = 0;
704 data.term.c_cc[VTIME] = 0;
9cb98459 705
b251be4b
ML
706 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
707 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
bccc7c9f 708#endif
9cb98459 709
e33ab9aa
ML
710 ret = set_config(port, &data, &config);
711
eac329d2 712 if (ret < 0) {
e33ab9aa 713 sp_close(port);
c33efc48 714 RETURN_CODEVAL(ret);
e33ab9aa 715 }
74510d4b 716
c33efc48 717 RETURN_OK();
74510d4b
ML
718}
719
eb6ed20f 720enum sp_return sp_close(struct sp_port *port)
74510d4b 721{
c33efc48
ML
722 TRACE("%p", port);
723
dec10e31 724 CHECK_OPEN_PORT();
74510d4b 725
ea667be7
ML
726 DEBUG("Closing port %s", port->name);
727
74510d4b
ML
728#ifdef _WIN32
729 /* Returns non-zero upon success, 0 upon failure. */
730 if (CloseHandle(port->hdl) == 0)
c33efc48 731 RETURN_FAIL("CloseHandle() failed");
8f471c66 732 port->hdl = INVALID_HANDLE_VALUE;
a3cb91f5 733 if (port->nonblocking) {
a3cb91f5
ML
734 /* Close event handle created for overlapped writes. */
735 if (CloseHandle(port->write_ovl.hEvent) == 0)
736 RETURN_FAIL("CloseHandle() failed");
737 }
74510d4b
ML
738#else
739 /* Returns 0 upon success, -1 upon failure. */
740 if (close(port->fd) == -1)
c33efc48 741 RETURN_FAIL("close() failed");
8f471c66 742 port->fd = -1;
74510d4b
ML
743#endif
744
c33efc48 745 RETURN_OK();
74510d4b
ML
746}
747
fd8fd11a 748enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
74510d4b 749{
00d8c56d 750 TRACE("%p, 0x%x", port, buffers);
c33efc48 751
dec10e31
ML
752 CHECK_OPEN_PORT();
753
754 if (buffers > SP_BUF_BOTH)
755 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
74510d4b 756
0ba3e49b 757 const char *buffer_names[] = {"no", "input", "output", "both"};
ea667be7
ML
758
759 DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
760
74510d4b 761#ifdef _WIN32
fd8fd11a
ML
762 DWORD flags = 0;
763 if (buffers & SP_BUF_INPUT)
764 flags |= PURGE_RXCLEAR;
765 if (buffers & SP_BUF_OUTPUT)
766 flags |= PURGE_TXCLEAR;
767
74510d4b 768 /* Returns non-zero upon success, 0 upon failure. */
fd8fd11a 769 if (PurgeComm(port->hdl, flags) == 0)
c33efc48 770 RETURN_FAIL("PurgeComm() failed");
74510d4b 771#else
fd8fd11a
ML
772 int flags = 0;
773 if (buffers & SP_BUF_BOTH)
774 flags = TCIOFLUSH;
775 else if (buffers & SP_BUF_INPUT)
776 flags = TCIFLUSH;
82f424e6 777 else if (buffers & SP_BUF_OUTPUT)
fd8fd11a
ML
778 flags = TCOFLUSH;
779
74510d4b 780 /* Returns 0 upon success, -1 upon failure. */
fd8fd11a 781 if (tcflush(port->fd, flags) < 0)
c33efc48 782 RETURN_FAIL("tcflush() failed");
74510d4b 783#endif
c33efc48 784 RETURN_OK();
74510d4b
ML
785}
786
69a3739c
ML
787enum sp_return sp_drain(struct sp_port *port)
788{
c33efc48
ML
789 TRACE("%p", port);
790
dec10e31 791 CHECK_OPEN_PORT();
69a3739c 792
ea667be7
ML
793 DEBUG("Draining port %s", port->name);
794
69a3739c
ML
795#ifdef _WIN32
796 /* Returns non-zero upon success, 0 upon failure. */
797 if (FlushFileBuffers(port->hdl) == 0)
c33efc48 798 RETURN_FAIL("FlushFileBuffers() failed");
69a3739c
ML
799#else
800 /* Returns 0 upon success, -1 upon failure. */
801 if (tcdrain(port->fd) < 0)
c33efc48 802 RETURN_FAIL("tcdrain() failed");
69a3739c
ML
803#endif
804
c33efc48 805 RETURN_OK();
69a3739c
ML
806}
807
eb6ed20f 808enum sp_return sp_write(struct sp_port *port, const void *buf, size_t count)
74510d4b 809{
c33efc48
ML
810 TRACE("%p, %p, %d", port, buf, count);
811
dec10e31 812 CHECK_OPEN_PORT();
74510d4b
ML
813
814 if (!buf)
c33efc48 815 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
74510d4b 816
ea667be7
ML
817 DEBUG("Writing up to %d bytes to port %s", count, port->name);
818
a3cb91f5
ML
819 if (count == 0)
820 RETURN_VALUE("0", 0);
821
74510d4b
ML
822#ifdef _WIN32
823 DWORD written = 0;
0765af56 824 BYTE *ptr = (BYTE *) buf;
f92f1f0c 825
a3cb91f5
ML
826 if (port->nonblocking) {
827 /* Non-blocking write. */
828
829 /* Check whether previous write is complete. */
830 if (port->writing) {
831 if (HasOverlappedIoCompleted(&port->write_ovl)) {
832 DEBUG("Previous write completed");
833 port->writing = 0;
a3cb91f5
ML
834 } else {
835 DEBUG("Previous write not complete");
836 /* Can't take a new write until the previous one finishes. */
837 RETURN_VALUE("0", 0);
838 }
839 }
840
0765af56
ML
841 /* Keep writing data until the OS has to actually start an async IO for it.
842 * At that point we know the buffer is full. */
843 while (written < count)
844 {
845 /* Copy first byte of user buffer. */
846 port->pending_byte = *ptr++;
847
848 /* Start asynchronous write. */
849 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
850 if (GetLastError() == ERROR_IO_PENDING) {
851 DEBUG("Asynchronous write started");
852 port->writing = 1;
853 RETURN_VALUE("%d", ++written);
854 } else {
855 /* Actual failure of some kind. */
856 RETURN_FAIL("WriteFile() failed");
857 }
a3cb91f5 858 } else {
0765af56
ML
859 DEBUG("Single byte written immediately.");
860 written++;
a3cb91f5 861 }
a3cb91f5 862 }
0765af56
ML
863
864 DEBUG("All bytes written immediately.");
865
a3cb91f5
ML
866 } else {
867 /* Blocking write. */
868 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0) {
869 RETURN_FAIL("WriteFile() failed");
870 }
871 }
872
c33efc48 873 RETURN_VALUE("%d", written);
74510d4b
ML
874#else
875 /* Returns the number of bytes written, or -1 upon failure. */
876 ssize_t written = write(port->fd, buf, count);
f92f1f0c 877
74510d4b 878 if (written < 0)
c33efc48 879 RETURN_FAIL("write() failed");
74510d4b 880 else
c33efc48 881 RETURN_VALUE("%d", written);
74510d4b
ML
882#endif
883}
884
eb6ed20f 885enum sp_return sp_read(struct sp_port *port, void *buf, size_t count)
74510d4b 886{
c33efc48
ML
887 TRACE("%p, %p, %d", port, buf, count);
888
dec10e31 889 CHECK_OPEN_PORT();
74510d4b
ML
890
891 if (!buf)
c33efc48 892 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
74510d4b 893
ea667be7
ML
894 DEBUG("Reading up to %d bytes from port %s", count, port->name);
895
74510d4b
ML
896#ifdef _WIN32
897 DWORD bytes_read = 0;
f92f1f0c 898
74510d4b
ML
899 /* Returns non-zero upon success, 0 upon failure. */
900 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
c33efc48
ML
901 RETURN_FAIL("ReadFile() failed");
902 RETURN_VALUE("%d", bytes_read);
74510d4b
ML
903#else
904 ssize_t bytes_read;
f92f1f0c 905
74510d4b 906 /* Returns the number of bytes read, or -1 upon failure. */
33d5ff47
ML
907 if ((bytes_read = read(port->fd, buf, count)) < 0) {
908 if (port->nonblocking && errno == EAGAIN)
909 /* Port is opened in nonblocking mode and there are no bytes available. */
910 bytes_read = 0;
911 else
912 /* This is an actual failure. */
913 RETURN_FAIL("read() failed");
914 }
c33efc48 915 RETURN_VALUE("%d", bytes_read);
74510d4b
ML
916#endif
917}
918
7a6d2196
ML
919#ifdef __linux__
920static enum sp_return get_baudrate(int fd, int *baudrate)
921{
922 void *data;
923
c33efc48
ML
924 TRACE("%d, %p", fd, baudrate);
925
ea667be7
ML
926 DEBUG("Getting baud rate");
927
7a6d2196 928 if (!(data = malloc(get_termios_size())))
c33efc48 929 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
7a6d2196 930
8d43110a
ML
931 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
932 free(data);
c33efc48 933 RETURN_FAIL("getting termios failed");
8d43110a 934 }
7a6d2196
ML
935
936 *baudrate = get_termios_speed(data);
937
8d43110a
ML
938 free(data);
939
c33efc48 940 RETURN_OK();
7a6d2196
ML
941}
942
943static enum sp_return set_baudrate(int fd, int baudrate)
944{
945 void *data;
946
c33efc48
ML
947 TRACE("%d, %d", fd, baudrate);
948
ea667be7
ML
949 DEBUG("Getting baud rate");
950
7a6d2196 951 if (!(data = malloc(get_termios_size())))
c33efc48 952 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
7a6d2196 953
8d43110a
ML
954 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
955 free(data);
c33efc48 956 RETURN_FAIL("getting termios failed");
8d43110a 957 }
7a6d2196 958
ea667be7
ML
959 DEBUG("Setting baud rate");
960
7a6d2196
ML
961 set_termios_speed(data, baudrate);
962
8d43110a
ML
963 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
964 free(data);
c33efc48 965 RETURN_FAIL("setting termios failed");
8d43110a
ML
966 }
967
968 free(data);
7a6d2196 969
c33efc48 970 RETURN_OK();
7a6d2196 971}
40978c2b
ML
972
973#ifdef USE_TERMIOX
974static enum sp_return get_flow(int fd, int *flow)
975{
976 void *data;
977
c33efc48
ML
978 TRACE("%d, %p", fd, flow);
979
ea667be7
ML
980 DEBUG("Getting advanced flow control");
981
40978c2b 982 if (!(data = malloc(get_termiox_size())))
c33efc48 983 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
40978c2b 984
8d43110a
ML
985 if (ioctl(fd, TCGETX, data) < 0) {
986 free(data);
c33efc48 987 RETURN_FAIL("getting termiox failed");
8d43110a 988 }
40978c2b
ML
989
990 *flow = get_termiox_flow(data);
991
8d43110a
ML
992 free(data);
993
c33efc48 994 RETURN_OK();
40978c2b
ML
995}
996
997static enum sp_return set_flow(int fd, int flow)
998{
999 void *data;
1000
c33efc48
ML
1001 TRACE("%d, %d", fd, flow);
1002
ea667be7
ML
1003 DEBUG("Getting advanced flow control");
1004
40978c2b 1005 if (!(data = malloc(get_termiox_size())))
c33efc48 1006 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
40978c2b 1007
8d43110a
ML
1008 if (ioctl(fd, TCGETX, data) < 0) {
1009 free(data);
c33efc48 1010 RETURN_FAIL("getting termiox failed");
8d43110a 1011 }
40978c2b 1012
ea667be7
ML
1013 DEBUG("Setting advanced flow control");
1014
40978c2b
ML
1015 set_termiox_flow(data, flow);
1016
8d43110a
ML
1017 if (ioctl(fd, TCSETX, data) < 0) {
1018 free(data);
c33efc48 1019 RETURN_FAIL("setting termiox failed");
8d43110a
ML
1020 }
1021
1022 free(data);
40978c2b 1023
c33efc48 1024 RETURN_OK();
40978c2b
ML
1025}
1026#endif /* USE_TERMIOX */
1027#endif /* __linux__ */
7a6d2196 1028
eb6ed20f
ML
1029static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1030 struct sp_port_config *config)
8094e4a0 1031{
da2748bf 1032 unsigned int i;
cbf628c7 1033
c33efc48
ML
1034 TRACE("%p, %p, %p", port, data, config);
1035
ea667be7
ML
1036 DEBUG("Getting configuration for port %s", port->name);
1037
8094e4a0 1038#ifdef _WIN32
e33ab9aa 1039 if (!GetCommState(port->hdl, &data->dcb))
c33efc48 1040 RETURN_FAIL("GetCommState() failed");
8094e4a0 1041
067417af 1042 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
e33ab9aa 1043 if (data->dcb.BaudRate == std_baudrates[i].index) {
067417af
ML
1044 config->baudrate = std_baudrates[i].value;
1045 break;
1046 }
1047 }
1048
1049 if (i == NUM_STD_BAUDRATES)
1050 /* BaudRate field can be either an index or a custom baud rate. */
e33ab9aa 1051 config->baudrate = data->dcb.BaudRate;
067417af 1052
e33ab9aa 1053 config->bits = data->dcb.ByteSize;
067417af 1054
e33ab9aa
ML
1055 if (data->dcb.fParity)
1056 switch (data->dcb.Parity) {
067417af
ML
1057 case NOPARITY:
1058 config->parity = SP_PARITY_NONE;
1059 break;
e432ce60
ML
1060 case ODDPARITY:
1061 config->parity = SP_PARITY_ODD;
1062 break;
067417af
ML
1063 case EVENPARITY:
1064 config->parity = SP_PARITY_EVEN;
1065 break;
e432ce60
ML
1066 case MARKPARITY:
1067 config->parity = SP_PARITY_MARK;
1068 break;
1069 case SPACEPARITY:
1070 config->parity = SP_PARITY_SPACE;
067417af
ML
1071 break;
1072 default:
1073 config->parity = -1;
1074 }
1075 else
1076 config->parity = SP_PARITY_NONE;
1077
e33ab9aa 1078 switch (data->dcb.StopBits) {
067417af
ML
1079 case ONESTOPBIT:
1080 config->stopbits = 1;
1081 break;
1082 case TWOSTOPBITS:
1083 config->stopbits = 2;
1084 break;
1085 default:
1086 config->stopbits = -1;
1087 }
1088
e33ab9aa 1089 switch (data->dcb.fRtsControl) {
eac329d2
UH
1090 case RTS_CONTROL_DISABLE:
1091 config->rts = SP_RTS_OFF;
1092 break;
1093 case RTS_CONTROL_ENABLE:
1094 config->rts = SP_RTS_ON;
1095 break;
1096 case RTS_CONTROL_HANDSHAKE:
1097 config->rts = SP_RTS_FLOW_CONTROL;
1098 break;
1099 default:
1100 config->rts = -1;
067417af
ML
1101 }
1102
e33ab9aa 1103 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
067417af 1104
e33ab9aa 1105 switch (data->dcb.fDtrControl) {
eac329d2
UH
1106 case DTR_CONTROL_DISABLE:
1107 config->dtr = SP_DTR_OFF;
1108 break;
1109 case DTR_CONTROL_ENABLE:
1110 config->dtr = SP_DTR_ON;
1111 break;
1112 case DTR_CONTROL_HANDSHAKE:
1113 config->dtr = SP_DTR_FLOW_CONTROL;
1114 break;
1115 default:
1116 config->dtr = -1;
067417af
ML
1117 }
1118
e33ab9aa
ML
1119 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1120
c6754b45
ML
1121 if (data->dcb.fInX) {
1122 if (data->dcb.fOutX)
1123 config->xon_xoff = SP_XONXOFF_INOUT;
1124 else
1125 config->xon_xoff = SP_XONXOFF_IN;
1126 } else {
1127 if (data->dcb.fOutX)
1128 config->xon_xoff = SP_XONXOFF_OUT;
1129 else
1130 config->xon_xoff = SP_XONXOFF_DISABLED;
1131 }
1132
e33ab9aa
ML
1133#else // !_WIN32
1134
1135 if (tcgetattr(port->fd, &data->term) < 0)
c33efc48 1136 RETURN_FAIL("tcgetattr() failed");
e33ab9aa
ML
1137
1138 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
c33efc48 1139 RETURN_FAIL("TIOCMGET ioctl failed");
40978c2b
ML
1140
1141#ifdef USE_TERMIOX
68ec29db
ML
1142 int ret = get_flow(port->fd, &data->flow);
1143
1144 if (ret == SP_ERR_FAIL && errno == EINVAL)
1145 data->termiox_supported = 0;
1146 else if (ret < 0)
c33efc48 1147 RETURN_CODEVAL(ret);
68ec29db
ML
1148 else
1149 data->termiox_supported = 1;
1150#else
1151 data->termiox_supported = 0;
40978c2b
ML
1152#endif
1153
067417af 1154 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
e33ab9aa 1155 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
067417af
ML
1156 config->baudrate = std_baudrates[i].value;
1157 break;
1158 }
1159 }
1160
31b3a8f5
MH
1161 if (i == NUM_STD_BAUDRATES) {
1162#ifdef __APPLE__
1163 config->baudrate = (int)data->term.c_ispeed;
7a6d2196
ML
1164#elif defined(__linux__)
1165 TRY(get_baudrate(port->fd, &config->baudrate));
31b3a8f5 1166#else
067417af 1167 config->baudrate = -1;
31b3a8f5
MH
1168#endif
1169 }
067417af 1170
e33ab9aa 1171 switch (data->term.c_cflag & CSIZE) {
067417af
ML
1172 case CS8:
1173 config->bits = 8;
1174 break;
1175 case CS7:
1176 config->bits = 7;
1177 break;
1178 case CS6:
1179 config->bits = 6;
1180 break;
1181 case CS5:
1182 config->bits = 5;
1183 break;
1184 default:
1185 config->bits = -1;
1186 }
1187
e33ab9aa 1188 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
067417af 1189 config->parity = SP_PARITY_NONE;
e33ab9aa 1190 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
067417af 1191 config->parity = -1;
c3e05092 1192#ifdef CMSPAR
e432ce60
ML
1193 else if (data->term.c_cflag & CMSPAR)
1194 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
c3e05092 1195#endif
067417af 1196 else
e33ab9aa 1197 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
067417af 1198
e33ab9aa 1199 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
067417af 1200
e33ab9aa 1201 if (data->term.c_cflag & CRTSCTS) {
067417af
ML
1202 config->rts = SP_RTS_FLOW_CONTROL;
1203 config->cts = SP_CTS_FLOW_CONTROL;
1204 } else {
68ec29db 1205 if (data->termiox_supported && data->flow & RTS_FLOW)
40978c2b
ML
1206 config->rts = SP_RTS_FLOW_CONTROL;
1207 else
1208 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1209
68ec29db
ML
1210 config->cts = (data->termiox_supported && data->flow & CTS_FLOW) ?
1211 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
067417af
ML
1212 }
1213
68ec29db 1214 if (data->termiox_supported && data->flow & DTR_FLOW)
40978c2b
ML
1215 config->dtr = SP_DTR_FLOW_CONTROL;
1216 else
1217 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1218
68ec29db
ML
1219 config->dsr = (data->termiox_supported && data->flow & DSR_FLOW) ?
1220 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
705bdc69 1221
e29b93a5
ML
1222 if (data->term.c_iflag & IXOFF) {
1223 if (data->term.c_iflag & IXON)
1224 config->xon_xoff = SP_XONXOFF_INOUT;
1225 else
1226 config->xon_xoff = SP_XONXOFF_IN;
1227 } else {
1228 if (data->term.c_iflag & IXON)
1229 config->xon_xoff = SP_XONXOFF_OUT;
1230 else
1231 config->xon_xoff = SP_XONXOFF_DISABLED;
1232 }
067417af
ML
1233#endif
1234
c33efc48 1235 RETURN_OK();
067417af
ML
1236}
1237
7a6d2196 1238static enum sp_return set_config(struct sp_port *port, struct port_data *data,
eb6ed20f 1239 const struct sp_port_config *config)
18fc2dd1 1240{
e33ab9aa 1241 unsigned int i;
31b3a8f5
MH
1242#ifdef __APPLE__
1243 BAUD_TYPE baud_nonstd;
1244
1245 baud_nonstd = B0;
1246#endif
7a6d2196
ML
1247#ifdef __linux__
1248 int baud_nonstd = 0;
1249#endif
18fc2dd1 1250
c33efc48
ML
1251 TRACE("%p, %p, %p", port, data, config);
1252
ea667be7
ML
1253 DEBUG("Setting configuration for port %s", port->name);
1254
e33ab9aa 1255#ifdef _WIN32
eac329d2 1256 if (config->baudrate >= 0) {
e33ab9aa
ML
1257 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1258 if (config->baudrate == std_baudrates[i].value) {
1259 data->dcb.BaudRate = std_baudrates[i].index;
1260 break;
1261 }
1262 }
18fc2dd1 1263
e33ab9aa
ML
1264 if (i == NUM_STD_BAUDRATES)
1265 data->dcb.BaudRate = config->baudrate;
1266 }
18fc2dd1 1267
e33ab9aa
ML
1268 if (config->bits >= 0)
1269 data->dcb.ByteSize = config->bits;
1270
1271 if (config->parity >= 0) {
1272 switch (config->parity) {
1273 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
1274 case SP_PARITY_NONE:
1275 data->dcb.Parity = NOPARITY;
1276 break;
e432ce60
ML
1277 case SP_PARITY_ODD:
1278 data->dcb.Parity = ODDPARITY;
1279 break;
e33ab9aa
ML
1280 case SP_PARITY_EVEN:
1281 data->dcb.Parity = EVENPARITY;
1282 break;
e432ce60
ML
1283 case SP_PARITY_MARK:
1284 data->dcb.Parity = MARKPARITY;
1285 break;
1286 case SP_PARITY_SPACE:
1287 data->dcb.Parity = SPACEPARITY;
e33ab9aa
ML
1288 break;
1289 default:
c33efc48 1290 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
e33ab9aa 1291 }
18fc2dd1
ML
1292 }
1293
e33ab9aa
ML
1294 if (config->stopbits >= 0) {
1295 switch (config->stopbits) {
1296 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1297 case 1:
1298 data->dcb.StopBits = ONESTOPBIT;
1299 break;
1300 case 2:
1301 data->dcb.StopBits = TWOSTOPBITS;
1302 break;
1303 default:
c33efc48 1304 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
e33ab9aa
ML
1305 }
1306 }
1307
1308 if (config->rts >= 0) {
1309 switch (config->rts) {
1310 case SP_RTS_OFF:
1311 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1312 break;
1313 case SP_RTS_ON:
1314 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1315 break;
1316 case SP_RTS_FLOW_CONTROL:
1317 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1318 break;
1319 default:
c33efc48 1320 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
e33ab9aa
ML
1321 }
1322 }
1323
1324 if (config->cts >= 0) {
1325 switch (config->cts) {
1326 case SP_CTS_IGNORE:
1327 data->dcb.fOutxCtsFlow = FALSE;
1328 break;
1329 case SP_CTS_FLOW_CONTROL:
1330 data->dcb.fOutxCtsFlow = TRUE;
1331 break;
1332 default:
c33efc48 1333 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
e33ab9aa
ML
1334 }
1335 }
1336
1337 if (config->dtr >= 0) {
1338 switch (config->dtr) {
1339 case SP_DTR_OFF:
1340 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1341 break;
1342 case SP_DTR_ON:
1343 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1344 break;
1345 case SP_DTR_FLOW_CONTROL:
1346 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1347 break;
1348 default:
c33efc48 1349 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
e33ab9aa
ML
1350 }
1351 }
1352
1353 if (config->dsr >= 0) {
1354 switch (config->dsr) {
1355 case SP_DSR_IGNORE:
1356 data->dcb.fOutxDsrFlow = FALSE;
1357 break;
1358 case SP_DSR_FLOW_CONTROL:
1359 data->dcb.fOutxDsrFlow = TRUE;
1360 break;
1361 default:
c33efc48 1362 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
e33ab9aa 1363 }
18fc2dd1
ML
1364 }
1365
e33ab9aa
ML
1366 if (config->xon_xoff >= 0) {
1367 switch (config->xon_xoff) {
1368 case SP_XONXOFF_DISABLED:
1369 data->dcb.fInX = FALSE;
1370 data->dcb.fOutX = FALSE;
1371 break;
1372 case SP_XONXOFF_IN:
1373 data->dcb.fInX = TRUE;
1374 data->dcb.fOutX = FALSE;
1375 break;
1376 case SP_XONXOFF_OUT:
1377 data->dcb.fInX = FALSE;
1378 data->dcb.fOutX = TRUE;
1379 break;
1380 case SP_XONXOFF_INOUT:
1381 data->dcb.fInX = TRUE;
1382 data->dcb.fOutX = TRUE;
1383 break;
1384 default:
c33efc48 1385 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
e33ab9aa
ML
1386 }
1387 }
1388
1389 if (!SetCommState(port->hdl, &data->dcb))
c33efc48 1390 RETURN_FAIL("SetCommState() failed");
e33ab9aa 1391
31b3a8f5 1392#else /* !_WIN32 */
e33ab9aa 1393
7a6d2196
ML
1394 int controlbits;
1395
eac329d2 1396 if (config->baudrate >= 0) {
e33ab9aa
ML
1397 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1398 if (config->baudrate == std_baudrates[i].value) {
1399 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
c33efc48 1400 RETURN_FAIL("cfsetospeed() failed");
e33ab9aa
ML
1401
1402 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
c33efc48 1403 RETURN_FAIL("cfsetispeed() failed");
e33ab9aa
ML
1404 break;
1405 }
1406 }
1407
31b3a8f5
MH
1408 /* Non-standard baud rate */
1409 if (i == NUM_STD_BAUDRATES) {
1410#ifdef __APPLE__
24abdb68 1411 /* Set "dummy" baud rate. */
31b3a8f5 1412 if (cfsetspeed(&data->term, B9600) < 0)
c33efc48 1413 RETURN_FAIL("cfsetspeed() failed");
31b3a8f5 1414 baud_nonstd = config->baudrate;
7a6d2196
ML
1415#elif defined(__linux__)
1416 baud_nonstd = 1;
31b3a8f5 1417#else
c33efc48 1418 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
31b3a8f5
MH
1419#endif
1420 }
e33ab9aa
ML
1421 }
1422
1423 if (config->bits >= 0) {
1424 data->term.c_cflag &= ~CSIZE;
1425 switch (config->bits) {
1426 case 8:
1427 data->term.c_cflag |= CS8;
1428 break;
1429 case 7:
1430 data->term.c_cflag |= CS7;
1431 break;
1432 case 6:
1433 data->term.c_cflag |= CS6;
1434 break;
23922313
UH
1435 case 5:
1436 data->term.c_cflag |= CS5;
1437 break;
e33ab9aa 1438 default:
c33efc48 1439 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
e33ab9aa
ML
1440 }
1441 }
1442
1443 if (config->parity >= 0) {
1444 data->term.c_iflag &= ~IGNPAR;
c3e05092
UH
1445 data->term.c_cflag &= ~(PARENB | PARODD);
1446#ifdef CMSPAR
1447 data->term.c_cflag &= ~CMSPAR;
1448#endif
e33ab9aa
ML
1449 switch (config->parity) {
1450 case SP_PARITY_NONE:
1451 data->term.c_iflag |= IGNPAR;
1452 break;
1453 case SP_PARITY_EVEN:
1454 data->term.c_cflag |= PARENB;
1455 break;
1456 case SP_PARITY_ODD:
1457 data->term.c_cflag |= PARENB | PARODD;
1458 break;
e432ce60 1459 case SP_PARITY_MARK:
c3e05092
UH
1460 data->term.c_cflag |= PARENB | PARODD;
1461#ifdef CMSPAR
1462 data->term.c_cflag |= CMSPAR;
1463#endif
e432ce60
ML
1464 break;
1465 case SP_PARITY_SPACE:
c3e05092
UH
1466 data->term.c_cflag |= PARENB;
1467#ifdef CMSPAR
1468 data->term.c_cflag |= CMSPAR;
1469#endif
e432ce60 1470 break;
e33ab9aa 1471 default:
c33efc48 1472 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
e33ab9aa
ML
1473 }
1474 }
1475
1476 if (config->stopbits >= 0) {
1477 data->term.c_cflag &= ~CSTOPB;
1478 switch (config->stopbits) {
1479 case 1:
1480 data->term.c_cflag &= ~CSTOPB;
1481 break;
1482 case 2:
1483 data->term.c_cflag |= CSTOPB;
1484 break;
1485 default:
c33efc48 1486 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
e33ab9aa
ML
1487 }
1488 }
1489
eac329d2 1490 if (config->rts >= 0 || config->cts >= 0) {
68ec29db
ML
1491 if (data->termiox_supported) {
1492 data->flow &= ~(RTS_FLOW | CTS_FLOW);
1493 switch (config->rts) {
1494 case SP_RTS_OFF:
1495 case SP_RTS_ON:
1496 controlbits = TIOCM_RTS;
1497 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
c33efc48 1498 RETURN_FAIL("Setting RTS signal level failed");
68ec29db
ML
1499 break;
1500 case SP_RTS_FLOW_CONTROL:
1501 data->flow |= RTS_FLOW;
1502 break;
1503 default:
1504 break;
e33ab9aa 1505 }
68ec29db
ML
1506 if (config->cts == SP_CTS_FLOW_CONTROL)
1507 data->flow |= CTS_FLOW;
e33ab9aa 1508
68ec29db 1509 if (data->flow & (RTS_FLOW | CTS_FLOW))
e33ab9aa 1510 data->term.c_iflag |= CRTSCTS;
68ec29db
ML
1511 else
1512 data->term.c_iflag &= ~CRTSCTS;
1513 } else {
1514 /* Asymmetric use of RTS/CTS not supported. */
1515 if (data->term.c_iflag & CRTSCTS) {
1516 /* Flow control can only be disabled for both RTS & CTS together. */
1517 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1518 if (config->cts != SP_CTS_IGNORE)
c33efc48 1519 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
68ec29db
ML
1520 }
1521 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1522 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
c33efc48 1523 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
68ec29db 1524 }
e33ab9aa 1525 } else {
68ec29db
ML
1526 /* Flow control can only be enabled for both RTS & CTS together. */
1527 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1528 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
c33efc48 1529 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
68ec29db
ML
1530 }
1531
1532 if (config->rts >= 0) {
1533 if (config->rts == SP_RTS_FLOW_CONTROL) {
1534 data->term.c_iflag |= CRTSCTS;
1535 } else {
1536 controlbits = TIOCM_RTS;
1537 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1538 &controlbits) < 0)
c33efc48 1539 RETURN_FAIL("Setting RTS signal level failed");
68ec29db 1540 }
e33ab9aa
ML
1541 }
1542 }
1543 }
1544
eac329d2 1545 if (config->dtr >= 0 || config->dsr >= 0) {
68ec29db
ML
1546 if (data->termiox_supported) {
1547 data->flow &= ~(DTR_FLOW | DSR_FLOW);
1548 switch (config->dtr) {
1549 case SP_DTR_OFF:
1550 case SP_DTR_ON:
1551 controlbits = TIOCM_DTR;
1552 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
c33efc48 1553 RETURN_FAIL("Setting DTR signal level failed");
68ec29db
ML
1554 break;
1555 case SP_DTR_FLOW_CONTROL:
1556 data->flow |= DTR_FLOW;
1557 break;
1558 default:
1559 break;
1560 }
1561 if (config->dsr == SP_DSR_FLOW_CONTROL)
1562 data->flow |= DSR_FLOW;
1563 } else {
1564 /* DTR/DSR flow control not supported. */
1565 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
c33efc48 1566 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
e33ab9aa 1567
68ec29db
ML
1568 if (config->dtr >= 0) {
1569 controlbits = TIOCM_DTR;
1570 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1571 &controlbits) < 0)
c33efc48 1572 RETURN_FAIL("Setting DTR signal level failed");
68ec29db 1573 }
e33ab9aa
ML
1574 }
1575 }
1576
1577 if (config->xon_xoff >= 0) {
1578 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1579 switch (config->xon_xoff) {
1580 case SP_XONXOFF_DISABLED:
1581 break;
1582 case SP_XONXOFF_IN:
1583 data->term.c_iflag |= IXOFF;
1584 break;
1585 case SP_XONXOFF_OUT:
1586 data->term.c_iflag |= IXON | IXANY;
1587 break;
1588 case SP_XONXOFF_INOUT:
1589 data->term.c_iflag |= IXON | IXOFF | IXANY;
1590 break;
1591 default:
c33efc48 1592 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
e33ab9aa
ML
1593 }
1594 }
1595
3f5c06d0 1596 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
c33efc48 1597 RETURN_FAIL("tcsetattr() failed");
31b3a8f5
MH
1598
1599#ifdef __APPLE__
1600 if (baud_nonstd != B0) {
1601 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
c33efc48 1602 RETURN_FAIL("IOSSIOSPEED ioctl failed");
31b3a8f5
MH
1603 /* Set baud rates in data->term to correct, but incompatible
1604 * with tcsetattr() value, same as delivered by tcgetattr(). */
1605 if (cfsetspeed(&data->term, baud_nonstd) < 0)
c33efc48 1606 RETURN_FAIL("cfsetspeed() failed");
31b3a8f5 1607 }
7a6d2196
ML
1608#elif defined(__linux__)
1609 if (baud_nonstd)
1610 TRY(set_baudrate(port->fd, config->baudrate));
40978c2b 1611#ifdef USE_TERMIOX
68ec29db
ML
1612 if (data->termiox_supported)
1613 TRY(set_flow(port->fd, data->flow));
40978c2b 1614#endif
7a6d2196 1615#endif
31b3a8f5
MH
1616
1617#endif /* !_WIN32 */
e33ab9aa 1618
c33efc48 1619 RETURN_OK();
e33ab9aa
ML
1620}
1621
9b1502ef
ML
1622enum sp_return sp_new_config(struct sp_port_config **config_ptr)
1623{
59131d60 1624 struct sp_port_config *config;
9b1502ef 1625
00d8c56d
UH
1626 TRACE("%p", config_ptr);
1627
9b1502ef
ML
1628 if (!config_ptr)
1629 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1630
59131d60
ML
1631 *config_ptr = NULL;
1632
1633 if (!(config = malloc(sizeof(struct sp_port_config))))
9b1502ef
ML
1634 RETURN_ERROR(SP_ERR_MEM, "config malloc failed");
1635
59131d60
ML
1636 config->baudrate = -1;
1637 config->bits = -1;
1638 config->parity = -1;
1639 config->stopbits = -1;
1640 config->rts = -1;
1641 config->cts = -1;
1642 config->dtr = -1;
1643 config->dsr = -1;
1644
1645 *config_ptr = config;
1646
9b1502ef
ML
1647 RETURN_OK();
1648}
1649
1650void sp_free_config(struct sp_port_config *config)
1651{
1652 TRACE("%p", config);
1653
1654 if (!config)
1655 DEBUG("Null config");
1656 else
1657 free(config);
1658
1659 RETURN();
1660}
1661
70cd37de
ML
1662enum sp_return sp_get_config(struct sp_port *port, struct sp_port_config *config)
1663{
1664 struct port_data data;
1665
1666 TRACE("%p, %p", port, config);
1667
1668 CHECK_OPEN_PORT();
1669
1670 if (!config)
9b1502ef 1671 RETURN_ERROR(SP_ERR_ARG, "Null config");
70cd37de
ML
1672
1673 TRY(get_config(port, &data, config));
1674
1675 RETURN_OK();
1676}
1677
eb6ed20f 1678enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
e33ab9aa 1679{
8f189c4c 1680 struct port_data data;
e33ab9aa
ML
1681 struct sp_port_config prev_config;
1682
c33efc48
ML
1683 TRACE("%p, %p", port, config);
1684
dec10e31 1685 CHECK_OPEN_PORT();
823690ae
ML
1686
1687 if (!config)
c33efc48 1688 RETURN_ERROR(SP_ERR_ARG, "Null config");
823690ae 1689
e33ab9aa
ML
1690 TRY(get_config(port, &data, &prev_config));
1691 TRY(set_config(port, &data, config));
74510d4b 1692
c33efc48 1693 RETURN_OK();
74510d4b
ML
1694}
1695
9b1502ef
ML
1696#define CREATE_ACCESSORS(x, type) \
1697enum sp_return sp_set_##x(struct sp_port *port, type x) { \
8f189c4c 1698 struct port_data data; \
e33ab9aa 1699 struct sp_port_config config; \
c33efc48 1700 TRACE("%p, %d", port, x); \
dec10e31 1701 CHECK_OPEN_PORT(); \
e33ab9aa
ML
1702 TRY(get_config(port, &data, &config)); \
1703 config.x = x; \
1704 TRY(set_config(port, &data, &config)); \
c33efc48 1705 RETURN_OK(); \
9b1502ef
ML
1706} \
1707enum sp_return sp_get_config_##x(const struct sp_port_config *config, type *x) { \
00d8c56d 1708 TRACE("%p, %p", config, x); \
9b1502ef
ML
1709 if (!config) \
1710 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
1711 *x = config->x; \
1712 RETURN_OK(); \
1713} \
1714enum sp_return sp_set_config_##x(struct sp_port_config *config, type x) { \
1715 TRACE("%p, %d", config, x); \
1716 if (!config) \
1717 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
1718 config->x = x; \
1719 RETURN_OK(); \
9069c2fb
ML
1720}
1721
9b1502ef
ML
1722CREATE_ACCESSORS(baudrate, int)
1723CREATE_ACCESSORS(bits, int)
1724CREATE_ACCESSORS(parity, enum sp_parity)
1725CREATE_ACCESSORS(stopbits, int)
1726CREATE_ACCESSORS(rts, enum sp_rts)
1727CREATE_ACCESSORS(cts, enum sp_cts)
1728CREATE_ACCESSORS(dtr, enum sp_dtr)
1729CREATE_ACCESSORS(dsr, enum sp_dsr)
1730CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
1731
1732enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config, enum sp_flowcontrol flowcontrol)
e33ab9aa 1733{
9b1502ef
ML
1734 if (!config)
1735 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
dec10e31
ML
1736
1737 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
1738 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
823690ae 1739
e33ab9aa 1740 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
9b1502ef 1741 config->xon_xoff = SP_XONXOFF_INOUT;
e33ab9aa 1742 else
9b1502ef 1743 config->xon_xoff = SP_XONXOFF_DISABLED;
e33ab9aa
ML
1744
1745 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
9b1502ef
ML
1746 config->rts = SP_RTS_FLOW_CONTROL;
1747 config->cts = SP_CTS_FLOW_CONTROL;
e33ab9aa 1748 } else {
9b1502ef
ML
1749 if (config->rts == SP_RTS_FLOW_CONTROL)
1750 config->rts = SP_RTS_ON;
1751 config->cts = SP_CTS_IGNORE;
e33ab9aa
ML
1752 }
1753
1754 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
9b1502ef
ML
1755 config->dtr = SP_DTR_FLOW_CONTROL;
1756 config->dsr = SP_DSR_FLOW_CONTROL;
e33ab9aa 1757 } else {
9b1502ef
ML
1758 if (config->dtr == SP_DTR_FLOW_CONTROL)
1759 config->dtr = SP_DTR_ON;
1760 config->dsr = SP_DSR_IGNORE;
e33ab9aa
ML
1761 }
1762
9b1502ef
ML
1763 RETURN_OK();
1764}
1765
1766enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
1767{
1768 struct port_data data;
1769 struct sp_port_config config;
1770
1771 TRACE("%p, %d", port, flowcontrol);
1772
1773 CHECK_OPEN_PORT();
1774
1775 TRY(get_config(port, &data, &config));
1776
1777 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
1778
e33ab9aa
ML
1779 TRY(set_config(port, &data, &config));
1780
c33efc48 1781 RETURN_OK();
e33ab9aa
ML
1782}
1783
8cf7c697
ML
1784enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
1785{
c33efc48
ML
1786 TRACE("%p, %p", port, signals);
1787
dec10e31 1788 CHECK_OPEN_PORT();
8cf7c697
ML
1789
1790 if (!signals)
c33efc48 1791 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
8cf7c697 1792
ea667be7
ML
1793 DEBUG("Getting control signals for port %s", port->name);
1794
8cf7c697
ML
1795 *signals = 0;
1796#ifdef _WIN32
1797 DWORD bits;
1798 if (GetCommModemStatus(port->hdl, &bits) == 0)
c33efc48 1799 RETURN_FAIL("GetCommModemStatus() failed");
8cf7c697
ML
1800 if (bits & MS_CTS_ON)
1801 *signals |= SP_SIG_CTS;
1802 if (bits & MS_DSR_ON)
1803 *signals |= SP_SIG_DSR;
8cf7c697 1804 if (bits & MS_RLSD_ON)
a6cda1e8
ML
1805 *signals |= SP_SIG_DCD;
1806 if (bits & MS_RING_ON)
8cf7c697
ML
1807 *signals |= SP_SIG_RI;
1808#else
1809 int bits;
1810 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
c33efc48 1811 RETURN_FAIL("TIOCMGET ioctl failed");
8cf7c697
ML
1812 if (bits & TIOCM_CTS)
1813 *signals |= SP_SIG_CTS;
1814 if (bits & TIOCM_DSR)
1815 *signals |= SP_SIG_DSR;
1816 if (bits & TIOCM_CAR)
1817 *signals |= SP_SIG_DCD;
1818 if (bits & TIOCM_RNG)
1819 *signals |= SP_SIG_RI;
1820#endif
c33efc48 1821 RETURN_OK();
8cf7c697
ML
1822}
1823
90cc3ee6
ML
1824enum sp_return sp_start_break(struct sp_port *port)
1825{
c33efc48
ML
1826 TRACE("%p", port);
1827
dec10e31 1828 CHECK_OPEN_PORT();
90cc3ee6
ML
1829#ifdef _WIN32
1830 if (SetCommBreak(port->hdl) == 0)
c33efc48 1831 RETURN_FAIL("SetCommBreak() failed");
90cc3ee6
ML
1832#else
1833 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
c33efc48 1834 RETURN_FAIL("TIOCSBRK ioctl failed");
90cc3ee6
ML
1835#endif
1836
c33efc48 1837 RETURN_OK();
90cc3ee6
ML
1838}
1839
1840enum sp_return sp_end_break(struct sp_port *port)
1841{
c33efc48
ML
1842 TRACE("%p", port);
1843
dec10e31 1844 CHECK_OPEN_PORT();
90cc3ee6
ML
1845#ifdef _WIN32
1846 if (ClearCommBreak(port->hdl) == 0)
c33efc48 1847 RETURN_FAIL("ClearCommBreak() failed");
90cc3ee6
ML
1848#else
1849 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
c33efc48 1850 RETURN_FAIL("TIOCCBRK ioctl failed");
90cc3ee6
ML
1851#endif
1852
c33efc48 1853 RETURN_OK();
90cc3ee6
ML
1854}
1855
74510d4b
ML
1856int sp_last_error_code(void)
1857{
c33efc48 1858 TRACE("");
74510d4b 1859#ifdef _WIN32
c33efc48 1860 RETURN_VALUE("%d", GetLastError());
74510d4b 1861#else
c33efc48 1862 RETURN_VALUE("%d", errno);
74510d4b
ML
1863#endif
1864}
1865
74510d4b
ML
1866char *sp_last_error_message(void)
1867{
c33efc48
ML
1868 TRACE("");
1869
74510d4b
ML
1870#ifdef _WIN32
1871 LPVOID message;
1872 DWORD error = GetLastError();
1873
1874 FormatMessage(
1875 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1876 FORMAT_MESSAGE_FROM_SYSTEM |
1877 FORMAT_MESSAGE_IGNORE_INSERTS,
1878 NULL,
1879 error,
1880 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1881 (LPTSTR) &message,
1882 0, NULL );
1883
c33efc48 1884 RETURN_VALUE("%s", message);
74510d4b 1885#else
c33efc48 1886 RETURN_VALUE("%s", strerror(errno));
74510d4b
ML
1887#endif
1888}
1889
74510d4b
ML
1890void sp_free_error_message(char *message)
1891{
c33efc48
ML
1892 TRACE("%s", message);
1893
74510d4b
ML
1894#ifdef _WIN32
1895 LocalFree(message);
64eec30d
ML
1896#else
1897 (void)message;
74510d4b 1898#endif
c33efc48
ML
1899
1900 RETURN();
74510d4b 1901}
863b35e6
ML
1902
1903void sp_set_debug_handler(void (*handler)(const char *format, ...))
1904{
c33efc48
ML
1905 TRACE("%p", handler);
1906
863b35e6 1907 sp_debug_handler = handler;
c33efc48
ML
1908
1909 RETURN();
863b35e6
ML
1910}
1911
1912void sp_default_debug_handler(const char *format, ...)
1913{
1914 va_list args;
1915 va_start(args, format);
1916 if (getenv("LIBSERIALPORT_DEBUG")) {
dd7742fb 1917 fputs("sp: ", stderr);
863b35e6
ML
1918 vfprintf(stderr, format, args);
1919 }
1920 va_end(args);
1921}