weather_agent.rb 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. require 'date'
  2. require 'cgi'
  3. module Agents
  4. class WeatherAgent < Agent
  5. cannot_receive_events!
  6. gem_dependency_check { defined?(ForecastIO) }
  7. description <<~MD
  8. The Weather Agent creates an event for the day's weather at a given `location`.
  9. #{'## Include `forecast_io` in your Gemfile to use this Agent!' if dependencies_missing?}
  10. You also must select when you would like to get the weather forecast for using the `which_day` option, where the number 1 represents today, 2 represents tomorrow and so on. Weather forecast inforation is only returned for at most one week at a time.
  11. The weather forecast information is provided by Dark Sky.
  12. The `location` must be a comma-separated string of map co-ordinates (longitude, latitude). For example, San Francisco would be `37.7771,-122.4196`.
  13. You must set up an [API key for Dark Sky](https://darksky.net/dev/) in order to use this Agent.
  14. 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.
  15. MD
  16. event_description <<~MD
  17. Events look like this:
  18. {
  19. "location": "12345",
  20. "date": {
  21. "epoch": "1357959600",
  22. "pretty": "10:00 PM EST on January 11, 2013"
  23. },
  24. "high": {
  25. "fahrenheit": "64",
  26. "celsius": "18"
  27. },
  28. "low": {
  29. "fahrenheit": "52",
  30. "celsius": "11"
  31. },
  32. "conditions": "Rain Showers",
  33. "icon": "rain",
  34. "icon_url": "https://icons-ak.wxug.com/i/c/k/rain.gif",
  35. "skyicon": "mostlycloudy",
  36. ...
  37. }
  38. MD
  39. default_schedule "8pm"
  40. def working?
  41. event_created_within?((interpolated['expected_update_period_in_days'].presence || 2).to_i) && !recent_error_logs? && key_setup?
  42. end
  43. def key_setup?
  44. interpolated['api_key'].present? && interpolated['api_key'] != "your-key" && interpolated['api_key'] != "put-your-key-here"
  45. end
  46. def default_options
  47. {
  48. 'api_key' => 'your-key',
  49. 'location' => '37.779329,-122.41915',
  50. 'which_day' => '1',
  51. 'expected_update_period_in_days' => '2',
  52. 'language' => 'en'
  53. }
  54. end
  55. def check
  56. if key_setup?
  57. create_event payload: model(which_day).merge('location' => location)
  58. end
  59. end
  60. private
  61. def which_day
  62. (interpolated["which_day"].presence || 1).to_i
  63. end
  64. def location
  65. interpolated["location"].presence || interpolated["zipcode"]
  66. end
  67. def coordinates
  68. location.split(',').map { |e| e.to_f }
  69. end
  70. def language
  71. interpolated["language"].presence || "en"
  72. end
  73. def wunderground?
  74. interpolated["service"].presence && interpolated["service"].presence.downcase == "wunderground"
  75. end
  76. VALID_COORDS_REGEX = /^\s*-?\d{1,3}\.\d+\s*,\s*-?\d{1,3}\.\d+\s*$/
  77. def validate_location
  78. errors.add(:base, "location is required") unless location.present?
  79. if location =~ VALID_COORDS_REGEX
  80. lat, lon = coordinates
  81. errors.add :base, "too low of a latitude" unless lat > -90
  82. errors.add :base, "too big of a latitude" unless lat < 90
  83. errors.add :base, "too low of a longitude" unless lon > -180
  84. errors.add :base, "too high of a longitude" unless lon < 180
  85. else
  86. errors.add(
  87. :base,
  88. "Location #{location} is malformed. Location for " +
  89. 'Dark Sky must be in the format "-00.000,-00.00000". The ' +
  90. "number of decimal places does not matter."
  91. )
  92. end
  93. end
  94. def validate_options
  95. errors.add(:base,
  96. "The Weather Underground API has been disabled since Jan 1st 2018, please switch to DarkSky") if wunderground?
  97. validate_location
  98. errors.add(:base, "api_key is required") unless interpolated['api_key'].present?
  99. errors.add(:base, "which_day selection is required") unless which_day.present?
  100. end
  101. def dark_sky
  102. if key_setup?
  103. ForecastIO.api_key = interpolated['api_key']
  104. lat, lng = coordinates
  105. ForecastIO.forecast(lat, lng, params: { lang: language.downcase })['daily']['data']
  106. end
  107. end
  108. def model(which_day)
  109. value = dark_sky[which_day - 1]
  110. if value
  111. timestamp = Time.at(value.time)
  112. {
  113. 'date' => {
  114. 'epoch' => value.time.to_s,
  115. 'pretty' => timestamp.strftime("%l:%M %p %Z on %B %d, %Y"),
  116. 'day' => timestamp.day,
  117. 'month' => timestamp.month,
  118. 'year' => timestamp.year,
  119. 'yday' => timestamp.yday,
  120. 'hour' => timestamp.hour,
  121. 'min' => timestamp.strftime("%M"),
  122. 'sec' => timestamp.sec,
  123. 'isdst' => timestamp.isdst ? 1 : 0,
  124. 'monthname' => timestamp.strftime("%B"),
  125. 'monthname_short' => timestamp.strftime("%b"),
  126. 'weekday_short' => timestamp.strftime("%a"),
  127. 'weekday' => timestamp.strftime("%A"),
  128. 'ampm' => timestamp.strftime("%p"),
  129. 'tz_short' => timestamp.zone
  130. },
  131. 'period' => which_day.to_i,
  132. 'high' => {
  133. 'fahrenheit' => value.temperatureMax.round.to_s,
  134. 'epoch' => value.temperatureMaxTime.to_s,
  135. 'fahrenheit_apparent' => value.apparentTemperatureMax.round.to_s,
  136. 'epoch_apparent' => value.apparentTemperatureMaxTime.to_s,
  137. 'celsius' => ((5 * (Float(value.temperatureMax) - 32)) / 9).round.to_s
  138. },
  139. 'low' => {
  140. 'fahrenheit' => value.temperatureMin.round.to_s,
  141. 'epoch' => value.temperatureMinTime.to_s,
  142. 'fahrenheit_apparent' => value.apparentTemperatureMin.round.to_s,
  143. 'epoch_apparent' => value.apparentTemperatureMinTime.to_s,
  144. 'celsius' => ((5 * (Float(value.temperatureMin) - 32)) / 9).round.to_s
  145. },
  146. 'conditions' => value.summary,
  147. 'icon' => value.icon,
  148. 'avehumidity' => (value.humidity * 100).to_i,
  149. 'sunriseTime' => value.sunriseTime.to_s,
  150. 'sunsetTime' => value.sunsetTime.to_s,
  151. 'moonPhase' => value.moonPhase.to_s,
  152. 'precip' => {
  153. 'intensity' => value.precipIntensity.to_s,
  154. 'intensity_max' => value.precipIntensityMax.to_s,
  155. 'intensity_max_epoch' => value.precipIntensityMaxTime.to_s,
  156. 'probability' => value.precipProbability.to_s,
  157. 'type' => value.precipType
  158. },
  159. 'dewPoint' => value.dewPoint.to_s,
  160. 'avewind' => {
  161. 'mph' => value.windSpeed.round.to_s,
  162. 'kph' => (Float(value.windSpeed) * 1.609344).round.to_s,
  163. 'degrees' => value.windBearing.to_s
  164. },
  165. 'visibility' => value.visibility.to_s,
  166. 'cloudCover' => value.cloudCover.to_s,
  167. 'pressure' => value.pressure.to_s,
  168. 'ozone' => value.ozone.to_s
  169. }
  170. end
  171. end
  172. end
  173. end