Class: Barometer::WeatherService::WeatherBug

Inherits:
Barometer::WeatherService show all
Defined in:
lib/barometer/weather_services/weather_bug.rb

Overview

WeatherBug

www.weatherbug.com

  • key required: YES (api_code)

  • registration required: YES

  • supported countries: US (by zipcode), International (by coordinates)

performs geo coding

  • city: YES

  • coordinates: PARTIAL (just for weather station)

time info

  • sun rise/set: YES

  • provides timezone: NO, but provides a timezone short code and utc offset

  • requires TZInfo: NO

resources

Possible queries:

where query can be:

  • zipcode (US) [5 digits only]

  • coordinates (International)

WeatherBug.com terms of use

???

notes

  • WeatherBug also supports queries using “citycode” and “stationID”, but these are specific to WeatherBug and un-supported by Barometer

Constant Summary collapse

@@api_code =
nil

Class Method Summary collapse

Methods inherited from Barometer::WeatherService

_build_links, _build_local_time, _keys=, _links_result, _local_time, _measure, _meets_requirements?, _parse_full_timezone, _supports_country?, _timezone, measure, source

Class Method Details

._accepted_formatsObject



53
# File 'lib/barometer/weather_services/weather_bug.rb', line 53

def self._accepted_formats; [:short_zipcode, :coordinates]; end

._build_current(data, metric = true) ⇒ Object

Raises:

  • (ArgumentError)


97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/barometer/weather_services/weather_bug.rb', line 97

def self._build_current(data, metric=true)
  raise ArgumentError unless data.is_a?(Hash)

  current = Measurement::Current.new
  # current.updated_at = Data::LocalDateTime.parse(data['observation_time']) if data['observation_time']
  current.humidity = data['aws:humidity'].to_i
  current.condition = data['aws:current_condition'] if data['aws:current_condition']
  current.icon = data['aws:icon'].to_i.to_s if data['aws:icon']

  current.temperature = Data::Temperature.new(metric)
  current.temperature << data['aws:temp']

  current.wind = Data::Speed.new(metric)
  current.wind << data['aws:wind_speed'].to_f
  current.wind.direction = data['aws:wind_direction']

  current.pressure = Data::Pressure.new(metric)
  current.pressure << data['aws:pressure']

  current.dew_point = Data::Temperature.new(metric)
  current.dew_point << data['aws:dew_point']

  current.wind_chill = Data::Temperature.new(metric)
  current.wind_chill << data['aws:feels_like']

  current
end

._build_extra(measurement, result, metric = true) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/barometer/weather_services/weather_bug.rb', line 69

def self._build_extra(measurement, result, metric=true)
  #raise ArgumentError unless measurement.is_a?(Data::Measurement)
  #raise ArgumentError unless query.is_a?(Barometer::Query)

  # use todays sun data for all future days
  if measurement.forecast && measurement.current.sun
    measurement.forecast.each do |forecast|
      forecast.sun = measurement.current.sun
    end
  end
  
  measurement
end

._build_forecast(data, metric = true) ⇒ Object

Raises:

  • (ArgumentError)


125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/barometer/weather_services/weather_bug.rb', line 125

def self._build_forecast(data, metric=true)
  raise ArgumentError unless data.is_a?(Hash)
  forecasts = Measurement::ForecastArray.new
  # go through each forecast and create an instance
  if data && data["aws:forecast"]
    start_date = Date.parse(data['date'])
    i = 0
    data["aws:forecast"].each do |forecast|
      forecast_measurement = Measurement::Forecast.new
      icon_match = forecast['aws:image'].match(/cond(\d*)\.gif$/)
      forecast_measurement.icon = icon_match[1].to_i.to_s if icon_match
      forecast_measurement.date = start_date + i
      forecast_measurement.condition = forecast['aws:short_prediction']

      forecast_measurement.high = Data::Temperature.new(metric)
      forecast_measurement.high << forecast['aws:high']

      forecast_measurement.low = Data::Temperature.new(metric)
      forecast_measurement.low << forecast['aws:low']

      forecasts << forecast_measurement
      i += 1
    end
  end
  forecasts
end

._build_location(data, geo = nil) ⇒ Object

Raises:

  • (ArgumentError)


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/barometer/weather_services/weather_bug.rb', line 152

