Somewhat fancy voice command recognition software
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

darksky.py 4.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. # This is part of Kaylee
  2. # -- this code is licensed GPLv3
  3. # Copyright 2015-2017 Clayton G. Hobbs
  4. # Portions Copyright 2013 Jezra
  5. """Dark Sky weather plugin for Kaylee
  6. This plugin provides weather information `powered by Dark Sky
  7. <https://darksky.net/poweredby/>`__. The user must provide a key for
  8. the Dark Sky API, as well as decimal latitude and longitude::
  9. ".darksky": {
  10. "api_key": "USER_API_KEY",
  11. "latitude": USER_LATITUDE,
  12. "longitude": USER_LONGITUDE
  13. }
  14. Weather information is cached for up to ``cache_max_age`` seconds
  15. (default 1800, half an hour). To conserve API calls, the cache is not
  16. updated until the first time the user requests weather information
  17. after the cache becomes stale.
  18. """
  19. import json
  20. import os
  21. import time
  22. import requests
  23. from .pluginbase import PluginBase
  24. class Plugin(PluginBase):
  25. """Main class for the Dark Sky weather plugin"""
  26. def __init__(self, config, name):
  27. """Initialize the Dark Sky weather plugin"""
  28. super().__init__(config, name)
  29. self._cache_filename = os.path.join(config.cache_dir, 'darksky.json')
  30. self._weather_url = 'https://api.darksky.net/forecast/{}/{},{}'.format(
  31. self.options['api_key'],
  32. self.options['latitude'],
  33. self.options['longitude']
  34. )
  35. try:
  36. self._cache_max_age = self.options['cache_max_age']
  37. except KeyError:
  38. self._cache_max_age = 1800
  39. self.commands = {
  40. 'whats the temperature': self._temperature,
  41. 'whats todays low': self._todays_low,
  42. 'whats todays high': self._todays_high,
  43. 'whats tomorrows high': self._tomorrows_high,
  44. 'whats the humidity': self._relative_humidity,
  45. 'whats the weather': self._current_conditions,
  46. 'whens sunset': self._sunset_time,
  47. 'hoos your weather provider': self._provider_credits
  48. }
  49. self.corpus_strings.update(self.commands)
  50. def _format_temperature(self, temperature, unit='Fahrenheit'):
  51. """Format a temperature for the TTS system"""
  52. return '{:.1f} degrees {}'.format(temperature, unit)
  53. def _temperature(self):
  54. return self._format_temperature(self.cache['currently']['temperature'])
  55. def _todays_low(self):
  56. return self._format_temperature(
  57. self.cache['daily']['data'][0]['temperatureMin'])
  58. def _todays_high(self):
  59. return self._format_temperature(
  60. self.cache['daily']['data'][0]['temperatureMax'])
  61. def _tomorrows_high(self):
  62. return self._format_temperature(
  63. self.cache['daily']['data'][1]['temperatureMax'])
  64. def _relative_humidity(self):
  65. return '{:.0f} percent'.format(
  66. 100 * self.cache['currently']['humidity'])
  67. def _current_conditions(self):
  68. return '{}, {}, relative humidity {}'.format(
  69. self.cache['currently']['summary'],
  70. self._temperature(),
  71. self._relative_humidity())
  72. def _sunset_time(self):
  73. # Get the time in a more useful structure
  74. t = time.localtime(self.cache['daily']['data'][0]['sunsetTime'])
  75. # Format each part of the time to be pronounced nicely
  76. hour = time.strftime('%I', t)
  77. if hour[0] == '0':
  78. hour = hour[1]
  79. minute = time.strftime('%M', t)
  80. if minute[0] == '0':
  81. if minute[1] == '0':
  82. minute = "o'clock"
  83. else:
  84. minute = 'O' + minute[1]
  85. ante_post = time.strftime('%p', t)
  86. if ante_post[0] == 'A':
  87. ante_post = 'AE ' + ante_post[1]
  88. # Put the parts together
  89. return '{} {} {}'.format(hour, minute, ante_post)
  90. def _provider_credits(self):
  91. return 'Powered by Dark Sky, https://darksky.net/poweredby/.'
  92. def _update_cache_if_stale(self):
  93. try:
  94. st = os.stat(self._cache_filename)
  95. except FileNotFoundError:
  96. # If there's no cache file, we need to get one
  97. self._update_cache()
  98. else:
  99. if time.time() - st.st_mtime > self._cache_max_age:
  100. self._update_cache()
  101. def _update_cache(self):
  102. r = requests.get(self._weather_url, stream=True)
  103. if r.status_code == 200:
  104. with open(self._cache_filename, 'wb') as f:
  105. for chunk in r:
  106. f.write(chunk)
  107. def _read_cache(self):
  108. with open(self._cache_filename, 'r') as f:
  109. return json.load(f)
  110. def recognizer_finished(self, recognizer, text):
  111. """Speak reasonably up-to-date weather information"""
  112. # Is there a matching command?
  113. if text in self.corpus_strings:
  114. self.emit('processed', text)
  115. self._update_cache_if_stale()
  116. self.cache = self._read_cache()
  117. self.emit('tts', self.commands[text]())
  118. return True
  119. else:
  120. return False