#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL3XvWT_aYr"
#define BLYNK_TEMPLATE_NAME "poject3"
#define BLYNK_AUTH_TOKEN "rFi0f-_r4Nc94SPsGuA2k-DVSN2CKigs"

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

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

BlynkTimer timer;

#define LED1 13  // Merah
#define LED2 12  // Kuning
#define LED3 14  // Hijau
int SW_State_M = 0;
int SW_State_K = 0;
int SW_State_H = 0;
DHTesp dhtSensor;
const int DHT_PIN = 15;

#define Trig 18
#define Echo 19
float jarak = 0;
float ketinggian_air = 0;


BLYNK_WRITE (V0)
{
  SW_State_M = param.asInt();
  if (SW_State_M == 1)
  {
    digitalWrite(LED1, HIGH);
    Serial.println("RED ON");
    //Blynk.virtualWrite(V1, HIGH);
  }
  else
  {
    digitalWrite(LED1, LOW);
    Serial.println("RED OFF");
    //Blynk.virtualWrite(V1, LOW);
  }
}

BLYNK_WRITE (V1)
{
  SW_State_K = param.asInt();
  if (SW_State_K == 1)
  {
    digitalWrite(LED2, HIGH);
    Serial.println("YELLOW ON");
    //Blynk.virtualWrite(V3, HIGH);
  }
  else
  {
    digitalWrite(LED2, LOW);
    Serial.println("YELLOW OFF");
    //Blynk.virtualWrite(V3, LOW);
  }
}

BLYNK_WRITE (V2)
{
  SW_State_H = param.asInt();
  if (SW_State_H == 1)
  {
    digitalWrite(LED3, HIGH);
    Serial.println("GREEN ON");
    //Blynk.virtualWrite(V5, HIGH);
  }
  else
  {
    digitalWrite(LED3, LOW);
    Serial.println("GREEN OFF");
    //Blynk.virtualWrite(V5, LOW);
  }
}

// baca jarak dari sensor ultra sonic
void baca_jarak()
{
  digitalWrite(Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trig, LOW);

  int duration = pulseIn(Echo, HIGH);
  jarak = duration * 0.034 / 2;
  ketinggian_air = jarak;
}



void setup()
{
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(Trig, OUTPUT);
  pinMode(Echo, INPUT);
  Serial.begin(9600);
  //Blynk.begin(auth, ssid, pass);
  Blynk.begin(auth, ssid, pass, "iot.serangkota.go.id", 8080);
}

void loop()
{
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  baca_jarak();
  Blynk.virtualWrite(V12, data.temperature);
  Blynk.virtualWrite(V13, data.humidity);
  Blynk.virtualWrite(V14, ketinggian_air);

  Blynk.run();
  timer.run();
}