DESKTOP-PC6TBNS\강환석씨

The API call result was not normally contained in the (info) object because node…

…js processed the function asynchronously. So we used the following grammar rules, async, await, and changed it to call api synchronously. Good operation
...@@ -5,98 +5,126 @@ const lat = "37.239795"; ...@@ -5,98 +5,126 @@ const lat = "37.239795";
5 const lon = "127.083240"; 5 const lon = "127.083240";
6 module.exports = (server, app) => { 6 module.exports = (server, app) => {
7 7
8 - const io = require('socket.io', )(server, { 8 + const io = require('socket.io', )(server, {
9 - transports: ['websocket'] 9 + transports: ['websocket']
10 - }); 10 + });
11 11
12 - let info = {} 12 + let info = {}
13 - const CALL = (when, what) => { 13 + const CALL = (when, what) => {
14 - requesting.get({ 14 + return new Promise((resolve, reject) => {
15 - // api를 요청할 주소 -- 시크릿키,위도,경도 입력 15 + requesting.get({
16 - url: `https://api2.sktelecom.com/weather/${when}/${what}?appKey=${secret_key}&lat=${lat}&lon=${lon}`, 16 + // api를 요청할 주소 -- 시크릿키,위도,경도 입력
17 - json: true 17 + url: `https://api2.sktelecom.com/weather/${when}/${what}?appKey=${secret_key}&lat=${lat}&lon=${lon}`,
18 - }, 18 + json: true
19 - //api에게 응답 받았을때 실행되는 callback function 19 + },
20 - function (err, api_res, api_body) { 20 + //api에게 응답 받았을때 실행되는 callback function
21 - if (err) throw err; 21 + function (err, api_res, api_body) {
22 - // api의 대답이 있을경우 실행 22 + //err 존재시 promise reject 호출
23 - if (api_res) { 23 + if (err) reject(err);
24 - return api_body;
25 - // api_body.weather.minutely[0]
26 - }
27 - });
28 - }
29 - io.on('connection', (socket) => { //웹 페이지 연결시 루프 동작
30 - let API_CALL;
31 - let Current_Weather ={};
32 - let Sensible_T;
33 - let Heat_index={};
34 - let Discomport_index={};
35 - let Ultra_Violet_index={};
36 - let sending_to_client_info={};
37 - let client_send={};
38 - let sql;
39 24
40 - socket.on("connection", () => { 25 + // api의 response이 있을경우 promise resolve 호출
41 - API_CALL = setInterval(() => { 26 + if (api_res) {
27 + console.log("call");
28 + resolve(api_body);
29 + }
30 + });
31 + })
32 + }
33 + io.on('connection', (socket) => { //웹 페이지 연결시 루프 동작
34 + let API_CALL;
35 + //명시적으로 객체임을 선언
36 + let Current_Weather = {};
37 + let Sensible_T = {};
38 + let Heat_index = {};
39 + let Discomport_index = {};
40 + let Ultra_Violet_index = {};
41 + let sending_to_client_info = {};
42 + let client_send = {};
43 + let sql;
42 44
43 - Current_Weather = CALL("current","minutely"); //현재날씨 (분별) 45 + socket.on("connection", () => {
44 - Sensible_T = CALL("index","wct"); //체감온도 46 + console.log("lala");
45 - Heat_index = CALL("index","heat"); //열지수 47 + // API_CALL = setInterval(() => {
46 - Discomport_index = CALL("index","th"); //불쾌지수 48 + console.log("lala");
47 - Ultra_Violet_index = CALL("index","uv"); //자외선지수
48 -
49 - info = {
50 - heat : Sensible_T.weather.wIndex.heatIndex[0].current.index, //열지수
51 - sensible_temperature : Sensible_T.weather.wIndex.wctIndex[0].current.index, //체감온도
52 - discomport : Discomport_index.weather.wIndex.thIndex[0].current.index, //불쾌지수
53 - UV : Ultra_Violet_index.weather.wIndex.uvindex[0].day00.index, //자외선지수
54 - windspd : Current_Weather.weather.minutely[0].wind.wspd, //바람 속도
55 - sky : Current_Weather.weather.minutely[0].sky.code, //하늘 상태
56 - rain : Current_Weather.weather.minutely[0].rain.last24hour, //강수량
57 - current_temperature : Current_Weather.weather.minutely[0].temperature.tc, //현재 온도
58 - lightning : Current_Weather.weather.minutely[0].lightning, //현재 낙뢰
59 - warning : Current_Weather.common.alertYn, //현재 특보 유무
60 - typhoon : Current_Weather.common.stormYn, //현재 태풍
61 - time : Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각
62 - death_prob:0 //확률
63 - }
64 49
65 - info.death_prob += info.sky.substr(5)*1 //하늘 상태에 따라 확률 증가
66 50
67 - if(info.lightning===1) //낙뢰시에 확률 증가 51 + const API_bundle = async () => {
68 - info.death_prob += 10;
69 - if(info.typhoon === "Y") //태풍시에 확률 증가
70 - info.death_prob += 10;
71 - if(info.warning === "Y") // 특보 발령시 확률 증가
72 - info.death_prob += 5
73 52
74 - //죽을 확률 계산(내맘대로) 53 + try {
75 - info.death_prob =( 54 + Current_Weather = await CALL("current", "minutely"); //현재날씨 (분별)
76 - (info.heat/8) + (abs(info.sensible_temperature-15)/2) + (info.discomport/10) + (info.UV/5) 55 + Sensible_T = await CALL("index", "wct"); //체감온도
77 - + (info.windspd*3) + (info.rain/10) + (abs(info.current_temperature-15)/2) 56 + Heat_index = await CALL("index", "heat"); //열지수
78 - ); 57 + Discomport_index = await CALL("index", "th"); //불쾌지수
58 + Ultra_Violet_index = await CALL("index", "uv"); //자외선지수
59 + console.log("bundle");
79 60
80 - client_send={ 61 + info = {
81 - time : info.time, 62 + heat: Heat_index.weather.wIndex.heatIndex[0].current.index, //열지수
82 - wind : info.windspd, 63 + sensible_temperature: Sensible_T.weather.wIndex.wctIndex[0].current.index, //체감온도
83 - temperature : info.current_temperature, 64 + discomport: Discomport_index.weather.wIndex.thIndex[0].current.index, //불쾌지수
84 - rain : info.rain, 65 + UV: Ultra_Violet_index.weather.wIndex.uvindex[0].day01.index, //자외선지수
85 - death : info.death_prob 66 + windspd: Current_Weather.weather.minutely[0].wind.wspd, //바람 속도
86 - }; 67 + sky: Current_Weather.weather.minutely[0].sky.code, //하늘 상태
68 + rain: Current_Weather.weather.minutely[0].rain.last24hour, //강수량
69 + current_temperature: Current_Weather.weather.minutely[0].temperature.tc, //현재 온도
70 + lightning: Current_Weather.weather.minutely[0].lightning, //현재 낙뢰
71 + warning: Current_Weather.common.alertYn, //현재 특보 유무
72 + typhoon: Current_Weather.common.stormYn, //현재 태풍
73 + time: Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각
74 + death_prob: 0 //확률
75 + }
76 + console.log("callback")
77 + console.log(info);
78 +
79 + // ------------------------------ death_prob 정의 ------------------------------
87 80
88 - //db에 저장 81 + info.death_prob += info.sky.substr(5)*1 //하늘 상태에 따라 확률 증가
89 - sql="INSERT INTO weatherInfo (time,wind,temperature,rain,prob) VALUES (?,?,?,?,?)"; 82 +
90 - db.query(sql,[client_send.time,client_send.wind,client_send.temperature,client_send.rain,client_send.death],(err,result)=>{ 83 + if(info.lightning===1) //낙뢰시에 확률 증가
91 - if(err) console.log(err); 84 + info.death_prob += 10;
92 - socket.emit("weatherInfo_minutely_send_to_client",client_send); // 클라이언트에게 정보 담아서 이벤트 발산 85 + if(info.typhoon === "Y") //태풍시에 확률 증가
93 - }) 86 + info.death_prob += 10;
94 - }, 60 * 1000); //1분마다 호출 87 + if(info.warning === "Y") // 특보 발령시 확률 증가
95 - }); 88 + info.death_prob += 5
89 +
90 + //죽을 확률 계산(내맘대로 커스텀)
91 + info.death_prob =(
92 + (info.heat/8) + (Math.abs(info.sensible_temperature-15)/2) + (info.discomport/10) + (info.UV/5)
93 + + (info.windspd*3) + (info.rain/10) + (Math.abs(info.current_temperature-15)/2)
94 + );
96 95
97 - socket.on('disconnecting', (reason) => { 96 + //이벤트 기반으로 일정 시간 간격으로 클라이언트에게 보낼 정보
98 - clearInterval(API_CALL); //연결 종료시 해제 97 + client_send={
99 - }) 98 + time : info.time,
100 - }) 99 + wind : info.windspd,
101 -} 100 + temperature : info.current_temperature,
101 + rain : info.rain,
102 + death : info.death_prob
103 + };
102 104
105 + //만약 날이 너무 안좋아서 확률이 100을 넘긴다면 100으로 예외처리
106 + if(client_send.death>=100){
107 + client_send.death=100;
108 + }
109 +
110 + console.log(client_send)
111 + } catch (err) { //promise err or try err catch
112 + console.log("================Error Occured !!================\n",err);
113 + }
114 + }
115 + API_bundle();
116 +
117 + // //db에 저장
118 + // sql="INSERT INTO weatherInfo (time,wind,temperature,rain,prob) VALUES (?,?,?,?,?)";
119 + // db.query(sql,[client_send.time,client_send.wind,client_send.temperature,client_send.rain,client_send.death],(err,result)=>{
120 + // if(err) console.log(err);
121 + // socket.emit("weatherInfo_minutely_send_to_client",client_send); // 클라이언트에게 정보 담아서 이벤트 발산
122 + // })
123 + // }, 1* 1000); //1분마다 호출
124 + });
125 +
126 + socket.on('disconnecting', (reason) => {
127 + clearInterval(API_CALL); //연결 종료시 해제
128 + })
129 + })
130 + }
......
...@@ -38,20 +38,19 @@ ...@@ -38,20 +38,19 @@
38 ></div> 38 ></div>
39 </div> 39 </div>
40 </div> 40 </div>
41 -<<<<<<< HEAD
42 41
43 <script src="/socket.io/socket.io.js"></script> 42 <script src="/socket.io/socket.io.js"></script>
44 <script> 43 <script>
45 - var socket = io.connect('/'); 44 + var socket = io('http://localhost',{transports: ['websocket']});
46 - socket.emit("connection"); 45 + socket.emit("connection",()=>{
47 - socket.on("weatherInfo_minutely_send_to_cliend",(info)=>{ //서버에서 client에게 메세지 전송 46 + console.log("connected");
47 + });
48 + socket.on("weatherInfo_minutely_send_to_client",(info)=>{ //서버에서 client에게 메세지 전송
48 console.log(info); 49 console.log(info);
49 }); 50 });
50 </script> 51 </script>
51 52
52 -=======
53 53
54 ->>>>>>> 0f5edf6316e2444f5fd2a050fed5e771e5141733
55 <!-- 첫번째 그래프 --> 54 <!-- 첫번째 그래프 -->
56 <script type="text/javascript"> 55 <script type="text/javascript">
57 Highcharts.chart("container1", { 56 Highcharts.chart("container1", {
......