#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"; 

int broche_commande=12;
int id=2;

int humidite_sol=0;
String temp="";

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

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 etat_interrupteur_virtuel= recuperer_donnee(id,"Data",2);
  //Serial.println(etat_interrupteur_virtuel); 
    if (etat_interrupteur_virtuel=="On"){ 
      humidite_sol = analogRead(A0);
      if(humidite_sol <500){
        digitalWrite(broche_commande, HIGH); 
        //Serial.println("Horaire On + humidite trop faible => ON"); 
      }else{
        digitalWrite(broche_commande, LOW);
        //Serial.println("Horaire Off + humidite suffisante => OFF"); 
      }
    }else{
        digitalWrite(broche_commande, LOW);  
        //Serial.println("Horaire OFF => OFF "); 
    }
  }else{
    digitalWrite(broche_commande, LOW); 
    connexion_reseau();
  } 
  delay(300000);
}

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) {
        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;
          }
        }
        //Serial.println(temp);
      //
    }else{
      temp="-999";
    }
    http.end();
    return temp;
}
