Git Product home page Git Product logo

mobizt / firebase-esp32 Goto Github PK

View Code? Open in Web Editor NEW
413.0 17.0 118.0 5.73 MB

[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.

License: MIT License

C++ 36.64% C 63.36%
esp32 firebase firebase-database arduino firebase-realtime-database stream firebase-calls jwt-token rsa256 oauth2-authentication

firebase-esp32's Introduction

Mobizt's GitHub stats

I'm engineer from Thailand.

I'm working on machine condition monitoring and vibration analysis.

The Industrial IoTs, data processing and data acquisition are the fields that I focused.

I develop and maintain the Arduino C++ opensource libraries for embedded devices.

One of my projects Firebase Arduino Client Library for ESP8266 and ESP32 wins the Google Open Source Peer Bonus Program.

The E-mail client library for Arduino project is the first E-mail client library in the Arduino platform that allows the embedded device to send and receive E-mail.

I'm ready to support and help for fixing the issues and answering the questions related to my libraries

firebase-esp32's People

Contributors

mobizt avatar ode1022 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-esp32's Issues

HELP: Cloud_Messaging.ino can the tokens be MAC address

Hi,
In Cloud_Messaging.ino example :


#define FIREBASE_FCM_DEVICE_TOKEN_1 "RECIPIENT_DEVICE_TOKEN"
#define FIREBASE_FCM_DEVICE_TOKEN_2 "ANOTHER_RECIPIENT_DEVICE_TOKEN"

What are Device Tokens?
How does one get them from Firebase?
Are they assigned by the user or firebase?
If they are assigned by user, are they arbitrary strings? Mac addresses?
If they are Mac addresses, then two ESP32's located on different WiFi networks should be able
to send messages to each other?

I was unable to figure it out by reading the firebase docs, or searching online.
Please help

Consecutive Firebase.getInt returns wrong value

I have a program that accepts performs the following operations:

  1. Acts as UDP Server
  2. Operates in AP_STA WiFi mode
  3. Shows IP Address of devices connected to ESP32's AP
  4. Uploads certain data to firebase on regular interval of 10s
#include "FirebaseESP32.h"

#define FASTLED_ESP8266_RAW_PIN_ORDER
#include<Arduino.h>
#include<WiFi.h>
#include<WiFiAP.h>
#include<esp_wifi.h>
#include<WiFiClientSecure.h>
#include<AsyncUDP.h>
#include<SPI.h>//load the spi library
#include<EEPROM.h>
#include<ArduinoJson.h>
#include<TimeLib.h>
#include<time.h>
#include<FastLED.h>
#include <HTTPClient.h>
#include <HTTPUpdate.h>
#include "D:/esp-idf/components/freertos/include/freertos/FreeRTOS.h"
#include "D:/esp-idf/components/freertos/include/freertos/task.h"
#include "D:/esp-idf/components/freertos/include/freertos/event_groups.h"
#include "D:/esp-idf/components/esp32/include/esp_system.h"
#include "D:/esp-idf/components/esp32/include/esp_wifi.h"
#include "D:/esp-idf/components/esp32/include/esp_event_loop.h"
#include "D:/esp-idf/components/log/include/esp_log.h"
#include "D:/esp-idf/components/nvs_flash/include/nvs_flash.h"

#ifdef CONFIG_AP_HIDE_SSID
  #define CONFIG_AP_SSID_HIDDEN 1
#else
  #define CONFIG_AP_SSID_HIDDEN 0
#endif  
#ifdef CONFIG_WIFI_AUTH_OPEN
  #define CONFIG_AP_AUTHMODE WIFI_AUTH_OPEN
#endif
#ifdef CONFIG_WIFI_AUTH_WEP
  #define CONFIG_AP_AUTHMODE WIFI_AUTH_WEP
#endif
#ifdef CONFIG_WIFI_AUTH_WPA_PSK
  #define CONFIG_AP_AUTHMODE WIFI_AUTH_WPA_PSK
#endif
#ifdef CONFIG_WIFI_AUTH_WPA2_PSK
  #define CONFIG_AP_AUTHMODE WIFI_AUTH_WPA2_PSK
#endif
#ifdef CONFIG_WIFI_AUTH_WPA_WPA2_PSK
  #define CONFIG_AP_AUTHMODE WIFI_AUTH_WPA_WPA2_PSK
#endif
#ifdef CONFIG_WIFI_AUTH_WPA2_ENTERPRISE
  #define CONFIG_AP_AUTHMODE WIFI_AUTH_WPA2_ENTERPRISE
#endif

#define MAX_WIFI_INFO_LENGTH 100
#define NUM_LEDS 1
#define led 25

//FIREBASE CREDENTIALS
#define FIREBASE_HOST "example.firebaseio.com"
#define FIREBASE_AUTH "exampleKey"
FirebaseData firebaseData;

void AccessPointInit();
void Sync();
void FirebaseSetInt(String path , int dat);
void FirebaseSetString(String path , String dat);
int FirebaseGetInt(String path);
String FirebaseGetString(String path);

uint8_t pin_led = 16;
char ssid[MAX_WIFI_INFO_LENGTH] = "home";
char pass[MAX_WIFI_INFO_LENGTH] = "12345678";

uint8_t pins[4] = {5 , 18 , 19 , 21};
int stta[4] = {0 , 0 , 0 , 0};

int runtime[4] = {0 , 0 , 0 , 0};

char myssid[] = "ESP32";
IPAddress ip(192, 168, 22, 22);
IPAddress fixedIp(192 , 168 , 0 , 200);
IPAddress gateway(192, 168, 22, 1);
IPAddress subnet(255, 255, 255, 0);

unsigned int localPort = 5000; //assign a port to talk over
String Data; //string for our Data
int packetSize; //variable storing the size of the packet

int numOfOutput;

CRGB leds[NUM_LEDS];

AsyncUDP udp;

void WiFiEvent(WiFiEvent_t event)
{
    Serial.printf("[WiFi-event] event: %d\n", event);

    switch (event)
    {
    case SYSTEM_EVENT_STA_GOT_IP:
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
        break;
    case SYSTEM_EVENT_STA_DISCONNECTED:
        Serial.println("WiFi lost connection");
        break;
    }
}

String client_status();
void PostData();
void UDPSetup();

void setup() {
  Serial.begin(115200);
  while(!Serial){;}//wait for Serial to begin
  Serial.println();
  //Prepare status led-->
  FastLED.addLeds<WS2812, led , GRB>(leds , NUM_LEDS);
  leds[0] = CRGB(255,0,0);
  FastLED.show();

  AccessPointInit();
  
  WiFi.begin(ssid, pass);
  WiFi.onEvent(WiFiEvent);
  UDPSetup();
  delay(2000); //wait 2 seconds
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);
  Sync();
}

void UDPSetup(){
  if(udp.listen(5000)) { //port 5000
    Serial.print("UDP Listening on IP: ");
    Serial.println(WiFi.localIP());
    udp.onPacket([](AsyncUDPPacket packet) {
      uint8_t *packets = new uint8_t[packet.length() + 1];
      int it=0;
      for(it=0 ; it < packet.length() ; it++){
        packets[it] = packet.data()[it];
      }
      packets[it] = 0;
      String Data = (char*)packets;
      delete[] packets;
      Serial.print("Data : ");
      Serial.println(Data);
      packet.printf("got it");
    });
  }
}

int lastDate = -1;
void Sync(){
  String outside_string = FirebaseGetString("/out");
  if(outside_string == ""){
    //means if we are not able to connect with Firebase, restart the module
    ESP.restart();
  }
  if(outside_string == "1" || outside_string == "0"){
    lastDate = FirebaseGetInt("/date");
  }
  int prevDate = FirebaseGetInt("/date");
  if(String(prevDate) != ""){
    if(prevDate != day()){
      FirebaseSetInt("/date" , day());
      CheckFlag();
    }
  }
  String stta_string = FirebaseGetString("/stta");
  String shouldWeUpdate = FirebaseGetString("/update");
}

void CheckFlag(){
  Serial.println("Checking for Flag");
  int flag = FirebaseGetString("/flag").toInt();
  Serial.print("Flag is : ");
  Serial.println(flag);
}

void AddUpTime(){
  for(int i = 0 ; i < numOfOutput ; i++){
    runtime[i] = runtime[i] + 10; //add 10 seconds
  }
}
long previousTime = 0;
long interval = 10000;
void loop() {
  if(millis()-previousTime > interval){ //every 10 seconds
    previousTime = millis();
    AddUpTime();
    Sync(); //using as a general purpose sync function
    PostData();
    Serial.println(client_status());
  }
}


void PostData(){
  String outside_string = FirebaseGetString("/outside");
  if(outside_string == ""){
    //means if we are not able to connect with Firebase, restart the module
    ESP.restart();
  }
  String temp = "1;1;1;1";
  FirebaseSetString("/status", temp);
  FirebaseSetString("/last_update", String(hour())+":"+String(minute())+":"+String(second()));
  temp = "0;0;0;0";
  FirebaseSetString("/current", temp);
} 

void AccessPointInit() {
  // initialize NVS
  ESP_ERROR_CHECK(nvs_flash_init());
  // initialize the tcp stack
  tcpip_adapter_init();
  // stop DHCP server
  ESP_ERROR_CHECK(tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP));
  // assign a static IP to the network interface
  tcpip_adapter_ip_info_t info;
    memset(&info, 0, sizeof(info));
  IP4_ADDR(&info.ip, 192, 168, 22, 1);
    IP4_ADDR(&info.gw, 192, 168, 22, 1);
    IP4_ADDR(&info.netmask, 255, 255, 255, 0);
  ESP_ERROR_CHECK(tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_AP, &info));
  // start the DHCP server   
    ESP_ERROR_CHECK(tcpip_adapter_dhcps_start(TCPIP_ADAPTER_IF_AP));
  Serial.println("Beginning Access Points");
  WiFi.mode(WIFI_AP_STA);
  WiFi.softAPConfig(ip , gateway , subnet);
  WiFi.softAP(myssid , pass);
  Serial.println("Server started");
}
String client_status() 
{ 
  wifi_sta_list_t wifi_sta_list;
  tcpip_adapter_sta_list_t adapter_sta_list;
   
  memset(&wifi_sta_list, 0, sizeof(wifi_sta_list));
  memset(&adapter_sta_list, 0, sizeof(adapter_sta_list));
   
  ESP_ERROR_CHECK(esp_wifi_ap_get_sta_list(&wifi_sta_list));  
  ESP_ERROR_CHECK(tcpip_adapter_get_sta_list(&wifi_sta_list, &adapter_sta_list));
  String temp = "";
  for(int i = 0; i < adapter_sta_list.num; i++) {
    
    tcpip_adapter_sta_info_t station = adapter_sta_list.sta[i];
    temp += String(ip4addr_ntoa(&(station.ip))) + ";";
  }
  return temp;
}

