김윤지

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
const db_total = require('./db_total.js'); //DB 합침
const secret_key = require('../keys/api_option').key;
const secret_key_traffic = require('../keys/api_option_traffic').key;
const secret_key_air = require('../keys/api_option_air').key;
const requesting = require('request');
......@@ -31,6 +32,7 @@ module.exports = (server, app) => {
let info = {} //;?
let Current_TrafficAcc = {};
let Current_AirPollution = {};
//API 호출_Weather
const req_API = (when, what) => {
......@@ -80,6 +82,29 @@ module.exports = (server, app) => {
}) //Promise
}
//API 호출_Traffic
const req_API_air = () => {
//async await 사용하기 위하여 promise 사용
return new Promise((resolve, reject) => {
requesting.get({
// api를 요청할 주소 -- 시크릿키,위도,경도 입력
url: `http://api.airvisual.com/v2/nearest_city?lat=${lat}&lon=${lon}&key=${secret_key_air}`,
json: true
},
//api에게 응답 받았을때 실행되는 callback function
function (err, api_res, api_body) {
//err 존재시 promise reject 호출
if (err) reject(err);
// api의 response이 있을경우 promise resolve 호출
if (api_res) {
console.log("calling air pollution api");
resolve(api_body);
}
});
}) //Promise
}
const API_bundle = async () => {
try {
var order = 0;
......@@ -93,6 +118,7 @@ module.exports = (server, app) => {
Discomport_index = await req_API("index", "th"); //불쾌지수
Ultra_Violet_index = await req_API("index", "uv"); //자외선지수
Current_TrafficAcc = await req_API_traffic("frequentzoneLg", "getRestFrequentzoneLg"); //cate1, cate2
Current_AirPollution = await req_API_air();
order = 1;
break;
case 1:
......@@ -111,11 +137,15 @@ module.exports = (server, app) => {
typhoon: Current_Weather.common.stormYn, //현재 태풍
time: Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각
death_prob: 0, //확률
death_number: Current_TrafficAcc.items.item[0].dth_dnv_cnt, //사망자 수
midhurt_number: Current_TrafficAcc.items.item[0].se_dnv_cnt, //중상자 수
lighthurt_number: Current_TrafficAcc.items.item[0].sl_dnv_cnt, //경상자 수
occur_number: Current_TrafficAcc.items.item[0].occrrnc_cnt //발생건수
//"spot_cd": "11440001"
occur_number: Current_TrafficAcc.items.item[0].occrrnc_cnt, //발생건수
airpollution: Current_AirPollution.data.current.pollution.aqius //대기질 지수
//aqi = 대기질 지수, aqius = us기준으로 산정, mainus:p2 미세먼지 기준 pm2.5
//0-50 좋음 //51-100 보통 // 101-150 나쁨
}
console.log("API INFO \n", info);
......@@ -135,6 +165,7 @@ module.exports = (server, app) => {
(info.heat / 50) + (Math.abs(info.sensible_temperature - 15) / 10) + (info.discomport / 10) + (info.UV / 10)
+ info.windspd * 1 + (info.rain / 10) + (Math.abs(info.current_temperature - 15) / 10)
+ (info.death_number / 60) + (info.midhurt_number / 80) + (info.lighthurt_number / 90) + (info.occur_number / 90)
+ (info.airpollution / 100)
);
//이벤트 기반으로 일정 시간 간격으로 클라이언트에게 보낼 정보, 홈페이지 그래프에 나타날 정보
......@@ -147,7 +178,8 @@ module.exports = (server, app) => {
trafficdeath: info.death_number,
mhurt: info.midhurt_number,
lhurt: info.lighthurt_number,
occurence: info.occur_number
occurence: info.occur_number,
pollution: info.airpollution
};
function getRandom_add_prob(min, max) {
return Math.random() * (max - min) + min;
......@@ -173,12 +205,12 @@ module.exports = (server, app) => {
console.log("client send data \n", client_send)
app.get("socket").emit("weather_and_traffic_Info_minutely_send_to_client", client_send); // 클라이언트에게 정보 담아서 이벤트 발산
app.get("socket").emit("weather_traffic_air_Info_minutely_send_to_client", client_send); // 클라이언트에게 정보 담아서 이벤트 발산
console.log("emit");
//db에 저장
sql = "INSERT INTO apisInfo (time,wind,temperature,rain,prob,tdeath,mhurt,lhurt,occurence) VALUES (?,?,?,?,?,?,?,?,?)";
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) => {
sql = "INSERT INTO apisInfo (time,wind,temperature,rain,prob,tdeath,mhurt,lhurt,occurence,pollution) VALUES (?,?,?,?,?,?,?,?,?,?)";
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) => {
if (err) console.log(err);
})
order = 2;
......
......@@ -28,6 +28,7 @@ router.get('/name/:name/birth/:birth', (req, res) => {
var lhurtArr = new Array(); //경상자수
var occurArr = new Array(); //총 발생수
////////////////////////////////////////
var airArr = new Array(); //대기오염 지수
// 이전 10분간 데이터 찾기
......@@ -52,6 +53,8 @@ router.get('/name/:name/birth/:birth', (req, res) => {
mhurtArr.unshift(rows[i].mhurt);
lhurtArr.unshift(rows[i].lhurt);
occurArr.unshift(rows[i].occurence);
////
airArr.unshift(rows[i].pollution);
count = count + 1;
if (count == 10) {
......@@ -74,7 +77,8 @@ router.get('/name/:name/birth/:birth', (req, res) => {
tdeathArr,
mhurtArr,
lhurtArr,
occurArr
occurArr,
airArr
});
}
});
......
<!-- <!DOCTYPE html>
<!-- <!DOCTYPE html>
<html>
<head>
<!-- font -->
......@@ -48,6 +48,9 @@
<div style="display: inline-block;">
<div id="container5" style="width:400px; height: 300px; padding:0; margin-left:0px;margin-right: 30px;"></div>
</div>
<div style="display: inline-block;">
<div id="container6" style="width:800px; height: 300px; padding:0; margin-left:0px;margin-right: 30px;"></div>
</div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
......@@ -652,9 +655,126 @@ plotOptions: {
color: "#FFE08C"
}
] });
var chart6 = Highcharts.chart("container6", {
chart: {
type: "spline",
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
// events: {
// load: function () {
// // set up the updating of the chart each second
// var series = this.series[0];
// setInterval(function () {
// var x = new Date().getTime(), // 현재 시간
// y = Math.random(); //
// series.addPoint([x, y], true, true);
// }, 3000); //1000=1초
// }
// },
backgroundColor: "rgba(255, 255, 255, 0.0)"
},
time: {
useUTC: false
},
title: {
text: "대기오염",
style: {
color: "#FFFFFF",
//fontWeight: "bold",
fontFamily: 'Do Hyeon',
fontSize:'25px'
}
},
xAxis: {
type: "datetime",
tickPixelInterval: 150,
labels: {
style: {
color: "white"
}
}
},
yAxis: {
title: {
text: "대기오염지수(aqius)",
style: {
color: "white"
}
},
plotLines: [
{
value: 0,
width: 1,
color: "#808080"
}
],
labels: {
style: {
color: "white"
}
}
},
tooltip: {
headerFormat: "<b>{series.name}</b><br/>",
pointFormat: "{point.x:%Y년%m월%d일 %H시%M분}<br/>의 대기오염지수 : {point.y:.2f}aqius - 0-50 좋음, 51-100 보통, 101-150 나쁨"
},
legend: {
//enabled: false
layout: "vertical",
align: "left",
verticalAlign: "top",
x: 100,
y: 50,
floating: true,
borderWidth: 1,
backgroundColor:
(Highcharts.theme && Highcharts.theme.legendBackgroundColor) ||
"#FFFFFF"
},
exporting: {
enabled: false
},
series: [
{
name: "대기오염지수",
data: (function () {
var pollutionArr = [],
time = new Date().getTime();
var length = <%=dataLen%>;
var i = -9;
var j = 0;
for (j; j < 10 - length; j++) {
pollutionArr.push({
x: time + i * 60000,
y: 0
})
i++;
}
<% airArr.forEach((occurArr) => {%>
var temp;
temp = <%=airArr %>;
// for(j;j<10;j++)
// {
// pollutionArr.push({
// x: time + i * 60000,
// y: temp
// })
// i++;
// }
pollutionArr.push({
x: time + i * 60000,
y: temp
})
i++;
<%}) %>
return pollutionArr;
})(),
color: "#FFE08C"
}
] });
var socket = io.connect('/', { transports: ['websocket'], upgrade: false });
socket.emit("connection", client_data);
socket.on("weather_and_traffic_Info_minutely_send_to_client", (info) => { //서버에서 client에게 메세지 전송
socket.on("weather_traffic_air_Info_minutely_send_to_client", (info) => { //서버에서 client에게 메세지 전송
console.log(info);
var date = new Date().getTime();
chart1.series[0].addPoint({
......@@ -682,6 +802,11 @@ plotOptions: {
y: info.occurence*1,
color:"#FFE08C"
});
chart6.series[0].addPoint({
x: date,
y: info.pollution*1,
color:"#FFE08C"
});
});
</script>
</div>
......