#include <ESP8266WiFi.h>
#include "FirebaseESP8266.h"
#include "DHT.h"  
                                    
boolean state=false;
const char* FIREBASE_HOST ="https://coldchain-e420b-default-rtdb.firebaseio.com/";
const char* FIREBASE_AUTH ="5zs6dFebZp9LnWxFXyX34oqU2eH2ozCw0Dl8uAoK";
static char celsiusTemp[7];
static char indexTemp[7];
static char humidityTemp[7];
String nodo = "ColdChain_";
String ssid,password,cadena,a,b;
float t=0,h=0;
struct tm * timeinfo;
FirebaseData firebaseData;
DHT dht(12, DHT11);
time_t now;


void setup() {
  Serial.begin(115200);
  dht.begin();
}

void loop() 
{  
if(Serial.available()){ 
      if (!state)
  {
    ///Gómez Cardoso /123456789a/001/
    cadena=Serial.readString();
    ssid= getValue(cadena,'/',0);
    password= getValue(cadena,'/',1);
    b= getValue(cadena,'/',2);
    nodo+=b;
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(".");
  }
  Firebase.begin(FIREBASE_HOST,FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);
  state = true;
  Serial.println("conectado");   
  }
  else
  {
    time(&now);
    float h = dht.readHumidity();
          // Leyendo humedad 
          float t = dht.readTemperature();
          // Leyendo temperatura 
          if (isnan(h) || isnan(t) ) {
            Serial.println("Fallos al leer el sensor DHT");
            strcpy(celsiusTemp, "Fallido");
            strcpy(indexTemp, "Fallido");
            strcpy(humidityTemp, "Fallido");
          }
          else {
            // Calculando indice de temperatura 
            float hic = dht.computeHeatIndex(t, h, false);
            dtostrf(hic, 6, 2, indexTemp);
            dtostrf(h, 6, 2, humidityTemp);
            dtostrf(t, 6, 2, celsiusTemp);
            timeinfo = localtime(&now);
            a=(timeinfo->tm_mday-1);
            a+=":";
            a+=(timeinfo->tm_hour);
            a+=":";
            a+=(timeinfo->tm_min);
            Firebase.setString(firebaseData,nodo +"/Temperature",celsiusTemp);
            Firebase.setString(firebaseData,nodo +"/IndexHeat",indexTemp);
            Firebase.setString(firebaseData,nodo +"/Run",a);
            Firebase.setString(firebaseData,nodo +"/Humidity",humidityTemp);
            Serial.println("actualizado");  
            delay(1000);
            }
  }
 }
}

String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;
  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }

  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
