Git Product home page Git Product logo

firebase-arduino-wifinina's Introduction

Google Firebase Realtime Database Arduino Library based on WiFiNINA library

GitHub Sponsors

This library supports Arduino NANO 33 IoT, Arduino MKR WiFi 1010, Arduino MKR VIDOR 4000, Arduino Nano RP2040 Connect and Arduino UNO WiFi Rev.2.

This library aims to keep support low memory and flash space device like UNO WiFi Rev.2 with simple Firebase RTDB functions.

We have moved to the new library

Warning

This library is now deprecated but no further supports for feature request. We recommended the FirebaseClient library for ongoing supports. You have to read the library documentation thoroughly before use.

The new async FirebaseClient library is now availavle in Arduino IDE and PlatformIO's Library Manager.

The new library provides simpler APIs interface, faster and more reliable operations. It can use in both sync and async operations.

License

The MIT License (MIT)

Copyright (c) 2024 K. Suwatchai (Mobizt)

Permission is hereby granted, free of charge, to any person returning a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

firebase-arduino-wifinina's People

Contributors

dx724 avatar mobizt avatar zedanamr avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-arduino-wifinina's Issues

How to read Firebase timestamps

Hi. I am currently trying to read timestamps stored in Firebase on my Arduino Nano 33 IoT.
However timestamps are very high numbers. The current timestamp I am writing this message for example is: 1634573019348.

Using the getInt() function doesn't work because the return value only reaches up to 2147483647, which is the highest a long variable can get. Using unsigned long should work, however this data type as it looks to me is not supported by the library.

Is there any other way to read timestamps?
Thanks for your help :)

Firebase stream problem

Using mkr1010

Line 137

Error:
Call of overloaded println(long long int) is ambiguous

I'm not nearly good enough to solve this one myself but I think it has something to do with trying to print "int64Data" based on the suggestions on Google for "how to print int64" help would be much appreciated.

Edit: it seems this problem is in all of the version 1.2.0 and up

Connection lost or connection refused in Firebase stream after some time Arduino Nano IoT

Dear Mobizt,

Can you help me with the following. Since a few days I'm having problems with the Firebase connection to my Arduino nano 33 IoT. The Arduino establishes the code, but won't keep it running. After some time, it just says 'connection refused', or 'connection lost'. After that it says 'stream timeout'.

Maybe it's my code?

`

#include <Wire.h>
#include <Adafruit_NeoPixel.h>
#include "paj7620.h"
#include "Firebase_Arduino_WiFiNINA.h"

FirebaseData HeartbeatData;

#define PIN_RING 5
#define NUMPIXELS_RING 9 //Coded as GRB

String heartbeatLevel = ""; //Stresslevel indicator

int previousGestureTime = 0;

Adafruit_NeoPixel pixels_ring = Adafruit_NeoPixel(NUMPIXELS_RING, PIN_RING, NEO_RGB + NEO_KHZ800);

// constants for min and max PWM
const int minPWM = 0;
const int maxPWM = 65;

// Global Fade Value
// but be bigger than byte and signed, for rollover
float fadeValue = 0;
int InOrOut = 1;

// How smooth to fade?
float fadeIncrement = .075;
float fadeIncrementFire = .2;

// millis() timing Variables
int previousFadeMillis;
unsigned long previousDatabaseCheck;
unsigned long currentMillis = 0;
unsigned long previousMillis;

// How fast to increment?
const unsigned long fadeInterval = 3000;
const unsigned long fadeIntervalFire = 1000;
const unsigned long holdBreathInterval = 1; // Must be longer than time it takes to light the LEDS!

int excerciseID = 0;
boolean excerciseChosen = false;
boolean gestureOK = false;

boolean once = false;
boolean notBreathing = true;

void setup() {
pixels_ring.begin(); // This initializes the NeoPixel library.
pixels_ring.setPixelColor(NUMPIXELS_RING, pixels_ring.Color(0, 0, 0)); //Set all pixels to OFF
pixels_ring.show(); // This sends the updated pixel color to the hardware.
Serial.begin(9600);

uint8_t error = 0;
error = paj7620Init(); // initialize Paj7620 registers
if (error) {
Serial.print("INIT ERROR,CODE:");
Serial.println(error);
} else {
Serial.println("INIT OK");
}
Serial.println("Please input your gestures:\n");
Serial.print("Connecting to Wi-Fi");
int status = WL_IDLE_STATUS;
while (status != WL_CONNECTED) {
status = WiFi.begin(secret, secret);
Serial.print(".");
for (int i = 0; i < NUMPIXELS_RING; i = i + 1) {
pixels_ring.setPixelColor(i, pixels_ring.Color(0, 0, 0)); //White neutral color LEDS
pixels_ring.show();
}
delay(50);
}
Serial.println("Connected with IP: ");
Serial.println(WiFi.localIP());

for (int i = 0; i < NUMPIXELS_RING; i = i + 1) {
pixels_ring.setPixelColor(i, pixels_ring.Color(50, 0, 0)); //White neutral color LEDS
pixels_ring.show();
}
delay(2000);
for (int i = 0; i < NUMPIXELS_RING; i = i + 1) {
pixels_ring.setPixelColor(i, pixels_ring.Color(0, 0, 0)); //White neutral color LEDS
pixels_ring.show();
}

Firebase.begin("secret", "secret", "secret", "secret");
Firebase.reconnectWiFi(true);

if (!Firebase.beginStream(HeartbeatData, "/actions/excercise")) {
Serial.println("------Can't begin stream connection------");
Serial.println("REASON: " + HeartbeatData.errorReason());
Serial.println();
}
if (Firebase.setBool(HeartbeatData, "/actions/response", false)) {} //Variabelen uitzetten
if (Firebase.setBool(HeartbeatData, "/actions/stopped", false)) {} //Variabelen uitzetten
if (Firebase.setBool(HeartbeatData, "/actions/response-breath", false)) {} //Variabelen uitzetten
if (Firebase.setBool(HeartbeatData, "/actions/response-negative", false)) {} //Variabelen uitzetten
}

void loop() {
normalBehaviour();
}
void normalBehaviour() {
int val = 0;

if (!Firebase.readStream(HeartbeatData)) {
Serial.println("Can't read stream data");
Serial.println("REASON: " + HeartbeatData.errorReason());
Serial.println();
}
if (HeartbeatData.streamTimeout()) {
Serial.println("Stream timeout, resume streaming...");
Serial.println();
}

if (HeartbeatData.streamAvailable()) {
Serial.println("-------Stream Data available-------");
Serial.println("STREAM PATH: " + HeartbeatData.streamPath());
Serial.println("EVENT PATH: " + HeartbeatData.dataPath());
Serial.println("DATA TYPE: " + HeartbeatData.dataType());
Serial.println("EVENT TYPE: " + HeartbeatData.eventType());
Serial.print("VALUE: ");
if (HeartbeatData.dataType() == "int") {
Serial.println(HeartbeatData.intData());
}
Serial.println();
val = HeartbeatData.intData();
}

if (val == 101) {
heartbeatLevel = "high";
}
if (val == 100) {
heartbeatLevel = "normal";
}
if (val == 99) {
heartbeatLevel = "low";
}
if (val == 404) {
excerciseChosen = false;
gestureOK = false;
}
if (val == 303) {
gestureOK = false;
}
if (val == 304) {
gestureOK = true;
}
else if (val > 0 && val < 60) {
excerciseID = val;
excerciseChosen = true;
gestureOK == false;
}

else if (excerciseChosen == true) {
uint8_t data = 0, data1 = 0, error;
error = paj7620ReadReg(0x43, 1, &data);

if (excerciseID == 51 || excerciseID == 52) {
  if (gestureOK == false) {
    switch (data) {
      case GES_UP_FLAG:
        //some code
        break;
      case GES_DOWN_FLAG:
        //some code
        break;
      default:
        //some code
        break;
    }
  }

  else if (gestureOK == true) {
    switch (data) {
      case GES_FORWARD_FLAG:
        //some code
        break;
    }
  }
}

if (excerciseID == 1 || excerciseID == 2 || excerciseID == 6 || excerciseID == 7 || excerciseID == 21) {
  if (gestureOK == false) {
    switch (data) {
      case GES_UP_FLAG:
        //some code
        break;
      case GES_DOWN_FLAG:
        //some code
        break;
      default:
        //some code
        break;
    }
  } else if (gestureOK == true) {
    switch (data) {
      case GES_FORWARD_FLAG:
        //some code
        break;
    }
  }
}

}
}
`

