#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "LiquidCrystal_I2C.h"
#include "DHT.h"
#include "FC28.h"

#define relayPin 18
#define ldrPin 35
#define DHT_PIN 15
#define DHTTYPE DHT22
#define LED_PIN 33
#define SensorFC28_Pin 34

const char* mqtt_server = "broker.hivemq.com"; // Alamat broker MQTT
const char* topic = "smartfarming/data";      // Topik untuk Node-RED
const char* ssid = "Wokwi-GUEST";
const char* password = "";

WiFiClient espClient;
PubSubClient client(espClient);

DHT dht(DHT_PIN, DHT22);
LiquidCrystal_I2C lcd(0x27, 20, 4);
FC28Sensor mySensor;

float soil_moisture;
const float gama = 0.7;
const float rl10 = 50;

// Fungsi untuk koneksi WiFi
void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to WiFi...");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
}

// Callback jika menerima pesan MQTT (tidak digunakan dalam proyek ini)
void callback(char* topic, byte* message, unsigned int length) {}

// Fungsi untuk melakukan reconnect MQTT
void reconnect() {
  // Coba untuk terhubung jika tidak terhubung
  while (!client.connected()) {
    Serial.print("Connecting to MQTT...");
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
    } else {
      Serial.print("failed with state ");
      Serial.println(client.state());
      delay(2000);
    }
  }
}

void setup() {
  Serial.begin(9600);
  pinMode(ldrPin, INPUT);
  pinMode(DHT_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  pinMode(relayPin, OUTPUT);
  mySensor.initFC28Sensor(115200, SensorFC28_Pin);

  dht.begin();
  lcd.init();
  lcd.backlight();

  setup_wifi();

  // Koneksi MQTT
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  reconnect();  // Panggil reconnect saat pertama kali setup
}

void loop() {
  // Cek koneksi MQTT, jika terputus panggil reconnect
  if (!client.connected()) {
    reconnect();  // Jika terputus, panggil reconnect
  }
  client.loop();

  // Data sensor
  float hum = dht.readHumidity();
  float temp = dht.readTemperature();
  int ldrValue = analogRead(ldrPin);
  ldrValue = map(ldrValue, 4095, 0, 1024, 0);
  float ldrVoltage = ldrValue / 1024.0 * 5;
  float ldrResistance = 2000 * ldrVoltage / (1 - ldrVoltage / 5);
  float lux = pow(rl10 * 1e3 * pow(10, gama) / ldrResistance, (1 / gama));
  soil_moisture = mySensor.getSoilMoisture();

  // Kontrol relay berdasarkan kelembaban tanah
  if (soil_moisture > 66.66) {
    digitalWrite(relayPin, HIGH);
  } else {
    digitalWrite(relayPin, LOW);
  }

  // Tampilan data di LCD
  lcd.setCursor(0, 0);
  lcd.print("Tanah  :");
  lcd.print(soil_moisture < 33.33 ? "Basah" : soil_moisture > 66.66 ? "Kering" : "Normal");
  lcd.setCursor(0, 1);
  lcd.print("Kecerahan :");
  lcd.print(lux);
  lcd.setCursor(0, 2);
  lcd.print("Suhu :");
  lcd.print(temp);
  lcd.print("C");
  lcd.setCursor(0, 3);
  lcd.print("Kelembaban :");
  lcd.print(hum);
  lcd.print("%");

  // Publikasi data ke Node-RED melalui MQTT
  String payload = "{\"soil_moisture\": " + String(soil_moisture) +
                   ", \"lux\": " + String(lux) +
                   ", \"temperature\": " + String(temp) +
                   ", \"humidity\": " + String(hum) + "}";
  client.publish(topic, payload.c_str());

  delay(2000);
}
NOCOMNCVCCGNDINLED1PWRRelay Module