__init__.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. """The Solar of Things integration."""
  2. from __future__ import annotations
  3. import logging
  4. from datetime import timedelta
  5. from homeassistant.config_entries import ConfigEntry
  6. from homeassistant.const import Platform
  7. from homeassistant.core import HomeAssistant
  8. from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
  9. from .const import DOMAIN
  10. from .api import SolarOfThingsAPI
  11. _LOGGER = logging.getLogger(__name__)
  12. PLATFORMS: list[Platform] = [Platform.SENSOR, Platform.NUMBER, Platform.SELECT, Platform.SWITCH]
  13. UPDATE_INTERVAL = timedelta(minutes=5)
  14. async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
  15. """Set up Solar of Things from a config entry."""
  16. hass.data.setdefault(DOMAIN, {})
  17. # Create API instance
  18. api = SolarOfThingsAPI(
  19. iot_token=entry.data["iot_token"],
  20. station_id=entry.data.get("station_id"),
  21. device_id=entry.data.get("device_id")
  22. )
  23. # Create coordinator
  24. coordinator = SolarOfThingsDataUpdateCoordinator(
  25. hass,
  26. api=api,
  27. entry=entry,
  28. )
  29. # Fetch initial data
  30. await coordinator.async_config_entry_first_refresh()
  31. hass.data[DOMAIN][entry.entry_id] = {
  32. "coordinator": coordinator,
  33. "api": api,
  34. }
  35. # Setup platforms
  36. await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
  37. return True
  38. async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
  39. """Unload a config entry."""
  40. if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
  41. hass.data[DOMAIN].pop(entry.entry_id)
  42. return unload_ok
  43. class SolarOfThingsDataUpdateCoordinator(DataUpdateCoordinator):
  44. """Class to manage fetching Solar of Things data."""
  45. def __init__(
  46. self,
  47. hass: HomeAssistant,
  48. api: SolarOfThingsAPI,
  49. entry: ConfigEntry,
  50. ) -> None:
  51. """Initialize."""
  52. self.api = api
  53. self.entry = entry
  54. super().__init__(
  55. hass,
  56. _LOGGER,
  57. name=DOMAIN,
  58. update_interval=UPDATE_INTERVAL,
  59. )
  60. async def _async_update_data(self):
  61. """Update data via library."""
  62. try:
  63. # Fetch time-series data
  64. time_series_data = await self.hass.async_add_executor_job(
  65. self.api.fetch_latest_data
  66. )
  67. # Fetch monthly summary if station_id is available
  68. monthly_data = None
  69. if self.entry.data.get("station_id"):
  70. monthly_data = await self.hass.async_add_executor_job(
  71. self.api.fetch_monthly_summary
  72. )
  73. # Fetch device settings
  74. settings_data = await self.hass.async_add_executor_job(
  75. self.api.fetch_settings
  76. )
  77. return {
  78. "time_series": time_series_data,
  79. "monthly": monthly_data,
  80. "settings": settings_data,
  81. "station_id": self.entry.data.get("station_id"),
  82. "device_id": self.entry.data.get("device_id"),
  83. }
  84. except Exception as err:
  85. raise UpdateFailed(f"Error communicating with API: {err}")