2024-04-08 13:39:24 +02:00

109 lines
1.7 KiB
C

#include "CLI.h"
#include <stddef.h>
#include <stdlib.h>
#include "../FIFOBuff/FIFOBuffChar.h"
void (*CLI_lineOut)(char* line);
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();
}
bool CLI_deinit()
{
CLI_lineOut = NULL;
CMDList = NULL;
FIFOBuffChar_delete(FIFO);
}
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);
return true;
}
else
{
printf("command not found: %s\n", line);
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
{
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;
//TODO: add hire backspace and arrow detection
default:
break;
}
}
return ok;
}