Skip to content

Commit

Permalink
Clean up integration sensor (#98552)
Browse files Browse the repository at this point in the history
always update
  • Loading branch information
dgomes committed Aug 18, 2023
1 parent 268e524 commit f96446c
Showing 1 changed file with 6 additions and 15 deletions.
21 changes: 6 additions & 15 deletions homeassistant/components/integration/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,29 +298,22 @@ def calc_integration(event: EventType[EventStateChangedData]) -> None:
old_state = event.data["old_state"]
new_state = event.data["new_state"]

# We may want to update our state before an early return,
# based on the source sensor's unit_of_measurement
# or device_class.
update_state = False

if (
source_state := self.hass.states.get(self._sensor_source_id)
) is None or source_state.state == STATE_UNAVAILABLE:
self._attr_available = False
update_state = True
else:
self._attr_available = True
self.async_write_ha_state()
return

self._attr_available = True

if old_state is None or new_state is None:
# we can't calculate the elapsed time, so we can't calculate the integral
return

unit = new_state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
if unit is not None:
new_unit_of_measurement = self._unit(unit)
if self._unit_of_measurement != new_unit_of_measurement:
self._unit_of_measurement = new_unit_of_measurement
update_state = True
self._unit_of_measurement = self._unit(unit)

if (
self.device_class is None
Expand All @@ -329,10 +322,8 @@ def calc_integration(event: EventType[EventStateChangedData]) -> None:
):
self._attr_device_class = SensorDeviceClass.ENERGY
self._attr_icon = None
update_state = True

if update_state:
self.async_write_ha_state()
self.async_write_ha_state()

try:
# integration as the Riemann integral of previous measures.
Expand Down

0 comments on commit f96446c

Please sign in to comment.