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 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. Temperatures are read to the nearest ``temp_precision`` decimal places
  19. (default 0).
  20. """
  21. import json
  22. import os
  23. import time
  24. import requests
  25. from . import PluginBase, Handler
  26. class Plugin(PluginBase):
  27. """Main class for the Dark Sky weather plugin"""
  28. def __init__(self, config, name):
  29. """Initialize the Dark Sky weather plugin"""
  30. super().__init__(config, name)
  31. self._cache_filename = os.path.join(config.cache_dir, 'darksky.json')
  32. self._weather_url = 'https://api.darksky.net/forecast/{}/{},{}'.format(
  33. self.options['api_key'],
  34. self.options['latitude'],
  35. self.options['longitude']
  36. )
  37. try:
  38. self._cache_max_age = self.options['cache_max_age']
  39. except KeyError:
  40. self._cache_max_age = 1800
  41. try:
  42. self._temp_precision = self.options['temp_precision']
  43. except KeyError:
  44. self._temp_precision = 0
  45. self.commands = {
  46. 'whats the temperature': DarkSkyTemperatureHandler,
  47. 'whats todays high': DarkSkyTodaysHighHandler,
  48. 'whats todays low': DarkSkyTodaysLowHandler,
  49. 'whats tomorrows high': DarkSkyTomorrowsHighHandler,
  50. 'whats the humidity': DarkSkyHumidityHandler,
  51. 'whats the weather': DarkSkyCurrentConditionsHandler,
  52. 'whens sunset': DarkSkySunsetHandler,
  53. 'hoos your weather provider': DarkSkyProviderHandler
  54. }
  55. self.corpus_strings.update(self.commands)
  56. def get_handler(self, text):
  57. """Return a handler if a recognized command is heard"""
  58. if text in self.corpus_strings:
  59. return self.commands[text](1, self._cache_filename,
  60. self._weather_url, self._cache_max_age,
  61. self._temp_precision)
  62. else:
  63. return None
  64. class DarkSkyHandler(Handler):
  65. """Base class for Dark Sky plugin handlers"""
  66. def __init__(self, confidence, cache_filename, url, cache_max_age,
  67. temp_precision):
  68. super().__init__(confidence)
  69. self._cache_filename = cache_filename
  70. self._url = url
  71. self._cache_max_age = cache_max_age
  72. self._temp_precision = temp_precision
  73. def _update_cache_if_stale(self):
  74. try:
  75. st = os.stat(self._cache_filename)
  76. except FileNotFoundError:
  77. # If there's no cache file, we need to get one
  78. self._update_cache()
  79. else:
  80. if time.time() - st.st_mtime > self._cache_max_age:
  81. self._update_cache()
  82. def _update_cache(self):
  83. r = requests.get(self._url, stream=True)
  84. if r.status_code == 200:
  85. with open(self._cache_filename, 'wb') as f:
  86. for chunk in r:
  87. f.write(chunk)
  88. def _read_cache(self):
  89. with open(self._cache_filename, 'r') as f:
  90. return json.load(f)
  91. def _format_temperature(self, temperature, unit='Fahrenheit'):
  92. """Format a temperature for the TTS system"""
  93. return '{:.{prec}f} degrees {}'.format(temperature, unit,
  94. prec=self._temp_precision)
  95. def _format_percent(self, value):
  96. """Format a percentage value for the TTS system"""
  97. return '{:.0f} percent'.format(100 * value)
  98. def _format_time(self, epoch_time):
  99. """Format a time in seconds since the epoch for the TTS system"""
  100. t = time.localtime(epoch_time)
  101. # Format each part of the time to be pronounced nicely
  102. hour = time.strftime('%I', t)
  103. if hour[0] == '0':
  104. hour = hour[1]
  105. minute = time.strftime('%M', t)
  106. if minute[0] == '0':
  107. if minute[1] == '0':
  108. minute = "o'clock"
  109. else:
  110. minute = 'O' + minute[1]
  111. ante_post = time.strftime('%p', t)
  112. if ante_post[0] == 'A':
  113. ante_post = 'AE ' + ante_post[1]
  114. # Put the parts together
  115. return '{} {} {}'.format(hour, minute, ante_post)
  116. def __call__(self, tts):
  117. """Update the cache if necessary and load it"""
  118. self._update_cache_if_stale()
  119. self.cache = self._read_cache()
  120. class DarkSkyTemperatureHandler(DarkSkyHandler):
  121. """Handler to speak the current temperature"""
  122. def __call__(self, tts):
  123. """Speak the current temperature"""
  124. super().__call__(tts)
  125. tts(self._format_temperature(self.cache['currently']['temperature']))
  126. class DarkSkyTodaysHighHandler(DarkSkyHandler):
  127. """Handler to speak today's high temperature"""
  128. def __call__(self, tts):
  129. """Speak today's high"""
  130. super().__call__(tts)
  131. tts(self._format_temperature(
  132. self.cache['daily']['data'][0]['temperatureMax']))
  133. class DarkSkyTodaysLowHandler(DarkSkyHandler):
  134. """Handler to speak today's low temperature"""
  135. def __call__(self, tts):
  136. """Speak today's low"""
  137. super().__call__(tts)
  138. tts(self._format_temperature(
  139. self.cache['daily']['data'][0]['temperatureMin']))
  140. class DarkSkyTomorrowsHighHandler(DarkSkyHandler):
  141. """Handler to speak tomorrow's high temperature"""
  142. def __call__(self, tts):
  143. """Speak tomorrow's high"""
  144. super().__call__(tts)
  145. tts(self._format_temperature(
  146. self.cache['daily']['data'][1]['temperatureMax']))
  147. class DarkSkyHumidityHandler(DarkSkyHandler):
  148. """Handler to speak the current relative humidity"""
  149. def __call__(self, tts):
  150. """Speak the current relative humidity"""
  151. super().__call__(tts)
  152. tts(self._format_percent(self.cache['currently']['humidity']))
  153. class DarkSkyCurrentConditionsHandler(DarkSkyHandler):
  154. """Handler to speak the current weather conditions"""
  155. def __call__(self, tts):
  156. """Speak the current weather conditions"""
  157. super().__call__(tts)
  158. tts('{}, {}, relative humidity {}'.format(
  159. self.cache['currently']['summary'],
  160. self._format_temperature(self.cache['currently']['temperature']),
  161. self._format_percent(self.cache['currently']['humidity'])))
  162. class DarkSkySunsetHandler(DarkSkyHandler):
  163. """Handler to speak the time of sunset"""
  164. def __call__(self, tts):
  165. """Speak the time of sunset"""
  166. super().__call__(tts)
  167. tts(self._format_time(self.cache['daily']['data'][0]['sunsetTime']))
  168. class DarkSkyProviderHandler(DarkSkyHandler):
  169. """Handler to speak information about the weather provider"""
  170. def __call__(self, tts):
  171. """Speak information about the weather provider"""
  172. # No need for super since this doesn't need any weather information
  173. tts('Powered by Dark Sky, https:// dark sky .net/ powered by/.')