Skip to content

Commit

Permalink
Various small improvements (#49)
Browse files Browse the repository at this point in the history
Added option to set serial number
Changed history timer to make use of advantages in newer fakegato version
Fixed precipitation calculation in dark sky api
Code cleaned up
  • Loading branch information
simont77 authored and naofireblade committed Jan 27, 2019
1 parent 722dfda commit 31ef67e
Show file tree
Hide file tree
Showing 8 changed files with 161 additions and 166 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,9 @@
* Added option to rename forecastAccessory
* Added plugin version to Accessory Info
* Updated debug dependency

## 2.6.0

* Added option to set serial number
* Changed history timer to make use of advantages in newer fakegato version
* Fixed precipitation calculation in dark sky api
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ The **currentObservations** parameter is *optional* and sets how the 3 current o

The **fakegatoParameters** parameter is *optional*. By default, history is persisted on filesystem. You can pass your own parameters to *fakegato-history* module using this paramter, in order to change the location of the persisted file or use GoogleDrive persistance. See https://github.com/simont77/fakegato-history#file-system and https://github.com/simont77/fakegato-history#google-drive for more info. **IMPORTANT NOTE:** Do not modify the parameter for the fakegato internal timer.

The **serial** parameter is *optional* and sets the Serial Number of the accessory. If it's not provided the serial number will be set to the **location** if present, or to 999 if not. Note that for proper operation of fakegato when multiple fakegato-enabled weather accessories are present in your system, the serial number must be unique.


### Dark Sky

Expand Down
90 changes: 45 additions & 45 deletions api/darksky.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,24 +85,24 @@ var init = function (apiKey, language, locationGeo, l, d) {
});
};

