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"
61 /* Helper functions for configuring ports. */
62 static int start_config(struct sp_port *port, struct sp_port_data *data);
63 static int set_baudrate(struct sp_port_data *data, int baudrate);
64 static int set_bits(struct sp_port_data *data, int bits);
65 static int set_parity(struct sp_port_data *data, int parity);
66 static int set_stopbits(struct sp_port_data *data, int stopbits);
67 static int set_rts(struct sp_port_data *data, int rts);
68 static int set_cts(struct sp_port_data *data, int cts);
69 static int set_dtr(struct sp_port_data *data, int dtr);
70 static int set_dsr(struct sp_port_data *data, int dsr);
71 static int set_xon_xoff(struct sp_port_data *data, int xon_xoff);
72 static int apply_config(struct sp_port *port, struct sp_port_data *data);
74 int sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
87 if (!(port = malloc(sizeof(struct sp_port))))
90 len = strlen(portname) + 1;
92 if (!(port->name = malloc(len)))
98 memcpy(port->name, portname, len);
105 int sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
112 if (!port || !port->name)
115 return sp_get_port_by_name(port->name, copy_ptr);
118 void sp_free_port(struct sp_port *port)
129 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
134 for (count = 0; list[count]; count++);
135 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
138 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
140 list[count + 1] = NULL;
144 sp_free_port_list(list);
148 int sp_list_ports(struct sp_port ***list_ptr)
150 struct sp_port **list;
153 if (!(list = malloc(sizeof(struct sp_port **))))
161 DWORD max_value_len, max_data_size, max_data_len;
162 DWORD value_len, data_size, data_len;
163 DWORD type, index = 0;
167 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
168 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
173 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
174 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
179 max_data_len = max_data_size / sizeof(TCHAR);
180 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
185 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
191 value_len = max_value_len + 1,
192 data_size = max_data_size,
193 RegEnumValue(key, index, value, &value_len,
194 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
196 data_len = data_size / sizeof(TCHAR);
197 data[data_len] = '\0';
199 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
201 name_len = data_len + 1;
203 if (!(name = malloc(name_len)))
209 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
213 if (type == REG_SZ && !(list = sp_list_append(list, name)))
230 CFMutableDictionaryRef classes;
237 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
243 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
249 CFDictionarySetValue(classes,
250 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
252 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS)
258 if (!(path = malloc(PATH_MAX)))
264 while ((port = IOIteratorNext(iter))) {
265 cf_path = IORegistryEntryCreateCFProperty(port,
266 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
268 result = CFStringGetCString(cf_path,
269 path, PATH_MAX, kCFStringEncodingASCII);
271 if (result && !(list = sp_list_append(list, path)))
274 IOObjectRelease(port);
278 IOObjectRelease(port);
283 IOObjectRelease(iter);
288 struct udev_enumerate *ud_enumerate;
289 struct udev_list_entry *ud_list;
290 struct udev_list_entry *ud_entry;
292 struct udev_device *ud_dev, *ud_parent;
295 int fd, ioctl_result;
296 struct serial_struct serial_info;
299 ud_enumerate = udev_enumerate_new(ud);
300 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
301 udev_enumerate_scan_devices(ud_enumerate);
302 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
303 udev_list_entry_foreach(ud_entry, ud_list)
305 path = udev_list_entry_get_name(ud_entry);
306 ud_dev = udev_device_new_from_syspath(ud, path);
307 /* If there is no parent device, this is a virtual tty. */
308 ud_parent = udev_device_get_parent(ud_dev);
309 if (ud_parent == NULL)
311 udev_device_unref(ud_dev);
314 name = udev_device_get_devnode(ud_dev);
315 /* The serial8250 driver has a hardcoded number of ports.
316 * The only way to tell which actually exist on a given system
317 * is to try to open them and make an ioctl call. */
318 driver = udev_device_get_driver(ud_parent);
319 if (driver && !strcmp(driver, "serial8250"))
321 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
323 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
325 if (ioctl_result != 0)
327 if (serial_info.type == PORT_UNKNOWN)
330 list = sp_list_append(list, name);
332 udev_device_unref(ud_dev);
340 udev_enumerate_unref(ud_enumerate);
351 sp_free_port_list(list);
359 void sp_free_port_list(struct sp_port **list)
363 for (i = 0; list[i]; i++)
364 sp_free_port(list[i]);
368 static int sp_validate_port(struct sp_port *port)
373 if (port->hdl == INVALID_HANDLE_VALUE)
382 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
384 int sp_open(struct sp_port *port, int flags)
390 DWORD desired_access = 0, flags_and_attributes = 0;
391 char *escaped_port_name;
393 /* Prefix port name with '\\.\' to work with ports above COM9. */
394 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
396 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
398 /* Map 'flags' to the OS-specific settings. */
399 desired_access |= GENERIC_READ;
400 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
401 if (flags & SP_MODE_RDWR)
402 desired_access |= GENERIC_WRITE;
403 if (flags & SP_MODE_NONBLOCK)
404 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
406 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
407 OPEN_EXISTING, flags_and_attributes, 0);
409 free(escaped_port_name);
411 if (port->hdl == INVALID_HANDLE_VALUE)
416 /* Map 'flags' to the OS-specific settings. */
417 if (flags & SP_MODE_RDWR)
418 flags_local |= O_RDWR;
419 if (flags & SP_MODE_RDONLY)
420 flags_local |= O_RDONLY;
421 if (flags & SP_MODE_NONBLOCK)
422 flags_local |= O_NONBLOCK;
424 if ((port->fd = open(port->name, flags_local)) < 0)
431 int sp_close(struct sp_port *port)
436 /* Returns non-zero upon success, 0 upon failure. */
437 if (CloseHandle(port->hdl) == 0)
440 /* Returns 0 upon success, -1 upon failure. */
441 if (close(port->fd) == -1)
448 int sp_flush(struct sp_port *port)
453 /* Returns non-zero upon success, 0 upon failure. */
454 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
457 /* Returns 0 upon success, -1 upon failure. */
458 if (tcflush(port->fd, TCIOFLUSH) < 0)
464 int sp_write(struct sp_port *port, const void *buf, size_t count)
474 /* Returns non-zero upon success, 0 upon failure. */
475 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
479 /* Returns the number of bytes written, or -1 upon failure. */
480 ssize_t written = write(port->fd, buf, count);
489 int sp_read(struct sp_port *port, void *buf, size_t count)
497 DWORD bytes_read = 0;
499 /* Returns non-zero upon success, 0 upon failure. */
500 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
506 /* Returns the number of bytes read, or -1 upon failure. */
507 if ((bytes_read = read(port->fd, buf, count)) < 0)
513 static int start_config(struct sp_port *port, struct sp_port_data *data)
517 if (!GetCommState(port->hdl, &data->dcb))
522 if (tcgetattr(port->fd, &data->term) < 0)
525 if (ioctl(port->fd, TIOCMGET, &controlbits) < 0)
528 if (data->term.c_cflag & CRTSCTS) {
529 data->rts = SP_RTS_FLOW_CONTROL;
530 data->cts = SP_CTS_FLOW_CONTROL;
532 data->rts = (controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
533 data->cts = SP_CTS_IGNORE;
536 data->dtr = (controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
537 data->dsr = SP_DSR_IGNORE;
542 static int set_baudrate(struct sp_port_data *data, int baudrate)
547 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
548 * have documented CBR_* macros.
551 data->dcb.BaudRate = CBR_110;
554 data->dcb.BaudRate = CBR_300;
557 data->dcb.BaudRate = CBR_600;
560 data->dcb.BaudRate = CBR_1200;
563 data->dcb.BaudRate = CBR_2400;
566 data->dcb.BaudRate = CBR_4800;
569 data->dcb.BaudRate = CBR_9600;
572 data->dcb.BaudRate = CBR_14400; /* Not available on Unix? */
575 data->dcb.BaudRate = CBR_19200;
578 data->dcb.BaudRate = CBR_38400;
581 data->dcb.BaudRate = CBR_57600;
584 data->dcb.BaudRate = CBR_115200;
587 data->dcb.BaudRate = CBR_128000; /* Not available on Unix? */
590 data->dcb.BaudRate = CBR_256000; /* Not available on Unix? */
652 #if !defined(__APPLE__) && !defined(__OpenBSD__)
661 if (cfsetospeed(&data->term, baud) < 0)
664 if (cfsetispeed(&data->term, baud) < 0)
671 static int set_bits(struct sp_port_data *data, int bits)
674 data->dcb.ByteSize = bits;
676 data->term.c_cflag &= ~CSIZE;
679 data->term.c_cflag |= CS8;
682 data->term.c_cflag |= CS7;
685 data->term.c_cflag |= CS6;
694 static int set_parity(struct sp_port_data *data, int parity)
698 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
700 data->dcb.Parity = NOPARITY;
703 data->dcb.Parity = EVENPARITY;
706 data->dcb.Parity = ODDPARITY;
712 data->term.c_iflag &= ~IGNPAR;
713 data->term.c_cflag &= ~(PARENB | PARODD);
716 data->term.c_iflag |= IGNPAR;
719 data->term.c_cflag |= PARENB;
722 data->term.c_cflag |= PARENB | PARODD;
731 static int set_stopbits(struct sp_port_data *data, int stopbits)
735 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
737 data->dcb.StopBits = ONESTOPBIT;
740 data->dcb.StopBits = TWOSTOPBITS;
746 data->term.c_cflag &= ~CSTOPB;
749 data->term.c_cflag &= ~CSTOPB;
752 data->term.c_cflag |= CSTOPB;
761 static int set_rts(struct sp_port_data *data, int rts)
766 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
769 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
771 case SP_RTS_FLOW_CONTROL:
772 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
783 static int set_cts(struct sp_port_data *data, int cts)
788 data->dcb.fOutxCtsFlow = FALSE;
790 case SP_CTS_FLOW_CONTROL:
791 data->dcb.fOutxCtsFlow = TRUE;
802 static int set_dtr(struct sp_port_data *data, int dtr)
807 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
810 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
812 case SP_DTR_FLOW_CONTROL:
813 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
824 static int set_dsr(struct sp_port_data *data, int dsr)
829 data->dcb.fOutxDsrFlow = FALSE;
831 case SP_DSR_FLOW_CONTROL:
832 data->dcb.fOutxDsrFlow = TRUE;
843 static int set_xon_xoff(struct sp_port_data *data, int xon_xoff)
847 case SP_XONXOFF_DISABLED:
848 data->dcb.fInX = FALSE;
849 data->dcb.fOutX = FALSE;
852 data->dcb.fInX = TRUE;
853 data->dcb.fOutX = FALSE;
856 data->dcb.fInX = FALSE;
857 data->dcb.fOutX = TRUE;
859 case SP_XONXOFF_INOUT:
860 data->dcb.fInX = TRUE;
861 data->dcb.fOutX = TRUE;
867 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
869 case SP_XONXOFF_DISABLED:
872 data->term.c_iflag |= IXOFF;
875 data->term.c_iflag |= IXON | IXANY;
877 case SP_XONXOFF_INOUT:
878 data->term.c_iflag |= IXON | IXOFF | IXANY;
887 static int apply_config(struct sp_port *port, struct sp_port_data *data)
890 if (!SetCommState(port->hdl, &data->dcb))
895 /* Turn off all serial port cooking. */
896 data->term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
897 data->term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
898 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
899 data->term.c_oflag &= ~OFILL;
901 /* Disable canonical mode, and don't echo input characters. */
902 data->term.c_lflag &= ~(ICANON | ECHO);
904 /* Ignore modem status lines; enable receiver */
905 data->term.c_cflag |= (CLOCAL | CREAD);
907 /* Asymmetric use of RTS/CTS not supported yet. */
908 if ((data->rts == SP_RTS_FLOW_CONTROL) != (data->cts == SP_CTS_FLOW_CONTROL))
911 /* DTR/DSR flow control not supported yet. */
912 if (data->dtr == SP_DTR_FLOW_CONTROL || data->dsr == SP_DSR_FLOW_CONTROL)
915 if (data->rts == SP_RTS_FLOW_CONTROL)
916 data->term.c_iflag |= CRTSCTS;
919 controlbits = TIOCM_RTS;
920 if (ioctl(port->fd, data->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
925 controlbits = TIOCM_DTR;
926 if (ioctl(port->fd, data->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
930 /* Write the configured settings. */
931 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
937 #define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
938 #define TRY_SET(x) do { if (config->x >= 0) TRY(set_##x(&data, config->x)); } while (0)
940 int sp_set_config(struct sp_port *port, struct sp_port_config *config)
942 struct sp_port_data data;
944 TRY(start_config(port, &data));
954 TRY(apply_config(port, &data));
959 int sp_last_error_code(void)
962 return GetLastError();
968 char *sp_last_error_message(void)
972 DWORD error = GetLastError();
975 FORMAT_MESSAGE_ALLOCATE_BUFFER |
976 FORMAT_MESSAGE_FROM_SYSTEM |
977 FORMAT_MESSAGE_IGNORE_INSERTS,
980 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
986 return strerror(errno);
990 void sp_free_error_message(char *message)