#include <WiFi.h>
  #include <DHT.h>
  #include <FirebaseESP32.h>
  #include <HTTPClient.h>
//#include "addons/TokenHelper.h"
//#include "addons/RTDBHelper.h"
  #include <ESP32Servo.h>

const int servoPin = 27;

Servo servo;

const char* ssid = "Wokwi-GUEST";
const char* password = "";

#define FIREBASE_HOST "https://sistem-monitoring-da624-default-rtdb.firebaseio.com/"
#define FIREBASE_AUTH "AIzaSyDHSAZoCxh_KDD-DdewiLIsZ7NXWUlVmAo"

#define TRIG_PIN 18 // ESP32 pin GIOP23 connected to Ultrasonic Sensor's TRIG pin
#define ECHO_PIN 5 // ESP32 pin GIOP22 connected to Ultrasonic Sensor's ECHO pin
float durasi, jarak;
#define DHTTYPE DHT22
#define DHTPIN 13
#define led  14



FirebaseData fbdo;
FirebaseJson json;

void wifiConnection(){
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(500);
  }
  Serial.println("Wifi Connected");
  Serial.println(WiFi.SSID());
  Serial.println(WiFi.RSSI());
  Serial.println(WiFi.macAddress());
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.gatewayIP());
  Serial.println(WiFi.dnsIP());
}

DHT dht(DHTPIN, DHTTYPE);

void firebase(void) {
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);
}

float ultra(){
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
 
  
  durasi = pulseIn(ECHO_PIN, HIGH);
  
  // calculate the distance
  jarak = 0.017 * durasi;
  return jarak;
}

void setup() {
  Serial.begin(115200);
  wifiConnection();
  dht.begin();
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(led, OUTPUT);
  servo.attach(servoPin);
  firebase();
}
void kirim() {
  // Kirim data ke Firebase (contoh menggunakan String)
  int angka = 200;
  Firebase.setInt(fbdo, "/nilai/angka", angka);
}

void terima() {
  // Ambil data dari Firebase (contoh pengambilan String)
  if (Firebase.getInt(fbdo, "/nilai/angka")) {
   if(fbdo.intData()){
    Serial.print("data dari firebase : ");
    Serial.println(fbdo.intData());
   }
  }
}


void loop() {
  float nilai_jarak=ultra();
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  Firebase.setFloat(fbdo, "/suhu", t);
  Firebase.setFloat(fbdo, "/lembab", h);
  Firebase.setFloat(fbdo, "/jarak", nilai_jarak);
  kirim();
  terima();
  //  if (Firebase.getString(fbdo, "/LED")== 0){
  //    digitalWrite(led, fbdo.intData());
  //    Serial.println("mati");
  //  }
  //  else if(Firebase.getString(fbdo, "/LED")==1){
  //   digitalWrite(led, fbdo.intData());
  //   Serial.println("nyala");
  // }
  // if(h>=50 && t>=50){
  //   servo.write(180);
  // }
  // else{
  //   servo.write(0);
  // }
  
}