Newer
Older
serialAgent / SerialAgent.h
#define HARD_SERIAL Serial

class SerialAgent {
private:
  String str_buff;
  bool isAvailable;
  void serialRead();
public:
  SerialAgent();
  void begin(int);
  int available();
  void print(String);
  void println(String);
  String readStringUntil(char c);
};

SerialAgent::SerialAgent() {
  isAvailable = false;
}

void SerialAgent::begin(int baudrate) {
  HARD_SERIAL.begin(baudrate);
}

void SerialAgent::serialRead() {
  if (isAvailable) {
    str_buff = "";
    isAvailable = false;
  }
  if (int count = HARD_SERIAL.available() > 0) {
    char c_buff = '\0';
    for (int i = 0; i < count; i++) {
      c_buff = (char)HARD_SERIAL.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;
}

void SerialAgent::print(String str) {
  HARD_SERIAL.print(str);
}

void SerialAgent::println(String str) {
  HARD_SERIAL.println(str);
}