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>
38 #include <serial/IOSerialKeys.h>
44 #include "serialport.h"
46 static char **sp_list_new(void)
49 if ((list = malloc(sizeof(char *))))
54 static char **sp_list_append(char **list, void *data, size_t len)
58 for (count = 0; list[count]; count++);
59 if (!(tmp = realloc(list, sizeof(char *) * (++count + 1))))
62 if (!(list[count] = malloc(len)))
64 memcpy(list[count], data, len);
67 sp_free_port_list(list);
72 * List the serial ports available on the system.
74 * @return A null-terminated array of port name strings.
76 char **sp_list_ports(void)
83 DWORD max_name_len, max_data_size, max_data_len;
84 DWORD name_len, data_size, data_len;
85 DWORD type, index = 0;
87 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
88 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
90 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
91 &max_name_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
93 max_data_len = max_data_size / sizeof(TCHAR);
94 if (!(name = malloc((max_name_len + 1) * sizeof(TCHAR))))
96 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
98 if (!(list = sp_list_new()))
101 name_len = max_name_len,
102 data_size = max_data_size,
103 RegEnumValue(key, index, name, &name_len,
104 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
106 data_len = data_size / sizeof(TCHAR);
107 data[data_len] = '\0';
109 if (!(list = sp_list_append(list,
110 data, (data_len + 1) * sizeof(TCHAR))))
124 CFMutableDictionaryRef classes;
131 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
134 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
137 CFDictionarySetValue(classes,
138 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
140 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
143 if (!(path = malloc(PATH_MAX)))
146 if (!(list = sp_list_new()))
149 while (port = IOIteratorNext(iter)) {
150 cf_path = IORegistryEntryCreateCFProperty(port,
151 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
153 result = CFStringGetCString(cf_path,
154 path, PATH_MAX, kCFStringEncodingASCII);
157 if (!(list = sp_list_append(list, path, strlen(path) + 1)))
159 IOObjectRelease(port);
163 IOObjectRelease(port);
169 IOObjectRelease(iter);
174 struct udev_enumerate *ud_enumerate;
175 struct udev_list_entry *ud_list;
176 struct udev_list_entry *ud_entry;
178 struct udev_device *ud_dev;
182 ud_enumerate = udev_enumerate_new(ud);
183 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
184 udev_enumerate_scan_devices(ud_enumerate);
185 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
186 if (!(list = sp_list_new()))
188 udev_list_entry_foreach(ud_entry, ud_list)
190 path = udev_list_entry_get_name(ud_entry);
191 ud_dev = udev_device_new_from_syspath(ud, path);
192 name = udev_device_get_devnode(ud_dev);
193 list = sp_list_append(list, (void *)name, strlen(name) + 1);
194 udev_device_unref(ud_dev);
199 udev_enumerate_unref(ud_enumerate);
206 * Free a port list returned by sp_list_ports.
208 void sp_free_port_list(char **list)
211 for (i = 0; list[i]; i++)
216 static int sp_validate_port(struct sp_port *port)
221 if (port->hdl == INVALID_HANDLE_VALUE)
230 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
233 * Open the specified serial port.
235 * @param port Pointer to empty port structure allocated by caller.
236 * @param portname Name of port to open.
237 * @param flags Flags to use when opening the serial port. Possible flags
238 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
240 * @return SP_OK on success, SP_ERR_FAIL on failure,
241 * or SP_ERR_ARG if an invalid port or name is passed.
243 int sp_open(struct sp_port *port, char *portname, int flags)
251 port->name = portname;
254 DWORD desired_access = 0, flags_and_attributes = 0;
255 /* Map 'flags' to the OS-specific settings. */
256 desired_access |= GENERIC_READ;
257 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
258 if (flags & SP_MODE_RDWR)
259 desired_access |= GENERIC_WRITE;
260 if (flags & SP_MODE_NONBLOCK)
261 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
263 port->hdl = CreateFile(port->name, desired_access, 0, 0,
264 OPEN_EXISTING, flags_and_attributes, 0);
265 if (port->hdl == INVALID_HANDLE_VALUE)
269 /* Map 'flags' to the OS-specific settings. */
270 if (flags & SP_MODE_RDWR)
271 flags_local |= O_RDWR;
272 if (flags & SP_MODE_RDONLY)
273 flags_local |= O_RDONLY;
274 if (flags & SP_MODE_NONBLOCK)
275 flags_local |= O_NONBLOCK;
277 if ((port->fd = open(port->name, flags_local)) < 0)
285 * Close the specified serial port.
287 * @param port Pointer to port structure.
289 * @return SP_OK on success, SP_ERR_FAIL on failure,
290 * or SP_ERR_ARG if an invalid port is passed.
292 int sp_close(struct sp_port *port)
297 /* Returns non-zero upon success, 0 upon failure. */
298 if (CloseHandle(port->hdl) == 0)
301 /* Returns 0 upon success, -1 upon failure. */
302 if (close(port->fd) == -1)
310 * Flush serial port buffers.
312 * @param port Pointer to port structure.
314 * @return SP_OK on success, SP_ERR_FAIL on failure,
315 * or SP_ERR_ARG if an invalid port is passed.
317 int sp_flush(struct sp_port *port)
322 /* Returns non-zero upon success, 0 upon failure. */
323 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
326 /* Returns 0 upon success, -1 upon failure. */
327 if (tcflush(port->fd, TCIOFLUSH) < 0)
334 * Write a number of bytes to the specified serial port.
336 * @param port Pointer to port structure.
337 * @param buf Buffer containing the bytes to write.
338 * @param count Number of bytes to write.
340 * @return The number of bytes written, SP_ERR_FAIL on failure,
341 * or SP_ERR_ARG if an invalid port is passed.
343 int sp_write(struct sp_port *port, const void *buf, size_t count)
352 /* Returns non-zero upon success, 0 upon failure. */
353 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
357 /* Returns the number of bytes written, or -1 upon failure. */
358 ssize_t written = write(port->fd, buf, count);
367 * Read a number of bytes from the specified serial port.
369 * @param port Pointer to port structure.
370 * @param buf Buffer where to store the bytes that are read.
371 * @param count The number of bytes to read.
373 * @return The number of bytes read, SP_ERR_FAIL on failure,
374 * or SP_ERR_ARG if an invalid port is passed.
376 int sp_read(struct sp_port *port, void *buf, size_t count)
384 DWORD bytes_read = 0;
385 /* Returns non-zero upon success, 0 upon failure. */
386 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
391 /* Returns the number of bytes read, or -1 upon failure. */
392 if ((bytes_read = read(port->fd, buf, count)) < 0)
399 * Set serial parameters for the specified serial port.
401 * @param port Pointer to port structure.
402 * @param baudrate The baudrate to set.
403 * @param bits The number of data bits to use.
404 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
405 * @param stopbits The number of stop bits to use (1 or 2).
406 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
409 * @return The number of bytes read, SP_ERR_FAIL on failure,
410 * or SP_ERR_ARG if an invalid argument is passed.
412 int sp_set_params(struct sp_port *port, int baudrate,
413 int bits, int parity, int stopbits,
414 int flowcontrol, int rts, int dtr)
421 if (!GetCommState(port->hdl, &dcb))
426 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
427 * have documented CBR_* macros.
430 dcb.BaudRate = CBR_110;
433 dcb.BaudRate = CBR_300;
436 dcb.BaudRate = CBR_600;
439 dcb.BaudRate = CBR_1200;
442 dcb.BaudRate = CBR_2400;
445 dcb.BaudRate = CBR_4800;
448 dcb.BaudRate = CBR_9600;
451 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
454 dcb.BaudRate = CBR_19200;
457 dcb.BaudRate = CBR_38400;
460 dcb.BaudRate = CBR_57600;
463 dcb.BaudRate = CBR_115200;
466 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
469 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
476 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
478 dcb.StopBits = ONESTOPBIT;
481 dcb.StopBits = TWOSTOPBITS;
488 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
490 dcb.Parity = NOPARITY;
493 dcb.Parity = EVENPARITY;
496 dcb.Parity = ODDPARITY;
504 dcb.fRtsControl = RTS_CONTROL_ENABLE;
506 dcb.fRtsControl = RTS_CONTROL_DISABLE;
511 dcb.fDtrControl = DTR_CONTROL_ENABLE;
513 dcb.fDtrControl = DTR_CONTROL_DISABLE;
516 if (!SetCommState(port->hdl, &dcb))
523 if (tcgetattr(port->fd, &term) < 0)
581 #if !defined(__APPLE__) && !defined(__OpenBSD__)
590 if (cfsetospeed(&term, baud) < 0)
593 if (cfsetispeed(&term, baud) < 0)
596 term.c_cflag &= ~CSIZE;
608 term.c_cflag &= ~CSTOPB;
611 term.c_cflag &= ~CSTOPB;
614 term.c_cflag |= CSTOPB;
620 term.c_iflag &= ~(IXON | IXOFF);
621 term.c_cflag &= ~CRTSCTS;
622 switch (flowcontrol) {
624 /* No flow control. */
627 term.c_cflag |= CRTSCTS;
630 term.c_iflag |= IXON | IXOFF;
636 term.c_iflag &= ~IGNPAR;
637 term.c_cflag &= ~(PARODD | PARENB);
640 term.c_iflag |= IGNPAR;
643 term.c_cflag |= PARENB;
646 term.c_cflag |= PARENB | PARODD;
652 /* Turn off all serial port cooking. */
653 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
654 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
655 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
656 term.c_oflag &= ~OFILL;
659 /* Disable canonical mode, and don't echo input characters. */
660 term.c_lflag &= ~(ICANON | ECHO);
662 /* Write the configured settings. */
663 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
667 controlbits = TIOCM_RTS;
668 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
674 controlbits = TIOCM_DTR;
675 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
685 * Get error code for failed operation.
687 * In order to obtain the correct result, this function should be called
688 * straight after the failure, before executing any other system operations.
690 * @return The system's numeric code for the error that caused the last
693 int sp_last_error_code(void)
696 return GetLastError();
703 * Get error message for failed operation.
705 * In order to obtain the correct result, this function should be called
706 * straight after the failure, before executing other system operations.
708 * @return The system's message for the error that caused the last
709 * operation to fail. This string may be allocated by the function,
710 * and can be freed after use by calling sp_free_error_message.
712 char *sp_last_error_message(void)
716 DWORD error = GetLastError();
719 FORMAT_MESSAGE_ALLOCATE_BUFFER |
720 FORMAT_MESSAGE_FROM_SYSTEM |
721 FORMAT_MESSAGE_IGNORE_INSERTS,
724 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
730 return strerror(errno);
735 * Free error message.
737 * This function can be used to free a string returned by the
738 * sp_last_error_message function.
740 void sp_free_error_message(char *message)