]> sigrok.org Git - libserialport.git/blame - serialport.c
get_config(): Add a quickfix for xon_xoff.
[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>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Lesser General Public License as
10 * published by the Free Software Foundation, either version 3 of the
11 * License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#include <string.h>
23#include <sys/types.h>
24#include <sys/stat.h>
25#include <fcntl.h>
26#include <unistd.h>
3b63f34d
ML
27#include <stdlib.h>
28#include <errno.h>
74510d4b
ML
29#ifdef _WIN32
30#include <windows.h>
3b63f34d 31#include <tchar.h>
767c5ba8 32#include <stdio.h>
74510d4b 33#else
74510d4b
ML
34#include <termios.h>
35#include <sys/ioctl.h>
36#endif
3b63f34d 37#ifdef __APPLE__
1ebf4347
ML
38#include <IOKit/IOKitLib.h>
39#include <IOKit/serial/IOSerialKeys.h>
40#include <sys/syslimits.h>
3b63f34d
ML
41#endif
42#ifdef __linux__
43#include "libudev.h"
4b97c9fc 44#include "linux/serial.h"
3b63f34d 45#endif
74510d4b 46
f6a1fb65 47#include "libserialport.h"
74510d4b 48
8f189c4c 49struct port_data {
8094e4a0
ML
50#ifdef _WIN32
51 DCB dcb;
52#else
53 struct termios term;
824dcb45 54 int controlbits;
8094e4a0
ML
55#endif
56};
57
da2748bf
ML
58/* Standard baud rates. */
59#ifdef _WIN32
60#define BAUD_TYPE DWORD
61#define BAUD(n) {CBR_##n, n}
62#else
63#define BAUD_TYPE speed_t
64#define BAUD(n) {B##n, n}
65#endif
66
67struct std_baudrate {
68 BAUD_TYPE index;
69 int value;
70};
71
72const struct std_baudrate std_baudrates[] = {
73#ifdef _WIN32
74 /*
75 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
76 * have documented CBR_* macros.
77 */
78 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
79 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
80 BAUD(115200), BAUD(128000), BAUD(256000)
81#else
82 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200), BAUD(300),
83 BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800), BAUD(9600),
84 BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200), BAUD(230400),
85#if !defined(__APPLE__) && !defined(__OpenBSD__)
86 BAUD(460800)
87#endif
88#endif
89};
90
91#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
92#define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
93
348e23cc 94/* Helper functions. */
eb6ed20f 95static enum sp_return validate_port(struct sp_port *port);
348e23cc 96static struct sp_port **list_append(struct sp_port **list, const char *portname);
eb6ed20f
ML
97static enum sp_return get_config(struct sp_port *port, struct port_data *data,
98 struct sp_port_config *config);
99static enum sp_return set_config(struct sp_port *port, struct port_data *data,
100 const struct sp_port_config *config);
80186526 101
eb6ed20f 102enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
d54e9004
ML
103{
104 struct sp_port *port;
5919c913 105 int len;
d54e9004 106
32b5ac05
ML
107 if (!port_ptr)
108 return SP_ERR_ARG;
109
77f262c4
ML
110 *port_ptr = NULL;
111
d4babed2 112 if (!portname)
77f262c4 113 return SP_ERR_ARG;
d4babed2 114
d54e9004 115 if (!(port = malloc(sizeof(struct sp_port))))
77f262c4 116 return SP_ERR_MEM;
d54e9004 117
5919c913
ML
118 len = strlen(portname) + 1;
119
d54e9004
ML
120 if (!(port->name = malloc(len)))
121 {
122 free(port);
77f262c4 123 return SP_ERR_MEM;
d54e9004
ML
124 }
125
126 memcpy(port->name, portname, len);
127
8f471c66
ML
128#ifdef _WIN32
129 port->hdl = INVALID_HANDLE_VALUE;
130#else
131 port->fd = -1;
132#endif
133
77f262c4
ML
134 *port_ptr = port;
135
136 return SP_OK;
d54e9004
ML
137}
138
eb6ed20f 139enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
32b5ac05
ML
140{
141 if (!copy_ptr)
142 return SP_ERR_ARG;
143
144 *copy_ptr = NULL;
145
146 if (!port || !port->name)
147 return SP_ERR_ARG;
148
149 return sp_get_port_by_name(port->name, copy_ptr);
150}
151
e3b2f7a4
ML
152void sp_free_port(struct sp_port *port)
153{
154 if (!port)
155 return;
156
157 if (port->name)
158 free(port->name);
159
160 free(port);
161}
162
348e23cc 163static struct sp_port **list_append(struct sp_port **list, const char *portname)
3b63f34d
ML
164{
165 void *tmp;
166 unsigned int count;
f92f1f0c 167
3b63f34d 168 for (count = 0; list[count]; count++);
d54e9004 169 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
3b63f34d
ML
170 goto fail;
171 list = tmp;
77f262c4 172 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
3b63f34d 173 goto fail;
db2794ce 174 list[count + 1] = NULL;
3b63f34d 175 return list;
f92f1f0c 176
3b63f34d
ML
177fail:
178 sp_free_port_list(list);
179 return NULL;
180}
181
eb6ed20f 182enum sp_return sp_list_ports(struct sp_port ***list_ptr)
3b63f34d 183{
d54e9004 184 struct sp_port **list;
77f262c4 185 int ret = SP_OK;
24c1a4bb 186
d54e9004 187 if (!(list = malloc(sizeof(struct sp_port **))))
f92f1f0c 188 return SP_ERR_MEM;
24c1a4bb
ML
189
190 list[0] = NULL;
3b63f34d
ML
191
192#ifdef _WIN32
193 HKEY key;
bdfb5b8c
ML
194 TCHAR *value, *data;
195 DWORD max_value_len, max_data_size, max_data_len;
196 DWORD value_len, data_size, data_len;
3b63f34d 197 DWORD type, index = 0;
8b532d9c
ML
198 char *name;
199 int name_len;
3b63f34d
ML
200
201 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
202 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
77f262c4
ML
203 {
204 ret = SP_ERR_FAIL;
205 goto out_done;
206 }
3b63f34d 207 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
bdfb5b8c 208 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
77f262c4
ML
209 {
210 ret = SP_ERR_FAIL;
3b63f34d 211 goto out_close;
77f262c4 212 }
3b63f34d 213 max_data_len = max_data_size / sizeof(TCHAR);
bdfb5b8c 214 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
77f262c4
ML
215 {
216 ret = SP_ERR_MEM;
3b63f34d 217 goto out_close;
77f262c4 218 }
3b63f34d 219 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
77f262c4
ML
220 {
221 ret = SP_ERR_MEM;
bdfb5b8c 222 goto out_free_value;
77f262c4 223 }
3b63f34d 224 while (
d9573bad 225 value_len = max_value_len + 1,
3b63f34d 226 data_size = max_data_size,
bdfb5b8c 227 RegEnumValue(key, index, value, &value_len,
3b63f34d
ML
228 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
229 {
230 data_len = data_size / sizeof(TCHAR);
231 data[data_len] = '\0';
8b532d9c
ML
232#ifdef UNICODE
233 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
234#else
235 name_len = data_len + 1;
236#endif
237 if (!(name = malloc(name_len)))
77f262c4
ML
238 {
239 ret = SP_ERR_MEM;
8b532d9c 240 goto out;
77f262c4 241 }
8b532d9c
ML
242#ifdef UNICODE
243 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
244#else
245 strcpy(name, data);
246#endif
348e23cc 247 if (type == REG_SZ && !(list = list_append(list, name)))
77f262c4
ML
248 {
249 ret = SP_ERR_MEM;
250 goto out;
251 }
3b63f34d
ML
252 index++;
253 }
254out:
255 free(data);
bdfb5b8c
ML
256out_free_value:
257 free(value);
3b63f34d
ML
258out_close:
259 RegCloseKey(key);
77f262c4 260out_done:
3b63f34d
ML
261#endif
262#ifdef __APPLE__
263 mach_port_t master;
264 CFMutableDictionaryRef classes;
265 io_iterator_t iter;
266 char *path;
267 io_object_t port;
268 CFTypeRef cf_path;
269 Boolean result;
270
271 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
77f262c4
ML
272 {
273 ret = SP_ERR_FAIL;
274 goto out_done;
275 }
3b63f34d
ML
276
277 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
77f262c4
ML
278 {
279 ret = SP_ERR_FAIL;
280 goto out_done;
281 }
3b63f34d
ML
282
283 CFDictionarySetValue(classes,
284 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
285
0d34b451 286 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS)
77f262c4
ML
287 {
288 ret = SP_ERR_FAIL;
289 goto out_done;
290 }
3b63f34d
ML
291
292 if (!(path = malloc(PATH_MAX)))
77f262c4
ML
293 {
294 ret = SP_ERR_MEM;
3b63f34d 295 goto out_release;
77f262c4 296 }
3b63f34d 297
1ebf4347 298 while ((port = IOIteratorNext(iter))) {
3b63f34d
ML
299 cf_path = IORegistryEntryCreateCFProperty(port,
300 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
301 if (cf_path) {
302 result = CFStringGetCString(cf_path,
303 path, PATH_MAX, kCFStringEncodingASCII);
304 CFRelease(cf_path);
348e23cc 305 if (result && !(list = list_append(list, path)))
77f262c4
ML
306 {
307 ret = SP_ERR_MEM;
308 IOObjectRelease(port);
309 goto out;
310 }
3b63f34d
ML
311 }
312 IOObjectRelease(port);
313 }
3b63f34d
ML
314out:
315 free(path);
316out_release:
317 IOObjectRelease(iter);
77f262c4 318out_done:
3b63f34d
ML
319#endif
320#ifdef __linux__
321 struct udev *ud;
322 struct udev_enumerate *ud_enumerate;
323 struct udev_list_entry *ud_list;
324 struct udev_list_entry *ud_entry;
325 const char *path;
08fe0bdb 326 struct udev_device *ud_dev, *ud_parent;
3b63f34d 327 const char *name;
4b97c9fc
ML
328 const char *driver;
329 int fd, ioctl_result;
330 struct serial_struct serial_info;
3b63f34d
ML
331
332 ud = udev_new();
333 ud_enumerate = udev_enumerate_new(ud);
334 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
335 udev_enumerate_scan_devices(ud_enumerate);
336 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
3b63f34d
ML
337 udev_list_entry_foreach(ud_entry, ud_list)
338 {
339 path = udev_list_entry_get_name(ud_entry);
340 ud_dev = udev_device_new_from_syspath(ud, path);
08fe0bdb
ML
341 /* If there is no parent device, this is a virtual tty. */
342 ud_parent = udev_device_get_parent(ud_dev);
343 if (ud_parent == NULL)
344 {
345 udev_device_unref(ud_dev);
346 continue;
347 }
3b63f34d 348 name = udev_device_get_devnode(ud_dev);
4b97c9fc
ML
349 /* The serial8250 driver has a hardcoded number of ports.
350 * The only way to tell which actually exist on a given system
351 * is to try to open them and make an ioctl call. */
352 driver = udev_device_get_driver(ud_parent);
353 if (driver && !strcmp(driver, "serial8250"))
354 {
355 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
356 goto skip;
357 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
358 close(fd);
359 if (ioctl_result != 0)
360 goto skip;
361 if (serial_info.type == PORT_UNKNOWN)
362 goto skip;
363 }
348e23cc 364 list = list_append(list, name);
4b97c9fc 365skip:
3b63f34d
ML
366 udev_device_unref(ud_dev);
367 if (!list)
77f262c4
ML
368 {
369 ret = SP_ERR_MEM;
3b63f34d 370 goto out;
77f262c4 371 }
3b63f34d
ML
372 }
373out:
374 udev_enumerate_unref(ud_enumerate);
375 udev_unref(ud);
3b63f34d 376#endif
77f262c4
ML
377
378 if (ret == SP_OK)
379 {
380 *list_ptr = list;
381 }
382 else
383 {
384 if (list)
385 sp_free_port_list(list);
386
387 *list_ptr = NULL;
388 }
389
390 return ret;
3b63f34d
ML
391}
392
d54e9004 393void sp_free_port_list(struct sp_port **list)
3b63f34d
ML
394{
395 unsigned int i;
f92f1f0c 396
3b63f34d 397 for (i = 0; list[i]; i++)
e3b2f7a4 398 sp_free_port(list[i]);
3b63f34d
ML
399 free(list);
400}
401
eb6ed20f 402static enum sp_return validate_port(struct sp_port *port)
74510d4b
ML
403{
404 if (port == NULL)
405 return 0;
406#ifdef _WIN32
407 if (port->hdl == INVALID_HANDLE_VALUE)
408 return 0;
409#else
410 if (port->fd < 0)
411 return 0;
412#endif
413 return 1;
414}
415
348e23cc 416#define CHECK_PORT() do { if (!validate_port(port)) return SP_ERR_ARG; } while (0)
74510d4b 417
eb6ed20f 418enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
74510d4b
ML
419{
420 if (!port)
421 return SP_ERR_ARG;
422
74510d4b
ML
423#ifdef _WIN32
424 DWORD desired_access = 0, flags_and_attributes = 0;
99945a1f
ML
425 char *escaped_port_name;
426
427 /* Prefix port name with '\\.\' to work with ports above COM9. */
428 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
429 return SP_ERR_MEM;
430 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
431
74510d4b
ML
432 /* Map 'flags' to the OS-specific settings. */
433 desired_access |= GENERIC_READ;
434 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
435 if (flags & SP_MODE_RDWR)
436 desired_access |= GENERIC_WRITE;
437 if (flags & SP_MODE_NONBLOCK)
438 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
439
99945a1f 440 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
74510d4b 441 OPEN_EXISTING, flags_and_attributes, 0);
99945a1f
ML
442
443 free(escaped_port_name);
444
74510d4b
ML
445 if (port->hdl == INVALID_HANDLE_VALUE)
446 return SP_ERR_FAIL;
447#else
448 int flags_local = 0;
8f189c4c 449 struct port_data data;
e33ab9aa
ML
450 struct sp_port_config config;
451 int ret;
f92f1f0c 452
74510d4b
ML
453 /* Map 'flags' to the OS-specific settings. */
454 if (flags & SP_MODE_RDWR)
455 flags_local |= O_RDWR;
456 if (flags & SP_MODE_RDONLY)
457 flags_local |= O_RDONLY;
458 if (flags & SP_MODE_NONBLOCK)
459 flags_local |= O_NONBLOCK;
460
461 if ((port->fd = open(port->name, flags_local)) < 0)
462 return SP_ERR_FAIL;
9cb98459 463
e33ab9aa
ML
464 ret = get_config(port, &data, &config);
465
466 if (ret < 0)
467 {
468 sp_close(port);
469 return ret;
470 }
9cb98459
ML
471
472 /* Turn off all serial port cooking. */
473 data.term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
474 data.term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
475#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
476 data.term.c_oflag &= ~OFILL;
477#endif
478 /* Disable canonical mode, and don't echo input characters. */
479 data.term.c_lflag &= ~(ICANON | ECHO);
480
481 /* Ignore modem status lines; enable receiver */
482 data.term.c_cflag |= (CLOCAL | CREAD);
483
e33ab9aa
ML
484 ret = set_config(port, &data, &config);
485
486 if (ret < 0)
487 {
488 sp_close(port);
489 return ret;
490 }
74510d4b
ML
491#endif
492
493 return SP_OK;
494}
495
eb6ed20f 496enum sp_return sp_close(struct sp_port *port)
74510d4b
ML
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;
8f471c66 504 port->hdl = INVALID_HANDLE_VALUE;
74510d4b
ML
505#else
506 /* Returns 0 upon success, -1 upon failure. */
507 if (close(port->fd) == -1)
508 return SP_ERR_FAIL;
8f471c66 509 port->fd = -1;
74510d4b
ML
510#endif
511
512 return SP_OK;
513}
514
eb6ed20f 515enum sp_return sp_flush(struct sp_port *port)
74510d4b
ML
516{
517 CHECK_PORT();
518
519#ifdef _WIN32
520 /* Returns non-zero upon success, 0 upon failure. */
521 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
522 return SP_ERR_FAIL;
523#else
524 /* Returns 0 upon success, -1 upon failure. */
525 if (tcflush(port->fd, TCIOFLUSH) < 0)
526 return SP_ERR_FAIL;
527#endif
528 return SP_OK;
529}
530
eb6ed20f 531enum sp_return sp_write(struct sp_port *port, const void *buf, size_t count)
74510d4b
ML
532{
533 CHECK_PORT();
534
535 if (!buf)
536 return SP_ERR_ARG;
537
538#ifdef _WIN32
539 DWORD written = 0;
f92f1f0c 540
74510d4b
ML
541 /* Returns non-zero upon success, 0 upon failure. */
542 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
543 return SP_ERR_FAIL;
544 return written;
545#else
546 /* Returns the number of bytes written, or -1 upon failure. */
547 ssize_t written = write(port->fd, buf, count);
f92f1f0c 548
74510d4b
ML
549 if (written < 0)
550 return SP_ERR_FAIL;
551 else
f92f1f0c 552 return written;
74510d4b
ML
553#endif
554}
555
eb6ed20f 556enum sp_return sp_read(struct sp_port *port, void *buf, size_t count)
74510d4b
ML
557{
558 CHECK_PORT();
559
560 if (!buf)
561 return SP_ERR_ARG;
562
563#ifdef _WIN32
564 DWORD bytes_read = 0;
f92f1f0c 565
74510d4b
ML
566 /* Returns non-zero upon success, 0 upon failure. */
567 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
568 return SP_ERR_FAIL;
569 return bytes_read;
570#else
571 ssize_t bytes_read;
f92f1f0c 572
74510d4b
ML
573 /* Returns the number of bytes read, or -1 upon failure. */
574 if ((bytes_read = read(port->fd, buf, count)) < 0)
575 return SP_ERR_FAIL;
576 return bytes_read;
577#endif
578}
579
eb6ed20f
ML
580static enum sp_return get_config(struct sp_port *port, struct port_data *data,
581 struct sp_port_config *config)
8094e4a0 582{
da2748bf 583 unsigned int i;
cbf628c7 584
8094e4a0 585#ifdef _WIN32
e33ab9aa 586 if (!GetCommState(port->hdl, &data->dcb))
d514a26f 587 return SP_ERR_FAIL;
8094e4a0 588
067417af 589 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
e33ab9aa 590 if (data->dcb.BaudRate == std_baudrates[i].index) {
067417af
ML
591 config->baudrate = std_baudrates[i].value;
592 break;
593 }
594 }
595
596 if (i == NUM_STD_BAUDRATES)
597 /* BaudRate field can be either an index or a custom baud rate. */
e33ab9aa 598 config->baudrate = data->dcb.BaudRate;
067417af 599
e33ab9aa 600 config->bits = data->dcb.ByteSize;
067417af 601
e33ab9aa
ML
602 if (data->dcb.fParity)
603 switch (data->dcb.Parity) {
067417af
ML
604 case NOPARITY:
605 config->parity = SP_PARITY_NONE;
606 break;
607 case EVENPARITY:
608 config->parity = SP_PARITY_EVEN;
609 break;
610 case ODDPARITY:
611 config->parity = SP_PARITY_ODD;
612 break;
613 default:
614 config->parity = -1;
615 }
616 else
617 config->parity = SP_PARITY_NONE;
618
e33ab9aa 619 switch (data->dcb.StopBits) {
067417af
ML
620 case ONESTOPBIT:
621 config->stopbits = 1;
622 break;
623 case TWOSTOPBITS:
624 config->stopbits = 2;
625 break;
626 default:
627 config->stopbits = -1;
628 }
629
e33ab9aa 630 switch (data->dcb.fRtsControl) {
067417af
ML
631 case RTS_CONTROL_DISABLE:
632 config->rts = SP_RTS_OFF;
633 break;
634 case RTS_CONTROL_ENABLE:
635 config->rts = SP_RTS_ON;
636 break;
637 case RTS_CONTROL_HANDSHAKE:
638 config->rts = SP_RTS_FLOW_CONTROL;
639 break;
640 default:
641 config->rts = -1;
642 }
643
e33ab9aa 644 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
067417af 645
e33ab9aa 646 switch (data->dcb.fDtrControl) {
067417af
ML
647 case DTR_CONTROL_DISABLE:
648 config->dtr = SP_DTR_OFF;
649 break;
650 case DTR_CONTROL_ENABLE:
651 config->dtr = SP_DTR_ON;
652 break;
653 case DTR_CONTROL_HANDSHAKE:
654 config->dtr = SP_DTR_FLOW_CONTROL;
655 break;
656 default:
657 config->dtr = -1;
658 }
659
e33ab9aa
ML
660 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
661
c6754b45
ML
662 if (data->dcb.fInX) {
663 if (data->dcb.fOutX)
664 config->xon_xoff = SP_XONXOFF_INOUT;
665 else
666 config->xon_xoff = SP_XONXOFF_IN;
667 } else {
668 if (data->dcb.fOutX)
669 config->xon_xoff = SP_XONXOFF_OUT;
670 else
671 config->xon_xoff = SP_XONXOFF_DISABLED;
672 }
673
e33ab9aa
ML
674#else // !_WIN32
675
676 if (tcgetattr(port->fd, &data->term) < 0)
677 return SP_ERR_FAIL;
678
679 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
680 return SP_ERR_FAIL;
067417af 681 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
e33ab9aa 682 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
067417af
ML
683 config->baudrate = std_baudrates[i].value;
684 break;
685 }
686 }
687
688 if (i == NUM_STD_BAUDRATES)
689 config->baudrate = -1;
690
e33ab9aa 691 switch (data->term.c_cflag & CSIZE) {
067417af
ML
692 case CS8:
693 config->bits = 8;
694 break;
695 case CS7:
696 config->bits = 7;
697 break;
698 case CS6:
699 config->bits = 6;
700 break;
701 case CS5:
702 config->bits = 5;
703 break;
704 default:
705 config->bits = -1;
706 }
707
e33ab9aa 708 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
067417af 709 config->parity = SP_PARITY_NONE;
e33ab9aa 710 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
067417af
ML
711 config->parity = -1;
712 else
e33ab9aa 713 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
067417af 714
e33ab9aa 715 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
067417af 716
e33ab9aa 717 if (data->term.c_cflag & CRTSCTS) {
067417af
ML
718 config->rts = SP_RTS_FLOW_CONTROL;
719 config->cts = SP_CTS_FLOW_CONTROL;
720 } else {
e33ab9aa 721 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
067417af
ML
722 config->cts = SP_CTS_IGNORE;
723 }
724
e33ab9aa 725 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
067417af 726 config->dsr = SP_DSR_IGNORE;
705bdc69
UH
727
728 /* FIXME: Set config->xon_xoff properly, depending on data->term. */
729 config->xon_xoff = SP_XONXOFF_DISABLED;
067417af
ML
730#endif
731
732 return SP_OK;
733}
734
eb6ed20f
ML
735static enum sp_return set_config(struct sp_port *port, struct port_data *data,
736 const struct sp_port_config *config)
18fc2dd1 737{
e33ab9aa 738 unsigned int i;
18fc2dd1 739
e33ab9aa
ML
740#ifdef _WIN32
741 if (config->baudrate >= 0)
742 {
743 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
744 if (config->baudrate == std_baudrates[i].value) {
745 data->dcb.BaudRate = std_baudrates[i].index;
746 break;
747 }
748 }
18fc2dd1 749
e33ab9aa
ML
750 if (i == NUM_STD_BAUDRATES)
751 data->dcb.BaudRate = config->baudrate;
752 }
18fc2dd1 753
e33ab9aa
ML
754 if (config->bits >= 0)
755 data->dcb.ByteSize = config->bits;
756
757 if (config->parity >= 0) {
758 switch (config->parity) {
759 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
760 case SP_PARITY_NONE:
761 data->dcb.Parity = NOPARITY;
762 break;
763 case SP_PARITY_EVEN:
764 data->dcb.Parity = EVENPARITY;
765 break;
766 case SP_PARITY_ODD:
767 data->dcb.Parity = ODDPARITY;
768 break;
769 default:
770 return SP_ERR_ARG;
771 }
18fc2dd1
ML
772 }
773
e33ab9aa
ML
774 if (config->stopbits >= 0) {
775 switch (config->stopbits) {
776 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
777 case 1:
778 data->dcb.StopBits = ONESTOPBIT;
779 break;
780 case 2:
781 data->dcb.StopBits = TWOSTOPBITS;
782 break;
783 default:
784 return SP_ERR_ARG;
785 }
786 }
787
788 if (config->rts >= 0) {
789 switch (config->rts) {
790 case SP_RTS_OFF:
791 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
792 break;
793 case SP_RTS_ON:
794 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
795 break;
796 case SP_RTS_FLOW_CONTROL:
797 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
798 break;
799 default:
800 return SP_ERR_ARG;
801 }
802 }
803
804 if (config->cts >= 0) {
805 switch (config->cts) {
806 case SP_CTS_IGNORE:
807 data->dcb.fOutxCtsFlow = FALSE;
808 break;
809 case SP_CTS_FLOW_CONTROL:
810 data->dcb.fOutxCtsFlow = TRUE;
811 break;
812 default:
813 return SP_ERR_ARG;
814 }
815 }
816
817 if (config->dtr >= 0) {
818 switch (config->dtr) {
819 case SP_DTR_OFF:
820 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
821 break;
822 case SP_DTR_ON:
823 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
824 break;
825 case SP_DTR_FLOW_CONTROL:
826 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
827 break;
828 default:
829 return SP_ERR_ARG;
830 }
831 }
832
833 if (config->dsr >= 0) {
834 switch (config->dsr) {
835 case SP_DSR_IGNORE:
836 data->dcb.fOutxDsrFlow = FALSE;
837 break;
838 case SP_DSR_FLOW_CONTROL:
839 data->dcb.fOutxDsrFlow = TRUE;
840 break;
841 default:
842 return SP_ERR_ARG;
843 }
18fc2dd1
ML
844 }
845
e33ab9aa
ML
846 if (config->xon_xoff >= 0) {
847 switch (config->xon_xoff) {
848 case SP_XONXOFF_DISABLED:
849 data->dcb.fInX = FALSE;
850 data->dcb.fOutX = FALSE;
851 break;
852 case SP_XONXOFF_IN:
853 data->dcb.fInX = TRUE;
854 data->dcb.fOutX = FALSE;
855 break;
856 case SP_XONXOFF_OUT:
857 data->dcb.fInX = FALSE;
858 data->dcb.fOutX = TRUE;
859 break;
860 case SP_XONXOFF_INOUT:
861 data->dcb.fInX = TRUE;
862 data->dcb.fOutX = TRUE;
863 break;
864 default:
865 return SP_ERR_ARG;
866 }
867 }
868
869 if (!SetCommState(port->hdl, &data->dcb))
870 return SP_ERR_FAIL;
871
872#else // !_WIN32
873
874 if (config->baudrate >= 0)
875 {
876 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
877 if (config->baudrate == std_baudrates[i].value) {
878 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
879 return SP_ERR_FAIL;
880
881 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
882 return SP_ERR_FAIL;
883 break;
884 }
885 }
886
887 if (i == NUM_STD_BAUDRATES)
888 return SP_ERR_ARG;
889 }
890
891 if (config->bits >= 0) {
892 data->term.c_cflag &= ~CSIZE;
893 switch (config->bits) {
894 case 8:
895 data->term.c_cflag |= CS8;
896 break;
897 case 7:
898 data->term.c_cflag |= CS7;
899 break;
900 case 6:
901 data->term.c_cflag |= CS6;
902 break;
23922313
UH
903 case 5:
904 data->term.c_cflag |= CS5;
905 break;
e33ab9aa
ML
906 default:
907 return SP_ERR_ARG;
908 }
909 }
910
911 if (config->parity >= 0) {
912 data->term.c_iflag &= ~IGNPAR;
913 data->term.c_cflag &= ~(PARENB | PARODD);
914 switch (config->parity) {
915 case SP_PARITY_NONE:
916 data->term.c_iflag |= IGNPAR;
917 break;
918 case SP_PARITY_EVEN:
919 data->term.c_cflag |= PARENB;
920 break;
921 case SP_PARITY_ODD:
922 data->term.c_cflag |= PARENB | PARODD;
923 break;
924 default:
925 return SP_ERR_ARG;
926 }
927 }
928
929 if (config->stopbits >= 0) {
930 data->term.c_cflag &= ~CSTOPB;
931 switch (config->stopbits) {
932 case 1:
933 data->term.c_cflag &= ~CSTOPB;
934 break;
935 case 2:
936 data->term.c_cflag |= CSTOPB;
937 break;
938 default:
939 return SP_ERR_ARG;
940 }
941 }
942
943 if (config->rts >= 0 || config->cts >= 0)
944 {
945 /* Asymmetric use of RTS/CTS not supported yet. */
946
947 if (data->term.c_iflag & CRTSCTS) {
948 /* Flow control can only be disabled for both RTS & CTS together. */
949 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
950 if (config->cts != SP_CTS_IGNORE)
951 return SP_ERR_ARG;
952 }
953 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
954 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
955 return SP_ERR_ARG;
956 }
957 } else {
958 /* Flow control can only be enabled for both RTS & CTS together. */
959 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
960 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
961 return SP_ERR_ARG;
962 }
963
964 if (config->rts >= 0) {
965 if (config->rts == SP_RTS_FLOW_CONTROL) {
966 data->term.c_iflag |= CRTSCTS;
967 } else {
968 int controlbits = TIOCM_RTS;
969 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
970 &controlbits) < 0)
971 return SP_ERR_FAIL;
972 }
973 }
974 }
975
976 if (config->dtr >= 0 || config->dsr >= 0)
977 {
978 /* DTR/DSR flow control not supported yet. */
979 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
980 return SP_ERR_ARG;
981
982 if (config->dtr >= 0) {
983 int controlbits = TIOCM_DTR;
984 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
985 &controlbits) < 0)
986 return SP_ERR_FAIL;
987 }
988 }
989
990 if (config->xon_xoff >= 0) {
991 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
992 switch (config->xon_xoff) {
993 case SP_XONXOFF_DISABLED:
994 break;
995 case SP_XONXOFF_IN:
996 data->term.c_iflag |= IXOFF;
997 break;
998 case SP_XONXOFF_OUT:
999 data->term.c_iflag |= IXON | IXANY;
1000 break;
1001 case SP_XONXOFF_INOUT:
1002 data->term.c_iflag |= IXON | IXOFF | IXANY;
1003 break;
1004 default:
1005 return SP_ERR_ARG;
1006 }
1007 }
1008
1009 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
1010 return SP_ERR_FAIL;
1011#endif
1012
1013 return SP_OK;
1014}
1015
1016#define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
1017
eb6ed20f 1018enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
e33ab9aa 1019{
8f189c4c 1020 struct port_data data;
e33ab9aa
ML
1021 struct sp_port_config prev_config;
1022
823690ae
ML
1023 CHECK_PORT();
1024
1025 if (!config)
1026 return SP_ERR_ARG;
1027
e33ab9aa
ML
1028 TRY(get_config(port, &data, &prev_config));
1029 TRY(set_config(port, &data, config));
74510d4b
ML
1030
1031 return SP_OK;
1032}
1033
eb6ed20f 1034#define CREATE_SETTER(x, type) int sp_set_##x(struct sp_port *port, type x) { \
8f189c4c 1035 struct port_data data; \
e33ab9aa 1036 struct sp_port_config config; \
823690ae 1037 CHECK_PORT(); \
e33ab9aa
ML
1038 TRY(get_config(port, &data, &config)); \
1039 config.x = x; \
1040 TRY(set_config(port, &data, &config)); \
9069c2fb
ML
1041 return SP_OK; \
1042}
1043
eb6ed20f
ML
1044CREATE_SETTER(baudrate, int)
1045CREATE_SETTER(bits, int)
1046CREATE_SETTER(parity, enum sp_parity)
1047CREATE_SETTER(stopbits, int)
1048CREATE_SETTER(rts, enum sp_rts)
1049CREATE_SETTER(cts, enum sp_cts)
1050CREATE_SETTER(dtr, enum sp_dtr)
1051CREATE_SETTER(dsr, enum sp_dsr)
1052CREATE_SETTER(xon_xoff, enum sp_xonxoff)
1053
1054enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
e33ab9aa 1055{
8f189c4c 1056 struct port_data data;
e33ab9aa
ML
1057 struct sp_port_config config;
1058
823690ae
ML
1059 CHECK_PORT();
1060
e33ab9aa
ML
1061 TRY(get_config(port, &data, &config));
1062
1063 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
1064 config.xon_xoff = SP_XONXOFF_INOUT;
1065 else
1066 config.xon_xoff = SP_XONXOFF_DISABLED;
1067
1068 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
1069 config.rts = SP_RTS_FLOW_CONTROL;
1070 config.cts = SP_CTS_FLOW_CONTROL;
1071 } else {
1072 if (config.rts == SP_RTS_FLOW_CONTROL)
1073 config.rts = SP_RTS_ON;
1074 config.cts = SP_CTS_IGNORE;
1075 }
1076
1077 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
1078 config.dtr = SP_DTR_FLOW_CONTROL;
1079 config.dsr = SP_DSR_FLOW_CONTROL;
1080 } else {
1081 if (config.dtr == SP_DTR_FLOW_CONTROL)
1082 config.dtr = SP_DTR_ON;
1083 config.dsr = SP_DSR_IGNORE;
1084 }
1085
1086 TRY(set_config(port, &data, &config));
1087
1088 return SP_OK;
1089}
1090
74510d4b
ML
1091int sp_last_error_code(void)
1092{
1093#ifdef _WIN32
1094 return GetLastError();
1095#else
1096 return errno;
1097#endif
1098}
1099
74510d4b
ML
1100char *sp_last_error_message(void)
1101{
1102#ifdef _WIN32
1103 LPVOID message;
1104 DWORD error = GetLastError();
1105
1106 FormatMessage(
1107 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1108 FORMAT_MESSAGE_FROM_SYSTEM |
1109 FORMAT_MESSAGE_IGNORE_INSERTS,
1110 NULL,
1111 error,
1112 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1113 (LPTSTR) &message,
1114 0, NULL );
1115
1116 return message;
1117#else
1118 return strerror(errno);
1119#endif
1120}
1121
74510d4b
ML
1122void sp_free_error_message(char *message)
1123{
1124#ifdef _WIN32
1125 LocalFree(message);
64eec30d
ML
1126#else
1127 (void)message;
74510d4b
ML
1128#endif
1129}