How to get ultrasonic sensor data when value is ON from Firebase?

Hi everybody :wave:,

I actually succeeded in set data and works perfectly through my code but just for once, when i turn the value to OFF then back to ON it wont read!

I'm trying to get ultrasonic sensor data when the LED light is ON and not get it when it's OFF from Firebase through a stream, does anyone have an idea how it could be done?

Please note both of LED lights in code works perfectly but the sensor read once.

Here is my code:

#include <ESP8266WiFi.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 */
#define API_KEY "AIza********************************"
/* 3. Define the RTDB URL */
#define DATABASE_URL "https://s************************"
/* 4. Define the user Email and password that alreadey registerd or added in your project */
#define USER_EMAIL "a@a.com"
#define USER_PASSWORD "123456"

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

String uid;
String path;
const int trigPin = D5; 
const int echoPin = D6; 

long duration;
int distance;

#define PUMP1 2
//#define PUMP2 4

// 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(D1, HIGH);
       // Transmitting pulse
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      Serial.println("Sensor ON");
    }
    if (data.stringData() == "off") {
      digitalWrite(D1, LOW);
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, LOW);
      delayMicroseconds(10);
      digitalWrite(trigPin, 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);
  Serial.print("Connecting to Wi-Fi");

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  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;

  /* 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 = "esp/" + 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())
  {
    path = "esp/" + uid + "/espLight";
    Serial.print("Set initial pump 1 state as bool... " );
    if (Firebase.RTDB.setBool(&fbdo, path.c_str(), true))
      Serial.println("ok");
    else
      Serial.println(fbdo.errorReason().c_str());

  //------------------
  //LED LIGHT
  //------------------
    path = "esp/" + uid + "/ledLight";
    Serial.print("Set initial pump 2 state as String... " );
    if (Firebase.RTDB.setString(&fbdo, path.c_str(), "on"))
      Serial.println("ok");
    else
      Serial.println(fbdo.errorReason().c_str());

  //------------
  //SENSOR
  //------------
  
  long t = 0, h = 0, hp = 0;
  
  // Waiting for pulse
  t = pulseIn(echoPin, HIGH);
  
  // Calculating distance 
  h = t / 58;
 
  h = h - 6 ;  // offset correction
  h = 20 - h;  // water height, 0 - 50 cm
  
  distance = 5 * h;  // distance in %, 0-100 %

   path = "esp/" + uid + "/sensor";
    Serial.print("Set initial sensor state as int... " );
    if (Firebase.RTDB.set(&fbdo, path.c_str(), distance))
      Serial.println("ok");
    else
      Serial.println(fbdo.errorReason().c_str());

  }

}

void loop()
{
  // 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());
    }
  }
}