diff --git a/SerialAgent.h b/SerialAgent.h new file mode 100644 index 0000000..90fb41c --- /dev/null +++ b/SerialAgent.h @@ -0,0 +1,47 @@ +class SerialAgent : public SoftwareSerial{ +private: + String str_buff; + bool isAvailable; + void serialRead(); +public: + SerialAgent(int rx, int tx); + int available(); + String readStringUntil(char c); +}; + + +SerialAgent::SerialAgent(int rx, int tx) :SoftwareSerial(rx, tx) { + isAvailable = false; +} + +void SerialAgent::serialRead() { + if (isAvailable) { + str_buff = ""; + isAvailable = false; + } + if (int count = SoftwareSerial::available() > 0) { + char c_buff = '\0'; + for (int i = 0; i < count; i++) { + c_buff = (char)SoftwareSerial::read(); + if ( c_buff != '\n' ) { + str_buff += c_buff; + } else { + this->isAvailable = true; + break; + } + } + } +} + +String SerialAgent::readStringUntil(char c) { + int foundIndex = str_buff.indexOf(c); + if ( foundIndex == -1 ) return "\n"; + String result = str_buff.substring(0,foundIndex); + str_buff = str_buff.substring(foundIndex+1); + return result; +} + +int SerialAgent::available() { + serialRead(); + return isAvailable; +}