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>
34 #include <sys/ioctl.h>
37 #include <IOKit/IOKitLib.h>
38 #include <IOKit/serial/IOSerialKeys.h>
39 #include <sys/syslimits.h>
43 #include "linux/serial.h"
46 #include "libserialport.h"
48 int sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
58 if (!(port = malloc(sizeof(struct sp_port))))
61 len = strlen(portname) + 1;
63 if (!(port->name = malloc(len)))
69 memcpy(port->name, portname, len);
76 void sp_free_port(struct sp_port *port)
87 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
91 for (count = 0; list[count]; count++);
92 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
95 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
97 list[count + 1] = NULL;
100 sp_free_port_list(list);
104 int sp_list_ports(struct sp_port ***list_ptr)
106 struct sp_port **list;
109 if (!(list = malloc(sizeof(struct sp_port **))))
117 DWORD max_value_len, max_data_size, max_data_len;
118 DWORD value_len, data_size, data_len;
119 DWORD type, index = 0;
123 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
124 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
129 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
130 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
135 max_data_len = max_data_size / sizeof(TCHAR);
136 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
141 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
147 value_len = max_value_len + 1,
148 data_size = max_data_size,
149 RegEnumValue(key, index, value, &value_len,
150 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
152 data_len = data_size / sizeof(TCHAR);
153 data[data_len] = '\0';
155 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
157 name_len = data_len + 1;
159 if (!(name = malloc(name_len)))
165 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
169 if (type == REG_SZ && !(list = sp_list_append(list, name)))
186 CFMutableDictionaryRef classes;
193 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
199 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
205 CFDictionarySetValue(classes,
206 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
208 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS)
214 if (!(path = malloc(PATH_MAX)))
220 while ((port = IOIteratorNext(iter))) {
221 cf_path = IORegistryEntryCreateCFProperty(port,
222 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
224 result = CFStringGetCString(cf_path,
225 path, PATH_MAX, kCFStringEncodingASCII);
227 if (result && !(list = sp_list_append(list, path)))
230 IOObjectRelease(port);
234 IOObjectRelease(port);
239 IOObjectRelease(iter);
244 struct udev_enumerate *ud_enumerate;
245 struct udev_list_entry *ud_list;
246 struct udev_list_entry *ud_entry;
248 struct udev_device *ud_dev, *ud_parent;
251 int fd, ioctl_result;
252 struct serial_struct serial_info;
255 ud_enumerate = udev_enumerate_new(ud);
256 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
257 udev_enumerate_scan_devices(ud_enumerate);
258 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
259 udev_list_entry_foreach(ud_entry, ud_list)
261 path = udev_list_entry_get_name(ud_entry);
262 ud_dev = udev_device_new_from_syspath(ud, path);
263 /* If there is no parent device, this is a virtual tty. */
264 ud_parent = udev_device_get_parent(ud_dev);
265 if (ud_parent == NULL)
267 udev_device_unref(ud_dev);
270 name = udev_device_get_devnode(ud_dev);
271 /* The serial8250 driver has a hardcoded number of ports.
272 * The only way to tell which actually exist on a given system
273 * is to try to open them and make an ioctl call. */
274 driver = udev_device_get_driver(ud_parent);
275 if (driver && !strcmp(driver, "serial8250"))
277 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
279 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
281 if (ioctl_result != 0)
283 if (serial_info.type == PORT_UNKNOWN)
286 list = sp_list_append(list, name);
288 udev_device_unref(ud_dev);
296 udev_enumerate_unref(ud_enumerate);
307 sp_free_port_list(list);
315 void sp_free_port_list(struct sp_port **list)
318 for (i = 0; list[i]; i++)
319 sp_free_port(list[i]);
323 static int sp_validate_port(struct sp_port *port)
328 if (port->hdl == INVALID_HANDLE_VALUE)
337 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
339 int sp_open(struct sp_port *port, int flags)
345 DWORD desired_access = 0, flags_and_attributes = 0;
346 char *escaped_port_name;
348 /* Prefix port name with '\\.\' to work with ports above COM9. */
349 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
351 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
353 /* Map 'flags' to the OS-specific settings. */
354 desired_access |= GENERIC_READ;
355 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
356 if (flags & SP_MODE_RDWR)
357 desired_access |= GENERIC_WRITE;
358 if (flags & SP_MODE_NONBLOCK)
359 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
361 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
362 OPEN_EXISTING, flags_and_attributes, 0);
364 free(escaped_port_name);
366 if (port->hdl == INVALID_HANDLE_VALUE)
370 /* Map 'flags' to the OS-specific settings. */
371 if (flags & SP_MODE_RDWR)
372 flags_local |= O_RDWR;
373 if (flags & SP_MODE_RDONLY)
374 flags_local |= O_RDONLY;
375 if (flags & SP_MODE_NONBLOCK)
376 flags_local |= O_NONBLOCK;
378 if ((port->fd = open(port->name, flags_local)) < 0)
385 int sp_close(struct sp_port *port)
390 /* Returns non-zero upon success, 0 upon failure. */
391 if (CloseHandle(port->hdl) == 0)
394 /* Returns 0 upon success, -1 upon failure. */
395 if (close(port->fd) == -1)
402 int sp_flush(struct sp_port *port)
407 /* Returns non-zero upon success, 0 upon failure. */
408 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
411 /* Returns 0 upon success, -1 upon failure. */
412 if (tcflush(port->fd, TCIOFLUSH) < 0)
418 int sp_write(struct sp_port *port, const void *buf, size_t count)
427 /* Returns non-zero upon success, 0 upon failure. */
428 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
432 /* Returns the number of bytes written, or -1 upon failure. */
433 ssize_t written = write(port->fd, buf, count);
441 int sp_read(struct sp_port *port, void *buf, size_t count)
449 DWORD bytes_read = 0;
450 /* Returns non-zero upon success, 0 upon failure. */
451 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
456 /* Returns the number of bytes read, or -1 upon failure. */
457 if ((bytes_read = read(port->fd, buf, count)) < 0)
463 int sp_set_params(struct sp_port *port, int baudrate,
464 int bits, int parity, int stopbits,
465 int flowcontrol, int rts, int dtr)
472 if (!GetCommState(port->hdl, &dcb))
477 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
478 * have documented CBR_* macros.
481 dcb.BaudRate = CBR_110;
484 dcb.BaudRate = CBR_300;
487 dcb.BaudRate = CBR_600;
490 dcb.BaudRate = CBR_1200;
493 dcb.BaudRate = CBR_2400;
496 dcb.BaudRate = CBR_4800;
499 dcb.BaudRate = CBR_9600;
502 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
505 dcb.BaudRate = CBR_19200;
508 dcb.BaudRate = CBR_38400;
511 dcb.BaudRate = CBR_57600;
514 dcb.BaudRate = CBR_115200;
517 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
520 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
527 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
529 dcb.StopBits = ONESTOPBIT;
532 dcb.StopBits = TWOSTOPBITS;
539 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
541 dcb.Parity = NOPARITY;
544 dcb.Parity = EVENPARITY;
547 dcb.Parity = ODDPARITY;
555 dcb.fRtsControl = RTS_CONTROL_ENABLE;
557 dcb.fRtsControl = RTS_CONTROL_DISABLE;
562 dcb.fDtrControl = DTR_CONTROL_ENABLE;
564 dcb.fDtrControl = DTR_CONTROL_DISABLE;
567 if (!SetCommState(port->hdl, &dcb))
574 if (tcgetattr(port->fd, &term) < 0)
632 #if !defined(__APPLE__) && !defined(__OpenBSD__)
641 if (cfsetospeed(&term, baud) < 0)
644 if (cfsetispeed(&term, baud) < 0)
647 term.c_cflag &= ~CSIZE;
659 term.c_cflag &= ~CSTOPB;
662 term.c_cflag &= ~CSTOPB;
665 term.c_cflag |= CSTOPB;
671 term.c_iflag &= ~(IXON | IXOFF | IXANY);
672 term.c_cflag &= ~CRTSCTS;
673 switch (flowcontrol) {
675 /* No flow control. */
678 term.c_cflag |= CRTSCTS;
681 term.c_iflag |= IXON | IXOFF | IXANY;
687 term.c_iflag &= ~IGNPAR;
688 term.c_cflag &= ~(PARENB | PARODD);
691 term.c_iflag |= IGNPAR;
694 term.c_cflag |= PARENB;
697 term.c_cflag |= PARENB | PARODD;
703 /* Turn off all serial port cooking. */
704 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
705 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
706 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
707 term.c_oflag &= ~OFILL;
710 /* Disable canonical mode, and don't echo input characters. */
711 term.c_lflag &= ~(ICANON | ECHO);
713 /* Ignore modem status lines; enable receiver */
714 term.c_cflag |= (CLOCAL | CREAD);
716 /* Write the configured settings. */
717 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
721 controlbits = TIOCM_RTS;
722 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
728 controlbits = TIOCM_DTR;
729 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
738 int sp_last_error_code(void)
741 return GetLastError();
747 char *sp_last_error_message(void)
751 DWORD error = GetLastError();
754 FORMAT_MESSAGE_ALLOCATE_BUFFER |
755 FORMAT_MESSAGE_FROM_SYSTEM |
756 FORMAT_MESSAGE_IGNORE_INSERTS,
759 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
765 return strerror(errno);
769 void sp_free_error_message(char *message)