FirebaseExtended / firebase-arduino

Arduino samples for Firebase.
Apache License 2.0
943 stars 494 forks source link

How to convert my current code work from RTDB to Firestore through your library? #557

Open abddi opened 1 year ago

abddi commented 1 year ago

Hi guys, Actually chatgpt recommended I work with your library to convert my current project to work with Firesotre in the same process that i'm doing with RTDB but i couldn't figure it out where to start!!

So here is my work and hope some of you can help me to convert it from RTDB to Firestore:

#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <Firebase_ESP_Client.h>
#include <addons/TokenHelper.h>  //Provide the token generation process info.
#include <addons/RTDBHelper.h>   //Provide the RTDB payload printing info and other helper functions.

/* 1. Define the WiFi credentials */
//#define WIFI_SSID "Abdallah Agha"
//#define WIFI_PASSWORD "abdallah123"
/* 2. Define the API Key */
/* 2. Define the API Key */
#define API_KEY "********************************"
/* 3. Define the RTDB URL */
#define DATABASE_URL "*************************************"
/* 4. Define the user Email and password that alreadey registerd or added in your project */
#define USER_EMAIL "me@test.com"
#define USER_PASSWORD "123456"

#define USONIC_DIV 0.034

//Define Firebase Data object
FirebaseData stream;
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

String uid;
String path;
const int trigPin = D1;
const int echoPin = D2;

long duration;
int oldDistance;

#define PUMP1 2
//#define PUMP2 4

//------------
//SENSOR
//------------
int readDistance() {
  long dur;
  long dis;
  int percentage;

  // Transmitting pulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Waiting for pulse
  dur = pulseIn(echoPin, HIGH);

  dis = dur * USONIC_DIV/2;

  //190cm (2500L) is our 0 percentage: ya3ni bs yosal mostawa el mai lal 218cm (ya3ni bs yeb3ed 3an el sensor 218cm) hek el tank bkoon fedi
  //30 is our 1800 percentage: ya3ni lama etgareb el mai w tseer bainha w bean el sensor 30cm hek full 
  //percentage = map(dis, 218, 20, 0, 1800);

  //190cm (2500L) is our 0 percentage: ya3ni bs yosal mostawa el mai lal 200cm (ya3ni bs yeb3ed 3an el sensor 200cm) hek el tank bkoon fedi
  //30 is our 1800 percentage: ya3ni lama etgareb el mai w tseer bainha w bean el sensor 30cm hek full 
  percentage = map(dis, 190, 30, 0, 2500);

  if(percentage < 0){
    percentage = 0;
  } else if (percentage > 2500){
    percentage = 2500;
  }

  return percentage; 
}

//-------------------
//Firebase RTDB Sensor
//-------------------

bool setDistanceValue(int distance) {

  //----------------------------
  // RTDB mainTankLitersAmount
  //----------------------------

  path = "users/" + uid + "/roofTanks" "/1" "/mainTankLitersAmount";
  Serial.print("Update sensor state as int... " );
  if (Firebase.RTDB.set(&fbdo, path.c_str(), distance)) {    
    Serial.println("ok");
    return true;
  }
  Serial.println(fbdo.errorReason().c_str());
  return false;
}

// This is the callback function called when stream from firebase was received (every time data has changed)
void streamCallback(FirebaseStream data)
{
  Serial.println("\nStream data available...");
  Serial.println("STREAM PATH: " + data.streamPath());
  Serial.println("EVENT PATH: " + data.dataPath());
  Serial.println("DATA TYPE: " + data.dataType());
  Serial.println("EVENT TYPE: " + data.eventType());

  if (data.dataType() == "boolean")
  {
    digitalWrite(PUMP1, data.boolData());
  }

  if (data.dataType() == "string")
  {
    if (data.stringData() == "on") {
      digitalWrite(D0, HIGH);
      Serial.println("Sensor ON");
      // Update RTDB online data about sensor distance
      int distance = readDistance();
      setDistanceValue(distance);
    }
    if (data.stringData() == "off") {
      digitalWrite(D0, LOW);      
      Serial.println("Sensor OFF");
    }
  }
}

void streamTimeoutCallback(bool timeout)
{
  if (timeout)
    Serial.println("stream timed out, resuming...\n");
  if (!stream.httpConnected())
    Serial.printf("error code: %d, reason: %s\n\n", stream.httpCode(), stream.errorReason().c_str());
}

void setup()
{
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  pinMode(PUMP1, OUTPUT);

  Serial.begin(115200);
//-------------------Wifi Manager Work-----------------

  WiFiManager wifiManager;
  wifiManager.autoConnect("i-Device");

  Serial.println("Connectted....");

  Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION);

  /* Assign the api key (required) */
  config.api_key = API_KEY;

  /* Assign the user sign in credentials */
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;

  /* Assign the RTDB URL (required) */
  config.database_url = DATABASE_URL;

  /* 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);

  //Recommend for ESP8266 stream, adjust the buffer size to match your stream data size
  stream.setBSSLBufferSize(2048 /* Rx in bytes, 512 - 16384 */, 512 /* Tx in bytes, 512 - 16384 */);

  //----------------------------------------------
  // 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);
  path = "users/" + uid;

  // Set the stream callback (every change in data related to path, will trig the callback function)
  if (!Firebase.RTDB.beginStream(&stream, path.c_str()))
    Serial.printf("sream begin error, %s\n\n", stream.errorReason().c_str());

  Firebase.RTDB.setStreamCallback(&stream, streamCallback, streamTimeoutCallback);

  // Write some test data in RTDB

  //------------------
  //ESP LIGHT (PUMP 1)
  //------------------
  if (Firebase.ready())
  {
    //---------------------------
    //RTDB espLight
    //---------------------------

    path = "users/" + uid + "/roofTanks" "/1" "/espLight";
    Serial.print("Set initial espLight state as bool... " );
    if (Firebase.RTDB.setBool(&fbdo, path.c_str(), true))
      Serial.println("ok");
    else
      Serial.println(fbdo.errorReason().c_str());

    //------------------
    //RTDB status
    //------------------

    path = "users/" + uid + "/roofStatus" "/status";
    Serial.print("Set initial roof tank state as int... " );
    if (Firebase.RTDB.setString(&fbdo, path.c_str(), "on"))
      Serial.println("ok");
    else
      Serial.println(fbdo.errorReason().c_str());

    Serial.print("Set initial sensor state as int... " );
    int distance = readDistance();
    setDistanceValue(distance);
  }

}

void loop()
{
  // Check distance, if value is different from last state, update RTDB
  // In order to avoid continuous writing at every minimum variation, 
  // is possible to define a minimum offset for example 1%)

  int distance = readDistance();      // get actual distance
 // if (abs(distance - oldDistance) > 1 )
   if (abs(distance - oldDistance) > 1  &&  digitalRead(D1) )   // check also if sensor is enabled
  {
     oldDistance = distance;
     setDistanceValue(distance);      // Send to RTDB only if change
  }

  // Need to be called in order to check if stream data is avalaible
  if (Firebase.ready())
  {
    if (!Firebase.RTDB.readStream(&fbdo))
      Serial.printf("sream read error, %s\n\n", fbdo.errorReason().c_str());

    if (fbdo.streamTimeout())
    {
      Serial.println("stream timed out, resuming...\n");
      if (!fbdo.httpConnected())
        Serial.printf("error code: %d, reason: %s\n\n", fbdo.httpCode(), fbdo.errorReason().c_str());
    }
  }
}