mobizt / Firebase-ESP32

[DEPRECATED]🔥 Firebase RTDB Arduino Library for ESP32. The complete, fast, secured and reliable Firebase Arduino client library that supports CRUD (create, read, update, delete) and Stream operations.
MIT License
415 stars 118 forks source link

"Connection lost" and "connection refused" errors when Firebase related code runs on 2 cores #56

Closed mrdc closed 4 years ago

mrdc commented 4 years ago

Hello,

When I run my code related to Firebase by default on Core 1, everything works normal, but when I put some code related to Firebase on Core 0, I receive errors in Serial related to Firebase. See my code below.

18:42:33.316 -> connection lost
18:44:46.416 -> connection refused

IDE and its version:

This code runs on Core 1 by default and works OK:


void setup() {
...
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); 
Firebase.setReadTimeout(firebaseData, 1000 * 60);
Firebase.setwriteSizeLimit(firebaseData, "tiny");
...
}

void Callback1() {
...
if (inValue.find("SomeString") != -1) {
          Do some stuff;
          Firebase.setString(firebaseData, "/Path", "SomeValue");
        }
        else if (inValue.find("("SomeOtherString") ") != -1) {
          Do some other stuff;
          Firebase.setString(firebaseData, "/Path", "SomeValue2");
        }
}

void loop() {
if (!Firebase.readStream(firebaseData))
{
  Serial.println(firebaseData.errorReason());
}

if (firebaseData.streamTimeout())
{
  Serial.println("Stream timeout, resume streaming...");
  Serial.println();
}

if (firebaseData.streamAvailable())
{
    RemoteData = firebaseData.stringData();  
    if RemoteData == "Value1") {
      Do some stuff;
    }
    else if RemoteData == "Value2") {
      Do some other stuff;
    }
    else {
      Serial.println("Wrong Data!");
    }
}

Callback1, setup() run on default Core 1, Task1code runs on Core 0. The difference with the code I've posted earlier - code is moved from loop() to Task1:


void setup()
{
...
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); 
Firebase.setReadTimeout(firebaseData, 1000 * 60);
Firebase.setwriteSizeLimit(firebaseData, "tiny");

xTaskCreatePinnedToCore(
                    Task1code,   /* Task function. */
                    "Task1",     /* name of task. */
                    10000,       /* Stack size of task */
                    NULL,        /* parameter of the task */
                    1,           /* priority of the task */
                    &Task1,      /* Task handle to keep track of created task */
                    0);          /* pin task to core 0 */                  
  delay(500); 
...
}

void Callback1() {
...
if (inValue.find("SomeString") != -1) {
          Do some stuff;
          Firebase.setString(firebaseData, "/Path", "SomeValue");
        }
        else if (inValue.find("("SomeOtherString") ") != -1) {
          Do some other stuff;
          Firebase.setString(firebaseData, "/Path", "SomeValue2");
        }

}

void Task1code( void * pvParameters ){
if (!Firebase.readStream(firebaseData))
{
  Serial.println(firebaseData.errorReason());
}

if (firebaseData.streamTimeout())
{
  Serial.println("Stream timeout, resume streaming...");
  Serial.println();
}

if (firebaseData.streamAvailable())
{
RemoteData = firebaseData.stringData();  
    if RemoteData == "Value1") {
      Do some stuff;
    }
    else if RemoteData == "Value2") {
      Do some other stuff;
    }
    else {
      Serial.println("Wrong Data!");
    }
}

void loop() {
}
mobizt commented 4 years ago

This is the issue in Arduino platform which WiFi task only pin to core 0. https://esp32.com/viewtopic.php?t=9225

mrdc commented 4 years ago

By default WiFi and all code (setup(), loop(), functions()) run on Core 1. In my case I'm moving some Firebase tasks to Core 0. So is it the issue that there is no internet connection when code runs on Core 0?

mobizt commented 4 years ago

For user's task (use WiFi client) on core 0 is ok from my test. Let me check the library and inform you later.

mobizt commented 4 years ago

Please test this code.


#include <WiFi.h>
#include "FirebaseESP32.h"

