2014-03-08 00:23:46 +01:00

101 lines
2.1 KiB
C++

#include <HardwareSerial.h>
#include "cmd.h"
#include "fatal.h"
#include "Resources.h"
void Cmd::registerYourself(CmdServer *cmdServer) {
cmdServer->registerCmd(this);
}
CmdServer::CmdServer(Stream *p_stream) :
m_stream(p_stream), cmd(""), params(""), cmdListIdx(0)
{
}
void CmdServer::begin() {
//((Serial*)m_stream)->begin(9600);
}
void CmdServer::exec() {
static uint8_t state = 0;
bool done = false;
if (m_stream->available()) {
int chi;
while ((chi = m_stream->read()) != -1) {
char ch = (char) chi;
switch (state) {
case 0:
if ((ch != ' ') && (ch != '\n')) {
cmd += ch;
} else if (ch == '\n') {
done = true;
} else {
state = 1;
}
break;
case 1:
if (ch != '\n') {
params += ch;
} else {
done = true;
state = 0;
}
break;
}
if (done) {
m_stream->println("Cmd: " + cmd);
parseCommand();
cmd = "";
params = "";
}
}
}
}
void CmdServer::registerCmd(Cmd *cmdObj) {
if (cmdListIdx < NUM_OF_COMMANDS) {
cmdList[cmdListIdx] = cmdObj;
cmdListIdx++;
} else {
fatal(FATAL_NOT_ENOUGH_CMD_SLOTS);
}
}
void CmdServer::parseCommand() {
//m_stream->println("cmd: " + cmd);
//m_stream->println("params: " + params);
if (cmd.equalsIgnoreCase("help")) {
for (uint8_t i = 0; i < cmdListIdx; i++) {
Cmd *c = cmdList[i];
m_stream->println(c->getCmdName() + " " + c->getHelp());
}
m_stream->println(getResource(CMDSERVER_HELP_KEY));
} else {
bool found = false;
for (uint8_t i = 0; i < cmdListIdx; i++) {
//m_stream->println("Check: " + cmdList[i]->getCmdName());
if (cmdList[i]->getCmdName().equalsIgnoreCase(cmd)) {
found = true;
// m_client.println("cmd found");
cmdList[i]->setClient(m_stream);
String res = cmdList[i]->exec(params);
m_stream->println(res);
break;
}
}
if (! found)
m_stream->println(getResource(CMDSERVER_CMD_NOT_FOUND_KEY));
}
}