// Les librairies
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <FS.h>   
#include "DHT.h"

// ses identifiants du reseau wifi
const char *ssid = "XXXX";
const char *password = "YYYY";

// la sonde dht22
#define DHTTYPE DHT22                  
uint8_t DHTPin = 4; 
float Temperature, Humidite;
DHT dht(DHTPin, DHTTYPE); 

// le serveur web
ESP8266WebServer server(80);

// fonction qui lit la sonde et envoi les data au seveur web
void handleData(){
  Temperature = dht.readTemperature();  
  Serial.println(Temperature);
  Humidite = dht.readHumidity(); 
  Serial.println(Humidite);
  char datas[64];
  snprintf(datas, 64, "%.2f,%.2f", Temperature, Humidite);
  server.send(200, "text/html",datas);
}

// la fonction qui renvoie vers la page index.html quand on est a la racine du serveur
void handleRoot(){
  server.sendHeader("Location", "/index.html",true);   
  server.send(302, "text/plain","");
}

// la fonction qui traite la requète HTTP
void handleWebRequests(){
  if(loadFromSpiffs(server.uri())) return;
  String message = "File Not Detected\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " NAME:"+server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  Serial.println(message);
}


void setup() {
  delay(1000);
  Serial.begin(115200);
  Serial.println();
  pinMode(DHTPin, INPUT); 
  dht.begin();
  //Initialise la mèmoire SPIFFS
  SPIFFS.begin();
  Serial.println("File System Initialized");
 
  // on SE CONNECTE AU RESEAU
  WiFi.begin(ssid, password);     //Connect to your WiFi router
  Serial.println("");
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  

  // on nitialise le serveur web
  server.on("/",handleRoot);            // la fonction associé a la racine du serveur
  server.on("/getData",handleData);     // la fonction associé a l'onglet /getData
  server.onNotFound(handleWebRequests); // la fonction qui traite la requete HTTP si la page n'est pas trouvé
  server.begin();                       // on demarre le serveur web 
}

void loop() {
 server.handleClient();                 // on attend un client en boucle
}


// la fonction qui lit et traite les fichiers presents dans la mémoire SPIFFS 
bool loadFromSpiffs(String path){
  String dataType = "text/plain";
  if(path.endsWith("/")) path += "index.htm";
  if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf("."));
  else if(path.endsWith(".html")) dataType = "text/html";
  else if(path.endsWith(".htm")) dataType = "text/html";
  else if(path.endsWith(".css")) dataType = "text/css";
  else if(path.endsWith(".js")) dataType = "application/javascript";
  else if(path.endsWith(".png")) dataType = "image/png";
  else if(path.endsWith(".gif")) dataType = "image/gif";
  else if(path.endsWith(".jpg")) dataType = "image/jpeg";
  else if(path.endsWith(".ico")) dataType = "image/x-icon";
  else if(path.endsWith(".xml")) dataType = "text/xml";
  else if(path.endsWith(".pdf")) dataType = "application/pdf";
  else if(path.endsWith(".zip")) dataType = "application/zip";
  File dataFile = SPIFFS.open(path.c_str(), "r");
  
  if (server.hasArg("download")) dataType = "application/octet-stream";
  if (server.streamFile(dataFile, dataType) != dataFile.size()) {    
  }
  dataFile.close();  
  return true;
}