]> sigrok.org Git - libserialport.git/blob - serialport.c
Fix list append.
[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;
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                 name = udev_device_get_devnode(ud_dev);
194                 list = sp_list_append(list, (void *)name, strlen(name) + 1);
195                 udev_device_unref(ud_dev);
196                 if (!list)
197                         goto out;
198         }
199 out:
200         udev_enumerate_unref(ud_enumerate);
201         udev_unref(ud);
202         return list;
203 #endif
204 }
205
206 /**
207  * Free a port list returned by sp_list_ports.
208  */
209 void sp_free_port_list(char **list)
210 {
211         unsigned int i;
212         for (i = 0; list[i]; i++)
213                 free(list[i]);
214         free(list);
215 }
216
217 static int sp_validate_port(struct sp_port *port)
218 {
219         if (port == NULL)
220                 return 0;
221 #ifdef _WIN32
222         if (port->hdl == INVALID_HANDLE_VALUE)
223                 return 0;
224 #else
225         if (port->fd < 0)
226                 return 0;
227 #endif
228         return 1;
229 }
230
231 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
232
233 /**
234  * Open the specified serial port.
235  *
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.
240  *
241  * @return SP_OK on success, SP_ERR_FAIL on failure,
242  *         or SP_ERR_ARG if an invalid port or name is passed.
243  */
244 int sp_open(struct sp_port *port, char *portname, int flags)
245 {
246         if (!port)
247                 return SP_ERR_ARG;
248
249         if (!portname)
250                 return SP_ERR_ARG;
251
252         port->name = portname;
253
254 #ifdef _WIN32
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;
263
264         port->hdl = CreateFile(port->name, desired_access, 0, 0,
265                          OPEN_EXISTING, flags_and_attributes, 0);
266         if (port->hdl == INVALID_HANDLE_VALUE)
267                 return SP_ERR_FAIL;
268 #else
269         int flags_local = 0;
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;
277
278         if ((port->fd = open(port->name, flags_local)) < 0)
279                 return SP_ERR_FAIL;
280 #endif
281
282         return SP_OK;
283 }
284
285 /**
286  * Close the specified serial port.
287  *
288  * @param port Pointer to port structure.
289  *
290  * @return SP_OK on success, SP_ERR_FAIL on failure,
291  *         or SP_ERR_ARG if an invalid port is passed.
292  */
293 int sp_close(struct sp_port *port)
294 {
295         CHECK_PORT();
296
297 #ifdef _WIN32
298         /* Returns non-zero upon success, 0 upon failure. */
299         if (CloseHandle(port->hdl) == 0)
300                 return SP_ERR_FAIL;
301 #else
302         /* Returns 0 upon success, -1 upon failure. */
303         if (close(port->fd) == -1)
304                 return SP_ERR_FAIL;
305 #endif
306
307         return SP_OK;
308 }
309
310 /**
311  * Flush serial port buffers.
312  *
313  * @param port Pointer to port structure.
314  *
315  * @return SP_OK on success, SP_ERR_FAIL on failure,
316  *         or SP_ERR_ARG if an invalid port is passed.
317  */
318 int sp_flush(struct sp_port *port)
319 {
320         CHECK_PORT();
321
322 #ifdef _WIN32
323         /* Returns non-zero upon success, 0 upon failure. */
324         if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
325                 return SP_ERR_FAIL;
326 #else
327         /* Returns 0 upon success, -1 upon failure. */
328         if (tcflush(port->fd, TCIOFLUSH) < 0)
329                 return SP_ERR_FAIL;
330 #endif
331         return SP_OK;
332 }
333
334 /**
335  * Write a number of bytes to the specified serial port.
336  *
337  * @param port Pointer to port structure.
338  * @param buf Buffer containing the bytes to write.
339  * @param count Number of bytes to write.
340  *
341  * @return The number of bytes written, SP_ERR_FAIL on failure,
342  *         or SP_ERR_ARG if an invalid port is passed.
343  */
344 int sp_write(struct sp_port *port, const void *buf, size_t count)
345 {
346         CHECK_PORT();
347
348         if (!buf)
349                 return SP_ERR_ARG;
350
351 #ifdef _WIN32
352         DWORD written = 0;
353         /* Returns non-zero upon success, 0 upon failure. */
354         if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
355                 return SP_ERR_FAIL;
356         return written;
357 #else
358         /* Returns the number of bytes written, or -1 upon failure. */
359         ssize_t written = write(port->fd, buf, count);
360         if (written < 0)
361                 return SP_ERR_FAIL;
362         else
363                 return written;;
364 #endif
365 }
366
367 /**
368  * Read a number of bytes from the specified serial port.
369  *
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.
373  *
374  * @return The number of bytes read, SP_ERR_FAIL on failure,
375  *         or SP_ERR_ARG if an invalid port is passed.
376  */
377 int sp_read(struct sp_port *port, void *buf, size_t count)
378 {
379         CHECK_PORT();
380
381         if (!buf)
382                 return SP_ERR_ARG;
383
384 #ifdef _WIN32
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)
388                 return SP_ERR_FAIL;
389         return bytes_read;
390 #else
391         ssize_t bytes_read;
392         /* Returns the number of bytes read, or -1 upon failure. */
393         if ((bytes_read = read(port->fd, buf, count)) < 0)
394                 return SP_ERR_FAIL;
395         return bytes_read;
396 #endif
397 }
398
399 /**
400  * Set serial parameters for the specified serial port.
401  *
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,
408  *                    2 = XON/XOFF).
409  *
410  * @return The number of bytes read, SP_ERR_FAIL on failure,
411  *         or SP_ERR_ARG if an invalid argument is passed.
412  */
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)
416 {
417         CHECK_PORT();
418
419 #ifdef _WIN32
420         DCB dcb;
421
422         if (!GetCommState(port->hdl, &dcb))
423                 return SP_ERR_FAIL;
424
425         switch (baudrate) {
426         /*
427          * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
428          * have documented CBR_* macros.
429          */
430         case 110:
431                 dcb.BaudRate = CBR_110;
432                 break;
433         case 300:
434                 dcb.BaudRate = CBR_300;
435                 break;
436         case 600:
437                 dcb.BaudRate = CBR_600;
438                 break;
439         case 1200:
440                 dcb.BaudRate = CBR_1200;
441                 break;
442         case 2400:
443                 dcb.BaudRate = CBR_2400;
444                 break;
445         case 4800:
446                 dcb.BaudRate = CBR_4800;
447                 break;
448         case 9600:
449                 dcb.BaudRate = CBR_9600;
450                 break;
451         case 14400:
452                 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
453                 break;
454         case 19200:
455                 dcb.BaudRate = CBR_19200;
456                 break;
457         case 38400:
458                 dcb.BaudRate = CBR_38400;
459                 break;
460         case 57600:
461                 dcb.BaudRate = CBR_57600;
462                 break;
463         case 115200:
464                 dcb.BaudRate = CBR_115200;
465                 break;
466         case 128000:
467                 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
468                 break;
469         case 256000:
470                 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
471                 break;
472         default:
473                 return SP_ERR_ARG;
474         }
475
476         switch (stopbits) {
477         /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
478         case 1:
479                 dcb.StopBits = ONESTOPBIT;
480                 break;
481         case 2:
482                 dcb.StopBits = TWOSTOPBITS;
483                 break;
484         default:
485                 return SP_ERR_ARG;
486         }
487
488         switch (parity) {
489         /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
490         case SP_PARITY_NONE:
491                 dcb.Parity = NOPARITY;
492                 break;
493         case SP_PARITY_EVEN:
494                 dcb.Parity = EVENPARITY;
495                 break;
496         case SP_PARITY_ODD:
497                 dcb.Parity = ODDPARITY;
498                 break;
499         default:
500                 return SP_ERR_ARG;
501         }
502
503         if (rts != -1) {
504                 if (rts)
505                         dcb.fRtsControl = RTS_CONTROL_ENABLE;
506                 else
507                         dcb.fRtsControl = RTS_CONTROL_DISABLE;
508         }
509
510         if (dtr != -1) {
511                 if (dtr)
512                         dcb.fDtrControl = DTR_CONTROL_ENABLE;
513                 else
514                         dcb.fDtrControl = DTR_CONTROL_DISABLE;
515         }
516
517         if (!SetCommState(port->hdl, &dcb))
518                 return SP_ERR_FAIL;
519 #else
520         struct termios term;
521         speed_t baud;
522         int controlbits;
523
524         if (tcgetattr(port->fd, &term) < 0)
525                 return SP_ERR_FAIL;
526
527         switch (baudrate) {
528         case 50:
529                 baud = B50;
530                 break;
531         case 75:
532                 baud = B75;
533                 break;
534         case 110:
535                 baud = B110;
536                 break;
537         case 134:
538                 baud = B134;
539                 break;
540         case 150:
541                 baud = B150;
542                 break;
543         case 200:
544                 baud = B200;
545                 break;
546         case 300:
547                 baud = B300;
548                 break;
549         case 600:
550                 baud = B600;
551                 break;
552         case 1200:
553                 baud = B1200;
554                 break;
555         case 1800:
556                 baud = B1800;
557                 break;
558         case 2400:
559                 baud = B2400;
560                 break;
561         case 4800:
562                 baud = B4800;
563                 break;
564         case 9600:
565                 baud = B9600;
566                 break;
567         case 19200:
568                 baud = B19200;
569                 break;
570         case 38400:
571                 baud = B38400;
572                 break;
573         case 57600:
574                 baud = B57600;
575                 break;
576         case 115200:
577                 baud = B115200;
578                 break;
579         case 230400:
580                 baud = B230400;
581                 break;
582 #if !defined(__APPLE__) && !defined(__OpenBSD__)
583         case 460800:
584                 baud = B460800;
585                 break;
586 #endif
587         default:
588                 return SP_ERR_ARG;
589         }
590
591         if (cfsetospeed(&term, baud) < 0)
592                 return SP_ERR_FAIL;
593
594         if (cfsetispeed(&term, baud) < 0)
595                 return SP_ERR_FAIL;
596
597         term.c_cflag &= ~CSIZE;
598         switch (bits) {
599         case 8:
600                 term.c_cflag |= CS8;
601                 break;
602         case 7:
603                 term.c_cflag |= CS7;
604                 break;
605         default:
606                 return SP_ERR_ARG;
607         }
608
609         term.c_cflag &= ~CSTOPB;
610         switch (stopbits) {
611         case 1:
612                 term.c_cflag &= ~CSTOPB;
613                 break;
614         case 2:
615                 term.c_cflag |= CSTOPB;
616                 break;
617         default:
618                 return SP_ERR_ARG;
619         }
620
621         term.c_iflag &= ~(IXON | IXOFF);
622         term.c_cflag &= ~CRTSCTS;
623         switch (flowcontrol) {
624         case 0:
625                 /* No flow control. */
626                 break;
627         case 1:
628                 term.c_cflag |= CRTSCTS;
629                 break;
630         case 2:
631                 term.c_iflag |= IXON | IXOFF;
632                 break;
633         default:
634                 return SP_ERR_ARG;
635         }
636
637         term.c_iflag &= ~IGNPAR;
638         term.c_cflag &= ~(PARODD | PARENB);
639         switch (parity) {
640         case SP_PARITY_NONE:
641                 term.c_iflag |= IGNPAR;
642                 break;
643         case SP_PARITY_EVEN:
644                 term.c_cflag |= PARENB;
645                 break;
646         case SP_PARITY_ODD:
647                 term.c_cflag |= PARENB | PARODD;
648                 break;
649         default:
650                 return SP_ERR_ARG;
651         }
652
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;
658 #endif
659
660         /* Disable canonical mode, and don't echo input characters. */
661         term.c_lflag &= ~(ICANON | ECHO);
662
663         /* Write the configured settings. */
664         if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
665                 return SP_ERR_FAIL;
666
667         if (rts != -1) {
668                 controlbits = TIOCM_RTS;
669                 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
670                                 &controlbits) < 0)
671                         return SP_ERR_FAIL;
672         }
673
674         if (dtr != -1) {
675                 controlbits = TIOCM_DTR;
676                 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
677                                 &controlbits) < 0)
678                         return SP_ERR_FAIL;
679         }
680 #endif
681
682         return SP_OK;
683 }
684
685 /**
686  * Get error code for failed operation.
687  *
688  * In order to obtain the correct result, this function should be called
689  * straight after the failure, before executing any other system operations.
690  *
691  * @return The system's numeric code for the error that caused the last
692  *         operation to fail.
693  */
694 int sp_last_error_code(void)
695 {
696 #ifdef _WIN32
697         return GetLastError();
698 #else
699         return errno;
700 #endif
701 }
702
703 /**
704  * Get error message for failed operation.
705  *
706  * In order to obtain the correct result, this function should be called
707  * straight after the failure, before executing other system operations.
708  *
709  * @return The system's message for the error that caused the last
710  *         operation to fail. This string may be allocated by the function,
711  *         and can be freed after use by calling sp_free_error_message.
712  */
713 char *sp_last_error_message(void)
714 {
715 #ifdef _WIN32
716         LPVOID message;
717         DWORD error = GetLastError();
718
719         FormatMessage(
720                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
721                 FORMAT_MESSAGE_FROM_SYSTEM |
722                 FORMAT_MESSAGE_IGNORE_INSERTS,
723                 NULL,
724                 error,
725                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
726                 (LPTSTR) &message,
727                 0, NULL );
728
729         return message;
730 #else
731         return strerror(errno);
732 #endif
733 }
734
735 /**
736  * Free error message.
737  *
738  * This function can be used to free a string returned by the
739  * sp_last_error_message function.
740  */
741 void sp_free_error_message(char *message)
742 {
743 #ifdef _WIN32
744         LocalFree(message);
745 #else
746         (void)message;
747 #endif
748 }