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