/*
This software is provided "as-is," without any express or implied warranty. 
In no event shall CW Electronx be held liable for any damages arising from the use of the software.
*/

// pins for the LEDs:
const int out12 = 12;
const int out13 = 13;
const int adHoc = 2;
String data, readData;
String pinNum;
String pinStatus;
int pinNumInt;
int sensorValue = 0;  

void setup() 
{
  //Initialize serial
    Serial.begin(9600);
    //Serial1.begin(9600);
  
  //Set the pins to be outputs
    pinMode(adHoc, OUTPUT);
    pinMode(3, OUTPUT); 
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT); 
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT); 
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT); 
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT); 
    pinMode(out12, OUTPUT);
    pinMode(out13, OUTPUT); 
  
    //Serial1.println("Everthing should be setup ok"); //Diagnostics designed for Mega //uncomment/comment as needed
}

void loop() 
{
  //Set the RN171 to ADHOC Mode
  digitalWrite(adHoc, HIGH);
  
  //Get Serial Command============================================== 
  // Read Serial Data when Available
  while (Serial.available() > 0) 
  {    
      readData = Serial.readString();
      //Serial1.println("Read Data: " + readData); //Diagnostics designed for Mega //uncomment/comment as needed
    
      data = readData.substring(readData.indexOf('D'), readData.indexOf('$')); 
      //Serial1.println("Data Request Command: " + data); //Diagnostics designed for Mega //uncomment/comment as needed
      
      //e.i. D02L or D02H ---> Pin#: 2 Status Request: L or H
      pinNum = data.substring(1,3);
      //Serial1.println("Pin Number: " + pinNum); //Diagnostics designed for Mega //uncomment/comment as needed
       
      pinStatus = data.substring(3,4);
      //Serial1.println("Pin Status: " + pinStatus); //Diagnostics designed for Mega //uncomment/comment as needed
      //Serial1.println(); //Diagnostics designed for Mega //uncomment/comment as needed
   }
   
   //Process and Set Command to Outputs=============================
   //Convert pin number String to int
   pinNumInt = pinNum.toInt();
   
   //Check to see if request is in the range of the outputs
   if((pinNumInt < 14) && (pinNumInt > 1))
   {
       setOutput(pinStatus, pinNumInt);
   }
   
}
void sendAnalogInputs()
{
    // read the analog in value:
  sensorValue = analogRead(A0); 
  Serial.println("AIN0:" + String(sensorValue) + "$"); 
  //Serial1.println("AIN0:" + String(sensorValue) + "$");   
}

void setOutput(String statusStringIN, int pinIN)
{
  if(0 == statusStringIN.compareTo("H"))
  {
      digitalWrite(pinIN, HIGH);
  }
  else if(0 == statusStringIN.compareTo("L"))
  {
      digitalWrite(pinIN, LOW);
  }
  //else Do NOTHING if Command not recognized
}






