#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif
#include <esp_wifi.h>
#include "DHTesp.h"
#include "ThingsBoard.h"
#include <Wire.h>
#include "DHTesp.h"
#include <ESP32Servo.h>
#define pinRelay 2
#define pinSwitch 13

#define CURRENT_FIRMWARE_TITLE    "TEST"
#define CURRENT_FIRMWARE_VERSION  "1.0.0"

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

#define TOKEN               "WV3QqF6sbzu5AC4AkvCE"
#define THINGSBOARD_SERVER  "thingsboard.cloud"

// Baud rate for debug serial
#define SERIAL_DEBUG_BAUD   115200

// Initialize ThingsBoard client
WiFiClient espClient;
// Initialize ThingsBoard instance
ThingsBoard tb(espClient);
// the Wifi radio's status
int status = WL_IDLE_STATUS;

// data yang diinputkan 
Servo myservo;  
DHTesp dhtSensor;

int pos;  
const int DHT_PIN = 12;
int suhu;
int lembap;
const float GAMMA = 0.7;
const float RL10 = 50;

void InitWiFi()
{
  Serial.println("Connecting to AP ...");
  // attempt to connect to WiFi network

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {

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

void reconnect() {
  // Loop until we're reconnected
  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() {
  // initialize serial for debugging
  Serial.begin(SERIAL_DEBUG_BAUD);
  Serial.println();
  InitWiFi();
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  Serial.print("[OLD] ESP32 Board MAC Address:  ");
  Serial.println(WiFi.macAddress());
  
  // ESP32 Board add-on before version < 1.0.5
  //esp_wifi_set_mac(ESP_IF_WIFI_STA, &newMACAddress[0]);
  
  // ESP32 Board add-on after version > 1.0.5
 // esp_wifi_set_mac(WIFI_IF_STA, &newMACAddress[0]);
  
  Serial.print("[NEW] ESP32 Board MAC Address:  ");
  Serial.println(WiFi.macAddress());

//Setup DHT,relay,servo
  //dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  myservo.attach(14);  
  pinMode(pinRelay, OUTPUT);
  pinMode (pinSwitch, INPUT_PULLUP);


}

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

  Serial.println("Sending data...");

  // Uploads new telemetry to ThingsBoard using MQTT.
  // See https://thingsboard.io/docs/reference/mqtt-api/#telemetry-upload-api
  // for more details

  //sensor hujan
  int hujan= digitalRead((pinSwitch));
  //DHT
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  Serial.println("---");
  delay(1000);
  suhu= data.temperature;
  lembap= data.humidity;
  // ldr 
  int analogValue = analogRead(36);
  float voltage = analogValue * 5/4095.0;
  float resistance = 2000 * voltage / (1 - voltage / 5);
  float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
  Serial.print("Lux: ");
  Serial.println(lux);
          if (suhu>=30 || lux>=200) {//siang dan panas maka  atap nutup 
             //for (pos; pos>=180; pos+=1){
                 myservo.write(0);            
                 //delay(15);
                 digitalWrite (pinRelay,LOW);// atap tutup menghdap kebawah
                //}
          }if (suhu<= 30 && lux <=200) { // suhu normal kembali dan cahaya kurang
              //for (pos; pos <=0; pos-=1){
                 myservo.write(180); // atap membuka menghadap keatas           
                // delay(15);
                 digitalWrite (pinRelay,HIGH);// ungu menyala
              //}
          } /*if (lembap < 80 && hujan== 0){
            myservo.write(180);//atap membuka menghadap keatas
            Serial.println("sedanghujan");*/
//sendDataToThingsBoard
tb.sendTelemetryInt("temperature",suhu);
tb.sendTelemetryFloat("Humudity",lembap);
tb.sendTelemetryInt("Lux",lux);
Serial.print("temp");
Serial.print(suhu);
Serial.print("hum");
Serial.print(lembap);

tb.loop();

tb.loop();
  
}