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