#include <WiFi.h>
#include <PubSubClient.h>
#include <DHTesp.h>
#include <LiquidCrystal_I2C.h>

const int DHT_PIN = 15;
DHTesp dht; 

const char* ssid = "Wokwi-GUEST"; // WiFi SSID
const char* password = ""; // WiFi password
const char* mqtt_server = "test.mosquitto.org"; // MQTT server URL
const char *mqtt_topic = "temperature-humidity";

WiFiClient espClient;
PubSubClient client(espClient);

LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 columns and 2 rows

unsigned long lastPublishTime = 0;
float lastTemperature = 0.0;
float lastHumidity = 0.0;

bool wifiConnected = false;

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  int attempts = 0;
  while (WiFi.status() != WL_CONNECTED && attempts < 10) {
    delay(500);
    Serial.print(".");
    attempts++;
  }

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    wifiConnected = true;
  } else {
    Serial.println("");
    Serial.println("Connection failed");
    wifiConnected = false;
  }
}
void reconnect() { 
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str())) {
      Serial.println("Connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }}
}
void setup() {
  lcd.init();
  lcd.backlight();
  Serial.begin(115200);
  
  setup_wifi();
  dht.setup(DHT_PIN, DHTesp::DHT22);

  
}

void loop() {
  unsigned long currentMillis = millis();
  
  // Read temperature and humidity
  TempAndHumidity data = dht.getTempAndHumidity();
  float humidity = data.humidity;
  float temperature = data.temperature;

  // Update LCD with real-time data
  if (!isnan(humidity) && !isnan(temperature)) {
    if (temperature != lastTemperature || humidity != lastHumidity) {
      lastTemperature = temperature;
      lastHumidity = humidity;
      lcd.clear();
      // Initial LCD display
      lcd.setCursor(0, 0);
      lcd.print("Temp: ");
      lcd.setCursor(0, 1);
      lcd.print("Humidity: ");
      lcd.setCursor(6, 0);
      lcd.print(temperature);
      lcd.print("*C");

      lcd.setCursor(10, 1);
      lcd.print(humidity);
      lcd.print("%");
    }
  } else {
    Serial.println("Failed to read from DHT sensor!");
  }

  // Publish temperature and humidity readings to MQTT every 10 seconds if WiFi is connected
  if (wifiConnected && currentMillis - lastPublishTime >= 5000) {
      if (client.connected()) {
          String temp = String(temperature, 2);
          client.publish("/CyberDash/temp", temp.c_str()); // publish temp topic /ThinkIOT/temp
          String hum = String(humidity, 1); 
          client.publish("/CyberDash/hum", hum.c_str());   // publish hum topic /ThinkIOT/hum
          client.subscribe("/Thinkitive/switch");
          
          lastPublishTime = currentMillis;
      } else {
          Serial.println("MQTT client not connected.");
      }
  }


  // Reconnect to WiFi if connection is lost
  if (!wifiConnected && currentMillis - lastPublishTime >= 2000) {
    setup_wifi();
  }

  // Maintain MQTT connection
  if (wifiConnected) {
    if (!client.connected()) {
      reconnect();
    }
    client.loop();
    
  }
}