1 /*
2  * Copyright (c) 2018-2023 O.S.Systems
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/logging/log.h>
8 LOG_MODULE_DECLARE(updatehub, CONFIG_UPDATEHUB_LOG_LEVEL);
9 
10 #include <zephyr/shell/shell.h>
11 #include <zephyr/mgmt/updatehub.h>
12 
13 #include "updatehub_firmware.h"
14 #include "updatehub_device.h"
15 #include "updatehub_storage.h"
16 
17 #if defined(CONFIG_UPDATEHUB_CE)
18 #define UPDATEHUB_SERVER CONFIG_UPDATEHUB_SERVER
19 #else
20 #define UPDATEHUB_SERVER "coap.updatehub.io"
21 #endif
22 
cmd_run(const struct shell * sh,size_t argc,char ** argv)23 static int cmd_run(const struct shell *sh, size_t argc,
24 		   char **argv)
25 {
26 	int ret = -1;
27 
28 	shell_fprintf(sh, SHELL_INFO, "Starting UpdateHub run...\n");
29 
30 	switch (updatehub_probe()) {
31 	case UPDATEHUB_HAS_UPDATE:
32 		switch (updatehub_update()) {
33 		case UPDATEHUB_OK:
34 			ret = 0;
35 			break;
36 		default:
37 			shell_fprintf(sh, SHELL_ERROR, "Error installing update.\n");
38 			break;
39 		}
40 		break;
41 
42 	case UPDATEHUB_NO_UPDATE:
43 		shell_fprintf(sh, SHELL_INFO, "No update found\n");
44 		ret = 0;
45 		break;
46 
47 	default:
48 		shell_fprintf(sh, SHELL_ERROR, "Invalid response\n");
49 		break;
50 	}
51 
52 	return ret;
53 }
54 
cmd_info(const struct shell * sh,size_t argc,char ** argv)55 static int cmd_info(const struct shell *sh, size_t argc, char **argv)
56 {
57 	ARG_UNUSED(argc);
58 	ARG_UNUSED(argv);
59 
60 	char *device_id = k_malloc(DEVICE_ID_HEX_MAX_SIZE);
61 	char *firmware_version = k_malloc(FIRMWARE_IMG_VER_STRLEN_MAX);
62 	int ret = 0;
63 
64 	if (device_id == NULL || firmware_version == NULL) {
65 		LOG_ERR("Could not alloc device_id or firmware_version memory");
66 
67 		ret = -ENOMEM;
68 
69 		goto updatehub_shell_error;
70 	}
71 
72 	updatehub_get_device_identity(device_id, DEVICE_ID_HEX_MAX_SIZE);
73 	updatehub_get_firmware_version(UPDATEHUB_SLOT_PARTITION_0,
74 				       firmware_version,
75 				       FIRMWARE_IMG_VER_STRLEN_MAX);
76 
77 	shell_fprintf(sh, SHELL_NORMAL, "Unique device id: %s\n",
78 		      device_id);
79 	shell_fprintf(sh, SHELL_NORMAL, "Firmware Version: %s\n",
80 		      firmware_version);
81 	shell_fprintf(sh, SHELL_NORMAL, "Product uid: %s\n",
82 		      CONFIG_UPDATEHUB_PRODUCT_UID);
83 	shell_fprintf(sh, SHELL_NORMAL, "UpdateHub Server: %s\n",
84 		      UPDATEHUB_SERVER);
85 
86 updatehub_shell_error:
87 	if (device_id) {
88 		k_free(device_id);
89 	}
90 
91 	if (firmware_version) {
92 		k_free(firmware_version);
93 	}
94 
95 	return ret;
96 }
97 
98 SHELL_STATIC_SUBCMD_SET_CREATE(sub_updatehub, SHELL_CMD(info, NULL, "Dump UpdateHub information",
99 							cmd_info),
100 			       SHELL_CMD(run, NULL, "Trigger an UpdateHub update run", cmd_run),
101 			       SHELL_SUBCMD_SET_END);
102 
103 SHELL_CMD_REGISTER(updatehub, &sub_updatehub, "UpdateHub commands", NULL);
104