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

char clientId[50];

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

void setup() {
  Serial.begin(115200);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
    WiFi.mode(WIFI_STA);
  WiFi.begin("Wokwi-GUEST", "");
  
  client.setServer("broker.emqx.io", 1883);
  // client.setCallback(callback);
}
float getTemperature(void)
{
  TempAndHumidity data = dhtSensor.getTempAndHumidity();

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


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");
      // client.subscribe("topicName/time");
    } 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(strTemperature, "%.2fC", getTemperature());
  sprintf(strHumidity, "%.2f", getHumidity());
  client.publish("topicName/time", strTemperature);
  client.publish("topicName/time", strHumidity);

  delay(1000);
}