byte   gSeq = 0;
String gInputString = ""; 
String gOutputString = "";
String gInputBuffer = "";
boolean gIsInputSuccess = true;

void setup(){
  Serial.begin(9600);
}

void loop(){
  sendMessage("loop:" + String(millis()));
  int a1=analogRead(0);
  setData("/cells.xhtml#fromArduino1", a1);
  int p = getData("/cells.xhtml#toArduino1");
  if (gIsInputSuccess)
    analogWrite(3,p);
  delay(10);
}

void sendMessage(String message)
{
  gOutputString = "M" + message;
  serialSend();
}

void setData(String path, int value)
{
  gOutputString = "S" + path + "," + String(value);
  serialSend();  
}

int getData(String path)
{
  gOutputString = "G" + path;  
  serialSendAndLoad();
  if (gIsInputSuccess)
    return int(gInputString.toInt());
  else
    return 0;  
}

void serialSend()
{
  gSeq ++;
  if (gSeq > 99)
  {
    gSeq = 1;
  }
  if (gSeq < 10)
  {
    Serial.print("0");
  }
  Serial.print(gSeq, DEC);
  Serial.println(gOutputString);
}

void serialSendAndLoad()
{
  serialSend();
  gIsInputSuccess = false;
  unsigned long timeout = millis() + 1000;
  gInputString = "";
  int isDataRecieved = false;
  while(!isDataRecieved && millis() < timeout)
  {
    while (Serial.available() > 0)
    {
      // get the new byte:
      char inChar = (char)Serial.read(); 
      // add it to the inputString:
      if (inChar != '\n' && inChar != '\r')
      {
        gInputBuffer += inChar;
      }
      // if the incoming character is a newline, set a flag
      // so the main loop can do something about it:
      if (inChar == '\n') 
      {
        //check input data
        if (gInputBuffer.length() >= 2)
        {
          String s = gInputBuffer.substring(0,2);
          if (s.toInt() == gSeq)
          {          
            gInputString = gInputBuffer.substring(2);
            isDataRecieved = true;
            gIsInputSuccess = true;
          }
          else
          {
            gIsInputSuccess = false;
          }
        }
        gInputBuffer = "";
      }
    }
  }
}

