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 static char **sp_list_new(void)
51 if ((list = malloc(sizeof(char *))))
56 static char **sp_list_append(char **list, void *data, size_t len)
60 for (count = 0; list[count]; count++);
61 if (!(tmp = realloc(list, sizeof(char *) * (count + 2))))
64 if (!(list[count] = malloc(len)))
66 memcpy(list[count], data, len);
67 list[count + 1] = NULL;
70 sp_free_port_list(list);
75 * List the serial ports available on the system.
77 * @return A null-terminated array of port name strings.
79 char **sp_list_ports(void)
86 DWORD max_value_len, max_data_size, max_data_len;
87 DWORD value_len, data_size, data_len;
88 DWORD type, index = 0;
90 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
91 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
93 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
94 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
96 max_data_len = max_data_size / sizeof(TCHAR);
97 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
99 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
101 if (!(list = sp_list_new()))
104 value_len = max_value_len,
105 data_size = max_data_size,
106 RegEnumValue(key, index, value, &value_len,
107 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
109 data_len = data_size / sizeof(TCHAR);
110 data[data_len] = '\0';
112 if (!(list = sp_list_append(list,
113 data, (data_len + 1) * sizeof(TCHAR))))
127 CFMutableDictionaryRef classes;
134 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
137 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
140 CFDictionarySetValue(classes,
141 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
143 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
146 if (!(path = malloc(PATH_MAX)))
149 if (!(list = sp_list_new()))
152 while ((port = IOIteratorNext(iter))) {
153 cf_path = IORegistryEntryCreateCFProperty(port,
154 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
156 result = CFStringGetCString(cf_path,
157 path, PATH_MAX, kCFStringEncodingASCII);
160 if (!(list = sp_list_append(list, path, strlen(path) + 1)))
162 IOObjectRelease(port);
166 IOObjectRelease(port);
172 IOObjectRelease(iter);
177 struct udev_enumerate *ud_enumerate;
178 struct udev_list_entry *ud_list;
179 struct udev_list_entry *ud_entry;
181 struct udev_device *ud_dev, *ud_parent;
184 int fd, ioctl_result;
185 struct serial_struct serial_info;
188 ud_enumerate = udev_enumerate_new(ud);
189 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
190 udev_enumerate_scan_devices(ud_enumerate);
191 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
192 if (!(list = sp_list_new()))
194 udev_list_entry_foreach(ud_entry, ud_list)
196 path = udev_list_entry_get_name(ud_entry);
197 ud_dev = udev_device_new_from_syspath(ud, path);
198 /* If there is no parent device, this is a virtual tty. */
199 ud_parent = udev_device_get_parent(ud_dev);
200 if (ud_parent == NULL)
202 udev_device_unref(ud_dev);
205 name = udev_device_get_devnode(ud_dev);
206 /* The serial8250 driver has a hardcoded number of ports.
207 * The only way to tell which actually exist on a given system
208 * is to try to open them and make an ioctl call. */
209 driver = udev_device_get_driver(ud_parent);
210 if (driver && !strcmp(driver, "serial8250"))
212 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
214 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
216 if (ioctl_result != 0)
218 if (serial_info.type == PORT_UNKNOWN)
221 list = sp_list_append(list, (void *)name, strlen(name) + 1);
223 udev_device_unref(ud_dev);
228 udev_enumerate_unref(ud_enumerate);
235 * Free a port list returned by sp_list_ports.
237 void sp_free_port_list(char **list)
240 for (i = 0; list[i]; i++)
245 static int sp_validate_port(struct sp_port *port)
250 if (port->hdl == INVALID_HANDLE_VALUE)
259 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
262 * Open the specified serial port.
264 * @param port Pointer to empty port structure allocated by caller.
265 * @param portname Name of port to open.
266 * @param flags Flags to use when opening the serial port. Possible flags
267 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
269 * @return SP_OK on success, SP_ERR_FAIL on failure,
270 * or SP_ERR_ARG if an invalid port or name is passed.
272 int sp_open(struct sp_port *port, char *portname, int flags)
280 port->name = portname;
283 DWORD desired_access = 0, flags_and_attributes = 0;
284 /* Map 'flags' to the OS-specific settings. */
285 desired_access |= GENERIC_READ;
286 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
287 if (flags & SP_MODE_RDWR)
288 desired_access |= GENERIC_WRITE;
289 if (flags & SP_MODE_NONBLOCK)
290 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
292 port->hdl = CreateFile(port->name, desired_access, 0, 0,
293 OPEN_EXISTING, flags_and_attributes, 0);
294 if (port->hdl == INVALID_HANDLE_VALUE)
298 /* Map 'flags' to the OS-specific settings. */
299 if (flags & SP_MODE_RDWR)
300 flags_local |= O_RDWR;
301 if (flags & SP_MODE_RDONLY)
302 flags_local |= O_RDONLY;
303 if (flags & SP_MODE_NONBLOCK)
304 flags_local |= O_NONBLOCK;
306 if ((port->fd = open(port->name, flags_local)) < 0)
314 * Close the specified serial port.
316 * @param port Pointer to port structure.
318 * @return SP_OK on success, SP_ERR_FAIL on failure,
319 * or SP_ERR_ARG if an invalid port is passed.
321 int sp_close(struct sp_port *port)
326 /* Returns non-zero upon success, 0 upon failure. */
327 if (CloseHandle(port->hdl) == 0)
330 /* Returns 0 upon success, -1 upon failure. */
331 if (close(port->fd) == -1)
339 * Flush serial port buffers.
341 * @param port Pointer to port structure.
343 * @return SP_OK on success, SP_ERR_FAIL on failure,
344 * or SP_ERR_ARG if an invalid port is passed.
346 int sp_flush(struct sp_port *port)
351 /* Returns non-zero upon success, 0 upon failure. */
352 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
355 /* Returns 0 upon success, -1 upon failure. */
356 if (tcflush(port->fd, TCIOFLUSH) < 0)
363 * Write a number of bytes to the specified serial port.
365 * @param port Pointer to port structure.
366 * @param buf Buffer containing the bytes to write.
367 * @param count Number of bytes to write.
369 * @return The number of bytes written, SP_ERR_FAIL on failure,
370 * or SP_ERR_ARG if an invalid port is passed.
372 int sp_write(struct sp_port *port, const void *buf, size_t count)
381 /* Returns non-zero upon success, 0 upon failure. */
382 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
386 /* Returns the number of bytes written, or -1 upon failure. */
387 ssize_t written = write(port->fd, buf, count);
396 * Read a number of bytes from the specified serial port.
398 * @param port Pointer to port structure.
399 * @param buf Buffer where to store the bytes that are read.
400 * @param count The number of bytes to read.
402 * @return The number of bytes read, SP_ERR_FAIL on failure,
403 * or SP_ERR_ARG if an invalid port is passed.
405 int sp_read(struct sp_port *port, void *buf, size_t count)
413 DWORD bytes_read = 0;
414 /* Returns non-zero upon success, 0 upon failure. */
415 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
420 /* Returns the number of bytes read, or -1 upon failure. */
421 if ((bytes_read = read(port->fd, buf, count)) < 0)
428 * Set serial parameters for the specified serial port.
430 * @param port Pointer to port structure.
431 * @param baudrate The baudrate to set.
432 * @param bits The number of data bits to use.
433 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
434 * @param stopbits The number of stop bits to use (1 or 2).
435 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
438 * @return The number of bytes read, SP_ERR_FAIL on failure,
439 * or SP_ERR_ARG if an invalid argument is passed.
441 int sp_set_params(struct sp_port *port, int baudrate,
442 int bits, int parity, int stopbits,
443 int flowcontrol, int rts, int dtr)
450 if (!GetCommState(port->hdl, &dcb))
455 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
456 * have documented CBR_* macros.
459 dcb.BaudRate = CBR_110;
462 dcb.BaudRate = CBR_300;
465 dcb.BaudRate = CBR_600;
468 dcb.BaudRate = CBR_1200;
471 dcb.BaudRate = CBR_2400;
474 dcb.BaudRate = CBR_4800;
477 dcb.BaudRate = CBR_9600;
480 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
483 dcb.BaudRate = CBR_19200;
486 dcb.BaudRate = CBR_38400;
489 dcb.BaudRate = CBR_57600;
492 dcb.BaudRate = CBR_115200;
495 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
498 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
505 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
507 dcb.StopBits = ONESTOPBIT;
510 dcb.StopBits = TWOSTOPBITS;
517 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
519 dcb.Parity = NOPARITY;
522 dcb.Parity = EVENPARITY;
525 dcb.Parity = ODDPARITY;
533 dcb.fRtsControl = RTS_CONTROL_ENABLE;
535 dcb.fRtsControl = RTS_CONTROL_DISABLE;
540 dcb.fDtrControl = DTR_CONTROL_ENABLE;
542 dcb.fDtrControl = DTR_CONTROL_DISABLE;
545 if (!SetCommState(port->hdl, &dcb))
552 if (tcgetattr(port->fd, &term) < 0)
610 #if !defined(__APPLE__) && !defined(__OpenBSD__)
619 if (cfsetospeed(&term, baud) < 0)
622 if (cfsetispeed(&term, baud) < 0)
625 term.c_cflag &= ~CSIZE;
637 term.c_cflag &= ~CSTOPB;
640 term.c_cflag &= ~CSTOPB;
643 term.c_cflag |= CSTOPB;
649 term.c_iflag &= ~(IXON | IXOFF | IXANY);
650 term.c_cflag &= ~CRTSCTS;
651 switch (flowcontrol) {
653 /* No flow control. */
656 term.c_cflag |= CRTSCTS;
659 term.c_iflag |= IXON | IXOFF | IXANY;
665 term.c_iflag &= ~IGNPAR;
666 term.c_cflag &= ~(PARENB | PARODD);
669 term.c_iflag |= IGNPAR;
672 term.c_cflag |= PARENB;
675 term.c_cflag |= PARENB | PARODD;
681 /* Turn off all serial port cooking. */
682 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
683 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
684 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
685 term.c_oflag &= ~OFILL;
688 /* Disable canonical mode, and don't echo input characters. */
689 term.c_lflag &= ~(ICANON | ECHO);
691 /* Ignore modem status lines; enable receiver */
692 term.c_cflag |= (CLOCAL | CREAD);
694 /* Write the configured settings. */
695 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
699 controlbits = TIOCM_RTS;
700 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
706 controlbits = TIOCM_DTR;
707 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
717 * Get error code for failed operation.
719 * In order to obtain the correct result, this function should be called
720 * straight after the failure, before executing any other system operations.
722 * @return The system's numeric code for the error that caused the last
725 int sp_last_error_code(void)
728 return GetLastError();
735 * Get error message for failed operation.
737 * In order to obtain the correct result, this function should be called
738 * straight after the failure, before executing other system operations.
740 * @return The system's message for the error that caused the last
741 * operation to fail. This string may be allocated by the function,
742 * and can be freed after use by calling sp_free_error_message.
744 char *sp_last_error_message(void)
748 DWORD error = GetLastError();
751 FORMAT_MESSAGE_ALLOCATE_BUFFER |
752 FORMAT_MESSAGE_FROM_SYSTEM |
753 FORMAT_MESSAGE_IGNORE_INSERTS,
756 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
762 return strerror(errno);
767 * Free error message.
769 * This function can be used to free a string returned by the
770 * sp_last_error_message function.
772 void sp_free_error_message(char *message)