Maybe it's the combination with the PAJ7620 Gesture sensor of the Neopixel library I'm using in my compelte code? Hope you can help me!

Greetz,

Fre

Bad Request Error (arduino uno wifi firebase)

A friend and I are working on a coding project and we are using an Arduino Wifi Rev 2 to connect to firebase. As we were doing so, we ran into a bit of an issue, but we can't figure it out. So, we simplified our code into just the connection part of it. Still, when we run our code, the error "bad request" returns. Could you help us out?

#include <ArduinoJson.h>
#include <Firebase_Arduino_WiFiNINA_HTTPClient.h>
#include <Firebase_Arduino_WiFiNINA.h>
#define FIREBASE_HOST "https://arduino-nitrate-fb-v1-default-rtdb.asia-southeast1.firebasedatabase.app"
#define FIREBASE_AUTH "8hH7udfKry2GQcjBSd3Pr2g3XQCnpIcGD7kRERC8"
#define WIFI_SSID "Dr.Asg HT-2.4g"
#define WIFI_PASSWORD "amudhan12"
FirebaseData firebaseData;
String path = "/IMU_LSM6DS3";
String jsonData;

void setup()
{
  Serial.begin(9600);
  delay(1000);
  Serial.println();
  Serial.println(" done");
  Serial.print("Connecting to WiFi…");
  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED) {
    status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print(".");
    delay(300);
  }
  Serial.print(" IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH, WIFI_SSID, WIFI_PASSWORD);
  Firebase.reconnectWiFi(true);
}

void loop()
{
  uploadData();
  delay(2000);
}


void uploadData()
{
  
  Serial.println(firebaseData.dataPath() + " = " + jsonData);
// Push data using pushJSON
  jsonData = "{\"parent_001\":\"parent 001 text\", \"parent 002\":{\"child_of_002\":123.456}}";
  if (Firebase.pushJSON(firebaseData, path + "/test/append", jsonData)) {
    Serial.println(firebaseData.dataPath()); //Should be "/test/append"
  //New created key/name
  Serial.println(firebaseData.pushName());
  //Absolute path of new appended data
    Serial.println(firebaseData.dataPath() + "/"+ firebaseData.pushName());
  }
  else {
    Serial.println("Error: " + firebaseData.errorReason());
  }   
}

.beginEnterprise

So I'd like to use this over an enterprise connection, and in the Wifinina library we'd use wifi.beginEnterprise to do that. I don't see such a method with this library but I do see a .begin method. Is there a way to use this library over an enterprise connection?

firebaseData.errorReason - Error: not found, 404 Not Found

Hi, I am trying to send data from my Arduino Uno WiFi Rev2 to firebase but it does not seem to work. Here is my code. I would like to send the number 1634631042000 to my real-time database. When I run the code, it connects to the internet but then when it tries to push data I get the error "Error: not found, 404 Not Found". Thank you

`/*

*/

//Example shows how to connect to Firebase RTDB and perform basic operation for set, get, push and update data to database

//Required WiFiNINA Library for Arduino from https://github.com/arduino-libraries/WiFiNINA

#include "Firebase_Arduino_WiFiNINA.h"

#define DATABASE_URL "humid-sample.firebaseio.com" //.firebaseio.com or ..firebasedatabase.app
#define DATABASE_SECRET ""
#define WIFI_SSID "
"
#define WIFI_PASSWORD "
_______"

//Define Firebase data object
FirebaseData fbdo;

void setup()
{

Serial.begin(9600);
delay(100);
Serial.println();

Serial.print("Connecting to Wi-Fi");
int status = WL_IDLE_STATUS;
while (status != WL_CONNECTED)
{
status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print(".");
delay(100);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();

//Provide the autntication data
Firebase.begin(DATABASE_URL, DATABASE_SECRET, WIFI_SSID, WIFI_PASSWORD);
Firebase.reconnectWiFi(true);

String path = "/test";
String jsonStr;

Serial.print("Set int... ");

unsigned long long val = 1634631042000;

if (Firebase.setInt(fbdo, path + "/int/data", val)) //support large number
{
Serial.println("ok");
Serial.println("path: " + fbdo.dataPath());
Serial.println("type: " + fbdo.dataType());
Serial.print("value: ");
if (fbdo.dataType() == "int")
Serial.println(fbdo.intData());
if (fbdo.dataType() == "int64")
Serial.println(fbdo.int64Data());
if (fbdo.dataType() == "uint64")
Serial.println(fbdo.uint64Data());
else if (fbdo.dataType() == "double")
Serial.println(fbdo.doubleData());
else if (fbdo.dataType() == "float")
Serial.println(fbdo.floatData());
else if (fbdo.dataType() == "boolean")
Serial.println(fbdo.boolData() == 1 ? "true" : "false");
else if (fbdo.dataType() == "string")
Serial.println(fbdo.stringData());
else if (fbdo.dataType() == "json")
Serial.println(fbdo.jsonData());
else if (fbdo.dataType() == "array")
Serial.println(fbdo.arrayData());
}
else
{
Serial.println("error, " + fbdo.errorReason());
}

Serial.println();

}

void loop()
{
}`

Firebase.deleteNode strange behavior

Hello,
I am facing a strange behavior with the Firebase.deleteNode function. Firebase_Arduino_WiFiNINA.h library version 1.1.4

I want to delete a node at a certain path in a firebase realtime database , and created the following function.

void deleteFBNode(String nodePath)
{

       Serial.println ("Delete Update Node Received ...");
             
       
       Serial.println (" Deleting at:" + nodePath);
      
        if ( Firebase.deleteNode(firebaseData,nodePath))
           {Serial.println ("Successfully deleted node at:");
             Serial.println (nodePath);}
       else
         {Serial.println ("Error deleteing data at:");
          Serial.println (nodePath);
          Serial.println(firebaseData.errorReason());}  

}

