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(const char *portname)
53 if (!(port = malloc(sizeof(struct sp_port))))
56 len = strlen(portname) + 1;
58 if (!(port->name = malloc(len)))
64 memcpy(port->name, portname, len);
69 static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
73 for (count = 0; list[count]; count++);
74 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
77 if (!(list[count] = sp_port_new(portname)))
79 list[count + 1] = NULL;
82 sp_free_port_list(list);
87 * List the serial ports available on the system.
89 * @return A null-terminated array of port name strings.
91 struct sp_port **sp_list_ports(void)
93 struct sp_port **list;
95 if (!(list = malloc(sizeof(struct sp_port **))))
103 DWORD max_value_len, max_data_size, max_data_len;
104 DWORD value_len, data_size, data_len;
105 DWORD type, index = 0;
109 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
110 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
112 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
113 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
115 max_data_len = max_data_size / sizeof(TCHAR);
116 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
118 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
121 value_len = max_value_len,
122 data_size = max_data_size,
123 RegEnumValue(key, index, value, &value_len,
124 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
126 data_len = data_size / sizeof(TCHAR);
127 data[data_len] = '\0';
129 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
131 name_len = data_len + 1;
133 if (!(name = malloc(name_len)))
136 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
141 if (!(list = sp_list_append(list, name)))
155 CFMutableDictionaryRef classes;
162 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
165 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
168 CFDictionarySetValue(classes,
169 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
171 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
174 if (!(path = malloc(PATH_MAX)))
177 while ((port = IOIteratorNext(iter))) {
178 cf_path = IORegistryEntryCreateCFProperty(port,
179 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
181 result = CFStringGetCString(cf_path,
182 path, PATH_MAX, kCFStringEncodingASCII);
185 if (!(list = sp_list_append(list, path)))
187 IOObjectRelease(port);
191 IOObjectRelease(port);
197 IOObjectRelease(iter);
202 struct udev_enumerate *ud_enumerate;
203 struct udev_list_entry *ud_list;
204 struct udev_list_entry *ud_entry;
206 struct udev_device *ud_dev, *ud_parent;
209 int fd, ioctl_result;
210 struct serial_struct serial_info;
213 ud_enumerate = udev_enumerate_new(ud);
214 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
215 udev_enumerate_scan_devices(ud_enumerate);
216 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
217 udev_list_entry_foreach(ud_entry, ud_list)
219 path = udev_list_entry_get_name(ud_entry);
220 ud_dev = udev_device_new_from_syspath(ud, path);
221 /* If there is no parent device, this is a virtual tty. */
222 ud_parent = udev_device_get_parent(ud_dev);
223 if (ud_parent == NULL)
225 udev_device_unref(ud_dev);
228 name = udev_device_get_devnode(ud_dev);
229 /* The serial8250 driver has a hardcoded number of ports.
230 * The only way to tell which actually exist on a given system
231 * is to try to open them and make an ioctl call. */
232 driver = udev_device_get_driver(ud_parent);
233 if (driver && !strcmp(driver, "serial8250"))
235 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
237 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
239 if (ioctl_result != 0)
241 if (serial_info.type == PORT_UNKNOWN)
244 list = sp_list_append(list, name);
246 udev_device_unref(ud_dev);
251 udev_enumerate_unref(ud_enumerate);
258 * Free a port list returned by sp_list_ports.
260 void sp_free_port_list(struct sp_port **list)
263 for (i = 0; list[i]; i++)
268 static int sp_validate_port(struct sp_port *port)
273 if (port->hdl == INVALID_HANDLE_VALUE)
282 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
285 * Open the specified serial port.
287 * @param port Pointer to empty port structure allocated by caller.
288 * @param portname Name of port to open.
289 * @param flags Flags to use when opening the serial port. Possible flags
290 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
292 * @return SP_OK on success, SP_ERR_FAIL on failure,
293 * or SP_ERR_ARG if an invalid port or name is passed.
295 int sp_open(struct sp_port *port, int flags)
301 DWORD desired_access = 0, flags_and_attributes = 0;
302 /* Map 'flags' to the OS-specific settings. */
303 desired_access |= GENERIC_READ;
304 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
305 if (flags & SP_MODE_RDWR)
306 desired_access |= GENERIC_WRITE;
307 if (flags & SP_MODE_NONBLOCK)
308 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
310 port->hdl = CreateFile(port->name, desired_access, 0, 0,
311 OPEN_EXISTING, flags_and_attributes, 0);
312 if (port->hdl == INVALID_HANDLE_VALUE)
316 /* Map 'flags' to the OS-specific settings. */
317 if (flags & SP_MODE_RDWR)
318 flags_local |= O_RDWR;
319 if (flags & SP_MODE_RDONLY)
320 flags_local |= O_RDONLY;
321 if (flags & SP_MODE_NONBLOCK)
322 flags_local |= O_NONBLOCK;
324 if ((port->fd = open(port->name, flags_local)) < 0)
332 * Close the specified serial port.
334 * @param port Pointer to port structure.
336 * @return SP_OK on success, SP_ERR_FAIL on failure,
337 * or SP_ERR_ARG if an invalid port is passed.
339 int sp_close(struct sp_port *port)
344 /* Returns non-zero upon success, 0 upon failure. */
345 if (CloseHandle(port->hdl) == 0)
348 /* Returns 0 upon success, -1 upon failure. */
349 if (close(port->fd) == -1)
357 * Flush serial port buffers.
359 * @param port Pointer to port structure.
361 * @return SP_OK on success, SP_ERR_FAIL on failure,
362 * or SP_ERR_ARG if an invalid port is passed.
364 int sp_flush(struct sp_port *port)
369 /* Returns non-zero upon success, 0 upon failure. */
370 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
373 /* Returns 0 upon success, -1 upon failure. */
374 if (tcflush(port->fd, TCIOFLUSH) < 0)
381 * Write a number of bytes to the specified serial port.
383 * @param port Pointer to port structure.
384 * @param buf Buffer containing the bytes to write.
385 * @param count Number of bytes to write.
387 * @return The number of bytes written, SP_ERR_FAIL on failure,
388 * or SP_ERR_ARG if an invalid port is passed.
390 int sp_write(struct sp_port *port, const void *buf, size_t count)
399 /* Returns non-zero upon success, 0 upon failure. */
400 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
404 /* Returns the number of bytes written, or -1 upon failure. */
405 ssize_t written = write(port->fd, buf, count);
414 * Read a number of bytes from the specified serial port.
416 * @param port Pointer to port structure.
417 * @param buf Buffer where to store the bytes that are read.
418 * @param count The number of bytes to read.
420 * @return The number of bytes read, SP_ERR_FAIL on failure,
421 * or SP_ERR_ARG if an invalid port is passed.
423 int sp_read(struct sp_port *port, void *buf, size_t count)
431 DWORD bytes_read = 0;
432 /* Returns non-zero upon success, 0 upon failure. */
433 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
438 /* Returns the number of bytes read, or -1 upon failure. */
439 if ((bytes_read = read(port->fd, buf, count)) < 0)
446 * Set serial parameters for the specified serial port.
448 * @param port Pointer to port structure.
449 * @param baudrate The baudrate to set.
450 * @param bits The number of data bits to use.
451 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
452 * @param stopbits The number of stop bits to use (1 or 2).
453 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
456 * @return The number of bytes read, SP_ERR_FAIL on failure,
457 * or SP_ERR_ARG if an invalid argument is passed.
459 int sp_set_params(struct sp_port *port, int baudrate,
460 int bits, int parity, int stopbits,
461 int flowcontrol, int rts, int dtr)
468 if (!GetCommState(port->hdl, &dcb))
473 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
474 * have documented CBR_* macros.
477 dcb.BaudRate = CBR_110;
480 dcb.BaudRate = CBR_300;
483 dcb.BaudRate = CBR_600;
486 dcb.BaudRate = CBR_1200;
489 dcb.BaudRate = CBR_2400;
492 dcb.BaudRate = CBR_4800;
495 dcb.BaudRate = CBR_9600;
498 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
501 dcb.BaudRate = CBR_19200;
504 dcb.BaudRate = CBR_38400;
507 dcb.BaudRate = CBR_57600;
510 dcb.BaudRate = CBR_115200;
513 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
516 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
523 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
525 dcb.StopBits = ONESTOPBIT;
528 dcb.StopBits = TWOSTOPBITS;
535 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
537 dcb.Parity = NOPARITY;
540 dcb.Parity = EVENPARITY;
543 dcb.Parity = ODDPARITY;
551 dcb.fRtsControl = RTS_CONTROL_ENABLE;
553 dcb.fRtsControl = RTS_CONTROL_DISABLE;
558 dcb.fDtrControl = DTR_CONTROL_ENABLE;
560 dcb.fDtrControl = DTR_CONTROL_DISABLE;
563 if (!SetCommState(port->hdl, &dcb))
570 if (tcgetattr(port->fd, &term) < 0)
628 #if !defined(__APPLE__) && !defined(__OpenBSD__)
637 if (cfsetospeed(&term, baud) < 0)
640 if (cfsetispeed(&term, baud) < 0)
643 term.c_cflag &= ~CSIZE;
655 term.c_cflag &= ~CSTOPB;
658 term.c_cflag &= ~CSTOPB;
661 term.c_cflag |= CSTOPB;
667 term.c_iflag &= ~(IXON | IXOFF | IXANY);
668 term.c_cflag &= ~CRTSCTS;
669 switch (flowcontrol) {
671 /* No flow control. */
674 term.c_cflag |= CRTSCTS;
677 term.c_iflag |= IXON | IXOFF | IXANY;
683 term.c_iflag &= ~IGNPAR;
684 term.c_cflag &= ~(PARENB | PARODD);
687 term.c_iflag |= IGNPAR;
690 term.c_cflag |= PARENB;
693 term.c_cflag |= PARENB | PARODD;
699 /* Turn off all serial port cooking. */
700 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
701 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
702 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
703 term.c_oflag &= ~OFILL;
706 /* Disable canonical mode, and don't echo input characters. */
707 term.c_lflag &= ~(ICANON | ECHO);
709 /* Ignore modem status lines; enable receiver */
710 term.c_cflag |= (CLOCAL | CREAD);
712 /* Write the configured settings. */
713 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
717 controlbits = TIOCM_RTS;
718 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
724 controlbits = TIOCM_DTR;
725 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
735 * Get error code for failed operation.
737 * In order to obtain the correct result, this function should be called
738 * straight after the failure, before executing any other system operations.
740 * @return The system's numeric code for the error that caused the last
743 int sp_last_error_code(void)
746 return GetLastError();
753 * Get error message for failed operation.
755 * In order to obtain the correct result, this function should be called
756 * straight after the failure, before executing other system operations.
758 * @return The system's message for the error that caused the last
759 * operation to fail. This string may be allocated by the function,
760 * and can be freed after use by calling sp_free_error_message.
762 char *sp_last_error_message(void)
766 DWORD error = GetLastError();
769 FORMAT_MESSAGE_ALLOCATE_BUFFER |
770 FORMAT_MESSAGE_FROM_SYSTEM |
771 FORMAT_MESSAGE_IGNORE_INSERTS,
774 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
780 return strerror(errno);
785 * Free error message.
787 * This function can be used to free a string returned by the
788 * sp_last_error_message function.
790 void sp_free_error_message(char *message)