#include <Arduino.h>
// Wifi untuk menyambungkan ESP ke Jaringan internet
#include <WiFi.h>
// import library time
#include <ESP32Time.h>
// Firebase ESP Client dari library yang diunduh melalui platform io, membuat esp sebagai client yang mengirimkan data ke server(firebase)
#include "FirebaseESP32.h"
// Provide the token generation process info
#include "addons/TokenHelper.h"
// Insert your netword credentials
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// users email and password in firebase
#define USER_EMAIL "[email protected]"
#define USER_PASSWORD "sempakdewazeusgacor"
// Inert Firebase project API key
#define API_KEY "AIzaSyAJ2cuB_Und1oKlEvjD8-vijWrh0jDKj2c"
// Insert RTDB URLefine the RTDB URL
#define DATABASE_URL "https://kelompok1-soilmoist-iot-e7b80-default-rtdb.firebaseio.com"
// Define Firebase Data Object
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
// bagian dari library movingAVG
const int zone_1_pin = 34; // VP OR A0
// const int zone_2_pin = 33; // D33 OR A5
// const uint8_t PHOTOCELL_PIN_ZONE_1(zone_1_pin);
// MovingAverage photoCell(10);
const int dry = 2700; // dry = max = 2700
const int wet = 0; // wet = min = 0
String uid = "";
// ESP32Time rtc;
ESP32Time rtc(0); // offset in seconds GMT+0
void connectingWifi()
{
// method ini berfungsi untuk mengkoneksikan esp ke jaringan WIFI
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Try to Connecting Wi-fi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(1000);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
}
void setUpFirebase()
{
// Method ini berfungsi untuk melalukan setting awal dan koneksi ke firebase
// Assign the api key (required)
config.api_key = API_KEY;
// Assign the RTDB URL (required)
config.database_url = DATABASE_URL;
/* Assign the user sign in credentials */
auth.user.email = USER_EMAIL;
auth.user.password = USER_PASSWORD;
// sign up for anonymous
// if (Firebase.signUp(&config, &auth, "", ""))
// {
// Serial.println("Sign Up berhasil");
// signupOK = true;
// }
// else
// {
// Serial.printf("%s\n", config.signer.signupError.message.c_str());
// }
// Assign the callback function for the long running token generation task
config.token_status_callback = tokenStatusCallback; // see addons/TokenHelper.h
Firebase.begin(&config, &auth);
Firebase.reconnectWiFi(true);
//----------------------------------------------
// Getting the user UID might take a few seconds
//-----------------------------------------------
Serial.println("Getting User UID");
while ((auth.token.uid) == "")
{
Serial.print('.');
delay(1000);
}
//-----------------
// Print user UID
//------------------
uid = auth.token.uid.c_str();
Serial.print("User UID: ");
Serial.println(uid);
if (uid != "")
{
Serial.println("Sign Up berhasil");
}
}
int getSensorData(int sensor_pin)
{
// method ini berfungsi untuk membaca nilai analog dari sensor berdasarkan pin yang terkoneksi
int value = analogRead(sensor_pin);
// int value_avg = photoCell.reading(value);
return value;
}
int map_value(int value)
{
// method ini berfungsi untuk mengembalikan nilai sensor dalam bentuk 0-100 (%)
return map(value, wet, dry, 100, 0);
}
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200);
// pinMode(zone_1_pin, OUTPUT);
// pinMode(zone_2_pin, OUTPUT);
// pinMode(PHOTOCELL_PIN_ZONE_1, INPUT_PULLUP);
// photoCell.begin();
pinMode(zone_1_pin, OUTPUT);
// setTime();
// rtc.setTime(0, 10, 20, 30, 11, 2023); 30th November 2023 20:10:0
rtc.setTime(0, 10, 20, 20, 11, 2023); // set current time before upload code
// mencoba koneksi ke wifi
connectingWifi();
// setting firebase
setUpFirebase();
Serial.println("Complete!!! Start the program");
}
void loop()
{
if (Firebase.ready())
{
Serial.println("------------Prepare to Send Data-------------");
// get current timestamp
FirebaseJsonArray timestamp;
timestamp.add("date", rtc.getDay());
timestamp.add("month", rtc.getMonth() + 1);
timestamp.add("year", rtc.getYear());
timestamp.add("hour", rtc.getHour(true));
timestamp.add("minut", rtc.getMinute());
timestamp.add("sec", rtc.getSecond());
timestamp.add("epoch", rtc.getEpoch());
Serial.println("Step 0");
// start prepare data from zone 1
// get data from zone 1
int zone_1_data = getSensorData(zone_1_pin);
int zone_1_data_percent = map_value(zone_1_data);
Serial.println("Step 0.1");
// create json data for zone 1
FirebaseJson zone_1_json;
zone_1_json.add("zone", "Zone 1");
zone_1_json.add("sensor_type", "Soil Moisture");
Serial.println("Step 1");
zone_1_json.add("timestamp", timestamp);
Serial.println("Step 2");
FirebaseJson zone_1_sensor_value;
zone_1_sensor_value.add("raw_value", zone_1_data);
zone_1_sensor_value.add("percent_value", zone_1_data_percent);
zone_1_json.add("sensor_value", zone_1_sensor_value);
Serial.println("Step 3");
// Convert the JSON object to a string
String jsonString;
zone_1_json.toString(jsonString);
Serial.println("Step 4");
Serial.println(jsonString);
// complete prepare data from zone 1
Serial.println("------------Sending Data-------------");
// Write an Int number on the database path test/int
// if (Firebase.pushJSON(fbdo, "soil_zone_1", zone_1_json))
// {
// Serial.println("PASSED");
// Serial.print("PATH: ");
// Serial.println(fbdo.dataPath());
// Serial.print("TYPE: ");
// Serial.println(fbdo.dataType());
// }
// else
// {
// Serial.println("FAILED");
// Serial.print("REASON: ");
// Serial.println(fbdo.errorReason());
// }
}
Serial.println("============================================");
delay(10000);
}