]> sigrok.org Git - libserialport.git/blame - serialport.c
Document enumeration functions.
[libserialport.git] / serialport.c
CommitLineData
74510d4b
ML
1/*
2 * This file is part of the libserialport project.
3 *
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>
7 *
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.
12 *
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.
17 *
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/>.
20 */
21
22#include <string.h>
23#include <sys/types.h>
24#include <sys/stat.h>
25#include <fcntl.h>
26#include <unistd.h>
3b63f34d
ML
27#include <stdlib.h>
28#include <errno.h>
74510d4b
ML
29#ifdef _WIN32
30#include <windows.h>
3b63f34d 31#include <tchar.h>
74510d4b 32#else
74510d4b
ML
33#include <termios.h>
34#include <sys/ioctl.h>
35#endif
3b63f34d
ML
36#ifdef __APPLE__
37#include <IOKitLib.h>
38#include <serial/IOSerialKeys.h>
39#endif
40#ifdef __linux__
41#include "libudev.h"
42#endif
74510d4b
ML
43
44#include "serialport.h"
45
3b63f34d
ML
46static char **sp_list_new(void)
47{
48 char **list;
49 if ((list = malloc(sizeof(char *))))
50 list[0] = NULL;
51 return list;
52}
53
54static char **sp_list_append(char **list, void *data, size_t len)
55{
56 void *tmp;
57 unsigned int count;
58 for (count = 0; list[count]; count++);
59 if (!(tmp = realloc(list, sizeof(char *) * (++count + 1))))
60 goto fail;
61 list = tmp;
62 if (!(list[count] = malloc(len)))
63 goto fail;
64 memcpy(list[count], data, len);
65 return list;
66fail:
67 sp_free_port_list(list);
68 return NULL;
69}
70
68ab64cc
ML
71/**
72 * List the serial ports available on the system.
73 *
74 * @return A null-terminated array of port name strings.
75 */
3b63f34d
ML
76char **sp_list_ports(void)
77{
78 char **list = NULL;
79
80#ifdef _WIN32
81 HKEY key;
82 TCHAR *name, *data;
83 DWORD max_name_len, max_data_size, max_data_len;
84 DWORD name_len, data_size, data_len;
85 DWORD type, index = 0;
86
87 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
88 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
89 return NULL;
90 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
91 &max_name_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
92 goto out_close;
93 max_data_len = max_data_size / sizeof(TCHAR);
94 if (!(name = malloc((max_name_len + 1) * sizeof(TCHAR))))
95 goto out_close;
96 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
97 goto out_free_name;
98 if (!(list = sp_list_new()))
99 goto out;
100 while (
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)
105 {
106 data_len = data_size / sizeof(TCHAR);
107 data[data_len] = '\0';
108 if (type == REG_SZ)
109 if (!(list = sp_list_append(list,
110 data, (data_len + 1) * sizeof(TCHAR))))
111 goto out;
112 index++;
113 }
114out:
115 free(data);
116out_free_name:
117 free(name);
118out_close:
119 RegCloseKey(key);
120 return list;
121#endif
122#ifdef __APPLE__
123 mach_port_t master;
124 CFMutableDictionaryRef classes;
125 io_iterator_t iter;
126 char *path;
127 io_object_t port;
128 CFTypeRef cf_path;
129 Boolean result;
130
131 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
132 return NULL;
133
134 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
135 return NULL;
136
137 CFDictionarySetValue(classes,
138 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
139
140 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
141 return NULL;
142
143 if (!(path = malloc(PATH_MAX)))
144 goto out_release;
145
146 if (!(list = sp_list_new()))
147 goto out;
148
149 while (port = IOIteratorNext(iter)) {
150 cf_path = IORegistryEntryCreateCFProperty(port,
151 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
152 if (cf_path) {
153 result = CFStringGetCString(cf_path,
154 path, PATH_MAX, kCFStringEncodingASCII);
155 CFRelease(cf_path);
156 if (result)
157 if (!(list = sp_list_append(list, path, strlen(path) + 1)))
158 {
159 IOObjectRelease(port);
160 goto out;
161 }
162 }
163 IOObjectRelease(port);
164 }
165
166out:
167 free(path);
168out_release:
169 IOObjectRelease(iter);
170 return list;
171#endif
172#ifdef __linux__
173 struct udev *ud;
174 struct udev_enumerate *ud_enumerate;
175 struct udev_list_entry *ud_list;
176 struct udev_list_entry *ud_entry;
177 const char *path;
178 struct udev_device *ud_dev;
179 const char *name;
180
181 ud = udev_new();
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()))
187 goto out;
188 udev_list_entry_foreach(ud_entry, ud_list)
189 {
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);
195 if (!list)
196 goto out;
197 }
198out:
199 udev_enumerate_unref(ud_enumerate);
200 udev_unref(ud);
201 return list;
202#endif
203}
204
68ab64cc
ML
205/**
206 * Free a port list returned by sp_list_ports.
207 */
3b63f34d
ML
208void sp_free_port_list(char **list)
209{
210 unsigned int i;
211 for (i = 0; list[i]; i++)
212 free(list[i]);
213 free(list);
214}
215
74510d4b
ML
216static int sp_validate_port(struct sp_port *port)
217{
218 if (port == NULL)
219 return 0;
220#ifdef _WIN32
221 if (port->hdl == INVALID_HANDLE_VALUE)
222 return 0;
223#else
224 if (port->fd < 0)
225 return 0;
226#endif
227 return 1;
228}
229
230#define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
231
232/**
233 * Open the specified serial port.
234 *
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.
239 *
240 * @return SP_OK on success, SP_ERR_FAIL on failure,
241 * or SP_ERR_ARG if an invalid port or name is passed.
242 */
243int sp_open(struct sp_port *port, char *portname, int flags)
244{
245 if (!port)
246 return SP_ERR_ARG;
247
248 if (!portname)
249 return SP_ERR_ARG;
250
251 port->name = portname;
252
253#ifdef _WIN32
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;
262
263 port->hdl = CreateFile(port->name, desired_access, 0, 0,
264 OPEN_EXISTING, flags_and_attributes, 0);
265 if (port->hdl == INVALID_HANDLE_VALUE)
266 return SP_ERR_FAIL;
267#else
268 int flags_local = 0;
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;
276
277 if ((port->fd = open(port->name, flags_local)) < 0)
278 return SP_ERR_FAIL;
279#endif
280
281 return SP_OK;
282}
283
284/**
285 * Close the specified serial port.
286 *
287 * @param port Pointer to port structure.
288 *
289 * @return SP_OK on success, SP_ERR_FAIL on failure,
290 * or SP_ERR_ARG if an invalid port is passed.
291 */
292int sp_close(struct sp_port *port)
293{
294 CHECK_PORT();
295
296#ifdef _WIN32
297 /* Returns non-zero upon success, 0 upon failure. */
298 if (CloseHandle(port->hdl) == 0)
299 return SP_ERR_FAIL;
300#else
301 /* Returns 0 upon success, -1 upon failure. */
302 if (close(port->fd) == -1)
303 return SP_ERR_FAIL;
304#endif
305
306 return SP_OK;
307}
308
309/**
310 * Flush serial port buffers.
311 *
312 * @param port Pointer to port structure.
313 *
314 * @return SP_OK on success, SP_ERR_FAIL on failure,
315 * or SP_ERR_ARG if an invalid port is passed.
316 */
317int sp_flush(struct sp_port *port)
318{
319 CHECK_PORT();
320
321#ifdef _WIN32
322 /* Returns non-zero upon success, 0 upon failure. */
323 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
324 return SP_ERR_FAIL;
325#else
326 /* Returns 0 upon success, -1 upon failure. */
327 if (tcflush(port->fd, TCIOFLUSH) < 0)
328 return SP_ERR_FAIL;
329#endif
330 return SP_OK;
331}
332
333/**
334 * Write a number of bytes to the specified serial port.
335 *
336 * @param port Pointer to port structure.
337 * @param buf Buffer containing the bytes to write.
338 * @param count Number of bytes to write.
339 *
340 * @return The number of bytes written, SP_ERR_FAIL on failure,
341 * or SP_ERR_ARG if an invalid port is passed.
342 */
343int sp_write(struct sp_port *port, const void *buf, size_t count)
344{
345 CHECK_PORT();
346
347 if (!buf)
348 return SP_ERR_ARG;
349
350#ifdef _WIN32
351 DWORD written = 0;
352 /* Returns non-zero upon success, 0 upon failure. */
353 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
354 return SP_ERR_FAIL;
355 return written;
356#else
357 /* Returns the number of bytes written, or -1 upon failure. */
358 ssize_t written = write(port->fd, buf, count);
359 if (written < 0)
360 return SP_ERR_FAIL;
361 else
362 return written;;
363#endif
364}
365
366/**
367 * Read a number of bytes from the specified serial port.
368 *
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.
372 *
373 * @return The number of bytes read, SP_ERR_FAIL on failure,
374 * or SP_ERR_ARG if an invalid port is passed.
375 */
376int sp_read(struct sp_port *port, void *buf, size_t count)
377{
378 CHECK_PORT();
379
380 if (!buf)
381 return SP_ERR_ARG;
382
383#ifdef _WIN32
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)
387 return SP_ERR_FAIL;
388 return bytes_read;
389#else
390 ssize_t bytes_read;
391 /* Returns the number of bytes read, or -1 upon failure. */
392 if ((bytes_read = read(port->fd, buf, count)) < 0)
393 return SP_ERR_FAIL;
394 return bytes_read;
395#endif
396}
397
398/**
399 * Set serial parameters for the specified serial port.
400 *
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,
407 * 2 = XON/XOFF).
408 *
409 * @return The number of bytes read, SP_ERR_FAIL on failure,
410 * or SP_ERR_ARG if an invalid argument is passed.
411 */
412int sp_set_params(struct sp_port *port, int baudrate,
413 int bits, int parity, int stopbits,
414 int flowcontrol, int rts, int dtr)
415{
416 CHECK_PORT();
417
418#ifdef _WIN32
419 DCB dcb;
420
421 if (!GetCommState(port->hdl, &dcb))
422 return SP_ERR_FAIL;
423
424 switch (baudrate) {
425 /*
426 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
427 * have documented CBR_* macros.
428 */
429 case 110:
430 dcb.BaudRate = CBR_110;
431 break;
432 case 300:
433 dcb.BaudRate = CBR_300;
434 break;
435 case 600:
436 dcb.BaudRate = CBR_600;
437 break;
438 case 1200:
439 dcb.BaudRate = CBR_1200;
440 break;
441 case 2400:
442 dcb.BaudRate = CBR_2400;
443 break;
444 case 4800:
445 dcb.BaudRate = CBR_4800;
446 break;
447 case 9600:
448 dcb.BaudRate = CBR_9600;
449 break;
450 case 14400:
451 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
452 break;
453 case 19200:
454 dcb.BaudRate = CBR_19200;
455 break;
456 case 38400:
457 dcb.BaudRate = CBR_38400;
458 break;
459 case 57600:
460 dcb.BaudRate = CBR_57600;
461 break;
462 case 115200:
463 dcb.BaudRate = CBR_115200;
464 break;
465 case 128000:
466 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
467 break;
468 case 256000:
469 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
470 break;
471 default:
472 return SP_ERR_ARG;
473 }
474
475 switch (stopbits) {
476 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
477 case 1:
478 dcb.StopBits = ONESTOPBIT;
479 break;
480 case 2:
481 dcb.StopBits = TWOSTOPBITS;
482 break;
483 default:
484 return SP_ERR_ARG;
485 }
486
487 switch (parity) {
488 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
489 case SP_PARITY_NONE:
490 dcb.Parity = NOPARITY;
491 break;
492 case SP_PARITY_EVEN:
493 dcb.Parity = EVENPARITY;
494 break;
495 case SP_PARITY_ODD:
496 dcb.Parity = ODDPARITY;
497 break;
498 default:
499 return SP_ERR_ARG;
500 }
501
502 if (rts != -1) {
503 if (rts)
504 dcb.fRtsControl = RTS_CONTROL_ENABLE;
505 else
506 dcb.fRtsControl = RTS_CONTROL_DISABLE;
507 }
508
509 if (dtr != -1) {
510 if (dtr)
511 dcb.fDtrControl = DTR_CONTROL_ENABLE;
512 else
513 dcb.fDtrControl = DTR_CONTROL_DISABLE;
514 }
515
516 if (!SetCommState(port->hdl, &dcb))
517 return SP_ERR_FAIL;
518#else
519 struct termios term;
520 speed_t baud;
521 int controlbits;
522
523 if (tcgetattr(port->fd, &term) < 0)
524 return SP_ERR_FAIL;
525
526 switch (baudrate) {
527 case 50:
528 baud = B50;
529 break;
530 case 75:
531 baud = B75;
532 break;
533 case 110:
534 baud = B110;
535 break;
536 case 134:
537 baud = B134;
538 break;
539 case 150:
540 baud = B150;
541 break;
542 case 200:
543 baud = B200;
544 break;
545 case 300:
546 baud = B300;
547 break;
548 case 600:
549 baud = B600;
550 break;
551 case 1200:
552 baud = B1200;
553 break;
554 case 1800:
555 baud = B1800;
556 break;
557 case 2400:
558 baud = B2400;
559 break;
560 case 4800:
561 baud = B4800;
562 break;
563 case 9600:
564 baud = B9600;
565 break;
566 case 19200:
567 baud = B19200;
568 break;
569 case 38400:
570 baud = B38400;
571 break;
572 case 57600:
573 baud = B57600;
574 break;
575 case 115200:
576 baud = B115200;
577 break;
578 case 230400:
579 baud = B230400;
580 break;
581#if !defined(__APPLE__) && !defined(__OpenBSD__)
582 case 460800:
583 baud = B460800;
584 break;
585#endif
586 default:
587 return SP_ERR_ARG;
588 }
589
590 if (cfsetospeed(&term, baud) < 0)
591 return SP_ERR_FAIL;
592
593 if (cfsetispeed(&term, baud) < 0)
594 return SP_ERR_FAIL;
595
596 term.c_cflag &= ~CSIZE;
597 switch (bits) {
598 case 8:
599 term.c_cflag |= CS8;
600 break;
601 case 7:
602 term.c_cflag |= CS7;
603 break;
604 default:
605 return SP_ERR_ARG;
606 }
607
608 term.c_cflag &= ~CSTOPB;
609 switch (stopbits) {
610 case 1:
611 term.c_cflag &= ~CSTOPB;
612 break;
613 case 2:
614 term.c_cflag |= CSTOPB;
615 break;
616 default:
617 return SP_ERR_ARG;
618 }
619
620 term.c_iflag &= ~(IXON | IXOFF);
621 term.c_cflag &= ~CRTSCTS;
622 switch (flowcontrol) {
623 case 0:
624 /* No flow control. */
625 break;
626 case 1:
627 term.c_cflag |= CRTSCTS;
628 break;
629 case 2:
630 term.c_iflag |= IXON | IXOFF;
631 break;
632 default:
633 return SP_ERR_ARG;
634 }
635
636 term.c_iflag &= ~IGNPAR;
637 term.c_cflag &= ~(PARODD | PARENB);
638 switch (parity) {
639 case SP_PARITY_NONE:
640 term.c_iflag |= IGNPAR;
641 break;
642 case SP_PARITY_EVEN:
643 term.c_cflag |= PARENB;
644 break;
645 case SP_PARITY_ODD:
646 term.c_cflag |= PARENB | PARODD;
647 break;
648 default:
649 return SP_ERR_ARG;
650 }
651
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;
657#endif
658
659 /* Disable canonical mode, and don't echo input characters. */
660 term.c_lflag &= ~(ICANON | ECHO);
661
662 /* Write the configured settings. */
663 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
664 return SP_ERR_FAIL;
665
666 if (rts != -1) {
667 controlbits = TIOCM_RTS;
668 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
669 &controlbits) < 0)
670 return SP_ERR_FAIL;
671 }
672
673 if (dtr != -1) {
674 controlbits = TIOCM_DTR;
675 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
676 &controlbits) < 0)
677 return SP_ERR_FAIL;
678 }
679#endif
680
681 return SP_OK;
682}
683
684/**
685 * Get error code for failed operation.
686 *
687 * In order to obtain the correct result, this function should be called
688 * straight after the failure, before executing any other system operations.
689 *
690 * @return The system's numeric code for the error that caused the last
691 * operation to fail.
692 */
693int sp_last_error_code(void)
694{
695#ifdef _WIN32
696 return GetLastError();
697#else
698 return errno;
699#endif
700}
701
702/**
703 * Get error message for failed operation.
704 *
705 * In order to obtain the correct result, this function should be called
706 * straight after the failure, before executing other system operations.
707 *
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.
711 */
712char *sp_last_error_message(void)
713{
714#ifdef _WIN32
715 LPVOID message;
716 DWORD error = GetLastError();
717
718 FormatMessage(
719 FORMAT_MESSAGE_ALLOCATE_BUFFER |
720 FORMAT_MESSAGE_FROM_SYSTEM |
721 FORMAT_MESSAGE_IGNORE_INSERTS,
722 NULL,
723 error,
724 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
725 (LPTSTR) &message,
726 0, NULL );
727
728 return message;
729#else
730 return strerror(errno);
731#endif
732}
733
734/**
735 * Free error message.
736 *
737 * This function can be used to free a string returned by the
738 * sp_last_error_message function.
739 */
740void sp_free_error_message(char *message)
741{
742#ifdef _WIN32
743 LocalFree(message);
64eec30d
ML
744#else
745 (void)message;
74510d4b
ML
746#endif
747}