#define FIREBASE_HOST "xxxxxxxxxxx.firebaseio.com"
#define FIREBASE_AUTH "xxxxxxxxxxxxxxxxxxxxxxxx"

#define WIFI_SSID "xxxxxxxx"
#define WIFI_PASSWORD "xxxxxxxxxxx"

FirebaseData firebaseData;
FirebaseData firebaseData2;

TaskHandle_t Task1;

String Path = "/Test123";

int count = 0;

void Task1code( void * parameter) {

  for (;;) {

    if (!Firebase.readStream(firebaseData))
    {
      Serial.print("Read stream error: ");
      Serial.println(firebaseData.errorReason());
      Serial.println();
    }

    if (firebaseData.streamTimeout())
    {
      Serial.println("Stream timeout");
      Serial.println();
    }

    if (firebaseData.streamAvailable())
    {
      Serial.print("Stream data: ");
      String data = firebaseData.stringData();
      Serial.println(data);
      Serial.println();
    }

    vTaskDelay(10);
  }
}

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();

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);

  if (!Firebase.beginStream(firebaseData, Path))
  {

    Serial.println("Can't begin stream connection...");
    Serial.println(firebaseData.errorReason());

  }

  xTaskCreatePinnedToCore(Task1code, "Task1", 10000, NULL, 0, &Task1, 0/* core 0 */);
}

void loop()
{
  count++;
  String data = "Hello " + String(count);
  Firebase.set(firebaseData2, Path,  data);
  delay(2000);
}

It works without any issue.

Are you forget to call beginStream?

mrdc commented 4 years ago

It works without any issue.

Thanks, I'll check it. BTW In my case I receive errors when Callback1 is executed. My Task1code works fine. Will test it on Wrover board - to be sure that it's not a low RAM issue.

Are you forget to call beginStream?

It's in my code - missed it during copy&paste to the issue.

mobizt commented 4 years ago

If you use the same Firebase Data object for stream and normal firebase calls as in your code, which object holds the same instance of WiFi client, no matter what you call/stream it from different tasks or different cpu cores, you need to allow idle time between call to let stream to be established.

Below is the loop task on core 1 that uses the same Firebase Data object as in core 0 stream task.

void loop()
{
  count++;

  String data = "Test " + String(count);
  if(!Firebase.set(firebaseData, Path,  data))
  {

    Serial.println("Can't set data...");
    Serial.println(firebaseData.errorReason());

  }else{
    Serial.println("set data ok");
  }

 //idle time for stream
  delay(2000);

}

For single Firebase Data object usage, the resources in Firebase Data object were shared. To prevent the data collision from different tasks use the same resources, then incoming firebase call from other tasks need to wait until the current firebase call to be completed or reject when the wait timeout was reached.

The stream call has lower priority than normal firebase calls, when readStream was called during current firebase call, the stream operation will be quit and no stream read error was set.

The use of Firebase Data object for stream in user's defined RTOS task was set to be obsoleted due to it was not handle/manage by the library since version 3.0.0, stream callback was recommended which run under managed task in core 1.

The causes of connection lost and connection refused are different.

The connection lost status was set due to WiFi was disconnected. The connection refused status was due to server close connection from bad request or internet connection was failed (also low ram under 100 k for mbedTLS to use in SSL handshake) and also set when some backup/restore errors.

mrdc commented 4 years ago

If you use the same Firebase Data object for stream and normal firebase calls as in your code, which object holds the same instance of WiFi client, no matter what you call/stream it from different tasks or different cpu cores, you need to allow idle time between call to let stream to be established.

I understand it, but in my case when code for readStream runs on default Core 1 everything is fine without delays. When the same readStream code runs on Core 0, I receive errors. Is using 2 Firebase objects for the same path (setString and readStream) from this example https://github.com/mobizt/Firebase-ESP32/blob/master/examples/Different_objects_stream/Different_objects_stream.ino a better approach to fix connection issues and eliminate delays?

The stream call has lower priority than normal firebase calls, when readStream was called during current firebase call, the stream operation will be quit and no stream read error was set.

So my issue is caused by usage of 1 Firebase object for readStream and setString?

mrdc commented 4 years ago

Will test it on Wrover board - to be sure that it's not a low RAM issue.

