#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h> 
#endif

// #include <WiFiEspClient.h> 
// #include <WiFiEsp.h> 
// #include <WiFiEspUdp.h> 
#include "ThingsBoard.h"
#include <DHTesp.h>

#define WIFI_SSID           "Wokwi-GUEST"
#define WIFI_PASSWORD       ""

#define TOKEN               "8p2qb4jfgxfen7n3cqeh"
#define THINGSBOARD_SERVER  "thingsboard.cloud"

WiFiClient espClient;
ThingsBoard<8> tb(espClient);

int status = WL_IDLE_STATUS;

#define TOKEN               "sBGU1mlUTo9ypc0XKPMu" //GANTI SESUAI AKUN TB ANDA
#define THINGSBOARD_SERVER  "thingsboard.cloud" // FIXED

const int DHT_PIN = 15;
DHTesp dhtSensor;

void connect()
{
  Serial.println("Connecting to AP ...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {

    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected to AP");
}

void reconnect() 
{
  status = WiFi.status();
  if ( status != WL_CONNECTED) 
  {
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    while (WiFi.status() != WL_CONNECTED) 
    {
      delay(500);
      Serial.print(".");
    }
    Serial.println("Connected to AP");
  }
}
void setup() 
{
  Serial.begin(115200);
  
  connect();
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
}

void loop() 
{
  // put your main code here, to run repeatedly:
  delay(1000); // this speeds up the simulation
   if (WiFi.status() != WL_CONNECTED) 
  {
    reconnect();
  }

  if (!tb.connected()) 
  {
    Serial.print("Connecting to: ");
    Serial.print(THINGSBOARD_SERVER);
    Serial.print(" with token ");
    Serial.println(TOKEN);
    if (!tb.connect(THINGSBOARD_SERVER, TOKEN)) 
    {
      Serial.println("Failed to connect");
      return;
    }
  }
  Serial.println("Sending data...");

  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  tb.sendTelemetryFloat("Suhu", data.temperature);
  tb.sendTelemetryFloat("Kelembaban", data.humidity);
  Serial.print("Suhu : ");
  Serial.print(data.temperature);
  Serial.print(" Kelembaban : ");
  Serial.println(data.humidity);
  // checkSuhu();
  tb.loop();
}

void checkSuhu()
{
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
}