refactor: Update integration version handling in TibberPrices components

This commit is contained in:
Julian Pawlowski 2025-11-07 23:43:39 +00:00
parent 6b2c45d52c
commit df9fb37fe4
6 changed files with 17 additions and 10 deletions

View file

@ -56,16 +56,21 @@ async def async_setup_entry(
# Register services when a config entry is loaded # Register services when a config entry is loaded
async_setup_services(hass) async_setup_services(hass)
integration = async_get_loaded_integration(hass, entry.domain)
coordinator = TibberPricesDataUpdateCoordinator( coordinator = TibberPricesDataUpdateCoordinator(
hass=hass, hass=hass,
config_entry=entry, config_entry=entry,
version=integration.version,
) )
entry.runtime_data = TibberPricesData( entry.runtime_data = TibberPricesData(
client=TibberPricesApiClient( client=TibberPricesApiClient(
access_token=entry.data[CONF_ACCESS_TOKEN], access_token=entry.data[CONF_ACCESS_TOKEN],
session=async_get_clientsession(hass), session=async_get_clientsession(hass),
version=integration.version,
), ),
integration=async_get_loaded_integration(hass, entry.domain), integration=integration,
coordinator=coordinator, coordinator=coordinator,
) )

View file

@ -15,8 +15,6 @@ import aiohttp
from homeassistant.const import __version__ as ha_version from homeassistant.const import __version__ as ha_version
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from .const import VERSION
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
HTTP_BAD_REQUEST = 400 HTTP_BAD_REQUEST = 400
@ -273,12 +271,12 @@ def _is_data_empty(data: dict, query_type: str) -> bool:
return is_empty return is_empty
def _prepare_headers(access_token: str) -> dict[str, str]: def _prepare_headers(access_token: str, version: str) -> dict[str, str]:
"""Prepare headers for API request.""" """Prepare headers for API request."""
return { return {
"Authorization": f"Bearer {access_token}", "Authorization": f"Bearer {access_token}",
"Accept": "application/json", "Accept": "application/json",
"User-Agent": f"HomeAssistant/{ha_version} tibber_prices/{VERSION}", "User-Agent": f"HomeAssistant/{ha_version} tibber_prices/{version}",
} }
@ -361,10 +359,12 @@ class TibberPricesApiClient:
self, self,
access_token: str, access_token: str,
session: aiohttp.ClientSession, session: aiohttp.ClientSession,
version: str,
) -> None: ) -> None:
"""Tibber API Client.""" """Tibber API Client."""
self._access_token = access_token self._access_token = access_token
self._session = session self._session = session
self._version = version
self._request_semaphore = asyncio.Semaphore(2) # Max 2 concurrent requests self._request_semaphore = asyncio.Semaphore(2) # Max 2 concurrent requests
self._last_request_time = dt_util.now() self._last_request_time = dt_util.now()
self._min_request_interval = timedelta(seconds=1) # Min 1 second between requests self._min_request_interval = timedelta(seconds=1) # Min 1 second between requests
@ -798,7 +798,7 @@ class TibberPricesApiClient:
query_type: QueryType = QueryType.USER, query_type: QueryType = QueryType.USER,
) -> Any: ) -> Any:
"""Get information from the API with rate limiting and retry logic.""" """Get information from the API with rate limiting and retry logic."""
headers = headers or _prepare_headers(self._access_token) headers = headers or _prepare_headers(self._access_token, self._version)
last_error: Exception | None = None last_error: Exception | None = None
for retry in range(self._max_retries + 1): for retry in range(self._max_retries + 1):

View file

@ -30,6 +30,7 @@ from homeassistant.helpers.selector import (
TextSelectorConfig, TextSelectorConfig,
TextSelectorType, TextSelectorType,
) )
from homeassistant.loader import async_get_integration
from .api import ( from .api import (
TibberPricesApiClient, TibberPricesApiClient,
@ -311,9 +312,11 @@ class TibberPricesFlowHandler(ConfigFlow, domain=DOMAIN):
async def _get_viewer_details(self, access_token: str) -> dict: async def _get_viewer_details(self, access_token: str) -> dict:
"""Validate credentials and return information about the account (viewer object).""" """Validate credentials and return information about the account (viewer object)."""
integration = await async_get_integration(self.hass, DOMAIN)
client = TibberPricesApiClient( client = TibberPricesApiClient(
access_token=access_token, access_token=access_token,
session=async_create_clientsession(self.hass), session=async_create_clientsession(self.hass),
version=integration.version,
) )
result = await client.async_get_viewer_details() result = await client.async_get_viewer_details()
return result["viewer"] return result["viewer"]

View file

@ -16,9 +16,6 @@ from homeassistant.const import (
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
# Version should match manifest.json
VERSION = "0.1.0"
DOMAIN = "tibber_prices" DOMAIN = "tibber_prices"
CONF_EXTENDED_DESCRIPTIONS = "extended_descriptions" CONF_EXTENDED_DESCRIPTIONS = "extended_descriptions"
CONF_BEST_PRICE_FLEX = "best_price_flex" CONF_BEST_PRICE_FLEX = "best_price_flex"

View file

@ -116,6 +116,7 @@ class TibberPricesDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
self, self,
hass: HomeAssistant, hass: HomeAssistant,
config_entry: ConfigEntry, config_entry: ConfigEntry,
version: str,
) -> None: ) -> None:
"""Initialize the coordinator.""" """Initialize the coordinator."""
super().__init__( super().__init__(
@ -129,6 +130,7 @@ class TibberPricesDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
self.api = TibberPricesApiClient( self.api = TibberPricesApiClient(
access_token=config_entry.data[CONF_ACCESS_TOKEN], access_token=config_entry.data[CONF_ACCESS_TOKEN],
session=aiohttp_client.async_get_clientsession(hass), session=aiohttp_client.async_get_clientsession(hass),
version=version,
) )
# Storage for persistence # Storage for persistence

View file

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "tibber_prices" name = "tibber_prices"
version = "0.1.0" version = "0.0.0" # Version is managed in manifest.json only
requires-python = ">=3.13" requires-python = ">=3.13"
[tool.setuptools] [tool.setuptools]