#define BLYNK_TEMPLATE_ID "TMPL3Oq7BVhWr"
#define BLYNK_TEMPLATE_NAME "TEMPERATURE"
#define BLYNK_AUTH_TOKEN "VhP1snmMJxc7svcsAO4-XVgeSLw3kqeh"

#include <DHTesp.h>
#include <BlynkSimpleEsp32.h>
#include <LiquidCrystal_I2C.h>
#define DHTPIN 13
#define LED_PIN 4
#define LED1 5
#define LED2 18
#define LED3 19

LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);


DHTesp dhtSensor;
char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

BlynkTimer timer;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  Serial.begin(115200);
  dhtSensor.setup(DHTPIN, DHTesp::DHT22);
  LCD.init();
  LCD.backlight();  
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, sendDHTData); // Send DHT data every 2 seconds
}

BLYNK_WRITE(V3) {
  int buttonState = param.asInt();
  if (buttonState == 1) {
    digitalWrite(LED_PIN, HIGH);
  } else {
    digitalWrite(LED_PIN, LOW);
  }
}

void sendDHTData() {
  float t = dhtSensor.getTemperature();
  float h = dhtSensor.getHumidity();
  
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Blynk.virtualWrite(V0, t);
  Blynk.virtualWrite(V1, h);
  
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print("%\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.println(" °C");
 
}

void loop() {
TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  LCD.setCursor(0, 0);
  LCD.println("Temperature:" + String(data.temperature, 2) + ".C");
  LCD.setCursor(0, 1);
  LCD.println("Humidity:" + String(data.humidity, 1) + "%");
 if (data.temperature < 48 || data.temperature > 80) {
    digitalWrite(LED3, LOW);}
  else{
    digitalWrite(LED3, HIGH);
  }

  if (data.temperature < 36 || data.temperature > 47 ) {
    digitalWrite(LED2, LOW);}
  else{
    digitalWrite(LED2, HIGH);
  }

  if (data.temperature < 10 || data.temperature > 35 ) {
    digitalWrite(LED1, LOW);}
  else{
    digitalWrite(LED1, HIGH);
  }
  delay(1000);
  Blynk.run();
  timer.run();
}