Skip to content

Instantly share code, notes, and snippets.

@dagon666
Created December 31, 2013 10:12
cli interpreter
#define POSINC(__x) (((__x) < (CLI_CMD_BUFFER_SIZE - 1)) ? (__x + 1) : (__x))
#define POSDEC(__x) ((__x) ? ((__x) - 1) : 0)
#define KEY_CODE_BACKSPACE 0x7f
#define KEY_CODE_DELETE 0x1b
#define KEY_CODE_ENTER 0x0a
#define CLI_IO_INPUT(__data) \
linux_getc(__data)
#define CLI_IO_OUTPUT(__data, __len) \
linux_putc(__data, __len)
static void _cli_prompt(t_cli_ctx *a_ctx __attribute__((unused)), unsigned char nl) {
if (nl) CLI_IO_OUTPUT("\r\n", 2);
CLI_IO_OUTPUT("#> ", 3);
}
void cli_read(t_cli_ctx *a_ctx) {
unsigned char i = 0x00;
// if no character available - then exit
if (!CLI_IO_INPUT(&i)) return;
/// char by char matching
switch(i) {
case KEY_CODE_BACKSPACE: // backspace
case KEY_CODE_DELETE: // del
if (a_ctx->cpos) {
a_ctx->cmd[a_ctx->cpos--] = '\0';
CLI_IO_OUTPUT("\b \b", 3);
}
break;
case KEY_CODE_ENTER: // new line
a_ctx->cmd[POSINC(a_ctx->cpos)] = '\0';
CLI_IO_OUTPUT("\r\n", 2);
a_ctx->cpos = 0;
memset(a_ctx->cmd, 0x00, CLI_CMD_BUFFER_SIZE);
_cli_prompt(a_ctx, 1);
break;
default:
/* echo */
if (a_ctx->cpos < (CLI_CMD_BUFFER_SIZE - 1) && isprint(i)) {
a_ctx->cmd[a_ctx->cpos++] = i;
CLI_IO_OUTPUT(&i, 1);
}
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment