Showing
1 changed file
with
74 additions
and
55 deletions
| ... | @@ -5,12 +5,23 @@ const lat = "37.239795"; | ... | @@ -5,12 +5,23 @@ 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 | + |
| 23 | + const req_API = (when, what) => { | ||
| 24 | + //async await 사용하기 위하여 promise 사용 | ||
| 14 | return new Promise((resolve, reject) => { | 25 | return new Promise((resolve, reject) => { |
| 15 | requesting.get({ | 26 | requesting.get({ |
| 16 | // api를 요청할 주소 -- 시크릿키,위도,경도 입력 | 27 | // api를 요청할 주소 -- 시크릿키,위도,경도 입력 |
| ... | @@ -24,38 +35,21 @@ module.exports = (server, app) => { | ... | @@ -24,38 +35,21 @@ module.exports = (server, app) => { |
| 24 | 35 | ||
| 25 | // api의 response이 있을경우 promise resolve 호출 | 36 | // api의 response이 있을경우 promise resolve 호출 |
| 26 | if (api_res) { | 37 | if (api_res) { |
| 27 | - console.log("call"); | 38 | + console.log("calling api"); |
| 28 | resolve(api_body); | 39 | resolve(api_body); |
| 29 | } | 40 | } |
| 30 | }); | 41 | }); |
| 31 | }) | 42 | }) |
| 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; | ||
| 44 | - | ||
| 45 | - socket.on("connection", () => { | ||
| 46 | - console.log("lala"); | ||
| 47 | - // API_CALL = setInterval(() => { | ||
| 48 | - console.log("lala"); | ||
| 49 | - | ||
| 50 | 43 | ||
| 44 | + } | ||
| 51 | const API_bundle = async () => { | 45 | const API_bundle = async () => { |
| 52 | 46 | ||
| 53 | try { | 47 | try { |
| 54 | - Current_Weather = await CALL("current", "minutely"); //현재날씨 (분별) | 48 | + Current_Weather = await req_API("current", "minutely"); //현재날씨 (분별) |
| 55 | - Sensible_T = await CALL("index", "wct"); //체감온도 | 49 | + Sensible_T = await req_API("index", "wct"); //체감온도 |
| 56 | - Heat_index = await CALL("index", "heat"); //열지수 | 50 | + Heat_index = await req_API("index", "heat"); //열지수 |
| 57 | - Discomport_index = await CALL("index", "th"); //불쾌지수 | 51 | + Discomport_index = await req_API("index", "th"); //불쾌지수 |
| 58 | - Ultra_Violet_index = await CALL("index", "uv"); //자외선지수 | 52 | + Ultra_Violet_index = await req_API("index", "uv"); //자외선지수 |
| 59 | console.log("bundle"); | 53 | console.log("bundle"); |
| 60 | 54 | ||
| 61 | info = { | 55 | info = { |
| ... | @@ -78,53 +72,78 @@ module.exports = (server, app) => { | ... | @@ -78,53 +72,78 @@ module.exports = (server, app) => { |
| 78 | 72 | ||
| 79 | // ------------------------------ death_prob 정의 ------------------------------ | 73 | // ------------------------------ death_prob 정의 ------------------------------ |
| 80 | 74 | ||
| 81 | - info.death_prob += info.sky.substr(5)*1 //하늘 상태에 따라 확률 증가 | 75 | + info.death_prob += info.sky.substr(5) * 1 //하늘 상태에 따라 확률 증가 |
| 82 | 76 | ||
| 83 | - if(info.lightning===1) //낙뢰시에 확률 증가 | 77 | + if (info.lightning === 1) //낙뢰시에 확률 증가 |
| 84 | info.death_prob += 10; | 78 | info.death_prob += 10; |
| 85 | - if(info.typhoon === "Y") //태풍시에 확률 증가 | 79 | + if (info.typhoon === "Y") //태풍시에 확률 증가 |
| 86 | info.death_prob += 10; | 80 | info.death_prob += 10; |
| 87 | - if(info.warning === "Y") // 특보 발령시 확률 증가 | 81 | + if (info.warning === "Y") // 특보 발령시 확률 증가 |
| 88 | info.death_prob += 5 | 82 | info.death_prob += 5 |
| 89 | 83 | ||
| 90 | //죽을 확률 계산(내맘대로 커스텀) | 84 | //죽을 확률 계산(내맘대로 커스텀) |
| 91 | - info.death_prob =( | 85 | + info.death_prob = ( |
| 92 | - (info.heat/8) + (Math.abs(info.sensible_temperature-15)/2) + (info.discomport/10) + (info.UV/5) | 86 | + (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) | 87 | + + (info.windspd * 3) + (info.rain / 10) + (Math.abs(info.current_temperature - 15) / 2) |
| 94 | ); | 88 | ); |
| 95 | 89 | ||
| 96 | //이벤트 기반으로 일정 시간 간격으로 클라이언트에게 보낼 정보 | 90 | //이벤트 기반으로 일정 시간 간격으로 클라이언트에게 보낼 정보 |
| 97 | - client_send={ | 91 | + client_send = { |
| 98 | - time : info.time, | 92 | + time: info.time, |
| 99 | - wind : info.windspd, | 93 | + wind: info.windspd, |
| 100 | - temperature : info.current_temperature, | 94 | + temperature: info.current_temperature, |
| 101 | - rain : info.rain, | 95 | + rain: info.rain, |
| 102 | - death : info.death_prob | 96 | + death: info.death_prob |
| 103 | }; | 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 | + | ||
| 104 | 105 | ||
| 105 | //만약 날이 너무 안좋아서 확률이 100을 넘긴다면 100으로 예외처리 | 106 | //만약 날이 너무 안좋아서 확률이 100을 넘긴다면 100으로 예외처리 |
| 106 | - if(client_send.death>=100){ | 107 | + if (client_send.death >= 100) { |
| 107 | - client_send.death=100; | 108 | + client_send.death = 100; |
| 108 | } | 109 | } |
| 109 | 110 | ||
| 110 | console.log(client_send) | 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 | + }) | ||
| 111 | } catch (err) { //promise err or try err catch | 121 | } catch (err) { //promise err or try err catch |
| 112 | - console.log("================Error Occured !!================\n",err); | 122 | + console.log("================Error Occured !!================\n", err); |
| 113 | } | 123 | } |
| 114 | } | 124 | } |
| 115 | - API_bundle(); | 125 | + |
| 116 | - | 126 | + let call_interval; |
| 117 | - // //db에 저장 | 127 | + |
| 118 | - // sql="INSERT INTO weatherInfo (time,wind,temperature,rain,prob) VALUES (?,?,?,?,?)"; | 128 | + const Start_Interval = (second, CALL) => { |
| 119 | - // db.query(sql,[client_send.time,client_send.wind,client_send.temperature,client_send.rain,client_send.death],(err,result)=>{ | 129 | + CALL(); //처음 불러올때 한번 호출하고 |
| 120 | - // if(err) console.log(err); | 130 | + call_interval = setInterval(CALL, second * 1000); //그 후에 1분마다 호출 |
| 121 | - // socket.emit("weatherInfo_minutely_send_to_client",client_send); // 클라이언트에게 정보 담아서 이벤트 발산 | 131 | + } |
| 122 | - // }) | 132 | + |
| 123 | - // }, 1* 1000); //1분마다 호출 | 133 | + io.on('connection', (socket) => { //프론트와 소켓 연결시 이벤트 루프 동작 |
| 134 | + | ||
| 135 | + app.set("socket", socket); | ||
| 136 | + socket.on("connection", () => { | ||
| 137 | + console.log("SOCKET CONNECTED"); | ||
| 138 | + | ||
| 139 | + Start_Interval(60, API_bundle); //소켓 연결후 interval 활성화하여 1분마다 API 호출 | ||
| 140 | + | ||
| 124 | }); | 141 | }); |
| 125 | 142 | ||
| 126 | - socket.on('disconnecting', (reason) => { | 143 | + socket.on('disconnect', (reason) => { |
| 127 | - clearInterval(API_CALL); //연결 종료시 해제 | 144 | + console.log("disconnected"); |
| 145 | + clearInterval(call_interval); //연결 종료시 interval 해제 | ||
| 128 | }) | 146 | }) |
| 129 | }) | 147 | }) |
| 130 | - } | 148 | + |
| 149 | +} | ... | ... |
-
Please register or login to post a comment