Take json string from ESP8266WiFi, and save it as a string variable in NodeJS to write a CSV file

余生颓废 提交于 2021-01-29 09:02:24

问题


I want to take a JSON string of DHT22 sensor value (temperature and humidity) from this ESP8266WiFi through WiFi.

    #include <DHT.h> //library DHT.h
    #include <ESP8266WiFi.h>
    #define DHTPIN 14 // GPIO14
    #define DHTTYPE DHT22 // DHT 22 (AM2302)
    DHT dht(DHTPIN, DHTTYPE, 15);

    const char* ssid = "myhotspot";
    const char* password = "mypassword";

    WiFiServer server(80);

    void setup() {
      Serial.begin(115200);
      dht.begin();
      Serial.println();
      Serial.print("Wifi connecting to ");
      Serial.println( ssid );

      WiFi.begin(ssid,password);

      Serial.println();
      Serial.print("Connecting");

      while( WiFi.status() != WL_CONNECTED ){
          delay(500);
          Serial.print(".");
      }
      Serial.println();

      Serial.println("Wifi Connected Success!");
      Serial.print("NodeMCU IP Address : ");
      Serial.println(WiFi.localIP() );

      server.begin();
      Serial.println("NodeMCU Server started");

      // Print the IP address
      Serial.print("Use this URL to connect: ");
      Serial.print("http://");
      Serial.print(WiFi.localIP());
      Serial.println("/");
    }
    void sendJsonString(float temperature, float humidity, String dataStatus, String reason){
      /*
      {
        "data" : {
          "temperature" : 0.0, // 0,NaN
          "humidity" : 0.0 
        }, 
        "status" : "OK", //OK, Error
        "reason" : ""
      }
      */
      String s = "";
      s += String("{");
      s += String("\"temperature\" : " + String(temperature) + "," );
      s += String("\"humidity\" : " + String(humidity) );
      s += String("} ," );
      Serial.println(s); //this line specifically
    }
    void loop() {
      // Reading temperature or humidity takes about 250 milliseconds!
      delayMicroseconds(250);
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      delay(2000);
      // Set up data
      float h = dht.readHumidity();
      float t = dht.readTemperature();
      // check if returns are valid, if they are NaN (not a number) then something went wrong! 
      float temperature = t;
      float humidity = h; 
      String dataStatus = "OK";
      String reason = "";
      if (isnan(t) || isnan(h)) {
        temperature = 0;
        humidity = 0; 
        dataStatus = "Error";
        reason = "Failed to read from DHT";
      }
      // Send data
      sendJsonString(temperature, humidity, dataStatus, reason); 
    }

And then use NodeJS to take the JSON string and convert it into two String, one of Temperature and one of Humidity, store it in variable and add a date and time on it.

    var express = require('express')
    var bodyParser = require('body-parser')
    var app = express()
    var cors = require('cors')

    app.use(cors())
    app.use(bodyParser.json())

    app.set('port', (process.env.PORT || 9999))
    app.use(bodyParser.urlencoded({extended: false}))
    app.use(bodyParser.json())

    app.post('/', function (req, res) {
      var dateTime = new Date().toISOString().replace('T', ' ').substr(0, 19);
        console.log(dateTime + ',' + req.body.temperature)
      console.log(dateTime + ',' + req.body.humidity)
        res.send('success : ' + req.body.temperature + ',' + req.body.humidity)
    })

    app.listen(app.get('port'), function () {
      console.log('run at port', app.get('port'))
    })

Then, if possible, I want to use the same NodeJS code file to use the strings I store to write a CSV files in the form that can be used to make a graph on webservice, with the same webpage to this Raspberry Pi project.

http://www.home-automation-community.com/temperature-and-humidity-from-am2302-dht22-sensor-displayed-as-chart/

There are a lot of inconsistency in my code, so, it would be great if the user here could provide me what should I do to achieve my goal. I am just an amature in this field. Thanks for the help in advance.

来源:https://stackoverflow.com/questions/60125125/take-json-string-from-esp8266wifi-and-save-it-as-a-string-variable-in-nodejs-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!