从NodeMCU发送到Firebase时如何构造传感器数据?

时间:2019-02-02 07:50:28

标签: firebase firebase-realtime-database iot sensor nodemcu

我已使用以下代码将DHT传感器数据从NodeMCU发送到Firebase。

void loop() {
  if(timeSinceLastRead > 2000) {
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    float f = dht.readTemperature(true);
    if (isnan(h) || isnan(t) || isnan(f)) {
      Serial.println("Failed to read from DHT sensor!");
      timeSinceLastRead = 0;
      return;
    }

    float hif = dht.computeHeatIndex(f, h);
    float hic = dht.computeHeatIndex(t, h, false);

    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.print(" *C ");
    Serial.print(f);
    Serial.print(" *F\t");
    Serial.print("Heat index: ");
    Serial.print(hic);
    Serial.print(" *C ");
    Serial.print(hif);
    Serial.println(" *F");
    Firebase.setFloat("Temp",t);
    Firebase.setFloat("Humidity",h);
    Firebase.setFloat("HeatIndex",hic);

    timeSinceLastRead = 0;
  }
  delay(100);
  timeSinceLastRead += 100;
 }

它已成功将数据发送到Firebase,但采用以下结构。

Field-Root
|_ HeatIndex: <value>
|_ Humidity : <value>
|_ Temp     : <value>

但是,我还有两个用户定义的ID参数要发送到Firebase,并且需要以下结构。

Field-Root
|_ ID1
   |_ ID2
      |_ HeatIndex: <value>
      |_ Humidity : <value>
      |_ Temp     : <value>

但是,我没有获得所需的层次结构,而是获得了旧结构。我怎么得到的?

2 个答案:

答案 0 :(得分:2)

setFloat方法的第一个参数允许您指定数据路径。

来自https://firebase-arduino.readthedocs.io/en/latest/#_CPPv2N15FirebaseArduino8setFloatERK6Stringf

void setFloat(const String &path, float value)

  Writes the float value to the node located at path equivalent to 
  the REST API’s PUT.

parameters
  path: The path inside of your db to the node you wish to update.
  value: Float value that you wish to write. 

因此,您可以使用以下路径:

Firebase.setFloat("ID-Floor1/ID-Bathroom/Temp", 1.1);
Firebase.setFloat("ID-Floor1/ID-Bathroom/Humidity", 2.2);
Firebase.setFloat("ID-Floor1/ID-Bathroom/HeatIndex", 3.3);

哪个将出现在Firebase中,如:

Firebase screenshot

您还可以根据ID1和ID2何时可用来最小化字符串操作。

如果在您的设置中已知它们,则可以按照上面的示例对路径进行硬编码。

否则,您可以使用以下方法形成路径(最好是一次):

String path = Id1;
path.concat("/");
path.concat(Id2);
path.concat("/");

String temperaturePath = path;
temperaturePath.concat("Temp");
String humidityPath = path;
humidityPath.concat("Temp");
String heatIndexPath = path;
heatIndexPath.concat("Temp");

然后在loop函数中使用:

Firebase.setFloat(temperaturePath, 1.1);
Firebase.setFloat(humidityPath, 2.2);
Firebase.setFloat(heatIndexPath, 3.3);

答案 1 :(得分:1)

要获取所需的数据库结构,请在setFloat函数内部使用以下类似代码编写t,h或hic浮点值之前,需要获取对ID2的引用(这假定数据库结构中显示了Field-Root是您的Firebase数据库的根目录

function setFloat(fieldName, fieldValue) {
    //.....
    firebase.database().ref( ID1 + '/' + ID2 + '/' + fieldName).set(fieldValue);
    //.....
}

这将为您提供以下结构

Field-Root
|_ ID1
   |_ ID2
      |_ HeatIndex: <value>
      |_ Humidity : <value>
      |_ Temp     : <value>
相关问题