Ubuntu

add city, county, village / convert lat, lon

No preview for this file type
1 +const db = require('./db.js');
2 +const secret_key = require('./keys/api_option').key;
3 +const requesting = require('request');
4 +const key = require('./keys/api_map').key;
5 +const lat = "37.239795";
6 +const lon = "127.083240";
7 +//const city = client_data.city;
8 +//const county = client_data.county;
9 +//const village = client_data.village;
10 +module.exports = (server, app) => {
11 +
12 + const io = require('socket.io')(server, {
13 + transports: ['websocket'] // websocket 사용시 polling 사용을 배제하고 안정적인 websocket만 사용함
14 + });
15 + //명시적 형 선언
16 + let Current_Weather = {};
17 + let Sensible_T = {};
18 + let Heat_index = {};
19 + let Discomport_index = {};
20 + let Ultra_Violet_index = {};
21 + let sending_to_client_info = {};
22 + let client_send = {};
23 + let client_name = "";
24 + let client_birth ;
25 + let Destiny;
26 + let sql;
27 + let city;
28 + let county;
29 + let village;
30 + let info = {};
31 + let query;
32 +
33 + const req_API = (when, what) => {
34 + //async await 사용하기 위하여 promise 사용
35 + return new Promise((resolve, reject) => {
36 + requesting.get({
37 + // api를 요청할 주소 -- 시크릿키,위도,경도 입력
38 + url: encodeURI(`https://api2.sktelecom.com/weather/${when}/${what}?version=1&city=${city}&county=${county}&village=${village}&appKey=${secret_key}`),
39 + json: true
40 + },
41 + //api에게 응답 받았을때 실행되는 callback function
42 + function (err, api_res, api_body) {
43 + //err 존재시 promise reject 호출
44 + if (err) reject(err);
45 +
46 + // api의 response이 있을경우 promise resolve 호출
47 + if (api_res) {
48 + console.log("calling api");
49 + resolve(api_body);
50 + }
51 + });
52 + })
53 +
54 + }
55 +
56 + const API_bundle = async () => {
57 +
58 + try {
59 + Current_Weather = await req_API("current", "minutely"); //현재날씨 (분별)
60 + Sensible_T = await req_API("index", "wct"); //체감온도
61 + Heat_index = await req_API("index", "heat"); //열지수
62 + Discomport_index = await req_API("index", "th"); //불쾌지수
63 + Ultra_Violet_index = await req_API("index", "uv"); //자외선지수
64 +
65 + info = {
66 + heat: Heat_index.weather.wIndex.heatIndex[0].current.index, //열지수
67 + sensible_temperature: Sensible_T.weather.wIndex.wctIndex[0].current.index, //체감온도
68 + discomport: Discomport_index.weather.wIndex.thIndex[0].current.index, //불쾌지수
69 + UV: Ultra_Violet_index.weather.wIndex.uvindex[0].day01.index, //자외선지수
70 + windspd: Current_Weather.weather.minutely[0].wind.wspd, //바람 속도
71 + sky: Current_Weather.weather.minutely[0].sky.code, //하늘 상태
72 + rain: Current_Weather.weather.minutely[0].rain.last24hour, //강수량
73 + current_temperature: Current_Weather.weather.minutely[0].temperature.tc, //현재 온도
74 + lightning: Current_Weather.weather.minutely[0].lightning, //현재 낙뢰
75 + warning: Current_Weather.common.alertYn, //현재 특유무
76 + typhoon: Current_Weather.common.stormYn, //현재 태풍
77 + time: Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각
78 + death_prob: 0 //확률
79 + }
80 + console.log("API INFO \n", info);
81 +
82 + // ------------------------------ death_prob 정의 ------------------------------
83 +
84 + info.death_prob += info.sky.substr(5) * 1 //하늘 상태에 따라 확률 증가
85 +
86 + if (info.lightning === 1) //낙뢰시에 확률 증가
87 + info.death_prob += 1.5;
88 + if (info.typhoon === "Y") //태풍시에 확률 증가
89 + info.death_prob += 1.5;
90 + if (info.warning === "Y") // 특보 발령시 확률 증가
91 + info.death_prob += 1
92 +
93 + //죽을 확률 계산(내맘대로 커스텀)
94 + info.death_prob = (
95 + (info.heat / 50) + (Math.abs(info.sensible_temperature - 15) / 10) + (info.discomport / 10) + (info.UV / 10)
96 + + info.windspd*1 + (info.rain / 10) + (Math.abs(info.current_temperature - 15) / 10)
97 + );
98 +
99 + //이벤트 기반으로 일정 시간 간격으로 클라이언트에게 보낼 정보
100 + client_send = {
101 + time: info.time,
102 + wind: info.windspd,
103 + temperature: info.current_temperature,
104 + rain: info.rain,
105 + death: info.death_prob
106 + };
107 + function getRandom_add_prob(min, max) {
108 + return Math.random() * (max - min) + min;
109 + }
110 +
111 +
112 + // 심장이 크게 뛰며 확률이 증가하거나 감소 할 수 있음
113 + Math.random() * 2 >= 1 ? client_send.death += getRandom_add_prob(0,5) : client_send.death -= getRandom_add_prob(0,5) ;
114 +
115 +
116 + //운명의 장난으로 죽을 확률이 증가하거나 감소함
117 + const rand = Math.floor(Math.random() * 6) //생년월일 중 한자리 뽑음
118 +
119 + Destiny=client_birth.charAt(rand)/3; //명시적 형 변환
120 + if(Destiny==0)Destiny=1; //사용자 잘못 입력했을때 예외처리
121 + Math.random() * 2 >= 1 ? client_send.death += Destiny : client_send.death -= Destiny ;
122 +
123 +
124 + //만약 날이 너무 안좋아서 확률이 100을 넘긴다면 100으로 예외처리
125 + if (client_send.death >= 100) {
126 + client_send.death = 100;
127 + }
128 +
129 + console.log("client send data \n",client_send)
130 +
131 + app.get("socket").emit("weatherInfo_minutely_send_to_client", client_send); // 클라이언트에게 정보 담아서 이벤트 발산
132 + console.log("emit");
133 +
134 + //db에 저장
135 + sql = "INSERT INTO weatherInfo (time,wind,temperature,rain,prob) VALUES (?,?,?,?,?)";
136 + db.query(sql, [client_send.time, client_send.wind, client_send.temperature, client_send.rain, client_send.death], (err, result) => {
137 + if (err) console.log(err);
138 + })
139 + } catch (err) { //promise err or try err catch
140 + console.log("================Error Occured !!================\n", err);
141 + }
142 + }
143 +
144 + let call_interval;
145 +
146 + const Start_Interval = (second, CALL) => {
147 + CALL(); //처음 불러올때 한번 호출하고
148 + call_interval = setInterval(CALL, second * 1000); //그 후에 1분마다 호출
149 + }
150 +
151 + io.on('connection', (socket) => { //프론트와 소켓 연결시 이벤트 루프 동작
152 +
153 + app.set("socket", socket);
154 + socket.on("connection", (client_data) => {
155 + console.log("SOCKET CONNECTED");
156 + client_name = client_data.name;
157 + client_birth = client_data.birth;
158 + city = client_data.city;
159 + county = client_data.county;
160 + village = client_data.village;
161 + query = city+' '+county+' '+village;
162 +var headers = {
163 + 'Authorization': 'KakaoAK '+ key
164 +};
165 +
166 +var options = {
167 + url: encodeURI('https://dapi.kakao.com/v2/local/search/address.json?query=' + query),
168 + headers: headers
169 +};
170 +
171 +function callback(error, response, body) {
172 + if (!error && response.statusCode == 200) {
173 + console.log(body);
174 + console.log(body.documents[1].y);
175 + }
176 +// console.log(response);
177 +}
178 +
179 +requesting.get(options, callback);
180 +
181 +
182 +
183 + Start_Interval(60, API_bundle); //소켓 연결후 interval 활성화하여 1분마다 API 호출
184 +
185 + });
186 +
187 + socket.on('disconnect', (reason) => {
188 + console.log("disconnected");
189 + clearInterval(call_interval); //연결 종료시 interval 해제
190 + })
191 + })
192 +
193 +}
...@@ -20,9 +20,8 @@ app.use(express.urlencoded({ extended: false })); ...@@ -20,9 +20,8 @@ app.use(express.urlencoded({ extended: false }));
20 app.use(cookieParser()); 20 app.use(cookieParser());
21 app.use('/',express.static(path.join(__dirname, 'public'))); 21 app.use('/',express.static(path.join(__dirname, 'public')));
22 app.use('/',express.static(path.join(__dirname, 'code'))); 22 app.use('/',express.static(path.join(__dirname, 'code')));
23 -app.use('/name/:name/birth',express.static(path.join(__dirname, 'public'))); 23 +app.use('/name/:name/birth/:birth/city/:city/county/:county/village/:village',express.static(path.join(__dirname, 'public')));
24 -app.use('/name/:name/birth',express.static(path.join(__dirname, 'code'))); 24 +app.use('/name/:name/birth/:birth/city/:city/county/:county/village/:village',express.static(path.join(__dirname, 'code')));
25 -
26 app.use('/', indexRouter); 25 app.use('/', indexRouter);
27 app.use('/users', usersRouter); 26 app.use('/users', usersRouter);
28 27
......
No preview for this file type
1 const db = require('./db.js'); 1 const db = require('./db.js');
2 const secret_key = require('./keys/api_option').key; 2 const secret_key = require('./keys/api_option').key;
3 const requesting = require('request'); 3 const requesting = require('request');
4 -const lat = "37.239795"; 4 +const key = require('./keys/api_map').key;
5 -const lon = "127.083240"; 5 +
6 +//const city = client_data.city;
7 +//const county = client_data.county;
8 +//const village = client_data.village;
6 module.exports = (server, app) => { 9 module.exports = (server, app) => {
7 10
8 const io = require('socket.io')(server, { 11 const io = require('socket.io')(server, {
...@@ -20,15 +23,20 @@ module.exports = (server, app) => { ...@@ -20,15 +23,20 @@ module.exports = (server, app) => {
20 let client_birth ; 23 let client_birth ;
21 let Destiny; 24 let Destiny;
22 let sql; 25 let sql;
23 - 26 + let city;
24 - let info = {} 27 + let county;
28 + let village;
29 + let info = {};
30 + let query;
31 + let lat;
32 + let lon;
25 33
26 const req_API = (when, what) => { 34 const req_API = (when, what) => {
27 //async await 사용하기 위하여 promise 사용 35 //async await 사용하기 위하여 promise 사용
28 return new Promise((resolve, reject) => { 36 return new Promise((resolve, reject) => {
29 requesting.get({ 37 requesting.get({
30 // api를 요청할 주소 -- 시크릿키,위도,경도 입력 38 // api를 요청할 주소 -- 시크릿키,위도,경도 입력
31 - url: `https://api2.sktelecom.com/weather/${when}/${what}?lat=${lat}&lon=${lon}&appKey=${secret_key}`, 39 + url: encodeURI(`https://api2.sktelecom.com/weather/${when}/${what}?version=1&lat=${lat}&lon=${lon}&appKey=${secret_key}`),
32 json: true 40 json: true
33 }, 41 },
34 //api에게 응답 받았을때 실행되는 callback function 42 //api에게 응답 받았을때 실행되는 callback function
...@@ -45,10 +53,12 @@ module.exports = (server, app) => { ...@@ -45,10 +53,12 @@ module.exports = (server, app) => {
45 }) 53 })
46 54
47 } 55 }
56 +
48 const API_bundle = async () => { 57 const API_bundle = async () => {
49 58
50 try { 59 try {
51 Current_Weather = await req_API("current", "minutely"); //현재날씨 (분별) 60 Current_Weather = await req_API("current", "minutely"); //현재날씨 (분별)
61 +console.log(Current_Weather);
52 Sensible_T = await req_API("index", "wct"); //체감온도 62 Sensible_T = await req_API("index", "wct"); //체감온도
53 Heat_index = await req_API("index", "heat"); //열지수 63 Heat_index = await req_API("index", "heat"); //열지수
54 Discomport_index = await req_API("index", "th"); //불쾌지수 64 Discomport_index = await req_API("index", "th"); //불쾌지수
...@@ -64,7 +74,7 @@ module.exports = (server, app) => { ...@@ -64,7 +74,7 @@ module.exports = (server, app) => {
64 rain: Current_Weather.weather.minutely[0].rain.last24hour, //강수량 74 rain: Current_Weather.weather.minutely[0].rain.last24hour, //강수량
65 current_temperature: Current_Weather.weather.minutely[0].temperature.tc, //현재 온도 75 current_temperature: Current_Weather.weather.minutely[0].temperature.tc, //현재 온도
66 lightning: Current_Weather.weather.minutely[0].lightning, //현재 낙뢰 76 lightning: Current_Weather.weather.minutely[0].lightning, //현재 낙뢰
67 - warning: Current_Weather.common.alertYn, //현재 특유무 77 + warning: Current_Weather.common.alertYn, //현재 특유무
68 typhoon: Current_Weather.common.stormYn, //현재 태풍 78 typhoon: Current_Weather.common.stormYn, //현재 태풍
69 time: Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각 79 time: Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각
70 death_prob: 0 //확률 80 death_prob: 0 //확률
...@@ -146,7 +156,34 @@ module.exports = (server, app) => { ...@@ -146,7 +156,34 @@ module.exports = (server, app) => {
146 socket.on("connection", (client_data) => { 156 socket.on("connection", (client_data) => {
147 console.log("SOCKET CONNECTED"); 157 console.log("SOCKET CONNECTED");
148 client_name = client_data.name; 158 client_name = client_data.name;
149 - client_birth = client_data.birth; 159 + client_birth = client_data.birth;
160 + city = client_data.city;
161 + county = client_data.county;
162 + village = client_data.village;
163 + query = city+' '+county+' '+village;
164 +var headers = {
165 + 'Authorization': 'KakaoAK '+ key
166 +};
167 +
168 +var options = {
169 + url: encodeURI('https://dapi.kakao.com/v2/local/search/address.json?query=' + query),
170 + headers: headers,
171 + json : true
172 +};
173 +
174 +function callback(error, response, body) {
175 + if (!error && response.statusCode == 200) {
176 + console.log(body);
177 + lat = body.documents[0].x;
178 + lat = lat.substring(0, 6);
179 +console.log(lat);
180 + lon = body.documents[0].y;
181 + lon = lon.substring(0, 6);
182 + }
183 +
184 +}
185 +
186 + requesting.get(options, callback);
150 Start_Interval(60, API_bundle); //소켓 연결후 interval 활성화하여 1분마다 API 호출 187 Start_Interval(60, API_bundle); //소켓 연결후 interval 활성화하여 1분마다 API 호출
151 188
152 }); 189 });
......
This diff is collapsed. Click to expand it.
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
9 "body-parser": "^1.18.3", 9 "body-parser": "^1.18.3",
10 "compression": "^1.7.3", 10 "compression": "^1.7.3",
11 "cookie-parser": "~1.4.3", 11 "cookie-parser": "~1.4.3",
12 + "curl-request": "^1.1.1",
12 "date-utils": "^1.2.21", 13 "date-utils": "^1.2.21",
13 "debug": "~2.6.9", 14 "debug": "~2.6.9",
14 "ejs": "~2.5.7", 15 "ejs": "~2.5.7",
......
...@@ -5,9 +5,9 @@ var db = require('../lib/db'); ...@@ -5,9 +5,9 @@ var db = require('../lib/db');
5 /* GET home page. */ 5 /* GET home page. */
6 6
7 router.post('/starting' , (req,res) => { 7 router.post('/starting' , (req,res) => {
8 - res.redirect(`/name/${req.body.name}/birth/${req.body.birth}`); 8 + res.redirect(`/name/${req.body.name}/birth/${req.body.birth}/city/${req.body.city}/county/${req.body.county}/village/${req.body.village}`);
9 }) 9 })
10 -router.get('/name/:name/birth/:birth', (req,res) => { 10 +router.get('/name/:name/birth/:birth/city/:city/county/:county/village/:village', (req,res) => {
11 11
12 // 렌더링 변수 12 // 렌더링 변수
13 var time = new Array(); // 타임스탬프 13 var time = new Array(); // 타임스탬프
...@@ -21,6 +21,9 @@ router.get('/name/:name/birth/:birth', (req,res) => { ...@@ -21,6 +21,9 @@ router.get('/name/:name/birth/:birth', (req,res) => {
21 var count = 0; 21 var count = 0;
22 const name = req.params.name; 22 const name = req.params.name;
23 const birth = req.params.birth; 23 const birth = req.params.birth;
24 + const city = req.params.city;
25 + const county = req.params.county;
26 + const village = req.params.village;
24 27
25 // 이전 10분간 데이터 찾기 28 // 이전 10분간 데이터 찾기
26 sql = "SELECT * FROM weatherInfo WHERE time >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -20 MINUTE), '%Y-%m-%d %H:%i:%s')"; 29 sql = "SELECT * FROM weatherInfo WHERE time >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -20 MINUTE), '%Y-%m-%d %H:%i:%s')";
...@@ -62,7 +65,10 @@ router.get('/name/:name/birth/:birth', (req,res) => { ...@@ -62,7 +65,10 @@ router.get('/name/:name/birth/:birth', (req,res) => {
62 probArr, 65 probArr,
63 dataLen, 66 dataLen,
64 name, 67 name,
65 - birth 68 + birth,
69 + city,
70 + county,
71 + village
66 }); 72 });
67 } 73 }
68 }); 74 });
......
...@@ -61,7 +61,10 @@ ...@@ -61,7 +61,10 @@
61 <script type="text/javascript"> 61 <script type="text/javascript">
62 let client_data = { 62 let client_data = {
63 birth: "<%=birth%>", 63 birth: "<%=birth%>",
64 - name: "<%=name%>" 64 + name: "<%=name%>",
65 + city: "<%=city%>",
66 + county: "<%=county%>",
67 + village: "<%=village%>"
65 } 68 }
66 69
67 70
...@@ -630,4 +633,4 @@ plotOptions: { ...@@ -630,4 +633,4 @@ plotOptions: {
630 633
631 </body> 634 </body>
632 635
633 -</html>
...\ No newline at end of file ...\ No newline at end of file
636 +</html>
......
...@@ -85,7 +85,14 @@ ...@@ -85,7 +85,14 @@
85 &nbsp &nbsp&nbsp&nbsp 85 &nbsp &nbsp&nbsp&nbsp
86 <label>생년월일</label> 86 <label>생년월일</label>
87 <input type="text" name="birth" class="form-control" placeholder="971009" style="width:200px;"> 87 <input type="text" name="birth" class="form-control" placeholder="971009" style="width:200px;">
88 - <br><br><br> 88 +
89 +<label>현재 장소(시)</label>
90 + <input type="text" name="city" class="form-control" placeholder="서울" style="width:200px;">
91 + <label>현재 장소(구)(</label>
92 + <input type="text" name="county" class="form-control" placeholder="강남구" style="width:200px;">
93 + <label>현재 장소(동)</label>
94 + <input type="text" name="village" class="form-control" placeholder="삼성동" style="width:200px;">
95 +<br><br><br>
89 <input type="submit" value="시작하기" class="btn btn-default" style="font-family: 'Yeon Sung', cursive; width:100px;font-weight: bold; font-size: 18px; background-color: white;"> 96 <input type="submit" value="시작하기" class="btn btn-default" style="font-family: 'Yeon Sung', cursive; width:100px;font-weight: bold; font-size: 18px; background-color: white;">
90 </div> 97 </div>
91 </form> 98 </form>
...@@ -93,7 +100,7 @@ ...@@ -93,7 +100,7 @@
93 100
94 </div> 101 </div>
95 102
96 - <div id="footer">오픈소스SW개발 조민지 강환석 배희수</div> 103 + <div id="footer">오픈소스SW개발 조민지 강환석 배희수/ 개선_김가영 /</div>
97 </body> 104 </body>
98 105
99 -</html>
...\ No newline at end of file ...\ No newline at end of file
106 +</html>
......
...@@ -61,7 +61,10 @@ ...@@ -61,7 +61,10 @@
61 <script> 61 <script>
62 let client_data = { 62 let client_data = {
63 birth: "<%=birth%>", 63 birth: "<%=birth%>",
64 - name: "<%=name%>" 64 + name: "<%=name%>",
65 + city: "<%=city%>",
66 + county: "<%=county%>",
67 + village: "<%=village%>"
65 } 68 }
66 var socket = io.connect('/', { transports: ['websocket'], upgrade: false }); 69 var socket = io.connect('/', { transports: ['websocket'], upgrade: false });
67 socket.emit("connection", client_data); 70 socket.emit("connection", client_data);
...@@ -638,4 +641,4 @@ ...@@ -638,4 +641,4 @@
638 641
639 </body> 642 </body>
640 643
641 -</html>
...\ No newline at end of file ...\ No newline at end of file
644 +</html>
......