dataController.js 6.73 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
    const weather_out = result_weather.slice(-9);
139
140
    const weather_predict = result_weather.slice(-3);

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    const pyprocess = spawn("python", [
      envs.inner_dir.data_processing_prediction,
      user_info.email,
    ]);

    pyprocess.stdout.on("data", (data) => {
      const str_result = data.toString();
      console.log(data.toString()); // Buffer to String.

      const temp_predict = str_result.split(" ");

      res.json({
        msg: resForm.msg.ok,
        contents: { weather_in: weather_out, weather_predict: temp_predict },
      });
    });

    pyprocess.stderr.on("data", (error) => {
      console.log("Error in the data predicting.");
      console.log(error.toString());
      res.json({
        msg: resForm.msg.err,
        contents: {
          weather_in: weather_out,
          weather_predict: weather_predict,
          error: error.toString(),
        },
      });
    });

    pyprocess.on("close", () => {
      console.log("The data prediction is done.");
173
    });
174
175
  } catch (err) {
    console.log(err);
176
177
178
179
    res.json({
      msg: resForm.msg.err,
      contents: { weather_in: [], error: err },
    });
180
  }
181
182
};

183
// 실외 날씨 데이터 요청 처리
184
export const getOutWeatherData = async (req, res) => {
185
  const {
186
    query: { loccode },
187
188
189
  } = req;
  try {
    // 실외 지역 번호를 통해 날씨 데이터 전송.
190
    const result = await db.Weather_Out.findAll({
191
      where: { loc_code: loccode },
192
      order: [["collected_at", "ASC"]],
193
194
195
      logging: false,
    });

196
197
198
    const weather_out = result.slice(-9);

    res.json({ msg: resForm.msg.ok, contents: { weather_out: weather_out } });
199
200
201
202
  } catch (err) {
    console.log(err);
    res.json({ msg: resForm.msg.err, contents: { error: err } });
  }
203
204
};

205
// 지역 코드 요청 처리
206
export const getLocCode = async (req, res) => {
207
208
  try {
    /* 통합 지역 코드 및 이름 json으로 생성 및 전송 */
209
210
211
212
213
214
215
216
217
218
219
220
    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,
    });
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261

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