if i call this function from the void setup () section , it works well and deletes the node.
while if i call it from the void loop() section based on a trigger condition, it doesn't delete the node and it returns a "Successfully deleted node at:" ... the path provided.

the same nodePath value is passed to the function , and i tested it with passing a constant string value as a nodePath value.

Appreciate any input on this matter.

Regards

Nano 33 iot connection lost and then refused

Hi, I have implemented all the suggestions in previous issues but none of them work. I have updated the firmware with the correct Firebase SSL and secrets. I have also the correct Wi-Fi credentials. The hardware is also not an issue as the same code and PCB is working with MKR but not with nano 33 iot. The code works fine in submitting the data on the firebase cloud but stops working with the connection refused error first and then the connection lost error.
Can you suggest any other solution?

Getting empty errorReason

Hello! I am using the Arduino Uno WiFi Rev2.

When I try to use the any of the methods (get/set/push), I get a newline as the errorReason in my serial monitor. I have excluded http:// from the host string, as well as excluding a "/" at the end, and can successfully connect to my WiFi access point.

Here is a piece of my code, where I am trying to access the int value stored at this key. And I defined the firebase constants like how it is done in the basic example ino.

Would this be a problem with my Firebase.begin, or an issue with how I am trying to read the data?

  #include <Firebase_Arduino_WiFiNINA.h>
  #include <Firebase_Arduino_WiFiNINA_HTTPClient.h>

  // WiFi Connection
  Serial.print("Connecting to Wi-Fi");
  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED)
  {
    status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();


  // Firebase Connection
  FirebaseData firebaseData;
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH, WIFI_SSID, WIFI_PASSWORD);
  Firebase.reconnectWiFi(true);


  // Firebase data retrieval
  if (Firebase.getInt(firebaseData, "/test")) {
    if (firebaseData.dataType() == "int")
      Serial.println(firebaseData.intData());
  } else {
    //Failed, then print out the error detail
    Serial.println("----------Can't get data--------");
    Serial.println("REASON: " + firebaseData.errorReason());
    Serial.println("--------------------------------");
    Serial.println();
  }

And for reference, my serial monitor output:

Connecting to Wi-Fi..
Connected with IP: xxx.xxx.x.xx

----------Can't get data--------

--------------------------------

This library seems awesome and I would love to get it working for me, so any help would be appreciated!

Connection refused

Hi. I'm a young programer and i cant seam to get a break. I'm working on a arduino mkr wifi 1010. My friend has setup a firebase real time database, i would like to connect to it via this arduino and pull a json from it so i can format it to a usable state and use the data from the database to check if it maches a cody i imput through a 4x4 keypad. This project should be mostly done, except the logic to for checking and the actual connection becase my attempts to connect to this database are resulting in a refused connection message.
I don't know how to proceed? Can you help ?

This is the code I'm using:

#include <WiFi.h>
#include <WiFiUdp.h>
#include <Wire.h>
#include <Arduino.h>
#include <U8g2lib.h>
#include <Keypad.h>
#include "Firebase_Arduino_WiFiNINA.h"
using namespace std;

U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);

const byte ROWS = 4;
const byte COLS = 4;
const int MAX_LENGTH = 9;

char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};

byte rowPins[COLS] = {A4, A3, A2, A1};
byte colPins[ROWS] = {5, 4, 3, 2};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String input = "";

#define Firebase_Host "https://□□□□□□□□□□□□□□□□□.firebasedatabase.app/"
#define Firebase_Auth "EY□□□□□□□□□□□□□□□XCEwJUZh7gdwuAzwT"
#define WSsid "Vik"
#define Wpassword "ToJeMojeMeno"
String path = "/Skrinky";
String path2 = "/Objednávka";

const char* ssid = "Vik";
const char* password = "ToJeMojeMeno";

WiFiClient client;
unsigned long startTime;

class PingGoogle {
public: void ping() {
startTime = millis();
if (WiFi.begin(ssid, password)) {
if (client.connect("www.google.com", 80)) {
Serial.println("Connected to Google");
} else {
Serial.println("Failed to connect to Google");
}
client.stop();
Serial.println("Response time: " + String(millis() - startTime) + "ms");
delay(5000);
} else {
Serial.println("Failed to connect to WiFi network");
}
}
};

class PingServer {
public: void ping() {
unsigned long startTime = millis();
WiFiClient client;
if (WiFi.begin(ssid, password)) {
if (client.connect("https://bilza-8760c-default-rtdb.europe-west1.firebasedatabase.app/", 3315)) {
Serial.println("Connected to server");
client.stop();
unsigned long responseTime = millis() - startTime;
if (responseTime > 3000) {
Serial.println("Response time exceeded 3000ms");
client.stop();
return;
}
Serial.println("Response time: " + String(responseTime) + "ms");
} else {
Serial.println("Failed to connect to server");
}
} else {
Serial.println("Failed to connect to WiFi network");
}
delay(500);
}
};

PingGoogle pingGoogle;
PingServer pingServer;

void setup()
{
Serial.begin(9600);
Wire.begin();
u8g2.begin();
u8g2.setFont(u8g2_font_ncenB14_tr);
u8g2.firstPage();
u8g2.clearBuffer();
u8g2.drawStr(3,25,"Zadaj kod:");
while (!Serial) {
;
}

if (WiFi.begin(ssid, password) == WL_CONNECTED) {
Serial.println("Connected to WiFi");
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
} else {
Serial.println("Failed to connect to WiFi");
}

delay(500);

pingGoogle.ping();

Firebase.begin(Firebase_Host, Firebase_Auth, WSsid, Wpassword);

Firebase.reconnectWiFi(true);

FirebaseData data;

if (Firebase.getJSON(data, path)) {
Serial.println("Data Retrieved: ");
Serial.println(data.jsonData());
} else {
Serial.println("Error Retrieving Data: ");
Serial.println(data.errorReason());
}
if (Firebase.getJSON(data, path2)) {
Serial.println("Data Retrieved: ");
Serial.println(data.jsonData());
} else {
Serial.println("Error Retrieving Data: ");
Serial.println(data.errorReason());
}

}

void loop() {
u8g2.setFont(u8g2_font_ncenB14_tr);
u8g2.firstPage();
u8g2.clearBuffer();
u8g2.drawStr(3,25,"Zadaj kod:");
char key = keypad.getKey();

if (key)
{
if (key == 'A' || key == 'B' || key=='C' || key=='D' || input.length() >= MAX_LENGTH) {
input = "";
u8g2.clearBuffer();
u8g2.drawStr(5,25,"Zadaj kod:");

} else {
  input += key;
}        
do {
  u8g2.drawRFrame(0,0,127,63,7);
  
  u8g2.drawStr(5,50,input.c_str());     
  Serial.println(input.c_str());
}while ( u8g2.nextPage() );

}
}

this is my serial monitor:
obrázok_2023-02-11_213431227

