1 /*
2  * Copyright (c) 2015 Christopher Anderson
3  *
4  * Use of this source code is governed by a MIT-style
5  * license that can be found in the LICENSE file or at
6  * https://opensource.org/licenses/MIT
7  */
8 
9 #include <dev/gpio.h>
10 #include <lk/console_cmd.h>
11 #include <string.h>
12 #include <stdio.h>
13 
14 struct flag_labels {
15     unsigned id;
16     const char *label;
17 };
18 
19 struct flag_labels gpio_flag_labels[] = {
20     { GPIO_INPUT,       "input" },
21     { GPIO_OUTPUT,      "output" },
22     { GPIO_LEVEL,       "level" },
23     { GPIO_EDGE,        "edge" },
24     { GPIO_RISING,      "rising" },
25     { GPIO_FALLING,     "falling" },
26     { GPIO_HIGH,        "high" },
27     { GPIO_LOW,         "low" },
28     { GPIO_PULLUP,      "pullup" },
29     { GPIO_PULLDOWN,    "pulldown" },
30 };
31 
get_flag_value(const char * str)32 static unsigned int get_flag_value(const char *str) {
33     for (unsigned i = 0; i < countof(gpio_flag_labels); i++) {
34         if (!strcmp(str, gpio_flag_labels[i].label)) {
35             return gpio_flag_labels[i].id;
36         }
37     }
38 
39     return 0;
40 }
41 
42 /* Ideally this would be generic, but different platforms have varying manners of handling gpio
43  * numbers / banks etc. Nvidia uses A-F, ST uses # and ports, Xilinx uses #s and banks. Etc.
44  */
cmd_gpio(int argc,const console_cmd_args * argv)45 static int cmd_gpio(int argc, const console_cmd_args *argv) {
46     if (argc == 4 && !strcmp(argv[1].str,"set")) {
47         unsigned int gpio = argv[2].u;
48         unsigned int value = argv[3].u;
49 
50         gpio_set(gpio, value);
51     } else if (argc == 3 && !strcmp(argv[1].str,"get")) {
52         unsigned int gpio = argv[2].u;
53 
54         printf("gpio %u: %d\n", gpio, gpio_get(gpio));
55     } else if (argc >= 3 && !strcmp(argv[1].str,"cfg")) {
56         unsigned int gpio = argv[2].u;
57         unsigned int flags = 0;
58 
59         for (int i = 3; i < argc; i++) {
60             flags |= get_flag_value(argv[i].str);
61         }
62 
63         gpio_config(gpio, flags);
64     } else {
65         printf("gpio set <gpio #> <value>\n");
66         printf("gpio get <gpio #>\n");
67         printf("gpio cfg <gpio #> [flags: ");
68         for (unsigned int i = 0; i < countof(gpio_flag_labels); i++) {
69             printf("%s ", gpio_flag_labels[i].label);
70         }
71         putchar(']');
72         putchar('\n');
73     }
74 
75     return 0;
76 }
77 STATIC_COMMAND_START
78 STATIC_COMMAND("gpio", "commands for manipulating system gpios", &cmd_gpio)
79 STATIC_COMMAND_END(gpio);
80