__init__.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. """Support for Gardena Smart System devices."""
  2. import asyncio
  3. import logging
  4. from gardena.exceptions.authentication_exception import AuthenticationException
  5. from gardena.smart_system import SmartSystem
  6. from homeassistant.config_entries import ConfigEntry
  7. from homeassistant.const import (
  8. CONF_CLIENT_ID,
  9. CONF_CLIENT_SECRET,
  10. EVENT_HOMEASSISTANT_STOP,
  11. )
  12. from homeassistant.core import HomeAssistant
  13. from oauthlib.oauth2.rfc6749.errors import (
  14. AccessDeniedError,
  15. InvalidClientError,
  16. MissingTokenError,
  17. )
  18. from .const import (
  19. DOMAIN,
  20. GARDENA_LOCATION,
  21. GARDENA_SYSTEM,
  22. )
  23. _LOGGER = logging.getLogger(__name__)
  24. PLATFORMS = ["vacuum", "sensor", "switch", "binary_sensor"]
  25. async def async_setup(hass: HomeAssistant, config: dict):
  26. """Set up the Gardena Smart System integration."""
  27. if DOMAIN not in hass.data:
  28. hass.data[DOMAIN] = {}
  29. return True
  30. async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
  31. _LOGGER.debug("Setting up Gardena Smart System component")
  32. gardena_system = GardenaSmartSystem(
  33. hass,
  34. client_id=entry.data[CONF_CLIENT_ID],
  35. client_secret=entry.data[CONF_CLIENT_SECRET],
  36. )
  37. try:
  38. await gardena_system.start()
  39. except AccessDeniedError as ex:
  40. _LOGGER.error('Got Access Denied Error when setting up Gardena Smart System: %s', ex)
  41. return False
  42. except InvalidClientError as ex:
  43. _LOGGER.error('Got Invalid Client Error when setting up Gardena Smart System: %s', ex)
  44. return False
  45. except MissingTokenError as ex:
  46. _LOGGER.error('Got Missing Token Error when setting up Gardena Smart System: %s', ex)
  47. return False
  48. hass.data[DOMAIN][GARDENA_SYSTEM] = gardena_system
  49. hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, lambda event: hass.async_create_task(gardena_system.stop()))
  50. for component in PLATFORMS:
  51. hass.async_create_task(
  52. hass.config_entries.async_forward_entry_setup(entry, component))
  53. _LOGGER.debug("Gardena Smart System component setup finished")
  54. return True
  55. class GardenaSmartSystem:
  56. """A Gardena Smart System wrapper class."""
  57. def __init__(self, hass, client_id, client_secret):
  58. """Initialize the Gardena Smart System."""
  59. self._hass = hass
  60. self.smart_system = SmartSystem(
  61. client_id=client_id,
  62. client_secret=client_secret)
  63. async def start(self):
  64. try:
  65. _LOGGER.debug("Starting GardenaSmartSystem")
  66. await self.smart_system.authenticate()
  67. await self.smart_system.update_locations()
  68. if len(self.smart_system.locations) < 1:
  69. _LOGGER.error("No locations found")
  70. raise Exception("No locations found")
  71. # currently gardena supports only one location and gateway, so we can take the first
  72. location = list(self.smart_system.locations.values())[0]
  73. _LOGGER.debug(f"Using location: {location.name} ({location.id})")
  74. await self.smart_system.update_devices(location)
  75. self._hass.data[DOMAIN][GARDENA_LOCATION] = location
  76. _LOGGER.debug("Starting GardenaSmartSystem websocket")
  77. asyncio.create_task(self.smart_system.start_ws(self._hass.data[DOMAIN][GARDENA_LOCATION]))
  78. _LOGGER.debug("Websocket thread launched !")
  79. except AuthenticationException as ex:
  80. _LOGGER.error(
  81. f"Authentication failed : {ex.message}. You may need to check your token or create a new app in the gardena api and use the new token.")
  82. async def stop(self):
  83. _LOGGER.debug("Stopping GardenaSmartSystem")
  84. await self.smart_system.quit()