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