Newer
Older
serialAgent / SerialAgent.h
@takayun takayun on 12 May 2016 1022 bytes first commit
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;
}