I am creating an app controlled light using ESP32 with Firebase Realtime Database. My problem is the connection between ESP32 and Firebase/Internet is not stable. For instance. 10 Seconds the connection is Good after that connection refused. Then reconnect and so on. Does anybody have an idea or facing this problem and solved it. Thanks..
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <Servo.h>
#define WIFI_SSID "###"
#define WIFI_PASSWORD "###"
#define API_KEY "###"
#define DATABASE_URL "###"
#define USER_EMAIL "###"
#define USER_PASSWORD "###"
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
unsigned long sendDataPrevMillis = 0;
const int relayPin = 2; // GPIO pin where your relay is connected
void setup()
{
Serial.begin(115200);
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();
/* 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;
// Comment or pass false value when WiFi reconnection will control by your code or third party library e.g. WiFiManager
Firebase.reconnectNetwork(true);
// Since v4.4.x, BearSSL engine was used, the SSL buffer need to be set.
// Large data transmission may require larger RX buffer, otherwise connection issue or data read time out can be occurred.
fbdo.setBSSLBufferSize(4096 /* Rx buffer size in bytes from 512 - 16384 */, 1024 /* Tx buffer size in bytes from 512 - 16384 */);
// Limit the size of response payload to be collected in FirebaseData
fbdo.setResponseSize(2048);
Firebase.begin(&config, &auth);
Firebase.setDoubleDigits(5);
config.timeout.serverResponse = 10 * 1000;
pinMode(relayPin, OUTPUT);
}
void loop()
{
// Firebase.ready() should be called repeatedly to handle authentication tasks.
if (Firebase.ready() && (millis() - sendDataPrevMillis > 1000 || sendDataPrevMillis == 0))
{
sendDataPrevMillis = millis();
int lightState;
if(Firebase.RTDB.getInt(&fbdo, "/light", &lightState)){
digitalWrite(relayPin, lightState);
}else{
Serial.println(fbdo.errorReason().c_str());
}
}
}