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

const char * MQTTServer = "broker.hivemq.com";
const char * MQTT_Topic1 = "IoT/temp";
const char * MQTT_Topic2 = "IoT/humidity";

// Tạo ID ngẫu nhiên tại: https://www.guidgen.com/
const char * MQTT_ID = "526ca1f1-01e9-4c0e-ba36-4624c68da7bc";
int Port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

const int DHT_PIN = 15;
DHTesp dhtSensor;


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

void MQTT_Reconnect() {
  while (!client.connected()) {
    if (client.connect(MQTT_ID)) {
      Serial.print("MQTT Topic1: ");
      Serial.print(MQTT_Topic1);
      Serial.println(" connected");
      Serial.print("MQTT Topic2: ");
      Serial.print(MQTT_Topic2);
      Serial.println(" connected");
      client.subscribe(MQTT_Topic1);
      client.subscribe(MQTT_Topic2);
      Serial.println("");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.println(topic);
  Serial.print("Message: ");
  String stMessage;

  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    stMessage += (char)message[i];
  }
  Serial.println();
}

void setup() {
  Serial.begin(115200);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  WIFIConnect();
  client.setServer(MQTTServer, Port);
  client.setCallback(callback);

}

void loop() {
  delay(10);
  if (!client.connected()) {
    MQTT_Reconnect();
  }
  client.loop();
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  Serial.println("---");

  String temp = String(data.temperature, 2);
  String humid = String(data.humidity, 1);

  client.publish("IoT/temp",temp.c_str());
  client.publish("IoT/humidity",humid.c_str());


  delay(1000);
}