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

#define BLYNK_TEMPLATE_ID "TMPLGZ6cBRWQ"
#define BLYNK_DEVICE_NAME "SUHUDHT22"
#define BLYNK_AUTH_TOKEN "twL9M-rhXAX9rsVc1D4SCF1Z9JjljJFn"

char auth[]="twL9M-rhXAX9rsVc1D4SCF1Z9JjljJFn"

#define BLYNK_PRINT Serial

WiFiClient client;

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

BlynkTimer timer;

const int DHT_PIN = 15;
const int trig = 2;
const int echo = 4;
const int ledM = 14;
const int ledK = 27;
const int ledH = 26;
const int ledB = 13;
const int ledP = 12;

DHTesp dhtSensor;

void sendSensor(){
  Serial.print("Jarak sensor dengan permukaan: ");
  Serial.print(readDistanceCM());
  Serial.println(" cm.");
  Serial.print("Ketinggian air sungai: ");
  Serial.print(300-readDistanceCM());
  Serial.println(" cm.");
  Serial.println("---");
  Blynk.virtualWrite(V1, 300-readDistanceCM()); //mengirimkan data ke Virtual pin di Blynk Cloud
  delay(100);
}

void setup() {
  pinMode(echo, INPUT);
  pinMode(trig, OUTPUT);
  pinMode(ledH, OUTPUT);
  pinMode(ledK, OUTPUT);
  pinMode(ledM, OUTPUT);
  pinMode(ledB, OUTPUT);
  pinMode(ledP, OUTPUT);
  Serial.begin(115200);
  WiFi.disconnect();
  WiFi.begin("Wokwi-GUEST", "");
  while (WiFi.status() != WL_CONNECTED){
    delay(300);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  Blynk.begin(auth, ssid, pass);
  //dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  timer.setInterval(2000L, sendSensor);
}

float ultrasonik(){
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  int durasiPantulan = pulseIn(echo, HIGH);
  return durasiPantulan * 0.034 / 2;
}

void loop() {
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  Serial.println("Jarak: " + String(ultrasonik()) + "cm");
  Serial.println("---");

  float jarakPer = ultrasonik();
  if(jarakPer>150){
    digitalWrite(ledH, HIGH);
    digitalWrite(ledK, LOW);
  }
  else if(jarakPer<=150 && jarakPer>100){
    digitalWrite(ledK, HIGH);
    digitalWrite(ledH, LOW);
    digitalWrite(ledM, LOW);
  }
  else if(jarakPer<=100){
    digitalWrite(ledM, HIGH);
    digitalWrite(ledK, LOW);
  }

  if(data.temperature<25){
    digitalWrite(ledB, LOW);
    digitalWrite(ledP, HIGH);    
  } else if(data.temperature>29){
    digitalWrite(ledB, HIGH);
    digitalWrite(ledP, LOW);     
  }

  delay(1000);
}