김윤지

Merge branch 'master' into 'master'

대기오염  api 추가

대기오염 api 추가

See merge request !9

71.6 KB | W: | H:

75.3 KB | W: | H:

  • 2-up
  • Swipe
  • Onion skin
1 const db_total = require('./db_total.js'); //DB 합침 1 const db_total = require('./db_total.js'); //DB 합침
2 const secret_key = require('../keys/api_option').key; 2 const secret_key = require('../keys/api_option').key;
3 const secret_key_traffic = require('../keys/api_option_traffic').key; 3 const secret_key_traffic = require('../keys/api_option_traffic').key;
4 +const secret_key_air = require('../keys/api_option_air').key;
4 5
5 const requesting = require('request'); 6 const requesting = require('request');
6 7
...@@ -31,6 +32,7 @@ module.exports = (server, app) => { ...@@ -31,6 +32,7 @@ module.exports = (server, app) => {
31 let info = {} //;? 32 let info = {} //;?
32 33
33 let Current_TrafficAcc = {}; 34 let Current_TrafficAcc = {};
35 + let Current_AirPollution = {};
34 36
35 //API 호출_Weather 37 //API 호출_Weather
36 const req_API = (when, what) => { 38 const req_API = (when, what) => {
...@@ -80,6 +82,29 @@ module.exports = (server, app) => { ...@@ -80,6 +82,29 @@ module.exports = (server, app) => {
80 }) //Promise 82 }) //Promise
81 } 83 }
82 84
85 + //API 호출_Traffic
86 + const req_API_air = () => {
87 + //async await 사용하기 위하여 promise 사용
88 + return new Promise((resolve, reject) => {
89 + requesting.get({
90 + // api를 요청할 주소 -- 시크릿키,위도,경도 입력
91 + url: `http://api.airvisual.com/v2/nearest_city?lat=${lat}&lon=${lon}&key=${secret_key_air}`,
92 + json: true
93 + },
94 + //api에게 응답 받았을때 실행되는 callback function
95 + function (err, api_res, api_body) {
96 + //err 존재시 promise reject 호출
97 + if (err) reject(err);
98 +
99 + // api의 response이 있을경우 promise resolve 호출
100 + if (api_res) {
101 + console.log("calling air pollution api");
102 + resolve(api_body);
103 + }
104 + });
105 + }) //Promise
106 + }
107 +
83 const API_bundle = async () => { 108 const API_bundle = async () => {
84 try { 109 try {
85 var order = 0; 110 var order = 0;
...@@ -93,6 +118,7 @@ module.exports = (server, app) => { ...@@ -93,6 +118,7 @@ module.exports = (server, app) => {
93 Discomport_index = await req_API("index", "th"); //불쾌지수 118 Discomport_index = await req_API("index", "th"); //불쾌지수
94 Ultra_Violet_index = await req_API("index", "uv"); //자외선지수 119 Ultra_Violet_index = await req_API("index", "uv"); //자외선지수
95 Current_TrafficAcc = await req_API_traffic("frequentzoneLg", "getRestFrequentzoneLg"); //cate1, cate2 120 Current_TrafficAcc = await req_API_traffic("frequentzoneLg", "getRestFrequentzoneLg"); //cate1, cate2
121 + Current_AirPollution = await req_API_air();
96 order = 1; 122 order = 1;
97 break; 123 break;
98 case 1: 124 case 1:
...@@ -111,11 +137,15 @@ module.exports = (server, app) => { ...@@ -111,11 +137,15 @@ module.exports = (server, app) => {
111 typhoon: Current_Weather.common.stormYn, //현재 태풍 137 typhoon: Current_Weather.common.stormYn, //현재 태풍
112 time: Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각 138 time: Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각
113 death_prob: 0, //확률 139 death_prob: 0, //확률
140 +
114 death_number: Current_TrafficAcc.items.item[0].dth_dnv_cnt, //사망자 수 141 death_number: Current_TrafficAcc.items.item[0].dth_dnv_cnt, //사망자 수
115 midhurt_number: Current_TrafficAcc.items.item[0].se_dnv_cnt, //중상자 수 142 midhurt_number: Current_TrafficAcc.items.item[0].se_dnv_cnt, //중상자 수
116 lighthurt_number: Current_TrafficAcc.items.item[0].sl_dnv_cnt, //경상자 수 143 lighthurt_number: Current_TrafficAcc.items.item[0].sl_dnv_cnt, //경상자 수
117 - occur_number: Current_TrafficAcc.items.item[0].occrrnc_cnt //발생건수 144 + occur_number: Current_TrafficAcc.items.item[0].occrrnc_cnt, //발생건수
118 - //"spot_cd": "11440001" 145 +
146 + airpollution: Current_AirPollution.data.current.pollution.aqius //대기질 지수
147 + //aqi = 대기질 지수, aqius = us기준으로 산정, mainus:p2 미세먼지 기준 pm2.5
148 + //0-50 좋음 //51-100 보통 // 101-150 나쁨
119 } 149 }
120 console.log("API INFO \n", info); 150 console.log("API INFO \n", info);
121 151
...@@ -135,6 +165,7 @@ module.exports = (server, app) => { ...@@ -135,6 +165,7 @@ module.exports = (server, app) => {
135 (info.heat / 50) + (Math.abs(info.sensible_temperature - 15) / 10) + (info.discomport / 10) + (info.UV / 10) 165 (info.heat / 50) + (Math.abs(info.sensible_temperature - 15) / 10) + (info.discomport / 10) + (info.UV / 10)
136 + info.windspd * 1 + (info.rain / 10) + (Math.abs(info.current_temperature - 15) / 10) 166 + info.windspd * 1 + (info.rain / 10) + (Math.abs(info.current_temperature - 15) / 10)
137 + (info.death_number / 60) + (info.midhurt_number / 80) + (info.lighthurt_number / 90) + (info.occur_number / 90) 167 + (info.death_number / 60) + (info.midhurt_number / 80) + (info.lighthurt_number / 90) + (info.occur_number / 90)
168 + + (info.airpollution / 100)
138 ); 169 );
139 170
140 //이벤트 기반으로 일정 시간 간격으로 클라이언트에게 보낼 정보, 홈페이지 그래프에 나타날 정보 171 //이벤트 기반으로 일정 시간 간격으로 클라이언트에게 보낼 정보, 홈페이지 그래프에 나타날 정보
...@@ -147,7 +178,8 @@ module.exports = (server, app) => { ...@@ -147,7 +178,8 @@ module.exports = (server, app) => {
147 trafficdeath: info.death_number, 178 trafficdeath: info.death_number,
148 mhurt: info.midhurt_number, 179 mhurt: info.midhurt_number,
149 lhurt: info.lighthurt_number, 180 lhurt: info.lighthurt_number,
150 - occurence: info.occur_number 181 + occurence: info.occur_number,
182 + pollution: info.airpollution
151 }; 183 };
152 function getRandom_add_prob(min, max) { 184 function getRandom_add_prob(min, max) {
153 return Math.random() * (max - min) + min; 185 return Math.random() * (max - min) + min;
...@@ -173,12 +205,12 @@ module.exports = (server, app) => { ...@@ -173,12 +205,12 @@ module.exports = (server, app) => {
173 205
174 console.log("client send data \n", client_send) 206 console.log("client send data \n", client_send)
175 207
176 - app.get("socket").emit("weather_and_traffic_Info_minutely_send_to_client", client_send); // 클라이언트에게 정보 담아서 이벤트 발산 208 + app.get("socket").emit("weather_traffic_air_Info_minutely_send_to_client", client_send); // 클라이언트에게 정보 담아서 이벤트 발산
177 console.log("emit"); 209 console.log("emit");
178 210
179 //db에 저장 211 //db에 저장
180 - sql = "INSERT INTO apisInfo (time,wind,temperature,rain,prob,tdeath,mhurt,lhurt,occurence) VALUES (?,?,?,?,?,?,?,?,?)"; 212 + sql = "INSERT INTO apisInfo (time,wind,temperature,rain,prob,tdeath,mhurt,lhurt,occurence,pollution) VALUES (?,?,?,?,?,?,?,?,?,?)";
181 - db_total.query(sql, [client_send.time, client_send.wind, client_send.temperature, client_send.rain, client_send.death, client_send.trafficdeath, client_send.mhurt, client_send.lhurt, client_send.occurence], (err, result) => { 213 + db_total.query(sql, [client_send.time, client_send.wind, client_send.temperature, client_send.rain, client_send.death, client_send.trafficdeath, client_send.mhurt, client_send.lhurt, client_send.occurence, client_send.pollution], (err, result) => {
182 if (err) console.log(err); 214 if (err) console.log(err);
183 }) 215 })
184 order = 2; 216 order = 2;
......
...@@ -28,6 +28,7 @@ router.get('/name/:name/birth/:birth', (req, res) => { ...@@ -28,6 +28,7 @@ router.get('/name/:name/birth/:birth', (req, res) => {
28 var lhurtArr = new Array(); //경상자수 28 var lhurtArr = new Array(); //경상자수
29 var occurArr = new Array(); //총 발생수 29 var occurArr = new Array(); //총 발생수
30 //////////////////////////////////////// 30 ////////////////////////////////////////
31 + var airArr = new Array(); //대기오염 지수
31 32
32 33
33 // 이전 10분간 데이터 찾기 34 // 이전 10분간 데이터 찾기
...@@ -52,6 +53,8 @@ router.get('/name/:name/birth/:birth', (req, res) => { ...@@ -52,6 +53,8 @@ router.get('/name/:name/birth/:birth', (req, res) => {
52 mhurtArr.unshift(rows[i].mhurt); 53 mhurtArr.unshift(rows[i].mhurt);
53 lhurtArr.unshift(rows[i].lhurt); 54 lhurtArr.unshift(rows[i].lhurt);
54 occurArr.unshift(rows[i].occurence); 55 occurArr.unshift(rows[i].occurence);
56 + ////
57 + airArr.unshift(rows[i].pollution);
55 count = count + 1; 58 count = count + 1;
56 59
57 if (count == 10) { 60 if (count == 10) {
...@@ -74,7 +77,8 @@ router.get('/name/:name/birth/:birth', (req, res) => { ...@@ -74,7 +77,8 @@ router.get('/name/:name/birth/:birth', (req, res) => {
74 tdeathArr, 77 tdeathArr,
75 mhurtArr, 78 mhurtArr,
76 lhurtArr, 79 lhurtArr,
77 - occurArr 80 + occurArr,
81 + airArr
78 }); 82 });
79 } 83 }
80 }); 84 });
......
1 -<!-- <!DOCTYPE html> 1 +<!-- <!DOCTYPE html>
2 <html> 2 <html>
3 <head> 3 <head>
4 <!-- font --> 4 <!-- font -->
...@@ -48,6 +48,9 @@ ...@@ -48,6 +48,9 @@
48 <div style="display: inline-block;"> 48 <div style="display: inline-block;">
49 <div id="container5" style="width:400px; height: 300px; padding:0; margin-left:0px;margin-right: 30px;"></div> 49 <div id="container5" style="width:400px; height: 300px; padding:0; margin-left:0px;margin-right: 30px;"></div>
50 </div> 50 </div>
51 + <div style="display: inline-block;">
52 + <div id="container6" style="width:800px; height: 300px; padding:0; margin-left:0px;margin-right: 30px;"></div>
53 + </div>
51 </div> 54 </div>
52 <script src="/socket.io/socket.io.js"></script> 55 <script src="/socket.io/socket.io.js"></script>
53 <script type="text/javascript"> 56 <script type="text/javascript">
...@@ -652,9 +655,126 @@ plotOptions: { ...@@ -652,9 +655,126 @@ plotOptions: {
652 color: "#FFE08C" 655 color: "#FFE08C"
653 } 656 }
654 ] }); 657 ] });
658 + var chart6 = Highcharts.chart("container6", {
659 + chart: {
660 + type: "spline",
661 + animation: Highcharts.svg, // don't animate in old IE
662 + marginRight: 10,
663 + // events: {
664 + // load: function () {
665 + // // set up the updating of the chart each second
666 + // var series = this.series[0];
667 + // setInterval(function () {
668 + // var x = new Date().getTime(), // 현재 시간
669 + // y = Math.random(); //
670 + // series.addPoint([x, y], true, true);
671 + // }, 3000); //1000=1초
672 + // }
673 + // },
674 + backgroundColor: "rgba(255, 255, 255, 0.0)"
675 + },
676 + time: {
677 + useUTC: false
678 + },
679 + title: {
680 + text: "대기오염",
681 + style: {
682 + color: "#FFFFFF",
683 + //fontWeight: "bold",
684 + fontFamily: 'Do Hyeon',
685 + fontSize:'25px'
686 + }
687 + },
688 + xAxis: {
689 + type: "datetime",
690 + tickPixelInterval: 150,
691 + labels: {
692 + style: {
693 + color: "white"
694 + }
695 + }
696 + },
697 + yAxis: {
698 + title: {
699 + text: "대기오염지수(aqius)",
700 + style: {
701 + color: "white"
702 + }
703 + },
704 + plotLines: [
705 + {
706 + value: 0,
707 + width: 1,
708 + color: "#808080"
709 + }
710 + ],
711 + labels: {
712 + style: {
713 + color: "white"
714 + }
715 + }
716 + },
717 + tooltip: {
718 + headerFormat: "<b>{series.name}</b><br/>",
719 + pointFormat: "{point.x:%Y년%m월%d일 %H시%M분}<br/>의 대기오염지수 : {point.y:.2f}aqius - 0-50 좋음, 51-100 보통, 101-150 나쁨"
720 + },
721 + legend: {
722 + //enabled: false
723 + layout: "vertical",
724 + align: "left",
725 + verticalAlign: "top",
726 + x: 100,
727 + y: 50,
728 + floating: true,
729 + borderWidth: 1,
730 + backgroundColor:
731 + (Highcharts.theme && Highcharts.theme.legendBackgroundColor) ||
732 + "#FFFFFF"
733 + },
734 + exporting: {
735 + enabled: false
736 + },
737 + series: [
738 + {
739 + name: "대기오염지수",
740 + data: (function () {
741 + var pollutionArr = [],
742 + time = new Date().getTime();
743 + var length = <%=dataLen%>;
744 + var i = -9;
745 + var j = 0;
746 + for (j; j < 10 - length; j++) {
747 + pollutionArr.push({
748 + x: time + i * 60000,
749 + y: 0
750 + })
751 + i++;
752 + }
753 + <% airArr.forEach((occurArr) => {%>
754 + var temp;
755 + temp = <%=airArr %>;
756 + // for(j;j<10;j++)
757 + // {
758 + // pollutionArr.push({
759 + // x: time + i * 60000,
760 + // y: temp
761 + // })
762 + // i++;
763 + // }
764 + pollutionArr.push({
765 + x: time + i * 60000,
766 + y: temp
767 + })
768 + i++;
769 + <%}) %>
770 + return pollutionArr;
771 + })(),
772 + color: "#FFE08C"
773 + }
774 + ] });
655 var socket = io.connect('/', { transports: ['websocket'], upgrade: false }); 775 var socket = io.connect('/', { transports: ['websocket'], upgrade: false });
656 socket.emit("connection", client_data); 776 socket.emit("connection", client_data);
657 - socket.on("weather_and_traffic_Info_minutely_send_to_client", (info) => { //서버에서 client에게 메세지 전송 777 + socket.on("weather_traffic_air_Info_minutely_send_to_client", (info) => { //서버에서 client에게 메세지 전송
658 console.log(info); 778 console.log(info);
659 var date = new Date().getTime(); 779 var date = new Date().getTime();
660 chart1.series[0].addPoint({ 780 chart1.series[0].addPoint({
...@@ -682,6 +802,11 @@ plotOptions: { ...@@ -682,6 +802,11 @@ plotOptions: {
682 y: info.occurence*1, 802 y: info.occurence*1,
683 color:"#FFE08C" 803 color:"#FFE08C"
684 }); 804 });
805 + chart6.series[0].addPoint({
806 + x: date,
807 + y: info.pollution*1,
808 + color:"#FFE08C"
809 + });
685 }); 810 });
686 </script> 811 </script>
687 </div> 812 </div>
......