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 /* Standard baud rates. */
64 #define BAUD_TYPE DWORD
65 #define BAUD(n) {CBR_##n, n}
67 #define BAUD_TYPE speed_t
68 #define BAUD(n) {B##n, n}
76 const struct std_baudrate std_baudrates[] = {
79 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
80 * have documented CBR_* macros.
82 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
83 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
84 BAUD(115200), BAUD(128000), BAUD(256000)
86 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200), BAUD(300),
87 BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800), BAUD(9600),
88 BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200), BAUD(230400),
89 #if !defined(__APPLE__) && !defined(__OpenBSD__)
95 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
96 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
98 /* Helper functions for configuring ports. */
99 static int start_config(struct sp_port *port, struct sp_port_data *data);
100 static int set_baudrate(struct sp_port_data *data, int baudrate);
101 static int set_bits(struct sp_port_data *data, int bits);
102 static int set_parity(struct sp_port_data *data, int parity);
103 static int set_stopbits(struct sp_port_data *data, int stopbits);
104 static int set_rts(struct sp_port_data *data, int rts);
105 static int set_cts(struct sp_port_data *data, int cts);
106 static int set_dtr(struct sp_port_data *data, int dtr);
107 static int set_dsr(struct sp_port_data *data, int dsr);
108 static int set_xon_xoff(struct sp_port_data *data, int xon_xoff);
109 static int apply_config(struct sp_port *port, struct sp_port_data *data);
111 int sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
113 struct sp_port *port;
124 if (!(port = malloc(sizeof(struct sp_port))))
127 len = strlen(portname) + 1;
129 if (!(port->name = malloc(len)))
135 memcpy(port->name, portname, len);
142 int sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
149 if (!port || !port->name)
152 return sp_get_port_by_name(port->name, copy_ptr);
155 void sp_free_port(struct sp_port *port)
166 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
171 for (count = 0; list[count]; count++);
172 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
175 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
177 list[count + 1] = NULL;
181 sp_free_port_list(list);
185 int sp_list_ports(struct sp_port ***list_ptr)
187 struct sp_port **list;
190 if (!(list = malloc(sizeof(struct sp_port **))))
198 DWORD max_value_len, max_data_size, max_data_len;
199 DWORD value_len, data_size, data_len;
200 DWORD type, index = 0;
204 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
205 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
210 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
211 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
216 max_data_len = max_data_size / sizeof(TCHAR);
217 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
222 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
228 value_len = max_value_len + 1,
229 data_size = max_data_size,
230 RegEnumValue(key, index, value, &value_len,
231 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
233 data_len = data_size / sizeof(TCHAR);
234 data[data_len] = '\0';
236 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
238 name_len = data_len + 1;
240 if (!(name = malloc(name_len)))
246 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
250 if (type == REG_SZ && !(list = sp_list_append(list, name)))
267 CFMutableDictionaryRef classes;
274 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
280 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
286 CFDictionarySetValue(classes,
287 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
289 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS)
295 if (!(path = malloc(PATH_MAX)))
301 while ((port = IOIteratorNext(iter))) {
302 cf_path = IORegistryEntryCreateCFProperty(port,
303 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
305 result = CFStringGetCString(cf_path,
306 path, PATH_MAX, kCFStringEncodingASCII);
308 if (result && !(list = sp_list_append(list, path)))
311 IOObjectRelease(port);
315 IOObjectRelease(port);
320 IOObjectRelease(iter);
325 struct udev_enumerate *ud_enumerate;
326 struct udev_list_entry *ud_list;
327 struct udev_list_entry *ud_entry;
329 struct udev_device *ud_dev, *ud_parent;
332 int fd, ioctl_result;
333 struct serial_struct serial_info;
336 ud_enumerate = udev_enumerate_new(ud);
337 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
338 udev_enumerate_scan_devices(ud_enumerate);
339 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
340 udev_list_entry_foreach(ud_entry, ud_list)
342 path = udev_list_entry_get_name(ud_entry);
343 ud_dev = udev_device_new_from_syspath(ud, path);
344 /* If there is no parent device, this is a virtual tty. */
345 ud_parent = udev_device_get_parent(ud_dev);
346 if (ud_parent == NULL)
348 udev_device_unref(ud_dev);
351 name = udev_device_get_devnode(ud_dev);
352 /* The serial8250 driver has a hardcoded number of ports.
353 * The only way to tell which actually exist on a given system
354 * is to try to open them and make an ioctl call. */
355 driver = udev_device_get_driver(ud_parent);
356 if (driver && !strcmp(driver, "serial8250"))
358 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
360 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
362 if (ioctl_result != 0)
364 if (serial_info.type == PORT_UNKNOWN)
367 list = sp_list_append(list, name);
369 udev_device_unref(ud_dev);
377 udev_enumerate_unref(ud_enumerate);
388 sp_free_port_list(list);
396 void sp_free_port_list(struct sp_port **list)
400 for (i = 0; list[i]; i++)
401 sp_free_port(list[i]);
405 static int sp_validate_port(struct sp_port *port)
410 if (port->hdl == INVALID_HANDLE_VALUE)
419 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
421 int sp_open(struct sp_port *port, int flags)
427 DWORD desired_access = 0, flags_and_attributes = 0;
428 char *escaped_port_name;
430 /* Prefix port name with '\\.\' to work with ports above COM9. */
431 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
433 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
435 /* Map 'flags' to the OS-specific settings. */
436 desired_access |= GENERIC_READ;
437 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
438 if (flags & SP_MODE_RDWR)
439 desired_access |= GENERIC_WRITE;
440 if (flags & SP_MODE_NONBLOCK)
441 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
443 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
444 OPEN_EXISTING, flags_and_attributes, 0);
446 free(escaped_port_name);
448 if (port->hdl == INVALID_HANDLE_VALUE)
452 struct sp_port_data data;
454 /* Map 'flags' to the OS-specific settings. */
455 if (flags & SP_MODE_RDWR)
456 flags_local |= O_RDWR;
457 if (flags & SP_MODE_RDONLY)
458 flags_local |= O_RDONLY;
459 if (flags & SP_MODE_NONBLOCK)
460 flags_local |= O_NONBLOCK;
462 if ((port->fd = open(port->name, flags_local)) < 0)
465 start_config(port, &data);
467 /* Turn off all serial port cooking. */
468 data.term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
469 data.term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
470 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
471 data.term.c_oflag &= ~OFILL;
473 /* Disable canonical mode, and don't echo input characters. */
474 data.term.c_lflag &= ~(ICANON | ECHO);
476 /* Ignore modem status lines; enable receiver */
477 data.term.c_cflag |= (CLOCAL | CREAD);
479 apply_config(port, &data);
485 int sp_close(struct sp_port *port)
490 /* Returns non-zero upon success, 0 upon failure. */
491 if (CloseHandle(port->hdl) == 0)
494 /* Returns 0 upon success, -1 upon failure. */
495 if (close(port->fd) == -1)
502 int sp_flush(struct sp_port *port)
507 /* Returns non-zero upon success, 0 upon failure. */
508 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
511 /* Returns 0 upon success, -1 upon failure. */
512 if (tcflush(port->fd, TCIOFLUSH) < 0)
518 int sp_write(struct sp_port *port, const void *buf, size_t count)
528 /* Returns non-zero upon success, 0 upon failure. */
529 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
533 /* Returns the number of bytes written, or -1 upon failure. */
534 ssize_t written = write(port->fd, buf, count);
543 int sp_read(struct sp_port *port, void *buf, size_t count)
551 DWORD bytes_read = 0;
553 /* Returns non-zero upon success, 0 upon failure. */
554 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
560 /* Returns the number of bytes read, or -1 upon failure. */
561 if ((bytes_read = read(port->fd, buf, count)) < 0)
567 static int start_config(struct sp_port *port, struct sp_port_data *data)
571 if (!GetCommState(port->hdl, &data->dcb))
574 if (tcgetattr(port->fd, &data->term) < 0)
577 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
580 if (data->term.c_cflag & CRTSCTS) {
581 data->rts = SP_RTS_FLOW_CONTROL;
582 data->cts = SP_CTS_FLOW_CONTROL;
584 data->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
585 data->cts = SP_CTS_IGNORE;
588 data->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
589 data->dsr = SP_DSR_IGNORE;
594 static int set_baudrate(struct sp_port_data *data, int baudrate)
597 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
598 if (baudrate == std_baudrates[i].value) {
600 data->dcb.BaudRate = std_baudrates[i].index;
602 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
605 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
612 if (i == NUM_STD_BAUDRATES)
618 static int set_bits(struct sp_port_data *data, int bits)
621 data->dcb.ByteSize = bits;
623 data->term.c_cflag &= ~CSIZE;
626 data->term.c_cflag |= CS8;
629 data->term.c_cflag |= CS7;
632 data->term.c_cflag |= CS6;
641 static int set_parity(struct sp_port_data *data, int parity)
645 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
647 data->dcb.Parity = NOPARITY;
650 data->dcb.Parity = EVENPARITY;
653 data->dcb.Parity = ODDPARITY;
659 data->term.c_iflag &= ~IGNPAR;
660 data->term.c_cflag &= ~(PARENB | PARODD);
663 data->term.c_iflag |= IGNPAR;
666 data->term.c_cflag |= PARENB;
669 data->term.c_cflag |= PARENB | PARODD;
678 static int set_stopbits(struct sp_port_data *data, int stopbits)
682 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
684 data->dcb.StopBits = ONESTOPBIT;
687 data->dcb.StopBits = TWOSTOPBITS;
693 data->term.c_cflag &= ~CSTOPB;
696 data->term.c_cflag &= ~CSTOPB;
699 data->term.c_cflag |= CSTOPB;
708 static int set_rts(struct sp_port_data *data, int rts)
713 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
716 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
718 case SP_RTS_FLOW_CONTROL:
719 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
730 static int set_cts(struct sp_port_data *data, int cts)
735 data->dcb.fOutxCtsFlow = FALSE;
737 case SP_CTS_FLOW_CONTROL:
738 data->dcb.fOutxCtsFlow = TRUE;
749 static int set_dtr(struct sp_port_data *data, int dtr)
754 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
757 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
759 case SP_DTR_FLOW_CONTROL:
760 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
771 static int set_dsr(struct sp_port_data *data, int dsr)
776 data->dcb.fOutxDsrFlow = FALSE;
778 case SP_DSR_FLOW_CONTROL:
779 data->dcb.fOutxDsrFlow = TRUE;
790 static int set_xon_xoff(struct sp_port_data *data, int xon_xoff)
794 case SP_XONXOFF_DISABLED:
795 data->dcb.fInX = FALSE;
796 data->dcb.fOutX = FALSE;
799 data->dcb.fInX = TRUE;
800 data->dcb.fOutX = FALSE;
803 data->dcb.fInX = FALSE;
804 data->dcb.fOutX = TRUE;
806 case SP_XONXOFF_INOUT:
807 data->dcb.fInX = TRUE;
808 data->dcb.fOutX = TRUE;
814 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
816 case SP_XONXOFF_DISABLED:
819 data->term.c_iflag |= IXOFF;
822 data->term.c_iflag |= IXON | IXANY;
824 case SP_XONXOFF_INOUT:
825 data->term.c_iflag |= IXON | IXOFF | IXANY;
834 static int apply_config(struct sp_port *port, struct sp_port_data *data)
837 if (!SetCommState(port->hdl, &data->dcb))
842 /* Asymmetric use of RTS/CTS not supported yet. */
843 if ((data->rts == SP_RTS_FLOW_CONTROL) != (data->cts == SP_CTS_FLOW_CONTROL))
846 /* DTR/DSR flow control not supported yet. */
847 if (data->dtr == SP_DTR_FLOW_CONTROL || data->dsr == SP_DSR_FLOW_CONTROL)
850 if (data->rts == SP_RTS_FLOW_CONTROL)
851 data->term.c_iflag |= CRTSCTS;
854 controlbits = TIOCM_RTS;
855 if (ioctl(port->fd, data->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
860 controlbits = TIOCM_DTR;
861 if (ioctl(port->fd, data->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
865 /* Write the configured settings. */
866 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
872 #define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
873 #define TRY_SET(x, y) do { if (y >= 0) TRY(set_##x(&data, y)); } while (0)
874 #define TRY_SET_CONFIG(x) TRY_SET(x, config->x)
876 int sp_set_config(struct sp_port *port, struct sp_port_config *config)
878 struct sp_port_data data;
880 TRY(start_config(port, &data));
881 TRY_SET_CONFIG(baudrate);
882 TRY_SET_CONFIG(bits);
883 TRY_SET_CONFIG(parity);
884 TRY_SET_CONFIG(stopbits);
889 TRY_SET_CONFIG(xon_xoff);
890 TRY(apply_config(port, &data));
895 int sp_get_config(struct sp_port *port, struct sp_port_config *config)
897 struct sp_port_data data;
900 TRY(start_config(port, &data));
903 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
904 if (data.dcb.BaudRate == std_baudrates[i].index) {
905 config->baudrate = std_baudrates[i].value;
910 if (i == NUM_STD_BAUDRATES)
911 /* BaudRate field can be either an index or a custom baud rate. */
912 config->baudrate = data.dcb.BaudRate;
914 config->bits = data.dcb.ByteSize;
916 if (data.dcb.fParity)
917 switch (data.dcb.Parity) {
919 config->parity = SP_PARITY_NONE;
922 config->parity = SP_PARITY_EVEN;
925 config->parity = SP_PARITY_ODD;
931 config->parity = SP_PARITY_NONE;
933 switch (data.dcb.StopBits) {
935 config->stopbits = 1;
938 config->stopbits = 2;
941 config->stopbits = -1;
944 switch (data.dcb.fRtsControl) {
945 case RTS_CONTROL_DISABLE:
946 config->rts = SP_RTS_OFF;
948 case RTS_CONTROL_ENABLE:
949 config->rts = SP_RTS_ON;
951 case RTS_CONTROL_HANDSHAKE:
952 config->rts = SP_RTS_FLOW_CONTROL;
958 config->cts = data.dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
960 switch (data.dcb.fDtrControl) {
961 case DTR_CONTROL_DISABLE:
962 config->dtr = SP_DTR_OFF;
964 case DTR_CONTROL_ENABLE:
965 config->dtr = SP_DTR_ON;
967 case DTR_CONTROL_HANDSHAKE:
968 config->dtr = SP_DTR_FLOW_CONTROL;
974 config->dsr = data.dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
976 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
977 if (cfgetispeed(&data.term) == std_baudrates[i].index) {
978 config->baudrate = std_baudrates[i].value;
983 if (i == NUM_STD_BAUDRATES)
984 config->baudrate = -1;
986 switch (data.term.c_cflag & CSIZE) {
1003 if (!(data.term.c_cflag & PARENB) && (data.term.c_iflag & IGNPAR))
1004 config->parity = SP_PARITY_NONE;
1005 else if (!(data.term.c_cflag & PARENB) || (data.term.c_iflag & IGNPAR))
1006 config->parity = -1;
1008 config->parity = (data.term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1010 config->stopbits = (data.term.c_cflag & CSTOPB) ? 2 : 1;
1012 if (data.term.c_cflag & CRTSCTS) {
1013 config->rts = SP_RTS_FLOW_CONTROL;
1014 config->cts = SP_CTS_FLOW_CONTROL;
1016 config->rts = (data.controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1017 config->cts = SP_CTS_IGNORE;
1020 config->dtr = (data.controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1021 config->dsr = SP_DSR_IGNORE;
1027 int sp_set_flowcontrol(struct sp_port *port, int flowcontrol)
1029 struct sp_port_data data;
1031 TRY(start_config(port, &data));
1033 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
1034 TRY_SET(xon_xoff, SP_XONXOFF_INOUT);
1036 TRY_SET(xon_xoff, SP_XONXOFF_DISABLED);
1038 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
1039 TRY_SET(rts, SP_RTS_FLOW_CONTROL);
1040 TRY_SET(cts, SP_CTS_FLOW_CONTROL);
1042 TRY_SET(rts, SP_RTS_ON);
1043 TRY_SET(cts, SP_CTS_IGNORE);
1046 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
1047 TRY_SET(dtr, SP_DTR_FLOW_CONTROL);
1048 TRY_SET(dsr, SP_DSR_FLOW_CONTROL);
1050 TRY_SET(dtr, SP_DTR_ON);
1051 TRY_SET(dsr, SP_DSR_IGNORE);
1054 TRY(apply_config(port, &data));
1059 #define CREATE_SETTER(x) int sp_set_##x(struct sp_port *port, int x) { \
1060 struct sp_port_data data; \
1061 TRY(start_config(port, &data)); \
1062 TRY(set_##x(&data, x)); \
1063 TRY(apply_config(port, &data)); \
1067 CREATE_SETTER(baudrate)
1069 CREATE_SETTER(parity)
1070 CREATE_SETTER(stopbits)
1075 CREATE_SETTER(xon_xoff)
1077 int sp_last_error_code(void)
1080 return GetLastError();
1086 char *sp_last_error_message(void)
1090 DWORD error = GetLastError();
1093 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1094 FORMAT_MESSAGE_FROM_SYSTEM |
1095 FORMAT_MESSAGE_IGNORE_INSERTS,
1098 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1104 return strerror(errno);
1108 void sp_free_error_message(char *message)