weather-streamoverlay/controller/weather_api.js

61 lines
1.8 KiB
JavaScript

import fs from 'fs';
import fetch from 'node-fetch';
import { Config } from '../config/config.js';
import { Storage } from "./storage.js";
class WeatherData {
timestamp = 0;
humidity = 0;
temp = 0;
weather = [];
wind_speed = 0;
wind_deg = 0;
}
export class Weather {
constructor() {
//let x = new WeatherData();
//this.writeFile(x);
Storage.weather = this;
this.data = this.readFile();
this.readApi();
this.inter = setInterval(this.readApi, 1000 * 60);
}
async readApi() {
let me = Storage.weather;
//console.log(`DIFF FROM TO ${(Math.floor((+ new Date) / 1000))} ${me.data.timestamp}`);
if (((Math.floor((+ new Date) / 1000)) - me.data.timestamp) > Config.WEATHER_API.READING) {
console.log("GET NEW DATA")
let d = Math.floor((+ new Date) / 1000)
me.data.timestamp = d;
let url = `http://api.openweathermap.org/data/2.5/weather?q=${Config.WEATHER_API.CITY}&units=metric&appid=${Config.WEATHER_API.API_KEY}`;
const response = await fetch(url, {
method: 'get',
headers: { 'Content-Type': 'application/json' }
});
const data = await response.json();
data.timestamp = data.dt;
me.data = data;
me.writeFile(me.data);
}
}
readFile() {
let jso = {};
try {
let data = fs.readFileSync(`${Storage.dir}/data/weather.json`);
jso = JSON.parse(data);
} catch (e) {
jso = {timestamp:0};
}
console.log(jso);
return jso;
}
writeFile(data) {
fs.writeFileSync(`${Storage.dir}/data/weather.json`, JSON.stringify(data));
}
}