Explorar o código

#5 weather service

Martin %!s(int64=9) %!d(string=hai) anos
pai
achega
60420f4ca1
Modificáronse 4 ficheiros con 119 adicións e 1 borrados
  1. 1 0
      README.md
  2. 4 0
      voice_control/conf.py
  3. 11 1
      voice_control/services/__init__.py
  4. 103 0
      voice_control/services/weather.py

+ 1 - 0
README.md

@@ -9,6 +9,7 @@ Python requirements:
     requests
     arrow
     slackclient
+    xmltodict
 
 Linux:
     alsa-base alsa-utils alsa-tools libasound-dev easy_install python-dev libportaudio2 flac

+ 4 - 0
voice_control/conf.py

@@ -30,3 +30,7 @@ MAILGUN_RECIPIENTS = {
 # Wunderlist
 WUNDERLIST_CLIENT_ID = '34e0e31945afeb63e1b8'
 WUNDERLIST_ACCESS_TOKEN = 'a7258e8b6596fdaffc904fc6b65d40c23afe6d2a28bfe7be1a9026d44b59'
+
+# met.no weather service
+WEATHER_LAT = 53.283148
+WEATHER_LON = -6.146421

+ 11 - 1
voice_control/services/__init__.py

@@ -1,4 +1,6 @@
 import threading
+import traceback
+
 import email_mailgun
 import todo_wunderlist
 import input_sources
@@ -8,6 +10,7 @@ import services.help
 import echo
 import duckduckgo_answers
 import music
+import conf
 
 def _get_services(cclient):
     res = {
@@ -22,6 +25,10 @@ def _get_services(cclient):
 
     res['help'] = services.help.Help(res)
 
+    if conf.WEATHER_LAT and conf.WEATHER_LON:
+        import weather
+        res['weather'] = weather.Weather()
+
     return res
 
 def launch_services(cclient, interrupted):
@@ -38,7 +45,10 @@ def launch_services(cclient, interrupted):
         input_sources.PREFERRED_PHRASES = _services.keys() + ['quit']
         t = input_sources.get_token(1)
         if t is not None and t in _services and _services[t].initialized:
-            _services[t].call()
+            try:
+                _services[t].call()
+            except Exception, e:
+                output.failure(s='Error: %s' % traceback.format_exc())
         elif t == 'quit':
             return
         elif t is not None:

+ 103 - 0
voice_control/services/weather.py

@@ -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)