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 void sp_free_port(struct sp_port *port)
87 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
91 for (count = 0; list[count]; count++);
92 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
95 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
97 list[count + 1] = NULL;
100 sp_free_port_list(list);
105 * List the serial ports available on the system.
107 * @return A null-terminated array of port name strings.
109 int sp_list_ports(struct sp_port ***list_ptr)
111 struct sp_port **list;
114 if (!(list = malloc(sizeof(struct sp_port **))))
122 DWORD max_value_len, max_data_size, max_data_len;
123 DWORD value_len, data_size, data_len;
124 DWORD type, index = 0;
128 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
129 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
134 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
135 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
140 max_data_len = max_data_size / sizeof(TCHAR);
141 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
146 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
152 value_len = max_value_len,
153 data_size = max_data_size,
154 RegEnumValue(key, index, value, &value_len,
155 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
157 data_len = data_size / sizeof(TCHAR);
158 data[data_len] = '\0';
160 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
162 name_len = data_len + 1;
164 if (!(name = malloc(name_len)))
170 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
174 if (type == REG_SZ && !(list = sp_list_append(list, name)))
191 CFMutableDictionaryRef classes;
198 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
204 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
210 CFDictionarySetValue(classes,
211 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
213 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
219 if (!(path = malloc(PATH_MAX)))
225 while ((port = IOIteratorNext(iter))) {
226 cf_path = IORegistryEntryCreateCFProperty(port,
227 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
229 result = CFStringGetCString(cf_path,
230 path, PATH_MAX, kCFStringEncodingASCII);
232 if (result && !(list = sp_list_append(list, path)))
235 IOObjectRelease(port);
239 IOObjectRelease(port);
244 IOObjectRelease(iter);
249 struct udev_enumerate *ud_enumerate;
250 struct udev_list_entry *ud_list;
251 struct udev_list_entry *ud_entry;
253 struct udev_device *ud_dev, *ud_parent;
256 int fd, ioctl_result;
257 struct serial_struct serial_info;
260 ud_enumerate = udev_enumerate_new(ud);
261 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
262 udev_enumerate_scan_devices(ud_enumerate);
263 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
264 udev_list_entry_foreach(ud_entry, ud_list)
266 path = udev_list_entry_get_name(ud_entry);
267 ud_dev = udev_device_new_from_syspath(ud, path);
268 /* If there is no parent device, this is a virtual tty. */
269 ud_parent = udev_device_get_parent(ud_dev);
270 if (ud_parent == NULL)
272 udev_device_unref(ud_dev);
275 name = udev_device_get_devnode(ud_dev);
276 /* The serial8250 driver has a hardcoded number of ports.
277 * The only way to tell which actually exist on a given system
278 * is to try to open them and make an ioctl call. */
279 driver = udev_device_get_driver(ud_parent);
280 if (driver && !strcmp(driver, "serial8250"))
282 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
284 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
286 if (ioctl_result != 0)
288 if (serial_info.type == PORT_UNKNOWN)
291 list = sp_list_append(list, name);
293 udev_device_unref(ud_dev);
301 udev_enumerate_unref(ud_enumerate);
312 sp_free_port_list(list);
321 * Free a port list returned by sp_list_ports.
323 void sp_free_port_list(struct sp_port **list)
326 for (i = 0; list[i]; i++)
327 sp_free_port(list[i]);
331 static int sp_validate_port(struct sp_port *port)
336 if (port->hdl == INVALID_HANDLE_VALUE)
345 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
348 * Open the specified serial port.
350 * @param port Pointer to empty port structure allocated by caller.
351 * @param portname Name of port to open.
352 * @param flags Flags to use when opening the serial port. Possible flags
353 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
355 * @return SP_OK on success, SP_ERR_FAIL on failure,
356 * or SP_ERR_ARG if an invalid port or name is passed.
358 int sp_open(struct sp_port *port, int flags)
364 DWORD desired_access = 0, flags_and_attributes = 0;
365 /* Map 'flags' to the OS-specific settings. */
366 desired_access |= GENERIC_READ;
367 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
368 if (flags & SP_MODE_RDWR)
369 desired_access |= GENERIC_WRITE;
370 if (flags & SP_MODE_NONBLOCK)
371 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
373 port->hdl = CreateFile(port->name, desired_access, 0, 0,
374 OPEN_EXISTING, flags_and_attributes, 0);
375 if (port->hdl == INVALID_HANDLE_VALUE)
379 /* Map 'flags' to the OS-specific settings. */
380 if (flags & SP_MODE_RDWR)
381 flags_local |= O_RDWR;
382 if (flags & SP_MODE_RDONLY)
383 flags_local |= O_RDONLY;
384 if (flags & SP_MODE_NONBLOCK)
385 flags_local |= O_NONBLOCK;
387 if ((port->fd = open(port->name, flags_local)) < 0)
395 * Close the specified serial port.
397 * @param port Pointer to port structure.
399 * @return SP_OK on success, SP_ERR_FAIL on failure,
400 * or SP_ERR_ARG if an invalid port is passed.
402 int sp_close(struct sp_port *port)
407 /* Returns non-zero upon success, 0 upon failure. */
408 if (CloseHandle(port->hdl) == 0)
411 /* Returns 0 upon success, -1 upon failure. */
412 if (close(port->fd) == -1)
420 * Flush serial port buffers.
422 * @param port Pointer to port structure.
424 * @return SP_OK on success, SP_ERR_FAIL on failure,
425 * or SP_ERR_ARG if an invalid port is passed.
427 int sp_flush(struct sp_port *port)
432 /* Returns non-zero upon success, 0 upon failure. */
433 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
436 /* Returns 0 upon success, -1 upon failure. */
437 if (tcflush(port->fd, TCIOFLUSH) < 0)
444 * Write a number of bytes to the specified serial port.
446 * @param port Pointer to port structure.
447 * @param buf Buffer containing the bytes to write.
448 * @param count Number of bytes to write.
450 * @return The number of bytes written, SP_ERR_FAIL on failure,
451 * or SP_ERR_ARG if an invalid port is passed.
453 int sp_write(struct sp_port *port, const void *buf, size_t count)
462 /* Returns non-zero upon success, 0 upon failure. */
463 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
467 /* Returns the number of bytes written, or -1 upon failure. */
468 ssize_t written = write(port->fd, buf, count);
477 * Read a number of bytes from the specified serial port.
479 * @param port Pointer to port structure.
480 * @param buf Buffer where to store the bytes that are read.
481 * @param count The number of bytes to read.
483 * @return The number of bytes read, SP_ERR_FAIL on failure,
484 * or SP_ERR_ARG if an invalid port is passed.
486 int sp_read(struct sp_port *port, void *buf, size_t count)
494 DWORD bytes_read = 0;
495 /* Returns non-zero upon success, 0 upon failure. */
496 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
501 /* Returns the number of bytes read, or -1 upon failure. */
502 if ((bytes_read = read(port->fd, buf, count)) < 0)
509 * Set serial parameters for the specified serial port.
511 * @param port Pointer to port structure.
512 * @param baudrate The baudrate to set.
513 * @param bits The number of data bits to use.
514 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
515 * @param stopbits The number of stop bits to use (1 or 2).
516 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
519 * @return The number of bytes read, SP_ERR_FAIL on failure,
520 * or SP_ERR_ARG if an invalid argument is passed.
522 int sp_set_params(struct sp_port *port, int baudrate,
523 int bits, int parity, int stopbits,
524 int flowcontrol, int rts, int dtr)
531 if (!GetCommState(port->hdl, &dcb))
536 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
537 * have documented CBR_* macros.
540 dcb.BaudRate = CBR_110;
543 dcb.BaudRate = CBR_300;
546 dcb.BaudRate = CBR_600;
549 dcb.BaudRate = CBR_1200;
552 dcb.BaudRate = CBR_2400;
555 dcb.BaudRate = CBR_4800;
558 dcb.BaudRate = CBR_9600;
561 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
564 dcb.BaudRate = CBR_19200;
567 dcb.BaudRate = CBR_38400;
570 dcb.BaudRate = CBR_57600;
573 dcb.BaudRate = CBR_115200;
576 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
579 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
586 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
588 dcb.StopBits = ONESTOPBIT;
591 dcb.StopBits = TWOSTOPBITS;
598 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
600 dcb.Parity = NOPARITY;
603 dcb.Parity = EVENPARITY;
606 dcb.Parity = ODDPARITY;
614 dcb.fRtsControl = RTS_CONTROL_ENABLE;
616 dcb.fRtsControl = RTS_CONTROL_DISABLE;
621 dcb.fDtrControl = DTR_CONTROL_ENABLE;
623 dcb.fDtrControl = DTR_CONTROL_DISABLE;
626 if (!SetCommState(port->hdl, &dcb))
633 if (tcgetattr(port->fd, &term) < 0)
691 #if !defined(__APPLE__) && !defined(__OpenBSD__)
700 if (cfsetospeed(&term, baud) < 0)
703 if (cfsetispeed(&term, baud) < 0)
706 term.c_cflag &= ~CSIZE;
718 term.c_cflag &= ~CSTOPB;
721 term.c_cflag &= ~CSTOPB;
724 term.c_cflag |= CSTOPB;
730 term.c_iflag &= ~(IXON | IXOFF | IXANY);
731 term.c_cflag &= ~CRTSCTS;
732 switch (flowcontrol) {
734 /* No flow control. */
737 term.c_cflag |= CRTSCTS;
740 term.c_iflag |= IXON | IXOFF | IXANY;
746 term.c_iflag &= ~IGNPAR;
747 term.c_cflag &= ~(PARENB | PARODD);
750 term.c_iflag |= IGNPAR;
753 term.c_cflag |= PARENB;
756 term.c_cflag |= PARENB | PARODD;
762 /* Turn off all serial port cooking. */
763 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
764 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
765 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
766 term.c_oflag &= ~OFILL;
769 /* Disable canonical mode, and don't echo input characters. */
770 term.c_lflag &= ~(ICANON | ECHO);
772 /* Ignore modem status lines; enable receiver */
773 term.c_cflag |= (CLOCAL | CREAD);
775 /* Write the configured settings. */
776 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
780 controlbits = TIOCM_RTS;
781 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
787 controlbits = TIOCM_DTR;
788 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
798 * Get error code for failed operation.
800 * In order to obtain the correct result, this function should be called
801 * straight after the failure, before executing any other system operations.
803 * @return The system's numeric code for the error that caused the last
806 int sp_last_error_code(void)
809 return GetLastError();
816 * Get error message for failed operation.
818 * In order to obtain the correct result, this function should be called
819 * straight after the failure, before executing other system operations.
821 * @return The system's message for the error that caused the last
822 * operation to fail. This string may be allocated by the function,
823 * and can be freed after use by calling sp_free_error_message.
825 char *sp_last_error_message(void)
829 DWORD error = GetLastError();
832 FORMAT_MESSAGE_ALLOCATE_BUFFER |
833 FORMAT_MESSAGE_FROM_SYSTEM |
834 FORMAT_MESSAGE_IGNORE_INSERTS,
837 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
843 return strerror(errno);
848 * Free error message.
850 * This function can be used to free a string returned by the
851 * sp_last_error_message function.
853 void sp_free_error_message(char *message)