Guest User

Untitled

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