#define BLYNK_PRINT Serial

#define BLYNK_TEMPLATE_ID "TMPL621OpxBG5"
#define BLYNK_TEMPLATE_NAME "HUM TEMP"
#define BLYNK_AUTH_TOKEN "AyV_RoifGZQ0pbUkovbu8xG-cVr2IYnS"

#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include "DHTesp.h"
#include <LiquidCrystal_I2C.h>

int buzzer = 12;
const int DHT_PIN = 15;
int enStat, setTemp;
LiquidCrystal_I2C lcd(0x27, 20, 4); 

DHTesp dhtSensor;

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

BlynkTimer timer;

BLYNK_WRITE(V4)
{
  int enValue = param.asInt();
  enStat = enValue;
  lcd.setCursor(5,1);
  lcd.print("e:");
  if(enStat == 0){
    lcd.print("OFF");
  } else {
    lcd.print("ON ");
    }
  }

BLYNK_WRITE(V3)
{
  int setValue = param.asInt();
  setTemp = setValue;
  lcd.setCursor(0,1);
  lcd.print("s:");
  lcd.print(setTemp);
}

void sendData(){
    TempAndHumidity  data = dhtSensor.getTempAndHumidity();
    float suhu = data.temperature;
    float hum = data.humidity;

    Blynk.virtualWrite(V0,"HELLO INI PROJECT ZULKARNAIN E. A");
    
    Blynk.virtualWrite(V1, data.temperature); 
    lcd.setCursor(0,0);
    lcd.print("t:");
    lcd.print(suhu);
    
    Blynk.virtualWrite(V2, data.humidity);
    lcd.setCursor(9,0);
    lcd.print("h:");
    lcd.print(hum);

    lcd.setCursor(11,1);
    lcd.print("b:");
  
    if ( enStat == HIGH && setTemp <= data.temperature)
    {
        digitalWrite(buzzer, HIGH);
        lcd.print("ON ");
        Blynk.virtualWrite(V5, HIGH);
    }
  else
    {
      lcd.print("OFF");
      digitalWrite(buzzer, LOW);
      Blynk.virtualWrite(V5, LOW);
  }
}

void setup() {
  Blynk.begin(auth, ssid, pass);
  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  pinMode(buzzer, OUTPUT);
  pinMode(DHT_PIN, INPUT);  
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  timer.setInterval(200L, sendData);
}

void loop() {
  delay(200);
  Blynk.run();
  timer.run();
}