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