dataController.js 5 KB
Newer Older
1
import fs from "fs";
2
import fetch from "node-fetch";
3
4
import { serverMSG, statusCode } from "../serverinfo";
import { pool as db, dbMSG, pool } from "../db";
5
6
7
import dotenv from "dotenv";

dotenv.config();
8

9
10
11
const OUT = "Out";
const IN = "In";

12
13
14
const OUTSIDE = "Outside";
const USERS = "Users";

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 데이터 수집 기로 부터 받아온 지역 코드 세분화
const locCodeSep = (code = "") => {
  const DO = code.slice(0, 2);
  const SGG = code.slice(0, 5);
  const EMD = code;

  const loc = {
    DO: DO,
    SGG: SGG,
    EMD: EMD,
  };

  return loc;
};

// 데이터가 들어온 시간 데이터 생성
const getTimeInfo = () => {
  const cur = new Date();

  const year = cur.getFullYear();
  const month = cur.getMonth() + 1;
  const date = cur.getDate();
  const hour = cur.getHours();
  const minute = cur.getMinutes();

  const time = {
    year: year,
    month: month,
    date: date,
    hour: hour,
    minute: minute,
  };

  return time;
};

51
52
// Data 접근 경로 반환, DB에 존재 하지 않을 시 Update 동작
const getDataDIR = async (loc, time, type, id) => {
53
54
55
56
  const year = time.year;
  const month = time.month < 10 ? `0${time.month}` : time.month;
  const date = time.date < 10 ? `0${time.date}` : time.date;

57
58
59
60
61
62
  const select_query =
    "SELECT DATALINK" +
    " " +
    `FROM ${type === OUT ? "LOCINFO" : "USER"}` +
    " " +
    `WHERE ${type === OUT ? `CODE=${loc.EMD}` : `ID='${id}'`}`;
63

64
65
  const [row, fields] = await db.execute(select_query);

66
67
68
  let baseDIR;
  if (row.length != 0) baseDIR = row[0]["DATALINK"];
  else baseDIR = null;
69
70
71
72

  // DB에 Data 저장 경로가 존재하지 않을 시 UPDATE
  if (baseDIR === null) {
    baseDIR =
73
      "/data" +
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
      `/${loc.DO}` +
      `/${loc.SGG}` +
      `/${loc.EMD}` +
      `/${type === OUT ? OUTSIDE : USERS + "/" + id}`;

    const update_query =
      `UPDATE ${type === OUT ? "LOCINFO" : "USER"}` +
      " " +
      `SET DATALINK='${baseDIR}'` +
      " " +
      `WHERE ${type === OUT ? `CODE=${loc.EMD}` : `ID='${id}'`}`;

    db.execute(update_query);
  }

  const timeDIR = `/${year}` + `/${year}${month}` + `/${year}${month}${date}`;

  // 최종 Data 저장소 경로
92
  const repoDIR = process.env.LOCAL_SERVER_DIR + baseDIR + timeDIR;
93

94
95
96
  return repoDIR;
};

97
98
// 데이터를 파일 형식으로 저장
const storeData = (type, time, loc, fdir, data) => {
99
  const fileName = "weather.csv";
100
101
102
103
104
105
106
107
108
109
110
111

  fs.open(fdir + `/${fileName}`, "a", (err, fd) => {
    if (err) {
      // Directory가 존재하지 않는 경우, 생성
      if (err.code === "ENOENT") {
        console.log("There is no directory.");

        fs.mkdirSync(fdir, { recursive: true }, (err) => {
          if (err) console.log(err);
        });

        console.log("Create directory.");
112
113
114
      }
      // 그 외의 에러는 출력
      else console.log(err);
115
116
117
118
119
120
121
122
    }

    fs.appendFile(fdir + `/${fileName}`, data, (err) => {
      if (err) console.log(err);
      else
        console.log(
          `${time.year}/${time.month}/${time.date} ${time.hour}:${
            time.minute
123
          } - ${loc.EMD} ${type === OUT ? OUTSIDE : USERS} data append.`
124
125
126
127
128
129
        );
    });
  });
};

// 외부 수집기로 부터 들어온 정보 처리
130
const handleOutData = async (locCode, lat, lng) => {
131
  // OpenWeatherAPI로 부터 지역의 날씨 정보획득
132
  // 지역의 경도와 위도, API KEy, 단위 기준 metric 전달
133
  const response = await fetch(
134
    `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${process.env.OPENWEATHERMAP_API_KEY}&units=metric`
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
  );
  const json = await response.json();

  const temp = json["main"]["temp"];
  const humi = json["main"]["humidity"];
  const press = json["main"]["pressure"];
  const wind_speed = json["wind"]["speed"];

  const loc = locCodeSep(locCode);
  const time = getTimeInfo();

  const fdir = await getDataDIR(loc, time, OUT, OUTSIDE);

  const data = `${time.month},${time.date},${time.hour},${time.minute},${temp},${humi},${press},${wind_speed}\n`;

  storeData(OUT, time, loc, fdir, data);
151
152
153
};

// 내부 수집기로 부터 들어온 정보 처리
154
const handleInData = async (id, locCode, temp, humi, lights) => {
155
156
157
  const loc = locCodeSep(locCode);
  const time = getTimeInfo();

158
  const fdir = await getDataDIR(loc, time, IN, id);
159
160
  // 데이터 형식 - [ 월 | 일 | 시 | 분 | 온도 | 습도 | 광도 ]
  const data = `${time.month},${time.date},${time.hour},${time.minute},${temp},${humi},${lights}\n`;
161
162
163
164
165

  storeData(IN, time, loc, fdir, data);
};

// 데이터 수신 처리
166
export const getDataInput = (req, res) => {
167
168
169
170
171
172
  try {
    if (req.query.type === OUT) {
      // 외부 데이터 수집기
      const {
        query: { locCode, lat, lng },
      } = req;
173

174
175
176
177
178
179
180
181
182
183
      handleOutData(locCode, lat, lng);
    } else {
      // 내부 데이터 수집기 동작
      const {
        query: { id, locCode, temp, humi, lights },
      } = req;

      handleInData(id, locCode, temp, humi, lights);
    }

184
    res.status(statusCode.ok).send(serverMSG.server_ok);
185
186
  } catch (error) {
    console.log(error);
187
    res.status(statusCode.err).send(serverMSG.server_err);
188
  }
KangMin An's avatar
KangMin An committed
189
};