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

#define LED_BUILTIN 2 // Built-in LED pin for ESP32

const int DHT_PIN = 15; // Pin where the DHT sensor is connected

WiFiClient espClient;
PubSubClient mqttClient(espClient);
DHTesp dhtSensor; // Create an instance of the DHT sensor

char tempAr[6]; // Buffer to hold the temperature value as a string

void setupWiFi() {
  WiFi.begin("Wokwi-GUEST", "");
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
}

void receiveCallback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("]: ");
  
  char payloadCharAr[length];
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    payloadCharAr[i] = (char)payload[i];
  }
  Serial.println();

  if(strcmp(topic, "MSE-ON-OFF")==0){
    if(payloadCharAr[0] == '1'){
      digitalWrite(LED_BUILTIN, HIGH); // Turn on the LED
    }
    else if(payloadCharAr[0] == '0'){
      digitalWrite(LED_BUILTIN, LOW); // Turn off the LED
    }
  }
}

void setupMQTT() {
  mqttClient.setServer("test.mosquitto.org", 1883);
  mqttClient.setCallback(receiveCallback); // Set the callback function to handle incoming messages
  }

void connectToBroker(){
  while (!mqttClient.connected()) {
    Serial.println("Attempting MQTT Connection...");
    if(mqttClient.connect("ESP32-442458")) {
      Serial.println("Connected to MQTT broker");
      mqttClient.subscribe("MSE-ON-OFF"); // Subscribe to the topic
    }
    else {
      Serial.print("Failed to connect, rc=");
      Serial.print(mqttClient.state());
      delay(5000);
    }
  }
}

void updateTemperature(){
  TempAndHumidity data = dhtSensor.getTempAndHumidity();
  String(data.temperature).toCharArray(tempAr, 6); // Convert temperature to string and store in tempAr
}

void setup() {
    Serial.begin(115200);
    setupWiFi(); // Function to connect to Wi-Fi
    setupMQTT(); // Function to set up MQTT client
    dhtSensor.setup(DHT_PIN, DHTesp::DHT22); // Initialize the DHT sensor

    pinMode(LED_BUILTIN, OUTPUT); // Set the built-in LED pin as output
    digitalWrite(LED_BUILTIN, LOW); // Turn off the LED initially
}

void loop(){
  if (!mqttClient.connected()) {
    connectToBroker(); // Function to connect to MQTT broker
  }

  updateTemperature(); // Function to read temperature from DHT sensor

  mqttClient.loop(); // Keep the MQTT connection alive

  Serial.println(tempAr); // Print the temperature value to the serial monitor
  mqttClient.publish("MSE-TEMP", tempAr); // Publish a message to the topic
  delay(2000); // Delay for 2 seconds before the next publish
}