diff --git a/custom_components/adaptive_cover/calculation.py b/custom_components/adaptive_cover/calculation.py index 3f84021..f157eb3 100644 --- a/custom_components/adaptive_cover/calculation.py +++ b/custom_components/adaptive_cover/calculation.py @@ -10,7 +10,7 @@ from numpy import cos, sin, tan from numpy import radians as rad -from .helpers import get_domain, get_safe_state +from .helpers import get_domain, get_safe_attribute, get_safe_state from .sun import SunData @@ -156,12 +156,9 @@ def current_temperature(self) -> float: if get_domain(self.temp_entity) != "climate": temp = get_safe_state(self.hass, self.temp_entity) else: - if self.hass.states.get(self.temp_entity).attributes[ - "current_temperature" - ]: - temp = self.hass.states.get(self.temp_entity).attributes[ - "current_temperature" - ] + temp = get_safe_attribute( + self.hass, self.temp_entity, "current_temperature" + ) return temp @property diff --git a/custom_components/adaptive_cover/coordinator.py b/custom_components/adaptive_cover/coordinator.py index 371f049..b338751 100644 --- a/custom_components/adaptive_cover/coordinator.py +++ b/custom_components/adaptive_cover/coordinator.py @@ -43,6 +43,7 @@ DOMAIN, LOGGER, ) +from .helpers import get_safe_attribute @dataclass @@ -85,8 +86,8 @@ async def async_check_entity_state_change( async def _async_update_data(self) -> AdaptiveCoverData: pos_sun = [ - self.hass.states.get("sun.sun").attributes["azimuth"], - self.hass.states.get("sun.sun").attributes["elevation"], + get_safe_attribute(self.hass, "sun.sun", "azimuth"), + get_safe_attribute(self.hass, "sun.sun", "elevation"), ] common_data = [ diff --git a/custom_components/adaptive_cover/helpers.py b/custom_components/adaptive_cover/helpers.py index 06f8e8a..ddc5e3b 100644 --- a/custom_components/adaptive_cover/helpers.py +++ b/custom_components/adaptive_cover/helpers.py @@ -11,6 +11,16 @@ def get_safe_state(hass, entity_id: str): return state.state +def get_safe_attribute(hass, entity_id: str, attribute: str): + """Get a safe value from attribute.""" + if not get_safe_state(hass, entity_id): + return None + attr_obj = hass.states.get(entity_id).attributes + if attribute not in attr_obj: + return None + return attr_obj[attribute] + + def get_domain(entity: str): """Get domain of entity.""" if entity is not None: