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;
106 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
107 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
109 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
110 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
112 max_data_len = max_data_size / sizeof(TCHAR);
113 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
115 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
118 value_len = max_value_len,
119 data_size = max_data_size,
120 RegEnumValue(key, index, value, &value_len,
121 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
123 data_len = data_size / sizeof(TCHAR);
124 data[data_len] = '\0';
126 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
128 name_len = data_len + 1;
130 if (!(name = malloc(name_len)))
133 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
138 if (!(list = sp_list_append(list, name, name_len)))
152 CFMutableDictionaryRef classes;
159 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
162 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
165 CFDictionarySetValue(classes,
166 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
168 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
171 if (!(path = malloc(PATH_MAX)))
174 while ((port = IOIteratorNext(iter))) {
175 cf_path = IORegistryEntryCreateCFProperty(port,
176 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
178 result = CFStringGetCString(cf_path,
179 path, PATH_MAX, kCFStringEncodingASCII);
182 if (!(list = sp_list_append(list, path, strlen(path) + 1)))
184 IOObjectRelease(port);
188 IOObjectRelease(port);
194 IOObjectRelease(iter);
199 struct udev_enumerate *ud_enumerate;
200 struct udev_list_entry *ud_list;
201 struct udev_list_entry *ud_entry;
203 struct udev_device *ud_dev, *ud_parent;
206 int fd, ioctl_result;
207 struct serial_struct serial_info;
210 ud_enumerate = udev_enumerate_new(ud);
211 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
212 udev_enumerate_scan_devices(ud_enumerate);
213 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
214 udev_list_entry_foreach(ud_entry, ud_list)
216 path = udev_list_entry_get_name(ud_entry);
217 ud_dev = udev_device_new_from_syspath(ud, path);
218 /* If there is no parent device, this is a virtual tty. */
219 ud_parent = udev_device_get_parent(ud_dev);
220 if (ud_parent == NULL)
222 udev_device_unref(ud_dev);
225 name = udev_device_get_devnode(ud_dev);
226 /* The serial8250 driver has a hardcoded number of ports.
227 * The only way to tell which actually exist on a given system
228 * is to try to open them and make an ioctl call. */
229 driver = udev_device_get_driver(ud_parent);
230 if (driver && !strcmp(driver, "serial8250"))
232 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
234 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
236 if (ioctl_result != 0)
238 if (serial_info.type == PORT_UNKNOWN)
241 list = sp_list_append(list, (void *)name, strlen(name) + 1);
243 udev_device_unref(ud_dev);
248 udev_enumerate_unref(ud_enumerate);
255 * Free a port list returned by sp_list_ports.
257 void sp_free_port_list(struct sp_port **list)
260 for (i = 0; list[i]; i++)
265 static int sp_validate_port(struct sp_port *port)
270 if (port->hdl == INVALID_HANDLE_VALUE)
279 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
282 * Open the specified serial port.
284 * @param port Pointer to empty port structure allocated by caller.
285 * @param portname Name of port to open.
286 * @param flags Flags to use when opening the serial port. Possible flags
287 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
289 * @return SP_OK on success, SP_ERR_FAIL on failure,
290 * or SP_ERR_ARG if an invalid port or name is passed.
292 int sp_open(struct sp_port *port, int flags)
298 DWORD desired_access = 0, flags_and_attributes = 0;
299 /* Map 'flags' to the OS-specific settings. */
300 desired_access |= GENERIC_READ;
301 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
302 if (flags & SP_MODE_RDWR)
303 desired_access |= GENERIC_WRITE;
304 if (flags & SP_MODE_NONBLOCK)
305 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
307 port->hdl = CreateFile(port->name, desired_access, 0, 0,
308 OPEN_EXISTING, flags_and_attributes, 0);
309 if (port->hdl == INVALID_HANDLE_VALUE)
313 /* Map 'flags' to the OS-specific settings. */
314 if (flags & SP_MODE_RDWR)
315 flags_local |= O_RDWR;
316 if (flags & SP_MODE_RDONLY)
317 flags_local |= O_RDONLY;
318 if (flags & SP_MODE_NONBLOCK)
319 flags_local |= O_NONBLOCK;
321 if ((port->fd = open(port->name, flags_local)) < 0)
329 * Close the specified serial port.
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_close(struct sp_port *port)
341 /* Returns non-zero upon success, 0 upon failure. */
342 if (CloseHandle(port->hdl) == 0)
345 /* Returns 0 upon success, -1 upon failure. */
346 if (close(port->fd) == -1)
354 * Flush serial port buffers.
356 * @param port Pointer to port structure.
358 * @return SP_OK on success, SP_ERR_FAIL on failure,
359 * or SP_ERR_ARG if an invalid port is passed.
361 int sp_flush(struct sp_port *port)
366 /* Returns non-zero upon success, 0 upon failure. */
367 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
370 /* Returns 0 upon success, -1 upon failure. */
371 if (tcflush(port->fd, TCIOFLUSH) < 0)
378 * Write a number of bytes to the specified serial port.
380 * @param port Pointer to port structure.
381 * @param buf Buffer containing the bytes to write.
382 * @param count Number of bytes to write.
384 * @return The number of bytes written, SP_ERR_FAIL on failure,
385 * or SP_ERR_ARG if an invalid port is passed.
387 int sp_write(struct sp_port *port, const void *buf, size_t count)
396 /* Returns non-zero upon success, 0 upon failure. */
397 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
401 /* Returns the number of bytes written, or -1 upon failure. */
402 ssize_t written = write(port->fd, buf, count);
411 * Read a number of bytes from the specified serial port.
413 * @param port Pointer to port structure.
414 * @param buf Buffer where to store the bytes that are read.
415 * @param count The number of bytes to read.
417 * @return The number of bytes read, SP_ERR_FAIL on failure,
418 * or SP_ERR_ARG if an invalid port is passed.
420 int sp_read(struct sp_port *port, void *buf, size_t count)
428 DWORD bytes_read = 0;
429 /* Returns non-zero upon success, 0 upon failure. */
430 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
435 /* Returns the number of bytes read, or -1 upon failure. */
436 if ((bytes_read = read(port->fd, buf, count)) < 0)
443 * Set serial parameters for the specified serial port.
445 * @param port Pointer to port structure.
446 * @param baudrate The baudrate to set.
447 * @param bits The number of data bits to use.
448 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
449 * @param stopbits The number of stop bits to use (1 or 2).
450 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
453 * @return The number of bytes read, SP_ERR_FAIL on failure,
454 * or SP_ERR_ARG if an invalid argument is passed.
456 int sp_set_params(struct sp_port *port, int baudrate,
457 int bits, int parity, int stopbits,
458 int flowcontrol, int rts, int dtr)
465 if (!GetCommState(port->hdl, &dcb))
470 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
471 * have documented CBR_* macros.
474 dcb.BaudRate = CBR_110;
477 dcb.BaudRate = CBR_300;
480 dcb.BaudRate = CBR_600;
483 dcb.BaudRate = CBR_1200;
486 dcb.BaudRate = CBR_2400;
489 dcb.BaudRate = CBR_4800;
492 dcb.BaudRate = CBR_9600;
495 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
498 dcb.BaudRate = CBR_19200;
501 dcb.BaudRate = CBR_38400;
504 dcb.BaudRate = CBR_57600;
507 dcb.BaudRate = CBR_115200;
510 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
513 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
520 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
522 dcb.StopBits = ONESTOPBIT;
525 dcb.StopBits = TWOSTOPBITS;
532 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
534 dcb.Parity = NOPARITY;
537 dcb.Parity = EVENPARITY;
540 dcb.Parity = ODDPARITY;
548 dcb.fRtsControl = RTS_CONTROL_ENABLE;
550 dcb.fRtsControl = RTS_CONTROL_DISABLE;
555 dcb.fDtrControl = DTR_CONTROL_ENABLE;
557 dcb.fDtrControl = DTR_CONTROL_DISABLE;
560 if (!SetCommState(port->hdl, &dcb))
567 if (tcgetattr(port->fd, &term) < 0)
625 #if !defined(__APPLE__) && !defined(__OpenBSD__)
634 if (cfsetospeed(&term, baud) < 0)
637 if (cfsetispeed(&term, baud) < 0)
640 term.c_cflag &= ~CSIZE;
652 term.c_cflag &= ~CSTOPB;
655 term.c_cflag &= ~CSTOPB;
658 term.c_cflag |= CSTOPB;
664 term.c_iflag &= ~(IXON | IXOFF | IXANY);
665 term.c_cflag &= ~CRTSCTS;
666 switch (flowcontrol) {
668 /* No flow control. */
671 term.c_cflag |= CRTSCTS;
674 term.c_iflag |= IXON | IXOFF | IXANY;
680 term.c_iflag &= ~IGNPAR;
681 term.c_cflag &= ~(PARENB | PARODD);
684 term.c_iflag |= IGNPAR;
687 term.c_cflag |= PARENB;
690 term.c_cflag |= PARENB | PARODD;
696 /* Turn off all serial port cooking. */
697 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
698 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
699 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
700 term.c_oflag &= ~OFILL;
703 /* Disable canonical mode, and don't echo input characters. */
704 term.c_lflag &= ~(ICANON | ECHO);
706 /* Ignore modem status lines; enable receiver */
707 term.c_cflag |= (CLOCAL | CREAD);
709 /* Write the configured settings. */
710 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
714 controlbits = TIOCM_RTS;
715 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
721 controlbits = TIOCM_DTR;
722 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
732 * Get error code for failed operation.
734 * In order to obtain the correct result, this function should be called
735 * straight after the failure, before executing any other system operations.
737 * @return The system's numeric code for the error that caused the last
740 int sp_last_error_code(void)
743 return GetLastError();
750 * Get error message for failed operation.
752 * In order to obtain the correct result, this function should be called
753 * straight after the failure, before executing other system operations.
755 * @return The system's message for the error that caused the last
756 * operation to fail. This string may be allocated by the function,
757 * and can be freed after use by calling sp_free_error_message.
759 char *sp_last_error_message(void)
763 DWORD error = GetLastError();
766 FORMAT_MESSAGE_ALLOCATE_BUFFER |
767 FORMAT_MESSAGE_FROM_SYSTEM |
768 FORMAT_MESSAGE_IGNORE_INSERTS,
771 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
777 return strerror(errno);
782 * Free error message.
784 * This function can be used to free a string returned by the
785 * sp_last_error_message function.
787 void sp_free_error_message(char *message)