#define presetTimedelaytoStartGen 2500 // time delay in milliseconds
#define presetTimedelaytoSMSOn 1000 // time delay in milliseconds to send SMS as Gen ON
#define presetTimedelaytoSMSOff 1200 // time delay in milliseconds to send SMS as Gen OFF
#define presetTimedelaytoStopGen 1500 //

unsigned long CEBPowerfailtimecheck ;
unsigned long CEBPowerRestoretimecheck;
unsigned long GeneratorOnSMSTimeCheck;
unsigned long GeneratorOffSMSTimeCheck;
//unsigned long GeneratorONTimechack ;
bool CEBPowerOk;  //Slide Switch right to Simulate power failure
bool GeneratorRelaySignal; // Relay signal will be high when enerator on
bool GenOnSMSSent = false;
bool GenOffSMSSent = false;


void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(3, INPUT_PULLUP); // CEB power 
  pinMode(4, INPUT); // Generator 230V relay
  pinMode(9, OUTPUT); // Generator ON
  //timecheck = millis(); //
}

void loop() {
  // put your main code here, to run repeatedly:
CEBPowerOk = digitalRead(3);
GeneratorRelaySignal = digitalRead(4);

if(CEBPowerOk)  // Slide switch RH
{
    CEBPowerfailtimecheck = millis(); // this is the important code part don't delete
}
else  //  slide Switch LH
{       
    CEBPowerRestoretimecheck = millis(); // this is the important code part don't delete
}

if(millis() - CEBPowerfailtimecheck > presetTimedelaytoStartGen )  // if CEB power down more than 2.5 sec
{
    digitalWrite(9, HIGH);
}

if(millis() - CEBPowerRestoretimecheck > presetTimedelaytoStopGen ) // IF CEB power Restored more than 1.5 sec
{
  digitalWrite(9, LOW);
}

if(GeneratorRelaySignal)  // Generator on  , SMSOn check time will not rise
{
  GeneratorOffSMSTimeCheck = millis();  // SMSoff check time will increase
}
else // Generator off, SMS off check time will not rise 
{
  GeneratorOnSMSTimeCheck = millis(); // smsOn check time will increase
}

if ( millis() - GeneratorOnSMSTimeCheck > presetTimedelaytoSMSOn  )  // if generator on for more than ...
{
  if(not GenOnSMSSent)
  {
    Serial.println(" Generator ON ");
    GenOnSMSSent = true;
    GenOffSMSSent = false;
  }
  
}

if (millis() - GeneratorOffSMSTimeCheck > presetTimedelaytoSMSOff )
{
  if(not GenOffSMSSent)
  {
    Serial.println(" Generator OFF ");
    GenOffSMSSent = true;
    GenOnSMSSent = false;
  }
}

}