doc: Provided channel is binary, not necessarily 8-bit.
[libserialport/gsi.git] / serialport.c
blob7af818e2d2574ca022b5a0cce57b55da8ffcabaf
1 /*
2 * This file is part of the libserialport project.
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>
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.
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.
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/>.
24 #include "libserialport.h"
25 #include "libserialport_internal.h"
27 static const struct std_baudrate std_baudrates[] = {
28 #ifdef _WIN32
30 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
31 * have documented CBR_* macros.
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
47 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
49 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
51 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
52 struct sp_port_config *config);
54 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
55 const struct sp_port_config *config);
57 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
59 struct sp_port *port;
60 #ifndef NO_PORT_METADATA
61 enum sp_return ret;
62 #endif
63 int len;
65 TRACE("%s, %p", portname, port_ptr);
67 if (!port_ptr)
68 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
70 *port_ptr = NULL;
72 if (!portname)
73 RETURN_ERROR(SP_ERR_ARG, "Null port name");
75 DEBUG_FMT("Building structure for port %s", portname);
77 if (!(port = malloc(sizeof(struct sp_port))))
78 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
80 len = strlen(portname) + 1;
82 if (!(port->name = malloc(len))) {
83 free(port);
84 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
87 memcpy(port->name, portname, len);
89 #ifdef _WIN32
90 port->usb_path = NULL;
91 port->hdl = INVALID_HANDLE_VALUE;
92 #else
93 port->fd = -1;
94 #endif
96 port->description = NULL;
97 port->transport = SP_TRANSPORT_NATIVE;
98 port->usb_bus = -1;
99 port->usb_address = -1;
100 port->usb_vid = -1;
101 port->usb_pid = -1;
102 port->usb_manufacturer = NULL;
103 port->usb_product = NULL;
104 port->usb_serial = NULL;
105 port->bluetooth_address = NULL;
107 #ifndef NO_PORT_METADATA
108 if ((ret = get_port_details(port)) != SP_OK) {
109 sp_free_port(port);
110 return ret;
112 #endif
114 *port_ptr = port;
116 RETURN_OK();
119 SP_API char *sp_get_port_name(const struct sp_port *port)
121 TRACE("%p", port);
123 if (!port)
124 return NULL;
126 RETURN_STRING(port->name);
129 SP_API char *sp_get_port_description(const struct sp_port *port)
131 TRACE("%p", port);
133 if (!port || !port->description)
134 return NULL;
136 RETURN_STRING(port->description);
139 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
141 TRACE("%p", port);
143 if (!port)
144 RETURN_ERROR(SP_ERR_ARG, "Null port");
146 RETURN_INT(port->transport);
149 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
150 int *usb_bus,int *usb_address)
152 TRACE("%p", port);
154 if (!port)
155 RETURN_ERROR(SP_ERR_ARG, "Null port");
156 if (port->transport != SP_TRANSPORT_USB)
157 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
158 if (port->usb_bus < 0 || port->usb_address < 0)
159 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
161 if (usb_bus)
162 *usb_bus = port->usb_bus;
163 if (usb_address)
164 *usb_address = port->usb_address;
166 RETURN_OK();
169 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
170 int *usb_vid, int *usb_pid)
172 TRACE("%p", port);
174 if (!port)
175 RETURN_ERROR(SP_ERR_ARG, "Null port");
176 if (port->transport != SP_TRANSPORT_USB)
177 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
178 if (port->usb_vid < 0 || port->usb_pid < 0)
179 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
181 if (usb_vid)
182 *usb_vid = port->usb_vid;
183 if (usb_pid)
184 *usb_pid = port->usb_pid;
186 RETURN_OK();
189 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
191 TRACE("%p", port);
193 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
194 return NULL;
196 RETURN_STRING(port->usb_manufacturer);
199 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
201 TRACE("%p", port);
203 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
204 return NULL;
206 RETURN_STRING(port->usb_product);
209 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
211 TRACE("%p", port);
213 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
214 return NULL;
216 RETURN_STRING(port->usb_serial);
219 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
221 TRACE("%p", port);
223 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
224 || !port->bluetooth_address)
225 return NULL;
227 RETURN_STRING(port->bluetooth_address);
230 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
231 void *result_ptr)
233 TRACE("%p, %p", port, result_ptr);
235 if (!port)
236 RETURN_ERROR(SP_ERR_ARG, "Null port");
237 if (!result_ptr)
238 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
240 #ifdef _WIN32
241 HANDLE *handle_ptr = result_ptr;
242 *handle_ptr = port->hdl;
243 #else
244 int *fd_ptr = result_ptr;
245 *fd_ptr = port->fd;
246 #endif
248 RETURN_OK();
251 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
252 struct sp_port **copy_ptr)
254 TRACE("%p, %p", port, copy_ptr);
256 if (!copy_ptr)
257 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
259 *copy_ptr = NULL;
261 if (!port)
262 RETURN_ERROR(SP_ERR_ARG, "Null port");
264 if (!port->name)
265 RETURN_ERROR(SP_ERR_ARG, "Null port name");
267 DEBUG("Copying port structure");
269 RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
272 SP_API void sp_free_port(struct sp_port *port)
274 TRACE("%p", port);
276 if (!port) {
277 DEBUG("Null port");
278 RETURN();
281 DEBUG("Freeing port structure");
283 if (port->name)
284 free(port->name);
285 if (port->description)
286 free(port->description);
287 if (port->usb_manufacturer)
288 free(port->usb_manufacturer);
289 if (port->usb_product)
290 free(port->usb_product);
291 if (port->usb_serial)
292 free(port->usb_serial);
293 if (port->bluetooth_address)
294 free(port->bluetooth_address);
295 #ifdef _WIN32
296 if (port->usb_path)
297 free(port->usb_path);
298 #endif
300 free(port);
302 RETURN();
305 SP_PRIV struct sp_port **list_append(struct sp_port **list,
306 const char *portname)
308 void *tmp;
309 unsigned int count;
311 for (count = 0; list[count]; count++);
312 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
313 goto fail;
314 list = tmp;
315 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
316 goto fail;
317 list[count + 1] = NULL;
318 return list;
320 fail:
321 sp_free_port_list(list);
322 return NULL;
325 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
327 #ifndef NO_ENUMERATION
328 struct sp_port **list;
329 int ret;
330 #endif
332 TRACE("%p", list_ptr);
334 if (!list_ptr)
335 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
337 *list_ptr = NULL;
339 #ifdef NO_ENUMERATION
340 RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
341 #else
342 DEBUG("Enumerating ports");
344 if (!(list = malloc(sizeof(struct sp_port *))))
345 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
347 list[0] = NULL;
349 ret = list_ports(&list);
351 if (ret == SP_OK) {
352 *list_ptr = list;
353 } else {
354 sp_free_port_list(list);
355 *list_ptr = NULL;
358 RETURN_CODEVAL(ret);
359 #endif
362 SP_API void sp_free_port_list(struct sp_port **list)
364 unsigned int i;
366 TRACE("%p", list);
368 if (!list) {
369 DEBUG("Null list");
370 RETURN();
373 DEBUG("Freeing port list");
375 for (i = 0; list[i]; i++)
376 sp_free_port(list[i]);
377 free(list);
379 RETURN();
382 #define CHECK_PORT() do { \
383 if (!port) \
384 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
385 if (!port->name) \
386 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
387 } while (0)
388 #ifdef _WIN32
389 #define CHECK_PORT_HANDLE() do { \
390 if (port->hdl == INVALID_HANDLE_VALUE) \
391 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
392 } while (0)
393 #else
394 #define CHECK_PORT_HANDLE() do { \
395 if (port->fd < 0) \
396 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
397 } while (0)
398 #endif
399 #define CHECK_OPEN_PORT() do { \
400 CHECK_PORT(); \
401 CHECK_PORT_HANDLE(); \
402 } while (0)
404 #ifdef WIN32
405 /** To be called after port receive buffer is emptied. */
406 static enum sp_return restart_wait(struct sp_port *port)
408 DWORD wait_result;
410 if (port->wait_running) {
411 /* Check status of running wait operation. */
412 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
413 &wait_result, FALSE)) {
414 DEBUG("Previous wait completed");
415 port->wait_running = FALSE;
416 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
417 DEBUG("Previous wait still running");
418 RETURN_OK();
419 } else {
420 RETURN_FAIL("GetOverlappedResult() failed");
424 if (!port->wait_running) {
425 /* Start new wait operation. */
426 if (WaitCommEvent(port->hdl, &port->events,
427 &port->wait_ovl)) {
428 DEBUG("New wait returned, events already pending");
429 } else if (GetLastError() == ERROR_IO_PENDING) {
430 DEBUG("New wait running in background");
431 port->wait_running = TRUE;
432 } else {
433 RETURN_FAIL("WaitCommEvent() failed");
437 RETURN_OK();
439 #endif
441 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
443 struct port_data data;
444 struct sp_port_config config;
445 enum sp_return ret;
447 TRACE("%p, 0x%x", port, flags);
449 CHECK_PORT();
451 if (flags > SP_MODE_READ_WRITE)
452 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
454 DEBUG_FMT("Opening port %s", port->name);
456 #ifdef _WIN32
457 DWORD desired_access = 0, flags_and_attributes = 0, errors;
458 char *escaped_port_name;
459 COMSTAT status;
461 /* Prefix port name with '\\.\' to work with ports above COM9. */
462 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
463 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
464 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
466 /* Map 'flags' to the OS-specific settings. */
467 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
468 if (flags & SP_MODE_READ)
469 desired_access |= GENERIC_READ;
470 if (flags & SP_MODE_WRITE)
471 desired_access |= GENERIC_WRITE;
473 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
474 OPEN_EXISTING, flags_and_attributes, 0);
476 free(escaped_port_name);
478 if (port->hdl == INVALID_HANDLE_VALUE)
479 RETURN_FAIL("Port CreateFile() failed");
481 /* All timeouts initially disabled. */
482 port->timeouts.ReadIntervalTimeout = 0;
483 port->timeouts.ReadTotalTimeoutMultiplier = 0;
484 port->timeouts.ReadTotalTimeoutConstant = 0;
485 port->timeouts.WriteTotalTimeoutMultiplier = 0;
486 port->timeouts.WriteTotalTimeoutConstant = 0;
488 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
489 sp_close(port);
490 RETURN_FAIL("SetCommTimeouts() failed");
493 /* Prepare OVERLAPPED structures. */
494 #define INIT_OVERLAPPED(ovl) do { \
495 memset(&port->ovl, 0, sizeof(port->ovl)); \
496 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
497 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
498 == INVALID_HANDLE_VALUE) { \
499 sp_close(port); \
500 RETURN_FAIL(#ovl "CreateEvent() failed"); \
502 } while (0)
504 INIT_OVERLAPPED(read_ovl);
505 INIT_OVERLAPPED(write_ovl);
506 INIT_OVERLAPPED(wait_ovl);
508 /* Set event mask for RX and error events. */
509 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
510 sp_close(port);
511 RETURN_FAIL("SetCommMask() failed");
514 port->writing = FALSE;
515 port->wait_running = FALSE;
517 ret = restart_wait(port);
519 if (ret < 0) {
520 sp_close(port);
521 RETURN_CODEVAL(ret);
523 #else
524 int flags_local = O_NONBLOCK | O_NOCTTY;
526 /* Map 'flags' to the OS-specific settings. */
527 if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
528 flags_local |= O_RDWR;
529 else if (flags & SP_MODE_READ)
530 flags_local |= O_RDONLY;
531 else if (flags & SP_MODE_WRITE)
532 flags_local |= O_WRONLY;
534 if ((port->fd = open(port->name, flags_local)) < 0)
535 RETURN_FAIL("open() failed");
536 #endif
538 ret = get_config(port, &data, &config);
540 if (ret < 0) {
541 sp_close(port);
542 RETURN_CODEVAL(ret);
545 /* Set sane port settings. */
546 #ifdef _WIN32
547 data.dcb.fBinary = TRUE;
548 data.dcb.fDsrSensitivity = FALSE;
549 data.dcb.fErrorChar = FALSE;
550 data.dcb.fNull = FALSE;
551 data.dcb.fAbortOnError = FALSE;
552 #else
553 /* Turn off all fancy termios tricks, give us a raw channel. */
554 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
555 #ifdef IUCLC
556 data.term.c_iflag &= ~IUCLC;
557 #endif
558 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
559 #ifdef OLCUC
560 data.term.c_oflag &= ~OLCUC;
561 #endif
562 #ifdef NLDLY
563 data.term.c_oflag &= ~NLDLY;
564 #endif
565 #ifdef CRDLY
566 data.term.c_oflag &= ~CRDLY;
567 #endif
568 #ifdef TABDLY
569 data.term.c_oflag &= ~TABDLY;
570 #endif
571 #ifdef BSDLY
572 data.term.c_oflag &= ~BSDLY;
573 #endif
574 #ifdef VTDLY
575 data.term.c_oflag &= ~VTDLY;
576 #endif
577 #ifdef FFDLY
578 data.term.c_oflag &= ~FFDLY;
579 #endif
580 #ifdef OFILL
581 data.term.c_oflag &= ~OFILL;
582 #endif
583 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
584 data.term.c_cc[VMIN] = 0;
585 data.term.c_cc[VTIME] = 0;
587 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
588 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
589 #endif
591 #ifdef _WIN32
592 if (ClearCommError(port->hdl, &errors, &status) == 0)
593 RETURN_FAIL("ClearCommError() failed");
594 #endif
596 ret = set_config(port, &data, &config);
598 if (ret < 0) {
599 sp_close(port);
600 RETURN_CODEVAL(ret);
603 RETURN_OK();
606 SP_API enum sp_return sp_close(struct sp_port *port)
608 TRACE("%p", port);
610 CHECK_OPEN_PORT();
612 DEBUG_FMT("Closing port %s", port->name);
614 #ifdef _WIN32
615 /* Returns non-zero upon success, 0 upon failure. */
616 if (CloseHandle(port->hdl) == 0)
617 RETURN_FAIL("Port CloseHandle() failed");
618 port->hdl = INVALID_HANDLE_VALUE;
620 /* Close event handles for overlapped structures. */
621 #define CLOSE_OVERLAPPED(ovl) do { \
622 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
623 CloseHandle(port->ovl.hEvent) == 0) \
624 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
625 } while (0)
626 CLOSE_OVERLAPPED(read_ovl);
627 CLOSE_OVERLAPPED(write_ovl);
628 CLOSE_OVERLAPPED(wait_ovl);
630 #else
631 /* Returns 0 upon success, -1 upon failure. */
632 if (close(port->fd) == -1)
633 RETURN_FAIL("close() failed");
634 port->fd = -1;
635 #endif
637 RETURN_OK();
640 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
642 TRACE("%p, 0x%x", port, buffers);
644 CHECK_OPEN_PORT();
646 if (buffers > SP_BUF_BOTH)
647 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
649 const char *buffer_names[] = {"no", "input", "output", "both"};
651 DEBUG_FMT("Flushing %s buffers on port %s",
652 buffer_names[buffers], port->name);
654 #ifdef _WIN32
655 DWORD flags = 0;
656 if (buffers & SP_BUF_INPUT)
657 flags |= PURGE_RXCLEAR;
658 if (buffers & SP_BUF_OUTPUT)
659 flags |= PURGE_TXCLEAR;
661 /* Returns non-zero upon success, 0 upon failure. */
662 if (PurgeComm(port->hdl, flags) == 0)
663 RETURN_FAIL("PurgeComm() failed");
665 if (buffers & SP_BUF_INPUT)
666 TRY(restart_wait(port));
667 #else
668 int flags = 0;
669 if (buffers == SP_BUF_BOTH)
670 flags = TCIOFLUSH;
671 else if (buffers == SP_BUF_INPUT)
672 flags = TCIFLUSH;
673 else if (buffers == SP_BUF_OUTPUT)
674 flags = TCOFLUSH;
676 /* Returns 0 upon success, -1 upon failure. */
677 if (tcflush(port->fd, flags) < 0)
678 RETURN_FAIL("tcflush() failed");
679 #endif
680 RETURN_OK();
683 SP_API enum sp_return sp_drain(struct sp_port *port)
685 TRACE("%p", port);
687 CHECK_OPEN_PORT();
689 DEBUG_FMT("Draining port %s", port->name);
691 #ifdef _WIN32
692 /* Returns non-zero upon success, 0 upon failure. */
693 if (FlushFileBuffers(port->hdl) == 0)
694 RETURN_FAIL("FlushFileBuffers() failed");
695 RETURN_OK();
696 #else
697 int result;
698 while (1) {
699 #ifdef __ANDROID__
700 int arg = 1;
701 result = ioctl(port->fd, TCSBRK, &arg);
702 #else
703 result = tcdrain(port->fd);
704 #endif
705 if (result < 0) {
706 if (errno == EINTR) {
707 DEBUG("tcdrain() was interrupted");
708 continue;
709 } else {
710 RETURN_FAIL("tcdrain() failed");
712 } else {
713 RETURN_OK();
716 #endif
719 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
720 size_t count, unsigned int timeout_ms)
722 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
724 CHECK_OPEN_PORT();
726 if (!buf)
727 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
729 if (timeout_ms)
730 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
731 count, port->name, timeout_ms);
732 else
733 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
734 count, port->name);
736 if (count == 0)
737 RETURN_INT(0);
739 #ifdef _WIN32
740 DWORD bytes_written = 0;
741 BOOL result;
743 /* Wait for previous non-blocking write to complete, if any. */
744 if (port->writing) {
745 DEBUG("Waiting for previous write to complete");
746 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
747 port->writing = 0;
748 if (!result)
749 RETURN_FAIL("Previous write failed to complete");
750 DEBUG("Previous write completed");
753 /* Set timeout. */
754 if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
755 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
756 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
757 RETURN_FAIL("SetCommTimeouts() failed");
760 /* Start write. */
761 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
762 DEBUG("Write completed immediately");
763 RETURN_INT(count);
764 } else if (GetLastError() == ERROR_IO_PENDING) {
765 DEBUG("Waiting for write to complete");
766 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0)
767 RETURN_FAIL("GetOverlappedResult() failed");
768 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
769 RETURN_INT(bytes_written);
770 } else {
771 RETURN_FAIL("WriteFile() failed");
773 #else
774 size_t bytes_written = 0;
775 unsigned char *ptr = (unsigned char *) buf;
776 struct timeval start, delta, now, end = {0, 0};
777 int started = 0;
778 fd_set fds;
779 int result;
781 if (timeout_ms) {
782 /* Get time at start of operation. */
783 gettimeofday(&start, NULL);
784 /* Define duration of timeout. */
785 delta.tv_sec = timeout_ms / 1000;
786 delta.tv_usec = (timeout_ms % 1000) * 1000;
787 /* Calculate time at which we should give up. */
788 timeradd(&start, &delta, &end);
791 FD_ZERO(&fds);
792 FD_SET(port->fd, &fds);
794 /* Loop until we have written the requested number of bytes. */
795 while (bytes_written < count) {
797 * Check timeout only if we have run select() at least once,
798 * to avoid any issues if a short timeout is reached before
799 * select() is even run.
801 if (timeout_ms && started) {
802 gettimeofday(&now, NULL);
803 if (timercmp(&now, &end, >))
804 /* Timeout has expired. */
805 break;
806 timersub(&end, &now, &delta);
808 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
809 started = 1;
810 if (result < 0) {
811 if (errno == EINTR) {
812 DEBUG("select() call was interrupted, repeating");
813 continue;
814 } else {
815 RETURN_FAIL("select() failed");
817 } else if (result == 0) {
818 /* Timeout has expired. */
819 break;
822 /* Do write. */
823 result = write(port->fd, ptr, count - bytes_written);
825 if (result < 0) {
826 if (errno == EAGAIN)
827 /* This shouldn't happen because we did a select() first, but handle anyway. */
828 continue;
829 else
830 /* This is an actual failure. */
831 RETURN_FAIL("write() failed");
834 bytes_written += result;
835 ptr += result;
838 if (bytes_written < count)
839 DEBUG("Write timed out");
841 RETURN_INT(bytes_written);
842 #endif
845 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
846 const void *buf, size_t count)
848 TRACE("%p, %p, %d", port, buf, count);
850 CHECK_OPEN_PORT();
852 if (!buf)
853 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
855 DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
857 if (count == 0)
858 RETURN_INT(0);
860 #ifdef _WIN32
861 DWORD written = 0;
862 BYTE *ptr = (BYTE *) buf;
864 /* Check whether previous write is complete. */
865 if (port->writing) {
866 if (HasOverlappedIoCompleted(&port->write_ovl)) {
867 DEBUG("Previous write completed");
868 port->writing = 0;
869 } else {
870 DEBUG("Previous write not complete");
871 /* Can't take a new write until the previous one finishes. */
872 RETURN_INT(0);
876 /* Set timeout. */
877 if (port->timeouts.WriteTotalTimeoutConstant != 0) {
878 port->timeouts.WriteTotalTimeoutConstant = 0;
879 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
880 RETURN_FAIL("SetCommTimeouts() failed");
884 * Keep writing data until the OS has to actually start an async IO
885 * for it. At that point we know the buffer is full.
887 while (written < count) {
888 /* Copy first byte of user buffer. */
889 port->pending_byte = *ptr++;
891 /* Start asynchronous write. */
892 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
893 if (GetLastError() == ERROR_IO_PENDING) {
894 if (HasOverlappedIoCompleted(&port->write_ovl)) {
895 DEBUG("Asynchronous write completed immediately");
896 port->writing = 0;
897 written++;
898 continue;
899 } else {
900 DEBUG("Asynchronous write running");
901 port->writing = 1;
902 RETURN_INT(++written);
904 } else {
905 /* Actual failure of some kind. */
906 RETURN_FAIL("WriteFile() failed");
908 } else {
909 DEBUG("Single byte written immediately");
910 written++;
914 DEBUG("All bytes written immediately");
916 RETURN_INT(written);
917 #else
918 /* Returns the number of bytes written, or -1 upon failure. */
919 ssize_t written = write(port->fd, buf, count);
921 if (written < 0)
922 RETURN_FAIL("write() failed");
923 else
924 RETURN_INT(written);
925 #endif
928 #ifdef _WIN32
929 /* Restart wait operation if buffer was emptied. */
930 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
932 DWORD errors;
933 COMSTAT comstat;
935 if (bytes_read == 0)
936 RETURN_OK();
938 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
939 RETURN_FAIL("ClearCommError() failed");
941 if (comstat.cbInQue == 0)
942 TRY(restart_wait(port));
944 RETURN_OK();
946 #endif
948 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
949 size_t count, unsigned int timeout_ms)
951 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
953 CHECK_OPEN_PORT();
955 if (!buf)
956 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
958 if (timeout_ms)
959 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
960 count, port->name, timeout_ms);
961 else
962 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
963 count, port->name);
965 if (count == 0)
966 RETURN_INT(0);
968 #ifdef _WIN32
969 DWORD bytes_read = 0;
971 /* Set timeout. */
972 if (port->timeouts.ReadIntervalTimeout != 0 ||
973 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
974 port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
975 port->timeouts.ReadIntervalTimeout = 0;
976 port->timeouts.ReadTotalTimeoutMultiplier = 0;
977 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
978 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
979 RETURN_FAIL("SetCommTimeouts() failed");
982 /* Start read. */
983 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
984 DEBUG("Read completed immediately");
985 bytes_read = count;
986 } else if (GetLastError() == ERROR_IO_PENDING) {
987 DEBUG("Waiting for read to complete");
988 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
989 RETURN_FAIL("GetOverlappedResult() failed");
990 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
991 } else {
992 RETURN_FAIL("ReadFile() failed");
995 TRY(restart_wait_if_needed(port, bytes_read));
997 RETURN_INT(bytes_read);
999 #else
1000 size_t bytes_read = 0;
1001 unsigned char *ptr = (unsigned char *) buf;
1002 struct timeval start, delta, now, end = {0, 0};
1003 int started = 0;
1004 fd_set fds;
1005 int result;
1007 if (timeout_ms) {
1008 /* Get time at start of operation. */
1009 gettimeofday(&start, NULL);
1010 /* Define duration of timeout. */
1011 delta.tv_sec = timeout_ms / 1000;
1012 delta.tv_usec = (timeout_ms % 1000) * 1000;
1013 /* Calculate time at which we should give up. */
1014 timeradd(&start, &delta, &end);
1017 FD_ZERO(&fds);
1018 FD_SET(port->fd, &fds);
1020 /* Loop until we have the requested number of bytes. */
1021 while (bytes_read < count) {
1023 * Check timeout only if we have run select() at least once,
1024 * to avoid any issues if a short timeout is reached before
1025 * select() is even run.
1027 if (timeout_ms && started) {
1028 gettimeofday(&now, NULL);
1029 if (timercmp(&now, &end, >))
1030 /* Timeout has expired. */
1031 break;
1032 timersub(&end, &now, &delta);
1034 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1035 started = 1;
1036 if (result < 0) {
1037 if (errno == EINTR) {
1038 DEBUG("select() call was interrupted, repeating");
1039 continue;
1040 } else {
1041 RETURN_FAIL("select() failed");
1043 } else if (result == 0) {
1044 /* Timeout has expired. */
1045 break;
1048 /* Do read. */
1049 result = read(port->fd, ptr, count - bytes_read);
1051 if (result < 0) {
1052 if (errno == EAGAIN)
1054 * This shouldn't happen because we did a
1055 * select() first, but handle anyway.
1057 continue;
1058 else
1059 /* This is an actual failure. */
1060 RETURN_FAIL("read() failed");
1063 bytes_read += result;
1064 ptr += result;
1067 if (bytes_read < count)
1068 DEBUG("Read timed out");
1070 RETURN_INT(bytes_read);
1071 #endif
1074 SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
1075 size_t count, unsigned int timeout_ms)
1077 TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
1079 CHECK_OPEN_PORT();
1081 if (!buf)
1082 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1084 if (count == 0)
1085 RETURN_ERROR(SP_ERR_ARG, "Zero count");
1087 if (timeout_ms)
1088 DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
1089 count, port->name, timeout_ms);
1090 else
1091 DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
1092 count, port->name);
1094 #ifdef _WIN32
1095 DWORD bytes_read = 0;
1097 /* If timeout_ms == 0, set maximum timeout. */
1098 DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
1100 /* Set timeout. */
1101 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1102 port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
1103 port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
1104 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1105 port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
1106 port->timeouts.ReadTotalTimeoutConstant = timeout_val;
1107 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1108 RETURN_FAIL("SetCommTimeouts() failed");
1111 /* Loop until we have at least one byte, or timeout is reached. */
1112 while (bytes_read == 0) {
1113 /* Start read. */
1114 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
1115 DEBUG("Read completed immediately");
1116 bytes_read = count;
1117 } else if (GetLastError() == ERROR_IO_PENDING) {
1118 DEBUG("Waiting for read to complete");
1119 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1120 RETURN_FAIL("GetOverlappedResult() failed");
1121 if (bytes_read > 0) {
1122 DEBUG("Read completed");
1123 } else if (timeout_ms > 0) {
1124 DEBUG("Read timed out");
1125 break;
1126 } else {
1127 DEBUG("Restarting read");
1129 } else {
1130 RETURN_FAIL("ReadFile() failed");
1134 TRY(restart_wait_if_needed(port, bytes_read));
1136 RETURN_INT(bytes_read);
1138 #else
1139 size_t bytes_read = 0;
1140 struct timeval start, delta, now, end = {0, 0};
1141 int started = 0;
1142 fd_set fds;
1143 int result;
1145 if (timeout_ms) {
1146 /* Get time at start of operation. */
1147 gettimeofday(&start, NULL);
1148 /* Define duration of timeout. */
1149 delta.tv_sec = timeout_ms / 1000;
1150 delta.tv_usec = (timeout_ms % 1000) * 1000;
1151 /* Calculate time at which we should give up. */
1152 timeradd(&start, &delta, &end);
1155 FD_ZERO(&fds);
1156 FD_SET(port->fd, &fds);
1158 /* Loop until we have at least one byte, or timeout is reached. */
1159 while (bytes_read == 0) {
1161 * Check timeout only if we have run select() at least once,
1162 * to avoid any issues if a short timeout is reached before
1163 * select() is even run.
1165 if (timeout_ms && started) {
1166 gettimeofday(&now, NULL);
1167 if (timercmp(&now, &end, >))
1168 /* Timeout has expired. */
1169 break;
1170 timersub(&end, &now, &delta);
1172 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1173 started = 1;
1174 if (result < 0) {
1175 if (errno == EINTR) {
1176 DEBUG("select() call was interrupted, repeating");
1177 continue;
1178 } else {
1179 RETURN_FAIL("select() failed");
1181 } else if (result == 0) {
1182 /* Timeout has expired. */
1183 break;
1186 /* Do read. */
1187 result = read(port->fd, buf, count);
1189 if (result < 0) {
1190 if (errno == EAGAIN)
1191 /* This shouldn't happen because we did a select() first, but handle anyway. */
1192 continue;
1193 else
1194 /* This is an actual failure. */
1195 RETURN_FAIL("read() failed");
1198 bytes_read = result;
1201 if (bytes_read == 0)
1202 DEBUG("Read timed out");
1204 RETURN_INT(bytes_read);
1205 #endif
1208 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1209 size_t count)
1211 TRACE("%p, %p, %d", port, buf, count);
1213 CHECK_OPEN_PORT();
1215 if (!buf)
1216 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1218 DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1220 #ifdef _WIN32
1221 DWORD bytes_read;
1223 /* Set timeout. */
1224 if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1225 port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
1226 port->timeouts.ReadTotalTimeoutConstant != 0) {
1227 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1228 port->timeouts.ReadTotalTimeoutMultiplier = 0;
1229 port->timeouts.ReadTotalTimeoutConstant = 0;
1230 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1231 RETURN_FAIL("SetCommTimeouts() failed");
1234 /* Do read. */
1235 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1236 RETURN_FAIL("ReadFile() failed");
1238 /* Get number of bytes read. */
1239 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1240 RETURN_FAIL("GetOverlappedResult() failed");
1242 TRY(restart_wait_if_needed(port, bytes_read));
1244 RETURN_INT(bytes_read);
1245 #else
1246 ssize_t bytes_read;
1248 /* Returns the number of bytes read, or -1 upon failure. */
1249 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1250 if (errno == EAGAIN)
1251 /* No bytes available. */
1252 bytes_read = 0;
1253 else
1254 /* This is an actual failure. */
1255 RETURN_FAIL("read() failed");
1257 RETURN_INT(bytes_read);
1258 #endif
1261 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1263 TRACE("%p", port);
1265 CHECK_OPEN_PORT();
1267 DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1269 #ifdef _WIN32
1270 DWORD errors;
1271 COMSTAT comstat;
1273 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1274 RETURN_FAIL("ClearCommError() failed");
1275 RETURN_INT(comstat.cbInQue);
1276 #else
1277 int bytes_waiting;
1278 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1279 RETURN_FAIL("TIOCINQ ioctl failed");
1280 RETURN_INT(bytes_waiting);
1281 #endif
1284 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1286 TRACE("%p", port);
1288 CHECK_OPEN_PORT();
1290 DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1292 #ifdef _WIN32
1293 DWORD errors;
1294 COMSTAT comstat;
1296 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1297 RETURN_FAIL("ClearCommError() failed");
1298 RETURN_INT(comstat.cbOutQue);
1299 #else
1300 int bytes_waiting;
1301 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1302 RETURN_FAIL("TIOCOUTQ ioctl failed");
1303 RETURN_INT(bytes_waiting);
1304 #endif
1307 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1309 struct sp_event_set *result;
1311 TRACE("%p", result_ptr);
1313 if (!result_ptr)
1314 RETURN_ERROR(SP_ERR_ARG, "Null result");
1316 *result_ptr = NULL;
1318 if (!(result = malloc(sizeof(struct sp_event_set))))
1319 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1321 memset(result, 0, sizeof(struct sp_event_set));
1323 *result_ptr = result;
1325 RETURN_OK();
1328 static enum sp_return add_handle(struct sp_event_set *event_set,
1329 event_handle handle, enum sp_event mask)
1331 void *new_handles;
1332 enum sp_event *new_masks;
1334 TRACE("%p, %d, %d", event_set, handle, mask);
1336 if (!(new_handles = realloc(event_set->handles,
1337 sizeof(event_handle) * (event_set->count + 1))))
1338 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1340 event_set->handles = new_handles;
1342 if (!(new_masks = realloc(event_set->masks,
1343 sizeof(enum sp_event) * (event_set->count + 1))))
1344 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1346 event_set->masks = new_masks;
1348 ((event_handle *) event_set->handles)[event_set->count] = handle;
1349 event_set->masks[event_set->count] = mask;
1351 event_set->count++;
1353 RETURN_OK();
1356 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1357 const struct sp_port *port, enum sp_event mask)
1359 TRACE("%p, %p, %d", event_set, port, mask);
1361 if (!event_set)
1362 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1364 if (!port)
1365 RETURN_ERROR(SP_ERR_ARG, "Null port");
1367 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1368 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1370 if (!mask)
1371 RETURN_OK();
1373 #ifdef _WIN32
1374 enum sp_event handle_mask;
1375 if ((handle_mask = mask & SP_EVENT_TX_READY))
1376 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1377 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1378 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1379 #else
1380 TRY(add_handle(event_set, port->fd, mask));
1381 #endif
1383 RETURN_OK();
1386 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1388 TRACE("%p", event_set);
1390 if (!event_set) {
1391 DEBUG("Null event set");
1392 RETURN();
1395 DEBUG("Freeing event set");
1397 if (event_set->handles)
1398 free(event_set->handles);
1399 if (event_set->masks)
1400 free(event_set->masks);
1402 free(event_set);
1404 RETURN();
1407 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1408 unsigned int timeout_ms)
1410 TRACE("%p, %d", event_set, timeout_ms);
1412 if (!event_set)
1413 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1415 #ifdef _WIN32
1416 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1417 timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1418 RETURN_FAIL("WaitForMultipleObjects() failed");
1420 RETURN_OK();
1421 #else
1422 struct timeval start, delta, now, end = {0, 0};
1423 int started = 0;
1424 int result, timeout_remaining_ms;
1425 struct pollfd *pollfds;
1426 unsigned int i;
1428 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1429 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1431 for (i = 0; i < event_set->count; i++) {
1432 pollfds[i].fd = ((int *) event_set->handles)[i];
1433 pollfds[i].events = 0;
1434 pollfds[i].revents = 0;
1435 if (event_set->masks[i] & SP_EVENT_RX_READY)
1436 pollfds[i].events |= POLLIN;
1437 if (event_set->masks[i] & SP_EVENT_TX_READY)
1438 pollfds[i].events |= POLLOUT;
1439 if (event_set->masks[i] & SP_EVENT_ERROR)
1440 pollfds[i].events |= POLLERR;
1443 if (timeout_ms) {
1444 /* Get time at start of operation. */
1445 gettimeofday(&start, NULL);
1446 /* Define duration of timeout. */
1447 delta.tv_sec = timeout_ms / 1000;
1448 delta.tv_usec = (timeout_ms % 1000) * 1000;
1449 /* Calculate time at which we should give up. */
1450 timeradd(&start, &delta, &end);
1453 /* Loop until an event occurs. */
1454 while (1) {
1456 * Check timeout only if we have run poll() at least once,
1457 * to avoid any issues if a short timeout is reached before
1458 * poll() is even run.
1460 if (!timeout_ms) {
1461 timeout_remaining_ms = -1;
1462 } else if (!started) {
1463 timeout_remaining_ms = timeout_ms;
1464 } else {
1465 gettimeofday(&now, NULL);
1466 if (timercmp(&now, &end, >)) {
1467 DEBUG("Wait timed out");
1468 break;
1470 timersub(&end, &now, &delta);
1471 timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1474 result = poll(pollfds, event_set->count, timeout_remaining_ms);
1475 started = 1;
1477 if (result < 0) {
1478 if (errno == EINTR) {
1479 DEBUG("poll() call was interrupted, repeating");
1480 continue;
1481 } else {
1482 free(pollfds);
1483 RETURN_FAIL("poll() failed");
1485 } else if (result == 0) {
1486 DEBUG("poll() timed out");
1487 break;
1488 } else {
1489 DEBUG("poll() completed");
1490 break;
1494 free(pollfds);
1495 RETURN_OK();
1496 #endif
1499 #ifdef USE_TERMIOS_SPEED
1500 static enum sp_return get_baudrate(int fd, int *baudrate)
1502 void *data;
1504 TRACE("%d, %p", fd, baudrate);
1506 DEBUG("Getting baud rate");
1508 if (!(data = malloc(get_termios_size())))
1509 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1511 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1512 free(data);
1513 RETURN_FAIL("Getting termios failed");
1516 *baudrate = get_termios_speed(data);
1518 free(data);
1520 RETURN_OK();
1523 static enum sp_return set_baudrate(int fd, int baudrate)
1525 void *data;
1527 TRACE("%d, %d", fd, baudrate);
1529 DEBUG("Getting baud rate");
1531 if (!(data = malloc(get_termios_size())))
1532 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1534 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1535 free(data);
1536 RETURN_FAIL("Getting termios failed");
1539 DEBUG("Setting baud rate");
1541 set_termios_speed(data, baudrate);
1543 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1544 free(data);
1545 RETURN_FAIL("Setting termios failed");
1548 free(data);
1550 RETURN_OK();
1552 #endif /* USE_TERMIOS_SPEED */
1554 #ifdef USE_TERMIOX
1555 static enum sp_return get_flow(int fd, struct port_data *data)
1557 void *termx;
1559 TRACE("%d, %p", fd, data);
1561 DEBUG("Getting advanced flow control");
1563 if (!(termx = malloc(get_termiox_size())))
1564 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1566 if (ioctl(fd, TCGETX, termx) < 0) {
1567 free(termx);
1568 RETURN_FAIL("Getting termiox failed");
1571 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1572 &data->dtr_flow, &data->dsr_flow);
1574 free(termx);
1576 RETURN_OK();
1579 static enum sp_return set_flow(int fd, struct port_data *data)
1581 void *termx;
1583 TRACE("%d, %p", fd, data);
1585 DEBUG("Getting advanced flow control");
1587 if (!(termx = malloc(get_termiox_size())))
1588 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1590 if (ioctl(fd, TCGETX, termx) < 0) {
1591 free(termx);
1592 RETURN_FAIL("Getting termiox failed");
1595 DEBUG("Setting advanced flow control");
1597 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1598 data->dtr_flow, data->dsr_flow);
1600 if (ioctl(fd, TCSETX, termx) < 0) {
1601 free(termx);
1602 RETURN_FAIL("Setting termiox failed");
1605 free(termx);
1607 RETURN_OK();
1609 #endif /* USE_TERMIOX */
1611 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1612 struct sp_port_config *config)
1614 unsigned int i;
1616 TRACE("%p, %p, %p", port, data, config);
1618 DEBUG_FMT("Getting configuration for port %s", port->name);
1620 #ifdef _WIN32
1621 if (!GetCommState(port->hdl, &data->dcb))
1622 RETURN_FAIL("GetCommState() failed");
1624 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1625 if (data->dcb.BaudRate == std_baudrates[i].index) {
1626 config->baudrate = std_baudrates[i].value;
1627 break;
1631 if (i == NUM_STD_BAUDRATES)
1632 /* BaudRate field can be either an index or a custom baud rate. */
1633 config->baudrate = data->dcb.BaudRate;
1635 config->bits = data->dcb.ByteSize;
1637 if (data->dcb.fParity)
1638 switch (data->dcb.Parity) {
1639 case NOPARITY:
1640 config->parity = SP_PARITY_NONE;
1641 break;
1642 case ODDPARITY:
1643 config->parity = SP_PARITY_ODD;
1644 break;
1645 case EVENPARITY:
1646 config->parity = SP_PARITY_EVEN;
1647 break;
1648 case MARKPARITY:
1649 config->parity = SP_PARITY_MARK;
1650 break;
1651 case SPACEPARITY:
1652 config->parity = SP_PARITY_SPACE;
1653 break;
1654 default:
1655 config->parity = -1;
1657 else
1658 config->parity = SP_PARITY_NONE;
1660 switch (data->dcb.StopBits) {
1661 case ONESTOPBIT:
1662 config->stopbits = 1;
1663 break;
1664 case TWOSTOPBITS:
1665 config->stopbits = 2;
1666 break;
1667 default:
1668 config->stopbits = -1;
1671 switch (data->dcb.fRtsControl) {
1672 case RTS_CONTROL_DISABLE:
1673 config->rts = SP_RTS_OFF;
1674 break;
1675 case RTS_CONTROL_ENABLE:
1676 config->rts = SP_RTS_ON;
1677 break;
1678 case RTS_CONTROL_HANDSHAKE:
1679 config->rts = SP_RTS_FLOW_CONTROL;
1680 break;
1681 default:
1682 config->rts = -1;
1685 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1687 switch (data->dcb.fDtrControl) {
1688 case DTR_CONTROL_DISABLE:
1689 config->dtr = SP_DTR_OFF;
1690 break;
1691 case DTR_CONTROL_ENABLE:
1692 config->dtr = SP_DTR_ON;
1693 break;
1694 case DTR_CONTROL_HANDSHAKE:
1695 config->dtr = SP_DTR_FLOW_CONTROL;
1696 break;
1697 default:
1698 config->dtr = -1;
1701 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1703 if (data->dcb.fInX) {
1704 if (data->dcb.fOutX)
1705 config->xon_xoff = SP_XONXOFF_INOUT;
1706 else
1707 config->xon_xoff = SP_XONXOFF_IN;
1708 } else {
1709 if (data->dcb.fOutX)
1710 config->xon_xoff = SP_XONXOFF_OUT;
1711 else
1712 config->xon_xoff = SP_XONXOFF_DISABLED;
1715 #else // !_WIN32
1717 if (tcgetattr(port->fd, &data->term) < 0)
1718 RETURN_FAIL("tcgetattr() failed");
1720 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1721 RETURN_FAIL("TIOCMGET ioctl failed");
1723 #ifdef USE_TERMIOX
1724 int ret = get_flow(port->fd, data);
1726 if (ret == SP_ERR_FAIL && errno == EINVAL)
1727 data->termiox_supported = 0;
1728 else if (ret < 0)
1729 RETURN_CODEVAL(ret);
1730 else
1731 data->termiox_supported = 1;
1732 #else
1733 data->termiox_supported = 0;
1734 #endif
1736 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1737 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1738 config->baudrate = std_baudrates[i].value;
1739 break;
1743 if (i == NUM_STD_BAUDRATES) {
1744 #ifdef __APPLE__
1745 config->baudrate = (int)data->term.c_ispeed;
1746 #elif defined(USE_TERMIOS_SPEED)
1747 TRY(get_baudrate(port->fd, &config->baudrate));
1748 #else
1749 config->baudrate = -1;
1750 #endif
1753 switch (data->term.c_cflag & CSIZE) {
1754 case CS8:
1755 config->bits = 8;
1756 break;
1757 case CS7:
1758 config->bits = 7;
1759 break;
1760 case CS6:
1761 config->bits = 6;
1762 break;
1763 case CS5:
1764 config->bits = 5;
1765 break;
1766 default:
1767 config->bits = -1;
1770 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1771 config->parity = SP_PARITY_NONE;
1772 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1773 config->parity = -1;
1774 #ifdef CMSPAR
1775 else if (data->term.c_cflag & CMSPAR)
1776 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1777 #endif
1778 else
1779 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1781 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1783 if (data->term.c_cflag & CRTSCTS) {
1784 config->rts = SP_RTS_FLOW_CONTROL;
1785 config->cts = SP_CTS_FLOW_CONTROL;
1786 } else {
1787 if (data->termiox_supported && data->rts_flow)
1788 config->rts = SP_RTS_FLOW_CONTROL;
1789 else
1790 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1792 config->cts = (data->termiox_supported && data->cts_flow) ?
1793 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1796 if (data->termiox_supported && data->dtr_flow)
1797 config->dtr = SP_DTR_FLOW_CONTROL;
1798 else
1799 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1801 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1802 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1804 if (data->term.c_iflag & IXOFF) {
1805 if (data->term.c_iflag & IXON)
1806 config->xon_xoff = SP_XONXOFF_INOUT;
1807 else
1808 config->xon_xoff = SP_XONXOFF_IN;
1809 } else {
1810 if (data->term.c_iflag & IXON)
1811 config->xon_xoff = SP_XONXOFF_OUT;
1812 else
1813 config->xon_xoff = SP_XONXOFF_DISABLED;
1815 #endif
1817 RETURN_OK();
1820 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1821 const struct sp_port_config *config)
1823 unsigned int i;
1824 #ifdef __APPLE__
1825 BAUD_TYPE baud_nonstd;
1827 baud_nonstd = B0;
1828 #endif
1829 #ifdef USE_TERMIOS_SPEED
1830 int baud_nonstd = 0;
1831 #endif
1833 TRACE("%p, %p, %p", port, data, config);
1835 DEBUG_FMT("Setting configuration for port %s", port->name);
1837 #ifdef _WIN32
1838 if (config->baudrate >= 0) {
1839 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1840 if (config->baudrate == std_baudrates[i].value) {
1841 data->dcb.BaudRate = std_baudrates[i].index;
1842 break;
1846 if (i == NUM_STD_BAUDRATES)
1847 data->dcb.BaudRate = config->baudrate;
1850 if (config->bits >= 0)
1851 data->dcb.ByteSize = config->bits;
1853 if (config->parity >= 0) {
1854 switch (config->parity) {
1855 case SP_PARITY_NONE:
1856 data->dcb.Parity = NOPARITY;
1857 break;
1858 case SP_PARITY_ODD:
1859 data->dcb.Parity = ODDPARITY;
1860 break;
1861 case SP_PARITY_EVEN:
1862 data->dcb.Parity = EVENPARITY;
1863 break;
1864 case SP_PARITY_MARK:
1865 data->dcb.Parity = MARKPARITY;
1866 break;
1867 case SP_PARITY_SPACE:
1868 data->dcb.Parity = SPACEPARITY;
1869 break;
1870 default:
1871 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1875 if (config->stopbits >= 0) {
1876 switch (config->stopbits) {
1877 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1878 case 1:
1879 data->dcb.StopBits = ONESTOPBIT;
1880 break;
1881 case 2:
1882 data->dcb.StopBits = TWOSTOPBITS;
1883 break;
1884 default:
1885 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1889 if (config->rts >= 0) {
1890 switch (config->rts) {
1891 case SP_RTS_OFF:
1892 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1893 break;
1894 case SP_RTS_ON:
1895 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1896 break;
1897 case SP_RTS_FLOW_CONTROL:
1898 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1899 break;
1900 default:
1901 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1905 if (config->cts >= 0) {
1906 switch (config->cts) {
1907 case SP_CTS_IGNORE:
1908 data->dcb.fOutxCtsFlow = FALSE;
1909 break;
1910 case SP_CTS_FLOW_CONTROL:
1911 data->dcb.fOutxCtsFlow = TRUE;
1912 break;
1913 default:
1914 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1918 if (config->dtr >= 0) {
1919 switch (config->dtr) {
1920 case SP_DTR_OFF:
1921 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1922 break;
1923 case SP_DTR_ON:
1924 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1925 break;
1926 case SP_DTR_FLOW_CONTROL:
1927 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1928 break;
1929 default:
1930 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1934 if (config->dsr >= 0) {
1935 switch (config->dsr) {
1936 case SP_DSR_IGNORE:
1937 data->dcb.fOutxDsrFlow = FALSE;
1938 break;
1939 case SP_DSR_FLOW_CONTROL:
1940 data->dcb.fOutxDsrFlow = TRUE;
1941 break;
1942 default:
1943 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1947 if (config->xon_xoff >= 0) {
1948 switch (config->xon_xoff) {
1949 case SP_XONXOFF_DISABLED:
1950 data->dcb.fInX = FALSE;
1951 data->dcb.fOutX = FALSE;
1952 break;
1953 case SP_XONXOFF_IN:
1954 data->dcb.fInX = TRUE;
1955 data->dcb.fOutX = FALSE;
1956 break;
1957 case SP_XONXOFF_OUT:
1958 data->dcb.fInX = FALSE;
1959 data->dcb.fOutX = TRUE;
1960 break;
1961 case SP_XONXOFF_INOUT:
1962 data->dcb.fInX = TRUE;
1963 data->dcb.fOutX = TRUE;
1964 break;
1965 default:
1966 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1970 if (!SetCommState(port->hdl, &data->dcb))
1971 RETURN_FAIL("SetCommState() failed");
1973 #else /* !_WIN32 */
1975 int controlbits;
1977 if (config->baudrate >= 0) {
1978 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1979 if (config->baudrate == std_baudrates[i].value) {
1980 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1981 RETURN_FAIL("cfsetospeed() failed");
1983 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1984 RETURN_FAIL("cfsetispeed() failed");
1985 break;
1989 /* Non-standard baud rate */
1990 if (i == NUM_STD_BAUDRATES) {
1991 #ifdef __APPLE__
1992 /* Set "dummy" baud rate. */
1993 if (cfsetspeed(&data->term, B9600) < 0)
1994 RETURN_FAIL("cfsetspeed() failed");
1995 baud_nonstd = config->baudrate;
1996 #elif defined(USE_TERMIOS_SPEED)
1997 baud_nonstd = 1;
1998 #else
1999 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
2000 #endif
2004 if (config->bits >= 0) {
2005 data->term.c_cflag &= ~CSIZE;
2006 switch (config->bits) {
2007 case 8:
2008 data->term.c_cflag |= CS8;
2009 break;
2010 case 7:
2011 data->term.c_cflag |= CS7;
2012 break;
2013 case 6:
2014 data->term.c_cflag |= CS6;
2015 break;
2016 case 5:
2017 data->term.c_cflag |= CS5;
2018 break;
2019 default:
2020 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
2024 if (config->parity >= 0) {
2025 data->term.c_iflag &= ~IGNPAR;
2026 data->term.c_cflag &= ~(PARENB | PARODD);
2027 #ifdef CMSPAR
2028 data->term.c_cflag &= ~CMSPAR;
2029 #endif
2030 switch (config->parity) {
2031 case SP_PARITY_NONE:
2032 data->term.c_iflag |= IGNPAR;
2033 break;
2034 case SP_PARITY_EVEN:
2035 data->term.c_cflag |= PARENB;
2036 break;
2037 case SP_PARITY_ODD:
2038 data->term.c_cflag |= PARENB | PARODD;
2039 break;
2040 #ifdef CMSPAR
2041 case SP_PARITY_MARK:
2042 data->term.c_cflag |= PARENB | PARODD;
2043 data->term.c_cflag |= CMSPAR;
2044 break;
2045 case SP_PARITY_SPACE:
2046 data->term.c_cflag |= PARENB;
2047 data->term.c_cflag |= CMSPAR;
2048 break;
2049 #else
2050 case SP_PARITY_MARK:
2051 case SP_PARITY_SPACE:
2052 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
2053 #endif
2054 default:
2055 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
2059 if (config->stopbits >= 0) {
2060 data->term.c_cflag &= ~CSTOPB;
2061 switch (config->stopbits) {
2062 case 1:
2063 data->term.c_cflag &= ~CSTOPB;
2064 break;
2065 case 2:
2066 data->term.c_cflag |= CSTOPB;
2067 break;
2068 default:
2069 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
2073 if (config->rts >= 0 || config->cts >= 0) {
2074 if (data->termiox_supported) {
2075 data->rts_flow = data->cts_flow = 0;
2076 switch (config->rts) {
2077 case SP_RTS_OFF:
2078 case SP_RTS_ON:
2079 controlbits = TIOCM_RTS;
2080 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2081 RETURN_FAIL("Setting RTS signal level failed");
2082 break;
2083 case SP_RTS_FLOW_CONTROL:
2084 data->rts_flow = 1;
2085 break;
2086 default:
2087 break;
2089 if (config->cts == SP_CTS_FLOW_CONTROL)
2090 data->cts_flow = 1;
2092 if (data->rts_flow && data->cts_flow)
2093 data->term.c_iflag |= CRTSCTS;
2094 else
2095 data->term.c_iflag &= ~CRTSCTS;
2096 } else {
2097 /* Asymmetric use of RTS/CTS not supported. */
2098 if (data->term.c_iflag & CRTSCTS) {
2099 /* Flow control can only be disabled for both RTS & CTS together. */
2100 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2101 if (config->cts != SP_CTS_IGNORE)
2102 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2104 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2105 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2106 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2108 } else {
2109 /* Flow control can only be enabled for both RTS & CTS together. */
2110 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2111 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2112 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2115 if (config->rts >= 0) {
2116 if (config->rts == SP_RTS_FLOW_CONTROL) {
2117 data->term.c_iflag |= CRTSCTS;
2118 } else {
2119 controlbits = TIOCM_RTS;
2120 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2121 &controlbits) < 0)
2122 RETURN_FAIL("Setting RTS signal level failed");
2128 if (config->dtr >= 0 || config->dsr >= 0) {
2129 if (data->termiox_supported) {
2130 data->dtr_flow = data->dsr_flow = 0;
2131 switch (config->dtr) {
2132 case SP_DTR_OFF:
2133 case SP_DTR_ON:
2134 controlbits = TIOCM_DTR;
2135 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2136 RETURN_FAIL("Setting DTR signal level failed");
2137 break;
2138 case SP_DTR_FLOW_CONTROL:
2139 data->dtr_flow = 1;
2140 break;
2141 default:
2142 break;
2144 if (config->dsr == SP_DSR_FLOW_CONTROL)
2145 data->dsr_flow = 1;
2146 } else {
2147 /* DTR/DSR flow control not supported. */
2148 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2149 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2151 if (config->dtr >= 0) {
2152 controlbits = TIOCM_DTR;
2153 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2154 &controlbits) < 0)
2155 RETURN_FAIL("Setting DTR signal level failed");
2160 if (config->xon_xoff >= 0) {
2161 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2162 switch (config->xon_xoff) {
2163 case SP_XONXOFF_DISABLED:
2164 break;
2165 case SP_XONXOFF_IN:
2166 data->term.c_iflag |= IXOFF;
2167 break;
2168 case SP_XONXOFF_OUT:
2169 data->term.c_iflag |= IXON | IXANY;
2170 break;
2171 case SP_XONXOFF_INOUT:
2172 data->term.c_iflag |= IXON | IXOFF | IXANY;
2173 break;
2174 default:
2175 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2179 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2180 RETURN_FAIL("tcsetattr() failed");
2182 #ifdef __APPLE__
2183 if (baud_nonstd != B0) {
2184 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2185 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2187 * Set baud rates in data->term to correct, but incompatible
2188 * with tcsetattr() value, same as delivered by tcgetattr().
2190 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2191 RETURN_FAIL("cfsetspeed() failed");
2193 #elif defined(__linux__)
2194 #ifdef USE_TERMIOS_SPEED
2195 if (baud_nonstd)
2196 TRY(set_baudrate(port->fd, config->baudrate));
2197 #endif
2198 #ifdef USE_TERMIOX
2199 if (data->termiox_supported)
2200 TRY(set_flow(port->fd, data));
2201 #endif
2202 #endif
2204 #endif /* !_WIN32 */
2206 RETURN_OK();
2209 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2211 struct sp_port_config *config;
2213 TRACE("%p", config_ptr);
2215 if (!config_ptr)
2216 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2218 *config_ptr = NULL;
2220 if (!(config = malloc(sizeof(struct sp_port_config))))
2221 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2223 config->baudrate = -1;
2224 config->bits = -1;
2225 config->parity = -1;
2226 config->stopbits = -1;
2227 config->rts = -1;
2228 config->cts = -1;
2229 config->dtr = -1;
2230 config->dsr = -1;
2232 *config_ptr = config;
2234 RETURN_OK();
2237 SP_API void sp_free_config(struct sp_port_config *config)
2239 TRACE("%p", config);
2241 if (!config)
2242 DEBUG("Null config");
2243 else
2244 free(config);
2246 RETURN();
2249 SP_API enum sp_return sp_get_config(struct sp_port *port,
2250 struct sp_port_config *config)
2252 struct port_data data;
2254 TRACE("%p, %p", port, config);
2256 CHECK_OPEN_PORT();
2258 if (!config)
2259 RETURN_ERROR(SP_ERR_ARG, "Null config");
2261 TRY(get_config(port, &data, config));
2263 RETURN_OK();
2266 SP_API enum sp_return sp_set_config(struct sp_port *port,
2267 const struct sp_port_config *config)
2269 struct port_data data;
2270 struct sp_port_config prev_config;
2272 TRACE("%p, %p", port, config);
2274 CHECK_OPEN_PORT();
2276 if (!config)
2277 RETURN_ERROR(SP_ERR_ARG, "Null config");
2279 TRY(get_config(port, &data, &prev_config));
2280 TRY(set_config(port, &data, config));
2282 RETURN_OK();
2285 #define CREATE_ACCESSORS(x, type) \
2286 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2287 struct port_data data; \
2288 struct sp_port_config config; \
2289 TRACE("%p, %d", port, x); \
2290 CHECK_OPEN_PORT(); \
2291 TRY(get_config(port, &data, &config)); \
2292 config.x = x; \
2293 TRY(set_config(port, &data, &config)); \
2294 RETURN_OK(); \
2296 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2297 type *x) { \
2298 TRACE("%p, %p", config, x); \
2299 if (!x) \
2300 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2301 if (!config) \
2302 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2303 *x = config->x; \
2304 RETURN_OK(); \
2306 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2307 type x) { \
2308 TRACE("%p, %d", config, x); \
2309 if (!config) \
2310 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2311 config->x = x; \
2312 RETURN_OK(); \
2315 CREATE_ACCESSORS(baudrate, int)
2316 CREATE_ACCESSORS(bits, int)
2317 CREATE_ACCESSORS(parity, enum sp_parity)
2318 CREATE_ACCESSORS(stopbits, int)
2319 CREATE_ACCESSORS(rts, enum sp_rts)
2320 CREATE_ACCESSORS(cts, enum sp_cts)
2321 CREATE_ACCESSORS(dtr, enum sp_dtr)
2322 CREATE_ACCESSORS(dsr, enum sp_dsr)
2323 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2325 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2326 enum sp_flowcontrol flowcontrol)
2328 if (!config)
2329 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2331 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2332 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2334 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2335 config->xon_xoff = SP_XONXOFF_INOUT;
2336 else
2337 config->xon_xoff = SP_XONXOFF_DISABLED;
2339 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2340 config->rts = SP_RTS_FLOW_CONTROL;
2341 config->cts = SP_CTS_FLOW_CONTROL;
2342 } else {
2343 if (config->rts == SP_RTS_FLOW_CONTROL)
2344 config->rts = SP_RTS_ON;
2345 config->cts = SP_CTS_IGNORE;
2348 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2349 config->dtr = SP_DTR_FLOW_CONTROL;
2350 config->dsr = SP_DSR_FLOW_CONTROL;
2351 } else {
2352 if (config->dtr == SP_DTR_FLOW_CONTROL)
2353 config->dtr = SP_DTR_ON;
2354 config->dsr = SP_DSR_IGNORE;
2357 RETURN_OK();
2360 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2361 enum sp_flowcontrol flowcontrol)
2363 struct port_data data;
2364 struct sp_port_config config;
2366 TRACE("%p, %d", port, flowcontrol);
2368 CHECK_OPEN_PORT();
2370 TRY(get_config(port, &data, &config));
2372 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2374 TRY(set_config(port, &data, &config));
2376 RETURN_OK();
2379 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2380 enum sp_signal *signals)
2382 TRACE("%p, %p", port, signals);
2384 CHECK_OPEN_PORT();
2386 if (!signals)
2387 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2389 DEBUG_FMT("Getting control signals for port %s", port->name);
2391 *signals = 0;
2392 #ifdef _WIN32
2393 DWORD bits;
2394 if (GetCommModemStatus(port->hdl, &bits) == 0)
2395 RETURN_FAIL("GetCommModemStatus() failed");
2396 if (bits & MS_CTS_ON)
2397 *signals |= SP_SIG_CTS;
2398 if (bits & MS_DSR_ON)
2399 *signals |= SP_SIG_DSR;
2400 if (bits & MS_RLSD_ON)
2401 *signals |= SP_SIG_DCD;
2402 if (bits & MS_RING_ON)
2403 *signals |= SP_SIG_RI;
2404 #else
2405 int bits;
2406 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2407 RETURN_FAIL("TIOCMGET ioctl failed");
2408 if (bits & TIOCM_CTS)
2409 *signals |= SP_SIG_CTS;
2410 if (bits & TIOCM_DSR)
2411 *signals |= SP_SIG_DSR;
2412 if (bits & TIOCM_CAR)
2413 *signals |= SP_SIG_DCD;
2414 if (bits & TIOCM_RNG)
2415 *signals |= SP_SIG_RI;
2416 #endif
2417 RETURN_OK();
2420 SP_API enum sp_return sp_start_break(struct sp_port *port)
2422 TRACE("%p", port);
2424 CHECK_OPEN_PORT();
2425 #ifdef _WIN32
2426 if (SetCommBreak(port->hdl) == 0)
2427 RETURN_FAIL("SetCommBreak() failed");
2428 #else
2429 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2430 RETURN_FAIL("TIOCSBRK ioctl failed");
2431 #endif
2433 RETURN_OK();
2436 SP_API enum sp_return sp_end_break(struct sp_port *port)
2438 TRACE("%p", port);
2440 CHECK_OPEN_PORT();
2441 #ifdef _WIN32
2442 if (ClearCommBreak(port->hdl) == 0)
2443 RETURN_FAIL("ClearCommBreak() failed");
2444 #else
2445 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2446 RETURN_FAIL("TIOCCBRK ioctl failed");
2447 #endif
2449 RETURN_OK();
2452 SP_API int sp_last_error_code(void)
2454 TRACE_VOID();
2455 #ifdef _WIN32
2456 RETURN_INT(GetLastError());
2457 #else
2458 RETURN_INT(errno);
2459 #endif
2462 SP_API char *sp_last_error_message(void)
2464 TRACE_VOID();
2466 #ifdef _WIN32
2467 TCHAR *message;
2468 DWORD error = GetLastError();
2470 DWORD length = FormatMessage(
2471 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2472 FORMAT_MESSAGE_FROM_SYSTEM |
2473 FORMAT_MESSAGE_IGNORE_INSERTS,
2474 NULL,
2475 error,
2476 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2477 (LPTSTR) &message,
2478 0, NULL );
2480 if (length >= 2 && message[length - 2] == '\r')
2481 message[length - 2] = '\0';
2483 RETURN_STRING(message);
2484 #else
2485 RETURN_STRING(strerror(errno));
2486 #endif
2489 SP_API void sp_free_error_message(char *message)
2491 TRACE("%s", message);
2493 #ifdef _WIN32
2494 LocalFree(message);
2495 #else
2496 (void)message;
2497 #endif
2499 RETURN();
2502 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2504 TRACE("%p", handler);
2506 sp_debug_handler = handler;
2508 RETURN();
2511 SP_API void sp_default_debug_handler(const char *format, ...)
2513 va_list args;
2514 va_start(args, format);
2515 if (getenv("LIBSERIALPORT_DEBUG")) {
2516 fputs("sp: ", stderr);
2517 vfprintf(stderr, format, args);
2519 va_end(args);
2522 SP_API int sp_get_major_package_version(void)
2524 return SP_PACKAGE_VERSION_MAJOR;
2527 SP_API int sp_get_minor_package_version(void)
2529 return SP_PACKAGE_VERSION_MINOR;
2532 SP_API int sp_get_micro_package_version(void)
2534 return SP_PACKAGE_VERSION_MICRO;
2537 SP_API const char *sp_get_package_version_string(void)
2539 return SP_PACKAGE_VERSION_STRING;
2542 SP_API int sp_get_current_lib_version(void)
2544 return SP_LIB_VERSION_CURRENT;
2547 SP_API int sp_get_revision_lib_version(void)
2549 return SP_LIB_VERSION_REVISION;
2552 SP_API int sp_get_age_lib_version(void)
2554 return SP_LIB_VERSION_AGE;
2557 SP_API const char *sp_get_lib_version_string(void)
2559 return SP_LIB_VERSION_STRING;
2562 /** @} */