#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPLKFD9kPLi"
#define BLYNK_DEVICE_NAME "Monitoring Intensitas Cahaya melalui Apps"
#define BLYNK_AUTH_TOKEN "wmp9VqrrN9JJXBiCQiWMgrElW38S5HP7"

#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 13
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();
}

//LED pakai 5V jadi R= 220 ohm, kalo 3V pakai R=100 ohm
//pin ADC di group 2 tidak bisa digunakan ketika wifi on
//jika pin ADC tersebut telah digunakan maka hasilnya akan infinity
//untuk pembacakan analog sensor pakai ADC di group 1
//cek data sheet dari ESP32 nya
//Link program ada di https://unyacid-my.sharepoint.com/personal/abdul128ft_2021_student_uny_ac_id/_layouts/15/onedrive.aspx?id=%2Fpersonal%2Fabdul128ft%5F2021%5Fstudent%5Funy%5Fac%5Fid%2FDocuments%2FDTS%20IoT%20Batch%204%2FMateri%20%2D%20Abdul%20Aziz%20STP&ga=1