#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// --- CẤU HÌNH WIFI ---
const char* ssid = "Wokwi-GUEST"; // Thay bằng SSID của bạn nếu chạy thực tế
const char* password = "";
// --- LINK FIREBASE CỦA TUẤN (Thêm .json ở cuối) ---
const String firebase_url = "https://dash--board-iot-d3a52-default-rtdb.asia-southeast1.firebasedatabase.app/.json";
const int ledPin = 2; // Thường ESP32 dùng chân GPIO 2 cho LED onboard
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Kết nối WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n>>> KET NOI WIFI THANH CONG!");
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
// Bắt đầu kết nối tới Firebase qua REST API
http.begin(firebase_url);
int httpCode = http.GET(); // Lấy dữ liệu về
if (httpCode > 0) {
String payload = http.getString();
// Khởi tạo bộ nhớ cho JSON (tăng lên 1024 để an toàn)
StaticJsonDocument<1024> doc;
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
// 1. LẤY DỮ LIỆU CẢM BIẾN (Để in lên Serial)
// Chú ý: Ép kiểu float vì trong Python bạn gửi định dạng ".1f"
float temp = doc["temperature"].as<float>();
float humi = doc["humidity"].as<float>();
int light = doc["light"].as<int>();
// 2. LẤY TRẠNG THÁI ĐIỀU KHIỂN (Từ nhánh "devices")
// Dựa trên hàm send_to_firebase trong hình trước của bạn
String lamp_status = doc["devices"]["lamp"].as<String>();
lamp_status.trim();
// IN RA SERIAL MONITOR ĐỂ KIỂM TRA
Serial.println("--- DỮ LIỆU TỪ FIREBASE ---");
Serial.printf("Temp: %.1f°C | Humi: %.1f%% | Light: %d\n", temp, humi, light);
Serial.print("Trạng thái đèn: ["); Serial.print(lamp_status); Serial.println("]");
// 3. ĐIỀU KHIỂN LED
if (lamp_status == "ON") {
digitalWrite(ledPin, HIGH);
Serial.println("===> THIẾT BỊ: BẬT");
} else {
digitalWrite(ledPin, LOW);
Serial.println("===> THIẾT BỊ: TẮT");
}
} else {
Serial.print("Lỗi giải mã JSON: ");
Serial.println(error.c_str());
}
} else {
Serial.printf("Lỗi kết nối HTTP: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(3000); // Đợi 3 giây rồi cập nhật tiếp
}