]> sigrok.org Git - libserialport.git/blob - serialport.c
Fix build for platforms without enumeration & port metadata support.
[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  * Copyright (C) 2013 Matthias Heidbrink <m-sigrok@heidbrink.biz>
8  * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Lesser General Public License as
12  * published by the Free Software Foundation, either version 3 of the
13  * License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24 #include "libserialport.h"
25 #include "libserialport_internal.h"
26
27 const struct std_baudrate std_baudrates[] = {
28 #ifdef _WIN32
29         /*
30          * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
31          * have documented CBR_* macros.
32          */
33         BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
34         BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
35         BAUD(115200), BAUD(128000), BAUD(256000),
36 #else
37         BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
38         BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
39         BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
40         BAUD(230400),
41 #if !defined(__APPLE__) && !defined(__OpenBSD__)
42         BAUD(460800),
43 #endif
44 #endif
45 };
46
47 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
48
49 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
50         struct sp_port_config *config);
51
52 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
53         const struct sp_port_config *config);
54
55 enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
56 {
57         struct sp_port *port;
58         enum sp_return ret;
59         int len;
60
61         TRACE("%s, %p", portname, port_ptr);
62
63         if (!port_ptr)
64                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
65
66         *port_ptr = NULL;
67
68         if (!portname)
69                 RETURN_ERROR(SP_ERR_ARG, "Null port name");
70
71         DEBUG("Building structure for port %s", portname);
72
73         if (!(port = malloc(sizeof(struct sp_port))))
74                 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
75
76         len = strlen(portname) + 1;
77
78         if (!(port->name = malloc(len))) {
79                 free(port);
80                 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
81         }
82
83         memcpy(port->name, portname, len);
84
85 #ifdef _WIN32
86         port->hdl = INVALID_HANDLE_VALUE;
87 #else
88         port->fd = -1;
89 #endif
90
91         port->description = NULL;
92         port->transport = SP_TRANSPORT_NATIVE;
93         port->usb_bus = -1;
94         port->usb_address = -1;
95         port->usb_vid = -1;
96         port->usb_pid = -1;
97         port->usb_manufacturer = NULL;
98         port->usb_product = NULL;
99         port->usb_serial = NULL;
100         port->bluetooth_address = NULL;
101
102 #ifndef NO_PORT_METADATA
103         if ((ret = get_port_details(port)) != SP_OK) {
104                 sp_free_port(port);
105                 return ret;
106         }
107 #endif
108
109         *port_ptr = port;
110
111         RETURN_OK();
112 }
113
114 char *sp_get_port_name(const struct sp_port *port)
115 {
116         TRACE("%p", port);
117
118         if (!port)
119                 return NULL;
120
121         RETURN_VALUE("%s", port->name);
122 }
123
124 char *sp_get_port_description(struct sp_port *port)
125 {
126         TRACE("%p", port);
127
128         if (!port || !port->description)
129                 return NULL;
130
131         RETURN_VALUE("%s", port->description);
132 }
133
134 enum sp_transport sp_get_port_transport(struct sp_port *port)
135 {
136         TRACE("%p", port);
137
138         if (!port)
139                 RETURN_ERROR(SP_ERR_ARG, "Null port");
140
141         RETURN_VALUE("%d", port->transport);
142 }
143
144 enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
145                                            int *usb_bus, int *usb_address)
146 {
147         TRACE("%p", port);
148
149         if (!port)
150                 RETURN_ERROR(SP_ERR_ARG, "Null port");
151         if (port->transport != SP_TRANSPORT_USB)
152                 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
153         if (port->usb_bus < 0 || port->usb_address < 0)
154                 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
155
156         if (usb_bus)      *usb_bus     = port->usb_bus;
157         if (usb_address)  *usb_address = port->usb_address;
158
159         RETURN_OK();
160 }
161
162 enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
163                                        int *usb_vid, int *usb_pid)
164 {
165         TRACE("%p", port);
166
167         if (!port)
168                 RETURN_ERROR(SP_ERR_ARG, "Null port");
169         if (port->transport != SP_TRANSPORT_USB)
170                 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
171         if (port->usb_vid < 0 || port->usb_pid < 0)
172                 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
173
174         if (usb_vid)  *usb_vid = port->usb_vid;
175         if (usb_pid)  *usb_pid = port->usb_pid;
176
177         RETURN_OK();
178 }
179
180 char *sp_get_port_usb_manufacturer(const struct sp_port *port)
181 {
182         TRACE("%p", port);
183
184         if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
185                 return NULL;
186
187         RETURN_VALUE("%s", port->usb_manufacturer);
188 }
189
190 char *sp_get_port_usb_product(const struct sp_port *port)
191 {
192         TRACE("%p", port);
193
194         if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
195                 return NULL;
196
197         RETURN_VALUE("%s", port->usb_product);
198 }
199
200 char *sp_get_port_usb_serial(const struct sp_port *port)
201 {
202         TRACE("%p", port);
203
204         if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
205                 return NULL;
206
207         RETURN_VALUE("%s", port->usb_serial);
208 }
209
210 char *sp_get_port_bluetooth_address(const struct sp_port *port)
211 {
212         TRACE("%p", port);
213
214         if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
215             || !port->bluetooth_address)
216                 return NULL;
217
218         RETURN_VALUE("%s", port->bluetooth_address);
219 }
220
221 enum sp_return sp_get_port_handle(const struct sp_port *port, void *result_ptr)
222 {
223         TRACE("%p, %p", port, result_ptr);
224
225         if (!port)
226                 RETURN_ERROR(SP_ERR_ARG, "Null port");
227
228 #ifdef _WIN32
229         HANDLE *handle_ptr = result_ptr;
230         *handle_ptr = port->hdl;
231 #else
232         int *fd_ptr = result_ptr;
233         *fd_ptr = port->fd;
234 #endif
235
236         RETURN_OK();
237 }
238
239 enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
240 {
241         TRACE("%p, %p", port, copy_ptr);
242
243         if (!copy_ptr)
244                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
245
246         *copy_ptr = NULL;
247
248         if (!port)
249                 RETURN_ERROR(SP_ERR_ARG, "Null port");
250
251         if (!port->name)
252                 RETURN_ERROR(SP_ERR_ARG, "Null port name");
253
254         DEBUG("Copying port structure");
255
256         RETURN_VALUE("%p", sp_get_port_by_name(port->name, copy_ptr));
257 }
258
259 void sp_free_port(struct sp_port *port)
260 {
261         TRACE("%p", port);
262
263         if (!port) {
264                 DEBUG("Null port");
265                 RETURN();
266         }
267
268         DEBUG("Freeing port structure");
269
270         if (port->name)
271                 free(port->name);
272         if (port->description)
273                 free(port->description);
274         if (port->usb_manufacturer)
275                 free(port->usb_manufacturer);
276         if (port->usb_product)
277                 free(port->usb_product);
278         if (port->usb_serial)
279                 free(port->usb_serial);
280         if (port->bluetooth_address)
281                 free(port->bluetooth_address);
282 #ifdef _WIN32
283         if (port->usb_path)
284                 free(port->usb_path);
285 #endif
286
287         free(port);
288
289         RETURN();
290 }
291
292 struct sp_port **list_append(struct sp_port **list, const char *portname)
293 {
294         void *tmp;
295         unsigned int count;
296
297         for (count = 0; list[count]; count++);
298         if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
299                 goto fail;
300         list = tmp;
301         if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
302                 goto fail;
303         list[count + 1] = NULL;
304         return list;
305
306 fail:
307         sp_free_port_list(list);
308         return NULL;
309 }
310
311 enum sp_return sp_list_ports(struct sp_port ***list_ptr)
312 {
313         struct sp_port **list;
314         int ret;
315
316         TRACE("%p", list_ptr);
317
318         if (!list_ptr)
319                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
320
321         DEBUG("Enumerating ports");
322
323         if (!(list = malloc(sizeof(struct sp_port **))))
324                 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
325
326         list[0] = NULL;
327
328 #ifdef NO_ENUMERATION
329         ret = SP_ERR_SUPP;
330 #else
331         ret = list_ports(&list);
332 #endif
333
334         switch (ret) {
335         case SP_OK:
336                 *list_ptr = list;
337                 RETURN_OK();
338         case SP_ERR_SUPP:
339                 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
340         default:
341                 if (list)
342                         sp_free_port_list(list);
343                 *list_ptr = NULL;
344                 return ret;
345         }
346 }
347
348 void sp_free_port_list(struct sp_port **list)
349 {
350         unsigned int i;
351
352         TRACE("%p", list);
353
354         if (!list) {
355                 DEBUG("Null list");
356                 RETURN();
357         }
358
359         DEBUG("Freeing port list");
360
361         for (i = 0; list[i]; i++)
362                 sp_free_port(list[i]);
363         free(list);
364
365         RETURN();
366 }
367
368 #define CHECK_PORT() do { \
369         if (port == NULL) \
370                 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
371         if (port->name == NULL) \
372                 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
373 } while (0)
374 #ifdef _WIN32
375 #define CHECK_PORT_HANDLE() do { \
376         if (port->hdl == INVALID_HANDLE_VALUE) \
377                 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
378 } while (0)
379 #else
380 #define CHECK_PORT_HANDLE() do { \
381         if (port->fd < 0) \
382                 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
383 } while (0)
384 #endif
385 #define CHECK_OPEN_PORT() do { \
386         CHECK_PORT(); \
387         CHECK_PORT_HANDLE(); \
388 } while (0)
389
390 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
391 {
392         struct port_data data;
393         struct sp_port_config config;
394         enum sp_return ret;
395
396         TRACE("%p, 0x%x", port, flags);
397
398         CHECK_PORT();
399
400         if (flags > (SP_MODE_READ | SP_MODE_WRITE))
401                 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
402
403         DEBUG("Opening port %s", port->name);
404
405 #ifdef _WIN32
406         DWORD desired_access = 0, flags_and_attributes = 0, errors;
407         char *escaped_port_name;
408         COMSTAT status;
409
410         /* Prefix port name with '\\.\' to work with ports above COM9. */
411         if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
412                 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
413         sprintf(escaped_port_name, "\\\\.\\%s", port->name);
414
415         /* Map 'flags' to the OS-specific settings. */
416         flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
417         if (flags & SP_MODE_READ)
418                 desired_access |= GENERIC_READ;
419         if (flags & SP_MODE_WRITE)
420                 desired_access |= GENERIC_WRITE;
421
422         port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
423                          OPEN_EXISTING, flags_and_attributes, 0);
424
425         free(escaped_port_name);
426
427         if (port->hdl == INVALID_HANDLE_VALUE)
428                 RETURN_FAIL("port CreateFile() failed");
429
430         /* All timeouts initially disabled. */
431         port->timeouts.ReadIntervalTimeout = 0;
432         port->timeouts.ReadTotalTimeoutMultiplier = 0;
433         port->timeouts.ReadTotalTimeoutConstant = 0;
434         port->timeouts.WriteTotalTimeoutMultiplier = 0;
435         port->timeouts.WriteTotalTimeoutConstant = 0;
436
437         if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
438                 sp_close(port);
439                 RETURN_FAIL("SetCommTimeouts() failed");
440         }
441
442         /* Prepare OVERLAPPED structures. */
443 #define INIT_OVERLAPPED(ovl) do { \
444         memset(&port->ovl, 0, sizeof(port->ovl)); \
445         port->ovl.hEvent = INVALID_HANDLE_VALUE; \
446         if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
447                         == INVALID_HANDLE_VALUE) { \
448                 sp_close(port); \
449                 RETURN_FAIL(#ovl "CreateEvent() failed"); \
450         } \
451 } while (0)
452
453         INIT_OVERLAPPED(read_ovl);
454         INIT_OVERLAPPED(write_ovl);
455         INIT_OVERLAPPED(wait_ovl);
456
457         /* Set event mask for RX and error events. */
458         if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
459                 sp_close(port);
460                 RETURN_FAIL("SetCommMask() failed");
461         }
462
463         /* Start background operation for RX and error events. */
464         if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
465                 if (GetLastError() != ERROR_IO_PENDING) {
466                         sp_close(port);
467                         RETURN_FAIL("WaitCommEvent() failed");
468                 }
469         }
470
471         port->writing = FALSE;
472
473 #else
474         int flags_local = O_NONBLOCK | O_NOCTTY;
475
476         /* Map 'flags' to the OS-specific settings. */
477         if (flags & (SP_MODE_READ | SP_MODE_WRITE))
478                 flags_local |= O_RDWR;
479         else if (flags & SP_MODE_READ)
480                 flags_local |= O_RDONLY;
481         else if (flags & SP_MODE_WRITE)
482                 flags_local |= O_WRONLY;
483
484         if ((port->fd = open(port->name, flags_local)) < 0)
485                 RETURN_FAIL("open() failed");
486 #endif
487
488         ret = get_config(port, &data, &config);
489
490         if (ret < 0) {
491                 sp_close(port);
492                 RETURN_CODEVAL(ret);
493         }
494
495         /* Set sane port settings. */
496 #ifdef _WIN32
497         data.dcb.fBinary = TRUE;
498         data.dcb.fDsrSensitivity = FALSE;
499         data.dcb.fErrorChar = FALSE;
500         data.dcb.fNull = FALSE;
501         data.dcb.fAbortOnError = TRUE;
502 #else
503         /* Turn off all fancy termios tricks, give us a raw channel. */
504         data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
505 #ifdef IUCLC
506         data.term.c_iflag &= ~IUCLC;
507 #endif
508         data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
509 #ifdef OLCUC
510         data.term.c_oflag &= ~OLCUC;
511 #endif
512 #ifdef NLDLY
513         data.term.c_oflag &= ~NLDLY;
514 #endif
515 #ifdef CRDLY
516         data.term.c_oflag &= ~CRDLY;
517 #endif
518 #ifdef TABDLY
519         data.term.c_oflag &= ~TABDLY;
520 #endif
521 #ifdef BSDLY
522         data.term.c_oflag &= ~BSDLY;
523 #endif
524 #ifdef VTDLY
525         data.term.c_oflag &= ~VTDLY;
526 #endif
527 #ifdef FFDLY
528         data.term.c_oflag &= ~FFDLY;
529 #endif
530 #ifdef OFILL
531         data.term.c_oflag &= ~OFILL;
532 #endif
533         data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
534         data.term.c_cc[VMIN] = 0;
535         data.term.c_cc[VTIME] = 0;
536
537         /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
538         data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
539 #endif
540
541 #ifdef _WIN32
542         if (ClearCommError(port->hdl, &errors, &status) == 0)
543                 RETURN_FAIL("ClearCommError() failed");
544 #endif
545
546         ret = set_config(port, &data, &config);
547
548         if (ret < 0) {
549                 sp_close(port);
550                 RETURN_CODEVAL(ret);
551         }
552
553         RETURN_OK();
554 }
555
556 enum sp_return sp_close(struct sp_port *port)
557 {
558         TRACE("%p", port);
559
560         CHECK_OPEN_PORT();
561
562         DEBUG("Closing port %s", port->name);
563
564 #ifdef _WIN32
565         /* Returns non-zero upon success, 0 upon failure. */
566         if (CloseHandle(port->hdl) == 0)
567                 RETURN_FAIL("port CloseHandle() failed");
568         port->hdl = INVALID_HANDLE_VALUE;
569
570         /* Close event handles for overlapped structures. */
571 #define CLOSE_OVERLAPPED(ovl) do { \
572         if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
573                 CloseHandle(port->ovl.hEvent) == 0) \
574                 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
575 } while (0)
576         CLOSE_OVERLAPPED(read_ovl);
577         CLOSE_OVERLAPPED(write_ovl);
578         CLOSE_OVERLAPPED(wait_ovl);
579
580 #else
581         /* Returns 0 upon success, -1 upon failure. */
582         if (close(port->fd) == -1)
583                 RETURN_FAIL("close() failed");
584         port->fd = -1;
585 #endif
586
587         RETURN_OK();
588 }
589
590 enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
591 {
592         TRACE("%p, 0x%x", port, buffers);
593
594         CHECK_OPEN_PORT();
595
596         if (buffers > SP_BUF_BOTH)
597                 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
598
599         const char *buffer_names[] = {"no", "input", "output", "both"};
600
601         DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
602
603 #ifdef _WIN32
604         DWORD flags = 0;
605         if (buffers & SP_BUF_INPUT)
606                 flags |= PURGE_RXCLEAR;
607         if (buffers & SP_BUF_OUTPUT)
608                 flags |= PURGE_TXCLEAR;
609
610         /* Returns non-zero upon success, 0 upon failure. */
611         if (PurgeComm(port->hdl, flags) == 0)
612                 RETURN_FAIL("PurgeComm() failed");
613 #else
614         int flags = 0;
615         if (buffers & SP_BUF_BOTH)
616                 flags = TCIOFLUSH;
617         else if (buffers & SP_BUF_INPUT)
618                 flags = TCIFLUSH;
619         else if (buffers & SP_BUF_OUTPUT)
620                 flags = TCOFLUSH;
621
622         /* Returns 0 upon success, -1 upon failure. */
623         if (tcflush(port->fd, flags) < 0)
624                 RETURN_FAIL("tcflush() failed");
625 #endif
626         RETURN_OK();
627 }
628
629 enum sp_return sp_drain(struct sp_port *port)
630 {
631         TRACE("%p", port);
632
633         CHECK_OPEN_PORT();
634
635         DEBUG("Draining port %s", port->name);
636
637 #ifdef _WIN32
638         /* Returns non-zero upon success, 0 upon failure. */
639         if (FlushFileBuffers(port->hdl) == 0)
640                 RETURN_FAIL("FlushFileBuffers() failed");
641         RETURN_OK();
642 #else
643         int result;
644         while (1) {
645 #ifdef __ANDROID__
646                 int arg = 1;
647                 result = ioctl(port->fd, TCSBRK, &arg);
648 #else
649                 result = tcdrain(port->fd);
650 #endif
651                 if (result < 0) {
652                         if (errno == EINTR) {
653                                 DEBUG("tcdrain() was interrupted");
654                                 continue;
655                         } else {
656                                 RETURN_FAIL("tcdrain() failed");
657                         }
658                 } else {
659                         RETURN_OK();
660                 }
661         }
662 #endif
663 }
664
665 enum sp_return sp_blocking_write(struct sp_port *port, const void *buf, size_t count, unsigned int timeout)
666 {
667         TRACE("%p, %p, %d, %d", port, buf, count, timeout);
668
669         CHECK_OPEN_PORT();
670
671         if (!buf)
672                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
673
674         if (timeout)
675                 DEBUG("Writing %d bytes to port %s, timeout %d ms", count, port->name, timeout);
676         else
677                 DEBUG("Writing %d bytes to port %s, no timeout", count, port->name);
678
679         if (count == 0)
680                 RETURN_VALUE("0", 0);
681
682 #ifdef _WIN32
683         DWORD bytes_written = 0;
684         BOOL result;
685
686         /* Wait for previous non-blocking write to complete, if any. */
687         if (port->writing) {
688                 DEBUG("Waiting for previous write to complete");
689                 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
690                 port->writing = 0;
691                 if (!result)
692                         RETURN_FAIL("Previous write failed to complete");
693                 DEBUG("Previous write completed");
694         }
695
696         /* Set timeout. */
697         port->timeouts.WriteTotalTimeoutConstant = timeout;
698         if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
699                 RETURN_FAIL("SetCommTimeouts() failed");
700
701         /* Start write. */
702         if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) {
703                 if (GetLastError() == ERROR_IO_PENDING) {
704                         DEBUG("Waiting for write to complete");
705                         GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
706                         DEBUG("Write completed, %d/%d bytes written", bytes_written, count);
707                         RETURN_VALUE("%d", bytes_written);
708                 } else {
709                         RETURN_FAIL("WriteFile() failed");
710                 }
711         } else {
712                 DEBUG("Write completed immediately");
713                 RETURN_VALUE("%d", count);
714         }
715 #else
716         size_t bytes_written = 0;
717         unsigned char *ptr = (unsigned char *) buf;
718         struct timeval start, delta, now, end = {0, 0};
719         fd_set fds;
720         int result;
721
722         if (timeout) {
723                 /* Get time at start of operation. */
724                 gettimeofday(&start, NULL);
725                 /* Define duration of timeout. */
726                 delta.tv_sec = timeout / 1000;
727                 delta.tv_usec = (timeout % 1000) * 1000;
728                 /* Calculate time at which we should give up. */
729                 timeradd(&start, &delta, &end);
730         }
731
732         /* Loop until we have written the requested number of bytes. */
733         while (bytes_written < count)
734         {
735                 /* Wait until space is available. */
736                 FD_ZERO(&fds);
737                 FD_SET(port->fd, &fds);
738                 if (timeout) {
739                         gettimeofday(&now, NULL);
740                         if (timercmp(&now, &end, >)) {
741                                 DEBUG("write timed out");
742                                 RETURN_VALUE("%d", bytes_written);
743                         }
744                         timersub(&end, &now, &delta);
745                 }
746                 result = select(port->fd + 1, NULL, &fds, NULL, timeout ? &delta : NULL);
747                 if (result < 0) {
748                         if (errno == EINTR) {
749                                 DEBUG("select() call was interrupted, repeating");
750                                 continue;
751                         } else {
752                                 RETURN_FAIL("select() failed");
753                         }
754                 } else if (result == 0) {
755                         DEBUG("write timed out");
756                         RETURN_VALUE("%d", bytes_written);
757                 }
758
759                 /* Do write. */
760                 result = write(port->fd, ptr, count - bytes_written);
761
762                 if (result < 0) {
763                         if (errno == EAGAIN)
764                                 /* This shouldn't happen because we did a select() first, but handle anyway. */
765                                 continue;
766                         else
767                                 /* This is an actual failure. */
768                                 RETURN_FAIL("write() failed");
769                 }
770
771                 bytes_written += result;
772                 ptr += result;
773         }
774
775         RETURN_VALUE("%d", bytes_written);
776 #endif
777 }
778
779 enum sp_return sp_nonblocking_write(struct sp_port *port, const void *buf, size_t count)
780 {
781         TRACE("%p, %p, %d", port, buf, count);
782
783         CHECK_OPEN_PORT();
784
785         if (!buf)
786                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
787
788         DEBUG("Writing up to %d bytes to port %s", count, port->name);
789
790         if (count == 0)
791                 RETURN_VALUE("0", 0);
792
793 #ifdef _WIN32
794         DWORD written = 0;
795         BYTE *ptr = (BYTE *) buf;
796
797         /* Check whether previous write is complete. */
798         if (port->writing) {
799                 if (HasOverlappedIoCompleted(&port->write_ovl)) {
800                         DEBUG("Previous write completed");
801                         port->writing = 0;
802                 } else {
803                         DEBUG("Previous write not complete");
804                         /* Can't take a new write until the previous one finishes. */
805                         RETURN_VALUE("0", 0);
806                 }
807         }
808
809         /* Set timeout. */
810         port->timeouts.WriteTotalTimeoutConstant = 0;
811         if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
812                 RETURN_FAIL("SetCommTimeouts() failed");
813
814         /* Keep writing data until the OS has to actually start an async IO for it.
815          * At that point we know the buffer is full. */
816         while (written < count)
817         {
818                 /* Copy first byte of user buffer. */
819                 port->pending_byte = *ptr++;
820
821                 /* Start asynchronous write. */
822                 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
823                         if (GetLastError() == ERROR_IO_PENDING) {
824                                 if (HasOverlappedIoCompleted(&port->write_ovl)) {
825                                         DEBUG("Asynchronous write completed immediately");
826                                         port->writing = 0;
827                                         written++;
828                                         continue;
829                                 } else {
830                                         DEBUG("Asynchronous write running");
831                                         port->writing = 1;
832                                         RETURN_VALUE("%d", ++written);
833                                 }
834                         } else {
835                                 /* Actual failure of some kind. */
836                                 RETURN_FAIL("WriteFile() failed");
837                         }
838                 } else {
839                         DEBUG("Single byte written immediately");
840                         written++;
841                 }
842         }
843
844         DEBUG("All bytes written immediately");
845
846         RETURN_VALUE("%d", written);
847 #else
848         /* Returns the number of bytes written, or -1 upon failure. */
849         ssize_t written = write(port->fd, buf, count);
850
851         if (written < 0)
852                 RETURN_FAIL("write() failed");
853         else
854                 RETURN_VALUE("%d", written);
855 #endif
856 }
857
858 enum sp_return sp_blocking_read(struct sp_port *port, void *buf, size_t count, unsigned int timeout)
859 {
860         TRACE("%p, %p, %d, %d", port, buf, count, timeout);
861
862         CHECK_OPEN_PORT();
863
864         if (!buf)
865                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
866
867         if (timeout)
868                 DEBUG("Reading %d bytes from port %s, timeout %d ms", count, port->name, timeout);
869         else
870                 DEBUG("Reading %d bytes from port %s, no timeout", count, port->name);
871
872         if (count == 0)
873                 RETURN_VALUE("0", 0);
874
875 #ifdef _WIN32
876         DWORD bytes_read = 0;
877
878         /* Set timeout. */
879         port->timeouts.ReadIntervalTimeout = 0;
880         port->timeouts.ReadTotalTimeoutConstant = timeout;
881         if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
882                 RETURN_FAIL("SetCommTimeouts() failed");
883
884         /* Start read. */
885         if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) {
886                 if (GetLastError() == ERROR_IO_PENDING) {
887                         DEBUG("Waiting for read to complete");
888                         GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
889                         DEBUG("Read completed, %d/%d bytes read", bytes_read, count);
890                 } else {
891                         RETURN_FAIL("ReadFile() failed");
892                 }
893         } else {
894                 DEBUG("Read completed immediately");
895                 bytes_read = count;
896         }
897
898         /* Start background operation for subsequent events. */
899         if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
900                 if (GetLastError() != ERROR_IO_PENDING)
901                         RETURN_FAIL("WaitCommEvent() failed");
902         }
903
904         RETURN_VALUE("%d", bytes_read);
905
906 #else
907         size_t bytes_read = 0;
908         unsigned char *ptr = (unsigned char *) buf;
909         struct timeval start, delta, now, end = {0, 0};
910         fd_set fds;
911         int result;
912
913         if (timeout) {
914                 /* Get time at start of operation. */
915                 gettimeofday(&start, NULL);
916                 /* Define duration of timeout. */
917                 delta.tv_sec = timeout / 1000;
918                 delta.tv_usec = (timeout % 1000) * 1000;
919                 /* Calculate time at which we should give up. */
920                 timeradd(&start, &delta, &end);
921         }
922
923         /* Loop until we have the requested number of bytes. */
924         while (bytes_read < count)
925         {
926                 /* Wait until data is available. */
927                 FD_ZERO(&fds);
928                 FD_SET(port->fd, &fds);
929                 if (timeout) {
930                         gettimeofday(&now, NULL);
931                         if (timercmp(&now, &end, >))
932                                 /* Timeout has expired. */
933                                 RETURN_VALUE("%d", bytes_read);
934                         timersub(&end, &now, &delta);
935                 }
936                 result = select(port->fd + 1, &fds, NULL, NULL, timeout ? &delta : NULL);
937                 if (result < 0) {
938                         if (errno == EINTR) {
939                                 DEBUG("select() call was interrupted, repeating");
940                                 continue;
941                         } else {
942                                 RETURN_FAIL("select() failed");
943                         }
944                 } else if (result == 0) {
945                         DEBUG("read timed out");
946                         RETURN_VALUE("%d", bytes_read);
947                 }
948
949                 /* Do read. */
950                 result = read(port->fd, ptr, count - bytes_read);
951
952                 if (result < 0) {
953                         if (errno == EAGAIN)
954                                 /* This shouldn't happen because we did a select() first, but handle anyway. */
955                                 continue;
956                         else
957                                 /* This is an actual failure. */
958                                 RETURN_FAIL("read() failed");
959                 }
960
961                 bytes_read += result;
962                 ptr += result;
963         }
964
965         RETURN_VALUE("%d", bytes_read);
966 #endif
967 }
968
969 enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf, size_t count)
970 {
971         TRACE("%p, %p, %d", port, buf, count);
972
973         CHECK_OPEN_PORT();
974
975         if (!buf)
976                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
977
978         DEBUG("Reading up to %d bytes from port %s", count, port->name);
979
980 #ifdef _WIN32
981         DWORD bytes_read;
982
983         /* Set timeout. */
984         port->timeouts.ReadIntervalTimeout = MAXDWORD;
985         port->timeouts.ReadTotalTimeoutConstant = 0;
986         if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
987                 RETURN_FAIL("SetCommTimeouts() failed");
988
989         /* Do read. */
990         if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
991                 RETURN_FAIL("ReadFile() failed");
992
993         /* Get number of bytes read. */
994         if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
995                 RETURN_FAIL("GetOverlappedResult() failed");
996
997         if (bytes_read > 0) {
998                 /* Start background operation for subsequent events. */
999                 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
1000                         if (GetLastError() != ERROR_IO_PENDING)
1001                                 RETURN_FAIL("WaitCommEvent() failed");
1002                 }
1003         }
1004
1005         RETURN_VALUE("%d", bytes_read);
1006 #else
1007         ssize_t bytes_read;
1008
1009         /* Returns the number of bytes read, or -1 upon failure. */
1010         if ((bytes_read = read(port->fd, buf, count)) < 0) {
1011                 if (errno == EAGAIN)
1012                         /* No bytes available. */
1013                         bytes_read = 0;
1014                 else
1015                         /* This is an actual failure. */
1016                         RETURN_FAIL("read() failed");
1017         }
1018         RETURN_VALUE("%d", bytes_read);
1019 #endif
1020 }
1021
1022 enum sp_return sp_input_waiting(struct sp_port *port)
1023 {
1024         TRACE("%p", port);
1025
1026         CHECK_OPEN_PORT();
1027
1028         DEBUG("Checking input bytes waiting on port %s", port->name);
1029
1030 #ifdef _WIN32
1031         DWORD errors;
1032         COMSTAT comstat;
1033
1034         if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1035                 RETURN_FAIL("ClearCommError() failed");
1036         RETURN_VALUE("%d", comstat.cbInQue);
1037 #else
1038         int bytes_waiting;
1039         if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1040                 RETURN_FAIL("TIOCINQ ioctl failed");
1041         RETURN_VALUE("%d", bytes_waiting);
1042 #endif
1043 }
1044
1045 enum sp_return sp_output_waiting(struct sp_port *port)
1046 {
1047         TRACE("%p", port);
1048
1049         CHECK_OPEN_PORT();
1050
1051         DEBUG("Checking output bytes waiting on port %s", port->name);
1052
1053 #ifdef _WIN32
1054         DWORD errors;
1055         COMSTAT comstat;
1056
1057         if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1058                 RETURN_FAIL("ClearCommError() failed");
1059         RETURN_VALUE("%d", comstat.cbOutQue);
1060 #else
1061         int bytes_waiting;
1062         if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1063                 RETURN_FAIL("TIOCOUTQ ioctl failed");
1064         RETURN_VALUE("%d", bytes_waiting);
1065 #endif
1066 }
1067
1068 enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1069 {
1070         struct sp_event_set *result;
1071
1072         TRACE("%p", result_ptr);
1073
1074         if (!result_ptr)
1075                 RETURN_ERROR(SP_ERR_ARG, "Null result");
1076
1077         *result_ptr = NULL;
1078
1079         if (!(result = malloc(sizeof(struct sp_event_set))))
1080                 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1081
1082         memset(result, 0, sizeof(struct sp_event_set));
1083
1084         *result_ptr = result;
1085
1086         RETURN_OK();
1087 }
1088
1089 static enum sp_return add_handle(struct sp_event_set *event_set,
1090                 event_handle handle, enum sp_event mask)
1091 {
1092         void *new_handles;
1093         enum sp_event *new_masks;
1094
1095         TRACE("%p, %d, %d", event_set, handle, mask);
1096
1097         if (!(new_handles = realloc(event_set->handles,
1098                         sizeof(event_handle) * (event_set->count + 1))))
1099                 RETURN_ERROR(SP_ERR_MEM, "handle array realloc() failed");
1100
1101         if (!(new_masks = realloc(event_set->masks,
1102                         sizeof(enum sp_event) * (event_set->count + 1))))
1103                 RETURN_ERROR(SP_ERR_MEM, "mask array realloc() failed");
1104
1105         event_set->handles = new_handles;
1106         event_set->masks = new_masks;
1107
1108         ((event_handle *) event_set->handles)[event_set->count] = handle;
1109         event_set->masks[event_set->count] = mask;
1110
1111         event_set->count++;
1112
1113         RETURN_OK();
1114 }
1115
1116 enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1117         const struct sp_port *port, enum sp_event mask)
1118 {
1119         TRACE("%p, %p, %d", event_set, port, mask);
1120
1121         if (!event_set)
1122                 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1123
1124         if (!port)
1125                 RETURN_ERROR(SP_ERR_ARG, "Null port");
1126
1127         if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1128                 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1129
1130         if (!mask)
1131                 RETURN_OK();
1132
1133 #ifdef _WIN32
1134         enum sp_event handle_mask;
1135         if ((handle_mask = mask & SP_EVENT_TX_READY))
1136                 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1137         if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1138                 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1139 #else
1140         TRY(add_handle(event_set, port->fd, mask));
1141 #endif
1142
1143         RETURN_OK();
1144 }
1145
1146 void sp_free_event_set(struct sp_event_set *event_set)
1147 {
1148         TRACE("%p", event_set);
1149
1150         if (!event_set) {
1151                 DEBUG("Null event set");
1152                 RETURN();
1153         }
1154
1155         DEBUG("Freeing event set");
1156
1157         if (event_set->handles)
1158                 free(event_set->handles);
1159         if (event_set->masks)
1160                 free(event_set->masks);
1161
1162         free(event_set);
1163
1164         RETURN();
1165 }
1166
1167 enum sp_return sp_wait(struct sp_event_set *event_set, unsigned int timeout)
1168 {
1169         TRACE("%p, %d", event_set, timeout);
1170
1171         if (!event_set)
1172                 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1173
1174 #ifdef _WIN32
1175         if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1176                         timeout ? timeout : INFINITE) == WAIT_FAILED)
1177                 RETURN_FAIL("WaitForMultipleObjects() failed");
1178
1179         RETURN_OK();
1180 #else
1181         struct timeval start, delta, now, end = {0, 0};
1182         int result, timeout_remaining;
1183         struct pollfd *pollfds;
1184         unsigned int i;
1185
1186         if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1187                 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1188
1189         for (i = 0; i < event_set->count; i++) {
1190                 pollfds[i].fd = ((int *) event_set->handles)[i];
1191                 pollfds[i].events = 0;
1192                 pollfds[i].revents = 0;
1193                 if (event_set->masks[i] & SP_EVENT_RX_READY)
1194                         pollfds[i].events |= POLLIN;
1195                 if (event_set->masks[i] & SP_EVENT_TX_READY)
1196                         pollfds[i].events |= POLLOUT;
1197                 if (event_set->masks[i] & SP_EVENT_ERROR)
1198                         pollfds[i].events |= POLLERR;
1199         }
1200
1201         if (timeout) {
1202                 /* Get time at start of operation. */
1203                 gettimeofday(&start, NULL);
1204                 /* Define duration of timeout. */
1205                 delta.tv_sec = timeout / 1000;
1206                 delta.tv_usec = (timeout % 1000) * 1000;
1207                 /* Calculate time at which we should give up. */
1208                 timeradd(&start, &delta, &end);
1209         }
1210
1211         /* Loop until an event occurs. */
1212         while (1)
1213         {
1214                 if (timeout) {
1215                         gettimeofday(&now, NULL);
1216                         if (timercmp(&now, &end, >)) {
1217                                 DEBUG("wait timed out");
1218                                 break;
1219                         }
1220                         timersub(&end, &now, &delta);
1221                         timeout_remaining = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1222                 }
1223
1224                 result = poll(pollfds, event_set->count, timeout ? timeout_remaining : -1);
1225
1226                 if (result < 0) {
1227                         if (errno == EINTR) {
1228                                 DEBUG("poll() call was interrupted, repeating");
1229                                 continue;
1230                         } else {
1231                                 free(pollfds);
1232                                 RETURN_FAIL("poll() failed");
1233                         }
1234                 } else if (result == 0) {
1235                         DEBUG("poll() timed out");
1236                         break;
1237                 } else {
1238                         DEBUG("poll() completed");
1239                         break;
1240                 }
1241         }
1242
1243         free(pollfds);
1244         RETURN_OK();
1245 #endif
1246 }
1247
1248 #ifdef USE_TERMIOS_SPEED
1249 static enum sp_return get_baudrate(int fd, int *baudrate)
1250 {
1251         void *data;
1252
1253         TRACE("%d, %p", fd, baudrate);
1254
1255         DEBUG("Getting baud rate");
1256
1257         if (!(data = malloc(get_termios_size())))
1258                 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1259
1260         if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1261                 free(data);
1262                 RETURN_FAIL("getting termios failed");
1263         }
1264
1265         *baudrate = get_termios_speed(data);
1266
1267         free(data);
1268
1269         RETURN_OK();
1270 }
1271
1272 static enum sp_return set_baudrate(int fd, int baudrate)
1273 {
1274         void *data;
1275
1276         TRACE("%d, %d", fd, baudrate);
1277
1278         DEBUG("Getting baud rate");
1279
1280         if (!(data = malloc(get_termios_size())))
1281                 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1282
1283         if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1284                 free(data);
1285                 RETURN_FAIL("getting termios failed");
1286         }
1287
1288         DEBUG("Setting baud rate");
1289
1290         set_termios_speed(data, baudrate);
1291
1292         if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1293                 free(data);
1294                 RETURN_FAIL("setting termios failed");
1295         }
1296
1297         free(data);
1298
1299         RETURN_OK();
1300 }
1301 #endif /* USE_TERMIOS_SPEED */
1302
1303 #ifdef USE_TERMIOX
1304 static enum sp_return get_flow(int fd, struct port_data *data)
1305 {
1306         void *termx;
1307
1308         TRACE("%d, %p", fd, data);
1309
1310         DEBUG("Getting advanced flow control");
1311
1312         if (!(termx = malloc(get_termiox_size())))
1313                 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1314
1315         if (ioctl(fd, TCGETX, termx) < 0) {
1316                 free(termx);
1317                 RETURN_FAIL("getting termiox failed");
1318         }
1319
1320         get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1321                         &data->dtr_flow, &data->dsr_flow);
1322
1323         free(termx);
1324
1325         RETURN_OK();
1326 }
1327
1328 static enum sp_return set_flow(int fd, struct port_data *data)
1329 {
1330         void *termx;
1331
1332         TRACE("%d, %p", fd, data);
1333
1334         DEBUG("Getting advanced flow control");
1335
1336         if (!(termx = malloc(get_termiox_size())))
1337                 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1338
1339         if (ioctl(fd, TCGETX, termx) < 0) {
1340                 free(termx);
1341                 RETURN_FAIL("getting termiox failed");
1342         }
1343
1344         DEBUG("Setting advanced flow control");
1345
1346         set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1347                         data->dtr_flow, data->dsr_flow);
1348
1349         if (ioctl(fd, TCSETX, termx) < 0) {
1350                 free(termx);
1351                 RETURN_FAIL("setting termiox failed");
1352         }
1353
1354         free(termx);
1355
1356         RETURN_OK();
1357 }
1358 #endif /* USE_TERMIOX */
1359
1360 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1361         struct sp_port_config *config)
1362 {
1363         unsigned int i;
1364
1365         TRACE("%p, %p, %p", port, data, config);
1366
1367         DEBUG("Getting configuration for port %s", port->name);
1368
1369 #ifdef _WIN32
1370         if (!GetCommState(port->hdl, &data->dcb))
1371                 RETURN_FAIL("GetCommState() failed");
1372
1373         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1374                 if (data->dcb.BaudRate == std_baudrates[i].index) {
1375                         config->baudrate = std_baudrates[i].value;
1376                         break;
1377                 }
1378         }
1379
1380         if (i == NUM_STD_BAUDRATES)
1381                 /* BaudRate field can be either an index or a custom baud rate. */
1382                 config->baudrate = data->dcb.BaudRate;
1383
1384         config->bits = data->dcb.ByteSize;
1385
1386         if (data->dcb.fParity)
1387                 switch (data->dcb.Parity) {
1388                 case NOPARITY:
1389                         config->parity = SP_PARITY_NONE;
1390                         break;
1391                 case ODDPARITY:
1392                         config->parity = SP_PARITY_ODD;
1393                         break;
1394                 case EVENPARITY:
1395                         config->parity = SP_PARITY_EVEN;
1396                         break;
1397                 case MARKPARITY:
1398                         config->parity = SP_PARITY_MARK;
1399                         break;
1400                 case SPACEPARITY:
1401                         config->parity = SP_PARITY_SPACE;
1402                         break;
1403                 default:
1404                         config->parity = -1;
1405                 }
1406         else
1407                 config->parity = SP_PARITY_NONE;
1408
1409         switch (data->dcb.StopBits) {
1410         case ONESTOPBIT:
1411                 config->stopbits = 1;
1412                 break;
1413         case TWOSTOPBITS:
1414                 config->stopbits = 2;
1415                 break;
1416         default:
1417                 config->stopbits = -1;
1418         }
1419
1420         switch (data->dcb.fRtsControl) {
1421         case RTS_CONTROL_DISABLE:
1422                 config->rts = SP_RTS_OFF;
1423                 break;
1424         case RTS_CONTROL_ENABLE:
1425                 config->rts = SP_RTS_ON;
1426                 break;
1427         case RTS_CONTROL_HANDSHAKE:
1428                 config->rts = SP_RTS_FLOW_CONTROL;
1429                 break;
1430         default:
1431                 config->rts = -1;
1432         }
1433
1434         config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1435
1436         switch (data->dcb.fDtrControl) {
1437         case DTR_CONTROL_DISABLE:
1438                 config->dtr = SP_DTR_OFF;
1439                 break;
1440         case DTR_CONTROL_ENABLE:
1441                 config->dtr = SP_DTR_ON;
1442                 break;
1443         case DTR_CONTROL_HANDSHAKE:
1444                 config->dtr = SP_DTR_FLOW_CONTROL;
1445                 break;
1446         default:
1447                 config->dtr = -1;
1448         }
1449
1450         config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1451
1452         if (data->dcb.fInX) {
1453                 if (data->dcb.fOutX)
1454                         config->xon_xoff = SP_XONXOFF_INOUT;
1455                 else
1456                         config->xon_xoff = SP_XONXOFF_IN;
1457         } else {
1458                 if (data->dcb.fOutX)
1459                         config->xon_xoff = SP_XONXOFF_OUT;
1460                 else
1461                         config->xon_xoff = SP_XONXOFF_DISABLED;
1462         }
1463
1464 #else // !_WIN32
1465
1466         if (tcgetattr(port->fd, &data->term) < 0)
1467                 RETURN_FAIL("tcgetattr() failed");
1468
1469         if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1470                 RETURN_FAIL("TIOCMGET ioctl failed");
1471
1472 #ifdef USE_TERMIOX
1473         int ret = get_flow(port->fd, data);
1474
1475         if (ret == SP_ERR_FAIL && errno == EINVAL)
1476                 data->termiox_supported = 0;
1477         else if (ret < 0)
1478                 RETURN_CODEVAL(ret);
1479         else
1480                 data->termiox_supported = 1;
1481 #else
1482         data->termiox_supported = 0;
1483 #endif
1484
1485         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1486                 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1487                         config->baudrate = std_baudrates[i].value;
1488                         break;
1489                 }
1490         }
1491
1492         if (i == NUM_STD_BAUDRATES) {
1493 #ifdef __APPLE__
1494                 config->baudrate = (int)data->term.c_ispeed;
1495 #elif defined(USE_TERMIOS_SPEED)
1496                 TRY(get_baudrate(port->fd, &config->baudrate));
1497 #else
1498                 config->baudrate = -1;
1499 #endif
1500         }
1501
1502         switch (data->term.c_cflag & CSIZE) {
1503         case CS8:
1504                 config->bits = 8;
1505                 break;
1506         case CS7:
1507                 config->bits = 7;
1508                 break;
1509         case CS6:
1510                 config->bits = 6;
1511                 break;
1512         case CS5:
1513                 config->bits = 5;
1514                 break;
1515         default:
1516                 config->bits = -1;
1517         }
1518
1519         if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1520                 config->parity = SP_PARITY_NONE;
1521         else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1522                 config->parity = -1;
1523 #ifdef CMSPAR
1524         else if (data->term.c_cflag & CMSPAR)
1525                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1526 #endif
1527         else
1528                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1529
1530         config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1531
1532         if (data->term.c_cflag & CRTSCTS) {
1533                 config->rts = SP_RTS_FLOW_CONTROL;
1534                 config->cts = SP_CTS_FLOW_CONTROL;
1535         } else {
1536                 if (data->termiox_supported && data->rts_flow)
1537                         config->rts = SP_RTS_FLOW_CONTROL;
1538                 else
1539                         config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1540
1541                 config->cts = (data->termiox_supported && data->cts_flow) ?
1542                         SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1543         }
1544
1545         if (data->termiox_supported && data->dtr_flow)
1546                 config->dtr = SP_DTR_FLOW_CONTROL;
1547         else
1548                 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1549
1550         config->dsr = (data->termiox_supported && data->dsr_flow) ?
1551                 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1552
1553         if (data->term.c_iflag & IXOFF) {
1554                 if (data->term.c_iflag & IXON)
1555                         config->xon_xoff = SP_XONXOFF_INOUT;
1556                 else
1557                         config->xon_xoff = SP_XONXOFF_IN;
1558         } else {
1559                 if (data->term.c_iflag & IXON)
1560                         config->xon_xoff = SP_XONXOFF_OUT;
1561                 else
1562                         config->xon_xoff = SP_XONXOFF_DISABLED;
1563         }
1564 #endif
1565
1566         RETURN_OK();
1567 }
1568
1569 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1570         const struct sp_port_config *config)
1571 {
1572         unsigned int i;
1573 #ifdef __APPLE__
1574         BAUD_TYPE baud_nonstd;
1575
1576         baud_nonstd = B0;
1577 #endif
1578 #ifdef USE_TERMIOS_SPEED
1579         int baud_nonstd = 0;
1580 #endif
1581
1582         TRACE("%p, %p, %p", port, data, config);
1583
1584         DEBUG("Setting configuration for port %s", port->name);
1585
1586 #ifdef _WIN32
1587         if (config->baudrate >= 0) {
1588                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1589                         if (config->baudrate == std_baudrates[i].value) {
1590                                 data->dcb.BaudRate = std_baudrates[i].index;
1591                                 break;
1592                         }
1593                 }
1594
1595                 if (i == NUM_STD_BAUDRATES)
1596                         data->dcb.BaudRate = config->baudrate;
1597         }
1598
1599         if (config->bits >= 0)
1600                 data->dcb.ByteSize = config->bits;
1601
1602         if (config->parity >= 0) {
1603                 switch (config->parity) {
1604                 case SP_PARITY_NONE:
1605                         data->dcb.Parity = NOPARITY;
1606                         break;
1607                 case SP_PARITY_ODD:
1608                         data->dcb.Parity = ODDPARITY;
1609                         break;
1610                 case SP_PARITY_EVEN:
1611                         data->dcb.Parity = EVENPARITY;
1612                         break;
1613                 case SP_PARITY_MARK:
1614                         data->dcb.Parity = MARKPARITY;
1615                         break;
1616                 case SP_PARITY_SPACE:
1617                         data->dcb.Parity = SPACEPARITY;
1618                         break;
1619                 default:
1620                         RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1621                 }
1622         }
1623
1624         if (config->stopbits >= 0) {
1625                 switch (config->stopbits) {
1626                 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1627                 case 1:
1628                         data->dcb.StopBits = ONESTOPBIT;
1629                         break;
1630                 case 2:
1631                         data->dcb.StopBits = TWOSTOPBITS;
1632                         break;
1633                 default:
1634                         RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1635                 }
1636         }
1637
1638         if (config->rts >= 0) {
1639                 switch (config->rts) {
1640                 case SP_RTS_OFF:
1641                         data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1642                         break;
1643                 case SP_RTS_ON:
1644                         data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1645                         break;
1646                 case SP_RTS_FLOW_CONTROL:
1647                         data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1648                         break;
1649                 default:
1650                         RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1651                 }
1652         }
1653
1654         if (config->cts >= 0) {
1655                 switch (config->cts) {
1656                 case SP_CTS_IGNORE:
1657                         data->dcb.fOutxCtsFlow = FALSE;
1658                         break;
1659                 case SP_CTS_FLOW_CONTROL:
1660                         data->dcb.fOutxCtsFlow = TRUE;
1661                         break;
1662                 default:
1663                         RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1664                 }
1665         }
1666
1667         if (config->dtr >= 0) {
1668                 switch (config->dtr) {
1669                 case SP_DTR_OFF:
1670                         data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1671                         break;
1672                 case SP_DTR_ON:
1673                         data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1674                         break;
1675                 case SP_DTR_FLOW_CONTROL:
1676                         data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1677                         break;
1678                 default:
1679                         RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1680                 }
1681         }
1682
1683         if (config->dsr >= 0) {
1684                 switch (config->dsr) {
1685                 case SP_DSR_IGNORE:
1686                         data->dcb.fOutxDsrFlow = FALSE;
1687                         break;
1688                 case SP_DSR_FLOW_CONTROL:
1689                         data->dcb.fOutxDsrFlow = TRUE;
1690                         break;
1691                 default:
1692                         RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1693                 }
1694         }
1695
1696         if (config->xon_xoff >= 0) {
1697                 switch (config->xon_xoff) {
1698                 case SP_XONXOFF_DISABLED:
1699                         data->dcb.fInX = FALSE;
1700                         data->dcb.fOutX = FALSE;
1701                         break;
1702                 case SP_XONXOFF_IN:
1703                         data->dcb.fInX = TRUE;
1704                         data->dcb.fOutX = FALSE;
1705                         break;
1706                 case SP_XONXOFF_OUT:
1707                         data->dcb.fInX = FALSE;
1708                         data->dcb.fOutX = TRUE;
1709                         break;
1710                 case SP_XONXOFF_INOUT:
1711                         data->dcb.fInX = TRUE;
1712                         data->dcb.fOutX = TRUE;
1713                         break;
1714                 default:
1715                         RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1716                 }
1717         }
1718
1719         if (!SetCommState(port->hdl, &data->dcb))
1720                 RETURN_FAIL("SetCommState() failed");
1721
1722 #else /* !_WIN32 */
1723
1724         int controlbits;
1725
1726         if (config->baudrate >= 0) {
1727                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1728                         if (config->baudrate == std_baudrates[i].value) {
1729                                 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1730                                         RETURN_FAIL("cfsetospeed() failed");
1731
1732                                 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1733                                         RETURN_FAIL("cfsetispeed() failed");
1734                                 break;
1735                         }
1736                 }
1737
1738                 /* Non-standard baud rate */
1739                 if (i == NUM_STD_BAUDRATES) {
1740 #ifdef __APPLE__
1741                         /* Set "dummy" baud rate. */
1742                         if (cfsetspeed(&data->term, B9600) < 0)
1743                                 RETURN_FAIL("cfsetspeed() failed");
1744                         baud_nonstd = config->baudrate;
1745 #elif defined(USE_TERMIOS_SPEED)
1746                         baud_nonstd = 1;
1747 #else
1748                         RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1749 #endif
1750                 }
1751         }
1752
1753         if (config->bits >= 0) {
1754                 data->term.c_cflag &= ~CSIZE;
1755                 switch (config->bits) {
1756                 case 8:
1757                         data->term.c_cflag |= CS8;
1758                         break;
1759                 case 7:
1760                         data->term.c_cflag |= CS7;
1761                         break;
1762                 case 6:
1763                         data->term.c_cflag |= CS6;
1764                         break;
1765                 case 5:
1766                         data->term.c_cflag |= CS5;
1767                         break;
1768                 default:
1769                         RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1770                 }
1771         }
1772
1773         if (config->parity >= 0) {
1774                 data->term.c_iflag &= ~IGNPAR;
1775                 data->term.c_cflag &= ~(PARENB | PARODD);
1776 #ifdef CMSPAR
1777                 data->term.c_cflag &= ~CMSPAR;
1778 #endif
1779                 switch (config->parity) {
1780                 case SP_PARITY_NONE:
1781                         data->term.c_iflag |= IGNPAR;
1782                         break;
1783                 case SP_PARITY_EVEN:
1784                         data->term.c_cflag |= PARENB;
1785                         break;
1786                 case SP_PARITY_ODD:
1787                         data->term.c_cflag |= PARENB | PARODD;
1788                         break;
1789 #ifdef CMSPAR
1790                 case SP_PARITY_MARK:
1791                         data->term.c_cflag |= PARENB | PARODD;
1792                         data->term.c_cflag |= CMSPAR;
1793                         break;
1794                 case SP_PARITY_SPACE:
1795                         data->term.c_cflag |= PARENB;
1796                         data->term.c_cflag |= CMSPAR;
1797                         break;
1798 #else
1799                 case SP_PARITY_MARK:
1800                 case SP_PARITY_SPACE:
1801                         RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1802 #endif
1803                 default:
1804                         RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1805                 }
1806         }
1807
1808         if (config->stopbits >= 0) {
1809                 data->term.c_cflag &= ~CSTOPB;
1810                 switch (config->stopbits) {
1811                 case 1:
1812                         data->term.c_cflag &= ~CSTOPB;
1813                         break;
1814                 case 2:
1815                         data->term.c_cflag |= CSTOPB;
1816                         break;
1817                 default:
1818                         RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1819                 }
1820         }
1821
1822         if (config->rts >= 0 || config->cts >= 0) {
1823                 if (data->termiox_supported) {
1824                         data->rts_flow = data->cts_flow = 0;
1825                         switch (config->rts) {
1826                         case SP_RTS_OFF:
1827                         case SP_RTS_ON:
1828                                 controlbits = TIOCM_RTS;
1829                                 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1830                                         RETURN_FAIL("Setting RTS signal level failed");
1831                                 break;
1832                         case SP_RTS_FLOW_CONTROL:
1833                                 data->rts_flow = 1;
1834                                 break;
1835                         default:
1836                                 break;
1837                         }
1838                         if (config->cts == SP_CTS_FLOW_CONTROL)
1839                                 data->cts_flow = 1;
1840
1841                         if (data->rts_flow && data->cts_flow)
1842                                 data->term.c_iflag |= CRTSCTS;
1843                         else
1844                                 data->term.c_iflag &= ~CRTSCTS;
1845                 } else {
1846                         /* Asymmetric use of RTS/CTS not supported. */
1847                         if (data->term.c_iflag & CRTSCTS) {
1848                                 /* Flow control can only be disabled for both RTS & CTS together. */
1849                                 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1850                                         if (config->cts != SP_CTS_IGNORE)
1851                                                 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1852                                 }
1853                                 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1854                                         if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1855                                                 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1856                                 }
1857                         } else {
1858                                 /* Flow control can only be enabled for both RTS & CTS together. */
1859                                 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1860                                         ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1861                                         RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1862                         }
1863
1864                         if (config->rts >= 0) {
1865                                 if (config->rts == SP_RTS_FLOW_CONTROL) {
1866                                         data->term.c_iflag |= CRTSCTS;
1867                                 } else {
1868                                         controlbits = TIOCM_RTS;
1869                                         if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1870                                                         &controlbits) < 0)
1871                                                 RETURN_FAIL("Setting RTS signal level failed");
1872                                 }
1873                         }
1874                 }
1875         }
1876
1877         if (config->dtr >= 0 || config->dsr >= 0) {
1878                 if (data->termiox_supported) {
1879                         data->dtr_flow = data->dsr_flow = 0;
1880                         switch (config->dtr) {
1881                         case SP_DTR_OFF:
1882                         case SP_DTR_ON:
1883                                 controlbits = TIOCM_DTR;
1884                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1885                                         RETURN_FAIL("Setting DTR signal level failed");
1886                                 break;
1887                         case SP_DTR_FLOW_CONTROL:
1888                                 data->dtr_flow = 1;
1889                                 break;
1890                         default:
1891                                 break;
1892                         }
1893                         if (config->dsr == SP_DSR_FLOW_CONTROL)
1894                                 data->dsr_flow = 1;
1895                 } else {
1896                         /* DTR/DSR flow control not supported. */
1897                         if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1898                                 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1899
1900                         if (config->dtr >= 0) {
1901                                 controlbits = TIOCM_DTR;
1902                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1903                                                 &controlbits) < 0)
1904                                         RETURN_FAIL("Setting DTR signal level failed");
1905                         }
1906                 }
1907         }
1908
1909         if (config->xon_xoff >= 0) {
1910                 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1911                 switch (config->xon_xoff) {
1912                 case SP_XONXOFF_DISABLED:
1913                         break;
1914                 case SP_XONXOFF_IN:
1915                         data->term.c_iflag |= IXOFF;
1916                         break;
1917                 case SP_XONXOFF_OUT:
1918                         data->term.c_iflag |= IXON | IXANY;
1919                         break;
1920                 case SP_XONXOFF_INOUT:
1921                         data->term.c_iflag |= IXON | IXOFF | IXANY;
1922                         break;
1923                 default:
1924                         RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1925                 }
1926         }
1927
1928         if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
1929                 RETURN_FAIL("tcsetattr() failed");
1930
1931 #ifdef __APPLE__
1932         if (baud_nonstd != B0) {
1933                 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1934                         RETURN_FAIL("IOSSIOSPEED ioctl failed");
1935                 /* Set baud rates in data->term to correct, but incompatible
1936                  * with tcsetattr() value, same as delivered by tcgetattr(). */
1937                 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1938                         RETURN_FAIL("cfsetspeed() failed");
1939         }
1940 #elif defined(__linux__)
1941 #ifdef USE_TERMIOS_SPEED
1942         if (baud_nonstd)
1943                 TRY(set_baudrate(port->fd, config->baudrate));
1944 #endif
1945 #ifdef USE_TERMIOX
1946         if (data->termiox_supported)
1947                 TRY(set_flow(port->fd, data));
1948 #endif
1949 #endif
1950
1951 #endif /* !_WIN32 */
1952
1953         RETURN_OK();
1954 }
1955
1956 enum sp_return sp_new_config(struct sp_port_config **config_ptr)
1957 {
1958         struct sp_port_config *config;
1959
1960         TRACE("%p", config_ptr);
1961
1962         if (!config_ptr)
1963                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1964
1965         *config_ptr = NULL;
1966
1967         if (!(config = malloc(sizeof(struct sp_port_config))))
1968                 RETURN_ERROR(SP_ERR_MEM, "config malloc failed");
1969
1970         config->baudrate = -1;
1971         config->bits = -1;
1972         config->parity = -1;
1973         config->stopbits = -1;
1974         config->rts = -1;
1975         config->cts = -1;
1976         config->dtr = -1;
1977         config->dsr = -1;
1978
1979         *config_ptr = config;
1980
1981         RETURN_OK();
1982 }
1983
1984 void sp_free_config(struct sp_port_config *config)
1985 {
1986         TRACE("%p", config);
1987
1988         if (!config)
1989                 DEBUG("Null config");
1990         else
1991                 free(config);
1992
1993         RETURN();
1994 }
1995
1996 enum sp_return sp_get_config(struct sp_port *port, struct sp_port_config *config)
1997 {
1998         struct port_data data;
1999
2000         TRACE("%p, %p", port, config);
2001
2002         CHECK_OPEN_PORT();
2003
2004         if (!config)
2005                 RETURN_ERROR(SP_ERR_ARG, "Null config");
2006
2007         TRY(get_config(port, &data, config));
2008
2009         RETURN_OK();
2010 }
2011
2012 enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
2013 {
2014         struct port_data data;
2015         struct sp_port_config prev_config;
2016
2017         TRACE("%p, %p", port, config);
2018
2019         CHECK_OPEN_PORT();
2020
2021         if (!config)
2022                 RETURN_ERROR(SP_ERR_ARG, "Null config");
2023
2024         TRY(get_config(port, &data, &prev_config));
2025         TRY(set_config(port, &data, config));
2026
2027         RETURN_OK();
2028 }
2029
2030 #define CREATE_ACCESSORS(x, type) \
2031 enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2032         struct port_data data; \
2033         struct sp_port_config config; \
2034         TRACE("%p, %d", port, x); \
2035         CHECK_OPEN_PORT(); \
2036         TRY(get_config(port, &data, &config)); \
2037         config.x = x; \
2038         TRY(set_config(port, &data, &config)); \
2039         RETURN_OK(); \
2040 } \
2041 enum sp_return sp_get_config_##x(const struct sp_port_config *config, type *x) { \
2042         TRACE("%p, %p", config, x); \
2043         if (!config) \
2044                 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2045         *x = config->x; \
2046         RETURN_OK(); \
2047 } \
2048 enum sp_return sp_set_config_##x(struct sp_port_config *config, type x) { \
2049         TRACE("%p, %d", config, x); \
2050         if (!config) \
2051                 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2052         config->x = x; \
2053         RETURN_OK(); \
2054 }
2055
2056 CREATE_ACCESSORS(baudrate, int)
2057 CREATE_ACCESSORS(bits, int)
2058 CREATE_ACCESSORS(parity, enum sp_parity)
2059 CREATE_ACCESSORS(stopbits, int)
2060 CREATE_ACCESSORS(rts, enum sp_rts)
2061 CREATE_ACCESSORS(cts, enum sp_cts)
2062 CREATE_ACCESSORS(dtr, enum sp_dtr)
2063 CREATE_ACCESSORS(dsr, enum sp_dsr)
2064 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2065
2066 enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config, enum sp_flowcontrol flowcontrol)
2067 {
2068         if (!config)
2069                 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2070
2071         if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2072                 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2073
2074         if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2075                 config->xon_xoff = SP_XONXOFF_INOUT;
2076         else
2077                 config->xon_xoff = SP_XONXOFF_DISABLED;
2078
2079         if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2080                 config->rts = SP_RTS_FLOW_CONTROL;
2081                 config->cts = SP_CTS_FLOW_CONTROL;
2082         } else {
2083                 if (config->rts == SP_RTS_FLOW_CONTROL)
2084                         config->rts = SP_RTS_ON;
2085                 config->cts = SP_CTS_IGNORE;
2086         }
2087
2088         if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2089                 config->dtr = SP_DTR_FLOW_CONTROL;
2090                 config->dsr = SP_DSR_FLOW_CONTROL;
2091         } else {
2092                 if (config->dtr == SP_DTR_FLOW_CONTROL)
2093                         config->dtr = SP_DTR_ON;
2094                 config->dsr = SP_DSR_IGNORE;
2095         }
2096
2097         RETURN_OK();
2098 }
2099
2100 enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
2101 {
2102         struct port_data data;
2103         struct sp_port_config config;
2104
2105         TRACE("%p, %d", port, flowcontrol);
2106
2107         CHECK_OPEN_PORT();
2108
2109         TRY(get_config(port, &data, &config));
2110
2111         TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2112
2113         TRY(set_config(port, &data, &config));
2114
2115         RETURN_OK();
2116 }
2117
2118 enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
2119 {
2120         TRACE("%p, %p", port, signals);
2121
2122         CHECK_OPEN_PORT();
2123
2124         if (!signals)
2125                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2126
2127         DEBUG("Getting control signals for port %s", port->name);
2128
2129         *signals = 0;
2130 #ifdef _WIN32
2131         DWORD bits;
2132         if (GetCommModemStatus(port->hdl, &bits) == 0)
2133                 RETURN_FAIL("GetCommModemStatus() failed");
2134         if (bits & MS_CTS_ON)
2135                 *signals |= SP_SIG_CTS;
2136         if (bits & MS_DSR_ON)
2137                 *signals |= SP_SIG_DSR;
2138         if (bits & MS_RLSD_ON)
2139                 *signals |= SP_SIG_DCD;
2140         if (bits & MS_RING_ON)
2141                 *signals |= SP_SIG_RI;
2142 #else
2143         int bits;
2144         if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2145                 RETURN_FAIL("TIOCMGET ioctl failed");
2146         if (bits & TIOCM_CTS)
2147                 *signals |= SP_SIG_CTS;
2148         if (bits & TIOCM_DSR)
2149                 *signals |= SP_SIG_DSR;
2150         if (bits & TIOCM_CAR)
2151                 *signals |= SP_SIG_DCD;
2152         if (bits & TIOCM_RNG)
2153                 *signals |= SP_SIG_RI;
2154 #endif
2155         RETURN_OK();
2156 }
2157
2158 enum sp_return sp_start_break(struct sp_port *port)
2159 {
2160         TRACE("%p", port);
2161
2162         CHECK_OPEN_PORT();
2163 #ifdef _WIN32
2164         if (SetCommBreak(port->hdl) == 0)
2165                 RETURN_FAIL("SetCommBreak() failed");
2166 #else
2167         if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2168                 RETURN_FAIL("TIOCSBRK ioctl failed");
2169 #endif
2170
2171         RETURN_OK();
2172 }
2173
2174 enum sp_return sp_end_break(struct sp_port *port)
2175 {
2176         TRACE("%p", port);
2177
2178         CHECK_OPEN_PORT();
2179 #ifdef _WIN32
2180         if (ClearCommBreak(port->hdl) == 0)
2181                 RETURN_FAIL("ClearCommBreak() failed");
2182 #else
2183         if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2184                 RETURN_FAIL("TIOCCBRK ioctl failed");
2185 #endif
2186
2187         RETURN_OK();
2188 }
2189
2190 int sp_last_error_code(void)
2191 {
2192         TRACE("");
2193 #ifdef _WIN32
2194         RETURN_VALUE("%d", GetLastError());
2195 #else
2196         RETURN_VALUE("%d", errno);
2197 #endif
2198 }
2199
2200 char *sp_last_error_message(void)
2201 {
2202         TRACE("");
2203
2204 #ifdef _WIN32
2205         LPVOID message;
2206         DWORD error = GetLastError();
2207
2208         FormatMessage(
2209                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2210                 FORMAT_MESSAGE_FROM_SYSTEM |
2211                 FORMAT_MESSAGE_IGNORE_INSERTS,
2212                 NULL,
2213                 error,
2214                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2215                 (LPTSTR) &message,
2216                 0, NULL );
2217
2218         RETURN_VALUE("%s", message);
2219 #else
2220         RETURN_VALUE("%s", strerror(errno));
2221 #endif
2222 }
2223
2224 void sp_free_error_message(char *message)
2225 {
2226         TRACE("%s", message);
2227
2228 #ifdef _WIN32
2229         LocalFree(message);
2230 #else
2231         (void)message;
2232 #endif
2233
2234         RETURN();
2235 }
2236
2237 void sp_set_debug_handler(void (*handler)(const char *format, ...))
2238 {
2239         TRACE("%p", handler);
2240
2241         sp_debug_handler = handler;
2242
2243         RETURN();
2244 }
2245
2246 void sp_default_debug_handler(const char *format, ...)
2247 {
2248         va_list args;
2249         va_start(args, format);
2250         if (getenv("LIBSERIALPORT_DEBUG")) {
2251                 fputs("sp: ", stderr);
2252                 vfprintf(stderr, format, args);
2253         }
2254         va_end(args);
2255 }
2256
2257 int sp_get_major_package_version(void)
2258 {
2259         return SP_PACKAGE_VERSION_MAJOR;
2260 }
2261
2262 int sp_get_minor_package_version(void)
2263 {
2264         return SP_PACKAGE_VERSION_MINOR;
2265 }
2266
2267 int sp_get_micro_package_version(void)
2268 {
2269         return SP_PACKAGE_VERSION_MICRO;
2270 }
2271
2272 const char *sp_get_package_version_string(void)
2273 {
2274         return SP_PACKAGE_VERSION_STRING;
2275 }
2276
2277 int sp_get_current_lib_version(void)
2278 {
2279         return SP_LIB_VERSION_CURRENT;
2280 }
2281
2282 int sp_get_revision_lib_version(void)
2283 {
2284         return SP_LIB_VERSION_REVISION;
2285 }
2286
2287 int sp_get_age_lib_version(void)
2288 {
2289         return SP_LIB_VERSION_AGE;
2290 }
2291
2292 const char *sp_get_lib_version_string(void)
2293 {
2294         return SP_LIB_VERSION_STRING;
2295 }
2296
2297 /** @} */