1.. _shell_api:
2
3Shell
4######
5
6.. contents::
7    :local:
8    :depth: 2
9
10Overview
11********
12
13This module allows you to create and handle a shell with a user-defined command
14set. You can use it in examples where more than simple button or LED user
15interaction is required. This module is a Unix-like shell with these features:
16
17* Support for multiple instances.
18* Advanced cooperation with the :ref:`logging_api`.
19* Support for static and dynamic commands.
20* Support for dictionary commands.
21* Smart command completion with the :kbd:`Tab` key.
22* Built-in commands: :command:`clear`, :command:`shell`, :command:`colors`,
23  :command:`echo`, :command:`history` and :command:`resize`.
24* Viewing recently executed commands using keys: :kbd:`↑` :kbd:`↓` or meta keys.
25* Text edition using keys: :kbd:`←`, :kbd:`→`, :kbd:`Backspace`,
26  :kbd:`Delete`, :kbd:`End`, :kbd:`Home`, :kbd:`Insert`.
27* Support for ANSI escape codes: ``VT100`` and ``ESC[n~`` for cursor control
28  and color printing.
29* Support for editing multiline commands.
30* Built-in handler to display help for the commands.
31* Support for wildcards: ``*`` and ``?``.
32* Support for meta keys.
33* Support for getopt and getopt_long.
34* Kconfig configuration to optimize memory usage.
35
36.. note::
37	Some of these features have a significant impact on RAM and flash usage,
38	but many can be disabled when not needed.  To default to options which
39	favor reduced RAM and flash requirements instead of features, you should
40	enable :kconfig:option:`CONFIG_SHELL_MINIMAL` and selectively enable just the
41	features you want.
42
43.. _backends:
44
45Backends
46********
47
48The module can be connected to any transport for command input and output.
49At this point, the following transport layers are implemented:
50
51* MQTT
52* Segger RTT
53* SMP
54* Telnet
55* UART
56* USB
57* Bluetooth LE (NUS)
58* RPMSG
59* DUMMY - not a physical transport layer.
60
61Telnet
62======
63
64Enabling :kconfig:option:`CONFIG_SHELL_BACKEND_TELNET` will allow users to use telnet
65as a shell backend. Connecting to it can be done using PuTTY or any ``telnet`` client.
66For example:
67
68.. code-block:: none
69
70  telnet <ip address> <port>
71
72By default the telnet client won't handle telnet commands and configuration. Although
73command support can be enabled with :kconfig:option:`CONFIG_SHELL_TELNET_SUPPORT_COMMAND`.
74This will give the telnet client access to a very limited set of supported commands but
75still can be turned on if needed. One of the command options it supports is the ``ECHO``
76option. This will allow the client to be in character mode (character at a time),
77similar to a UART backend in that regard. This will make the client send a character
78as soon as it is typed having the effect of increasing the network traffic
79considerably. For that cost, it will enable the line editing,
80`tab completion <tab-feature_>`_, and `history <history-feature_>`_
81features of the shell.
82
83USB CDC ACM
84===========
85
86To configure Shell USB CDC ACM backend, simply add the snippet ``cdc-acm-console``
87to your build:
88
89.. code-block:: console
90
91   west build -S cdc-acm-console [...]
92
93Details on the configuration settings are captured in the following files:
94
95- :zephyr_file:`snippets/cdc-acm-console/cdc-acm-console.conf`.
96- :zephyr_file:`snippets/cdc-acm-console/cdc-acm-console.overlay`.
97
98Bluetooth LE (NUS)
99==================
100
101To configure Bluetooth LE (NUS) backend, simply add the snippet ``nus-console``
102to your build:
103
104.. code-block:: console
105
106   west build -S nus-console [...]
107
108Details on the configuration settings are captured in the following files:
109
110- :zephyr_file:`snippets/nus-console/nus-console.conf`.
111- :zephyr_file:`snippets/nus-console/nus-console.overlay`.
112
113Segger RTT
114==========
115
116To configure Segger RTT backend, add the following configurations to your build:
117
118- :kconfig:option:`CONFIG_USE_SEGGER_RTT`
119- :kconfig:option:`CONFIG_SHELL_BACKEND_RTT`
120- :kconfig:option:`CONFIG_SHELL_BACKEND_SERIAL`
121
122Details on additional configuration settings are captured in:
123:zephyr_file:`samples/subsys/shell/shell_module/prj_minimal_rtt.conf`.
124
125.. _shell_rtt_west:
126
127Using west
128-----------
129
130Attach to and configure RTT with:
131
132.. code-block:: console
133
134   $ west rtt
135
136.. note::
137
138   If your default runner does not have support for RTT, check your board's documentation page for
139   any other runners that support RTT. You may then use the ``--runner`` option to specify a
140   different runner.
141
142  .. code-block:: console
143
144     $ west rtt --runner <runner>
145
146.. _shell_rtt_putty:
147
148Using PuTTY
149-----------
150
151Use following procedure:
152
153* Open debug session and continue running the application.
154
155  .. code-block:: none
156
157     west attach
158
159* Open ``PuTTY``. Use telnet port 19021 and specific Terminal configuration. Set ``Local echo``
160  to ``Force off`` and ``Local line editing`` to ``Force off`` (see image below).
161
162
163.. image:: images/putty_rtt.png
164      :align: center
165      :alt: RTT PuTTY terminal configuration.
166
167* Now you should have a network connection to RTT that will let you enter input
168  to the shell.
169
170Connecting to Segger RTT via TCP (on macOS, for example)
171--------------------------------------------------------
172
173On macOS JLinkRTTClient won't let you enter input. Instead, please use following
174procedure:
175
176* Open up a first Terminal window and enter:
177
178  .. code-block:: none
179
180     JLinkRTTLogger -Device NRF52840_XXAA -RTTChannel 1 -if SWD -Speed 4000 ~/rtt.log
181
182  (change device if required)
183
184* Open up a second Terminal window and enter:
185
186  .. code-block:: none
187
188     nc localhost 19021
189
190* Now you should have a network connection to RTT that will let you enter input
191  to the shell. However, contrary to `PuTTY <shell_rtt_putty_>`_ some features like
192  ``Tab`` completion do not work.
193
194
195Commands
196********
197
198Shell commands are organized in a tree structure and grouped into the following
199types:
200
201* Root command (level 0): Gathered and alphabetically sorted in a dedicated
202  memory section.
203* Static subcommand (level > 0): Number and syntax must be known during compile
204  time. Created in the software module.
205* Dynamic subcommand (level > 0): Number and syntax does not need to be known
206  during compile time. Created in the software module.
207
208
209Commonly-used command groups
210============================
211
212The following list is a set of useful command groups and how to enable them:
213
214GPIO
215----
216
217- :kconfig:option:`CONFIG_GPIO`
218- :kconfig:option:`CONFIG_GPIO_SHELL`
219
220I2C
221---
222
223- :kconfig:option:`CONFIG_I2C`
224- :kconfig:option:`CONFIG_I2C_SHELL`
225
226Sensor
227------
228
229- :kconfig:option:`CONFIG_SENSOR`
230- :kconfig:option:`CONFIG_SENSOR_SHELL`
231
232Flash
233-----
234
235- :kconfig:option:`CONFIG_FLASH`
236- :kconfig:option:`CONFIG_FLASH_SHELL`
237
238File-System
239-----------
240
241- :kconfig:option:`CONFIG_FILE_SYSTEM`
242- :kconfig:option:`CONFIG_FILE_SYSTEM_SHELL`
243
244Creating commands
245=================
246
247Use the following macros for adding shell commands:
248
249* :c:macro:`SHELL_CMD_REGISTER` - Create root command. All root commands must
250  have different name.
251* :c:macro:`SHELL_COND_CMD_REGISTER` - Conditionally (if compile time flag is
252  set) create root command. All root commands must have different name.
253* :c:macro:`SHELL_CMD_ARG_REGISTER` - Create root command with arguments.
254  All root commands must have different name.
255* :c:macro:`SHELL_COND_CMD_ARG_REGISTER` - Conditionally (if compile time flag
256  is set) create root command with arguments. All root commands must have
257  different name.
258* :c:macro:`SHELL_CMD` - Initialize a command.
259* :c:macro:`SHELL_COND_CMD` - Initialize a command if compile time flag is set.
260* :c:macro:`SHELL_EXPR_CMD` - Initialize a command if compile time expression is
261  non-zero.
262* :c:macro:`SHELL_CMD_ARG` - Initialize a command with arguments.
263* :c:macro:`SHELL_COND_CMD_ARG` - Initialize a command with arguments if compile
264  time flag is set.
265* :c:macro:`SHELL_EXPR_CMD_ARG` - Initialize a command with arguments if compile
266  time expression is non-zero.
267* :c:macro:`SHELL_STATIC_SUBCMD_SET_CREATE` - Create a static subcommands
268  array.
269* :c:macro:`SHELL_SUBCMD_DICT_SET_CREATE` - Create a dictionary subcommands
270  array.
271* :c:macro:`SHELL_DYNAMIC_CMD_CREATE` - Create a dynamic subcommands array.
272
273Commands can be created in any file in the system that includes
274:zephyr_file:`include/zephyr/shell/shell.h`. All created commands are available for all
275shell instances.
276
277Static commands
278---------------
279
280Example code demonstrating how to create a root command with static
281subcommands.
282
283.. image:: images/static_cmd.PNG
284      :align: center
285      :alt: Command tree with static commands.
286
287.. code-block:: c
288
289	/* Creating subcommands (level 1 command) array for command "demo". */
290	SHELL_STATIC_SUBCMD_SET_CREATE(sub_demo,
291		SHELL_CMD(params, NULL, "Print params command.",
292						       cmd_demo_params),
293		SHELL_CMD(ping,   NULL, "Ping command.", cmd_demo_ping),
294		SHELL_SUBCMD_SET_END
295	);
296	/* Creating root (level 0) command "demo" */
297	SHELL_CMD_REGISTER(demo, &sub_demo, "Demo commands", NULL);
298
299Example implementation can be found under following location:
300:zephyr_file:`samples/subsys/shell/shell_module/src/main.c`.
301
302Dictionary commands
303===================
304This is a special kind of static commands. Dictionary commands can be used
305every time you want to use a pair: (string <-> corresponding data) in
306a command handler. The string is usually a verbal description of a given data.
307The idea is to use the string as a command syntax that can be prompted by the
308shell and corresponding data can be used to process the command.
309
310Let's use an example. Suppose you created a command to set an ADC gain.
311It is a perfect place where a dictionary can be used. The dictionary would
312be a set of pairs: (string: gain_value, int: value) where int value could
313be used with the ADC driver API.
314
315Abstract code for this task would look like this:
316
317.. code-block:: c
318
319	static int gain_cmd_handler(const struct shell *sh,
320				    size_t argc, char **argv, void *data)
321	{
322		int gain;
323
324		/* data is a value corresponding to called command syntax */
325		gain = (int)data;
326		adc_set_gain(gain);
327
328		shell_print(sh, "ADC gain set to: %s\n"
329				   "Value send to ADC driver: %d",
330				   argv[0],
331				   gain);
332
333		return 0;
334	}
335
336	SHELL_SUBCMD_DICT_SET_CREATE(sub_gain, gain_cmd_handler,
337		(gain_1, 1, "gain 1"), (gain_2, 2, "gain 2"),
338		(gain_1_2, 3, "gain 1/2"), (gain_1_4, 4, "gain 1/4")
339	);
340	SHELL_CMD_REGISTER(gain, &sub_gain, "Set ADC gain", NULL);
341
342
343This is how it would look like in the shell:
344
345.. image:: images/dict_cmd.png
346      :align: center
347      :alt: Dictionary commands example.
348
349Dynamic commands
350----------------
351
352Example code demonstrating how to create a root command with static and dynamic
353subcommands. At the beginning dynamic command list is empty. New commands
354can be added by typing:
355
356.. code-block:: none
357
358	dynamic add <new_dynamic_command>
359
360Newly added commands can be prompted or autocompleted with the :kbd:`Tab` key.
361
362.. image:: images/dynamic_cmd.PNG
363      :align: center
364      :alt: Command tree with static and dynamic commands.
365
366.. code-block:: c
367
368	/* Buffer for 10 dynamic commands */
369	static char dynamic_cmd_buffer[10][50];
370
371	/* commands counter */
372	static uint8_t dynamic_cmd_cnt;
373
374	/* Function returning command dynamically created
375	 * in  dynamic_cmd_buffer.
376	 */
377	static void dynamic_cmd_get(size_t idx,
378				    struct shell_static_entry *entry)
379	{
380		if (idx < dynamic_cmd_cnt) {
381			entry->syntax = dynamic_cmd_buffer[idx];
382			entry->handler  = NULL;
383			entry->subcmd = NULL;
384			entry->help = "Show dynamic command name.";
385		} else {
386			/* if there are no more dynamic commands available
387			 * syntax must be set to NULL.
388			 */
389			entry->syntax = NULL;
390		}
391	}
392
393	SHELL_DYNAMIC_CMD_CREATE(m_sub_dynamic_set, dynamic_cmd_get);
394	SHELL_STATIC_SUBCMD_SET_CREATE(m_sub_dynamic,
395		SHELL_CMD(add, NULL,"Add new command to dynamic_cmd_buffer and"
396			  " sort them alphabetically.",
397			  cmd_dynamic_add),
398		SHELL_CMD(execute, &m_sub_dynamic_set,
399			  "Execute a command.", cmd_dynamic_execute),
400		SHELL_CMD(remove, &m_sub_dynamic_set,
401			  "Remove a command from dynamic_cmd_buffer.",
402			  cmd_dynamic_remove),
403		SHELL_CMD(show, NULL,
404			  "Show all commands in dynamic_cmd_buffer.",
405			  cmd_dynamic_show),
406		SHELL_SUBCMD_SET_END
407	);
408	SHELL_CMD_REGISTER(dynamic, &m_sub_dynamic,
409		   "Demonstrate dynamic command usage.", cmd_dynamic);
410
411Example implementation can be found under following location:
412:zephyr_file:`samples/subsys/shell/shell_module/src/dynamic_cmd.c`.
413
414Commands execution
415==================
416
417Each command or subcommand may have a handler. The shell executes the handler
418that is found deepest in the command tree and further subcommands (without a
419handler) are passed as arguments. Characters within parentheses are treated
420as one argument. If shell won't find a handler it will display an error message.
421
422Commands can be also executed from a user application using any active backend
423and a function :c:func:`shell_execute_cmd`, as shown in this example:
424
425.. code-block:: c
426
427	int main(void)
428	{
429		/* Below code will execute "clear" command on a DUMMY backend */
430		shell_execute_cmd(NULL, "clear");
431
432		/* Below code will execute "shell colors off" command on
433		 * an UART backend
434		 */
435		shell_execute_cmd(shell_backend_uart_get_ptr(),
436				  "shell colors off");
437	}
438
439Enable the DUMMY backend by setting the Kconfig
440:kconfig:option:`CONFIG_SHELL_BACKEND_DUMMY` option.
441
442Commands execution example
443--------------------------
444
445Let's assume a command structure as in the following figure, where:
446
447* :c:macro:`root_cmd` - root command without a handler
448* :c:macro:`cmd_xxx_h` - command has a handler
449* :c:macro:`cmd_xxx` - command does not have a handler
450
451.. image:: images/execution.png
452      :align: center
453      :alt: Command tree with static commands.
454
455Example 1
456^^^^^^^^^
457Sequence: :c:macro:`root_cmd` :c:macro:`cmd_1_h` :c:macro:`cmd_12_h`
458:c:macro:`cmd_121_h` :c:macro:`parameter` will execute command
459:c:macro:`cmd_121_h` and :c:macro:`parameter` will be passed as an argument.
460
461Example 2
462^^^^^^^^^
463Sequence: :c:macro:`root_cmd` :c:macro:`cmd_2` :c:macro:`cmd_22_h`
464:c:macro:`parameter1` :c:macro:`parameter2` will execute command
465:c:macro:`cmd_22_h` and :c:macro:`parameter1` :c:macro:`parameter2`
466will be passed as an arguments.
467
468Example 3
469^^^^^^^^^
470Sequence: :c:macro:`root_cmd` :c:macro:`cmd_1_h` :c:macro:`parameter1`
471:c:macro:`cmd_121_h` :c:macro:`parameter2` will execute command
472:c:macro:`cmd_1_h` and :c:macro:`parameter1`, :c:macro:`cmd_121_h` and
473:c:macro:`parameter2` will be passed as an arguments.
474
475Example 4
476^^^^^^^^^
477Sequence: :c:macro:`root_cmd` :c:macro:`parameter` :c:macro:`cmd_121_h`
478:c:macro:`parameter2` will not execute any command.
479
480
481Command handler
482----------------
483
484Simple command handler implementation:
485
486.. code-block:: c
487
488	static int cmd_handler(const struct shell *sh, size_t argc,
489				char **argv)
490	{
491		ARG_UNUSED(argc);
492		ARG_UNUSED(argv);
493
494		shell_fprintf(shell, SHELL_INFO, "Print info message\n");
495
496		shell_print(sh, "Print simple text.");
497
498		shell_warn(sh, "Print warning text.");
499
500		shell_error(sh, "Print error text.");
501
502		return 0;
503	}
504
505Function :c:func:`shell_fprintf` or the shell print macros:
506:c:macro:`shell_print`, :c:macro:`shell_info`, :c:macro:`shell_warn` and
507:c:macro:`shell_error` can be used from the command handler or from threads,
508but not from an interrupt context. Instead, interrupt handlers should use
509:ref:`logging_api` for printing.
510
511Command help
512------------
513
514Every user-defined command or subcommand can have its own help description.
515The help for commands and subcommands can be created with respective macros:
516:c:macro:`SHELL_CMD_REGISTER`, :c:macro:`SHELL_CMD_ARG_REGISTER`,
517:c:macro:`SHELL_CMD`, and :c:macro:`SHELL_CMD_ARG`.
518
519Shell prints this help message when you call a command
520or subcommand with ``-h`` or ``--help`` parameter.
521
522Parent commands
523---------------
524
525In the subcommand handler, you can access both the parameters passed to
526commands or the parent commands, depending on how you index ``argv``.
527
528* When indexing ``argv`` with positive numbers, you can access the parameters.
529* When indexing ``argv`` with negative numbers, you can access the parent
530  commands.
531* The subcommand to which the handler belongs has the ``argv`` index of 0.
532
533.. code-block:: c
534
535	static int cmd_handler(const struct shell *sh, size_t argc,
536			       char **argv)
537	{
538		ARG_UNUSED(argc);
539
540		/* If it is a subcommand handler parent command syntax
541		 * can be found using argv[-1].
542		 */
543		shell_print(sh, "This command has a parent command: %s",
544			      argv[-1]);
545
546		/* Print this command syntax */
547		shell_print(sh, "This command syntax is: %s", argv[0]);
548
549		/* Print first argument */
550		shell_print(sh, "%s", argv[1]);
551
552		return 0;
553	}
554
555Built-in commands
556=================
557
558These commands are activated by :kconfig:option:`CONFIG_SHELL_CMDS` set to ``y``.
559
560* :command:`clear` - Clears the screen.
561* :command:`history` - Shows the recently entered commands.
562* :command:`resize` - Must be executed when terminal width is different than 80
563  characters or after each change of terminal width. It ensures proper
564  multiline text display and :kbd:`←`, :kbd:`→`, :kbd:`End`, :kbd:`Home` keys
565  handling. Currently this command works only with UART flow control switched
566  on. It can be also called with a subcommand:
567
568	* :command:`default` - Shell will send terminal width = 80 to the
569	  terminal and assume successful delivery.
570
571  These command needs extra activation:
572  :kconfig:option:`CONFIG_SHELL_CMDS_RESIZE` set to ``y``.
573* :command:`select` - It can be used to set new root command. Exit to main
574  command tree is with alt+r. This command needs extra activation:
575  :kconfig:option:`CONFIG_SHELL_CMDS_SELECT` set to ``y``.
576* :command:`shell` - Root command with useful shell-related subcommands like:
577
578	* :command:`echo` - Toggles shell echo.
579        * :command:`colors` - Toggles colored syntax. This might be helpful in
580          case of Bluetooth shell to limit the amount of transferred bytes.
581	* :command:`stats` - Shows shell statistics.
582
583.. _tab-feature:
584
585Tab Feature
586***********
587
588The Tab button can be used to suggest commands or subcommands. This feature
589is enabled by :kconfig:option:`CONFIG_SHELL_TAB` set to ``y``.
590It can also be used for partial or complete auto-completion of commands.
591This feature is activated by
592:kconfig:option:`CONFIG_SHELL_TAB_AUTOCOMPLETION` set to ``y``.
593When user starts writing a command and presses the :kbd:`Tab` button then
594the shell will do one of 3 possible things:
595
596* Autocomplete the command.
597* Prompts available commands and if possible partly completes the command.
598* Will not do anything if there are no available or matching commands.
599
600.. image:: images/tab_prompt.png
601      :align: center
602      :alt: Tab Feature usage example
603
604.. _history-feature:
605
606History Feature
607***************
608
609This feature enables commands history in the shell. It is activated by:
610:kconfig:option:`CONFIG_SHELL_HISTORY` set to ``y``. History can be accessed
611using keys: :kbd:`↑` :kbd:`↓` or :kbd:`Ctrl+n` and :kbd:`Ctrl+p`
612if meta keys are active.
613Number of commands that can be stored depends on size
614of :kconfig:option:`CONFIG_SHELL_HISTORY_BUFFER` parameter.
615
616Wildcards Feature
617*****************
618
619The shell module can handle wildcards. Wildcards are interpreted correctly
620when expanded command and its subcommands do not have a handler. For example,
621if you want to set logging level to ``err`` for the ``app`` and ``app_test``
622modules you can execute the following command:
623
624.. code-block:: none
625
626	log enable err a*
627
628.. image:: images/wildcard.png
629      :align: center
630      :alt: Wildcard usage example
631
632This feature is activated by :kconfig:option:`CONFIG_SHELL_WILDCARD` set to ``y``.
633
634Meta Keys Feature
635*****************
636
637The shell module supports the following meta keys:
638
639.. list-table:: Implemented meta keys
640   :widths: 10 40
641   :header-rows: 1
642
643   * - Meta keys
644     - Action
645   * - :kbd:`Ctrl+a`
646     - Moves the cursor to the beginning of the line.
647   * - :kbd:`Ctrl+b`
648     - Moves the cursor backward one character.
649   * - :kbd:`Ctrl+c`
650     - Preserves the last command on the screen and starts a new command in
651       a new line.
652   * - :kbd:`Ctrl+d`
653     - Deletes the character under the cursor.
654   * - :kbd:`Ctrl+e`
655     - Moves the cursor to the end of the line.
656   * - :kbd:`Ctrl+f`
657     - Moves the cursor forward one character.
658   * - :kbd:`Ctrl+k`
659     - Deletes from the cursor to the end of the line.
660   * - :kbd:`Ctrl+l`
661     - Clears the screen and leaves the currently typed command at the top of
662       the screen.
663   * - :kbd:`Ctrl+n`
664     - Moves in history to next entry.
665   * - :kbd:`Ctrl+p`
666     - Moves in history to previous entry.
667   * - :kbd:`Ctrl+u`
668     - Clears the currently typed command.
669   * - :kbd:`Ctrl+w`
670     - Removes the word or part of the word to the left of the cursor. Words
671       separated by period instead of space are treated as one word.
672   * - :kbd:`Alt+b`
673     - Moves the cursor backward one word.
674   * - :kbd:`Alt+f`
675     - Moves the cursor forward one word.
676
677This feature is activated by :kconfig:option:`CONFIG_SHELL_METAKEYS` set to ``y``.
678
679Getopt Feature
680*****************
681
682Some shell users apart from subcommands might need to use options as well.
683the arguments string, looking for supported options. Typically, this task
684is accomplished by the ``getopt`` family functions.
685
686For this purpose shell supports the getopt and getopt_long libraries available
687in the FreeBSD project. This feature is activated by:
688:kconfig:option:`CONFIG_POSIX_C_LIB_EXT` set to ``y`` and :kconfig:option:`CONFIG_GETOPT_LONG`
689set to ``y``.
690
691This feature can be used in thread safe as well as non thread safe manner.
692The former is full compatible with regular getopt usage while the latter
693a bit differs.
694
695An example non-thread safe usage:
696
697.. code-block:: c
698
699  char *cvalue = NULL;
700  while ((char c = getopt(argc, argv, "abhc:")) != -1) {
701        switch (c) {
702        case 'c':
703                cvalue = optarg;
704                break;
705        default:
706                break;
707        }
708  }
709
710An example thread safe usage:
711
712.. code-block:: c
713
714  char *cvalue = NULL;
715  struct getopt_state *state;
716  while ((char c = getopt(argc, argv, "abhc:")) != -1) {
717        state = getopt_state_get();
718        switch (c) {
719        case 'c':
720                cvalue = state->optarg;
721                break;
722        default:
723                break;
724        }
725  }
726
727Thread safe getopt functionality is activated by
728:kconfig:option:`CONFIG_SHELL_GETOPT` set to ``y``.
729
730Obscured Input Feature
731**********************
732
733With the obscured input feature, the shell can be used for implementing a login
734prompt or other user interaction whereby the characters the user types should
735not be revealed on screen, such as when entering a password.
736
737Once the obscured input has been accepted, it is normally desired to return the
738shell to normal operation.  Such runtime control is possible with the
739``shell_obscure_set`` function.
740
741An example of login and logout commands using this feature is located in
742:zephyr_file:`samples/subsys/shell/shell_module/src/main.c` and the config file
743:zephyr_file:`samples/subsys/shell/shell_module/prj_login.conf`.
744
745This feature is activated upon startup by :kconfig:option:`CONFIG_SHELL_START_OBSCURED`
746set to ``y``. With this set either way, the option can still be controlled later
747at runtime. :kconfig:option:`CONFIG_SHELL_CMDS_SELECT` is useful to prevent entry
748of any other command besides a login command, by means of the
749``shell_set_root_cmd`` function. Likewise, :kconfig:option:`CONFIG_SHELL_PROMPT_UART`
750allows you to set the prompt upon startup, but it can be changed later with the
751``shell_prompt_change`` function.
752
753Shell Logger Backend Feature
754****************************
755
756Shell instance can act as the :ref:`logging_api` backend. Shell ensures that log
757messages are correctly multiplexed with shell output. Log messages from logger
758thread are enqueued and processed in the shell thread. Logger thread will block
759for configurable amount of time if queue is full, blocking logger thread context
760for that time. Oldest log message is removed from the queue after timeout and
761new message is enqueued. Use the ``shell stats show`` command to retrieve
762number of log messages dropped by the shell instance. Log queue size and timeout
763are :c:macro:`SHELL_DEFINE` arguments.
764
765This feature is activated by: :kconfig:option:`CONFIG_SHELL_LOG_BACKEND` set to ``y``.
766
767.. warning::
768	Enqueuing timeout must be set carefully when multiple backends are used
769	in the system. The shell instance could	have a slow transport or could
770	block, for example, by a UART with hardware flow control. If timeout is
771	set too high, the logger thread could be blocked and impact other logger
772	backends.
773
774.. warning::
775	As the shell is a complex logger backend, it can not output logs if
776	the application crashes before the shell thread is running. In this
777	situation, you can enable one of the simple logging backends instead,
778	such as UART (:kconfig:option:`CONFIG_LOG_BACKEND_UART`) or
779	RTT (:kconfig:option:`CONFIG_LOG_BACKEND_RTT`), which are available earlier
780	during system initialization.
781
782RTT Backend Channel Selection
783*****************************
784
785Instead of using the shell as a logger backend, RTT shell backend and RTT log
786backend can also be used simultaneously, but over different channels. By
787separating them, the log can be captured or monitored without shell output or
788the shell may be scripted without log interference. Enabling both the Shell RTT
789backend and the Log RTT backend does not work by default, because both default
790to channel ``0``. There are two options:
791
7921. The Shell buffer can use an alternate channel, for example using
793:kconfig:option:`CONFIG_SHELL_BACKEND_RTT_BUFFER` set to ``1``.
794This allows monitoring the log using `JLinkRTTViewer
795<https://www.segger.com/products/debug-probes/j-link/technology/about-real-time-transfer/#j-link-rtt-viewer>`_
796while a script interfaces over channel 1.
797
7982. The Log buffer can use an alternate channel, for example using
799:kconfig:option:`CONFIG_LOG_BACKEND_RTT_BUFFER` set to ``1``.
800This allows interactive use of the shell through JLinkRTTViewer, while the log
801is written to file.
802
803See `shell backends <backends_>`_ for details on how to enable RTT as a Shell backend.
804
805Usage
806*****
807
808The following code shows a simple use case of this library:
809
810.. code-block:: c
811
812	int main(void)
813	{
814
815	}
816
817	static int cmd_demo_ping(const struct shell *sh, size_t argc,
818				 char **argv)
819	{
820		ARG_UNUSED(argc);
821		ARG_UNUSED(argv);
822
823		shell_print(sh, "pong");
824		return 0;
825	}
826
827	static int cmd_demo_params(const struct shell *sh, size_t argc,
828				   char **argv)
829	{
830		int cnt;
831
832		shell_print(sh, "argc = %d", argc);
833		for (cnt = 0; cnt < argc; cnt++) {
834			shell_print(sh, "  argv[%d] = %s", cnt, argv[cnt]);
835		}
836		return 0;
837	}
838
839	/* Creating subcommands (level 1 command) array for command "demo". */
840	SHELL_STATIC_SUBCMD_SET_CREATE(sub_demo,
841		SHELL_CMD(params, NULL, "Print params command.",
842						       cmd_demo_params),
843		SHELL_CMD(ping,   NULL, "Ping command.", cmd_demo_ping),
844		SHELL_SUBCMD_SET_END
845	);
846	/* Creating root (level 0) command "demo" without a handler */
847	SHELL_CMD_REGISTER(demo, &sub_demo, "Demo commands", NULL);
848
849	/* Creating root (level 0) command "version" */
850	SHELL_CMD_REGISTER(version, NULL, "Show kernel version", cmd_version);
851
852
853Users may use the :kbd:`Tab` key to complete a command/subcommand or to see the
854available subcommands for the currently entered command level.
855For example, when the cursor is positioned at the beginning of the command
856line and the :kbd:`Tab` key is pressed, the user will see all root (level 0)
857commands:
858
859.. code-block:: none
860
861	  clear  demo  shell  history  log  resize  version
862
863
864.. note::
865	To view the subcommands that are available for a specific command, you
866	must first type a :kbd:`space` after this command and then hit
867	:kbd:`Tab`.
868
869These commands are registered by various modules, for example:
870
871* :command:`clear`, :command:`shell`, :command:`history`, and :command:`resize`
872  are built-in commands which have been registered by
873  :zephyr_file:`subsys/shell/shell.c`
874* :command:`demo` and :command:`version` have been registered in example code
875  above by main.c
876* :command:`log` has been registered by :zephyr_file:`subsys/logging/log_cmds.c`
877
878Then, if a user types a :command:`demo` command and presses the :kbd:`Tab` key,
879the shell will only print the subcommands registered for this command:
880
881.. code-block:: none
882
883	  params  ping
884
885API Reference
886*************
887
888.. doxygengroup:: shell_api
889