From 0b6ec47510d6d71779946f39c0ca84ecdf9fd0a1 Mon Sep 17 00:00:00 2001 From: suwatchai Date: Wed, 19 May 2021 12:58:54 +0700 Subject: [PATCH] Rewrite the Authentications and RTDB examples. --- README.md | 13 +- .../Access_Token_from_File.ino | 150 -------- .../LegacyTokenAuthen.ino} | 27 +- .../AccessTokenFile/AccessTokenFile.ino | 137 +++++++ .../AccessTokenFile/data/gsr2.pem | 22 ++ .../AnonymousSignin/AnonymousSignin.ino} | 46 +-- .../CustomToken/CustomToken.ino} | 32 +- .../CustomTokenFile/CustomTokenFile.ino} | 34 +- .../EmailPassword/EmailPassword.ino} | 40 +- .../ResetPassword/ResetPassword.ino} | 17 +- .../SendVerification/SendVerification.ino} | 48 +-- .../{ => UserManagement}/Signup/Signup.ino | 43 +-- .../CallFunction/CallFunction.ino} | 25 +- .../CreateFunctionFromSources.ino} | 9 +- .../CreateFunctionWithCallback.ino} | 9 +- .../data/helloWorld.zip | Bin .../CreateFunctionWithEventTriggger.ino} | 9 +- .../data/firestoreImageDownloadTrigger.zip | Bin .../example.png | Bin .../CreateFunctionWithReturnStatus.ino} | 9 +- .../data/helloWorld.zip | Bin .../DeployAutoZipFunction}/AutoZIP.h | 0 .../DeployAutoZipFunction.ino} | 8 +- .../DeleteFunction/DeleteFunction.ino} | 25 +- .../DownloadFunction/DownloadFunction.ino} | 25 +- .../IAMPolicy/CreatePolicy/CreatePolicy.ino} | 2 + .../IAMPolicy/GetPolicy/GetPolicy.ino} | 25 +- .../IAMPolicy/SetPolicy/SetPolicy.ino} | 25 +- .../ListFunctions/ListFunctions.ino} | 25 +- .../PatchFunction/PatchFunction.ino} | 29 +- .../AppendArray/AppendArray.ino} | 25 +- .../SetUpdateDelete/SetUpdateDelete.ino} | 25 +- .../CreateDocuments.ino} | 25 +- .../DataQuery.ino} | 26 +- .../DeleteDocument.ino} | 45 +-- .../ExportDocuments.ino} | 28 +- .../GetDocument.ino} | 46 +-- .../ImportDocuments.ino} | 28 +- .../ListCollectionIds.ino} | 28 +- .../ListDocuments.ino} | 29 +- .../PatchDocument.ino} | 44 +-- .../AppInstanceInfo.ino} | 28 +- .../RegistAPNsTokens.ino} | 28 +- .../SendMessage.ino} | 30 +- .../SendTopic.ino} | 29 +- .../BroadcastMessage/BroadcastMessage.ino} | 28 +- .../SendMessage/SendMessage.ino} | 28 +- .../SendTopic/SendTopic.ino} | 28 +- .../SubscribeTopic.ino} | 28 +- .../UnsubscribeTopic.ino} | 28 +- .../Flash/Flash.ino} | 60 +-- .../SD/SD.ino} | 63 +--- .../Backup_and_Send_Email.ino | 242 ------------ examples/RTDB/Basic/Basic.ino | 180 ++------- examples/RTDB/BasicCert/BasicCert.ino | 157 ++++++++ .../data/gsr2.der | Bin .../BasicCert}/data/gsr2.pem | 0 .../BasicEthernetESP32/BasicEthernetESP32.ino | 216 +++++++++++ .../lan8720_modified_board.png | Bin .../lan8720_modified_schematic.png | Bin .../Basic_ESP32_with_Ethernet.ino | 344 ------------------ .../RTDB/Basic_with_Cert/Basic_with_Cert.ino | 282 -------------- examples/RTDB/Basic_with_Cert/data/gsr2.pem | 22 -- .../Beginner_Start_Here.ino | 171 --------- examples/RTDB/Blob/Blob.ino | 128 ++----- examples/RTDB/Blynk/Blynk.ino | 117 ++---- examples/{Test => RTDB/Browser}/index.html | 0 .../DataChangesListener/Callback/Callback.ino | 128 +++++++ .../MultiPath/MultiPath.ino} | 80 ++-- .../NoCallback/NoCallback.ino | 130 +++++++ .../SingleDataObject/SingleDataObject.ino | 126 +++++++ .../DataFilter.ino} | 68 +--- .../DatabaseRules.ino} | 72 +--- .../Different_Objects_Stream.ino | 208 ----------- .../Dynamic_FirebasseData.ino | 243 ------------- examples/RTDB/ETag/ETag.ino | 120 +----- examples/RTDB/FastSend/FastSend.ino | 50 +-- examples/RTDB/File/File.ino | 292 --------------- examples/RTDB/File/Flash/Flash.ino | 161 ++++++++ examples/RTDB/File/SD/SD.ino | 165 +++++++++ .../File_Flash_Memory/File_Flash_Memory.ino | 279 -------------- .../AnalogRead.ino} | 4 +- .../AutomaticPlantWatering.ino} | 3 + examples/RTDB/FireSense/Blink/Blink.ino | 3 + examples/RTDB/FireSense/Sensors/Sensors.ino | 3 + examples/RTDB/Line_Notify/Line_Notify.ino | 272 -------------- examples/RTDB/Priority/Priority.ino | 70 +--- .../Retry_and_Queue.ino => Queue/Queue.ino} | 219 +++-------- .../ShallowedData.ino} | 47 +-- examples/RTDB/Stream/Stream.ino | 160 -------- .../RTDB/Stream_Callback/Stream_Callback.ino | 174 --------- examples/RTDB/Timestamp/Timestamp.ino | 106 +----- examples/RTDB/jsonArray/jsonArray.ino | 193 ---------- examples/RTDB/jsonObject/jsonObject.ino | 186 ---------- .../DeleteFile/DeleteFile.ino} | 29 +- .../DownloadFile/DownloadFile.ino} | 30 +- .../ListFiles/ListFiles.ino} | 25 +- .../Metadata/Metadata.ino | 21 +- .../UploadByteArrayMemory.ino} | 21 +- .../UploadFile/UploadFile.ino} | 23 +- .../UploadFile}/data/media.mp4 | Bin .../DeleteFile/DeleteFile.ino} | 29 +- .../DownloadFile/DownloadFile.ino} | 29 +- .../ListFiles/ListFiles.ino} | 24 +- .../Metadata/Metadata.ino | 26 +- .../UploadFile/UploadFile.ino} | 19 +- .../UploadFile}/data/media.mp4 | Bin library.json | 2 +- library.properties | 2 +- src/Firebase_ESP_Client.cpp | 4 +- src/Firebase_ESP_Client.h | 8 +- src/README.md | 2 +- src/addons/RTDBHelper.h | 34 +- src/common.h | 3 +- src/rtdb/FB_RTDB.cpp | 8 +- src/rtdb/FB_RTDB.h | 4 +- src/stream/FB_MP_Stream.cpp | 8 +- src/stream/FB_MP_Stream.h | 5 +- 118 files changed, 1915 insertions(+), 5423 deletions(-) delete mode 100644 examples/Authentications/Access_Token_from_File/Access_Token_from_File.ino rename examples/Authentications/{Legacy_Token/Legacy_Token.ino => LegacyTokenAuthen/LegacyTokenAuthen.ino} (73%) create mode 100644 examples/Authentications/SignInAsAdmin/AccessTokenFile/AccessTokenFile.ino create mode 100644 examples/Authentications/SignInAsAdmin/AccessTokenFile/data/gsr2.pem rename examples/Authentications/{Anonymous_Signin/Anonymous_Signin.ino => SignInAsGuest/AnonymousSignin/AnonymousSignin.ino} (76%) rename examples/Authentications/{Custom_Token/Custom_Token.ino => SignInAsUser/CustomToken/CustomToken.ino} (89%) rename examples/Authentications/{Custom_Token_from_File/Custom_Token_from_File.ino => SignInAsUser/CustomTokenFile/CustomTokenFile.ino} (86%) rename examples/Authentications/{Email_Password/Email_Password.ino => SignInAsUser/EmailPassword/EmailPassword.ino} (77%) rename examples/Authentications/{Reset_Password/Reset_Password.ino => UserManagement/ResetPassword/ResetPassword.ino} (77%) rename examples/Authentications/{Send_Verification/Send_Verification.ino => UserManagement/SendVerification/SendVerification.ino} (65%) rename examples/Authentications/{ => UserManagement}/Signup/Signup.ino (75%) rename examples/{Cloud_Functions/Call_Function/Call_Function.ino => CloudFunctions/CallFunction/CallFunction.ino} (82%) rename examples/{Cloud_Functions/Create_Function/Create_Function_from_Sources/Create_Function_from_Sources.ino => CloudFunctions/CreateFunction/CreateFunctionFromSources/CreateFunctionFromSources.ino} (95%) rename examples/{Cloud_Functions/Create_Function/Create_Function_with_Callback/Create_Function_with_Callback.ino => CloudFunctions/CreateFunction/CreateFunctionWithCallback/CreateFunctionWithCallback.ino} (95%) rename examples/{Cloud_Functions/Create_Function/Create_Function_with_Callback => CloudFunctions/CreateFunction/CreateFunctionWithCallback}/data/helloWorld.zip (100%) rename examples/{Cloud_Functions/Create_Function/Create_Function_with_Event_Triggger/Create_Function_with_Event_Triggger.ino => CloudFunctions/CreateFunction/CreateFunctionWithEventTriggger/CreateFunctionWithEventTriggger.ino} (95%) rename examples/{Cloud_Functions/Create_Function/Create_Function_with_Event_Triggger => CloudFunctions/CreateFunction/CreateFunctionWithEventTriggger}/data/firestoreImageDownloadTrigger.zip (100%) rename examples/{Cloud_Functions/Create_Function/Create_Function_with_Event_Triggger => CloudFunctions/CreateFunction/CreateFunctionWithEventTriggger}/example.png (100%) rename examples/{Cloud_Functions/Create_Function/Create_Function_with_Return_Status/Create_Function_with_Return_Status.ino => CloudFunctions/CreateFunction/CreateFunctionWithReturnStatus/CreateFunctionWithReturnStatus.ino} (95%) rename examples/{Cloud_Functions/Create_Function/Create_Function_with_Return_Status => CloudFunctions/CreateFunction/CreateFunctionWithReturnStatus}/data/helloWorld.zip (100%) rename examples/{Cloud_Functions/Create_Function/Deploy_AutoZip_Function => CloudFunctions/CreateFunction/DeployAutoZipFunction}/AutoZIP.h (100%) rename examples/{Cloud_Functions/Create_Function/Deploy_AutoZip_Function/Deploy_AutoZip_Function.ino => CloudFunctions/CreateFunction/DeployAutoZipFunction/DeployAutoZipFunction.ino} (95%) rename examples/{Cloud_Functions/Delete_Function/Delete_Function.ino => CloudFunctions/DeleteFunction/DeleteFunction.ino} (81%) rename examples/{Cloud_Functions/Download_Function/Download_Function.ino => CloudFunctions/DownloadFunction/DownloadFunction.ino} (81%) rename examples/{Cloud_Functions/IAM_Policy/Create_Policy/Create_Policy.ino => CloudFunctions/IAMPolicy/CreatePolicy/CreatePolicy.ino} (94%) rename examples/{Cloud_Functions/IAM_Policy/Get_Policy/Get_Policy.ino => CloudFunctions/IAMPolicy/GetPolicy/GetPolicy.ino} (81%) rename examples/{Cloud_Functions/IAM_Policy/Set_Policy/Set_Policy.ino => CloudFunctions/IAMPolicy/SetPolicy/SetPolicy.ino} (83%) rename examples/{Cloud_Functions/List_Functions/List_Functions.ino => CloudFunctions/ListFunctions/ListFunctions.ino} (81%) rename examples/{Cloud_Functions/Patch_Function/Patch_Function.ino => CloudFunctions/PatchFunction/PatchFunction.ino} (80%) rename examples/Firestore/{Commit_Document/Append_Array/Append_Array.ino => CommitDocument/AppendArray/AppendArray.ino} (82%) rename examples/Firestore/{Commit_Document/Set_Update_Delete/Set_Update_Delete.ino => CommitDocument/SetUpdateDelete/SetUpdateDelete.ino} (87%) rename examples/Firestore/{Create_Documents/Create_Documents.ino => CreateDocuments/CreateDocuments.ino} (75%) rename examples/Firestore/{Data_Query/Data_Query.ino => DataQuery/DataQuery.ino} (78%) rename examples/Firestore/{Delete_Document/Delete_Document.ino => DeleteDocument/DeleteDocument.ino} (64%) rename examples/Firestore/{Export_Documents/Export_Documents.ino => ExportDocuments/ExportDocuments.ino} (75%) rename examples/Firestore/{Get_Document/Get_Document.ino => GetDocument/GetDocument.ino} (67%) rename examples/Firestore/{Import_Documents/Import_Documents.ino => ImportDocuments/ImportDocuments.ino} (76%) rename examples/Firestore/{List_CollectionIds/List_CollectionIds.ino => ListCollectionIds/ListCollectionIds.ino} (75%) rename examples/Firestore/{List_Documents/List_Documents.ino => ListDocuments/ListDocuments.ino} (71%) rename examples/Firestore/{Patch_Document/Patch_Document.ino => PatchDocument/PatchDocument.ino} (67%) rename examples/Messaging/{App_Instance_Info/App_Instance_Info.ino => AppInstanceInfo/AppInstanceInfo.ino} (63%) rename examples/Messaging/{Regist_APNs_Tokens/Regist_APNs_Tokens.ino => RegistAPNsTokens/RegistAPNsTokens.ino} (66%) rename examples/Messaging/Send/HTTPv1/{Send_Message/Send_Message.ino => SendMessage/SendMessage.ino} (77%) rename examples/Messaging/Send/HTTPv1/{Send_Topic/Send_Topic.ino => SendTopic/SendTopic.ino} (77%) rename examples/Messaging/Send/{Legacy_API/Broadcast_Message/Broadcast_Message.ino => LegacyAPI/BroadcastMessage/BroadcastMessage.ino} (75%) rename examples/Messaging/Send/{Legacy_API/Send_Message/Send_Message.ino => LegacyAPI/SendMessage/SendMessage.ino} (73%) rename examples/Messaging/Send/{Legacy_API/Send_Topic/Send_Topic.ino => LegacyAPI/SendTopic/SendTopic.ino} (72%) rename examples/Messaging/{Subscribe_Topic/Subscribe_Topic.ino => SubscribeTopic/SubscribeTopic.ino} (66%) rename examples/Messaging/{Unsubscribe_Topic/Unsubscribe_Topic.ino => UnsubscribeTopic/UnsubscribeTopic.ino} (67%) rename examples/RTDB/{Backup_and_Restore_Flash_Memory/Backup_and_Restore_Flash_Memory.ino => BackupRestore/Flash/Flash.ino} (59%) rename examples/RTDB/{Backup_and_Restore/Backup_and_Restore.ino => BackupRestore/SD/SD.ino} (57%) delete mode 100644 examples/RTDB/Backup_and_Send_Email/Backup_and_Send_Email.ino create mode 100644 examples/RTDB/BasicCert/BasicCert.ino rename examples/RTDB/{Basic_with_Cert => BasicCert}/data/gsr2.der (100%) rename examples/{Authentications/Access_Token_from_File => RTDB/BasicCert}/data/gsr2.pem (100%) create mode 100644 examples/RTDB/BasicEthernetESP32/BasicEthernetESP32.ino rename examples/RTDB/{Basic_ESP32_with_Ethernet => BasicEthernetESP32}/modified_LAN8720_board_images/lan8720_modified_board.png (100%) rename examples/RTDB/{Basic_ESP32_with_Ethernet => BasicEthernetESP32}/modified_LAN8720_board_images/lan8720_modified_schematic.png (100%) delete mode 100644 examples/RTDB/Basic_ESP32_with_Ethernet/Basic_ESP32_with_Ethernet.ino delete mode 100644 examples/RTDB/Basic_with_Cert/Basic_with_Cert.ino delete mode 100644 examples/RTDB/Basic_with_Cert/data/gsr2.pem delete mode 100644 examples/RTDB/Beginner_Start_Here/Beginner_Start_Here.ino rename examples/{Test => RTDB/Browser}/index.html (100%) create mode 100644 examples/RTDB/DataChangesListener/Callback/Callback.ino rename examples/RTDB/{MultiPath_Stream/MultiPath_Stream.ino => DataChangesListener/MultiPath/MultiPath.ino} (54%) create mode 100644 examples/RTDB/DataChangesListener/NoCallback/NoCallback.ino create mode 100644 examples/RTDB/DataChangesListener/SingleDataObject/SingleDataObject.ino rename examples/RTDB/{Data_Filter/Data_Filter.ino => DataFilter/DataFilter.ino} (60%) rename examples/RTDB/{Get_Set_Database_Rules/Get_Set_Database_Rules.ino => DatabaseRules/DatabaseRules.ino} (56%) delete mode 100644 examples/RTDB/Different_Objects_Stream/Different_Objects_Stream.ino delete mode 100644 examples/RTDB/Dynamic_FirebaseData/Dynamic_FirebasseData.ino delete mode 100644 examples/RTDB/File/File.ino create mode 100644 examples/RTDB/File/Flash/Flash.ino create mode 100644 examples/RTDB/File/SD/SD.ino delete mode 100644 examples/RTDB/File_Flash_Memory/File_Flash_Memory.ino rename examples/RTDB/FireSense/{Analog_Read/Analog_Read.ino => AnalogRead/AnalogRead.ino} (96%) rename examples/RTDB/FireSense/{Automatic_Plant_Watering/Automatic_Plant_Watering.ino => AutomaticPlantWatering/AutomaticPlantWatering.ino} (96%) delete mode 100644 examples/RTDB/Line_Notify/Line_Notify.ino rename examples/RTDB/{Retry_and_Queue/Retry_and_Queue.ino => Queue/Queue.ino} (52%) rename examples/RTDB/{Shallowed_Data/Shallowed_Data.ino => ShallowedData/ShallowedData.ino} (63%) delete mode 100644 examples/RTDB/Stream/Stream.ino delete mode 100644 examples/RTDB/Stream_Callback/Stream_Callback.ino delete mode 100644 examples/RTDB/jsonArray/jsonArray.ino delete mode 100644 examples/RTDB/jsonObject/jsonObject.ino rename examples/Storage/{Firebase_Storage/Delete_File/Delete_File.ino => FirebaseStorage/DeleteFile/DeleteFile.ino} (68%) rename examples/Storage/{Firebase_Storage/Download_File/Download_File.ino => FirebaseStorage/DownloadFile/DownloadFile.ino} (65%) rename examples/Storage/{Firebase_Storage/List_Files/List_Files.ino => FirebaseStorage/ListFiles/ListFiles.ino} (72%) rename examples/Storage/{Firebase_Storage => FirebaseStorage}/Metadata/Metadata.ino (77%) rename examples/Storage/{Firebase_Storage/Upload_Byte_Array_Memory/Upload_Byte_Array_Memory.ino => FirebaseStorage/UploadByteArrayMemory/UploadByteArrayMemory.ino} (80%) rename examples/Storage/{Firebase_Storage/Upload_File/Upload_File.ino => FirebaseStorage/UploadFile/UploadFile.ino} (82%) rename examples/Storage/{Firebase_Storage/Upload_File => FirebaseStorage/UploadFile}/data/media.mp4 (100%) rename examples/Storage/{Google_Cloud_Storage/Delete_File/Delete_File.ino => GoogleCloudStorage/DeleteFile/DeleteFile.ino} (76%) rename examples/Storage/{Google_Cloud_Storage/Download_File/Download_File.ino => GoogleCloudStorage/DownloadFile/DownloadFile.ino} (77%) rename examples/Storage/{Google_Cloud_Storage/List_Files/List_Files.ino => GoogleCloudStorage/ListFiles/ListFiles.ino} (78%) rename examples/Storage/{Google_Cloud_Storage => GoogleCloudStorage}/Metadata/Metadata.ino (80%) rename examples/Storage/{Google_Cloud_Storage/Upload_File/Upload_File.ino => GoogleCloudStorage/UploadFile/UploadFile.ino} (90%) rename examples/Storage/{Google_Cloud_Storage/Upload_File => GoogleCloudStorage/UploadFile}/data/media.mp4 (100%) diff --git a/README.md b/README.md index 0a3ecb1ba..d98c3fa42 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Firebase Arduino Client Library for ESP8266 and ESP32 -Google's Firebase Arduino Client Library for ESP8266 and ESP32 v2.2.1 +Google's Firebase Arduino Client Library for ESP8266 and ESP32 v2.2.2 This library supports ESP8266 and ESP32 MCU from Espressif. The following are platforms in which the libraries are also available (RTDB only). @@ -182,17 +182,6 @@ fbdo.setResponseSize(1024); //minimum size is 1024 bytes ``` -### Important Information - -In ESP8266 Arduino Core SDK v3.x.x - -The free heap is significantly reduced as much as 5-6 kB from v2.7.4. - -This may lead to out of memory sitation when two Firebase Data objects are used simultaneously (when sessions connected). - -Minimize the reserved memory for BearSSL will gain the free heap a bit but may not enough for your usage. - -You can stay with Core SDK v2.7.4 until this memory issue was solve in the Core SDK. diff --git a/examples/Authentications/Access_Token_from_File/Access_Token_from_File.ino b/examples/Authentications/Access_Token_from_File/Access_Token_from_File.ino deleted file mode 100644 index b0f2c4996..000000000 --- a/examples/Authentications/Access_Token_from_File/Access_Token_from_File.ino +++ /dev/null @@ -1,150 +0,0 @@ - -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -/** This example will show how to authenticate as admin using - * the Service Account file to create the access token to sign in internally. -*/ - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" -//Provide the RTDB payload printing info and other helper functions. -#include "addons/RTDBHelper.h" - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. If work with RTDB, define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 3. Define the Firebase Data object */ -FirebaseData fbdo; - -/* 4. Define the FirebaseAuth data for authentication data */ -FirebaseAuth auth; - -/* 5. Define the FirebaseConfig data for config data */ -FirebaseConfig config; - - -String path = "/Test"; -unsigned long dataMillis = 0; -int count = 0; - -void setup() -{ - - Serial.begin(115200); - - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); - Serial.print("Connecting to Wi-Fi"); - while (WiFi.status() != WL_CONNECTED) - { - Serial.print("."); - delay(300); - } - Serial.println(); - Serial.print("Connected with IP: "); - Serial.println(WiFi.localIP()); - Serial.println(); - - /* Assign the certificate file (optional) */ - config.cert.file = "/gsr2.pem"; - config.cert.file_storage = mem_storage_type_flash; //or mem_storage_type_sd - - - /* The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. */ - - /* Assign the sevice account JSON file and the file storage type (required) */ - config.service_account.json.path = "/service_account_file.json"; //change this for your json file - config.service_account.json.storage_type = mem_storage_type_flash; - - /** The user UID set to empty to sign in as admin */ - auth.token.uid = ""; - - /* Assign the RTDB URL */ - config.database_url = DATABASE_URL; - - /** The scope of the OAuth2.0 authentication - * If you wan't this access token for others Google Cloud Services. - */ - //config.signer.tokens.scope = "Google Scope 1 Url, Google Scope 2 Url,.."; - - Firebase.reconnectWiFi(true); - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - /** Assign the maximum retry of token generation */ - config.max_token_generation_retry = 5; - - /** To set system time with the timestamp from RTC - * The internal NTP server time acquisition - * of token generation process will be skipped, - * if the system time is already set. - * - * sec is the seconds from midnight Jan 1, 1970 - */ - //Firebase.setSystemTime(sec); - - /* Now we start to signin using access token */ - - /** Initialize the library with the Firebase authen and config. - * - * The device time will be set by sending request to the NTP server - * befor token generation and exchanging. - * - * The signed RSA256 jwt token will be created and used for access token exchanging. - * - * Theses process may take time to complete. - */ - Firebase.begin(&config, &auth); - - /* The access token (C++ string) can be accessed from config.signer.tokens.access_token. */ -} - -void loop() -{ - if (millis() - dataMillis > 5000) - { - dataMillis = millis(); - - if (Firebase.ready()) - { - Serial.println("------------------------------------"); - Serial.println("Set int test..."); - - String node = path + "/int"; - - if (Firebase.RTDB.set(&fbdo, node.c_str(), count++)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - } -} \ No newline at end of file diff --git a/examples/Authentications/Legacy_Token/Legacy_Token.ino b/examples/Authentications/LegacyTokenAuthen/LegacyTokenAuthen.ino similarity index 73% rename from examples/Authentications/Legacy_Token/Legacy_Token.ino rename to examples/Authentications/LegacyTokenAuthen/LegacyTokenAuthen.ino index 7cffd1b10..ba506b18b 100644 --- a/examples/Authentications/Legacy_Token/Legacy_Token.ino +++ b/examples/Authentications/LegacyTokenAuthen/LegacyTokenAuthen.ino @@ -13,6 +13,7 @@ /** This example will show how to authenticate using * the legacy token or database secret with the new APIs (using config and auth data). */ + #if defined(ESP32) #include #elif defined(ESP8266) @@ -40,7 +41,6 @@ FirebaseAuth auth; /* Define the FirebaseConfig data for config data */ FirebaseConfig config; -String path = "/Test"; unsigned long dataMillis = 0; int count = 0; @@ -61,6 +61,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the certificate file (optional) */ //config.cert.file = "/cert.cer"; //config.cert.file_storage = StorageType::FLASH; @@ -73,6 +75,9 @@ void setup() /* Initialize the library with the Firebase authen and config */ Firebase.begin(&config, &auth); + + //Or use legacy authenticate method + //Firebase.begin(DATABASE_URL, DATABASE_SECRET); } void loop() @@ -80,24 +85,6 @@ void loop() if (millis() - dataMillis > 5000) { dataMillis = millis(); - - Serial.println("------------------------------------"); - Serial.println("Set int test..."); - - String node = path + "/int"; - - if (Firebase.RTDB.set(&fbdo, node.c_str(), count++)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("Set int... %s\n", Firebase.RTDB.setInt(&fbdo, "/test/int", count++) ? "ok" : fbdo.errorReason().c_str()); } } diff --git a/examples/Authentications/SignInAsAdmin/AccessTokenFile/AccessTokenFile.ino b/examples/Authentications/SignInAsAdmin/AccessTokenFile/AccessTokenFile.ino new file mode 100644 index 000000000..3c3825374 --- /dev/null +++ b/examples/Authentications/SignInAsAdmin/AccessTokenFile/AccessTokenFile.ino @@ -0,0 +1,137 @@ + +/** + * Created by K. Suwatchai (Mobizt) + * + * Email: k_suwatchai@hotmail.com + * + * Github: https://github.com/mobizt + * + * Copyright (c) 2021 mobizt + * +*/ + +/** This example will show how to authenticate as admin using + * the Service Account file to create the access token to sign in internally. + * + * The library will connect to NTP server to get the time (in case your device + * time was not set) + * and waiting for the time to be ready. + * + * If the waiting is timed out and the system time is not ready, the custom and + * OAuth2.0 acces tokens generation will fail + * because of invalid expiration time in JWT token that used in the id/access + * token request. +*/ + +#if defined(ESP32) +#include +#elif defined(ESP8266) +#include +#endif +#include + +//Provide the token generation process info. +#include "addons/TokenHelper.h" +//Provide the RTDB payload printing info and other helper functions. +#include "addons/RTDBHelper.h" + +/* 1. Define the WiFi credentials */ +#define WIFI_SSID "WIFI_AP" +#define WIFI_PASSWORD "WIFI_PASSWORD" + +/* 2. If work with RTDB, define the RTDB URL */ +#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app + +/* 3. Define the Firebase Data object */ +FirebaseData fbdo; + +/* 4. Define the FirebaseAuth data for authentication data */ +FirebaseAuth auth; + +/* 5. Define the FirebaseConfig data for config data */ +FirebaseConfig config; + +unsigned long dataMillis = 0; +int count = 0; + +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(); + + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + + /* Assign the certificate file (optional) */ + config.cert.file = "/gsr2.pem"; + config.cert.file_storage = mem_storage_type_flash; //or mem_storage_type_sd + + /* The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. */ + + /* Assign the sevice account JSON file and the file storage type (required) */ + config.service_account.json.path = "/service_account_file.json"; //change this for your json file + config.service_account.json.storage_type = mem_storage_type_flash; //or mem_storage_type_sd + + /** The user UID set to empty to sign in as admin */ + auth.token.uid = ""; + + /* Assign the RTDB URL */ + config.database_url = DATABASE_URL; + + /** The scope of the OAuth2.0 authentication + * If you wan't this access token for others Google Cloud Services. + */ + //config.signer.tokens.scope = "Google Scope 1 Url, Google Scope 2 Url,.."; + + Firebase.reconnectWiFi(true); + + /* Assign the callback function for the long running token generation task */ + config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h + + /** Assign the maximum retry of token generation */ + config.max_token_generation_retry = 5; + + /** To set system time with the timestamp from RTC + * The internal NTP server time acquisition + * of token generation process will be skipped, + * if the system time is already set. + * + * sec is the seconds from midnight Jan 1, 1970 + */ + //Firebase.setSystemTime(sec); + + /* Now we start to signin using access token */ + + /** Initialize the library with the Firebase authen and config. + * + * The device time will be set by sending request to the NTP server + * befor token generation and exchanging. + * + * The signed RSA256 jwt token will be created and used for access token exchanging. + * + * Theses process may take time to complete. + */ + Firebase.begin(&config, &auth); + + /* The access token (C++ string) can be accessed from config.signer.tokens.access_token. */ +} + +void loop() +{ + if (Firebase.ready() && millis() - dataMillis > 5000) + { + dataMillis = millis(); + Serial.printf("Set int... %s\n", Firebase.RTDB.setInt(&fbdo, "/test/int", count++) ? "ok" : fbdo.errorReason().c_str()); + } +} \ No newline at end of file diff --git a/examples/Authentications/SignInAsAdmin/AccessTokenFile/data/gsr2.pem b/examples/Authentications/SignInAsAdmin/AccessTokenFile/data/gsr2.pem new file mode 100644 index 000000000..6ebf7bec0 --- /dev/null +++ b/examples/Authentications/SignInAsAdmin/AccessTokenFile/data/gsr2.pem @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4G +A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNp +Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1 +MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEG +A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPL +v4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8 +eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklq +tTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd +C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pa +zq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCB +mTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IH +V2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5n +bG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG +3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs +J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO +291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavS +ot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd +AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7 +TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg== +-----END CERTIFICATE----- diff --git a/examples/Authentications/Anonymous_Signin/Anonymous_Signin.ino b/examples/Authentications/SignInAsGuest/AnonymousSignin/AnonymousSignin.ino similarity index 76% rename from examples/Authentications/Anonymous_Signin/Anonymous_Signin.ino rename to examples/Authentications/SignInAsGuest/AnonymousSignin/AnonymousSignin.ino index dd3c17330..17574e9f3 100644 --- a/examples/Authentications/Anonymous_Signin/Anonymous_Signin.ino +++ b/examples/Authentications/SignInAsGuest/AnonymousSignin/AnonymousSignin.ino @@ -60,7 +60,6 @@ FirebaseAuth auth; /* 6. Define the FirebaseConfig data for config data */ FirebaseConfig config; -String path = ""; unsigned long dataMillis = 0; int count = 0; bool signupOK = false; @@ -82,6 +81,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the API key (required) */ config.api_key = API_KEY; @@ -90,9 +91,6 @@ void setup() Firebase.reconnectWiFi(true); - Serial.println("------------------------------------"); - Serial.println("Sign up new user..."); - /** To sign in as anonymous user, just sign up as anonymous user * with blank email and password. * @@ -104,23 +102,25 @@ void setup() * * Warning: this will create anonymous user everytime you call this function */ + + Serial.print("Sign up new user... "); + + /* Sign up */ if (Firebase.signUp(&config, &auth, "", "")) { - Serial.println("Success"); + Serial.println("ok"); signupOK = true; - /** if the database rules were set as in the example "Email_Password.ino" + /** if the database rules were set as in the example "EmailPassword.ino" * This new user can be access the following location. * - * The new user UID can be taken from auth.token.uid + * "/UserData/" + * + * The new user UID or can be taken from auth.token.uid */ - path = "/UsersData2/"; - path += auth.token.uid.c_str(); } else - { - Serial.printf("Failed, %s\n", config.signer.signupError.message.c_str()); - } + Serial.printf("%s\n", config.signer.signupError.message.c_str()); /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h @@ -141,24 +141,8 @@ void loop() if (millis() - dataMillis > 5000 && signupOK && Firebase.ready()) { dataMillis = millis(); - - Serial.println("------------------------------------"); - Serial.println("Set int test..."); - - String node = path + "/int"; - - if (Firebase.RTDB.set(&fbdo, node.c_str(), count++)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + String path = auth.token.uid.c_str(); //<- user uid + path += "/test/int"; + Serial.printf("Set int... %s\n", Firebase.RTDB.setInt(&fbdo, path.c_str(), count++) ? "ok" : fbdo.errorReason().c_str()); } } diff --git a/examples/Authentications/Custom_Token/Custom_Token.ino b/examples/Authentications/SignInAsUser/CustomToken/CustomToken.ino similarity index 89% rename from examples/Authentications/Custom_Token/Custom_Token.ino rename to examples/Authentications/SignInAsUser/CustomToken/CustomToken.ino index d65e3fc32..247d5d06e 100644 --- a/examples/Authentications/Custom_Token/Custom_Token.ino +++ b/examples/Authentications/SignInAsUser/CustomToken/CustomToken.ino @@ -107,7 +107,6 @@ FirebaseAuth auth; /* 7. Define the FirebaseConfig data for config data */ FirebaseConfig config; -String path = ""; unsigned long dataMillis = 0; int count = 0; @@ -128,6 +127,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the certificate data (optional) */ //config.cert.data = rootCACert; @@ -200,8 +201,8 @@ void setup() * which located at some level in the rule structure and use as reference variable * in .read, .write and .validate rules * - * For this case $userId represents any xxxx node that places under UsersData node i.e. - * /UsersData/xxxxx which xxxx is user UID or "Node1" in this case. + * For this case $userId represents any node that places under UsersData node i.e. + * /UsersData/ which is user UID or "Node1" in this case. * * Please check your the database rules to see the changes after run the below code. */ @@ -220,8 +221,6 @@ void setup() * * The id token (C++ string) can be accessed from config.signer.tokens.id_token. */ - - path = base_path + auth.token.uid.c_str(); } void loop() @@ -229,24 +228,9 @@ void loop() if (millis() - dataMillis > 5000 && Firebase.ready()) { dataMillis = millis(); - - Serial.println("------------------------------------"); - Serial.println("Set int test..."); - - String node = path + "/int"; - - if (Firebase.RTDB.set(&fbdo, node.c_str(), count++)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + String path = "/UsersData/"; + path += auth.token.uid.c_str(); //<- user uid or "Node1" + path += "/test/int"; + Serial.printf("Set int... %s\n", Firebase.RTDB.setInt(&fbdo, path.c_str(), count++) ? "ok" : fbdo.errorReason().c_str()); } } \ No newline at end of file diff --git a/examples/Authentications/Custom_Token_from_File/Custom_Token_from_File.ino b/examples/Authentications/SignInAsUser/CustomTokenFile/CustomTokenFile.ino similarity index 86% rename from examples/Authentications/Custom_Token_from_File/Custom_Token_from_File.ino rename to examples/Authentications/SignInAsUser/CustomTokenFile/CustomTokenFile.ino index f298935c7..8712bbc04 100644 --- a/examples/Authentications/Custom_Token_from_File/Custom_Token_from_File.ino +++ b/examples/Authentications/SignInAsUser/CustomTokenFile/CustomTokenFile.ino @@ -71,7 +71,6 @@ FirebaseAuth auth; /* 7. Define the FirebaseConfig data for config data */ FirebaseConfig config; -String path = ""; unsigned long dataMillis = 0; int count = 0; @@ -92,6 +91,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the certificate file (optional) */ //config.cert.file = "/cert.cer"; //config.cert.file_storage = mem_storage_type_flash; @@ -103,7 +104,7 @@ void setup() /* Assign the sevice account JSON file and the file storage type (required) */ config.service_account.json.path = "/service_account_file.json"; //change this for your json file - config.service_account.json.storage_type = mem_storage_type_flash; //or mem_storage_type_sd + config.service_account.json.storage_type = mem_storage_type_flash; //or mem_storage_type_sd /** Assign the unique user ID (uid) (required) * This uid will be compare to the auth.uid variable in the database rules. @@ -175,8 +176,8 @@ void setup() * which located at some level in the rule structure and use as reference variable * in .read, .write and .validate rules * - * For this case $userId represents any xxxx node that places under UsersData node i.e. - * /UsersData/xxxxx which xxxx is user UID or "Node1" in this case. + * For this case $userId represents any node that places under UsersData node i.e. + * /UsersData/ which is user UID or "Node1" in this case. * * Please check your the database rules to see the changes after run the below code. */ @@ -195,8 +196,6 @@ void setup() * * The id token (C++ string) can be accessed from config.signer.tokens.id_token. */ - - path = base_path + auth.token.uid.c_str(); } void loop() @@ -204,24 +203,9 @@ void loop() if (millis() - dataMillis > 5000 && Firebase.ready()) { dataMillis = millis(); - - Serial.println("------------------------------------"); - Serial.println("Set int test..."); - - String node = path + "/int"; - - if (Firebase.RTDB.set(&fbdo, node.c_str(), count++)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + String path = "/UsersData/"; + path += auth.token.uid.c_str(); //<- user uid is "Node1" + path += "/test/int"; + Serial.printf("Set int... %s\n", Firebase.RTDB.setInt(&fbdo, path.c_str(), count++) ? "ok" : fbdo.errorReason().c_str()); } } diff --git a/examples/Authentications/Email_Password/Email_Password.ino b/examples/Authentications/SignInAsUser/EmailPassword/EmailPassword.ino similarity index 77% rename from examples/Authentications/Email_Password/Email_Password.ino rename to examples/Authentications/SignInAsUser/EmailPassword/EmailPassword.ino index 06bdef920..dfdda0e16 100644 --- a/examples/Authentications/Email_Password/Email_Password.ino +++ b/examples/Authentications/SignInAsUser/EmailPassword/EmailPassword.ino @@ -77,7 +77,6 @@ FirebaseAuth auth; /* 8. Define the FirebaseConfig data for config data */ FirebaseConfig config; -String path = ""; unsigned long dataMillis = 0; int count = 0; @@ -98,6 +97,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -111,7 +112,7 @@ void setup() Firebase.reconnectWiFi(true); fbdo.setResponseSize(4096); - String base_path = "/UsersData2/"; + String base_path = "/UsersData/"; /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h @@ -124,9 +125,8 @@ void setup() /** Now modify the database rules (if not yet modified) * - * The user, Node1 in this case will be granted to read and write - * at the curtain location i.e. "/UsersData/Node1" and we will also check the - * custom claims in the rules which must be matched. + * The user, in this case will be granted to read and write + * at the certain location i.e. "/UsersData/". * * If you database rules has been modified, please comment this code out. * @@ -134,8 +134,8 @@ void setup() * which located at some level in the rule structure and use as reference variable * in .read, .write and .validate rules * - * For this case $userId represents any xxxx node that places under UsersData node i.e. - * /UsersData/xxxxx which xxxx is user UID or "Node1" in this case. + * For this case $userId represents any node that places under UsersData node i.e. + * /UsersData/ which is user UID. * * Please check your the database rules to see the changes after run the below code. */ @@ -143,10 +143,9 @@ void setup() String val = "($userId === auth.uid && auth.token.premium_account === true && auth.token.admin === true)"; Firebase.RTDB.setReadWriteRules(&fbdo, base_path.c_str(), var.c_str(), val.c_str(), val.c_str(), DATABASE_SECRET); - /** path for user data is now "/UsersData2/YOUR_USER_UID" + /** path for user data is now "/UsersData/" * The user UID can be taken from auth.token.uid */ - path = base_path + auth.token.uid.c_str(); } void loop() @@ -154,24 +153,9 @@ void loop() if (millis() - dataMillis > 5000 && Firebase.ready()) { dataMillis = millis(); - - Serial.println("------------------------------------"); - Serial.println("Set int test..."); - - String node = path + "/int"; - - if (Firebase.RTDB.set(&fbdo, node.c_str(), count++)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + String path = "/UsersData/"; + path += auth.token.uid.c_str(); //<- user uid of current user that sign in with Emal/Password + path += "/test/int"; + Serial.printf("Set int... %s\n", Firebase.RTDB.setInt(&fbdo, path.c_str(), count++) ? "ok" : fbdo.errorReason().c_str()); } } diff --git a/examples/Authentications/Reset_Password/Reset_Password.ino b/examples/Authentications/UserManagement/ResetPassword/ResetPassword.ino similarity index 77% rename from examples/Authentications/Reset_Password/Reset_Password.ino rename to examples/Authentications/UserManagement/ResetPassword/ResetPassword.ino index bb7496537..2053965b1 100644 --- a/examples/Authentications/Reset_Password/Reset_Password.ino +++ b/examples/Authentications/UserManagement/ResetPassword/ResetPassword.ino @@ -46,7 +46,6 @@ /* 5. Define the FirebaseConfig data for config data */ FirebaseConfig config; - void setup() { @@ -64,6 +63,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the API key (required) */ config.api_key = API_KEY; @@ -72,21 +73,9 @@ void setup() Firebase.reconnectWiFi(true); - Serial.println("------------------------------------"); - Serial.println("Send Email reset password link..."); - - /* Send password reset link to user Email */ - if (Firebase.sendResetPassword(&config, USER_EMAIL)) - { - Serial.printf("Success, the reset password link was sent to %s\n\n", USER_EMAIL); - } - else - { - Serial.printf("Failed, %s\n\n", config.signer.resetPswError.message.c_str()); - } + Serial.printf("Send Email reset password link... %s\n", Firebase.sendResetPassword(&config, USER_EMAIL) ? "ok" : config.signer.resetPswError.message.c_str()); } void loop() { - } diff --git a/examples/Authentications/Send_Verification/Send_Verification.ino b/examples/Authentications/UserManagement/SendVerification/SendVerification.ino similarity index 65% rename from examples/Authentications/Send_Verification/Send_Verification.ino rename to examples/Authentications/UserManagement/SendVerification/SendVerification.ino index 110514aab..193a4d703 100644 --- a/examples/Authentications/Send_Verification/Send_Verification.ino +++ b/examples/Authentications/UserManagement/SendVerification/SendVerification.ino @@ -18,7 +18,6 @@ * * In the database rules, you can guard the unverified user from access by adding "auth.token.email_verified == true" */ - #if defined(ESP32) #include #elif defined(ESP8266) @@ -63,7 +62,6 @@ FirebaseAuth auth; /* 7. Define the FirebaseConfig data for config data */ FirebaseConfig config; -String path = ""; unsigned long dataMillis = 0; int count = 0; bool signupOK = false; @@ -85,6 +83,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the API key (required) */ config.api_key = API_KEY; @@ -102,54 +102,14 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - String base_path = "/UsersData2/"; - /* Initialize the library with the Firebase authen and config */ Firebase.begin(&config, &auth); - /** path for user data is now "/UsersData2/YOUR_USER_UID" - * The user UID can be taken from auth.token.uid - */ - path = base_path + auth.token.uid.c_str(); + Serial.printf("Send Email verification... %s\n", Firebase.sendEmailVerification(&config) ? "ok" : config.signer.verificationError.message.c_str()); - Serial.println("------------------------------------"); - Serial.println("Send Email verification..."); - - /* Send verification Email using internal created id token after Email/Password signed in */ - if (Firebase.sendEmailVerification(&config)) - { - Serial.printf("Success, the verification link was sent to %s\n\n", auth.user.email.c_str()); - } - else - { - Serial.printf("Failed, %s\n\n", config.signer.verificationError.message.c_str()); - } - } void loop() { - if (millis() - dataMillis > 5000 && Firebase.ready()) - { - dataMillis = millis(); - - Serial.println("------------------------------------"); - Serial.println("Set int test..."); - - String Path = path + "/int"; - - if (Firebase.RTDB.set(&fbdo, Path.c_str(), count++)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } + } diff --git a/examples/Authentications/Signup/Signup.ino b/examples/Authentications/UserManagement/Signup/Signup.ino similarity index 75% rename from examples/Authentications/Signup/Signup.ino rename to examples/Authentications/UserManagement/Signup/Signup.ino index d8b472282..b2b774d9f 100644 --- a/examples/Authentications/Signup/Signup.ino +++ b/examples/Authentications/UserManagement/Signup/Signup.ino @@ -57,7 +57,6 @@ FirebaseAuth auth; /* 6. Define the FirebaseConfig data for config data */ FirebaseConfig config; -String path = ""; unsigned long dataMillis = 0; int count = 0; bool signupOK = false; @@ -79,6 +78,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the API key (required) */ config.api_key = API_KEY; @@ -87,27 +88,24 @@ void setup() Firebase.reconnectWiFi(true); - Serial.println("------------------------------------"); - Serial.println("Sign up new user..."); + Serial.print("Sign up new user... "); /* Sign up */ if (Firebase.signUp(&config, &auth, "test_user@gmail.com", "password")) { - Serial.println("Success"); + Serial.println("ok"); signupOK = true; - /** if the database rules were set as in the example "Email_Password.ino" + /** if the database rules were set as in the example "EmailPassword.ino" * This new user can be access the following location. * + * "/UsersData/" + * * The new user UID can be taken from auth.token.uid */ - path = "/UsersData2/"; - path += auth.token.uid.c_str(); } else - { - Serial.printf("Failed, %s\n", config.signer.signupError.message.c_str()); - } + Serial.printf("%s\n", config.signer.signupError.message.c_str()); /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h @@ -121,8 +119,6 @@ void setup() * the internal authentication credentials are not created. */ Firebase.begin(&config, &auth); - - } void loop() @@ -130,24 +126,9 @@ void loop() if (millis() - dataMillis > 5000 && signupOK && Firebase.ready()) { dataMillis = millis(); - - Serial.println("------------------------------------"); - Serial.println("Set int test..."); - - String Path = path + "/int"; - - if (Firebase.RTDB.set(&fbdo, Path.c_str(), count++)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + String path = "/UsersData/"; + path += auth.token.uid.c_str();//<- user uid + path += "/test/int"; + Serial.printf("Set int... %s\n", Firebase.RTDB.setInt(&fbdo, path.c_str(), count++) ? "ok" : fbdo.errorReason().c_str()); } } \ No newline at end of file diff --git a/examples/Cloud_Functions/Call_Function/Call_Function.ino b/examples/CloudFunctions/CallFunction/CallFunction.ino similarity index 82% rename from examples/Cloud_Functions/Call_Function/Call_Function.ino rename to examples/CloudFunctions/CallFunction/CallFunction.ino index 40afa385c..9216ca99e 100644 --- a/examples/Cloud_Functions/Call_Function/Call_Function.ino +++ b/examples/CloudFunctions/CallFunction/CallFunction.ino @@ -90,6 +90,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -102,12 +104,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -123,21 +121,10 @@ void callFunction() { //Assumed that the function named helloWorld is already created and deployed for project. - Serial.println("------------------------------------"); - Serial.println("Call the Cloud Function..."); + Serial.print("Call the Cloud Function... "); if (Firebase.Functions.callFunction(&fbdo, FIREBASE_PROJECT_ID /* project id */, PROJECT_LOCATION /* location id */, "helloWorld" /* function name */, "" /* data pass to Cloud function */)) - { - Serial.println("PASSED"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } diff --git a/examples/Cloud_Functions/Create_Function/Create_Function_from_Sources/Create_Function_from_Sources.ino b/examples/CloudFunctions/CreateFunction/CreateFunctionFromSources/CreateFunctionFromSources.ino similarity index 95% rename from examples/Cloud_Functions/Create_Function/Create_Function_from_Sources/Create_Function_from_Sources.ino rename to examples/CloudFunctions/CreateFunction/CreateFunctionFromSources/CreateFunctionFromSources.ino index e6a45aafd..f61c5252a 100644 --- a/examples/Cloud_Functions/Create_Function/Create_Function_from_Sources/Create_Function_from_Sources.ino +++ b/examples/CloudFunctions/CreateFunction/CreateFunctionFromSources/CreateFunctionFromSources.ino @@ -131,6 +131,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -143,12 +145,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -185,7 +183,6 @@ void creatFunction() function_config.setIamPolicy(&policy); - Serial.println("------------------------------------"); Serial.println("Create the Googgle Cloud Function..."); Firebase.Functions.createFunction(&fbdo, &function_config /* FunctionsConfig */, functionCreationCallback /* the callback function */); diff --git a/examples/Cloud_Functions/Create_Function/Create_Function_with_Callback/Create_Function_with_Callback.ino b/examples/CloudFunctions/CreateFunction/CreateFunctionWithCallback/CreateFunctionWithCallback.ino similarity index 95% rename from examples/Cloud_Functions/Create_Function/Create_Function_with_Callback/Create_Function_with_Callback.ino rename to examples/CloudFunctions/CreateFunction/CreateFunctionWithCallback/CreateFunctionWithCallback.ino index 67fa8e4b5..9a6819440 100644 --- a/examples/Cloud_Functions/Create_Function/Create_Function_with_Callback/Create_Function_with_Callback.ino +++ b/examples/CloudFunctions/CreateFunction/CreateFunctionWithCallback/CreateFunctionWithCallback.ino @@ -116,6 +116,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -128,12 +130,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -179,7 +177,6 @@ void creatFunction() function_config.setIamPolicy(&policy); - Serial.println("------------------------------------"); Serial.println("Create the Googgle Cloud Function..."); Firebase.Functions.createFunction(&fbdo, &function_config /* FunctionsConfig */, functionCreationCallback /* the callback function */); diff --git a/examples/Cloud_Functions/Create_Function/Create_Function_with_Callback/data/helloWorld.zip b/examples/CloudFunctions/CreateFunction/CreateFunctionWithCallback/data/helloWorld.zip similarity index 100% rename from examples/Cloud_Functions/Create_Function/Create_Function_with_Callback/data/helloWorld.zip rename to examples/CloudFunctions/CreateFunction/CreateFunctionWithCallback/data/helloWorld.zip diff --git a/examples/Cloud_Functions/Create_Function/Create_Function_with_Event_Triggger/Create_Function_with_Event_Triggger.ino b/examples/CloudFunctions/CreateFunction/CreateFunctionWithEventTriggger/CreateFunctionWithEventTriggger.ino similarity index 95% rename from examples/Cloud_Functions/Create_Function/Create_Function_with_Event_Triggger/Create_Function_with_Event_Triggger.ino rename to examples/CloudFunctions/CreateFunction/CreateFunctionWithEventTriggger/CreateFunctionWithEventTriggger.ino index 2cb65341d..3ec10f8cb 100644 --- a/examples/Cloud_Functions/Create_Function/Create_Function_with_Event_Triggger/Create_Function_with_Event_Triggger.ino +++ b/examples/CloudFunctions/CreateFunction/CreateFunctionWithEventTriggger/CreateFunctionWithEventTriggger.ino @@ -125,6 +125,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -137,12 +139,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -189,7 +187,6 @@ void creatFunction() function_config.setIamPolicy(&policy); - Serial.println("------------------------------------"); Serial.println("Create the Googgle Cloud Function..."); Firebase.Functions.createFunction(&fbdo, &function_config /* FunctionsConfig */, functionCreationCallback /* the callback function */); diff --git a/examples/Cloud_Functions/Create_Function/Create_Function_with_Event_Triggger/data/firestoreImageDownloadTrigger.zip b/examples/CloudFunctions/CreateFunction/CreateFunctionWithEventTriggger/data/firestoreImageDownloadTrigger.zip similarity index 100% rename from examples/Cloud_Functions/Create_Function/Create_Function_with_Event_Triggger/data/firestoreImageDownloadTrigger.zip rename to examples/CloudFunctions/CreateFunction/CreateFunctionWithEventTriggger/data/firestoreImageDownloadTrigger.zip diff --git a/examples/Cloud_Functions/Create_Function/Create_Function_with_Event_Triggger/example.png b/examples/CloudFunctions/CreateFunction/CreateFunctionWithEventTriggger/example.png similarity index 100% rename from examples/Cloud_Functions/Create_Function/Create_Function_with_Event_Triggger/example.png rename to examples/CloudFunctions/CreateFunction/CreateFunctionWithEventTriggger/example.png diff --git a/examples/Cloud_Functions/Create_Function/Create_Function_with_Return_Status/Create_Function_with_Return_Status.ino b/examples/CloudFunctions/CreateFunction/CreateFunctionWithReturnStatus/CreateFunctionWithReturnStatus.ino similarity index 95% rename from examples/Cloud_Functions/Create_Function/Create_Function_with_Return_Status/Create_Function_with_Return_Status.ino rename to examples/CloudFunctions/CreateFunction/CreateFunctionWithReturnStatus/CreateFunctionWithReturnStatus.ino index 183e2dfc7..3afc4824d 100644 --- a/examples/Cloud_Functions/Create_Function/Create_Function_with_Return_Status/Create_Function_with_Return_Status.ino +++ b/examples/CloudFunctions/CreateFunction/CreateFunctionWithReturnStatus/CreateFunctionWithReturnStatus.ino @@ -120,6 +120,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -132,12 +134,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -193,7 +191,6 @@ void creatFunction() function_config.setIamPolicy(&policy); - Serial.println("------------------------------------"); Serial.println("Create the Googgle Cloud Function..."); Firebase.Functions.createFunction(&fbdo, &function_config /* FunctionsConfig */, &statusInfo /* FunctionsOperationStatusInfo data to read the operation status */); diff --git a/examples/Cloud_Functions/Create_Function/Create_Function_with_Return_Status/data/helloWorld.zip b/examples/CloudFunctions/CreateFunction/CreateFunctionWithReturnStatus/data/helloWorld.zip similarity index 100% rename from examples/Cloud_Functions/Create_Function/Create_Function_with_Return_Status/data/helloWorld.zip rename to examples/CloudFunctions/CreateFunction/CreateFunctionWithReturnStatus/data/helloWorld.zip diff --git a/examples/Cloud_Functions/Create_Function/Deploy_AutoZip_Function/AutoZIP.h b/examples/CloudFunctions/CreateFunction/DeployAutoZipFunction/AutoZIP.h similarity index 100% rename from examples/Cloud_Functions/Create_Function/Deploy_AutoZip_Function/AutoZIP.h rename to examples/CloudFunctions/CreateFunction/DeployAutoZipFunction/AutoZIP.h diff --git a/examples/Cloud_Functions/Create_Function/Deploy_AutoZip_Function/Deploy_AutoZip_Function.ino b/examples/CloudFunctions/CreateFunction/DeployAutoZipFunction/DeployAutoZipFunction.ino similarity index 95% rename from examples/Cloud_Functions/Create_Function/Deploy_AutoZip_Function/Deploy_AutoZip_Function.ino rename to examples/CloudFunctions/CreateFunction/DeployAutoZipFunction/DeployAutoZipFunction.ino index 4e0093b3a..22be00715 100644 --- a/examples/Cloud_Functions/Create_Function/Deploy_AutoZip_Function/Deploy_AutoZip_Function.ino +++ b/examples/CloudFunctions/CreateFunction/DeployAutoZipFunction/DeployAutoZipFunction.ino @@ -116,6 +116,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -128,12 +130,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() diff --git a/examples/Cloud_Functions/Delete_Function/Delete_Function.ino b/examples/CloudFunctions/DeleteFunction/DeleteFunction.ino similarity index 81% rename from examples/Cloud_Functions/Delete_Function/Delete_Function.ino rename to examples/CloudFunctions/DeleteFunction/DeleteFunction.ino index a0141ebed..f3123a98c 100644 --- a/examples/Cloud_Functions/Delete_Function/Delete_Function.ino +++ b/examples/CloudFunctions/DeleteFunction/DeleteFunction.ino @@ -91,6 +91,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -103,12 +105,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -124,21 +122,10 @@ void deleteFunction() { //Assumed that the function named helloWorld is already created and deployed for project. - Serial.println("------------------------------------"); - Serial.println("Delete the Googgle Cloud Function..."); + Serial.print("Delete the Googgle Cloud Function... "); if (Firebase.Functions.deleteFunction(&fbdo, FIREBASE_PROJECT_ID /* project id */, PROJECT_LOCATION /* project location */, "helloWorld" /* function name */)) - { - Serial.println("PASSED"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } diff --git a/examples/Cloud_Functions/Download_Function/Download_Function.ino b/examples/CloudFunctions/DownloadFunction/DownloadFunction.ino similarity index 81% rename from examples/Cloud_Functions/Download_Function/Download_Function.ino rename to examples/CloudFunctions/DownloadFunction/DownloadFunction.ino index 6495b8133..980fa9cb0 100644 --- a/examples/Cloud_Functions/Download_Function/Download_Function.ino +++ b/examples/CloudFunctions/DownloadFunction/DownloadFunction.ino @@ -91,6 +91,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -103,12 +105,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -124,21 +122,10 @@ void generateUrl() { //Assumed that the function named helloWorld is already created and deployed for project. - Serial.println("------------------------------------"); - Serial.println("Generate the download Url of the Googgle Cloud Function..."); + Serial.print("Generate the download Url of the Googgle Cloud Function... "); if (Firebase.Functions.generateDownloadUrl(&fbdo, FIREBASE_PROJECT_ID /* project id */, PROJECT_LOCATION /* project location */, "helloWorld" /* function name */, "1" /* version id */)) - { - Serial.println("PASSED"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } diff --git a/examples/Cloud_Functions/IAM_Policy/Create_Policy/Create_Policy.ino b/examples/CloudFunctions/IAMPolicy/CreatePolicy/CreatePolicy.ino similarity index 94% rename from examples/Cloud_Functions/IAM_Policy/Create_Policy/Create_Policy.ino rename to examples/CloudFunctions/IAMPolicy/CreatePolicy/CreatePolicy.ino index 6040a9e63..c3f565bd8 100644 --- a/examples/Cloud_Functions/IAM_Policy/Create_Policy/Create_Policy.ino +++ b/examples/CloudFunctions/IAMPolicy/CreatePolicy/CreatePolicy.ino @@ -39,6 +39,8 @@ void setup() Serial.begin(115200); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + Firebase.begin(&config, &auth); //This will create the policy JSON object as in this document diff --git a/examples/Cloud_Functions/IAM_Policy/Get_Policy/Get_Policy.ino b/examples/CloudFunctions/IAMPolicy/GetPolicy/GetPolicy.ino similarity index 81% rename from examples/Cloud_Functions/IAM_Policy/Get_Policy/Get_Policy.ino rename to examples/CloudFunctions/IAMPolicy/GetPolicy/GetPolicy.ino index 3b7fd00f2..47d25ca98 100644 --- a/examples/Cloud_Functions/IAM_Policy/Get_Policy/Get_Policy.ino +++ b/examples/CloudFunctions/IAMPolicy/GetPolicy/GetPolicy.ino @@ -89,6 +89,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -101,12 +103,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + Firebase.reconnectWiFi(true); } void loop() @@ -123,21 +121,10 @@ void getPolicy() { //Assumed that the function named helloWorld is already created and deployed for the project. - Serial.println("------------------------------------"); - Serial.println("Get the IAM Policy of Googgle Cloud Function..."); + Serial.print("Get the IAM Policy of Googgle Cloud Function... "); if (Firebase.Functions.getIamPolicy(&fbdo, FIREBASE_PROJECT_ID /* project id */, PROJECT_LOCATION /* project location */, "helloWorld" /* function name */)) - { - Serial.println("PASSED"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } diff --git a/examples/Cloud_Functions/IAM_Policy/Set_Policy/Set_Policy.ino b/examples/CloudFunctions/IAMPolicy/SetPolicy/SetPolicy.ino similarity index 83% rename from examples/Cloud_Functions/IAM_Policy/Set_Policy/Set_Policy.ino rename to examples/CloudFunctions/IAMPolicy/SetPolicy/SetPolicy.ino index 39675eedf..5352d6258 100644 --- a/examples/Cloud_Functions/IAM_Policy/Set_Policy/Set_Policy.ino +++ b/examples/CloudFunctions/IAMPolicy/SetPolicy/SetPolicy.ino @@ -94,6 +94,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -106,12 +108,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -135,21 +133,10 @@ void setPolicy() binding.addMember("allUsers"); policy.addBinding(&binding); - Serial.println("------------------------------------"); - Serial.println("Set the IAM Policy for Googgle Cloud Function..."); + Serial.print("Set the IAM Policy for Googgle Cloud Function... "); if (Firebase.Functions.setIamPolicy(&fbdo, FIREBASE_PROJECT_ID /* project id */, PROJECT_LOCATION /* project location */, "helloWorld" /* function name */, &policy /* IAM Policy */)) - { - Serial.println("PASSED"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } diff --git a/examples/Cloud_Functions/List_Functions/List_Functions.ino b/examples/CloudFunctions/ListFunctions/ListFunctions.ino similarity index 81% rename from examples/Cloud_Functions/List_Functions/List_Functions.ino rename to examples/CloudFunctions/ListFunctions/ListFunctions.ino index 51ea46da2..e149e45ad 100644 --- a/examples/Cloud_Functions/List_Functions/List_Functions.ino +++ b/examples/CloudFunctions/ListFunctions/ListFunctions.ino @@ -91,6 +91,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -103,12 +105,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -123,21 +121,10 @@ void loop() void listFunctions() { - Serial.println("------------------------------------"); - Serial.println("List the Googgle Cloud Functions..."); + Serial.print("List the Googgle Cloud Functions... "); if (Firebase.Functions.listFunctions(&fbdo, FIREBASE_PROJECT_ID /* project id */, PROJECT_LOCATION /* project location */, 1 /* page size */)) - { - Serial.println("PASSED"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } diff --git a/examples/Cloud_Functions/Patch_Function/Patch_Function.ino b/examples/CloudFunctions/PatchFunction/PatchFunction.ino similarity index 80% rename from examples/Cloud_Functions/Patch_Function/Patch_Function.ino rename to examples/CloudFunctions/PatchFunction/PatchFunction.ino index 085959b23..bdd437b67 100644 --- a/examples/Cloud_Functions/Patch_Function/Patch_Function.ino +++ b/examples/CloudFunctions/PatchFunction/PatchFunction.ino @@ -94,6 +94,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -106,12 +108,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -127,9 +125,6 @@ void patchFunction() { //Assumed that the function named helloWorld is already created and deployed for project. - Serial.println("------------------------------------"); - Serial.println("Update the Googgle Cloud Function..."); - FunctionsConfig patch(FIREBASE_PROJECT_ID, PROJECT_LOCATION, STORAGE_BUCKET_ID); patch.setDescription("The new description"); @@ -139,22 +134,10 @@ void patchFunction() patch.setAvailableMemoryMb(128); patch.setMaxInstances(5); - - Serial.println("------------------------------------"); - Serial.println("Update the Googgle Cloud Function..."); + Serial.print("Update the Cloud Function... "); if (Firebase.Functions.patchFunction(&fbdo, "helloWorld" /* function id */, &patch /* FunctionsConfig to patch */)) - { - Serial.println("PASSED"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } diff --git a/examples/Firestore/Commit_Document/Append_Array/Append_Array.ino b/examples/Firestore/CommitDocument/AppendArray/AppendArray.ino similarity index 82% rename from examples/Firestore/Commit_Document/Append_Array/Append_Array.ino rename to examples/Firestore/CommitDocument/AppendArray/AppendArray.ino index ec11192f2..38d29df71 100644 --- a/examples/Firestore/Commit_Document/Append_Array/Append_Array.ino +++ b/examples/Firestore/CommitDocument/AppendArray/AppendArray.ino @@ -62,6 +62,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -73,12 +75,9 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -89,8 +88,7 @@ void loop() dataMillis = millis(); count++; - Serial.println("------------------------------------"); - Serial.println("Commit a document (append array)..."); + Serial.print("Commit a document (append array)... "); //The dyamic array of write object fb_esp_firestore_document_write_t. std::vector writes; @@ -141,19 +139,8 @@ void loop() writes.push_back(transform_write); if (Firebase.Firestore.commitDocument(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, writes /* dynamic array of fb_esp_firestore_document_write_t */, "" /* transaction */)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Firestore/Commit_Document/Set_Update_Delete/Set_Update_Delete.ino b/examples/Firestore/CommitDocument/SetUpdateDelete/SetUpdateDelete.ino similarity index 87% rename from examples/Firestore/Commit_Document/Set_Update_Delete/Set_Update_Delete.ino rename to examples/Firestore/CommitDocument/SetUpdateDelete/SetUpdateDelete.ino index 6625db499..d1aae9b70 100644 --- a/examples/Firestore/Commit_Document/Set_Update_Delete/Set_Update_Delete.ino +++ b/examples/Firestore/CommitDocument/SetUpdateDelete/SetUpdateDelete.ino @@ -62,6 +62,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -73,12 +75,9 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -89,8 +88,7 @@ void loop() dataMillis = millis(); count++; - Serial.println("------------------------------------"); - Serial.println("Commit a document (set server value, update document)..."); + Serial.print("Commit a document (set server value, update document)... "); //The dyamic array of write object fb_esp_firestore_document_write_t. std::vector writes; @@ -210,19 +208,8 @@ void loop() */ if (Firebase.Firestore.commitDocument(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, writes /* dynamic array of fb_esp_firestore_document_write_t */, "" /* transaction */)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Firestore/Create_Documents/Create_Documents.ino b/examples/Firestore/CreateDocuments/CreateDocuments.ino similarity index 75% rename from examples/Firestore/Create_Documents/Create_Documents.ino rename to examples/Firestore/CreateDocuments/CreateDocuments.ino index 0fbad68e4..f0cbae8f4 100644 --- a/examples/Firestore/Create_Documents/Create_Documents.ino +++ b/examples/Firestore/CreateDocuments/CreateDocuments.ino @@ -62,6 +62,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -73,12 +75,9 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -103,23 +102,11 @@ void loop() count++; - Serial.println("------------------------------------"); - Serial.println("Create a document..."); + Serial.print("Create a document... "); if (Firebase.Firestore.createDocument(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, documentPath.c_str(), content.c_str())) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Firestore/Data_Query/Data_Query.ino b/examples/Firestore/DataQuery/DataQuery.ino similarity index 78% rename from examples/Firestore/Data_Query/Data_Query.ino rename to examples/Firestore/DataQuery/DataQuery.ino index 5ceb062a6..9a33c090d 100644 --- a/examples/Firestore/Data_Query/Data_Query.ino +++ b/examples/Firestore/DataQuery/DataQuery.ino @@ -62,6 +62,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the project host and api key (required) */ config.api_key = API_KEY; @@ -73,12 +75,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -88,8 +86,7 @@ void loop() { dataMillis = millis(); - Serial.println("------------------------------------"); - Serial.println("Query a Firestore database..."); + Serial.print("Query a Firestore database... "); //If you have run the Create_Documents example, the document b0 (in collection a0) contains the document collection c0, and //c0 contains the collections d?. @@ -114,19 +111,8 @@ void loop() //https://github.com/mobizt/Firebase-ESP-Client/tree/main/src#runs-a-query if (Firebase.Firestore.runQuery(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, "a0/b0" /* The document path */, &query /* The FirebaseJson object holds the StructuredQuery data */)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Firestore/Delete_Document/Delete_Document.ino b/examples/Firestore/DeleteDocument/DeleteDocument.ino similarity index 64% rename from examples/Firestore/Delete_Document/Delete_Document.ino rename to examples/Firestore/DeleteDocument/DeleteDocument.ino index 2a81d3781..83a79429c 100644 --- a/examples/Firestore/Delete_Document/Delete_Document.ino +++ b/examples/Firestore/DeleteDocument/DeleteDocument.ino @@ -62,6 +62,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -73,15 +75,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - - } void loop() @@ -101,40 +96,18 @@ void loop() js.set("fields/v2/doubleValue", 123.456); js.toString(content); - Serial.println("------------------------------------"); - Serial.println("Create a document..."); + Serial.print("Create a document... "); if (Firebase.Firestore.createDocument(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, documentPath.c_str(), content.c_str())) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println("Delete a document..."); + Serial.print("Delete a document... "); if (Firebase.Firestore.deleteDocument(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, documentPath.c_str())) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Firestore/Export_Documents/Export_Documents.ino b/examples/Firestore/ExportDocuments/ExportDocuments.ino similarity index 75% rename from examples/Firestore/Export_Documents/Export_Documents.ino rename to examples/Firestore/ExportDocuments/ExportDocuments.ino index 0b897c010..306f0f279 100644 --- a/examples/Firestore/Export_Documents/Export_Documents.ino +++ b/examples/Firestore/ExportDocuments/ExportDocuments.ino @@ -70,6 +70,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the user sign in credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -79,14 +81,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - } void loop() @@ -95,23 +91,11 @@ void loop() { taskCompleted = true; - Serial.println("------------------------------------"); - Serial.println("Export documents to the Storage bucket..."); + Serial.print("Export documents to the Storage bucket... "); if (Firebase.Firestore.exportDocuments(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, STORAGE_BUCKET_ID, "test_path" /* The path in the Firebase Storage bucket to store the data */, "" /* Which collection ids to export. Unspecified means all collections. */)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Firestore/Get_Document/Get_Document.ino b/examples/Firestore/GetDocument/GetDocument.ino similarity index 67% rename from examples/Firestore/Get_Document/Get_Document.ino rename to examples/Firestore/GetDocument/GetDocument.ino index f6613fb86..bfd4c38aa 100644 --- a/examples/Firestore/Get_Document/Get_Document.ino +++ b/examples/Firestore/GetDocument/GetDocument.ino @@ -63,6 +63,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -74,14 +76,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - + Firebase.reconnectWiFi(true); } void loop() @@ -112,47 +108,23 @@ void loop() //info is the collection id, countries is the document id in collection info. String documentPath = "info/countries"; - Serial.println("------------------------------------"); - Serial.println("Create document..."); + Serial.print("Create document... "); if (Firebase.Firestore.createDocument(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, documentPath.c_str(), content.c_str())) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } String documentPath = "info/countries"; String mask = "Singapore"; - Serial.println("------------------------------------"); - Serial.println("Get a document..."); + Serial.print("Get a document... "); if (Firebase.Firestore.getDocument(&fbdo, FIREBASE_PROJECT_ID, "", documentPath.c_str(), mask.c_str())) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Firestore/Import_Documents/Import_Documents.ino b/examples/Firestore/ImportDocuments/ImportDocuments.ino similarity index 76% rename from examples/Firestore/Import_Documents/Import_Documents.ino rename to examples/Firestore/ImportDocuments/ImportDocuments.ino index 496bbc9c7..735c1fd6a 100644 --- a/examples/Firestore/Import_Documents/Import_Documents.ino +++ b/examples/Firestore/ImportDocuments/ImportDocuments.ino @@ -70,6 +70,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the user sign in credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -79,14 +81,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - } void loop() @@ -96,23 +92,11 @@ void loop() taskCompleted = true; //Should run the Export_Documents.ino prior to test this example to export the database to the Storage bucket at test_path folder - Serial.println("------------------------------------"); - Serial.println("Import documents from the Storage bucket..."); + Serial.print("Import documents from the Storage bucket... "); if (Firebase.Firestore.importDocuments(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, STORAGE_BUCKET_ID, "test_path" /* The path in the Firebase Storage bucket to store the data */, "" /* Which collection ids to import. Unspecified means all collections. */)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Firestore/List_CollectionIds/List_CollectionIds.ino b/examples/Firestore/ListCollectionIds/ListCollectionIds.ino similarity index 75% rename from examples/Firestore/List_CollectionIds/List_CollectionIds.ino rename to examples/Firestore/ListCollectionIds/ListCollectionIds.ino index 48cd73d74..56e9cfc71 100644 --- a/examples/Firestore/List_CollectionIds/List_CollectionIds.ino +++ b/examples/Firestore/ListCollectionIds/ListCollectionIds.ino @@ -68,6 +68,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the user sign in credentials */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -77,14 +79,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - } void loop() @@ -97,23 +93,11 @@ void loop() //root collection String documentPath = "/"; - Serial.println("------------------------------------"); - Serial.println("List CollectionIds in a document..."); + Serial.print("List CollectionIds in a document... "); if (Firebase.Firestore.listCollectionIds(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, documentPath.c_str(), 3 /* The maximum number of documents to return */, "" /* The nextPageToken value returned from a previous List request, if any. */)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Firestore/List_Documents/List_Documents.ino b/examples/Firestore/ListDocuments/ListDocuments.ino similarity index 71% rename from examples/Firestore/List_Documents/List_Documents.ino rename to examples/Firestore/ListDocuments/ListDocuments.ino index d5b16319d..3920b8aa6 100644 --- a/examples/Firestore/List_Documents/List_Documents.ino +++ b/examples/Firestore/ListDocuments/ListDocuments.ino @@ -61,6 +61,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -72,13 +74,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - } void loop() @@ -92,25 +89,11 @@ void loop() //a0 is the collection id, b0 is the document id in collection a0 and c0 is the collection id id in the document b0. String collectionId = "a0/b0/c0"; - Serial.println("------------------------------------"); - Serial.println("List the documents in a collection..."); + Serial.print("List the documents in a collection... "); if (Firebase.Firestore.listDocuments(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, collectionId.c_str(), 3 /* The maximum number of documents to return */, "" /* The nextPageToken value returned from a previous List request, if any. */, "" /* The order to sort results by. For example: priority desc, name. */, "count" /* the field name to mask */, false /* showMissing, iIf the list should show missing documents. A missing document is a document that does not exist but has sub-documents. */)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - //if the showMissing parameter of listDocuments is true, and the error shows "Missing or insufficient permissions." - //The OAuth2.0 authentication is required to perform this operation. - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Firestore/Patch_Document/Patch_Document.ino b/examples/Firestore/PatchDocument/PatchDocument.ino similarity index 67% rename from examples/Firestore/Patch_Document/Patch_Document.ino rename to examples/Firestore/PatchDocument/PatchDocument.ino index 286dbfa73..cc95a8bc6 100644 --- a/examples/Firestore/Patch_Document/Patch_Document.ino +++ b/examples/Firestore/PatchDocument/PatchDocument.ino @@ -64,6 +64,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -75,12 +77,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -104,24 +102,12 @@ void loop() js.set("fields/status/booleanValue", count % 2 == 0); js.toString(content); - Serial.println("------------------------------------"); - Serial.println("Create a document..."); + Serial.print("Create a document... "); if (Firebase.Firestore.createDocument(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, documentPath.c_str(), content.c_str())) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } String content; @@ -135,27 +121,15 @@ void loop() js.set("fields/status/booleanValue", count % 2 == 0); js.toString(content); - Serial.println("------------------------------------"); - Serial.println("Update a document..."); + Serial.print("Update a document... "); /** if updateMask contains the field name that exists in the remote document and * this field name does not exist in the document (content), that field will be delete from remote document */ if (Firebase.Firestore.patchDocument(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, documentPath.c_str(), content.c_str(), "count,status" /* updateMask */)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(fbdo.payload()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", fbdo.payload().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Messaging/App_Instance_Info/App_Instance_Info.ino b/examples/Messaging/AppInstanceInfo/AppInstanceInfo.ino similarity index 63% rename from examples/Messaging/App_Instance_Info/App_Instance_Info.ino rename to examples/Messaging/AppInstanceInfo/AppInstanceInfo.ino index 1dee74efd..b5b00c811 100644 --- a/examples/Messaging/App_Instance_Info/App_Instance_Info.ino +++ b/examples/Messaging/AppInstanceInfo/AppInstanceInfo.ino @@ -59,37 +59,19 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + Firebase.FCM.setServerKey(FIREBASE_FCM_SERVER_KEY); Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - Serial.println("------------------------------------"); - Serial.println("Get the app instance info..."); + Serial.print("Get the app instance info... "); //The subscribed topic also included in the info if (Firebase.FCM.appInstanceInfo(&fbdo, DEVICE_REGISTRATION_ID_TOKEN)) - { - - Serial.println("PASSED"); - Serial.println(Firebase.FCM.payload(&fbdo)); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", Firebase.FCM.payload(&fbdo).c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } void loop() diff --git a/examples/Messaging/Regist_APNs_Tokens/Regist_APNs_Tokens.ino b/examples/Messaging/RegistAPNsTokens/RegistAPNsTokens.ino similarity index 66% rename from examples/Messaging/Regist_APNs_Tokens/Regist_APNs_Tokens.ino rename to examples/Messaging/RegistAPNsTokens/RegistAPNsTokens.ino index d1518826d..5ec5f4be3 100644 --- a/examples/Messaging/Regist_APNs_Tokens/Regist_APNs_Tokens.ino +++ b/examples/Messaging/RegistAPNsTokens/RegistAPNsTokens.ino @@ -60,20 +60,13 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + Firebase.FCM.setServerKey(FIREBASE_FCM_SERVER_KEY); Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - Serial.println("------------------------------------"); - Serial.println("Subscribe the topic..."); + Serial.print("Subscribe the topic... "); int numToken = 2; const char *APNs[2]; @@ -81,20 +74,9 @@ void setup() APNs[1] = APN_TOKEN_1; if (Firebase.FCM.regisAPNsTokens(&fbdo, "com.google.FCMTestApp" /* Bundle id of the app */, false /* sandbox */, APNs /* array of APNs tokens */, numToken)) - { - - Serial.println("PASSED"); - Serial.println(Firebase.FCM.payload(&fbdo)); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", Firebase.FCM.payload(&fbdo).c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } void loop() diff --git a/examples/Messaging/Send/HTTPv1/Send_Message/Send_Message.ino b/examples/Messaging/Send/HTTPv1/SendMessage/SendMessage.ino similarity index 77% rename from examples/Messaging/Send/HTTPv1/Send_Message/Send_Message.ino rename to examples/Messaging/Send/HTTPv1/SendMessage/SendMessage.ino index 135b772a4..714ebdabd 100644 --- a/examples/Messaging/Send/HTTPv1/Send_Message/Send_Message.ino +++ b/examples/Messaging/Send/HTTPv1/SendMessage/SendMessage.ino @@ -72,6 +72,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the sevice account credentials and private key (required) */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -83,16 +85,6 @@ void setup() Firebase.begin(&config, &auth); Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - } void loop() @@ -109,8 +101,7 @@ void loop() void sendMessage() { - Serial.println("------------------------------------"); - Serial.println("Send Firebase Cloud Messaging..."); + Serial.print("Send Firebase Cloud Messaging... "); //Read more details about HTTP v1 API here https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages FCM_HTTPv1_JSON_Message msg; @@ -131,20 +122,9 @@ void sendMessage() msg.data = payload.c_str(); if (Firebase.FCM.send(&fbdo, &msg)) //send message to recipient - { - - Serial.println("PASSED"); - Serial.println(Firebase.FCM.payload(&fbdo)); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", Firebase.FCM.payload(&fbdo).c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); count++; } diff --git a/examples/Messaging/Send/HTTPv1/Send_Topic/Send_Topic.ino b/examples/Messaging/Send/HTTPv1/SendTopic/SendTopic.ino similarity index 77% rename from examples/Messaging/Send/HTTPv1/Send_Topic/Send_Topic.ino rename to examples/Messaging/Send/HTTPv1/SendTopic/SendTopic.ino index 64b932bfc..87099ea12 100644 --- a/examples/Messaging/Send/HTTPv1/Send_Topic/Send_Topic.ino +++ b/examples/Messaging/Send/HTTPv1/SendTopic/SendTopic.ino @@ -72,6 +72,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the sevice account credentials and private key (required) */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -83,15 +85,6 @@ void setup() Firebase.begin(&config, &auth); Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - } void loop() @@ -107,8 +100,7 @@ void loop() void sendMessage() { - Serial.println("------------------------------------"); - Serial.println("Send Firebase Cloud Messaging..."); + Serial.print("Send Firebase Cloud Messaging... "); //Read more details about HTTP v1 API here https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages FCM_HTTPv1_JSON_Message msg; @@ -128,20 +120,9 @@ void sendMessage() msg.data = payload.c_str(); if (Firebase.FCM.send(&fbdo, &msg)) //send message to recipient - { - - Serial.println("PASSED"); - Serial.println(Firebase.FCM.payload(&fbdo)); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", Firebase.FCM.payload(&fbdo).c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); count++; } diff --git a/examples/Messaging/Send/Legacy_API/Broadcast_Message/Broadcast_Message.ino b/examples/Messaging/Send/LegacyAPI/BroadcastMessage/BroadcastMessage.ino similarity index 75% rename from examples/Messaging/Send/Legacy_API/Broadcast_Message/Broadcast_Message.ino rename to examples/Messaging/Send/LegacyAPI/BroadcastMessage/BroadcastMessage.ino index 62ec7c2fc..52b4be5a8 100644 --- a/examples/Messaging/Send/Legacy_API/Broadcast_Message/Broadcast_Message.ino +++ b/examples/Messaging/Send/LegacyAPI/BroadcastMessage/BroadcastMessage.ino @@ -61,19 +61,13 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + //required for legacy HTTP API Firebase.FCM.setServerKey(FIREBASE_FCM_SERVER_KEY); Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - sendMessage(); } @@ -91,8 +85,7 @@ void loop() void sendMessage() { - Serial.println("------------------------------------"); - Serial.println("Send Firebase Cloud Messaging..."); + Serial.print("Send Firebase Cloud Messaging... "); //Read more details about legacy HTTP API here https://firebase.google.com/docs/cloud-messaging/http-server-ref FCM_Legacy_HTTP_Message msg; @@ -125,20 +118,9 @@ void sendMessage() msg.payloads.data = payload.c_str(); if (Firebase.FCM.send(&fbdo, &msg)) //send message to recipient - { - - Serial.println("PASSED"); - Serial.println(Firebase.FCM.payload(&fbdo)); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", Firebase.FCM.payload(&fbdo).c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); count++; } diff --git a/examples/Messaging/Send/Legacy_API/Send_Message/Send_Message.ino b/examples/Messaging/Send/LegacyAPI/SendMessage/SendMessage.ino similarity index 73% rename from examples/Messaging/Send/Legacy_API/Send_Message/Send_Message.ino rename to examples/Messaging/Send/LegacyAPI/SendMessage/SendMessage.ino index aed553a33..eb8d4e338 100644 --- a/examples/Messaging/Send/Legacy_API/Send_Message/Send_Message.ino +++ b/examples/Messaging/Send/LegacyAPI/SendMessage/SendMessage.ino @@ -59,19 +59,13 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + //required for legacy HTTP API Firebase.FCM.setServerKey(FIREBASE_FCM_SERVER_KEY); Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - sendMessage(); } @@ -89,8 +83,7 @@ void loop() void sendMessage() { - Serial.println("------------------------------------"); - Serial.println("Send Firebase Cloud Messaging..."); + Serial.print("Send Firebase Cloud Messaging... "); //Read more details about legacy HTTP API here https://firebase.google.com/docs/cloud-messaging/http-server-ref FCM_Legacy_HTTP_Message msg; @@ -116,20 +109,9 @@ void sendMessage() msg.payloads.data = payload.c_str(); if (Firebase.FCM.send(&fbdo, &msg)) //send message to recipient - { - - Serial.println("PASSED"); - Serial.println(Firebase.FCM.payload(&fbdo)); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", Firebase.FCM.payload(&fbdo).c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); count++; } diff --git a/examples/Messaging/Send/Legacy_API/Send_Topic/Send_Topic.ino b/examples/Messaging/Send/LegacyAPI/SendTopic/SendTopic.ino similarity index 72% rename from examples/Messaging/Send/Legacy_API/Send_Topic/Send_Topic.ino rename to examples/Messaging/Send/LegacyAPI/SendTopic/SendTopic.ino index fddca9967..66555395f 100644 --- a/examples/Messaging/Send/Legacy_API/Send_Topic/Send_Topic.ino +++ b/examples/Messaging/Send/LegacyAPI/SendTopic/SendTopic.ino @@ -56,19 +56,13 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + //required for legacy HTTP API Firebase.FCM.setServerKey(FIREBASE_FCM_SERVER_KEY); Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - sendMessage(); } @@ -86,8 +80,7 @@ void loop() void sendMessage() { - Serial.println("------------------------------------"); - Serial.println("Send Firebase Cloud Messaging..."); + Serial.print("Send Firebase Cloud Messaging... "); //Read more details about legacy HTTP API here https://firebase.google.com/docs/cloud-messaging/http-server-ref FCM_Legacy_HTTP_Message msg; @@ -113,20 +106,9 @@ void sendMessage() msg.payloads.data = payload.c_str(); if (Firebase.FCM.send(&fbdo, &msg)) //send message to recipient - { - - Serial.println("PASSED"); - Serial.println(Firebase.FCM.payload(&fbdo)); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", Firebase.FCM.payload(&fbdo).c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); count++; } diff --git a/examples/Messaging/Subscribe_Topic/Subscribe_Topic.ino b/examples/Messaging/SubscribeTopic/SubscribeTopic.ino similarity index 66% rename from examples/Messaging/Subscribe_Topic/Subscribe_Topic.ino rename to examples/Messaging/SubscribeTopic/SubscribeTopic.ino index be3b3f583..448a3d73b 100644 --- a/examples/Messaging/Subscribe_Topic/Subscribe_Topic.ino +++ b/examples/Messaging/SubscribeTopic/SubscribeTopic.ino @@ -60,20 +60,13 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + Firebase.FCM.setServerKey(FIREBASE_FCM_SERVER_KEY); Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - Serial.println("------------------------------------"); - Serial.println("Subscribe the topic..."); + Serial.print("Subscribe the topic... "); int numToken = 2; const char *iid[2]; @@ -81,20 +74,9 @@ void setup() iid[1] = DEVICE_REGISTRATION_ID_TOKEN_2; if (Firebase.FCM.subscibeTopic(&fbdo, "testTopic" /* topic to subscribe */, iid /* IID tokens array */, numToken)) - { - - Serial.println("PASSED"); - Serial.println(Firebase.FCM.payload(&fbdo)); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", Firebase.FCM.payload(&fbdo).c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } void loop() diff --git a/examples/Messaging/Unsubscribe_Topic/Unsubscribe_Topic.ino b/examples/Messaging/UnsubscribeTopic/UnsubscribeTopic.ino similarity index 67% rename from examples/Messaging/Unsubscribe_Topic/Unsubscribe_Topic.ino rename to examples/Messaging/UnsubscribeTopic/UnsubscribeTopic.ino index e74850cba..e62f17187 100644 --- a/examples/Messaging/Unsubscribe_Topic/Unsubscribe_Topic.ino +++ b/examples/Messaging/UnsubscribeTopic/UnsubscribeTopic.ino @@ -60,20 +60,13 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + Firebase.FCM.setServerKey(FIREBASE_FCM_SERVER_KEY); Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - Serial.println("------------------------------------"); - Serial.println("Unsubscribe the topic..."); + Serial.print("Unsubscribe the topic... "); int numToken = 2; const char *iid[2]; @@ -81,20 +74,9 @@ void setup() iid[1] = DEVICE_REGISTRATION_ID_TOKEN_2; if (Firebase.FCM.unsubscibeTopic(&fbdo, "testTopic" /* topic to subscribe */, iid /* IID tokens array */, numToken)) - { - - Serial.println("PASSED"); - Serial.println(Firebase.FCM.payload(&fbdo)); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("ok\n%s\n\n", Firebase.FCM.payload(&fbdo).c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } void loop() diff --git a/examples/RTDB/Backup_and_Restore_Flash_Memory/Backup_and_Restore_Flash_Memory.ino b/examples/RTDB/BackupRestore/Flash/Flash.ino similarity index 59% rename from examples/RTDB/Backup_and_Restore_Flash_Memory/Backup_and_Restore_Flash_Memory.ino rename to examples/RTDB/BackupRestore/Flash/Flash.ino index 4adf75849..59de28028 100644 --- a/examples/RTDB/Backup_and_Restore_Flash_Memory/Backup_and_Restore_Flash_Memory.ino +++ b/examples/RTDB/BackupRestore/Flash/Flash.ino @@ -59,6 +59,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -72,17 +74,13 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#ifdef ESP8266 - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); + Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); } void loop() @@ -91,49 +89,27 @@ void loop() { taskCompleted = true; - Serial.println("------------------------------------"); - Serial.println("Backup test..."); - //Download and save data to Flash memory. // is the full path of database to backup and restore. // is file name included path to save to Flash meory //The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. - if (!Firebase.RTDB.backup(&fbdo, mem_storage_type_flash, "/", "/")) - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - else + + Serial.printf("Backup... %s\n", Firebase.RTDB.backup(&fbdo, mem_storage_type_flash, "/", "/") ? "ok" : fbdo.fileTransferError().c_str()); + + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) { - Serial.println("PASSED"); - Serial.println("BACKUP FILE: " + fbdo.getBackupFilename()); - Serial.printf("FILE SIZE: %d\n", fbdo.getBackupFileSize()); - Serial.println("------------------------------------"); - Serial.println(); + Serial.printf("backup file, %s\n", fbdo.getBackupFilename().c_str()); + Serial.printf("file size, %d\n", fbdo.getBackupFileSize()); } - Serial.println("------------------------------------"); - Serial.println("Restore test..."); - //Restore data to defined database path using backup file on Flash memory. // is the full path of database to restore // is file name included path of backed up file. //The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. - if (!Firebase.RTDB.restore(&fbdo, mem_storage_type_flash, "/", "/")) - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("PASSED"); - Serial.println("BACKUP FILE: " + fbdo.getBackupFilename()); - Serial.println("------------------------------------"); - Serial.println(); - } + + Serial.printf("Restore... %s\n", Firebase.RTDB.restore(&fbdo, mem_storage_type_flash, "/", "/") ? "ok" : fbdo.fileTransferError().c_str()); + + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) + Serial.printf("backup file, %s\n", fbdo.getBackupFilename().c_str()); } } diff --git a/examples/RTDB/Backup_and_Restore/Backup_and_Restore.ino b/examples/RTDB/BackupRestore/SD/SD.ino similarity index 57% rename from examples/RTDB/Backup_and_Restore/Backup_and_Restore.ino rename to examples/RTDB/BackupRestore/SD/SD.ino index 656d23a23..9c1a7b9b4 100644 --- a/examples/RTDB/Backup_and_Restore/Backup_and_Restore.ino +++ b/examples/RTDB/BackupRestore/SD/SD.ino @@ -60,6 +60,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -73,17 +75,13 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#ifdef ESP8266 - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); + Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); } void loop() @@ -91,50 +89,27 @@ void loop() if (Firebase.ready() && !taskCompleted) { taskCompleted = true; - Serial.println("------------------------------------"); - Serial.println("Backup test..."); //Download and save data to SD card. // is the full path of database to backup and restore. // is file name in 8.3 DOS format (max. 8 bytes file name and 3 bytes file extension) - if (!Firebase.RTDB.backup(&fbdo, mem_storage_type_sd, "/", "/")) - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - else + Serial.printf("Backup... %s\n", Firebase.RTDB.backup(&fbdo, mem_storage_type_sd, "/", "/") ? "ok" : fbdo.fileTransferError().c_str()); + + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) { - Serial.println("PASSED"); - Serial.println("BACKUP FILE: " + fbdo.getBackupFilename()); - Serial.printf("FILE SIZE: %d\n", fbdo.getBackupFileSize()); - Serial.println("------------------------------------"); - Serial.println(); + Serial.printf("backup file, %s\n", fbdo.getBackupFilename().c_str()); + Serial.printf("file size, %d\n", fbdo.getBackupFileSize()); } - Serial.println("------------------------------------"); - Serial.println("Restore test..."); - - //Restore data to defined database path using backup file on SD card. + //Restore data to defined database path using backup file on Flash memory. // is the full path of database to restore - // is file name in 8.3 DOS format (max. 8 bytes file name and 3 bytes file extension) - + // is file name included path of backed up file. //The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. - if (!Firebase.RTDB.restore(&fbdo, mem_storage_type_sd, "/", "/")) - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("PASSED"); - Serial.println("BACKUP FILE: " + fbdo.getBackupFilename()); - Serial.println("------------------------------------"); - Serial.println(); - } + + Serial.printf("Restore... %s\n", Firebase.RTDB.restore(&fbdo, mem_storage_type_sd, "/", "/") ? "ok" : fbdo.fileTransferError().c_str()); + + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) + Serial.printf("backup file, %s\n", fbdo.getBackupFilename().c_str()); } } diff --git a/examples/RTDB/Backup_and_Send_Email/Backup_and_Send_Email.ino b/examples/RTDB/Backup_and_Send_Email/Backup_and_Send_Email.ino deleted file mode 100644 index b4f0c87c3..000000000 --- a/examples/RTDB/Backup_and_Send_Email/Backup_and_Send_Email.ino +++ /dev/null @@ -1,242 +0,0 @@ -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -//This example shows how to backup database and send the Email - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" - -/* - Required ESP Mail Client library for Arduino - https://github.com/mobizt/ESP-Mail-Client -*/ - -#include - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. Define the API Key */ -#define API_KEY "API_KEY" - -/* 3. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 4. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -/* 5. The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook */ -#define SMTP_HOST "################" - -/** 6. The smtp port e.g. - * 25 or esp_mail_smtp_port_25 - * 465 or esp_mail_smtp_port_465 - * 587 or esp_mail_smtp_port_587 -*/ -#define SMTP_PORT 25 - -/* 7. The sign in credentials */ -#define AUTHOR_EMAIL "################" -#define AUTHOR_PASSWORD "################" - -/* The SMTP Session object used for Email sending */ -SMTPSession smtp; - -//Define Firebase Data object -FirebaseData fbdo; - -FirebaseAuth auth; -FirebaseConfig config; - -bool taskCompleted = false; - -/* Callback function to get the Email sending status */ -void smtpCallback(SMTP_Status status); - -void setup() -{ - - Serial.begin(115200); - - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); - Serial.print("Connecting to Wi-Fi"); - while (WiFi.status() != WL_CONNECTED) - { - Serial.print("."); - delay(300); - } - Serial.println(); - Serial.print("Connected with IP: "); - Serial.println(WiFi.localIP()); - Serial.println(); - - /* Assign the api key (required) */ - config.api_key = API_KEY; - - /* Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - - Serial.println(); - -} - -void loop() -{ - if(Firebase.ready() && !taskCompleted) - { - taskCompleted - true; - - Serial.println("------------------------------------"); - Serial.println("Backup test..."); - - //The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. - if (!Firebase.RTDB.backup(&fbdo, mem_storage_type_flash, "/", "/")) - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("PASSED"); - Serial.println("SAVE PATH: " + fbdo.getBackupFilename()); - Serial.printf("FILE SIZE: %d\n", fbdo.getBackupFileSize()); - Serial.println("------------------------------------"); - Serial.println(); - - String filename = fbdo.getBackupFilename(); - - if (fbdo.pauseFirebase(true)) - { - - //Send backup file via Email - - smtp.debug(1); - - /* Set the callback function to get the sending results */ - smtp.callback(smtpCallback); - - /* Declare the session config data */ - ESP_Mail_Session session; - - /* Set the session config */ - session.server.host_name = SMTP_HOST; - session.server.port = SMTP_PORT; - session.login.email = AUTHOR_EMAIL; - session.login.password = AUTHOR_PASSWORD; - session.login.user_domain = "mydomain.net"; - - /* Declare the message class */ - SMTP_Message message; - - /* Set the message headers */ - message.sender.name = "ESP Mail"; - message.sender.email = AUTHOR_EMAIL; - message.subject = "Firebase Database Backup File"; - message.addRecipient("Someone", "yourmail@mail.com"); - - message.text.content = "Firebase Database Backup File\r\nSent from ESP device"; - - /** The Plain text message character set */ - message.text.charSet = "us-ascii"; - - /** The content transfer encoding */ - message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit; - - /** The message priority */ - message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low; - - /* The attachment data item */ - SMTP_Attachment att; - - /** Set the attachment info */ - att.descr.filename = filename.c_str(); - att.descr.mime = "application/octet-stream"; - String path = "/" + filename; - - att.file.path = path.c_str(); - att.file.storage_type = esp_mail_file_storage_type_flash; - att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64; - - /* Add attachment to the message */ - message.addAttachment(att); - - /* Connect to server with the session config */ - if (!smtp.connect(&session)) - return; - - /* Start sending Email and close the session */ - if (!MailClient.sendMail(&smtp, &message)) - Serial.println("Error sending Email, " + smtp.errorReason()); - - Serial.println(); - } - else - { - Serial.println("Could not pause Firebase"); - } - } - - //Quit Firebase and release all resources - Firebase.RTDB.end(&fbdo); - } -} - -/* Callback function to get the Email sending status */ -void smtpCallback(SMTP_Status status) -{ - /* Print the current status */ - Serial.println(status.info()); - - /* Print the sending result */ - if (status.success()) - { - Serial.println("----------------"); - Serial.printf("Message sent success: %d\n", status.completedCount()); - Serial.printf("Message sent failled: %d\n", status.failedCount()); - Serial.println("----------------\n"); - struct tm dt; - - for (size_t i = 0; i < smtp.sendingResult.size(); i++) - { - /* Get the result item */ - SMTP_Result result = smtp.sendingResult.getItem(i); - localtime_r(&result.timesstamp, &dt); - - Serial.printf("Message No: %d\n", i + 1); - Serial.printf("Status: %s\n", result.completed ? "success" : "failed"); - Serial.printf("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900, dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec); - Serial.printf("Recipient: %s\n", result.recipients); - Serial.printf("Subject: %s\n", result.subject); - } - Serial.println("----------------\n"); - } -} diff --git a/examples/RTDB/Basic/Basic.ino b/examples/RTDB/Basic/Basic.ino index c233386ac..17d29d4b8 100644 --- a/examples/RTDB/Basic/Basic.ino +++ b/examples/RTDB/Basic/Basic.ino @@ -42,9 +42,9 @@ FirebaseData fbdo; FirebaseAuth auth; FirebaseConfig config; -bool taskCompleted = false; +unsigned long sendDataPrevMillis = 0; -FirebaseJson json; +int count = 0; void setup() { @@ -63,6 +63,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -76,165 +78,33 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + Firebase.begin(&config, &auth); - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - //Set database read timeout to 1 minute (max 15 minutes) - Firebase.RTDB.setReadTimeout(&fbdo, 1000 * 60); - //tiny, small, medium, large and unlimited. - //Size and its write timeout e.g. tiny (1s), small (10s), medium (30s) and large (60s). - Firebase.RTDB.setwriteSizeLimit(&fbdo, "tiny"); - - //optional, set the decimal places for float and double data to be stored in database - Firebase.setFloatDigits(2); - Firebase.setDoubleDigits(6); - - /** - * This option allows get and delete functions (PUT and DELETE HTTP requests) works for device connected behind the - * Firewall that allows only GET and POST requests. - * - * Firebase.RTDB.enableClassicRequest(&fbdo, true); - */ + Firebase.reconnectWiFi(true); } void loop() { - if (Firebase.ready() && !taskCompleted) + if (Firebase.ready() && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)) { - taskCompleted = true; - - String path = "/Test"; - String node; - - Serial.println("------------------------------------"); - Serial.println("Set double test..."); - - for (uint8_t i = 0; i < 10; i++) - { - node = path + "/Double/Data" + String(i + 1); - //Also can use Firebase.set instead of Firebase.setDouble - if (Firebase.RTDB.setDouble(&fbdo, node.c_str(), ((i + 1) * 10) + 0.123456789)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - Serial.println("------------------------------------"); - Serial.println("Get double test..."); - - for (uint8_t i = 0; i < 10; i++) - { - node = path + "/Double/Data" + String(i + 1); - //Also can use Firebase.get instead of Firebase.setInt - if (Firebase.RTDB.getInt(&fbdo, node.c_str())) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.println("ETag: " + fbdo.ETag()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - Serial.println("------------------------------------"); - Serial.println("Push integer test..."); - - for (uint8_t i = 0; i < 5; i++) - { - node = path + "/Push/Int"; - //Also can use Firebase.push instead of Firebase.pushInt - if (Firebase.RTDB.pushInt(&fbdo, node.c_str(), (i + 1))) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - Serial.println("------------------------------------"); - Serial.println("Push JSON test..."); - - for (uint8_t i = 5; i < 10; i++) - { - - json.clear().add("Data" + String(i + 1), i + 1); - - node = path + "/Push/Int"; - - //Also can use Firebase.push instead of Firebase.pushJSON - //Json string is not support in v 2.6.0 and later, only FirebaseJson object is supported. - if (Firebase.RTDB.pushJSON(&fbdo, node.c_str(), &json)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - Serial.println("------------------------------------"); - Serial.println("Update test..."); - - for (uint8_t i = 0; i < 5; i++) - { - - json.set("Data" + String(i + 1), i + 5.5); - - node = path + "/float"; - - if (Firebase.RTDB.updateNode(&fbdo, node.c_str(), &json)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } + sendDataPrevMillis = millis(); + + Serial.printf("Set int... %s\n", Firebase.RTDB.setInt(&fbdo, "/test/int", count) ? "ok" : fbdo.errorReason().c_str()); + + Serial.printf("Get int... %s\n", Firebase.RTDB.getInt(&fbdo, "/test/int") ? String(fbdo.intData()).c_str() : fbdo.errorReason().c_str()); + + FirebaseJson json; + json.add("value", count); + + Serial.printf("Push json... %s\n", Firebase.RTDB.pushJSON(&fbdo, "/test/push", &json) ? "ok" : fbdo.errorReason().c_str()); + + json.set("value", count + 100); + Serial.printf("Update json... %s\n\n", Firebase.RTDB.updateNode(&fbdo, String("/test/push/" + fbdo.pushName()).c_str(), &json) ? "ok" : fbdo.errorReason().c_str()); + + count++; } } diff --git a/examples/RTDB/BasicCert/BasicCert.ino b/examples/RTDB/BasicCert/BasicCert.ino new file mode 100644 index 000000000..efa8f2953 --- /dev/null +++ b/examples/RTDB/BasicCert/BasicCert.ino @@ -0,0 +1,157 @@ + +/** + * Created by K. Suwatchai (Mobizt) + * + * Email: k_suwatchai@hotmail.com + * + * Github: https://github.com/mobizt + * + * Copyright (c) 2021 mobizt + * +*/ + +#if defined(ESP32) +#include +#elif defined(ESP8266) +#include +#endif +#include + +//Provide the token generation process info. +#include "addons/TokenHelper.h" +//Provide the RTDB payload printing info and other helper functions. +#include "addons/RTDBHelper.h" + +/* 1. Define the WiFi credentials */ +#define WIFI_SSID "WIFI_AP" +#define WIFI_PASSWORD "WIFI_PASSWORD" + +/* 2. Define the API Key */ +#define API_KEY "API_KEY" + +/* 3. Define the RTDB URL */ +#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app + +/* 4. Define the user Email and password that alreadey registerd or added in your project */ +#define USER_EMAIL "USER_EMAIL" +#define USER_PASSWORD "USER_PASSWORD" + +/* Google Root CA can be downloaded from https://pki.goog/repository/ */ +const char rootCACert[] PROGMEM = "-----BEGIN CERTIFICATE-----\n" + "MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4G\n" + "A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNp\n" + "Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1\n" + "MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEG\n" + "A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI\n" + "hvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPL\n" + "v4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8\n" + "eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklq\n" + "tTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd\n" + "C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pa\n" + "zq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCB\n" + "mTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IH\n" + "V2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5n\n" + "bG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG\n" + "3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs\n" + "J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO\n" + "291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavS\n" + "ot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd\n" + "AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7\n" + "TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg==\n" + "-----END CERTIFICATE-----\n"; + +//Define Firebase Data object +FirebaseData fbdo; + +FirebaseAuth auth; +FirebaseConfig config; + +unsigned long sendDataPrevMillis = 0; + +int count = 0; + +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(); + + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + + /* Assign the api key (required) */ + config.api_key = API_KEY; + + /* Assign the user sign in credentials */ + auth.user.email = USER_EMAIL; + auth.user.password = USER_PASSWORD; + + /* Assign the RTDB URL (required) */ + config.database_url = DATABASE_URL; + + /** + * In case using flash mem to keep the certificate files + * Upload the certificate files cert.pem and cert.der to flash memory. + * Use the following lines to set the certificate file. + * + * config.cert.file = "/gsr2.der"; or + * config.cert.file = "/gsr2.pem"; + * config.cert.file_storage = mem_storage_type_flash; //or mem_storage_type_sd + * + * Or set the certificate data string + * + * config.cert.data = rootCACert; + * + * ESP32 ssl_client class is alble to parse PEM certificate format. + * + * The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. + */ + + /* In case the certificate data was used */ + config.cert.data = rootCACert; + + /* Assign the callback function for the long running token generation task */ + config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h + + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; + + Firebase.begin(&config, &auth); + + //Or use legacy authenticate method + + Firebase.reconnectWiFi(true); +} + +void loop() +{ + if (Firebase.ready() && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)) + { + sendDataPrevMillis = millis(); + + Serial.printf("Set int... %s\n", Firebase.RTDB.setInt(&fbdo, "/test/int", count) ? "ok" : fbdo.errorReason().c_str()); + + Serial.printf("Get int... %s\n", Firebase.RTDB.getInt(&fbdo, "/test/int") ? String(fbdo.intData()).c_str() : fbdo.errorReason().c_str()); + + FirebaseJson json; + json.add("value", count); + + Serial.printf("Push json... %s\n", Firebase.RTDB.pushJSON(&fbdo, "/test/push", &json) ? "ok" : fbdo.errorReason().c_str()); + + json.set("value", count + 100); + Serial.printf("Update json... %s\n\n", Firebase.RTDB.updateNode(&fbdo, String("/test/push/" + fbdo.pushName()).c_str(), &json) ? "ok" : fbdo.errorReason().c_str()); + + count++; + } +} \ No newline at end of file diff --git a/examples/RTDB/Basic_with_Cert/data/gsr2.der b/examples/RTDB/BasicCert/data/gsr2.der similarity index 100% rename from examples/RTDB/Basic_with_Cert/data/gsr2.der rename to examples/RTDB/BasicCert/data/gsr2.der diff --git a/examples/Authentications/Access_Token_from_File/data/gsr2.pem b/examples/RTDB/BasicCert/data/gsr2.pem similarity index 100% rename from examples/Authentications/Access_Token_from_File/data/gsr2.pem rename to examples/RTDB/BasicCert/data/gsr2.pem diff --git a/examples/RTDB/BasicEthernetESP32/BasicEthernetESP32.ino b/examples/RTDB/BasicEthernetESP32/BasicEthernetESP32.ino new file mode 100644 index 000000000..17695c48f --- /dev/null +++ b/examples/RTDB/BasicEthernetESP32/BasicEthernetESP32.ino @@ -0,0 +1,216 @@ + +/** + * Created by K. Suwatchai (Mobizt) + * + * Email: k_suwatchai@hotmail.com + * + * Github: https://github.com/mobizt + * + * Copyright (c) 2021 mobizt + * +*/ + +//This example shows how to read, store and update database using get, set, push and update functions. + +//This example is for ESP32 with LAN8720 Ethernet board. + +/** + * There are may sources for LAN8720 and ESP32 interconnection on the internet which may + * work for your LAN8720 board. + * + * Some methods worked unless no IP is available. + * + * This modification and interconnection provided in this example are mostly worked as + * the 50 MHz clock was created internally in ESP32 which GPIO 17 is set to be output of this clock + * and feeds to the LAN8720 chip XTAL input. + * + * The on-board LAN8720 50 MHz XTAL chip will be disabled by connect its enable pin or pin 1 to GND. + * + * Pleae see the images in the folder "modified_LAN8720_board_images" for how to modify the LAN8720 board. + * + * The LAN8720 Ethernet modified board and ESP32 board wiring connection. + * + * ESP32 LAN8720 + * + * GPIO17 - EMAC_CLK_OUT_180 nINT/REFCLK - LAN8720 XTAL1/CLKIN 4k7 Pulldown + * GPIO22 - EMAC_TXD1 TX1 + * GPIO19 - EMAC_TXD0 TX0 + * GPIO21 - EMAC_TX_EN TX_EN + * GPIO26 - EMAC_RXD1 RX1 + * GPIO25 - EMAC_RXD0 RX0 + * GPIO27 - EMAC_RX_DV CRS + * GPIO23 - MDC MDC + * GPIO18 - MDIO MDIO + * GND GND + * 3V3 VCC + * +*/ + +#include + +//Provide the token generation process info. +#include "addons/TokenHelper.h" +//Provide the RTDB payload printing info and other helper functions. +#include "addons/RTDBHelper.h" + +/* 1. Define the API Key */ +#define API_KEY "API_KEY" + +/* 2. Define the RTDB URL */ +#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app + +/* 3. Define the user Email and password that alreadey registerd or added in your project */ +#define USER_EMAIL "USER_EMAIL" +#define USER_PASSWORD "USER_PASSWORD" + +#ifdef ETH_CLK_MODE +#undef ETH_CLK_MODE +#endif +#define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT //RMII clock output from GPIO17 + +// Pin# of the enable signal for the external crystal oscillator (-1 to disable) +#define ETH_POWER_PIN -1 + +// Type of the Ethernet PHY (LAN8720 or TLK110) +#define ETH_TYPE ETH_PHY_LAN8720 + +// I²C-address of Ethernet PHY (0 or 1 for LAN8720, 31 for TLK110) +#define ETH_ADDR 1 + +// Pin# of the I²C clock signal for the Ethernet PHY +#define ETH_MDC_PIN 23 + +// Pin# of the I²C IO signal for the Ethernet PHY +#define ETH_MDIO_PIN 18 + +static bool eth_connected = false; + +//Define Firebase Data object +FirebaseData fbdo; + +FirebaseAuth auth; +FirebaseConfig config; + +unsigned long sendDataPrevMillis = 0; + +int count = 0; + +bool firebaseConfigReady = false; + +#if defined(ESP32) + +void WiFiEvent(WiFiEvent_t event) +{ + //Do not run any function here to prevent stack overflow or nested interrupt + switch (event) + { + case SYSTEM_EVENT_ETH_START: + Serial.println("ETH Started"); + //set eth hostname here + ETH.setHostname("esp32-ethernet"); + break; + case SYSTEM_EVENT_ETH_CONNECTED: + Serial.println("ETH Connected"); + break; + case SYSTEM_EVENT_ETH_GOT_IP: + Serial.print("ETH MAC: "); + Serial.print(ETH.macAddress()); + Serial.print(", IPv4: "); + Serial.print(ETH.localIP()); + if (ETH.fullDuplex()) + { + Serial.print(", FULL_DUPLEX"); + } + Serial.print(", "); + Serial.print(ETH.linkSpeed()); + Serial.println("Mbps"); + eth_connected = true; + break; + case SYSTEM_EVENT_ETH_DISCONNECTED: + Serial.println("ETH Disconnected"); + eth_connected = false; + break; + case SYSTEM_EVENT_ETH_STOP: + Serial.println("ETH Stopped"); + eth_connected = false; + break; + default: + break; + } +} + +#endif + +void setupFirebase() +{ + if (firebaseConfigReady) + return; + + firebaseConfigReady = true; + + /* Assign the api key (required) */ + config.api_key = API_KEY; + + /* Assign the user sign in credentials */ + auth.user.email = USER_EMAIL; + auth.user.password = USER_PASSWORD; + + /* Assign the RTDB URL (required) */ + config.database_url = DATABASE_URL; + + /* Assign the callback function for the long running token generation task */ + config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h + + config.max_token_generation_retry = 30; + + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; + + Firebase.begin(&config, &auth); + + Firebase.reconnectWiFi(true); +} + +void testFirebase() +{ + + Serial.printf("Set int... %s\n", Firebase.RTDB.setInt(&fbdo, "/test/int", count) ? "ok" : fbdo.errorReason().c_str()); + + Serial.printf("Get int... %s\n", Firebase.RTDB.getInt(&fbdo, "/test/int") ? String(fbdo.intData()).c_str() : fbdo.errorReason().c_str()); + + FirebaseJson json; + json.add("value", count); + + Serial.printf("Push json... %s\n", Firebase.RTDB.pushJSON(&fbdo, "/test/push", &json) ? "ok" : fbdo.errorReason().c_str()); + + json.set("value", count + 100); + Serial.printf("Update json... %s\n\n", Firebase.RTDB.updateNode(&fbdo, String("/test/push/" + fbdo.pushName()).c_str(), &json) ? "ok" : fbdo.errorReason().c_str()); + + count++; +} + +void setup() +{ + + Serial.begin(115200); + Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); +#if defined(ESP32) + WiFi.onEvent(WiFiEvent); + ETH.begin(ETH_ADDR, ETH_POWER_PIN, ETH_MDC_PIN, ETH_MDIO_PIN, ETH_TYPE, ETH_CLK_MODE); +#endif +} + +void loop() +{ +#if defined(ESP32) + if (eth_connected && (millis() - sendDataPrevMillis > 30000 || sendDataPrevMillis == 0)) + { + sendDataPrevMillis = millis(); + setupFirebase(); + if (Firebase.ready()) + testFirebase(); + } +#endif +} diff --git a/examples/RTDB/Basic_ESP32_with_Ethernet/modified_LAN8720_board_images/lan8720_modified_board.png b/examples/RTDB/BasicEthernetESP32/modified_LAN8720_board_images/lan8720_modified_board.png similarity index 100% rename from examples/RTDB/Basic_ESP32_with_Ethernet/modified_LAN8720_board_images/lan8720_modified_board.png rename to examples/RTDB/BasicEthernetESP32/modified_LAN8720_board_images/lan8720_modified_board.png diff --git a/examples/RTDB/Basic_ESP32_with_Ethernet/modified_LAN8720_board_images/lan8720_modified_schematic.png b/examples/RTDB/BasicEthernetESP32/modified_LAN8720_board_images/lan8720_modified_schematic.png similarity index 100% rename from examples/RTDB/Basic_ESP32_with_Ethernet/modified_LAN8720_board_images/lan8720_modified_schematic.png rename to examples/RTDB/BasicEthernetESP32/modified_LAN8720_board_images/lan8720_modified_schematic.png diff --git a/examples/RTDB/Basic_ESP32_with_Ethernet/Basic_ESP32_with_Ethernet.ino b/examples/RTDB/Basic_ESP32_with_Ethernet/Basic_ESP32_with_Ethernet.ino deleted file mode 100644 index 0a6de4110..000000000 --- a/examples/RTDB/Basic_ESP32_with_Ethernet/Basic_ESP32_with_Ethernet.ino +++ /dev/null @@ -1,344 +0,0 @@ - -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -//This example shows how to read, store and update database using get, set, push and update functions. - -//This example is for ESP32 with LAN8720 Ethernet board. - -/** - * There are may sources for LAN8720 and ESP32 interconnection on the internet which may - * work for your LAN8720 board. - * - * Some methods worked unless no IP is available. - * - * This modification and interconnection provided in this example are mostly worked as - * the 50 MHz clock was created internally in ESP32 which GPIO 17 is set to be output of this clock - * and feeds to the LAN8720 chip XTAL input. - * - * The on-board LAN8720 50 MHz XTAL chip will be disabled by connect its enable pin or pin 1 to GND. - * - * Pleae see the images in the folder "modified_LAN8720_board_images" for how to modify the LAN8720 board. - * - * The LAN8720 Ethernet modified board and ESP32 board wiring connection. - * - * ESP32 LAN8720 - * - * GPIO17 - EMAC_CLK_OUT_180 nINT/REFCLK - LAN8720 XTAL1/CLKIN 4k7 Pulldown - * GPIO22 - EMAC_TXD1 TX1 - * GPIO19 - EMAC_TXD0 TX0 - * GPIO21 - EMAC_TX_EN TX_EN - * GPIO26 - EMAC_RXD1 RX1 - * GPIO25 - EMAC_RXD0 RX0 - * GPIO27 - EMAC_RX_DV CRS - * GPIO23 - MDC MDC - * GPIO18 - MDIO MDIO - * GND GND - * 3V3 VCC - * -*/ - -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" -//Provide the RTDB payload printing info and other helper functions. -#include "addons/RTDBHelper.h" - -/* 1. Define the API Key */ -#define API_KEY "API_KEY" - -/* 2. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 3. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -#ifdef ETH_CLK_MODE -#undef ETH_CLK_MODE -#endif -#define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT //RMII clock output from GPIO17 - -// Pin# of the enable signal for the external crystal oscillator (-1 to disable) -#define ETH_POWER_PIN -1 - -// Type of the Ethernet PHY (LAN8720 or TLK110) -#define ETH_TYPE ETH_PHY_LAN8720 - -// I²C-address of Ethernet PHY (0 or 1 for LAN8720, 31 for TLK110) -#define ETH_ADDR 1 - -// Pin# of the I²C clock signal for the Ethernet PHY -#define ETH_MDC_PIN 23 - -// Pin# of the I²C IO signal for the Ethernet PHY -#define ETH_MDIO_PIN 18 - -static bool eth_connected = false; - -//Define Firebase Data object -FirebaseData fbdo; - -FirebaseAuth auth; -FirebaseConfig config; - -FirebaseJson json; - -unsigned long prevMillis = 0; - -bool firebaseConfigReady = false; - -#if defined(ESP32) - -void WiFiEvent(WiFiEvent_t event) -{ - //Do not run any function here to prevent stack overflow or nested interrupt - switch (event) - { - case SYSTEM_EVENT_ETH_START: - Serial.println("ETH Started"); - //set eth hostname here - ETH.setHostname("esp32-ethernet"); - break; - case SYSTEM_EVENT_ETH_CONNECTED: - Serial.println("ETH Connected"); - break; - case SYSTEM_EVENT_ETH_GOT_IP: - Serial.print("ETH MAC: "); - Serial.print(ETH.macAddress()); - Serial.print(", IPv4: "); - Serial.print(ETH.localIP()); - if (ETH.fullDuplex()) - { - Serial.print(", FULL_DUPLEX"); - } - Serial.print(", "); - Serial.print(ETH.linkSpeed()); - Serial.println("Mbps"); - eth_connected = true; - break; - case SYSTEM_EVENT_ETH_DISCONNECTED: - Serial.println("ETH Disconnected"); - eth_connected = false; - break; - case SYSTEM_EVENT_ETH_STOP: - Serial.println("ETH Stopped"); - eth_connected = false; - break; - default: - break; - } -} - -#endif - -void setupFirebase() -{ - if (firebaseConfigReady) - return; - - firebaseConfigReady = true; - - /* Assign the api key (required) */ - config.api_key = API_KEY; - - /* Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - config.max_token_generation_retry = 30; - - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - //Set database read timeout to 1 minute (max 15 minutes) - Firebase.RTDB.setReadTimeout(&fbdo, 1000 * 60); - //tiny, small, medium, large and unlimited. - //Size and its write timeout e.g. tiny (1s), small (10s), medium (30s) and large (60s). - Firebase.RTDB.setwriteSizeLimit(&fbdo, "tiny"); - - //optional, set the decimal places for float and double data to be stored in database - Firebase.setFloatDigits(2); - Firebase.setDoubleDigits(6); - - /** - * This option allows get and delete functions (PUT and DELETE HTTP requests) works for device connected behind the - * irewall that allows only GET and POST requests. - - Firebase.RTDB.enableClassicRequest(&fbdo, true); - */ -} - -void testFirebase() -{ - - String path = "/Test"; - String node; - - Serial.println("------------------------------------"); - Serial.println("Set double test..."); - - for (uint8_t i = 0; i < 10; i++) - { - node = path + "/Double/Data" + String(i + 1); - //Also can use Firebase.set instead of Firebase.setDouble - if (Firebase.RTDB.setDouble(&fbdo, node.c_str(), ((i + 1) * 10) + 0.123456789)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - Serial.println("------------------------------------"); - Serial.println("Get double test..."); - - for (uint8_t i = 0; i < 10; i++) - { - node = path + "/Double/Data" + String(i + 1); - //Also can use Firebase.get instead of Firebase.setInt - if (Firebase.RTDB.getInt(&fbdo, node.c_str())) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.println("ETag: " + fbdo.ETag()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - Serial.println("------------------------------------"); - Serial.println("Push integer test..."); - - for (uint8_t i = 0; i < 5; i++) - { - node = path + "/Push/Int"; - //Also can use Firebase.push instead of Firebase.pushInt - if (Firebase.RTDB.pushInt(&fbdo, node.c_str(), (i + 1))) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - Serial.println("------------------------------------"); - Serial.println("Push JSON test..."); - - for (uint8_t i = 5; i < 10; i++) - { - - json.clear().add("Data" + String(i + 1), i + 1); - - node = path + "/Push/Int"; - - //Also can use Firebase.push instead of Firebase.pushJSON - //Json string is not support in v 2.6.0 and later, only FirebaseJson object is supported. - if (Firebase.RTDB.pushJSON(&fbdo, node.c_str(), &json)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - Serial.println("------------------------------------"); - Serial.println("Update test..."); - - for (uint8_t i = 0; i < 5; i++) - { - - json.set("Data" + String(i + 1), i + 5.5); - - node = path + "/float"; - - if (Firebase.RTDB.updateNode(&fbdo, node.c_str(), &json)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } -} - -void setup() -{ - - Serial.begin(115200); - Serial.println(); -#if defined(ESP32) - WiFi.onEvent(WiFiEvent); - ETH.begin(ETH_ADDR, ETH_POWER_PIN, ETH_MDC_PIN, ETH_MDIO_PIN, ETH_TYPE, ETH_CLK_MODE); -#endif -} - -void loop() -{ -#if defined(ESP32) - if (eth_connected && (millis() - prevMillis > 30000 || prevMillis == 0)) - { - struct token_info_t info = Firebase.authTokenInfo(); - - prevMillis = millis(); - setupFirebase(); - if (Firebase.ready()) - testFirebase(); - } -#endif -} diff --git a/examples/RTDB/Basic_with_Cert/Basic_with_Cert.ino b/examples/RTDB/Basic_with_Cert/Basic_with_Cert.ino deleted file mode 100644 index 95e5f76f6..000000000 --- a/examples/RTDB/Basic_with_Cert/Basic_with_Cert.ino +++ /dev/null @@ -1,282 +0,0 @@ - -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" -//Provide the RTDB payload printing info and other helper functions. -#include "addons/RTDBHelper.h" - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. Define the API Key */ -#define API_KEY "API_KEY" - -/* 3. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 4. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -/* Google Root CA can be downloaded from https://pki.goog/repository/ */ -const char rootCACert[] PROGMEM = "-----BEGIN CERTIFICATE-----\n" - "MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4G\n" - "A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNp\n" - "Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1\n" - "MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEG\n" - "A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI\n" - "hvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPL\n" - "v4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8\n" - "eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklq\n" - "tTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd\n" - "C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pa\n" - "zq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCB\n" - "mTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IH\n" - "V2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5n\n" - "bG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG\n" - "3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs\n" - "J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO\n" - "291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavS\n" - "ot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd\n" - "AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7\n" - "TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg==\n" - "-----END CERTIFICATE-----\n"; - -//Define Firebase Data object -FirebaseData fbdo; - -FirebaseAuth auth; -FirebaseConfig config; - -bool taskCompleted = false; - -FirebaseJson json; - -void setup() -{ - - Serial.begin(115200); - - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); - Serial.print("Connecting to Wi-Fi"); - while (WiFi.status() != WL_CONNECTED) - { - Serial.print("."); - delay(300); - } - Serial.println(); - Serial.print("Connected with IP: "); - Serial.println(WiFi.localIP()); - Serial.println(); - - /* Assign the api key (required) */ - config.api_key = API_KEY; - - /* Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /** - * In case using flash mem to keep the certificate files - * Upload the certificate files cert.pem and cert.der to flash memory. - * Use the following lines to set the certificate file. - * - * config.cert.file = "/gsr2.der"; or - * config.cert.file = "/gsr2.pem"; - * config.cert.file_storage = mem_storage_type_flash; //or mem_storage_type_sd - * - * ESP32 ssl_client class is alble to parse PEM certificate format. - * - * The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. - */ - - /* In case the certificate data was used */ - config.cert.data = rootCACert; - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - //Set database read timeout to 1 minute (max 15 minutes) - Firebase.RTDB.setReadTimeout(&fbdo, 1000 * 60); - //tiny, small, medium, large and unlimited. - //Size and its write timeout e.g. tiny (1s), small (10s), medium (30s) and large (60s). - Firebase.RTDB.setwriteSizeLimit(&fbdo, "tiny"); - - //optional, set the decimal places for float and double data to be stored in database - Firebase.setFloatDigits(2); - Firebase.setDoubleDigits(6); - - /* - This option allows get and delete functions (PUT and DELETE HTTP requests) works for device connected behind the - Firewall that allows only GET and POST requests. - - Firebase.RTDB.enableClassicRequest(&fbdo, true); - */ - -} - -void loop() -{ - if (Firebase.ready() && !taskCompleted) - { - taskCompleted = true; - - String path = "/Test"; - String node; - - Serial.println("------------------------------------"); - Serial.println("Set double test..."); - - for (uint8_t i = 0; i < 10; i++) - { - node = path + "/Double/Data" + String(i + 1); - //Also can use Firebase.set instead of Firebase.setDouble - if (Firebase.RTDB.setDouble(&fbdo, node.c_str(), ((i + 1) * 10) + 0.123456789)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - Serial.println("------------------------------------"); - Serial.println("Get double test..."); - - for (uint8_t i = 0; i < 10; i++) - { - node = path + "/Double/Data" + String(i + 1); - //Also can use Firebase.get instead of Firebase.setInt - if (Firebase.RTDB.getInt(&fbdo, node.c_str())) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.println("ETag: " + fbdo.ETag()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - Serial.println("------------------------------------"); - Serial.println("Push integer test..."); - - for (uint8_t i = 0; i < 5; i++) - { - node = path + "/Push/Int"; - //Also can use Firebase.push instead of Firebase.pushInt - if (Firebase.RTDB.pushInt(&fbdo, node.c_str(), (i + 1))) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - Serial.println("------------------------------------"); - Serial.println("Push JSON test..."); - - for (uint8_t i = 5; i < 10; i++) - { - - json.clear().add("Data" + String(i + 1), i + 1); - - node = path + "/Push/Int"; - - //Also can use Firebase.push instead of Firebase.pushJSON - //Json string is not support in v 2.6.0 and later, only FirebaseJson object is supported. - if (Firebase.RTDB.pushJSON(&fbdo, node.c_str(), &json)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - Serial.println("------------------------------------"); - Serial.println("Update test..."); - - for (uint8_t i = 0; i < 5; i++) - { - - json.set("Data" + String(i + 1), i + 5.5); - - node = path + "/float"; - - if (Firebase.RTDB.updateNode(&fbdo, node.c_str(), &json)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - } -} \ No newline at end of file diff --git a/examples/RTDB/Basic_with_Cert/data/gsr2.pem b/examples/RTDB/Basic_with_Cert/data/gsr2.pem deleted file mode 100644 index 75a695d2b..000000000 --- a/examples/RTDB/Basic_with_Cert/data/gsr2.pem +++ /dev/null @@ -1,22 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDvDCCAqSgAwIBAgINAgPk9GHsmdnVeWbKejANBgkqhkiG9w0BAQUFADBMMSAw -HgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMKR2xvYmFs -U2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0wNjEyMTUwODAwMDBaFw0yMTEy -MTUwODAwMDBaMEwxIDAeBgNVBAsTF0dsb2JhbFNpZ24gUm9vdCBDQSAtIFIyMRMw -EQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWduMIIBIjANBgkq -hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAps8kDr4ubyiZRULEqz4hVJsL03+EcPoS -s8u/h1/Gf4bTsjBc1v2t8Xvc5fhglgmSEPXQU977e35ziKxSiHtKpspJpl6op4xa -Ebx6guu+jOmzrJYlB5dKmSoHL7Qed7+KD7UCfBuWuMW5Oiy81hK561l94tAGhl9e -SWq1OV6INOy8eAwImIRsqM1LtKB9DHlN8LgtyyHK1WxbfeGgKYSh+dOUScskYpEg -vN0L1dnM+eonCitzkcadG6zIy+jgoPQvkItN+7A2G/YZeoXgbfJhE4hcn+CTClGX -ilrOr6vV96oJqmC93Nlf33KpYBNeAAHJSvo/pOoHAyECjoLKA8KbjwIDAQABo4Gc -MIGZMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSb -4gdXZxwewGoG3lm0mi3f3BmGLjAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0mi3f -3BmGLjA2BgNVHR8ELzAtMCugKaAnhiVodHRwOi8vY3JsLmdsb2JhbHNpZ24ubmV0 -L3Jvb3QtcjIuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQANeX81Z1YqDIs4EaLjG0qP -OxIzaJI/y4kiRj3a+y3KOx74clIkLuMgi/9/5iv/n+1LyhGU9g7174slbzJOPbSp -p1eT19ST2mYbdgTLx/hm3tTLoHIY/w4ZbnQYwfnPwAG4RefnEFYPQJmpD+Wh8BJw -Bgtm2drTale/T6NBwmwnEFunfaMfMX3g6IBrx7VKnxIkJh/3p190WveLKgl9n7i5 -SWce/4woPimEn9WfEQWRvp6wKhaCKFjuCMuulEZusoOUJ4LfJnXxcuQTgIrSnwI7 -KfSSjsd42w3lX1fbgJp7vPmLM6OBRvAXuYRKTFqMAWbb7OaGIEE+cbxY6PDepnva ------END CERTIFICATE----- diff --git a/examples/RTDB/Beginner_Start_Here/Beginner_Start_Here.ino b/examples/RTDB/Beginner_Start_Here/Beginner_Start_Here.ino deleted file mode 100644 index 1586c25b3..000000000 --- a/examples/RTDB/Beginner_Start_Here/Beginner_Start_Here.ino +++ /dev/null @@ -1,171 +0,0 @@ - -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. Define the API Key */ -#define API_KEY "API_KEY" - -/* 3. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 4. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -/* 5. Define FirebaseESP8266 data object for data sending and receiving */ -FirebaseData fbdo; - -/* 6. Define the FirebaseAuth data for authentication data */ -FirebaseAuth auth; - -/* 7. Define the FirebaseConfig data for config data */ -FirebaseConfig config; - -bool taskCompleted = false; - -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(); - - /* 8. Assign the api key (required) */ - config.api_key = API_KEY; - - /* 9. Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* 10. Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /* 11. Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - /* 12. Initialize the library with the autentication data */ - Firebase.begin(&config, &auth); - - /* 13. Enable auto reconnect the WiFi when connection lost */ - Firebase.reconnectWiFi(true); -} - -void loop() -{ - /* 14. Check the ready state of Firebase before calling other functions that related to data transfer */ - if (Firebase.ready() && !taskCompleted) - { - taskCompleted = true; - - /* 15. Try to set int data to Firebase */ - //The set function returns bool for the status of operation - //fbdo requires for sending the data and pass as the pointer - if (Firebase.RTDB.setInt(&fbdo, "/LED_Status", 1)) - { - //Success - Serial.println("Set int data success"); - } - else - { - //Failed?, get the error reason from fbdo - - Serial.print("Error in setInt, "); - Serial.println(fbdo.errorReason()); - } - - /* 16. Try to get int data from Firebase */ - //The get function returns bool for the status of operation - //fbdo requires for receiving the data - if (Firebase.RTDB.getInt(&fbdo, "/LED_Status")) - { - //Success - Serial.print("Get int data success, int = "); - Serial.println(fbdo.intData()); - } - else - { - //Failed?, get the error reason from fbdo - - Serial.print("Error in getInt, "); - Serial.println(fbdo.errorReason()); - } - - /* - - In case where you want to set other data types i.e. bool, float, double and String, you can use setBool, setFloat, setDouble and setString. - If you want to get data which you known its type at specific node, use getInt, getBool, getFloat, getDouble, getString. - If you don't know the data type at specific node, use get and check its type. - - The following shows how to get the variant data - - */ - - if (Firebase.RTDB.get(&fbdo, "/LED_Status")) - { - //Success - Serial.print("Get variant data success, type = "); - Serial.println(fbdo.dataType()); - - if (fbdo.dataType() == "int") - { - Serial.print("data = "); - Serial.println(fbdo.intData()); - } - else if (fbdo.dataType() == "bool") - { - if (fbdo.boolData()) - Serial.println("data = true"); - else - Serial.println("data = false"); - } - } - else - { - //Failed?, get the error reason from fbdo - - Serial.print("Error in get, "); - Serial.println(fbdo.errorReason()); - } - - /* - - If you want to get the data in realtime instead of using get, see the stream examples. - If you want to work with JSON, see the FirebaseJson, jsonObject and jsonArray examples. - - If you have questions or found the bugs, feel free to open the issue here https://github.com/mobizt/Firebase-ESP-Client - - */ - } -} diff --git a/examples/RTDB/Blob/Blob.ino b/examples/RTDB/Blob/Blob.ino index bf006c830..8582764df 100644 --- a/examples/RTDB/Blob/Blob.ino +++ b/examples/RTDB/Blob/Blob.ino @@ -43,9 +43,9 @@ FirebaseData fbdo; FirebaseAuth auth; FirebaseConfig config; -bool taskCompleted = false; +unsigned long sendDataPrevMillis = 0; -String path = "/Test"; +int count = 0; void setup() { @@ -66,6 +66,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -75,123 +77,39 @@ void setup() /* Assign the RTDB URL (required) */ config.database_url = DATABASE_URL; - + /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); + Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); } void loop() { - if (Firebase.ready() && !taskCompleted) + if (Firebase.ready() && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)) { - taskCompleted = true; - - Serial.println("------------------------------------"); - Serial.println("Set BLOB data test..."); + sendDataPrevMillis = millis(); //Create demo data uint8_t data[256]; for (int i = 0; i < 256; i++) - data[i] = i; - - String Path = path + "/Binary/Blob/data"; - //Set binary data to database (also can use Firebase.set) - if (Firebase.RTDB.setBlob(&fbdo, Path.c_str(), data, sizeof(data))) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Get BLOB data test..."); - - //Get binary data from database (also can use Firebase.get) - if (Firebase.RTDB.getBlob(&fbdo, Path.c_str())) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Append BLOB data test..."); + data[i] = count; - //Create demo data - for (int i = 0; i < 256; i++) - data[i] = 255 - i; - - Path = path + "/Binary/Blob/Logs"; - - //Append binary data to database (also can use Firebase.push) - if (Firebase.RTDB.pushBlob(&fbdo, Path.c_str(), data, sizeof(data))) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("PUSH NAME: " + fbdo.pushName()); - Serial.println("------------------------------------"); - Serial.println(); - - Serial.println("------------------------------------"); - Serial.println("Get appended BLOB data test..."); - - Path = path + "/Binary/Blob/Logs/" + fbdo.pushName(); - - //Get appended binary data from database (also can use Firebase.get) - if (Firebase.RTDB.getBlob(&fbdo, Path.c_str())) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("Set BLOB... %s\n", Firebase.RTDB.setBlob(&fbdo, "/test/blob", data, sizeof(data)) ? "ok" : fbdo.errorReason().c_str()); + + Serial.printf("Get BLOB... %s\n", Firebase.RTDB.getBlob(&fbdo, "/test/blob") ? "ok" : fbdo.errorReason().c_str()); + + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) //200 + printResult(fbdo); //see addons/RTDBHelper.h + + Serial.println(); + + (count < 255) ? count++ : count = 0; } } diff --git a/examples/RTDB/Blynk/Blynk.ino b/examples/RTDB/Blynk/Blynk.ino index 898af7d96..37add062a 100644 --- a/examples/RTDB/Blynk/Blynk.ino +++ b/examples/RTDB/Blynk/Blynk.ino @@ -40,8 +40,8 @@ #define USER_PASSWORD "USER_PASSWORD" //Define Firebase Data object -FirebaseData fbdo1; -FirebaseData fbdo2; +FirebaseData fbdo; +FirebaseData stream; FirebaseAuth auth; FirebaseConfig config; @@ -85,6 +85,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -98,114 +100,61 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo1.setBSSLBufferSize(1024, 1024); -#endif + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo1.setResponseSize(1024); + Firebase.begin(&config, &auth); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo2.setBSSLBufferSize(1024, 1024); -#endif + Firebase.reconnectWiFi(true); - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo2.setResponseSize(1024); - - - if (!Firebase.RTDB.beginStream(&fbdo1, path.c_str())) - { - Serial.println("------------------------------------"); - Serial.println("Can't begin stream connection..."); - Serial.println("REASON: " + fbdo1.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + if (!Firebase.RTDB.beginStream(&stream, "/test/blynk/int")) + Serial.printf("sream begin error, %s\n\n", stream.errorReason().c_str()); Blynk.begin(BLYNK_AUTH, WIFI_SSID, WIFI_PASSWORD); } void loop() { + Blynk.run(); if (Firebase.ready()) { - if (!Firebase.RTDB.readStream(&fbdo1)) - { - Serial.println("------------------------------------"); - Serial.println("Can't read stream data..."); - Serial.println("REASON: " + fbdo1.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + if (!Firebase.RTDB.readStream(&stream)) + Serial.printf("sream read error, %s\n\n", stream.errorReason().c_str()); - if (fbdo1.streamTimeout()) - { - Serial.println("Stream timeout, resume streaming..."); - Serial.println(); - } + if (stream.streamTimeout()) + Serial.println("stream timeout, resuming...\n"); - if (fbdo1.streamAvailable()) + if (stream.streamAvailable()) { - Serial.println("------------------------------------"); - Serial.println("Stream Data available..."); - Serial.println("STREAM PATH: " + fbdo1.streamPath()); - Serial.println("EVENT PATH: " + fbdo1.dataPath()); - Serial.println("DATA TYPE: " + fbdo1.dataType()); - Serial.println("EVENT TYPE: " + fbdo1.eventType()); - Serial.print("VALUE: "); - if (fbdo1.dataType() == "int") - { - Serial.println(fbdo1.intData()); - if (fbdo1.intData() == 0) - { - digitalWrite(BuiltIn_LED, LOW); - led.off(); - } - else if (fbdo1.intData() == 1) + Serial.printf("sream path, %s\nevent path, %s\ndata type, %s\nevent type, %s\nvalue, %d\n\n", + stream.streamPath().c_str(), + stream.dataPath().c_str(), + stream.dataType().c_str(), + stream.eventType().c_str(), + stream.intData()); + + if (stream.dataType() == "int") + { + if (stream.intData() == 1) { digitalWrite(BuiltIn_LED, HIGH); led.on(); } + else + { + digitalWrite(BuiltIn_LED, LOW); + led.off(); + } } - Serial.println("------------------------------------"); - Serial.println(); } } } - - BLYNK_WRITE(V1) { - int pinValue = param.asInt(); // assigning incoming value from pin V1 to a variable - - Serial.println("------------------------------------"); - Serial.println("Set integer..."); - //Also can use Firebase.set instead of Firebase.setInt - if (Firebase.RTDB.setInt(&fbdo2, path.c_str(), pinValue)) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo2.dataPath()); - Serial.println("TYPE: " + fbdo2.dataType()); - Serial.print("VALUE: "); - if (fbdo2.dataType() == "int") - Serial.println(fbdo2.intData()); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo2.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("Set int... %s\n\n", Firebase.RTDB.setInt(&fbdo, "/test/blynk/int", param.asInt()) ? "ok" : fbdo.errorReason().c_str()); } diff --git a/examples/Test/index.html b/examples/RTDB/Browser/index.html similarity index 100% rename from examples/Test/index.html rename to examples/RTDB/Browser/index.html diff --git a/examples/RTDB/DataChangesListener/Callback/Callback.ino b/examples/RTDB/DataChangesListener/Callback/Callback.ino new file mode 100644 index 000000000..c9df86378 --- /dev/null +++ b/examples/RTDB/DataChangesListener/Callback/Callback.ino @@ -0,0 +1,128 @@ +/** + * Created by K. Suwatchai (Mobizt) + * + * Email: k_suwatchai@hotmail.com + * + * Github: https://github.com/mobizt + * + * Copyright (c) 2021 mobizt + * +*/ + +#if defined(ESP32) +#include +#elif defined(ESP8266) +#include +#endif +#include + +//Provide the token generation process info. +#include "addons/TokenHelper.h" +//Provide the RTDB payload printing info and other helper functions. +#include "addons/RTDBHelper.h" + +/* 1. Define the WiFi credentials */ +#define WIFI_SSID "WIFI_AP" +#define WIFI_PASSWORD "WIFI_PASSWORD" + +/* 2. Define the API Key */ +#define API_KEY "API_KEY" + +/* 3. Define the RTDB URL */ +#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app + +/* 4. Define the user Email and password that alreadey registerd or added in your project */ +#define USER_EMAIL "USER_EMAIL" +#define USER_PASSWORD "USER_PASSWORD" + +//Define Firebase Data object +FirebaseData stream; +FirebaseData fbdo; + +FirebaseAuth auth; +FirebaseConfig config; + +unsigned long sendDataPrevMillis = 0; + +int count = 0; + +void streamCallback(FirebaseStream data) +{ + Serial.printf("sream path, %s\nevent path, %s\ndata type, %s\nevent type, %s\n\n", + data.streamPath().c_str(), + data.dataPath().c_str(), + data.dataType().c_str(), + data.eventType().c_str()); + printResult(data); //see addons/RTDBHelper.h + Serial.println(); +} + +void streamTimeoutCallback(bool timeout) +{ + if (timeout) + Serial.println("stream timeout, resuming...\n"); +} + +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(); + + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + + /* Assign the api key (required) */ + config.api_key = API_KEY; + + /* Assign the user sign in credentials */ + auth.user.email = USER_EMAIL; + auth.user.password = USER_PASSWORD; + + /* Assign the RTDB URL (required) */ + config.database_url = DATABASE_URL; + + /* Assign the callback function for the long running token generation task */ + config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h + + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; + + Firebase.begin(&config, &auth); + + Firebase.reconnectWiFi(true); + + //The data under the node being stream (parent path) should keep small + //Large stream payload leads to the parsing error due to memory allocation. + + if (!Firebase.RTDB.beginStream(&stream, "/test/stream/data")) + Serial.printf("sream begin error, %s\n\n", stream.errorReason().c_str()); + + Firebase.RTDB.setStreamCallback(&stream, streamCallback, streamTimeoutCallback); +} + +void loop() +{ + + if (Firebase.ready() && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)) + { + sendDataPrevMillis = millis(); + count++; + FirebaseJson json; + json.add("data", "hello"); + json.add("num", count); + Serial.printf("Set json... %s\n\n", Firebase.RTDB.setJSON(&fbdo, "/test/stream/data/json", &json) ? "ok" : fbdo.errorReason().c_str()); + + } +} diff --git a/examples/RTDB/MultiPath_Stream/MultiPath_Stream.ino b/examples/RTDB/DataChangesListener/MultiPath/MultiPath.ino similarity index 54% rename from examples/RTDB/MultiPath_Stream/MultiPath_Stream.ino rename to examples/RTDB/DataChangesListener/MultiPath/MultiPath.ino index 94941de1b..1f41bad8d 100644 --- a/examples/RTDB/MultiPath_Stream/MultiPath_Stream.ino +++ b/examples/RTDB/DataChangesListener/MultiPath/MultiPath.ino @@ -35,34 +35,23 @@ #define USER_EMAIL "USER_EMAIL" #define USER_PASSWORD "USER_PASSWORD" -//Define FirebaseESP8266 data object -FirebaseData fbdo1; -FirebaseData fbdo2; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -//Important information -//In ESP8266 Aruino Core SDK v3.x.x -//The free heap is significantly reduced as much as 5-6 kB from v2.7.4. -//This may lead to out of memory sitation when two Firebase Data objects are used simultaneously (when sessions connected). -//Minimize the reserved memory for BearSSL will gain the free heap a bit but may not enough for your usage. -//You can stay with Core SDK v2.7.4 until this memory issue was solve in the Core SDK. -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +//Define Firebase Data object +FirebaseData fbdo; +FirebaseData stream; FirebaseAuth auth; FirebaseConfig config; unsigned long sendDataPrevMillis = 0; -String parentPath = "/Test/Stream"; +String parentPath = "/test/stream/data"; String childPath[2] = {"/node1", "/node2"}; size_t childPathSize = 2; -uint16_t count = 0; +int count = 0; void streamCallback(MultiPathStream stream) { - Serial.println(); - Serial.println("Stream Data1 available..."); size_t numChild = sizeof(childPath) / sizeof(childPath[0]); @@ -70,7 +59,7 @@ void streamCallback(MultiPathStream stream) { if (stream.get(childPath[i])) { - Serial.println("path: " + stream.dataPath + ", type: " + stream.type + ", value: " + stream.value); + Serial.printf("path: %s, event: %s, type: %s, value: %s%s", stream.dataPath.c_str(), stream.eventType.c_str(), stream.type.c_str(), stream.value.c_str(), i < numChild - 1 ? "\n" : ""); } } @@ -80,11 +69,7 @@ void streamCallback(MultiPathStream stream) void streamTimeoutCallback(bool timeout) { if (timeout) - { - Serial.println(); - Serial.println("Stream timeout, resume streaming..."); - Serial.println(); - } + Serial.println("stream timeout, resuming...\n"); } void setup() @@ -104,6 +89,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -117,25 +104,13 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo1.setBSSLBufferSize(1024, 512); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo1.setResponseSize(1024); + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo2.setBSSLBufferSize(1024, 512); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo2.setResponseSize(1024); + Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); //The data under the node being stream (parent path) should keep small //Large stream payload leads to the parsing error due to memory allocation. @@ -145,16 +120,11 @@ void setup() //The changes occurred in any child node that is not in the child paths array will sent to the //client as usual. - if (!Firebase.RTDB.beginMultiPathStream(&fbdo1, parentPath.c_str(), childPath, childPathSize)) - { - Serial.println("------------------------------------"); - Serial.println("Can't begin stream connection..."); - Serial.println("REASON: " + fbdo1.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - Firebase.RTDB.setMultiPathStreamCallback(&fbdo1, streamCallback, streamTimeoutCallback); + if (!Firebase.RTDB.beginMultiPathStream(&stream, parentPath.c_str(), childPath, childPathSize)) + Serial.printf("sream begin error, %s\n\n", stream.errorReason().c_str()); + + Firebase.RTDB.setMultiPathStreamCallback(&stream, streamCallback, streamTimeoutCallback); } void loop() @@ -164,22 +134,22 @@ void loop() { sendDataPrevMillis = millis(); - Serial.println("------------------------------------"); - Serial.println("Set JSON..."); + Serial.print("\nSet json..."); FirebaseJson json; for (size_t i = 0; i < 10; i++) { - json.set("node1/data", "hello"); + json.set("node1/data", "v1"); json.set("node1/num", count); - json.set("node2/data", "hi"); - json.set("node2/num", count); - + json.set("node2/data", "v2"); + json.set("node2/num", count * 3); //The response is ignored in this async function, it may return true as long as the connection is established. //The purpose for this async function is to set, push and update data instantly. - Firebase.RTDB.setJSONAsync(&fbdo2, parentPath.c_str(), &json); + Firebase.RTDB.setJSONAsync(&fbdo, parentPath.c_str(), &json); count++; } + + Serial.println("ok\n"); } } diff --git a/examples/RTDB/DataChangesListener/NoCallback/NoCallback.ino b/examples/RTDB/DataChangesListener/NoCallback/NoCallback.ino new file mode 100644 index 000000000..bbdaef914 --- /dev/null +++ b/examples/RTDB/DataChangesListener/NoCallback/NoCallback.ino @@ -0,0 +1,130 @@ +/** + * Created by K. Suwatchai (Mobizt) + * + * Email: k_suwatchai@hotmail.com + * + * Github: https://github.com/mobizt + * + * Copyright (c) 2021 mobizt + * +*/ + +#if defined(ESP32) +#include +#elif defined(ESP8266) +#include +#endif +#include + +//Provide the token generation process info. +#include "addons/TokenHelper.h" +//Provide the RTDB payload printing info and other helper functions. +#include "addons/RTDBHelper.h" + +/* 1. Define the WiFi credentials */ +#define WIFI_SSID "WIFI_AP" +#define WIFI_PASSWORD "WIFI_PASSWORD" + +/* 2. Define the API Key */ +#define API_KEY "API_KEY" + +/* 3. Define the RTDB URL */ +#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app + +/* 4. Define the user Email and password that alreadey registerd or added in your project */ +#define USER_EMAIL "USER_EMAIL" +#define USER_PASSWORD "USER_PASSWORD" + +//Define Firebase Data objects +FirebaseData fbdo; +FirebaseData stream; + +FirebaseAuth auth; +FirebaseConfig config; + +unsigned long sendDataPrevMillis1; + +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(); + + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + + /* Assign the api key (required) */ + config.api_key = API_KEY; + + /* Assign the user sign in credentials */ + auth.user.email = USER_EMAIL; + auth.user.password = USER_PASSWORD; + + /* Assign the RTDB URL (required) */ + config.database_url = DATABASE_URL; + + /* Assign the callback function for the long running token generation task */ + config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h + + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; + + Firebase.begin(&config, &auth); + + Firebase.reconnectWiFi(true); + + if (!Firebase.RTDB.beginStream(&stream, "/test/stream/data")) + Serial.printf("sream begin error, %s\n\n", stream.errorReason().c_str()); +} + +void loop() +{ + + if (!Firebase.ready()) + return; + + if (!Firebase.RTDB.readStream(&stream)) + Serial.printf("sream read error, %s\n\n", stream.errorReason().c_str()); + + if (stream.streamTimeout()) + Serial.println("stream timeout, resuming...\n"); + + if (stream.streamAvailable()) + { + Serial.printf("sream path, %s\nevent path, %s\ndata type, %s\nevent type, %s\n\n", + stream.streamPath().c_str(), + stream.dataPath().c_str(), + stream.dataType().c_str(), + stream.eventType().c_str()); + printResult(stream); //see addons/RTDBHelper.h + Serial.println(); + } + + if (millis() - sendDataPrevMillis1 > 15000) + { + sendDataPrevMillis1 = millis(); + + //Create demo data + uint8_t data[256]; + for (int i = 0; i < 256; i++) + data[i] = i; + data[255] = rand(); + + Serial.printf("Set BLOB... %s\n", Firebase.RTDB.setBlob(&fbdo, "/test/stream/data", data, sizeof(data)) ? "ok" : fbdo.errorReason().c_str()); + Serial.printf("Free Heap, %d\n", (int)ESP.getFreeHeap()); + Serial.println(); + } +} \ No newline at end of file diff --git a/examples/RTDB/DataChangesListener/SingleDataObject/SingleDataObject.ino b/examples/RTDB/DataChangesListener/SingleDataObject/SingleDataObject.ino new file mode 100644 index 000000000..382f607c1 --- /dev/null +++ b/examples/RTDB/DataChangesListener/SingleDataObject/SingleDataObject.ino @@ -0,0 +1,126 @@ +/** + * Created by K. Suwatchai (Mobizt) + * + * Email: k_suwatchai@hotmail.com + * + * Github: https://github.com/mobizt + * + * Copyright (c) 2021 mobizt + * +*/ + +#if defined(ESP32) +#include +#elif defined(ESP8266) +#include +#endif +#include + +//Provide the token generation process info. +#include "addons/TokenHelper.h" +//Provide the RTDB payload printing info and other helper functions. +#include "addons/RTDBHelper.h" + +/* 1. Define the WiFi credentials */ +#define WIFI_SSID "WIFI_AP" +#define WIFI_PASSWORD "WIFI_PASSWORD" + +/* 2. Define the API Key */ +#define API_KEY "API_KEY" + +/* 3. Define the RTDB URL */ +#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app + +/* 4. Define the user Email and password that alreadey registerd or added in your project */ +#define USER_EMAIL "USER_EMAIL" +#define USER_PASSWORD "USER_PASSWORD" + +//Define Firebase Data object +FirebaseData fbdo; + +FirebaseAuth auth; +FirebaseConfig config; + +unsigned long sendDataPrevMillis = 0; + +int count = 0; + +uint32_t idleTimeForStream = 15000; + +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(); + + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + + /* Assign the api key (required) */ + config.api_key = API_KEY; + + /* Assign the user sign in credentials */ + auth.user.email = USER_EMAIL; + auth.user.password = USER_PASSWORD; + + /* Assign the RTDB URL (required) */ + config.database_url = DATABASE_URL; + + /* Assign the callback function for the long running token generation task */ + config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h + + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; + + Firebase.begin(&config, &auth); + + Firebase.reconnectWiFi(true); + + //The data under the node being stream (parent path) should keep small + //Large stream payload leads to the parsing error due to memory allocation. + if (!Firebase.RTDB.beginStream(&fbdo, "/test/stream/data")) + Serial.printf("sream begin error, %s\n\n", fbdo.errorReason().c_str()); +} + +void loop() +{ + + if (Firebase.ready() && (millis() - sendDataPrevMillis > idleTimeForStream || sendDataPrevMillis == 0)) + { + sendDataPrevMillis = millis(); + count++; + String Value = "Hello World! " + String(count); + Serial.printf("Set string... %s\n\n", Firebase.RTDB.setString(&fbdo, "/test/stream/data", Value) ? "ok" : fbdo.errorReason().c_str()); + } + + if (Firebase.ready()) + { + + if (!Firebase.RTDB.readStream(&fbdo)) + Serial.printf("sream read error, %s\n\n", fbdo.errorReason().c_str()); + + if (fbdo.streamTimeout()) + Serial.println("stream timeout, resuming...\n"); + + if (fbdo.streamAvailable()) + { + Serial.printf("sream path, %s\nevent path, %s\ndata type, %s\nevent type, %s\nvalue, %s\n\n", + fbdo.streamPath().c_str(), + fbdo.dataPath().c_str(), + fbdo.dataType().c_str(), + fbdo.eventType().c_str(), + fbdo.stringData().c_str()); + } + } +} \ No newline at end of file diff --git a/examples/RTDB/Data_Filter/Data_Filter.ino b/examples/RTDB/DataFilter/DataFilter.ino similarity index 60% rename from examples/RTDB/Data_Filter/Data_Filter.ino rename to examples/RTDB/DataFilter/DataFilter.ino index a0f75601d..f9a787804 100644 --- a/examples/RTDB/Data_Filter/Data_Filter.ino +++ b/examples/RTDB/DataFilter/DataFilter.ino @@ -48,8 +48,6 @@ FirebaseConfig config; bool taskCompleted = false; -FirebaseJson json; - void setup() { @@ -69,6 +67,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -82,87 +82,59 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; + Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + //Or use legacy authenticate method + //Firebase.begin(DATABASE_URL, DATABASE_SECRET); - //Set the size of HTTP response buffers in the case where we want to work with large data in this example. - fbdo.setResponseSize(1024); + Firebase.reconnectWiFi(true); } void loop() { if (Firebase.ready() && !taskCompleted) { + taskCompleted = true; - Serial.println("------------------------------------"); - Serial.println("Push JSON test..."); + FirebaseJson json; for (uint8_t i = 0; i < 30; i++) { json.set("Data1", i + 1); json.set("Data2", i + 100); - - //Also can use Firebase.push instead of Firebase.pushJSON - //JSON string does not support in v 2.6.0 and later, only FirebaseJson object is supported. - if (Firebase.RTDB.pushJSON(&fbdo, "/Test/Int", &json)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("Push json... %s\n", Firebase.RTDB.pushAsync(&fbdo, "/test/push", &json) ? "ok" : fbdo.errorReason().c_str()); } + Serial.println(); //Add an index to the node that being query. - //Update the existing database rules by adding key "Test/Int/.indexOn" and value "Data2" + //Update the existing database rules by adding key "test/push/.indexOn" and value "Data2" //Check your database rules changes after running this function. /** If the authentication type is OAuth2.0 which allows the admin right access, * the database secret is not necessary by set this parameter with empty string "". */ - Firebase.RTDB.setQueryIndex(&fbdo, "Test/Int", "Data2", DATABASE_SECRET); + Firebase.RTDB.setQueryIndex(&fbdo, "/test/push", "Data2", DATABASE_SECRET); QueryFilter query; query.orderBy("Data2"); query.startAt(105); query.endAt(120); + //get only last 8 results query.limitToLast(8); - //Begin the data filtering test - Serial.println("------------------------------------"); - Serial.println("Data Filtering test..."); - - if (Firebase.RTDB.getJSON(&fbdo, "/Test/Int", &query)) - { + //Get filtered data + Serial.printf("Get json... %s\n", Firebase.RTDB.getJSON(&fbdo, "/test/push", &query) ? "ok" : fbdo.errorReason().c_str()); - Serial.println("PASSED"); - Serial.println("JSON DATA: "); + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } //Clear all query parameters query.clear(); } -} +} \ No newline at end of file diff --git a/examples/RTDB/Get_Set_Database_Rules/Get_Set_Database_Rules.ino b/examples/RTDB/DatabaseRules/DatabaseRules.ino similarity index 56% rename from examples/RTDB/Get_Set_Database_Rules/Get_Set_Database_Rules.ino rename to examples/RTDB/DatabaseRules/DatabaseRules.ino index a52740991..f50076359 100644 --- a/examples/RTDB/Get_Set_Database_Rules/Get_Set_Database_Rules.ino +++ b/examples/RTDB/DatabaseRules/DatabaseRules.ino @@ -71,6 +71,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -85,17 +87,13 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); + Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); } void loop() @@ -106,67 +104,17 @@ void loop() String rules = ""; - Serial.println("------------------------------------"); - Serial.println("Read Database Rules test..."); + Serial.printf("Get RTDB rules... %s\n", Firebase.RTDB.getRules(&fbdo) ? "ok" : fbdo.errorReason().c_str()); - if (Firebase.RTDB.getRules(&fbdo)) + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) { - Serial.println("PASSED"); - Serial.println("DATABASE RULES: "); FirebaseJson &json = fbdo.jsonObject(); json.toString(rules, true); Serial.println(rules); - - Serial.println(); - Serial.println("------------------------------------"); - Serial.println("PARSE: "); - - size_t len = json.iteratorBegin(); - String key, value = ""; - int type = 0; - for (size_t i = 0; i < len; i++) - { - json.iteratorGet(i, type, key, value); - Serial.print(i); - Serial.print(", "); - Serial.print("Type: "); - Serial.print(type == FirebaseJson::JSON_OBJECT ? "object" : "array"); - if (type == FirebaseJson::JSON_OBJECT) - { - Serial.print(", Key: "); - Serial.print(key); - } - Serial.print(", Value: "); - Serial.println(value); - } - - json.iteratorEnd(); Serial.println(); } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Write Database Rules test..."); - if (Firebase.RTDB.setRules(&fbdo, rules.c_str())) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("Set RTDB rules... %s\n", Firebase.RTDB.setRules(&fbdo, rules.c_str()) ? "ok" : fbdo.errorReason().c_str()); } } diff --git a/examples/RTDB/Different_Objects_Stream/Different_Objects_Stream.ino b/examples/RTDB/Different_Objects_Stream/Different_Objects_Stream.ino deleted file mode 100644 index eadf24634..000000000 --- a/examples/RTDB/Different_Objects_Stream/Different_Objects_Stream.ino +++ /dev/null @@ -1,208 +0,0 @@ -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" -//Provide the RTDB payload printing info and other helper functions. -#include "addons/RTDBHelper.h" - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. Define the API Key */ -#define API_KEY "API_KEY" - -/* 3. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 4. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -//Define Firebase Data objects -FirebaseData fbdo1; -FirebaseData fbdo2; - -FirebaseAuth auth; -FirebaseConfig config; - -unsigned long sendDataPrevMillis1; - -uint16_t count1; - -String path = ""; - -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(); - - /* Assign the api key (required) */ - config.api_key = API_KEY; - - /* Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo1.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo1.setResponseSize(1024); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo2.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo2.setResponseSize(1024); - - Serial.println("------------------------------------"); - Serial.println("Begin stream 1..."); - String node = path + "/Stream/data1"; - if (!Firebase.RTDB.beginStream(&fbdo2, node.c_str())) - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo2.errorReason()); - Serial.println(); - } - else - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } -} - -void loop() -{ - - if (!Firebase.ready()) - return; - - if (!Firebase.RTDB.readStream(&fbdo2)) - { - Serial.println("Can't read stream data"); - Serial.println("REASON: " + fbdo2.errorReason()); - Serial.println(); - } - - if (fbdo2.streamTimeout()) - { - Serial.println("Stream timeout, resume streaming..."); - Serial.println(); - } - - if (fbdo2.streamAvailable()) - { - Serial.println("------------------------------------"); - Serial.println("Stream Data Available..."); - Serial.println("STREAM PATH: " + fbdo2.streamPath()); - Serial.println("EVENT PATH: " + fbdo2.dataPath()); - Serial.println("DATA TYPE: " + fbdo2.dataType()); - Serial.println("EVENT TYPE: " + fbdo2.eventType()); - Serial.print("VALUE: "); - printResult(fbdo2); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - - if (millis() - sendDataPrevMillis1 > 15000) - { - sendDataPrevMillis1 = millis(); - - //Create demo data - uint8_t data[256]; - for (int i = 0; i < 256; i++) - data[i] = i; - data[255] = rand(); - - Serial.println("------------------------------------"); - Serial.println("Set Blob Data 1..."); - String Path = path + "/Stream/data1"; - if (Firebase.RTDB.setBlob(&fbdo1, Path.c_str(), data, sizeof(data))) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo1.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - FirebaseJson json; - json.add("data1-1", count1).add("data1-2", count1 + 1).add("data1-3", count1 + 2); - Serial.println("------------------------------------"); - Serial.println("Update Data 1..."); - Path = path + "/Stream/data1"; - if (Firebase.RTDB.updateNode(&fbdo1, Path.c_str(), &json)) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo1.dataPath()); - Serial.println("TYPE: " + fbdo1.dataType()); - Serial.print("VALUE: "); - printResult(fbdo1); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo1.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.print("Free Heap: "); - Serial.println(ESP.getFreeHeap()); - Serial.println(); - - count1 += 3; - } -} diff --git a/examples/RTDB/Dynamic_FirebaseData/Dynamic_FirebasseData.ino b/examples/RTDB/Dynamic_FirebaseData/Dynamic_FirebasseData.ino deleted file mode 100644 index 0fb08a29c..000000000 --- a/examples/RTDB/Dynamic_FirebaseData/Dynamic_FirebasseData.ino +++ /dev/null @@ -1,243 +0,0 @@ - -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -//This example shows how to dynamic allocated the Firebase Data object and deallocated it for release the memory when no further use. - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" -//Provide the RTDB payload printing info and other helper functions. -#include "addons/RTDBHelper.h" - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. Define the API Key */ -#define API_KEY "API_KEY" - -/* 3. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 4. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -FirebaseAuth auth; -FirebaseConfig config; - -//Define FirebaseESP8266 data object -FirebaseData *fbdo1 = new FirebaseData(); -FirebaseData *fbdo2 = new FirebaseData(); - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -//Important information -//In ESP8266 Aruino Core SDK v3.x.x -//The free heap is significantly reduced as much as 5-6 kB from v2.7.4. -//This may lead to out of memory sitation when two Firebase Data objects are used simultaneously (when sessions connected). -//Minimize the reserved memory for BearSSL will gain the free heap a bit but may not enough for your usage. -//You can stay with Core SDK v2.7.4 until this memory issue was solve in the Core SDK. -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -unsigned long sendDataPrevMillis = 0; - -String path = "/Test/Stream"; - -int count = 0; - -bool deallocated = false; - -void streamCallback(FirebaseStream data) -{ - - Serial.println("Stream Data1 available..."); - Serial.println("STREAM PATH: " + data.streamPath()); - Serial.println("EVENT PATH: " + data.dataPath()); - Serial.println("DATA TYPE: " + data.dataType()); - Serial.println("EVENT TYPE: " + data.eventType()); - Serial.print("VALUE: "); - printResult(data); //see addons/RTDBHelper.h - Serial.println(); -} - -void streamTimeoutCallback(bool timeout) -{ - if (timeout) - { - Serial.println(); - Serial.println("Stream timeout, resume streaming..."); - Serial.println(); - } -} - -void setup() -{ - - Serial.begin(115200); - - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); - Serial.print("Connecting to Wi-Fi"); - while (WiFi.status() != WL_CONNECTED) - { - Serial.print("."); - delay(300); - } - Serial.println(); - Serial.print("Connected with IP: "); - Serial.println(WiFi.localIP()); - Serial.println(); - - /* Assign the api key (required) */ - config.api_key = API_KEY; - - /* Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo1->setBSSLBufferSize(1024, 512); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo1->setResponseSize(1024); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo2->setBSSLBufferSize(1024, 512); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo2->setResponseSize(1024); - - if (!Firebase.RTDB.beginStream(fbdo1, path.c_str())) - { - Serial.println("------------------------------------"); - Serial.println("Can't begin stream connection..."); - Serial.println("REASON: " + fbdo1->errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Firebase.RTDB.setStreamCallback(fbdo1, streamCallback, streamTimeoutCallback); -} - -void loop() -{ - if (Firebase.ready() && (millis() - sendDataPrevMillis > 5000 || sendDataPrevMillis == 0)) - { - count++; - sendDataPrevMillis = millis(); - - if (count == 10) - { - deallocated = false; - - Serial.println("Reallocate the Firebase Data objects again after 10 times Firebasse call"); - - fbdo1 = new FirebaseData(); - fbdo2 = new FirebaseData(); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo1->setBSSLBufferSize(1024, 512); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo1->setResponseSize(1024); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo2->setBSSLBufferSize(1024, 512); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo2->setResponseSize(1024); - - if (!Firebase.RTDB.beginStream(fbdo1, path.c_str())) - { - Serial.println("------------------------------------"); - Serial.println("Can't begin stream connection..."); - Serial.println("REASON: " + fbdo1->errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Firebase.RTDB.setStreamCallback(fbdo1, streamCallback, streamTimeoutCallback); - - count = 0; - } - - if (!deallocated) - Serial.print("Free Heap after allocated the Firebase Data objects: "); - else - Serial.print("Free Heap after deallocated the Firebase Data objects: "); - - Serial.println(ESP.getFreeHeap()); - - delay(0); - - if (deallocated) - return; - - Serial.println("------------------------------------"); - Serial.println("Set Int..."); - String Path = path + "/Int"; - - if (Firebase.RTDB.set(fbdo2, Path.c_str(), count)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo2->errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - if (count == 5) - { - Serial.println("Deallocate the Firebase Data objects after 3 times Firebasse call"); - - deallocated = true; - - //Need to stop the stream to prevent the readStream and callback to be called after objects deallocation - Firebase.RTDB.endStream(fbdo1); - Firebase.RTDB.removeStreamCallback(fbdo1); - - //Deallocate - delete fbdo1; - delete fbdo2; - - fbdo1 = nullptr; - fbdo2 = nullptr; - } - } -} \ No newline at end of file diff --git a/examples/RTDB/ETag/ETag.ino b/examples/RTDB/ETag/ETag.ino index b23b8ddbe..8fb16d470 100644 --- a/examples/RTDB/ETag/ETag.ino +++ b/examples/RTDB/ETag/ETag.ino @@ -65,6 +65,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -78,17 +80,13 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); + Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); } void loop() @@ -97,111 +95,25 @@ void loop() { taskCompleted = true; - String path = "/Test"; - String ETag = ""; String wrong_ETag = "ANY_WRONG_ETag"; - Serial.println("------------------------------------"); - Serial.println("Set integer without ETag test..."); - String Path = path + "/Int/Data"; + Serial.printf("Set int... %s\n", Firebase.RTDB.setInt(&fbdo, "/test/int/data", 100) ? "ok" : fbdo.errorReason().c_str()); - if (Firebase.RTDB.setInt(&fbdo, Path.c_str(), 100)) + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.println("CURRENT ETag: " + fbdo.ETag()); + Serial.printf("etag, %s\n\n", fbdo.ETag().c_str()); ETag = fbdo.ETag(); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); } - Serial.println("------------------------------------"); - Serial.println("Set integer with valid ETag test..."); + Serial.printf("Set int with valid ETag... %s\n", Firebase.RTDB.setInt(&fbdo, "/test/int/data", 200, ETag.c_str()) ? "ok" : fbdo.errorReason().c_str()); - if (Firebase.RTDB.setInt(&fbdo, Path.c_str(), 200)) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.println("CURRENT ETag: " + fbdo.ETag()); - ETag = fbdo.ETag(); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Set integer with wrong ETag test..."); + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) + Serial.printf("etag, %s\n\n", fbdo.ETag().c_str()); - if (Firebase.RTDB.setInt(&fbdo, Path.c_str(), 300, wrong_ETag.c_str())) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.println("ETag: " + fbdo.ETag()); - ETag = fbdo.ETag(); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - - //If provided ETag is not match to current ETag (httpCode 412) - if (fbdo.httpCode() == 412) - { - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.println("PROVIDED ETag: " + wrong_ETag); - Serial.println("CURRENT ETag: " + fbdo.ETag()); - ETag = fbdo.ETag(); - Serial.print("CURRENT VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - } - - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("Set int with invalid ETag... %s\n", Firebase.RTDB.setInt(&fbdo, "/test/int/data", 200, wrong_ETag.c_str()) ? "ok" : fbdo.errorReason().c_str()); - Serial.println("------------------------------------"); - Serial.println("Delete node with wrong ETag test..."); - if (Firebase.RTDB.deleteNode(&fbdo, Path.c_str(), wrong_ETag.c_str())) - { - - Serial.println("PASSED"); - Serial.println("CURRENT ETag: " + fbdo.ETag()); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) + Serial.printf("etag, %s\n\n", fbdo.ETag().c_str()); } } diff --git a/examples/RTDB/FastSend/FastSend.ino b/examples/RTDB/FastSend/FastSend.ino index ba040b987..a82d021c4 100644 --- a/examples/RTDB/FastSend/FastSend.ino +++ b/examples/RTDB/FastSend/FastSend.ino @@ -40,19 +40,18 @@ #define USER_EMAIL "USER_EMAIL" #define USER_PASSWORD "USER_PASSWORD" -// Define Firebase Data object +//Define Firebase Data object FirebaseData fbdo; FirebaseAuth auth; FirebaseConfig config; -String path = "/Test/Async"; - unsigned long sendDataPrevMillis = 0; int count = 0; -void setup() { +void setup() +{ Serial.begin(115200); Serial.println(); @@ -60,7 +59,8 @@ void setup() { WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("Connecting to Wi-Fi"); - while (WiFi.status() != WL_CONNECTED) { + while (WiFi.status() != WL_CONNECTED) + { Serial.print("."); delay(300); } @@ -69,6 +69,8 @@ void setup() { Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -80,36 +82,34 @@ void setup() { config.database_url = DATABASE_URL; /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; // see addons/TokenHelper.h + config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h + + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); -#if defined(ESP8266) - // Set the size of WiFi rx/tx buffers in the case where we want to work with - // large data. fbdo.setBSSLBufferSize(512, 2048); -#endif - - // Set the size of HTTP response buffers in the case where we want to work - // with large data. - fbdo.setResponseSize(1024); } void loop() { - if (Firebase.ready() && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)) - { - sendDataPrevMillis = millis(); + if (Firebase.ready() && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)) + { + sendDataPrevMillis = millis(); - Serial.println("Set Int Async..."); + Serial.print("Set int async... "); - for (size_t i = 0; i < 10; i++) - { - //The response is ignored in this async function, it may return true as long as the connection is established. - //The purpose for this async function is to set, push and update data instantly. - Firebase.RTDB.setIntAsync(&fbdo, path.c_str(), count); - count++; - } + for (size_t i = 0; i < 10; i++) + { + //The response is ignored in this async function, it may return true as long as the connection is established. + //The purpose for this async function is to set, push and update data instantly. + Firebase.RTDB.setIntAsync(&fbdo, "/test/int", count); + count++; } + Serial.println("ok"); + } } diff --git a/examples/RTDB/File/File.ino b/examples/RTDB/File/File.ino deleted file mode 100644 index 7b238132f..000000000 --- a/examples/RTDB/File/File.ino +++ /dev/null @@ -1,292 +0,0 @@ -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -//This example shows how to store and read binary data from file on SD card to database. - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" -//Provide the RTDB payload printing info and other helper functions. -#include "addons/RTDBHelper.h" - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. Define the API Key */ -#define API_KEY "API_KEY" - -/* 3. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 4. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -//Define Firebase Data object -FirebaseData fbdo; - -FirebaseAuth auth; -FirebaseConfig config; - -bool taskCompleted = false; - -String path = "/Test"; - -File file; - -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(); - - /* Assign the api key (required) */ - config.api_key = API_KEY; - - /* Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - //Mount SD card -#if defined(ESP32) - if (!Firebase.sdBegin(13, 14, 2, 15)) //SS, SCK,MISO, MOSI -#elif defined(ESP8266) - if (!Firebase.sdBegin(15)) //SS -#endif - { - Serial.println("SD Card mounted failed"); - return; - } - - //Delete demo files - if (SD.exists("/file1.txt")) - SD.remove("/file1.txt"); - - if (SD.exists("/file2.txt")) - SD.remove("/file2.txt"); - - if (SD.exists("/file3.txt")) - SD.remove("/file3.txt"); - - Serial.println("------------------------------------"); - Serial.println("Set file data test..."); - - //Write demo data to file - file = SD.open("/file1.txt", FILE_WRITE); - uint8_t v = 0; - for (int i = 0; i < 512; i++) - { - file.write(v); - v++; - } - - file.close(); -} - -void loop() -{ - if (Firebase.ready() && !taskCompleted) - { - taskCompleted = true; - - //In case of Root CA was set, set this option to false to disable low memory for secured mode BearSSL to support large file data - //Firebase.lowMemBSSL(false); - - String Path = path + "/Binary/File/data"; - - //Set file (read file from SD card and set to database) - //File name must be in 8.3 DOS format (max. 8 bytes file name and 3 bytes file extension) - if (Firebase.RTDB.setFile(&fbdo, mem_storage_type_sd, Path.c_str(), "/file1.txt")) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Get file data test..."); - - //Get file (download file to SD card) - //File name must be in 8.3 DOS format (max. 8 bytes file name and 3 bytes file extension) - if (Firebase.RTDB.getFile(&fbdo, mem_storage_type_sd, Path.c_str(), "/file2.txt")) - { - - Serial.println("PASSED"); - Serial.println("DATA"); - -#if defined(ESP32) - Firebase.sdBegin(13, 14, 2, 15); //SS, SCK,MISO, MOSI -#elif defined(ESP8266) - Firebase.sdBegin(15); //SS -#endif - - //Readout the downloaded file - file = SD.open("/file2.txt", FILE_READ); - int i = 0; - - while (file.available()) - { - if (i > 0 && i % 16 == 0) - Serial.println(); - - uint8_t v = file.read(); - - if (v < 16) - Serial.print("0"); - - Serial.print(v, HEX); - Serial.print(" "); - i++; - } - Serial.println(); - Serial.println("------------------------------------"); - Serial.println(); - file.close(); - } - else - { - - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Append file data test..."); - - if (SD.exists("/file1.txt")) - SD.remove("/file1.txt"); - - //Write demo data to file - file = SD.open("/file1.txt", FILE_WRITE); - for (int i = 255; i >= 0; i--) - file.write((uint8_t)i); - - file.close(); - - Path = path + "/Binary/File/Logs"; - - //Append file data to database - //File name must be in 8.3 DOS format (max. 8 bytes file name and 3 bytes file extension) - if (Firebase.RTDB.pushFile(&fbdo, mem_storage_type_sd, Path.c_str(), "/file1.txt")) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("PUSH NAME: " + fbdo.pushName()); - Serial.println("------------------------------------"); - - Serial.println(); - - Serial.println("------------------------------------"); - Serial.println("Get appended file data test..."); - - Path = path + "/Binary/File/Logs/" + fbdo.pushName(); - - //Get the recently appended file (download file to SD card) - //File name must be in 8.3 DOS format (max. 8 bytes file name and 3 bytes file extension) - if (Firebase.RTDB.getFile(&fbdo, mem_storage_type_sd, Path.c_str(), "/file3.txt")) - { - - Serial.println("PASSED"); - Serial.println("DATA"); - -#if defined(ESP32) - Firebase.sdBegin(13, 14, 2, 15); //SS, SCK,MISO, MOSI -#elif defined(ESP8266) - Firebase.sdBegin(15); //SS -#endif - - //Readout the downloaded file - file = SD.open("/file3.txt", FILE_READ); - int i = 0; - int idx = 0; - - while (file.available()) - { - i = file.read(); - if (i < 16) - Serial.print("0"); - - Serial.print(i, HEX); - Serial.print(" "); - - if (idx > 0 && (idx + 1) % 16 == 0) - Serial.println(); - idx++; - } - Serial.println(); - Serial.println("------------------------------------"); - Serial.println(); - file.close(); - } - else - { - - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - } -} diff --git a/examples/RTDB/File/Flash/Flash.ino b/examples/RTDB/File/Flash/Flash.ino new file mode 100644 index 000000000..075939748 --- /dev/null +++ b/examples/RTDB/File/Flash/Flash.ino @@ -0,0 +1,161 @@ +/** + * Created by K. Suwatchai (Mobizt) + * + * Email: k_suwatchai@hotmail.com + * + * Github: https://github.com/mobizt + * + * Copyright (c) 2021 mobizt + * +*/ + +//This example shows how to store and read binary data from file on Flash memory to database. + +#if defined(ESP32) +#include +#elif defined(ESP8266) +#include +#endif +#include + +//Provide the token generation process info. +#include "addons/TokenHelper.h" +//Provide the RTDB payload printing info and other helper functions. +#include "addons/RTDBHelper.h" + +/* 1. Define the WiFi credentials */ +#define WIFI_SSID "WIFI_AP" +#define WIFI_PASSWORD "WIFI_PASSWORD" + +/* 2. Define the API Key */ +#define API_KEY "API_KEY" + +/* 3. Define the RTDB URL */ +#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app + +/* 4. Define the user Email and password that alreadey registerd or added in your project */ +#define USER_EMAIL "USER_EMAIL" +#define USER_PASSWORD "USER_PASSWORD" + +//Define Firebase Data object +FirebaseData fbdo; + +FirebaseAuth auth; +FirebaseConfig config; + +bool taskCompleted = false; + +fs::File file; + +/* + +To use LittleFS file system instead of SPIFFS. add #define USE_LITTLEFS to FirebaseFS.h +and replace all SPIFFS class in this sketch with LittleFS + +*/ + +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(); + + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + + /* Assign the api key (required) */ + config.api_key = API_KEY; + + /* Assign the user sign in credentials */ + auth.user.email = USER_EMAIL; + auth.user.password = USER_PASSWORD; + + /* Assign the RTDB URL (required) */ + config.database_url = DATABASE_URL; + + /* Assign the callback function for the long running token generation task */ + config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h + + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; + + Firebase.begin(&config, &auth); + + Firebase.reconnectWiFi(true); + + if (!DEFAULT_FLASH_FS.begin()) + { + Serial.println("SPIFFS/LittleFS initialization failed."); + Serial.println("For Arduino IDE, please select flash size from menu Tools > Flash size"); + return; + } + + //Delete demo files + if (DEFAULT_FLASH_FS.exists("/file1.txt")) + DEFAULT_FLASH_FS.remove("/file1.txt"); + + if (DEFAULT_FLASH_FS.exists("/file2.txt")) + DEFAULT_FLASH_FS.remove("/file2.txt"); + + //Write demo data to file + file = DEFAULT_FLASH_FS.open("/file1.txt", "w"); + uint8_t v = 0; + for (int i = 0; i < 512; i++) + { + file.write(v); + v++; + } + + file.close(); +} + +void loop() +{ + if (Firebase.ready() && !taskCompleted) + { + taskCompleted = true; + + //File name must be in 8.3 DOS format (max. 8 bytes file name and 3 bytes file extension) + Serial.printf("Set file... %s\n", Firebase.RTDB.setFile(&fbdo, mem_storage_type_flash, "test/file/data", "/file1.txt") ? "ok" : fbdo.errorReason().c_str()); + + Serial.printf("Get file... %s\n", Firebase.RTDB.getFile(&fbdo, mem_storage_type_flash, "test/file/data", "/file2.txt") ? "ok" : fbdo.errorReason().c_str()); + + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) + { + //Readout the downloaded file + file = DEFAULT_FLASH_FS.open("/file2.txt", "r"); + int i = 0; + + while (file.available()) + { + if (i > 0 && i % 16 == 0) + Serial.println(); + + uint8_t v = file.read(); + + if (v < 16) + Serial.print("0"); + + Serial.print(v, HEX); + Serial.print(" "); + i++; + } + + Serial.println(); + file.close(); + } + } +} diff --git a/examples/RTDB/File/SD/SD.ino b/examples/RTDB/File/SD/SD.ino new file mode 100644 index 000000000..930f4a629 --- /dev/null +++ b/examples/RTDB/File/SD/SD.ino @@ -0,0 +1,165 @@ +/** + * Created by K. Suwatchai (Mobizt) + * + * Email: k_suwatchai@hotmail.com + * + * Github: https://github.com/mobizt + * + * Copyright (c) 2021 mobizt + * +*/ + +//This example shows how to store and read binary data from file on SD card to database. + +#if defined(ESP32) +#include +#elif defined(ESP8266) +#include +#endif +#include + +//Provide the token generation process info. +#include "addons/TokenHelper.h" +//Provide the RTDB payload printing info and other helper functions. +#include "addons/RTDBHelper.h" + +/* 1. Define the WiFi credentials */ +#define WIFI_SSID "WIFI_AP" +#define WIFI_PASSWORD "WIFI_PASSWORD" + +/* 2. Define the API Key */ +#define API_KEY "API_KEY" + +/* 3. Define the RTDB URL */ +#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app + +/* 4. Define the user Email and password that alreadey registerd or added in your project */ +#define USER_EMAIL "USER_EMAIL" +#define USER_PASSWORD "USER_PASSWORD" + +//Define Firebase Data object +FirebaseData fbdo; + +FirebaseAuth auth; +FirebaseConfig config; + +bool taskCompleted = false; + +File file; + +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(); + + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + + /* Assign the api key (required) */ + config.api_key = API_KEY; + + /* Assign the user sign in credentials */ + auth.user.email = USER_EMAIL; + auth.user.password = USER_PASSWORD; + + /* Assign the RTDB URL (required) */ + config.database_url = DATABASE_URL; + + /* Assign the callback function for the long running token generation task */ + config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h + + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; + + Firebase.begin(&config, &auth); + + Firebase.reconnectWiFi(true); + + //Mount SD card +#if defined(ESP32) + if (!Firebase.sdBegin(13, 14, 2, 15)) //SS, SCK,MISO, MOSI +#elif defined(ESP8266) + if (!Firebase.sdBegin(15)) //SS +#endif + { + Serial.println("SD Card mounted failed"); + return; + } + + //Delete demo files + if (DEFAULT_SD_FS.exists("/file1.txt")) + DEFAULT_SD_FS.remove("/file1.txt"); + + if (DEFAULT_SD_FS.exists("/file2.txt")) + DEFAULT_SD_FS.remove("/file2.txt"); + + //Write demo data to file + file = DEFAULT_SD_FS.open("/file1.txt", FILE_WRITE); + uint8_t v = 0; + for (int i = 0; i < 512; i++) + { + file.write(v); + v++; + } + + file.close(); +} + +void loop() +{ + if (Firebase.ready() && !taskCompleted) + { + taskCompleted = true; + + //File name must be in 8.3 DOS format (max. 8 bytes file name and 3 bytes file extension) + Serial.printf("Set file... %s\n", Firebase.RTDB.setFile(&fbdo, mem_storage_type_sd, "test/file/data", "/file1.txt") ? "ok" : fbdo.errorReason().c_str()); + + Serial.printf("Get file... %s\n", Firebase.RTDB.getFile(&fbdo, mem_storage_type_sd, "test/file/data", "/file2.txt") ? "ok" : fbdo.errorReason().c_str()); + + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) + { + +#if defined(ESP32) + Firebase.sdBegin(13, 14, 2, 15); //SS, SCK,MISO, MOSI +#elif defined(ESP8266) + Firebase.sdBegin(15); //SS +#endif + + //Readout the downloaded file + file = DEFAULT_SD_FS.open("/file2.txt", FILE_READ); + int i = 0; + + while (file.available()) + { + if (i > 0 && i % 16 == 0) + Serial.println(); + + uint8_t v = file.read(); + + if (v < 16) + Serial.print("0"); + + Serial.print(v, HEX); + Serial.print(" "); + i++; + } + + Serial.println(); + file.close(); + } + } +} diff --git a/examples/RTDB/File_Flash_Memory/File_Flash_Memory.ino b/examples/RTDB/File_Flash_Memory/File_Flash_Memory.ino deleted file mode 100644 index 1ba88330b..000000000 --- a/examples/RTDB/File_Flash_Memory/File_Flash_Memory.ino +++ /dev/null @@ -1,279 +0,0 @@ -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -//This example shows how to store and read binary data from file on Flash memory to database. - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" -//Provide the RTDB payload printing info and other helper functions. -#include "addons/RTDBHelper.h" - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. Define the API Key */ -#define API_KEY "API_KEY" - -/* 3. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 4. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -//Define Firebase Data object -FirebaseData fbdo; - -FirebaseAuth auth; -FirebaseConfig config; - -bool taskCompleted = false; - -String path = "/Test"; - -fs::File file; - -/* - -To use LittleFS file system instead of SPIFFS. add #define USE_LITTLEFS to FirebaseFS.h -and replace all SPIFFS class in this sketch with LittleFS - -*/ - -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(); - - /* Assign the api key (required) */ - config.api_key = API_KEY; - - /* Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - if (!SPIFFS.begin()) - { - Serial.println("SPIFFS initialization failed."); - Serial.println("For Arduino IDE, please select flash size from menu Tools > Flash size"); - return; - } - - //Delete demo files - if (SPIFFS.exists("/file1.txt")) - SPIFFS.remove("/file1.txt"); - - if (SPIFFS.exists("/file2.txt")) - SPIFFS.remove("/file2.txt"); - - if (SPIFFS.exists("/file3.txt")) - SPIFFS.remove("/file3.txt"); - - Serial.println("------------------------------------"); - Serial.println("Set file data test..."); - - //Write demo data to file - file = SPIFFS.open("/file1.txt", "w"); - uint8_t v = 0; - for (int i = 0; i < 512; i++) - { - file.write(v); - v++; - } - - file.close(); - -} - -void loop() -{ - if (Firebase.ready() && !taskCompleted) - { - taskCompleted = true; - - //In case of Root CA was set, set this option to false to disable low memory for secured mode BearSSL to support large file data - //Firebase.lowMemBSSL(false); - String Path = path + "/Binary/File/data"; - - //Set file (read file from Flash memory and set to database) - if (Firebase.RTDB.setFile(&fbdo, mem_storage_type_flash, Path.c_str(), "/file1.txt")) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Get file data test..."); - - //Get file (download file to Flash memory) - if (Firebase.RTDB.getFile(&fbdo, mem_storage_type_flash, Path.c_str(), "/file2.txt")) - { - - Serial.println("PASSED"); - Serial.println("DATA"); - - //Readout the downloaded file - file = SPIFFS.open("/file2.txt", "r"); - int i = 0; - - while (file.available()) - { - if (i > 0 && i % 16 == 0) - Serial.println(); - - uint8_t v = file.read(); - - if (v < 16) - Serial.print("0"); - - Serial.print(v, HEX); - Serial.print(" "); - i++; - } - Serial.println(); - Serial.println("------------------------------------"); - Serial.println(); - file.close(); - } - else - { - - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Append file data test..."); - - if (SPIFFS.exists("/file1.txt")) - SPIFFS.remove("/file1.txt"); - - //Write demo data to file - file = SPIFFS.open("/file1.txt", "w"); - for (int i = 255; i >= 0; i--) - file.write((uint8_t)i); - - file.close(); - - Path = path + "/Binary/File/Logs"; - - //Append file data to database - if (Firebase.RTDB.pushFile(&fbdo, mem_storage_type_flash, Path.c_str(), "/file1.txt")) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("PUSH NAME: " + fbdo.pushName()); - Serial.println("------------------------------------"); - - Serial.println(); - - Serial.println("------------------------------------"); - Serial.println("Get appended file data test..."); - - Path = path + "/Binary/File/Logs/" + fbdo.pushName(); - - //Get the recently appended file (download file to Flash memory) - if (Firebase.RTDB.getFile(&fbdo, mem_storage_type_flash, Path.c_str(), "/file3.txt")) - { - - Serial.println("PASSED"); - Serial.println("DATA"); - - //Readout the downloaded file - file = SPIFFS.open("/file3.txt", "r"); - int i = 0; - int idx = 0; - - while (file.available()) - { - i = file.read(); - if (i < 16) - Serial.print("0"); - - Serial.print(i, HEX); - Serial.print(" "); - - if (idx > 0 && (idx + 1) % 16 == 0) - Serial.println(); - idx++; - } - Serial.println(); - Serial.println("------------------------------------"); - Serial.println(); - file.close(); - } - else - { - - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.fileTransferError()); - Serial.println("------------------------------------"); - Serial.println(); - } - } -} diff --git a/examples/RTDB/FireSense/Analog_Read/Analog_Read.ino b/examples/RTDB/FireSense/AnalogRead/AnalogRead.ino similarity index 96% rename from examples/RTDB/FireSense/Analog_Read/Analog_Read.ino rename to examples/RTDB/FireSense/AnalogRead/AnalogRead.ino index 2a9d5bbf0..e2dcd555a 100644 --- a/examples/RTDB/FireSense/Analog_Read/Analog_Read.ino +++ b/examples/RTDB/FireSense/AnalogRead/AnalogRead.ino @@ -93,7 +93,7 @@ /* 5. Define the database secret in case we need to access database rules*/ #define DATABASE_SECRET "DATABASE_SECRET" - +//Define Firebase Data object FirebaseData fbdo1; FirebaseData fbdo2; @@ -198,6 +198,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; diff --git a/examples/RTDB/FireSense/Automatic_Plant_Watering/Automatic_Plant_Watering.ino b/examples/RTDB/FireSense/AutomaticPlantWatering/AutomaticPlantWatering.ino similarity index 96% rename from examples/RTDB/FireSense/Automatic_Plant_Watering/Automatic_Plant_Watering.ino rename to examples/RTDB/FireSense/AutomaticPlantWatering/AutomaticPlantWatering.ino index 523710df9..af3b48c70 100644 --- a/examples/RTDB/FireSense/Automatic_Plant_Watering/Automatic_Plant_Watering.ino +++ b/examples/RTDB/FireSense/AutomaticPlantWatering/AutomaticPlantWatering.ino @@ -98,6 +98,7 @@ /* 5. Define the database secret in case we need to access database rules*/ #define DATABASE_SECRET "DATABASE_SECRET" +//Define Firebase Data object FirebaseData fbdo1; FirebaseData fbdo2; @@ -173,6 +174,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; diff --git a/examples/RTDB/FireSense/Blink/Blink.ino b/examples/RTDB/FireSense/Blink/Blink.ino index 77c6656f8..68438b4a2 100644 --- a/examples/RTDB/FireSense/Blink/Blink.ino +++ b/examples/RTDB/FireSense/Blink/Blink.ino @@ -91,6 +91,7 @@ /* 5. Define the database secret in case we need to access database rules*/ #define DATABASE_SECRET "DATABASE_SECRET" +//Define Firebase Data object FirebaseData fbdo1; FirebaseAuth auth; @@ -160,6 +161,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; diff --git a/examples/RTDB/FireSense/Sensors/Sensors.ino b/examples/RTDB/FireSense/Sensors/Sensors.ino index 633e8eed4..fb9cb036f 100644 --- a/examples/RTDB/FireSense/Sensors/Sensors.ino +++ b/examples/RTDB/FireSense/Sensors/Sensors.ino @@ -88,6 +88,7 @@ /* 5. Define the database secret in case we need to access database rules*/ #define DATABASE_SECRET "DATABASE_SECRET" +//Define Firebase Data object FirebaseData fbdo1; FirebaseData fbdo2; @@ -176,6 +177,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; diff --git a/examples/RTDB/Line_Notify/Line_Notify.ino b/examples/RTDB/Line_Notify/Line_Notify.ino deleted file mode 100644 index 4f57824d1..000000000 --- a/examples/RTDB/Line_Notify/Line_Notify.ino +++ /dev/null @@ -1,272 +0,0 @@ -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -//Example showed how to pause Firebase and use shared WiFi Client to send Line message. - -/* - * This shows how to pause the Firbase and send LINE Notify. - * Install Line Notify Arduino library for ESP8266 and ESP32 https://github.com/mobizt/ESP-Line-Notify - * - * More about Line Notify service https://notify-bot.line.me/en/ - */ - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" -//Provide the RTDB payload printing info and other helper functions. -#include "addons/RTDBHelper.h" - -#include - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. Define the API Key */ -#define API_KEY "API_KEY" - -/* 3. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 4. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -//Define Firebase Data object -FirebaseData fbdo; - -FirebaseAuth auth; -FirebaseConfig config; - -String path = "/Test"; - -unsigned long sendDataPrevMillis = 0; - -unsigned long sendMessagePrevMillis = 0; - -uint16_t count = 0; - -/* Define the LineNotifyClient object */ -LineNotiFyClient client; - -/* Function to print the sending result via Serial (optional) */ -void LineNotifyResult(LineNotifySendingResult result); - -/* The sending callback function (optional) */ -void LineNotifyCallback(LineNotifySendingResult result); - -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(); - - /* Assign the api key (required) */ - config.api_key = API_KEY; - - /* Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - String Path = path + "/Stream/String"; - - Serial.println("------------------------------------"); - Serial.println("Begin stream..."); - if (!Firebase.RTDB.beginStream(&fbdo, Path.c_str())) - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } -} - -void loop() -{ - - if (Firebase.ready() && (millis() - sendDataPrevMillis > 30000 || sendDataPrevMillis == 0)) - { - sendDataPrevMillis = millis(); - count++; - - Serial.println("------------------------------------"); - Serial.println("Set Data..."); - String Path = path + "/Stream/String"; - String value = "Hello World! " + String(count); - if (Firebase.RTDB.set(&fbdo, Path.c_str(), value.c_str())) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - //pause Firebase - fbdo.pauseFirebase(true); - - Serial.println("------------------------------------"); - - client.reconnect_wifi = true; - - Serial.println("Sending Line Notify message..."); - - client.token = "Your Line Notify Access Token"; - client.message = "Hello world"; - - //Assign the Line Notify Sending Callback function. - client.sendingg_callback = LineNotifyCallback; - - LineNotifySendingResult result = LineNotify.send(client); - - //Print the Line Notify sending result. - LineNotifyResult(result); - - Serial.println("--------------------------------"); - Serial.println(); - - //resume Firebase - fbdo.pauseFirebase(false); - } - - if (Firebase.ready()) - { - - if (!Firebase.RTDB.readStream(&fbdo)) - { - Serial.println("------------------------------------"); - Serial.println("Read stream..."); - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - if (fbdo.streamTimeout()) - { - Serial.println("Stream timeout, resume streaming..."); - Serial.println(); - } - - if (fbdo.streamAvailable()) - { - Serial.println("------------------------------------"); - Serial.println("Stream Data available..."); - Serial.println("STREAM PATH: " + fbdo.streamPath()); - Serial.println("EVENT PATH: " + fbdo.dataPath()); - Serial.println("DATA TYPE: " + fbdo.dataType()); - Serial.println("EVENT TYPE: " + fbdo.eventType()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - } -} - -/* Function to print the sending result via Serial */ -void LineNotifyResult(LineNotifySendingResult result) -{ - if (result.status == LineNotify_Sending_Success) - { - Serial.printf("Status: %s\n", "success"); - Serial.printf("Text limit: %d\n", result.quota.text.limit); - Serial.printf("Text remaining: %d\n", result.quota.text.remaining); - Serial.printf("Image limit: %d\n", result.quota.image.limit); - Serial.printf("Image remaining: %d\n", result.quota.image.remaining); - Serial.printf("Reset: %d\n", result.quota.reset); - } - else if (result.status == LineNotify_Sending_Error) - { - Serial.printf("Status: %s\n", "error"); - Serial.printf("error code: %d\n", result.error.code); - Serial.printf("error msg: %s\n", result.error.message.c_str()); - } -} - -/* The sending callback function (optional) */ -void LineNotifyCallback(LineNotifySendingResult result) -{ - if (result.status == LineNotify_Sending_Begin) - { - Serial.println("Sending begin"); - } - else if (result.status == LineNotify_Sending_Upload) - { - Serial.printf("Uploaded %s, %d%s\n", result.file_name.c_str(), (int)result.progress, "%"); - } - else if (result.status == LineNotify_Sending_Success) - { - Serial.println("Sending success\n\n"); - Serial.printf("Text limit: %d\n", result.quota.text.limit); - Serial.printf("Text remaining: %d\n", result.quota.text.remaining); - Serial.printf("Image limit: %d\n", result.quota.image.limit); - Serial.printf("Image remaining: %d\n", result.quota.image.remaining); - Serial.printf("Reset: %d\n", result.quota.reset); - } - else if (result.status == LineNotify_Sending_Error) - { - Serial.println("Sending failed\n\n"); - Serial.printf("error code: %d\n", result.error.code); - Serial.printf("error msg: %s\n", result.error.message.c_str()); - } -} diff --git a/examples/RTDB/Priority/Priority.ino b/examples/RTDB/Priority/Priority.ino index 5dfe18561..0ee51fdc0 100644 --- a/examples/RTDB/Priority/Priority.ino +++ b/examples/RTDB/Priority/Priority.ino @@ -40,7 +40,7 @@ #define USER_EMAIL "USER_EMAIL" #define USER_PASSWORD "USER_PASSWORD" -//Define FirebaseESP8266 data object +//Define Firebase Data object FirebaseData fbdo; FirebaseAuth auth; @@ -69,6 +69,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -82,16 +84,13 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + Firebase.begin(&config, &auth); - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); + Firebase.reconnectWiFi(true); } void loop() @@ -100,11 +99,6 @@ void loop() { taskCompleted = true; - String path = "/Test"; - - Serial.println("------------------------------------"); - Serial.println("Set priority test..."); - for (int i = 0; i < 15; i++) { @@ -113,53 +107,19 @@ void loop() String val = "value_" + String(i + 1); json.clear(); json.set(key, val); - String Path = path + "/Items/priority_" + String(15 - i); - - if (Firebase.RTDB.setJSON(&fbdo, Path.c_str(), &json, priority)) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.println("CURRENT ETag: " + fbdo.ETag()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + String Path = "/test/items/priority_" + String(15 - i); + + Serial.printf("Set json with proprity... %s\n", Firebase.RTDB.setJSONAsync(&fbdo, Path.c_str(), &json, priority) ? "ok" : fbdo.errorReason().c_str()); } - //Qury child nodes under "/Test/Item" with priority between 3.0 and 8.0 + //Qury child nodes under "/test/items" with priority between 3.0 and 8.0 //Since data ordering is not supported in Firebase's REST APIs, then the query result will not sorted. QueryFilter query; query.orderBy("$priority").startAt(3.0).endAt(8.0); - Serial.println("------------------------------------"); - Serial.println("Filtering based on priority test..."); - - String Path = path + "/Items"; - - if (Firebase.RTDB.getJSON(&fbdo, Path.c_str(), &query)) - { + Serial.printf("Set json with proprity... %s\n", Firebase.RTDB.getJSON(&fbdo, "/test/items", &query) ? "ok" : fbdo.errorReason().c_str()); - Serial.println("PASSED"); - Serial.println("JSON DATA: "); + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } } -} +} \ No newline at end of file diff --git a/examples/RTDB/Retry_and_Queue/Retry_and_Queue.ino b/examples/RTDB/Queue/Queue.ino similarity index 52% rename from examples/RTDB/Retry_and_Queue/Retry_and_Queue.ino rename to examples/RTDB/Queue/Queue.ino index 783ed9430..18c0ecee1 100644 --- a/examples/RTDB/Retry_and_Queue/Retry_and_Queue.ino +++ b/examples/RTDB/Queue/Queue.ino @@ -37,7 +37,7 @@ #define USER_EMAIL "USER_EMAIL" #define USER_PASSWORD "USER_PASSWORD" -//Define FirebaseESP8266 data object +//Define Firebase Data object FirebaseData fbdo; FirebaseAuth auth; @@ -45,8 +45,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/Test"; - std::vector myblob; double mydouble = 0; @@ -98,6 +96,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -111,16 +111,16 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; + Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + //Or use legacy authenticate method + //Firebase.begin(DATABASE_URL, DATABASE_SECRET); - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); + Firebase.reconnectWiFi(true); //Open and retore Firebase Error Queues from file. //The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. @@ -130,11 +130,13 @@ void setup() Firebase.RTDB.deleteStorageFile("/test.txt", mem_storage_type_flash); } - //Set maximum Firebase read/store retry operation (0 - 255) in case of network problems and buffer overflow + //Set maximum Firebase read/store retry operation (0 - 255) in case of + //network problems and buffer overflow Firebase.RTDB.setMaxRetry(&fbdo, 3); //Set the maximum Firebase Error Queues in collection (0 - 255). - //Firebase read/store operation causes by network problems and buffer overflow will be added to Firebase Error Queues collection. + //Firebase read/store operation causes by network problems and buffer + //overflow will be added to Firebase Error Queues collection. Firebase.RTDB.setMaxErrorQueue(&fbdo, 10); Firebase.RTDB.beginAutoRunErrorQueue(&fbdo, callback); @@ -148,64 +150,27 @@ void loop() { taskCompleted = true; - Serial.println("------------------------------------"); - Serial.println("Set double test..."); + Serial.printf("Set double... %s\n", Firebase.RTDB.setDouble(&fbdo, "/test/double", 340.123456789) ? "ok" : fbdo.errorReason().c_str()); - String node = path + "/Double/Data"; - - if (Firebase.RTDB.setDouble(&fbdo, node.c_str(), 340.123456789)) + if (fbdo.httpCode() != FIREBASE_ERROR_HTTP_CODE_OK && Firebase.RTDB.getErrorQueueID(&fbdo) > 0) { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); + Serial.println("Error Queue ID: " + String(Firebase.RTDB.getErrorQueueID(&fbdo))); + queueID[qIdx] = Firebase.RTDB.getErrorQueueID(&fbdo); + qIdx++; } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - if (Firebase.RTDB.getErrorQueueID(&fbdo) > 0) - { - Serial.println("Error Queue ID: " + String(Firebase.RTDB.getErrorQueueID(&fbdo))); - queueID[qIdx] = Firebase.RTDB.getErrorQueueID(&fbdo); - qIdx++; - } - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Set BLOB data test..."); //Create demo data uint8_t data[256]; for (int i = 0; i < 256; i++) data[i] = i; - node = path + "/Binary/Blob/data"; + Serial.printf("Set Blob... %s\n", Firebase.RTDB.setBlob(&fbdo, "/test/blob", data, sizeof(data)) ? "ok" : fbdo.errorReason().c_str()); - //Set binary data to database - if (Firebase.RTDB.setBlob(&fbdo, node.c_str(), data, sizeof(data))) + if (fbdo.httpCode() != FIREBASE_ERROR_HTTP_CODE_OK && Firebase.RTDB.getErrorQueueID(&fbdo) > 0) { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - if (Firebase.RTDB.getErrorQueueID(&fbdo) > 0) - { - Serial.println("Error Queue ID: " + String(Firebase.RTDB.getErrorQueueID(&fbdo))); - queueID[qIdx] = Firebase.RTDB.getErrorQueueID(&fbdo); - qIdx++; - } - Serial.println("------------------------------------"); - Serial.println(); + Serial.println("Error Queue ID: " + String(Firebase.RTDB.getErrorQueueID(&fbdo))); + queueID[qIdx] = Firebase.RTDB.getErrorQueueID(&fbdo); + qIdx++; } if (WiFi.status() == WL_CONNECTED) @@ -214,87 +179,33 @@ void loop() Serial.println("To test error queue, turn off WiFi AP to make error in the next operation"); Serial.println("--------------------------------------------------------------------------"); Serial.println(); - delay(10000); } - Serial.println("------------------------------------"); - Serial.println("Get BLOB data test..."); - - node = path + "/Binary/Blob/data"; - - //Get binary data from database - //Assign myblob as the target variable - if (Firebase.RTDB.getBlob(&fbdo, node.c_str(), &myblob)) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.print("VALUE: "); - if (fbdo.dataType() == "blob") - { - - Serial.println(); - - for (size_t i = 0; i < myblob.size(); i++) - { - if (i > 0 && i % 16 == 0) - Serial.println(); - - if (i < 16) - Serial.print("0"); - - Serial.print(myblob[i], HEX); - Serial.print(" "); - } - myblob.clear(); - Serial.println(); - } - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("Get double... %s\n", Firebase.RTDB.getDouble(&fbdo, "/test/double", &mydouble) ? "ok" : fbdo.errorReason().c_str()); + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) + printResult(fbdo); else { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); if (Firebase.RTDB.getErrorQueueID(&fbdo) > 0) { Serial.println("Error Queue ID: " + String(Firebase.RTDB.getErrorQueueID(&fbdo))); queueID[qIdx] = Firebase.RTDB.getErrorQueueID(&fbdo); qIdx++; } - Serial.println("------------------------------------"); - Serial.println(); } - Serial.println("------------------------------------"); - Serial.println("Get double test..."); - - node = path + "/Double/Data"; - - if (Firebase.RTDB.getDouble(&fbdo, node.c_str(), &mydouble)) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - mydouble = 0; - } + Serial.printf("Get blob... %s\n", Firebase.RTDB.getBlob(&fbdo, "/test/blob", &myblob) ? "ok" : fbdo.errorReason().c_str()); + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) + printResult(fbdo); else { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); if (Firebase.RTDB.getErrorQueueID(&fbdo) > 0) { Serial.println("Error Queue ID: " + String(Firebase.RTDB.getErrorQueueID(&fbdo))); queueID[qIdx] = Firebase.RTDB.getErrorQueueID(&fbdo); qIdx++; } - Serial.println("------------------------------------"); - Serial.println(); } if (Firebase.RTDB.errorQueueCount(&fbdo) > 0) @@ -313,27 +224,13 @@ void loop() //Firebase.RTDB.endAutoRunErrorQueue(&fbdo); } - if (!Firebase.ready()) - return; + /* - if (mydouble > 0) - { - Serial.println("------------------------------------"); - Serial.println("Double Data gets from Queue"); - printf("%.9lf\n", mydouble); - Serial.println(); - mydouble = 0; - } - - if (Firebase.RTDB.errorQueueCount(&fbdo) > 0) - { + if Firebase.RTDB.beginAutoRunErrorQueue was not call, + to manaul run the Firebase Error Queues, just call + Firebase.RTDB.processErrorQueue in loop - /* - if Firebase.RTDB.beginAutoRunErrorQueue was not call, - to manaul run the Firebase Error Queues, just call Firebase.RTDB.processErrorQueue in loop - - Firebase.RTDB.processErrorQueue(&fbdo); delay(1000); @@ -357,34 +254,30 @@ void loop() } Serial.println(); - */ + */ - if (mydouble > 0) - { - Serial.println("------------------------------------"); - Serial.println("Double Data gets from Queue"); - Serial.println(mydouble, 9); - Serial.println(); - mydouble = 0; - } + if (mydouble > 0) + { + Serial.println("Double Data gets from Queue"); + printf("%.9lf\n", mydouble); + Serial.println(); + mydouble = 0; + } - if (myblob.size() > 0) + if (myblob.size() > 0) + { + Serial.println("Blob Data gets from Queue"); + for (size_t i = 0; i < myblob.size(); i++) { - Serial.println("------------------------------------"); - Serial.println("Blob Data gets from Queue"); - Serial.println(); - for (size_t i = 0; i < myblob.size(); i++) - { - if (i > 0 && i % 16 == 0) - Serial.println(); - if (myblob[i] < 16) - Serial.print("0"); - Serial.print(myblob[i], HEX); - Serial.print(" "); - } - Serial.println(); - Serial.println(); - myblob.clear(); + if (i > 0 && i % 16 == 0) + Serial.println(); + if (myblob[i] < 16) + Serial.print("0"); + Serial.print(myblob[i], HEX); + Serial.print(" "); } + Serial.println(); + Serial.println(); + myblob.clear(); } -} +} \ No newline at end of file diff --git a/examples/RTDB/Shallowed_Data/Shallowed_Data.ino b/examples/RTDB/ShallowedData/ShallowedData.ino similarity index 63% rename from examples/RTDB/Shallowed_Data/Shallowed_Data.ino rename to examples/RTDB/ShallowedData/ShallowedData.ino index 55bc43fb0..4e5cec284 100644 --- a/examples/RTDB/Shallowed_Data/Shallowed_Data.ino +++ b/examples/RTDB/ShallowedData/ShallowedData.ino @@ -37,7 +37,7 @@ #define USER_EMAIL "USER_EMAIL" #define USER_PASSWORD "USER_PASSWORD" -//Define FirebaseESP8266 data object +//Define Firebase Data object FirebaseData fbdo; FirebaseAuth auth; @@ -45,8 +45,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/"; - void setup() { @@ -66,6 +64,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -79,15 +79,13 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; - //Set database read timeout to 1 minute (max 15 minutes) - Firebase.RTDB.setReadTimeout(&fbdo, 1000 * 60); - //tiny, small, medium, large and unlimited. - //Size and its write timeout e.g. tiny (1s), small (10s), medium (30s) and large (60s). - Firebase.RTDB.setwriteSizeLimit(&fbdo, "tiny"); + Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); } void loop() @@ -95,29 +93,10 @@ void loop() if (Firebase.ready() && !taskCompleted) { taskCompleted = true; - - //The following test will print all parent nodes and their shallowed data - - Serial.println("------------------------------------"); - Serial.println("Shallowed Data test..."); - Serial.println(); - - if (Firebase.RTDB.getShallowData(&fbdo, path.c_str())) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.print("VALUE: "); + + Serial.printf("Get shallow data... %s\n", Firebase.RTDB.getShallowData(&fbdo, "/") ? "ok" : fbdo.errorReason().c_str()); + + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } } +} \ No newline at end of file diff --git a/examples/RTDB/Stream/Stream.ino b/examples/RTDB/Stream/Stream.ino deleted file mode 100644 index 9f2ee5c44..000000000 --- a/examples/RTDB/Stream/Stream.ino +++ /dev/null @@ -1,160 +0,0 @@ -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" -//Provide the RTDB payload printing info and other helper functions. -#include "addons/RTDBHelper.h" - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. Define the API Key */ -#define API_KEY "API_KEY" - -/* 3. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 4. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -//Define FirebaseESP8266 data object -FirebaseData fbdo; - -FirebaseAuth auth; -FirebaseConfig config; - -unsigned long sendDataPrevMillis = 0; - -String path = "/Test/Stream"; - -uint16_t count = 0; - -void setup() -{ - - Serial.begin(115200); - - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); - Serial.print("Connecting to Wi-Fi"); - while (WiFi.status() != WL_CONNECTED) - { - Serial.print("."); - delay(300); - } - Serial.println(); - Serial.print("Connected with IP: "); - Serial.println(WiFi.localIP()); - Serial.println(); - - /* Assign the api key (required) */ - config.api_key = API_KEY; - - /* Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - //The data under the node being stream (parent path) should keep small - //Large stream payload leads to the parsing error due to memory allocation. - if (!Firebase.RTDB.beginStream(&fbdo, path.c_str())) - { - Serial.println("------------------------------------"); - Serial.println("Can't begin stream connection..."); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } -} - -void loop() -{ - - if (Firebase.ready() && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)) - { - sendDataPrevMillis = millis(); - count++; - String Path = path + "/String"; - String Value = "Hello World! " + String(count); - - Serial.println("------------------------------------"); - Serial.println("Set string..."); - if (Firebase.RTDB.setString(&fbdo, Path.c_str(), Value.c_str())) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - if (Firebase.ready()) - { - if (!Firebase.RTDB.readStream(&fbdo)) - { - Serial.println("------------------------------------"); - Serial.println("Can't read stream data..."); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - if (fbdo.streamTimeout()) - { - Serial.println("Stream timeout, resume streaming..."); - Serial.println(); - } - - if (fbdo.streamAvailable()) - { - Serial.println("------------------------------------"); - Serial.println("Stream Data available..."); - Serial.println("STREAM PATH: " + fbdo.streamPath()); - Serial.println("EVENT PATH: " + fbdo.dataPath()); - Serial.println("DATA TYPE: " + fbdo.dataType()); - Serial.println("EVENT TYPE: " + fbdo.eventType()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - } -} diff --git a/examples/RTDB/Stream_Callback/Stream_Callback.ino b/examples/RTDB/Stream_Callback/Stream_Callback.ino deleted file mode 100644 index e8069a1e4..000000000 --- a/examples/RTDB/Stream_Callback/Stream_Callback.ino +++ /dev/null @@ -1,174 +0,0 @@ -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" -//Provide the RTDB payload printing info and other helper functions. -#include "addons/RTDBHelper.h" - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. Define the API Key */ -#define API_KEY "API_KEY" - -/* 3. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 4. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -//Define FirebaseESP8266 data object -FirebaseData fbdo1; -FirebaseData fbdo2; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -//Important information -//In ESP8266 Aruino Core SDK v3.x.x -//The free heap is significantly reduced as much as 5-6 kB from v2.7.4. -//This may lead to out of memory sitation when two Firebase Data objects are used simultaneously (when sessions connected). -//Minimize the reserved memory for BearSSL will gain the free heap a bit but may not enough for your usage. -//You can stay with Core SDK v2.7.4 until this memory issue was solve in the Core SDK. -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -FirebaseAuth auth; -FirebaseConfig config; - -unsigned long sendDataPrevMillis = 0; - -String path = "/Test/Stream"; - -uint16_t count = 0; - -void streamCallback(FirebaseStream data) -{ - - Serial.println("Stream Data1 available..."); - Serial.println("STREAM PATH: " + data.streamPath()); - Serial.println("EVENT PATH: " + data.dataPath()); - Serial.println("DATA TYPE: " + data.dataType()); - Serial.println("EVENT TYPE: " + data.eventType()); - Serial.print("VALUE: "); - printResult(data); //see addons/RTDBHelper.h - Serial.println(); -} - -void streamTimeoutCallback(bool timeout) -{ - if (timeout) - { - Serial.println(); - Serial.println("Stream timeout, resume streaming..."); - Serial.println(); - } -} - -void setup() -{ - - Serial.begin(115200); - - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); - Serial.print("Connecting to Wi-Fi"); - while (WiFi.status() != WL_CONNECTED) - { - Serial.print("."); - delay(300); - } - Serial.println(); - Serial.print("Connected with IP: "); - Serial.println(WiFi.localIP()); - Serial.println(); - - /* Assign the api key (required) */ - config.api_key = API_KEY; - - /* Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo1.setBSSLBufferSize(1024, 512); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo1.setResponseSize(1024); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo2.setBSSLBufferSize(1024, 512); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo2.setResponseSize(1024); - - //The data under the node being stream (parent path) should keep small - //Large stream payload leads to the parsing error due to memory allocation. - if (!Firebase.RTDB.beginStream(&fbdo1, path.c_str())) - { - Serial.println("------------------------------------"); - Serial.println("Can't begin stream connection..."); - Serial.println("REASON: " + fbdo1.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Firebase.RTDB.setStreamCallback(&fbdo1, streamCallback, streamTimeoutCallback); -} - -void loop() -{ - - if (Firebase.ready() && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)) - { - sendDataPrevMillis = millis(); - count++; - - Serial.println("------------------------------------"); - Serial.println("Set JSON..."); - - FirebaseJson json; - json.add("data", "hello").add("num", count); - String Path = path + "/Json"; - if (Firebase.RTDB.setJSON(&fbdo2, Path.c_str(), &json)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo2.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } -} diff --git a/examples/RTDB/Timestamp/Timestamp.ino b/examples/RTDB/Timestamp/Timestamp.ino index 29b3fa3de..23cab10e6 100644 --- a/examples/RTDB/Timestamp/Timestamp.ino +++ b/examples/RTDB/Timestamp/Timestamp.ino @@ -38,7 +38,7 @@ #define USER_EMAIL "USER_EMAIL" #define USER_PASSWORD "USER_PASSWORD" -//Define FirebaseESP8266 data object +//Define Firebase Data object FirebaseData fbdo; FirebaseAuth auth; @@ -65,6 +65,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -78,23 +80,13 @@ void setup() /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); + //Or use legacy authenticate method + //config.database_url = DATABASE_URL; + //config.signer.tokens.legacy_token = ""; -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); + Firebase.begin(&config, &auth); - /* - This option allows get and delete functions (PUT and DELETE HTTP requests) works for device connected behind the - Firewall that allows only GET and POST requests. - - Firebase.enableClassicRequest(&fbdo, true); - */ + Firebase.reconnectWiFi(true); } void loop() @@ -103,18 +95,10 @@ void loop() { taskCompleted = true; - String path = "/Test"; - String Path = path + "/Set/Timestamp"; + Serial.printf("Set timestamp... %s\n", Firebase.RTDB.setTimestamp(&fbdo, "/test/timestamp") ? "ok" : fbdo.errorReason().c_str()); - Serial.println("------------------------------------"); - Serial.println("Set Timestamp test..."); - - if (Firebase.RTDB.setTimestamp(&fbdo, Path.c_str())) + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - //Timestamp saved in millisecond, get its seconds from intData() Serial.print("TIMESTAMP (Seconds): "); Serial.println(fbdo.intData()); @@ -122,76 +106,10 @@ void loop() //Or print the total milliseconds from doubleData() //Due to bugs in Serial.print in Arduino library, use printf to print double instead. printf("TIMESTAMP (milliSeconds): %.0lf\n", fbdo.doubleData()); - - //Or print it from payload directly - Serial.print("TIMESTAMP (milliSeconds): "); - Serial.println(fbdo.payload()); - - Path = path + "/Set/Timestamp"; - - //Due to some internal server error, ETag cannot get from setTimestamp - //Try to get ETag manually - Serial.println("ETag: " + Firebase.RTDB.getETag(&fbdo, Path.c_str())); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); } - Serial.println("------------------------------------"); - Serial.println("Get Timestamp (double of milliseconds) test..."); - - Path = path + "/Set/Timestamp"; - - if (Firebase.RTDB.getDouble(&fbdo, Path.c_str())) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - + Serial.printf("Get timestamp... %s\n", Firebase.RTDB.getDouble(&fbdo, "/test/timestamp") ? "ok" : fbdo.errorReason().c_str()); + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) printf("TIMESTAMP: %.0lf\n", fbdo.doubleData()); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Push Timestamp test..."); - - Path = path + "/Push/Timestamp"; - - if (Firebase.RTDB.pushTimestamp(&fbdo, Path.c_str())) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.print("PUSH NAME: "); - Serial.println(fbdo.pushName()); - - Path = path + "/Push/Timestamp/" + fbdo.pushName(); - - //Due to some internal server error, ETag cannot get from pushTimestamp - //Try to get ETag manually - Serial.println("ETag: " + Firebase.RTDB.getETag(&fbdo, Path.c_str())); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } } } \ No newline at end of file diff --git a/examples/RTDB/jsonArray/jsonArray.ino b/examples/RTDB/jsonArray/jsonArray.ino deleted file mode 100644 index 6caca5683..000000000 --- a/examples/RTDB/jsonArray/jsonArray.ino +++ /dev/null @@ -1,193 +0,0 @@ - -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -//This example shows how to set array data through FirebaseJsonArray object then read the data back and parse them. - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" -//Provide the RTDB payload printing info and other helper functions. -#include "addons/RTDBHelper.h" - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. Define the API Key */ -#define API_KEY "API_KEY" - -/* 3. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 4. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -//Define Firebase Data object -FirebaseData fbdo; - -FirebaseAuth auth; -FirebaseConfig config; - -FirebaseJsonArray arr; - -unsigned long sendDataPrevMillis = 0; - -String path = "/Test/Array"; - -uint16_t count = 0; - -void setup() -{ - - Serial.begin(115200); - - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); - Serial.print("Connecting to Wi-Fi"); - while (WiFi.status() != WL_CONNECTED) - { - Serial.print("."); - delay(300); - } - Serial.println(); - Serial.print("Connected with IP: "); - Serial.println(WiFi.localIP()); - Serial.println(); - - /* Assign the api key (required) */ - config.api_key = API_KEY; - - /* Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); - - - if (!Firebase.RTDB.beginStream(&fbdo, path.c_str())) - { - Serial.println("------------------------------------"); - Serial.println("Can't begin stream connection..."); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } -} - -void loop() -{ - - if (Firebase.ready() && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)) - { - sendDataPrevMillis = millis(); - count++; - - Serial.println("------------------------------------"); - Serial.println("Set Array..."); - - arr.clear(); - arr.set("/[0]", count); - arr.set("/[1]", "hello"); - arr.set("/[4]", 76.54); - String Path = path + "/Data"; - if (Firebase.RTDB.set(&fbdo, Path.c_str(), &arr)) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Get Array..."); - if (Firebase.RTDB.get(&fbdo, Path.c_str())) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } - - if (Firebase.ready()) - { - if (!Firebase.RTDB.readStream(&fbdo)) - { - Serial.println("------------------------------------"); - Serial.println("Can't read stream data..."); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - if (fbdo.streamTimeout()) - { - Serial.println("Stream timeout, resume streaming..."); - Serial.println(); - } - - if (fbdo.streamAvailable()) - { - Serial.println("------------------------------------"); - Serial.println("Stream Data available..."); - Serial.println("STREAM PATH: " + fbdo.streamPath()); - Serial.println("EVENT PATH: " + fbdo.dataPath()); - Serial.println("DATA TYPE: " + fbdo.dataType()); - Serial.println("EVENT TYPE: " + fbdo.eventType()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - } -} \ No newline at end of file diff --git a/examples/RTDB/jsonObject/jsonObject.ino b/examples/RTDB/jsonObject/jsonObject.ino deleted file mode 100644 index 3a2400d68..000000000 --- a/examples/RTDB/jsonObject/jsonObject.ino +++ /dev/null @@ -1,186 +0,0 @@ - -/** - * Created by K. Suwatchai (Mobizt) - * - * Email: k_suwatchai@hotmail.com - * - * Github: https://github.com/mobizt - * - * Copyright (c) 2021 mobizt - * -*/ - -//This example shows how to set complex json data through FirebaseJson object then read the data back and parse them. - -#if defined(ESP32) -#include -#elif defined(ESP8266) -#include -#endif -#include - -//Provide the token generation process info. -#include "addons/TokenHelper.h" -//Provide the RTDB payload printing info and other helper functions. -#include "addons/RTDBHelper.h" - -/* 1. Define the WiFi credentials */ -#define WIFI_SSID "WIFI_AP" -#define WIFI_PASSWORD "WIFI_PASSWORD" - -/* 2. Define the API Key */ -#define API_KEY "API_KEY" - -/* 3. Define the RTDB URL */ -#define DATABASE_URL "URL" //.firebaseio.com or ..firebasedatabase.app - -/* 4. Define the user Email and password that alreadey registerd or added in your project */ -#define USER_EMAIL "USER_EMAIL" -#define USER_PASSWORD "USER_PASSWORD" - -//Define Firebase Data object -FirebaseData fbdo; - -FirebaseAuth auth; -FirebaseConfig config; - -bool taskCompleted = false; - -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(); - - /* Assign the api key (required) */ - config.api_key = API_KEY; - - /* Assign the user sign in credentials */ - auth.user.email = USER_EMAIL; - auth.user.password = USER_PASSWORD; - - /* Assign the RTDB URL (required) */ - config.database_url = DATABASE_URL; - - /* Assign the callback function for the long running token generation task */ - config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h - - Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); -} - -void loop() -{ - if (Firebase.ready() && !taskCompleted) - { - taskCompleted = true; - - String path = "/Test/Json"; - - String jsonStr = ""; - - FirebaseJson json1; - - FirebaseJsonData jsonObj; - - json1.set("Hi/myInt", 200); - json1.set("Hi/myDouble", 0.0023); - json1.set("Who/are/[0]", "you"); - json1.set("Who/are/[1]", "they"); - json1.set("Who/is/[0]", "she"); - json1.set("Who/is/[1]", "he"); - json1.set("This/is/[0]", false); - json1.set("This/is/[1]", true); - json1.set("This/is/[2]", "my house"); - json1.set("This/is/[3]/my", "world"); - - Serial.println("------------------------------------"); - Serial.println("JSON Data"); - json1.toString(jsonStr, true); - Serial.println(jsonStr); - Serial.println("------------------------------------"); - - Serial.println("------------------------------------"); - Serial.println("Set JSON test..."); - - if (Firebase.RTDB.set(&fbdo, path.c_str(), &json1)) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.print("VALUE: "); - printResult(fbdo); //see addons/RTDBHelper.h - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Get JSON test..."); - - if (Firebase.RTDB.get(&fbdo, path.c_str())) - { - Serial.println("PASSED"); - Serial.println("PATH: " + fbdo.dataPath()); - Serial.println("TYPE: " + fbdo.dataType()); - Serial.print("VALUE: "); - if (fbdo.dataType() == "json") - { - printResult(fbdo); //see addons/RTDBHelper.h - } - - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - - Serial.println("------------------------------------"); - Serial.println("Try to parse return data and get value.."); - - json1 = fbdo.jsonObject(); - - json1.get(jsonObj, "This/is/[3]/my"); - - Serial.println("This/is/[3]/my: " + jsonObj.stringValue); - - json1.get(jsonObj, "Hi/myDouble"); - Serial.print("Hi/myDouble: "); - Serial.println(jsonObj.doubleValue, 4); - - Serial.println("------------------------------------"); - Serial.println(); - } -} diff --git a/examples/Storage/Firebase_Storage/Delete_File/Delete_File.ino b/examples/Storage/FirebaseStorage/DeleteFile/DeleteFile.ino similarity index 68% rename from examples/Storage/Firebase_Storage/Delete_File/Delete_File.ino rename to examples/Storage/FirebaseStorage/DeleteFile/DeleteFile.ino index f11b2bcb3..f7aaff76f 100644 --- a/examples/Storage/Firebase_Storage/Delete_File/Delete_File.ino +++ b/examples/Storage/FirebaseStorage/DeleteFile/DeleteFile.ino @@ -43,8 +43,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/Test"; - void setup() { @@ -64,6 +62,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -75,13 +75,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + Firebase.reconnectWiFi(true); } void loop() @@ -90,21 +85,7 @@ void loop() { taskCompleted = true; - Serial.println("------------------------------------"); - Serial.println("Delete file test..."); - - if (Firebase.Storage.deleteFile(&fbdo, STORAGE_BUCKET_ID, "path/to/file/filename")) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("Delete file... %s\n", Firebase.Storage.deleteFile(&fbdo, STORAGE_BUCKET_ID, "path/to/file/filename") ? "ok" : fbdo.errorReason().c_str()); + } } diff --git a/examples/Storage/Firebase_Storage/Download_File/Download_File.ino b/examples/Storage/FirebaseStorage/DownloadFile/DownloadFile.ino similarity index 65% rename from examples/Storage/Firebase_Storage/Download_File/Download_File.ino rename to examples/Storage/FirebaseStorage/DownloadFile/DownloadFile.ino index 44352ae01..10d16d251 100644 --- a/examples/Storage/Firebase_Storage/Download_File/Download_File.ino +++ b/examples/Storage/FirebaseStorage/DownloadFile/DownloadFile.ino @@ -43,8 +43,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/Test"; - void setup() { @@ -64,6 +62,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -75,13 +75,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + Firebase.reconnectWiFi(true); } void loop() @@ -95,22 +90,9 @@ void loop() #elif defined(ESP8266) Firebase.sdBegin(15); //SS #endif - - Serial.println("------------------------------------"); - Serial.println("Download file test..."); //The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. - if (Firebase.Storage.download(&fbdo, STORAGE_BUCKET_ID /* Firebase Storage bucket id */, "path/to/file/filename" /* path of remote file stored in the bucket */, "/path/to/save/filename" /* path to local file */, mem_storage_type_sd /* memory storage type, mem_storage_type_flash and mem_storage_type_sd */)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("Download file... %s\n", Firebase.Storage.download(&fbdo, STORAGE_BUCKET_ID /* Firebase Storage bucket id */, "path/to/file/filename" /* path of remote file stored in the bucket */, "/path/to/save/filename" /* path to local file */, mem_storage_type_sd /* memory storage type, mem_storage_type_flash and mem_storage_type_sd */) ? "ok" : fbdo.errorReason().c_str()); + + } } diff --git a/examples/Storage/Firebase_Storage/List_Files/List_Files.ino b/examples/Storage/FirebaseStorage/ListFiles/ListFiles.ino similarity index 72% rename from examples/Storage/Firebase_Storage/List_Files/List_Files.ino rename to examples/Storage/FirebaseStorage/ListFiles/ListFiles.ino index 6e2a2417f..959b256fa 100644 --- a/examples/Storage/Firebase_Storage/List_Files/List_Files.ino +++ b/examples/Storage/FirebaseStorage/ListFiles/ListFiles.ino @@ -43,8 +43,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/Test"; - void setup() { @@ -64,6 +62,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -75,12 +75,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif } void loop() @@ -89,24 +85,13 @@ void loop() { taskCompleted = true; - Serial.println("------------------------------------"); - Serial.println("List files test..."); + Serial.printf("List files... %s\n", Firebase.Storage.listFiles(&fbdo, STORAGE_BUCKET_ID) ? "ok" : fbdo.errorReason().c_str()); - if (Firebase.Storage.listFiles(&fbdo, STORAGE_BUCKET_ID)) + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) { - Serial.println("PASSED"); FileList *files = fbdo.fileList(); for (size_t i = 0; i < files->items.size(); i++) Serial.printf("name: %s, bucket: %s\n", files->items[i].name.c_str(), files->items[i].bucket.c_str()); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); } } } diff --git a/examples/Storage/Firebase_Storage/Metadata/Metadata.ino b/examples/Storage/FirebaseStorage/Metadata/Metadata.ino similarity index 77% rename from examples/Storage/Firebase_Storage/Metadata/Metadata.ino rename to examples/Storage/FirebaseStorage/Metadata/Metadata.ino index 145ca2fab..115c64468 100644 --- a/examples/Storage/Firebase_Storage/Metadata/Metadata.ino +++ b/examples/Storage/FirebaseStorage/Metadata/Metadata.ino @@ -43,8 +43,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/Test"; - void setup() { @@ -64,6 +62,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -89,12 +89,10 @@ void loop() { taskCompleted = true; - Serial.println("------------------------------------"); - Serial.println("Get file Metadata test..."); + Serial.printf("Get file Metadata... %s\n", Firebase.Storage.listFiles(&fbdo, STORAGE_BUCKET_ID) ? "ok" : fbdo.errorReason().c_str()); - if (Firebase.Storage.getMetadata(&fbdo, STORAGE_BUCKET_ID, "path/to/file/filename")) + if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK) { - Serial.println("PASSED"); FileMetaInfo meta = fbdo.metaData(); Serial.printf("Name: %s\n", meta.name.c_str()); Serial.printf("Bucket: %s\n", meta.bucket.c_str()); @@ -105,16 +103,7 @@ void loop() Serial.printf("ETag: %s\n", meta.etag.c_str()); Serial.printf("CRC32: %s\n", meta.crc32.c_str()); Serial.printf("Token: %s\n", meta.downloadTokens.c_str()); - Serial.printf("Download URL: %s\n", fbdo.downloadURL().c_str()); - Serial.println("------------------------------------"); - Serial.println(); - } - else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); + Serial.printf("Download URL: %s\n\n", fbdo.downloadURL().c_str()); } } } diff --git a/examples/Storage/Firebase_Storage/Upload_Byte_Array_Memory/Upload_Byte_Array_Memory.ino b/examples/Storage/FirebaseStorage/UploadByteArrayMemory/UploadByteArrayMemory.ino similarity index 80% rename from examples/Storage/Firebase_Storage/Upload_Byte_Array_Memory/Upload_Byte_Array_Memory.ino rename to examples/Storage/FirebaseStorage/UploadByteArrayMemory/UploadByteArrayMemory.ino index cc4af342d..60f8bf91b 100644 --- a/examples/Storage/Firebase_Storage/Upload_Byte_Array_Memory/Upload_Byte_Array_Memory.ino +++ b/examples/Storage/FirebaseStorage/UploadByteArrayMemory/UploadByteArrayMemory.ino @@ -43,8 +43,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/Test"; - void setup() { @@ -64,6 +62,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -97,23 +97,12 @@ void loop() for (int i = 0; i < 256; i++) test_data[i] = i; - Serial.println("------------------------------------"); - Serial.println("Upload byte array test..."); + Serial.print("Upload byte array... "); //MIME type should be valid to avoid the download problem. if (Firebase.Storage.upload(&fbdo, STORAGE_BUCKET_ID /* Firebase Storage bucket id */, test_data /* byte array from ram or flash */, 256 /* size of data in bytes */, "test.dat" /* path of remote file stored in the bucket */, "application/octet-stream" /* mime type */)) - { - - Serial.printf("Download URL: %s\n", fbdo.downloadURL().c_str()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("\nDownload URL: %s\n", fbdo.downloadURL().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Storage/Firebase_Storage/Upload_File/Upload_File.ino b/examples/Storage/FirebaseStorage/UploadFile/UploadFile.ino similarity index 82% rename from examples/Storage/Firebase_Storage/Upload_File/Upload_File.ino rename to examples/Storage/FirebaseStorage/UploadFile/UploadFile.ino index d1c48961f..b86d01ecf 100644 --- a/examples/Storage/Firebase_Storage/Upload_File/Upload_File.ino +++ b/examples/Storage/FirebaseStorage/UploadFile/UploadFile.ino @@ -44,8 +44,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/Test"; - void setup() { @@ -65,6 +63,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the api key (required) */ config.api_key = API_KEY; @@ -94,9 +94,8 @@ void loop() if (Firebase.ready() && !taskCompleted) { taskCompleted = true; - - Serial.println("------------------------------------"); - Serial.println("Upload file test..."); + + Serial.print("Upload file test... "); //Upload large file over fews hundreds KiB is not allowable in Firebase Storage by using this method. //To upload the large file, please use the Firebase.GCStorage.upload instead. @@ -104,18 +103,8 @@ void loop() //MIME type should be valid to avoid the download problem. //The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. if (Firebase.Storage.upload(&fbdo, STORAGE_BUCKET_ID /* Firebase Storage bucket id */, "/media.mp4" /* path to local file */, mem_storage_type_flash /* memory storage type, mem_storage_type_flash and mem_storage_type_sd */, "media.mp4" /* path of remote file stored in the bucket */, "video/mp4" /* mime type */)) - { - - Serial.printf("Download URL: %s\n", fbdo.downloadURL().c_str()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.printf("\nDownload URL: %s\n", fbdo.downloadURL().c_str()); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Storage/Firebase_Storage/Upload_File/data/media.mp4 b/examples/Storage/FirebaseStorage/UploadFile/data/media.mp4 similarity index 100% rename from examples/Storage/Firebase_Storage/Upload_File/data/media.mp4 rename to examples/Storage/FirebaseStorage/UploadFile/data/media.mp4 diff --git a/examples/Storage/Google_Cloud_Storage/Delete_File/Delete_File.ino b/examples/Storage/GoogleCloudStorage/DeleteFile/DeleteFile.ino similarity index 76% rename from examples/Storage/Google_Cloud_Storage/Delete_File/Delete_File.ino rename to examples/Storage/GoogleCloudStorage/DeleteFile/DeleteFile.ino index f7725ee0b..42e2fcf8d 100644 --- a/examples/Storage/Google_Cloud_Storage/Delete_File/Delete_File.ino +++ b/examples/Storage/GoogleCloudStorage/DeleteFile/DeleteFile.ino @@ -42,8 +42,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/Test"; - void setup() { @@ -63,6 +61,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials for OAuth2.0 authen */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -72,13 +72,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + Firebase.reconnectWiFi(true); } void loop() @@ -86,25 +81,15 @@ void loop() if (Firebase.ready() && !taskCompleted) { taskCompleted = true; - - Serial.println("------------------------------------"); - Serial.println("Delete file with Google Cloud Storage JSON API test..."); + + Serial.print("Delete file with Google Cloud Storage JSON API... "); //DeleteOptions option; //For query parameters description of DeleteOptions, see https://cloud.google.com/storage/docs/json_api/v1/objects/delete#optional-parameters if (Firebase.GCStorage.deleteFile(&fbdo, STORAGE_BUCKET_ID /* The Firebase or Google Cloud Storage bucket id */, "path/to/file/filename" /* remote file path stored in the Storage bucket*/, nullptr /* DeleteOptions data */)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println("ok"); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Storage/Google_Cloud_Storage/Download_File/Download_File.ino b/examples/Storage/GoogleCloudStorage/DownloadFile/DownloadFile.ino similarity index 77% rename from examples/Storage/Google_Cloud_Storage/Download_File/Download_File.ino rename to examples/Storage/GoogleCloudStorage/DownloadFile/DownloadFile.ino index a35c1077e..857c12afc 100644 --- a/examples/Storage/Google_Cloud_Storage/Download_File/Download_File.ino +++ b/examples/Storage/GoogleCloudStorage/DownloadFile/DownloadFile.ino @@ -42,8 +42,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/Test"; - void setup() { @@ -63,6 +61,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials for OAuth2.0 authen */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -72,13 +72,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - } void loop() @@ -87,24 +82,14 @@ void loop() { taskCompleted = true; - Serial.println("------------------------------------"); - Serial.println("Download file with Google Cloud Storage JSON API test..."); + Serial.print("Download file with Google Cloud Storage JSON API... "); //StorageGetOptions option; //For query parameters description of StorageGetOptions, see https://cloud.google.com/storage/docs/json_api/v1/objects/get#optional-parameters //The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. if (Firebase.GCStorage.download(&fbdo, STORAGE_BUCKET_ID /* Firebase or Google Cloud Storage bucket id */, "path/to/file/filename" /* path of remote file stored in the bucket */, "/path/to/save/filename" /* path to local file */, mem_storage_type_flash /* memory storage type, mem_storage_type_flash and mem_storage_type_sd */, nullptr /* StorageGetOptions data */)) - { - Serial.println("PASSED"); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println("ok"); else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } - } + Serial.println(fbdo.errorReason()); } +} diff --git a/examples/Storage/Google_Cloud_Storage/List_Files/List_Files.ino b/examples/Storage/GoogleCloudStorage/ListFiles/ListFiles.ino similarity index 78% rename from examples/Storage/Google_Cloud_Storage/List_Files/List_Files.ino rename to examples/Storage/GoogleCloudStorage/ListFiles/ListFiles.ino index 23c9c8c13..1bad7904d 100644 --- a/examples/Storage/Google_Cloud_Storage/List_Files/List_Files.ino +++ b/examples/Storage/GoogleCloudStorage/ListFiles/ListFiles.ino @@ -42,8 +42,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/Test"; - void setup() { @@ -63,6 +61,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials for OAuth2.0 authen */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -72,12 +72,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); - Firebase.reconnectWiFi(true); -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif + Firebase.reconnectWiFi(true); } void loop() @@ -86,8 +82,7 @@ void loop() { taskCompleted = true; - Serial.println("------------------------------------"); - Serial.println("List files with Google Cloud Storage JSON API test..."); + Serial.print("List files with Google Cloud Storage JSON API... "); //Fore query parameters description of ListOptions, see https://cloud.google.com/storage/docs/json_api/v1/objects/list#optional-parameters ListOptions option; @@ -95,19 +90,12 @@ void loop() if (Firebase.GCStorage.listFiles(&fbdo, STORAGE_BUCKET_ID /* The Firebase or Google Cloud Storage bucket id */, &option /* ListOptions data */)) { - Serial.println("PASSED"); + Serial.println("ok"); FileList *files = fbdo.fileList(); for (size_t i = 0; i < files->items.size(); i++) Serial.printf("name: %s, bucket: %s, contentType: %s, size: %d\n", files->items[i].name.c_str(), files->items[i].bucket.c_str(), files->items[i].contentType.c_str(), files->items[i].size); - Serial.println("------------------------------------"); - Serial.println(); } else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Storage/Google_Cloud_Storage/Metadata/Metadata.ino b/examples/Storage/GoogleCloudStorage/Metadata/Metadata.ino similarity index 80% rename from examples/Storage/Google_Cloud_Storage/Metadata/Metadata.ino rename to examples/Storage/GoogleCloudStorage/Metadata/Metadata.ino index 226873fba..a35b29b4b 100644 --- a/examples/Storage/Google_Cloud_Storage/Metadata/Metadata.ino +++ b/examples/Storage/GoogleCloudStorage/Metadata/Metadata.ino @@ -42,8 +42,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/Test"; - void setup() { @@ -63,6 +61,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials for OAuth2.0 authen */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -72,14 +72,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - } void loop() @@ -88,15 +82,14 @@ void loop() { taskCompleted = true; - Serial.println("------------------------------------"); - Serial.println("Get file Metadata with Google Cloud Storage JSON API test..."); + Serial.print("Get file Metadata with Google Cloud Storage JSON API... "); //StorageGetOptions option; //For query parameters description of StorageGetOptions, see https://cloud.google.com/storage/docs/json_api/v1/objects/get#optional-parameters if (Firebase.GCStorage.getMetadata(&fbdo, STORAGE_BUCKET_ID /* The Firebase or Google Cloud Storage bucket id */, "path/to/file/filename" /* The remote filename stored in the Storage bucket */, nullptr /* StorageGetOptions data */)) { - Serial.println("PASSED"); + Serial.println("ok"); FileMetaInfo meta = fbdo.metaData(); Serial.printf("Name: %s\n", meta.name.c_str()); Serial.printf("Bucket: %s\n", meta.bucket.c_str()); @@ -109,15 +102,8 @@ void loop() Serial.printf("Token: %s\n", meta.downloadTokens.c_str()); Serial.printf("Media Link: %s\n", meta.mediaLink.c_str()); Serial.printf("Download URL: %s\n", fbdo.downloadURL().c_str()); - Serial.println("------------------------------------"); - Serial.println(); } else - { - Serial.println("FAILED"); - Serial.println("REASON: " + fbdo.errorReason()); - Serial.println("------------------------------------"); - Serial.println(); - } + Serial.println(fbdo.errorReason()); } } diff --git a/examples/Storage/Google_Cloud_Storage/Upload_File/Upload_File.ino b/examples/Storage/GoogleCloudStorage/UploadFile/UploadFile.ino similarity index 90% rename from examples/Storage/Google_Cloud_Storage/Upload_File/Upload_File.ino rename to examples/Storage/GoogleCloudStorage/UploadFile/UploadFile.ino index 905eb41c0..8e69c89a3 100644 --- a/examples/Storage/Google_Cloud_Storage/Upload_File/Upload_File.ino +++ b/examples/Storage/GoogleCloudStorage/UploadFile/UploadFile.ino @@ -43,8 +43,6 @@ FirebaseConfig config; bool taskCompleted = false; -String path = "/Test"; - //The Google Cloud Storage upload callback function void gcsUploadCallback(UploadStatusInfo info); @@ -67,6 +65,8 @@ void setup() Serial.println(WiFi.localIP()); Serial.println(); + Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); + /* Assign the Service Account credentials for OAuth2.0 authen */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; @@ -76,15 +76,8 @@ void setup() config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&config, &auth); + Firebase.reconnectWiFi(true); - -#if defined(ESP8266) - //Set the size of WiFi rx/tx buffers in the case where we want to work with large data. - fbdo.setBSSLBufferSize(1024, 1024); -#endif - - //Set the size of HTTP response buffers in the case where we want to work with large data. - fbdo.setResponseSize(1024); } //The Google Cloud Storage upload callback function @@ -111,8 +104,7 @@ void gcsUploadCallback(UploadStatusInfo info) Serial.printf("CRC32: %s\n", meta.crc32.c_str()); Serial.printf("Token: %s\n", meta.downloadTokens.c_str()); //only gcs_upload_type_multipart and gcs_upload_type_resumable upload types. Serial.printf("Download URL: %s\n", fbdo.downloadURL().c_str()); //only gcs_upload_type_multipart and gcs_upload_type_resumable upload types. - Serial.println("------------------------------------"); - Serial.println(); + } else if (info.status == fb_esp_gcs_upload_status_error) { @@ -126,8 +118,7 @@ void loop() { taskCompleted = true; - Serial.println("------------------------------------"); - Serial.println("Upload file via Google Cloud Storage JSON API test..."); + Serial.println("Upload file via Google Cloud Storage JSON API..."); /** * The following function uses Google Cloud Storage JSON API to upload the file (object). diff --git a/examples/Storage/Google_Cloud_Storage/Upload_File/data/media.mp4 b/examples/Storage/GoogleCloudStorage/UploadFile/data/media.mp4 similarity index 100% rename from examples/Storage/Google_Cloud_Storage/Upload_File/data/media.mp4 rename to examples/Storage/GoogleCloudStorage/UploadFile/data/media.mp4 diff --git a/library.json b/library.json index d0c8d8eae..8937f6119 100644 --- a/library.json +++ b/library.json @@ -1,6 +1,6 @@ { "name": "Firebase Arduino Client Library for ESP8266 and ESP32", - "version": "2.2.1", + "version": "2.2.2", "keywords": "communication, REST, esp32, esp8266, arduino", "description": "This client library provides the functions to work with Firebase Realtime database, Firestore, Storage and Cloud messaging.", "repository": { diff --git a/library.properties b/library.properties index b82974e21..2652c0377 100644 --- a/library.properties +++ b/library.properties @@ -1,6 +1,6 @@ name=Firebase Arduino Client Library for ESP8266 and ESP32 -version=2.2.1 +version=2.2.2 author=Mobizt diff --git a/src/Firebase_ESP_Client.cpp b/src/Firebase_ESP_Client.cpp index 2bb9f4113..db57735b3 100644 --- a/src/Firebase_ESP_Client.cpp +++ b/src/Firebase_ESP_Client.cpp @@ -1,9 +1,9 @@ /** - * Google's Firebase ESP Client Main class, Firebase_ESP_Client.h version 2.2.1 + * Google's Firebase ESP Client Main class, Firebase_ESP_Client.cpp v2.2.2 * * This library supports Espressif ESP8266 and ESP32 * - * Created May 17, 2021 + * Created May 19, 2021 * * This work is a part of Firebase ESP Client library * Copyright (c) 2021 K. Suwatchai (Mobizt) diff --git a/src/Firebase_ESP_Client.h b/src/Firebase_ESP_Client.h index 4ae546642..da50cc27a 100644 --- a/src/Firebase_ESP_Client.h +++ b/src/Firebase_ESP_Client.h @@ -1,9 +1,13 @@ +#ifndef FIREBASE_CLIENT_VERSION +#define FIREBASE_CLIENT_VERSION "2.2.2" +#endif + /** - * Google's Firebase ESP Client Main class, Firebase_ESP_Client.h version 2.2.1 + * Google's Firebase ESP Client Main class, Firebase_ESP_Client.h v2.2.2 * * This library supports Espressif ESP8266 and ESP32 * - * Created May 17, 2021 + * Created May 19, 2021 * * This work is a part of Firebase ESP Client library * Copyright (c) 2021 K. Suwatchai (Mobizt) diff --git a/src/README.md b/src/README.md index 76d269816..464de46cd 100644 --- a/src/README.md +++ b/src/README.md @@ -1,7 +1,7 @@ # Firebase Arduino Client Library for ESP8266 and ESP32 -Google's Firebase Arduino Client Library for ESP8266 and ESP32 v2.2.1 +Google's Firebase Arduino Client Library for ESP8266 and ESP32 v2.2.2 The default filessystem used in the library is flash and SD. diff --git a/src/addons/RTDBHelper.h b/src/addons/RTDBHelper.h index edfeaf3ed..7ad1ae6f0 100644 --- a/src/addons/RTDBHelper.h +++ b/src/addons/RTDBHelper.h @@ -1,11 +1,20 @@ #ifndef RTDBHelper_H #define RTDBHelper_H #include +#include "FirebaseFS.h" + +#if defined(FIREBASE_ESP_CLIENT) #include +#elif defined(FIREBASE_ESP32_CLIENT) || defined(FIREBASE_ESP8266_CLIENT) +#if defined(ESP32) +#include +#elif defined(ESP8266) +#include +#endif +#endif void printResult(FirebaseData &data) { - if (data.dataType() == "int") Serial.println(data.intData()); else if (data.dataType() == "float") @@ -18,7 +27,6 @@ void printResult(FirebaseData &data) Serial.println(data.stringData()); else if (data.dataType() == "json") { - Serial.println(); FirebaseJson &json = data.jsonObject(); //Print all object data Serial.println("Pretty printed JSON data:"); @@ -50,7 +58,6 @@ void printResult(FirebaseData &data) } else if (data.dataType() == "array") { - Serial.println(); //get array data from FirebaseData using FirebaseJsonArray object FirebaseJsonArray &arr = data.jsonArray(); //Print all array values @@ -86,11 +93,7 @@ void printResult(FirebaseData &data) } else if (data.dataType() == "blob") { - - Serial.println(); - std::vector blob = data.blobData(); - Serial.println(); for (size_t i = 0; i < blob.size(); i++) { if (i > 0 && i % 16 == 0) @@ -104,12 +107,8 @@ void printResult(FirebaseData &data) } else if (data.dataType() == "file") { - - Serial.println(); - File file = data.fileStream(); int i = 0; - while (file.available()) { if (i > 0 && i % 16 == 0) @@ -133,7 +132,7 @@ void printResult(FirebaseData &data) } } -void printResult(FirebaseStream &data) +void printResult(FIREBASE_STREAM_CLASS &data) { if (data.dataType() == "int") @@ -148,7 +147,6 @@ void printResult(FirebaseStream &data) Serial.println(data.stringData()); else if (data.dataType() == "json") { - Serial.println(); FirebaseJson *json = data.jsonObjectPtr(); //Print all object data Serial.println("Pretty printed JSON data:"); @@ -180,7 +178,6 @@ void printResult(FirebaseStream &data) } else if (data.dataType() == "array") { - Serial.println(); //get array data from FirebaseData using FirebaseJsonArray object FirebaseJsonArray *arr = data.jsonArrayPtr(); //Print all array values @@ -196,7 +193,6 @@ void printResult(FirebaseStream &data) { Serial.print(i); Serial.print(", Value: "); - FirebaseJsonData *jsonData = data.jsonDataPtr(); //Get the result data from FirebaseJsonArray object arr->get(*jsonData, i); @@ -217,11 +213,7 @@ void printResult(FirebaseStream &data) } else if (data.dataType() == "blob") { - - Serial.println(); - std::vector blob = data.blobData(); - Serial.println(); for (size_t i = 0; i < blob.size(); i++) { if (i > 0 && i % 16 == 0) @@ -235,12 +227,8 @@ void printResult(FirebaseStream &data) } else if (data.dataType() == "file") { - - Serial.println(); - File file = data.fileStream(); int i = 0; - while (file.available()) { if (i > 0 && i % 16 == 0) diff --git a/src/common.h b/src/common.h index 229a53a78..05f7c02f9 100644 --- a/src/common.h +++ b/src/common.h @@ -1,6 +1,6 @@ /** - * Created May 11, 2021 + * Created May 19, 2021 * * This work is a part of Firebase ESP Client library * Copyright (c) 2021 K. Suwatchai (Mobizt) @@ -577,6 +577,7 @@ struct fb_esp_stream_info_t std::string m_data = ""; std::string m_path = ""; std::string m_type_str = ""; + std::string m_event_type_str = ""; FirebaseJson *m_json = nullptr; }; diff --git a/src/rtdb/FB_RTDB.cpp b/src/rtdb/FB_RTDB.cpp index 8d510657b..1784353fb 100644 --- a/src/rtdb/FB_RTDB.cpp +++ b/src/rtdb/FB_RTDB.cpp @@ -1,9 +1,9 @@ /** - * Google's Firebase Realtime Database class, FB_RTDB.cpp version 1.0.16 + * Google's Firebase Realtime Database class, FB_RTDB.cpp version 1.0.17 * * This library supports Espressif ESP8266 and ESP32 * - * Created May 17, 2021 + * Created May 19, 2021 * * This work is a part of Firebase ESP Client library * Copyright (c) 2021 K. Suwatchai (Mobizt) @@ -3060,9 +3060,6 @@ void FB_RTDB::processErrorQueue(FirebaseData *fbdo, FirebaseData::QueueInfoCallb if (item.doublePtr) *item.doublePtr = fbdo->doubleData(); - Serial.println(fbdo->doubleData()); - Serial.println(*item.doublePtr); - fbdo->clearQueueItem(&item); fbdo->_qMan.remove(i); } @@ -4857,6 +4854,7 @@ void FB_RTDB::sendCB(FirebaseData *fbdo) mdata.sif->m_type = fbdo->_ss.rtdb.resp_data_type; mdata.sif->m_path = fbdo->_ss.rtdb.path; mdata.sif->m_type_str = fbdo->getDataType(mdata.sif->m_type); + mdata.sif->m_event_type_str = fbdo->_ss.rtdb.event_type; if (mdata.sif->m_type == d_json) mdata.sif->m_json = &fbdo->_ss.json; diff --git a/src/rtdb/FB_RTDB.h b/src/rtdb/FB_RTDB.h index 1c080d9f1..f7e531ff3 100644 --- a/src/rtdb/FB_RTDB.h +++ b/src/rtdb/FB_RTDB.h @@ -1,9 +1,9 @@ /** - * Google's Firebase Realtime Database class, FB_RTDB.h version 1.0.16 + * Google's Firebase Realtime Database class, FB_RTDB.h version 1.0.17 * * This library supports Espressif ESP8266 and ESP32 * - * Created May 17, 2021 + * Created May 19, 2021 * * This work is a part of Firebase ESP Client library * Copyright (c) 2021 K. Suwatchai (Mobizt) diff --git a/src/stream/FB_MP_Stream.cpp b/src/stream/FB_MP_Stream.cpp index 581216cb7..99a6a5e73 100644 --- a/src/stream/FB_MP_Stream.cpp +++ b/src/stream/FB_MP_Stream.cpp @@ -1,9 +1,9 @@ /** - * Google's Firebase MultiPathStream class, FB_MP_Stream.cpp version 1.0.2 + * Google's Firebase MultiPathStream class, FB_MP_Stream.cpp version 1.0.3 * * This library supports Espressif ESP8266 and ESP32 * - * Created May 5, 2021 + * Created May 19, 2021 * * This work is a part of Firebase ESP Client library * Copyright (c) 2021 K. Suwatchai (Mobizt) @@ -69,6 +69,7 @@ bool FIREBASE_MP_STREAM_CLASS::get(const String &path) char *buf = ut->strP(fb_esp_pgm_str_186); if (strcmp(type.c_str(), buf) == 0) type = sif->m_type_str.c_str(); + eventType = sif->m_event_type_str.c_str(); value = data.stringValue; dataPath = path; ut->delS(buf); @@ -87,6 +88,7 @@ bool FIREBASE_MP_STREAM_CLASS::get(const String &path) { sif->m_json->toString(value, true); type = sif->m_type_str.c_str(); + eventType = sif->m_event_type_str.c_str(); dataPath = sif->m_path.c_str(); res = true; } @@ -107,6 +109,7 @@ bool FIREBASE_MP_STREAM_CLASS::get(const String &path) value = sif->m_data.c_str(); dataPath = sif->m_path.c_str(); type = sif->m_type_str.c_str(); + eventType = sif->m_event_type_str.c_str(); res = true; } std::string().swap(p1); @@ -120,6 +123,7 @@ void FIREBASE_MP_STREAM_CLASS::empty() std::string().swap(sif->m_data); std::string().swap(sif->m_path); std::string().swap(sif->m_type_str); + std::string().swap(sif->m_event_type_str); dataPath.clear(); value.clear(); type.clear(); diff --git a/src/stream/FB_MP_Stream.h b/src/stream/FB_MP_Stream.h index ac6522e1b..096442eb9 100644 --- a/src/stream/FB_MP_Stream.h +++ b/src/stream/FB_MP_Stream.h @@ -1,9 +1,9 @@ /** - * Google's Firebase MultiPathStream class, FB_MP_Stream.h version 1.0.2 + * Google's Firebase MultiPathStream class, FB_MP_Stream.h version 1.0.3 * * This library supports Espressif ESP8266 and ESP32 * - * Created March 5, 2021 + * Created May 19, 2021 * * This work is a part of Firebase ESP Client library * Copyright (c) 2021 K. Suwatchai (Mobizt) @@ -54,6 +54,7 @@ class FIREBASE_MP_STREAM_CLASS String dataPath; String value; String type; + String eventType; private: