tbm-mcu/source/shell/cmd.c

69 lines
1.2 KiB
C
Raw Normal View History

2017-03-12 00:33:09 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <console.h>
2017-03-12 00:33:09 +00:00
#include <shell.h>
void cmd_exec(struct cmd *cmds, FILE *out, const char **argv, size_t argc)
2017-06-14 13:20:28 +02:00
{
struct cmd *cmd;
2017-06-14 13:20:28 +02:00
if (argc < 1)
return;
for (cmd = cmds; cmd->cmd; ++cmd) {
if (strcmp(cmd->cmd, argv[0]) == 0) {
cmd->exec(out, argv + 1, argc - 1);
break;
}
}
2017-06-14 13:20:28 +02:00
}
void cmd_parse(struct cmd *cmds, FILE *out, const char *line)
2017-03-12 00:33:09 +00:00
{
char **argv;
size_t argc;
2017-03-12 00:33:09 +00:00
if (!(argv = parse_args(line, &argc)))
return;
2017-03-12 00:33:09 +00:00
cmd_exec(cmds, out, (const char **)argv, argc);
free(argv);
2017-03-12 00:33:09 +00:00
}
int shell_init(struct shell *shell, struct cmd *cmds,
struct usart_console *con, const char *prompt)
2017-03-12 00:33:09 +00:00
{
if (!shell || !con)
return -1;
2017-03-12 00:33:09 +00:00
memset(shell->line, '\0', sizeof shell->line);
shell->cmds = cmds;
shell->con = con;
shell->fp = console_to_fp(con);
shell->prompt = prompt;
2017-03-12 00:33:09 +00:00
fprintf(shell->fp, "%s ", prompt ? prompt : "#");
2017-03-12 00:33:09 +00:00
return 0;
2017-03-12 00:33:09 +00:00
}
int shell_parse(struct shell *shell)
2017-03-12 00:33:09 +00:00
{
int ret;
2017-03-12 00:33:09 +00:00
if (!shell)
return -1;
2017-06-14 13:20:28 +02:00
if ((ret = console_getline(shell->con, shell->line, sizeof shell->line)) <
0)
return ret;
cmd_parse(shell->cmds, shell->fp, shell->line);
fprintf(shell->fp, "%s ", shell->prompt ? shell->prompt : "#");
*shell->line = '\0';
return 0;
2017-03-12 00:33:09 +00:00
}