上次教了用聚合方式找到指定資料的平均值 這次要把資料平均值POST上去
不過因為上次我們只是指定特定時間區間 這次我們需要隨者日期做搜尋
同樣先直接看到程式碼
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://127.0.0.1:1883')
const Readline = require('@serialport/parser-readline')
var SerialPort = require("serialport");
const parser = new Readline()
var arduinoCOMPort = "/dev/ttyUSB0";
var arduinoport = new SerialPort(arduinoCOMPort, {baudRate: 9600}).setEncoding('utf8');
var MongoClient=require('mongodb').MongoClient, assert = require('assert');;
const request = require('request-promise');
const { Console } = require('console');
var yesterdayStart = new Date(new Date(new Date().setHours(new Date().getHours()-1,00,00 )) );
var yesterdayEnd = new Date(new Date(new Date().setHours(new Date().getHours(),00,00 )) );
var lasttime = yesterdayStart.toLocaleString('zh-hant', { timeZone: 'Asia/Taipei' })
var nowtime = yesterdayEnd.toLocaleString('zh-hant', { timeZone: 'Asia/Taipei' })
var CO2avg,TVOCavg
console.log(lasttime)
console.log(nowtime)
arduinoport.on("open", (err) => {
console.log('serial port open'); //成功連接時印出port open
if(err){
console.log("no serial device found")//失敗時印出 device not found
}
},20);
arduinoport.pipe(parser)
parser.on('data', line =>{
console.log(line)
Arduno_data = JSON.parse(line);
Sensor_data = Object.values(Arduno_data)
Sensor_key = Object.keys(Arduno_data)
console.log(Sensor_key)
console.log(Sensor_data)
MongoClient.connect("mongodb://127.0.0.1:27017/test", function(err,client){
if(err){
console.log(err);
console.log('connecting fail');
return;
}
console.log('connecting');
setInterval(function(){
var yesterdayStart = new Date(new Date(new Date().setHours(new Date().getHours()-1,00,00 )) );
var yesterdayEnd = new Date(new Date(new Date().setHours(new Date().getHours(),00,00 )) );
lasttime = yesterdayStart.toLocaleString('zh-hant', { timeZone: 'Asia/Taipei' })
nowtime = yesterdayEnd.toLocaleString('zh-hant', { timeZone: 'Asia/Taipei' })
console.log(lasttime)
console.log(nowtime)
},3600000)
let udate = new Date();
let time = udate.toLocaleString('zh-hant', { timeZone: 'Asia/Taipei' })
var db_client = client.db('data_test')
var db_table = db_client.collection('data')
// console.log('connection success')
db_client.collection('data',async function(err,collection){
for(var i=0 ; i<Sensor_key.length;i++){
collection.insertOne({ time:time, name:Sensor_key[i], data:Sensor_data[i] });
}
var getCO2Avg = await collection.aggregate([
{ $match: {'time': {"$gte": lasttime, "$lte": nowtime},'name':'CO2' } },
{
$group: {
_id: "$name",
avg: {
$avg: "$data"
}
}
}
]).toArray();
var getTVOCAvg = await collection.aggregate([
{ $match: {'time': {"$gte": lasttime, "$lte": nowtime},'name':'TVOC' } },
{
$group: {_id: "$name",avg: {$avg: "$data" }}
}
]).toArray();
CO2avg = Math.round(getCO2Avg[0].avg*100)/100
TVOCavg = Math.round(getTVOCAvg[0].avg*100)/100
console.log(CO2avg)
console.log(TVOCavg)
collection.find({'time': {"$gte": lasttime, "$lte": nowtime},'name':'CO2' }).toArray(function(err,items){
if(err) throw err;
for(i=0 ; i<items.length-1; i++){
var sum = 0
sum = sum + items[i].data
let avgCO2 = (sum/items.length)
// console.log(avgCO2)
// console.log(sum)
if(i = items.length-1){
console.log(items[i]);
}
}
console.log("DATA FOUND");
});
});
})
push()
})
let push = async () => {
if(Sensor_key[0] == 'CO2'){
Sensordata = {
method: 'POST',
uri: 'http://127.0.0.1:30001/insert' ,
headers: {
'Content-Type': 'application/json'
},
body: {
mac : "3024324b3a84",
"sensorData" : {
"CO2" : Sensor_data[0],
"TVOC" : Sensor_data[1],
"CO2平均" : CO2avg,
"TVOC平均" : TVOCavg,
}
},
json: true
}
}
request(Sensordata).then(function (response) {
console.log(response)
console.log("post success")
}).catch(function (err) {
console.error(err);
});
}
setInterval(function(){
arduinoport.write('g')
},5000)
我們可以先看到 新的函式 Date()其實顧名思義就是 抓到現在的時間然後在用sethour 去取得上一個小時 的零分零秒 跟現在的零分零秒 能夠取得時間後 我們再來就要去修改我們抓資料的區間 把原本設定固定的時間改成隨時間不同會去做每小時的二氧化碳平均值更新
$match: {'time': {"$gte": lasttime, "$lte": nowtime},'name':'TVOC' }
最後就是將資料POST上汶萊網站
這樣我們就完成每小時做平均值計算了