64 lines
2.4 KiB
JavaScript
Raw Normal View History

2020-09-28 11:12:35 +01:00
const http = require('http')
const globalVars = require('../libs/globalVars')
const led = require('../libs/led')
const common = require('../libs/common')
const lcd = require('../libs/lcd')
2020-10-10 13:56:55 +01:00
const logger = require('perfect-logger');
2020-09-28 11:12:35 +01:00
const city = "Basingstoke"
const appid = "ba24c6018ddd72041749018d0c1b1ef8"
module.exports = {
getStatus: () => {
var rest_options = {
host: 'api.openweathermap.org',
port: 80,
path: '/data/2.5/weather?q=' + city + '&appid=' + appid + '&units=metric',
method: 'GET'
};
2020-10-10 13:56:55 +01:00
logger.info('weather request')
2020-09-28 11:12:35 +01:00
var request = http.request(rest_options, function (response) {
var content = "";
// Handle data chunks
response.on('data', function (chunk) {
content += chunk;
});
// Once we're done streaming the response, parse it as json.
response.on('end', async function () {
var data = JSON.parse(content);
2020-09-29 10:23:41 +01:00
let weatherData = {
"city": data.name,
"weatherDescription": data.weather[0].description,
"currentTemp": Math.floor(data.main.temp),
"highTemp": Math.floor(data.main.temp_max),
"lowTemp": Math.floor(data.main.temp_min)
}
async function updateWeather() {
2020-10-10 13:56:55 +01:00
logger.info('weather updated')
2020-09-29 10:23:41 +01:00
globalVars.lastWeatherRequest = weatherData
await lcd.weather(weatherData.city, weatherData.weatherDescription, weatherData.currentTemp, weatherData.highTemp, weatherData.lowTemp)
}
if (globalVars.lastWeatherRequest === "") {
2020-10-10 13:56:55 +01:00
logger.info('initial load')
2020-09-29 10:23:41 +01:00
globalVars.lastWeatherRequest = weatherData
updateWeather()
2020-10-10 13:56:55 +01:00
} else if (JSON.stringify(globalVars.lastWeatherRequest) == JSON.stringify(weatherData)) {
logger.info('no update')
2020-09-29 10:23:41 +01:00
} else {
updateWeather()
}
2020-09-28 11:12:35 +01:00
});
})
// Report errors
request.on('error', function (error) {
led.set('green')
lcd.heatingStatus('Error No Data')
globalVars.heatingOn = 'error'
});
request.end();
}
}