김주희

socketio.js db 하나로 통합

1 -const db = require('./db.js'); 1 +//const db = require('./db.js');
2 -const db_traffic = require('./db_traffic.js'); 2 +//const db_traffic = require('./db_traffic.js');
3 +const db_total = require('./db_total.js'); //DB 합침
3 const secret_key = require('../keys/api_option').key; 4 const secret_key = require('../keys/api_option').key;
4 const secret_key_traffic = require('../keys/api_option_traffic').key; 5 const secret_key_traffic = require('../keys/api_option_traffic').key;
5 6
...@@ -26,20 +27,20 @@ module.exports = (server, app) => { ...@@ -26,20 +27,20 @@ module.exports = (server, app) => {
26 let sending_to_client_info = {}; 27 let sending_to_client_info = {};
27 let client_send = {}; 28 let client_send = {};
28 let client_name = ""; 29 let client_name = "";
29 - let client_birth ; 30 + let client_birth;
30 let Destiny; 31 let Destiny;
31 let sql; 32 let sql;
32 let info = {} //;? 33 let info = {} //;?
33 34
34 - let Current_TrafficAcc = {}; 35 + let Current_TrafficAcc = {};
35 - let sql_traffic; 36 + //let sql_traffic;
36 - //let DeathNum_index = {}; //사 37 + //let DeathNum_index = {}; //사
37 //let M_HurtNum_index = {}; //중상자 38 //let M_HurtNum_index = {}; //중상자
38 //let L_HurtNum_index = {}; //경상자 39 //let L_HurtNum_index = {}; //경상자
39 //let LocalName_index = {}; //지역 이름 40 //let LocalName_index = {}; //지역 이름
40 //let OccurNum_index = {}; //발생 건수 41 //let OccurNum_index = {}; //발생 건수
41 //afos_fid: 다발지역 FID, bjd_cd: 법정동 코드, spot_cd:지점코드 42 //afos_fid: 다발지역 FID, bjd_cd: 법정동 코드, spot_cd:지점코드
42 - 43 +
43 //API 호출_Weather 44 //API 호출_Weather
44 const req_API = (when, what) => { 45 const req_API = (when, what) => {
45 //async await 사용하기 위하여 promise 사용 46 //async await 사용하기 위하여 promise 사용
...@@ -56,12 +57,14 @@ module.exports = (server, app) => { ...@@ -56,12 +57,14 @@ module.exports = (server, app) => {
56 57
57 // api의 response이 있을경우 promise resolve 호출 58 // api의 response이 있을경우 promise resolve 호출
58 if (api_res) { 59 if (api_res) {
59 - console.log("calling weather api"); 60 + console.log("calling weather & trafffic api");
60 resolve(api_body); 61 resolve(api_body);
61 } 62 }
62 }); 63 });
63 }) 64 })
64 } 65 }
66 +
67 +
65 //API 호출_Traffic 68 //API 호출_Traffic
66 const req_API_traffic = (cate1, cate2) => { 69 const req_API_traffic = (cate1, cate2) => {
67 //async await 사용하기 위하여 promise 사용 70 //async await 사용하기 위하여 promise 사용
...@@ -121,7 +124,7 @@ module.exports = (server, app) => { ...@@ -121,7 +124,7 @@ module.exports = (server, app) => {
121 typhoon: Current_Weather.common.stormYn, //현재 태풍 124 typhoon: Current_Weather.common.stormYn, //현재 태풍
122 time: Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각 125 time: Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각
123 death_prob: 0, //확률 126 death_prob: 0, //확률
124 - death_number: Current_TrafficAcc.items.item[0].caslt_cnt, //사상자 수 127 + death_number: Current_TrafficAcc.items.item[0].dth_dnv_cnt, //사망자 수
125 midhurt_number: Current_TrafficAcc.items.item[0].se_dnv_cnt, //중상자 수 128 midhurt_number: Current_TrafficAcc.items.item[0].se_dnv_cnt, //중상자 수
126 lighthurt_number: Current_TrafficAcc.items.item[0].sl_dnv_cnt, //경상자 수 129 lighthurt_number: Current_TrafficAcc.items.item[0].sl_dnv_cnt, //경상자 수
127 occur_number: Current_TrafficAcc.items.item[0].occrrnc_cnt //발생건수 130 occur_number: Current_TrafficAcc.items.item[0].occrrnc_cnt //발생건수
...@@ -143,7 +146,8 @@ module.exports = (server, app) => { ...@@ -143,7 +146,8 @@ module.exports = (server, app) => {
143 //죽을 확률 계산(내맘대로 커스텀) 146 //죽을 확률 계산(내맘대로 커스텀)
144 info.death_prob = ( 147 info.death_prob = (
145 (info.heat / 50) + (Math.abs(info.sensible_temperature - 15) / 10) + (info.discomport / 10) + (info.UV / 10) 148 (info.heat / 50) + (Math.abs(info.sensible_temperature - 15) / 10) + (info.discomport / 10) + (info.UV / 10)
146 - + info.windspd*1 + (info.rain / 10) + (Math.abs(info.current_temperature - 15) / 10) 149 + + info.windspd * 1 + (info.rain / 10) + (Math.abs(info.current_temperature - 15) / 10)
150 + + (info.death_number / 50) + (info.midhurt_number / 80) + (info.lighthurt_number / 90) + (info.occur_number / 90)
147 ); 151 );
148 152
149 //이벤트 기반으로 일정 시간 간격으로 클라이언트에게 보낼 정보, 홈페이지 그래프에 나타날 정보 153 //이벤트 기반으로 일정 시간 간격으로 클라이언트에게 보낼 정보, 홈페이지 그래프에 나타날 정보
...@@ -160,19 +164,19 @@ module.exports = (server, app) => { ...@@ -160,19 +164,19 @@ module.exports = (server, app) => {
160 }; 164 };
161 function getRandom_add_prob(min, max) { 165 function getRandom_add_prob(min, max) {
162 return Math.random() * (max - min) + min; 166 return Math.random() * (max - min) + min;
163 - } 167 + }
164 - 168 +
169 +
170 + // 심장이 크게 뛰며 확률이 증가하거나 감소 할 수 있음
171 + Math.random() * 2 >= 1 ? client_send.death += getRandom_add_prob(0, 5) : client_send.death -= getRandom_add_prob(0, 5);
165 172
166 - // 심장이 크게 뛰며 확률이 증가하거나 감소 할 수 있음 173 +
167 - Math.random() * 2 >= 1 ? client_send.death += getRandom_add_prob(0,5) : client_send.death -= getRandom_add_prob(0,5) ; 174 + //운명의 장난으로 죽을 확률이 증가하거나 감소함
168 - 175 + const rand = Math.floor(Math.random() * 6) //생년월일 중 한자리 뽑음
169 - 176 +
170 - //운명의 장난으로 죽을 확률이 증가하거나 감소함 177 + Destiny = client_birth.charAt(rand) / 3; //명시적 형 변환
171 - const rand = Math.floor(Math.random() * 6) //생년월일 중 한자리 뽑음 178 + if (Destiny == 0) Destiny = 1; //사용자 잘못 입력했을때 예외처리
172 - 179 + Math.random() * 2 >= 1 ? client_send.death += Destiny : client_send.death -= Destiny;
173 - Destiny=client_birth.charAt(rand)/3; //명시적 형 변환
174 - if(Destiny==0)Destiny=1; //사용자 잘못 입력했을때 예외처리
175 - Math.random() * 2 >= 1 ? client_send.death += Destiny : client_send.death -= Destiny ;
176 180
177 181
178 //만약 날이 너무 안좋아서 확률이 100을 넘긴다면 100으로 예외처리 182 //만약 날이 너무 안좋아서 확률이 100을 넘긴다면 100으로 예외처리
...@@ -180,13 +184,13 @@ module.exports = (server, app) => { ...@@ -180,13 +184,13 @@ module.exports = (server, app) => {
180 client_send.death = 100; 184 client_send.death = 100;
181 } 185 }
182 186
183 - console.log("client send data \n",client_send) 187 + console.log("client send data \n", client_send)
184 - 188 +
185 app.get("socket").emit("weather_and_traffic_Info_minutely_send_to_client", client_send); // 클라이언트에게 정보 담아서 이벤트 발산 189 app.get("socket").emit("weather_and_traffic_Info_minutely_send_to_client", client_send); // 클라이언트에게 정보 담아서 이벤트 발산
186 console.log("emit"); 190 console.log("emit");
187 191
188 //db에 저장 192 //db에 저장
189 - sql = "INSERT INTO weatherInfo (time,wind,temperature,rain,prob) VALUES (?,?,?,?,?)"; 193 + /*sql = "INSERT INTO weatherInfo (time,wind,temperature,rain,prob) VALUES (?,?,?,?,?)";
190 db.query(sql, [client_send.time, client_send.wind, client_send.temperature, client_send.rain, client_send.death], (err, result) => { 194 db.query(sql, [client_send.time, client_send.wind, client_send.temperature, client_send.rain, client_send.death], (err, result) => {
191 if (err) console.log(err); 195 if (err) console.log(err);
192 }) 196 })
...@@ -194,7 +198,12 @@ module.exports = (server, app) => { ...@@ -194,7 +198,12 @@ module.exports = (server, app) => {
194 sql_traffic = "INSERT INTO trafficInfo (tdeath,mhurt,lhurt,occurence,prob) VALUES (?,?,?,?,?)"; 198 sql_traffic = "INSERT INTO trafficInfo (tdeath,mhurt,lhurt,occurence,prob) VALUES (?,?,?,?,?)";
195 db_traffic.query(sql_traffic, [client_send.trafficdeath, client_send.mhurt, client_send.lhurt, client_send.occurence, client_send.death], (err, result) => { 199 db_traffic.query(sql_traffic, [client_send.trafficdeath, client_send.mhurt, client_send.lhurt, client_send.occurence, client_send.death], (err, result) => {
196 if (err) console.log(err); 200 if (err) console.log(err);
201 + })*/
202 + sql = "INSERT INTO apisInfo (time,wind,temperature,rain,prob,tdeath,mhurt,lhurt,occurence) VALUES (?,?,?,?,?,?,?,?,?)";
203 + 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) => {
204 + if (err) console.log(err);
197 }) 205 })
206 +
198 } catch (err) { //promise err or try err catch 207 } catch (err) { //promise err or try err catch
199 console.log("================Error Occured !!================\n", err); 208 console.log("================Error Occured !!================\n", err);
200 } 209 }
...@@ -205,7 +214,7 @@ module.exports = (server, app) => { ...@@ -205,7 +214,7 @@ module.exports = (server, app) => {
205 const Start_Interval = (second, CALL) => { 214 const Start_Interval = (second, CALL) => {
206 CALL(); //처음 불러올때 한번 호출하고 215 CALL(); //처음 불러올때 한번 호출하고
207 call_interval = setInterval(CALL, second * 1000); //그 후에 1분마다 호출 216 call_interval = setInterval(CALL, second * 1000); //그 후에 1분마다 호출
208 - } 217 + }
209 218
210 io.on('connection', (socket) => { //프론트와 소켓 연결시 이벤트 루프 동작 219 io.on('connection', (socket) => { //프론트와 소켓 연결시 이벤트 루프 동작
211 220
......