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

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* FIREBASE_HOST = "ttiot-890d6-default-rtdb.firebaseio.com";
const char* FIREBASE_AUTH = "wAXeruXt8rwguV5tiYSkSBvbYTAPW4yZ5qs1zUCy";
const char* databaseURL = "https://ttiot-890d6-default-rtdb.firebaseio.com/data.json";

#define DHT_PIN 5  // GPIO pin connected to the DHT22 sensor

DHT dht(DHT_PIN, DHT22);

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");
  dht.begin();
}

void loop() {
  delay(1000); // đợi cảm biến ổn định
  // đọc nhiệt độ và độ ẩm
  
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();

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

    // Send data to Firebase
    String data1 = 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(data1);

    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();
  } else {
    Serial.println("Failed to read from DHT sensor");
  }

  delay(500); // Send data every 0.5 seconds
}