-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.c
78 lines (62 loc) · 1.65 KB
/
cli.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* cli.c
*
* Created: 09.11.2014 19:51:50
* Author: ole
*/
#include "cli.h"
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define MAX_CMD 16
char cmdbuf[128];
struct Command_t cmdlist[MAX_CMD];
uint8_t numcmd = 0;
bool cli_task(void)
{
// read line from uart
memset(cmdbuf, 0, 128 * sizeof(char));
fgets(cmdbuf, 127, stdin);
// parse command
int i=0;
while (i < numcmd && strncmp(cmdbuf, cmdlist[i].cmdstr, cmdlist[i].cmdstrlen)) { i++; };
if (i == numcmd) { //cmd not found
printf("Could not find command %s", cmdbuf);
printf(CLI_PROMPT);
return true;
}
cmdlist[i].cmdfunc(&cmdbuf[cmdlist[i].cmdstrlen+1]); // pass rest of string to command function
printf(CLI_PROMPT);
return true;
}
void register_cli_command(char * cmdstr, void (*cmdfunc)(char*), void (*cmdhelp)(void))
{
cmdlist[numcmd].cmdstr = cmdstr;
cmdlist[numcmd].cmdstrlen = strlen(cmdstr);
cmdlist[numcmd].cmdhelp = cmdhelp;
cmdlist[numcmd].cmdfunc = cmdfunc;
numcmd++;
}
void cmd_help(char * stropt)
{
if (*stropt == '\n' || *stropt == 0) {
printf("Available commands:\n");
for (int i=0; i<numcmd; i++) {
printf("%s\n", cmdlist[i].cmdstr);
}
printf("Type help <command> to get help for that command.\n");
return;
}
// parse stropt
int i=0;
while (i < numcmd && !strstr(stropt, cmdlist[i].cmdstr)) { i++; };
if (i == numcmd) { //cmd not found
printf("Could not find help for %s", stropt);
return;
}
cmdlist[i].cmdhelp(); // run help function for this command
}
void cmd_help_help(void)
{
cmd_help(NULL);
}