this is my ruleset for my database:
obrázok_2023-02-11_213549577

Pushing array of data to firebase

Hi, I am trying to push sensor data to firebase from Arduino. I would like to push an array of data to firebase like about 100 sensor data per sec. Right now I am able to push data to firebase perfectly fine with this:

// compute the required size
const size_t CAPACITY = JSON_ARRAY_SIZE(100);
// allocate the memory for the document
StaticJsonDocument doc;
// create an empty array
JsonArray array = doc.to();
JsonObject obj = doc.as();
// add some values
array.add(a);
array.add(b);
array.add(c);
String output;
// serialize the array and send the result to Serial
serializeJsonPretty(doc, output);
if (Firebase.pushArray(fbdo, "/path2demo", output))
{
Serial.println("push array ok");
}else{
Serial.println("push array failed");
Serial.println(fbdo.errorReason());
}

But I would like to increase the frequency of data that is being sent over to firebase preferably 10Hz since with the code above Im only getting about 2Hz
I am trying to use this:``
String abc = "["1,","2,","3,"]";
if (Firebase.pushArray(fbdo, "/anumber", abc)) {
Serial.println("ok");
}
but I keep getting an error: expected ',' or ';' before numeric constant

And I am unsure how to move forward. Thank you in advance for the help!

Automatoc node when using push method

Dear mobizt,

I'm running on a project using nano and firebase, thankfully I found your helpful library.
But when I tried to push some value using push() method, seems Firebase generate an automatic ID using random character.
Can we eliminate that process so we can pass our json string as we want ?
Thanks and best regards,
Hery

Arduino Nano Connect

Hello!

I am working on Arduino NANo connect on Low power Solution.

I have a problem when I turn off the Wifi.

At first turn off the Wifi NINA with the command "WiFi.end();" and when I try to update the value on Firebase and turn on the WiFi again the Wifi Turns on well but I can't update any value after that My board starts to blinking LED on board.

Is Anny a solution?? or does exist any sequence specific to reconnecting to Firebase after Wifi connection is lost?

Firebase PushJSON

Hi @mobizt , I have a temperature and humidity sensor testing on an Arduino MKR Wifi 1010 board. I got the sensor values stored as float and would like to pushJSON to Firebase and as mentioned in your Readme, you are using the original ArduinoJson library. However, I keep getting bad request and invalid data type. Could you elaborate further how you push a float data type to Firebase via pushJSON?

The following is my code example:

#include <Wire.h>
#include <Adafruit_AM2315.h>
#define ARDUINOJSON_ENABLE_ARDUINO_STRING_1
#include <ArduinoJson.h>
#include <Firebase_Arduino_WiFiNINA.h>

Adafruit_AM2315 am2315;

float temperature, humidity; // declare sensor data type

#define FIREBASE_HOST "***"
#define FIREBASE_AUTH "***"

#define WIFI_SSID "***"
#define WIFI_PASSWORD "***"

//Define Firebase data object
FirebaseData firebaseData;

// Firebase data path
String path = "/UNO_WiFi_REV2_Test";


void setup() {
  Serial.begin(9600);
  delay(100);

  Serial.print("Connecting to Wi-Fi");
  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED)
  {
    status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  // Provide the authentication data
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH, WIFI_SSID, WIFI_PASSWORD);
  Firebase.reconnectWiFi(true);
  
  
  while (!Serial) {
    delay(10);
  }
  Serial.println("AM2315 Test!");

  if (! am2315.begin()) {
     Serial.println("Sensor not found, check wiring & pullups!");
     while (1);
  }
}

void loop() {

  if (! am2315.readTemperatureAndHumidity(&temperature, &humidity)) {
    Serial.println("Failed to read data from AM2315");
    return;
  }
  Serial.print("Temp *C: "); Serial.println(temperature);
  Serial.print("Hum %: "); Serial.println(humidity);

  FirebasePush(); // push to Firebase database

  delay(3000);
}

// Function to push data to database
void FirebasePush() {

  Serial.println("-----------------------------------");
  Serial.println("----------Begin Push Test----------");
  Serial.println("-----------------------------------");
  Serial.println();

  String json2 = "{\"Temperature\":temperature,\"Humidity\":humidity}";

    if (Firebase.pushJSON(firebaseData, path + "/Sensors/Temp&Humid_Sensors", json2))
    {
      Serial.println("----------Push result-----------");
      Serial.println("PATH: " + firebaseData.dataPath());
      Serial.print("PUSH NAME: ");
      Serial.println(firebaseData.pushName());
      Serial.println("--------------------------------");
      Serial.println();
    }
    else
    {
      Serial.println("----------Can't push data--------");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println("--------------------------------");
      Serial.println();
    }
}

Please advise if I am parsing the data into the String json2 in the wrong way. Very much appreciated :)

WiFiNINA Watchdog Implementation with Firebase Read/Write

Hi - The WiFiNINA library includes a function void WiFiClass::setFeedWatchdogFunc(FeedHostProcessorWatchdogFuncPointer func), and the library seems to call void WiFiClass::feedWatchdog() periodically.

Since your library is built upon WiFiNINA, will the watchdog function continue to be fed if I declare it before calling your functions?

I want to make sure that if a poor WiFi signal causes a read/write function to take longer than the max watchdog reset time (16s), that it won't cause my chip to reset.

Thanks!

Couldn't get my Arduino to update my Firebase

Hello. I am currently using an Arduino MKR Wifi 1010 Board along with an MKR Env Shield. Here is the code I currently have:

#include "Firebase_Arduino_WiFiNINA.h"
#include <WiFiNINA.h>
#include <Arduino_MKRENV.h>

#define FIREBASE_URL "https://nasahunch-174c5-default-rtdb.firebaseio.com/"
#define FIREBASE_SECRET ""
#define WIFI_SSID ""
#define WIFI_PASSWORD ""

//Define Firebase data object
FirebaseData fbdo;

void setup() {
  Serial.begin(9600);
  Serial.println("Connecting to Wi-Fi");

  int status = WL_IDLE_STATUS;

  while (status != WL_CONNECTED) {
    status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print(".");
    delay(300);
  }

  if (status == WL_CONNECTED) {
    Serial.println("\nConnected to Wi-Fi");
    Serial.println("Initializing Firebase");
  } else {
    Serial.println("\nFailed to connect to Wi-Fi");
  }

  // Initialize Firebase
  Firebase.begin(FIREBASE_URL, FIREBASE_SECRET, WIFI_SSID, WIFI_PASSWORD);

  // Initialize environmental sensor
  if (!ENV.begin()) {
    Serial.println("Failed to initialize ENV sensor!");
    while (1);
  }
  Serial.println("ENV sensor initialized");
}

