Guest User

Untitled

a guest
Mar 26th, 2018
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.51 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.  
  156. //function that will check if the device is connented to internet or not.!!!!!
  157. setInterval(function(){
  158.  
  159. },10000);
  160.  
  161.  
  162.  
  163. //function to save the data form particle cloud to Mongo
  164. function save_data_into_collection(name,Device_Id,Time_Stamp,Area_Id,data,db){
  165.  
  166.  
  167. var collection = db.collection(name);
  168. var tep = JSON.parse(data.data);
  169. live_data ={
  170. device_id : Device_Id,
  171. CO: tep.CO,
  172. CO2:tep.CO2,
  173. PM25:tep.PM25,
  174. PM10:tep.PM10
  175. }
  176. //console.log(live_data)
  177. 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){
  178. if(err){
  179. throw err;
  180. }else{
  181. console.log("Data Saved into Collection");
  182.  
  183. console.log("----------------------------------------")
  184.  
  185.  
  186. }
  187. });
  188. }
  189. var flag;
  190.  
  191. app.get('/flash',function(req,res){
  192. console.log("Flash Get");
  193. res.render('flash');
  194. });
  195. counter_stop_reading=0;
  196. counter_start_reading = 0;
  197. counter_start_signal = 0;
  198. counter_stop_signal = 0;
  199. app.post('/flash',function (req,res){
  200. // body...
  201. var temp = req.body.status;
  202. var send_device = [];
  203. console.log(req.body.test);
  204. var temp1 = req.body.test;
  205. // console.log("ID"+temp1)
  206. console.log(temp);
  207.  
  208. if(temp == "Status"){
  209. devicesPr = particle.listDevices({ auth: secure_token }).then(
  210. function(devices){
  211. console.log(devices)
  212. var len = devices.body.length;
  213. //console.log(devices);
  214. for(var i=0;i<len;i++){
  215. send_device[i] = devices.body[i];
  216.  
  217.  
  218.  
  219. }
  220. flag =1;
  221.  
  222. //console.log(Ids);
  223. res.render("new_flash",{pranav:send_device});
  224. //res.send({pranav:Ids});
  225.  
  226. },
  227. function(err) {
  228. flag = 0;
  229. console.log('List devices call failed: ', err)
  230. res.render('err_file',{temp:flag,});
  231. });
  232.  
  233. }
  234. else if(temp == "stopReading"){
  235. particle.flashDevice({ deviceId: temp1, files: { file1: './off_sensor.bin' }, auth: secure_token }).then(function(data) {
  236. flag = 1;
  237.  
  238. console.log('Device Stop');
  239. res.send({data:"Decvice "+temp1+" reading is STOP Please wait for Some Time to come Device Online Again"})
  240. }, function(err) {
  241. counter_stop_reading++;
  242. if(counter_stop_reading==2 ){
  243. counter_stop_reading=0;
  244. 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."})
  245. flag = 0;
  246. mailOptions = {
  247. from: 'fourthyearscet@gmail.com',
  248. to: 'fourthyearscetadmi@gmail.com',
  249. subject:"Error in Stop Reading"+temp1,
  250. text: "There is a error in device who's Device Id is: "+temp1 //please add the area information tooo....!
  251. }
  252. transporter.sendMail(mailOptions, function(error, info){
  253. if (error) {
  254. console.log(error);
  255. } else {
  256. console.log('Email sent: ' + info.response);
  257. }
  258. });
  259. }else{
  260. res.send({data:"Fail To Stop Reading of Device "+temp1+" try agian"})
  261. }
  262.  
  263.  
  264. })
  265. }
  266.  
  267. else if(temp == "startReading"){
  268. particle.flashDevice({ deviceId: temp1, files: { file1: './start_sensor.bin' }, auth: secure_token }).then(function(data) {
  269. flag = 1;
  270. console.log('Device Started');
  271. res.send({data:"Decvice "+temp1+" reading is START Please wait for Some Time to come Device Online Again"})
  272. //res.render("flash1",{pranav:send_device});
  273. }, function(err) {
  274. flag = 0;
  275. 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."})
  276.  
  277. mailOptions = {
  278. from: 'fourthyearscet@gmail.com',
  279. to: 'fourthyearscetadmi@gmail.com',
  280. subject:"Error in Start Reading"+temp1,
  281. text: "There is a error in device who's Device Id is: "+temp1 //please add the area information tooo....!
  282. }
  283. transporter.sendMail(mailOptions, function(error, info){
  284. if (error) {
  285. console.log(error);
  286. } else {
  287. console.log('Email sent: ' + info.response);
  288. }
  289.  
  290.  
  291. });
  292. })
  293. }
  294. else if(temp == "signalDevice"){
  295. particle.signalDevice({ deviceId: temp1, signal: true, auth: secure_token }).then(function(data) {
  296. flag = 1;
  297. console.log('Signal started....!!!!!!');
  298. res.send({data:"Decvice "+temp1+" signal is START check "+temp1+" dicvice LED light"})
  299. // res.render("flash1",{pranav:send_device});
  300. }, function(err) {
  301. flag = 0;
  302. res.send({data:"Can't Signal to Device "+temp1+"..! Email has send to the Technician according to the Problem.Your prblem will solved shortly."})
  303. mailOptions = {
  304. from: 'fourthyearscet@gmail.com',
  305. to: 'fourthyearscetadmi@gmail.com',
  306. subject:"Error in Signal Signal"+temp1,
  307. text: "There is a error in device who's Device Id is: "+temp1 //please add the area information tooo....!
  308. }
  309. transporter.sendMail(mailOptions, function(error, info){
  310. if (error) {
  311. console.log(error);
  312. } else {
  313. console.log('Email sent: ' + info.response);
  314. }
  315. })
  316. ; })
  317. }
  318. else if(temp =="stopsignalDevice"){
  319. particle.signalDevice({ deviceId: temp1, signal: false, auth: secure_token }).then(function(data) {
  320. flag = 1;
  321. console.log('Signal Stop....!!!!!!!');
  322. res.send({data:"Decvice "+temp1+" signal is STOP check "+temp1+" dicvice LED light"})
  323. }, function(err) {
  324.  
  325. 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."})
  326. flag = 0
  327. ;mailOptions = {
  328. from: 'fourthyearscet@gmail.com',
  329. to: 'fourthyearscetadmi@gmail.com',
  330. subject:"Error in Stop Signal"+temp1,
  331. text: "There is a error in device who's Device Id is: "+temp1 //please add the area information tooo....!
  332. }
  333. transporter.sendMail(mailOptions, function(error, info){
  334. if (error) {
  335. console.log(error);
  336. } else {
  337. console.log('Email sent: ' + info.response);
  338. }
  339. });
  340. })
  341. }
  342.  
  343. });
  344.  
  345. app.get('/issue_form',function (req,res) {
  346. // body...
  347. res.render('issue_from');
  348. });
  349.  
  350.  
  351. app.get('/area_form',function(req,res){
  352. res.render('area_form')
  353. })
  354. app.get('/index',function(req,res){
  355. res.render('test_date_server');
  356. });
  357.  
  358. app.post('/gas_form',function(req,res){
  359. var Gas_Id = req.body.gas_id;
  360. var Gas_Code = req.body.gas_code;
  361. var Gas_Name = req.body.gas_name;
  362. console.log(Gas_Id+"\n"+Gas_Code+"\n"+Gas_Name);
  363. var gas_collection = glo_db.collection("Gas");
  364. gas_collection.insertOne({Gas_Id,Gas_Code,Gas_Name},function(err,data){
  365. if(err){ throw err; res.send({msg:"Data Not Inserted Try Agian"}) }else{
  366. console.log("Data Stored")
  367. res.send({msg:"Data Inserted"})
  368. }
  369. });
  370. })
  371. app.post('/index',function(req,res){
  372. var test,test1,test2;
  373. test = req.body.area;
  374. test1 = req.body.gas;
  375. test2 = req.body.s_date;
  376. test3 = req.body.e_date;
  377.  
  378. var areas = req.body.area;
  379. var gases = req.body.gas;
  380.  
  381. var start_date = new Date(test2);
  382. var end_date = new Date(test3);
  383. //console.log(start_date)
  384.  
  385. // hours = start_date.getHours()-5;
  386. // minutes = start_date.getMinutes()-30;
  387. // start_date.setHours(hours);start_date.setMinutes(minutes);
  388. // //console.log("Hour"+hours+"\n"+"Minutes"+minutes);
  389. // //console.log(start_date)
  390. // hours = end_date.getHours()-5;
  391. // minutes = end_date.getMinutes()-30;
  392. // //console.log("Hour"+hours+"\n"+"Minutes"+minutes);
  393. // end_date.setHours(hours);end_date.setMinutes(minutes);
  394. //console.log(end_date)
  395. //var date = new Date(test2.toISOString());
  396. //console.log(date2)
  397. var collection1 = glo_db.collection('reading');
  398. // collection1.find({},{_id:true ,Gas:true,PPM:true,time_stamp:true}).toArray(function(err,result){
  399. // if(err){ throw err }
  400. // else{
  401. // console.log(result)
  402. // }
  403. // });
  404. start_date = start_date.toISOString();
  405. end_date = end_date.toISOString();
  406. collection1.aggregate([{$unwind:"$Concentration"},{$match:{Time_Stamp:{$gte: start_date,$lte:end_date}}},
  407. {$group:{_id:"$Concentration.Gas_Name",avg_ppm:{$avg:"$Concentration.Gas_PPM"}}}
  408. ]).toArray(function (err,result) {
  409. // body..
  410. if(err){ throw err}
  411. else{
  412. console.log(result)
  413. res.send(result)
  414. // var output = [];
  415. // output.push(["Area "].concat(gases));
  416.  
  417. // res.send({result})
  418. }
  419. })
  420.  
  421. // collection1.aggregate( [ {$group: { _id: "$Gas", abc:{ $push:{ gases: "$Gas" }} } }])
  422. // .toArray(function(err,result){
  423.  
  424. // if (err){throw err;}
  425.  
  426. // else{
  427.  
  428. // console.log(result);
  429.  
  430. // }
  431.  
  432. // });
  433.  
  434.  
  435. });
  436.  
  437. app.get('/area',function(req,res){
  438. res.render("area_find");
  439. })
  440. app.post('/area',function (req,res) {
  441. // body...
  442. console.log("Area");
  443. var collection1 = glo_db.collection("Area");
  444. collection1.find({},{_id:false,Area_Id:true}).toArray(function(err,data) {
  445. if(err){throw err;}
  446. else{
  447. console.log(data);
  448. res.send(data)
  449. }
  450.  
  451. // body...
  452. })
  453. })
  454.  
  455. var area_name ;
  456.  
  457.  
  458. var j=0;
  459. var temp_area
  460. app.post('/data',function(req,res) {
  461. // body..
  462. //console.log(req.body.area_name);
  463. var device_result = [] ;
  464.  
  465. var flag = req.body.flag;
  466. //console.log(typeof(flag));
  467. if(flag == "1"){
  468.  
  469. temp_area = "";
  470.  
  471. temp_area = req.body.area_name;
  472.  
  473. }
  474. else if(flag == "0"){
  475.  
  476. temp_area = "";
  477. temp_area = req.body.area_name;
  478.  
  479.  
  480. }
  481. // //temp_area = "";
  482. var collection1 = glo_db.collection("Area");
  483. var collection2 = glo_db.collection("Device");
  484. var collection3 = glo_db.collection("inventory");
  485. collection1.find({Area_Id:temp_area},{_id:false,Area_Id:true}).toArray(function(err,data){
  486. if(err){ throw err ;}
  487. else{
  488. area_name = data[0].Area_Id;
  489. temp_area = "";
  490.  
  491. //console.log(data[0].Area_Id)
  492. collection2.find({Area_Id:data[0].Area_Id},{_id:false,Device_Id:true}).toArray(function(err,data){
  493. if(err){ throw err; }
  494. else{
  495.  
  496.  
  497. for(var i=0;i<data.length;i++){
  498.  
  499. device_result.push(data[i].Device_Id)
  500.  
  501. }
  502. //console.log(device_result);
  503. collection3.aggregate([
  504. {$match:{Device_Id:{$in:device_result}}},
  505. {$group:{_id:"$Device_Id",average_ppm:{$avg:"$Concentraction"}}}
  506. ]).toArray(function(err,data1){
  507. if(err){ throw err; }else{
  508. console.log(data1)
  509. //res.send(data1)
  510. }
  511. });
  512. }
  513. })
  514. }
  515.  
  516. })
  517.  
  518. })
  519.  
  520.  
  521. app.get('/tebs',function(req,res){
  522. res.render('tabs');
  523. })
  524. app.get('/html',function(req,res){
  525. //res.render('test1')
  526.  
  527. console.log(secure_token)
  528.  
  529.  
  530. })
  531. // app.post('/result',function(req,res) {
  532. // // body...
  533. // var collection3 = glo_db.collection("reading")
  534. // console.log("result")
  535. // console.log(area_name)
  536. // console.log(device_result)
  537. // collection3.aggregate([
  538. // {$match:{Device_Id:device_result}},
  539. // {$group:{_id:"$Device_Id",average_ppm:{$avg:"$Concentraction"}}}
  540. // ]).toArray(function(err,data){
  541. // if(err){ throw err; }else{
  542. // console.log(data)
  543. // }
  544. // })
  545.  
  546. // })
  547.  
  548.  
  549. // app.get("/table_dynamic",function(req,res){
  550. // var collection3 = glo_db.collection("reading");
  551. // setInterval(function(){
  552. // collection3.aggregate([{
  553. // $group:{_id:"$Device_Id",lat_data:{$last:"$Time_Stamp"}}
  554. // }]).toArray(function(err,data){
  555. // if(err){ throw err; }else{
  556. // console.log(data)
  557. // }
  558. // })
  559. // },10000)
  560. // })
  561. // app.post("/table_dynamic",function(req,res){
  562.  
  563.  
  564. // })
  565.  
  566. app.get('/dynamicData',function(req,res){
  567. res.render('table_change')
  568.  
  569.  
  570.  
  571. })
  572. app.post('/dynamicData',function(req,res){
  573. var area_find = req.body.area;
  574. console.log(area_find)
  575. var collection3 = glo_db.collection("reading");
  576. var collection_device = glo_db.collection("Device");
  577. var device_ids = [];
  578. collection_device.find({Area_Id:area_find},{_id:0,Device_Id:1}).toArray(function(err,data_area){
  579. if(err){ throw err; }else{
  580. for(var i=0;i<data_area.length;i++){
  581. device_ids.push(data_area[i].Device_Id)
  582. //console.log(device_ids)
  583. }
  584. }
  585. })
  586. collection3.aggregate([{$group:{_id:"$Device_Id", Gas_Con:{$last:"$Concentration"}}}
  587. ],function(err,data){
  588. if(err){
  589. throw err
  590. }
  591.  
  592. var output=[];
  593. output.push(["Device_Id","CO","CO2","PM25","PM10"])
  594.  
  595. for(var i=0;i<device_ids.length;i++){
  596. for(var j=0;j<data.length;j++){
  597. if(data[j]._id == device_ids[i]){
  598. var o = [];
  599. //console.log(data[0].Gas_Con)
  600. o.push(data[j]._id);
  601. for(var k=0;k<data[j].Gas_Con.length;k++){
  602. //console.log(data[j].Gas_Con[k].Gas_PPM)
  603. o.push(data[j].Gas_Con[k].Gas_PPM)
  604.  
  605. }
  606. output.push(o);
  607.  
  608.  
  609. }
  610. }
  611. }
  612. var string_array = JSON.stringify(output)
  613. if(output.length > 1){
  614.  
  615. res.status(200).send(output)
  616. }else{
  617. res.status(200).send({msg:"No data"})
  618. }
  619. })
  620.  
  621. })
  622.  
  623. app.get('/timePass',function(req,res){
  624.  
  625. console.log("in get timepass")
  626.  
  627. }) /// get timepass
  628. app.post('/timePass',function(req,res){
  629.  
  630. console.log("in post timepass")
  631.  
  632. }) /// get timepass
  633.  
  634.  
  635. app.listen(2525);
  636. console.log("Magic started on 2525");
  637.  
  638. //$gt: ISODate("2018-02-19T00:00:00.000Z")
Add Comment
Please, Sign In to add comment