#include "CLI.h" #include #include #include #include #include "../FIFOBuff/FIFOBuffChar.h" CLI_charOutFn CLI_charOut; CMDList_t* CMDList; FIFOBuffChar_t* FIFO; void CLI_charOut_save(char ch) { if (CLI_charOut != NULL) { // create string of size one to be compatable with string print function char c[2] = {ch, 0}; (*CLI_charOut)(&c[0]); } } void CLI_stringOut(char* str) { for (; *str != 0; str++) { CLI_charOut_save(*str); } } // initilize and register the lineout print function bool CLI_init(CLI_charOutFn lineOut, CMDList_t* cmdList) { CLI_charOut = lineOut; CMDList = cmdList; FIFO = FIFOBuffChar_create(); if (CLI_charOut != NULL) { CLI_stringOut((char*)"> "); } return true; } bool CLI_deinit() { CLI_charOut = 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) { int ret = 0; char* line = fifoToString(fifo); CMD_t* cmd = CMDList_get(CMDList, line); if (cmd != NULL) { int ret = (*(cmd->fn))(line); if (ret != INT_MIN) { CLI_stringOut((char*)"> "); } ret = 0; } else { if (CLI_charOut != NULL) { char err[100]; sprintf(&err[0], "command not found: %s\n> ", line); CLI_stringOut(&err[0]); } ret = -1; } free(line); return ret; } // to recive a single caracter bool CLI_charIn(char c) { bool ok = true; char C = c; 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 CLI_charOut_save(c); } else { char str[100]; switch (c) { case '\n': case '\r': if (CLI_charOut != NULL) { // echo to terminal char ch[2] = {c, 0}; (*CLI_charOut)(&ch[0]); } FIFOBuffChar_t* fifo = FIFO; FIFO = FIFOBuffChar_create(); ok = (tryExecute(fifo) == 0); FIFOBuffChar_delete(fifo); break; case 127: // backspace if (FIFOBuffChar_pop(FIFO)) { // pop something of the buffer CLI_stringOut((char*)"\x1b[D \x1b[D"); // "" } break; case 27: // escape (start for arrow keys) sprintf(&str[0], "\ninvlid char: ESC - (%i)\n", c); CLI_stringOut(&str[0]); break; default: sprintf(&str[0], "\ninvlid char: '%c' - (%i)\n", c, c); CLI_stringOut(&str[0]); break; } } return ok; }