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