|
|
@@ -0,0 +1,103 @@
|
|
|
+import time
|
|
|
+import datetime
|
|
|
+
|
|
|
+import requests
|
|
|
+import xmltodict
|
|
|
+import arrow
|
|
|
+
|
|
|
+import base
|
|
|
+import conf
|
|
|
+import output
|
|
|
+import util
|
|
|
+
|
|
|
+_URL = 'http://api.met.no/weatherapi/locationforecast/1.9/?lat=%f;lon=%f'
|
|
|
+
|
|
|
+# sample: http://api.met.no/weatherapi/locationforecast/1.9/?lat=60.10;lon=9.58;msl=70
|
|
|
+
|
|
|
+_WIND_DIRECTIONS = {
|
|
|
+ 'N': 'north',
|
|
|
+ 'S': 'south',
|
|
|
+ 'E': 'east',
|
|
|
+ 'W': 'west',
|
|
|
+ 'NE': 'northeast',
|
|
|
+ 'NW': 'northwest',
|
|
|
+ 'SW': 'southwest',
|
|
|
+ 'SE': 'southeast',
|
|
|
+}
|
|
|
+
|
|
|
+_WIND_STRENGTHS = {
|
|
|
+ 0: 'calm',
|
|
|
+ 1: 'light air',
|
|
|
+ 2: 'light breeze',
|
|
|
+ 3: 'gentle breeze',
|
|
|
+ 4: 'moderate breeze',
|
|
|
+ 5: 'fresh breeze',
|
|
|
+ 6: 'strong breeze',
|
|
|
+ 7: 'high wind',
|
|
|
+ 8: 'gale',
|
|
|
+ 9: 'strong gale',
|
|
|
+ 10: 'storm',
|
|
|
+ 11: 'violent storm',
|
|
|
+ 12: 'hurricane',
|
|
|
+}
|
|
|
+
|
|
|
+class Weather(base.BaseService):
|
|
|
+ def help(self):
|
|
|
+ return 'Returns the weather.'
|
|
|
+
|
|
|
+ def _merge_forecasts(self, forecasts):
|
|
|
+ now = arrow.get().timestamp
|
|
|
+ res = {}
|
|
|
+ best_times = {}
|
|
|
+
|
|
|
+ for f in forecasts:
|
|
|
+ start = arrow.get(f['@from']).timestamp
|
|
|
+ end = arrow.get(f['@to']).timestamp
|
|
|
+ diff = abs(now - 0.5 * (start + end))
|
|
|
+
|
|
|
+ for k, v in f['location'].iteritems():
|
|
|
+ if k not in res:
|
|
|
+ res[k] = v
|
|
|
+ best_times[k] = diff
|
|
|
+ elif diff < best_times[k]:
|
|
|
+ res[k] = v
|
|
|
+ best_times[k] = diff
|
|
|
+
|
|
|
+ return res
|
|
|
+
|
|
|
+ def _get_xml(self):
|
|
|
+ res = requests.get(_URL % (conf.WEATHER_LAT, conf.WEATHER_LON))
|
|
|
+
|
|
|
+ if res.status_code != 200:
|
|
|
+ output.failure(s='Status: %i' % res.status_code)
|
|
|
+ return None
|
|
|
+ else:
|
|
|
+ return res.content
|
|
|
+
|
|
|
+ def call(self):
|
|
|
+ xml = self._get_xml()
|
|
|
+ if not xml:
|
|
|
+ return
|
|
|
+
|
|
|
+ data = xmltodict.parse(xml)
|
|
|
+
|
|
|
+ forecasts = data['weatherdata']['product']['time']
|
|
|
+ forecast = self._merge_forecasts(forecasts)
|
|
|
+
|
|
|
+ if 'temperature' in forecast:
|
|
|
+ temperature = int(round(float(forecast['temperature']['@value'])))
|
|
|
+ output.tts('%i degrees' % temperature)
|
|
|
+ time.sleep(1)
|
|
|
+
|
|
|
+ if 'windSpeed' in forecast and 'windDirection' in forecast:
|
|
|
+ windspeed_mps = float(forecast['windSpeed']['@mps'])
|
|
|
+ windspeed_beaufort = int(forecast['windSpeed']['@beaufort'])
|
|
|
+ windstrength = _WIND_STRENGTHS[windspeed_beaufort]
|
|
|
+ winddirection = _WIND_DIRECTIONS[forecast['windDirection']['@name']]
|
|
|
+ output.tts('%s from %s' % (windstrength, winddirection))
|
|
|
+ time.sleep(1)
|
|
|
+
|
|
|
+ if 'precipitation' in forecast:
|
|
|
+ v = float(forecast['precipitation']['@value'])
|
|
|
+ if v > -1:
|
|
|
+ output.tts('precipitation: %.1f' % v)
|