def self._build_location(data, geo=nil)
  raise ArgumentError unless data.is_a?(Hash)
  raise ArgumentError unless (geo.nil? || geo.is_a?(Data::Geo))
  location = Data::Location.new
  # use the geocoded data if available, otherwise get data from result
  if geo
    location.city = geo.locality
    location.state_code = geo.region
    location.country = geo.country
    location.country_code = geo.country_code
    location.latitude = geo.latitude
    location.longitude = geo.longitude
  else
    if data && data['aws:location']
      location.city = data['aws:location']['aws:city']
      location.state_code = data['aws:location']['aws:state']
      location.zip_code = data['aws:location']['aws:zip']
    end
  end
  location
end

._build_station(data) ⇒ Object

Raises:

  • (ArgumentError)


174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/barometer/weather_services/weather_bug.rb', line 174

def self._build_station(data)
  raise ArgumentError unless data.is_a?(Hash)
  station = Data::Location.new
  station.id = data['aws:station_id']
  station.name = data['aws:station']
  station.city = data['aws:city_state'].split(',')[0].strip
  station.state_code = data['aws:city_state'].split(',')[1].strip
  station.country = data['aws:country']
  station.zip_code = data['aws:station_zipcode']
  station.latitude = data['aws:latitude']
  station.longitude = data['aws:longitude']
  station
end

._build_sun(data) ⇒ Object

Raises:

  • (ArgumentError)


188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/barometer/weather_services/weather_bug.rb', line 188

def self._build_sun(data)
  raise ArgumentError unless data.is_a?(Hash)
  sun = nil
  if data
    if data['aws:sunrise']
      rise = Data::LocalTime.new(
        data['aws:sunrise']['aws:hour']['hour_24'].to_i,
        data['aws:sunrise']['aws:minute']['number'].to_i,
        data['aws:sunrise']['aws:second']['number'].to_i
      )
    end
    if data['aws:sunset']
      set = Data::LocalTime.new(
        data['aws:sunset']['aws:hour']['hour_24'].to_i,
        data['aws:sunset']['aws:minute']['number'].to_i,
        data['aws:sunset']['aws:second']['number'].to_i
      )
      sun = Data::Sun.new(rise,set)
    end
  end
  sun || Data::Sun.new
end

._build_timezone(data) ⇒ Object



91
92
93
94
95
# File 'lib/barometer/weather_services/weather_bug.rb', line 91

def self._build_timezone(data)
  if data && data["aws:ob_date"] && data["aws:ob_date"]["aws:time_zone"]
    Data::Zone.new(data["aws:ob_date"]["aws:time_zone"]["abbrv"])
  end
end

._current_result(data) ⇒ Object

since we have two sets of data, override these calls to choose the right set of data



286
# File 'lib/barometer/weather_services/weather_bug.rb', line 286

def self._current_result(data); data[0]; end

._fetch(query, metric = true) ⇒ Object

override default _fetch behavior this service requires TWO seperate http requests (one for current and one for forecasted weather) … combine the results



215
216
217
218
219
220
# File 'lib/barometer/weather_services/weather_bug.rb', line 215

def self._fetch(query, metric=true)
  result = []
  result << _fetch_current(query,metric)
  result << _fetch_forecast(query,metric)
  result
end

._fetch_current(query, metric = true) ⇒ Object

use HTTParty to get the current weather



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/barometer/weather_services/weather_bug.rb', line 224

