]> sigrok.org Git - libserialport.git/blame - serialport.c
Use named enums instead of ints for clearer documentation.
[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
ML
726 config->dsr = SP_DSR_IGNORE;
727#endif
728
729 return SP_OK;
730}
731
eb6ed20f
ML
732static enum sp_return set_config(struct sp_port *port, struct port_data *data,
733 const struct sp_port_config *config)
18fc2dd1 734{
e33ab9aa 735 unsigned int i;
18fc2dd1 736
e33ab9aa
ML
737#ifdef _WIN32
738 if (config->baudrate >= 0)
739 {
740 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
741 if (config->baudrate == std_baudrates[i].value) {
742 data->dcb.BaudRate = std_baudrates[i].index;
743 break;
744 }
745 }
18fc2dd1 746
e33ab9aa
ML
747 if (i == NUM_STD_BAUDRATES)
748 data->dcb.BaudRate = config->baudrate;
749 }
18fc2dd1 750
e33ab9aa
ML
751 if (config->bits >= 0)
752 data->dcb.ByteSize = config->bits;
753
754 if (config->parity >= 0) {
755 switch (config->parity) {
756 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
757 case SP_PARITY_NONE:
758 data->dcb.Parity = NOPARITY;
759 break;
760 case SP_PARITY_EVEN:
761 data->dcb.Parity = EVENPARITY;
762 break;
763 case SP_PARITY_ODD:
764 data->dcb.Parity = ODDPARITY;
765 break;
766 default:
767 return SP_ERR_ARG;
768 }
18fc2dd1
ML
769 }
770
e33ab9aa
ML
771 if (config->stopbits >= 0) {
772 switch (config->stopbits) {
773 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
774 case 1:
775 data->dcb.StopBits = ONESTOPBIT;
776 break;
777 case 2:
778 data->dcb.StopBits = TWOSTOPBITS;
779 break;
780 default:
781 return SP_ERR_ARG;
782 }
783 }
784
785 if (config->rts >= 0) {
786 switch (config->rts) {
787 case SP_RTS_OFF:
788 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
789 break;
790 case SP_RTS_ON:
791 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
792 break;
793 case SP_RTS_FLOW_CONTROL:
794 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
795 break;
796 default:
797 return SP_ERR_ARG;
798 }
799 }
800
801 if (config->cts >= 0) {
802 switch (config->cts) {
803 case SP_CTS_IGNORE:
804 data->dcb.fOutxCtsFlow = FALSE;
805 break;
806 case SP_CTS_FLOW_CONTROL:
807 data->dcb.fOutxCtsFlow = TRUE;
808 break;
809 default:
810 return SP_ERR_ARG;
811 }
812 }
813
814 if (config->dtr >= 0) {
815 switch (config->dtr) {
816 case SP_DTR_OFF:
817 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
818 break;
819 case SP_DTR_ON:
820 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
821 break;
822 case SP_DTR_FLOW_CONTROL:
823 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
824 break;
825 default:
826 return SP_ERR_ARG;
827 }
828 }
829
830 if (config->dsr >= 0) {
831 switch (config->dsr) {
832 case SP_DSR_IGNORE:
833 data->dcb.fOutxDsrFlow = FALSE;
834 break;
835 case SP_DSR_FLOW_CONTROL:
836 data->dcb.fOutxDsrFlow = TRUE;
837 break;
838 default:
839 return SP_ERR_ARG;
840 }
18fc2dd1
ML
841 }
842
e33ab9aa
ML
843 if (config->xon_xoff >= 0) {
844 switch (config->xon_xoff) {
845 case SP_XONXOFF_DISABLED:
846 data->dcb.fInX = FALSE;
847 data->dcb.fOutX = FALSE;
848 break;
849 case SP_XONXOFF_IN:
850 data->dcb.fInX = TRUE;
851 data->dcb.fOutX = FALSE;
852 break;
853 case SP_XONXOFF_OUT:
854 data->dcb.fInX = FALSE;
855 data->dcb.fOutX = TRUE;
856 break;
857 case SP_XONXOFF_INOUT:
858 data->dcb.fInX = TRUE;
859 data->dcb.fOutX = TRUE;
860 break;
861 default:
862 return SP_ERR_ARG;
863 }
864 }
865
866 if (!SetCommState(port->hdl, &data->dcb))
867 return SP_ERR_FAIL;
868
869#else // !_WIN32
870
871 if (config->baudrate >= 0)
872 {
873 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
874 if (config->baudrate == std_baudrates[i].value) {
875 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
876 return SP_ERR_FAIL;
877
878 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
879 return SP_ERR_FAIL;
880 break;
881 }
882 }
883
884 if (i == NUM_STD_BAUDRATES)
885 return SP_ERR_ARG;
886 }
887
888 if (config->bits >= 0) {
889 data->term.c_cflag &= ~CSIZE;
890 switch (config->bits) {
891 case 8:
892 data->term.c_cflag |= CS8;
893 break;
894 case 7:
895 data->term.c_cflag |= CS7;
896 break;
897 case 6:
898 data->term.c_cflag |= CS6;
899 break;
900 default:
901 return SP_ERR_ARG;
902 }
903 }
904
905 if (config->parity >= 0) {
906 data->term.c_iflag &= ~IGNPAR;
907 data->term.c_cflag &= ~(PARENB | PARODD);
908 switch (config->parity) {
909 case SP_PARITY_NONE:
910 data->term.c_iflag |= IGNPAR;
911 break;
912 case SP_PARITY_EVEN:
913 data->term.c_cflag |= PARENB;
914 break;
915 case SP_PARITY_ODD:
916 data->term.c_cflag |= PARENB | PARODD;
917 break;
918 default:
919 return SP_ERR_ARG;
920 }
921 }
922
923 if (config->stopbits >= 0) {
924 data->term.c_cflag &= ~CSTOPB;
925 switch (config->stopbits) {
926 case 1:
927 data->term.c_cflag &= ~CSTOPB;
928 break;
929 case 2:
930 data->term.c_cflag |= CSTOPB;
931 break;
932 default:
933 return SP_ERR_ARG;
934 }
935 }
936
937 if (config->rts >= 0 || config->cts >= 0)
938 {
939 /* Asymmetric use of RTS/CTS not supported yet. */
940
941 if (data->term.c_iflag & CRTSCTS) {
942 /* Flow control can only be disabled for both RTS & CTS together. */
943 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
944 if (config->cts != SP_CTS_IGNORE)
945 return SP_ERR_ARG;
946 }
947 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
948 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
949 return SP_ERR_ARG;
950 }
951 } else {
952 /* Flow control can only be enabled for both RTS & CTS together. */
953 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
954 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
955 return SP_ERR_ARG;
956 }
957
958 if (config->rts >= 0) {
959 if (config->rts == SP_RTS_FLOW_CONTROL) {
960 data->term.c_iflag |= CRTSCTS;
961 } else {
962 int controlbits = TIOCM_RTS;
963 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
964 &controlbits) < 0)
965 return SP_ERR_FAIL;
966 }
967 }
968 }
969
970 if (config->dtr >= 0 || config->dsr >= 0)
971 {
972 /* DTR/DSR flow control not supported yet. */
973 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
974 return SP_ERR_ARG;
975
976 if (config->dtr >= 0) {
977 int controlbits = TIOCM_DTR;
978 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
979 &controlbits) < 0)
980 return SP_ERR_FAIL;
981 }
982 }
983
984 if (config->xon_xoff >= 0) {
985 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
986 switch (config->xon_xoff) {
987 case SP_XONXOFF_DISABLED:
988 break;
989 case SP_XONXOFF_IN:
990 data->term.c_iflag |= IXOFF;
991 break;
992 case SP_XONXOFF_OUT:
993 data->term.c_iflag |= IXON | IXANY;
994 break;
995 case SP_XONXOFF_INOUT:
996 data->term.c_iflag |= IXON | IXOFF | IXANY;
997 break;
998 default:
999 return SP_ERR_ARG;
1000 }
1001 }
1002
1003 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
1004 return SP_ERR_FAIL;
1005#endif
1006
1007 return SP_OK;
1008}
1009
1010#define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
1011
eb6ed20f 1012enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
e33ab9aa 1013{
8f189c4c 1014 struct port_data data;
e33ab9aa
ML
1015 struct sp_port_config prev_config;
1016
823690ae
ML
1017 CHECK_PORT();
1018
1019 if (!config)
1020 return SP_ERR_ARG;
1021
e33ab9aa
ML
1022 TRY(get_config(port, &data, &prev_config));
1023 TRY(set_config(port, &data, config));
74510d4b
ML
1024
1025 return SP_OK;
1026}
1027
eb6ed20f 1028#define CREATE_SETTER(x, type) int sp_set_##x(struct sp_port *port, type x) { \
8f189c4c 1029 struct port_data data; \
e33ab9aa 1030 struct sp_port_config config; \
823690ae 1031 CHECK_PORT(); \
e33ab9aa
ML
1032 TRY(get_config(port, &data, &config)); \
1033 config.x = x; \
1034 TRY(set_config(port, &data, &config)); \
9069c2fb
ML
1035 return SP_OK; \
1036}
1037
eb6ed20f
ML
1038CREATE_SETTER(baudrate, int)
1039CREATE_SETTER(bits, int)
1040CREATE_SETTER(parity, enum sp_parity)
1041CREATE_SETTER(stopbits, int)
1042CREATE_SETTER(rts, enum sp_rts)
1043CREATE_SETTER(cts, enum sp_cts)
1044CREATE_SETTER(dtr, enum sp_dtr)
1045CREATE_SETTER(dsr, enum sp_dsr)
1046CREATE_SETTER(xon_xoff, enum sp_xonxoff)
1047
1048enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
e33ab9aa 1049{
8f189c4c 1050 struct port_data data;
e33ab9aa
ML
1051 struct sp_port_config config;
1052
823690ae
ML
1053 CHECK_PORT();
1054
e33ab9aa
ML
1055 TRY(get_config(port, &data, &config));
1056
1057 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
1058 config.xon_xoff = SP_XONXOFF_INOUT;
1059 else
1060 config.xon_xoff = SP_XONXOFF_DISABLED;
1061
1062 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
1063 config.rts = SP_RTS_FLOW_CONTROL;
1064 config.cts = SP_CTS_FLOW_CONTROL;
1065 } else {
1066 if (config.rts == SP_RTS_FLOW_CONTROL)
1067 config.rts = SP_RTS_ON;
1068 config.cts = SP_CTS_IGNORE;
1069 }
1070
1071 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
1072 config.dtr = SP_DTR_FLOW_CONTROL;
1073 config.dsr = SP_DSR_FLOW_CONTROL;
1074 } else {
1075 if (config.dtr == SP_DTR_FLOW_CONTROL)
1076 config.dtr = SP_DTR_ON;
1077 config.dsr = SP_DSR_IGNORE;
1078 }
1079
1080 TRY(set_config(port, &data, &config));
1081
1082 return SP_OK;
1083}
1084
74510d4b
ML
1085int sp_last_error_code(void)
1086{
1087#ifdef _WIN32
1088 return GetLastError();
1089#else
1090 return errno;
1091#endif
1092}
1093
74510d4b
ML
1094char *sp_last_error_message(void)
1095{
1096#ifdef _WIN32
1097 LPVOID message;
1098 DWORD error = GetLastError();
1099
1100 FormatMessage(
1101 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1102 FORMAT_MESSAGE_FROM_SYSTEM |
1103 FORMAT_MESSAGE_IGNORE_INSERTS,
1104 NULL,
1105 error,
1106 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1107 (LPTSTR) &message,
1108 0, NULL );
1109
1110 return message;
1111#else
1112 return strerror(errno);
1113#endif
1114}
1115
74510d4b
ML
1116void sp_free_error_message(char *message)
1117{
1118#ifdef _WIN32
1119 LocalFree(message);
64eec30d
ML
1120#else
1121 (void)message;
74510d4b
ML
1122#endif
1123}