|
| 1 | +#include <libserialport.h> |
| 2 | +#include <stdio.h> |
| 3 | +#include <stdbool.h> |
| 4 | +#include <string.h> |
| 5 | +/* Example of how to get a list of serial ports on the system. |
| 6 | + * |
| 7 | + * This example file is released to the public domain. */ |
| 8 | + |
| 9 | +int main(int argc, char **argv) |
| 10 | +{ |
| 11 | + /* A pointer to a null-terminated array of pointers to |
| 12 | + * struct sp_port, which will contain the ports found.*/ |
| 13 | + struct sp_port **port_list; |
| 14 | + char *search_name = NULL; |
| 15 | + bool found = false; |
| 16 | + bool search = false; |
| 17 | + if (argc>2) |
| 18 | + { |
| 19 | + printf("Usage %s <optional serial port to search>\n", argv[0]); |
| 20 | + return -1; |
| 21 | + } |
| 22 | + if (argc == 2) { |
| 23 | + search_name = argv[1]; |
| 24 | + search = true; |
| 25 | + } |
| 26 | + if (!search) { |
| 27 | + printf("Getting port list.\n"); |
| 28 | + } |
| 29 | + /* Call sp_list_ports() to get the ports. The port_list |
| 30 | + * pointer will be updated to refer to the array created. */ |
| 31 | + enum sp_return result = sp_list_ports(&port_list); |
| 32 | + |
| 33 | + if (result != SP_OK) { |
| 34 | + printf("sp_list_ports() failed!\n"); |
| 35 | + return -1; |
| 36 | + } |
| 37 | + |
| 38 | + /* Iterate through the ports. When port_list[i] is NULL |
| 39 | + * this indicates the end of the list. */ |
| 40 | + int i; |
| 41 | + for (i = 0; port_list[i] != NULL; i++) { |
| 42 | + struct sp_port *port = port_list[i]; |
| 43 | + |
| 44 | + /* Get the name of the port. */ |
| 45 | + char *port_name = sp_get_port_name(port); |
| 46 | + if (!search) { |
| 47 | + printf("Found port: %s\n", port_name); |
| 48 | + } else { |
| 49 | + if (strcmp( search_name, port_name ) == 0) { |
| 50 | + found = true; |
| 51 | + break; |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + if (!search){ |
| 56 | + printf("Found %d ports.\n", i); |
| 57 | + printf("Freeing port list.\n"); |
| 58 | + } |
| 59 | + |
| 60 | + /* Free the array created by sp_list_ports(). */ |
| 61 | + sp_free_port_list(port_list); |
| 62 | + |
| 63 | + /* Note that this will also free all the sp_port structures |
| 64 | + * it points to. If you want to keep one of them (e.g. to |
| 65 | + * use that port in the rest of your program), take a copy |
| 66 | + * of it first using sp_copy_port(). */ |
| 67 | + |
| 68 | + return (search) ? !found : 0; |
| 69 | +} |
0 commit comments