#define gas 5
#define buzzer 34
#define light 19
#define LED 14
#define LED2 13
#define LED3 26
int valueGas ;


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


const int DHTPIN = 15;
const int DHTTYPE = DHT22;
DHT dht(DHTPIN,DHTTYPE);



#define FIREBASE_HOST "pt-iot-b7ba2-default-rtdb.firebaseio.com/"
#define FIREBASE_AUTH "xYugVpRqWqgzRDaCtMChEvgzVHyQI675Zi2PQaU3"
FirebaseData firebaseData;

void WIFIConnect() {
  Serial.println("Connecting to SSID: Wokwi-GUEST");
  WiFi.begin("Wokwi-GUEST", "");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("WiFi connected");
  Serial.print(", IP address: ");
  Serial.println(WiFi.localIP());
}

void setup() {
 dht.begin();
 Serial.begin(115200);
 WIFIConnect();
 pinMode(gas,INPUT);
 pinMode(light,INPUT);
 pinMode(LED,OUTPUT);
 pinMode(LED2,OUTPUT);
 pinMode(LED3,OUTPUT);
 pinMode(buzzer,OUTPUT);
 Firebase.begin(FIREBASE_HOST,FIREBASE_AUTH);
 Firebase.reconnectWiFi(true);
 Firebase.setReadTimeout(firebaseData,1000 *60);
 Firebase.setwriteSizeLimit(firebaseData,"tiny");

}

 void Gas(){
  valueGas = analogRead(gas);
 valueGas = 130;
 int tt = digitalRead(gas);
 Serial.print("CAM BIEN GAS :");
 Serial.println(tt);
 Firebase.setInt(firebaseData,"/DuLieu/Gas/GTri",valueGas);
 if(tt == 1){
   Firebase.setInt(firebaseData,"DuLieu/Gas/CB_Gas",1);
   digitalWrite(buzzer, HIGH);
  }else{
       Firebase.setInt(firebaseData,"DuLieu/Gas/CB_Gas",0);
      digitalWrite(buzzer,LOW);
    }
  }

 void Light(){
   int a = digitalRead(light);
  if(a==1){
    digitalWrite(LED,HIGH);
      Serial.println("TROI TOI ");
      Serial.println(a);
    Firebase.setString(firebaseData,"DuLieu/TT/Light","Trời Tối");
    Firebase.setInt(firebaseData,"DuLieu/TT/CB_Led",1);
    }else{
      digitalWrite(LED,LOW);
       Serial.println("TROI SANG ");
        Serial.println(a);
    Firebase.setString(firebaseData,"DuLieu/TT/Light","Trời Sáng");
    Firebase.setInt(firebaseData,"DuLieu/TT/CB_Led",0);
      }
    
  }

void loop() {
 
 float doam = dht.readHumidity();
 float doC = dht.readTemperature();
 if(doC>33 && doC <=50){
   digitalWrite(LED3, HIGH);
 }else{
   digitalWrite(LED3, LOW);
 }
 Serial.println(doam);
 Serial.println(doC);
 Firebase.setInt(firebaseData,"/DuLieu/doam",doam);
  Firebase.setInt(firebaseData,"/DuLieu/doc",doC);
  Gas();
  Light();
delay(300);
 if(Firebase.getInt(firebaseData,"Den/Led")== true){
  int St = firebaseData.to<int>();
  if(St == 1){
    digitalWrite(LED2,HIGH);
    }else if(St == 0){
        digitalWrite(LED2,LOW);
      }
  }
}