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 int sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
58 if (!(port = malloc(sizeof(struct sp_port))))
61 len = strlen(portname) + 1;
63 if (!(port->name = malloc(len)))
69 memcpy(port->name, portname, len);
76 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
80 for (count = 0; list[count]; count++);
81 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
84 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
86 list[count + 1] = NULL;
89 sp_free_port_list(list);
94 * List the serial ports available on the system.
96 * @return A null-terminated array of port name strings.
98 int sp_list_ports(struct sp_port ***list_ptr)
100 struct sp_port **list;
103 if (!(list = malloc(sizeof(struct sp_port **))))
111 DWORD max_value_len, max_data_size, max_data_len;
112 DWORD value_len, data_size, data_len;
113 DWORD type, index = 0;
117 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
118 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
123 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
124 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
129 max_data_len = max_data_size / sizeof(TCHAR);
130 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
135 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
141 value_len = max_value_len,
142 data_size = max_data_size,
143 RegEnumValue(key, index, value, &value_len,
144 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
146 data_len = data_size / sizeof(TCHAR);
147 data[data_len] = '\0';
149 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
151 name_len = data_len + 1;
153 if (!(name = malloc(name_len)))
159 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
163 if (type == REG_SZ && !(list = sp_list_append(list, name)))
180 CFMutableDictionaryRef classes;
187 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
193 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
199 CFDictionarySetValue(classes,
200 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
202 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
208 if (!(path = malloc(PATH_MAX)))
214 while ((port = IOIteratorNext(iter))) {
215 cf_path = IORegistryEntryCreateCFProperty(port,
216 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
218 result = CFStringGetCString(cf_path,
219 path, PATH_MAX, kCFStringEncodingASCII);
221 if (result && !(list = sp_list_append(list, path)))
224 IOObjectRelease(port);
228 IOObjectRelease(port);
233 IOObjectRelease(iter);
238 struct udev_enumerate *ud_enumerate;
239 struct udev_list_entry *ud_list;
240 struct udev_list_entry *ud_entry;
242 struct udev_device *ud_dev, *ud_parent;
245 int fd, ioctl_result;
246 struct serial_struct serial_info;
249 ud_enumerate = udev_enumerate_new(ud);
250 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
251 udev_enumerate_scan_devices(ud_enumerate);
252 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
253 udev_list_entry_foreach(ud_entry, ud_list)
255 path = udev_list_entry_get_name(ud_entry);
256 ud_dev = udev_device_new_from_syspath(ud, path);
257 /* If there is no parent device, this is a virtual tty. */
258 ud_parent = udev_device_get_parent(ud_dev);
259 if (ud_parent == NULL)
261 udev_device_unref(ud_dev);
264 name = udev_device_get_devnode(ud_dev);
265 /* The serial8250 driver has a hardcoded number of ports.
266 * The only way to tell which actually exist on a given system
267 * is to try to open them and make an ioctl call. */
268 driver = udev_device_get_driver(ud_parent);
269 if (driver && !strcmp(driver, "serial8250"))
271 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
273 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
275 if (ioctl_result != 0)
277 if (serial_info.type == PORT_UNKNOWN)
280 list = sp_list_append(list, name);
282 udev_device_unref(ud_dev);
290 udev_enumerate_unref(ud_enumerate);
301 sp_free_port_list(list);
310 * Free a port list returned by sp_list_ports.
312 void sp_free_port_list(struct sp_port **list)
315 for (i = 0; list[i]; i++)
320 static int sp_validate_port(struct sp_port *port)
325 if (port->hdl == INVALID_HANDLE_VALUE)
334 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
337 * Open the specified serial port.
339 * @param port Pointer to empty port structure allocated by caller.
340 * @param portname Name of port to open.
341 * @param flags Flags to use when opening the serial port. Possible flags
342 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
344 * @return SP_OK on success, SP_ERR_FAIL on failure,
345 * or SP_ERR_ARG if an invalid port or name is passed.
347 int sp_open(struct sp_port *port, int flags)
353 DWORD desired_access = 0, flags_and_attributes = 0;
354 /* Map 'flags' to the OS-specific settings. */
355 desired_access |= GENERIC_READ;
356 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
357 if (flags & SP_MODE_RDWR)
358 desired_access |= GENERIC_WRITE;
359 if (flags & SP_MODE_NONBLOCK)
360 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
362 port->hdl = CreateFile(port->name, desired_access, 0, 0,
363 OPEN_EXISTING, flags_and_attributes, 0);
364 if (port->hdl == INVALID_HANDLE_VALUE)
368 /* Map 'flags' to the OS-specific settings. */
369 if (flags & SP_MODE_RDWR)
370 flags_local |= O_RDWR;
371 if (flags & SP_MODE_RDONLY)
372 flags_local |= O_RDONLY;
373 if (flags & SP_MODE_NONBLOCK)
374 flags_local |= O_NONBLOCK;
376 if ((port->fd = open(port->name, flags_local)) < 0)
384 * Close the specified serial port.
386 * @param port Pointer to port structure.
388 * @return SP_OK on success, SP_ERR_FAIL on failure,
389 * or SP_ERR_ARG if an invalid port is passed.
391 int sp_close(struct sp_port *port)
396 /* Returns non-zero upon success, 0 upon failure. */
397 if (CloseHandle(port->hdl) == 0)
400 /* Returns 0 upon success, -1 upon failure. */
401 if (close(port->fd) == -1)
409 * Flush serial port buffers.
411 * @param port Pointer to port structure.
413 * @return SP_OK on success, SP_ERR_FAIL on failure,
414 * or SP_ERR_ARG if an invalid port is passed.
416 int sp_flush(struct sp_port *port)
421 /* Returns non-zero upon success, 0 upon failure. */
422 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
425 /* Returns 0 upon success, -1 upon failure. */
426 if (tcflush(port->fd, TCIOFLUSH) < 0)
433 * Write a number of bytes to the specified serial port.
435 * @param port Pointer to port structure.
436 * @param buf Buffer containing the bytes to write.
437 * @param count Number of bytes to write.
439 * @return The number of bytes written, SP_ERR_FAIL on failure,
440 * or SP_ERR_ARG if an invalid port is passed.
442 int sp_write(struct sp_port *port, const void *buf, size_t count)
451 /* Returns non-zero upon success, 0 upon failure. */
452 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
456 /* Returns the number of bytes written, or -1 upon failure. */
457 ssize_t written = write(port->fd, buf, count);
466 * Read a number of bytes from the specified serial port.
468 * @param port Pointer to port structure.
469 * @param buf Buffer where to store the bytes that are read.
470 * @param count The number of bytes to read.
472 * @return The number of bytes read, SP_ERR_FAIL on failure,
473 * or SP_ERR_ARG if an invalid port is passed.
475 int sp_read(struct sp_port *port, void *buf, size_t count)
483 DWORD bytes_read = 0;
484 /* Returns non-zero upon success, 0 upon failure. */
485 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
490 /* Returns the number of bytes read, or -1 upon failure. */
491 if ((bytes_read = read(port->fd, buf, count)) < 0)
498 * Set serial parameters for the specified serial port.
500 * @param port Pointer to port structure.
501 * @param baudrate The baudrate to set.
502 * @param bits The number of data bits to use.
503 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
504 * @param stopbits The number of stop bits to use (1 or 2).
505 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
508 * @return The number of bytes read, SP_ERR_FAIL on failure,
509 * or SP_ERR_ARG if an invalid argument is passed.
511 int sp_set_params(struct sp_port *port, int baudrate,
512 int bits, int parity, int stopbits,
513 int flowcontrol, int rts, int dtr)
520 if (!GetCommState(port->hdl, &dcb))
525 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
526 * have documented CBR_* macros.
529 dcb.BaudRate = CBR_110;
532 dcb.BaudRate = CBR_300;
535 dcb.BaudRate = CBR_600;
538 dcb.BaudRate = CBR_1200;
541 dcb.BaudRate = CBR_2400;
544 dcb.BaudRate = CBR_4800;
547 dcb.BaudRate = CBR_9600;
550 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
553 dcb.BaudRate = CBR_19200;
556 dcb.BaudRate = CBR_38400;
559 dcb.BaudRate = CBR_57600;
562 dcb.BaudRate = CBR_115200;
565 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
568 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
575 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
577 dcb.StopBits = ONESTOPBIT;
580 dcb.StopBits = TWOSTOPBITS;
587 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
589 dcb.Parity = NOPARITY;
592 dcb.Parity = EVENPARITY;
595 dcb.Parity = ODDPARITY;
603 dcb.fRtsControl = RTS_CONTROL_ENABLE;
605 dcb.fRtsControl = RTS_CONTROL_DISABLE;
610 dcb.fDtrControl = DTR_CONTROL_ENABLE;
612 dcb.fDtrControl = DTR_CONTROL_DISABLE;
615 if (!SetCommState(port->hdl, &dcb))
622 if (tcgetattr(port->fd, &term) < 0)
680 #if !defined(__APPLE__) && !defined(__OpenBSD__)
689 if (cfsetospeed(&term, baud) < 0)
692 if (cfsetispeed(&term, baud) < 0)
695 term.c_cflag &= ~CSIZE;
707 term.c_cflag &= ~CSTOPB;
710 term.c_cflag &= ~CSTOPB;
713 term.c_cflag |= CSTOPB;
719 term.c_iflag &= ~(IXON | IXOFF | IXANY);
720 term.c_cflag &= ~CRTSCTS;
721 switch (flowcontrol) {
723 /* No flow control. */
726 term.c_cflag |= CRTSCTS;
729 term.c_iflag |= IXON | IXOFF | IXANY;
735 term.c_iflag &= ~IGNPAR;
736 term.c_cflag &= ~(PARENB | PARODD);
739 term.c_iflag |= IGNPAR;
742 term.c_cflag |= PARENB;
745 term.c_cflag |= PARENB | PARODD;
751 /* Turn off all serial port cooking. */
752 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
753 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
754 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
755 term.c_oflag &= ~OFILL;
758 /* Disable canonical mode, and don't echo input characters. */
759 term.c_lflag &= ~(ICANON | ECHO);
761 /* Ignore modem status lines; enable receiver */
762 term.c_cflag |= (CLOCAL | CREAD);
764 /* Write the configured settings. */
765 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
769 controlbits = TIOCM_RTS;
770 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
776 controlbits = TIOCM_DTR;
777 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
787 * Get error code for failed operation.
789 * In order to obtain the correct result, this function should be called
790 * straight after the failure, before executing any other system operations.
792 * @return The system's numeric code for the error that caused the last
795 int sp_last_error_code(void)
798 return GetLastError();
805 * Get error message for failed operation.
807 * In order to obtain the correct result, this function should be called
808 * straight after the failure, before executing other system operations.
810 * @return The system's message for the error that caused the last
811 * operation to fail. This string may be allocated by the function,
812 * and can be freed after use by calling sp_free_error_message.
814 char *sp_last_error_message(void)
818 DWORD error = GetLastError();
821 FORMAT_MESSAGE_ALLOCATE_BUFFER |
822 FORMAT_MESSAGE_FROM_SYSTEM |
823 FORMAT_MESSAGE_IGNORE_INSERTS,
826 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
832 return strerror(errno);
837 * Free error message.
839 * This function can be used to free a string returned by the
840 * sp_last_error_message function.
842 void sp_free_error_message(char *message)