// #if defined(ESP32)
#include <WiFi.h>
#include <FirebaseESP32.h>
// #elif defined(ESP8266)
// #include <ESP8266WiFi.h>
// #include <FirebaseESP8266.h>
// #endif
//Provide the token generation process info.
#include <addons/TokenHelper.h>
//Provide the RTDB payload printing info and other helper functions.
#include <addons/RTDBHelper.h>
/* 1. Define the WiFi credentials */
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
//For the following credentials, see examples/Authentications/SignInAsUser/EmailPassword/EmailPassword.ino
/* 2. Define the API Key */
#define API_KEY "AIzaSyAnYaDHj1Yu2WH40H4n1Ji5t4h4WIRrES8"
/* 3. Define the RTDB URL */
#define DATABASE_URL "https://firedetector-94e12-default-rtdb.asia-southeast1.firebasedatabase.app/" //<databaseName>.firebaseio.com or <databaseName>.<region>.firebasedatabase.app
#define redPin T2
//Define Firebase Data object
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
int powerValue;
void setup()
{
pinMode(redPin, OUTPUT);
Serial.begin(115200);
delay(2000);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION);
/* Assign the api key (required) */
config.api_key = API_KEY;
config.database_url = DATABASE_URL;
//////////////////////////////////////////////////////////////////////////////////////////////
//Please make sure the device free Heap is not lower than 80 k for ESP32 and 10 k for ESP8266,
//otherwise the SSL connection will fail.
//////////////////////////////////////////////////////////////////////////////////////////////
Firebase.begin(DATABASE_URL, API_KEY);
//Comment or pass false value when WiFi reconnection will control by your code or third party library
Firebase.reconnectWiFi(true);
Firebase.setDoubleDigits(5);
}
void loop()
{
if (Firebase.ready())
{
if (Firebase.RTDB.get(&fbdo, "/devices/lalang")) {
Serial.println("sudah ada di database");
if (Firebase.RTDB.getInt(&fbdo, "/devices/lalang/power")) {
if (fbdo.dataType() == "int") {
powerValue = fbdo.intData();
if(powerValue == 1){
digitalWrite(redPin, HIGH);
}
if(powerValue == 0){
digitalWrite(redPin, LOW);
}
}
}
else {
Serial.println(fbdo.errorReason());
}
}
else {
//ketika belum ada device di database
Serial.println("belum ada di database");
createDBNode();
}
delay(1000);
}
}
void createDBNode() {
// fungsi untuk setup device pertama kali di database
Firebase.RTDB.setInt(&fbdo, "devices/lalang/sensorApi", 0);
Firebase.RTDB.setInt(&fbdo, "devices/lalang/sensorGas", 0);
Firebase.RTDB.setInt(&fbdo, "devices/lalang/power", 1);
Firebase.RTDB.setString(&fbdo, "devices/lalang/alamat", "Musuk");
}