Guest User

Untitled

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