Skip to content

Commit

Permalink
Fix bug with previous value
Browse files Browse the repository at this point in the history
  • Loading branch information
woopstar committed Sep 29, 2024
1 parent c5b2fc2 commit 41f3693
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,14 @@ async def async_update(self):
ema_filter(input_value, self._previous_value, self._alpha), 2
)

# Update the previous value and last updated time
self._previous_value = input_value
# Log detailed information about the update
_LOGGER.debug(f"Input value: {input_value}, Previous EMA value: {self._previous_value}, Alpha: {self._alpha}")
_LOGGER.debug(f"New EMA value: {self._state}")

# Update the previous EMA value to the new EMA value
self._previous_value = self._state

# Update the last updated time
self._last_updated = now.isoformat()

# Update count and last update time
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
_LOGGER = logging.getLogger(__name__)


def lowpass_filter(current_value, previous_value, time_constant):
def lowpass_filter(input_value, previous_value, time_constant):
"""Apply a lowpass filter to smooth out fast fluctuations."""
alpha = time_constant / (time_constant + 1)
return alpha * current_value + (1 - alpha) * previous_value
return alpha * input_value + (1 - alpha) * previous_value


class LowpassSensor(SmoothingAnalyticsEntity, RestoreEntity):
Expand Down Expand Up @@ -100,7 +100,7 @@ async def async_update(self):
_LOGGER.warning(f"Sensor {self._input_sensor} not found.")
return
try:
current_value = float(input_state.state)
input_value = float(input_state.state)
except ValueError:
_LOGGER.error(
f"Invalid value from {self._input_sensor}: {input_state.state}"
Expand All @@ -113,11 +113,17 @@ async def async_update(self):

# Apply lowpass filter
self._state = round(
lowpass_filter(current_value, self._previous_value, self._time_constant), 2
lowpass_filter(input_value, self._previous_value, self._time_constant), 2
)

# Update the previous value and last updated time
self._previous_value = current_value
# Log detailed information about the update
_LOGGER.debug(f"Input value: {input_value}, Previous lowpass value: {self._previous_value}")
_LOGGER.debug(f"New lowpass value: {self._state}")

# Update the previous lowpass value to the new lowpass value
self._previous_value = self._state

# Update the last updated time
self._last_updated = now.isoformat()

# Update count and last update time
Expand Down

0 comments on commit 41f3693

Please sign in to comment.