无法使用Nodemcu将数据上传到Firebase [英] Cannot upload data to firebase using Nodemcu

查看:198
本文介绍了无法使用Nodemcu将数据上传到Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的传感器正在正确收集数据,但没有将数据推送到Firebase.如预期的那样,Firebase.failed返回true,但Firebase.error为空.请为我提供代码,因为我的项目将在三天内完成.

我尝试更改FirebaseHttpClient.h文件中的指纹.我也尝试过使用"/"和不使用"/"来更改Firebase HOST.

#include "DHT.h"
#include <FirebaseArduino.h>
#include  <ESP8266WiFi.h>

#define FIREBASE_HOST "your-project.firebaseio.com"
#define FIREBASE_AUTH "69DtX********************"
#define WIFI_SSID "LAPTOP" // Change the name of your WIFI
#define WIFI_PASSWORD "********" // Change the password of your WIFI

#define DHTPIN 14    // Data Pin of DHT 11 , for NodeMCU D5 GPIO no. is 14

#define DHTTYPE DHT11   // DHT 11
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  WiFi.begin (WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
   delay(500);
    Serial.print(".");
  }
   dht.begin();
  Serial.println ("");
  Serial.println ("WiFi Connected!");
  Firebase.begin(FIREBASE_HOST,FIREBASE_AUTH);

}

void loop() {

  float h = dht.readHumidity();

  float t = dht.readTemperature();  // Reading temperature as Celsius (the default)
  String firehumid = String(h) + String("%");
  String firetemp = String(t) + String("C");
  Serial.println("Humidity = ");
  Serial.println(h);
  Serial.println("Temperature = ");
  Serial.println(t); 
  Firebase.setString("/Humidity",firehumid);
  Firebase.setString("/Temperature",firetemp);
  delay(4000);
  if(Firebase.failed())
  {
    Serial.println("error!");
    Serial.println(Firebase.error());
  }

}

解决方案

几天前,我遇到了同样的问题,并提出了大约一年前的草图. Firebase.failed()返回true,但是 error 为空.

据我所知,不建议使用(将其与秘密一起使用实时数据库)的旧方法(在项目设置的数据库秘密"页面上指出),并且有<替换为OAuth 2.0的a href ="https://firebase.google.com/docs/admin/setup?authuser=0" rel ="nofollow noreferrer"> Firebase Admin SDK .

但是,据我所知,到目前为止,还没有直接支持firebase身份验证的Arduino库,所以我想找到另一种方法来使其工作./p>

我设法找到了一种对我有效的解决方法,并且我认为它更适合于此类IOT应用,因为它在传感器端所需的资源更少.

对我来说,解决方案是使用 Firebase Cloud Functions http触发器. 基本上,您可以定义JS函数,而不是使用Firebase的Arduino库,从而可以存储或从数据库中检索数据,将其部署到Firebase并通过简单的 https http 通话.

所以我的arduino草图的相关部分看起来像这样:

     #include <ESP8266HTTPClient.h>
    HTTPClient http;

    // you will see this url, after you deployed your functions to firebase
    #define FIREBASE_CLOUDFUNCTION_URL "http://<your-function-url>.cloudfunctions.net/add"

    ...

    // Make sure you are connected to the internet before you call this function
    void uploadMeasurements(float lux, float ctemp, float hum) {
        String url = String(FIREBASE_CLOUDFUNCTION_URL) + "?lux=" + String(lux,2)
                            + "&temp=" + String(ctemp,2) + "&hum=" + String(hum,2); 

        http.begin(url);
        int httpCode = http.GET();

        // you don't have to handle the response, if you dont need it.
        String payload = http.getString();
        Serial.println(payload);

        http.end();
    }
 

我将度量放入查询参数中,但是您也可以将它们发送到请求的正文中.

我存储数据的云功能如下:

     const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();


    exports.add = functions.https.onRequest((request, response)=>
    {
        console.log('Called with queries: ', request.query, ' and body: ', request.body);
        var ref = admin.database().ref("any/endpoint/child");
        var childRef = ref.push();

        let weatherData = {
            lux: request.query.lux,
            temp: request.query.temp,
            hum: request.query.hum,
            // this automatically fills this value, with the current time
            timestamp : admin.database.ServerValue.TIMESTAMP 
        };

        childRef.set(
            weatherData
        );
        response.status(200).send("OK!");
    });
 

您可以初始化一个存储您的云功能的项目,并可以使用 Firebase CLI ,在您的项目文件夹中调用 firebase init ,然后通过设置过程选择cloudfunctions(我还选择了托管功能,因为我有一个前端来查看收集的数据.)

现在,我有一个使用此解决方案的小传感器,它每分钟都会上传一次测量结果,并且工作正常.

我希望这会有所帮助.

My sensor is collecting data correctly but is not pushing the data to Firebase. As expected Firebase.failed returns true but Firebase.error is empty. Please help me with the code as my project is due in three days.

I have tried changing the fingerprint in FirebaseHttpClient.h file. I have also tried changing the Firebase HOST with and without "/".

#include "DHT.h"
#include <FirebaseArduino.h>
#include  <ESP8266WiFi.h>

#define FIREBASE_HOST "your-project.firebaseio.com"
#define FIREBASE_AUTH "69DtX********************"
#define WIFI_SSID "LAPTOP" // Change the name of your WIFI
#define WIFI_PASSWORD "********" // Change the password of your WIFI

#define DHTPIN 14    // Data Pin of DHT 11 , for NodeMCU D5 GPIO no. is 14

#define DHTTYPE DHT11   // DHT 11
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  WiFi.begin (WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
   delay(500);
    Serial.print(".");
  }
   dht.begin();
  Serial.println ("");
  Serial.println ("WiFi Connected!");
  Firebase.begin(FIREBASE_HOST,FIREBASE_AUTH);

}

