158 lines
2.6 KiB
C

#include "CLI.h"
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include "../FIFOBuff/FIFOBuffChar.h"
CLI_lineOutFn CLI_lineOut;
CMDList_t* CMDList;
FIFOBuffChar_t* FIFO;
// initilize and register the lineout print function
bool CLI_init(CLI_lineOutFn lineOut, CMDList_t* cmdList)
{
CLI_lineOut = lineOut;
CMDList = cmdList;
FIFO = FIFOBuffChar_create();
if (CLI_lineOut != NULL)
{
(*CLI_lineOut)(">");
(*CLI_lineOut)(" ");
}
return true;
}
bool CLI_deinit()
{
CLI_lineOut = NULL;
CMDList = NULL;
FIFOBuffChar_delete(FIFO);
return true;
}
char* fifoToString(FIFOBuffChar_t* fifo)
{
char* out = malloc(fifo->size + 1);
char* write_p = out;
for (int i = fifo->size; i > 0; i--)
{
FIFOBuffChar_get(fifo, write_p);
write_p++;
}
*write_p = 0;
return out;
}
int tryExecute(FIFOBuffChar_t* fifo)
{
char* line = fifoToString(fifo);
CMD_t* cmd = CMDList_get(CMDList, line);
if (cmd != NULL)
{
(*(cmd->fn))(line);
if (CLI_lineOut != NULL)
{
(*CLI_lineOut)(">");
(*CLI_lineOut)(" ");
}
return true;
}
else
{
if (CLI_lineOut != NULL)
{
char err[100];
sprintf(&err[0], "command not found: %s\n> ", line);
for (int i=0; err[i] != 0; i++)
{
char c[2] = {err[i], 0};
(*CLI_lineOut)(&c[0]);
}
}
return false;
}
}
// to recive a single caracter
bool CLI_charIn(char c)
{
bool ok = true;
if ((c >= 'a') && (c <= 'z'))
{
c &= (~0x20); // convert to uppercase
}
if ( //TODO: update list of accepted characters
((c >= 'A') && (c <= 'Z'))
|| ((c >= '0') && (c <= '9'))
|| (c == ' ')
|| (c == '-')
|| (c == '_')
)
{
FIFOBuffChar_put(FIFO, c); // save char in buffer
if (CLI_lineOut != NULL)
{ // echo to terminal
(*CLI_lineOut)(&c);
}
}
else
{
char str[100];
switch (c)
{
case '\n':
case '\r':
if (CLI_lineOut != NULL)
{ // echo to terminal
(*CLI_lineOut)(&c);
}
FIFOBuffChar_t* fifo = FIFO;
FIFO = FIFOBuffChar_create();
ok = tryExecute(fifo);
FIFOBuffChar_delete(fifo);
break;
case 127: // backspace
if (FIFOBuffChar_pop(FIFO))
{
(*CLI_lineOut)("\x1b");
(*CLI_lineOut)("[");
(*CLI_lineOut)("D");
}
break;
case 27: // escape (start for arrow keys)
sprintf(&str[0], "\ninvlid char: ESC - (%i)\n", c);
for (int i=0; str[i] != 0; i++)
{
char ch[2] = {str[i], 0};
(*CLI_lineOut)(&ch[0]);
}
break;
default:
sprintf(&str[0], "\ninvlid char: '%c' - (%i)\n", c, c);
for (int i=0; str[i] != 0; i++)
{
char ch[2] = {str[i], 0};
(*CLI_lineOut)(&ch[0]);
}
break;
}
}
return ok;
}