diff options
Diffstat (limited to 'serial/usbdev.c')
-rw-r--r-- | serial/usbdev.c | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/serial/usbdev.c b/serial/usbdev.c new file mode 100644 index 0000000..2a543fa --- /dev/null +++ b/serial/usbdev.c | |||
@@ -0,0 +1,65 @@ | |||
1 | #include <dirent.h> | ||
2 | #include <errno.h> | ||
3 | #include <fcntl.h> | ||
4 | #include <stdio.h> | ||
5 | #include <stdlib.h> | ||
6 | #include <string.h> | ||
7 | #include <termios.h> | ||
8 | #include <unistd.h> | ||
9 | |||
10 | #define LIDAR_SERIAL "dce74d177fdc724ba5757727edc269bf" | ||
11 | #define WHEEL_SERIAL "0001" | ||
12 | |||
13 | enum usbDevice { lidar, wheel, other }; | ||
14 | char device_path[256]; | ||
15 | |||
16 | int identify_device(const char *port) { | ||
17 | char cmd[256]; | ||
18 | snprintf(cmd, sizeof(cmd), "udevadm info --name=%s | grep 'E: ID_SERIAL='", | ||
19 | port); | ||
20 | FILE *fp = popen(cmd, "r"); | ||
21 | if (!fp) { | ||
22 | perror("popen"); | ||
23 | return other; | ||
24 | } | ||
25 | |||
26 | static char serial[256]; | ||
27 | if (fgets(serial, sizeof(serial), fp) != NULL) { | ||
28 | if (strstr(serial, WHEEL_SERIAL)) { | ||
29 | pclose(fp); | ||
30 | return wheel; | ||
31 | } else if (strstr(serial, LIDAR_SERIAL)) { | ||
32 | pclose(fp); | ||
33 | return lidar; | ||
34 | } | ||
35 | } | ||
36 | pclose(fp); | ||
37 | return other; | ||
38 | } | ||
39 | |||
40 | const char *findUSBDev(const char *device_type) { | ||
41 | DIR *dir; | ||
42 | struct dirent *entry; | ||
43 | |||
44 | dir = opendir("/dev"); | ||
45 | if (dir == NULL) { | ||
46 | perror("opendir"); | ||
47 | return NULL; | ||
48 | } | ||
49 | |||
50 | while ((entry = readdir(dir)) != NULL) { | ||
51 | if (strncmp(entry->d_name, "ttyUSB", 6) == 0) { | ||
52 | snprintf(device_path, sizeof(device_path), "/dev/%s", | ||
53 | entry->d_name); | ||
54 | int dev_type = identify_device(device_path); | ||
55 | if ((dev_type == lidar && strcmp(device_type, "lidar") == 0) || | ||
56 | (dev_type == wheel && strcmp(device_type, "wheel") == 0)) { | ||
57 | closedir(dir); | ||
58 | return device_path; | ||
59 | } | ||
60 | } | ||
61 | } | ||
62 | |||
63 | closedir(dir); | ||
64 | return NULL; | ||
65 | } | ||