103 lines
2.2 KiB
C++
Raw Permalink Normal View History

2014-05-14 19:37:04 +02:00
#include "cmd.h"
#include "fatal.h"
void Cmd::registerYourself(CmdServer *cmdServer) {
if (cmdServer) {
cmdServer->registerCmd(this);
}
}
CmdServer::CmdServer(uint16_t port) :
m_server(port), m_client(255), cmd(""), params(""), cmdListIdx(0)
{
}
void CmdServer::begin() {
m_server.begin();
}
void CmdServer::exec() {
static uint8_t state = 0;
bool done = false;
m_client = m_server.available();
if (m_client) {
int chi;
while ((chi = m_client.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) {
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_client.println("cmd: " + cmd);
//m_client.println("params: " + params);
if (cmd.equalsIgnoreCase("quit")) {
m_client.println("good bye");
m_client.flush();
m_client.stop();
} else if (cmd.equalsIgnoreCase("help")) {
for (uint8_t i = 0; i < cmdListIdx; i++) {
Cmd *c = cmdList[i];
m_client.println(c->getCmdName() + " " + c->getHelp());
}
m_client.println("HELP help");
m_client.println("QUIT quit");
} else {
// m_client.print("cmdListIdx: "); m_client.println(cmdListIdx);
bool found = false;
for (uint8_t i = 0; i < cmdListIdx; i++) {
// m_client.println("Check: " + cmdList[i]->getCmdName());
if (cmdList[i]->getCmdName().equalsIgnoreCase(cmd)) {
found = true;
// m_client.println("cmd found");
cmdList[i]->setClient(&m_client);
cmdList[i]->setServer(&m_server);
String res = cmdList[i]->exec(params);
m_client.println(res);
break;
}
}
if (! found)
m_client.println("command not found");
}
}