1 /*
2  * Copyright (c) 2023 Basalte bv
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <string.h>
8 #include <zephyr/net/coap_service.h>
9 #include <zephyr/shell/shell.h>
10 
11 
cmd_list(const struct shell * sh,size_t argc,char ** argv)12 static int cmd_list(const struct shell *sh, size_t argc, char **argv)
13 {
14 	int count = 0;
15 
16 	ARG_UNUSED(argv);
17 
18 	if (argc > 1) {
19 		return -EINVAL;
20 	}
21 
22 	shell_print(sh, "     Name             State            Endpoint");
23 	COAP_SERVICE_FOREACH(service) {
24 		shell_print(sh,
25 			    "[%2d] %-16s %-16s %s:%d",
26 			    ++count,
27 			    service->name,
28 			    service->data->sock_fd < 0 ? "INACTIVE" : "ACTIVE",
29 			    service->host != NULL ? service->host : "",
30 			    *service->port);
31 	}
32 
33 	if (count == 0) {
34 		shell_print(sh, "No services available");
35 		return -ENOENT;
36 	}
37 
38 	return 0;
39 }
40 
cmd_start(const struct shell * sh,size_t argc,char ** argv)41 static int cmd_start(const struct shell *sh, size_t argc, char **argv)
42 {
43 	int ret = -ENOENT;
44 
45 	if (argc != 2) {
46 		shell_error(sh, "Usage: start <service>");
47 		return -EINVAL;
48 	}
49 
50 	COAP_SERVICE_FOREACH(service) {
51 		if (strcmp(argv[1], service->name) == 0) {
52 			ret = coap_service_start(service);
53 			break;
54 		}
55 	}
56 
57 	if (ret < 0) {
58 		shell_error(sh, "Failed to start service (%d)", ret);
59 	}
60 
61 	return ret;
62 }
63 
cmd_stop(const struct shell * sh,size_t argc,char ** argv)64 static int cmd_stop(const struct shell *sh, size_t argc, char **argv)
65 {
66 	int ret = -ENOENT;
67 
68 	if (argc != 2) {
69 		shell_error(sh, "Usage: stop <service>");
70 		return -EINVAL;
71 	}
72 
73 	COAP_SERVICE_FOREACH(service) {
74 		if (strcmp(argv[1], service->name) == 0) {
75 			ret = coap_service_stop(service);
76 			break;
77 		}
78 	}
79 
80 	if (ret < 0) {
81 		shell_error(sh, "Failed to stop service (%d)", ret);
82 	}
83 
84 	return ret;
85 }
86 
87 SHELL_STATIC_SUBCMD_SET_CREATE(sub_coap_service,
88 	SHELL_CMD(start, NULL,
89 		  "Start a CoAP Service\n"
90 		  "Usage: start <service>",
91 		  cmd_start),
92 	SHELL_CMD(stop, NULL,
93 		  "Stop a CoAP Service\n"
94 		  "Usage: stop <service>",
95 		  cmd_stop),
96 	SHELL_SUBCMD_SET_END /* Array terminated. */
97 );
98 SHELL_CMD_REGISTER(coap_service, &sub_coap_service, "CoAP Service commands", cmd_list);
99