   
 
 }
-


void setup() {
  Serial.begin(115200);
  myMqtt = new MqttConnection(SENSOR_ID, WLAN_SSID, WLAN_PASS, MQTT_SERVER, MQTT_PORT);
  myMqtt->registerCustomProcessing(&processEcsStateMsg);
  myMqtt->addSubscription("state");
  myMqtt->addSubscription("force");  
}

void loop() {
  float temp;
  if (!myMqtt->connected()) {
    myMqtt->reconnect();
  }
  myMqtt->loop();

#define MQTT_SERVER  "192.168.1.27"
#define MQTT_PORT 1883

#define DELAY_BETWEEN_TOGGLE_ON 9000 //00  //15min
#define DELAY_BETWEEN_TOGGLE_OFF 900 //000  //15min

long lastMsg = 0;
char ecsState = ECS_STATE_OFF;
char msg[2];
unsigned long lastSwitchOn = 0;
unsigned long lastSwitchOff = 0;

bool checkToggleTooFast(bool switchOn){
  Serial.print("now :");
  Serial.println(millis());
  Serial.print("last on:");
  Serial.println(lastSwitchOn);  
  Serial.print("last off:");
  Serial.println(lastSwitchOff);   
  if(switchOn){
      if(millis() - lastSwitchOff < DELAY_BETWEEN_TOGGLE_ON)
         return true;
      else
         return false;
   }
   else{
      if(millis() - lastSwitchOn < DELAY_BETWEEN_TOGGLE_OFF)
         return true;
      else
         return false;
  
   
   }
      
}

void processEcsStateMsg(char* topic, byte* payload, unsigned int length)
{

  Serial.print("Checking if state topic");
 // if(String(topic) == "ECS/state"){
	  Serial.println("Received ECS/State change message");
		 Serial.println("changing ECS relay state");
	     if ((char)payload[0] == ECS_STATE_ON) {
		    Serial.println("ECS ON received");
						
			if(!checkToggleTooFast(true)){
			    ecsState = ECS_STATE_ON;
			    digitalWrite(RELAY_PIN, HIGH);
				lastSwitchOn = millis();
			}
		    else
			    Serial.println("Skipping, switching too fast");
	     }
	     else if ((char)payload[0] == ECS_STATE_OFF){
		    Serial.println("ECS OFF received");

			if(!checkToggleTooFast(false)){
			   ecsState = ECS_STATE_OFF;
			   digitalWrite(RELAY_PIN, LOW);
			   lastSwitchOff = millis();
			}
	     }
		 else {
		    Serial.print("Unknown payload : ");
			Serial.println((char)payload[0]);
		 }

	  
  //}
  //else {
  //	  Serial.println("not for me...");
  //}  

	
}
