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>
38 #include <serial/IOSerialKeys.h>
42 #include "linux/serial.h"
45 #include "serialport.h"
47 static char **sp_list_new(void)
50 if ((list = malloc(sizeof(char *))))
55 static char **sp_list_append(char **list, void *data, size_t len)
59 for (count = 0; list[count]; count++);
60 if (!(tmp = realloc(list, sizeof(char *) * (count + 2))))
63 if (!(list[count] = malloc(len)))
65 memcpy(list[count], data, len);
66 list[count + 1] = NULL;
69 sp_free_port_list(list);
74 * List the serial ports available on the system.
76 * @return A null-terminated array of port name strings.
78 char **sp_list_ports(void)
85 DWORD max_value_len, max_data_size, max_data_len;
86 DWORD value_len, data_size, data_len;
87 DWORD type, index = 0;
89 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
90 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
92 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
93 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
95 max_data_len = max_data_size / sizeof(TCHAR);
96 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
98 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
100 if (!(list = sp_list_new()))
103 value_len = max_value_len,
104 data_size = max_data_size,
105 RegEnumValue(key, index, value, &value_len,
106 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
108 data_len = data_size / sizeof(TCHAR);
109 data[data_len] = '\0';
111 if (!(list = sp_list_append(list,
112 data, (data_len + 1) * sizeof(TCHAR))))
126 CFMutableDictionaryRef classes;
133 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
136 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
139 CFDictionarySetValue(classes,
140 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
142 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
145 if (!(path = malloc(PATH_MAX)))
148 if (!(list = sp_list_new()))
151 while (port = IOIteratorNext(iter)) {
152 cf_path = IORegistryEntryCreateCFProperty(port,
153 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
155 result = CFStringGetCString(cf_path,
156 path, PATH_MAX, kCFStringEncodingASCII);
159 if (!(list = sp_list_append(list, path, strlen(path) + 1)))
161 IOObjectRelease(port);
165 IOObjectRelease(port);
171 IOObjectRelease(iter);
176 struct udev_enumerate *ud_enumerate;
177 struct udev_list_entry *ud_list;
178 struct udev_list_entry *ud_entry;
180 struct udev_device *ud_dev, *ud_parent;
183 int fd, ioctl_result;
184 struct serial_struct serial_info;
187 ud_enumerate = udev_enumerate_new(ud);
188 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
189 udev_enumerate_scan_devices(ud_enumerate);
190 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
191 if (!(list = sp_list_new()))
193 udev_list_entry_foreach(ud_entry, ud_list)
195 path = udev_list_entry_get_name(ud_entry);
196 ud_dev = udev_device_new_from_syspath(ud, path);
197 /* If there is no parent device, this is a virtual tty. */
198 ud_parent = udev_device_get_parent(ud_dev);
199 if (ud_parent == NULL)
201 udev_device_unref(ud_dev);
204 name = udev_device_get_devnode(ud_dev);
205 /* The serial8250 driver has a hardcoded number of ports.
206 * The only way to tell which actually exist on a given system
207 * is to try to open them and make an ioctl call. */
208 driver = udev_device_get_driver(ud_parent);
209 if (driver && !strcmp(driver, "serial8250"))
211 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
213 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
215 if (ioctl_result != 0)
217 if (serial_info.type == PORT_UNKNOWN)
220 list = sp_list_append(list, (void *)name, strlen(name) + 1);
222 udev_device_unref(ud_dev);
227 udev_enumerate_unref(ud_enumerate);
234 * Free a port list returned by sp_list_ports.
236 void sp_free_port_list(char **list)
239 for (i = 0; list[i]; i++)
244 static int sp_validate_port(struct sp_port *port)
249 if (port->hdl == INVALID_HANDLE_VALUE)
258 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
261 * Open the specified serial port.
263 * @param port Pointer to empty port structure allocated by caller.
264 * @param portname Name of port to open.
265 * @param flags Flags to use when opening the serial port. Possible flags
266 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
268 * @return SP_OK on success, SP_ERR_FAIL on failure,
269 * or SP_ERR_ARG if an invalid port or name is passed.
271 int sp_open(struct sp_port *port, char *portname, int flags)
279 port->name = portname;
282 DWORD desired_access = 0, flags_and_attributes = 0;
283 /* Map 'flags' to the OS-specific settings. */
284 desired_access |= GENERIC_READ;
285 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
286 if (flags & SP_MODE_RDWR)
287 desired_access |= GENERIC_WRITE;
288 if (flags & SP_MODE_NONBLOCK)
289 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
291 port->hdl = CreateFile(port->name, desired_access, 0, 0,
292 OPEN_EXISTING, flags_and_attributes, 0);
293 if (port->hdl == INVALID_HANDLE_VALUE)
297 /* Map 'flags' to the OS-specific settings. */
298 if (flags & SP_MODE_RDWR)
299 flags_local |= O_RDWR;
300 if (flags & SP_MODE_RDONLY)
301 flags_local |= O_RDONLY;
302 if (flags & SP_MODE_NONBLOCK)
303 flags_local |= O_NONBLOCK;
305 if ((port->fd = open(port->name, flags_local)) < 0)
313 * Close the specified serial port.
315 * @param port Pointer to port structure.
317 * @return SP_OK on success, SP_ERR_FAIL on failure,
318 * or SP_ERR_ARG if an invalid port is passed.
320 int sp_close(struct sp_port *port)
325 /* Returns non-zero upon success, 0 upon failure. */
326 if (CloseHandle(port->hdl) == 0)
329 /* Returns 0 upon success, -1 upon failure. */
330 if (close(port->fd) == -1)
338 * Flush serial port buffers.
340 * @param port Pointer to port structure.
342 * @return SP_OK on success, SP_ERR_FAIL on failure,
343 * or SP_ERR_ARG if an invalid port is passed.
345 int sp_flush(struct sp_port *port)
350 /* Returns non-zero upon success, 0 upon failure. */
351 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
354 /* Returns 0 upon success, -1 upon failure. */
355 if (tcflush(port->fd, TCIOFLUSH) < 0)
362 * Write a number of bytes to the specified serial port.
364 * @param port Pointer to port structure.
365 * @param buf Buffer containing the bytes to write.
366 * @param count Number of bytes to write.
368 * @return The number of bytes written, SP_ERR_FAIL on failure,
369 * or SP_ERR_ARG if an invalid port is passed.
371 int sp_write(struct sp_port *port, const void *buf, size_t count)
380 /* Returns non-zero upon success, 0 upon failure. */
381 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
385 /* Returns the number of bytes written, or -1 upon failure. */
386 ssize_t written = write(port->fd, buf, count);
395 * Read a number of bytes from the specified serial port.
397 * @param port Pointer to port structure.
398 * @param buf Buffer where to store the bytes that are read.
399 * @param count The number of bytes to read.
401 * @return The number of bytes read, SP_ERR_FAIL on failure,
402 * or SP_ERR_ARG if an invalid port is passed.
404 int sp_read(struct sp_port *port, void *buf, size_t count)
412 DWORD bytes_read = 0;
413 /* Returns non-zero upon success, 0 upon failure. */
414 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
419 /* Returns the number of bytes read, or -1 upon failure. */
420 if ((bytes_read = read(port->fd, buf, count)) < 0)
427 * Set serial parameters for the specified serial port.
429 * @param port Pointer to port structure.
430 * @param baudrate The baudrate to set.
431 * @param bits The number of data bits to use.
432 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
433 * @param stopbits The number of stop bits to use (1 or 2).
434 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
437 * @return The number of bytes read, SP_ERR_FAIL on failure,
438 * or SP_ERR_ARG if an invalid argument is passed.
440 int sp_set_params(struct sp_port *port, int baudrate,
441 int bits, int parity, int stopbits,
442 int flowcontrol, int rts, int dtr)
449 if (!GetCommState(port->hdl, &dcb))
454 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
455 * have documented CBR_* macros.
458 dcb.BaudRate = CBR_110;
461 dcb.BaudRate = CBR_300;
464 dcb.BaudRate = CBR_600;
467 dcb.BaudRate = CBR_1200;
470 dcb.BaudRate = CBR_2400;
473 dcb.BaudRate = CBR_4800;
476 dcb.BaudRate = CBR_9600;
479 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
482 dcb.BaudRate = CBR_19200;
485 dcb.BaudRate = CBR_38400;
488 dcb.BaudRate = CBR_57600;
491 dcb.BaudRate = CBR_115200;
494 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
497 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
504 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
506 dcb.StopBits = ONESTOPBIT;
509 dcb.StopBits = TWOSTOPBITS;
516 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
518 dcb.Parity = NOPARITY;
521 dcb.Parity = EVENPARITY;
524 dcb.Parity = ODDPARITY;
532 dcb.fRtsControl = RTS_CONTROL_ENABLE;
534 dcb.fRtsControl = RTS_CONTROL_DISABLE;
539 dcb.fDtrControl = DTR_CONTROL_ENABLE;
541 dcb.fDtrControl = DTR_CONTROL_DISABLE;
544 if (!SetCommState(port->hdl, &dcb))
551 if (tcgetattr(port->fd, &term) < 0)
609 #if !defined(__APPLE__) && !defined(__OpenBSD__)
618 if (cfsetospeed(&term, baud) < 0)
621 if (cfsetispeed(&term, baud) < 0)
624 term.c_cflag &= ~CSIZE;
636 term.c_cflag &= ~CSTOPB;
639 term.c_cflag &= ~CSTOPB;
642 term.c_cflag |= CSTOPB;
648 term.c_iflag &= ~(IXON | IXOFF | IXANY);
649 term.c_cflag &= ~CRTSCTS;
650 switch (flowcontrol) {
652 /* No flow control. */
655 term.c_cflag |= CRTSCTS;
658 term.c_iflag |= IXON | IXOFF | IXANY;
664 term.c_iflag &= ~IGNPAR;
665 term.c_cflag &= ~(PARENB | PARODD);
668 term.c_iflag |= IGNPAR;
671 term.c_cflag |= PARENB;
674 term.c_cflag |= PARENB | PARODD;
680 /* Turn off all serial port cooking. */
681 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
682 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
683 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
684 term.c_oflag &= ~OFILL;
687 /* Disable canonical mode, and don't echo input characters. */
688 term.c_lflag &= ~(ICANON | ECHO);
690 /* Ignore modem status lines; enable receiver */
691 term.c_cflag |= (CLOCAL | CREAD);
693 /* Write the configured settings. */
694 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
698 controlbits = TIOCM_RTS;
699 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
705 controlbits = TIOCM_DTR;
706 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
716 * Get error code for failed operation.
718 * In order to obtain the correct result, this function should be called
719 * straight after the failure, before executing any other system operations.
721 * @return The system's numeric code for the error that caused the last
724 int sp_last_error_code(void)
727 return GetLastError();
734 * Get error message for failed operation.
736 * In order to obtain the correct result, this function should be called
737 * straight after the failure, before executing other system operations.
739 * @return The system's message for the error that caused the last
740 * operation to fail. This string may be allocated by the function,
741 * and can be freed after use by calling sp_free_error_message.
743 char *sp_last_error_message(void)
747 DWORD error = GetLastError();
750 FORMAT_MESSAGE_ALLOCATE_BUFFER |
751 FORMAT_MESSAGE_FROM_SYSTEM |
752 FORMAT_MESSAGE_IGNORE_INSERTS,
755 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
761 return strerror(errno);
766 * Free error message.
768 * This function can be used to free a string returned by the
769 * sp_last_error_message function.
771 void sp_free_error_message(char *message)