Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var express = require('express');
- var Particle = require('particle-api-js');
- var particle = new Particle();
- var mongooose = require('mongoose');
- var bodyParser = require('body-parser');
- var secure_token;
- var app = express();
- // var Schema = mongooose.Schema;
- // var readingSchema = new Schema({
- // Device_Id:String,
- // Time_Stamp:String,
- // Area_Id:String,
- // Concentration:{
- // CO:Number,
- // CO2:Number,
- // PM25:Number,
- // PM10:Number
- // },
- // Reading_Location:{
- // LAT: Number,
- // LONG: Number
- // }
- // });
- var live_data;
- var nodemailer = require('nodemailer');
- var mailOptions;
- var path = require('path');
- app.use(express.static(path.join(__dirname, 'public')));
- var gas_name = "CarbonMonoxide"
- app.use(bodyParser.json());
- app.set('views','views');
- app.set('view engine', 'ejs');
- //var Reading = mongooose.model('Reading',readingSchema);
- var glo_db;
- app.use(bodyParser.json());
- app.use(bodyParser.urlencoded({ extended: true }));
- var name = [];
- var result_send = [];
- var devices_pre_id;
- var hours,minutes;
- var avg_1;
- var count_data;
- var dyanmicData;
- var counter_stop_signal,counter_start_signal,counter_stop_reading,counter_start_reading;
- var transporter = nodemailer.createTransport({
- service: 'gmail',
- auth: {
- user: 'fourthyearscet@gmail.com',
- pass: 'scet1234@'
- }
- });
- var Area_Name,main_collection;
- //mongodb connection for globle access.........
- var uri = 'mongodb://localhost/user1';
- var promise = mongooose.connect(uri,{
- useMongoClient: true,
- }
- );
- promise.openUri(uri,function(errr,db){
- if(errr){
- throw errr;
- }else{
- console.log("Connection Successfull");
- glo_db = db;
- //console.log(glo_db);
- }
- })
- var collection_check_var = 0;
- var subscribeReading = function(channel, token) {
- var saveReading = function(data) {
- var temp = JSON.stringify(data.data);
- var device_ids = (data.coreid);
- if(collection_check_var == 0 && device_ids != 'null'){
- //console.log("Towords to create a Collection");
- create_collection("Reading",glo_db);
- collection_check_var = 1;
- }
- if(temp != 'null' ){
- //var temp_name = parseInt(data.data);
- var temp_time = new Date();
- var Time_Stamp = temp_time.toISOString();
- Area_Name = glo_db.collection("Device");
- collection_main = glo_db.collection('reading');
- Area_Name.find({Device_Id:device_ids},{_id:false,Area_Id:true}).toArray(function(err,data1){
- if(err){
- throw err;
- }else{
- if(data1.length>0){
- console.log("Hii")
- Area_Id = data1[0].Area_Id
- save_data_into_collection("reading",device_ids,Time_Stamp,Area_Id,data,glo_db)
- }
- }
- });
- }
- };
- //Get all events
- particle.getEventStream({name: channel, auth: token}).then(function(stream) {
- stream.on('event', saveReading);
- });
- //Get your devices events
- // particle.getEventStream({ deviceId: 'mine', auth: token }).then(function(stream) {
- // stream.on('event', function(data) {
- // console.log("Event: " + data);
- // });
- // });
- //Get test event for specific device
- // particle.getEventStream({ deviceId: 'DEVICE_ID', name: 'test', auth: token }).then(function(stream) {
- // stream.on('event', function(data) {
- // console.log("Event: " + data);
- // });
- // });
- }
- particle.login({username: 'rahul@winrtech.com', password: 'Scet@207@IOT'}).then(
- function(data) {
- //console.log(data.body);
- secure_token = data.body.access_token;
- subscribeReading("RCHAN1", secure_token);
- subscribeReading("RCHAN2",secure_token);
- },
- function (err) {
- console.log('Could not log in.', err);
- }
- );
- function create_collection(collection_name,glo_db){
- var collection = glo_db.collection(collection_name);
- if(collection){
- console.log("Collectoin Creatd");
- }
- }
- //function that will check if the device is connented to internet or not.!!!!!
- setInterval(function(){
- },10000);
- //function to save the data form particle cloud to Mongo
- function save_data_into_collection(name,Device_Id,Time_Stamp,Area_Id,data,db){
- var collection = db.collection(name);
- var tep = JSON.parse(data.data);
- live_data ={
- device_id : Device_Id,
- CO: tep.CO,
- CO2:tep.CO2,
- PM25:tep.PM25,
- PM10:tep.PM10
- }
- //console.log(live_data)
- collection.insertOne({Device_Id,Time_Stamp,Area_Id,Concentration:[{Gas_Name:"CO",Gas_PPM:tep.CO},{Gas_Name:"CO2",Gas_PPM:tep.CO2},{Gas_Name:"PM25",Gas_PPM:tep.PM25},{Gas_Name:"PM10",Gas_PPM:tep.PM10}],Reading_Location:{LAT:tep.LAT,LONG:tep.LONG}},function(err,res){
- if(err){
- throw err;
- }else{
- console.log("Data Saved into Collection");
- console.log("----------------------------------------")
- }
- });
- }
- var flag;
- app.get('/flash',function(req,res){
- console.log("Flash Get");
- res.render('flash');
- });
- counter_stop_reading=0;
- counter_start_reading = 0;
- counter_start_signal = 0;
- counter_stop_signal = 0;
- app.post('/flash',function (req,res){
- // body...
- var temp = req.body.status;
- var send_device = [];
- console.log(req.body.test);
- var temp1 = req.body.test;
- // console.log("ID"+temp1)
- console.log(temp);
- if(temp == "Status"){
- devicesPr = particle.listDevices({ auth: secure_token }).then(
- function(devices){
- console.log(devices)
- var len = devices.body.length;
- //console.log(devices);
- for(var i=0;i<len;i++){
- send_device[i] = devices.body[i];
- }
- flag =1;
- //console.log(Ids);
- res.render("new_flash",{pranav:send_device});
- //res.send({pranav:Ids});
- },
- function(err) {
- flag = 0;
- console.log('List devices call failed: ', err)
- res.render('err_file',{temp:flag,});
- });
- }
- else if(temp == "stopReading"){
- particle.flashDevice({ deviceId: temp1, files: { file1: './off_sensor.bin' }, auth: secure_token }).then(function(data) {
- flag = 1;
- console.log('Device Stop');
- res.send({data:"Decvice "+temp1+" reading is STOP Please wait for Some Time to come Device Online Again"})
- }, function(err) {
- counter_stop_reading++;
- if(counter_stop_reading==2 ){
- counter_stop_reading=0;
- res.send({data:"Can't able stop reading of Device "+temp1+"..! Email has send to the Technician according to the Problem.Your prblem will solved shortly."})
- flag = 0;
- mailOptions = {
- from: 'fourthyearscet@gmail.com',
- to: 'fourthyearscetadmi@gmail.com',
- subject:"Error in Stop Reading"+temp1,
- text: "There is a error in device who's Device Id is: "+temp1 //please add the area information tooo....!
- }
- transporter.sendMail(mailOptions, function(error, info){
- if (error) {
- console.log(error);
- } else {
- console.log('Email sent: ' + info.response);
- }
- });
- }else{
- res.send({data:"Fail To Stop Reading of Device "+temp1+" try agian"})
- }
- })
- }
- else if(temp == "startReading"){
- particle.flashDevice({ deviceId: temp1, files: { file1: './start_sensor.bin' }, auth: secure_token }).then(function(data) {
- flag = 1;
- console.log('Device Started');
- res.send({data:"Decvice "+temp1+" reading is START Please wait for Some Time to come Device Online Again"})
- //res.render("flash1",{pranav:send_device});
- }, function(err) {
- flag = 0;
- res.send({data:"Can't able start reading of Device "+temp1+"..! Email has send to the Technician according to the Problem.Your prblem will solved shortly."})
- mailOptions = {
- from: 'fourthyearscet@gmail.com',
- to: 'fourthyearscetadmi@gmail.com',
- subject:"Error in Start Reading"+temp1,
- text: "There is a error in device who's Device Id is: "+temp1 //please add the area information tooo....!
- }
- transporter.sendMail(mailOptions, function(error, info){
- if (error) {
- console.log(error);
- } else {
- console.log('Email sent: ' + info.response);
- }
- });
- })
- }
- else if(temp == "signalDevice"){
- particle.signalDevice({ deviceId: temp1, signal: true, auth: secure_token }).then(function(data) {
- flag = 1;
- console.log('Signal started....!!!!!!');
- res.send({data:"Decvice "+temp1+" signal is START check "+temp1+" dicvice LED light"})
- // res.render("flash1",{pranav:send_device});
- }, function(err) {
- flag = 0;
- res.send({data:"Can't Signal to Device "+temp1+"..! Email has send to the Technician according to the Problem.Your prblem will solved shortly."})
- mailOptions = {
- from: 'fourthyearscet@gmail.com',
- to: 'fourthyearscetadmi@gmail.com',
- subject:"Error in Signal Signal"+temp1,
- text: "There is a error in device who's Device Id is: "+temp1 //please add the area information tooo....!
- }
- transporter.sendMail(mailOptions, function(error, info){
- if (error) {
- console.log(error);
- } else {
- console.log('Email sent: ' + info.response);
- }
- })
- ; })
- }
- else if(temp =="stopsignalDevice"){
- particle.signalDevice({ deviceId: temp1, signal: false, auth: secure_token }).then(function(data) {
- flag = 1;
- console.log('Signal Stop....!!!!!!!');
- res.send({data:"Decvice "+temp1+" signal is STOP check "+temp1+" dicvice LED light"})
- }, function(err) {
- res.send({data:"Can't Stop Signal to Device "+temp1+"..! Email has send to the Technician according to the Problem.Your prblem will solved shortly."})
- flag = 0
- ;mailOptions = {
- from: 'fourthyearscet@gmail.com',
- to: 'fourthyearscetadmi@gmail.com',
- subject:"Error in Stop Signal"+temp1,
- text: "There is a error in device who's Device Id is: "+temp1 //please add the area information tooo....!
- }
- transporter.sendMail(mailOptions, function(error, info){
- if (error) {
- console.log(error);
- } else {
- console.log('Email sent: ' + info.response);
- }
- });
- })
- }
- });
- app.get('/issue_form',function (req,res) {
- // body...
- res.render('issue_from');
- });
- app.get('/area_form',function(req,res){
- res.render('area_form')
- })
- app.get('/index',function(req,res){
- res.render('test_date_server');
- });
- app.post('/gas_form',function(req,res){
- var Gas_Id = req.body.gas_id;
- var Gas_Code = req.body.gas_code;
- var Gas_Name = req.body.gas_name;
- console.log(Gas_Id+"\n"+Gas_Code+"\n"+Gas_Name);
- var gas_collection = glo_db.collection("Gas");
- gas_collection.insertOne({Gas_Id,Gas_Code,Gas_Name},function(err,data){
- if(err){ throw err; res.send({msg:"Data Not Inserted Try Agian"}) }else{
- console.log("Data Stored")
- res.send({msg:"Data Inserted"})
- }
- });
- })
- app.post('/index',function(req,res){
- var test,test1,test2;
- test = req.body.area;
- test1 = req.body.gas;
- test2 = req.body.s_date;
- test3 = req.body.e_date;
- var areas = req.body.area;
- var gases = req.body.gas;
- var start_date = new Date(test2);
- var end_date = new Date(test3);
- //console.log(start_date)
- // hours = start_date.getHours()-5;
- // minutes = start_date.getMinutes()-30;
- // start_date.setHours(hours);start_date.setMinutes(minutes);
- // //console.log("Hour"+hours+"\n"+"Minutes"+minutes);
- // //console.log(start_date)
- // hours = end_date.getHours()-5;
- // minutes = end_date.getMinutes()-30;
- // //console.log("Hour"+hours+"\n"+"Minutes"+minutes);
- // end_date.setHours(hours);end_date.setMinutes(minutes);
- //console.log(end_date)
- //var date = new Date(test2.toISOString());
- //console.log(date2)
- var collection1 = glo_db.collection('reading');
- // collection1.find({},{_id:true ,Gas:true,PPM:true,time_stamp:true}).toArray(function(err,result){
- // if(err){ throw err }
- // else{
- // console.log(result)
- // }
- // });
- start_date = start_date.toISOString();
- end_date = end_date.toISOString();
- collection1.aggregate([{$unwind:"$Concentration"},{$match:{Time_Stamp:{$gte: start_date,$lte:end_date}}},
- {$group:{_id:"$Concentration.Gas_Name",avg_ppm:{$avg:"$Concentration.Gas_PPM"}}}
- ]).toArray(function (err,result) {
- // body..
- if(err){ throw err}
- else{
- console.log(result)
- res.send(result)
- // var output = [];
- // output.push(["Area "].concat(gases));
- // res.send({result})
- }
- })
- // collection1.aggregate( [ {$group: { _id: "$Gas", abc:{ $push:{ gases: "$Gas" }} } }])
- // .toArray(function(err,result){
- // if (err){throw err;}
- // else{
- // console.log(result);
- // }
- // });
- });
- app.get('/area',function(req,res){
- res.render("area_find");
- })
- app.post('/area',function (req,res) {
- // body...
- console.log("Area");
- var collection1 = glo_db.collection("Area");
- collection1.find({},{_id:false,Area_Id:true}).toArray(function(err,data) {
- if(err){throw err;}
- else{
- console.log(data);
- res.send(data)
- }
- // body...
- })
- })
- var area_name ;
- var j=0;
- var temp_area
- app.post('/data',function(req,res) {
- // body..
- //console.log(req.body.area_name);
- var device_result = [] ;
- var flag = req.body.flag;
- //console.log(typeof(flag));
- if(flag == "1"){
- temp_area = "";
- temp_area = req.body.area_name;
- }
- else if(flag == "0"){
- temp_area = "";
- temp_area = req.body.area_name;
- }
- // //temp_area = "";
- var collection1 = glo_db.collection("Area");
- var collection2 = glo_db.collection("Device");
- var collection3 = glo_db.collection("inventory");
- collection1.find({Area_Id:temp_area},{_id:false,Area_Id:true}).toArray(function(err,data){
- if(err){ throw err ;}
- else{
- area_name = data[0].Area_Id;
- temp_area = "";
- //console.log(data[0].Area_Id)
- collection2.find({Area_Id:data[0].Area_Id},{_id:false,Device_Id:true}).toArray(function(err,data){
- if(err){ throw err; }
- else{
- for(var i=0;i<data.length;i++){
- device_result.push(data[i].Device_Id)
- }
- //console.log(device_result);
- collection3.aggregate([
- {$match:{Device_Id:{$in:device_result}}},
- {$group:{_id:"$Device_Id",average_ppm:{$avg:"$Concentraction"}}}
- ]).toArray(function(err,data1){
- if(err){ throw err; }else{
- console.log(data1)
- //res.send(data1)
- }
- });
- }
- })
- }
- })
- })
- app.get('/tebs',function(req,res){
- res.render('tabs');
- })
- app.get('/html',function(req,res){
- //res.render('test1')
- console.log(secure_token)
- })
- // app.post('/result',function(req,res) {
- // // body...
- // var collection3 = glo_db.collection("reading")
- // console.log("result")
- // console.log(area_name)
- // console.log(device_result)
- // collection3.aggregate([
- // {$match:{Device_Id:device_result}},
- // {$group:{_id:"$Device_Id",average_ppm:{$avg:"$Concentraction"}}}
- // ]).toArray(function(err,data){
- // if(err){ throw err; }else{
- // console.log(data)
- // }
- // })
- // })
- // app.get("/table_dynamic",function(req,res){
- // var collection3 = glo_db.collection("reading");
- // setInterval(function(){
- // collection3.aggregate([{
- // $group:{_id:"$Device_Id",lat_data:{$last:"$Time_Stamp"}}
- // }]).toArray(function(err,data){
- // if(err){ throw err; }else{
- // console.log(data)
- // }
- // })
- // },10000)
- // })
- // app.post("/table_dynamic",function(req,res){
- // })
- app.get('/dynamicData',function(req,res){
- res.render('table_change')
- })
- app.post('/dynamicData',function(req,res){
- var area_find = req.body.area;
- console.log(area_find)
- var collection3 = glo_db.collection("reading");
- var collection_device = glo_db.collection("Device");
- var device_ids = [];
- collection_device.find({Area_Id:area_find},{_id:0,Device_Id:1}).toArray(function(err,data_area){
- if(err){ throw err; }else{
- for(var i=0;i<data_area.length;i++){
- device_ids.push(data_area[i].Device_Id)
- //console.log(device_ids)
- }
- }
- })
- collection3.aggregate([{$group:{_id:"$Device_Id", Gas_Con:{$last:"$Concentration"}}}
- ],function(err,data){
- if(err){
- throw err
- }
- var output=[];
- output.push(["Device_Id","CO","CO2","PM25","PM10"])
- for(var i=0;i<device_ids.length;i++){
- for(var j=0;j<data.length;j++){
- if(data[j]._id == device_ids[i]){
- var o = [];
- //console.log(data[0].Gas_Con)
- o.push(data[j]._id);
- for(var k=0;k<data[j].Gas_Con.length;k++){
- //console.log(data[j].Gas_Con[k].Gas_PPM)
- o.push(data[j].Gas_Con[k].Gas_PPM)
- }
- output.push(o);
- }
- }
- }
- var string_array = JSON.stringify(output)
- if(output.length > 1){
- res.status(200).send(output)
- }else{
- res.status(200).send({msg:"No data"})
- }
- })
- })
- app.get('/timePass',function(req,res){
- console.log("in get timepass")
- }) /// get timepass
- app.post('/timePass',function(req,res){
- console.log("in post timepass")
- }) /// get timepass
- app.listen(2525);
- console.log("Magic started on 2525");
- //$gt: ISODate("2018-02-19T00:00:00.000Z")
Add Comment
Please, Sign In to add comment