void FirebaseSetInt(String path , int dat){
  if (!Firebase.setInt(firebaseData, path, dat))
  {
    Serial.println("Failed to upload data");
  }
}
void FirebaseSetString(String path , String dat){
  if (!Firebase.setString(firebaseData, path, dat))
  {
    Serial.println("Failed to upload data");
  }
}

int FirebaseGetInt(String path){
  if (Firebase.getInt(firebaseData, path))
  {
    if(firebaseData.dataType() == "int"){
      return firebaseData.intData();
    }
  }
  return 0;
}

String FirebaseGetString(String path){
  if (Firebase.getString(firebaseData, path))
  {
    if(firebaseData.dataType() == "string"){
      return firebaseData.stringData();
    }
  }
  return "";
}

These functions are called one after the other in regular intervals of 10 seconds.
The flag variable (in CheckFlag function) should return the flag value stored on the Firebase Database in path "/flag".
BUT Sometimes, the flag (in CheckFlag function) actually returns the value of the date variable stored on firebase database (which should be fetched by prevDate variable in Sync function). But instead prevDate returns 0 (i.e, it fails to fetch a value).

I even tried to make FirebaseData firebaseData a local variable to these functions instead of a global one. I thought some kind of an overwrite issue might be causing this. But turning it into local variables led the ESP32 to crash for some reason.

Does someone know a fix for this?
Thanks

HELP How to send JSON string to firebase

here is my code, i can set each value but need totaly 4 times, i know there is a setJSON but i cant get it work.
here is my code

JsonObject ID = object.createNestedObject(String(header.from_node));
        ID["Temperature"] = pack0.temperature;
        ID["Humidity"] = pack0.humidity;
        ID["Soil"] = pack0.soil;
        ID[ "Battery"] = pack0.battery;
        serializeJson(object, Serial);
        Firebase.setJSON(firebaseData, path1, object);
        //aFirebase.setJSON(firebaseData,path1, object);
        /*Firebase.setFloat(firebaseData, path1_h, ID["Humidity"]);
        Firebase.setFloat(firebaseData, path1_t, ID["Temperature"]);
        Firebase.setInt(firebaseData, path1_s, ID["Soil"]);
        Firebase.setFloat(firebaseData, path1_b, ID["Battery"]);*/

which i get from serial monitor: {"1":{"Temperature":29.8,"Humidity":41,"Soil":2,"Battery":3292.593}}
error is no match function code setJSON
My code and error

Pull data from void function and store them to int? How?

I followed the basic.ino example provided. I learned how to serial print using the void function printResult(dataObj). Now how do I store the data into an int variable without serial printing it?
.
My Code:
//
FirebaseData testData;
//
String path = "/Main";
void setup()
{
Serial.begin(9600);
Firebase.setInt(testData, path, 0);
}
//
void printResult(FirebaseData &data)
{
if (data.dataType() == "int")
Serial.println(data.intData());
else if (data.dataType() == "float")
Serial.println(data.floatData(), 5);
else if (data.dataType() == "double")
printf("%.9lf\n", data.doubleData());
else if (data.dataType() == "boolean")
Serial.println(data.boolData() == 1 ? "true" : "false");
else if (data.dataType() == "string")
Serial.println(data.stringData());
}
//
Firebase.getInt(testData, path);
//
int data1 = // here is where I want to store the int value data.intData() pulled from the printResult function without serial printing the value, how?
//

BUG getJSON when is string

Describe the bug
when I have
Test
|__node1
|____name:"Baudelio"
|____money: 50

and I get the json this FirebaseData is blank is not null, is BLANK, and when I try get the reason error too is blank

To Reproduce
Steps to reproduce the behavior:

  1. Create a node with 2 elements, one with type string and the other type int
  2. Use the example jsonObject with path Test/node1
  3. And is blank

Expected behavior
I consider that is just a error when I get different types of a json and when I received string in a json

Screenshots
Captura de Pantalla 2019-12-19 a la(s) 10 59 45

IDE and its version:

  • Arduino
  • Version 1.8.10

ESP32 Arduino Core SDK version

  • Version LAST 19 December

Additional context
and when I try get the database complete don't works when I try with the path "/"

Please,I would appreciate it if you could solve it
this is my email [email protected]
if you want to talk I will available

Stream Event Type Patch

Hi
I'm having some problem to detect a incoming event using stream functions. I can only detect a stream data when the event type is "PUT". When it's "PATCH" i can't.
I know this because i was using another firebase library where i could choose the event type to get the stream data.
As this library is much more reliable, i'd like to know if there is a way to get PACHT event type on STREAM.

Thanks

Coonection Refused

Hi, here are logs, I am simple writing data to realtime, Streaming data works perfectly,, I faced this issue suddenly, can you please help.

Thanks

Connected with IP: 192.168.1.105

