Guest User

Untitled

a guest
Mar 25th, 2018
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.54 KB | None | 0 0
  1. var express = require('express');
  2. var Particle = require('particle-api-js');
  3. var particle = new Particle();
  4. var mongooose = require('mongoose');
  5. var bodyParser = require('body-parser');
  6. var secure_token;
  7. var app = express();
  8. // var Schema = mongooose.Schema;
  9. // var readingSchema = new Schema({
  10.  
  11. // Device_Id:String,
  12. // Time_Stamp:String,
  13. // Area_Id:String,
  14. // Concentration:{
  15. // CO:Number,
  16. // CO2:Number,
  17. // PM25:Number,
  18. // PM10:Number
  19. // },
  20. // Reading_Location:{
  21. // LAT: Number,
  22. // LONG: Number
  23. // }
  24.  
  25. // });
  26. var live_data;
  27. var nodemailer = require('nodemailer');
  28. var mailOptions;
  29. var path = require('path');
  30. app.use(express.static(path.join(__dirname, 'public')));
  31. var gas_name = "CarbonMonoxide"
  32. app.use(bodyParser.json());
  33. app.set('views','views');
  34. app.set('view engine', 'ejs');
  35. //var Reading = mongooose.model('Reading',readingSchema);
  36. var glo_db;
  37. app.use(bodyParser.json());
  38. app.use(bodyParser.urlencoded({ extended: true }));
  39. var name = [];
  40. var result_send = [];
  41. var devices_pre_id;
  42. var hours,minutes;
  43. var avg_1;
  44. var count_data;
  45. var dyanmicData;
  46. var counter_stop_signal,counter_start_signal,counter_stop_reading,counter_start_reading;
  47. var transporter = nodemailer.createTransport({
  48. service: 'gmail',
  49. auth: {
  50. user: 'fourthyearscet@gmail.com',
  51. pass: 'scet1234@'
  52. }
  53. });
  54. var Area_Name,main_collection;
  55. //mongodb connection for globle access.........
  56. var uri = 'mongodb://localhost/user1';
  57. var promise = mongooose.connect(uri,{
  58. useMongoClient: true,
  59.  
  60. }
  61. );
  62. promise.openUri(uri,function(errr,db){
  63. if(errr){
  64. throw errr;
  65. }else{
  66. console.log("Connection Successfull");
  67.  
  68. glo_db = db;
  69. //console.log(glo_db);
  70. }
  71. })
  72.  
  73.  
  74.  
  75. var collection_check_var = 0;
  76. var subscribeReading = function(channel, token) {
  77.  
  78. var saveReading = function(data) {
  79.  
  80. var temp = JSON.stringify(data.data);
  81. var device_ids = (data.coreid);
  82. if(collection_check_var == 0 && device_ids != 'null'){
  83.  
  84. //console.log("Towords to create a Collection");
  85. create_collection("Reading",glo_db);
  86. collection_check_var = 1;
  87.  
  88.  
  89. }
  90. if(temp != 'null' ){
  91. //var temp_name = parseInt(data.data);
  92. var temp_time = new Date();
  93. var Time_Stamp = temp_time.toISOString();
  94. Area_Name = glo_db.collection("Device");
  95. collection_main = glo_db.collection('reading');
  96.  
  97. Area_Name.find({Device_Id:device_ids},{_id:false,Area_Id:true}).toArray(function(err,data1){
  98. if(err){
  99. throw err;
  100. }else{
  101. if(data1.length>0){
  102. console.log("Hii")
  103.  
  104.  
  105. Area_Id = data1[0].Area_Id
  106. save_data_into_collection("reading",device_ids,Time_Stamp,Area_Id,data,glo_db)
  107. }
  108. }
  109. });
  110. }
  111.  
  112.  
  113. };
  114.  
  115. //Get all events
  116. particle.getEventStream({name: channel, auth: token}).then(function(stream) {
  117. stream.on('event', saveReading);
  118.  
  119. });
  120.  
  121. //Get your devices events
  122. // particle.getEventStream({ deviceId: 'mine', auth: token }).then(function(stream) {
  123. // stream.on('event', function(data) {
  124. // console.log("Event: " + data);
  125. // });
  126. // });
  127.  
  128. //Get test event for specific device
  129. // particle.getEventStream({ deviceId: 'DEVICE_ID', name: 'test', auth: token }).then(function(stream) {
  130. // stream.on('event', function(data) {
  131. // console.log("Event: " + data);
  132. // });
  133. // });
  134. }
  135.  
  136. particle.login({username: 'rahul@winrtech.com', password: 'Scet@207@IOT'}).then(
  137. function(data) {
  138. //console.log(data.body);
  139. secure_token = data.body.access_token;
  140. subscribeReading("RCHAN1", secure_token);
  141. subscribeReading("RCHAN2",secure_token);
  142.  
  143. },
  144.  
  145. function (err) {
  146. console.log('Could not log in.', err);
  147. }
  148. );
  149. function create_collection(collection_name,glo_db){
  150. var collection = glo_db.collection(collection_name);
  151. if(collection){
  152. console.log("Collectoin Creatd");
  153. }
  154. }
  155. function save_data_into_collection(name,Device_Id,Time_Stamp,Area_Id,data,db){
  156.  
  157.  
  158. var collection = db.collection(name);
  159. var tep = JSON.parse(data.data);
  160. live_data ={
  161. device_id : Device_Id,
  162. CO: tep.CO,
  163. CO2:tep.CO2,
  164. PM25:tep.PM25,
  165. PM10:tep.PM10
  166. }
  167. //console.log(live_data)
  168. 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){
  169. if(err){
  170. throw err;
  171. }else{
  172. console.log("Data Saved into Collection");
  173.  
  174. collection.count(function (err,result_count) {
  175. //console.log("hiii");
  176. // body...
  177. if(err){ throw err; }
  178. else{
  179. //console.log(result_count);
  180.  
  181. collection.find({},{_id: false,Concentraction: true,time_stamp:true}).toArray(function(err,result){
  182. // console.log("hii2");
  183. if(err){ throw err;
  184. // console.log("hii3");
  185. }
  186. else{
  187. // collection.aggregate([{
  188. // $group:{
  189. // _id:{Gas_Name:"$Gas_Id",Device_Id:"$Device_Id"},
  190.  
  191. // data:{
  192. // $last:"$Concentraction"
  193. // }
  194. // }}]).toArray(function(err,data){
  195. // if(err){ throw err; }
  196. // else{
  197. // console.log(data)
  198. // result_send = data;
  199.  
  200. // }
  201. // });
  202.  
  203. collection.aggregate([
  204. {$group:{
  205. _id:{Gas_Name:"$Gas_Id",Device_Id:"$Device_Id"},
  206. average_ppm: {
  207. $avg : "$Concentraction"
  208.  
  209. }
  210. }}]).toArray(function(err,result_avg){
  211. if(err){ throw err;
  212. }
  213. else{
  214.  
  215. avg_1 = result_avg;
  216. //console.log(avg_1);
  217. }
  218. });
  219.  
  220. console.log("----------------------------------------------");
  221. //
  222. }
  223. });
  224.  
  225.  
  226. }
  227. });
  228.  
  229.  
  230. }
  231. });
  232. }
  233.  
  234. app.get('/home',function (req,res) {
  235. // body...
  236.  
  237.  
  238. res.render('tabel_ajax');
  239. console.log("Hii")
  240.  
  241.  
  242. });
  243. app.post('/home',function(req,res){
  244. // console.log("Avg is" +avg_1)
  245.  
  246. res.status(200).send({name1:avg_1,name2:result_send})
  247. })
  248.  
  249.  
  250. var flag;
  251.  
  252. app.get('/flash',function(req,res){
  253. console.log("Flash Get");
  254. res.render('flash');
  255. });
  256. counter_stop_reading=0;
  257. counter_start_reading = 0;
  258. counter_start_signal = 0;
  259. counter_stop_signal = 0;
  260. app.post('/flash',function (req,res){
  261. // body...
  262. var temp = req.body.status;
  263. var send_device = [];
  264. console.log(req.body.test);
  265. var temp1 = req.body.test;
  266. // console.log("ID"+temp1)
  267. console.log(temp);
  268.  
  269. if(temp == "Status"){
  270. devicesPr = particle.listDevices({ auth: secure_token }).then(
  271. function(devices){
  272. console.log(devices)
  273. var len = devices.body.length;
  274. //console.log(devices);
  275. for(var i=0;i<len;i++){
  276. send_device[i] = devices.body[i];
  277.  
  278.  
  279.  
  280. }
  281. flag =1;
  282.  
  283. //console.log(Ids);
  284. res.render("new_flash",{pranav:send_device});
  285. //res.send({pranav:Ids});
  286.  
  287. },
  288. function(err) {
  289. flag = 0;
  290. console.log('List devices call failed: ', err)
  291. res.render('err_file',{temp:flag,});
  292. });
  293.  
  294. }
  295. else if(temp == "stopReading"){
  296. particle.flashDevice({ deviceId: temp1, files: { file1: './off_sensor.bin' }, auth: secure_token }).then(function(data) {
  297. flag = 1;
  298.  
  299. console.log('Device Stop');
  300. res.send({data:"Decvice "+temp1+" reading is STOP Please wait for Some Time to come Device Online Again"})
  301. }, function(err) {
  302. counter_stop_reading++;
  303. if(counter_stop_reading==2 ){
  304. counter_stop_reading=0;
  305. 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."})
  306. flag = 0;
  307. mailOptions = {
  308. from: 'fourthyearscet@gmail.com',
  309. to: 'fourthyearscetadmi@gmail.com',
  310. subject:"Error in Stop Reading"+temp1,
  311. text: "There is a error in device who's Device Id is: "+temp1 //please add the area information tooo....!
  312. }
  313. transporter.sendMail(mailOptions, function(error, info){
  314. if (error) {
  315. console.log(error);
  316. } else {
  317. console.log('Email sent: ' + info.response);
  318. }
  319. });
  320. }else{
  321. res.send({data:"Fail To Stop Reading of Device "+temp1+" try agian"})
  322. }
  323.  
  324.  
  325. })
  326. }
  327.  
  328. else if(temp == "startReading"){
  329. particle.flashDevice({ deviceId: temp1, files: { file1: './start_sensor.bin' }, auth: secure_token }).then(function(data) {
  330. flag = 1;
  331. console.log('Device Started');
  332. res.send({data:"Decvice "+temp1+" reading is START Please wait for Some Time to come Device Online Again"})
  333. //res.render("flash1",{pranav:send_device});
  334. }, function(err) {
  335. flag = 0;
  336. 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."})
  337.  
  338. mailOptions = {
  339. from: 'fourthyearscet@gmail.com',
  340. to: 'fourthyearscetadmi@gmail.com',
  341. subject:"Error in Start Reading"+temp1,
  342. text: "There is a error in device who's Device Id is: "+temp1 //please add the area information tooo....!
  343. }
  344. transporter.sendMail(mailOptions, function(error, info){
  345. if (error) {
  346. console.log(error);
  347. } else {
  348. console.log('Email sent: ' + info.response);
  349. }
  350.  
  351.  
  352. });
  353. })
  354. }
  355. else if(temp == "signalDevice"){
  356. particle.signalDevice({ deviceId: temp1, signal: true, auth: secure_token }).then(function(data) {
  357. flag = 1;
  358. console.log('Signal started....!!!!!!');
  359. res.send({data:"Decvice "+temp1+" signal is START check "+temp1+" dicvice LED light"})
  360. // res.render("flash1",{pranav:send_device});
  361. }, function(err) {
  362. flag = 0;
  363. res.send({data:"Can't Signal to Device "+temp1+"..! Email has send to the Technician according to the Problem.Your prblem will solved shortly."})
  364. mailOptions = {
  365. from: 'fourthyearscet@gmail.com',
  366. to: 'fourthyearscetadmi@gmail.com',
  367. subject:"Error in Signal Signal"+temp1,
  368. text: "There is a error in device who's Device Id is: "+temp1 //please add the area information tooo....!
  369. }
  370. transporter.sendMail(mailOptions, function(error, info){
  371. if (error) {
  372. console.log(error);
  373. } else {
  374. console.log('Email sent: ' + info.response);
  375. }
  376. })
  377. ; })
  378. }
  379. else if(temp =="stopsignalDevice"){
  380. particle.signalDevice({ deviceId: temp1, signal: false, auth: secure_token }).then(function(data) {
  381. flag = 1;
  382. console.log('Signal Stop....!!!!!!!');
  383. res.send({data:"Decvice "+temp1+" signal is STOP check "+temp1+" dicvice LED light"})
  384. }, function(err) {
  385.  
  386. 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."})
  387. flag = 0
  388. ;mailOptions = {
  389. from: 'fourthyearscet@gmail.com',
  390. to: 'fourthyearscetadmi@gmail.com',
  391. subject:"Error in Stop Signal"+temp1,
  392. text: "There is a error in device who's Device Id is: "+temp1 //please add the area information tooo....!
  393. }
  394. transporter.sendMail(mailOptions, function(error, info){
  395. if (error) {
  396. console.log(error);
  397. } else {
  398. console.log('Email sent: ' + info.response);
  399. }
  400. });
  401. })
  402. }
  403.  
  404. });
  405.  
  406. app.get('/issue_form',function (req,res) {
  407. // body...
  408. res.render('issue_from');
  409. });
  410.  
  411.  
  412. app.get('/area_form',function(req,res){
  413. res.render('area_form')
  414. })
  415. app.get('/index',function(req,res){
  416. res.render('test_date_server');
  417. });
  418.  
  419. app.post('/gas_form',function(req,res){
  420. var Gas_Id = req.body.gas_id;
  421. var Gas_Code = req.body.gas_code;
  422. var Gas_Name = req.body.gas_name;
  423. console.log(Gas_Id+"\n"+Gas_Code+"\n"+Gas_Name);
  424. var gas_collection = glo_db.collection("Gas");
  425. gas_collection.insertOne({Gas_Id,Gas_Code,Gas_Name},function(err,data){
  426. if(err){ throw err; res.send({msg:"Data Not Inserted Try Agian"}) }else{
  427. console.log("Data Stored")
  428. res.send({msg:"Data Inserted"})
  429. }
  430. });
  431. })
  432. app.post('/index',function(req,res){
  433. var test,test1,test2;
  434. test = req.body.area;
  435. test1 = req.body.gas;
  436. test2 = req.body.s_date;
  437. test3 = req.body.e_date;
  438.  
  439. var areas = req.body.area;
  440. var gases = req.body.gas;
  441.  
  442. var start_date = new Date(test2);
  443. var end_date = new Date(test3);
  444. //console.log(start_date)
  445.  
  446. // hours = start_date.getHours()-5;
  447. // minutes = start_date.getMinutes()-30;
  448. // start_date.setHours(hours);start_date.setMinutes(minutes);
  449. // //console.log("Hour"+hours+"\n"+"Minutes"+minutes);
  450. // //console.log(start_date)
  451. // hours = end_date.getHours()-5;
  452. // minutes = end_date.getMinutes()-30;
  453. // //console.log("Hour"+hours+"\n"+"Minutes"+minutes);
  454. // end_date.setHours(hours);end_date.setMinutes(minutes);
  455. //console.log(end_date)
  456. //var date = new Date(test2.toISOString());
  457. //console.log(date2)
  458. var collection1 = glo_db.collection('reading');
  459. // collection1.find({},{_id:true ,Gas:true,PPM:true,time_stamp:true}).toArray(function(err,result){
  460. // if(err){ throw err }
  461. // else{
  462. // console.log(result)
  463. // }
  464. // });
  465. start_date = start_date.toISOString();
  466. end_date = end_date.toISOString();
  467. collection1.aggregate([{$unwind:"$Concentration"},{$match:{Time_Stamp:{$gte: start_date,$lte:end_date}}},
  468. {$group:{_id:"$Concentration.Gas_Name",avg_ppm:{$avg:"$Concentration.Gas_PPM"}}}
  469. ]).toArray(function (err,result) {
  470. // body..
  471. if(err){ throw err}
  472. else{
  473. console.log(result)
  474. res.send(result)
  475. // var output = [];
  476. // output.push(["Area "].concat(gases));
  477.  
  478. // res.send({result})
  479. }
  480. })
  481.  
  482. // collection1.aggregate( [ {$group: { _id: "$Gas", abc:{ $push:{ gases: "$Gas" }} } }])
  483. // .toArray(function(err,result){
  484.  
  485. // if (err){throw err;}
  486.  
  487. // else{
  488.  
  489. // console.log(result);
  490.  
  491. // }
  492.  
  493. // });
  494.  
  495.  
  496. });
  497.  
  498. app.get('/area',function(req,res){
  499. res.render("area_find");
  500. })
  501. app.post('/area',function (req,res) {
  502. // body...
  503. console.log("Area");
  504. var collection1 = glo_db.collection("Area");
  505. collection1.find({},{_id:false,Area_Id:true}).toArray(function(err,data) {
  506. if(err){throw err;}
  507. else{
  508. console.log(data);
  509. res.send(data)
  510. }
  511.  
  512. // body...
  513. })
  514. })
  515.  
  516. var area_name ;
  517.  
  518.  
  519. var j=0;
  520. var temp_area
  521. app.post('/data',function(req,res) {
  522. // body..
  523. //console.log(req.body.area_name);
  524. var device_result = [] ;
  525.  
  526. var flag = req.body.flag;
  527. //console.log(typeof(flag));
  528. if(flag == "1"){
  529.  
  530. temp_area = "";
  531.  
  532. temp_area = req.body.area_name;
  533.  
  534. }
  535. else if(flag == "0"){
  536.  
  537. temp_area = "";
  538. temp_area = req.body.area_name;
  539.  
  540.  
  541. }
  542. // //temp_area = "";
  543. var collection1 = glo_db.collection("Area");
  544. var collection2 = glo_db.collection("Device");
  545. var collection3 = glo_db.collection("inventory");
  546. collection1.find({Area_Id:temp_area},{_id:false,Area_Id:true}).toArray(function(err,data){
  547. if(err){ throw err ;}
  548. else{
  549. area_name = data[0].Area_Id;
  550. temp_area = "";
  551.  
  552. //console.log(data[0].Area_Id)
  553. collection2.find({Area_Id:data[0].Area_Id},{_id:false,Device_Id:true}).toArray(function(err,data){
  554. if(err){ throw err; }
  555. else{
  556.  
  557.  
  558. for(var i=0;i<data.length;i++){
  559.  
  560. device_result.push(data[i].Device_Id)
  561.  
  562. }
  563. //console.log(device_result);
  564. collection3.aggregate([
  565. {$match:{Device_Id:{$in:device_result}}},
  566. {$group:{_id:"$Device_Id",average_ppm:{$avg:"$Concentraction"}}}
  567. ]).toArray(function(err,data1){
  568. if(err){ throw err; }else{
  569. console.log(data1)
  570. //res.send(data1)
  571. }
  572. });
  573. }
  574. })
  575. }
  576.  
  577. })
  578.  
  579. })
  580.  
  581.  
  582. app.get('/tebs',function(req,res){
  583. res.render('tabs');
  584. })
  585. app.get('/html',function(req,res){
  586. //res.render('test1')
  587.  
  588. console.log(secure_token)
  589.  
  590.  
  591. })
  592. // app.post('/result',function(req,res) {
  593. // // body...
  594. // var collection3 = glo_db.collection("reading")
  595. // console.log("result")
  596. // console.log(area_name)
  597. // console.log(device_result)
  598. // collection3.aggregate([
  599. // {$match:{Device_Id:device_result}},
  600. // {$group:{_id:"$Device_Id",average_ppm:{$avg:"$Concentraction"}}}
  601. // ]).toArray(function(err,data){
  602. // if(err){ throw err; }else{
  603. // console.log(data)
  604. // }
  605. // })
  606.  
  607. // })
  608.  
  609.  
  610. // app.get("/table_dynamic",function(req,res){
  611. // var collection3 = glo_db.collection("reading");
  612. // setInterval(function(){
  613. // collection3.aggregate([{
  614. // $group:{_id:"$Device_Id",lat_data:{$last:"$Time_Stamp"}}
  615. // }]).toArray(function(err,data){
  616. // if(err){ throw err; }else{
  617. // console.log(data)
  618. // }
  619. // })
  620. // },10000)
  621. // })
  622. // app.post("/table_dynamic",function(req,res){
  623.  
  624.  
  625. // })
  626.  
  627. app.get('/dynamicData',function(req,res){
  628. res.render('table_change')
  629.  
  630.  
  631.  
  632. })
  633. app.post('/dynamicData',function(req,res){
  634. var area_find = req.body.area;
  635. console.log(area_find)
  636. var collection3 = glo_db.collection("reading");
  637. var collection_device = glo_db.collection("Device");
  638. var device_ids = [];
  639. collection_device.find({Area_Id:area_find},{_id:0,Device_Id:1}).toArray(function(err,data_area){
  640. if(err){ throw err; }else{
  641. for(var i=0;i<data_area.length;i++){
  642. device_ids.push(data_area[i].Device_Id)
  643. //console.log(device_ids)
  644. }
  645. }
  646. })
  647. collection3.aggregate([{$group:{_id:"$Device_Id", Gas_Con:{$last:"$Concentration"}}}
  648. ],function(err,data){
  649. if(err){
  650. throw err
  651. }
  652.  
  653. var output=[];
  654. output.push(["Device_Id","CO","CO2","PM25","PM10"])
  655.  
  656. for(var i=0;i<device_ids.length;i++){
  657. for(var j=0;j<data.length;j++){
  658. if(data[j]._id == device_ids[i]){
  659. var o = [];
  660. //console.log(data[0].Gas_Con)
  661. o.push(data[j]._id);
  662. for(var k=0;k<data[j].Gas_Con.length;k++){
  663. //console.log(data[j].Gas_Con[k].Gas_PPM)
  664. o.push(data[j].Gas_Con[k].Gas_PPM)
  665.  
  666. }
  667. output.push(o);
  668.  
  669.  
  670. }
  671. }
  672. }
  673. var string_array = JSON.stringify(output)
  674. if(output.length > 1){
  675.  
  676. res.status(200).send(output)
  677. }else{
  678. res.status(200).send({msg:"No data"})
  679. }
  680. })
  681.  
  682. })
  683. app.listen(2525);
  684. console.log("Magic started on 2525");
  685.  
  686. //$gt: ISODate("2018-02-19T00:00:00.000Z")
Add Comment
Please, Sign In to add comment