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

//WiFi Setup
#define WIFI_SSID           "Wokwi-GUEST"
#define WIFI_PASSWORD       ""
WiFiClient espClient;
ThingsBoard tb(espClient);
int status = WL_IDLE_STATUS;

//ThingsBoard Setup
#define CURRENT_FIRMWARE_TITLE    "TEST"
#define CURRENT_FIRMWARE_VERSION  "1.0.0"
#define TOKEN               "UJagIm8FQ178ExYitWiz" 
#define THINGSBOARD_SERVER  "thingsboard.cloud"

#define ledMerah 13
#define ledHijau 12

//#define WIFI_AP_NAME              "Wokwi-GUEST"
//#define WIFI_PASSWORD             ""
//#define THINGSBOARD_SERVER        "thingsboard.cloud"
//#define THINGSBOARD_ACCESSTOKEN   "pu0TDLdTgmiytnNUUKe4" //Ubah Token

//DHT Setup
const int DHT_PIN = 15;
DHTesp dhtSensor;

void setup() {
  Serial.begin(115200);
  Serial.println();
  InitWiFi();
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  pinMode(ledMerah, OUTPUT);
  pinMode(ledHijau, OUTPUT);
  pinMode(33, INPUT);
}

void loop() {
  delay(1000);

  if (WiFi.status() != WL_CONNECTED) {
    reconnect();
  }

  if (!tb.connected()) {
    // Connect to the ThingsBoard
    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;
    }
  }

  float adc=analogRead(33);
  //adc = map(adc, 0, 4095, 0, 100);
  Serial.println(adc);

  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);

 if (data.temperature > 33)
  {
    Serial.println("Suhu Tidak Normal");
    digitalWrite(ledHijau, LOW);
    //digitalWrite(ledKuning, LOW);
    digitalWrite(ledMerah, HIGH);
    tb.sendTelemetryString("Pompa Air","Hidup");
  }
 // else if (distance > 100 && distance < 150)
 // {
 //   Serial.println("Kuning (Waspada)");
 //   digitalWrite(ledHijau, LOW);
 //   digitalWrite(ledKuning, HIGH);
 //   digitalWrite(ledMerah, LOW);
 // }
  else 
  {
    Serial.println("Suhu Normal");
    digitalWrite(ledHijau, HIGH);
  //  digitalWrite(ledKuning, LOW);
    digitalWrite(ledMerah, LOW);
  }


  tb.loop();
}

void InitWiFi()
{
  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");
  }
}