1 /*
2  * Copyright (c) 2018 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifndef SHELL_H__
8 #define SHELL_H__
9 
10 #include <zephyr/kernel.h>
11 #include <zephyr/shell/shell_types.h>
12 #include <zephyr/shell/shell_history.h>
13 #include <zephyr/shell/shell_fprintf.h>
14 #include <zephyr/shell/shell_log_backend.h>
15 #include <zephyr/shell/shell_string_conv.h>
16 #include <zephyr/logging/log_instance.h>
17 #include <zephyr/logging/log.h>
18 #include <zephyr/sys/iterable_sections.h>
19 #include <zephyr/sys/util.h>
20 #include <zephyr/toolchain.h>
21 
22 #if defined CONFIG_SHELL_GETOPT
23 #include <zephyr/sys/sys_getopt.h>
24 #endif
25 
26 #ifdef __cplusplus
27 extern "C" {
28 #endif
29 
30 #ifndef CONFIG_SHELL_PROMPT_BUFF_SIZE
31 #define CONFIG_SHELL_PROMPT_BUFF_SIZE 0
32 #endif
33 
34 #ifndef CONFIG_SHELL_CMD_BUFF_SIZE
35 #define CONFIG_SHELL_CMD_BUFF_SIZE 0
36 #endif
37 
38 #ifndef CONFIG_SHELL_PRINTF_BUFF_SIZE
39 #define CONFIG_SHELL_PRINTF_BUFF_SIZE 0
40 #endif
41 
42 #ifndef CONFIG_SHELL_HISTORY_BUFFER
43 #define CONFIG_SHELL_HISTORY_BUFFER 0
44 #endif
45 
46 #define Z_SHELL_CMD_ROOT_LVL		(0u)
47 
48 #define SHELL_HEXDUMP_BYTES_IN_LINE	16
49 
50 /**
51  * @brief Flag indicates that optional arguments will be treated as one,
52  *	  unformatted argument.
53  *
54  * By default, shell is parsing all arguments, treats all spaces as argument
55  * separators unless they are within quotation marks which are removed in that
56  * case. If command rely on unformatted argument then this flag shall be used
57  * in place of number of optional arguments in command definition to indicate
58  * that only mandatory arguments shall be parsed and remaining command string is
59  * passed as a raw string.
60  */
61 #define SHELL_OPT_ARG_RAW	(0xFE)
62 
63 /**
64  * @brief Flag indicating that number of optional arguments is not limited.
65  */
66 #define SHELL_OPT_ARG_CHECK_SKIP (0xFF)
67 
68 /**
69  * @brief Flag indicating maximum number of optional arguments that can be
70  *	  validated.
71  */
72 #define SHELL_OPT_ARG_MAX		(0xFD)
73 
74 /**
75  * @brief Shell API
76  * @defgroup shell_api Shell API
77  * @since 1.14
78  * @version 1.0.0
79  * @ingroup os_services
80  * @{
81  */
82 
83 struct shell_static_entry;
84 
85 /**
86  * @brief Shell dynamic command descriptor.
87  *
88  * @details Function shall fill the received shell_static_entry structure
89  * with requested (idx) dynamic subcommand data. If there is more than
90  * one dynamic subcommand available, the function shall ensure that the
91  * returned commands: entry->syntax are sorted in alphabetical order.
92  * If idx exceeds the available dynamic subcommands, the function must
93  * write to entry->syntax NULL value. This will indicate to the shell
94  * module that there are no more dynamic commands to read.
95  */
96 typedef void (*shell_dynamic_get)(size_t idx,
97 				  struct shell_static_entry *entry);
98 
99 /**
100  * @brief Shell command descriptor.
101  */
102 union shell_cmd_entry {
103 	/** Pointer to function returning dynamic commands.*/
104 	shell_dynamic_get dynamic_get;
105 
106 	/** Pointer to array of static commands. */
107 	const struct shell_static_entry *entry;
108 };
109 
110 struct shell;
111 
112 struct shell_static_args {
113 	uint8_t mandatory; /*!< Number of mandatory arguments. */
114 	uint8_t optional;  /*!< Number of optional arguments. */
115 };
116 
117 /**
118  * @brief Get by index a device that matches .
119  *
120  * This can be used, for example, to identify I2C_1 as the second I2C
121  * device.
122  *
123  * Devices that failed to initialize or do not have a non-empty name
124  * are excluded from the candidates for a match.
125  *
126  * @param idx the device number starting from zero.
127  *
128  * @param prefix optional name prefix used to restrict candidate
129  * devices.  Indexing is done relative to devices with names that
130  * start with this text.  Pass null if no prefix match is required.
131  */
132 const struct device *shell_device_lookup(size_t idx,
133 					 const char *prefix);
134 
135 /**
136  * @brief Get by index a device that matches .
137  *
138  * This can be used, for example, to identify I2C_1 as the second I2C
139  * device.
140  *
141  * Devices that failed to initialize - or deferred to be - are included
142  * from the candidates for a match, minus the ones who do not have
143  * a non-empty name.
144  *
145  * @param idx the device number starting from zero.
146  *
147  * @param prefix optional name prefix used to restrict candidate
148  * devices.  Indexing is done relative to devices with names that
149  * start with this text.  Pass null if no prefix match is required.
150  */
151 const struct device *shell_device_lookup_all(size_t idx,
152 					     const char *prefix);
153 
154 /**
155  * @brief Get by index a non-initialized device that matches .
156  *
157  * This can be used, for example, to identify I2C_1 as the second I2C
158  * device.
159  *
160  * Devices that initialized successfully or do not have a non-empty name
161  * are excluded.
162  *
163  * @param idx the device number starting from zero.
164  *
165  * @param prefix optional name prefix used to restrict candidate
166  * devices.  Indexing is done relative to devices with names that
167  * start with this text.  Pass null if no prefix match is required.
168  */
169 const struct device *shell_device_lookup_non_ready(size_t idx,
170 						   const char *prefix);
171 
172 /**
173  * @brief Filter callback type, for use with shell_device_lookup_filter
174  *
175  * This is used as an argument of shell_device_lookup_filter to only return
176  * devices that match a specific condition, implemented by the filter.
177  *
178  * @param dev pointer to a struct device.
179  *
180  * @return bool, true if the filter matches the device type.
181  */
182 typedef bool (*shell_device_filter_t)(const struct device *dev);
183 
184 /**
185  * @brief Get a device by index and filter.
186  *
187  * This can be used to return devices matching a specific type.
188  *
189  * Devices that the filter returns false for, failed to initialize or do not
190  * have a non-empty name are excluded from the candidates for a match.
191  *
192  * @param idx the device number starting from zero.
193  *
194  * @param filter a pointer to a shell_device_filter_t function that returns
195  * true if the device matches the filter.
196  */
197 const struct device *shell_device_filter(size_t idx,
198 					 shell_device_filter_t filter);
199 
200 /**
201  * @brief Get a @ref device reference from its @ref device.name field or label.
202  *
203  * This function iterates through the devices on the system. If a device with
204  * the given @p name field is found, and that device initialized successfully at
205  * boot time, this function returns a pointer to the device.
206  *
207  * If no device has the given @p name, this function returns `NULL`.
208  *
209  * This function also returns NULL when a device is found, but it failed to
210  * initialize successfully at boot time. (To troubleshoot this case, set a
211  * breakpoint on your device driver's initialization function.)
212  *
213  * @param name device name to search for. A null pointer, or a pointer to an
214  * empty string, will cause NULL to be returned.
215  *
216  * @return pointer to device structure with the given name; `NULL` if the device
217  * is not found or if the device with that name's initialization function
218  * failed.
219  */
220 const struct device *shell_device_get_binding(const char *name);
221 
222 /**
223  * @brief Get a @ref device reference from its @ref device.name field or label.
224  *
225  * This function iterates through the devices on the system. If a device with
226  * the given @p name field is found, this function returns a pointer to the
227  * device.
228  *
229  * If no device has the given @p name, this function returns `NULL`.
230  *
231  * @param name device name to search for. A null pointer, or a pointer to an
232  * empty string, will cause NULL to be returned.
233  *
234  * @return pointer to device structure with the given name; `NULL` if the device
235  * is not found.
236  */
237 const struct device *shell_device_get_binding_all(const char *name);
238 
239 /**
240  * @brief Shell command handler prototype.
241  *
242  * @param sh Shell instance.
243  * @param argc  Arguments count.
244  * @param argv  Arguments.
245  *
246  * @retval 0 Successful command execution.
247  * @retval 1 Help printed and command not executed.
248  * @retval -EINVAL Argument validation failed.
249  * @retval -ENOEXEC Command not executed.
250  */
251 typedef int (*shell_cmd_handler)(const struct shell *sh,
252 				 size_t argc, char **argv);
253 
254 /**
255  * @brief Shell dictionary command handler prototype.
256  *
257  * @param sh Shell instance.
258  * @param argc  Arguments count.
259  * @param argv  Arguments.
260  * @param data  Pointer to the user data.
261  *
262  * @retval 0 Successful command execution.
263  * @retval 1 Help printed and command not executed.
264  * @retval -EINVAL Argument validation failed.
265  * @retval -ENOEXEC Command not executed.
266  */
267 typedef int (*shell_dict_cmd_handler)(const struct shell *sh, size_t argc,
268 				      char **argv, void *data);
269 
270 /* When entries are added to the memory section a padding is applied for
271  * the posix architecture with 64bits builds and x86_64 targets. Adding padding to allow handle data
272  * in the memory section as array.
273  */
274 #if (defined(CONFIG_ARCH_POSIX) && defined(CONFIG_64BIT)) || defined(CONFIG_X86_64)
275 #define Z_SHELL_STATIC_ENTRY_PADDING 24
276 #else
277 #define Z_SHELL_STATIC_ENTRY_PADDING 0
278 #endif
279 
280 /*
281  * @brief Shell static command descriptor.
282  */
283 struct shell_static_entry {
284 	const char *syntax;			/*!< Command syntax strings. */
285 	const char *help;			/*!< Command help string. */
286 	const union shell_cmd_entry *subcmd;	/*!< Pointer to subcommand. */
287 	shell_cmd_handler handler;		/*!< Command handler. */
288 	struct shell_static_args args;		/*!< Command arguments. */
289 	uint8_t padding[Z_SHELL_STATIC_ENTRY_PADDING];
290 };
291 
292 /**
293  * @brief Shell structured help descriptor.
294  *
295  * @details This structure provides an organized way to specify command help
296  * as opposed to a free-form string. This helps make help messages more
297  * consistent and easier to read.
298  */
299 struct shell_cmd_help {
300 	/* @cond INTERNAL_HIDDEN */
301 	uint32_t magic;
302 	/* @endcond */
303 	const char *description; /*!< Command description */
304 	const char *usage;       /*!< Command usage string */
305 };
306 
307 /**
308  * @cond INTERNAL_HIDDEN
309  */
310 
311 /**
312  * @brief Magic number used to identify the beginning of a structured help
313  * message when cast to a char pointer.
314  */
315 #define SHELL_STRUCTURED_HELP_MAGIC 0x86D20BC4
316 
317 /**
318  * @endcond
319  */
320 
321 /**
322  * @brief Check if help string is structured help.
323  *
324  * @param help Pointer to help string or structured help.
325  * @return true if help is structured, false otherwise.
326  */
shell_help_is_structured(const char * help)327 static inline bool shell_help_is_structured(const char *help)
328 {
329 	const struct shell_cmd_help *structured = (const struct shell_cmd_help *)help;
330 
331 	return structured != NULL && IS_PTR_ALIGNED(structured, struct shell_cmd_help) &&
332 	       structured->magic == SHELL_STRUCTURED_HELP_MAGIC;
333 }
334 
335 #if defined(CONFIG_SHELL_HELP) || defined(__DOXYGEN__)
336 /**
337  * @brief Helper macro to create structured help inline.
338  *
339  * This macro allows you to pass structured help directly to existing shell macros.
340  *
341  * Example:
342  *
343  * @code{.c}
344  * #define MY_CMD_HELP SHELL_HELP("Do stuff", "<device> <arg1> [<arg2>]")
345  * SHELL_CMD_REGISTER(my_cmd, NULL, MY_CMD_HELP, &my_cmd_handler, 1, 1);
346  * @endcode
347  *
348  * @param[in] _description	Command description.
349  *				This can be a multi-line string. First line should be one sentence
350  *				describing the command. Additional lines might be used to provide
351  *				additional details.
352  *
353  * @param[in] _usage		Command usage string.
354  *				This can be a multi-line string. First line should always be
355  *				indicating the command syntax (_without_ the command name).
356  *				Additional lines may be used to provide additional details, e.g.
357  *				explain the meaning of each argument, allowed values, etc.
358  */
359 #define SHELL_HELP(_description, _usage)                                                           \
360 	((const char *)&(const struct shell_cmd_help){                                             \
361 		.magic = SHELL_STRUCTURED_HELP_MAGIC,                                              \
362 		.description = (_description),                                                     \
363 		.usage = (_usage),                                                                 \
364 	})
365 #else
366 #define SHELL_HELP(_description, _usage) NULL
367 #endif /* CONFIG_SHELL_HELP */
368 
369 /**
370  * @brief Macro for defining and adding a root command (level 0) with required
371  * number of arguments.
372  *
373  * @note Each root command shall have unique syntax. If a command will be called
374  * with wrong number of arguments shell will print an error message and command
375  * handler will not be called.
376  *
377  * @param[in] syntax	Command syntax (for example: history).
378  * @param[in] subcmd	Pointer to a subcommands array.
379  * @param[in] help	Pointer to a command help string (use @ref SHELL_HELP for structured help)
380  * @param[in] handler	Pointer to a function handler.
381  * @param[in] mandatory	Number of mandatory arguments including command name.
382  * @param[in] optional	Number of optional arguments.
383  */
384 #define SHELL_CMD_ARG_REGISTER(syntax, subcmd, help, handler,		   \
385 			       mandatory, optional)			   \
386 	static const struct shell_static_entry UTIL_CAT(_shell_, syntax) = \
387 	SHELL_CMD_ARG(syntax, subcmd, help, handler, mandatory, optional); \
388 	static const TYPE_SECTION_ITERABLE(union shell_cmd_entry,	   \
389 		UTIL_CAT(shell_cmd_, syntax), shell_root_cmds,		   \
390 		UTIL_CAT(shell_cmd_, syntax)				   \
391 	) = {								   \
392 		.entry = &UTIL_CAT(_shell_, syntax)			   \
393 	}
394 
395 /**
396  * @brief Macro for defining and adding a conditional root command (level 0)
397  * with required number of arguments.
398  *
399  * @see SHELL_CMD_ARG_REGISTER for details.
400  *
401  * Macro can be used to create a command which can be conditionally present.
402  * It is and alternative to \#ifdefs around command registration and command
403  * handler. If command is disabled handler and subcommands are removed from
404  * the application.
405  *
406  * @param[in] flag	Compile time flag. Command is present only if flag
407  *			exists and equals 1.
408  * @param[in] syntax	Command syntax (for example: history).
409  * @param[in] subcmd	Pointer to a subcommands array.
410  * @param[in] help	Pointer to a command help string (use @ref SHELL_HELP for structured help).
411  * @param[in] handler	Pointer to a function handler.
412  * @param[in] mandatory	Number of mandatory arguments including command name.
413  * @param[in] optional	Number of optional arguments.
414  */
415 #define SHELL_COND_CMD_ARG_REGISTER(flag, syntax, subcmd, help, handler, \
416 					mandatory, optional) \
417 	COND_CODE_1(\
418 		flag, \
419 		(\
420 		SHELL_CMD_ARG_REGISTER(syntax, subcmd, help, handler, \
421 					mandatory, optional) \
422 		), \
423 		(\
424 		static shell_cmd_handler dummy_##syntax##_handler __unused = \
425 								handler;\
426 		static const union shell_cmd_entry *dummy_subcmd_##syntax \
427 			__unused = subcmd\
428 		) \
429 	)
430 /**
431  * @brief Macro for defining and adding a root command (level 0) with
432  * arguments.
433  *
434  * @note All root commands must have different name.
435  *
436  * @param[in] syntax	Command syntax (for example: history).
437  * @param[in] subcmd	Pointer to a subcommands array.
438  * @param[in] help	Pointer to a command help string. Use @ref SHELL_HELP for structured help.
439  * @param[in] handler	Pointer to a function handler.
440  */
441 #define SHELL_CMD_REGISTER(syntax, subcmd, help, handler) \
442 	SHELL_CMD_ARG_REGISTER(syntax, subcmd, help, handler, 0, 0)
443 
444 /**
445  * @brief Macro for defining and adding a conditional root command (level 0)
446  * with arguments.
447  *
448  * @see SHELL_COND_CMD_ARG_REGISTER.
449  *
450  * @param[in] flag	Compile time flag. Command is present only if flag
451  *			exists and equals 1.
452  * @param[in] syntax	Command syntax (for example: history).
453  * @param[in] subcmd	Pointer to a subcommands array.
454  * @param[in] help	Pointer to a command help string. Use @ref SHELL_HELP for structured help.
455  * @param[in] handler	Pointer to a function handler.
456  */
457 #define SHELL_COND_CMD_REGISTER(flag, syntax, subcmd, help, handler) \
458 	SHELL_COND_CMD_ARG_REGISTER(flag, syntax, subcmd, help, handler, 0, 0)
459 
460 /**
461  * @brief Macro for creating a subcommand set. It must be used outside of any
462  * function body.
463  *
464  * Example usage:
465  * @code{.c}
466  *	SHELL_STATIC_SUBCMD_SET_CREATE(
467  *		foo,
468  *		SHELL_CMD(abc, ...),
469  *		SHELL_CMD(def, ...),
470  *		SHELL_SUBCMD_SET_END
471  *	)
472  * @endcode
473  *
474  * @param[in] name	Name of the subcommand set.
475  * @param[in] ...	List of commands created with @ref SHELL_CMD_ARG or
476  *			or @ref SHELL_CMD
477  */
478 #define SHELL_STATIC_SUBCMD_SET_CREATE(name, ...)			\
479 	static const struct shell_static_entry shell_##name[] = {	\
480 		__VA_ARGS__						\
481 	};								\
482 	static const union shell_cmd_entry name = {			\
483 		.entry = shell_##name					\
484 	}
485 
486 #define Z_SHELL_UNDERSCORE(x) _##x
487 #define Z_SHELL_SUBCMD_NAME(...) \
488 	UTIL_CAT(shell_subcmds, MACRO_MAP_CAT(Z_SHELL_UNDERSCORE, __VA_ARGS__))
489 #define Z_SHELL_SUBCMD_SECTION_TAG(...) MACRO_MAP_CAT(Z_SHELL_UNDERSCORE, __VA_ARGS__)
490 #define Z_SHELL_SUBCMD_SET_SECTION_TAG(x) \
491 	Z_SHELL_SUBCMD_SECTION_TAG(NUM_VA_ARGS_LESS_1 x, __DEBRACKET x)
492 #define Z_SHELL_SUBCMD_ADD_SECTION_TAG(x, y) \
493 	Z_SHELL_SUBCMD_SECTION_TAG(NUM_VA_ARGS_LESS_1 x, __DEBRACKET x, y)
494 
495 /** @brief Create set of subcommands.
496  *
497  * Commands to this set are added using @ref SHELL_SUBCMD_ADD and @ref SHELL_SUBCMD_COND_ADD.
498  * Commands can be added from multiple files.
499  *
500  * @param[in] _name		Name of the set. @p _name is used to refer the set in the parent
501  * command.
502  *
503  * @param[in] _parent	Set of comma separated parent commands in parenthesis, e.g.
504  * (foo_cmd) if subcommands are for the root command "foo_cmd".
505  */
506 
507 #define SHELL_SUBCMD_SET_CREATE(_name, _parent) \
508 	static const TYPE_SECTION_ITERABLE(struct shell_static_entry, _name, shell_subcmds, \
509 					  Z_SHELL_SUBCMD_SET_SECTION_TAG(_parent))
510 
511 
512 /** @brief Conditionally add command to the set of subcommands.
513  *
514  * Add command to the set created with @ref SHELL_SUBCMD_SET_CREATE.
515  *
516  * @note The name of the section is formed as concatenation of number of parent
517  * commands, names of all parent commands and own syntax. Number of parent commands
518  * is added to ensure that section prefix is unique. Without it subcommands of
519  * (foo) and (foo, cmd1) would mix.
520  *
521  * @param[in] _flag	 Compile time flag. Command is present only if flag
522  *			 exists and equals 1.
523  * @param[in] _parent	 Parent command sequence. Comma separated in parenthesis.
524  * @param[in] _syntax	 Command syntax (for example: history).
525  * @param[in] _subcmd	 Pointer to a subcommands array.
526  * @param[in] _help	 Pointer to a command help string.
527  * @param[in] _handler	 Pointer to a function handler.
528  * @param[in] _mand	 Number of mandatory arguments including command name.
529  * @param[in] _opt	 Number of optional arguments.
530  */
531 #define SHELL_SUBCMD_COND_ADD(_flag, _parent, _syntax, _subcmd, _help, _handler, \
532 			   _mand, _opt) \
533 	COND_CODE_1(_flag, \
534 		(static const TYPE_SECTION_ITERABLE(struct shell_static_entry, \
535 					Z_SHELL_SUBCMD_NAME(__DEBRACKET _parent, _syntax), \
536 					shell_subcmds, \
537 					Z_SHELL_SUBCMD_ADD_SECTION_TAG(_parent, _syntax)) = \
538 			SHELL_EXPR_CMD_ARG(1, _syntax, _subcmd, _help, \
539 					   _handler, _mand, _opt)\
540 		), \
541 		(static shell_cmd_handler dummy_handler_##_syntax __unused = _handler;\
542 		 static const union shell_cmd_entry dummy_subcmd_##_syntax __unused = { \
543 			.entry = (const struct shell_static_entry *)_subcmd\
544 		 } \
545 		) \
546 	)
547 
548 /** @brief Add command to the set of subcommands.
549  *
550  * Add command to the set created with @ref SHELL_SUBCMD_SET_CREATE.
551  *
552  * @param[in] _parent	 Parent command sequence. Comma separated in parenthesis.
553  * @param[in] _syntax	 Command syntax (for example: history).
554  * @param[in] _subcmd	 Pointer to a subcommands array.
555  * @param[in] _help	 Pointer to a command help string.
556  * @param[in] _handler	 Pointer to a function handler.
557  * @param[in] _mand	 Number of mandatory arguments including command name.
558  * @param[in] _opt	 Number of optional arguments.
559  */
560 #define SHELL_SUBCMD_ADD(_parent, _syntax, _subcmd, _help, _handler, _mand, _opt) \
561 	SHELL_SUBCMD_COND_ADD(1, _parent, _syntax, _subcmd, _help, _handler, _mand, _opt)
562 
563 /**
564  * @brief Define ending subcommands set.
565  *
566  */
567 #define SHELL_SUBCMD_SET_END {0}
568 
569 /**
570  * @brief Macro for creating a dynamic entry.
571  *
572  * @param[in] name	Name of the dynamic entry.
573  * @param[in] get	Pointer to the function returning dynamic commands array
574  */
575 #define SHELL_DYNAMIC_CMD_CREATE(name, get)					\
576 	static const TYPE_SECTION_ITERABLE(union shell_cmd_entry, name,		\
577 		shell_dynamic_subcmds, name) =					\
578 	{									\
579 		.dynamic_get = get						\
580 	}
581 
582 /**
583  * @brief Initializes a shell command with arguments.
584  *
585  * @note If a command will be called with wrong number of arguments shell will
586  * print an error message and command handler will not be called.
587  *
588  * @param[in] syntax	 Command syntax (for example: history).
589  * @param[in] subcmd	 Pointer to a subcommands array.
590  * @param[in] help	 Pointer to a command help string. Use @ref SHELL_HELP for structured help.
591  * @param[in] handler	 Pointer to a function handler.
592  * @param[in] mand	 Number of mandatory arguments including command name.
593  * @param[in] opt	 Number of optional arguments.
594  */
595 #define SHELL_CMD_ARG(syntax, subcmd, help, handler, mand, opt) \
596 	SHELL_EXPR_CMD_ARG(1, syntax, subcmd, help, handler, mand, opt)
597 
598 /**
599  * @brief Initializes a conditional shell command with arguments.
600  *
601  * @see SHELL_CMD_ARG. Based on the flag, creates a valid entry or an empty
602  * command which is ignored by the shell. It is an alternative to \#ifdefs
603  * around command registration and command handler. However, empty structure is
604  * present in the flash even if command is disabled (subcommands and handler are
605  * removed). Macro internally handles case if flag is not defined so flag must
606  * be provided without any wrapper, e.g.: SHELL_COND_CMD_ARG(CONFIG_FOO, ...)
607  *
608  * @param[in] flag	 Compile time flag. Command is present only if flag
609  *			 exists and equals 1.
610  * @param[in] syntax	 Command syntax (for example: history).
611  * @param[in] subcmd	 Pointer to a subcommands array.
612  * @param[in] help	 Pointer to a command help string. Use @ref SHELL_HELP for structured help.
613  * @param[in] handler	 Pointer to a function handler.
614  * @param[in] mand	 Number of mandatory arguments including command name.
615  * @param[in] opt	 Number of optional arguments.
616  */
617 #define SHELL_COND_CMD_ARG(flag, syntax, subcmd, help, handler, mand, opt) \
618 	SHELL_EXPR_CMD_ARG(IS_ENABLED(flag), syntax, subcmd, help, \
619 			  handler, mand, opt)
620 
621 /**
622  * @brief Initializes a conditional shell command with arguments if expression
623  *	  gives non-zero result at compile time.
624  *
625  * @see SHELL_CMD_ARG. Based on the expression, creates a valid entry or an
626  * empty command which is ignored by the shell. It should be used instead of
627  * @ref SHELL_COND_CMD_ARG if condition is not a single configuration flag,
628  * e.g.:
629  * SHELL_EXPR_CMD_ARG(IS_ENABLED(CONFIG_FOO) &&
630  *		      IS_ENABLED(CONFIG_FOO_SETTING_1), ...)
631  *
632  * @param[in] _expr	 Expression.
633  * @param[in] _syntax	 Command syntax (for example: history).
634  * @param[in] _subcmd	 Pointer to a subcommands array.
635  * @param[in] _help	 Pointer to a command help string.
636  * @param[in] _handler	 Pointer to a function handler.
637  * @param[in] _mand	 Number of mandatory arguments including command name.
638  * @param[in] _opt	 Number of optional arguments.
639  */
640 #define SHELL_EXPR_CMD_ARG(_expr, _syntax, _subcmd, _help, _handler, \
641 			   _mand, _opt) \
642 	{ \
643 		.syntax = (_expr) ? (const char *)STRINGIFY(_syntax) : "", \
644 		.help  = (_expr) ? (const char *)_help : NULL, \
645 		.subcmd = (const union shell_cmd_entry *)((_expr) ? \
646 				_subcmd : NULL), \
647 		.handler = (shell_cmd_handler)((_expr) ? _handler : NULL), \
648 		.args = { .mandatory = _mand, .optional = _opt} \
649 	}
650 
651 /**
652  * @brief Initializes a shell command.
653  *
654  * @param[in] _syntax	Command syntax (for example: history).
655  * @param[in] _subcmd	Pointer to a subcommands array.
656  * @param[in] _help	Pointer to a command help string.
657  * @param[in] _handler	Pointer to a function handler.
658  */
659 #define SHELL_CMD(_syntax, _subcmd, _help, _handler) \
660 	SHELL_CMD_ARG(_syntax, _subcmd, _help, _handler, 0, 0)
661 
662 /**
663  * @brief Initializes a conditional shell command.
664  *
665  * @see SHELL_COND_CMD_ARG.
666  *
667  * @param[in] _flag	Compile time flag. Command is present only if flag
668  *			exists and equals 1.
669  * @param[in] _syntax	Command syntax (for example: history).
670  * @param[in] _subcmd	Pointer to a subcommands array.
671  * @param[in] _help	Pointer to a command help string.
672  * @param[in] _handler	Pointer to a function handler.
673  */
674 #define SHELL_COND_CMD(_flag, _syntax, _subcmd, _help, _handler) \
675 	SHELL_COND_CMD_ARG(_flag, _syntax, _subcmd, _help, _handler, 0, 0)
676 
677 /**
678  * @brief Initializes shell command if expression gives non-zero result at
679  *	  compile time.
680  *
681  * @see SHELL_EXPR_CMD_ARG.
682  *
683  * @param[in] _expr	Compile time expression. Command is present only if
684  *			expression is non-zero.
685  * @param[in] _syntax	Command syntax (for example: history).
686  * @param[in] _subcmd	Pointer to a subcommands array.
687  * @param[in] _help	Pointer to a command help string.
688  * @param[in] _handler	Pointer to a function handler.
689  */
690 #define SHELL_EXPR_CMD(_expr, _syntax, _subcmd, _help, _handler) \
691 	SHELL_EXPR_CMD_ARG(_expr, _syntax, _subcmd, _help, _handler, 0, 0)
692 
693 /* Internal macro used for creating handlers for dictionary commands. */
694 #define Z_SHELL_CMD_DICT_HANDLER_CREATE(_data, _handler)		\
695 static int UTIL_CAT(UTIL_CAT(cmd_dict_, UTIL_CAT(_handler, _)),		\
696 			GET_ARG_N(1, __DEBRACKET _data))(		\
697 		const struct shell *sh, size_t argc, char **argv)	\
698 {									\
699 	return _handler(sh, argc, argv,					\
700 			(void *)GET_ARG_N(2, __DEBRACKET _data));	\
701 }
702 
703 /* Internal macro used for creating dictionary commands. */
704 #define SHELL_CMD_DICT_CREATE(_data, _handler)				\
705 	SHELL_CMD_ARG(GET_ARG_N(1, __DEBRACKET _data), NULL, GET_ARG_N(3, __DEBRACKET _data),	\
706 		UTIL_CAT(UTIL_CAT(cmd_dict_, UTIL_CAT(_handler, _)),	\
707 			GET_ARG_N(1, __DEBRACKET _data)), 1, 0)
708 
709 /**
710  * @brief Initializes shell dictionary commands.
711  *
712  * This is a special kind of static commands. Dictionary commands can be used
713  * every time you want to use a pair: (string <-> corresponding data) in
714  * a command handler. The string is usually a verbal description of a given
715  * data. The idea is to use the string as a command syntax that can be prompted
716  * by the shell and corresponding data can be used to process the command.
717  *
718  * @param[in] _name	Name of the dictionary subcommand set
719  * @param[in] _handler	Command handler common for all dictionary commands.
720  *			@see shell_dict_cmd_handler
721  * @param[in] ...	Dictionary triplets: (command_syntax, value, helper). Value will be
722  *			passed to the _handler as user data.
723  *
724  * Example usage:
725  * @code{.c}
726  *	static int my_handler(const struct shell *sh,
727  *			      size_t argc, char **argv, void *data)
728  *	{
729  *		int val = (int)data;
730  *
731  *		shell_print(sh, "(syntax, value) : (%s, %d)", argv[0], val);
732  *		return 0;
733  *	}
734  *
735  *	SHELL_SUBCMD_DICT_SET_CREATE(sub_dict_cmds, my_handler,
736  *		(value_0, 0, "value 0"), (value_1, 1, "value 1"),
737  *		(value_2, 2, "value 2"), (value_3, 3, "value 3")
738  *	);
739  *	SHELL_CMD_REGISTER(dictionary, &sub_dict_cmds, NULL, NULL);
740  * @endcode
741  */
742 #define SHELL_SUBCMD_DICT_SET_CREATE(_name, _handler, ...)		\
743 	FOR_EACH_FIXED_ARG(Z_SHELL_CMD_DICT_HANDLER_CREATE, (),		\
744 			   _handler, __VA_ARGS__)			\
745 	SHELL_STATIC_SUBCMD_SET_CREATE(_name,				\
746 		FOR_EACH_FIXED_ARG(SHELL_CMD_DICT_CREATE, (,), _handler, __VA_ARGS__),	\
747 		SHELL_SUBCMD_SET_END					\
748 	)
749 
750 /**
751  * @internal @brief Internal shell state in response to data received from the
752  * terminal.
753  */
754 enum shell_receive_state {
755 	SHELL_RECEIVE_DEFAULT,
756 	SHELL_RECEIVE_ESC,
757 	SHELL_RECEIVE_ESC_SEQ,
758 	SHELL_RECEIVE_TILDE_EXP
759 };
760 
761 /**
762  * @internal @brief Internal shell state.
763  */
764 enum shell_state {
765 	SHELL_STATE_UNINITIALIZED,
766 	SHELL_STATE_INITIALIZED,
767 	SHELL_STATE_ACTIVE,
768 	SHELL_STATE_PANIC_MODE_ACTIVE,  /*!< Panic activated.*/
769 	SHELL_STATE_PANIC_MODE_INACTIVE /*!< Panic requested, not supported.*/
770 };
771 
772 /** @brief Shell transport event. */
773 enum shell_transport_evt {
774 	SHELL_TRANSPORT_EVT_RX_RDY,
775 	SHELL_TRANSPORT_EVT_TX_RDY
776 };
777 
778 typedef void (*shell_transport_handler_t)(enum shell_transport_evt evt,
779 					  void *context);
780 
781 
782 typedef void (*shell_uninit_cb_t)(const struct shell *sh, int res);
783 
784 /** @brief Bypass callback.
785  *
786  * @param sh Shell instance.
787  * @param data  Raw data from transport.
788  * @param len   Data length.
789  */
790 typedef void (*shell_bypass_cb_t)(const struct shell *sh,
791 				  uint8_t *data,
792 				  size_t len,
793 				  void *user_data);
794 
795 struct shell_transport;
796 
797 /**
798  * @struct shell_transport_api
799  * @brief Unified shell transport interface.
800  */
801 struct shell_transport_api {
802 	/**
803 	 * @brief Function for initializing the shell transport interface.
804 	 *
805 	 * @param[in] transport   Pointer to the transfer instance.
806 	 * @param[in] config      Pointer to instance configuration.
807 	 * @param[in] evt_handler Event handler.
808 	 * @param[in] context     Pointer to the context passed to event
809 	 *			  handler.
810 	 *
811 	 * @return Standard error code.
812 	 */
813 	int (*init)(const struct shell_transport *transport,
814 		    const void *config,
815 		    shell_transport_handler_t evt_handler,
816 		    void *context);
817 
818 	/**
819 	 * @brief Function for uninitializing the shell transport interface.
820 	 *
821 	 * @param[in] transport  Pointer to the transfer instance.
822 	 *
823 	 * @return Standard error code.
824 	 */
825 	int (*uninit)(const struct shell_transport *transport);
826 
827 	/**
828 	 * @brief Function for enabling transport in given TX mode.
829 	 *
830 	 * Function can be used to reconfigure TX to work in blocking mode.
831 	 *
832 	 * @param transport   Pointer to the transfer instance.
833 	 * @param blocking_tx If true, the transport TX is enabled in blocking
834 	 *		      mode.
835 	 *
836 	 * @return NRF_SUCCESS on successful enabling, error otherwise (also if
837 	 * not supported).
838 	 */
839 	int (*enable)(const struct shell_transport *transport,
840 		      bool blocking_tx);
841 
842 	/**
843 	 * @brief Function for writing data to the transport interface.
844 	 *
845 	 * @param[in]  transport  Pointer to the transfer instance.
846 	 * @param[in]  data       Pointer to the source buffer.
847 	 * @param[in]  length     Source buffer length.
848 	 * @param[out] cnt        Pointer to the sent bytes counter.
849 	 *
850 	 * @return Standard error code.
851 	 */
852 	int (*write)(const struct shell_transport *transport,
853 		     const void *data, size_t length, size_t *cnt);
854 
855 	/**
856 	 * @brief Function for reading data from the transport interface.
857 	 *
858 	 * @param[in]  transport    Pointer to the transfer instance.
859 	 * @param[in]  data         Pointer to the destination buffer.
860 	 * @param[in]  length       Destination buffer length.
861 	 * @param[out] cnt          Pointer to the received bytes counter.
862 	 *
863 	 * @return Standard error code.
864 	 */
865 	int (*read)(const struct shell_transport *transport,
866 		    void *data, size_t length, size_t *cnt);
867 
868 	/**
869 	 * @brief Function called in shell thread loop.
870 	 *
871 	 * Can be used for backend operations that require longer execution time
872 	 *
873 	 * @param[in] transport Pointer to the transfer instance.
874 	 */
875 	void (*update)(const struct shell_transport *transport);
876 
877 };
878 
879 struct shell_transport {
880 	const struct shell_transport_api *api;
881 	void *ctx;
882 };
883 
884 /**
885  * @brief Shell statistics structure.
886  */
887 struct shell_stats {
888 	atomic_t log_lost_cnt; /*!< Lost log counter.*/
889 };
890 
891 #ifdef CONFIG_SHELL_STATS
892 #define Z_SHELL_STATS_DEFINE(_name) static struct shell_stats _name##_stats
893 #define Z_SHELL_STATS_PTR(_name) (&(_name##_stats))
894 #else
895 #define Z_SHELL_STATS_DEFINE(_name)
896 #define Z_SHELL_STATS_PTR(_name) NULL
897 #endif /* CONFIG_SHELL_STATS */
898 
899 /**
900  * @internal @brief Flags for shell backend configuration.
901  */
902 struct shell_backend_config_flags {
903 	uint32_t insert_mode :1; /*!< Controls insert mode for text introduction */
904 	uint32_t echo        :1; /*!< Controls shell echo */
905 	uint32_t obscure     :1; /*!< If echo on, print asterisk instead */
906 	uint32_t mode_delete :1; /*!< Operation mode of backspace key */
907 	uint32_t use_colors  :1; /*!< Controls colored syntax */
908 	uint32_t use_vt100   :1; /*!< Controls VT100 commands usage in shell */
909 };
910 
911 BUILD_ASSERT((sizeof(struct shell_backend_config_flags) == sizeof(uint32_t)),
912 	     "Structure must fit in 4 bytes");
913 
914 /**
915  * @internal @brief Default backend configuration.
916  */
917 #define SHELL_DEFAULT_BACKEND_CONFIG_FLAGS				\
918 {									\
919 	.insert_mode	= 0,						\
920 	.echo		= 1,						\
921 	.obscure	= IS_ENABLED(CONFIG_SHELL_START_OBSCURED),	\
922 	.mode_delete	= 1,						\
923 	.use_colors	= 1,						\
924 	.use_vt100	= 1,						\
925 };
926 
927 struct shell_backend_ctx_flags {
928 	uint32_t processing   :1; /*!< Shell is executing process function */
929 	uint32_t tx_rdy       :1;
930 	uint32_t history_exit :1; /*!< Request to exit history mode */
931 	uint32_t last_nl      :8; /*!< Last received new line character */
932 	uint32_t cmd_ctx      :1; /*!< Shell is executing command */
933 	uint32_t print_noinit :1; /*!< Print request from not initialized shell */
934 	uint32_t sync_mode    :1; /*!< Shell in synchronous mode */
935 	uint32_t handle_log   :1; /*!< Shell is handling logger backend */
936 };
937 
938 BUILD_ASSERT((sizeof(struct shell_backend_ctx_flags) == sizeof(uint32_t)),
939 	     "Structure must fit in 4 bytes");
940 
941 /**
942  * @internal @brief Union for internal shell usage.
943  */
944 union shell_backend_cfg {
945 	atomic_t value;
946 	struct shell_backend_config_flags flags;
947 };
948 
949 /**
950  * @internal @brief Union for internal shell usage.
951  */
952 union shell_backend_ctx {
953 	uint32_t value;
954 	struct shell_backend_ctx_flags flags;
955 };
956 
957 enum shell_signal {
958 	SHELL_SIGNAL_RXRDY = BIT(0),
959 	SHELL_SIGNAL_LOG_MSG = BIT(1),
960 	SHELL_SIGNAL_KILL = BIT(2),
961 	SHELL_SIGNAL_TXDONE = BIT(3),
962 };
963 
964 /**
965  * @brief Shell instance context.
966  */
967 struct shell_ctx {
968 #if defined(CONFIG_SHELL_PROMPT_CHANGE) && CONFIG_SHELL_PROMPT_CHANGE
969 	char prompt[CONFIG_SHELL_PROMPT_BUFF_SIZE]; /*!< shell current prompt. */
970 #else
971 	const char *prompt;
972 #endif
973 
974 	enum shell_state state; /*!< Internal module state.*/
975 	enum shell_receive_state receive_state;/*!< Escape sequence indicator.*/
976 
977 	/** Currently executed command.*/
978 	struct shell_static_entry active_cmd;
979 
980 	/** New root command. If NULL shell uses default root commands. */
981 	const struct shell_static_entry *selected_cmd;
982 
983 	/** VT100 color and cursor position, terminal width.*/
984 	struct shell_vt100_ctx vt100_ctx;
985 
986 	/** Callback called from shell thread context when unitialization is
987 	 * completed just before aborting shell thread.
988 	 */
989 	shell_uninit_cb_t uninit_cb;
990 
991 	/** When bypass is set, all incoming data is passed to the callback. */
992 	shell_bypass_cb_t bypass;
993 
994 	/** When bypass is set, this user data pointer is passed to the callback. */
995 	void *bypass_user_data;
996 
997 	/*!< Logging level for a backend. */
998 	uint32_t log_level;
999 
1000 #if defined CONFIG_SHELL_GETOPT
1001 	/*!< getopt context for a shell backend. */
1002 	struct sys_getopt_state getopt;
1003 #endif
1004 
1005 	uint16_t cmd_buff_len; /*!< Command length.*/
1006 	uint16_t cmd_buff_pos; /*!< Command buffer cursor position.*/
1007 
1008 	uint16_t cmd_tmp_buff_len; /*!< Command length in tmp buffer.*/
1009 
1010 	/** Command input buffer.*/
1011 	char cmd_buff[CONFIG_SHELL_CMD_BUFF_SIZE];
1012 
1013 	/** Command temporary buffer.*/
1014 	char temp_buff[CONFIG_SHELL_CMD_BUFF_SIZE];
1015 
1016 	/** Printf buffer size.*/
1017 	char printf_buff[CONFIG_SHELL_PRINTF_BUFF_SIZE];
1018 
1019 	volatile union shell_backend_cfg cfg;
1020 	volatile union shell_backend_ctx ctx;
1021 
1022 	struct k_event signal_event;
1023 
1024 	struct k_sem lock_sem;
1025 	k_tid_t tid;
1026 	int ret_val;
1027 };
1028 
1029 extern const struct log_backend_api log_backend_shell_api;
1030 
1031 /**
1032  * @brief Flags for setting shell output newline sequence.
1033  */
1034 enum shell_flag {
1035 	SHELL_FLAG_CRLF_DEFAULT	= (1<<0),	/*!< Do not map CR or LF */
1036 	SHELL_FLAG_OLF_CRLF	= (1<<1)	/*!< Map LF to CRLF on output */
1037 };
1038 
1039 /**
1040  * @brief Shell instance internals.
1041  */
1042 struct shell {
1043 	const char *default_prompt; /*!< shell default prompt. */
1044 
1045 	const struct shell_transport *iface; /*!< Transport interface.*/
1046 	struct shell_ctx *ctx; /*!< Internal context.*/
1047 
1048 	struct shell_history *history;
1049 
1050 	const enum shell_flag shell_flag;
1051 
1052 	const struct shell_fprintf *fprintf_ctx;
1053 
1054 	struct shell_stats *stats;
1055 
1056 	const struct shell_log_backend *log_backend;
1057 
1058 	LOG_INSTANCE_PTR_DECLARE(log);
1059 
1060 	const char *name;
1061 	struct k_thread *thread;
1062 	k_thread_stack_t *stack;
1063 };
1064 
1065 extern void z_shell_print_stream(const void *user_ctx, const char *data,
1066 				 size_t data_len);
1067 
1068 /** @brief Internal macro for defining a shell instance.
1069  *
1070  * As it does not create the default shell logging backend it allows to use
1071  * custom approach for integrating logging with shell.
1072  *
1073  * @param[in] _name		Instance name.
1074  * @param[in] _prompt		Shell default prompt string.
1075  * @param[in] _transport_iface	Pointer to the transport interface.
1076  * @param[in] _out_buf		Output buffer.
1077  * @param[in] _log_backend	Pointer to the log backend instance.
1078  * @param[in] _shell_flag	Shell output newline sequence.
1079  */
1080 #define Z_SHELL_DEFINE(_name, _prompt, _transport_iface, _out_buf, _log_backend, _shell_flag)      \
1081 	static const struct shell _name;                                                           \
1082 	static struct shell_ctx UTIL_CAT(_name, _ctx);                                             \
1083 	Z_SHELL_HISTORY_DEFINE(_name##_history, CONFIG_SHELL_HISTORY_BUFFER);                      \
1084 	Z_SHELL_FPRINTF_DEFINE(_name##_fprintf, &_name, _out_buf, CONFIG_SHELL_PRINTF_BUFF_SIZE,   \
1085 			       IS_ENABLED(CONFIG_SHELL_PRINTF_AUTOFLUSH), z_shell_print_stream);   \
1086 	LOG_INSTANCE_REGISTER(shell, _name, CONFIG_SHELL_LOG_LEVEL);                               \
1087 	Z_SHELL_STATS_DEFINE(_name);                                                               \
1088 	static K_KERNEL_STACK_DEFINE(_name##_stack, CONFIG_SHELL_STACK_SIZE);                      \
1089 	static struct k_thread _name##_thread;                                                     \
1090 	static const STRUCT_SECTION_ITERABLE(shell, _name) = {                                     \
1091 		.default_prompt = _prompt,                                                         \
1092 		.iface = _transport_iface,                                                         \
1093 		.ctx = &UTIL_CAT(_name, _ctx),                                                     \
1094 		.history = IS_ENABLED(CONFIG_SHELL_HISTORY) ? &_name##_history : NULL,             \
1095 		.shell_flag = _shell_flag,                                                         \
1096 		.fprintf_ctx = &_name##_fprintf,                                                   \
1097 		.stats = Z_SHELL_STATS_PTR(_name),                                                 \
1098 		.log_backend = _log_backend,                                                       \
1099 		LOG_INSTANCE_PTR_INIT(log, shell, _name).name =                                    \
1100 			STRINGIFY(_name), .thread = &_name##_thread, .stack = _name##_stack}
1101 
1102 /**
1103  * @brief Macro for defining a shell instance.
1104  *
1105  * @param[in] _name		Instance name.
1106  * @param[in] _prompt		Shell default prompt string.
1107  * @param[in] _transport_iface	Pointer to the transport interface.
1108  * @param[in] _log_queue_size	Logger processing queue size.
1109  * @param[in] _log_timeout	Logger thread timeout in milliseconds on full
1110  *				log queue. If queue is full logger thread is
1111  *				blocked for given amount of time before log
1112  *				message is dropped.
1113  * @param[in] _shell_flag	Shell output newline sequence.
1114  */
1115 #define SHELL_DEFINE(_name, _prompt, _transport_iface, _log_queue_size, _log_timeout, _shell_flag) \
1116 	static uint8_t _name##_out_buffer[CONFIG_SHELL_PRINTF_BUFF_SIZE];                          \
1117 	Z_SHELL_LOG_BACKEND_DEFINE(_name, _name##_out_buffer, CONFIG_SHELL_PRINTF_BUFF_SIZE,       \
1118 				   _log_queue_size, _log_timeout);                                 \
1119 	Z_SHELL_DEFINE(_name, _prompt, _transport_iface, _name##_out_buffer,                       \
1120 		       Z_SHELL_LOG_BACKEND_PTR(_name), _shell_flag)
1121 
1122 /**
1123  * @brief Function for initializing a transport layer and internal shell state.
1124  *
1125  * @param[in] sh		Pointer to shell instance.
1126  * @param[in] transport_config	Transport configuration during initialization.
1127  * @param[in] cfg_flags		Initial backend configuration flags.
1128  *				Shell will copy this data.
1129  * @param[in] log_backend	If true, the console will be used as logger
1130  *				backend.
1131  * @param[in] init_log_level	Default severity level for the logger.
1132  *
1133  * @return Standard error code.
1134  */
1135 int shell_init(const struct shell *sh, const void *transport_config,
1136 	       struct shell_backend_config_flags cfg_flags,
1137 	       bool log_backend, uint32_t init_log_level);
1138 
1139 /**
1140  * @brief Uninitializes the transport layer and the internal shell state.
1141  *
1142  * @param sh Pointer to shell instance.
1143  * @param cb Callback called when uninitialization is completed.
1144  */
1145 void shell_uninit(const struct shell *sh, shell_uninit_cb_t cb);
1146 
1147 /**
1148  * @brief Function for starting shell processing.
1149  *
1150  * @param sh Pointer to the shell instance.
1151  *
1152  * @return Standard error code.
1153  */
1154 int shell_start(const struct shell *sh);
1155 
1156 /**
1157  * @brief Function for stopping shell processing.
1158  *
1159  * @param sh Pointer to shell instance.
1160  *
1161  * @return Standard error code.
1162  */
1163 int shell_stop(const struct shell *sh);
1164 
1165 /**
1166  * @brief Terminal default text color for shell_fprintf function.
1167  */
1168 #define SHELL_NORMAL	SHELL_VT100_COLOR_DEFAULT
1169 
1170 /**
1171  * @brief Green text color for shell_fprintf function.
1172  */
1173 #define SHELL_INFO	SHELL_VT100_COLOR_GREEN
1174 
1175 /**
1176  * @brief Cyan text color for shell_fprintf function.
1177  */
1178 #define SHELL_OPTION	SHELL_VT100_COLOR_CYAN
1179 
1180 /**
1181  * @brief Yellow text color for shell_fprintf function.
1182  */
1183 #define SHELL_WARNING	SHELL_VT100_COLOR_YELLOW
1184 
1185 /**
1186  * @brief Red text color for shell_fprintf function.
1187  */
1188 #define SHELL_ERROR	SHELL_VT100_COLOR_RED
1189 
1190 /**
1191  * @brief printf-like function which sends formatted data stream to the shell.
1192  *
1193  * This function can be used from the command handler or from threads, but not
1194  * from an interrupt context.
1195  *
1196  * @param[in] sh	Pointer to the shell instance.
1197  * @param[in] color	Printed text color.
1198  * @param[in] fmt	Format string.
1199  * @param[in] ...	List of parameters to print.
1200  */
1201 void __printf_like(3, 4) shell_fprintf_impl(const struct shell *sh, enum shell_vt100_color color,
1202 					    const char *fmt, ...);
1203 
1204 #define shell_fprintf(sh, color, fmt, ...) shell_fprintf_impl(sh, color, fmt, ##__VA_ARGS__)
1205 
1206 /**
1207  * @brief vprintf-like function which sends formatted data stream to the shell.
1208  *
1209  * This function can be used from the command handler or from threads, but not
1210  * from an interrupt context. It is similar to shell_fprintf() but takes a
1211  * va_list instead of variable arguments.
1212  *
1213  * @param[in] sh	Pointer to the shell instance.
1214  * @param[in] color	Printed text color.
1215  * @param[in] fmt	Format string.
1216  * @param[in] args	List of parameters to print.
1217  */
1218 void shell_vfprintf(const struct shell *sh, enum shell_vt100_color color,
1219 		   const char *fmt, va_list args);
1220 
1221 /**
1222  * @brief Print a line of data in hexadecimal format.
1223  *
1224  * Each line shows the offset, bytes and then ASCII representation.
1225  *
1226  * For example:
1227  *
1228  * 00008010: 20 25 00 20 2f 48 00 08  80 05 00 20 af 46 00
1229  *	| %. /H.. ... .F. |
1230  *
1231  * @param[in] sh	Pointer to the shell instance.
1232  * @param[in] offset	Offset to show for this line.
1233  * @param[in] data	Pointer to data.
1234  * @param[in] len	Length of data.
1235  */
1236 void shell_hexdump_line(const struct shell *sh, unsigned int offset,
1237 			const uint8_t *data, size_t len);
1238 
1239 /**
1240  * @brief Print data in hexadecimal format.
1241  *
1242  * @param[in] sh	Pointer to the shell instance.
1243  * @param[in] data	Pointer to data.
1244  * @param[in] len	Length of data.
1245  */
1246 void shell_hexdump(const struct shell *sh, const uint8_t *data, size_t len);
1247 
1248 /**
1249  * @brief Print info message to the shell.
1250  *
1251  * See @ref shell_fprintf.
1252  *
1253  * @param[in] _sh Pointer to the shell instance.
1254  * @param[in] _ft Format string.
1255  * @param[in] ... List of parameters to print.
1256  */
1257 #define shell_info(_sh, _ft, ...) \
1258 	shell_fprintf_info(_sh, _ft "\n", ##__VA_ARGS__)
1259 void __printf_like(2, 3) shell_fprintf_info(const struct shell *sh, const char *fmt, ...);
1260 
1261 /**
1262  * @brief Print normal message to the shell.
1263  *
1264  * See @ref shell_fprintf.
1265  *
1266  * @param[in] _sh Pointer to the shell instance.
1267  * @param[in] _ft Format string.
1268  * @param[in] ... List of parameters to print.
1269  */
1270 #define shell_print(_sh, _ft, ...) \
1271 	shell_fprintf_normal(_sh, _ft "\n", ##__VA_ARGS__)
1272 void __printf_like(2, 3) shell_fprintf_normal(const struct shell *sh, const char *fmt, ...);
1273 
1274 /**
1275  * @brief Print warning message to the shell.
1276  *
1277  * See @ref shell_fprintf.
1278  *
1279  * @param[in] _sh Pointer to the shell instance.
1280  * @param[in] _ft Format string.
1281  * @param[in] ... List of parameters to print.
1282  */
1283 #define shell_warn(_sh, _ft, ...) \
1284 	shell_fprintf_warn(_sh, _ft "\n", ##__VA_ARGS__)
1285 void __printf_like(2, 3) shell_fprintf_warn(const struct shell *sh, const char *fmt, ...);
1286 
1287 /**
1288  * @brief Print error message to the shell.
1289  *
1290  * See @ref shell_fprintf.
1291  *
1292  * @param[in] _sh Pointer to the shell instance.
1293  * @param[in] _ft Format string.
1294  * @param[in] ... List of parameters to print.
1295  */
1296 #define shell_error(_sh, _ft, ...) \
1297 	shell_fprintf_error(_sh, _ft "\n", ##__VA_ARGS__)
1298 void __printf_like(2, 3) shell_fprintf_error(const struct shell *sh, const char *fmt, ...);
1299 
1300 /**
1301  * @brief Process function, which should be executed when data is ready in the
1302  *	  transport interface. To be used if shell thread is disabled.
1303  *
1304  * @param[in] sh Pointer to the shell instance.
1305  */
1306 void shell_process(const struct shell *sh);
1307 
1308 /**
1309  * @brief Change displayed shell prompt.
1310  *
1311  * @param[in] sh	Pointer to the shell instance.
1312  * @param[in] prompt	New shell prompt.
1313  *
1314  * @return 0		Success.
1315  * @return -EINVAL	Pointer to new prompt is not correct.
1316  */
1317 int shell_prompt_change(const struct shell *sh, const char *prompt);
1318 
1319 /**
1320  * @brief Prints the current command help.
1321  *
1322  * Function will print a help string with: the currently entered command
1323  * and subcommands (if they exist).
1324  *
1325  * @param[in] sh      Pointer to the shell instance.
1326  */
1327 void shell_help(const struct shell *sh);
1328 
1329 /** @brief Command's help has been printed */
1330 #define SHELL_CMD_HELP_PRINTED	(1)
1331 
1332 /** @brief Execute command.
1333  *
1334  * Pass command line to shell to execute.
1335  *
1336  * Note: This by no means makes any of the commands a stable interface, so
1337  *	 this function should only be used for debugging/diagnostic.
1338  *
1339  *	 This function must not be called from shell command context!
1340 
1341  *
1342  * @param[in] sh	Pointer to the shell instance.
1343  *			It can be NULL when the
1344  *			@kconfig{CONFIG_SHELL_BACKEND_DUMMY} option is enabled.
1345  * @param[in] cmd	Command to be executed.
1346  *
1347  * @return		Result of the execution
1348  */
1349 int shell_execute_cmd(const struct shell *sh, const char *cmd);
1350 
1351 /** @brief Set root command for all shell instances.
1352  *
1353  * It allows setting from the code the root command. It is an equivalent of
1354  * calling select command with one of the root commands as the argument
1355  * (e.g "select log") except it sets command for all shell instances.
1356  *
1357  * @param cmd String with one of the root commands or null pointer to reset.
1358  *
1359  * @retval 0 if root command is set.
1360  * @retval -EINVAL if invalid root command is provided.
1361  */
1362 int shell_set_root_cmd(const char *cmd);
1363 
1364 /** @brief Set bypass callback.
1365  *
1366  * Bypass callback is called whenever data is received. Shell is bypassed and
1367  * data is passed directly to the callback. Use null to disable bypass functionality.
1368  *
1369  * @param[in] sh	Pointer to the shell instance.
1370  * @param[in] bypass	Bypass callback or null to disable.
1371  * @param[in] user_data	Bypass callback user data.
1372  */
1373 void shell_set_bypass(const struct shell *sh, shell_bypass_cb_t bypass, void *user_data);
1374 
1375 /** @brief Get shell readiness to execute commands.
1376  *
1377  * @param[in] sh	Pointer to the shell instance.
1378  *
1379  * @retval true		Shell backend is ready to execute commands.
1380  * @retval false	Shell backend is not initialized or not started.
1381  */
1382 bool shell_ready(const struct shell *sh);
1383 
1384 /**
1385  * @brief Allow application to control text insert mode.
1386  * Value is modified atomically and the previous value is returned.
1387  *
1388  * @param[in] sh	Pointer to the shell instance.
1389  * @param[in] val	Insert mode.
1390  *
1391  * @return 0 or 1: previous value
1392  * @retval -EINVAL if shell is NULL.
1393  */
1394 int shell_insert_mode_set(const struct shell *sh, bool val);
1395 
1396 /**
1397  * @brief Allow application to control whether terminal output uses colored
1398  * syntax.
1399  * Value is modified atomically and the previous value is returned.
1400  *
1401  * @param[in] sh	Pointer to the shell instance.
1402  * @param[in] val	Color mode.
1403  *
1404  * @return 0 or 1: previous value
1405  * @retval -EINVAL if shell is NULL.
1406  */
1407 int shell_use_colors_set(const struct shell *sh, bool val);
1408 
1409 /**
1410  * @brief Allow application to control whether terminal is using vt100 commands.
1411  * Value is modified atomically and the previous value is returned.
1412  *
1413  * @param[in] sh	Pointer to the shell instance.
1414  * @param[in] val	vt100 mode.
1415  *
1416  * @return 0 or 1: previous value
1417  * @retval -EINVAL if shell is NULL.
1418  */
1419 int shell_use_vt100_set(const struct shell *sh, bool val);
1420 
1421 /**
1422  * @brief Allow application to control whether user input is echoed back.
1423  * Value is modified atomically and the previous value is returned.
1424  *
1425  * @param[in] sh	Pointer to the shell instance.
1426  * @param[in] val	Echo mode.
1427  *
1428  * @return 0 or 1: previous value
1429  * @retval -EINVAL if shell is NULL.
1430  */
1431 int shell_echo_set(const struct shell *sh, bool val);
1432 
1433 /**
1434  * @brief Allow application to control whether user input is obscured with
1435  * asterisks -- useful for implementing passwords.
1436  * Value is modified atomically and the previous value is returned.
1437  *
1438  * @param[in] sh	Pointer to the shell instance.
1439  * @param[in] obscure	Obscure mode.
1440  *
1441  * @return 0 or 1: previous value.
1442  * @retval -EINVAL if shell is NULL.
1443  */
1444 int shell_obscure_set(const struct shell *sh, bool obscure);
1445 
1446 /**
1447  * @brief Allow application to control whether the delete key backspaces or
1448  * deletes.
1449  * Value is modified atomically and the previous value is returned.
1450  *
1451  * @param[in] sh	Pointer to the shell instance.
1452  * @param[in] val	Delete mode.
1453  *
1454  * @return 0 or 1: previous value
1455  * @retval -EINVAL if shell is NULL.
1456  */
1457 int shell_mode_delete_set(const struct shell *sh, bool val);
1458 
1459 /**
1460  * @brief Retrieve return value of most recently executed shell command.
1461  *
1462  * @param[in] sh Pointer to the shell instance
1463  *
1464  * @return return value of previous command
1465  */
1466 int shell_get_return_value(const struct shell *sh);
1467 
1468 /**
1469  * @}
1470  */
1471 
1472 #ifdef __cplusplus
1473 }
1474 #endif
1475 
1476 #ifdef CONFIG_SHELL_CUSTOM_HEADER
1477 /* This include must always be at the end of shell.h */
1478 #include <zephyr_custom_shell.h>
1479 #endif
1480 
1481 #endif /* SHELL_H__ */
1482