You'll be surprised but it's actually low RAM issue: on ESP32 Wrover with PSRAM my code works fine - no errors...

mobizt commented 4 years ago

Use single Firebase Data object can't cause connection lost and connection refused

As I state in the last paragraph, its network, data encryption/decrytion issue in low ram, and server issue.

You should set debug for WiFi in Arduino IDE and see what's actually happen.

Use different Firebase Data objects for stream and Firebase calls then stream will not interrupt by other Firebase calls.

If single object is used, the stream will be re-connected and it uses time during SSL handshake.

mobizt commented 4 years ago

on ESP32 Wrover with PSRAM my code works fine - no errors...

It's better if you test and compare debug message between enable and disable PSRAM in Arduino IDE.

keshij555 commented 3 years ago

same error but I'm using firebase streaming + painless mash. It works normally when I'm using firebase streaming only. can both work together?

mobizt commented 3 years ago

@keshij555

The different issue.

With ESP-Mesh protocol used in the mesh library, the internet access is not available.

You need to use another ESP8266 or ESP32 device that connected to a mesh network and send/receive data to/from the ESP32 device (internet access with Firebase) via a serial or I2C or SPI bus.

hansdiaz commented 3 years ago

I have the same issue but its only one core use and Bluetooth sensing is used, it worked one time, but now I cant push the data to the firebase. is there any solution? below is my code I'm an extreme beginner to this.

