#include <WiFi.h>
#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ESP32Servo.h>
#include <PubSubClient.h> // Include the PubSubClient library

#define DHTPIN 13 // DHT22 sensor pin
#define DHTTYPE DHT22 // DHT 22 (AM2302)
#define BLUE_LED_PIN 14 // Blue LED pin
#define RED_LED_PIN 27 // Red LED pin
#define BUZZER_PIN 26 // Buzzer pin
#define SERVO_PIN 12 // Servo motor pin

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com"; // MQTT broker address

WiFiClient espClient;
PubSubClient client(espClient);

DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD address to 0x27 for a 16 chars and 2 line display
Servo myServo; // Create a Servo object

int lastServoPosition = 90; // Start with servo at 90 degrees

void setup() {
  Serial.begin(115200);
  dht.begin();
  pinMode(BLUE_LED_PIN, OUTPUT);
  pinMode(RED_LED_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  
  myServo.attach(SERVO_PIN); // Attach the servo to the pin
  myServo.write(90); // Start servo at 90 degrees
  
  // Initialize LCD
  lcd.init();
  lcd.backlight();

  // Connect to Wi-Fi
  connectToWiFi();

  // Setup MQTT
  client.setServer(mqtt_server, 1883);
  client.setCallback(mqttCallback);

  // Welcome message on LCD
  lcd.setCursor(0, 0);
  lcd.print("Temp: ");
  lcd.setCursor(0, 1);
  lcd.print("Humi: ");
}

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

  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  // Check if any reads failed and exit early (to try again).
  if (isnan(temperature) || isnan(humidity)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Display temperature and humidity on LCD
  lcd.setCursor(6, 0);
  lcd.print(temperature);
  lcd.print("C");
  lcd.setCursor(6, 1);
  lcd.print(humidity);
  lcd.print("%");

  if (temperature < 35.0) {
    if (lastServoPosition != 0) { // Only move the servo if it's not already at 0 degrees
      myServo.write(0); // Return servo to 0 degrees
      lastServoPosition = 0;
      Serial.println("Servo moved to 0 degrees");
    }
    blinkLED(BLUE_LED_PIN, 500); // Blink blue LED
    digitalWrite(RED_LED_PIN, LOW); // Ensure red LED is off
    noTone(BUZZER_PIN); // Ensure buzzer is off
    Serial.println("Blue LED should blink");
  } else {
    if (lastServoPosition != 90) { // Only move the servo if it's not already at 90 degrees
      myServo.write(90); // Turn servo 90 degrees to the right
      lastServoPosition = 90;
      Serial.println("Servo moved to 90 degrees");
    }
    blinkLED(RED_LED_PIN, 200); // Blink red LED
    tone(BUZZER_PIN, 1000); // Sound the buzzer
    Serial.println("Red LED should blink and buzzer should sound");

    // Publish an alarm state to MQTT
    client.publish("esp32/alarm", "Temperature above 35C! Red LED and buzzer active.");
  }

  // Publish temperature and humidity to MQTT
  publishData(temperature, humidity);

  delay(2000); // Delay between readings
}

void blinkLED(int pin, int delayTime) {
  digitalWrite(pin, HIGH);
  delay(delayTime);
  digitalWrite(pin, LOW);
  delay(delayTime);
}

void connectToWiFi() {
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

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

  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void mqttCallback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  
  for (int i = 0; i < length; i++) {
    messageTemp += (char)message[i];
  }
  Serial.println(messageTemp);
  
  // You can add code here to handle messages received on subscribed topics
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a unique client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);

    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("esp32/status", "connected");
      // ... and resubscribe
      client.subscribe("9077874C/ROOM/IOT");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void publishData(float temperature, float humidity) {
  char tempString[8];
  char humString[8];
  dtostrf(temperature, 1, 2, tempString);
  dtostrf(humidity, 1, 2, humString);

  client.publish("esp32/temperature", tempString);
  client.publish("esp32/humidity",humString);
}