#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* FIREBASE_HOST = "tt-iothuykhaliem-default-rtdb.firebaseio.com";
const char* FIREBASE_AUTH = "0HQ5s8qyOApgXNdDDqpb06n9zXj1ZvphspXqp8bA";
const char* databaseURL = "https://tt-iothuykhaliem-default-rtdb.firebaseio.com/data2.json";

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

DHT dht(DHT_PIN, DHT22);

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

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();

  Wire.begin(21, 22);  // SDA pin 21, SCL pin 22

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // I2C address 0x3C
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
}

void loop() {
  delay(1000); // Wait for the sensor to stabilize
  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 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();

    // Display temperature and humidity on OLED
    display.clearDisplay();
    display.setTextSize(1.25);
    display.setCursor(0, 10);
    display.print("Temp: ");
    display.print(temperature);
    display.println(" C");
    display.setCursor(0, 40);
    display.print("Humidity: ");
    display.print(humidity);
    display.println(" %");
    display.display();
  } else {
    Serial.println("Failed to read from DHT sensor");
  }

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