[V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 216348
[V][ssl_client.cpp:58] start_ssl_client(): Starting socket
[V][ssl_client.cpp:93] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:102] start_ssl_client(): Setting up the SSL/TLS structure...
[I][ssl_client.cpp:156] start_ssl_client(): WARNING: Use certificates for a more secure communication!
[V][ssl_client.cpp:180] start_ssl_client(): Setting hostname for TLS session...
[V][ssl_client.cpp:195] start_ssl_client(): Performing the SSL/TLS handshake...
[V][ssl_client.cpp:216] start_ssl_client(): Verifying peer X.509 certificate...
[V][ssl_client.cpp:225] start_ssl_client(): Certificate verified.
[V][ssl_client.cpp:240] start_ssl_client(): Free internal heap after TLS 175132
[V][ssl_client.cpp:279] send_ssl_data(): Writing HTTP request...
[V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 171060
[V][ssl_client.cpp:58] start_ssl_client(): Starting socket
[V][ssl_client.cpp:93] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:102] start_ssl_client(): Setting up the SSL/TLS structure...
[I][ssl_client.cpp:156] start_ssl_client(): WARNING: Use certificates for a more secure communication!
[V][ssl_client.cpp:180] start_ssl_client(): Setting hostname for TLS session...
[V][ssl_client.cpp:195] start_ssl_client(): Performing the SSL/TLS handshake...
[V][ssl_client.cpp:216] start_ssl_client(): Verifying peer X.509 certificate...
[V][ssl_client.cpp:225] start_ssl_client(): Certificate verified.
[V][ssl_client.cpp:240] start_ssl_client(): Free internal heap after TLS 131592
[V][ssl_client.cpp:279] send_ssl_data(): Writing HTTP request...
[V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 127516
[V][ssl_client.cpp:58] start_ssl_client(): Starting socket
[V][ssl_client.cpp:93] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:102] start_ssl_client(): Setting up the SSL/TLS structure...
[I][ssl_client.cpp:156] start_ssl_client(): WARNING: Use certificates for a more secure communication!
[V][ssl_client.cpp:180] start_ssl_client(): Setting hostname for TLS session...
[V][ssl_client.cpp:195] start_ssl_client(): Performing the SSL/TLS handshake...
[V][ssl_client.cpp:216] start_ssl_client(): Verifying peer X.509 certificate...
[V][ssl_client.cpp:225] start_ssl_client(): Certificate verified.
[V][ssl_client.cpp:240] start_ssl_client(): Free internal heap after TLS 88044
[V][ssl_client.cpp:279] send_ssl_data(): Writing HTTP request...
[V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 83912
[V][ssl_client.cpp:58] start_ssl_client(): Starting socket
[V][ssl_client.cpp:93] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:102] start_ssl_client(): Setting up the SSL/TLS structure...
[I][ssl_client.cpp:156] start_ssl_client(): WARNING: Use certificates for a more secure communication!
[V][ssl_client.cpp:180] start_ssl_client(): Setting hostname for TLS session...
[E][ssl_client.cpp:33] _handle_error(): [start_ssl_client():190]: (-32512) SSL - Memory allocation failed
[E][WiFiClientSecure.cpp:132] connect(): start_ssl_client: -32512
[V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 85444
[V][ssl_client.cpp:58] start_ssl_client(): Starting socket
[V][ssl_client.cpp:93] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:102] start_ssl_client(): Setting up the SSL/TLS structure...
[I][ssl_client.cpp:156] start_ssl_client(): WARNING: Use certificates for a more secure communication!
[V][ssl_client.cpp:180] start_ssl_client(): Setting hostname for TLS session...
[E][ssl_client.cpp:33] _handle_error(): [start_ssl_client():190]: (-32512) SSL - Memory allocation failed
[E][WiFiClientSecure.cpp:132] connect(): start_ssl_client: -32512
[V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 84940
[V][ssl_client.cpp:58] start_ssl_client(): Starting socket
[V][ssl_client.cpp:93] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:102] start_ssl_client(): Setting up the SSL/TLS structure...
[I][ssl_client.cpp:156] start_ssl_client(): WARNING: Use certificates for a more secure communication!
[V][ssl_client.cpp:180] start_ssl_client(): Setting hostname for TLS session...
[E][ssl_client.cpp:33] _handle_error(): [start_ssl_client():190]: (-32512) SSL - Memory allocation failed
[E][WiFiClientSecure.cpp:132] connect(): start_ssl_client: -32512
[V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 83740
[V][ssl_client.cpp:58] start_ssl_client(): Starting socket
[V][ssl_client.cpp:93] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:102] start_ssl_client(): Setting up the SSL/TLS structure...
[I][ssl_client.cpp:156] start_ssl_client(): WARNING: Use certificates for a more secure communication!
[V][ssl_client.cpp:180] start_ssl_client(): Setting hostname for TLS session...
[E][ssl_client.cpp:33] _handle_error(): [start_ssl_client():190]: (-32512) SSL - Memory allocation failed
[E][WiFiClientSecure.cpp:132] connect(): start_ssl_client: -32512
[V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 83428
[V][ssl_client.cpp:58] start_ssl_client(): Starting socket
[V][ssl_client.cpp:93] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:102] start_ssl_client(): Setting up the SSL/TLS structure...
[I][ssl_client.cpp:156] start_ssl_client(): WARNING: Use certificates for a more secure communication!
[V][ssl_client.cpp:180] start_ssl_client(): Setting hostname for TLS session...
[E][ssl_client.cpp:33] _handle_error(): [start_ssl_client():190]: (-32512) SSL - Memory allocation failed
[E][WiFiClientSecure.cpp:132] connect(): start_ssl_client: -32512
[V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 83112
[V][ssl_client.cpp:58] start_ssl_client(): Starting socket
[V][ssl_client.cpp:93] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:102] start_ssl_client(): Setting up the SSL/TLS structure...
[I][ssl_client.cpp:156] start_ssl_client(): WARNING: Use certificates for a more secure communication!
[V][ssl_client.cpp:180] start_ssl_client(): Setting hostname for TLS session...
[E][ssl_client.cpp:33] _handle_error(): [start_ssl_client():190]: (-32512) SSL - Memory allocation failed
[E][WiFiClientSecure.cpp:132] connect(): start_ssl_client: -32512
[V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
FAILED
REASON: connection refused

HELP. connection refused

#include <FirebaseESP32.h>
#include <FirebaseESP32HTTPClient.h>
#include <FirebaseJson.h>
#include <jsmn.h>

const char* ssid = "Lab_118";
const char* password = "";
#include "img_converters.h"

String FIREBASE_HOST = "fotos-81fec.firebaseio.com";
String FIREBASE_AUTH = "RU0EZbsEhAZHdk8KhZXjsCLGGTuRe4Wp5vBZbMXI";

FirebaseData firebaseData;

#include <WiFi.h>
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
#include "Base64.h"

#include "esp_camera.h"


#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

#define XCLK_FREQUENZ  20000000
#define RESOLUTION  FRAMESIZE_XGA
#define BILDNAME "LED_CAM_"

static camera_config_t camera_config = {
    .pin_pwdn  = PWDN_GPIO_NUM,
    .pin_reset = RESET_GPIO_NUM,
    .pin_xclk  = XCLK_GPIO_NUM,
    .pin_sscb_sda = SIOD_GPIO_NUM,
    .pin_sscb_scl = SIOC_GPIO_NUM,

    .pin_d7 = Y9_GPIO_NUM,
    .pin_d6 = Y8_GPIO_NUM,
    .pin_d5 = Y7_GPIO_NUM,
    .pin_d4 = Y6_GPIO_NUM,
    .pin_d3 = Y5_GPIO_NUM,
    .pin_d2 = Y4_GPIO_NUM,
    .pin_d1 = Y3_GPIO_NUM,
    .pin_d0 = Y2_GPIO_NUM,
    .pin_vsync = VSYNC_GPIO_NUM,
    .pin_href = HREF_GPIO_NUM,
    .pin_pclk = PCLK_GPIO_NUM,

    //XCLK 20MHz or 10MHz for OV2640 double FPS (Experimental)
    .xclk_freq_hz = XCLK_FREQUENZ,
    .ledc_timer = LEDC_TIMER_0,
    .ledc_channel = LEDC_CHANNEL_0,

    .pixel_format = PIXFORMAT_JPEG,//YUV422,GRAYSCALE,RGB565,JPEG
    .frame_size = RESOLUTION,   //QQVGA-QXGA Do not use sizes above QVGA when not JPEG

    .jpeg_quality = 12, //0-63 lower number means higher quality
    .fb_count = 1 //if more than one, i2s runs in continuous mode. Use only with JPEG
};

esp_err_t camera_init(void);
esp_err_t camera_capture(void);
void setSensordaten(void);

void setup() { 
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  Serial.println();
  Serial.println("ssid: " + (String)ssid);
  Serial.println("password: " + (String)password);
  
  WiFi.begin(ssid, password);

  long int StartTime=millis();
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      if ((StartTime+10000) < millis()) break;
  } 

  if (WiFi.status() == WL_CONNECTED) {
    char* apssid = "ESP32-CAM";
    char* appassword = "12345678";         //AP password require at least 8 characters.
    Serial.println(""); 
    Serial.print("Camera Ready! Use 'http://");
    Serial.print(WiFi.localIP());
    Serial.println("' to connect");
    WiFi.softAP((WiFi.localIP().toString()+"_"+(String)apssid).c_str(), appassword);            
  }
  else {
    Serial.println("Connection failed");
    return;
  } 
  
  esp_err_t err = esp_camera_init(&camera_config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    delay(1000);
    ESP.restart();
  }
  
  setSensordaten();
  sensor_t *s = esp_camera_sensor_get();
  
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);
  Firebase.setMaxRetry(firebaseData, 3);
  Firebase.setMaxErrorQueue(firebaseData, 30); 
  Firebase.enableClassicRequest(firebaseData, true);

 // String jsonData = "{\"photo\":\"" + Photo2Base64() + "\"}";
  FirebaseJson json;
  json.set("{\"photo\":\"" + Photo2Base64() + "\"}");
  String photoPath = "/esp32cam";
  if (Firebase.pushJSON(firebaseData, photoPath, json)) {
    Serial.println(firebaseData.dataPath());
    Serial.println(firebaseData.pushName());
    Serial.println(firebaseData.dataPath() + "/"+ firebaseData.pushName());
  } else {
    Serial.println(firebaseData.errorReason());
  }
} 
 
void loop() { 
  delay(10000);
}

String Photo2Base64() {
    setSensordaten();
    sensor_t *s = esp_camera_sensor_get();
    camera_fb_t * fb = NULL;
    fb = esp_camera_fb_get();  
    if(!fb) {
      Serial.println("Camera capture failed");
      return "";
    }
  
    String imageFile = "data:image/jpeg;base64,";
    char *input = (char *)fb->buf;
    char output[base64_enc_len(3)];
    for (int i=0;i<fb->len;i++) {
      base64_encode(output, (input++), 3);
      if (i%3==0) imageFile += urlencode(String(output));
    }

    esp_camera_fb_return(fb);
    
    return imageFile;
}

//https://github.com/zenmanenergy/ESP8266-Arduino-Examples/
String urlencode(String str)
{
    String encodedString="";
    char c;
    char code0;
    char code1;
    char code2;
    for (int i =0; i < str.length(); i++){
      c=str.charAt(i);
      if (c == ' '){
        encodedString+= '+';
      } else if (isalnum(c)){
        encodedString+=c;
      } else{
        code1=(c & 0xf)+'0';
        if ((c & 0xf) >9){
            code1=(c & 0xf) - 10 + 'A';
        }
        c=(c>>4)&0xf;
        code0=c+'0';
        if (c > 9){
            code0=c - 10 + 'A';
        }
        code2='\0';
        encodedString+='%';
        encodedString+=code0;
        encodedString+=code1;
        //encodedString+=code2;
      }
      yield();
    }
    return encodedString;
}

void setSensordaten()
{
  size_t res = 0;
  sensor_t * s = esp_camera_sensor_get();

//  res = s->set_framesize(s, (framesize_t)val);          // Framesize      FRAMESIZE_(QQVGA, HQVGA, QVGQ, CIF, VGA, SVGA, XGA, SXGA, UXGA)
  res = s->set_quality(s, 10);                          // JPEG Quality   (10...63)  10
  res = s->set_contrast(s, 0);                          // Kontrast       (-2...+2)   0
  res = s->set_brightness(s, 0);                        // Helligkeit     (-2...+2)   0
  res = s->set_saturation(s, 0);                        // Farbsรคttigung  (-2...+2)   0 
  res = s->set_gainceiling(s, (gainceiling_t) GAINCEILING_2X);      // Verstรคrkung    GAINCEILING_(2x, 4x, 8x, 16x, 32x, 64x, 128x)   2x
  res = s->set_colorbar(s, 0);                          // Farbbalken     (off/on)   off 
  res = s->set_whitebal(s, 1);                          // WeiรŸbalance    (off/on)    on
  res = s->set_gain_ctrl(s, 1);                         // AGC            (off/on)    on
  res = s->set_exposure_ctrl(s, 1);                     // AEC            (off/on)    on               
//  res = s->set_hmirror(s, val);                         // H-Mirror       (off/on) 
//  res = s->set_vflip(s, val);                           // V-Flip         (off/on) 
//  res = s->set_awb_gain(s, val);                        // Verstรคrkung AWB
//  res = s->set_agc_gain(s, val);                        // Verstรคrkung AGC
//  res = s->set_aec_value(s, val);                       // Wert AEC       (0...1200)  
//  res = s->set_aec2(s, val);                            // Wert AEC2
  res = s->set_dcw(s, 1);                             // Downsize       (off/on)    on  
  res = s->set_bpc(s, 0);                             //                (off/on)   off
  res = s->set_wpc(s, 1);                             //                (off/on)    on
  res = s->set_raw_gma(s, 1);                         // RAW-Gamma      (off/on)    on
  res = s->set_lenc(s, 1);                            // Linsenkorr.    (off/on)    on 
//  res = s->set_special_effect(s, val);                  // Special Effekt 
//  res = s->set_wb_mode(s, val);                         // WB Mode         (Auto/Sunny/..) 
  res = s->set_ae_level(s, 0);                        // AE Level        (-2...+2)    0
}

BUG

Describe the bug
Error when trying to send double data to firebase through a json object: "bad request, Invalid data; couldn't parse JSON object. Are you sending a JSON object with valid key names?".

This happens when I try to send a double value of 0.

Printing the json object I see that the sensor data (double) is being displayed as "0." when this error occurs. Whenever I set some other value to this sensor different than 0, e.g. 0.1, everything works fine...

To Reproduce
FirebaseJson json;
double doubleVariable = 0;

json.set(pathVariable, doubleVariable);

if (!Firebase.updateNode(gFirebaseData, path, json)) {
Serial.println(gFirebaseData.errorReason());
return false;
}

IDE and its version:

  • Arduino
  • 1.8.10

ESP32 Arduino Core SDK version

  • 1.0.4

FirebaseESP32 version

  • 3.5.9

FirebaseJson version

  • 2.2.7

help:with accessing particular json path data.

hi there,
thanks for the library.
i need to access the particular json key data.
is there any way to access the particular key data with out using json.getiterator() function, because we need to put the particular array value to get the key and data.
thank you

