#include <ESP32Firebase.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include <WiFi.h>

// Define DHT sensor type and pin
#define DHTTYPE DHT22
#define DHTPIN 15

// Define pins for HC-SR04
#define TRIGPIN 17
#define ECHOPIN 16
#define MAX_DISTANCE 400  // Maximum distance we want to measure (in centimeters)

DHT dht(DHTPIN, DHTTYPE);

#define LDR_PIN 14

#define _SSID "Professor Moriarty"                                        // Your WiFi SSID
#define _PASSWORD "who are you?"                                          // Your WiFi Password
#define REFERENCE_URL "https://webapp-1ec8a-default-rtdb.firebaseio.com"  // Your Firebase project reference URL

long duration;  // Variable to store the duration of the echo pulse
int distanceCm; // Variable to store the distance in centimeters

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

Firebase firebase(REFERENCE_URL);

void setup() {
  Serial.begin(9600);

  pinMode(TRIGPIN, OUTPUT); // Set trigPin as OUTPUT
  pinMode(ECHOPIN, INPUT);  // Set echoPin as INPUT

  pinMode(LDR_PIN, INPUT);

  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(1000);

  // Connect to WiFi
  Serial.println();
  Serial.println();
  Serial.print("Connecting to: ");
  Serial.println(_SSID);
  //WiFi.begin(_SSID, _PASSWORD);
  WiFi.begin("Wokwi-GUEST", "", 6); // Uncomment this if you are using Wokwi-GUEST

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print("-");
  }

  Serial.println("");
  Serial.println("WiFi Connected");

  // Print the IP address
  Serial.print("IP Address: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

  dht.begin();
  
  // Configure ADC resolution
  analogReadResolution(12); // Ensure 12-bit resolution
}

void loop() {
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();

  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("Failed to read from DHT sensor!");
  } else {
    if (firebase.setInt("/humidity", (int)humidity) && firebase.setInt("/temperature", (int)temperature)) {
      Serial.println("Successfully wrote temperature and humidity values");
    } else {
      Serial.println("Failed to write temperature and humidity values");
    }
  }

  digitalWrite(TRIGPIN, LOW);
  delayMicroseconds(2);

  // Trigger the sensor by setting the trigPin HIGH for 10 microseconds
  digitalWrite(TRIGPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW);

  // Read the echoPin and calculate the duration of the echo pulse
  duration = pulseIn(ECHOPIN, HIGH);

  // Calculate the distance in centimeters
  distanceCm = duration * 0.0343 / 2;

  // Write distance value to Firebase
  if (firebase.setInt("/distance", (int)distanceCm)) {
    Serial.println("Successfully wrote distance value");
  } else {
    Serial.println("Failed to write distance value");
  }

  int analogValue = analogRead(LDR_PIN);
  Serial.print("Analog Value: ");
  Serial.println(analogValue);

  // Convert analog reading to voltage (assuming 12-bit resolution and 3.3V reference)
  float voltage = analogValue / 4095.0 * 3.3;
  Serial.print("Voltage: ");
  Serial.println(voltage);

  // Check if voltage is within expected range
  if (voltage > 0 && voltage < 3.3) {
    float resistance = 2000 * voltage / (1 - voltage /3.3);; // Adjusted the formula
    Serial.print("Resistance: ");
    Serial.println(resistance);

    if (resistance > 0) {
      float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
      Serial.print("Lux: ");
      Serial.println(lux);

      if (isnan(lux)) {
        Serial.println("Lux calculation resulted in NaN");
      } else {
        if (firebase.setFloat("/lux", lux)) {
          Serial.println("Successfully wrote lux value");
        } else {
          Serial.println("Failed to write lux value");
        }
      }
    } else {
      Serial.println("Invalid resistance value, unable to calculate lux");
    }
  } else {
    Serial.println("Voltage out of expected range");
  }

  delay(1000); // Adjust delay as needed
}
esp:0
esp:1
esp:2
esp:3
esp:4
esp:5
esp:6
esp:7
esp:8
esp:9
esp:10
esp:11
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:20
esp:21
esp:26
esp:33
esp:34
esp:35
esp:36
esp:37
esp:38
esp:39
esp:40
esp:41
esp:42
esp:45
esp:46
esp:3V3
esp:5V
esp:GND.1
esp:TX
esp:RX
esp:RST
esp:GND.2
dht1:VCC
dht1:SDA
dht1:NC
dht1:GND
ultrasonic1:VCC
ultrasonic1:TRIG
ultrasonic1:ECHO
ultrasonic1:GND
ldr1:VCC
ldr1:GND
ldr1:DO
ldr1:AO