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_append(char **list, void *data, size_t len)
52 for (count = 0; list[count]; count++);
53 if (!(tmp = realloc(list, sizeof(char *) * (count + 2))))
56 if (!(list[count] = malloc(len)))
58 memcpy(list[count], data, len);
59 list[count + 1] = NULL;
62 sp_free_port_list(list);
67 * List the serial ports available on the system.
69 * @return A null-terminated array of port name strings.
71 char **sp_list_ports(void)
75 if (!(list = malloc(sizeof(char *))))
83 DWORD max_value_len, max_data_size, max_data_len;
84 DWORD value_len, data_size, data_len;
85 DWORD type, index = 0;
87 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
88 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
90 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
91 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
93 max_data_len = max_data_size / sizeof(TCHAR);
94 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
96 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
99 value_len = max_value_len,
100 data_size = max_data_size,
101 RegEnumValue(key, index, value, &value_len,
102 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
104 data_len = data_size / sizeof(TCHAR);
105 data[data_len] = '\0';
107 if (!(list = sp_list_append(list,
108 data, (data_len + 1) * sizeof(TCHAR))))
122 CFMutableDictionaryRef classes;
129 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
132 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
135 CFDictionarySetValue(classes,
136 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
138 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
141 if (!(path = malloc(PATH_MAX)))
144 while ((port = IOIteratorNext(iter))) {
145 cf_path = IORegistryEntryCreateCFProperty(port,
146 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
148 result = CFStringGetCString(cf_path,
149 path, PATH_MAX, kCFStringEncodingASCII);
152 if (!(list = sp_list_append(list, path, strlen(path) + 1)))
154 IOObjectRelease(port);
158 IOObjectRelease(port);
164 IOObjectRelease(iter);
169 struct udev_enumerate *ud_enumerate;
170 struct udev_list_entry *ud_list;
171 struct udev_list_entry *ud_entry;
173 struct udev_device *ud_dev, *ud_parent;
176 int fd, ioctl_result;
177 struct serial_struct serial_info;
180 ud_enumerate = udev_enumerate_new(ud);
181 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
182 udev_enumerate_scan_devices(ud_enumerate);
183 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
184 udev_list_entry_foreach(ud_entry, ud_list)
186 path = udev_list_entry_get_name(ud_entry);
187 ud_dev = udev_device_new_from_syspath(ud, path);
188 /* If there is no parent device, this is a virtual tty. */
189 ud_parent = udev_device_get_parent(ud_dev);
190 if (ud_parent == NULL)
192 udev_device_unref(ud_dev);
195 name = udev_device_get_devnode(ud_dev);
196 /* The serial8250 driver has a hardcoded number of ports.
197 * The only way to tell which actually exist on a given system
198 * is to try to open them and make an ioctl call. */
199 driver = udev_device_get_driver(ud_parent);
200 if (driver && !strcmp(driver, "serial8250"))
202 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
204 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
206 if (ioctl_result != 0)
208 if (serial_info.type == PORT_UNKNOWN)
211 list = sp_list_append(list, (void *)name, strlen(name) + 1);
213 udev_device_unref(ud_dev);
218 udev_enumerate_unref(ud_enumerate);
225 * Free a port list returned by sp_list_ports.
227 void sp_free_port_list(char **list)
230 for (i = 0; list[i]; i++)
235 static int sp_validate_port(struct sp_port *port)
240 if (port->hdl == INVALID_HANDLE_VALUE)
249 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
252 * Open the specified serial port.
254 * @param port Pointer to empty port structure allocated by caller.
255 * @param portname Name of port to open.
256 * @param flags Flags to use when opening the serial port. Possible flags
257 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
259 * @return SP_OK on success, SP_ERR_FAIL on failure,
260 * or SP_ERR_ARG if an invalid port or name is passed.
262 int sp_open(struct sp_port *port, char *portname, int flags)
270 port->name = portname;
273 DWORD desired_access = 0, flags_and_attributes = 0;
274 /* Map 'flags' to the OS-specific settings. */
275 desired_access |= GENERIC_READ;
276 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
277 if (flags & SP_MODE_RDWR)
278 desired_access |= GENERIC_WRITE;
279 if (flags & SP_MODE_NONBLOCK)
280 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
282 port->hdl = CreateFile(port->name, desired_access, 0, 0,
283 OPEN_EXISTING, flags_and_attributes, 0);
284 if (port->hdl == INVALID_HANDLE_VALUE)
288 /* Map 'flags' to the OS-specific settings. */
289 if (flags & SP_MODE_RDWR)
290 flags_local |= O_RDWR;
291 if (flags & SP_MODE_RDONLY)
292 flags_local |= O_RDONLY;
293 if (flags & SP_MODE_NONBLOCK)
294 flags_local |= O_NONBLOCK;
296 if ((port->fd = open(port->name, flags_local)) < 0)
304 * Close the specified serial port.
306 * @param port Pointer to port structure.
308 * @return SP_OK on success, SP_ERR_FAIL on failure,
309 * or SP_ERR_ARG if an invalid port is passed.
311 int sp_close(struct sp_port *port)
316 /* Returns non-zero upon success, 0 upon failure. */
317 if (CloseHandle(port->hdl) == 0)
320 /* Returns 0 upon success, -1 upon failure. */
321 if (close(port->fd) == -1)
329 * Flush serial port buffers.
331 * @param port Pointer to port structure.
333 * @return SP_OK on success, SP_ERR_FAIL on failure,
334 * or SP_ERR_ARG if an invalid port is passed.
336 int sp_flush(struct sp_port *port)
341 /* Returns non-zero upon success, 0 upon failure. */
342 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
345 /* Returns 0 upon success, -1 upon failure. */
346 if (tcflush(port->fd, TCIOFLUSH) < 0)
353 * Write a number of bytes to the specified serial port.
355 * @param port Pointer to port structure.
356 * @param buf Buffer containing the bytes to write.
357 * @param count Number of bytes to write.
359 * @return The number of bytes written, SP_ERR_FAIL on failure,
360 * or SP_ERR_ARG if an invalid port is passed.
362 int sp_write(struct sp_port *port, const void *buf, size_t count)
371 /* Returns non-zero upon success, 0 upon failure. */
372 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
376 /* Returns the number of bytes written, or -1 upon failure. */
377 ssize_t written = write(port->fd, buf, count);
386 * Read a number of bytes from the specified serial port.
388 * @param port Pointer to port structure.
389 * @param buf Buffer where to store the bytes that are read.
390 * @param count The number of bytes to read.
392 * @return The number of bytes read, SP_ERR_FAIL on failure,
393 * or SP_ERR_ARG if an invalid port is passed.
395 int sp_read(struct sp_port *port, void *buf, size_t count)
403 DWORD bytes_read = 0;
404 /* Returns non-zero upon success, 0 upon failure. */
405 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
410 /* Returns the number of bytes read, or -1 upon failure. */
411 if ((bytes_read = read(port->fd, buf, count)) < 0)
418 * Set serial parameters for the specified serial port.
420 * @param port Pointer to port structure.
421 * @param baudrate The baudrate to set.
422 * @param bits The number of data bits to use.
423 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
424 * @param stopbits The number of stop bits to use (1 or 2).
425 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
428 * @return The number of bytes read, SP_ERR_FAIL on failure,
429 * or SP_ERR_ARG if an invalid argument is passed.
431 int sp_set_params(struct sp_port *port, int baudrate,
432 int bits, int parity, int stopbits,
433 int flowcontrol, int rts, int dtr)
440 if (!GetCommState(port->hdl, &dcb))
445 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
446 * have documented CBR_* macros.
449 dcb.BaudRate = CBR_110;
452 dcb.BaudRate = CBR_300;
455 dcb.BaudRate = CBR_600;
458 dcb.BaudRate = CBR_1200;
461 dcb.BaudRate = CBR_2400;
464 dcb.BaudRate = CBR_4800;
467 dcb.BaudRate = CBR_9600;
470 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
473 dcb.BaudRate = CBR_19200;
476 dcb.BaudRate = CBR_38400;
479 dcb.BaudRate = CBR_57600;
482 dcb.BaudRate = CBR_115200;
485 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
488 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
495 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
497 dcb.StopBits = ONESTOPBIT;
500 dcb.StopBits = TWOSTOPBITS;
507 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
509 dcb.Parity = NOPARITY;
512 dcb.Parity = EVENPARITY;
515 dcb.Parity = ODDPARITY;
523 dcb.fRtsControl = RTS_CONTROL_ENABLE;
525 dcb.fRtsControl = RTS_CONTROL_DISABLE;
530 dcb.fDtrControl = DTR_CONTROL_ENABLE;
532 dcb.fDtrControl = DTR_CONTROL_DISABLE;
535 if (!SetCommState(port->hdl, &dcb))
542 if (tcgetattr(port->fd, &term) < 0)
600 #if !defined(__APPLE__) && !defined(__OpenBSD__)
609 if (cfsetospeed(&term, baud) < 0)
612 if (cfsetispeed(&term, baud) < 0)
615 term.c_cflag &= ~CSIZE;
627 term.c_cflag &= ~CSTOPB;
630 term.c_cflag &= ~CSTOPB;
633 term.c_cflag |= CSTOPB;
639 term.c_iflag &= ~(IXON | IXOFF | IXANY);
640 term.c_cflag &= ~CRTSCTS;
641 switch (flowcontrol) {
643 /* No flow control. */
646 term.c_cflag |= CRTSCTS;
649 term.c_iflag |= IXON | IXOFF | IXANY;
655 term.c_iflag &= ~IGNPAR;
656 term.c_cflag &= ~(PARENB | PARODD);
659 term.c_iflag |= IGNPAR;
662 term.c_cflag |= PARENB;
665 term.c_cflag |= PARENB | PARODD;
671 /* Turn off all serial port cooking. */
672 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
673 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
674 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
675 term.c_oflag &= ~OFILL;
678 /* Disable canonical mode, and don't echo input characters. */
679 term.c_lflag &= ~(ICANON | ECHO);
681 /* Ignore modem status lines; enable receiver */
682 term.c_cflag |= (CLOCAL | CREAD);
684 /* Write the configured settings. */
685 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
689 controlbits = TIOCM_RTS;
690 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
696 controlbits = TIOCM_DTR;
697 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
707 * Get error code for failed operation.
709 * In order to obtain the correct result, this function should be called
710 * straight after the failure, before executing any other system operations.
712 * @return The system's numeric code for the error that caused the last
715 int sp_last_error_code(void)
718 return GetLastError();
725 * Get error message for failed operation.
727 * In order to obtain the correct result, this function should be called
728 * straight after the failure, before executing other system operations.
730 * @return The system's message for the error that caused the last
731 * operation to fail. This string may be allocated by the function,
732 * and can be freed after use by calling sp_free_error_message.
734 char *sp_last_error_message(void)
738 DWORD error = GetLastError();
741 FORMAT_MESSAGE_ALLOCATE_BUFFER |
742 FORMAT_MESSAGE_FROM_SYSTEM |
743 FORMAT_MESSAGE_IGNORE_INSERTS,
746 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
752 return strerror(errno);
757 * Free error message.
759 * This function can be used to free a string returned by the
760 * sp_last_error_message function.
762 void sp_free_error_message(char *message)