HELP: SPIFFS File I/O to firebase

Hi Mobizt

(Sorry if I repeat this question from closed issue "Save Data to Internal Memory ...." , please delete this new issue if this is repeat and you can help in the other thread)

Is it possible to "setfile" from SPIFF as follows:
Firebase.setFile(firebaseData, path, "/myfile.txt", StorageType::SPIFFS)
I see your QueueStorageType in your answer above, but it means one has to setup a que.
How about just reading from SPIFFS storage and doing file I/O from firebase?

Thank you

RAM usage improvement?

Hello,

I'm using the Firebase library in my project on ESP32 Wroom, it doesn't have additional PSRAM, so there is not too much free RAM to use.
What I've noticed is that my ESP32 Free Heap is 51292 after boot. I've compared Free Heap to the library IOXhop_FirebaseESP32 which gives me ~94700 after boot with the same code as used with your library.
Do you think there is space for RAM usage improvement?

How to delete old history data automatically

When we concern about the growth of data stores in the database.

We may delete the old data manually or with the help of other cloud functions.

With this Firebase library, you can use Query to select the old data at a specific node which its timestamp value exceeds the duration that we want to keep our data.

If our data structure is similar to the below picture.

Untitled

Which we have the sensor data that shore periodically at some interval. The data was pushed to Firebase which Firebase server creates the random UID for our new data as in the picture.

We also push timestamp (in seconds from midnight January 1, 1970) along with our sensor values. We will use this timestamp for the data query.

Now to query the data with a timestamp, we need to set the system time of device and set the database rules for indexing the data that we want to query (the node named time for this case).

To set the system time to the device (ESP32) we use this helper function, setClock.

bool setClock(float gmtOffset, float daylightOffset)
{
  configTime((gmtOffset) * 3600, (daylightOffset) * 60, "pool.ntp.org", "time.nist.gov", NULL);

  time_t now = time(nullptr);
  int cnt = 0;
  while (now < 8 * 3600 * 2 && cnt < 20)
  {
    delay(50);
    now = time(nullptr);
    cnt++;
  }

  bool clockReady = now > 8 * 3600 * 2;
  return clockReady;
}

For setting the Firebase's database rules we need this helper function, setDatabaseRules.

void setDatabaseRules()
{
  if (Firebase.getRules(firebaseData))
  {
    FirebaseJsonData jdata;
    FirebaseJson &json = firebaseData.jsonObject();
    bool ruleExisted = false;
    //SENSOR is the path which we want to query its children nodes
    String path = "rules/SENSOR/.indexOn";
    json.get(jdata, path);
    if (jdata.success && jdata.stringValue == "time")
      ruleExisted = true;

    if (!ruleExisted)
    {
      json.set(path, "time");
      String rules = "";
      json.toString(rules, true);
      if(!Firebase.setRules(firebaseData, rules)){
		 Serial.println(firebaseData.errorReason()); 
	  }
    }

    json.clear();
  }
}

After we call setDatabaseRules, our database rules will be something like this

Untitled2

The rules SENSOR/.indexOn was added and its value is time.

Don't worry about .read and.write rules which can be the same as the above picture or be "true" in your case.

Now we are ready to query the database data with a specific time interval.

Here is the full code.

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


#define WIFI_SSID "xxxxxxxxxxxxx"
#define WIFI_PASSWORD "xxxxxxxxxx"
#define FIREBASE_HOST "xxxxxxxx.firebaseio.com"
#define FIREBASE_AUTH "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"

FirebaseData firebaseData;

void clearDatabase();
void setDatabaseRules();
bool setClock(float gmtOffset, float daylightOffset);


void setup() {

  Serial.begin(115200);

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("connected with IP : ");
  Serial.println(WiFi.localIP());
  Serial.println();

  Serial.print("Setup Clock... ");

  //if Timezone offset is 3
  if (setClock(3, 0))
    Serial.println("OK");
  else
    Serial.println("FAILED");

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

  Firebase.reconnectWiFi(true);

  //Set the size of HTTP response buffers in the case where we want to work with large data.
  firebaseData.setResponseSize(1024);

  Serial.println("Add index to database rules");
  setDatabaseRules();
}

void loop() {


  //Code to push new data here
  //...

  //To delete old database
  Serial.println("Delete old database");
  clearDatabase();

  delay(5000);

}

void clearDatabase() {

  String sensorPath = "/SENSOR/-88116932";

  QueryFilter query;

  //Get the current timestamp
  time_t current_ts = time(nullptr);

  //Define the total seconds of duration form now that you need to keep the data
  unsigned long dataRetentionPeriod = 30 * 60 * 60 * 24; // 30 days

  double lastTS = current_ts - dataRetentionPeriod;

  //query for all data begin with time (timestamp) 0 to the last timestamp
  //limit the return result only last 8 data.
  query.orderBy("time").startAt(0).endAt(lastTS).limitToLast(8);

  if (Firebase.getJSON(firebaseData, sensorPath, query))
  {

    if (firebaseData.dataType() == "json" && firebaseData.jsonString().length() > 4)
    {
      //parse the query result
      FirebaseJson *myJson = firebaseData.jsonObjectPtr();
      size_t len = myJson->iteratorBegin();
      String key, value;
      int otype = 0;
      for (size_t i = 0; i < len; i++)
      {
        yield();
        myJson->iteratorGet(i, otype, key, value);
        if (otype == JSON_OBJECT && key.length() > 1)
        {
          //Here is the path of obsolete data in which its timestamp exceeds the specific period.
          String path = sensorPath + "/" + key;
          //Delete that data
          Firebase.deleteNode(firebaseData, path);
        }
      }
      myJson->iteratorEnd();
      myJson->clear();
    }
  }
  else
  {
    Serial.println(firebaseData.errorReason());
  }

  query.clear();
}

void setDatabaseRules()
{
  if (Firebase.getRules(firebaseData))
  {
    FirebaseJsonData jdata;
    FirebaseJson &json = firebaseData.jsonObject();
    bool ruleExisted = false;

    //SENSOR is the path which we want to query its children nodes
    String path = "rules/SENSOR/.indexOn";
    json.get(jdata, path);
    if (jdata.success && jdata.stringValue == "time")
      ruleExisted = true;

    if (!ruleExisted)
    {
      json.set("rules/SENSOR", "time"); 
      json.set(path, "time"); 
      String rules = "";
      json.toString(rules, true);
      if (!Firebase.setRules(firebaseData, rules)) {
        Serial.println(firebaseData.errorReason());
      }
    }

    json.clear();
  }
}

bool setClock(float gmtOffset, float daylightOffset)
{
  configTime((gmtOffset) * 3600, (daylightOffset) * 60, "pool.ntp.org", "time.nist.gov", NULL);

  time_t now = time(nullptr);
  int cnt = 0;
  while (now < 8 * 3600 * 2 && cnt < 20)
  {
    delay(50);
    now = time(nullptr);
    cnt++;
  }

  bool clockReady = now > 8 * 3600 * 2;
  return clockReady;
}

If you have a lot of old data to be deleted, every time you call clearDatabase, the last 8 obsoleted data will be deleted.

This approach doesn't require any server or system to manage data retention.

Firebase only works a while

I'm using the library on ESP32 WROOM32 DevKit, and It works but only a few seconds/minutes and after that stop getting/pushing data to the Firebase Database and stop sending Serial.print("Loop running "); seems to freeze during firebase call.

The code is:

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

#define FIREBASE_HOST "-----------.firebaseio.com"
#define FIREBASE_AUTH "----------------------------------------"
#define WIFI_SSID "-------------------"
#define WIFI_PASSWORD "----------------"

FirebaseData firebaseData;

String sID = WiFi.macAddress();

String sboton1 = sID + "/sboton1";

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

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

}

void loop()
{

Serial.print("Loop running ");

if (Firebase.getString(firebaseData, sboton1)) {
Serial.println("Obteniendo el valor de sboton1: ");
Serial.println(firebaseData.stringData());
if (firebaseData.stringData() == "on") {
Firebase.setString(firebaseData, sboton1, "off");
}
}

delay(1000);

}

Firebase issue 1

`

What do you call "Path"

Hello,
Could you tell me what does the String "path" means ? I tried to let it empty, to put the database name or a variable name, but nothing's working.. I get "Path xxxx is not exist"

Thanks in advance for your help.

HELP: firebase.pushJSON with JSONObject created by ArduinoJSON


name: Help and how to firebase.pushJSON with non-hardcoded JSON data?


const int BUFFER_SIZE = JSON_OBJECT_SIZE(3);
StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
JsonObject& logData = jsonBuffer.createObject();
logData["dBValue"] = 45.0;
logData["time"] = "2019-05-15T15:00:25";
logData["buttonState"] = 0;
Firebase.pushJSON(firebaseData, data_log + device_id, logData);

With the above codes, I had such an error.

no matching function for call to 'FirebaseESP32::pushJSON(FirebaseData&, StringSumHelper&, ArduinoJson::JsonObject&)'

I have tried using ArduinoJSON v5/v6, but JSONObject isn't supported by firebase.pushJSON. I wonder how other dudes include variables in the jsonData. From the example, the data is hardcoded though.
String jsonData = "{\"parent_001\":\"parent 001 text\", \"parent 002\":{\"child_of_002\":123.456}}";

Restore Error: Could not read/write backup file

Hi,
I'm trying to use the restore function, but is returning me:

REASON: Could not read/write backup file

The backup is working fine, and the file is being created in my SD card. I just cant restore this file. I created a edited a little the exemple code to post here:

`
//Define Firebase Data object
FirebaseData firebaseData;

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

//Print to see stack size and free memory
UBaseType_t uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL);
Serial.print("Stack: ");
Serial.println(uxHighWaterMark);
Serial.print("Heap: ");
Serial.println(esp_get_free_heap_size());

Serial.println("------------------------------------");
Serial.println("Backup test...");

//Provide specific SD card interface
//Firebase.sdBegin(14, 2, 15, 13); //SCK, MISO, MOSI,SS for TTGO T8 v1.7 or 1.8

//Download and save data at defined database path to SD card.
//{TARGET_NODE_PATH} is the full path of database to backup and restore.

