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

#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PW ""
#define MQTT_BROKER "broker.mqtt-dashboard.com"
#define MQTT_PORT 1883

const int DHT_PIN = 15;

WiFiClient espClient;
PubSubClient client(espClient);
DHTesp dhtSensor;

void setup() {
  Serial.begin(115200);
   dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
 
  WiFi.begin(WIFI_SSID, WIFI_PW);
   
while(WiFi.status()!=WL_CONNECTED){
    delay(250);
    Serial.print(" .");
  }
  Serial.println("");
  Serial.print("Connected to hotspot:");
  Serial.println(WIFI_SSID);
  Serial.print(" IP address is: ");
  Serial.println(WiFi.localIP());
  WiFi.mode(WIFI_STA);
  Serial.println("WIFI Connected Successful ");

client.setServer(MQTT_BROKER, MQTT_PORT);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");

  if (client.connect("espGood", "Qwerty12", "Qwerty12" )){
    Serial.println("Connected to broker");
    } 
  else{  
    Serial.print("failed with state ");
    Serial.print(client.state());
    delay(2000);
    }
    }

}

void loop() {
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  Serial.println("---");

client.publish("GM_TEMP", String(data.temperature,2).c_str());
client.publish("GM_HUMI", String(data.humidity,2).c_str());
delay(2000) ; 
}