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)
61 if (!(port = malloc(sizeof(struct sp_port))))
64 len = strlen(portname) + 1;
66 if (!(port->name = malloc(len)))
72 memcpy(port->name, portname, len);
79 int sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
86 if (!port || !port->name)
89 return sp_get_port_by_name(port->name, copy_ptr);
92 void sp_free_port(struct sp_port *port)
103 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
107 for (count = 0; list[count]; count++);
108 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
111 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
113 list[count + 1] = NULL;
116 sp_free_port_list(list);
120 int sp_list_ports(struct sp_port ***list_ptr)
122 struct sp_port **list;
125 if (!(list = malloc(sizeof(struct sp_port **))))
133 DWORD max_value_len, max_data_size, max_data_len;
134 DWORD value_len, data_size, data_len;
135 DWORD type, index = 0;
139 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
140 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
145 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
146 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
151 max_data_len = max_data_size / sizeof(TCHAR);
152 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
157 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
163 value_len = max_value_len + 1,
164 data_size = max_data_size,
165 RegEnumValue(key, index, value, &value_len,
166 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
168 data_len = data_size / sizeof(TCHAR);
169 data[data_len] = '\0';
171 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
173 name_len = data_len + 1;
175 if (!(name = malloc(name_len)))
181 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
185 if (type == REG_SZ && !(list = sp_list_append(list, name)))
202 CFMutableDictionaryRef classes;
209 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
215 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
221 CFDictionarySetValue(classes,
222 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
224 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS)
230 if (!(path = malloc(PATH_MAX)))
236 while ((port = IOIteratorNext(iter))) {
237 cf_path = IORegistryEntryCreateCFProperty(port,
238 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
240 result = CFStringGetCString(cf_path,
241 path, PATH_MAX, kCFStringEncodingASCII);
243 if (result && !(list = sp_list_append(list, path)))
246 IOObjectRelease(port);
250 IOObjectRelease(port);
255 IOObjectRelease(iter);
260 struct udev_enumerate *ud_enumerate;
261 struct udev_list_entry *ud_list;
262 struct udev_list_entry *ud_entry;
264 struct udev_device *ud_dev, *ud_parent;
267 int fd, ioctl_result;
268 struct serial_struct serial_info;
271 ud_enumerate = udev_enumerate_new(ud);
272 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
273 udev_enumerate_scan_devices(ud_enumerate);
274 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
275 udev_list_entry_foreach(ud_entry, ud_list)
277 path = udev_list_entry_get_name(ud_entry);
278 ud_dev = udev_device_new_from_syspath(ud, path);
279 /* If there is no parent device, this is a virtual tty. */
280 ud_parent = udev_device_get_parent(ud_dev);
281 if (ud_parent == NULL)
283 udev_device_unref(ud_dev);
286 name = udev_device_get_devnode(ud_dev);
287 /* The serial8250 driver has a hardcoded number of ports.
288 * The only way to tell which actually exist on a given system
289 * is to try to open them and make an ioctl call. */
290 driver = udev_device_get_driver(ud_parent);
291 if (driver && !strcmp(driver, "serial8250"))
293 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
295 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
297 if (ioctl_result != 0)
299 if (serial_info.type == PORT_UNKNOWN)
302 list = sp_list_append(list, name);
304 udev_device_unref(ud_dev);
312 udev_enumerate_unref(ud_enumerate);
323 sp_free_port_list(list);
331 void sp_free_port_list(struct sp_port **list)
334 for (i = 0; list[i]; i++)
335 sp_free_port(list[i]);
339 static int sp_validate_port(struct sp_port *port)
344 if (port->hdl == INVALID_HANDLE_VALUE)
353 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
355 int sp_open(struct sp_port *port, int flags)
361 DWORD desired_access = 0, flags_and_attributes = 0;
362 char *escaped_port_name;
364 /* Prefix port name with '\\.\' to work with ports above COM9. */
365 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
367 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
369 /* Map 'flags' to the OS-specific settings. */
370 desired_access |= GENERIC_READ;
371 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
372 if (flags & SP_MODE_RDWR)
373 desired_access |= GENERIC_WRITE;
374 if (flags & SP_MODE_NONBLOCK)
375 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
377 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
378 OPEN_EXISTING, flags_and_attributes, 0);
380 free(escaped_port_name);
382 if (port->hdl == INVALID_HANDLE_VALUE)
386 /* Map 'flags' to the OS-specific settings. */
387 if (flags & SP_MODE_RDWR)
388 flags_local |= O_RDWR;
389 if (flags & SP_MODE_RDONLY)
390 flags_local |= O_RDONLY;
391 if (flags & SP_MODE_NONBLOCK)
392 flags_local |= O_NONBLOCK;
394 if ((port->fd = open(port->name, flags_local)) < 0)
401 int sp_close(struct sp_port *port)
406 /* Returns non-zero upon success, 0 upon failure. */
407 if (CloseHandle(port->hdl) == 0)
410 /* Returns 0 upon success, -1 upon failure. */
411 if (close(port->fd) == -1)
418 int sp_flush(struct sp_port *port)
423 /* Returns non-zero upon success, 0 upon failure. */
424 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
427 /* Returns 0 upon success, -1 upon failure. */
428 if (tcflush(port->fd, TCIOFLUSH) < 0)
434 int sp_write(struct sp_port *port, const void *buf, size_t count)
443 /* Returns non-zero upon success, 0 upon failure. */
444 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
448 /* Returns the number of bytes written, or -1 upon failure. */
449 ssize_t written = write(port->fd, buf, count);
457 int sp_read(struct sp_port *port, void *buf, size_t count)
465 DWORD bytes_read = 0;
466 /* Returns non-zero upon success, 0 upon failure. */
467 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
472 /* Returns the number of bytes read, or -1 upon failure. */
473 if ((bytes_read = read(port->fd, buf, count)) < 0)
479 int sp_set_params(struct sp_port *port, int baudrate,
480 int bits, int parity, int stopbits,
481 int flowcontrol, int rts, int dtr)
488 if (!GetCommState(port->hdl, &dcb))
493 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
494 * have documented CBR_* macros.
497 dcb.BaudRate = CBR_110;
500 dcb.BaudRate = CBR_300;
503 dcb.BaudRate = CBR_600;
506 dcb.BaudRate = CBR_1200;
509 dcb.BaudRate = CBR_2400;
512 dcb.BaudRate = CBR_4800;
515 dcb.BaudRate = CBR_9600;
518 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
521 dcb.BaudRate = CBR_19200;
524 dcb.BaudRate = CBR_38400;
527 dcb.BaudRate = CBR_57600;
530 dcb.BaudRate = CBR_115200;
533 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
536 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
543 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
545 dcb.StopBits = ONESTOPBIT;
548 dcb.StopBits = TWOSTOPBITS;
555 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
557 dcb.Parity = NOPARITY;
560 dcb.Parity = EVENPARITY;
563 dcb.Parity = ODDPARITY;
571 dcb.fRtsControl = RTS_CONTROL_ENABLE;
573 dcb.fRtsControl = RTS_CONTROL_DISABLE;
578 dcb.fDtrControl = DTR_CONTROL_ENABLE;
580 dcb.fDtrControl = DTR_CONTROL_DISABLE;
583 if (!SetCommState(port->hdl, &dcb))
590 if (tcgetattr(port->fd, &term) < 0)
648 #if !defined(__APPLE__) && !defined(__OpenBSD__)
657 if (cfsetospeed(&term, baud) < 0)
660 if (cfsetispeed(&term, baud) < 0)
663 term.c_cflag &= ~CSIZE;
675 term.c_cflag &= ~CSTOPB;
678 term.c_cflag &= ~CSTOPB;
681 term.c_cflag |= CSTOPB;
687 term.c_iflag &= ~(IXON | IXOFF | IXANY);
688 term.c_cflag &= ~CRTSCTS;
689 switch (flowcontrol) {
691 /* No flow control. */
694 term.c_cflag |= CRTSCTS;
697 term.c_iflag |= IXON | IXOFF | IXANY;
703 term.c_iflag &= ~IGNPAR;
704 term.c_cflag &= ~(PARENB | PARODD);
707 term.c_iflag |= IGNPAR;
710 term.c_cflag |= PARENB;
713 term.c_cflag |= PARENB | PARODD;
719 /* Turn off all serial port cooking. */
720 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
721 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
722 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
723 term.c_oflag &= ~OFILL;
726 /* Disable canonical mode, and don't echo input characters. */
727 term.c_lflag &= ~(ICANON | ECHO);
729 /* Ignore modem status lines; enable receiver */
730 term.c_cflag |= (CLOCAL | CREAD);
732 /* Write the configured settings. */
733 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
737 controlbits = TIOCM_RTS;
738 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
744 controlbits = TIOCM_DTR;
745 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
754 int sp_last_error_code(void)
757 return GetLastError();
763 char *sp_last_error_message(void)
767 DWORD error = GetLastError();
770 FORMAT_MESSAGE_ALLOCATE_BUFFER |
771 FORMAT_MESSAGE_FROM_SYSTEM |
772 FORMAT_MESSAGE_IGNORE_INSERTS,
775 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
781 return strerror(errno);
785 void sp_free_error_message(char *message)