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

// Defining variables
WiFiClient espClient; //esp setup
PubSubClient client(espClient); //setup pub sub client 
char strHumidity[10];
char strTemp[10];
DHTesp dhtSensor;

//Setip ESP32 WIFI
void setup() {
  WiFi.mode(WIFI_STA); //esp wifi setup
  WiFi.begin("Wokwi-GUEST", "");

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


void loop() { //connection recheck if connection goes down
  if (!client.connected()) {
    client.connect("clientId123");
    Serial.println("ESP32 is Connected with MQTT!");
  }

  client.loop();
// Get the temp and humidity
  TempAndHumidity data = dhtSensor.getTempAndHumidity();
  sprintf(strHumidity, "%.2f", data.humidity);
  sprintf(strTemp, "%.2fC", data.temperature);

  //publish data 
  client.publish("python/iot", strHumidity);
  client.publish("python/iot", strTemp);

  delay(1000);
}