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