dataController.js 7.45 KB
Newer Older
1
import db from "../db/index";
2
import envs from "../../config/config";
KangMin An's avatar
KangMin An committed
3
4
import fetch from "node-fetch";
import jwt from "jsonwebtoken";
5
import resForm from "../resForm";
6
import { spawn } from "child_process";
7

8
// 외부 수집기로 부터 들어온 정보 처리
9
export const handleOutData = async (locCode, date, lat, lng) => {
10
11
12
13
14
15
  try {
    // OpenWeatherAPI로 부터 지역의 날씨 정보획득을 위해 지역의 경도와 위도, API Key, 단위 기준 metric 전달
    const response = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${envs.api.openweathermap.api_key}&units=metric`
    );
    const json = await response.json();
16

17
18
19
20
    const temp = json["main"]["temp"];
    const humi = json["main"]["humidity"];
    const press = json["main"]["pressure"];
    const wind_speed = json["wind"]["speed"];
21

22
23
24
25
26
27
28
29
30
31
32
33
34
    await db.Weather_Out.create(
      {
        loc_code: Number(locCode),
        collected_at: date,
        temp: temp,
        humi: humi,
        press: press,
        wind_speed: wind_speed,
      },
      {
        logging: false,
      }
    );
35
36

    console.log("Outside data successfully stored.");
37
38
39
40
  } catch (err) {
    console.log("Input Weather_Out Data Error.");
    console.log(err);
  }
41
42
43
};

// 내부 수집기로 부터 들어온 정보 처리
KangMin An's avatar
KangMin An committed
44
const handleInData = async (email, date, temp, humi, lights) => {
45
46
47
48
49
50
51
52
53
54
55
56
57
  try {
    await db.Weather_In.create(
      {
        host: email,
        collected_at: date,
        temp: temp,
        humi: humi,
        lights: lights,
      },
      {
        logging: false,
      }
    );
58
59

    console.log("Inside data successfully stored.");
60
61
62
63
  } catch (err) {
    console.log("Input Weather_In Data Error.");
    console.log(err);
  }
64
65
66
};

// 데이터 수신 처리
67
export const getDataInput = (req, res) => {
68
  try {
69
    if (req.query.type === "OUT") {
70
71
      // 외부 데이터 수집기
      const {
72
        query: { locCode, date, lat, lng },
73
      } = req;
74

KangMin An's avatar
KangMin An committed
75
76
77
78
79
80
      const trans_date = new Date(date);

      console.log(
        `Outside[${locCode}] Data(date: ${trans_date}/ lat: ${lat}/ lng: ${lng}) Input.`
      );
      handleOutData(locCode, trans_date, lat, lng);
81
82
83
    } else {
      // 내부 데이터 수집기 동작
      const {
KangMin An's avatar
KangMin An committed
84
        query: { email, date, temp, humi, lights },
85
86
      } = req;

KangMin An's avatar
KangMin An committed
87
88
89
90
91
92
      const trans_date = new Date(date);

      console.log(
        `User[${email}] Data(date: ${trans_date}/ temp: ${temp}/ humi: ${humi}/ lights: ${lights}) Input.`
      );
      handleInData(email, trans_date, temp, humi, lights);
93
    }
94
    res.status(resForm.code.ok).json({ msg: resForm.msg.ok });
95
96
  } catch (err) {
    console.log(err);
97
    res.status(resForm.code.err).json({ msg: resForm.msg.err });
98
  }
KangMin An's avatar
KangMin An committed
99
};
100
101

// 사용자의 데이터 가져오기 및 예측 값 전송
102
export const getUserWeatherData = async (req, res) => {
103
  const {
KangMin An's avatar
KangMin An committed
104
    cookies: { acs_token },
105
106
  } = req;

107
  try {
108
109
110
111
112
113
114
    /*
        # 사용자 email에 따른 사용자 날씨 데이터 가져오기 

        - 2021.08.07 기준, 데이터 수집기의 동작 오류로 인해 외부날씨 반환으로 대체.
        - 예측 날씨 반환 준비되는대로 업데이트
        
    */
115
    const decoded = jwt.decode(acs_token);
116
117
118
119
120
121

    // const result = db.Weather_In.findAll({
    //   where: { host: decoded.email },
    //   logging: false,
    // });

122
    const result_user = await db.User.findAll({
123
124
125
      where: {
        email: decoded.email,
      },
126
127
      logging: false,
    });
128
    const user_info = result_user[0];
129

130
    const result_weather = await db.Weather_Out.findAll({
131
132
133
      where: {
        loc_code: user_info.loc_code,
      },
134
      order: [["collected_at", "ASC"]],
135
136
137
      logging: false,
    });

138
139
140
141
142
143
    let temp_weather = result_weather.slice(-6);
    let weather = [];

    temp_weather.map((data) => {
      weather.push({
        loc_code: data["loc_code"],
KangMin An's avatar
KangMin An committed
144
        collected_at: new Date(new Date(data["collected_at"]).getTime()),
145
146
147
148
149
150
        temp: data["temp"],
        humi: data["humi"],
        press: data["press"],
        wind_speed: data["wind_speed"],
      });
    });
151

152
153
154
155
156
157
    const pyprocess = spawn("python", [
      envs.inner_dir.data_processing_prediction,
      user_info.email,
    ]);

    pyprocess.stdout.on("data", (data) => {
158
      let weather_predict = [];
159

160
      let temp_predict = data.toString();
161
162
      temp_predict = temp_predict.replace("]]", "");
      temp_predict = temp_predict.replace("[[", "");
163
      temp_predict = temp_predict.trim();
164
      temp_predict = temp_predict.split(" ");
165

166
167
      temp_predict = temp_predict.filter((val) => val.length > 0);

168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
      let date_10m = new Date(weather[weather.length - 1]["collected_at"]);
      date_10m.setMinutes(date_10m.getMinutes() + 10);

      let date_20m = new Date(weather[weather.length - 1]["collected_at"]);
      date_20m.setMinutes(date_20m.getMinutes() + 20);

      let date_30m = new Date(weather[weather.length - 1]["collected_at"]);
      date_30m.setMinutes(date_30m.getMinutes() + 30);

      let dates = [date_10m, date_20m, date_30m];

      temp_predict.map((temp, index) => {
        weather_predict.push({
          collected_at: dates[index],
          temp: Number(temp),
        });
184
185
186
      });

      res.json({
187
188
        msg: resForm.msg.ok,
        contents: { weather_in: weather, weather_predict: weather_predict },
189
      });
190
      return;
191
192
193
194
    });

    pyprocess.on("close", () => {
      console.log("The data prediction is done.");
195
    });
196
197
  } catch (err) {
    console.log(err);
198
199
200
201
    res.json({
      msg: resForm.msg.err,
      contents: { weather_in: [], error: err },
    });
202
  }
203
204
};

205
// 실외 날씨 데이터 요청 처리
206
export const getOutWeatherData = async (req, res) => {
207
  const {
208
    query: { loccode },
209
210
211
  } = req;
  try {
    // 실외 지역 번호를 통해 날씨 데이터 전송.
212
    const result = await db.Weather_Out.findAll({
213
      where: { loc_code: loccode },
214
      order: [["collected_at", "ASC"]],
215
216
217
      logging: false,
    });

218
219
220
    const weather_out = result.slice(-9);

    res.json({ msg: resForm.msg.ok, contents: { weather_out: weather_out } });
221
222
223
224
  } catch (err) {
    console.log(err);
    res.json({ msg: resForm.msg.err, contents: { error: err } });
  }
225
226
};

227
// 지역 코드 요청 처리
228
export const getLocCode = async (req, res) => {
229
230
  try {
    /* 통합 지역 코드 및 이름 json으로 생성 및 전송 */
231
232
233
234
235
236
237
238
239
240
241
242
    const does = await db.Doe.findAll({
      order: [["name_doe", "ASC"]],
      logging: false,
    });
    const sggs = await db.Sgg.findAll({
      order: [["name_sgg", "ASC"]],
      logging: false,
    });
    const emds = await db.Emd.findAll({
      order: [["name_emd", "ASC"]],
      logging: false,
    });
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283

    let doe_sgg = [];
    let sgg_emd = [];

    does.map((info_doe) => {
      let temp = {
        name_doe: info_doe["name_doe"],
        code_doe: info_doe["code_doe"],
      };
      temp.sgg = sggs.filter(
        (info_sgg) => info_sgg["code_doe"] === info_doe["code_doe"]
      );
      doe_sgg.push(temp);
    });

    sggs.map((info_sgg) => {
      let temp = {
        code_doe: info_sgg["code_doe"],
        name_sgg: info_sgg["name_sgg"],
        code_sgg: info_sgg["code_sgg"],
      };
      temp.emd = emds.filter(
        (info_emd) => info_emd["code_sgg"] === info_sgg["code_sgg"]
      );
      sgg_emd.push(temp);
    });

    res.json({
      msg: resForm.msg.ok,
      contents: {
        loc_code: {
          DOE: does,
          SGG: doe_sgg,
          EMD: sgg_emd,
        },
      },
    });
  } catch (err) {
    console.log(err);
    res.json({ msg: resForm.msg.err, contents: { error: err } });
  }
284
};