1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2020 Philippe Reynes <philippe.reynes@softathome.com>
4  *
5  * Based on led.c
6  */
7 
8 #include <common.h>
9 #include <command.h>
10 #include <dm.h>
11 #include <button.h>
12 #include <dm/uclass-internal.h>
13 
14 static const char *const state_label[] = {
15 	[BUTTON_OFF]	= "off",
16 	[BUTTON_ON]	= "on",
17 };
18 
show_button_state(struct udevice * dev)19 static int show_button_state(struct udevice *dev)
20 {
21 	int ret;
22 
23 	ret = button_get_state(dev);
24 	if (ret >= BUTTON_COUNT)
25 		ret = -EINVAL;
26 	if (ret >= 0)
27 		printf("%s\n", state_label[ret]);
28 
29 	return ret;
30 }
31 
list_buttons(void)32 static int list_buttons(void)
33 {
34 	struct udevice *dev;
35 	int ret;
36 
37 	for (uclass_find_first_device(UCLASS_BUTTON, &dev);
38 	     dev;
39 	     uclass_find_next_device(&dev)) {
40 		struct button_uc_plat *plat = dev_get_uclass_plat(dev);
41 
42 		if (!plat->label)
43 			continue;
44 		printf("%-15s ", plat->label);
45 		if (device_active(dev)) {
46 			ret = show_button_state(dev);
47 			if (ret < 0)
48 				printf("Error %d\n", ret);
49 		} else {
50 			printf("<inactive>\n");
51 		}
52 	}
53 
54 	return 0;
55 }
56 
do_button(struct cmd_tbl * cmdtp,int flag,int argc,char * const argv[])57 int do_button(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
58 {
59 	const char *button_label;
60 	struct udevice *dev;
61 	int ret;
62 
63 	/* Validate arguments */
64 	if (argc < 2)
65 		return CMD_RET_USAGE;
66 	button_label = argv[1];
67 	if (strncmp(button_label, "list", 4) == 0)
68 		return list_buttons();
69 
70 	ret = button_get_by_label(button_label, &dev);
71 	if (ret) {
72 		printf("Button '%s' not found (err=%d)\n", button_label, ret);
73 		return CMD_RET_FAILURE;
74 	}
75 
76 	ret = show_button_state(dev);
77 
78 	return !ret;
79 }
80 
81 U_BOOT_CMD(
82 	button, 2, 1, do_button,
83 	"manage buttons",
84 	"<button_label> \tGet button state\n"
85 	"button list\t\tShow a list of buttons"
86 );
87