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