Skip to content

Commit

Permalink
Fix potential issue with unit conversions in group sensor (#1656)
Browse files Browse the repository at this point in the history
* Fix potential issue with unit conversions in group sensor

* cleanup
  • Loading branch information
bramstroker committed Apr 30, 2023
1 parent f708158 commit 413ef55
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions custom_components/powercalc/sensors/group.py
Expand Up @@ -523,6 +523,7 @@ def on_state_change(self, event: Event) -> None:
self.async_schedule_update_ha_state(True)

def _get_state_value_in_native_unit(self, state: State) -> Decimal:
"""Convert value of member entity state to match the unit of measurement of the group sensor"""
value = float(state.state)
unit_of_measurement = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
if (
Expand Down Expand Up @@ -555,7 +556,6 @@ def calculate_new_state(self, member_states: list[State]) -> Decimal:
values = [
self._get_state_value_in_native_unit(state)
for state in member_states
if state is not None
]
return Decimal(sum([value for value in values if value is not None]))

Expand Down Expand Up @@ -588,6 +588,7 @@ def __init__(

@callback
def async_reset(self) -> None:
"""Reset the group sensor and underlying member sensor when supported"""
_LOGGER.debug(f"{self.entity_id}: Reset grouped energy sensor")
for entity_id in self._entities:
_LOGGER.debug(f"Resetting {entity_id}")
Expand All @@ -611,10 +612,10 @@ def calculate_new_state(self, member_states: list[State]) -> Decimal:
Calculate the new group energy sensor state
For each member sensor we calculate the delta by looking at the previous known state and compare it to the current.
"""
if self.state is None:
if self._attr_native_value is None:
group_sum = Decimal(0)
else:
group_sum = Decimal(self.state)
group_sum = Decimal(self._attr_native_value)
_LOGGER.debug(f"Current energy group value {self.entity_id}: {group_sum}")
for entity_state in member_states:
prev_state = self._prev_state_store.get_entity_state(entity_state.entity_id)
Expand All @@ -623,7 +624,7 @@ def calculate_new_state(self, member_states: list[State]) -> Decimal:
if prev_state:
prev_state_value = self._get_state_value_in_native_unit(prev_state)
else:
prev_state_value = cur_state_value if self.state else Decimal(0)
prev_state_value = cur_state_value if self._attr_native_value else Decimal(0)
self._prev_state_store.set_entity_state(
entity_state.entity_id, entity_state
)
Expand Down

0 comments on commit 413ef55

Please sign in to comment.