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 struct sp_port *sp_port_new(char *portname, size_t len)
52 if (!(port = malloc(sizeof(struct sp_port))))
55 if (!(port->name = malloc(len)))
61 memcpy(port->name, portname, len);
66 static struct sp_port **sp_list_append(struct sp_port **list, char *portname, size_t len)
70 for (count = 0; list[count]; count++);
71 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
74 if (!(list[count] = sp_port_new(portname, len)))
76 list[count + 1] = NULL;
79 sp_free_port_list(list);
84 * List the serial ports available on the system.
86 * @return A null-terminated array of port name strings.
88 struct sp_port **sp_list_ports(void)
90 struct sp_port **list;
92 if (!(list = malloc(sizeof(struct sp_port **))))
100 DWORD max_value_len, max_data_size, max_data_len;
101 DWORD value_len, data_size, data_len;
102 DWORD type, index = 0;
104 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
105 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
107 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
108 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
110 max_data_len = max_data_size / sizeof(TCHAR);
111 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
113 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
116 value_len = max_value_len,
117 data_size = max_data_size,
118 RegEnumValue(key, index, value, &value_len,
119 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
121 data_len = data_size / sizeof(TCHAR);
122 data[data_len] = '\0';
124 if (!(list = sp_list_append(list,
125 data, (data_len + 1) * sizeof(TCHAR))))
139 CFMutableDictionaryRef classes;
146 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
149 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
152 CFDictionarySetValue(classes,
153 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
155 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
158 if (!(path = malloc(PATH_MAX)))
161 while ((port = IOIteratorNext(iter))) {
162 cf_path = IORegistryEntryCreateCFProperty(port,
163 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
165 result = CFStringGetCString(cf_path,
166 path, PATH_MAX, kCFStringEncodingASCII);
169 if (!(list = sp_list_append(list, path, strlen(path) + 1)))
171 IOObjectRelease(port);
175 IOObjectRelease(port);
181 IOObjectRelease(iter);
186 struct udev_enumerate *ud_enumerate;
187 struct udev_list_entry *ud_list;
188 struct udev_list_entry *ud_entry;
190 struct udev_device *ud_dev, *ud_parent;
193 int fd, ioctl_result;
194 struct serial_struct serial_info;
197 ud_enumerate = udev_enumerate_new(ud);
198 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
199 udev_enumerate_scan_devices(ud_enumerate);
200 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
201 udev_list_entry_foreach(ud_entry, ud_list)
203 path = udev_list_entry_get_name(ud_entry);
204 ud_dev = udev_device_new_from_syspath(ud, path);
205 /* If there is no parent device, this is a virtual tty. */
206 ud_parent = udev_device_get_parent(ud_dev);
207 if (ud_parent == NULL)
209 udev_device_unref(ud_dev);
212 name = udev_device_get_devnode(ud_dev);
213 /* The serial8250 driver has a hardcoded number of ports.
214 * The only way to tell which actually exist on a given system
215 * is to try to open them and make an ioctl call. */
216 driver = udev_device_get_driver(ud_parent);
217 if (driver && !strcmp(driver, "serial8250"))
219 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
221 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
223 if (ioctl_result != 0)
225 if (serial_info.type == PORT_UNKNOWN)
228 list = sp_list_append(list, (void *)name, strlen(name) + 1);
230 udev_device_unref(ud_dev);
235 udev_enumerate_unref(ud_enumerate);
242 * Free a port list returned by sp_list_ports.
244 void sp_free_port_list(struct sp_port **list)
247 for (i = 0; list[i]; i++)
252 static int sp_validate_port(struct sp_port *port)
257 if (port->hdl == INVALID_HANDLE_VALUE)
266 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
269 * Open the specified serial port.
271 * @param port Pointer to empty port structure allocated by caller.
272 * @param portname Name of port to open.
273 * @param flags Flags to use when opening the serial port. Possible flags
274 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
276 * @return SP_OK on success, SP_ERR_FAIL on failure,
277 * or SP_ERR_ARG if an invalid port or name is passed.
279 int sp_open(struct sp_port *port, int flags)
285 DWORD desired_access = 0, flags_and_attributes = 0;
286 /* Map 'flags' to the OS-specific settings. */
287 desired_access |= GENERIC_READ;
288 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
289 if (flags & SP_MODE_RDWR)
290 desired_access |= GENERIC_WRITE;
291 if (flags & SP_MODE_NONBLOCK)
292 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
294 port->hdl = CreateFile(port->name, desired_access, 0, 0,
295 OPEN_EXISTING, flags_and_attributes, 0);
296 if (port->hdl == INVALID_HANDLE_VALUE)
300 /* Map 'flags' to the OS-specific settings. */
301 if (flags & SP_MODE_RDWR)
302 flags_local |= O_RDWR;
303 if (flags & SP_MODE_RDONLY)
304 flags_local |= O_RDONLY;
305 if (flags & SP_MODE_NONBLOCK)
306 flags_local |= O_NONBLOCK;
308 if ((port->fd = open(port->name, flags_local)) < 0)
316 * Close the specified serial port.
318 * @param port Pointer to port structure.
320 * @return SP_OK on success, SP_ERR_FAIL on failure,
321 * or SP_ERR_ARG if an invalid port is passed.
323 int sp_close(struct sp_port *port)
328 /* Returns non-zero upon success, 0 upon failure. */
329 if (CloseHandle(port->hdl) == 0)
332 /* Returns 0 upon success, -1 upon failure. */
333 if (close(port->fd) == -1)
341 * Flush serial port buffers.
343 * @param port Pointer to port structure.
345 * @return SP_OK on success, SP_ERR_FAIL on failure,
346 * or SP_ERR_ARG if an invalid port is passed.
348 int sp_flush(struct sp_port *port)
353 /* Returns non-zero upon success, 0 upon failure. */
354 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
357 /* Returns 0 upon success, -1 upon failure. */
358 if (tcflush(port->fd, TCIOFLUSH) < 0)
365 * Write a number of bytes to the specified serial port.
367 * @param port Pointer to port structure.
368 * @param buf Buffer containing the bytes to write.
369 * @param count Number of bytes to write.
371 * @return The number of bytes written, SP_ERR_FAIL on failure,
372 * or SP_ERR_ARG if an invalid port is passed.
374 int sp_write(struct sp_port *port, const void *buf, size_t count)
383 /* Returns non-zero upon success, 0 upon failure. */
384 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
388 /* Returns the number of bytes written, or -1 upon failure. */
389 ssize_t written = write(port->fd, buf, count);
398 * Read a number of bytes from the specified serial port.
400 * @param port Pointer to port structure.
401 * @param buf Buffer where to store the bytes that are read.
402 * @param count The number of bytes to read.
404 * @return The number of bytes read, SP_ERR_FAIL on failure,
405 * or SP_ERR_ARG if an invalid port is passed.
407 int sp_read(struct sp_port *port, void *buf, size_t count)
415 DWORD bytes_read = 0;
416 /* Returns non-zero upon success, 0 upon failure. */
417 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
422 /* Returns the number of bytes read, or -1 upon failure. */
423 if ((bytes_read = read(port->fd, buf, count)) < 0)
430 * Set serial parameters for the specified serial port.
432 * @param port Pointer to port structure.
433 * @param baudrate The baudrate to set.
434 * @param bits The number of data bits to use.
435 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
436 * @param stopbits The number of stop bits to use (1 or 2).
437 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
440 * @return The number of bytes read, SP_ERR_FAIL on failure,
441 * or SP_ERR_ARG if an invalid argument is passed.
443 int sp_set_params(struct sp_port *port, int baudrate,
444 int bits, int parity, int stopbits,
445 int flowcontrol, int rts, int dtr)
452 if (!GetCommState(port->hdl, &dcb))
457 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
458 * have documented CBR_* macros.
461 dcb.BaudRate = CBR_110;
464 dcb.BaudRate = CBR_300;
467 dcb.BaudRate = CBR_600;
470 dcb.BaudRate = CBR_1200;
473 dcb.BaudRate = CBR_2400;
476 dcb.BaudRate = CBR_4800;
479 dcb.BaudRate = CBR_9600;
482 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
485 dcb.BaudRate = CBR_19200;
488 dcb.BaudRate = CBR_38400;
491 dcb.BaudRate = CBR_57600;
494 dcb.BaudRate = CBR_115200;
497 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
500 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
507 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
509 dcb.StopBits = ONESTOPBIT;
512 dcb.StopBits = TWOSTOPBITS;
519 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
521 dcb.Parity = NOPARITY;
524 dcb.Parity = EVENPARITY;
527 dcb.Parity = ODDPARITY;
535 dcb.fRtsControl = RTS_CONTROL_ENABLE;
537 dcb.fRtsControl = RTS_CONTROL_DISABLE;
542 dcb.fDtrControl = DTR_CONTROL_ENABLE;
544 dcb.fDtrControl = DTR_CONTROL_DISABLE;
547 if (!SetCommState(port->hdl, &dcb))
554 if (tcgetattr(port->fd, &term) < 0)
612 #if !defined(__APPLE__) && !defined(__OpenBSD__)
621 if (cfsetospeed(&term, baud) < 0)
624 if (cfsetispeed(&term, baud) < 0)
627 term.c_cflag &= ~CSIZE;
639 term.c_cflag &= ~CSTOPB;
642 term.c_cflag &= ~CSTOPB;
645 term.c_cflag |= CSTOPB;
651 term.c_iflag &= ~(IXON | IXOFF | IXANY);
652 term.c_cflag &= ~CRTSCTS;
653 switch (flowcontrol) {
655 /* No flow control. */
658 term.c_cflag |= CRTSCTS;
661 term.c_iflag |= IXON | IXOFF | IXANY;
667 term.c_iflag &= ~IGNPAR;
668 term.c_cflag &= ~(PARENB | PARODD);
671 term.c_iflag |= IGNPAR;
674 term.c_cflag |= PARENB;
677 term.c_cflag |= PARENB | PARODD;
683 /* Turn off all serial port cooking. */
684 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
685 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
686 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
687 term.c_oflag &= ~OFILL;
690 /* Disable canonical mode, and don't echo input characters. */
691 term.c_lflag &= ~(ICANON | ECHO);
693 /* Ignore modem status lines; enable receiver */
694 term.c_cflag |= (CLOCAL | CREAD);
696 /* Write the configured settings. */
697 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
701 controlbits = TIOCM_RTS;
702 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
708 controlbits = TIOCM_DTR;
709 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
719 * Get error code for failed operation.
721 * In order to obtain the correct result, this function should be called
722 * straight after the failure, before executing any other system operations.
724 * @return The system's numeric code for the error that caused the last
727 int sp_last_error_code(void)
730 return GetLastError();
737 * Get error message for failed operation.
739 * In order to obtain the correct result, this function should be called
740 * straight after the failure, before executing other system operations.
742 * @return The system's message for the error that caused the last
743 * operation to fail. This string may be allocated by the function,
744 * and can be freed after use by calling sp_free_error_message.
746 char *sp_last_error_message(void)
750 DWORD error = GetLastError();
753 FORMAT_MESSAGE_ALLOCATE_BUFFER |
754 FORMAT_MESSAGE_FROM_SYSTEM |
755 FORMAT_MESSAGE_IGNORE_INSERTS,
758 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
764 return strerror(errno);
769 * Free error message.
771 * This function can be used to free a string returned by the
772 * sp_last_error_message function.
774 void sp_free_error_message(char *message)