From 049811601f17c49e2c22fb4f910ac8cb443c52cb Mon Sep 17 00:00:00 2001 From: Jakob Schlyter Date: Sat, 9 Nov 2024 17:02:03 +0100 Subject: [PATCH] improve ImageEntity URL processing --- custom_components/polestar_api/image.py | 26 +++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/custom_components/polestar_api/image.py b/custom_components/polestar_api/image.py index 8c7e2bc..e4379fb 100644 --- a/custom_components/polestar_api/image.py +++ b/custom_components/polestar_api/image.py @@ -2,21 +2,27 @@ from __future__ import annotations -import datetime import logging from dataclasses import dataclass -from functools import cached_property from typing import Final +import homeassistant.util.dt as dt_util from homeassistant.components.image import ImageEntity, ImageEntityDescription from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.typing import UndefinedType from .const import DOMAIN as POLESTAR_API_DOMAIN from .data import PolestarConfigEntry from .entity import PolestarEntity from .polestar import PolestarCar +try: + from propcache import cached_property +except ImportError: + from functools import cached_property + + _LOGGER = logging.getLogger(__name__) @@ -82,11 +88,19 @@ def __init__( f"polestar_{car.get_unique_id()}_{entity_description.key}" ) self._attr_translation_key = f"polestar_{entity_description.key}" - self._attr_image_last_updated = datetime.datetime.now() @cached_property - def image_url(self) -> str | None: + def image_url(self) -> str | None | UndefinedType: """Return the image URL.""" - return self.car.get_value( - self.entity_description.query, self.entity_description.field_name + value = self.car.get_value( + query=self.entity_description.query, + field_name=self.entity_description.field_name, ) + if value is None: + _LOGGER.debug("No URL found") + elif isinstance(value, str) and value != self._attr_image_url: + _LOGGER.debug("Returning URL %s", value) + self._attr_image_url = value + self._attr_image_last_updated = dt_util.utcnow() + return value + return self._attr_image_url