void loop() {
  // Read sensor data
  bool temperature_C = ENV.readTemperature();
  bool temperature_F = ENV.readTemperature(FAHRENHEIT);
  bool humidity = ENV.readHumidity();
  bool pressure = ENV.readPressure();
  bool luminosity = ENV.readIlluminance();


  if (Firebase.setBool(fbdo, "/temperature_C", temperature_C)) {
    Serial.println("Temperature_C updated successfully");
  } else {
    Serial.println("Failed to update Temperature_C");
  }

  if (Firebase.setBool(fbdo, "/temperature_F", temperature_F)) {
    Serial.println("Temperature_F updated successfully");
  } else {
    Serial.println("Failed to update Temperature_F");
  }

  if (Firebase.setBool(fbdo, "/humidity", humidity)) {
    Serial.println("Humidity updated successfully");
  } else {
    Serial.println("Failed to update Humidity");
  }

  if (Firebase.setBool(fbdo, "/pressure", pressure)) {
    Serial.println("Pressure updated successfully");
  } else {
    Serial.println("Failed to update Pressure");
  }

  if (Firebase.setBool(fbdo, "/luminosity", luminosity)) {
    Serial.println("Luminosity updated successfully");
  } else {
    Serial.println("Failed to update Luminosity");
  }

  // Print data to serial monitor
  Serial.print("Temperature_C: ");
  Serial.print(temperature_C);
  Serial.println(" °C");

  Serial.print("Temperature_F: ");
  Serial.print(temperature_F);
  Serial.println(" °F");

  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.println(" %");

  Serial.print("Pressure: ");
  Serial.print(pressure);
  Serial.println(" Pa");

  Serial.print("Luminosity: ");
  Serial.print(luminosity);
  Serial.println(" lux");

  delay(1000); // Wait for 1 second before sending data again
}

Does the FIREBASE_SECRET part cause the problem? I did define it properly but I didn't want to put it on GitHub. I am currently stuck on where the problem might be. Just in case, here are the steps I took to get the FIREBASE_SECRET:

  1. Went to project settings after clicking on the gear in the top left corner.
  2. Headed over to Service Accounts
  3. Clicked on Database Secrets and grabbed the thing from there. I only have one secret key so there's no possibility for me to mix it with something else.

Can anyone please help me?

Connection Refused

getting connection refused issue
I already applied firebase database project path without https:// and without last / symbol and also added Firebase database secret but it this API is not working even on example codes
Can anyone help?

Connection Refused

I am getting connection refused when trying to connect to my firebase RTDB in the example "Basic" any idea why this might be happening?

Can't set data reason: Connection Refused

I can not set data to firebase from Arduino Nano Iot 33. It was working perfectly before and the code is working 100% fine as I have tested it before and it was working fine but suddenly it has started to give an error "can't set data REASON: connection refused". I have a connection to internet and it works fine as it say Connected with IP: xxx.xxx.x.xx. I have tested the connection to same database from esp8266 and it works fine as well. I have added all the details correctly and this same code was working perfectly fine before. Your help in this matter will highly be appreciated!

Unable to specify pushId

It seems as though you're limited to using the random push Id assigned by firebase. This is a feature request to add that as a push parameter.

Writing data does not work with two streams

When I am using two concurrent streams, writing data does not work anymore:

Example:

/*
 * Created by K. Suwatchai (Mobizt)
 * 
 * Email: [email protected]
 * 
 * Github: https://github.com/mobizt
 * 
 * Copyright (c) 2021 mobizt
 *
*/

//Example shows how to connect to Firebase RTDB and get stream connection

//Required WiFiNINA Library for Arduino from https://github.com/arduino-libraries/WiFiNINA

#include "Firebase_Arduino_WiFiNINA.h"

#define DATABASE_URL "xx" //<databaseName>.firebaseio.com or <databaseName>.<region>.firebasedatabase.app
#define DATABASE_SECRET "xx"

#define WIFI_SSID "xx"
#define WIFI_PASSWORD "xx"

//Define Firebase data object
FirebaseData fbdo;

FirebaseData stream;
FirebaseData stream2;

unsigned long sendDataPrevMillis = 0;

String path = "/table_config/CUywk9RhoFTWTZTD4KuNcMvFDBC2/mcu_read/123456789";
String path2 = "/table_config/CUywk9RhoFTWTZTD4KuNcMvFDBC2/mcu_read_write/123456789";

int count = 0;

void setup()
{

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

  Serial.print("Connecting to Wi-Fi");
  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED)
  {
    status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print(".");
    delay(100);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  //Provide the autntication data
  Firebase.begin(DATABASE_URL, DATABASE_SECRET, WIFI_SSID, WIFI_PASSWORD);
  Firebase.reconnectWiFi(true);

  if (!Firebase.beginStream(stream, path))
  {
    Serial.println("Can't connect stream, " + stream.errorReason());
    Serial.println();
  }

  if (!Firebase.beginStream(stream2, path2))
  {
    Serial.println("Can't connect stream, " + stream2.errorReason());
    Serial.println();
  }
}

void loop()
{

  if (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)
  {
    sendDataPrevMillis = millis();
    count++;

    Serial.print("Set string... ");

    if (Firebase.setString(fbdo, path + "/string", "Hello World! " + String(count)))
    {
      Serial.println("ok");
      Serial.println("path: " + fbdo.dataPath());
      Serial.println("type: " + fbdo.dataType());
      Serial.print("value: ");
      if (fbdo.dataType() == "int")
        Serial.println(fbdo.intData());
      if (fbdo.dataType() == "int64")
        Serial.println(fbdo.int64Data());
      if (fbdo.dataType() == "uint64")
        Serial.println(fbdo.uint64Data());
      else if (fbdo.dataType() == "double")
        Serial.println(fbdo.doubleData());
      else if (fbdo.dataType() == "float")
        Serial.println(fbdo.floatData());
      else if (fbdo.dataType() == "boolean")
        Serial.println(fbdo.boolData() == 1 ? "true" : "false");
      else if (fbdo.dataType() == "string")
        Serial.println(fbdo.stringData());
      else if (fbdo.dataType() == "json")
        Serial.println(fbdo.jsonData());
      else if (fbdo.dataType() == "array")
        Serial.println(fbdo.arrayData());
    }
    else
    {
      Serial.println("error, "+ fbdo.errorReason());
    }
    Serial.println();
  }

  if (!Firebase.readStream(stream))
  {
    Serial.println("Can't read stream, "+ stream.errorReason());
  }

  if (stream.streamTimeout())
  {
    //Serial.println("Stream timed out, resuming...");
  }

  if (stream.streamAvailable())
  {
    count++;
    if (stream.dataType() == "null")
      count = 0;

    Serial.println("Stream data received... ");
    Serial.println("stream path: " + stream.streamPath());
    Serial.println("event path: " + stream.dataPath());
    Serial.println("data type: " + stream.dataType());
    Serial.println("event type: " + stream.eventType());
    Serial.print("value: ");
    if (stream.dataType() == "int")
      Serial.println(stream.intData());
    if (stream.dataType() == "int64")
      Serial.println(stream.int64Data());
    if (stream.dataType() == "uint64")
      Serial.println(stream.uint64Data());
    else if (stream.dataType() == "double")
      Serial.println(stream.doubleData());
    else if (stream.dataType() == "float")
      Serial.println(stream.floatData());
    else if (stream.dataType() == "boolean")
      Serial.println(stream.boolData() == 1 ? "true" : "false");
    else if (stream.dataType() == "string")
      Serial.println(stream.stringData());
    else if (stream.dataType() == "json")
      Serial.println(stream.jsonData());
    else if (stream.dataType() == "array")
      Serial.println(stream.arrayData());
    Serial.println();
  }

  if (!Firebase.readStream(stream2))
  {
    Serial.println("Can't read stream, "+ stream2.errorReason());
  }

  if (stream2.streamTimeout())
  {
    //Serial.println("Stream timed out, resuming...");
  }

  if (stream2.streamAvailable())
  {
    count++;
    if (stream2.dataType() == "null")
      count = 0;

    Serial.println("Stream data received... ");
    Serial.println("stream path: " + stream2.streamPath());
    Serial.println("event path: " + stream2.dataPath());
    Serial.println("data type: " + stream2.dataType());
    Serial.println("event type: " + stream2.eventType());
    Serial.print("value: ");
    if (stream2.dataType() == "int")
      Serial.println(stream2.intData());
    if (stream2.dataType() == "int64")
      Serial.println(stream2.int64Data());
    if (stream2.dataType() == "uint64")
      Serial.println(stream2.uint64Data());
    else if (stream2.dataType() == "double")
      Serial.println(stream2.doubleData());
    else if (stream2.dataType() == "float")
      Serial.println(stream2.floatData());
    else if (stream2.dataType() == "boolean")
      Serial.println(stream2.boolData() == 1 ? "true" : "false");
    else if (stream2.dataType() == "string")
      Serial.println(stream2.stringData());
    else if (stream2.dataType() == "json")
      Serial.println(stream2.jsonData());
    else if (stream2.dataType() == "array")
      Serial.println(stream2.arrayData());
    Serial.println();
  }
}

