#define BLYNK_TEMPLATE_ID "TMPL6Hn10vMDo"
#define BLYNK_TEMPLATE_NAME "ESP32 PENYIRAM TANAMAN OTOMATIS"
#define BLYNK_PRINT Serial

#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#include <LiquidCrystal_I2C.h>

// Inisialisasi LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);  // Alamat I2C LCD 16x2

// Definisi pin
#define LED_PIN 2   // GPIO 2 untuk LED (tidak digunakan dalam kode ini)
#define PUMP_PIN 19 // GPIO 19 untuk pompa (Relay)
#define SENSOR_PIN 34 // GPIO 34 untuk sensor kelembaban tanah (analog)

// Token dan WiFi
char auth[] = "LEUMijVPJO1Z27K_3nSHDbl7Y6wzLD_u";   // ISI TOKEN PADA APLIKASI BLYNK ANDROID
char ssid[] = "Wokwi-GUEST";                       // NAMA HOTSPOT
char pass[] = "";                        // PASSWORD HOTSPOT

BlynkTimer timer;
WidgetLCD blynkLcd(V1); // LCD virtual pada aplikasi Blynk

// Fungsi untuk mengontrol pompa dari Blynk
bool pumpState = false; // Status awal pompa (OFF)

BLYNK_WRITE(V2) {
  pumpState = param.asInt();
  if (pumpState) {
    digitalWrite(PUMP_PIN, LOW); // Mengaktifkan pompa
    Serial.println("Pump ON");
  } else {
    digitalWrite(PUMP_PIN, HIGH); // Mematikan pompa
    Serial.println("Pump OFF");
  }
  updatePumpStatus();
}

void updatePumpStatus() {
  if (pumpState) {
    lcd.setCursor(0, 1); lcd.print("Pump: ON ");
    blynkLcd.print(0, 1, "Pump: ON ");
  } else {
    lcd.setCursor(0, 1); lcd.print("Pump: OFF");
    blynkLcd.print(0, 1, "Pump: OFF");
  }
}

void sendSensor() {
  int soilMoisture = analogRead(SENSOR_PIN);

  Serial.print("Soil Moisture: "); Serial.println(soilMoisture);

  blynkLcd.print(0, 0, "Moisture:");
  lcd.setCursor(0, 0); lcd.print("Moisture:"); lcd.setCursor(10, 0); lcd.print(soilMoisture);

  Blynk.virtualWrite(V0, soilMoisture);

  if (soilMoisture > 500) {
    Serial.println("Tanah Kering");
    blynkLcd.print(8, 0, "Kering");
    lcd.setCursor(0, 1); lcd.print("Pump: ON");
  } else if (soilMoisture >= 400 && soilMoisture <= 500) {
    Serial.println("Tanah Normal");
    blynkLcd.print(8, 0, "Normal");
    lcd.setCursor(0, 1); lcd.print("Pump: OFF");
  } else {
    Serial.println("Tanah Basah");
    blynkLcd.print(8, 0, "Basah ");
    lcd.setCursor(0, 1); lcd.print("Pump: OFF");
  }
}

void setup() {
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, sendSensor);
  pinMode(PUMP_PIN, OUTPUT);
  digitalWrite(PUMP_PIN, HIGH); // Pompa OFF pada awalnya
  lcd.init();
  lcd.backlight();
}

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