#define BLYNK_TEMPLATE_ID "TMPL6mpwy3ogQ"
#define BLYNK_TEMPLATE_NAME "Irrigation System"
#define BLYNK_AUTH_TOKEN "BC8ha6oumzgcMK_YvWFnM5HNWH92lRxv"

#define BLYNK_PRINT Serial

#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <DHT.h>


DHT dht(32, DHT22);

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


const int ldrPin = 35;
const int pumpPin = 26;
const int soilMoisturePin = 33;
const int rainPin = 14;

bool isPumpOn = false; 



void setup() {
  Serial.begin(115200);
  pinMode(pumpPin, OUTPUT);
  pinMode(rainPin, INPUT_PULLUP);
  dht.begin(); 

  Blynk.begin(auth, ssid, pass);
}

void loop() {
  Blynk.run();
  delay(10);

  int lightIntensity = analogRead(ldrPin);
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  int soilMoisture = analogRead(soilMoisturePin);
  bool isRaining = !digitalRead(rainPin);

  if (!isnan(temperature) && !isnan(humidity)) {
    // Below are the consitions that our water pump will be controlled
    if (lightIntensity < 200 && temperature > 25 && !isRaining && soilMoisture < 500) {
      digitalWrite(pumpPin, HIGH);
      isPumpOn = true;
    } else {
      digitalWrite(pumpPin, LOW);
      isPumpOn = false;
    }

    // Send sensor data to Blynk app
    Blynk.virtualWrite(V2, lightIntensity);      
    Blynk.virtualWrite(V1, temperature);          
    Blynk.virtualWrite(V4, isRaining ? 255 : 0); 
    Blynk.virtualWrite(V3, soilMoisture);        
    Blynk.virtualWrite(V5, isPumpOn ? 255 : 0); 

    

    
    Serial.print("Light Intensity: ");
    Serial.print(lightIntensity);
    Serial.print("\tTemperature: ");
    Serial.print(temperature);
    Serial.print("°C\tHumidity: ");
    Serial.print(humidity);
    Serial.print("%\tRain: ");
    Serial.print(isRaining ? "Yes" : "No");
    Serial.print("\tSoil Moisture: ");
    Serial.println(soilMoisture);
  } else {
    Serial.println("Error reading DHT sensor data!");
  }

  delay(1000);
}