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);
71 char **sp_list_ports(void)
78 DWORD max_name_len, max_data_size, max_data_len;
79 DWORD name_len, data_size, data_len;
80 DWORD type, index = 0;
82 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
83 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
85 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
86 &max_name_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
88 max_data_len = max_data_size / sizeof(TCHAR);
89 if (!(name = malloc((max_name_len + 1) * sizeof(TCHAR))))
91 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
93 if (!(list = sp_list_new()))
96 name_len = max_name_len,
97 data_size = max_data_size,
98 RegEnumValue(key, index, name, &name_len,
99 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
101 data_len = data_size / sizeof(TCHAR);
102 data[data_len] = '\0';
104 if (!(list = sp_list_append(list,
105 data, (data_len + 1) * sizeof(TCHAR))))
119 CFMutableDictionaryRef classes;
126 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
129 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
132 CFDictionarySetValue(classes,
133 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
135 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
138 if (!(path = malloc(PATH_MAX)))
141 if (!(list = sp_list_new()))
144 while (port = IOIteratorNext(iter)) {
145 cf_path = IORegistryEntryCreateCFProperty(port,
146 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
148 result = CFStringGetCString(cf_path,
149 path, PATH_MAX, kCFStringEncodingASCII);
152 if (!(list = sp_list_append(list, path, strlen(path) + 1)))
154 IOObjectRelease(port);
158 IOObjectRelease(port);
164 IOObjectRelease(iter);
169 struct udev_enumerate *ud_enumerate;
170 struct udev_list_entry *ud_list;
171 struct udev_list_entry *ud_entry;
173 struct udev_device *ud_dev;
177 ud_enumerate = udev_enumerate_new(ud);
178 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
179 udev_enumerate_scan_devices(ud_enumerate);
180 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
181 if (!(list = sp_list_new()))
183 udev_list_entry_foreach(ud_entry, ud_list)
185 path = udev_list_entry_get_name(ud_entry);
186 ud_dev = udev_device_new_from_syspath(ud, path);
187 name = udev_device_get_devnode(ud_dev);
188 list = sp_list_append(list, (void *)name, strlen(name) + 1);
189 udev_device_unref(ud_dev);
194 udev_enumerate_unref(ud_enumerate);
200 void sp_free_port_list(char **list)
203 for (i = 0; list[i]; i++)
208 static int sp_validate_port(struct sp_port *port)
213 if (port->hdl == INVALID_HANDLE_VALUE)
222 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
225 * Open the specified serial port.
227 * @param port Pointer to empty port structure allocated by caller.
228 * @param portname Name of port to open.
229 * @param flags Flags to use when opening the serial port. Possible flags
230 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
232 * @return SP_OK on success, SP_ERR_FAIL on failure,
233 * or SP_ERR_ARG if an invalid port or name is passed.
235 int sp_open(struct sp_port *port, char *portname, int flags)
243 port->name = portname;
246 DWORD desired_access = 0, flags_and_attributes = 0;
247 /* Map 'flags' to the OS-specific settings. */
248 desired_access |= GENERIC_READ;
249 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
250 if (flags & SP_MODE_RDWR)
251 desired_access |= GENERIC_WRITE;
252 if (flags & SP_MODE_NONBLOCK)
253 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
255 port->hdl = CreateFile(port->name, desired_access, 0, 0,
256 OPEN_EXISTING, flags_and_attributes, 0);
257 if (port->hdl == INVALID_HANDLE_VALUE)
261 /* Map 'flags' to the OS-specific settings. */
262 if (flags & SP_MODE_RDWR)
263 flags_local |= O_RDWR;
264 if (flags & SP_MODE_RDONLY)
265 flags_local |= O_RDONLY;
266 if (flags & SP_MODE_NONBLOCK)
267 flags_local |= O_NONBLOCK;
269 if ((port->fd = open(port->name, flags_local)) < 0)
277 * Close the specified serial port.
279 * @param port Pointer to port structure.
281 * @return SP_OK on success, SP_ERR_FAIL on failure,
282 * or SP_ERR_ARG if an invalid port is passed.
284 int sp_close(struct sp_port *port)
289 /* Returns non-zero upon success, 0 upon failure. */
290 if (CloseHandle(port->hdl) == 0)
293 /* Returns 0 upon success, -1 upon failure. */
294 if (close(port->fd) == -1)
302 * Flush serial port buffers.
304 * @param port Pointer to port structure.
306 * @return SP_OK on success, SP_ERR_FAIL on failure,
307 * or SP_ERR_ARG if an invalid port is passed.
309 int sp_flush(struct sp_port *port)
314 /* Returns non-zero upon success, 0 upon failure. */
315 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
318 /* Returns 0 upon success, -1 upon failure. */
319 if (tcflush(port->fd, TCIOFLUSH) < 0)
326 * Write a number of bytes to the specified serial port.
328 * @param port Pointer to port structure.
329 * @param buf Buffer containing the bytes to write.
330 * @param count Number of bytes to write.
332 * @return The number of bytes written, SP_ERR_FAIL on failure,
333 * or SP_ERR_ARG if an invalid port is passed.
335 int sp_write(struct sp_port *port, const void *buf, size_t count)
344 /* Returns non-zero upon success, 0 upon failure. */
345 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
349 /* Returns the number of bytes written, or -1 upon failure. */
350 ssize_t written = write(port->fd, buf, count);
359 * Read a number of bytes from the specified serial port.
361 * @param port Pointer to port structure.
362 * @param buf Buffer where to store the bytes that are read.
363 * @param count The number of bytes to read.
365 * @return The number of bytes read, SP_ERR_FAIL on failure,
366 * or SP_ERR_ARG if an invalid port is passed.
368 int sp_read(struct sp_port *port, void *buf, size_t count)
376 DWORD bytes_read = 0;
377 /* Returns non-zero upon success, 0 upon failure. */
378 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
383 /* Returns the number of bytes read, or -1 upon failure. */
384 if ((bytes_read = read(port->fd, buf, count)) < 0)
391 * Set serial parameters for the specified serial port.
393 * @param port Pointer to port structure.
394 * @param baudrate The baudrate to set.
395 * @param bits The number of data bits to use.
396 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
397 * @param stopbits The number of stop bits to use (1 or 2).
398 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
401 * @return The number of bytes read, SP_ERR_FAIL on failure,
402 * or SP_ERR_ARG if an invalid argument is passed.
404 int sp_set_params(struct sp_port *port, int baudrate,
405 int bits, int parity, int stopbits,
406 int flowcontrol, int rts, int dtr)
413 if (!GetCommState(port->hdl, &dcb))
418 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
419 * have documented CBR_* macros.
422 dcb.BaudRate = CBR_110;
425 dcb.BaudRate = CBR_300;
428 dcb.BaudRate = CBR_600;
431 dcb.BaudRate = CBR_1200;
434 dcb.BaudRate = CBR_2400;
437 dcb.BaudRate = CBR_4800;
440 dcb.BaudRate = CBR_9600;
443 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
446 dcb.BaudRate = CBR_19200;
449 dcb.BaudRate = CBR_38400;
452 dcb.BaudRate = CBR_57600;
455 dcb.BaudRate = CBR_115200;
458 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
461 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
468 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
470 dcb.StopBits = ONESTOPBIT;
473 dcb.StopBits = TWOSTOPBITS;
480 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
482 dcb.Parity = NOPARITY;
485 dcb.Parity = EVENPARITY;
488 dcb.Parity = ODDPARITY;
496 dcb.fRtsControl = RTS_CONTROL_ENABLE;
498 dcb.fRtsControl = RTS_CONTROL_DISABLE;
503 dcb.fDtrControl = DTR_CONTROL_ENABLE;
505 dcb.fDtrControl = DTR_CONTROL_DISABLE;
508 if (!SetCommState(port->hdl, &dcb))
515 if (tcgetattr(port->fd, &term) < 0)
573 #if !defined(__APPLE__) && !defined(__OpenBSD__)
582 if (cfsetospeed(&term, baud) < 0)
585 if (cfsetispeed(&term, baud) < 0)
588 term.c_cflag &= ~CSIZE;
600 term.c_cflag &= ~CSTOPB;
603 term.c_cflag &= ~CSTOPB;
606 term.c_cflag |= CSTOPB;
612 term.c_iflag &= ~(IXON | IXOFF);
613 term.c_cflag &= ~CRTSCTS;
614 switch (flowcontrol) {
616 /* No flow control. */
619 term.c_cflag |= CRTSCTS;
622 term.c_iflag |= IXON | IXOFF;
628 term.c_iflag &= ~IGNPAR;
629 term.c_cflag &= ~(PARODD | PARENB);
632 term.c_iflag |= IGNPAR;
635 term.c_cflag |= PARENB;
638 term.c_cflag |= PARENB | PARODD;
644 /* Turn off all serial port cooking. */
645 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
646 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
647 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
648 term.c_oflag &= ~OFILL;
651 /* Disable canonical mode, and don't echo input characters. */
652 term.c_lflag &= ~(ICANON | ECHO);
654 /* Write the configured settings. */
655 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
659 controlbits = TIOCM_RTS;
660 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
666 controlbits = TIOCM_DTR;
667 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
677 * Get error code for failed operation.
679 * In order to obtain the correct result, this function should be called
680 * straight after the failure, before executing any other system operations.
682 * @return The system's numeric code for the error that caused the last
685 int sp_last_error_code(void)
688 return GetLastError();
695 * Get error message for failed operation.
697 * In order to obtain the correct result, this function should be called
698 * straight after the failure, before executing other system operations.
700 * @return The system's message for the error that caused the last
701 * operation to fail. This string may be allocated by the function,
702 * and can be freed after use by calling sp_free_error_message.
704 char *sp_last_error_message(void)
708 DWORD error = GetLastError();
711 FORMAT_MESSAGE_ALLOCATE_BUFFER |
712 FORMAT_MESSAGE_FROM_SYSTEM |
713 FORMAT_MESSAGE_IGNORE_INSERTS,
716 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
722 return strerror(errno);
727 * Free error message.
729 * This function can be used to free a string returned by the
730 * sp_last_error_message function.
732 void sp_free_error_message(char *message)