Firebase ESP8266 return Error Connection Loss #281
-
Hello, How should I deal with Firebase connection lost? #if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
//#include <NTPClient.h>
#include <time.h>
#include <Firebase_ESP_Client.h>
//#include <WiFiUdp.h>
//Provide the RTDB payload printing info and other helper functions.
#include <addons/RTDBHelper.h>
/* 1. Define the WiFi credentials */
#define WIFI_SSID "xxx"
#define WIFI_PASSWORD "xxxx"
/* 2. If work with RTDB, define the RTDB URL and database secret */
#define FIREBASE_HOST "xxx"
#define API_KEY "yyy"
#define USER_EMAIL "aaa"
#define USER_PASSWORD "111"
/* 3. Define the Firebase Data object */
FirebaseData fbdo;
/* 4, Define the FirebaseAuth data for authentication data */
FirebaseAuth auth;
/* Define the FirebaseConfig data for config data */
FirebaseConfig config;
const long utcOffsetInSeconds = 25200;
//----------------------------------------Define NTP Client to get time
//WiFiUDP ntpUDP;
//NTPClient timeClient(ntpUDP, "id.pool.ntp.org", utcOffsetInSeconds);
//----------------------------------------
int count = 0;
String arrData[5]; //panjang array = jml data
String DBnm = "ParseSensorDatawithTime";
unsigned long sendDataPrevMillis = 0;
unsigned long sendDataPrevMillis1 = 0;
int LED_1 = 1;
String ActuatorStatus = "";
void setTime(int timezone)
{
// Synchronize time useing SNTP. This is necessary to verify that
// the TLS certificates offered by the server are currently valid.
Serial.print("[TIME] : Setting time using SNTP \n");
//UNIX TIMESTAMP UTC = Total seconds from 1970
configTime(timezone * 3600, 0, "id.pool.ntp.org");
time_t now = time(nullptr);
while (now < 1000)
{
delay(500);
// Serial.print(".");
now = time(nullptr);
}
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
Serial.printf("\n[TIME] : Current time: %s \n", asctime(&timeinfo));
}
void tokenStatusCallback(TokenInfo info);
void setup()
{
pinMode(BUILTIN_LED, OUTPUT);
Serial.begin(9600);
// pinMode(D1, OUTPUT);
// pinMode(D2, INPUT);
// pinMode(D3, OUTPUT);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
}
Serial.println ("");
Serial.println ("WiFi connected.");
Serial.println ("IP address: ");
Serial.println (WiFi.localIP());
delay(500);
setTime(7);
delay(500);
Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION);
/* Assign the certificate file (optional) */
//config.cert.file = "/cert.cer";
//config.cert.file_storage = StorageType::FLASH;
/* Assign the database URL and database secret(required) */
// config.database_url = DATABASE_URL;
// config.signer.tokens.legacy_token = DATABASE_SECRET;
config.host = FIREBASE_HOST;
config.api_key = API_KEY;
delay(500);
auth.user.email = USER_EMAIL;
auth.user.password = USER_PASSWORD;
delay(500);
config.token_status_callback = tokenStatusCallback;
delay(500);
/* Initialize the library with the Firebase authen and config */
Firebase.begin(&config, &auth);
Firebase.reconnectWiFi(true);
delay(500);
//Or use legacy authenticate method
// Firebase.begin(DATABASE_URL, DATABASE_SECRET);
// pinMode(LED_1, OUTPUT);
// delay(1000);
}
void tokenStatusCallback(TokenInfo info)
{
if (info.status == token_status_error)
{
Serial.printf("Token error code: %d, message: %s\n", info.error.code, info.error.message.c_str());
}
if (info.status == token_status_ready)
{
// if (Firebase.setString(fbdo, "/Test123", "Hello World! " ))
// {
// Serial.println("store data ok");
// }
// else
// {
// Serial.println("error, " + fbdo.errorReason());
// Serial.println("------------------------------------");
// Serial.println();
// }
}
else
{
Serial.printf("Token status code: %d\n", info.status);
}
}
void loop(){
if (millis() - sendDataPrevMillis >= 5000){
sendDataPrevMillis = millis();
digitalWrite(BUILTIN_LED, HIGH);
if(Firebase.RTDB.get(&fbdo, "Actuator/status/flag")){ //jika koneksi berhasil
ActuatorStatus = fbdo.to<String>();//kemudian ambil data konversi object fbdo berupa string
Serial.println(ActuatorStatus); //Kirim nilai ActuatorStatus secara serial
}else{
Serial.println("Error Firebase:"+fbdo.errorReason());
// digitalWrite(BUILTIN_LED, LOW);
}
if(ActuatorStatus == "Ya0"){
if (millis() - sendDataPrevMillis1 > 60000){
sendDataPrevMillis1 = millis();
kirimFirebase();
}
}else if(ActuatorStatus == "Ya110"){
if (millis() - sendDataPrevMillis1 > 60000){
sendDataPrevMillis1 = millis();
kirimFirebase();
}
}else if(ActuatorStatus == "Ya111"){
if (millis() - sendDataPrevMillis1 > 60000){
sendDataPrevMillis1 = millis();
kirimFirebase();
}
}else if(ActuatorStatus == "Ya120"){
if (millis() - sendDataPrevMillis1 > 60000){
sendDataPrevMillis1 = millis();
kirimFirebase();
}
}else if(ActuatorStatus == "Ya121"){
if (millis() - sendDataPrevMillis1 > 60000){
sendDataPrevMillis1 = millis();
kirimFirebase();
}
}else if(ActuatorStatus == "Ya130"){
if (millis() - sendDataPrevMillis1 > 60000){
sendDataPrevMillis1 = millis();
kirimFirebase();
}
}else if(ActuatorStatus == "Ya131"){
if (millis() - sendDataPrevMillis1 > 60000){
sendDataPrevMillis1 = millis();
kirimFirebase();
}
}
}
}
void kirimFirebase(){
// Serial.println(ActuatorStatus);
time_t now = time(nullptr);
struct tm* p_timeinfo = localtime(&now);
int monthDay = p_timeinfo->tm_mday;
int currentMonth = p_timeinfo->tm_mon+1;
// String currentMonthName = months[currentMonth-1];
int currentYear = p_timeinfo->tm_year+1900;
String currentDate = String(monthDay) + "-" + String(currentMonth) + "-" + String(currentYear);
String ReverseCurrentDate = String(currentYear) + "-" + String(currentMonth) + "-" + String(monthDay);
// Serial.printf("[NOW] : Time = %s \n", asctime(p_timeinfo));
// Serial.println(currentDate);
String hr, mn, sc;
if (p_timeinfo->tm_hour< 10) {
hr = "0" + String(p_timeinfo->tm_hour);
}
else {
hr = String(p_timeinfo->tm_hour);
}
if (p_timeinfo->tm_min < 10) {
mn = "0" + String(p_timeinfo->tm_min);
}
else {
mn = String(p_timeinfo->tm_min);
}
if (p_timeinfo->tm_sec < 10) {
sc = "0" + String(p_timeinfo->tm_sec);
}
else {
sc = String(p_timeinfo->tm_sec);
}
String TimeNow = hr + ":" + mn + ":" + sc;
// Serial.print(TimeNow);
String data = "";
while(Serial.available()>0){
data += char(Serial.read());
// digitalWrite(LED_1, HIGH);
// Serial.println(data);
}
//buang spasi data
data.trim();
//uji data
if(data != ""){
//Format data = 29.5#80 = array(setelah parsing)
//lakukan parsing data
int index = 0;
// Firebase.RTDB.setString(&fbdo, DBnm+"/"+currentDate+":"+TimeNow+"/help", data);
Firebase.RTDB.setString(&fbdo, DBnm+"test/help", data);
for(int i=0; i<=data.length(); i++){
char delimiter = '#';
if(data[i] != delimiter){
arrData[index] += data[i];
// Serial.println(arrData[index]);
}else{
index++;
}
}
// Index 0 berisi null
Firebase.RTDB.setString(&fbdo, DBnm+"/"+ReverseCurrentDate+":"+TimeNow+"/help", data);
delay(500);
Firebase.RTDB.setString(&fbdo, DBnm+"/"+ReverseCurrentDate+":"+TimeNow+"/Humidity", arrData[1]);
delay(500);
Firebase.RTDB.setString(&fbdo, DBnm+"/"+ReverseCurrentDate+":"+TimeNow+"/Temperature", arrData[2]);
delay(500);
Firebase.RTDB.setString(&fbdo, DBnm+"/"+ReverseCurrentDate+":"+TimeNow+"/SoilMoisture", arrData[3]);
delay(500);
Firebase.RTDB.setString(&fbdo, DBnm+"/"+ReverseCurrentDate+":"+TimeNow+"/SoilpH", arrData[4]);
delay(500);
Firebase.RTDB.setString(&fbdo, DBnm+"/"+ReverseCurrentDate+":"+TimeNow+"/LDR", arrData[5]);
delay(500);
Firebase.RTDB.setString(&fbdo, DBnm+"/"+ReverseCurrentDate+":"+TimeNow+"/Datetime", currentDate+"/"+TimeNow);
delay(500);
//Pastikan data yang dikirim lengkap
//urutannya 0=temperature dan 1=humidity
// if(index == 3){
////
// }
arrData[0] = "";
arrData[1] = "";
arrData[2] = "";
arrData[3] = "";
arrData[4] = "";
arrData[5] = "";
}
//Kirim request Ya ke Due
String kirimData = ActuatorStatus;
Serial.println(kirimData);
// DataSerial.println(kirimData);
}` and here's my screenshot Thankyou for any help |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 10 replies
-
You should call The function |
Beta Was this translation helpful? Give feedback.
-
You can call it once per iteration using For debugging, you should remove tokenStatusCallback function from your code and using the function from the TokenHelper instead. You should check the internet connection because it can't connect to the server even WiFi AP was connected. |
Beta Was this translation helpful? Give feedback.
-
What do you mean "sometimes the esp wifi connection was reset"? |
Beta Was this translation helpful? Give feedback.
You should call
Firebase.ready()
repeatedly inloop()
.The function
Firebase.ready()
will return true when device is authenticated. It also handles the authentication processes.