Shell 框架 API 参考

本节记录 Shell 框架 API。

Shell 核心

enum escape_state_t

Escape sequence parser states.

Values:

enumerator ESC_STATE_NORMAL

Normal input state

enumerator ESC_STATE_ESC

Received ESC (0x1B)

enumerator ESC_STATE_CSI

Received CSI (ESC [)

enumerator ESC_STATE_SS3

Received SS3 (ESC O)

enum escape_result_t

Parsed escape sequence result.

Values:

enumerator ESC_RESULT_NONE

No complete sequence yet

enumerator ESC_RESULT_UP

Up arrow

enumerator ESC_RESULT_DOWN

Down arrow

enumerator ESC_RESULT_LEFT

Left arrow

enumerator ESC_RESULT_RIGHT

Right arrow

enumerator ESC_RESULT_HOME

Home key

enumerator ESC_RESULT_END

End key

enumerator ESC_RESULT_DELETE

Delete key

enumerator ESC_RESULT_INVALID

Invalid/unknown sequence

static shell_context_t g_shell_ctx

Global shell context

static const char *const g_error_messages[] = {"Success", "Generic error", "Invalid parameter", "Shell not initialized", "Shell already initialized", "Memory allocation failed", "Item not found", "Item already exists", "No backend configured", "Buffer is full",}

Error message strings for each status code.

shell_status_t shell_init(const shell_config_t *config)

Initialize the Shell module.

参数:

config -- [in] Pointer to configuration structure

返回值:

SHELL_OK on success

返回值:

SHELL_ERROR_INVALID_PARAM if config is NULL or invalid

返回值:

SHELL_ERROR_ALREADY_INIT if already initialized

shell_status_t shell_deinit(void)

Deinitialize the Shell module.

返回值:

SHELL_OK on success

返回值:

SHELL_ERROR_NOT_INIT if not initialized

返回值:

SHELL_OK on success, error code otherwise

bool shell_is_initialized(void)

Check if Shell is initialized.

返回值:

true if initialized, false otherwise

shell_status_t shell_process(void)

Process Shell input.

注意

This function is non-blocking

返回值:

SHELL_OK on success

返回值:

SHELL_ERROR_NOT_INIT if not initialized

返回值:

SHELL_ERROR_NO_BACKEND if no backend configured

返回值:

SHELL_OK on success, error code otherwise

shell_status_t shell_get_last_error(void)

Get the last error code.

返回值:

Last error code

const char *shell_get_error_message(shell_status_t status)

Get error message string for a status code.

参数:

status -- [in] Status code to get message for

返回值:

Pointer to error message string (never NULL)

void shell_print_error(shell_status_t status)

Print error message to shell output.

参数:

status -- [in] Status code to print message for

void shell_print_error_context(shell_status_t status, const char *context)

Print error message with context.

参数:
  • status -- [in] Status code to print message for

  • context -- [in] Additional context string (can be NULL)

shell_status_t shell_recover(void)

Reset shell to a known good state after error.

返回值:

SHELL_OK on successful recovery, error code otherwise

const char *shell_get_version(void)

Get Shell version string.

返回值:

Version string (e.g., "1.0.0")

返回值:

Version string

void shell_print_prompt(void)

Print the Shell prompt.

void shell_clear_screen(void)

Clear the terminal screen.

static shell_status_t validate_config(const shell_config_t *config)

Validate shell configuration.

参数:

config -- [in] Configuration to validate

返回值:

SHELL_OK if valid, error code otherwise

static void reset_escape_state(void)

Reset escape sequence state machine.

static escape_result_t process_escape_char(uint8_t c)

Process a character in escape sequence.

参数:

c -- [in] Character to process

返回值:

Escape result (key identified or still processing)

static void handle_escape_result(escape_result_t result)

Handle escape sequence result.

参数:

result -- [in] Parsed escape sequence result

static void handle_printable_char(char c)

Handle printable character input.

参数:

c -- [in] Character to insert

static void handle_control_char(uint8_t c)

Handle control character input.

参数:

c -- [in] Control character

static void handle_tab_completion(void)

Handle Tab key for auto-completion.

static void execute_command_line(void)

Execute the current command line.

Parses and executes the command in the line editor buffer.

static void redraw_line(void)

Redraw the entire command line.

Clears the current line and redraws prompt and buffer content.

static void refresh_line_from_cursor(void)

Refresh line from cursor position to end.

Used after inserting or deleting characters.

history_manager_t *shell_get_history_manager(void)

Get the history manager.

返回值:

Pointer to history manager, or NULL if not initialized

SHELL_CONFIG_DEFAULT

Default Shell configuration.

SHELL_VERSION

Shell version string

SHELL_ESCAPE_BUFFER_SIZE

Maximum escape sequence buffer size

ANSI_CLEAR_SCREEN

ANSI escape sequences

ANSI_CURSOR_LEFT
ANSI_CURSOR_RIGHT
ANSI_ERASE_LINE
ANSI_CURSOR_SAVE
ANSI_CURSOR_RESTORE
SHELL_ERROR_MESSAGE_COUNT

Number of error messages

struct shell_config_t
#include <shell.h>

Shell configuration structure.

Public Members

const char *prompt

Prompt string (max 16 chars)

uint16_t cmd_buffer_size

Command buffer size (64-256)

uint8_t history_depth

History depth (4-32)

uint8_t max_commands

Max commands (default 32)

struct shell_context_t

Shell context structure.

Contains all state for the Shell module.

Public Members

bool initialized

Initialization flag

shell_config_t config

Configuration copy

const shell_backend_t *backend

I/O backend

line_editor_t editor

Line editor state

history_manager_t history

History manager state

char *cmd_buffer

Command buffer

char *saved_input

Saved input for history

shell_status_t last_error

Last error code

escape_state_t escape_state

Current escape state

uint8_t escape_buffer[8]
uint8_t escape_index

Escape buffer index

char **history_entries

History entry pointers

char *history_storage

History storage buffer

char prompt[SHELL_MAX_PROMPT_LEN + 1]

定义和常量

enum shell_status_t

Shell operation status codes.

Values:

enumerator SHELL_OK

Operation successful

enumerator SHELL_ERROR

Generic error

enumerator SHELL_ERROR_INVALID_PARAM

Invalid parameter

enumerator SHELL_ERROR_NOT_INIT

Module not initialized

enumerator SHELL_ERROR_ALREADY_INIT

Module already initialized

enumerator SHELL_ERROR_NO_MEMORY

Memory allocation failed

enumerator SHELL_ERROR_NOT_FOUND

Item not found

enumerator SHELL_ERROR_ALREADY_EXISTS

Item already exists

enumerator SHELL_ERROR_NO_BACKEND

No backend configured

enumerator SHELL_ERROR_BUFFER_FULL

Buffer is full

SHELL_MAX_PROMPT_LEN

Maximum prompt string length

SHELL_MIN_CMD_BUFFER_SIZE

Minimum command buffer size

SHELL_MAX_CMD_BUFFER_SIZE

Maximum command buffer size

SHELL_DEFAULT_CMD_BUFFER_SIZE

Default command buffer size

SHELL_MIN_HISTORY_DEPTH

Minimum history depth

SHELL_MAX_HISTORY_DEPTH

Maximum history depth

SHELL_DEFAULT_HISTORY_DEPTH

Default history depth

SHELL_MAX_COMMANDS

Maximum number of registered commands

SHELL_MAX_ARGS

Maximum number of arguments per command

SHELL_MAX_CMD_NAME

Maximum command name length

SHELL_MAX_COMPLETIONS

Maximum number of auto-completion matches

SHELL_DEFAULT_PROMPT

Default prompt string

命令管理

typedef int (*shell_cmd_handler_t)(int argc, char *argv[])

Command handler function type.

Param argc:

[in] Number of arguments (including command name)

Param argv:

[in] Array of argument strings

Return:

0 on success, non-zero error code on failure

typedef void (*shell_completion_cb_t)(const char *partial, char *completions[], int *count)

Command completion callback type.

Param partial:

[in] Partial argument string to complete

Param completions:

[out] Array to store completion suggestions

Param count:

[out] Pointer to store number of completions found

shell_status_t shell_register_command(const shell_command_t *cmd)

Register a command with the Shell.

参数:

cmd -- [in] Pointer to command structure (must remain valid)

返回值:

SHELL_OK on success

返回值:

SHELL_ERROR_INVALID_PARAM if cmd, name, or handler is NULL

返回值:

SHELL_ERROR_ALREADY_EXISTS if command name already registered

返回值:

SHELL_ERROR_NO_MEMORY if command registry is full

shell_status_t shell_unregister_command(const char *name)

Unregister a command from the Shell.

参数:

name -- [in] Command name to unregister

返回值:

SHELL_OK on success

返回值:

SHELL_ERROR_INVALID_PARAM if name is NULL

返回值:

SHELL_ERROR_NOT_FOUND if command not found

const shell_command_t *shell_get_command(const char *name)

Get a command by name.

参数:

name -- [in] Command name to look up

返回值:

Pointer to command structure, or NULL if not found

shell_status_t shell_get_commands(const shell_command_t **cmds[], int *count)

Get all registered commands.

参数:
  • cmds -- [out] Pointer to store command array pointer

  • count -- [out] Pointer to store number of commands

返回值:

SHELL_OK on success

int shell_get_command_count(void)

Get the number of registered commands.

返回值:

Number of currently registered commands

shell_status_t shell_set_completion_callback(shell_completion_cb_t callback)

Set global completion callback.

参数:

callback -- [in] Completion callback function

返回值:

SHELL_OK on success

shell_completion_cb_t shell_get_completion_callback(void)

Get the global completion callback.

返回值:

Current completion callback, or NULL if not set

void shell_clear_commands(void)

Clear all registered commands (for testing)

struct shell_command_t
#include <shell_command.h>

Shell command structure.

Public Members

const char *name

Command name (max 16 chars)

shell_cmd_handler_t handler

Command handler function

const char *help

Short help description

const char *usage

Usage string (e.g., "cmd [options]")

shell_completion_cb_t completion

Argument completion callback (optional)

行编辑器

void line_editor_init(line_editor_t *editor, char *buffer, uint16_t size)

Initialize line editor.

参数:
  • editor -- [inout] Pointer to line editor structure

  • buffer -- [in] Pointer to character buffer

  • size -- [in] Size of the buffer

bool line_editor_insert_char(line_editor_t *editor, char c)

Insert a character at cursor position.

参数:
  • editor -- [inout] Pointer to line editor

  • c -- [in] Character to insert

返回值:

true if character was inserted, false if buffer full

bool line_editor_delete_char(line_editor_t *editor)

Delete character at cursor position (Delete key)

参数:

editor -- [inout] Pointer to line editor

返回值:

true if character was deleted, false if at end

bool line_editor_backspace(line_editor_t *editor)

Delete character before cursor (Backspace)

参数:

editor -- [inout] Pointer to line editor

返回值:

true if character was deleted, false if at start

void line_editor_move_cursor(line_editor_t *editor, int offset)

Move cursor by offset.

参数:
  • editor -- [inout] Pointer to line editor

  • offset -- [in] Number of positions to move (can be negative)

void line_editor_move_to_start(line_editor_t *editor)

Move cursor to start of line (Home/Ctrl+A)

参数:

editor -- [inout] Pointer to line editor

void line_editor_move_to_end(line_editor_t *editor)

Move cursor to end of line (End/Ctrl+E)

参数:

editor -- [inout] Pointer to line editor

void line_editor_delete_to_end(line_editor_t *editor)

Delete from cursor to end of line (Ctrl+K)

参数:

editor -- [inout] Pointer to line editor

void line_editor_delete_to_start(line_editor_t *editor)

Delete from start to cursor (Ctrl+U)

参数:

editor -- [inout] Pointer to line editor

void line_editor_delete_word(line_editor_t *editor)

Delete word before cursor (Ctrl+W)

参数:

editor -- [inout] Pointer to line editor

void line_editor_clear(line_editor_t *editor)

Clear the entire line.

参数:

editor -- [inout] Pointer to line editor

const char *line_editor_get_buffer(const line_editor_t *editor)

Get current buffer content.

参数:

editor -- [in] Pointer to line editor

返回值:

Pointer to null-terminated buffer content

uint16_t line_editor_get_length(const line_editor_t *editor)

Get current content length.

参数:

editor -- [in] Pointer to line editor

返回值:

Current content length

uint16_t line_editor_get_cursor(const line_editor_t *editor)

Get current cursor position.

参数:

editor -- [in] Pointer to line editor

返回值:

Current cursor position

void line_editor_set_content(line_editor_t *editor, const char *content)

Set buffer content.

参数:
  • editor -- [inout] Pointer to line editor

  • content -- [in] String to set as buffer content

struct line_editor_t
#include <shell_line_editor.h>

Line editor state structure.

Public Members

char *buffer

Input buffer pointer

uint16_t buffer_size

Buffer size (capacity)

uint16_t length

Current content length

uint16_t cursor

Cursor position (0 to length)

bool insert_mode

Insert mode (true) or overwrite mode

历史

void history_init(history_manager_t *hist, char **entries, uint8_t capacity, uint16_t entry_size)

Initialize history manager.

参数:
  • hist -- [inout] Pointer to history manager structure

  • entries -- [in] Array of entry buffer pointers

  • capacity -- [in] Maximum number of history entries

  • entry_size -- [in] Maximum size of each entry (including null terminator)

void history_deinit(history_manager_t *hist)

Deinitialize history manager.

参数:

hist -- [inout] Pointer to history manager structure

bool history_add(history_manager_t *hist, const char *cmd)

Add command to history.

参数:
  • hist -- [inout] Pointer to history manager

  • cmd -- [in] Command string to add

返回值:

true if command was added, false if skipped (empty or duplicate)

const char *history_get_prev(history_manager_t *hist)

Get previous command (Up arrow)

参数:

hist -- [inout] Pointer to history manager

返回值:

Pointer to previous command, or NULL if at oldest

const char *history_get_next(history_manager_t *hist)

Get next command (Down arrow)

参数:

hist -- [inout] Pointer to history manager

返回值:

Pointer to next command, or NULL if at newest (current input)

void history_reset_browse(history_manager_t *hist)

Reset browse position.

参数:

hist -- [inout] Pointer to history manager

uint8_t history_get_count(const history_manager_t *hist)

Get current entry count.

参数:

hist -- [in] Pointer to history manager

返回值:

Number of entries in history

const char *history_get_entry(const history_manager_t *hist, uint8_t index)

Get entry at index.

参数:
  • hist -- [in] Pointer to history manager

  • index -- [in] Index of entry (0 = most recent)

返回值:

Pointer to entry, or NULL if index out of range

void history_clear(history_manager_t *hist)

Clear all history.

参数:

hist -- [inout] Pointer to history manager

bool history_is_browsing(const history_manager_t *hist)

Check if currently browsing history.

参数:

hist -- [in] Pointer to history manager

返回值:

true if browsing history, false if at current input

struct history_manager_t
#include <shell_history.h>

History manager state structure.

Public Members

char **entries

Array of history entry pointers

uint16_t entry_size

Maximum size of each entry

uint8_t capacity

Maximum number of entries

uint8_t count

Current number of entries

uint8_t head

Index of newest entry (circular buffer)

int8_t browse_index

Current browse position (-1 = current input)

自动补全

shell_status_t autocomplete_init(void)

Initialize the auto-completion module.

返回值:

SHELL_OK on success

shell_status_t autocomplete_command(const char *partial, completion_result_t *result)

Find command completions for partial input.

参数:
  • partial -- [in] Partial command name to complete

  • result -- [out] Pointer to store completion results

返回值:

SHELL_OK on success

返回值:

SHELL_ERROR_INVALID_PARAM if partial or result is NULL

void autocomplete_show_matches(const completion_result_t *result)

Show all matching completions to the user.

参数:

result -- [in] Pointer to completion results to display

int autocomplete_get_common_prefix(const completion_result_t *result, char *prefix, int prefix_size)

Get the common prefix from completion results.

参数:
  • result -- [in] Pointer to completion results

  • prefix -- [out] Buffer to store the common prefix

  • prefix_size -- [in] Size of the prefix buffer

返回值:

Length of the common prefix, or 0 if no common prefix

shell_status_t autocomplete_process(const char *input, int input_len, int cursor_pos, completion_result_t *result)

Process Tab key press for auto-completion.

参数:
  • input -- [in] Current input buffer

  • input_len -- [in] Length of current input

  • cursor_pos -- [in] Current cursor position

  • result -- [out] Pointer to store completion results

返回值:

SHELL_OK on success

返回值:

SHELL_ERROR_INVALID_PARAM if parameters are invalid

struct completion_result_t
#include <shell_autocomplete.h>

Auto-completion result structure.

Public Members

char matches[16][16 + 1]

Matching command names

int match_count

Number of matches found

int common_prefix_len

Length of common prefix

解析器

shell_status_t parse_command_line(char *line, parsed_command_t *result)

Parse a command line into command name and arguments.

注意

The line buffer is modified in place. The argv pointers point into the original line buffer.

注意

Empty lines result in argc=0 and cmd_name=NULL

注意

Unterminated quotes are handled gracefully (rest of string is argument)

参数:
  • line -- [inout] Input command line buffer (will be modified in place)

  • result -- [out] Output parsed command structure

返回值:

SHELL_OK on success

返回值:

SHELL_ERROR_INVALID_PARAM if line or result is NULL

返回值:

SHELL_ERROR_BUFFER_FULL if too many arguments (> SHELL_MAX_ARGS)

struct parsed_command_t
#include <shell_parser.h>

Parsed command structure.

Public Members

char *cmd_name

Command name (first token)

int argc

Argument count (including command name)

char *argv[8]

Argument array

后端接口

static const shell_backend_t *g_current_backend = NULL

Current backend pointer

shell_status_t shell_set_backend(const shell_backend_t *backend)

Set the Shell backend.

参数:

backend -- [in] Pointer to backend interface structure

返回值:

SHELL_OK on success, error code otherwise

const shell_backend_t *shell_get_backend(void)

Get the current Shell backend.

返回值:

Pointer to current backend, or NULL if not set

int shell_printf(const char *format, ...)

Printf-style output to Shell.

参数:
  • format -- [in] Printf-style format string

  • ... -- [in] Format arguments

返回值:

Number of characters written, or negative on error

int shell_write(const uint8_t *data, int len)

Write raw data to Shell backend.

参数:
  • data -- [in] Data buffer to write

  • len -- [in] Number of bytes to write

返回值:

Number of bytes written

int shell_putchar(char c)

Write a single character to Shell backend.

参数:

c -- [in] Character to write

返回值:

1 on success, 0 on failure

int shell_puts(const char *str)

Write a string to Shell backend.

参数:

str -- [in] Null-terminated string to write

返回值:

Number of characters written

SHELL_PRINTF_BUFFER_SIZE

Printf buffer size

struct shell_backend_t
#include <shell_backend.h>

Shell backend interface structure.

Public Members

int (*read)(uint8_t *data, int max_len)

Non-blocking read function.

Param data:

[out] Buffer to store read data

Param max_len:

[in] Maximum number of bytes to read

Return:

Number of bytes actually read, 0 if no data available

int (*write)(const uint8_t *data, int len)

Blocking write function.

Param data:

[in] Data buffer to write

Param len:

[in] Number of bytes to write

Return:

Number of bytes actually written