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"
60 int sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
73 if (!(port = malloc(sizeof(struct sp_port))))
76 len = strlen(portname) + 1;
78 if (!(port->name = malloc(len)))
84 memcpy(port->name, portname, len);
91 int sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
98 if (!port || !port->name)
101 return sp_get_port_by_name(port->name, copy_ptr);
104 void sp_free_port(struct sp_port *port)
115 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
119 for (count = 0; list[count]; count++);
120 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
123 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
125 list[count + 1] = NULL;
128 sp_free_port_list(list);
132 int sp_list_ports(struct sp_port ***list_ptr)
134 struct sp_port **list;
137 if (!(list = malloc(sizeof(struct sp_port **))))
145 DWORD max_value_len, max_data_size, max_data_len;
146 DWORD value_len, data_size, data_len;
147 DWORD type, index = 0;
151 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
152 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
157 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
158 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
163 max_data_len = max_data_size / sizeof(TCHAR);
164 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
169 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
175 value_len = max_value_len + 1,
176 data_size = max_data_size,
177 RegEnumValue(key, index, value, &value_len,
178 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
180 data_len = data_size / sizeof(TCHAR);
181 data[data_len] = '\0';
183 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
185 name_len = data_len + 1;
187 if (!(name = malloc(name_len)))
193 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
197 if (type == REG_SZ && !(list = sp_list_append(list, name)))
214 CFMutableDictionaryRef classes;
221 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
227 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
233 CFDictionarySetValue(classes,
234 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
236 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS)
242 if (!(path = malloc(PATH_MAX)))
248 while ((port = IOIteratorNext(iter))) {
249 cf_path = IORegistryEntryCreateCFProperty(port,
250 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
252 result = CFStringGetCString(cf_path,
253 path, PATH_MAX, kCFStringEncodingASCII);
255 if (result && !(list = sp_list_append(list, path)))
258 IOObjectRelease(port);
262 IOObjectRelease(port);
267 IOObjectRelease(iter);
272 struct udev_enumerate *ud_enumerate;
273 struct udev_list_entry *ud_list;
274 struct udev_list_entry *ud_entry;
276 struct udev_device *ud_dev, *ud_parent;
279 int fd, ioctl_result;
280 struct serial_struct serial_info;
283 ud_enumerate = udev_enumerate_new(ud);
284 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
285 udev_enumerate_scan_devices(ud_enumerate);
286 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
287 udev_list_entry_foreach(ud_entry, ud_list)
289 path = udev_list_entry_get_name(ud_entry);
290 ud_dev = udev_device_new_from_syspath(ud, path);
291 /* If there is no parent device, this is a virtual tty. */
292 ud_parent = udev_device_get_parent(ud_dev);
293 if (ud_parent == NULL)
295 udev_device_unref(ud_dev);
298 name = udev_device_get_devnode(ud_dev);
299 /* The serial8250 driver has a hardcoded number of ports.
300 * The only way to tell which actually exist on a given system
301 * is to try to open them and make an ioctl call. */
302 driver = udev_device_get_driver(ud_parent);
303 if (driver && !strcmp(driver, "serial8250"))
305 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
307 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
309 if (ioctl_result != 0)
311 if (serial_info.type == PORT_UNKNOWN)
314 list = sp_list_append(list, name);
316 udev_device_unref(ud_dev);
324 udev_enumerate_unref(ud_enumerate);
335 sp_free_port_list(list);
343 void sp_free_port_list(struct sp_port **list)
346 for (i = 0; list[i]; i++)
347 sp_free_port(list[i]);
351 static int sp_validate_port(struct sp_port *port)
356 if (port->hdl == INVALID_HANDLE_VALUE)
365 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
367 int sp_open(struct sp_port *port, int flags)
373 DWORD desired_access = 0, flags_and_attributes = 0;
374 char *escaped_port_name;
376 /* Prefix port name with '\\.\' to work with ports above COM9. */
377 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
379 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
381 /* Map 'flags' to the OS-specific settings. */
382 desired_access |= GENERIC_READ;
383 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
384 if (flags & SP_MODE_RDWR)
385 desired_access |= GENERIC_WRITE;
386 if (flags & SP_MODE_NONBLOCK)
387 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
389 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
390 OPEN_EXISTING, flags_and_attributes, 0);
392 free(escaped_port_name);
394 if (port->hdl == INVALID_HANDLE_VALUE)
398 /* Map 'flags' to the OS-specific settings. */
399 if (flags & SP_MODE_RDWR)
400 flags_local |= O_RDWR;
401 if (flags & SP_MODE_RDONLY)
402 flags_local |= O_RDONLY;
403 if (flags & SP_MODE_NONBLOCK)
404 flags_local |= O_NONBLOCK;
406 if ((port->fd = open(port->name, flags_local)) < 0)
413 int sp_close(struct sp_port *port)
418 /* Returns non-zero upon success, 0 upon failure. */
419 if (CloseHandle(port->hdl) == 0)
422 /* Returns 0 upon success, -1 upon failure. */
423 if (close(port->fd) == -1)
430 int sp_flush(struct sp_port *port)
435 /* Returns non-zero upon success, 0 upon failure. */
436 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
439 /* Returns 0 upon success, -1 upon failure. */
440 if (tcflush(port->fd, TCIOFLUSH) < 0)
446 int sp_write(struct sp_port *port, const void *buf, size_t count)
455 /* Returns non-zero upon success, 0 upon failure. */
456 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
460 /* Returns the number of bytes written, or -1 upon failure. */
461 ssize_t written = write(port->fd, buf, count);
469 int sp_read(struct sp_port *port, void *buf, size_t count)
477 DWORD bytes_read = 0;
478 /* Returns non-zero upon success, 0 upon failure. */
479 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
484 /* Returns the number of bytes read, or -1 upon failure. */
485 if ((bytes_read = read(port->fd, buf, count)) < 0)
491 static int start_config(struct sp_port *port, struct sp_port_data *data)
495 if (!GetCommState(port->hdl, &data->dcb))
498 if (tcgetattr(port->fd, &data->term) < 0)
504 static int set_baudrate(struct sp_port_data *data, int baudrate)
509 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
510 * have documented CBR_* macros.
513 data->dcb.BaudRate = CBR_110;
516 data->dcb.BaudRate = CBR_300;
519 data->dcb.BaudRate = CBR_600;
522 data->dcb.BaudRate = CBR_1200;
525 data->dcb.BaudRate = CBR_2400;
528 data->dcb.BaudRate = CBR_4800;
531 data->dcb.BaudRate = CBR_9600;
534 data->dcb.BaudRate = CBR_14400; /* Not available on Unix? */
537 data->dcb.BaudRate = CBR_19200;
540 data->dcb.BaudRate = CBR_38400;
543 data->dcb.BaudRate = CBR_57600;
546 data->dcb.BaudRate = CBR_115200;
549 data->dcb.BaudRate = CBR_128000; /* Not available on Unix? */
552 data->dcb.BaudRate = CBR_256000; /* Not available on Unix? */
608 data->baud = B115200;
611 data->baud = B230400;
613 #if !defined(__APPLE__) && !defined(__OpenBSD__)
615 data->baud = B460800;
625 static int set_bits(struct sp_port_data *data, int bits)
628 data->dcb.ByteSize = bits;
630 data->term.c_cflag &= ~CSIZE;
633 data->term.c_cflag |= CS8;
636 data->term.c_cflag |= CS7;
639 data->term.c_cflag |= CS6;
648 static int set_parity(struct sp_port_data *data, int parity)
652 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
654 data->dcb.Parity = NOPARITY;
657 data->dcb.Parity = EVENPARITY;
660 data->dcb.Parity = ODDPARITY;
666 data->term.c_iflag &= ~IGNPAR;
667 data->term.c_cflag &= ~(PARENB | PARODD);
670 data->term.c_iflag |= IGNPAR;
673 data->term.c_cflag |= PARENB;
676 data->term.c_cflag |= PARENB | PARODD;
685 static int set_stopbits(struct sp_port_data *data, int stopbits)
689 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
691 data->dcb.StopBits = ONESTOPBIT;
694 data->dcb.StopBits = TWOSTOPBITS;
700 data->term.c_cflag &= ~CSTOPB;
703 data->term.c_cflag &= ~CSTOPB;
706 data->term.c_cflag |= CSTOPB;
715 static int set_flowcontrol(struct sp_port_data *data, int flowcontrol)
718 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
719 data->term.c_cflag &= ~CRTSCTS;
720 switch (flowcontrol) {
722 /* No flow control. */
725 data->term.c_cflag |= CRTSCTS;
728 data->term.c_iflag |= IXON | IXOFF | IXANY;
737 static int set_rts(struct sp_port_data *data, int rts)
742 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
744 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
752 static int set_dtr(struct sp_port_data *data, int dtr)
757 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
759 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
767 static int apply_config(struct sp_port *port, struct sp_port_data *data)
770 if (!SetCommState(port->hdl, &data->dcb))
775 /* Turn off all serial port cooking. */
776 data->term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
777 data->term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
778 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
779 data->term.c_oflag &= ~OFILL;
781 /* Disable canonical mode, and don't echo input characters. */
782 data->term.c_lflag &= ~(ICANON | ECHO);
784 /* Ignore modem status lines; enable receiver */
785 data->term.c_cflag |= (CLOCAL | CREAD);
787 /* Write the configured settings. */
788 if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
791 if (cfsetospeed(&data->term, data->baud) < 0)
794 if (cfsetispeed(&data->term, data->baud) < 0)
797 if (data->rts != -1) {
798 controlbits = TIOCM_RTS;
799 if (ioctl(port->fd, data->rts ? TIOCMBIS : TIOCMBIC,
804 if (data->dtr != -1) {
805 controlbits = TIOCM_DTR;
806 if (ioctl(port->fd, data->dtr ? TIOCMBIS : TIOCMBIC,
814 #define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
816 int sp_set_params(struct sp_port *port, int baudrate, int bits, int parity,
817 int stopbits, int flowcontrol, int rts, int dtr)
819 struct sp_port_data data;
821 TRY(start_config(port, &data));
822 TRY(set_baudrate(&data, baudrate));
823 TRY(set_bits(&data, bits));
824 TRY(set_parity(&data, parity));
825 TRY(set_stopbits(&data, stopbits));
826 TRY(set_flowcontrol(&data, flowcontrol));
827 TRY(set_rts(&data, rts));
828 TRY(set_dtr(&data, dtr));
829 TRY(apply_config(port, &data));
834 int sp_last_error_code(void)
837 return GetLastError();
843 char *sp_last_error_message(void)
847 DWORD error = GetLastError();
850 FORMAT_MESSAGE_ALLOCATE_BUFFER |
851 FORMAT_MESSAGE_FROM_SYSTEM |
852 FORMAT_MESSAGE_IGNORE_INSERTS,
855 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
861 return strerror(errno);
865 void sp_free_error_message(char *message)