dataController.js 7.39 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
      const str_result = data.toString();

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

166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
      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),
        });
182
183
184
      });

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

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

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

216
217
218
    const weather_out = result.slice(-9);

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

225
// 지역 코드 요청 처리
226
export const getLocCode = async (req, res) => {
227
228
  try {
    /* 통합 지역 코드 및 이름 json으로 생성 및 전송 */
229
230
231
232
233
234
235
236
237
238
239
240
    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,
    });
241
242
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

    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 } });
  }
282
};