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 const struct std_baudrate std_baudrates[] = {
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),
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),
41 #if !defined(__APPLE__) && !defined(__OpenBSD__)
47 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
49 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
50 struct sp_port_config *config);
52 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
53 const struct sp_port_config *config);
55 enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
61 TRACE("%s, %p", portname, port_ptr);
64 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
69 RETURN_ERROR(SP_ERR_ARG, "Null port name");
71 DEBUG("Building structure for port %s", portname);
73 if (!(port = malloc(sizeof(struct sp_port))))
74 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
76 len = strlen(portname) + 1;
78 if (!(port->name = malloc(len))) {
80 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
83 memcpy(port->name, portname, len);
86 port->hdl = INVALID_HANDLE_VALUE;
91 port->description = NULL;
92 port->transport = SP_TRANSPORT_NATIVE;
94 port->usb_address = -1;
97 port->usb_manufacturer = NULL;
98 port->usb_product = NULL;
99 port->usb_serial = NULL;
100 port->bluetooth_address = NULL;
102 if ((ret = get_port_details(port)) != SP_OK) {
112 char *sp_get_port_name(const struct sp_port *port)
119 RETURN_VALUE("%s", port->name);
122 char *sp_get_port_description(struct sp_port *port)
126 if (!port || !port->description)
129 RETURN_VALUE("%s", port->description);
132 enum sp_transport sp_get_port_transport(struct sp_port *port)
137 RETURN_ERROR(SP_ERR_ARG, "Null port");
139 RETURN_VALUE("%d", port->transport);
142 enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
143 int *usb_bus, int *usb_address)
148 RETURN_ERROR(SP_ERR_ARG, "Null port");
149 if (port->transport != SP_TRANSPORT_USB)
150 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
151 if (port->usb_bus < 0 || port->usb_address < 0)
152 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
154 if (usb_bus) *usb_bus = port->usb_bus;
155 if (usb_address) *usb_address = port->usb_address;
160 enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
161 int *usb_vid, int *usb_pid)
166 RETURN_ERROR(SP_ERR_ARG, "Null port");
167 if (port->transport != SP_TRANSPORT_USB)
168 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
169 if (port->usb_vid < 0 || port->usb_pid < 0)
170 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
172 if (usb_vid) *usb_vid = port->usb_vid;
173 if (usb_pid) *usb_pid = port->usb_pid;
178 char *sp_get_port_usb_manufacturer(const struct sp_port *port)
182 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
185 RETURN_VALUE("%s", port->usb_manufacturer);
188 char *sp_get_port_usb_product(const struct sp_port *port)
192 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
195 RETURN_VALUE("%s", port->usb_product);
198 char *sp_get_port_usb_serial(const struct sp_port *port)
202 if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
205 RETURN_VALUE("%s", port->usb_serial);
208 char *sp_get_port_bluetooth_address(const struct sp_port *port)
212 if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
213 || !port->bluetooth_address)
216 RETURN_VALUE("%s", port->bluetooth_address);
219 enum sp_return sp_get_port_handle(const struct sp_port *port, void *result_ptr)
221 TRACE("%p, %p", port, result_ptr);
224 RETURN_ERROR(SP_ERR_ARG, "Null port");
227 HANDLE *handle_ptr = result_ptr;
228 *handle_ptr = port->hdl;
230 int *fd_ptr = result_ptr;
237 enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
239 TRACE("%p, %p", port, copy_ptr);
242 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
247 RETURN_ERROR(SP_ERR_ARG, "Null port");
250 RETURN_ERROR(SP_ERR_ARG, "Null port name");
252 DEBUG("Copying port structure");
254 RETURN_VALUE("%p", sp_get_port_by_name(port->name, copy_ptr));
257 void sp_free_port(struct sp_port *port)
266 DEBUG("Freeing port structure");
270 if (port->description)
271 free(port->description);
272 if (port->usb_manufacturer)
273 free(port->usb_manufacturer);
274 if (port->usb_product)
275 free(port->usb_product);
276 if (port->usb_serial)
277 free(port->usb_serial);
278 if (port->bluetooth_address)
279 free(port->bluetooth_address);
282 free(port->usb_path);
290 static struct sp_port **list_append(struct sp_port **list, const char *portname)
295 for (count = 0; list[count]; count++);
296 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
299 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
301 list[count + 1] = NULL;
305 sp_free_port_list(list);
309 enum sp_return sp_list_ports(struct sp_port ***list_ptr)
311 struct sp_port **list;
312 int ret = SP_ERR_SUPP;
314 TRACE("%p", list_ptr);
317 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
319 DEBUG("Enumerating ports");
321 if (!(list = malloc(sizeof(struct sp_port **))))
322 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
329 DWORD max_value_len, max_data_size, max_data_len;
330 DWORD value_len, data_size, data_len;
331 DWORD type, index = 0;
337 DEBUG("Opening registry key");
338 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
339 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
340 SET_FAIL(ret, "RegOpenKeyEx() failed");
343 DEBUG("Querying registry key value and data sizes");
344 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
345 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
346 SET_FAIL(ret, "RegQueryInfoKey() failed");
349 max_data_len = max_data_size / sizeof(TCHAR);
350 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
351 SET_ERROR(ret, SP_ERR_MEM, "registry value malloc failed");
354 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
355 SET_ERROR(ret, SP_ERR_MEM, "registry data malloc failed");
358 DEBUG("Iterating over values");
360 value_len = max_value_len + 1,
361 data_size = max_data_size,
362 RegEnumValue(key, index, value, &value_len,
363 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
365 data_len = data_size / sizeof(TCHAR);
366 data[data_len] = '\0';
368 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL);
370 name_len = data_len + 1;
372 if (!(name = malloc(name_len))) {
373 SET_ERROR(ret, SP_ERR_MEM, "registry port name malloc failed");
377 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
381 if (type == REG_SZ) {
382 DEBUG("Found port %s", name);
383 if (!(list = list_append(list, name))) {
384 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
399 CFMutableDictionaryRef classes;
408 DEBUG("Creating matching dictionary");
409 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) {
410 SET_FAIL(ret, "IOServiceMatching() failed");
414 DEBUG("Getting matching services");
415 if (IOServiceGetMatchingServices(kIOMasterPortDefault, classes,
416 &iter) != KERN_SUCCESS) {
417 SET_FAIL(ret, "IOServiceGetMatchingServices() failed");
421 DEBUG("Iterating over results");
422 while ((port = IOIteratorNext(iter))) {
423 cf_path = IORegistryEntryCreateCFProperty(port,
424 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
426 result = CFStringGetCString(cf_path, path, sizeof(path),
427 kCFStringEncodingASCII);
430 DEBUG("Found port %s", path);
431 if (!(list = list_append(list, path))) {
432 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
433 IOObjectRelease(port);
438 IOObjectRelease(port);
441 IOObjectRelease(iter);
445 char name[PATH_MAX], target[PATH_MAX];
446 struct dirent entry, *result;
447 struct serial_struct serial_info;
448 int len, fd, ioctl_result;
453 DEBUG("Enumerating tty devices");
454 if (!(dir = opendir("/sys/class/tty")))
455 RETURN_FAIL("could not open /sys/class/tty");
457 DEBUG("Iterating over results");
458 while (!readdir_r(dir, &entry, &result) && result) {
459 len = readlinkat(dirfd(dir), entry.d_name, target, sizeof(target));
460 if (len <= 0 || len >= (int) sizeof(target)-1)
463 if (strstr(target, "virtual"))
465 snprintf(name, sizeof(name), "/dev/%s", entry.d_name);
466 DEBUG("Found device %s", name);
467 if (strstr(target, "serial8250")) {
468 /* The serial8250 driver has a hardcoded number of ports.
469 * The only way to tell which actually exist on a given system
470 * is to try to open them and make an ioctl call. */
471 DEBUG("serial8250 device, attempting to open");
472 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0) {
473 DEBUG("open failed, skipping");
476 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
478 if (ioctl_result != 0) {
479 DEBUG("ioctl failed, skipping");
482 if (serial_info.type == PORT_UNKNOWN) {
483 DEBUG("port type is unknown, skipping");
487 DEBUG("Found port %s", name);
488 list = list_append(list, name);
490 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
502 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
505 sp_free_port_list(list);
511 void sp_free_port_list(struct sp_port **list)
522 DEBUG("Freeing port list");
524 for (i = 0; list[i]; i++)
525 sp_free_port(list[i]);
531 #define CHECK_PORT() do { \
533 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
534 if (port->name == NULL) \
535 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
538 #define CHECK_PORT_HANDLE() do { \
539 if (port->hdl == INVALID_HANDLE_VALUE) \
540 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
543 #define CHECK_PORT_HANDLE() do { \
545 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
548 #define CHECK_OPEN_PORT() do { \
550 CHECK_PORT_HANDLE(); \
553 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
555 struct port_data data;
556 struct sp_port_config config;
559 TRACE("%p, 0x%x", port, flags);
563 if (flags > (SP_MODE_READ | SP_MODE_WRITE))
564 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
566 DEBUG("Opening port %s", port->name);
569 DWORD desired_access = 0, flags_and_attributes = 0, errors;
570 char *escaped_port_name;
573 /* Prefix port name with '\\.\' to work with ports above COM9. */
574 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
575 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
576 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
578 /* Map 'flags' to the OS-specific settings. */
579 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
580 if (flags & SP_MODE_READ)
581 desired_access |= GENERIC_READ;
582 if (flags & SP_MODE_WRITE)
583 desired_access |= GENERIC_WRITE;
585 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
586 OPEN_EXISTING, flags_and_attributes, 0);
588 free(escaped_port_name);
590 if (port->hdl == INVALID_HANDLE_VALUE)
591 RETURN_FAIL("port CreateFile() failed");
593 /* All timeouts initially disabled. */
594 port->timeouts.ReadIntervalTimeout = 0;
595 port->timeouts.ReadTotalTimeoutMultiplier = 0;
596 port->timeouts.ReadTotalTimeoutConstant = 0;
597 port->timeouts.WriteTotalTimeoutMultiplier = 0;
598 port->timeouts.WriteTotalTimeoutConstant = 0;
600 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
602 RETURN_FAIL("SetCommTimeouts() failed");
605 /* Prepare OVERLAPPED structures. */
606 #define INIT_OVERLAPPED(ovl) do { \
607 memset(&port->ovl, 0, sizeof(port->ovl)); \
608 port->ovl.hEvent = INVALID_HANDLE_VALUE; \
609 if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
610 == INVALID_HANDLE_VALUE) { \
612 RETURN_FAIL(#ovl "CreateEvent() failed"); \
616 INIT_OVERLAPPED(read_ovl);
617 INIT_OVERLAPPED(write_ovl);
618 INIT_OVERLAPPED(wait_ovl);
620 /* Set event mask for RX and error events. */
621 if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
623 RETURN_FAIL("SetCommMask() failed");
626 /* Start background operation for RX and error events. */
627 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
628 if (GetLastError() != ERROR_IO_PENDING) {
630 RETURN_FAIL("WaitCommEvent() failed");
634 port->writing = FALSE;
637 int flags_local = O_NONBLOCK | O_NOCTTY;
639 /* Map 'flags' to the OS-specific settings. */
640 if (flags & (SP_MODE_READ | SP_MODE_WRITE))
641 flags_local |= O_RDWR;
642 else if (flags & SP_MODE_READ)
643 flags_local |= O_RDONLY;
644 else if (flags & SP_MODE_WRITE)
645 flags_local |= O_WRONLY;
647 if ((port->fd = open(port->name, flags_local)) < 0)
648 RETURN_FAIL("open() failed");
651 ret = get_config(port, &data, &config);
658 /* Set sane port settings. */
660 data.dcb.fBinary = TRUE;
661 data.dcb.fDsrSensitivity = FALSE;
662 data.dcb.fErrorChar = FALSE;
663 data.dcb.fNull = FALSE;
664 data.dcb.fAbortOnError = TRUE;
666 /* Turn off all fancy termios tricks, give us a raw channel. */
667 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
669 data.term.c_iflag &= ~IUCLC;
671 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
673 data.term.c_oflag &= ~OLCUC;
676 data.term.c_oflag &= ~NLDLY;
679 data.term.c_oflag &= ~CRDLY;
682 data.term.c_oflag &= ~TABDLY;
685 data.term.c_oflag &= ~BSDLY;
688 data.term.c_oflag &= ~VTDLY;
691 data.term.c_oflag &= ~FFDLY;
694 data.term.c_oflag &= ~OFILL;
696 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
697 data.term.c_cc[VMIN] = 0;
698 data.term.c_cc[VTIME] = 0;
700 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
701 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
705 if (ClearCommError(port->hdl, &errors, &status) == 0)
706 RETURN_FAIL("ClearCommError() failed");
709 ret = set_config(port, &data, &config);
719 enum sp_return sp_close(struct sp_port *port)
725 DEBUG("Closing port %s", port->name);
728 /* Returns non-zero upon success, 0 upon failure. */
729 if (CloseHandle(port->hdl) == 0)
730 RETURN_FAIL("port CloseHandle() failed");
731 port->hdl = INVALID_HANDLE_VALUE;
733 /* Close event handles for overlapped structures. */
734 #define CLOSE_OVERLAPPED(ovl) do { \
735 if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
736 CloseHandle(port->ovl.hEvent) == 0) \
737 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
739 CLOSE_OVERLAPPED(read_ovl);
740 CLOSE_OVERLAPPED(write_ovl);
741 CLOSE_OVERLAPPED(wait_ovl);
744 /* Returns 0 upon success, -1 upon failure. */
745 if (close(port->fd) == -1)
746 RETURN_FAIL("close() failed");
753 enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
755 TRACE("%p, 0x%x", port, buffers);
759 if (buffers > SP_BUF_BOTH)
760 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
762 const char *buffer_names[] = {"no", "input", "output", "both"};
764 DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
768 if (buffers & SP_BUF_INPUT)
769 flags |= PURGE_RXCLEAR;
770 if (buffers & SP_BUF_OUTPUT)
771 flags |= PURGE_TXCLEAR;
773 /* Returns non-zero upon success, 0 upon failure. */
774 if (PurgeComm(port->hdl, flags) == 0)
775 RETURN_FAIL("PurgeComm() failed");
778 if (buffers & SP_BUF_BOTH)
780 else if (buffers & SP_BUF_INPUT)
782 else if (buffers & SP_BUF_OUTPUT)
785 /* Returns 0 upon success, -1 upon failure. */
786 if (tcflush(port->fd, flags) < 0)
787 RETURN_FAIL("tcflush() failed");
792 enum sp_return sp_drain(struct sp_port *port)
798 DEBUG("Draining port %s", port->name);
801 /* Returns non-zero upon success, 0 upon failure. */
802 if (FlushFileBuffers(port->hdl) == 0)
803 RETURN_FAIL("FlushFileBuffers() failed");
810 result = ioctl(port->fd, TCSBRK, &arg);
812 result = tcdrain(port->fd);
815 if (errno == EINTR) {
816 DEBUG("tcdrain() was interrupted");
819 RETURN_FAIL("tcdrain() failed");
828 enum sp_return sp_blocking_write(struct sp_port *port, const void *buf, size_t count, unsigned int timeout)
830 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
835 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
838 DEBUG("Writing %d bytes to port %s, timeout %d ms", count, port->name, timeout);
840 DEBUG("Writing %d bytes to port %s, no timeout", count, port->name);
843 RETURN_VALUE("0", 0);
846 DWORD bytes_written = 0;
849 /* Wait for previous non-blocking write to complete, if any. */
851 DEBUG("Waiting for previous write to complete");
852 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
855 RETURN_FAIL("Previous write failed to complete");
856 DEBUG("Previous write completed");
860 port->timeouts.WriteTotalTimeoutConstant = timeout;
861 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
862 RETURN_FAIL("SetCommTimeouts() failed");
865 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) {
866 if (GetLastError() == ERROR_IO_PENDING) {
867 DEBUG("Waiting for write to complete");
868 GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
869 DEBUG("Write completed, %d/%d bytes written", bytes_written, count);
870 RETURN_VALUE("%d", bytes_written);
872 RETURN_FAIL("WriteFile() failed");
875 DEBUG("Write completed immediately");
876 RETURN_VALUE("%d", count);
879 size_t bytes_written = 0;
880 unsigned char *ptr = (unsigned char *) buf;
881 struct timeval start, delta, now, end = {0, 0};
886 /* Get time at start of operation. */
887 gettimeofday(&start, NULL);
888 /* Define duration of timeout. */
889 delta.tv_sec = timeout / 1000;
890 delta.tv_usec = (timeout % 1000) * 1000;
891 /* Calculate time at which we should give up. */
892 timeradd(&start, &delta, &end);
895 /* Loop until we have written the requested number of bytes. */
896 while (bytes_written < count)
898 /* Wait until space is available. */
900 FD_SET(port->fd, &fds);
902 gettimeofday(&now, NULL);
903 if (timercmp(&now, &end, >)) {
904 DEBUG("write timed out");
905 RETURN_VALUE("%d", bytes_written);
907 timersub(&end, &now, &delta);
909 result = select(port->fd + 1, NULL, &fds, NULL, timeout ? &delta : NULL);
911 if (errno == EINTR) {
912 DEBUG("select() call was interrupted, repeating");
915 RETURN_FAIL("select() failed");
917 } else if (result == 0) {
918 DEBUG("write timed out");
919 RETURN_VALUE("%d", bytes_written);
923 result = write(port->fd, ptr, count - bytes_written);
927 /* This shouldn't happen because we did a select() first, but handle anyway. */
930 /* This is an actual failure. */
931 RETURN_FAIL("write() failed");
934 bytes_written += result;
938 RETURN_VALUE("%d", bytes_written);
942 enum sp_return sp_nonblocking_write(struct sp_port *port, const void *buf, size_t count)
944 TRACE("%p, %p, %d", port, buf, count);
949 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
951 DEBUG("Writing up to %d bytes to port %s", count, port->name);
954 RETURN_VALUE("0", 0);
958 BYTE *ptr = (BYTE *) buf;
960 /* Check whether previous write is complete. */
962 if (HasOverlappedIoCompleted(&port->write_ovl)) {
963 DEBUG("Previous write completed");
966 DEBUG("Previous write not complete");
967 /* Can't take a new write until the previous one finishes. */
968 RETURN_VALUE("0", 0);
973 port->timeouts.WriteTotalTimeoutConstant = 0;
974 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
975 RETURN_FAIL("SetCommTimeouts() failed");
977 /* Keep writing data until the OS has to actually start an async IO for it.
978 * At that point we know the buffer is full. */
979 while (written < count)
981 /* Copy first byte of user buffer. */
982 port->pending_byte = *ptr++;
984 /* Start asynchronous write. */
985 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
986 if (GetLastError() == ERROR_IO_PENDING) {
987 if (HasOverlappedIoCompleted(&port->write_ovl)) {
988 DEBUG("Asynchronous write completed immediately");
993 DEBUG("Asynchronous write running");
995 RETURN_VALUE("%d", ++written);
998 /* Actual failure of some kind. */
999 RETURN_FAIL("WriteFile() failed");
1002 DEBUG("Single byte written immediately");
1007 DEBUG("All bytes written immediately");
1009 RETURN_VALUE("%d", written);
1011 /* Returns the number of bytes written, or -1 upon failure. */
1012 ssize_t written = write(port->fd, buf, count);
1015 RETURN_FAIL("write() failed");
1017 RETURN_VALUE("%d", written);
1021 enum sp_return sp_blocking_read(struct sp_port *port, void *buf, size_t count, unsigned int timeout)
1023 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
1028 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1031 DEBUG("Reading %d bytes from port %s, timeout %d ms", count, port->name, timeout);
1033 DEBUG("Reading %d bytes from port %s, no timeout", count, port->name);
1036 RETURN_VALUE("0", 0);
1039 DWORD bytes_read = 0;
1042 port->timeouts.ReadIntervalTimeout = 0;
1043 port->timeouts.ReadTotalTimeoutConstant = timeout;
1044 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1045 RETURN_FAIL("SetCommTimeouts() failed");
1048 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) {
1049 if (GetLastError() == ERROR_IO_PENDING) {
1050 DEBUG("Waiting for read to complete");
1051 GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
1052 DEBUG("Read completed, %d/%d bytes read", bytes_read, count);
1054 RETURN_FAIL("ReadFile() failed");
1057 DEBUG("Read completed immediately");
1061 /* Start background operation for subsequent events. */
1062 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
1063 if (GetLastError() != ERROR_IO_PENDING)
1064 RETURN_FAIL("WaitCommEvent() failed");
1067 RETURN_VALUE("%d", bytes_read);
1070 size_t bytes_read = 0;
1071 unsigned char *ptr = (unsigned char *) buf;
1072 struct timeval start, delta, now, end = {0, 0};
1077 /* Get time at start of operation. */
1078 gettimeofday(&start, NULL);
1079 /* Define duration of timeout. */
1080 delta.tv_sec = timeout / 1000;
1081 delta.tv_usec = (timeout % 1000) * 1000;
1082 /* Calculate time at which we should give up. */
1083 timeradd(&start, &delta, &end);
1086 /* Loop until we have the requested number of bytes. */
1087 while (bytes_read < count)
1089 /* Wait until data is available. */
1091 FD_SET(port->fd, &fds);
1093 gettimeofday(&now, NULL);
1094 if (timercmp(&now, &end, >))
1095 /* Timeout has expired. */
1096 RETURN_VALUE("%d", bytes_read);
1097 timersub(&end, &now, &delta);
1099 result = select(port->fd + 1, &fds, NULL, NULL, timeout ? &delta : NULL);
1101 if (errno == EINTR) {
1102 DEBUG("select() call was interrupted, repeating");
1105 RETURN_FAIL("select() failed");
1107 } else if (result == 0) {
1108 DEBUG("read timed out");
1109 RETURN_VALUE("%d", bytes_read);
1113 result = read(port->fd, ptr, count - bytes_read);
1116 if (errno == EAGAIN)
1117 /* This shouldn't happen because we did a select() first, but handle anyway. */
1120 /* This is an actual failure. */
1121 RETURN_FAIL("read() failed");
1124 bytes_read += result;
1128 RETURN_VALUE("%d", bytes_read);
1132 enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf, size_t count)
1134 TRACE("%p, %p, %d", port, buf, count);
1139 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1141 DEBUG("Reading up to %d bytes from port %s", count, port->name);
1147 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1148 port->timeouts.ReadTotalTimeoutConstant = 0;
1149 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1150 RETURN_FAIL("SetCommTimeouts() failed");
1153 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1154 RETURN_FAIL("ReadFile() failed");
1156 /* Get number of bytes read. */
1157 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1158 RETURN_FAIL("GetOverlappedResult() failed");
1160 if (bytes_read > 0) {
1161 /* Start background operation for subsequent events. */
1162 if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) {
1163 if (GetLastError() != ERROR_IO_PENDING)
1164 RETURN_FAIL("WaitCommEvent() failed");
1168 RETURN_VALUE("%d", bytes_read);
1172 /* Returns the number of bytes read, or -1 upon failure. */
1173 if ((bytes_read = read(port->fd, buf, count)) < 0) {
1174 if (errno == EAGAIN)
1175 /* No bytes available. */
1178 /* This is an actual failure. */
1179 RETURN_FAIL("read() failed");
1181 RETURN_VALUE("%d", bytes_read);
1185 enum sp_return sp_input_waiting(struct sp_port *port)
1191 DEBUG("Checking input bytes waiting on port %s", port->name);
1197 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1198 RETURN_FAIL("ClearCommError() failed");
1199 RETURN_VALUE("%d", comstat.cbInQue);
1202 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1203 RETURN_FAIL("TIOCINQ ioctl failed");
1204 RETURN_VALUE("%d", bytes_waiting);
1208 enum sp_return sp_output_waiting(struct sp_port *port)
1214 DEBUG("Checking output bytes waiting on port %s", port->name);
1220 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1221 RETURN_FAIL("ClearCommError() failed");
1222 RETURN_VALUE("%d", comstat.cbOutQue);
1225 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1226 RETURN_FAIL("TIOCOUTQ ioctl failed");
1227 RETURN_VALUE("%d", bytes_waiting);
1231 enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1233 struct sp_event_set *result;
1235 TRACE("%p", result_ptr);
1238 RETURN_ERROR(SP_ERR_ARG, "Null result");
1242 if (!(result = malloc(sizeof(struct sp_event_set))))
1243 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1245 memset(result, 0, sizeof(struct sp_event_set));
1247 *result_ptr = result;
1252 static enum sp_return add_handle(struct sp_event_set *event_set,
1253 event_handle handle, enum sp_event mask)
1256 enum sp_event *new_masks;
1258 TRACE("%p, %d, %d", event_set, handle, mask);
1260 if (!(new_handles = realloc(event_set->handles,
1261 sizeof(event_handle) * (event_set->count + 1))))
1262 RETURN_ERROR(SP_ERR_MEM, "handle array realloc() failed");
1264 if (!(new_masks = realloc(event_set->masks,
1265 sizeof(enum sp_event) * (event_set->count + 1))))
1266 RETURN_ERROR(SP_ERR_MEM, "mask array realloc() failed");
1268 event_set->handles = new_handles;
1269 event_set->masks = new_masks;
1271 ((event_handle *) event_set->handles)[event_set->count] = handle;
1272 event_set->masks[event_set->count] = mask;
1279 enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1280 const struct sp_port *port, enum sp_event mask)
1282 TRACE("%p, %p, %d", event_set, port, mask);
1285 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1288 RETURN_ERROR(SP_ERR_ARG, "Null port");
1290 if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1291 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1297 enum sp_event handle_mask;
1298 if ((handle_mask = mask & SP_EVENT_TX_READY))
1299 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1300 if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1301 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1303 TRY(add_handle(event_set, port->fd, mask));
1309 void sp_free_event_set(struct sp_event_set *event_set)
1311 TRACE("%p", event_set);
1314 DEBUG("Null event set");
1318 DEBUG("Freeing event set");
1320 if (event_set->handles)
1321 free(event_set->handles);
1322 if (event_set->masks)
1323 free(event_set->masks);
1330 enum sp_return sp_wait(struct sp_event_set *event_set, unsigned int timeout)
1332 TRACE("%p, %d", event_set, timeout);
1335 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1338 if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1339 timeout ? timeout : INFINITE) == WAIT_FAILED)
1340 RETURN_FAIL("WaitForMultipleObjects() failed");
1344 struct timeval start, delta, now, end = {0, 0};
1345 int result, timeout_remaining;
1346 struct pollfd *pollfds;
1349 if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1350 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1352 for (i = 0; i < event_set->count; i++) {
1353 pollfds[i].fd = ((int *) event_set->handles)[i];
1354 pollfds[i].events = 0;
1355 pollfds[i].revents = 0;
1356 if (event_set->masks[i] & SP_EVENT_RX_READY)
1357 pollfds[i].events |= POLLIN;
1358 if (event_set->masks[i] & SP_EVENT_TX_READY)
1359 pollfds[i].events |= POLLOUT;
1360 if (event_set->masks[i] & SP_EVENT_ERROR)
1361 pollfds[i].events |= POLLERR;
1365 /* Get time at start of operation. */
1366 gettimeofday(&start, NULL);
1367 /* Define duration of timeout. */
1368 delta.tv_sec = timeout / 1000;
1369 delta.tv_usec = (timeout % 1000) * 1000;
1370 /* Calculate time at which we should give up. */
1371 timeradd(&start, &delta, &end);
1374 /* Loop until an event occurs. */
1378 gettimeofday(&now, NULL);
1379 if (timercmp(&now, &end, >)) {
1380 DEBUG("wait timed out");
1383 timersub(&end, &now, &delta);
1384 timeout_remaining = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1387 result = poll(pollfds, event_set->count, timeout ? timeout_remaining : -1);
1390 if (errno == EINTR) {
1391 DEBUG("poll() call was interrupted, repeating");
1395 RETURN_FAIL("poll() failed");
1397 } else if (result == 0) {
1398 DEBUG("poll() timed out");
1401 DEBUG("poll() completed");
1411 #ifdef USE_TERMIOS_SPEED
1412 static enum sp_return get_baudrate(int fd, int *baudrate)
1416 TRACE("%d, %p", fd, baudrate);
1418 DEBUG("Getting baud rate");
1420 if (!(data = malloc(get_termios_size())))
1421 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1423 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1425 RETURN_FAIL("getting termios failed");
1428 *baudrate = get_termios_speed(data);
1435 static enum sp_return set_baudrate(int fd, int baudrate)
1439 TRACE("%d, %d", fd, baudrate);
1441 DEBUG("Getting baud rate");
1443 if (!(data = malloc(get_termios_size())))
1444 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1446 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1448 RETURN_FAIL("getting termios failed");
1451 DEBUG("Setting baud rate");
1453 set_termios_speed(data, baudrate);
1455 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1457 RETURN_FAIL("setting termios failed");
1464 #endif /* USE_TERMIOS_SPEED */
1467 static enum sp_return get_flow(int fd, struct port_data *data)
1471 TRACE("%d, %p", fd, data);
1473 DEBUG("Getting advanced flow control");
1475 if (!(termx = malloc(get_termiox_size())))
1476 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1478 if (ioctl(fd, TCGETX, termx) < 0) {
1480 RETURN_FAIL("getting termiox failed");
1483 get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1484 &data->dtr_flow, &data->dsr_flow);
1491 static enum sp_return set_flow(int fd, struct port_data *data)
1495 TRACE("%d, %p", fd, data);
1497 DEBUG("Getting advanced flow control");
1499 if (!(termx = malloc(get_termiox_size())))
1500 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1502 if (ioctl(fd, TCGETX, termx) < 0) {
1504 RETURN_FAIL("getting termiox failed");
1507 DEBUG("Setting advanced flow control");
1509 set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1510 data->dtr_flow, data->dsr_flow);
1512 if (ioctl(fd, TCSETX, termx) < 0) {
1514 RETURN_FAIL("setting termiox failed");
1521 #endif /* USE_TERMIOX */
1523 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1524 struct sp_port_config *config)
1528 TRACE("%p, %p, %p", port, data, config);
1530 DEBUG("Getting configuration for port %s", port->name);
1533 if (!GetCommState(port->hdl, &data->dcb))
1534 RETURN_FAIL("GetCommState() failed");
1536 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1537 if (data->dcb.BaudRate == std_baudrates[i].index) {
1538 config->baudrate = std_baudrates[i].value;
1543 if (i == NUM_STD_BAUDRATES)
1544 /* BaudRate field can be either an index or a custom baud rate. */
1545 config->baudrate = data->dcb.BaudRate;
1547 config->bits = data->dcb.ByteSize;
1549 if (data->dcb.fParity)
1550 switch (data->dcb.Parity) {
1552 config->parity = SP_PARITY_NONE;
1555 config->parity = SP_PARITY_ODD;
1558 config->parity = SP_PARITY_EVEN;
1561 config->parity = SP_PARITY_MARK;
1564 config->parity = SP_PARITY_SPACE;
1567 config->parity = -1;
1570 config->parity = SP_PARITY_NONE;
1572 switch (data->dcb.StopBits) {
1574 config->stopbits = 1;
1577 config->stopbits = 2;
1580 config->stopbits = -1;
1583 switch (data->dcb.fRtsControl) {
1584 case RTS_CONTROL_DISABLE:
1585 config->rts = SP_RTS_OFF;
1587 case RTS_CONTROL_ENABLE:
1588 config->rts = SP_RTS_ON;
1590 case RTS_CONTROL_HANDSHAKE:
1591 config->rts = SP_RTS_FLOW_CONTROL;
1597 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1599 switch (data->dcb.fDtrControl) {
1600 case DTR_CONTROL_DISABLE:
1601 config->dtr = SP_DTR_OFF;
1603 case DTR_CONTROL_ENABLE:
1604 config->dtr = SP_DTR_ON;
1606 case DTR_CONTROL_HANDSHAKE:
1607 config->dtr = SP_DTR_FLOW_CONTROL;
1613 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1615 if (data->dcb.fInX) {
1616 if (data->dcb.fOutX)
1617 config->xon_xoff = SP_XONXOFF_INOUT;
1619 config->xon_xoff = SP_XONXOFF_IN;
1621 if (data->dcb.fOutX)
1622 config->xon_xoff = SP_XONXOFF_OUT;
1624 config->xon_xoff = SP_XONXOFF_DISABLED;
1629 if (tcgetattr(port->fd, &data->term) < 0)
1630 RETURN_FAIL("tcgetattr() failed");
1632 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1633 RETURN_FAIL("TIOCMGET ioctl failed");
1636 int ret = get_flow(port->fd, data);
1638 if (ret == SP_ERR_FAIL && errno == EINVAL)
1639 data->termiox_supported = 0;
1641 RETURN_CODEVAL(ret);
1643 data->termiox_supported = 1;
1645 data->termiox_supported = 0;
1648 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1649 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1650 config->baudrate = std_baudrates[i].value;
1655 if (i == NUM_STD_BAUDRATES) {
1657 config->baudrate = (int)data->term.c_ispeed;
1658 #elif defined(USE_TERMIOS_SPEED)
1659 TRY(get_baudrate(port->fd, &config->baudrate));
1661 config->baudrate = -1;
1665 switch (data->term.c_cflag & CSIZE) {
1682 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1683 config->parity = SP_PARITY_NONE;
1684 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1685 config->parity = -1;
1687 else if (data->term.c_cflag & CMSPAR)
1688 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1691 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1693 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1695 if (data->term.c_cflag & CRTSCTS) {
1696 config->rts = SP_RTS_FLOW_CONTROL;
1697 config->cts = SP_CTS_FLOW_CONTROL;
1699 if (data->termiox_supported && data->rts_flow)
1700 config->rts = SP_RTS_FLOW_CONTROL;
1702 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1704 config->cts = (data->termiox_supported && data->cts_flow) ?
1705 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1708 if (data->termiox_supported && data->dtr_flow)
1709 config->dtr = SP_DTR_FLOW_CONTROL;
1711 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1713 config->dsr = (data->termiox_supported && data->dsr_flow) ?
1714 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1716 if (data->term.c_iflag & IXOFF) {
1717 if (data->term.c_iflag & IXON)
1718 config->xon_xoff = SP_XONXOFF_INOUT;
1720 config->xon_xoff = SP_XONXOFF_IN;
1722 if (data->term.c_iflag & IXON)
1723 config->xon_xoff = SP_XONXOFF_OUT;
1725 config->xon_xoff = SP_XONXOFF_DISABLED;
1732 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1733 const struct sp_port_config *config)
1737 BAUD_TYPE baud_nonstd;
1741 #ifdef USE_TERMIOS_SPEED
1742 int baud_nonstd = 0;
1745 TRACE("%p, %p, %p", port, data, config);
1747 DEBUG("Setting configuration for port %s", port->name);
1750 if (config->baudrate >= 0) {
1751 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1752 if (config->baudrate == std_baudrates[i].value) {
1753 data->dcb.BaudRate = std_baudrates[i].index;
1758 if (i == NUM_STD_BAUDRATES)
1759 data->dcb.BaudRate = config->baudrate;
1762 if (config->bits >= 0)
1763 data->dcb.ByteSize = config->bits;
1765 if (config->parity >= 0) {
1766 switch (config->parity) {
1767 case SP_PARITY_NONE:
1768 data->dcb.Parity = NOPARITY;
1771 data->dcb.Parity = ODDPARITY;
1773 case SP_PARITY_EVEN:
1774 data->dcb.Parity = EVENPARITY;
1776 case SP_PARITY_MARK:
1777 data->dcb.Parity = MARKPARITY;
1779 case SP_PARITY_SPACE:
1780 data->dcb.Parity = SPACEPARITY;
1783 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1787 if (config->stopbits >= 0) {
1788 switch (config->stopbits) {
1789 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1791 data->dcb.StopBits = ONESTOPBIT;
1794 data->dcb.StopBits = TWOSTOPBITS;
1797 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1801 if (config->rts >= 0) {
1802 switch (config->rts) {
1804 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1807 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1809 case SP_RTS_FLOW_CONTROL:
1810 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1813 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1817 if (config->cts >= 0) {
1818 switch (config->cts) {
1820 data->dcb.fOutxCtsFlow = FALSE;
1822 case SP_CTS_FLOW_CONTROL:
1823 data->dcb.fOutxCtsFlow = TRUE;
1826 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1830 if (config->dtr >= 0) {
1831 switch (config->dtr) {
1833 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1836 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1838 case SP_DTR_FLOW_CONTROL:
1839 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1842 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1846 if (config->dsr >= 0) {
1847 switch (config->dsr) {
1849 data->dcb.fOutxDsrFlow = FALSE;
1851 case SP_DSR_FLOW_CONTROL:
1852 data->dcb.fOutxDsrFlow = TRUE;
1855 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1859 if (config->xon_xoff >= 0) {
1860 switch (config->xon_xoff) {
1861 case SP_XONXOFF_DISABLED:
1862 data->dcb.fInX = FALSE;
1863 data->dcb.fOutX = FALSE;
1866 data->dcb.fInX = TRUE;
1867 data->dcb.fOutX = FALSE;
1869 case SP_XONXOFF_OUT:
1870 data->dcb.fInX = FALSE;
1871 data->dcb.fOutX = TRUE;
1873 case SP_XONXOFF_INOUT:
1874 data->dcb.fInX = TRUE;
1875 data->dcb.fOutX = TRUE;
1878 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1882 if (!SetCommState(port->hdl, &data->dcb))
1883 RETURN_FAIL("SetCommState() failed");
1889 if (config->baudrate >= 0) {
1890 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1891 if (config->baudrate == std_baudrates[i].value) {
1892 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1893 RETURN_FAIL("cfsetospeed() failed");
1895 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1896 RETURN_FAIL("cfsetispeed() failed");
1901 /* Non-standard baud rate */
1902 if (i == NUM_STD_BAUDRATES) {
1904 /* Set "dummy" baud rate. */
1905 if (cfsetspeed(&data->term, B9600) < 0)
1906 RETURN_FAIL("cfsetspeed() failed");
1907 baud_nonstd = config->baudrate;
1908 #elif defined(USE_TERMIOS_SPEED)
1911 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1916 if (config->bits >= 0) {
1917 data->term.c_cflag &= ~CSIZE;
1918 switch (config->bits) {
1920 data->term.c_cflag |= CS8;
1923 data->term.c_cflag |= CS7;
1926 data->term.c_cflag |= CS6;
1929 data->term.c_cflag |= CS5;
1932 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1936 if (config->parity >= 0) {
1937 data->term.c_iflag &= ~IGNPAR;
1938 data->term.c_cflag &= ~(PARENB | PARODD);
1940 data->term.c_cflag &= ~CMSPAR;
1942 switch (config->parity) {
1943 case SP_PARITY_NONE:
1944 data->term.c_iflag |= IGNPAR;
1946 case SP_PARITY_EVEN:
1947 data->term.c_cflag |= PARENB;
1950 data->term.c_cflag |= PARENB | PARODD;
1953 case SP_PARITY_MARK:
1954 data->term.c_cflag |= PARENB | PARODD;
1955 data->term.c_cflag |= CMSPAR;
1957 case SP_PARITY_SPACE:
1958 data->term.c_cflag |= PARENB;
1959 data->term.c_cflag |= CMSPAR;
1962 case SP_PARITY_MARK:
1963 case SP_PARITY_SPACE:
1964 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1967 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1971 if (config->stopbits >= 0) {
1972 data->term.c_cflag &= ~CSTOPB;
1973 switch (config->stopbits) {
1975 data->term.c_cflag &= ~CSTOPB;
1978 data->term.c_cflag |= CSTOPB;
1981 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1985 if (config->rts >= 0 || config->cts >= 0) {
1986 if (data->termiox_supported) {
1987 data->rts_flow = data->cts_flow = 0;
1988 switch (config->rts) {
1991 controlbits = TIOCM_RTS;
1992 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1993 RETURN_FAIL("Setting RTS signal level failed");
1995 case SP_RTS_FLOW_CONTROL:
2001 if (config->cts == SP_CTS_FLOW_CONTROL)
2004 if (data->rts_flow && data->cts_flow)
2005 data->term.c_iflag |= CRTSCTS;
2007 data->term.c_iflag &= ~CRTSCTS;
2009 /* Asymmetric use of RTS/CTS not supported. */
2010 if (data->term.c_iflag & CRTSCTS) {
2011 /* Flow control can only be disabled for both RTS & CTS together. */
2012 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
2013 if (config->cts != SP_CTS_IGNORE)
2014 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2016 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
2017 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
2018 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
2021 /* Flow control can only be enabled for both RTS & CTS together. */
2022 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
2023 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
2024 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
2027 if (config->rts >= 0) {
2028 if (config->rts == SP_RTS_FLOW_CONTROL) {
2029 data->term.c_iflag |= CRTSCTS;
2031 controlbits = TIOCM_RTS;
2032 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
2034 RETURN_FAIL("Setting RTS signal level failed");
2040 if (config->dtr >= 0 || config->dsr >= 0) {
2041 if (data->termiox_supported) {
2042 data->dtr_flow = data->dsr_flow = 0;
2043 switch (config->dtr) {
2046 controlbits = TIOCM_DTR;
2047 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
2048 RETURN_FAIL("Setting DTR signal level failed");
2050 case SP_DTR_FLOW_CONTROL:
2056 if (config->dsr == SP_DSR_FLOW_CONTROL)
2059 /* DTR/DSR flow control not supported. */
2060 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
2061 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
2063 if (config->dtr >= 0) {
2064 controlbits = TIOCM_DTR;
2065 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
2067 RETURN_FAIL("Setting DTR signal level failed");
2072 if (config->xon_xoff >= 0) {
2073 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
2074 switch (config->xon_xoff) {
2075 case SP_XONXOFF_DISABLED:
2078 data->term.c_iflag |= IXOFF;
2080 case SP_XONXOFF_OUT:
2081 data->term.c_iflag |= IXON | IXANY;
2083 case SP_XONXOFF_INOUT:
2084 data->term.c_iflag |= IXON | IXOFF | IXANY;
2087 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2091 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2092 RETURN_FAIL("tcsetattr() failed");
2095 if (baud_nonstd != B0) {
2096 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2097 RETURN_FAIL("IOSSIOSPEED ioctl failed");
2098 /* Set baud rates in data->term to correct, but incompatible
2099 * with tcsetattr() value, same as delivered by tcgetattr(). */
2100 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2101 RETURN_FAIL("cfsetspeed() failed");
2103 #elif defined(__linux__)
2104 #ifdef USE_TERMIOS_SPEED
2106 TRY(set_baudrate(port->fd, config->baudrate));
2109 if (data->termiox_supported)
2110 TRY(set_flow(port->fd, data));
2114 #endif /* !_WIN32 */
2119 enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2121 struct sp_port_config *config;
2123 TRACE("%p", config_ptr);
2126 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2130 if (!(config = malloc(sizeof(struct sp_port_config))))
2131 RETURN_ERROR(SP_ERR_MEM, "config malloc failed");
2133 config->baudrate = -1;
2135 config->parity = -1;
2136 config->stopbits = -1;
2142 *config_ptr = config;
2147 void sp_free_config(struct sp_port_config *config)
2149 TRACE("%p", config);
2152 DEBUG("Null config");
2159 enum sp_return sp_get_config(struct sp_port *port, struct sp_port_config *config)
2161 struct port_data data;
2163 TRACE("%p, %p", port, config);
2168 RETURN_ERROR(SP_ERR_ARG, "Null config");
2170 TRY(get_config(port, &data, config));
2175 enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
2177 struct port_data data;
2178 struct sp_port_config prev_config;
2180 TRACE("%p, %p", port, config);
2185 RETURN_ERROR(SP_ERR_ARG, "Null config");
2187 TRY(get_config(port, &data, &prev_config));
2188 TRY(set_config(port, &data, config));
2193 #define CREATE_ACCESSORS(x, type) \
2194 enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2195 struct port_data data; \
2196 struct sp_port_config config; \
2197 TRACE("%p, %d", port, x); \
2198 CHECK_OPEN_PORT(); \
2199 TRY(get_config(port, &data, &config)); \
2201 TRY(set_config(port, &data, &config)); \
2204 enum sp_return sp_get_config_##x(const struct sp_port_config *config, type *x) { \
2205 TRACE("%p, %p", config, x); \
2207 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2211 enum sp_return sp_set_config_##x(struct sp_port_config *config, type x) { \
2212 TRACE("%p, %d", config, x); \
2214 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2219 CREATE_ACCESSORS(baudrate, int)
2220 CREATE_ACCESSORS(bits, int)
2221 CREATE_ACCESSORS(parity, enum sp_parity)
2222 CREATE_ACCESSORS(stopbits, int)
2223 CREATE_ACCESSORS(rts, enum sp_rts)
2224 CREATE_ACCESSORS(cts, enum sp_cts)
2225 CREATE_ACCESSORS(dtr, enum sp_dtr)
2226 CREATE_ACCESSORS(dsr, enum sp_dsr)
2227 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2229 enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config, enum sp_flowcontrol flowcontrol)
2232 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2234 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2235 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2237 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2238 config->xon_xoff = SP_XONXOFF_INOUT;
2240 config->xon_xoff = SP_XONXOFF_DISABLED;
2242 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2243 config->rts = SP_RTS_FLOW_CONTROL;
2244 config->cts = SP_CTS_FLOW_CONTROL;
2246 if (config->rts == SP_RTS_FLOW_CONTROL)
2247 config->rts = SP_RTS_ON;
2248 config->cts = SP_CTS_IGNORE;
2251 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2252 config->dtr = SP_DTR_FLOW_CONTROL;
2253 config->dsr = SP_DSR_FLOW_CONTROL;
2255 if (config->dtr == SP_DTR_FLOW_CONTROL)
2256 config->dtr = SP_DTR_ON;
2257 config->dsr = SP_DSR_IGNORE;
2263 enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
2265 struct port_data data;
2266 struct sp_port_config config;
2268 TRACE("%p, %d", port, flowcontrol);
2272 TRY(get_config(port, &data, &config));
2274 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2276 TRY(set_config(port, &data, &config));
2281 enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
2283 TRACE("%p, %p", port, signals);
2288 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2290 DEBUG("Getting control signals for port %s", port->name);
2295 if (GetCommModemStatus(port->hdl, &bits) == 0)
2296 RETURN_FAIL("GetCommModemStatus() failed");
2297 if (bits & MS_CTS_ON)
2298 *signals |= SP_SIG_CTS;
2299 if (bits & MS_DSR_ON)
2300 *signals |= SP_SIG_DSR;
2301 if (bits & MS_RLSD_ON)
2302 *signals |= SP_SIG_DCD;
2303 if (bits & MS_RING_ON)
2304 *signals |= SP_SIG_RI;
2307 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2308 RETURN_FAIL("TIOCMGET ioctl failed");
2309 if (bits & TIOCM_CTS)
2310 *signals |= SP_SIG_CTS;
2311 if (bits & TIOCM_DSR)
2312 *signals |= SP_SIG_DSR;
2313 if (bits & TIOCM_CAR)
2314 *signals |= SP_SIG_DCD;
2315 if (bits & TIOCM_RNG)
2316 *signals |= SP_SIG_RI;
2321 enum sp_return sp_start_break(struct sp_port *port)
2327 if (SetCommBreak(port->hdl) == 0)
2328 RETURN_FAIL("SetCommBreak() failed");
2330 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2331 RETURN_FAIL("TIOCSBRK ioctl failed");
2337 enum sp_return sp_end_break(struct sp_port *port)
2343 if (ClearCommBreak(port->hdl) == 0)
2344 RETURN_FAIL("ClearCommBreak() failed");
2346 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2347 RETURN_FAIL("TIOCCBRK ioctl failed");
2353 int sp_last_error_code(void)
2357 RETURN_VALUE("%d", GetLastError());
2359 RETURN_VALUE("%d", errno);
2363 char *sp_last_error_message(void)
2369 DWORD error = GetLastError();
2372 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2373 FORMAT_MESSAGE_FROM_SYSTEM |
2374 FORMAT_MESSAGE_IGNORE_INSERTS,
2377 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2381 RETURN_VALUE("%s", message);
2383 RETURN_VALUE("%s", strerror(errno));
2387 void sp_free_error_message(char *message)
2389 TRACE("%s", message);
2400 void sp_set_debug_handler(void (*handler)(const char *format, ...))
2402 TRACE("%p", handler);
2404 sp_debug_handler = handler;
2409 void sp_default_debug_handler(const char *format, ...)
2412 va_start(args, format);
2413 if (getenv("LIBSERIALPORT_DEBUG")) {
2414 fputs("sp: ", stderr);
2415 vfprintf(stderr, format, args);
2420 int sp_get_major_package_version(void)
2422 return SP_PACKAGE_VERSION_MAJOR;
2425 int sp_get_minor_package_version(void)
2427 return SP_PACKAGE_VERSION_MINOR;
2430 int sp_get_micro_package_version(void)
2432 return SP_PACKAGE_VERSION_MICRO;
2435 const char *sp_get_package_version_string(void)
2437 return SP_PACKAGE_VERSION_STRING;
2440 int sp_get_current_lib_version(void)
2442 return SP_LIB_VERSION_CURRENT;
2445 int sp_get_revision_lib_version(void)
2447 return SP_LIB_VERSION_REVISION;
2450 int sp_get_age_lib_version(void)
2452 return SP_LIB_VERSION_AGE;
2455 const char *sp_get_lib_version_string(void)
2457 return SP_LIB_VERSION_STRING;