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