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