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