Feature/add language option to weather agent (#1544)

* Add language parameter to the weather agent

* Add text forecast for Wunderground data provider

Wunderground API returns forecast for the next few days. Returned JSON response has two types of data under the "forecast" key:
- "txt_forecast": pre-formatted text representation
- "simpleforecast": raw data representation

The "period" key contains which day the node belongs to.

Currently only "simpleforecast" is available to users of the Weather agent.
This commit appends the "txt_forecast" representation to the current data set.
This commit is contained in:
Géza Búza 2016-08-31 17:37:51 +02:00 committed by Andrew Cantino
parent a6fe9743f6
commit c3ab764efc

View file

@ -25,6 +25,8 @@ module Agents
You must setup an [API key for Forecast](https://developer.forecast.io/) in order to use this Agent with ForecastIO.
Set `expected_update_period_in_days` to the maximum amount of time that you'd expect to pass between Events being created by this Agent.
If you want to see the returned texts in your language, then set the `language` parameter in ISO 639-1 format.
MD
event_description <<-MD
@ -68,10 +70,11 @@ module Agents
'api_key' => 'your-key',
'location' => '94103',
'which_day' => '1',
'language' => 'EN',
'expected_update_period_in_days' => '2'
}
end
def check
if key_setup?
create_event :payload => model(weather_provider, which_day).merge('location' => location)
@ -79,7 +82,7 @@ module Agents
end
private
def weather_provider
interpolated["service"].presence || "wunderground"
end
@ -92,6 +95,10 @@ module Agents
interpolated["location"].presence || interpolated["zipcode"]
end
def language
interpolated['language'].presence || 'EN'
end
def validate_options
errors.add(:base, "service must be set to 'forecastio' or 'wunderground'") unless ["forecastio", "wunderground"].include?(weather_provider)
errors.add(:base, "location is required") unless location.present?
@ -100,14 +107,20 @@ module Agents
end
def wunderground
Wunderground.new(interpolated['api_key']).forecast_for(location)['forecast']['simpleforecast']['forecastday'] if key_setup?
if key_setup?
forecast = Wunderground.new(interpolated['api_key'], language: language.upcase).forecast_for(location)
merged = {}
forecast['forecast']['simpleforecast']['forecastday'].each { |daily| merged[daily['period']] = daily }
forecast['forecast']['txt_forecast']['forecastday'].each { |daily| (merged[daily['period']] || {}).merge!(daily) }
merged
end
end
def forecastio
if key_setup?
ForecastIO.api_key = interpolated['api_key']
lat, lng = location.split(',')
ForecastIO.forecast(lat,lng)['daily']['data']
ForecastIO.forecast(lat, lng, params: {lang: language.downcase})['daily']['data']
end
end