image

Is this a bug, or are concurrent streams not supported?
Should I turn off the stream before writing and turn it on again after that? Is there another solution?

Issue with WiFiNINA syntax with new Firebase library

I was using some code that was used with an older version of Firebase_Arduino-WiFiNINA, when I went to verify the code I was met with "'WL_IDLE_STATUS' was not declared in this scope" error. Please see the code below (credit to Cytron Technologies, https://www.youtube.com/watch?v=xNOk2o4iKZM).

I went through some troubleshooting and found if I replace the <Firebase_Arduino_WiFiNINA.h> library with <WiFiNINA.h> and <SPI.h> libraries I have no error with the int status (of course then I do not have a firebase library and all the firebase functions error out).

Please let me know if there is a work around!

#include <Arduino_LSM6DS3.h>
#include <Firebase_Arduino_WiFiNINA.h>


char FIREBASE_HOST[] = "host.domain.example";
char FIREBASE_AUTH[] = "firebase.secret.code.example";
char WIFI_SSID[] = "wifi.ssid.example";
char WIFI_PASSWORD[] = "wifi.password.example";



FirebaseData firebaseData;


String path = "/IMU_LSM6DS3";
String jsonStr;

void setup()
{
  Serial.begin(9600);
  delay(1000);
  Serial.println();

  Serial.print("Initialize IMU sensor…");
  if (!IMU.begin()) {
    Serial.println(" failed!");
    while (1);
  }
  Serial.println(" done");
  Serial.print("Accelerometer sample rate = ");
  Serial.print(IMU.accelerationSampleRate());
  Serial.println(" Hz");
  int status = WL_IDLE_STATUS;
  Serial.print("Connecting to WiFi…");

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

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH, WIFI_SSID, WIFI_PASSWORD);
  Firebase.reconnectWiFi(true);
}

