#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include "DHT.h"          
#include <WiFiClient.h>
WiFiClient clientTCP;
const int broche_mesure=12;          
DHT dht(broche_mesure, DHT22); 
         
const char* ssid = "ssid";         
const char* mot_de_passe = "mot_de_passe";
const int port=8080;
const String ip_controleur="192.168.1.123";

String utilisateur="utilisateur";
String mdp_domoticz="mdp_domoticz";

const int id=5;

void setup(){
  dht.begin();
  Serial.begin(74880);
  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(){
  delay(2000); 
  if(WiFi.status()== WL_CONNECTED){
    float t = dht.readTemperature(); 
    float rh = dht.readHumidity(); 
    
    if (isnan(t) || isnan(rh)) {
      Serial.println("Erreur de communication!"); 
      return; 
    }else{                     
      envoi_vers_controleur(id,"0",String(t)+";"+String(rh)+";0");
    }
  }else{
    connexion_reseau(); 
  } 
}

void envoi_vers_controleur(int id, String nvalue, String svalue){
    HTTPClient http;
    String connexion_domoticz="";
    if (utilisateur!="" && mdp_domoticz!=""){
      connexion_domoticz=utilisateur+":"+mdp_domoticz+"@";//"+utilisateur+":"+mdp_domoticz+"@"
    }else{
      connexion_domoticz="";
    }
    if (nvalue!="" && svalue!=""){
      http.begin(clientTCP,"http://"+connexion_domoticz+ip_controleur+":"+port+"/json.htm?type=command&param=udevice&idx="+String(id)+"&nvalue="+nvalue+"&svalue="+svalue);
    }else if(nvalue==""){
      http.begin(clientTCP,"http://"+connexion_domoticz+ip_controleur+":"+port+"/json.htm?type=command&param=udevice&idx="+String(id)+"&svalue="+svalue);
    }else{
      http.begin(clientTCP,"http://"+connexion_domoticz+ip_controleur+":"+port+"/json.htm?type=command&param=udevice&idx="+String(id)+"&nvalue="+nvalue);
    }
    int httpCode =http.GET();
    if (httpCode > 0){
      String reponse = http.getString();   
      Serial.println(reponse); 
    }else{
      Serial.println(millis());
    } 
    http.end();   //Close connection  
}