if (!Firebase.backup(firebaseData, "/ESP32_Test", "/bk"))
{
Serial.println("FAILED");
Serial.println("REASON: " + firebaseData.fileTransferError());
Serial.println("------------------------------------");
Serial.println();
}
else
{
Serial.println("PASSED");
Serial.println("BACKUP FILE: " + firebaseData.getBackupFilename());
Serial.println("FILE SIZE: " + String(firebaseData.getBackupFileSize()));
Serial.println("------------------------------------");
Serial.println();
}

Serial.println("------------------------------------");
Serial.println("Restore test...");

//Restore data to defined database path using backup file on SD card.
//{TARGET_NODE_PATH} is the full path of database to restore

if (!Firebase.restore(firebaseData, "/ESP32_Test", "/bk/ESP32_Test.json"))
{
Serial.println("FAILED");
Serial.println("REASON: " + firebaseData.fileTransferError());
Serial.println("------------------------------------");
Serial.println();
}
else
{
Serial.println("PASSED");
Serial.println("BACKUP FILE: " + firebaseData.getBackupFilename());
Serial.println("------------------------------------");
Serial.println();
}

//Quit Firebase and release all resources
Firebase.end(firebaseData);

}

void loop()
{
}`

HELP

I updated the library to the most recent version and my code stopped working.

I was using Firebase.updateNode(firebaseData, "", json) to upload a single json structure to firebase, but now I get an error.

After this update, I feel that the documentation is very confusing and it is making a lot harder to figure out what to do. For example, the "Changes from earlier version" section states that "getJson, setJson, pushJson, updateNode and updateNodeSilent." have been changed, but does this mean they are not supported anymore? Also, there are a lot of functions with similar names such as "setJsonData" and "setJson", but I dont know what's the difference.

Finally, you could add a content table for the functions descriptios to make it easier to find and understand their usage.

Obs.: Great library!

HELP: Not sure why the two level deep data is not accessed.

Hi,

Thank you for your quick comments last time. Also thank you
for the excellent library.

I was able to get the first level firebase access going with your kind comments last time.
I hope you can help me for this as well.

The problem I am having is using query with a second level data in the realtime database.

I took the Basic.ino and updated it as before. This time I inserted a second level data
when the code runs and accesses the firebase the first time. Then in the loop, I try to access the two level deep data : /post/post2.

`

================================ Basic.ino modified Code:
/*
 * Created by K. Suwatchai (Mobizt)
 * 
 * Email: [email protected]
 * 
 * Github: https://github.com/mobizt
 * 
 * Copyright (c) 2019 mobizt
 *
*/
//This example shows how to read, store and update database using get, set, push and update functions.
//Required HTTPClientESP32Ex library to be installed  https://github.com/mobizt/HTTPClientESP32Ex

#include <WiFi.h>
#include "FirebaseESP32.h"
#include "mycredentials.h"
#include <Preferences.h>
#include <ArduinoJson.h>

#define FIREBASE_HOST MYHOST //Do not include https:// in FIREBASE_HOST
#define FIREBASE_AUTH MYDBSECRET
#define WIFI_SSID mySSID
#define WIFI_PASSWORD myPWD

FirebaseData firebaseData;

static int av1 = 0; // add some values into strings
static int av2 = 1;

void pushmyData() {
String k1 = "{\"data1\":\"value";
String k2 = "\", \"data2\":{\"child2\":\"_value";
String ke = "\"}}";
//String updateData = "{\"data1\":\"value\", \"data2\":{\"child2\":\"_value\"}}";

String updateData = k1+String(av1)+k2+String(av2)+ke;
   av1++;
   av2++;  
   String s= "Kaboom"+String(av2);
   String s_json = "{\"NewData\":\"Kaboom"+String(av2)+"\"}";
   Serial.println(" My s_json string is : "+s_json);
   String SecondLevel = "{\"post\":{\"post1\":{\"author\":\"TOM\",\"vegitable\":\"tomato\"},\"post2\":{\"author\":\"JERRY\",\"vegitable\":\"potato\"}}}";
   if(av1 == 1 ) { 
      if( Firebase.setString(firebaseData, "/NewData", s) ) {
          Serial.println("Done setString /NewData:"+s);  // should post "Kaboom2" to node "NewData"
      } else {
          Serial.println(firebaseData.errorReason());
      }
      if( Firebase.updateNode(firebaseData, "/", SecondLevel) ) {
          Serial.println("Done second level setString /:"+SecondLevel);  // should pust "Kaboom2" to node "NewData"
      } else {
          Serial.println(firebaseData.errorReason());
      }
  } else {
      if (Firebase.updateNode(firebaseData, "/", s_json)) { // should add "Kaboom3" to "Kaboom2"
          Serial.println("Done updateNode "+s_json);     // Check firebase data base, to see if 
      } else {                                               // The value of NewData is "Kaboom2Kaboom3"
          Serial.println(firebaseData.errorReason());      // does not seem to be working          
      }
  }

if (Firebase.updateNode(firebaseData, "/", updateData)) {

  //Success, then try to read the payload value

  //Database path that updated
  Serial.println(firebaseData.dataPath());

  //Data type at updated database path
  Serial.println(firebaseData.dataType()); //Should be "json" -- yes it is

  //Print the JSON string payload that returned from server
  Serial.println(firebaseData.jsonData()); //OK, this works

  //Actual sent payload JSON data
  Serial.println(updateData);

} else {
  //Failed, then print out the error detail
  Serial.println(firebaseData.errorReason());
}

}

// call this routine in loop to see values that are read back 
void query_firebase () {
QueryFilter query;
query.orderBy("data1"); // try to get only data1

if (Firebase.getJSON(firebaseData, "/", query)) // gets the complete data base at "/"
{
  //Success, then try to read the JSON payload value 
  Serial.println(firebaseData.jsonData());   // prints everything, even if there is a ".indexOn": "data1" on-line at firebase
}
else
{
  //Failed to get JSON data at defined database path, print out the error reason
  Serial.println(firebaseData.errorReason());
}
//Clear all query parameters
query.clear();

}

// call GetSpecificData() in the main loop, and see if you can get specific
// data for node data2, child _data2, with the value

void GetSpecificData() {
  QueryFilter query;
  query.orderBy("child2");;
  String k="No News";
    if(Firebase.getString(firebaseData,"/NewData", k) ) {
      Serial.println("Got NewData as: "+k);
    } else {
      Serial.println(firebaseData.errorReason());
    }
    if (Firebase.getJSON(firebaseData, "/data2", query)) {
    //Success, then read the payload value
    //Make sure payload value returned from server is integer
    //This prevent you to get garbage data
    
    StaticJsonBuffer<200> jsonBuffer;
    JsonObject& mData = jsonBuffer.parseObject(firebaseData.jsonData());
    mData.printTo(Serial);
    Serial.println("");
    const char* val = mData["child2"];
      Serial.print("Value extracted from json key value pair: ");
      Serial.println(val);
  } else {
    //Failed, then print out the error detail
    Serial.println(firebaseData.errorReason());
  }
  //Clear all query parameters
 query.clear();
}

void GetSpecificSecondLevelData() {
  QueryFilter query;
  query.orderBy("post2");
    if (Firebase.getJSON(firebaseData, "/post", query)) {
    StaticJsonBuffer<200> jsonBuffer;
    JsonObject& mData = jsonBuffer.parseObject(firebaseData.jsonData());
    mData.printTo(Serial);
    Serial.println("");
    const char* val = mData["vegitable"];
      Serial.print("Posted Value extracted from vegitable: ");
      Serial.println(val);
  } else {
    //Failed, then print out the error detail
    Serial.println(firebaseData.errorReason());
  }
  //Clear all query parameters
 query.clear();
}


//////
void setup()
{

  Serial.begin(115200);
  Serial.println();
  Serial.println();
  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);
  Firebase.setMaxRetry(firebaseData, 3);
  Firebase.setMaxErrorQueue(firebaseData, 30);
}

void loop()
{
#define SomeDelay 10000
  Serial.println("======================== Pushing data ================================");
  pushmyData();
  delay(SomeDelay);
  Serial.println("======================== Get specific data ================================");
  GetSpecificData();
  delay(SomeDelay);
  Serial.println("======================== query specific second level data ================================");
  GetSpecificSecondLevelData(); //query_firebase ();
  delay(SomeDelay);
}

=================  Firebase realtime db
{
  "NewData" : "Kaboom4",
  "data1" : "value2",
  "data2" : {
    "child2" : "_value3"
  },
  "post" : {
    "post1" : {
      "author" : "TOM",
      "vegitable" : "tomato"
    },
    "post2" : {
      "author" : "JERRY",
      "vegitable" : "potato"
    }
  }
}
====================== rules
{
    "rules": {
    ".indexOn": ["post", 
                 "post/post1",
                 "post/post2",
                 "post/post1/author",
                 "post/post1/vegitable",
                 "post1/author",
                 "post1/vegitable", 
                 "post/post2/author",
                 "post/post2/vegitable",
                 "post2/author",
                 "post2/vegitable", 
                 "NewData", 
                 "data1",
                 "data2/child2",
                 "child2"], 
     "post":{
       ".read": true,
         ".write": true,
             ".indexOn": ["post1","post2"],
               "post1":{
                 ".indexOn":["author", "vegitable"],
                   "author": {
                   ".read": true,
                     ".write": true
                    },
                   "vegitable": {
                   ".read": true,
                     ".write": true
                    }
                   },
               "post2": {
                 ".indexOn":["author", "vegitable"],
                   "author": {
                   ".read": true,
                     ".write": true
                    },
                   "vegitable": {
                   ".read": true,
                     ".write": true
                    }
               } 
             },
    "NewData": {
          ".read": true,
          ".write": true
      },
      "data1": {
           ".read": true,
           ".write": true
      },
      "data2": {
        ".indexOn": "child2",
          "child2": {
            ".read":true,
            ".write":true
          }
      }
    }
}
====================== Output

======================== Pushing data ================================
 My s_json string is : {"NewData":"Kaboom2"}
Done setString /NewData:Kaboom2
Done second level setString /:{"post":{"post1":{"author":"TOM","vegitable":"tomato"},"post2":{"author":"JERRY","vegitable":"potato"}}}
/
json
{"data1":"value0","data2":{"child2":"_value1"}}
{"data1":"value0", "data2":{"child2":"_value1"}}
======================== Get specific data ================================
Got NewData as: Kaboom2
{"child2":"_value1"}
Value extracted from json key value pair: _value1
======================== query specific second level data ================================
{}
Posted Value extracted from vegitable: 
======================== Pushing data ================================
 My s_json string is : {"NewData":"Kaboom3"}