void loop()
{
  float x, y, z;

  // Read IMU acceleration data
  if (IMU.accelerationAvailable()) {
    IMU.readAcceleration(x, y, z);

    // Send data to Firebase with specific path
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/X", x)) {
      Serial.println(firebaseData.dataPath() + " = " + x);
    }
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/Y", y)) {
      Serial.println(firebaseData.dataPath() + " = " + y);
    }
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/Z", z)) {
      Serial.println(firebaseData.dataPath() + " = " + z);
    }

    // Push data using pushJSON
    jsonStr = "{\"X\":" + String(x,6) + ",\"Y\":" + String(y,6) + ",\"Z\":" + String(z,6) + "}";

    if (Firebase.pushJSON(firebaseData, path + "/2-pushJSON", jsonStr)) {
      Serial.println(firebaseData.dataPath() + " = " + firebaseData.pushName());
    }
    else {
      Serial.println("Error: " + firebaseData.errorReason());
    }

    Serial.println();
    delay(2000);
  }
}
```

Token error, connection refused, connection lost

Dear Mobizt,

Can you help me with the following. Since a few days I'm having problems with the Firebase connection to my esp32 dev kit. The esp32 establishes the code, but won't keep it running. After some time, it just says 'connection refused', or 'connection lost'. After that it says 'stream timeout'. I checked wifi status on when error occurred. Wifi status is connected in every time. Sometimes token refresh token automatically once or twice. After few hours on refreshing token get error. Never refresh the token. Is their any way to close the firebase connection and re initiate again when error occurs.? Firebase.reset() not works because callback function didn't stop after errors.

Issue with getJson when using OLED display libary

The code works perfectly fine on it's own. However when I add the following it fails:

// OLED display library from Adafruit
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); // commenting this line works - getJson is successful.

----The following line in code fails
Serial.println ("Getting Json... ");

if (Firebase.getJSON(firebaseData, "/")) { // this line is failing
// success code
}
else {
// fail
}

Unable to figure out how the two libraries are conflicting.
Board used: MKR 1010
Arduino IDE: 1.8.11 on WIndows 10
ArduinoJson v5 (used for parsing Json)

Any pointers/ guidance appreciated.

Connection refused IoT 33 Wifi

Hi! I'm trying to connect to my Firebase Database with my Arduino nano IoT 33 Wifi and always gets "connection refused"

imagen

I try with desktop IDE and arduino IoT cloud and always gets "connection refused".

I use the example code and the rules are read/write: true.
I don't know why is wrong

SSL Root Certificate Questions

Hi Mobizt,

This is more of a question rather than an issue.

My code was running great for about 7 days, when the Arduino IOT 33 stopped functioning, and generated an "error, connection refused" error code. I had not updated the SSL certificates on the WIFI NINA hardware for my Firebase database. I have since added this, and am hoping it will resolve the issue.

Ultimately, I plan on using this same design in a product, which could be distributed to people. I have concerns that the SSL certificates will expire in 1 year, and I will not be able to update them without physically plugging into the hardware and pushing new ones.

So I have a few questions for you.

  1. Why are the SSL root certificates required for use with Firebase and this library? Is there any way to run your library without SSL root certificates?

  2. Do you know if there is a sketch or other method that can be used to remotely push SSL certificates to the NINA hardware?

Thanks again

[SOLVED] Bad Request Error received on default examples

Hi, I am only receiving bad request errors while connecting to Firebase.

I was following this project at first, then I also tried to run the default examples of this lib, but still I am only receiving errors.

This one is from the Basic example:

23:21:22.263 -> .
23:21:22.552 -> Connected with IP: 192.168.73.250
23:21:22.552 -> 
23:21:22.552 -> -----------------------------------
23:21:22.552 -> ----------Begin Set Test-----------
23:21:22.552 -> -----------------------------------
23:21:22.552 -> 
23:21:25.926 -> ----------Can't set data--------
23:21:25.926 -> REASON: bad request
23:21:25.926 -> --------------------------------
23:21:25.926 -> 
23:21:29.401 -> ----------Can't set data--------
23:21:29.401 -> REASON: bad request
23:21:29.401 -> --------------------------------
23:21:29.401 -> 
23:21:32.725 -> ----------Can't set data--------
23:21:32.725 -> REASON: bad request
23:21:32.725 -> --------------------------------
23:21:32.725 -> 
23:21:35.950 -> ----------Can't set data--------
23:21:35.950 -> REASON: bad request
23:21:35.950 -> --------------------------------
23:21:35.950 -> 
23:21:39.250 -> ----------Can't set data--------
23:21:39.250 -> REASON: bad request
23:21:39.250 -> --------------------------------
23:21:39.250 -> 
23:21:42.525 -> ----------Can't set data--------
23:21:42.525 -> REASON: bad request
23:21:42.525 -> --------------------------------
23:21:42.525 -> 
23:21:46.208 -> ----------Can't set data--------
23:21:46.208 -> REASON: bad request
23:21:46.208 -> --------------------------------
23:21:46.208 -> 
23:21:49.579 -> ----------Can't set data--------
23:21:49.579 -> REASON: bad request
23:21:49.579 -> --------------------------------
23:21:49.579 -> 
23:21:52.983 -> ----------Can't set data--------
23:21:52.983 -> REASON: bad request
23:21:52.983 -> --------------------------------
23:21:52.983 -> 

Wifi ping is working fine, and Firebase Host and Secret are set.
I am wondering if I am missing something on Firebase configuration, like Auth (I also enabled Anonymous log in). Do you have any suggestions?

readStream error

Hi
After some minutes of use, Firebase.readStream(firebaseData) returns false, also if data is still readable and firebaseData.streamTimeout() returns false.
I'm now ignoring that message

if (!Firebase.readStream(firebaseData)) {
    Serial.print("Can't read stream data");
}

Nano RP2040 Connect support

The Nano RP2040 Connect is built on the same platform, right?
Will it also be supported in the future, or is it already?

Connection refused when using two FirebaseData objects

Hi,

I'm trying to use different FirebaseData objects for posting data and reading from a stream not to re-connect stream every
time after posting data, according to comment in Firebase_Arduino_WiFiNINA.h:

 Using the same Firebase Data object for stream read/monitoring associated
 with getXXX, setXXX, pushXXX, updateNode and deleteNode will break or quit
 the current stream connection.

After connecting to the stream I can't push data anymore, and after pushing data I can't read from the stream (depending on what happens first).

Is this use-case supported?

The code (based on Basic and Stream examples):

#include "Firebase_Arduino_WiFiNINA.h"

#define FIREBASE_HOST "crocus-bd208.firebaseio.com"
#define FIREBASE_AUTH "PLMQG02DK1S4muXnxgHuXNnxZRpLXeBw0qFP4LOv"
#define WIFI_SSID "TresspassersW"
#define WIFI_PASSWORD "SayFriendAndEnter"

//Define Firebase data object
FirebaseData firebaseData;
FirebaseData firebaseStream;

String path = "/MKR1010_stream_test";

void setup()
{

  Serial.begin(9600);
  delay(100);
  Serial.println();

  Serial.print("Connecting to Wi-Fi");
  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED)
  {
    status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  //Provide the autntication data
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH, WIFI_SSID, WIFI_PASSWORD);
  Firebase.reconnectWiFi(true);

  String jsonStr;


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

void loop()
{

  
  if (Firebase.pushInt(firebaseData, path + "/Push/Int", 1))
  {
    Serial.println("----------Push result-----------");
    Serial.println("PATH: " + firebaseData.dataPath());
    Serial.print("PUSH NAME: ");
    Serial.println(firebaseData.pushName());
    Serial.println("--------------------------------");
    Serial.println();
  }
  else
  {
    Serial.println("----------Can't push data--------");
    Serial.println("REASON: " + firebaseData.errorReason());
    Serial.println("--------------------------------");
    Serial.println();
  }
  
  
  if (!Firebase.readStream(firebaseStream))
  {
    Serial.println("Can't read stream data");
    Serial.println("REASON: " + firebaseStream.errorReason());
    Serial.println();
  }

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

  if (firebaseStream.streamAvailable())
  {
    Serial.println("-------Stream Data available-------");
    Serial.println("STREAM PATH: " + firebaseStream.streamPath());
    Serial.println("EVENT PATH: " + firebaseStream.dataPath());
    Serial.println("DATA TYPE: " + firebaseStream.dataType());
    Serial.println("EVENT TYPE: " + firebaseStream.eventType());
    Serial.print("VALUE: ");
    if (firebaseStream.dataType() == "int")
      Serial.println(firebaseStream.intData());
    else if (firebaseStream.dataType() == "float")
      Serial.println(firebaseData.floatData());
    else if (firebaseStream.dataType() == "boolean")
      Serial.println(firebaseStream.boolData() == 1 ? "true" : "false");
    else if (firebaseStream.dataType() == "string")
      Serial.println(firebaseStream.stringData());
    else if (firebaseStream.dataType() == "json")
      Serial.println(firebaseStream.jsonData());
    Serial.println();
  }
 

  delay(1000);
}

The output:

Connected with IP: 192.168.178.132

----------Can't push data--------
REASON: connection refused
--------------------------------

----------Can't push data--------
REASON: connection refused
--------------------------------

Can't read stream data
REASON: not connected

Stream timeout, resume streaming...

Too many ")" within the "READ" example code

Within the section Read, Store, Update, Delete, Backup and Restore Data there is some example code, and the following line has one too many brackets ")". Deleting one bracket ")" resolves the code.

if (firebaseData.dataType() == "int")) {

This was from the example code below - PS Thanks for the awesome work you've done!!!

Here is the example usage to read integer value from defined database path "/test/int".

//Read integer value from database at "/test/int" 

  int val = 0;

  if (Firebase.getInt(firebaseData, "/test/int")) {

    //Success, then read the payload value

    //Make sure payload value returned from server is integer
    //This prevent you to get garbage data
    if (firebaseData.dataType() == "int")) {
      val = firebaseData.intData();
      Serial.println(val);
    }

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

error: connection refused

I've read this one and this one. I've compiled with all your solutions but still, the same problem occurs.

My firmware is latest:

and here are my
image

I've also renew the database secret.

My FIREBASE_HOST is in correct syntax.
image

My board is Arduino Nano 33 IOT

Sorry for the inconvenience. Badly need your help for this!

Can't get examples to execute

Hi there - trying to run the basic examples to run but I keep getting error 5 (Connection Refused) consistently. No matter what I do.

I am using the following for the database URL
#define DATABASE_URL "poolmonitor-b661a-default-rtdb.firebaseio.com" //.firebaseio.com or ..firebasedatabase.app
and the database secret provided by google.

Wifi connects just fine, but I am struggling with getting a connection to firebase

Stream does not get new data when data is pushed

Hi,
I am using an Arduino Nano IoT to read a stream in the RTDB with the stream example at the path "/table_config/CUywk9RhoFTWTZTD4KuNcMvFDBC2/mcu_read/123456789"

I am pushing data with the Firebase JS SDK to the database to replace the data at the root node. When doing this, the data does not get received every time I would expect it. Therefore I checked another library also wrapping the Firebase REST API with Python, which should then be comparable to this one, right?

As you can see in the screenshots the data is received every time with python, but not on the Arduino. I also can see the data changing in the web console every time.
I am sorry, but I just do not understand that behaviour, as the Python library https://github.com/thisbejim/Pyrebase also works with the REST API, which should then get the same stream data in my opinion.

Bildschirmfoto 2022-02-22 um 20 16 29

Could you please explain what could be a reason for this? Do I really misunderstand something here with this library?
What would also really help me, is a way to further debug this. Is there a possibility?

Below you will find the Arduino code, the python code, js code and the json, that I am pushing.

Thanks in advance for your help.

Arduino code:

/*
 * Created by K. Suwatchai (Mobizt)
 * 
 * Email: [email protected]
 * 
 * Github: https://github.com/mobizt
 * 
 * Copyright (c) 2021 mobizt
 *
*/

//Example shows how to connect to Firebase RTDB and get stream connection

//Required WiFiNINA Library for Arduino from https://github.com/arduino-libraries/WiFiNINA

#include "Firebase_Arduino_WiFiNINA.h"

#define DATABASE_URL "" //<databaseName>.firebaseio.com or <databaseName>.<region>.firebasedatabase.app
#define DATABASE_SECRET ""
#define WIFI_SSID ""
#define WIFI_PASSWORD ""

//Define Firebase data object
FirebaseData fbdo;

FirebaseData stream;

unsigned long sendDataPrevMillis = 0;

String path = "/table_config/CUywk9RhoFTWTZTD4KuNcMvFDBC2/mcu_read/123456789";

int count = 0;

void setup()
{

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

  Serial.print("Connecting to Wi-Fi");
  int status = WL_IDLE_STATUS;

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

  //Provide the autntication data
  Firebase.begin(DATABASE_URL, DATABASE_SECRET, WIFI_SSID, WIFI_PASSWORD);
  Firebase.reconnectWiFi(true);

  if (!Firebase.beginStream(stream, path))
  {
    Serial.println("Can't connect stream, " + stream.errorReason());
    Serial.println();
  }
}

void loop()
{

  
  if (!Firebase.readStream(stream))
  {
    Serial.println("Can't read stream, "+ stream.errorReason());
  }

  if (stream.streamTimeout())
  {
    //Serial.println("Stream timed out, resuming...");
  }

  if (stream.streamAvailable())
  {
    count++;
    if (stream.dataType() == "null")
      count = 0;

    Serial.println("Stream data received... ");
    Serial.println("stream path: " + stream.streamPath());
    Serial.println("event path: " + stream.dataPath());
    Serial.println("data type: " + stream.dataType());
    Serial.println("event type: " + stream.eventType());
    Serial.print("value: ");
    if (stream.dataType() == "int")
      Serial.println(stream.intData());
    if (stream.dataType() == "int64")
      Serial.println(stream.int64Data());
    if (stream.dataType() == "uint64")
      Serial.println(stream.uint64Data());
    else if (stream.dataType() == "double")
      Serial.println(stream.doubleData());
    else if (stream.dataType() == "float")
      Serial.println(stream.floatData());
    else if (stream.dataType() == "boolean")
      Serial.println(stream.boolData() == 1 ? "true" : "false");
    else if (stream.dataType() == "string")
      Serial.println(stream.stringData());
    else if (stream.dataType() == "json")
      Serial.println(stream.jsonData());
    else if (stream.dataType() == "array")
      Serial.println(stream.arrayData());
    Serial.println();
  }
}

Python code:

import pyrebase

config = {
    "apiKey": "",
    "authDomain": "",
    "databaseURL": "",
    "storageBucket": ""
}

firebase = pyrebase.initialize_app(config)

# Get a reference to the database service
db = firebase.database()
auth = firebase.auth()
user = auth.sign_in_with_email_and_password("[email protected]", "12345678")

# Pass the user's idToken to the push method
#results = db.child("users").push(data, user['idToken'])


def stream_handler(message):
    print("event: " + message["event"])

    # >> put

    print("path: " + message["path"])

    # >> /-K7yGTTEp7O549EzTYtI

    print(message["data"])
    print("")
    # >> {'title': 'firebase', "body": "Python interface to the Google's Firebase REST APIs"}


my_stream = db.child("table_config").child("CUywk9RhoFTWTZTD4KuNcMvFDBC2").child(
    "mcu_read").child("123456789").stream(stream_handler, user['idToken'])

Javascript sdk using push function:

const sendConfig = (tableConfig: InitialTableState, tableId: string | number | null):
    Promise<ISendApiRequestResponse> => {
    return new Promise((resolve, reject) => {
        const userId = auth.currentUser?.uid
        const idPath = tableId !== null ? tableId : "general";
        const now = new Date();
        tableConfig.last_updated = Math.round(now.getTime() / 1000);

        db.ref(`/table_config/${userId}/mcu_read/${idPath}`).
            push(tableConfig).then((data) => {
                if (__DEV__) console.log("Updated whole config in fb db.")
                resolve({
                    error: false,
                    code: 0,
                });
            }).catch((error) => {
                console.log('error ', error)
                reject({
                    error: true,
                    code: -1,
                    message: error.message,
                });
            })
    })
}

The JSON:

{
    "configuration_per_state": {
        "Idle": {
            "allowed_effects": [
                0,
                2,
                6,
                1,
                3,
                5,
                4
            ],
            "brightness": 31,
            "default_effect": {
                "type": 0
            }
        },
        "In_Game": {
            "allowed_effects": [
                2,
                6,
                1,
                3,
                5,
                4
            ],
            "brightness": 57,
            "duration": 1200,
            "field_master": {
                "default_effect": {
                    "type": 2
                }
            },
            "field_slave": {
                "default_effect": {
                    "type": 2
                }
            },
            "limit_game_duration": true,
            "remaining_duration": 1200,
            "state": 0
        }
    },
    "id": "123456789",
    "last_updated": 1645558291,
    "name": "test",
    "state": "Idle",
    "wifi_mode": 1
}

Connection refused

I have the following error :

----------Can't set data--------
REASON: connection refused
--------------------------------

I have tried with both databaseURL and authDomain from the config.

const firebaseConfig = {
  apiKey: "secret",
  authDomain: "myproject.firebaseapp.com",
  databaseURL: "https://myproject-default-rtdb.europe-west1.firebasedatabase.app",
  projectId: "myproject",
  storageBucket: "myproject.appspot.com",
  messagingSenderId: "secret",
  appId: "secret"
};

I have used the database secret :

Capture d’écran 2021-04-08 à 09 50 58

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.