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 "serialport.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,
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)))
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 /* Map 'flags' to the OS-specific settings. */
347 desired_access |= GENERIC_READ;
348 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
349 if (flags & SP_MODE_RDWR)
350 desired_access |= GENERIC_WRITE;
351 if (flags & SP_MODE_NONBLOCK)
352 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
354 port->hdl = CreateFile(port->name, desired_access, 0, 0,
355 OPEN_EXISTING, flags_and_attributes, 0);
356 if (port->hdl == INVALID_HANDLE_VALUE)
360 /* Map 'flags' to the OS-specific settings. */
361 if (flags & SP_MODE_RDWR)
362 flags_local |= O_RDWR;
363 if (flags & SP_MODE_RDONLY)
364 flags_local |= O_RDONLY;
365 if (flags & SP_MODE_NONBLOCK)
366 flags_local |= O_NONBLOCK;
368 if ((port->fd = open(port->name, flags_local)) < 0)
375 int sp_close(struct sp_port *port)
380 /* Returns non-zero upon success, 0 upon failure. */
381 if (CloseHandle(port->hdl) == 0)
384 /* Returns 0 upon success, -1 upon failure. */
385 if (close(port->fd) == -1)
392 int sp_flush(struct sp_port *port)
397 /* Returns non-zero upon success, 0 upon failure. */
398 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
401 /* Returns 0 upon success, -1 upon failure. */
402 if (tcflush(port->fd, TCIOFLUSH) < 0)
408 int sp_write(struct sp_port *port, const void *buf, size_t count)
417 /* Returns non-zero upon success, 0 upon failure. */
418 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
422 /* Returns the number of bytes written, or -1 upon failure. */
423 ssize_t written = write(port->fd, buf, count);
431 int sp_read(struct sp_port *port, void *buf, size_t count)
439 DWORD bytes_read = 0;
440 /* Returns non-zero upon success, 0 upon failure. */
441 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
446 /* Returns the number of bytes read, or -1 upon failure. */
447 if ((bytes_read = read(port->fd, buf, count)) < 0)
453 int sp_set_params(struct sp_port *port, int baudrate,
454 int bits, int parity, int stopbits,
455 int flowcontrol, int rts, int dtr)
462 if (!GetCommState(port->hdl, &dcb))
467 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
468 * have documented CBR_* macros.
471 dcb.BaudRate = CBR_110;
474 dcb.BaudRate = CBR_300;
477 dcb.BaudRate = CBR_600;
480 dcb.BaudRate = CBR_1200;
483 dcb.BaudRate = CBR_2400;
486 dcb.BaudRate = CBR_4800;
489 dcb.BaudRate = CBR_9600;
492 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
495 dcb.BaudRate = CBR_19200;
498 dcb.BaudRate = CBR_38400;
501 dcb.BaudRate = CBR_57600;
504 dcb.BaudRate = CBR_115200;
507 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
510 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
517 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
519 dcb.StopBits = ONESTOPBIT;
522 dcb.StopBits = TWOSTOPBITS;
529 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
531 dcb.Parity = NOPARITY;
534 dcb.Parity = EVENPARITY;
537 dcb.Parity = ODDPARITY;
545 dcb.fRtsControl = RTS_CONTROL_ENABLE;
547 dcb.fRtsControl = RTS_CONTROL_DISABLE;
552 dcb.fDtrControl = DTR_CONTROL_ENABLE;
554 dcb.fDtrControl = DTR_CONTROL_DISABLE;
557 if (!SetCommState(port->hdl, &dcb))
564 if (tcgetattr(port->fd, &term) < 0)
622 #if !defined(__APPLE__) && !defined(__OpenBSD__)
631 if (cfsetospeed(&term, baud) < 0)
634 if (cfsetispeed(&term, baud) < 0)
637 term.c_cflag &= ~CSIZE;
649 term.c_cflag &= ~CSTOPB;
652 term.c_cflag &= ~CSTOPB;
655 term.c_cflag |= CSTOPB;
661 term.c_iflag &= ~(IXON | IXOFF | IXANY);
662 term.c_cflag &= ~CRTSCTS;
663 switch (flowcontrol) {
665 /* No flow control. */
668 term.c_cflag |= CRTSCTS;
671 term.c_iflag |= IXON | IXOFF | IXANY;
677 term.c_iflag &= ~IGNPAR;
678 term.c_cflag &= ~(PARENB | PARODD);
681 term.c_iflag |= IGNPAR;
684 term.c_cflag |= PARENB;
687 term.c_cflag |= PARENB | PARODD;
693 /* Turn off all serial port cooking. */
694 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
695 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
696 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
697 term.c_oflag &= ~OFILL;
700 /* Disable canonical mode, and don't echo input characters. */
701 term.c_lflag &= ~(ICANON | ECHO);
703 /* Ignore modem status lines; enable receiver */
704 term.c_cflag |= (CLOCAL | CREAD);
706 /* Write the configured settings. */
707 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
711 controlbits = TIOCM_RTS;
712 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
718 controlbits = TIOCM_DTR;
719 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
728 int sp_last_error_code(void)
731 return GetLastError();
737 char *sp_last_error_message(void)
741 DWORD error = GetLastError();
744 FORMAT_MESSAGE_ALLOCATE_BUFFER |
745 FORMAT_MESSAGE_FROM_SYSTEM |
746 FORMAT_MESSAGE_IGNORE_INSERTS,
749 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
755 return strerror(errno);
759 void sp_free_error_message(char *message)