weather_agent.rb 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. require 'date'
  2. module Agents
  3. class WeatherAgent < Agent
  4. cannot_receive_events!
  5. description <<-MD
  6. The WeatherAgent creates an event for the following day's weather at `zipcode`.
  7. You must setup an [API key for Wunderground](http://www.wunderground.com/weather/api/) in order to use this Agent.
  8. MD
  9. event_description <<-MD
  10. Events look like this:
  11. {
  12. :zipcode => 12345,
  13. :date => { :epoch=>"1357959600", :pretty=>"10:00 PM EST on January 11, 2013" },
  14. :high => { :fahrenheit=>"64", :celsius=>"18" },
  15. :low => { :fahrenheit=>"52", :celsius=>"11" },
  16. :conditions => "Rain Showers",
  17. :icon=>"rain",
  18. :icon_url => "http://icons-ak.wxug.com/i/c/k/rain.gif",
  19. :skyicon => "mostlycloudy",
  20. :pop => 80,
  21. :qpf_allday => { :in=>0.24, :mm=>6.1 },
  22. :qpf_day => { :in=>0.13, :mm=>3.3 },
  23. :qpf_night => { :in=>0.03, :mm=>0.8 },
  24. :snow_allday => { :in=>0, :cm=>0 },
  25. :snow_day => { :in=>0, :cm=>0 },
  26. :snow_night => { :in=>0, :cm=>0 },
  27. :maxwind => { :mph=>15, :kph=>24, :dir=>"SSE", :degrees=>160 },
  28. :avewind => { :mph=>9, :kph=>14, :dir=>"SSW", :degrees=>194 },
  29. :avehumidity => 85,
  30. :maxhumidity => 93,
  31. :minhumidity => 63
  32. }
  33. MD
  34. default_schedule "8pm"
  35. def working?
  36. (event = event_created_within(2.days)) && event.payload.present?
  37. end
  38. def wunderground
  39. Wunderground.new(options[:api_key]) if key_setup?
  40. end
  41. def key_setup?
  42. options[:api_key] && options[:api_key] != "your-key"
  43. end
  44. def default_options
  45. {
  46. :api_key => "your-key",
  47. :zipcode => "94103"
  48. }
  49. end
  50. def validate_options
  51. errors.add(:base, "zipcode is required") unless options[:zipcode].present?
  52. errors.add(:base, "api_key is required") unless options[:api_key].present?
  53. end
  54. def check
  55. if key_setup?
  56. wunderground.forecast_for(options[:zipcode])["forecast"]["simpleforecast"]["forecastday"].each do |day|
  57. if is_tomorrow?(day)
  58. create_event :payload => day.merge(:zipcode => options[:zipcode])
  59. end
  60. end
  61. end
  62. end
  63. def is_tomorrow?(day)
  64. Time.zone.at(day["date"]["epoch"].to_i).to_date == Time.zone.now.tomorrow.to_date
  65. end
  66. end
  67. end