`

include

include

include

include

include

include

include

include

HCSR04 hc(19, 18); WiFiServer server(80); const char ssid = "Hansa"; const char password = "678paris";

define FIREBASE_HOST "employee-behaviour-tracker.firebaseio.com"

define FIREBASE_AUTH "JY9dH294sB0HLIFYaAMQqYQKNj8vEwiskcxYuEEf"

FirebaseData firebaseData; FirebaseJsonArray uuidArray, valueArray, rssiArray;

int ECHO= 18, TRIG= 19, PIR= 21, OBST= 4; int LED1= 5, LED2= 26; int ULT_SWT=13, OBST_SWT=12, BEAN_SWT=14; String unitId="110011";

int ST_CNT=0, SD_CNT=0;

int deviceCount=0; int prevCount=0; String dev_uuid=""; class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { void onResult(BLEAdvertisedDevice advertisedDevice) { } };

BLEScan* pBLEScan; void setup() { Serial.begin(9600); pinMode(PIR, INPUT); pinMode(OBST, INPUT); pinMode(LED1, OUTPUT); pinMode(LED2, OUTPUT); digitalWrite(PIR, LOW); digitalWrite(LED1, LOW); digitalWrite(LED2, LOW); Serial.println("Scanning...");

BLEDevice::init(""); pBLEScan = BLEDevice::getScan(); //create new scan pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster pBLEScan->setInterval(100); pBLEScan->setWindow(99); // less or equal setInterval value

Serial.print("Connecting to "); Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected."); Serial.println("IP address: "); Serial.println(WiFi.localIP());

Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); Firebase.reconnectWiFi(true);

if (!Firebase.beginStream(firebaseData, (String)"/stationary/"+unitId)) { Serial.println("------------------------------------"); Serial.println("Can't begin stream connection..."); Serial.println("REASON: " + firebaseData.errorReason()); Serial.println("------------------------------------"); Serial.println(); } }

void pushToFirebase() { FirebaseJson physical;

int physicalChoice=0; if(digitalRead(OBST_SWT)==LOW && digitalRead(BEAN_SWT)==LOW) { physicalChoice=1; } else if(digitalRead(OBST_SWT)==HIGH) { physicalChoice=2; } else if(digitalRead(BEAN_SWT)==HIGH) { physicalChoice=3; }

physical.set("sit_timer",ST_CNT); physical.set("physcial_choice",physicalChoice); physical.set("device_count",deviceCount);

if (Firebase.set(firebaseData, ((String)"/stationary/"+unitId+"/physical"), physical)) { Serial.println("PASSED"); Serial.println("PATH: " + firebaseData.dataPath()); Serial.println("TYPE: " + firebaseData.dataType()); Serial.print("VALUE: "); Serial.println("------------------------------------"); Serial.println(); } else { Serial.println("FAILED"); Serial.println("REASON: " + firebaseData.errorReason()); Serial.println("------------------------------------"); Serial.println(); } if(deviceCount!=0){ if (Firebase.set(firebaseData, ((String)"/stationary/"+unitId+"/pervasive/UUID"), uuidArray)) { Serial.println("PASSED"); Serial.println("PATH: " + firebaseData.dataPath()); Serial.println("TYPE: " + firebaseData.dataType()); Serial.print("VALUE: ");

    Serial.println("------------------------------------");
    Serial.println();
}
else
{
    Serial.println("FAILED UUID");
    Serial.println("REASON: " + firebaseData.errorReason());
    Serial.println("------------------------------------");
    Serial.println();
}
if (Firebase.set(firebaseData, ((String)"/stationary/"+unitId+"/pervasive/Prox"), valueArray))
{
    Serial.println("PASSED");
    Serial.println("PATH: " + firebaseData.dataPath());
    Serial.println("TYPE: " + firebaseData.dataType());
    Serial.print("VALUE: ");

    Serial.println("------------------------------------");
    Serial.println();
}
else
{
    Serial.println("FAILED VALUE");
    Serial.println("REASON: " + firebaseData.errorReason());
    Serial.println("------------------------------------");
    Serial.println();
}

if (Firebase.set(firebaseData, ((String)"/stationary/"+unitId+"/pervasive/RSSI"), rssiArray))
{
    Serial.println("PASSED");
    Serial.println("PATH: " + firebaseData.dataPath());
    Serial.println("TYPE: " + firebaseData.dataType());
    Serial.print("VALUE: ");

    Serial.println("------------------------------------");
    Serial.println();
}
else
{
    Serial.println("FAILED RSSI");
    Serial.println("REASON: " + firebaseData.errorReason());
    Serial.println("------------------------------------");
    Serial.println();
}

}

}

//void bluetoothScanner(void* param) void bluetoothScanner() { BLEScanResults foundDevices = pBLEScan->start(1, false); Serial.println((String)"Devices found: "+deviceCount); deviceCount= foundDevices.getCount(); uuidArray.clear(); valueArray.clear(); rssiArray.clear(); uuidArray.add("UUID"); valueArray.add("Prox"); rssiArray.add("RSSI"); if (deviceCount!=0){
for (int i = 0; i < deviceCount; i++) {
int proxValue=0;

      BLEAdvertisedDevice advertisedDevice = foundDevices.getDevice(i);
      Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());

      int ble_rssi = advertisedDevice.getRSSI();
      int8_t bleTX= advertisedDevice.getTXPower();
      Serial.println("RSSI: " + String(ble_rssi));
      Serial.println("TX: " + String(bleTX));
      if (advertisedDevice.haveServiceUUID ())
      {
       //Serial.print("ServiceUUID : "); Serial.println(advertisedDevice.getServiceUUID().toString().c_str());
       dev_uuid=advertisedDevice.getServiceUUID().toString().c_str();
       dev_uuid=String(dev_uuid);
       Serial.print("ServiceUUID : "); Serial.println(dev_uuid);
      }

      //Serial.println("UUID: " + dev_uuid);
      Serial.println("----------------------------------------");

      if (ble_rssi < -80)
      {
        proxValue=3;
        Serial.println("Out of range but proximity detected");
      }
      if (ble_rssi > -80 && ble_rssi < -65)
      {
        proxValue=2;
        Serial.println("Close proximity detected");
      }
      if (ble_rssi > -65)
      {
        proxValue=1;
        Serial.println("Extremely close proximity detected");
      }
      String counter= String(i);
      valueArray.set("["+counter+"]/", proxValue);
      uuidArray.set("["+counter+"]/", dev_uuid);
      rssiArray.set("["+counter+"]/", ble_rssi);

  }
  Serial.println("Scan done!");
  pBLEScan->clearResults();

}else{ uuidArray.clear(); valueArray.clear(); rssiArray.clear(); uuidArray.set("[0]/", 0); valueArray.set("[0]/", 0); rssiArray.set("[0]/", 0); } prevCount=deviceCount;

}

void physicalValidator() { if (deviceCount!=0) { if(digitalRead(OBST_SWT)==LOW && digitalRead(BEAN_SWT)==LOW) { double distance= hc.dist(); if(distance>0 & distance<30 ) { if(digitalRead(PIR)==HIGH)
{ Serial.println("Somebody is here."); ST_CNT++; } else if(digitalRead(PIR)==LOW)
{ Serial.println("Nobody.");

      }
    }else{
    }
}
else if(digitalRead(OBST_SWT)==HIGH)
{
    if(digitalRead(OBST)==LOW)  {
      Serial.println("Obstacle detected.");

      if(digitalRead(PIR)==HIGH)  
      {
        Serial.println("Somebody is here.");
        ST_CNT++;

      }
      else  
      {
        Serial.println("Nobody.");

      }
    }
    else  {
       Serial.println("No Obstacle.");

    }
}
else if(digitalRead(BEAN_SWT)==HIGH)
{

}
pushToFirebase();

}else{ ST_CNT=0; SD_CNT=0; pushToFirebase(); }

}

void loop() { Serial.println("Blutooth scan function"); bluetoothScanner(); Serial.println("Physical validator function"); physicalValidator();

} `

