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


#include "ThingsBoard.h"
#include "DHTesp.h"

#include <Servo.h>

Servo myservo;  

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

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

// See https://thingsboard.io/docs/getting-started-guides/helloworld/
// to understand how to obtain an access token
#define TOKEN               ".."
#define THINGSBOARD_SERVER  "thingsboard.cloud"


// Baud rate for debug serial
#define SERIAL_DEBUG_BAUD   115200

#define LDR_PIN 34
const int DHT_PIN = 15;
int led = 0;
DHTesp dhtSensor;

const float GAMMA = 0.7;
const float RL10 = 50;

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

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();
  pinMode(2, OUTPUT);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  pinMode(LDR_PIN, INPUT);
  // s
  myservo.attach(4);
}

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

  // LDR
  int analogValue = analogRead(34);
  float voltage = analogValue / 4096. * 5;
  float resistance = 2000 * voltage / (1 - voltage / 5);
  float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));

  Serial.println(lux);
  // Serial.println(analogValue);
  tb.sendTelemetryFloat("light", lux);

  // DHT
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  tb.sendTelemetryInt("temperature", data.temperature);
  tb.sendTelemetryFloat("humidity", data.humidity);
  tb.sendTelemetryInt("led", led);
  Serial.print("Suhu : ");
  Serial.print(data.temperature);
  Serial.print(" Kelembaban : ");
  Serial.print(data.humidity);
  Serial.print(" Cahaya : ");
  Serial.println(lux);
  // suhu ideal tanaman tomat 24 - 29
  // intensitan cahaya ideal : 10.000-30.000 
  if(lux >= 10000 && lux <= 30000 && data.temperature >= 24 && data.temperature <=29){
    myservo.write(90);    
    digitalWrite(2, HIGH);
    led = 1;
  }
  else{
    digitalWrite(2, LOW);
    led = 0;
    myservo.write(0);    
  }
  tb.loop();

  tb.loop();
}