Done updateNode {"NewData":"Kaboom3"}
/
json
{"data1":"value1","data2":{"child2":"_value2"}}
{"data1":"value1", "data2":{"child2":"_value2"}}
======================== Get specific data ================================
Got NewData as: Kaboom3
{"child2":"_value2"}
Value extracted from json key value pair: _value2
======================== query specific second level data ================================
{}
Posted Value extracted from vegitable: 
======================== Pushing data ================================
 My s_json string is : {"NewData":"Kaboom4"}
Done updateNode {"NewData":"Kaboom4"}
/
json
{"data1":"value2","data2":{"child2":"_value3"}}
{"data1":"value2", "data2":{"child2":"_value3"}}
======================== Get specific data ================================
Got NewData as: Kaboom4
{"child2":"_value3"}
Value extracted from json key value pair: _value3
======================== query specific second level data ================================
{}
Posted Value extracted from vegitable: 
======================== Pushing data ================================
 My s_json string is : {"NewData":"Kaboom5"}
Done updateNode {"NewData":"Kaboom5"}
/
json
{"data1":"value3","data2":{"child2":"_value4"}}
{"data1":"value3", "data2":{"child2":"_value4"}}
======================== Get specific data ================================
Got NewData as: Kaboom5
{"child2":"_value4"}
Value extracted from json key value pair: _value4
======================== query specific second level data ================================
{}
Posted Value extracted from vegitable: 
======================== Pushing data ================================
 My s_json string is : {"NewData":"Kaboom6"}
Done updateNode {"NewData":"Kaboom6"}
/
json
{"data1":"value4","data2":{"child2":"_value5"}}
{"data1":"value4", "data2":{"child2":"_value5"}}
======================== Get specific data ================================
Got NewData as: Kaboom6
{"child2":"_value5"}
Value extracted from json key value pair: _value5
======================== query specific second level data ================================
{}
Posted Value extracted from vegitable: 
======================== Pushing data ================================
 My s_json string is : {"NewData":"Kaboom7"}
Done updateNode {"NewData":"Kaboom7"}
/
json
{"data1":"value5","data2":{"child2":"_value6"}}
{"data1":"value5", "data2":{"child2":"_value6"}}
======================== Get specific data ================================
Got NewData as: Kaboom7
{"child2":"_value6"}
Value extracted from json key value pair: _value6
======================== query specific second level data ================================
{}
Posted Value extracted from vegitable: 
======================== Pushing data ================================
 My s_json string is : {"NewData":"Kaboom8"}
Done updateNode {"NewData":"Kaboom8"}
/
json
{"data1":"value6","data2":{"child2":"_value7"}}
{"data1":"value6", "data2":{"child2":"_value7"}}


