#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.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 id=4;

void setup() { 
  Serial.begin(74800); 
  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(){
  float tension=lecture_tension();
  Serial.println(tension); 
  envoi_vers_controleur(id,"0",String(tension));
    delay(10000);
} 

float lecture_tension(){
  int valeur_analogique=analogRead(A0);
  float tension=valeur_analogique/1023.0*3.3; 
  //Serial.println(tension); 
  return tension;
}

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  
}
