When I Disconnect and Connect Again and Update a Value It Doesnt Change Firebase Flutter
Firebase Realtime Database Arduino Library for ESP32
This library supports ESP32 MCU from Espressif. The following are platforms in which libraries are besides available.
-
ESP8266 Firebase Arduino library
-
Arduino MKR WiFi 1010, Arduino MKR VIDOR 4000 and Arduino UNO WiFi Rev.2
-
Arduino WiFi Shield 101 and Arduino MKR1000 WIFI
New library for ESP8266 and ESP32 is available
The Firebase Client for ESP8266 and ESP32 supports Cloud Firestore, Firebase Storage, Google Cloud Storage and new API Cloud Messaging and Cloud Functions for Firebase is now available.
Please try information technology here https://github.com/mobizt/Firebase-ESP-Client
Tested Devices
- NodeMCU-32
- WEMOS LOLIN32
- TTGO T8 V1.eight
Most ESP32 boards are supported unless Sparkfun ESP32 Thing (old version) is not recommended due to it built with non-standard 26 MHz clock on board instead of forty MHz which causes the bugs and unstable network connectedness.
Other Arduino Devices supported using external Clients.
Since version three.14.4, library allows you to use external Arduino Clients network interfaces eastward.g. WiFiClient, EthernetClient and GSMClient, the Arduino supported devices that take enough flash size (> 128k) and memory can at present use this library.
To apply external Client, see the ExternalClient examples.
The authentication with OAuth2.0 and custom auth tokens, RTDB fault queue and downloadFileOTA features are non supported for other Arduino devices using external Clients.
The flash and SD filesystems supports depend on the devices and third political party filesystems libraries installed.
Features
-
Complete and secure Firebase RTDB's REST APIs Client
-
Supports database read, store, update, delete and value changes listener
-
Supports Examination Way (No Auth)
-
Supports Firmware OTA updates
-
Supports Firebase Cloud Messaging.
-
Congenital-in JSON editor and deserializer.
-
Supports external Heap via PSRAM.
-
Supports ethernet using LAN8720, TLK110 and IP101 Ethernet modules.
Basic Examples
Don't be dislocated with other Firebase Arduino libraries, this library has different working functions, the following examples provide the basic usages.
ESP32 | FLUTTER | FIREBASE - Temperature & Humidity Check App
Serverless IoTs with Firebase Realtime Database and ESP32 - Part 1
Serverless IoTs with Firebase Realtime Database and ESP32 - Part 2
Dependencies
This library required ESP32 Core SDK version 1.0.1 or above.
For Arduino IDE, ESP32 Core SDK can exist installed through Boards Director.
For PlatfoemIO IDE, ESP32 Core SDK tin be installed through PIO Dwelling > Platforms > Espressif 32.
Installation
Using Library Managing director
At Arduino IDE, become to bill of fare Sketch -> Include Library -> Manage Libraries...
In Library Manager Window, search "firebase" in the search grade then select "Firebase ESP32 Client"
Click "Install" button.
For PlatformIO IDE, using the following command.
pio lib install "Firebase ESP32 Customer"
Or at PIO Habitation -> Library -> Registry then search Firebase ESP32 Client.
If you ever installed this library in Global storage in PlatformIO version prior to v2.0.0 and you take updated the PlatformIO to v2.0.0 and later, the global library installation was not available, the sources files of erstwhile library version withal be able to search by the library dependency finder (LDF), you needed to remove the library from binder C:\Users\<UserName>\.platformio\lib to prevent unexpected beliefs when compile and run.
Transmission installation
For Arduino IDE, download naught file from the repository (Github page) by select Lawmaking dropdown at the pinnacle of repository, select Download Zilch
From Arduino IDE, select carte du jour Sketch -> Include Library -> Add together .ZIP Library....
Choose Firebase-ESP32-main.zero that previously downloaded.
Rename Firebase-ESP32-master binder to Firebase_ESP32_Client.
Go to menu Files -> Examples -> Firebase-ESP32-master and cull one from examples.
For PlatformIO, in folder "lib", create new binder named "Firebase-ESP32" and add these files in that binder.
Important Note for Manual Installation in Arduino IDE
Folder renaming to Firebase_ESP32_Client was required for making the library can be updated via Library Manager without bug.
Without folder renaming, when you lot update the library via Library Managing director, library will be updated to the another folder named Firebase_ESP32_Client which leads to compilation error when there are two different versions of library institute in the libraries folder and can cause the conflicts when file structures and functions inverse in the newer version.
For instance, the library version iii.12.10 and before were installed manually by downloading Naught file and extracted to Firebase-ESP32-chief folder. If the library was later updated to v3.fourteen.2 and newer via Library Manager, the compilation error will take place because the newer version files structures and functions changed and compiler is trying to compile these ii versions of source files together.
In this example, you need to delete Firebase-ESP32-chief folder from libraries folder.
Usages
See all examples for complete usages.
See role description for all available functions.
Initialization
// Include WiFi.h #include <WiFi.h> // Include Firebase ESP32 library (this library) #include <FirebaseESP32.h> // Define the Firebase Data object FirebaseData fbdo; // Ascertain the FirebaseAuth data for hallmark data FirebaseAuth auth; // Define the FirebaseConfig data for config data FirebaseConfig config; // Assign the projection host and api fundamental (required) config.host = FIREBASE_HOST; config.api_key = API_KEY; // Assign the user sign in credentials auth.user.email = USER_EMAIL; auth.user.password = USER_PASSWORD; // Initialize the library with the Firebase authen and config. Firebase.begin(&config, &auth); // Optional, set AP reconnection in setup() Firebase.reconnectWiFi(true); // Optional, set number of error retry Firebase.setMaxRetry(fbdo, three); // Optional, set number of error resumable queues Firebase.setMaxErrorQueue(fbdo, xxx); // Optional, apply archetype HTTP GET and Post requests. // This choice allows get and delete functions (PUT and DELETE HTTP requests) works for // device connected behind the Firewall that allows only GET and Postal service requests. Firebase.enableClassicRequest(fbdo, truthful); // Optional, set the size of HTTP response buffer // Forbid out of memory for large payload merely data may be truncated and can't determine its type. fbdo.setResponseSize(8192); // minimum size is 4096 bytes Retention Options for ESP32
In ESP32 module that has PSRAM installed, you can enable it and ready the library to use this external retentiveness instead.
Arduino IDE
To enable PSRAM in ESP32 module.
PlatformIO IDE
In PlatformIO on VSCode or Atom IDE, add the following build_flags in your project'due south platformio.ini file.
build_flags = -DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue In one case the external Heap retention was enabled in IDE, to allow the library to use the external memory, you lot can prepare it in FirebaseFS.h by define this macro.
#define FIREBASE_USE_PSRAM Authentication
This library supports many types of authentications.
See other authentication examples for more authentication methods.
Some authentication methods require the token generaion and exchanging process which accept more than time than using the legacy token.
The system time must be set before cosign using the custom and OAuth2.0 tokens or when the root document was set for information transfer.
The authentication with custom and OAuth2.0 tokens takes the time, several seconds in overall process which included the NTP time conquering (system fourth dimension setup), JWT token generation and signing process.
By setting the organization time prior to calling the Firebase.begin , the internal NTP time conquering process volition be ignored.
Yous can set up the system time using the RTC chip or manually by calling Firebase.setSystemTime .
While authenticate using Email and countersign, the process will exist perform faster because no token generation and time setup required.
The cosign using the legacy token (database secret) does non have these delay time because the token is set to use.
Speed of data transfer
This library focuses on the user privacy and user information protection which follows Google hallmark processes. Setting the security rules to allow public admission read and write, is not recommended even the information transmision time in this case was significantly reduced as information technology does not require any auth token and then the overall data size was reduced, but anyone can steal, modify, or delete data in your database.
Once the auth token is importance and when it was created and ready for authentication process, the data transmission time will depend on the fourth dimension used in SSL/TLS handshake process (only for new session opening), the size of http header (included auth token size) and payload to exist transmitted and the SSL client buffer reserved size peculiarly in ESP8266.
The legacy token size is relatively small, but 40 bytes, result in smallest header to send, while the size of id token generated using Electronic mail/Password is quite large, approx. 900 bytes. outcome in larger header to send.
There is a compromise betwixt the speed of information transfer and the Rx/Tx buffer which then reduced the free retention available peculiarly in ESP8266.
When the reserved SSL customer Rx/Tx buffer is smaller than the size of information to be transmitted, the data need to exist sent as multiple chunks which required more transmission time.
This affected especially in ESP8266 which has the express free memory.
To speed up the data transmission in ESP8266, the larger reserved Rx/Tx buffer size is necessary.
The reserved SSL Rx/Tx buffer size in ESP8266 can exist set up through the function <Firebase Data object>.setBSSLBufferSize, e.thou. fbdo.setBSSLBufferSize(2048, 2048);
The larger BearSSL buffer reserved for ESP8266, the lower free memory available as long as the session opened (server connexion).
Therefore the fourth dimension for information transfer will exist varied from approx. neary 200 ms to 500 ms based on the reserved SSL client Rx/Tx buffer size and the size of information to transmit.
In ESP8266, when the free memory and speed are concerned, the legacy token should be used instead of other hallmark to reduce the header size and the lower SSL Rx/Tx buffer i.e. 1024 for Rx and 512 for Tx are enough.
When the session was reused (in this library), the SSL handshake procedure will be ignored in the subsequence requests.
The session was shut when the host or ip changes or server closed or the session timed out in iii minutes.
When the new session need to exist opened, the SSL handshake will be processed again and used the time approx i - 2 seconds to be done.
For mail (push button) or put (set) request in RTDB, to speed upward the data transfer, utilise pushAsync or setAsync instead.
With pushAsync and setAsync, the payload response will be ignored and the side by side data will be processed immediately.
Admission in Test Fashion (No Auth)
In Test Style, token generation volition be ignored and no authentication practical to the request.
You tin can admission RTDB database in Test Manner by prepare the security rules like this.
{ "rules": { ".read": truthful, ".write": truthful } } And fix the config.signer.test_mode = truthful;, see TestMode.ino example.
The authenication credentials and prerequisites
To use Email/Password sign-in authentication as in the examples, the E-mail/Countersign Sign-in provider must be enabled.
Add E-mail and countersign for outset user in your projection so use this Email and password to sign in.
To utilise Anonymous sign-in, the Anonymous Sign-in provider must exist enabled past follow the below steps.
To become API Key used in Email/Countersign sign-in
To get the Service accounts fundamental JSON file used in Custom and OAuth2.0 tokens athentications.
For RTDB usages, create new real-time database (if not setup yet)
Edit the default database rules as following
{ "rules": { ".read": "auth != zippo" , ".write": "auth != null" } } This document provides the RTDB security rules details.
The Firebase RTDB security rules are JSON-based rules which it should valid to used with this library RTDB functions that involved the security rules modification and reading, otherwise the rules wont be inverse or read by these functions.
To get the database URL and surreptitious (legacy token).
For server SSL authentication by providing the server root certificate.
Server SSL document verification is the process to ensure that the server that client is beingness connected is a trusted (valid) server instead of simulated server.
The Google'due south GlobalSign R2 root certificate can exist download from https://pki.goog/repository/
Select the .PEM (base-64 encoded string) or .DER (binary) file to download.
From the test as of July 2021, GlobalSign Root CA was missing from Google server, the certificate chain, GTS Root R1 can exist used instead of root certificate.
Beneath is how to assign the certificate information for server verification.
/* In example the certificate data was used */ config.cert.information = rootCACert; // Or custom set the root certificate for each FirebaseData object fbdo.setCert(rootCACert); /* Or assign the certificate file */ /** From the test as of July 2021, GlobalSign Root CA was missing from Google server * as described above, GTS Root R1 (gsr1.pem or gsr1.der) tin be used instead. * ESP32 Arduino SDK supports PEM format only even mBedTLS supports DER format likewise. * ESP8266 SDK supports both PEM and DER format certificates. */ // config.cert.file = "/gsr1.pem"; // config.cert.file_storage = StorageType::Flash; //or StorageType::SD Excludes the unused classes to save memory
The internal classes, RTDB and FCM in this library tin can be excluded or disabled to salvage memory usage through FirebaseFS.h.
Past comment the following macros.
ENABLE_RTDB
ENABLE_FCM
To disable OTA update, comment this macro.
ENABLE_OTA_FIRMWARE_UPDATE Read Data
Data at a specific node in Firebase RTDB can be read through these go functions.
The functions included go, getInt, getFloat, getDouble, getBool, getString, getJSON, getArray, getBlob, getFile.
These functions return boolean value indicates the success of the operation which will be true if all of the following atmospheric condition were met.
-
Server returns HTTP status code 200
-
The data types matched between asking and response.
For generic get, use Firebase.go(fbdo, <path>).
And check its blazon with fbdo.dataType() or fbdo.dataTypeEnum() and cast the value from it e.thou. fbdo.to<int>(), fbdo.to<std::string>().
The data type of returning payload can be determined past fbdo.dataType() which returns String or fbdo.dataTypeEnum() returns enum value.
The String of blazon returns from fbdo.dataType() tin can exist cord, boolean, int, float, double, json, array, blob, file and naught.
The enum value type, fb_esp_rtdb_data_type returns from fbdo.dataTypeEnum() tin be fb_esp_rtdb_data_type_null (1), fb_esp_rtdb_data_type_integer, fb_esp_rtdb_data_type_float, fb_esp_rtdb_data_type_double, fb_esp_rtdb_data_type_boolean, fb_esp_rtdb_data_type_string, fb_esp_rtdb_data_type_json, fb_esp_rtdb_data_type_array, fb_esp_rtdb_data_type_blob, and fb_esp_rtdb_data_type_file (ten)
The database data'south payload (response) tin can be read or access through the casting value from FirebaseData object with to<type>() functions (since v2.4.0).
-
String s = fbdo.to<String>(); -
std::string _s = fbdo.to<std::cord>(); -
const char *str = fbdo.to<const char *>(); -
bool b = fbdo.to<bool>(); -
int16_t _i = fbdo.to<int16_t>(); -
int i = fbdo.to<int>(); -
double d = fbdo.to<double>(); -
bladder f = fbdo.to<float>(); -
FirebaseJson *json = fbdo.to<FirebaseJson *>();or -
FirebaseJson &json = fbdo.to<FirebaseJson>(); -
FirebaseJsonArray *arr = fbdo.to<FirebaseJsonArray *>();or -
FirebaseJsonArray &arr = fbdo.to<FirebaseJsonArray>(); -
std::vector<uint8_t> *blob = fbdo.to<std::vector<uint8_t> *>(); -
File file = fbdo.to<File>();
Or through the legacy methods
-
int i = fbdo.intData(); -
float f = fbdo.floatData(); -
double d = fbdo.doubleData(); -
bool b = fbdo.boolData(); -
String southward = fbdo.stringData(); -
Cord js = fbdo.jsonString(); -
FirebaseJson &json = fbdo.jsonObject(); -
FirebaseJson *jsonPtr = fbdo.jsonObjectPtr(); -
FirebaseJsonArray &arr = fbdo.jsonArray(); -
FirebaseJsonArray *arrPtr = fbdo.jsonArrayPtr(); -
std::vector<uint8_t> blob = fbdo.blobData(); -
File file = fbdo.fileStream();
Read the data which its type does not match the data blazon in the database from above functions will render empty (string, object or array).
Blob and file stream information are stored as special base64 encoded string which are merely supported and implemented by this library.
The encoded base64 string will be prefixed with some header string ("file,base64," and "blob,base64,") for data type manipulation.
The following example showed how to read integer value from node "/test/int".
if (Firebase.getInt(fbdo, "/test/int" )) { if (fbdo.dataTypeEnum() == fb_esp_rtdb_data_type_integer) { Serial.println(fbdo.to<int>()); } } else { Serial.println(fbdo.errorReason()); }
Shop Information
To store data at a specific node in Firebase RTDB, apply these ready functions.
The role included set, setInt, setFloat, setDouble, setBool, setString, setJSON, setArray, setBlob and setFile.
For faster sending information, non-waits or async mode functions are bachelor due east.m. setAsync, setIntAsync, setFloatAsync, setDoubleAsync, setBoolAsync, setStringAsync, setJSONAsync, setArrayAsync, setBlobAsync and setFileAsync.
For generic set up, apply Firebase.gear up(fbdo, <path>, <any variable or value>).
These async functions will ignore the server responses.
The above functions return boolean value indicates the success of the operation which will be true if all of the following conditions matched.
-
Server returns HTTP condition code 200
-
The information types matched between request and response.
Merely setBlob and setFile functions that make a silent asking to Firebase server, thus no payload response returned.
The priority, virtual node ".priority" of each database node can be gear up through Firebase's set functions.
The priority value tin exist used in a query or filtering the children's data under a divers node.
Priority option was removed from File and Blob functions since v2.iv.0.
ETag (unique identifier value) assigned to Firebase's prepare functions is used as conditional checking.
If defined Etag is not matched the defined path'south ETag, the set up operation volition fail with result 412 Precondition Failed.
ETag at any node tin be read through Firebase.getETag. ETag value changed upon the data was fix or delete.
The server's Timestamp can be stored in the database through Firebase.setTimestamp.
The returned Timestamp value can get from fbdo.to<int>().
The file systems for flash and sd memory can be changed in FirebaseFS.h.
The following example showed how to store file data to flash retentiveness at node "/exam/file_data".
if (Firebase.getFile(fbdo, StorateType::Wink, "/test/file_data" , "/examination.txt" )) { // FLASH.begin(); // not need to begin once again due to it has been chosen in function. File file = DEFAULT_FLASH_FS.open( "/exam.txt" , "r" ); while (file.bachelor()) { Serial.print(file.read(), HEX); } file.close(); Serial.println(); } else { Serial.println(fbdo.fileTransferError()); } Append Information
To append new data to a specific node in Firebase RTDB, use these push functions.
The function included push button, pushInt, pushFloat, pushDouble, pushBool, pushString, pushJSON, pushArray, pushBlob, and pushFile.
For faster sending data, non-waits or async way functions are bachelor e.g. pushAsync, pushIntAsync, pushFloatAsync, pushDoubleAsync, pushBoolAsync, pushStringAsync, pushJSONAsync, pushArrayAsync, pushBlobAsync and pushFileAsync.
These functions render boolean value indicates the success of the operation.
The unique key of a new appended node can exist determined from fbdo.pushName().
As ready functions, the Firebase'due south push functions support priority.
ETag was not bachelor later push unless read the ETag at that new appended unique key later on with Firebase.getETag.
The server's Timestamp tin can exist appended in the database through Firebase.pushTimestamp.
The unique key of Timestamp tin exist determined after Timestamp was appended.
The post-obit instance showed how to append new data (using FirebaseJson object) to node "/test/append.
FirebaseJson json; FirebaseJson json2; json2.gear up( "child_of_002" , 123.456); json.set( "parent_001" , "parent 001 text" ); json.set( "parent 002" , json2); if (Firebase.pushJSON(fbdo, "/test/append" , json)) { Serial.println(fbdo.dataPath()); Serial.println(fbdo.pushName()); Serial.println(fbdo.dataPath() + "/" + fbdo.pushName()); } else { Series.println(fbdo.errorReason()); } Patch Data
Firebase'southward update functions used to patch or update new or existing information at the defined node.
These functions, updateNode and updateNodeSilent are bachelor and work with JSON object (FirebaseJson object only).
For faster sending information, not-waits or async way functions are bachelor due east.grand. updateNodeAsync, and updateNodeSilentAsync.
If whatever key name provided at a divers node in JSON object has not existed, a new key will exist created.
The server returns JSON data payload which was successfully patched.
Return of big JSON payload volition price the network data, alternative office updateNodeSilent or updateNodeSilentAsync should be used to salvage the network information.
The following example showed how to patch data at "/test".
FirebaseJson updateData; FirebaseJson json; json.set( "_data2" , "_value2" ); updateData.set( "data1" , "value1" ); updateData.set( "data2" , json); if (Firebase.updateNode(fbdo, "/test/update" , updateData)) { Serial.println(fbdo.dataPath()); Serial.println(fbdo.dataType()); Series.println(fbdo.jsonString()); } else { Serial.println(fbdo.errorReason()); } Delete Data
The post-obit example showed how to delete data and its children at "/test/append"
Firebase.deleteNode(fbdo, "/exam/append" ); Filtering Data
To filter or query the data, the following query parameters are available through the QueryFilter class.
These parameters are orderBy, limitToFirst, limitToLast, startAt, endAt, and equalTo.
To filter data, parameter orderBy should be assigned.
Employ "$key" every bit the orderBy parameter if the cardinal of kid nodes was used for the query.
Use "$value" as the orderBy parameter if the value of child nodes was used for the query.
Utilize key (or full path) of child nodes as the orderBy parameter if all values of the specific primal were used for the query.
Utilize "$priority" as orderBy parameter if child nodes's "priority" was used for query.
The above orderBy parameter tin can be combined with the post-obit parameters for express and ranged the queries.
QueryFilter.limitToFirst - The total children (number) to filter from the starting time child.
QueryFilter.limitToLast - The full last children (number) to filter.
QueryFilter.startAt - Starting value of range (number or string) of query upon orderBy param.
QueryFilter.endAt - Catastrophe value of range (number or string) of query upon orderBy param.
QueryFilter.equalTo - Value (number or cord) matches the orderBy param
The following example showed how to utilize queries parameter in QueryFilter form to filter the data at node "/test/data"
// Assume that children that accept key "sensor" are under "/test/data" // Instantiate the QueryFilter class QueryFilter query; // Build query using specified child node key "sensor" under "/test/data" query.orderBy( "sensor" ); // Query whatever kid that its value begins with 2 (number), assumed that its information blazon is float or integer query.startAt(2); // Query whatsoever child that its value ends with 8 (number), assumed that its data type is float or integer query.endAt(8); // Limit the maximum query consequence to return only the last v nodes query.limitToLast(5); if (Firebase.getJSON(fbdo, "/test/data" , query)) { // Success, then endeavour to read the JSON payload value Serial.println(fbdo.jsonString()); } else { // Failed to get JSON data at defined database path, print out the fault reason Serial.println(fbdo.errorReason()); } // Clear all query parameters query.clear(); Server Information Changes Listener with Server-Sent Events or HTTP Streaming
This library uses HTTP Become request with text/event-stream header to make HTTP streaming connection.
The Firebase's functions that involved the stream operations are beginStream, beginMultiPathStream, setStreamCallback, setMultiPathStreamCallback and/or readStream.
Function beginStream is to subscribe to the data changes at a divers node.
Function beginMultiPathStream is to subscribe to the information changes at a defined parent node path with multiple child nodes value parsing and works with setMultiPathStreamCallback.
Function setStreamCallback is to assign the callback function that accepts the FirebaseStream grade every bit parameter.
Function setMultiPathStreamCallback is to assign the callback role that accepts the MultiPathStream class as parameter.
The FirebaseStream contains stream's event/data payloadd and interface function calls are similar to FirebaseData object.
The MultiPathStream contains stream's event/information payload for various child nodes.
To polling the stream's outcome/information payload manually, use readStream in loop().
Role readStream used in the loop() job to continuously read the stream'southward consequence and information.
Since polling the stream's result/data payload with readStream, apply fbdo.streamAvailable to check if stream event/data payoad is available.
Role fbdo.streamAvailable returned truthful when new stream's event/data payload was bachelor.
When new stream payload was bachelor, its information and effect can exist accessed from FirebaseData object functions.
Function endStream ends the stream operation.
Note that, when using the shared FirebaseData object for stream and Grime usages(normal operation to create,read, update and delete data), the stream connection volition be interrupted (airtight) to connect in other HTTP mode, the stream will be resumed (open) after the CRUD usages.
For the above case, you need to provide the idle time for FirebaseData object to established the streaming connectedness and received the stream payload. The changes on the server at the streaming node path during the stream intermission volition be missed.
To avoid this sitation, don't share the usage of stream'due south FirebaseData object, another FirebaseData object should be used.
In addition, delay office used in the same loop of readStream() will defer the streaming, the server data changes may be missed.
Keep in mind that FirebaseData object volition create the SSL client within of HTTPS data transaction and uses big retentivity.
The following example showed how to subscribe to the data changes at node "/test/data" with a callback function.
// In setup(), set the stream callback part to handle information // streamCallback is the function that called when database information changes or updates occurred // streamTimeoutCallback is the function that called when the connection between the server // and customer was timeout during HTTP stream Firebase.setStreamCallback(fbdo, streamCallback, streamTimeoutCallback); // In setup(), fix the streaming path to "/exam/data" and begin stream connectedness if (!Firebase.beginStream(fbdo, "/test/information" )) { // Could not begin stream connection, then print out the error particular Serial.println(fbdo.errorReason()); } // Global function that handles stream information void streamCallback(StreamData data) { // Impress out all information Serial.println( "Stream Data..." ); Serial.println(data.streamPath()); Serial.println(data.dataPath()); Serial.println(data.dataType()); // Impress out the value // Stream information tin exist many types which can exist determined from part dataType if (data.dataTypeEnum() == fb_esp_rtdb_data_type_integer) Serial.println(data.to<int>()); else if (data.dataTypeEnum() == fb_esp_rtdb_data_type_float) Serial.println(data.to<float>(), 5); else if (data.dataTypeEnum() == fb_esp_rtdb_data_type_double) printf( "%.9lf\n " , data.to<double>()); else if (information.dataTypeEnum() == fb_esp_rtdb_data_type_boolean) Series.println(data.to<bool>()? "truthful" : "faux" ); else if (data.dataTypeEnum() == fb_esp_rtdb_data_type_string) Serial.println(information.to<String>()); else if (data.dataTypeEnum() == fb_esp_rtdb_data_type_json) { FirebaseJson *json = data.to<FirebaseJson *>(); Serial.println(json->raw()); } else if (data.dataTypeEnum() == fb_esp_rtdb_data_type_array) { FirebaseJsonArray *arr = information.to<FirebaseJsonArray *>(); Series.println(arr->raw()); } } // Global office that notifies when stream connectedness lost // The library will resume the stream connexion automatically void streamTimeoutCallback(bool timeout) { if(timeout){ // Stream timeout occurred Series.println( "Stream timeout, resume streaming..." ); } } // For authentication except for legacy token, Firebase.ready() should exist called repeatedly // in loop() to handle authentication tasks. void loop() { if (Firebase.prepare()) { // Firebase is ready to use at present. } } For multiple paths stream, see the MultiPath_stream example.
The post-obit case showed how to subscribe to the stream changes at "/test/data" and read the stream manually.
// In setup(), set the streaming path to "/test/data" and begin stream connection if (!Firebase.beginStream(fbdo, "/test/information" )) { Series.println(fbdo.errorReason()); } //In loop() if (!Firebase.readStream(fbdo)) { Serial.println(fbdo.errorReason()); } if (fbdo.streamTimeout()) { Serial.println( "Stream timeout, resume streaming..." ); Serial.println(); } if (fbdo.streamAvailable()) { if (fbdo.dataTypeEnum() == fb_esp_rtdb_data_type_integer) Serial.println(fbdo.to<int>()); else if (fbdo.dataTypeEnum() == fb_esp_rtdb_data_type_float) Serial.println(fbdo.to<float>(), 5); else if (fbdo.dataTypeEnum() == fb_esp_rtdb_data_type_double) printf( "%.9lf\north " , fbdo.to<double>()); else if (fbdo.dataTypeEnum() == fb_esp_rtdb_data_type_boolean) Serial.println(fbdo.to<bool>() ? "true" : "false" ); else if (fbdo.dataTypeEnum() == fb_esp_rtdb_data_type_string) Series.println(fbdo.to<String>()); else if (fbdo.dataTypeEnum() == fb_esp_rtdb_data_type_json) { FirebaseJson *json = fbdo.to<FirebaseJson *>(); Serial.println(json->raw()); } else if (fbdo.dataTypeEnum() == fb_esp_rtdb_data_type_array) { FirebaseJsonArray *arr = fbdo.to<FirebaseJsonArray *>(); Serial.println(arr->raw()); } } // For authentication except for legacy token, Firebase.fix() should exist chosen repeatedly // in loop() to handle authentication tasks. void loop() { if (Firebase.gear up()) { // Firebase is prepare to use now. } }
Backup and Restore Data
This library allows data backup and restores at a defined path.
The backup file will store in SD/SDMMC bill of fare or flash memory.
The file systems for flash and SD memory tin be changed via FirebaseFS.h.
Due to SD library used, just 8.iii DOS format file name supported.
The maximum viii characters for a file proper name and 3 characters for file extension.
The database restoration returned completed condition but when Firebase server successfully updates the data.
Whatsoever failed operation will not impact the database (no updates or changes).
The following example showed how to backup all database data at "/" and restore.
String backupFileName; if (!Firebase.fill-in(fbdo, StorateType::SD, "/" , "/fill-in.txt" )) { Serial.println(fbdo.fileTransferError()); } else { Serial.println(fbdo.getBackupFilename()); Series.println(fbdo.getBackupFileSize()); backupFileName = fbdo.getBackupFilename(); } // Begin restore backed dup data back to database if (!Firebase.restore(fbdo, StorateType::SD, "/" , backupFileName)) { Serial.println(fbdo.fileTransferError()); } else { Serial.println(fbdo.getBackupFilename()); } Database Fault Handling
When read store, append and update operations were failed due to buffer overflow and network problems.
These operations can retry and queued afterward the retry corporeality was reached the maximum retry gear up in role setMaxRetry.
// gear up maximum retry amount to 3 Firebase.setMaxRetry(fbdo, three); The function setMaxErrorQueue limits the maximum queues in Error Queue collection.
The full of queue collection can be checked through part isErrorQueueFull.
// set maximum queues to 10 Firebase.setMaxErrorQueue(fbdo, ten); // decide whether Fault Queue collection is full or not Firebase.isErrorQueueFull(fbdo); This library provides ii approaches to run or procedure Error Queues with ii functions.
-
beginAutoRunErrorQueue -
processErrorQueue
The function beginAutoRunErrorQueue will run or procedure queues automatically and can exist called once.
While function processErrorQueue will run or process queues and should call inside the loop().
With function beginAutoRunErrorQueue, y'all can assigned callback function that accept QueueInfo object as parameter.
Which contains all information about beingness processed queue, number of remaining queues and Mistake Queue collection status.
Otherwise, Error Queues tin can be tracked manually with the following functions.
Office getErrorQueueID volition return the unsigned integer presents the id of the queue which volition keep using afterward.
Use getErrorQueueID and isErrorQueueExisted to bank check whether this queue id is still existed or not.
If Fault Queue ID does non exist in Mistake Queues collection, that queue is already done.
The following example showed how to run Error Queues automatically and track the status with the callback function.
// In setup() // Set the maximum Firebase Error Queues in collection (0 - 255). // Firebase read/store operation causes by network bug and buffer overflow will be // added to Firebase Fault Queues drove. Firebase.setMaxErrorQueue(fbdo, ten); // Begin to run Error Queues in Error Queue drove Firebase.beginAutoRunErrorQueue(fbdo, callback); // Utilize to finish the auto run queues // Firebase.endAutoRunErrorQueue(fbdo); void errorQueueCallback (QueueInfo queueinfo){ if (queueinfo.isQueueFull()) { Series.println( "Queue is full" ); } Serial.impress( "Remaining queues: " ); Serial.println(queueinfo.totalQueues()); Series.print( "Being processed queue ID: " ); Series.println(queueinfo.currentQueueID()); Series.print( "Information type:" ); Serial.println(queueinfo.dataType()); Series.print( "Method: " ); Serial.println(queueinfo.firebaseMethod()); Serial.print( "Path: " ); Serial.println(queueinfo.dataType()); Series.println(); } The post-obit example showed how to run Error Queues and track its condition manually.
// In setup() // Set the maximum Firebase Error Queues in collection (0 - 255). // Firebase read/store functioning causes by network problems and buffer overflow will be added to // Firebase Fault Queues drove. Firebase.setMaxErrorQueue(fbdo, ten); // All of the post-obit are in loop() Firebase.processErrorQueue(fbdo); // Detrnine the queue status if (Firebase.isErrorQueueFull(fbdo)) { Serial.println( "Queue is total" ); } // Remaining Mistake Queues in Error Queue collection Serial.print( "Remaining queues: " ); Serial.println(Firebase.errorQueueCount(fbdo)); // Causeless that queueID is unsigned integer array of queue that added to Error Queue collection // when error and utilize Firebase.getErrorQueueID to get this Error Queue id. for (uint8_t i = 0; i < LENGTH_OF_QUEUEID_ARRAY; i++) { Serial.print( "Error Queue " ); Serial.print(queueID[i]); if (Firebase.isErrorQueueExisted(fbdo, queueID[i])) Series.println( " is queuing" ); else Series.println( " is done" ); } Serial.println(); Error Queues can be saved as a file in SD menu or Flash memory with office saveErrorQueue.
Error Queues shop as a file can be restored to Error Queue collection with part restoreErrorQueue.
Two types of storage can be assigned with these functions, StorageType::FLASH and StorageType::SD.
Read information (go) functioning is not back up queues restore
The following example showed how to restore and salvage Mistake Queues in /test.txt file.
// To restore Error Queues if (Firebase.errorQueueCount(fbdo, "/examination.txt" , StorageType::Wink) > 0) { Firebase.restoreErrorQueue(fbdo, "/test.txt" , StorageType::FLASH); Firebase.deleteStorageFile( "/test.txt" , StorageType::Flash); } // To salve Error Queues to file Firebase.saveErrorQueue(fbdo, "/test.txt" , StorageType::Wink); FireSense, The Programmable Data Logging and IO Command (Add On)
This add together on library is for the advance usages and works with Firebase RTDB.
With this add on library, you can remotely program your device to control its IOs or do some task or telephone call predefined functions on the fly.
This allows you to change your device behaviour and functions without to flash a new firmware via serial or OTA.
See examples/FireSense for the usage.
For FireSense part description, run across src/addons/FireSense/README.md.
Firebase Cloud Messaging (FCM)
Ii types of FCM message data can be sent using this library e.g. notification and custom information.
These two types of data can send all together or separately.
Function Firebase.sendMessage will send a message to one recipient.
Function Firebase.broadcastMessage will circulate or send a bulletin to multiple recipients.
Function Firebase.sendTopic will ship a bulletin to whatsoever recipient who subscribed to the topic.
The FCM message itself offers a broad range of messaging options and capabilities for various recipient device platforms.
For Android, iOS and spider web platforms, these basic options can be set and work for all platforms.
Function fbdo.fcm.begin used to assign the server key of your Firebase project.
Role fbdo.fcm.addDeviceToken used to add recipient registered device token which wants to send message to.
Functions fbdo.fcm.removeDeviceToken and fbdo.fcm.clearDeviceToken used to remove or clear recipient device.
For the notification bulletin, title, torso, icon (optional), and click_action (optional) can be gear up through fbdo.fcm.setNotifyMessage.
And clear these notify bulletin information with fbdo.fcm.clearNotifyMessage.
For the information message, provide your custom data as JSON object (FirebaseJson object or string) to fbdo.fcm.setDataMessage which can be clear with fbdo.fcm.clearDataMessage.
The other options are priority, collapse key, Time to Live of the message and topic to send messages to, can be set from the following functions.
Call fbdo.fcm.setPriority for priority ("normal" or "high"), fbdo.fcm.setCollapseKey for collapse primal setup, fbdo.fcm.setTimeToLive for life span of message setup between 0 sec. to ii,419,200 sec. (or 4 weeks), and fbdo.fcm.setTopic for assigning the topic that bulletin to send to.
The following example showed how to send FCM message.
// Provide your Firebase projection'due south server key here fbdo.fcm.begin(FIREBASE_FCM_SERVER_KEY); // Prvide one or more the recipient registered token or instant ID token fbdo.fcm.addDeviceToken(FIREBASE_FCM_DEVICE_TOKEN); // Provide the priority (optional) fbdo.fcm.setPriority( "normal" ); // Provide the time to live (optional) fbdo.fcm.setTimeToLive(5000); // Gear up the notification message data fbdo.fcm.setNotifyMessage( "Notification" , "Howdy World!" , "firebase-logo.png" , "http://world wide web.google.com" ); // Set the custom message data fbdo.fcm.setDataMessage( "{\"myData\":\"myValue\"}" ); // Ship bulletin to i recipient with inddex one (index starts from 0) if (Firebase.sendMessage(fbdo, 1)) { // Success, print the result returned from server Serial.println(fbdo.fcm.getSendResult()); } else { // Failed, print the mistake reason Serial.println(fbdo.errorReason()); } Create, Edit, Serializing and Deserializing the JSON Objects
This library has congenital-in FirebaseJson Arduino library, the easiest JSON parser, architect and editor.
FirebaseJson usages are and then simple as you read, store and update(edit) the JSON node in Firebase RTDB.
It doesn't use the recursive call to parse or deserialize complex or nested JSON objects and arrays.
This makes the library can apply with a limited retentiveness device.
Since you declare the FirebaseJson or FirebaseJsonArray object, use the functions setJsonData, setJsonArrayData, add, set and remove to build or edit the JSON/Array object and utilize go to parse the node's contents.
Defined the relative path of the specific node to add, set, remove and get functions to add, ready, remove and go its contents.
Function FirebaseJson.setJsonData is to deserialize the JSON string to JSON object.
In add-on, function FirebaseJson.readFrom tin can be used to read the streaming JSON contents from WiFi/Ethernet Client, File and Harware Serial and serialize information technology as the streaming content contains valid JSON data.
Function FirebaseJson.add is used to add the new node with the contents e.g. String, Number (int and double), Boolean, Array and Object to the defined node.
Function FirebaseJson.set is used for edit, overwrite, create new (if not be) node with contents eastward.g. String, Number (int and double), Boolean, Assortment and Object at the defined relative path and node.
Office FirebaseJson.get is used for parsing or deserializee the JSON object and array. The deserialized or parsed result will keep in FirebaseJsonData object which can be casted to whatsoever type of value or variable east.g string, bool, int, float, double by using FirebaseJsonData.to<type>.
The casting from FirebaseJsonData to FirebaseJson and FirebaseJsonArray objects is unlike, by using FirebaseJsonData.getJSON(FirebaseJson) and FirebaseJsonData.getArray(FirebaseJsonArray).
Function FirebaseJson.search is used for searching the elements in JSON object and array. The search role supports criterias which can exist set using FirebaseJson::SearchCriteria data.
The search part returns the number of items or elements plant.
The SearchCriteria data consisted of the properties e.k. path, value, depth, endDepth, and searchAll.
The path property is the primal name or path to search which tin can utilize the wildcard * for path to exist any central or name at that depth and and then on.
The value belongings tin can be used with or without path assignment.
The depth property is brainstorm depth to search, default value is 0.
The endDepth belongings is the end depth to search, default value is -1 for unlimited end depth.
The searchAll belongings, when prepare to true, is to search all occurrences of elements found and search result stores in FirebaseJsonData object will be array of all items institute. The actual full path of search tin can be obtained by FirebaseJsonData.searchPath which volition be serialized array string of all paths for all elements found from search.
When searchAll property is false (default), the first occurrence will exist set to the result which tin be whatever value type.
The search path from FirebaseJsonData.searchPath will be string of the element or item full path.
The search result will keep in FirebaseJsonData object which later can cast to any type (ever be an array in case of searchAll belongings is true) past using FirebaseJsonData.to<type>.
Function FirebaseJson.remove is used to remove the node and all its children'south contents at the divers relative path and node.
Role FirebaseJson.toString is used for serializeing the JSON object to writable objects e.thousand. char array, Arduino String, C/C++ string, WiFi/Ethernet Client and Hardware/Software Serial.
Function FirebaseJson.serializedBufferLength is used for calculating the serialized buffer size that required for reserved buffer in serialization.
Office FirebaseJson.responseCode is used to get the http code response header while read the WiFi/Ethernet Client using FirebaseJson.toString.
Functions FirebaseJson.iteratorBegin, FirebaseJson.iteratorGet and FirebaseJson.iteratorEnd are used to parse all JSON object contents as a listing which tin can exist iterated with index.
Function FirebaseJson.clear is used to clear JSON object contents.
Role FirebaseJson.setFloatDigits is for bladder number precision when serialized to cord.
Part FirebaseJson.setDoubleDigits is for double number precision when serialized to cord.
Function FirebaseJsonArray.add together is used for adding the new contents e.chiliad. Cord, Number (int and double), Boolean, Array and Object to JSON array.
Function FirebaseJsonArray.set is for edit, overwrite, create new (if not be) contents eastward.k. Cord, Number (int and double), Boolean, Assortment and Object at the divers relative path or defined index of JSON assortment.
Role FirebaseJsonArray.get and FirebaseJsonArray.searchwork in the same way as FirebaseJson objects
Function FirebaseJsonArray.remove is used to remove the array'southward contents at the defined relative path or defined alphabetize of JSON array.
Role FirebaseJsonArray.toString is used for serializeing the JSON array object to writable objects e.thou. char array, Arduino String, C/C++ cord, WiFi/Ethernet Customer and Hardware/Software Serial.
Function FirebaseJsonArray.serializedBufferLength is used for calculating the serialized buffer size that required for reserved buffer in serialization.
Role FirebaseJsonArray.responseCode is used to get the http code response header while read the WiFi/Ethernet Client using FirebaseJson.toString.
Role FirebaseJsonArray.clear is used to articulate JSON array object contents.
Function FirebaseJsonArray.setFloatDigits is for float number precision when serialized to string.
Function FirebaseJsonArray.setDoubleDigits is for double number precision when serialized to string.
Run into examples/FirebaseJson for the usage.
For FirebaseJson part description, encounter FirebaseJSON object Functions.
The following case shows how to use FirebaseJson.
// Declare FirebaseJson object (global or local) FirebaseJson json; // Add proper name with value Living Room to JSON object json.add( "name" , "Living Room" ); // Add temp1 with value 120 and temp1 with xl to JSON object // Note: temp2 is not the kid of temp1 as in previous version. json.add( "temp1" , 120).add( "temp2" , 40); // Add nested kid contents directly json.gear up( "unit/temp1" , "Farenheit" ); json.set up( "unit/temp2" , "Celcius" ); // Deserialize to series with prettify option json.toString(Serial, truthful); Serial.println(); Serial.println(); /** This is the result of the above code { "name": "Living Room", "temp1": 120, "temp2": 40, "unit": { "temp1": "Farenheit", "temp2": "Celcius" } } */ // To set up assortment to the above JSON using FirebaseJson directly // Set up (add) array indexes 0,1,2,five,vii under temp1, the original value volition be replaced with new one. json.ready( "temp1/[0]" , 47); json.set( "temp1/[1]" , 28); json.set( "temp1/[ii]" , 34); json.prepare( "temp1/[five]" , 23); // null will be created at array index 3,four due to information technology'due south not yet assigned json.ready( "temp1/[vii]" , 25); // cypher will exist created at array alphabetize 6 // Print out as prettify string json.toString(Serial, true); Series.println(); Serial.println(); /** The result of the to a higher place code { "proper noun": "Living Room", "temp1": [ 47, 28, 34, zero, aught, 23, nada, 25 ], "temp2": 40, "unit of measurement": { "temp1": "Farenheit", "temp2": "Celcius" } } */ // Try to remove temp1 array at index 1 json.remove( "temp1/[ane]" ); // Attempt to remove temp2 json.remove( "temp2" ); // Print out as prettify string json.toString(Serial, true); Serial.println(); Serial.println(); /** The effect of the to a higher place code { "name": "Living Room", "temp1": [ 47, 34, null, null, 23, null, 25 ], "unit of measurement": { "temp1": "Farenheit", "temp2": "Celcius" } } */ // Now parse/read the contents from specific node unit of measurement/temp2 // FirebaseJsonData is required to keep the parse results which can be accessed later on FirebaseJsonData result; json.become(outcome, "unit/temp2" ); if (result.success) { // Print blazon of parsed information e.g string, int, double, bool, object, assortment, null and undefined Series.println(result.type); // Print its content east.thou.string, int, double, bool whereas object, array and null too can access every bit string Serial.println(result.to<Cord>()); // Serial.println(result.to<int>()); // Serial.println(upshot.to<bool>()); // Serial.println(result.to<float>()); // Serial.println(result.to<double>()); } // The above code will show /** string Celcius */ // To get the array temp from FirebaseJson json.get(effect, "temp1" ); // Prepare FirebaseJsonArray to take the array from FirebaseJson FirebaseJsonArray arr; // Get assortment data result.get<FirebaseJsonArray>(arr); // Phone call get with FirebaseJsonData to parse the array at defined alphabetize i for (size_t i = 0; i < arr.size(); i++) { // result now used as temporary object to get the parse results arr.get(result, i); // Print its value Serial.print( "Array index: " ); Serial.print(i); Serial.impress( ", type: " ); Serial.print(result.type); Serial.print( ", value: " ); Serial.println(issue.to<Cord>()); } /** The upshot of above code Array index: 0, type: int, value: 47 Array index: 1, type: int, value: 34 Array index: ii, blazon: nothing, value: goose egg Assortment alphabetize: iii, blazon: zippo, value: null Array index: 4, type: int, value: 23 Array index: 5, type: zippo, value: null Array alphabetize: 6, type: int, value: 25 */ The following example shows how to use FirebaseJsonArray.
// Declare FirebaseJsonArray object (global or local) FirebaseJsonArray arr; // Add some data arr.add( "banana" ); arr.add( "mango" ); arr.add( "coconut" ); // Change the array contents arr.fix( "[1]/food" , "salad" ); arr.set( "[1]/sweet" , "cake" ); arr.set( "[1]/titbit" , "snack" ); arr.ready( "[2]" , "apple tree" ); // or arr.set(2, "apple"); arr.set( "[four]/[0]/[1]/amount" , 20); // Print out array as prettify string arr.toString(Serial, true); Series.println(); Series.println(); /** This is the result of the in a higher place code [ "banana", { "food": "salad", "sweet": "cake", "appetizer": "snack" }, "apple", aught, [ [ null, { "amount": xx } ] ] ] */ // Remove assortment content at /4/0/1/amount arr.remove( "[4]/[0]/[1]/corporeality" ); // Impress out as prettify cord arr.toString(Series, true); Serial.println(); Serial.println(); /** The result of the above code [ "banana", { "nutrient": "salad", "sweet": "block", "appetizer": "snack" }, "apple", nix, [ [ aught ] ] ] */ // At present parse/read the array contents at some index FirebaseJsonData upshot; arr.get(result, "[1]/food" ); if(result.success) { // Type of parsed data Serial.println(event.type); // Its value Serial.println(issue.to<String>()); // Series.println(consequence.to<int>()); // Serial.println(result.to<bool>()); // Serial.println(result.to<bladder>()); // Serial.println(result.to<double>()); } // The in a higher place code will testify /** string salad */ // To go the JSON object at array index ane from FirebaseJsonArray arr.get(result, "[ane]" ); // or arr.go(result, one); // Prepare FirebaseJson to have the JSON object from FirebaseJsonArray FirebaseJson json; // Get FirebaseJson data effect.get<FirebaseJson>(json); // Parse the JSON object as list // Go the number of items size_t len = json.iteratorBegin(); FirebaseJson::IteratorValue value; for (size_t i = 0; i < len; i++) { value = json.valueAt(i); Serial.printf( "%d, Type: %s, Name: %s, Value: %south\north " , i, value.type == FirebaseJson::JSON_OBJECT ? "object" : "assortment" , value.key.c_str(), value.value.c_str()); } // Articulate all list to free memory json.iteratorEnd(); /** The result of the above code 0, Type: object, Key: food, Value: salad 1, Type: object, Fundamental: sweet, Value: block two, Type: object, Fundamental: appetizer, Value: snack */ License
The MIT License (MIT)
Copyright (C) 2022 K. Suwatchai (Mobizt)
Permission is hereby granted, free of charge, to any person returning a copy of this software and associated documentation files (the "Software"), to bargain in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, discipline to the post-obit atmospheric condition:
The above copyright find and this permission find shall exist included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF Whatsoever KIND, EXPRESS OR Unsaid, INCLUDING Only Not LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS Be LIABLE FOR Whatever CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN Action OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE Use OR OTHER DEALINGS IN THE SOFTWARE.
Source: https://github.com/mobizt/Firebase-ESP32
0 Response to "When I Disconnect and Connect Again and Update a Value It Doesnt Change Firebase Flutter"
Post a Comment