#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <WiFiClient.h>

WiFiClient clientTCP;
const char* ssid = "SSID";         
const char* mot_de_passe = "mot_de_passe";

const String ip_controleur="192.168.1.123";
const int port=8080;
String utilisateur="utilisateur";
String mdp_domoticz="mdp_domoticz"; 

float temperature=21; 
float differentiel=0.2;

int broche_commande=12;
int idx_thermostat=6;
int idx_temperature=5;

String temp="";


void setup() { 
  Serial.begin(74880);
  pinMode(broche_commande, OUTPUT);
  digitalWrite(broche_commande, LOW); 
  connexion_reseau();
}

void connexion_reseau(){
  delay(10);  
  Serial.print("Tentative de connexion: "); 
  Serial.println(ssid); 
  WiFi.begin(ssid, mot_de_passe);  
  while (WiFi.status() != WL_CONNECTED) { 
    delay(500); 
    Serial.print("."); 
  } 
  Serial.println("Connexion au réseau Wi-Fi réalisée"); 
  Serial.println("L'adresse IP est: "); 
  Serial.println(WiFi.localIP());
}

void loop() {
 if(WiFi.status()== WL_CONNECTED){
   String thermostat = recuperer_donnee(idx_thermostat,"Data",2);    
   String temperature = recuperer_donnee(idx_temperature,"Temp",1);
   //Serial.print(temperature);
   //Serial.print(" - ");
   //Serial.println(thermostat);
   if (temperature.toFloat()<thermostat.toFloat()){
    digitalWrite(broche_commande, HIGH);
    //Serial.println("Commande On "); 
   }
   if (temperature.toFloat()>thermostat.toFloat()+differentiel){
    digitalWrite(broche_commande, LOW);
    //Serial.println("Commande Off ");
   } 
 }else{
   connexion_reseau();
 } 
 delay(60000);
}

String recuperer_donnee(int idx,String quoi,int type)
{
    String connexion_domoticz="";
    if (utilisateur!="" && mdp_domoticz!=""){
      connexion_domoticz=utilisateur+":"+mdp_domoticz+"@";
    }else{
      connexion_domoticz="";
    }
    String url="http://"+connexion_domoticz+ip_controleur+":"+port+"/json.htm?type=devices&rid="+String(idx);
    HTTPClient http;   
     http.begin(clientTCP,url);
    int httpCode = http.GET();
    if (httpCode > 0) {
        const size_t bufferSize = 2000;
        DynamicJsonDocument root(2000);
        DeserializationError error = deserializeJson(root, http.getString());
        if (error){
          Serial.print(F("deserializeJson() failed: "));
          Serial.println(error.f_str());
          //return;
        }else{
          if (type==1){
            float result0 =  root["result"][0][quoi];
            
            temp=String(result0);
          }
          if (type==2){
            const char* result0 =  root["result"][0][quoi];
            temp= result0;
          }
        }
    }else{
      temp="-999";
    }
    http.end();
    return temp;
}
