Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add helper to get safe attributes #78

Merged
merged 1 commit into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions custom_components/adaptive_cover/calculation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions custom_components/adaptive_cover/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
DOMAIN,
LOGGER,
)
from .helpers import get_safe_attribute


@dataclass
Expand Down Expand Up @@ -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 = [
Expand Down
10 changes: 10 additions & 0 deletions custom_components/adaptive_cover/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down