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