Reducing firebase latency by only sending changed value?

Viewed 520

I am using an Wemos D1 Mini (Arduino) to send sensor data to Firebase. It is one value I'm sending. I found that this makes the program slow down, so the sensor isn't able to get the data as fast, as data is being sent (which is kind of obvious).

Anyhow, I want to send the value to Firebase only when this value changed its property. It is an int value, but I'm not sure how to go around this. Should I use a listener? This is a portion of my code:

int n = 0; // will be used to store the count
Firebase.setInt("Reps/Value", n); // sends value to fb
delay(100); // Wait 1 second and scan again

I was hoping that the sensor could scan every second, which it does. But at this rate (pun intended) the value is being pushed every second to FB. This slows down the scanning to every 3 seconds. How can I only use the firebaseSetInt method when n changes its value?

2 Answers

Coming from a professional use of remote databases, you should go for a gliding average approach. You do this by creating a circle buffer with lets say 30 sensor values and calculate an average value. As long as a value is +/- 3% within the average recorded at time0 you do not update. If the value is above or under you send to Firebase and set a new time0 average. Depending on your precision and needs you ease the stress on the systems.
Imho only life safers like current breakers or flow cutting (liquids) have to be real time, all hobby applications like measuring wind speed, heating etc are well designed with 20 - 60 sec intervals.
The event listener by the way is this approach, just do something if its out of the norm. If you have a fixed target value as a reference its much easier to check for the +/- difference. If the pricing of FB changes it will be an issue for devs - so plan ahead.

You can check after every reading every new value whether the value has been changed or not by adding just a simple conditional statement.

int n = 0; // will be used to store the count
int n_old; // old value saved to fb
if(n!=n_old)   {  //checks whether value is changed
   Firebase.setInt("Reps/Value", n); // sends value to fb
   n_old = n;  // updates the old value to the last updated
}

delay(100); // Wait 1 second and scan again

Or if you want to go for a tolerance approach, you can further do something like this:

int n = 0; // will be used to store the count
int n_old; // old value saved to fb
int tolerance = 3;  // tolerance upto 3%
if(abs((n-n_old)/((n+n_old)/2))*100 > tolerance)   {
   Firebase.setInt("Reps/Value", n); // sends value to fb
   n_old = n;  // updates the old value to the last updated
}

delay(100); // Wait 1 second and scan again
Related