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

char clientId[50];

WiFiClient espClient;
PubSubClient client(espClient);
const int DHT_PIN = 15;
static char strHumidity[10] = {0};
DHTesp dhtSensor;

void setup() {
  WiFi.mode(WIFI_STA);
  WiFi.begin("Wokwi-GUEST", "");

  client.setServer("broker.emqx.io", 1883);
  Serial.begin(9600);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
}


float getHumidity(void)
{
  TempAndHumidity data = dhtSensor.getTempAndHumidity();

  if (!(isnan(data.humidity)))
    return data.humidity;
  else
    return -99.99;
}

void mqttReconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect(clientId)) {
      Serial.println(" connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}


void loop() {
  if (!client.connected()) {
    mqttReconnect();
  }
  client.loop();
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  sprintf(strHumidity, "%.2f", getHumidity());
  client.publish("topicName/humidity", strHumidity);

  delay(1000);
}