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 struct sp_port *sp_get_port_by_name(const char *portname)
56 if (!(port = malloc(sizeof(struct sp_port))))
59 len = strlen(portname) + 1;
61 if (!(port->name = malloc(len)))
67 memcpy(port->name, portname, len);
72 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
76 for (count = 0; list[count]; count++);
77 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
80 if (!(list[count] = sp_get_port_by_name(portname)))
82 list[count + 1] = NULL;
85 sp_free_port_list(list);
90 * List the serial ports available on the system.
92 * @return A null-terminated array of port name strings.
94 struct sp_port **sp_list_ports(void)
96 struct sp_port **list;
98 if (!(list = malloc(sizeof(struct sp_port **))))
106 DWORD max_value_len, max_data_size, max_data_len;
107 DWORD value_len, data_size, data_len;
108 DWORD type, index = 0;
112 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
113 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
115 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
116 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
118 max_data_len = max_data_size / sizeof(TCHAR);
119 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
121 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
124 value_len = max_value_len,
125 data_size = max_data_size,
126 RegEnumValue(key, index, value, &value_len,
127 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
129 data_len = data_size / sizeof(TCHAR);
130 data[data_len] = '\0';
132 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
134 name_len = data_len + 1;
136 if (!(name = malloc(name_len)))
139 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
144 if (!(list = sp_list_append(list, name)))
158 CFMutableDictionaryRef classes;
165 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
168 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
171 CFDictionarySetValue(classes,
172 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
174 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
177 if (!(path = malloc(PATH_MAX)))
180 while ((port = IOIteratorNext(iter))) {
181 cf_path = IORegistryEntryCreateCFProperty(port,
182 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
184 result = CFStringGetCString(cf_path,
185 path, PATH_MAX, kCFStringEncodingASCII);
188 if (!(list = sp_list_append(list, path)))
190 IOObjectRelease(port);
194 IOObjectRelease(port);
200 IOObjectRelease(iter);
205 struct udev_enumerate *ud_enumerate;
206 struct udev_list_entry *ud_list;
207 struct udev_list_entry *ud_entry;
209 struct udev_device *ud_dev, *ud_parent;
212 int fd, ioctl_result;
213 struct serial_struct serial_info;
216 ud_enumerate = udev_enumerate_new(ud);
217 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
218 udev_enumerate_scan_devices(ud_enumerate);
219 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
220 udev_list_entry_foreach(ud_entry, ud_list)
222 path = udev_list_entry_get_name(ud_entry);
223 ud_dev = udev_device_new_from_syspath(ud, path);
224 /* If there is no parent device, this is a virtual tty. */
225 ud_parent = udev_device_get_parent(ud_dev);
226 if (ud_parent == NULL)
228 udev_device_unref(ud_dev);
231 name = udev_device_get_devnode(ud_dev);
232 /* The serial8250 driver has a hardcoded number of ports.
233 * The only way to tell which actually exist on a given system
234 * is to try to open them and make an ioctl call. */
235 driver = udev_device_get_driver(ud_parent);
236 if (driver && !strcmp(driver, "serial8250"))
238 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
240 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
242 if (ioctl_result != 0)
244 if (serial_info.type == PORT_UNKNOWN)
247 list = sp_list_append(list, name);
249 udev_device_unref(ud_dev);
254 udev_enumerate_unref(ud_enumerate);
261 * Free a port list returned by sp_list_ports.
263 void sp_free_port_list(struct sp_port **list)
266 for (i = 0; list[i]; i++)
271 static int sp_validate_port(struct sp_port *port)
276 if (port->hdl == INVALID_HANDLE_VALUE)
285 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
288 * Open the specified serial port.
290 * @param port Pointer to empty port structure allocated by caller.
291 * @param portname Name of port to open.
292 * @param flags Flags to use when opening the serial port. Possible flags
293 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
295 * @return SP_OK on success, SP_ERR_FAIL on failure,
296 * or SP_ERR_ARG if an invalid port or name is passed.
298 int sp_open(struct sp_port *port, int flags)
304 DWORD desired_access = 0, flags_and_attributes = 0;
305 /* Map 'flags' to the OS-specific settings. */
306 desired_access |= GENERIC_READ;
307 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
308 if (flags & SP_MODE_RDWR)
309 desired_access |= GENERIC_WRITE;
310 if (flags & SP_MODE_NONBLOCK)
311 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
313 port->hdl = CreateFile(port->name, desired_access, 0, 0,
314 OPEN_EXISTING, flags_and_attributes, 0);
315 if (port->hdl == INVALID_HANDLE_VALUE)
319 /* Map 'flags' to the OS-specific settings. */
320 if (flags & SP_MODE_RDWR)
321 flags_local |= O_RDWR;
322 if (flags & SP_MODE_RDONLY)
323 flags_local |= O_RDONLY;
324 if (flags & SP_MODE_NONBLOCK)
325 flags_local |= O_NONBLOCK;
327 if ((port->fd = open(port->name, flags_local)) < 0)
335 * Close the specified serial port.
337 * @param port Pointer to port structure.
339 * @return SP_OK on success, SP_ERR_FAIL on failure,
340 * or SP_ERR_ARG if an invalid port is passed.
342 int sp_close(struct sp_port *port)
347 /* Returns non-zero upon success, 0 upon failure. */
348 if (CloseHandle(port->hdl) == 0)
351 /* Returns 0 upon success, -1 upon failure. */
352 if (close(port->fd) == -1)
360 * Flush serial port buffers.
362 * @param port Pointer to port structure.
364 * @return SP_OK on success, SP_ERR_FAIL on failure,
365 * or SP_ERR_ARG if an invalid port is passed.
367 int sp_flush(struct sp_port *port)
372 /* Returns non-zero upon success, 0 upon failure. */
373 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
376 /* Returns 0 upon success, -1 upon failure. */
377 if (tcflush(port->fd, TCIOFLUSH) < 0)
384 * Write a number of bytes to the specified serial port.
386 * @param port Pointer to port structure.
387 * @param buf Buffer containing the bytes to write.
388 * @param count Number of bytes to write.
390 * @return The number of bytes written, SP_ERR_FAIL on failure,
391 * or SP_ERR_ARG if an invalid port is passed.
393 int sp_write(struct sp_port *port, const void *buf, size_t count)
402 /* Returns non-zero upon success, 0 upon failure. */
403 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
407 /* Returns the number of bytes written, or -1 upon failure. */
408 ssize_t written = write(port->fd, buf, count);
417 * Read a number of bytes from the specified serial port.
419 * @param port Pointer to port structure.
420 * @param buf Buffer where to store the bytes that are read.
421 * @param count The number of bytes to read.
423 * @return The number of bytes read, SP_ERR_FAIL on failure,
424 * or SP_ERR_ARG if an invalid port is passed.
426 int sp_read(struct sp_port *port, void *buf, size_t count)
434 DWORD bytes_read = 0;
435 /* Returns non-zero upon success, 0 upon failure. */
436 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
441 /* Returns the number of bytes read, or -1 upon failure. */
442 if ((bytes_read = read(port->fd, buf, count)) < 0)
449 * Set serial parameters for the specified serial port.
451 * @param port Pointer to port structure.
452 * @param baudrate The baudrate to set.
453 * @param bits The number of data bits to use.
454 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
455 * @param stopbits The number of stop bits to use (1 or 2).
456 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
459 * @return The number of bytes read, SP_ERR_FAIL on failure,
460 * or SP_ERR_ARG if an invalid argument is passed.
462 int sp_set_params(struct sp_port *port, int baudrate,
463 int bits, int parity, int stopbits,
464 int flowcontrol, int rts, int dtr)
471 if (!GetCommState(port->hdl, &dcb))
476 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
477 * have documented CBR_* macros.
480 dcb.BaudRate = CBR_110;
483 dcb.BaudRate = CBR_300;
486 dcb.BaudRate = CBR_600;
489 dcb.BaudRate = CBR_1200;
492 dcb.BaudRate = CBR_2400;
495 dcb.BaudRate = CBR_4800;
498 dcb.BaudRate = CBR_9600;
501 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
504 dcb.BaudRate = CBR_19200;
507 dcb.BaudRate = CBR_38400;
510 dcb.BaudRate = CBR_57600;
513 dcb.BaudRate = CBR_115200;
516 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
519 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
526 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
528 dcb.StopBits = ONESTOPBIT;
531 dcb.StopBits = TWOSTOPBITS;
538 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
540 dcb.Parity = NOPARITY;
543 dcb.Parity = EVENPARITY;
546 dcb.Parity = ODDPARITY;
554 dcb.fRtsControl = RTS_CONTROL_ENABLE;
556 dcb.fRtsControl = RTS_CONTROL_DISABLE;
561 dcb.fDtrControl = DTR_CONTROL_ENABLE;
563 dcb.fDtrControl = DTR_CONTROL_DISABLE;
566 if (!SetCommState(port->hdl, &dcb))
573 if (tcgetattr(port->fd, &term) < 0)
631 #if !defined(__APPLE__) && !defined(__OpenBSD__)
640 if (cfsetospeed(&term, baud) < 0)
643 if (cfsetispeed(&term, baud) < 0)
646 term.c_cflag &= ~CSIZE;
658 term.c_cflag &= ~CSTOPB;
661 term.c_cflag &= ~CSTOPB;
664 term.c_cflag |= CSTOPB;
670 term.c_iflag &= ~(IXON | IXOFF | IXANY);
671 term.c_cflag &= ~CRTSCTS;
672 switch (flowcontrol) {
674 /* No flow control. */
677 term.c_cflag |= CRTSCTS;
680 term.c_iflag |= IXON | IXOFF | IXANY;
686 term.c_iflag &= ~IGNPAR;
687 term.c_cflag &= ~(PARENB | PARODD);
690 term.c_iflag |= IGNPAR;
693 term.c_cflag |= PARENB;
696 term.c_cflag |= PARENB | PARODD;
702 /* Turn off all serial port cooking. */
703 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
704 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
705 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
706 term.c_oflag &= ~OFILL;
709 /* Disable canonical mode, and don't echo input characters. */
710 term.c_lflag &= ~(ICANON | ECHO);
712 /* Ignore modem status lines; enable receiver */
713 term.c_cflag |= (CLOCAL | CREAD);
715 /* Write the configured settings. */
716 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
720 controlbits = TIOCM_RTS;
721 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
727 controlbits = TIOCM_DTR;
728 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
738 * Get error code for failed operation.
740 * In order to obtain the correct result, this function should be called
741 * straight after the failure, before executing any other system operations.
743 * @return The system's numeric code for the error that caused the last
746 int sp_last_error_code(void)
749 return GetLastError();
756 * Get error message for failed operation.
758 * In order to obtain the correct result, this function should be called
759 * straight after the failure, before executing other system operations.
761 * @return The system's message for the error that caused the last
762 * operation to fail. This string may be allocated by the function,
763 * and can be freed after use by calling sp_free_error_message.
765 char *sp_last_error_message(void)
769 DWORD error = GetLastError();
772 FORMAT_MESSAGE_ALLOCATE_BUFFER |
773 FORMAT_MESSAGE_FROM_SYSTEM |
774 FORMAT_MESSAGE_IGNORE_INSERTS,
777 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
783 return strerror(errno);
788 * Free error message.
790 * This function can be used to free a string returned by the
791 * sp_last_error_message function.
793 void sp_free_error_message(char *message)