var update = function (callback) {
var update = function (callback, requestedForecastDays) {
let weather = {};
weather.forecasts = [];
let that = this;

updateCache(this.darkskyTimeMachine, function () {
updateCache(this.darkskyTimeMachine, requestedForecastDays, function () {
debug("Updating weather with dark sky");
that.darksky.get()
.then(function (response) {

// Current weather report
response['currently']['rainDay'] = cache.report.rainDay; // Load rainDay from cache
weather.report = parseReport(response['currently'], response['timezone']);
response.currently.rainDay = cache.report.rainDay; // Load rainDay from cache
weather.report = parseReport(response.currently, response.timezone);

// Forecasts for today and next 6 days
for (let i = 0; i <= 6; i++) {
response['daily']['data'][i]['rainDay'] = cache.forecast['day' + i].rainDay; // Load rainDay from cache
weather.forecasts.push(parseForecast(response['daily']['data'][i], response['timezone']));
response.daily.data[i].rainDay = cache.forecast['day' + i].rainDay; // Load rainDay from cache
weather.forecasts.push(parseForecast(response.daily.data[i], response.timezone));
}

callback(null, weather);
Expand All @@ -118,57 +118,57 @@ var update = function (callback) {
var parseReport = function (values, timezone) {
let report = {};

report.AirPressure = parseInt(values['pressure']);
report.CloudCover = parseInt(values['cloudCover'] * 100);
report.Condition = values['summary'];
report.ConditionCategory = converter.getConditionCategory(values['icon']);
report.DewPoint = parseInt(values['dewPoint']);
report.Humidity = parseInt(values['humidity'] * 100);
report.ObservationTime = moment.unix(values['time']).tz(timezone).format('HH:mm:ss');
report.Ozone = parseInt(values['ozone']);
report.Rain1h = isNaN(parseInt(values['precipIntensity'])) ? 0 : parseInt(values['precipIntensity']);
report.RainDay = values['rainDay']
report.Temperature = values['temperature'];
report.UVIndex = isNaN(parseInt(values['uvIndex'])) ? 0 : parseInt(values['uvIndex']);
report.Visibility = isNaN(parseInt(values['visibility'])) ? 0 : parseInt(values['visibility']);
report.WindDirection = converter.getWindDirection(values['windBearing']);
report.WindSpeed = parseFloat(values['windSpeed']);
report.WindSpeedMax = parseFloat(values['windGust']);
report.AirPressure = parseInt(values.pressure);
report.CloudCover = parseInt(values.cloudCover * 100);
report.Condition = values.summary;
report.ConditionCategory = converter.getConditionCategory(values.icon);
report.DewPoint = parseInt(values.dewPoint);
report.Humidity = parseInt(values.humidity * 100);
report.ObservationTime = moment.unix(values.time).tz(timezone).format('HH:mm:ss');
report.Ozone = parseInt(values.ozone);
report.Rain1h = isNaN(parseInt(values.precipIntensity)) ? 0 : parseInt(values.precipIntensity);
report.RainDay = values.rainDay;
report.Temperature = values.temperature;
report.UVIndex = isNaN(parseInt(values.uvIndex)) ? 0 : parseInt(values.uvIndex);
report.Visibility = isNaN(parseInt(values.visibility)) ? 0 : parseInt(values.visibility);
report.WindDirection = converter.getWindDirection(values.windBearing);
report.WindSpeed = parseFloat(values.windSpeed);
report.WindSpeedMax = parseFloat(values.windGust);

return report;
};

var parseForecast = function (values, timezone, i) {
let forecast = {};

forecast.AirPressure = parseInt(values['pressure']);
forecast.CloudCover = parseInt(values['cloudCover'] * 100);
forecast.Condition = values['summary'];
forecast.ConditionCategory = converter.getConditionCategory(values['icon']);
forecast.DewPoint = parseInt(values['dewPoint']);
forecast.ForecastDay = moment.unix(values['time']).tz(timezone).format('dddd');
forecast.Humidity = parseInt(values['humidity'] * 100);
forecast.Ozone = parseInt(values['ozone']);
forecast.RainChance = parseInt(values['precipProbability'] * 100);
forecast.RainDay = values['rainDay']
forecast.Temperature = values['temperatureHigh'];
forecast.TemperatureMin = values['temperatureLow'];
forecast.UVIndex = isNaN(parseInt(values['uvIndex'])) ? 0 : parseInt(values['uvIndex']);
forecast.Visibility = isNaN(parseInt(values['visibility'])) ? 0 : parseInt(values['visibility']);
forecast.WindDirection = converter.getWindDirection(values['windBearing']);
forecast.WindSpeed = parseFloat(values['windSpeed']);
forecast.WindSpeedMax = parseFloat(values['windGust']);
forecast.AirPressure = parseInt(values.pressure);
forecast.CloudCover = parseInt(values.cloudCover * 100);
forecast.Condition = values.summary;
forecast.ConditionCategory = converter.getConditionCategory(values.icon);
forecast.DewPoint = parseInt(values.dewPoint);
forecast.ForecastDay = moment.unix(values.time).tz(timezone).format('dddd');
forecast.Humidity = parseInt(values.humidity * 100);
forecast.Ozone = parseInt(values.ozone);
forecast.RainChance = parseInt(values.precipProbability * 100);
forecast.RainDay = values.rainDay;
forecast.Temperature = values.temperatureHigh;
forecast.TemperatureMin = values.temperatureLow;
forecast.UVIndex = isNaN(parseInt(values.uvIndex)) ? 0 : parseInt(values.uvIndex);
forecast.Visibility = isNaN(parseInt(values.visibility)) ? 0 : parseInt(values.visibility);
forecast.WindDirection = converter.getWindDirection(values.windBearing);
forecast.WindSpeed = parseFloat(values.windSpeed);
forecast.WindSpeedMax = parseFloat(values.windGust);

return forecast;
};

var updateCache = function (api, callback) {
var updateCache = function (api, requestedForecastDays, callback) {
if (typeof cache.lastUpdate === 'undefined' || new Date() - cache.lastUpdate > 3600000) {
debug("Called hourly update of rain data");
cache.lastUpdate = new Date();

let now = moment();
let callbacks = 8;
let callbacks = requestedForecastDays + 1;

doTimeMachineRequest(api, now, function (result) {
cache.report.rainDay = result;
Expand All @@ -178,7 +178,7 @@ var updateCache = function (api, callback) {
}
}, true);

for (let i = 0; i <= 6; i++) {
for (let i = 0; i < requestedForecastDays; i++) {
doTimeMachineRequest(api, now.clone().add(i, 'd'), function (result) {
cache.forecast['day' + i].rainDay = result;
callbacks--;
Expand All @@ -201,12 +201,12 @@ var doTimeMachineRequest = function (api, now, callback, limit = false) {
// Current hour in time zone of weather location
let hour = 24;
if (limit) {
hour = now.tz(response['timezone']).format('H');
hour = now.tz(response.timezone).format('H');
}

// Sum all values for the requested day
debug("Accumulate rain for " + now.tz(response['timezone']).format('dddd') + (limit ? (' until ' + hour + ':00') : ''));
let result = converter.getRainAccumulated(response['hourly']['data'].slice(0, hour), 'precipIntensity');
debug("Accumulate rain for " + now.tz(response.timezone).format('dddd') + (limit ? (' until ' + hour + ':00') : ''));
let result = converter.getRainAccumulated(response.hourly.data.slice(0, hour), 'precipIntensity');
debug("Accumulated rain: " + result);
callback(result);
})
Expand Down
58 changes: 29 additions & 29 deletions api/openweathermap.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ var update = function (callback) {

let weather = {};
Openweathermap.getAllWeather(function (err, jsonObj) {
if (!err && jsonObj['coord']) {
if (!err && jsonObj.coord) {
// Current weather report
parseReport(weather, jsonObj, callback);
}
Expand All @@ -69,7 +69,7 @@ var update = function (callback) {
});

Openweathermap.getWeatherForecast(function (err, jsonObj) {
if (!err && jsonObj['city']) {
if (!err && jsonObj.city) {
parseForecasts(weather, jsonObj, callback);
}
else {
Expand All @@ -82,17 +82,17 @@ var update = function (callback) {

var parseReport = function (weather, values, callback) {
let report = weather.report || {};
const timezone = geoTz(values['coord']['lat'], values['coord']['lon']);

report.AirPressure = parseInt(values['main']['pressure']);
report.CloudCover = parseInt(values['clouds']['all']);
report.Condition = values['weather'][0]['description'];
report.ConditionCategory = converter.getConditionCategoryOwm(values['weather'][0]['id']);
report.Humidity = parseInt(values['main']['humidity']);
report.ObservationTime = moment.unix(values['dt']).tz(timezone).format('HH:mm:ss');
report.Temperature = values['main']['temp'];
report.WindDirection = converter.getWindDirection(values['wind']['deg']);
report.WindSpeed = values['wind']['speed'];
const timezone = geoTz(values.coord.lat, values.coord.lon);

report.AirPressure = parseInt(values.main.pressure);
report.CloudCover = parseInt(values.clouds.all);
report.Condition = values.weather[0].description;
report.ConditionCategory = converter.getConditionCategoryOwm(values.weather[0].id);
report.Humidity = parseInt(values.main.humidity);
report.ObservationTime = moment.unix(values.dt).tz(timezone).format('HH:mm:ss');
report.Temperature = values.main.temp;
report.WindDirection = converter.getWindDirection(values.wind.deg);
report.WindSpeed = values.wind.speed;

weather.report = report;
if (weather.forecasts) {
Expand All @@ -101,11 +101,11 @@ var parseReport = function (weather, values, callback) {
};

var parseForecasts = function (weather, values, callback) {
const timezone = geoTz(values['city']['coord']['lat'], values['city']['coord']['lon']);
const timezone = geoTz(values.city.coord.lat, values.city.coord.lon);

let forecasts = [];
// We get a forecast for 5 days with values each 3 hours.
const itemsFiltered = prepareForecasts(values['list'], timezone);
const itemsFiltered = prepareForecasts(values.list, timezone);
for (let i = 0; i < itemsFiltered.length; i++) {
forecasts[forecasts.length] = parseForecast(itemsFiltered[i], timezone);
}
Expand All @@ -119,16 +119,16 @@ var parseForecasts = function (weather, values, callback) {
var parseForecast = function (values, timezone) {
let forecast = {};

forecast.AirPressure = parseInt(values['main']['pressure']);
forecast.CloudCover = parseInt(values['clouds']['all']);
forecast.Condition = values['weather'][0]['description'];
forecast.ConditionCategory = converter.getConditionCategoryOwm(values['weather'][0]['id']);
forecast.ForecastDay = moment.unix(values['dt']).tz(timezone).format('dddd');
forecast.Humidity = parseInt(values['main']['humidity']);
forecast.Temperature = values['main']['temp_max'];
forecast.TemperatureMin = values['main']['temp_min'];
forecast.WindDirection = converter.getWindDirection(values['wind']['deg']);
forecast.WindSpeed = values['wind']['speed'];
forecast.AirPressure = parseInt(values.main.pressure);
forecast.CloudCover = parseInt(values.clouds.all);
forecast.Condition = values.weather[0].description;
forecast.ConditionCategory = converter.getConditionCategoryOwm(values.weather[0].id);
forecast.ForecastDay = moment.unix(values.dt).tz(timezone).format('dddd');
forecast.Humidity = parseInt(values.main.humidity);
forecast.Temperature = values.main.temp_max;
forecast.TemperatureMin = values.main.temp_min;
forecast.WindDirection = converter.getWindDirection(values.wind.deg);
forecast.WindSpeed = values.wind.speed;

return forecast;
};
Expand All @@ -150,8 +150,8 @@ var prepareForecasts = function (forecasts, timezone) {
// Find one for today
for (let i = 0; i < forecasts.length; i++) {
const listItem = forecasts[i];
if (listItem['dt'] <= endOfToday) {
const hourOfDay = moment.unix(listItem['dt']).tz(timezone).format("H");
if (listItem.dt <= endOfToday) {
const hourOfDay = moment.unix(listItem.dt).tz(timezone).format("H");
if (parseInt(hourOfDay) >= 10 && parseInt(hourOfDay) <= 13) {
forecastsFiltered[forecastsFiltered.length] = forecasts[i];
}
Expand All @@ -165,8 +165,8 @@ var prepareForecasts = function (forecasts, timezone) {
// For all following days find exactly one value (best: noon)
for (let i = 0; i < forecasts.length; i++) {
const listItem = forecasts[i];
if (listItem['dt'] > endOfToday) {
const hourOfDay = moment.unix(listItem['dt']).tz(timezone).format("H");
if (listItem.dt > endOfToday) {
const hourOfDay = moment.unix(listItem.dt).tz(timezone).format("H");
if (parseInt(hourOfDay) >= 10 && parseInt(hourOfDay) <= 13) {
forecastsFiltered[forecastsFiltered.length] = forecasts[i];
}
Expand Down
62 changes: 31 additions & 31 deletions api/weatherunderground.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,13 @@ var update = function (callback) {
this.wunderground.conditions().forecast().request(this.location, function (error, response) {
if (!error) {
// Current weather report
weather.report = parseReport(response['current_observation']);
weather.report = parseReport(response.current_observation);

// Forecasts for today and next 3 days
weather.forecasts.push(parseForecast(response['forecast']['simpleforecast']['forecastday'][0]));
weather.forecasts.push(parseForecast(response['forecast']['simpleforecast']['forecastday'][1]));
weather.forecasts.push(parseForecast(response['forecast']['simpleforecast']['forecastday'][2]));
weather.forecasts.push(parseForecast(response['forecast']['simpleforecast']['forecastday'][3]));
weather.forecasts.push(parseForecast(response.forecast.simpleforecast.forecastday[0]));
weather.forecasts.push(parseForecast(response.forecast.simpleforecast.forecastday[1]));
weather.forecasts.push(parseForecast(response.forecast.simpleforecast.forecastday[2]));
weather.forecasts.push(parseForecast(response.forecast.simpleforecast.forecastday[3]));
callback(null, weather);
}
else {
Expand All @@ -76,39 +76,39 @@ var update = function (callback) {
var parseReport = function (values) {
let report = {};

report.AirPressure = parseInt(values['pressure_mb']);
report.Condition = values['weather'];
report.ConditionCategory = converter.getConditionCategory(values['icon']);
report.Humidity = parseInt(values['relative_humidity'].substr(0, values['relative_humidity'].length - 1));
report.ObservationStation = values['observation_location']['full'];
report.ObservationTime = values['observation_time_rfc822'].split(' ')[4];
report.Rain1h = isNaN(parseInt(values['precip_1hr_metric'])) ? 0 : parseInt(values['precip_1hr_metric']);
report.RainDay = isNaN(parseInt(values['precip_today_metric'])) ? 0 : parseInt(values['precip_today_metric']);
report.SolarRadiation = isNaN(parseInt(values['solarradiation'])) ? 0 : parseInt(values['solarradiation']);
report.Temperature = values['temp_c'];
report.UVIndex = isNaN(parseInt(values['UV'])) ? 0 : parseInt(values['UV']);
report.Visibility = isNaN(parseInt(values['visibility_km'])) ? 0 : parseInt(values['visibility_km']);
report.WindDirection = values['wind_dir'];
report.WindSpeed = parseFloat(values['wind_kph']);
report.WindSpeedMax = parseFloat(values['wind_gust_kph']);
report.AirPressure = parseInt(values.pressure_mb);
report.Condition = values.weather;
report.ConditionCategory = converter.getConditionCategory(values.icon);
report.Humidity = parseInt(values.relative_humidity.substr(0, values.relative_humidity.length - 1));
report.ObservationStation = values.observation_location.full;
report.ObservationTime = values.observation_time_rfc822.split(' ')[4];
report.Rain1h = isNaN(parseInt(values.precip_1hr_metric)) ? 0 : parseInt(values.precip_1hr_metric);
report.RainDay = isNaN(parseInt(values.precip_today_metric)) ? 0 : parseInt(values.precip_today_metric);
report.SolarRadiation = isNaN(parseInt(values.solarradiation)) ? 0 : parseInt(values.solarradiation);
report.Temperature = values.temp_c;
report.UVIndex = isNaN(parseInt(values.UV)) ? 0 : parseInt(values.UV);
report.Visibility = isNaN(parseInt(values.visibility_km)) ? 0 : parseInt(values.visibility_km);
report.WindDirection = values.wind_dir;
report.WindSpeed = parseFloat(values.wind_kph);
report.WindSpeedMax = parseFloat(values.wind_gust_kph);

return report;
};

var parseForecast = function (values) {
let forecast = {};

forecast.Condition = values['conditions'];
forecast.ConditionCategory = converter.getConditionCategory(values['icon']);
forecast.ForecastDay = values['date']['weekday'];
forecast.Humidity = parseInt(values['avehumidity'])
forecast.RainChance = values['pop'];
forecast.RainDay = isNaN(parseInt(values['qpf_allday']['mm'])) ? 0 : parseInt(values['qpf_allday']['mm']);
forecast.Temperature = values['high']['celsius'];
forecast.TemperatureMin = values['low']['celsius'];
forecast.WindDirection = values['avewind']['dir'];
forecast.WindSpeed = parseFloat(values['avewind']['kph']);
forecast.WindSpeedMax = parseFloat(values['maxwind']['kph']);
forecast.Condition = values.conditions;
forecast.ConditionCategory = converter.getConditionCategory(values.icon);
forecast.ForecastDay = values.date.weekday;
forecast.Humidity = parseInt(values.avehumidity);
forecast.RainChance = values.pop;
forecast.RainDay = isNaN(parseInt(values.qpf_allday.mm)) ? 0 : parseInt(values.qpf_allday.mm);
forecast.Temperature = values.high.celsius;
forecast.TemperatureMin = values.low.celsius;
forecast.WindDirection = values.avewind.dir;
forecast.WindSpeed = parseFloat(values.avewind.kph);
forecast.WindSpeedMax = parseFloat(values.maxwind.kph);

return forecast;
};
Expand Down
Loading

0 comments on commit 31ef67e

Please sign in to comment.