diff --git a/custom_components/bahmcloud_store/__init__.py b/custom_components/bahmcloud_store/__init__.py index 00dcd98..e0faf4a 100644 --- a/custom_components/bahmcloud_store/__init__.py +++ b/custom_components/bahmcloud_store/__init__.py @@ -3,9 +3,10 @@ from __future__ import annotations import logging from datetime import timedelta -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback +from homeassistant.const import EVENT_HOMEASSISTANT_STARTED from homeassistant.components.panel_custom import async_register_panel -from homeassistant.helpers.event import async_track_time_interval +from homeassistant.helpers.event import async_track_time_interval, async_call_later from homeassistant.helpers.discovery import async_load_platform from .core import BCSCore, BCSConfig, BCSError @@ -64,17 +65,30 @@ async def async_setup(hass: HomeAssistant, config: dict) -> bool: frontend_url_path="bahmcloud-store", webcomponent_name="bahmcloud-store-panel", # IMPORTANT: bump v to avoid caching old JS - module_url="/api/bahmcloud_store_static/panel.js?v=106", + module_url="/api/bahmcloud_store_static/panel.js?v=107", sidebar_title="Bahmcloud Store", sidebar_icon="mdi:store", require_admin=True, config={}, ) - try: - await core.full_refresh(source="startup") - except BCSError as e: - _LOGGER.error("Initial refresh failed: %s", e) + # IMPORTANT: + # Do NOT block Home Assistant startup with network-heavy refreshes. + # We wait until HA has fully started, then kick off the initial refresh. + async def _startup_refresh() -> None: + try: + await core.full_refresh(source="startup") + except BCSError as e: + _LOGGER.error("Initial refresh failed: %s", e) + except Exception: + _LOGGER.exception("Unexpected error during initial refresh") + + @callback + def _schedule_startup_refresh(_event=None) -> None: + # Give HA a short head-start (UI, recorder, etc.) before we start fetching lots of data. + async_call_later(hass, 30, lambda _now: hass.async_create_task(_startup_refresh())) + + hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, _schedule_startup_refresh) async def periodic(_now) -> None: try: @@ -87,4 +101,4 @@ async def async_setup(hass: HomeAssistant, config: dict) -> bool: interval_seconds = int(getattr(core, "refresh_seconds", 300) or 300) async_track_time_interval(hass, periodic, timedelta(seconds=interval_seconds)) - return True \ No newline at end of file + return True