void loop() {

  float h = dht.readHumidity();

  float t = dht.readTemperature();  // Reading temperature as Celsius (the default)
  String firehumid = String(h) + String("%");
  String firetemp = String(t) + String("C");
  Serial.println("Humidity = ");
  Serial.println(h);
  Serial.println("Temperature = ");
  Serial.println(t); 
  Firebase.setString("/Humidity",firehumid);
  Firebase.setString("/Temperature",firetemp);
  delay(4000);
  if(Firebase.failed())
  {
    Serial.println("error!");
    Serial.println(Firebase.error());
  }

}

解决方案

I ran into the same problem a few days ago with a sketch that worked about a year ago. Firebase.failed() returned true, but the error was empty.

As far as I understand, the old way of using the realtime database with a secret is deprecated (as it states, on the database secrets page in your project settings), and there is the Firebase Admin SDK with OAuth 2.0 in the place of it.

However, as of posting this, as far as I know, there is no Arduino library that supports this authentication for firebase directly, so I wanted to find an other way to make it work.

I managed to find a workaround, which works for me, and I think is more suitable for these kinds of IOT applications, as it requires fewer resources on the sensors side.

The solution for me was using Firebase Cloud Functions, with http triggers. Basically instead of using an Arduino library for Firebase, you can define JS functions, that can store or retrieve your data from the database, deploy them to Firebase and call them in your Arduino sketch through simple https and http calls.

So the relevant part of my arduino sketch look like this:

    #include <ESP8266HTTPClient.h>
    HTTPClient http;

    // you will see this url, after you deployed your functions to firebase
    #define FIREBASE_CLOUDFUNCTION_URL "http://<your-function-url>.cloudfunctions.net/add"

    ...

    // Make sure you are connected to the internet before you call this function
    void uploadMeasurements(float lux, float ctemp, float hum) {
        String url = String(FIREBASE_CLOUDFUNCTION_URL) + "?lux=" + String(lux,2)
                            + "&temp=" + String(ctemp,2) + "&hum=" + String(hum,2); 

        http.begin(url);
        int httpCode = http.GET();

        // you don't have to handle the response, if you dont need it.
        String payload = http.getString();
        Serial.println(payload);

        http.end();
    }

I put the measurements into the query params, but you can send them trought the body of the request as well.

And my cloud function that stores the data looks like this:

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();


    exports.add = functions.https.onRequest((request, response)=>
    {
        console.log('Called with queries: ', request.query, ' and body: ', request.body);
        var ref = admin.database().ref("any/endpoint/child");
        var childRef = ref.push();

        let weatherData = {
            lux: request.query.lux,
            temp: request.query.temp,
            hum: request.query.hum,
            // this automatically fills this value, with the current time
            timestamp : admin.database.ServerValue.TIMESTAMP 
        };

        childRef.set(
            weatherData
        );
        response.status(200).send("OK!");
    });

You can initialize a project that stores your cloud functions and can be deployed to Firebase with the Firebase CLI, calling firebase init in your project folder, and than selecting cloudfunctions through the setup process (I selected hosting as well, because I have a frontend to view the collected data.)

Right now, I have a little sensor that uses this solution, and uploads measurements every minute, and it works without any problem.

I hope this helped.

这篇关于无法使用Nodemcu将数据上传到Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