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, *ud_parent;
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 /* If there is no parent device, this is a virtual tty. */
194 ud_parent = udev_device_get_parent(ud_dev);
195 if (ud_parent == NULL)
197 udev_device_unref(ud_dev);
200 name = udev_device_get_devnode(ud_dev);
201 list = sp_list_append(list, (void *)name, strlen(name) + 1);
202 udev_device_unref(ud_dev);
207 udev_enumerate_unref(ud_enumerate);
214 * Free a port list returned by sp_list_ports.
216 void sp_free_port_list(char **list)
219 for (i = 0; list[i]; i++)
224 static int sp_validate_port(struct sp_port *port)
229 if (port->hdl == INVALID_HANDLE_VALUE)
238 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
241 * Open the specified serial port.
243 * @param port Pointer to empty port structure allocated by caller.
244 * @param portname Name of port to open.
245 * @param flags Flags to use when opening the serial port. Possible flags
246 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
248 * @return SP_OK on success, SP_ERR_FAIL on failure,
249 * or SP_ERR_ARG if an invalid port or name is passed.
251 int sp_open(struct sp_port *port, char *portname, int flags)
259 port->name = portname;
262 DWORD desired_access = 0, flags_and_attributes = 0;
263 /* Map 'flags' to the OS-specific settings. */
264 desired_access |= GENERIC_READ;
265 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
266 if (flags & SP_MODE_RDWR)
267 desired_access |= GENERIC_WRITE;
268 if (flags & SP_MODE_NONBLOCK)
269 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
271 port->hdl = CreateFile(port->name, desired_access, 0, 0,
272 OPEN_EXISTING, flags_and_attributes, 0);
273 if (port->hdl == INVALID_HANDLE_VALUE)
277 /* Map 'flags' to the OS-specific settings. */
278 if (flags & SP_MODE_RDWR)
279 flags_local |= O_RDWR;
280 if (flags & SP_MODE_RDONLY)
281 flags_local |= O_RDONLY;
282 if (flags & SP_MODE_NONBLOCK)
283 flags_local |= O_NONBLOCK;
285 if ((port->fd = open(port->name, flags_local)) < 0)
293 * Close the specified serial port.
295 * @param port Pointer to port structure.
297 * @return SP_OK on success, SP_ERR_FAIL on failure,
298 * or SP_ERR_ARG if an invalid port is passed.
300 int sp_close(struct sp_port *port)
305 /* Returns non-zero upon success, 0 upon failure. */
306 if (CloseHandle(port->hdl) == 0)
309 /* Returns 0 upon success, -1 upon failure. */
310 if (close(port->fd) == -1)
318 * Flush serial port buffers.
320 * @param port Pointer to port structure.
322 * @return SP_OK on success, SP_ERR_FAIL on failure,
323 * or SP_ERR_ARG if an invalid port is passed.
325 int sp_flush(struct sp_port *port)
330 /* Returns non-zero upon success, 0 upon failure. */
331 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
334 /* Returns 0 upon success, -1 upon failure. */
335 if (tcflush(port->fd, TCIOFLUSH) < 0)
342 * Write a number of bytes to the specified serial port.
344 * @param port Pointer to port structure.
345 * @param buf Buffer containing the bytes to write.
346 * @param count Number of bytes to write.
348 * @return The number of bytes written, SP_ERR_FAIL on failure,
349 * or SP_ERR_ARG if an invalid port is passed.
351 int sp_write(struct sp_port *port, const void *buf, size_t count)
360 /* Returns non-zero upon success, 0 upon failure. */
361 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
365 /* Returns the number of bytes written, or -1 upon failure. */
366 ssize_t written = write(port->fd, buf, count);
375 * Read a number of bytes from the specified serial port.
377 * @param port Pointer to port structure.
378 * @param buf Buffer where to store the bytes that are read.
379 * @param count The number of bytes to read.
381 * @return The number of bytes read, SP_ERR_FAIL on failure,
382 * or SP_ERR_ARG if an invalid port is passed.
384 int sp_read(struct sp_port *port, void *buf, size_t count)
392 DWORD bytes_read = 0;
393 /* Returns non-zero upon success, 0 upon failure. */
394 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
399 /* Returns the number of bytes read, or -1 upon failure. */
400 if ((bytes_read = read(port->fd, buf, count)) < 0)
407 * Set serial parameters for the specified serial port.
409 * @param port Pointer to port structure.
410 * @param baudrate The baudrate to set.
411 * @param bits The number of data bits to use.
412 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
413 * @param stopbits The number of stop bits to use (1 or 2).
414 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
417 * @return The number of bytes read, SP_ERR_FAIL on failure,
418 * or SP_ERR_ARG if an invalid argument is passed.
420 int sp_set_params(struct sp_port *port, int baudrate,
421 int bits, int parity, int stopbits,
422 int flowcontrol, int rts, int dtr)
429 if (!GetCommState(port->hdl, &dcb))
434 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
435 * have documented CBR_* macros.
438 dcb.BaudRate = CBR_110;
441 dcb.BaudRate = CBR_300;
444 dcb.BaudRate = CBR_600;
447 dcb.BaudRate = CBR_1200;
450 dcb.BaudRate = CBR_2400;
453 dcb.BaudRate = CBR_4800;
456 dcb.BaudRate = CBR_9600;
459 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
462 dcb.BaudRate = CBR_19200;
465 dcb.BaudRate = CBR_38400;
468 dcb.BaudRate = CBR_57600;
471 dcb.BaudRate = CBR_115200;
474 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
477 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
484 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
486 dcb.StopBits = ONESTOPBIT;
489 dcb.StopBits = TWOSTOPBITS;
496 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
498 dcb.Parity = NOPARITY;
501 dcb.Parity = EVENPARITY;
504 dcb.Parity = ODDPARITY;
512 dcb.fRtsControl = RTS_CONTROL_ENABLE;
514 dcb.fRtsControl = RTS_CONTROL_DISABLE;
519 dcb.fDtrControl = DTR_CONTROL_ENABLE;
521 dcb.fDtrControl = DTR_CONTROL_DISABLE;
524 if (!SetCommState(port->hdl, &dcb))
531 if (tcgetattr(port->fd, &term) < 0)
589 #if !defined(__APPLE__) && !defined(__OpenBSD__)
598 if (cfsetospeed(&term, baud) < 0)
601 if (cfsetispeed(&term, baud) < 0)
604 term.c_cflag &= ~CSIZE;
616 term.c_cflag &= ~CSTOPB;
619 term.c_cflag &= ~CSTOPB;
622 term.c_cflag |= CSTOPB;
628 term.c_iflag &= ~(IXON | IXOFF | IXANY);
629 term.c_cflag &= ~CRTSCTS;
630 switch (flowcontrol) {
632 /* No flow control. */
635 term.c_cflag |= CRTSCTS;
638 term.c_iflag |= IXON | IXOFF | IXANY;
644 term.c_iflag &= ~IGNPAR;
645 term.c_cflag &= ~(PARENB | PARODD);
648 term.c_iflag |= IGNPAR;
651 term.c_cflag |= PARENB;
654 term.c_cflag |= PARENB | PARODD;
660 /* Turn off all serial port cooking. */
661 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
662 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
663 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
664 term.c_oflag &= ~OFILL;
667 /* Disable canonical mode, and don't echo input characters. */
668 term.c_lflag &= ~(ICANON | ECHO);
670 /* Ignore modem status lines; enable receiver */
671 term.c_cflag |= (CLOCAL | CREAD);
673 /* Write the configured settings. */
674 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
678 controlbits = TIOCM_RTS;
679 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
685 controlbits = TIOCM_DTR;
686 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
696 * Get error code for failed operation.
698 * In order to obtain the correct result, this function should be called
699 * straight after the failure, before executing any other system operations.
701 * @return The system's numeric code for the error that caused the last
704 int sp_last_error_code(void)
707 return GetLastError();
714 * Get error message for failed operation.
716 * In order to obtain the correct result, this function should be called
717 * straight after the failure, before executing other system operations.
719 * @return The system's message for the error that caused the last
720 * operation to fail. This string may be allocated by the function,
721 * and can be freed after use by calling sp_free_error_message.
723 char *sp_last_error_message(void)
727 DWORD error = GetLastError();
730 FORMAT_MESSAGE_ALLOCATE_BUFFER |
731 FORMAT_MESSAGE_FROM_SYSTEM |
732 FORMAT_MESSAGE_IGNORE_INSERTS,
735 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
741 return strerror(errno);
746 * Free error message.
748 * This function can be used to free a string returned by the
749 * sp_last_error_message function.
751 void sp_free_error_message(char *message)