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

// WiFi
const char* ssid = "Wokwi-GUEST";
const char* password = "";

// MQTT broker
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char* mqtt_topic_temperature = "/ISTIC/TP4/INFOTRONIQUE/TEMPERATURE/";
const char* mqtt_topic_alert = "/ISTIC/TP4/INFOTRONIQUE/ALERT/";
WiFiClient espClient;
PubSubClient client(espClient);

// DHT sensor
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

// LED pins
const int led_red = 14;
const int led_blue = 13;

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

  WiFi.begin(ssid, password);

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

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

void reconnect() {
  while (!client.connected()) {
    Serial.print("Connecting to MQTT broker...");
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" retrying in 5 seconds");
      delay(5000);
    }
  }
}
void read_sensor(void *pvParameters) {
  (void) pvParameters;

  float temperature = 0;
  
  for (;;) {
    temperature = dht.readTemperature();

    Serial.print("Temperature: ");
    Serial.println(temperature);

    if (client.connected()) {
      client.publish(mqtt_topic_temperature, String(temperature).c_str());
    }

    if (temperature > 25) {
      digitalWrite(led_red, HIGH);
      digitalWrite(led_blue, LOW);

      if (client.connected()) {
        client.publish(mqtt_topic_alert, "CHAUD");
      }
    } else if (temperature < 25) {
      digitalWrite(led_red, LOW);
      digitalWrite(led_blue, HIGH);

      if (client.connected()) {
        client.publish(mqtt_topic_alert, "FROID");
      }
    } else {
      digitalWrite(led_red, LOW);
      digitalWrite(led_blue, LOW);
    }

    vTaskDelay(1000 / portTICK_PERIOD_MS);
  }
}

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

  dht.begin();

  pinMode(led_red, OUTPUT);
  pinMode(led_blue, OUTPUT);


  client.setServer(mqtt_server, mqtt_port);
}

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

  client.loop();
}

void app_main() {
  xTaskCreatePinnedToCore(
    read_sensor,     /* Function to implement the task */
    "Read Sensor",   /* Name of the task */
    10000,           /* Stack size in words */
    NULL,            /* Task input parameter */
    1,               /* Priority of the task */
    NULL,            /* Task handle. */
    0);              /* Core where the task should run */
}