#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>


const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* FIREBASE_HOST = "test-10e37-default-rtdb.firebaseio.com";
const char* FIREBASE_AUTH = "uyWibhaFFHuOEaBj5rCOaBkXSiSRLRqoU2cAVpGg";
const char* databaseURL = "https://test-10e37-default-rtdb.firebaseio.com/data2.json";


#define LED 12
#define DHT_PIN 5  
DHT dht(DHT_PIN, DHT22);

LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  pinMode(LED, OUTPUT);
  dht.begin();
  LCD.init(); 
  LCD.backlight();
  Wire.begin(22, 21);  
}

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

  if (!isnan(humidity) && !isnan(temperature)) {
    Serial.printf("Humidity: %.2f%%, Temperature: %.2f°C\n", humidity, temperature);
    String data = String("{\"temperature\": ") + String(temperature) + String(", \"humidity\": ") + String(humidity) + String("}");

    HTTPClient http;
    http.begin(databaseURL);
    http.addHeader("Content-Type", "application/json");
    http.addHeader("Authorization", FIREBASE_AUTH);

    int httpResponseCode = http.PUT(data);

    if (httpResponseCode > 0) {
      Serial.print("Data sent successfully, response code: ");
      Serial.println(httpResponseCode);
    } else {
      Serial.print("Error sending data, response code: ");
      Serial.println(httpResponseCode);
    }

    http.end();

    LCD.setCursor(0, 0);
    LCD.print("Temperature: " + String(temperature));

    LCD.setCursor(0, 1);
    LCD.print("Humidity" +  String(humidity));
  } else {
    Serial.println("Failed to read from DHT sensor");
  }

  delay(500); 
}