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>
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Lesser General Public License as
10 * published by the Free Software Foundation, either version 3 of the
11 * License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include <sys/types.h>
35 #include <sys/ioctl.h>
38 #include <IOKit/IOKitLib.h>
39 #include <IOKit/serial/IOSerialKeys.h>
40 #include <sys/syslimits.h>
44 #include "linux/serial.h"
47 #include "libserialport.h"
58 /* Standard baud rates. */
60 #define BAUD_TYPE DWORD
61 #define BAUD(n) {CBR_##n, n}
63 #define BAUD_TYPE speed_t
64 #define BAUD(n) {B##n, n}
72 const struct std_baudrate std_baudrates[] = {
75 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
76 * have documented CBR_* macros.
78 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
79 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
80 BAUD(115200), BAUD(128000), BAUD(256000)
82 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200), BAUD(300),
83 BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800), BAUD(9600),
84 BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200), BAUD(230400),
85 #if !defined(__APPLE__) && !defined(__OpenBSD__)
91 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
92 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
94 /* Helper functions for configuring ports. */
95 static int get_config(struct sp_port *port, struct sp_port_data *data, struct sp_port_config *config);
96 static int set_config(struct sp_port *port, struct sp_port_data *data, struct sp_port_config *config);
98 int sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
100 struct sp_port *port;
111 if (!(port = malloc(sizeof(struct sp_port))))
114 len = strlen(portname) + 1;
116 if (!(port->name = malloc(len)))
122 memcpy(port->name, portname, len);
129 int sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
136 if (!port || !port->name)
139 return sp_get_port_by_name(port->name, copy_ptr);
142 void sp_free_port(struct sp_port *port)
153 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
158 for (count = 0; list[count]; count++);
159 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
162 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
164 list[count + 1] = NULL;
168 sp_free_port_list(list);
172 int sp_list_ports(struct sp_port ***list_ptr)
174 struct sp_port **list;
177 if (!(list = malloc(sizeof(struct sp_port **))))
185 DWORD max_value_len, max_data_size, max_data_len;
186 DWORD value_len, data_size, data_len;
187 DWORD type, index = 0;
191 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
192 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
197 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
198 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
203 max_data_len = max_data_size / sizeof(TCHAR);
204 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
209 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
215 value_len = max_value_len + 1,
216 data_size = max_data_size,
217 RegEnumValue(key, index, value, &value_len,
218 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
220 data_len = data_size / sizeof(TCHAR);
221 data[data_len] = '\0';
223 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
225 name_len = data_len + 1;
227 if (!(name = malloc(name_len)))
233 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
237 if (type == REG_SZ && !(list = sp_list_append(list, name)))
254 CFMutableDictionaryRef classes;
261 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
267 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
273 CFDictionarySetValue(classes,
274 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
276 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS)
282 if (!(path = malloc(PATH_MAX)))
288 while ((port = IOIteratorNext(iter))) {
289 cf_path = IORegistryEntryCreateCFProperty(port,
290 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
292 result = CFStringGetCString(cf_path,
293 path, PATH_MAX, kCFStringEncodingASCII);
295 if (result && !(list = sp_list_append(list, path)))
298 IOObjectRelease(port);
302 IOObjectRelease(port);
307 IOObjectRelease(iter);
312 struct udev_enumerate *ud_enumerate;
313 struct udev_list_entry *ud_list;
314 struct udev_list_entry *ud_entry;
316 struct udev_device *ud_dev, *ud_parent;
319 int fd, ioctl_result;
320 struct serial_struct serial_info;
323 ud_enumerate = udev_enumerate_new(ud);
324 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
325 udev_enumerate_scan_devices(ud_enumerate);
326 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
327 udev_list_entry_foreach(ud_entry, ud_list)
329 path = udev_list_entry_get_name(ud_entry);
330 ud_dev = udev_device_new_from_syspath(ud, path);
331 /* If there is no parent device, this is a virtual tty. */
332 ud_parent = udev_device_get_parent(ud_dev);
333 if (ud_parent == NULL)
335 udev_device_unref(ud_dev);
338 name = udev_device_get_devnode(ud_dev);
339 /* The serial8250 driver has a hardcoded number of ports.
340 * The only way to tell which actually exist on a given system
341 * is to try to open them and make an ioctl call. */
342 driver = udev_device_get_driver(ud_parent);
343 if (driver && !strcmp(driver, "serial8250"))
345 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
347 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
349 if (ioctl_result != 0)
351 if (serial_info.type == PORT_UNKNOWN)
354 list = sp_list_append(list, name);
356 udev_device_unref(ud_dev);
364 udev_enumerate_unref(ud_enumerate);
375 sp_free_port_list(list);
383 void sp_free_port_list(struct sp_port **list)
387 for (i = 0; list[i]; i++)
388 sp_free_port(list[i]);
392 static int sp_validate_port(struct sp_port *port)
397 if (port->hdl == INVALID_HANDLE_VALUE)
406 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
408 int sp_open(struct sp_port *port, int flags)
414 DWORD desired_access = 0, flags_and_attributes = 0;
415 char *escaped_port_name;
417 /* Prefix port name with '\\.\' to work with ports above COM9. */
418 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
420 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
422 /* Map 'flags' to the OS-specific settings. */
423 desired_access |= GENERIC_READ;
424 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
425 if (flags & SP_MODE_RDWR)
426 desired_access |= GENERIC_WRITE;
427 if (flags & SP_MODE_NONBLOCK)
428 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
430 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
431 OPEN_EXISTING, flags_and_attributes, 0);
433 free(escaped_port_name);
435 if (port->hdl == INVALID_HANDLE_VALUE)
439 struct sp_port_data data;
440 struct sp_port_config config;
443 /* Map 'flags' to the OS-specific settings. */
444 if (flags & SP_MODE_RDWR)
445 flags_local |= O_RDWR;
446 if (flags & SP_MODE_RDONLY)
447 flags_local |= O_RDONLY;
448 if (flags & SP_MODE_NONBLOCK)
449 flags_local |= O_NONBLOCK;
451 if ((port->fd = open(port->name, flags_local)) < 0)
454 ret = get_config(port, &data, &config);
462 /* Turn off all serial port cooking. */
463 data.term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
464 data.term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
465 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
466 data.term.c_oflag &= ~OFILL;
468 /* Disable canonical mode, and don't echo input characters. */
469 data.term.c_lflag &= ~(ICANON | ECHO);
471 /* Ignore modem status lines; enable receiver */
472 data.term.c_cflag |= (CLOCAL | CREAD);
474 ret = set_config(port, &data, &config);
486 int sp_close(struct sp_port *port)
491 /* Returns non-zero upon success, 0 upon failure. */
492 if (CloseHandle(port->hdl) == 0)
495 /* Returns 0 upon success, -1 upon failure. */
496 if (close(port->fd) == -1)
503 int sp_flush(struct sp_port *port)
508 /* Returns non-zero upon success, 0 upon failure. */
509 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
512 /* Returns 0 upon success, -1 upon failure. */
513 if (tcflush(port->fd, TCIOFLUSH) < 0)
519 int sp_write(struct sp_port *port, const void *buf, size_t count)
529 /* Returns non-zero upon success, 0 upon failure. */
530 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
534 /* Returns the number of bytes written, or -1 upon failure. */
535 ssize_t written = write(port->fd, buf, count);
544 int sp_read(struct sp_port *port, void *buf, size_t count)
552 DWORD bytes_read = 0;
554 /* Returns non-zero upon success, 0 upon failure. */
555 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
561 /* Returns the number of bytes read, or -1 upon failure. */
562 if ((bytes_read = read(port->fd, buf, count)) < 0)
568 static int get_config(struct sp_port *port, struct sp_port_data *data, struct sp_port_config *config)
573 if (!GetCommState(port->hdl, &data->dcb))
576 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
577 if (data->dcb.BaudRate == std_baudrates[i].index) {
578 config->baudrate = std_baudrates[i].value;
583 if (i == NUM_STD_BAUDRATES)
584 /* BaudRate field can be either an index or a custom baud rate. */
585 config->baudrate = data->dcb.BaudRate;
587 config->bits = data->dcb.ByteSize;
589 if (data->dcb.fParity)
590 switch (data->dcb.Parity) {
592 config->parity = SP_PARITY_NONE;
595 config->parity = SP_PARITY_EVEN;
598 config->parity = SP_PARITY_ODD;
604 config->parity = SP_PARITY_NONE;
606 switch (data->dcb.StopBits) {
608 config->stopbits = 1;
611 config->stopbits = 2;
614 config->stopbits = -1;
617 switch (data->dcb.fRtsControl) {
618 case RTS_CONTROL_DISABLE:
619 config->rts = SP_RTS_OFF;
621 case RTS_CONTROL_ENABLE:
622 config->rts = SP_RTS_ON;
624 case RTS_CONTROL_HANDSHAKE:
625 config->rts = SP_RTS_FLOW_CONTROL;
631 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
633 switch (data->dcb.fDtrControl) {
634 case DTR_CONTROL_DISABLE:
635 config->dtr = SP_DTR_OFF;
637 case DTR_CONTROL_ENABLE:
638 config->dtr = SP_DTR_ON;
640 case DTR_CONTROL_HANDSHAKE:
641 config->dtr = SP_DTR_FLOW_CONTROL;
647 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
651 if (tcgetattr(port->fd, &data->term) < 0)
654 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
656 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
657 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
658 config->baudrate = std_baudrates[i].value;
663 if (i == NUM_STD_BAUDRATES)
664 config->baudrate = -1;
666 switch (data->term.c_cflag & CSIZE) {
683 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
684 config->parity = SP_PARITY_NONE;
685 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
688 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
690 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
692 if (data->term.c_cflag & CRTSCTS) {
693 config->rts = SP_RTS_FLOW_CONTROL;
694 config->cts = SP_CTS_FLOW_CONTROL;
696 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
697 config->cts = SP_CTS_IGNORE;
700 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
701 config->dsr = SP_DSR_IGNORE;
707 static int set_config(struct sp_port *port, struct sp_port_data *data, struct sp_port_config *config)
712 if (config->baudrate >= 0)
714 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
715 if (config->baudrate == std_baudrates[i].value) {
716 data->dcb.BaudRate = std_baudrates[i].index;
721 if (i == NUM_STD_BAUDRATES)
722 data->dcb.BaudRate = config->baudrate;
725 if (config->bits >= 0)
726 data->dcb.ByteSize = config->bits;
728 if (config->parity >= 0) {
729 switch (config->parity) {
730 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
732 data->dcb.Parity = NOPARITY;
735 data->dcb.Parity = EVENPARITY;
738 data->dcb.Parity = ODDPARITY;
745 if (config->stopbits >= 0) {
746 switch (config->stopbits) {
747 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
749 data->dcb.StopBits = ONESTOPBIT;
752 data->dcb.StopBits = TWOSTOPBITS;
759 if (config->rts >= 0) {
760 switch (config->rts) {
762 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
765 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
767 case SP_RTS_FLOW_CONTROL:
768 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
775 if (config->cts >= 0) {
776 switch (config->cts) {
778 data->dcb.fOutxCtsFlow = FALSE;
780 case SP_CTS_FLOW_CONTROL:
781 data->dcb.fOutxCtsFlow = TRUE;
788 if (config->dtr >= 0) {
789 switch (config->dtr) {
791 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
794 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
796 case SP_DTR_FLOW_CONTROL:
797 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
804 if (config->dsr >= 0) {
805 switch (config->dsr) {
807 data->dcb.fOutxDsrFlow = FALSE;
809 case SP_DSR_FLOW_CONTROL:
810 data->dcb.fOutxDsrFlow = TRUE;
817 if (config->xon_xoff >= 0) {
818 switch (config->xon_xoff) {
819 case SP_XONXOFF_DISABLED:
820 data->dcb.fInX = FALSE;
821 data->dcb.fOutX = FALSE;
824 data->dcb.fInX = TRUE;
825 data->dcb.fOutX = FALSE;
828 data->dcb.fInX = FALSE;
829 data->dcb.fOutX = TRUE;
831 case SP_XONXOFF_INOUT:
832 data->dcb.fInX = TRUE;
833 data->dcb.fOutX = TRUE;
840 if (!SetCommState(port->hdl, &data->dcb))
845 if (config->baudrate >= 0)
847 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
848 if (config->baudrate == std_baudrates[i].value) {
849 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
852 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
858 if (i == NUM_STD_BAUDRATES)
862 if (config->bits >= 0) {
863 data->term.c_cflag &= ~CSIZE;
864 switch (config->bits) {
866 data->term.c_cflag |= CS8;
869 data->term.c_cflag |= CS7;
872 data->term.c_cflag |= CS6;
879 if (config->parity >= 0) {
880 data->term.c_iflag &= ~IGNPAR;
881 data->term.c_cflag &= ~(PARENB | PARODD);
882 switch (config->parity) {
884 data->term.c_iflag |= IGNPAR;
887 data->term.c_cflag |= PARENB;
890 data->term.c_cflag |= PARENB | PARODD;
897 if (config->stopbits >= 0) {
898 data->term.c_cflag &= ~CSTOPB;
899 switch (config->stopbits) {
901 data->term.c_cflag &= ~CSTOPB;
904 data->term.c_cflag |= CSTOPB;
911 if (config->rts >= 0 || config->cts >= 0)
913 /* Asymmetric use of RTS/CTS not supported yet. */
915 if (data->term.c_iflag & CRTSCTS) {
916 /* Flow control can only be disabled for both RTS & CTS together. */
917 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
918 if (config->cts != SP_CTS_IGNORE)
921 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
922 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
926 /* Flow control can only be enabled for both RTS & CTS together. */
927 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
928 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
932 if (config->rts >= 0) {
933 if (config->rts == SP_RTS_FLOW_CONTROL) {
934 data->term.c_iflag |= CRTSCTS;
936 int controlbits = TIOCM_RTS;
937 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
944 if (config->dtr >= 0 || config->dsr >= 0)
946 /* DTR/DSR flow control not supported yet. */
947 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
950 if (config->dtr >= 0) {
951 int controlbits = TIOCM_DTR;
952 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
958 if (config->xon_xoff >= 0) {
959 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
960 switch (config->xon_xoff) {
961 case SP_XONXOFF_DISABLED:
964 data->term.c_iflag |= IXOFF;
967 data->term.c_iflag |= IXON | IXANY;
969 case SP_XONXOFF_INOUT:
970 data->term.c_iflag |= IXON | IXOFF | IXANY;
977 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
984 #define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
986 int sp_set_config(struct sp_port *port, struct sp_port_config *config)
988 struct sp_port_data data;
989 struct sp_port_config prev_config;
991 TRY(get_config(port, &data, &prev_config));
992 TRY(set_config(port, &data, config));
997 #define CREATE_SETTER(x) int sp_set_##x(struct sp_port *port, int x) { \
998 struct sp_port_data data; \
999 struct sp_port_config config; \
1000 TRY(get_config(port, &data, &config)); \
1002 TRY(set_config(port, &data, &config)); \
1006 CREATE_SETTER(baudrate)
1008 CREATE_SETTER(parity)
1009 CREATE_SETTER(stopbits)
1014 CREATE_SETTER(xon_xoff)
1016 int sp_set_flowcontrol(struct sp_port *port, int flowcontrol)
1018 struct sp_port_data data;
1019 struct sp_port_config config;
1021 TRY(get_config(port, &data, &config));
1023 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
1024 config.xon_xoff = SP_XONXOFF_INOUT;
1026 config.xon_xoff = SP_XONXOFF_DISABLED;
1028 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
1029 config.rts = SP_RTS_FLOW_CONTROL;
1030 config.cts = SP_CTS_FLOW_CONTROL;
1032 if (config.rts == SP_RTS_FLOW_CONTROL)
1033 config.rts = SP_RTS_ON;
1034 config.cts = SP_CTS_IGNORE;
1037 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
1038 config.dtr = SP_DTR_FLOW_CONTROL;
1039 config.dsr = SP_DSR_FLOW_CONTROL;
1041 if (config.dtr == SP_DTR_FLOW_CONTROL)
1042 config.dtr = SP_DTR_ON;
1043 config.dsr = SP_DSR_IGNORE;
1046 TRY(set_config(port, &data, &config));
1051 int sp_last_error_code(void)
1054 return GetLastError();
1060 char *sp_last_error_message(void)
1064 DWORD error = GetLastError();
1067 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1068 FORMAT_MESSAGE_FROM_SYSTEM |
1069 FORMAT_MESSAGE_IGNORE_INSERTS,
1072 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1078 return strerror(errno);
1082 void sp_free_error_message(char *message)