def self._fetch_current(query, metric=true)
  puts "fetch weatherbug current: #{query.q}" if Barometer::debug?
  
  q = ( query.format.to_sym == :short_zipcode ?
    { :zipCode => query.q } :
    { :lat => query.q.split(',')[0], :long => query.q.split(',')[1] })
  
  # httparty and the xml builder it uses miss some information
  # 1st - get the raw response
  # 2nd - manually get the missing information
  # 3rd - let httparty build xml as normal
  #
  response = self.get(
    "http://#{@@api_code}.api.wxbug.net/getLiveWeatherRSS.aspx",
    :query => { :ACode => @@api_code,
      :OutputType => "1", :UnitType => (metric ? '1' : '0')
    }.merge(q),
    :format => :plain,
    :timeout => Barometer.timeout
  )
  
  # get icon
  icon_match = response.match(/cond(\d*)\.gif/)
  icon = icon_match[1] if icon_match
  
  # get station zipcode
  zip_match = response.match(/zipcode=\"(\d*)\"/)
  zipcode = zip_match[1] if zip_match
  
  # build xml
  output = Crack::XML.parse(response)
  output = output["aws:weather"]["aws:ob"]
  
  # add missing data
  output["aws:icon"] = icon
  output["aws:station_zipcode"] = zipcode
  
  output
end

._fetch_forecast(query, metric = true) ⇒ Object

use HTTParty to get the current weather



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/barometer/weather_services/weather_bug.rb', line 266

def self._fetch_forecast(query, metric=true)
  puts "fetch weatherbug forecast: #{query.q}" if Barometer::debug?
  
  q = ( query.format.to_sym == :short_zipcode ?
    { :zipCode => query.q } :
    { :lat => query.q.split(',')[0], :long => query.q.split(',')[1] })
  
  self.get(
    "http://#{@@api_code}.api.wxbug.net/getForecastRSS.aspx",
    :query => { :ACode => @@api_code,
      :OutputType => "1", :UnitType => (metric ? '1' : '0')
    }.merge(q),
    :format => :xml,
    :timeout => Barometer.timeout
  )["aws:weather"]["aws:forecasts"]
end

._forecast_result(data = nil) ⇒ Object



287
# File 'lib/barometer/weather_services/weather_bug.rb', line 287

def self._forecast_result(data=nil); data[1]; end

._has_keys?Boolean

Returns:

  • (Boolean)


55
# File 'lib/barometer/weather_services/weather_bug.rb', line 55

def self._has_keys?; !@@api_code.nil?; end

._location_result(data = nil) ⇒ Object



288
# File 'lib/barometer/weather_services/weather_bug.rb', line 288

def self._location_result(data=nil); data[1]; end

._parse_local_time(data) ⇒ Object



83
84
85
86
87
88
89
# File 'lib/barometer/weather_services/weather_bug.rb', line 83

def self._parse_local_time(data)
  Data::LocalTime.new(
    data["aws:ob_date"]["aws:hour"]["hour_24"].to_i,
    data["aws:ob_date"]["aws:minute"]["number"].to_i,
    data["aws:ob_date"]["aws:second"]["number"].to_i
  ) if data && data["aws:ob_date"]
end

._requires_keys?Boolean

Returns:

  • (Boolean)


56
# File 'lib/barometer/weather_services/weather_bug.rb', line 56

def self._requires_keys?; true; end

._source_nameObject

PRIVATE If class methods could be private, the remaining methods would be.



52
# File 'lib/barometer/weather_services/weather_bug.rb', line 52

def self._source_name; :weather_bug; end

._station_result(data = nil) ⇒ Object



289
# File 'lib/barometer/weather_services/weather_bug.rb', line 289

def self._station_result(data=nil); data[0]; end

._sun_result(data = nil) ⇒ Object



290
# File 'lib/barometer/weather_services/weather_bug.rb', line 290

def self._sun_result(data=nil); data[0]; end

._sunny_icon_codesObject



64
65
66
67
# File 'lib/barometer/weather_services/weather_bug.rb', line 64

def self._sunny_icon_codes
  codes = [0,2,3,4,7,26,31,64,65,75]
  codes.collect {|c| c.to_s}
end

._time_result(data = nil) ⇒ Object



292
# File 'lib/barometer/weather_services/weather_bug.rb', line 292

def self._time_result(data=nil); data[0]; end

._timezone_result(data = nil) ⇒ Object



291
# File 'lib/barometer/weather_services/weather_bug.rb', line 291

def self._timezone_result(data=nil); data[0]; end

._wet_icon_codesObject



58
59
60
61
62
63
# File 'lib/barometer/weather_services/weather_bug.rb', line 58

def self._wet_icon_codes
  codes = [5,6,8,9,11,12,14,15] + (18..22).to_a + [25] + (27..30).to_a +
          [32,36] + (38..49).to_a + (52..63).to_a + (80..157).to_a +
          (161..176).to_a
  codes.collect {|c| c.to_s}
end

.keys=(keys) ⇒ Object

Raises:

  • (ArgumentError)


40
41
42
43
44
45
# File 'lib/barometer/weather_services/weather_bug.rb', line 40

def self.keys=(keys)
  raise ArgumentError unless keys.is_a?(Hash)
  keys.each do |key, value|
    @@api_code = value.to_s if key.to_s.downcase == "code"
  end
end