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"
62 /* Helper functions for configuring ports. */
63 static int start_config(struct sp_port *port, struct sp_port_data *data);
64 static int set_baudrate(struct sp_port_data *data, int baudrate);
65 static int set_bits(struct sp_port_data *data, int bits);
66 static int set_parity(struct sp_port_data *data, int parity);
67 static int set_stopbits(struct sp_port_data *data, int stopbits);
68 static int set_rts(struct sp_port_data *data, int rts);
69 static int set_cts(struct sp_port_data *data, int cts);
70 static int set_dtr(struct sp_port_data *data, int dtr);
71 static int set_dsr(struct sp_port_data *data, int dsr);
72 static int set_xon_xoff(struct sp_port_data *data, int xon_xoff);
73 static int apply_config(struct sp_port *port, struct sp_port_data *data);
75 int sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
88 if (!(port = malloc(sizeof(struct sp_port))))
91 len = strlen(portname) + 1;
93 if (!(port->name = malloc(len)))
99 memcpy(port->name, portname, len);
106 int sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
113 if (!port || !port->name)
116 return sp_get_port_by_name(port->name, copy_ptr);
119 void sp_free_port(struct sp_port *port)
130 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
135 for (count = 0; list[count]; count++);
136 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
139 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
141 list[count + 1] = NULL;
145 sp_free_port_list(list);
149 int sp_list_ports(struct sp_port ***list_ptr)
151 struct sp_port **list;
154 if (!(list = malloc(sizeof(struct sp_port **))))
162 DWORD max_value_len, max_data_size, max_data_len;
163 DWORD value_len, data_size, data_len;
164 DWORD type, index = 0;
168 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
169 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
174 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
175 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
180 max_data_len = max_data_size / sizeof(TCHAR);
181 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
186 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
192 value_len = max_value_len + 1,
193 data_size = max_data_size,
194 RegEnumValue(key, index, value, &value_len,
195 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
197 data_len = data_size / sizeof(TCHAR);
198 data[data_len] = '\0';
200 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
202 name_len = data_len + 1;
204 if (!(name = malloc(name_len)))
210 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
214 if (type == REG_SZ && !(list = sp_list_append(list, name)))
231 CFMutableDictionaryRef classes;
238 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
244 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
250 CFDictionarySetValue(classes,
251 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
253 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS)
259 if (!(path = malloc(PATH_MAX)))
265 while ((port = IOIteratorNext(iter))) {
266 cf_path = IORegistryEntryCreateCFProperty(port,
267 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
269 result = CFStringGetCString(cf_path,
270 path, PATH_MAX, kCFStringEncodingASCII);
272 if (result && !(list = sp_list_append(list, path)))
275 IOObjectRelease(port);
279 IOObjectRelease(port);
284 IOObjectRelease(iter);
289 struct udev_enumerate *ud_enumerate;
290 struct udev_list_entry *ud_list;
291 struct udev_list_entry *ud_entry;
293 struct udev_device *ud_dev, *ud_parent;
296 int fd, ioctl_result;
297 struct serial_struct serial_info;
300 ud_enumerate = udev_enumerate_new(ud);
301 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
302 udev_enumerate_scan_devices(ud_enumerate);
303 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
304 udev_list_entry_foreach(ud_entry, ud_list)
306 path = udev_list_entry_get_name(ud_entry);
307 ud_dev = udev_device_new_from_syspath(ud, path);
308 /* If there is no parent device, this is a virtual tty. */
309 ud_parent = udev_device_get_parent(ud_dev);
310 if (ud_parent == NULL)
312 udev_device_unref(ud_dev);
315 name = udev_device_get_devnode(ud_dev);
316 /* The serial8250 driver has a hardcoded number of ports.
317 * The only way to tell which actually exist on a given system
318 * is to try to open them and make an ioctl call. */
319 driver = udev_device_get_driver(ud_parent);
320 if (driver && !strcmp(driver, "serial8250"))
322 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
324 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
326 if (ioctl_result != 0)
328 if (serial_info.type == PORT_UNKNOWN)
331 list = sp_list_append(list, name);
333 udev_device_unref(ud_dev);
341 udev_enumerate_unref(ud_enumerate);
352 sp_free_port_list(list);
360 void sp_free_port_list(struct sp_port **list)
364 for (i = 0; list[i]; i++)
365 sp_free_port(list[i]);
369 static int sp_validate_port(struct sp_port *port)
374 if (port->hdl == INVALID_HANDLE_VALUE)
383 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
385 int sp_open(struct sp_port *port, int flags)
391 DWORD desired_access = 0, flags_and_attributes = 0;
392 char *escaped_port_name;
394 /* Prefix port name with '\\.\' to work with ports above COM9. */
395 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
397 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
399 /* Map 'flags' to the OS-specific settings. */
400 desired_access |= GENERIC_READ;
401 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
402 if (flags & SP_MODE_RDWR)
403 desired_access |= GENERIC_WRITE;
404 if (flags & SP_MODE_NONBLOCK)
405 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
407 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
408 OPEN_EXISTING, flags_and_attributes, 0);
410 free(escaped_port_name);
412 if (port->hdl == INVALID_HANDLE_VALUE)
416 struct sp_port_data data;
418 /* Map 'flags' to the OS-specific settings. */
419 if (flags & SP_MODE_RDWR)
420 flags_local |= O_RDWR;
421 if (flags & SP_MODE_RDONLY)
422 flags_local |= O_RDONLY;
423 if (flags & SP_MODE_NONBLOCK)
424 flags_local |= O_NONBLOCK;
426 if ((port->fd = open(port->name, flags_local)) < 0)
429 start_config(port, &data);
431 /* Turn off all serial port cooking. */
432 data.term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
433 data.term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
434 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
435 data.term.c_oflag &= ~OFILL;
437 /* Disable canonical mode, and don't echo input characters. */
438 data.term.c_lflag &= ~(ICANON | ECHO);
440 /* Ignore modem status lines; enable receiver */
441 data.term.c_cflag |= (CLOCAL | CREAD);
443 apply_config(port, &data);
449 int sp_close(struct sp_port *port)
454 /* Returns non-zero upon success, 0 upon failure. */
455 if (CloseHandle(port->hdl) == 0)
458 /* Returns 0 upon success, -1 upon failure. */
459 if (close(port->fd) == -1)
466 int sp_flush(struct sp_port *port)
471 /* Returns non-zero upon success, 0 upon failure. */
472 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
475 /* Returns 0 upon success, -1 upon failure. */
476 if (tcflush(port->fd, TCIOFLUSH) < 0)
482 int sp_write(struct sp_port *port, const void *buf, size_t count)
492 /* Returns non-zero upon success, 0 upon failure. */
493 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
497 /* Returns the number of bytes written, or -1 upon failure. */
498 ssize_t written = write(port->fd, buf, count);
507 int sp_read(struct sp_port *port, void *buf, size_t count)
515 DWORD bytes_read = 0;
517 /* Returns non-zero upon success, 0 upon failure. */
518 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
524 /* Returns the number of bytes read, or -1 upon failure. */
525 if ((bytes_read = read(port->fd, buf, count)) < 0)
531 static int start_config(struct sp_port *port, struct sp_port_data *data)
535 if (!GetCommState(port->hdl, &data->dcb))
538 if (tcgetattr(port->fd, &data->term) < 0)
541 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
544 if (data->term.c_cflag & CRTSCTS) {
545 data->rts = SP_RTS_FLOW_CONTROL;
546 data->cts = SP_CTS_FLOW_CONTROL;
548 data->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
549 data->cts = SP_CTS_IGNORE;
552 data->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
553 data->dsr = SP_DSR_IGNORE;
558 static int set_baudrate(struct sp_port_data *data, int baudrate)
563 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
564 * have documented CBR_* macros.
567 data->dcb.BaudRate = CBR_110;
570 data->dcb.BaudRate = CBR_300;
573 data->dcb.BaudRate = CBR_600;
576 data->dcb.BaudRate = CBR_1200;
579 data->dcb.BaudRate = CBR_2400;
582 data->dcb.BaudRate = CBR_4800;
585 data->dcb.BaudRate = CBR_9600;
588 data->dcb.BaudRate = CBR_14400; /* Not available on Unix? */
591 data->dcb.BaudRate = CBR_19200;
594 data->dcb.BaudRate = CBR_38400;
597 data->dcb.BaudRate = CBR_57600;
600 data->dcb.BaudRate = CBR_115200;
603 data->dcb.BaudRate = CBR_128000; /* Not available on Unix? */
606 data->dcb.BaudRate = CBR_256000; /* Not available on Unix? */
668 #if !defined(__APPLE__) && !defined(__OpenBSD__)
677 if (cfsetospeed(&data->term, baud) < 0)
680 if (cfsetispeed(&data->term, baud) < 0)
687 static int set_bits(struct sp_port_data *data, int bits)
690 data->dcb.ByteSize = bits;
692 data->term.c_cflag &= ~CSIZE;
695 data->term.c_cflag |= CS8;
698 data->term.c_cflag |= CS7;
701 data->term.c_cflag |= CS6;
710 static int set_parity(struct sp_port_data *data, int parity)
714 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
716 data->dcb.Parity = NOPARITY;
719 data->dcb.Parity = EVENPARITY;
722 data->dcb.Parity = ODDPARITY;
728 data->term.c_iflag &= ~IGNPAR;
729 data->term.c_cflag &= ~(PARENB | PARODD);
732 data->term.c_iflag |= IGNPAR;
735 data->term.c_cflag |= PARENB;
738 data->term.c_cflag |= PARENB | PARODD;
747 static int set_stopbits(struct sp_port_data *data, int stopbits)
751 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
753 data->dcb.StopBits = ONESTOPBIT;
756 data->dcb.StopBits = TWOSTOPBITS;
762 data->term.c_cflag &= ~CSTOPB;
765 data->term.c_cflag &= ~CSTOPB;
768 data->term.c_cflag |= CSTOPB;
777 static int set_rts(struct sp_port_data *data, int rts)
782 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
785 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
787 case SP_RTS_FLOW_CONTROL:
788 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
799 static int set_cts(struct sp_port_data *data, int cts)
804 data->dcb.fOutxCtsFlow = FALSE;
806 case SP_CTS_FLOW_CONTROL:
807 data->dcb.fOutxCtsFlow = TRUE;
818 static int set_dtr(struct sp_port_data *data, int dtr)
823 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
826 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
828 case SP_DTR_FLOW_CONTROL:
829 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
840 static int set_dsr(struct sp_port_data *data, int dsr)
845 data->dcb.fOutxDsrFlow = FALSE;
847 case SP_DSR_FLOW_CONTROL:
848 data->dcb.fOutxDsrFlow = TRUE;
859 static int set_xon_xoff(struct sp_port_data *data, int xon_xoff)
863 case SP_XONXOFF_DISABLED:
864 data->dcb.fInX = FALSE;
865 data->dcb.fOutX = FALSE;
868 data->dcb.fInX = TRUE;
869 data->dcb.fOutX = FALSE;
872 data->dcb.fInX = FALSE;
873 data->dcb.fOutX = TRUE;
875 case SP_XONXOFF_INOUT:
876 data->dcb.fInX = TRUE;
877 data->dcb.fOutX = TRUE;
883 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
885 case SP_XONXOFF_DISABLED:
888 data->term.c_iflag |= IXOFF;
891 data->term.c_iflag |= IXON | IXANY;
893 case SP_XONXOFF_INOUT:
894 data->term.c_iflag |= IXON | IXOFF | IXANY;
903 static int apply_config(struct sp_port *port, struct sp_port_data *data)
906 if (!SetCommState(port->hdl, &data->dcb))
911 /* Asymmetric use of RTS/CTS not supported yet. */
912 if ((data->rts == SP_RTS_FLOW_CONTROL) != (data->cts == SP_CTS_FLOW_CONTROL))
915 /* DTR/DSR flow control not supported yet. */
916 if (data->dtr == SP_DTR_FLOW_CONTROL || data->dsr == SP_DSR_FLOW_CONTROL)
919 if (data->rts == SP_RTS_FLOW_CONTROL)
920 data->term.c_iflag |= CRTSCTS;
923 controlbits = TIOCM_RTS;
924 if (ioctl(port->fd, data->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
929 controlbits = TIOCM_DTR;
930 if (ioctl(port->fd, data->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
934 /* Write the configured settings. */
935 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
941 #define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
942 #define TRY_SET(x, y) do { if (y >= 0) TRY(set_##x(&data, y)); } while (0)
943 #define TRY_SET_CONFIG(x) TRY_SET(x, config->x)
945 int sp_set_config(struct sp_port *port, struct sp_port_config *config)
947 struct sp_port_data data;
949 TRY(start_config(port, &data));
950 TRY_SET_CONFIG(baudrate);
951 TRY_SET_CONFIG(bits);
952 TRY_SET_CONFIG(parity);
953 TRY_SET_CONFIG(stopbits);
958 TRY_SET_CONFIG(xon_xoff);
959 TRY(apply_config(port, &data));
964 int sp_set_flowcontrol(struct sp_port *port, int flowcontrol)
966 struct sp_port_data data;
968 TRY(start_config(port, &data));
970 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
971 TRY_SET(xon_xoff, SP_XONXOFF_INOUT);
973 TRY_SET(xon_xoff, SP_XONXOFF_DISABLED);
975 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
976 TRY_SET(rts, SP_RTS_FLOW_CONTROL);
977 TRY_SET(cts, SP_CTS_FLOW_CONTROL);
979 TRY_SET(rts, SP_RTS_ON);
980 TRY_SET(cts, SP_CTS_IGNORE);
983 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
984 TRY_SET(dtr, SP_DTR_FLOW_CONTROL);
985 TRY_SET(dsr, SP_DSR_FLOW_CONTROL);
987 TRY_SET(dtr, SP_DTR_ON);
988 TRY_SET(dsr, SP_DSR_IGNORE);
991 TRY(apply_config(port, &data));
996 #define CREATE_SETTER(x) int sp_set_##x(struct sp_port *port, int x) { \
997 struct sp_port_data data; \
998 TRY(start_config(port, &data)); \
999 TRY(set_##x(&data, x)); \
1000 TRY(apply_config(port, &data)); \
1004 CREATE_SETTER(baudrate)
1006 CREATE_SETTER(parity)
1007 CREATE_SETTER(stopbits)
1012 CREATE_SETTER(xon_xoff)
1014 int sp_last_error_code(void)
1017 return GetLastError();
1023 char *sp_last_error_message(void)
1027 DWORD error = GetLastError();
1030 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1031 FORMAT_MESSAGE_FROM_SYSTEM |
1032 FORMAT_MESSAGE_IGNORE_INSERTS,
1035 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1041 return strerror(errno);
1045 void sp_free_error_message(char *message)