`

HELP FSR402 doesn't work with Firebase-ESP32

Specs

  • Board: Wemos Lolin32 Lite
  • Sensor: FSR402 (connected to GPIO 4)
  • Library version: lateset (3.5.4)

const int sensorPin = 4;
int pressureVal;

Issue

Hi @mobizt, my FSR402 works just fine without Firebase; But if I incorporate Firebase-ESP32 into the code, the reading of the sensor pin outputs a constant value 4095 for no reason.

What I have tried

  • commenting Firebase codes in the loop didn't solve the issue (commenting codes in the setup did though)
  • MPU6050 (6DOF sensor) works well with Firebase-ESP32

Here it's one piece of my code.

Serial.println(pressureVal);
setInt(firebaseData, path, pressureVal);
//also try with
//pushInt(firebaseData, path, pressureVal);

Do you have any idea where might go wrong?
Thanks!

HELP Which protocol does esp32 use for pushing data to Firebase?

Sorry this question isnt about your bug. This is question for which protocol do you use to push data.
In the case of Firebase Realtime Database, clients will be connected to the database and will maintain an open bidirectional connection via websockets i found this one said Firebase use websocket to receive or push data to client. in you code, i see you use HTTP protocol. i have confuse a bit.

Could you confirm which one is correct?

HELP:returning json data despite of posting bool data from hardware.

hi,
i am posting bool data from my hardware to data base. each time strem data function triggered and returning me the json data instead of bool data.
here is my working code.

#include <WiFi.h>
#include <FirebaseESP32.h>
#define WIFI_SSID "xxxxxxx"
#define WIFI_PASSWORD "xxxxxxx"
#define FIREBASE_HOST "xxxxxxxxx"
#define FIREBASE_AUTH "xxxxxxxxx"
const int relayPin1 = 19;
//Define Firebase data object
FirebaseData firebaseData;
FirebaseJsonData JsonData;
bool status1 = false;
String path = "xxxxx/xxx/xx/xx/xx";
int temp[]={1};
void printResult(FirebaseData &data);

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("------------------------------------");
    Serial.println("Can't begin stream connection...");
    Serial.println("REASON: " + firebaseData.errorReason());
    Serial.println("------------------------------------");
    Serial.println();
  }
}


void loop()
{
  if (Firebase.readStream(firebaseData) && firebaseData.streamAvailable())
  {
    Serial.println("------------------------------------");
    Serial.println("Stream Data available...");
    Serial.println("STREAM PATH: " + firebaseData.streamPath());
    Serial.println("EVENT PATH: " + firebaseData.dataPath());
    Serial.println("DATA TYPE: " + firebaseData.dataType());
    Serial.println("EVENT TYPE: " + firebaseData.eventType());
    Serial.print("VALUE: ");
    printResult(firebaseData);
   // Serial.println("------------------------------------");
    Serial.println();
        if (digitalRead(4)==HIGH)
  {
  Firebase.setBool(firebaseData,path+"/switch_1/status",true);
  }
  else{
   Firebase.setBool(firebaseData,path+"/switch_1/status",false); 
  }
  }
}
void printResult(FirebaseData &data)
{
  if (data.dataPath() == "/switch_1/status" && data.dataType() == "boolean") {
    temp[0] = data.boolData(); digitalWrite(relayPin1, !data.boolData()); Serial.println(data.boolData());
  }
    else if (data.dataType() == "json")
  {   
      Serial.println();
      FirebaseJson &json = data.jsonObject();
      json.get(JsonData, "/switch_1/status");
      temp[0] = JsonData.boolValue;
      digitalWrite(relayPin1, !temp[0]);
      Serial.print(temp[0]);          
  }
}

when i am changing the firebase data from firebase console it was returning bool data which is correct.
problem with when i triggered the data from my hardware.
thank you. please suggest me the needful.

HELP .....

Hi, I would like to thank you for actively maintaining this library. I need one help. I have gone through all the documentation. I'm not able to use a character array in json.set function. I need to send the character array of 7 bytes ( made of numbers) to RTDB as json . Please guide me for the same.

Thanking you in advance, Thank you, Thank you........

Error on FirebaseESP32.cpp str.erase(std::remove

Hi, i'm having the following error message when i compile my project:

...\Arduino\libraries\Firebase-ESP32-master\src\FirebaseESP32.cpp: In member function 'std::__cxx11::string FirebaseESP32::trim(std::__cxx11::string&)':

...\Arduino\libraries\Firebase-ESP32-master\src\FirebaseESP32.cpp:2030:13: error: 'remove' is not a member of 'std'

str.erase(std::remove(str.begin(), str.end(), '\r'), str.end());

I have commented the lines 2030 and 2031. Doing this i can compile and download. Everything seems to be ok with that.
mobizt Thaks for this amazing work you did and for sharing this great lib with us

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

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:

  • Arduino
  • 1.8.10
  • FirebaseESP32 3.5.9/3.6.2

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() {
}

Help me please

I have a question With Wifi Connection. Do They have Support?.

Setting the data only once in the database.

Assume I have the following setup :

//This example shows how to read, store and update database using get, set, push and update functions.
//Required HTTPClientESP32Ex library to be installed  https://github.com/mobizt/HTTPClientESP32Ex

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


#define FIREBASE_HOST "YOUR_FIREBASE_PROJECT.firebaseio.com" //Do not include https:// in FIREBASE_HOST
#define FIREBASE_AUTH "YOUR_FIREBASE_DATABASE_SECRET"
#define WIFI_SSID "YOUR_WIFI_AP"
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD"


//Define Firebase Data object
FirebaseData firebaseData;

void setup()
{

  Serial.begin(115200);
  Serial.println();
  Serial.println();

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

  //Quit Firebase and release all resources
  Firebase.end(firebaseData);
}

void loop()
{
  if (Firebase.pushInt(firebaseData, "/test/append", 0)) {
    Serial.println("Success");
  } else {
    Serial.println(firebaseData.errorReason());
  }
}

I am also running a MQTT server on the same ESP32 device and hence the MQTT has to publish a message on the push of a button. Is it possible for me to add the data to the database only once for every push of a button rather than continuously populate the database ?

two functions tested appear not to be working:append string and getting specific value

Hi tried this library and (a) could not append string and (b) could not get specific value of node.
see code below. Please let me know what I am missing?

#include "FirebaseESP32.h"
FirebaseData firebaseData;
static int av1 = 0; // add some values into strings
static int av2 = 1;

void init_firebase() {
Firebase.begin("myProject.firebaseio.com", "1234567890_blah_blah___"); // replace with your proj & secret 
Firebase.reconnectWiFi(true);
Firebase.setMaxRetry(firebaseData, 3);
Firebase.setMaxErrorQueue(firebaseData, 30);
}

//Append many data (multiple keys included nest data) to the database at "/test/update"
// call pushmyData in the loop for updating data1 and data2 values
// also try to setString NewData, and try to append to the string
void pushmyData() {
String k1 = "{\"data1\":\"value";
String k2 = "\", \"data2\":{\"_data2\":\"_value";
String ke = "\"}}";
//String updateData = "{\"data1\":\"value\", \"data2\":{\"_data2\":\"_value\"}}";

String updateData = k1+String(av1)+k2+String(av2)+ke;
   av1++;
   av2++;  
   String s= "Kaboom"+String(av2);
   if(av1 == 1 ) { 
      if( Firebase.setString(firebaseData, "/NewData", s) ) {
          Serial.println("Done setString /NewData:"+s);  // should pust "Kaboom2" to node "NewData"
      } else {
          Serial.println(firebaseData.errorReason());
      }
  } else {
      if (Firebase.pushString(firebaseData, "/NewData", s)) { // should add "Kaboom3" to "Kaboom2"
          Serial.println("Done pushString /NewData:"+s);     // Check firebase data base, to see if 
      } else {                                               // The value of NewData is "Kaboom2Kaboom3"
          Serial.println(firebaseData.errorReason());			// does not seem to be working					
      }
  }

if (Firebase.updateNode(firebaseData, "/", updateData)) {

  //Success, then try to read the payload value

  //Database path that updated
  Serial.println(firebaseData.dataPath());

  //Data type at updated database path
  Serial.println(firebaseData.dataType()); //Should be "json" -- yes it is

  //Print the JSON string payload that returned from server
  Serial.println(firebaseData.jsonData()); //OK, this works

  //Actual sent payload JSON data
  Serial.println(updateData);

} else {
  //Failed, then print out the error detail
  Serial.println(firebaseData.errorReason());
}

}

// call this routine in loop to see values that are read back 
void query_firebase () {
QueryFilter query;
query.orderBy("data1"); // try to get only data1

if (Firebase.getJSON(firebaseData, "/", query)) // gets the complete data base at "/"
{
  //Success, then try to read the JSON payload value 
  USBPrintln(firebaseData.jsonData());   // prints everything, even if there is a ".indexOn": "data1" on-line at firebase
}
else
{
  //Failed to get JSON data at defined database path, print out the error reason
  USBPrintln(firebaseData.errorReason());
}
//Clear all query parameters
query.clear();

}

// call GetSpecificData() in the main loop, and see if you can get specific
// data for node data2, child _data2, with the value

void GetSpecificData() {
  QueryFilter query;
  query.orderBy("data2");
  query.startAt("_data2");
  query.endAt("_data2");
  String k="No News";
    if(Firebase.getString(firebaseData,"/NewData", k) ) {
      Serial.println("Got NewData as: "+k);
    } else {
      Serial.println(firebaseData.errorReason());
    }
    if (Firebase.getJSON(firebaseData, "/", query)) {
    //Success, then read the payload value
    //Make sure payload value returned from server is integer
    //This prevent you to get garbage data
    if (firebaseData.dataType() == "json") {
      Serial.println(firebaseData.jsonData()); 
    }
  } else {
    //Failed, then print out the error detail
    Serial.println(firebaseData.errorReason());
  }
  //Clear all query parameters
 query.clear();
}

HELP: how to check the internet status thorugh firebase esp32 lib

hi there,
i need to check the live internet status. I ve gone through the library. I found httpCode and httpConnected () functions are for checking status server connection.
But i failed to get the live internet check through those functions.
Is there any particular function availble to know the internet check?
Thank you.

ENHANCEMENT

This is not really a problem but a request: do you think it is possible to implement the use of the FireBase Storage (not FireBase DataBase)?
Example: store a picture as a file.
Thank you,
Alain

get error with library

I get this error when i just try to compile the library

fatal error: HTTPClientESP32Ex.h: No such file or directory

Help anyone?

HELP StreamData limit Esp32

Hello,
is there a limit on how many StreamData instances can be initalized ? Because as soon as i use more than two for a stream with callback functions the streams stop working.

// basics
  Firebase.begin(this->config.FIREBASE_ID.c_str(), this->config.FIREBASE_SECRET.c_str());
  Firebase.reconnectWiFi(true);
  Firebase.setMaxRetry(firebaseData, 3);
  Firebase.setMaxErrorQueue(firebaseData, 30);
  Firebase.enableClassicRequest(firebaseData, true);

  // check connection
  Firebase.getBool(firebaseData, "/online") ? Serial.println("[INFO] Firebase initialized") : Serial.println("[ERROR] Firebase error: " + firebaseData.errorReason());
  if (firebaseData.dataType() == "boolean")
  {
    firebaseData.boolData() ? Serial.println("[INFO] Firebase database is online") : Serial.println("[INFO] Firebase database is offline");
    Firebase.setBool(firebaseData, this->config.FIREBASE_PATH + "/online", true);
  }

  /**** setup streams ****/
  // fbOnPing
  if (!Firebase.beginStream(test, (this->config.FIREBASE_PATH + "/cmd/ping").c_str()))
    Serial.println("[Error] Stream: " + test.errorReason());
  Firebase.setStreamCallback(test, fbOnPing, fbOnPingTimeout);

  // fbOnImpulse
  if (!Firebase.beginStream(fbDOnImpulse, (this->config.FIREBASE_PATH + "/cmd/impulse").c_str()))
    Serial.println("[Error] Stream: " + fbDOnImpulse.errorReason());
  Firebase.setStreamCallback(fbDOnImpulse, fbOnImpulse, fbOnImpulseTimeout);

  // fbOnLight
  if (!Firebase.beginStream(fbDOnLight, (this->config.FIREBASE_PATH + "/cmd/light").c_str()))
    Serial.println("[Error] Stream: " + fbDOnLight.errorReason());
  Firebase.setStreamCallback(fbDOnLight, fbOnLight, fbOnLightTimeout);

  Serial.println("[INFO] setupFirebase done");

image

Is this the wrong way to initialize multiple callback streams?

What am I missing? Any help is appreciated!

Device creashes when calling Firebase.begin()

When i write the line Firebase.begin("FIREBASE_ID", "SECRET") it continues to crash with the log

rst:0x3 (SW_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0, SPIWP:0xee clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 mode:DIO, clock div:1 load:0x3fff0018,len:4 load:0x3fff001c,len:1100 load:0x40078000,len:10088 load:0x40080400,len:6380 entry 0x400806a4

help pls!

FIle format

Hi,
first of all I would like to check if the text in README regarding file storing and reading is correct. The text says:

The following example showed how to store file data to Flash memory at "/test/file_data".

if (Firebase.setFile(firebaseData, StorateType::SPIFFS, "/test/file_data", "/test.txt"))

If I read this correctly then this is not correct, because setFile stores the file in Firebase not to SPIFFS.. I think there should be FirebasegetFile in the example.

Anyway, my question is if you can share/advise how to grab the file String encoded in the library specific 64BASE format. I need to grab the file from the Firebase node in an Android app, then decode and extract the saved jpg.
For this I need to know where actually the image data start in the encoded string and how to turn them back to the original jpg file before encoding to BASE64.
I am not asking to show me how to decode , what I need is to know if I can strip out the jpg part of the stream (e.g. take the data from the second slash???) and use any available BASE64 encoders to recreate the original jpg file?
Thanks
Marian

Stream stops working when delays are used

  1. Run the stream_loop example.

  2. Change the loop method like this:

    • Remove the database update part
    • Add a delay(1000); to the bottom of the loop method.
  3. Rerun it and apply changes to the database manually.

The changes will never be noticed by the readStream method. The initial state is not even queried on the first loop.

Arduino IDE 1.8.10
ESP32 Dev Module

streamCallback gets triggered randomly

I am having this strange issue with streamCallback function. Sometimes, even if there is no change in the Firebase RTDB, callback function gets called. Can anybody please help me out?

HELP

Hi there, I've connected esp32 to firebase, after some moments there is no response from the module when I change the database values.
More Info :
I've created a task for checking internet for every 5 seconds on other core. I don't know what I have done worng got confused. Please give me suggestion that would be a great help for me.
Thank you

How to parse JSON with Library

This is the information for everyone who wants to create, modify and parse JSON with the built-in JSON maker and parser without external JSON library.

This library introduces the 3 classes i.e. FirebaseJson, FirebaseJsonArray and FirebaseJsonData for creating, edit and parse JSON data.

FirebaseJson represents the JSON object, FirebaseJsonArray is for the JSON array, and FirebaseJsonData stores the parse information when you want to parse (extract) the data from JSON object or JSON array.

Here get JSON from Firebase and parse it.

Assume that we want to parse the JSON at node /Data/sensors

if (Firebase.getJSON(firebaseData, "/Data/sensors")) {

  //FirebaseJson object that returned from getJson
  FirebaseJson &json = firebaseData.jsonObject();

  //temporary object to store the data from parsing
  //this will be reused over and over
  FirebaseJsonData data;

  //parse data by key or path, the result is in FirebaseJsonData object
  json.get(data, "/path/to/node");

  //or parse the complex nested atrray in nested object
  //json.get(data, "/path/to/node/[0]/[3]"); //Where [0] is index 0, [3] is index 3

  //parsing ok?
  if (data.success) {
    
    //We determine the type of value from parsing, you can get the string by using **data.stringValue** of all data types.
    if (data.typeNum == JSON_INT) // or data.type == "int"
      Serial.println(data.intValue);
    else if (data.typeNum == JSON_BOOL) //or data.type == "bool"
      Serial.println(data.boolValue);
    else if (data.typeNum == JSON_DOUBLE) //or data.type == "double"
      Serial.println(data.doubleValue);
    else if (data.typeNum == JSON_STRING ||  data.typeNum == JSON_NULL) //or data.type == "string" || data.type == "null"
      Serial.println(data.stringValue);
    else if (data.typeNum == JSON_ARRAY) //or data.type == "array"
    {

      //get the FirebaseJson array object
      FirebaseJsonArray myArr;
      data.getArray(myArr);
      for (size_t i = 0; i < myArr.size(); i++)
      {
        //get array data at index
        myArr.get(data, i);

        //or parse JSON object or JSON array in Array
        //myArr.get(data, "/any_child/another_child/another_one");

        //parsing success?
        if (data.success) {

          if (data.typeNum == JSON_INT)
            Serial.println(data.intValue);
          else if (data.typeNum == JSON_BOOL)
            Serial.println(data.boolValue);
          else if (data.typeNum == JSON_DOUBLE)
            Serial.println(data.doubleValue);
          else if (data.typeNum == JSON_STRING )
            Serial.println(data.stringValue);
          else if (data.typeNum == JSON_ARRAY)
          {
            //parse array in array
          }
          else if (data.typeNum == JSON_OBJECT)
          {
            //parse JSON object in array
          }
        }

      } else if (data.typeNum == JSON_OBJECT) //or data.type == "object"
      {
        //parse the nested JSON object here

        FirebaseJsonA json2;
        data.getJSON(json2);
        //parse it
        json2.get(data, "/another/path/to/node");
        Serial.println(data.stringValue);

      }
    }

  }
}

HELP: File size during PUT and GET operations

Hi Mobizt,
In the File.ino example, you have the comments indicating file size > 10K leads to unexpected
results.

However, I tested with 16K, and the file write (PUT) appears to be OK.
But GET operation truncates at ~11K, as you mention.

I am wondering if it is due to SD being slow? Does your library de-couple
the firebase read and SD write operations?

Thank you


  /*/////////////////////////////////////////////////////
  Sending large file ( > 10k) leads to unexpected result
  /////////////////////////////////////////////////////*/


  //Write demo data to file (8192 bytes)
  file = SD.open("/source.txt", FILE_WRITE);
  for (int i = 0; i < 8192; i++)
    file.write(0xf);

  file.close();

Firebase set requestes does not works anywhere.

I made some changes to my code and discoverd something strage.


    Serial.begin(115200); 

    pinMode(READY_LED, OUTPUT);

    pinMode(ACTIVITY_LED, OUTPUT);

    pinMode(ERROR_LED, OUTPUT);

    pinMode(DEFAULT_BUTT, INPUT);

    pinMode(SERVICE_BUTT, INPUT);

    preferences.begin("my-app", false);

    SPIFFS.begin(true);

    ssid=preferences.getString("ssid"); //take my wifi data

    password=preferences.getString("password");

    utente=preferences.getString("utente");



    reconnectionTime = preferences.getInt("reconnectionTime", 60000);

    delayReconnectionTime = preferences.getInt("reconnectionDelay", 60000);



    Serial.print("SSID: "); Serial.println(ssid);

    Serial.print("UTENTE: "); Serial.println(utente);

    Serial.print("PASSWORD: "); Serial.println(password);

    Serial.print("MAC: "); Serial.println(preferences.getString("macAddress"));

    if(ssid != "" && !preferences.getBool("reset"))

    {

        preferences.putBool("reset", false); //not influent

        

		createThread(&reset, "reset", &resetTask, 1); //not influent

	

        if(utente == "") //decide if we're about to connect to a standard wifi or a peap one and connect

	    connectWiFi();

	else

	    connectPEAP();



        connectMQTT();

    }

    else

    {

        preferences.putBool("reset", true);

        createAP();

    }
    
    if(WiFi.status() == WL_CONNECTED) //if i'm connected to wifi ill connect to firebase

    {
		Serial.println("Connecting to firebase");

		Firebase.begin("SomeAddress", "SomeSecret");

		Firebase.setMaxRetry(firebase, 3);

		Firebase.setMaxErrorQueue(firebase, 100);
		Firebase.reconnectWiFi(true);

    }

    afterAlive = 0;

    PubAliveWiFi(); //in this function i call Firebase.setInt() onto a node that already exists but it doesnt make anything. If i put the Firebase.setInt() into an if statement if goes in the true path.

This is quite strange, i expect that note to change.

Arduino 1.8.9
ESP-32 WROOM 1.0.2 SDK Version.

HELP. Upload photo bigger than QVGA

Hi. I have this code to upload photos taken with esp32 cam and OV2640, but it only uploads a QVGA size.
Do you know why and how can I send a larger size?

`const char* ssid = "Lab_118";
const char* password = "";
#include "img_converters.h"

