weather.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import time
  2. import datetime
  3. import requests
  4. import xmltodict
  5. import arrow
  6. import base
  7. import conf
  8. import output
  9. import util
  10. _URL = 'http://api.met.no/weatherapi/locationforecast/1.9/?lat=%f;lon=%f'
  11. # sample: http://api.met.no/weatherapi/locationforecast/1.9/?lat=60.10;lon=9.58;msl=70
  12. _WIND_DIRECTIONS = {
  13. 'N': 'north',
  14. 'S': 'south',
  15. 'E': 'east',
  16. 'W': 'west',
  17. 'NE': 'northeast',
  18. 'NW': 'northwest',
  19. 'SW': 'southwest',
  20. 'SE': 'southeast',
  21. }
  22. _WIND_STRENGTHS = {
  23. 0: 'calm',
  24. 1: 'light air',
  25. 2: 'light breeze',
  26. 3: 'gentle breeze',
  27. 4: 'moderate breeze',
  28. 5: 'fresh breeze',
  29. 6: 'strong breeze',
  30. 7: 'high wind',
  31. 8: 'gale',
  32. 9: 'strong gale',
  33. 10: 'storm',
  34. 11: 'violent storm',
  35. 12: 'hurricane',
  36. }
  37. class Weather(base.BaseService):
  38. def help(self):
  39. return 'Returns the weather.'
  40. def _merge_forecasts(self, forecasts):
  41. now = arrow.get().timestamp
  42. res = {}
  43. best_times = {}
  44. for f in forecasts:
  45. start = arrow.get(f['@from']).timestamp
  46. end = arrow.get(f['@to']).timestamp
  47. diff = abs(now - 0.5 * (start + end))
  48. for k, v in f['location'].iteritems():
  49. if k not in res:
  50. res[k] = v
  51. best_times[k] = diff
  52. elif diff < best_times[k]:
  53. res[k] = v
  54. best_times[k] = diff
  55. return res
  56. def _get_xml(self):
  57. res = requests.get(_URL % (conf.WEATHER_LAT, conf.WEATHER_LON))
  58. if res.status_code != 200:
  59. output.failure(s='Status: %i' % res.status_code)
  60. return None
  61. else:
  62. return res.content
  63. def call(self):
  64. xml = self._get_xml()
  65. if not xml:
  66. return
  67. data = xmltodict.parse(xml)
  68. forecasts = data['weatherdata']['product']['time']
  69. forecast = self._merge_forecasts(forecasts)
  70. if 'temperature' in forecast:
  71. temperature = int(round(float(forecast['temperature']['@value'])))
  72. output.tts('%i degrees' % temperature)
  73. time.sleep(1)
  74. if 'windSpeed' in forecast and 'windDirection' in forecast:
  75. windspeed_mps = float(forecast['windSpeed']['@mps'])
  76. windspeed_beaufort = int(forecast['windSpeed']['@beaufort'])
  77. windstrength = _WIND_STRENGTHS[windspeed_beaufort]
  78. winddirection = _WIND_DIRECTIONS[forecast['windDirection']['@name']]
  79. output.tts('%s from %s' % (windstrength, winddirection))
  80. time.sleep(1)
  81. if 'precipitation' in forecast:
  82. v = float(forecast['precipitation']['@value'])
  83. if v > 0:
  84. output.tts('precipitation: %.1f' % v)