diff --git a/CVReader.ino b/CVReader.ino index 89e6b46..9e06dc6 100644 --- a/CVReader.ino +++ b/CVReader.ino @@ -30,40 +30,14 @@ void setup() { int value=DCC::readCV(cvnums[x]); DIAG(F("\nCV %d = %d 0x%x %s"),cvnums[x],value,value, value>=0?" VERIFIED OK":"FAILED VERIFICATION"); } - DIAG(F("\n===== CVReader done ==============================\n")); - - - - DIAG(F("\nReady for JMRI\n")); + DIAG(F("\n===== CVReader done ==============================\n")); + DIAG(F("\nReady for JMRI commands\n")); } -const byte MAX_BUFFER=100; -char buffer[MAX_BUFFER]; -byte bufferLength=0; -bool inCommandPayload=false; - void loop() { - DCC::loop(); - while(Serial.available()) { - if (bufferLength==MAX_BUFFER) { - DIAG(F("\n**Buffer cleared**\n")); - bufferLength=0; - inCommandPayload=false; - } - char ch = Serial.read(); - if (ch == '<') { - inCommandPayload = true; - bufferLength=0; - buffer[0]='\0'; - } - else if (ch == '>') { - buffer[bufferLength]='\0'; - JMRIParser::parse(Serial, buffer); - inCommandPayload = false; - } else if(inCommandPayload) { - buffer[bufferLength++]= ch; - } - } - } - + DCC::loop(); // required to keep locos running and check powwer + + // This line passes input on Serial to the JMRIparser + StringParser::loop(Serial, JMRIParser::parse); +} diff --git a/StringParser.cpp b/StringParser.cpp index 62881ac..46193f5 100644 --- a/StringParser.cpp +++ b/StringParser.cpp @@ -1,6 +1,31 @@ #include "StringParser.h" #include +byte StringParser::bufferLength=0; +bool StringParser::inCommandPayload=false; +char StringParser::buffer[MAX_BUFFER]; + +void StringParser::loop(Stream & stream, void (*callback)(Stream & stream, const char * data) ) { + while(stream.available()) { + if (bufferLength==MAX_BUFFER) { + bufferLength=0; + inCommandPayload=false; + } + char ch = stream.read(); + if (ch == '<') { + inCommandPayload = true; + bufferLength=0; + buffer[0]='\0'; + } + else if (ch == '>') { + buffer[bufferLength]='\0'; + (*callback)(Serial, buffer); + inCommandPayload = false; + } else if(inCommandPayload) { + buffer[bufferLength++]= ch; + } + } + } int StringParser::parse(const char * com, int result[], byte maxResults) { byte state=1; byte parameterCount=0; diff --git a/StringParser.h b/StringParser.h index 67c9cde..e1ec581 100644 --- a/StringParser.h +++ b/StringParser.h @@ -2,10 +2,15 @@ class StringParser { public: + static void loop(Stream & stream, void (*callback)(Stream & stream, const char * data) ); static int parse(const char * com, int result[], byte maxResults); static void print( const __FlashStringHelper* input...); static void send(Stream & serial, const __FlashStringHelper* input...); private: static void send(Stream & serial, const __FlashStringHelper* input,va_list args); + static byte bufferLength; + static bool inCommandPayload; + static const byte MAX_BUFFER=100; + static char buffer[MAX_BUFFER]; };