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

#include "ThingsBoard.h"
#include "DHTesp.h"
#include <ESP32Servo.h>
#include <LiquidCrystal_I2C.h>

#define CURRENT_FIRMWARE_TITLE    "TEST"
#define CURRENT_FIRMWARE_VERSION  "1.0.0"
#define WIFI_SSID           "Wokwi-GUEST"
#define WIFI_PASSWORD       ""
#define TOKEN               "pTt7THYrjpVbfDNbPG8J"
#define THINGSBOARD_SERVER  "thingsboard.cloud"
#define SERIAL_DEBUG_BAUD   115200
LiquidCrystal_I2C lcd(0x27, 20, 4);  // Type LCD yang digunakan 20x4 dengan alamat i2c 0x24
const float GAMMA = 0.7;
const float RL10 = 50;
int StatusAtap;   // Variable untuk menyimpan status atap
const int DHT_PIN = 15;  // DHT22 konek ke pin 15
DHTesp dhtSensor;
const int servoPin = 13;  // Servo konek ke pin 13
Servo servo;
#define LDR_PIN 32    // Pin LDR
#define PUSH_BUTTON 26     // Pin PUSH_Button
#define SWITCH_BUTTON 33   // PIN Switch
#define LED_PIN 25      // Pin LED
//int status = 0;         // Variabel yang menampung Nilai Pusbaten 0
int last_state;
int button_baca;

WiFiClient espClient;
ThingsBoard tb(espClient);
int status = WL_IDLE_STATUS;
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");
  }
}

void setup() {
   Serial.begin(SERIAL_DEBUG_BAUD);
  Serial.println();
  InitWiFi();
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  servo.attach(servoPin);
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("       IOT3-14      "); 
  lcd.setCursor(0, 1);
  lcd.print("  Sistem Monitoring  ");
  lcd.setCursor(0, 2);
  lcd.print("    Tanaman Tomat  ");
  lcd.setCursor(0, 3);
  lcd.print("    Kelompok Satu    ");
  delay(3000);
  lcd.clear();
}

void loop() {
  //delay(1000);
  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();
  lcd.setCursor(0, 0);
  lcd.print("Suhu Kebun : ");
  lcd.print(data.temperature);
  lcd.print((char)223);
  lcd.print("C");
  Serial.print("Suhu : ");
  Serial.print(data.temperature);
  lcd.setCursor(0, 1);
  lcd.print("Kelembaban : ");
  lcd.print(data.humidity);
  lcd.print("%");
  Serial.print(" Kelembaban : ");
  Serial.println(data.humidity);
int suhu = data.temperature;
int kelembaban = data.humidity;
  lcd.setCursor(0, 3);
  lcd.print("Status Atap: ");
if (( suhu  >=  24 && suhu <= 28) && ( kelembaban  >=  70 && kelembaban <= 80)) { // Jika suhu diantara 24-28 derajat dan kelembaban diantara 70-80 persen
  servo.write(180); // Maka atap membuka
  StatusAtap = 1; //  status atap buka : 1
  Serial.print("Status Atap : ");
  Serial.println(StatusAtap);
  lcd.setCursor(13, 3);
  lcd.print("Buka  ");
} else{             // Jika kondisi diatas tidak ada yang terpenuhi
  servo.write(0);  // Maka atap menutup
  StatusAtap = 0;  // status atap tutup : 0
  Serial.print("Status Atap : ");
  Serial.println(StatusAtap);
  lcd.setCursor(13, 3);
  lcd.print("Tutup  ");
}
  int analogValue = analogRead(32); // Sensor LDR intensitas cahaya konek ke pin 32
  float voltage = analogValue / 1024. * 5;
  float resistance = 2000 * voltage / (1 - voltage / 5);
  float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
  lcd.setCursor(0, 2);
  lcd.print("Lux Cahaya : ");
  Serial.print("Lux Cahaya : ");
  lcd.setCursor(13, 2);
  lcd.print(lux);
  Serial.println(lux);

  tb.sendTelemetryFloat("temperature", data.temperature); // kirim data suhu ke thingsboard
  tb.sendTelemetryFloat("humidity", data.humidity);       // kirim data kelembaban ke thingsboard
  tb.sendTelemetryInt("lux", lux);                        // kirim data lux ke thingsboard
  tb.sendTelemetryInt("statusatap", StatusAtap);          // kirim data status atap ke thingsboard (buka : 1 dan tutup : 0)
  tb.loop();
}