#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#include <ESP32Servo.h>
// #include <MFRC522.h>  // Removed for now

// WiFi and MQTT Server Details
const char* ssid = "Wokwi-GUEST"; // WiFi network SSID
const char* password = "";        // WiFi network password
const char* mqtt_server = "test.mosquitto.org"; // Public MQTT broker

// MQTT Topics
const char* temperatureTopic = "topic/sensor/temperature";
const char* humidityTopic = "topic/sensor/humidity";
const char* lightTopic = "topic/sensor/light";
const char* potTopic = "topic/sensor/pot";
// const char* rfidTopic = "topic/sensor/rfid"; // Removed RFID topic
const char* controlTopic = "Control";
const char* alertTopic = "topic/sensor/alert";
const char* tempThresholdTopic = "Control/temperatureThreshold";
const char* humThresholdTopic = "Control/humidityThreshold";

// Pin Definitions
#define DHT_PIN 13       // DHT22 connected to GPIO13
#define LED_PIN 25       // LED connected to GPIO25
#define PHOTO_PIN 34     // Photoresistor connected to GPIO34 (ADC pin)
#define SERVO_PIN 26     // Servo motor connected to GPIO26
#define POT_PIN 35       // Potentiometer connected to GPIO35 (ADC pin)

// RFID Pins (Removed)
// #define RST_PIN 4        // Configurable, see wiring
// #define SS_PIN 5         // Configurable, see wiring

WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHT_PIN, DHT22);  // Initialize the DHT22 sensor
Servo servo;

// RFID Reader Instance (Removed)
// MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

float temperature;
float humidity;
int lightLevel;
int potValue;
float temperatureThreshold = 30.0; // Default temperature threshold
float humidityThreshold = 60.0;    // Default humidity threshold

void setup() {
  Serial.begin(115200);

  // Initialize sensors and actuators
  dht.begin();  // Initialize DHT22 sensor
  servo.attach(SERVO_PIN); // Attach the servo to its pin
  pinMode(LED_PIN, OUTPUT); // Set the LED pin as output
  pinMode(PHOTO_PIN, INPUT); // Set the photoresistor pin as input
  pinMode(POT_PIN, INPUT);   // Set the potentiometer pin as input

  // Initialize SPI and RFID reader (Removed)
  // SPI.begin();        // Init SPI bus
  // mfrc522.PCD_Init(); // Init MFRC522
  // Serial.println("RFID reader initialized.");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected to WiFi");

  // Connect to MQTT Broker
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  reconnect(); // Attempt to connect to MQTT broker
}

void reconnect() {
  // Loop until reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, subscribe to control topic
      client.subscribe(controlTopic);
      client.subscribe(tempThresholdTopic);
      client.subscribe(humThresholdTopic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" - trying again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  // Handle messages received
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  for (unsigned int i = 0; i < length; i++) {
    messageTemp += (char)payload[i];
  }
  Serial.println(messageTemp);

  String topicStr = String(topic);

  // Handle control messages
  if (topicStr == controlTopic) {
    if (messageTemp == "OPEN_SERVO") {
      servo.write(90);
      Serial.println("Servo opened");
    } else if (messageTemp == "CLOSE_SERVO") {
      servo.write(0);
      Serial.println("Servo closed");
    } else if (messageTemp == "TURN_ON_LED") {
      digitalWrite(LED_PIN, HIGH);
      Serial.println("LED turned on");
    } else if (messageTemp == "TURN_OFF_LED") {
      digitalWrite(LED_PIN, LOW);
      Serial.println("LED turned off");
    }
    // Add other control messages as needed
  }

  // Handle threshold updates
  if (topicStr == tempThresholdTopic) {
    temperatureThreshold = messageTemp.toFloat();
    Serial.print("Updated temperature threshold: ");
    Serial.println(temperatureThreshold);
  } else if (topicStr == humThresholdTopic) {
    humidityThreshold = messageTemp.toFloat();
    Serial.print("Updated humidity threshold: ");
    Serial.println(humidityThreshold);
  }
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  // Read sensor data
  temperature = dht.readTemperature();
  humidity = dht.readHumidity();
  lightLevel = analogRead(PHOTO_PIN);
  potValue = analogRead(POT_PIN);

  // Convert sensor data to strings
  String tempString = String(temperature);
  String humString = String(humidity);
  String lightString = String(lightLevel);
  String potString = String(potValue);

  // Publish sensor data
  client.publish(temperatureTopic, tempString.c_str());
  client.publish(humidityTopic, humString.c_str());
  client.publish(lightTopic, lightString.c_str());
  client.publish(potTopic, potString.c_str());

  // Print to serial for debugging
  Serial.print("Temperature: ");
  Serial.println(tempString);
  Serial.print("Humidity: ");
  Serial.println(humString);
  Serial.print("Light Intensity: ");
  Serial.println(lightString);
  Serial.print("Potentiometer: ");
  Serial.println(potString);

  // Check if thresholds are crossed
  if (temperature > temperatureThreshold) {
    const char* alertMessage = "Temperature Alert";
    client.publish(alertTopic, alertMessage);
    Serial.println(alertMessage);
  }
  if (humidity > humidityThreshold) {
    const char* alertMessage = "Humidity Alert";
    client.publish(alertTopic, alertMessage);
    Serial.println(alertMessage);
  }

  delay(1000);  // Adjust delay as needed
}
$abcdeabcde151015202530fghijfghij