String FIREBASE_HOST = "fotos-81fec.firebaseio.com";
String FIREBASE_AUTH = "RU0EZbsEhAZHdk8KhZXjsCLGGTuRe4Wp5vBZbMXI";

//Library: https://github.com/mobizt/Firebase-ESP32
#include "FirebaseESP32.h"
FirebaseData firebaseData;

#include <WiFi.h>
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
#include "Base64.h"

#include "esp_camera.h"

//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

void setup() {

Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();
Serial.println("ssid: " + (String)ssid);
Serial.println("password: " + (String)password);

WiFi.begin(ssid, password);

long int StartTime=millis();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
if ((StartTime+10000) < millis()) break;
}

if (WiFi.status() == WL_CONNECTED) {
char* apssid = "ESP32-CAM";
char* appassword = "12345678"; //AP password require at least 8 characters.
Serial.println("");
Serial.print("Camera Ready! Use 'http://");
Serial.print(WiFi.localIP());
Serial.println("' to connect");
WiFi.softAP((WiFi.localIP().toString()+"_"+(String)apssid).c_str(), appassword);
}
else {
Serial.println("Connection failed");
return;
}

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;
config.frame_size = FRAMESIZE_QVGA; // UXGA|SXGA|XGA|SVGA|VGA|CIF|QVGA|HQVGA|QQVGA
config.jpeg_quality = 10;
config.fb_count = 1;

esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
delay(1000);
ESP.restart();
}

setSensordaten();
sensor_t *s = esp_camera_sensor_get();

Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
Firebase.setMaxRetry(firebaseData, 3);
Firebase.setMaxErrorQueue(firebaseData, 30);
Firebase.enableClassicRequest(firebaseData, true);

FirebaseJson json;
json.setJsonData("{"photo":"" + Photo2Base64() + ""}");
String photoPath = "/esp32-cam";
if (Firebase.pushJSON(firebaseData, photoPath, json)) {
Serial.println(firebaseData.dataPath());
Serial.println(firebaseData.pushName());
Serial.println(firebaseData.dataPath() + "/"+ firebaseData.pushName());
} else {
Serial.println(firebaseData.errorReason());
}
}

void loop() {
delay(10000);
}

String Photo2Base64() {
setSensordaten();
sensor_t *s = esp_camera_sensor_get();
camera_fb_t * fb = NULL;
fb = esp_camera_fb_get();
if(!fb) {
Serial.println("Camera capture failed");
return "";
}

String imageFile = "data:image/jpeg;base64,";
char *input = (char *)fb->buf;
char output[base64_enc_len(3)];
for (int i=0;i<fb->len;i++) {
  base64_encode(output, (input++), 3);
  if (i%3==0) imageFile += urlencode(String(output));
}

esp_camera_fb_return(fb);

return imageFile;

}

//https://github.com/zenmanenergy/ESP8266-Arduino-Examples/
String urlencode(String str)
{
String encodedString="";
char c;
char code0;
char code1;
char code2;
for (int i =0; i < str.length(); i++){
c=str.charAt(i);
if (c == ' '){
encodedString+= '+';
} else if (isalnum(c)){
encodedString+=c;
} else{
code1=(c & 0xf)+'0';
if ((c & 0xf) >9){
code1=(c & 0xf) - 10 + 'A';
}
c=(c>>4)&0xf;
code0=c+'0';
if (c > 9){
code0=c - 10 + 'A';
}
code2='\0';
encodedString+='%';
encodedString+=code0;
encodedString+=code1;
//encodedString+=code2;
}
yield();
}
return encodedString;
}

void setSensordaten()
{
size_t res = 0;
sensor_t * s = esp_camera_sensor_get();

res = s->set_quality(s, 10);
res = s->set_contrast(s, 0);
res = s->set_brightness(s, 0);
res = s->set_saturation(s, 0);
res = s->set_colorbar(s, 0);
res = s->set_whitebal(s, 1);
res = s->set_gain_ctrl(s, 1);
res = s->set_gainceiling(s, (gainceiling_t) GAINCEILING_2X);
res = s->set_exposure_ctrl(s, 1);
res = s->set_awb_gain(s, 1);
res = s->set_aec2(s, 0);
res = s->set_dcw(s, 1);
res = s->set_bpc(s, 0);
res = s->set_wpc(s, 1);
res = s->set_raw_gma(s, 1);
res = s->set_lenc(s, 1);
res = s->set_wb_mode(s, 0);
res = s->set_ae_level(s, 0);
delay(1000);
}`

HELP

How to implement remove device token after sending a message?
I used this code but not send any more for the next user.
I've got the error message "error":"InvalidRegistration"

#define FIREBASE_FCM_SERVER_KEY "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
#define MAX_USER 100
#define MAX_DEVICE 10

FirebaseData firebaseFCM;

String mUser[MAX_USER];
String mTokenDevice[MAX_DEVICE];
String mTitle = "This is title";
String mBody = "This is body"
String mDataMessage =
"{"
""data" : {"
""title" : "" + mTitle + "","
""body" : "" + mBody + """
"} }"

for (int z = 0; z < MAX_USER; z++) {
if (mUser[z] == "") break;

 firebaseFCM.fcm.begin(FIREBASE_FCM_SERVER_KEY);
 firebaseFCM.fcm.setPriority("high");
 firebaseFCM.fcm.setTimeToLive(5000);
 firebaseFCM.fcm.setDataMessage(mDataMessage);

 int index = 0;
 for (int y= 0; y< TOTAL_DEVICE; y++) {
      if (mTokenDevice[y] == "") break;

      firebaseFCM.fcm.addDeviceToken(mTokenDevice[y]);
      index = y;
      mTokenDevice[y] = "";
 }
 Firebase.sendMessage(firebaseFCM, index);
 firebaseFCM.fcm.removeDeviceToken(index);

}

HELP : After 2,3 hrs of connection to firebase esp32 is going unresponsive state.

Hi there, I've connected esp32 to firebase, after some moments there is no response from the module when I change the database values.
More Info :
I've created a task for checking internet for every 5 seconds on other core. I don't know what I have done worng got confused. Please give me suggestion that would be a great help for me.
Thank you

Library not working for Arduino UNO WiFi Rev2

I get an error trying to compile this library for my board. Is there any way I can make this library work for the Arduino UNO WiFi Rev2? It has an ESP32 included on the board:

Screenshot 2019-03-19 at 12 58 54

This is the error I get:

Arduino: 1.8.9 (Mac OS X), Board: "Arduino Uno WiFi Rev2, ATMEGA328"

Multiple libraries were found for "WiFi.h"
In file included from /Users/tommaarleveld/Documents/Arduino/libraries/Firebase_ESP32_Client/src/FirebaseESP32.h:38:0,
 Used: /Applications/Arduino.app/Contents/Java/libraries/WiFi
 Not used: /Users/tommaarleveld/Documents/Arduino/libraries/WiFiNINA
                 from /Users/tommaarleveld/Documents/Arduino/libraries/Firebase_ESP32_Client/examples/Basic/Basic.ino:6:
/Users/tommaarleveld/Documents/Arduino/libraries/HTTPClientESP32Ex-master/HTTPClientESP32Ex.h:37:24: fatal error: HTTPClient.h: No such file or directory
compilation terminated.
exit status 1
Error compiling for board Arduino Uno WiFi Rev2.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.