Simple embedded shell with runtime pluggable commands.

Dependents:   DataBus2018

Implements a simple unix-like shell for embedded systems with a pluggable command architecture.

SimpleShell.cpp

Committer:
shimniok
Date:
2018-12-02
Revision:
4:8b8fa59d0015
Parent:
3:ebb4893f033d
Child:
5:8f486f4d29d3

File content as of revision 4:8b8fa59d0015:

#include "SimpleShell.h"

SimpleShell::SimpleShell()
{
    lookupEnd = 0;
}

void SimpleShell::run()
{
    bool done=false;
    Callback<void()> cb;
    
    strcpy(_cwd, "/log");

    printf("Type help for assistance.\n");
    while (!done) {
        printPrompt();
        readCommand();
        if (cb = findCommand()) {
            printf("found\n");
            //  status = cb.call();
            //  done = status == EXIT
        } else {
            printf("command not found\n");
        }
    }
    puts("exiting shell\n");

    return;
}


void SimpleShell::attach(Callback<void()> cb, char *command) 
{  
    if (lookupEnd < MAXLOOKUP) {
        lookup[lookupEnd].cb = cb;
        lookup[lookupEnd].command = command;
        lookupEnd++;
    }
    
    for (int i=0; i < lookupEnd; i++) {
        printf("%s\n", lookup[i].command);
    }
        
    return;
}


Callback<void()> SimpleShell::findCommand()
{
    Callback<void()> cb=NULL;
    
    for (int i=0; i < lookupEnd; i++) {
        if (strncmp(cmd, lookup[i].command, MAXBUF) == 0) {
            cb = lookup[i].cb;
            break;
        }
    }
    
    return cb;
}


void SimpleShell::printPrompt()
{
    fputc('(', stdout);
    fputs(_cwd, stdout);
    fputs(")# ", stdout);
    
    return;
}


void SimpleShell::readCommand()
{
    int i=0;
    char c;
    bool done = false;
    
    memset(cmd, 0, MAXBUF);
    do {
        cmd[i] = 0;
        c = fgetc(stdin);
        if (c == '\r') { // if return is hit, we're done, don't add \r to cmd
            done = true;
        } else if (i < MAXBUF-1) {
            if (c == 0x7f || c == '\b') { // backspace or delete
                if (i > 0) { // if we're at the beginning, do nothing
                    i--;
                    fputs("\b \b", stdout);

                }
            } else {
                fputc(c, stdout);
                cmd[i++] = c;
            }
        }
    } while (!done);
    fputc('\n', stdout);

    return;
}