mobizt commented 3 years ago

@hansdiaz you can't use both WiFi and Bluetooth to work at the same time. https://esp32.com/viewtopic.php?t=6707

rd124 commented 3 years ago

Hi, I am using your Firebase_Arduino_WiFiNINA and it was previously working to send data from firebase to Arduino, but now it keeps saying "Connection Refused". How do I fix this?

mobizt commented 3 years ago

@rd124 Please check https://github.com/mobizt/Firebase-Arduino-WiFiNINA/issues/18

Firebase sever certificate may need to update to the U-Blox's ESP32 flash mem to make WiFiNINA firmware works.

rd124 commented 3 years ago

@mobizt thanks, I uploaded the SSL domain certificate of my database url and it worked.

Ockersz commented 1 year ago
#include <esp_now.h>
#include <WiFi.h>

//Camera Libraries
#include "esp_camera.h"
#include "Arduino.h"
#include "soc/soc.h"           // Disable brownout problems
#include "soc/rtc_cntl_reg.h"  // Disable brownout problems
#include "driver/rtc_io.h"
#include <SPIFFS.h>
#include <FS.h>
#include <Firebase_ESP_Client.h>
// Provide the token generation process info.
#include <addons/TokenHelper.h>

// Replace with your network credentials
const char *ssid = "Ockersz";
const char *password = "Ockersz@$5";

// Insert Firebase project API Key
#define API_KEY "AIzaSyD6CEddizEWMjDNcyiZ3xTvowH3c4EVRjU"

// Insert Authorized Email and Corresponding Password
#define USER_EMAIL "shaheinockersz1234@gmail.com"
#define USER_PASSWORD "123456"

// Insert Firebase storage bucket ID e.g bucket-name.appspot.com
#define STORAGE_BUCKET_ID "picture-abd01.appspot.com"

// Photo File Name to save in SPIFFS
#define FILE_PHOTO "/data/photo.jpg"

// OV2640 camera module pins (CAMERA_MODEL_AI_THINKER)
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22

boolean takeNewPhoto = true;
bool taskCompleted = false;
// Define Firebase Data objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig configF;

// Check if photo capture was successful
bool checkPhoto(fs::FS &fs) {
  File f_pic = fs.open(FILE_PHOTO);
  unsigned int pic_sz = f_pic.size();
  return (pic_sz > 100);
}

// Capture Photo and Save it to SPIFFS
void capturePhotoSaveSpiffs(void) {
  camera_fb_t *fb = NULL;  // pointer
  bool ok = 0;             // Boolean indicating if the picture has been taken correctly
  do {
    // Take a photo with the camera
    Serial.println("Taking a photo...");

    fb = esp_camera_fb_get();
    if (!fb) {
      Serial.println("Camera capture failed");
      return;
    }
    // Photo file name
    Serial.printf("Picture file name: %s\n", FILE_PHOTO);
    File file = SPIFFS.open(FILE_PHOTO, FILE_WRITE);
    // Insert the data in the photo file
    if (!file) {
      Serial.println("Failed to open file in writing mode");
    } else {
      file.write(fb->buf, fb->len);  // payload (image), payload length
      Serial.print("The picture has been saved in ");
      Serial.print(FILE_PHOTO);
      Serial.print(" - Size: ");
      Serial.print(file.size());
      Serial.println(" bytes");
    }
    // Close the file
    file.close();
    esp_camera_fb_return(fb);

    // check if file has been correctly saved in SPIFFS
    ok = checkPhoto(SPIFFS);
  } while (!ok);
}

