#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPLYNABOUKO"
#define BLYNK_DEVICE_NAME "Topik 9"
#define BLYNK_AUTH_TOKEN "Wtjlf7_8EmwJYP-1F4PjHxf16Mq7euGW"

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

const int DHT_PIN = 15;
DHTesp dhtSensor;

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

BlynkTimer timer;

const float GAMMA = 0.7;
const float RL10 = 50;

#define Relay 2
int SW_State=0;

void sendSensor()
{
  int analogValue = analogRead(33);
  float voltage = analogValue * 5/4095.0;
  float resistance = 2000 * voltage / (1 - voltage / 5);
  float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
  Serial.print("Lux: ");
  Serial.println(lux);
  
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  Serial.println("---");


  Blynk.virtualWrite(V0, data.temperature); 
  Blynk.virtualWrite(V1, data.humidity);
  Blynk.virtualWrite(V2, lux);
}

BLYNK_WRITE (V3)
{
  SW_State = param.asInt();
  if (SW_State == 1)
  {
    digitalWrite(Relay, HIGH);
    Serial.println("Pompa HIDUP");
    Blynk.virtualWrite(V4, "HIDUP");
  }
  else
  {
    digitalWrite(Relay, LOW);
    Serial.println("Pompa MATI");
    Blynk.virtualWrite(V4, "MATI");
  }
}

void setup()
{
  pinMode(Relay, OUTPUT);
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  timer.setInterval(1000L, sendSensor);
}

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