shell: add generic RX buffer flush function
Added a generic function `z_shell_backend_rx_buffer_flush` to clear the RX buffer when resuming the shell. The function repeatedly calls the backend's `read` API until the buffer is empty or a maximum of 1000 iterations is reached. This prevents unintended command execution after `shell_start`. Signed-off-by: Jakub Rzeszutko <jakub.rzeszutko@verkada.com>
This commit is contained in:
parent
d427d8a653
commit
5bb721264b
3 changed files with 31 additions and 0 deletions
|
|
@ -1452,6 +1452,14 @@ int shell_start(const struct shell *sh)
|
|||
z_cursor_next_line_move(sh);
|
||||
state_set(sh, SHELL_STATE_ACTIVE);
|
||||
|
||||
/*
|
||||
* If the shell is stopped with the shell_stop function, its backend remains active
|
||||
* and continues to buffer incoming data. As a result, when the shell is resumed,
|
||||
* all buffered data is processed, which may lead to the execution of commands
|
||||
* received while the shell was stopped.
|
||||
*/
|
||||
z_shell_backend_rx_buffer_flush(sh);
|
||||
|
||||
k_mutex_unlock(&sh->ctx->wr_mtx);
|
||||
|
||||
return 0;
|
||||
|
|
|
|||
|
|
@ -548,3 +548,17 @@ void z_shell_fprintf(const struct shell *sh,
|
|||
z_shell_vfprintf(sh, color, fmt, args);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
void z_shell_backend_rx_buffer_flush(const struct shell *sh)
|
||||
{
|
||||
__ASSERT_NO_MSG(sh);
|
||||
|
||||
int32_t max_iterations = 1000;
|
||||
uint8_t buf[64];
|
||||
size_t count = 0;
|
||||
int err;
|
||||
|
||||
do {
|
||||
err = sh->iface->api->read(sh->iface, buf, sizeof(buf), &count);
|
||||
} while (count != 0 && err == 0 && --max_iterations > 0);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -372,6 +372,15 @@ void z_shell_fprintf(const struct shell *sh, enum shell_vt100_color color,
|
|||
void z_shell_vfprintf(const struct shell *sh, enum shell_vt100_color color,
|
||||
const char *fmt, va_list args);
|
||||
|
||||
/**
|
||||
* @brief Flushes the shell backend receive buffer.
|
||||
*
|
||||
* This function repeatedly reads from the shell interface's receive buffer
|
||||
* until it is empty or a maximum number of iterations is reached.
|
||||
* It ensures that no additional data is left in the buffer.
|
||||
*/
|
||||
void z_shell_backend_rx_buffer_flush(const struct shell *sh);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
|
|
|||
Loading…
Reference in a new issue