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 + 2))))
62 if (!(list[count] = malloc(len)))
64 memcpy(list[count], data, len);
65 list[count + 1] = NULL;
68 sp_free_port_list(list);
73 * List the serial ports available on the system.
75 * @return A null-terminated array of port name strings.
77 char **sp_list_ports(void)
84 DWORD max_name_len, max_data_size, max_data_len;
85 DWORD name_len, data_size, data_len;
86 DWORD type, index = 0;
88 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
89 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
91 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
92 &max_name_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
94 max_data_len = max_data_size / sizeof(TCHAR);
95 if (!(name = malloc((max_name_len + 1) * sizeof(TCHAR))))
97 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
99 if (!(list = sp_list_new()))
102 name_len = max_name_len,
103 data_size = max_data_size,
104 RegEnumValue(key, index, name, &name_len,
105 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
107 data_len = data_size / sizeof(TCHAR);
108 data[data_len] = '\0';
110 if (!(list = sp_list_append(list,
111 data, (data_len + 1) * sizeof(TCHAR))))
125 CFMutableDictionaryRef classes;
132 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
135 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
138 CFDictionarySetValue(classes,
139 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
141 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
144 if (!(path = malloc(PATH_MAX)))
147 if (!(list = sp_list_new()))
150 while (port = IOIteratorNext(iter)) {
151 cf_path = IORegistryEntryCreateCFProperty(port,
152 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
154 result = CFStringGetCString(cf_path,
155 path, PATH_MAX, kCFStringEncodingASCII);
158 if (!(list = sp_list_append(list, path, strlen(path) + 1)))
160 IOObjectRelease(port);
164 IOObjectRelease(port);
170 IOObjectRelease(iter);
175 struct udev_enumerate *ud_enumerate;
176 struct udev_list_entry *ud_list;
177 struct udev_list_entry *ud_entry;
179 struct udev_device *ud_dev;
183 ud_enumerate = udev_enumerate_new(ud);
184 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
185 udev_enumerate_scan_devices(ud_enumerate);
186 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
187 if (!(list = sp_list_new()))
189 udev_list_entry_foreach(ud_entry, ud_list)
191 path = udev_list_entry_get_name(ud_entry);
192 ud_dev = udev_device_new_from_syspath(ud, path);
193 name = udev_device_get_devnode(ud_dev);
194 list = sp_list_append(list, (void *)name, strlen(name) + 1);
195 udev_device_unref(ud_dev);
200 udev_enumerate_unref(ud_enumerate);
207 * Free a port list returned by sp_list_ports.
209 void sp_free_port_list(char **list)
212 for (i = 0; list[i]; i++)
217 static int sp_validate_port(struct sp_port *port)
222 if (port->hdl == INVALID_HANDLE_VALUE)
231 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
234 * Open the specified serial port.
236 * @param port Pointer to empty port structure allocated by caller.
237 * @param portname Name of port to open.
238 * @param flags Flags to use when opening the serial port. Possible flags
239 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
241 * @return SP_OK on success, SP_ERR_FAIL on failure,
242 * or SP_ERR_ARG if an invalid port or name is passed.
244 int sp_open(struct sp_port *port, char *portname, int flags)
252 port->name = portname;
255 DWORD desired_access = 0, flags_and_attributes = 0;
256 /* Map 'flags' to the OS-specific settings. */
257 desired_access |= GENERIC_READ;
258 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
259 if (flags & SP_MODE_RDWR)
260 desired_access |= GENERIC_WRITE;
261 if (flags & SP_MODE_NONBLOCK)
262 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
264 port->hdl = CreateFile(port->name, desired_access, 0, 0,
265 OPEN_EXISTING, flags_and_attributes, 0);
266 if (port->hdl == INVALID_HANDLE_VALUE)
270 /* Map 'flags' to the OS-specific settings. */
271 if (flags & SP_MODE_RDWR)
272 flags_local |= O_RDWR;
273 if (flags & SP_MODE_RDONLY)
274 flags_local |= O_RDONLY;
275 if (flags & SP_MODE_NONBLOCK)
276 flags_local |= O_NONBLOCK;
278 if ((port->fd = open(port->name, flags_local)) < 0)
286 * Close the specified serial port.
288 * @param port Pointer to port structure.
290 * @return SP_OK on success, SP_ERR_FAIL on failure,
291 * or SP_ERR_ARG if an invalid port is passed.
293 int sp_close(struct sp_port *port)
298 /* Returns non-zero upon success, 0 upon failure. */
299 if (CloseHandle(port->hdl) == 0)
302 /* Returns 0 upon success, -1 upon failure. */
303 if (close(port->fd) == -1)
311 * Flush serial port buffers.
313 * @param port Pointer to port structure.
315 * @return SP_OK on success, SP_ERR_FAIL on failure,
316 * or SP_ERR_ARG if an invalid port is passed.
318 int sp_flush(struct sp_port *port)
323 /* Returns non-zero upon success, 0 upon failure. */
324 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
327 /* Returns 0 upon success, -1 upon failure. */
328 if (tcflush(port->fd, TCIOFLUSH) < 0)
335 * Write a number of bytes to the specified serial port.
337 * @param port Pointer to port structure.
338 * @param buf Buffer containing the bytes to write.
339 * @param count Number of bytes to write.
341 * @return The number of bytes written, SP_ERR_FAIL on failure,
342 * or SP_ERR_ARG if an invalid port is passed.
344 int sp_write(struct sp_port *port, const void *buf, size_t count)
353 /* Returns non-zero upon success, 0 upon failure. */
354 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
358 /* Returns the number of bytes written, or -1 upon failure. */
359 ssize_t written = write(port->fd, buf, count);
368 * Read a number of bytes from the specified serial port.
370 * @param port Pointer to port structure.
371 * @param buf Buffer where to store the bytes that are read.
372 * @param count The number of bytes to read.
374 * @return The number of bytes read, SP_ERR_FAIL on failure,
375 * or SP_ERR_ARG if an invalid port is passed.
377 int sp_read(struct sp_port *port, void *buf, size_t count)
385 DWORD bytes_read = 0;
386 /* Returns non-zero upon success, 0 upon failure. */
387 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
392 /* Returns the number of bytes read, or -1 upon failure. */
393 if ((bytes_read = read(port->fd, buf, count)) < 0)
400 * Set serial parameters for the specified serial port.
402 * @param port Pointer to port structure.
403 * @param baudrate The baudrate to set.
404 * @param bits The number of data bits to use.
405 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
406 * @param stopbits The number of stop bits to use (1 or 2).
407 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
410 * @return The number of bytes read, SP_ERR_FAIL on failure,
411 * or SP_ERR_ARG if an invalid argument is passed.
413 int sp_set_params(struct sp_port *port, int baudrate,
414 int bits, int parity, int stopbits,
415 int flowcontrol, int rts, int dtr)
422 if (!GetCommState(port->hdl, &dcb))
427 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
428 * have documented CBR_* macros.
431 dcb.BaudRate = CBR_110;
434 dcb.BaudRate = CBR_300;
437 dcb.BaudRate = CBR_600;
440 dcb.BaudRate = CBR_1200;
443 dcb.BaudRate = CBR_2400;
446 dcb.BaudRate = CBR_4800;
449 dcb.BaudRate = CBR_9600;
452 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
455 dcb.BaudRate = CBR_19200;
458 dcb.BaudRate = CBR_38400;
461 dcb.BaudRate = CBR_57600;
464 dcb.BaudRate = CBR_115200;
467 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
470 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
477 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
479 dcb.StopBits = ONESTOPBIT;
482 dcb.StopBits = TWOSTOPBITS;
489 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
491 dcb.Parity = NOPARITY;
494 dcb.Parity = EVENPARITY;
497 dcb.Parity = ODDPARITY;
505 dcb.fRtsControl = RTS_CONTROL_ENABLE;
507 dcb.fRtsControl = RTS_CONTROL_DISABLE;
512 dcb.fDtrControl = DTR_CONTROL_ENABLE;
514 dcb.fDtrControl = DTR_CONTROL_DISABLE;
517 if (!SetCommState(port->hdl, &dcb))
524 if (tcgetattr(port->fd, &term) < 0)
582 #if !defined(__APPLE__) && !defined(__OpenBSD__)
591 if (cfsetospeed(&term, baud) < 0)
594 if (cfsetispeed(&term, baud) < 0)
597 term.c_cflag &= ~CSIZE;
609 term.c_cflag &= ~CSTOPB;
612 term.c_cflag &= ~CSTOPB;
615 term.c_cflag |= CSTOPB;
621 term.c_iflag &= ~(IXON | IXOFF | IXANY);
622 term.c_cflag &= ~CRTSCTS;
623 switch (flowcontrol) {
625 /* No flow control. */
628 term.c_cflag |= CRTSCTS;
631 term.c_iflag |= IXON | IXOFF | IXANY;
637 term.c_iflag &= ~IGNPAR;
638 term.c_cflag &= ~(PARENB | PARODD);
641 term.c_iflag |= IGNPAR;
644 term.c_cflag |= PARENB;
647 term.c_cflag |= PARENB | PARODD;
653 /* Turn off all serial port cooking. */
654 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
655 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
656 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
657 term.c_oflag &= ~OFILL;
660 /* Disable canonical mode, and don't echo input characters. */
661 term.c_lflag &= ~(ICANON | ECHO);
663 /* Ignore modem status lines; enable receiver */
664 term.c_cflag |= (CLOCAL | CREAD);
666 /* Write the configured settings. */
667 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
671 controlbits = TIOCM_RTS;
672 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
678 controlbits = TIOCM_DTR;
679 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
689 * Get error code for failed operation.
691 * In order to obtain the correct result, this function should be called
692 * straight after the failure, before executing any other system operations.
694 * @return The system's numeric code for the error that caused the last
697 int sp_last_error_code(void)
700 return GetLastError();
707 * Get error message for failed operation.
709 * In order to obtain the correct result, this function should be called
710 * straight after the failure, before executing other system operations.
712 * @return The system's message for the error that caused the last
713 * operation to fail. This string may be allocated by the function,
714 * and can be freed after use by calling sp_free_error_message.
716 char *sp_last_error_message(void)
720 DWORD error = GetLastError();
723 FORMAT_MESSAGE_ALLOCATE_BUFFER |
724 FORMAT_MESSAGE_FROM_SYSTEM |
725 FORMAT_MESSAGE_IGNORE_INSERTS,
728 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
734 return strerror(errno);
739 * Free error message.
741 * This function can be used to free a string returned by the
742 * sp_last_error_message function.
744 void sp_free_error_message(char *message)