void initSPIFFS() {
  if (!SPIFFS.begin(true)) {
    Serial.println("An Error has occurred while mounting SPIFFS");
    ESP.restart();
  } else {
    delay(500);
    Serial.println("SPIFFS mounted successfully");
  }
}

void initCamera() {
  // OV2640 camera module
  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;

  if (psramFound()) {
    config.frame_size = FRAMESIZE_UXGA;
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }
  // Camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    ESP.restart();
  }else
  {
    Serial.println("Camera Initiated");
  }
}

// Must match the sender structure
typedef struct struct_message {
  char deviceName[20];
  bool movementDetected;
} struct_message;

// Create a struct_message called myData
struct_message myData;

void connectWiFi() {
  if (WiFi.status() == WL_CONNECTED) {
    return;
  }

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }

  Serial.println("\nConnected to Wi-Fi");
}

void connectFirebase() {
  // Firebase configuration
  configF.api_key = API_KEY;
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;
  configF.token_status_callback = tokenStatusCallback;

  Firebase.begin(&configF, &auth);
  Firebase.reconnectWiFi(true);

  if (Firebase.ready()) {
    Serial.println("Firebase connected successfully");
  } else {
    Serial.println("Firebase initialization failed");
  }
}

// Callback function that will be executed when data is received
void OnDataRecv(const uint8_t *mac, const uint8_t *incomingData, int len) {
  memcpy(&myData, incomingData, sizeof(myData));
  Serial.print("Device Name: ");
  Serial.println(myData.deviceName);
  Serial.print("Movement Detected: ");
  Serial.println(myData.movementDetected ? "Yes" : "No");

  initSPIFFS();

  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);

  // Firebase
  connectWiFi();
  connectFirebase();

  capturePhotoSaveSpiffs();

  delay(1);

  if (Firebase.ready()) {
    Serial.print("Uploading picture... ");

    // MIME type should be valid to avoid download problems.
    // The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h.
    if (Firebase.Storage.upload(&fbdo, STORAGE_BUCKET_ID, FILE_PHOTO, mem_storage_type_flash, FILE_PHOTO, "image/jpeg")) {
      Serial.printf("\nDownload URL: %s\n", fbdo.downloadURL().c_str());
    } else {
      Serial.println(fbdo.errorReason().c_str());
      Serial.printf("\nDownload URL: %s\n", fbdo.downloadURL().c_str());
    }
  } else {
    Serial.println("Firebase Awlk");
  }
}

void setup() {
  // Initialize Serial Monitor
  Serial.begin(115200);

  // Set the device as a Station and Soft Access Point simultaneously
  WiFi.mode(WIFI_AP_STA);

  int32_t channel = 3;
  esp_wifi_set_channel(channel, WIFI_SECOND_CHAN_NONE);

  // Set device as a Wi-Fi Station
  Serial.print("Connecting to Wi-Fi");
  connectWiFi();
  Serial.print("Station IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Wi-Fi Channel: ");
  Serial.println(WiFi.channel());

  connectFirebase();
  initSPIFFS();
  initCamera();

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }

  // Once ESPNow is successfully Init, we will register for recv CB to
  // get recv packet info
  esp_now_register_recv_cb(OnDataRecv);
}

void loop() {
}

Same issue says 'Connection Refused' when it tried to upload the image

mobizt commented 1 year ago

@Ockersz

It's the same result but different causes.

Your device memory is running out or no internet access from your AP or router.

The device is trying to send request to server but not success when TLS handshake failed.

You should debug for WiFi, SSL and OOM which can be configured in Arduino IDE debug options.