//Importar librerias
#include "thingProperties.h"
#include "DHTesp.h"
#include <Arduino.h>
#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <LiquidCrystal_I2C.h>

//Conf. dispositivos
const int DHT_PIN = 15;
DHTesp dhtSensor;
LiquidCrystal_I2C lcd(0x27,16,2);

//Def. Variables
int ID = 14101;
int temp;
String sen;
String fecha = "03-08-2022";

//Def. datos de red
const char* ssid = "Wokwi-GUEST";
const char* password = "";
HTTPClient client;

void setup() {

  //Iniciar dispositivos
  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  dhtSensor.setup(DHT_PIN,DHTesp::DHT22);

  //Conexion a WIFI
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid,password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  //Conexion a Firebase
  client.begin("https://temperatura-c7f79-default-rtdb.firebaseio.com/Arduino%20IoCloud.json");
  client.addHeader("Content-Type","application/json");
  
  //Conexion a Arduino Cloud
  initProperties();
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();
}

void loop() {

  //Actualización Arduino Cloud
  ArduinoCloud.update();
  if (vstate == true){
    //Lectura de sensor y definicion de estado
    TempAndHumidity  data = dhtSensor.getTempAndHumidity();
    temp = data.temperature;
    if(temp <= 0){
      sen = "Muy Frio";
    } else if (temp<=20){
      sen = "Frio";
    } else if (temp>=40){
      sen = "Caliente";
    } else {
      sen = "Agradable";
    }

    //Escritura en lcd
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(fecha + " " + String(ID));
    lcd.setCursor(0,1);
    lcd.print(String(temp) + " C " + sen);

    //Patch en Firebase
    String json;
    StaticJsonDocument<200> doc;
    doc["Fecha"]=fecha;
    doc["ID"]=String(ID);
    doc["Temperatura"]=String(temp);
    doc["Sensacion"]=sen;
    serializeJson(doc,json);
    client.PATCH(json);
    String payload = client.getString();
    Serial.println(payload);

    //Escritura en Arduino Cloud
    vvalor = temp;
    delay(1000);

  } else {
    lcd.clear();
  }
}

//Encendido de Led
void onVstateChange()  {
  if(vstate){
    Serial.println("On");
  }
  else{
    Serial.println("Off");
    vvalor = 0;
  }
}