From 7ff9b51d0f7dcd1d81b5e2f9a306d0bc15036398 Mon Sep 17 00:00:00 2001 From: rgc99 Date: Sun, 12 May 2024 03:03:17 +0000 Subject: [PATCH] Ignore initial sensor reading on flow rate calculation --- .../irrigation_unlimited.py | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/custom_components/irrigation_unlimited/irrigation_unlimited.py b/custom_components/irrigation_unlimited/irrigation_unlimited.py index ee5d897..aa79131 100644 --- a/custom_components/irrigation_unlimited/irrigation_unlimited.py +++ b/custom_components/irrigation_unlimited/irrigation_unlimited.py @@ -1151,15 +1151,16 @@ def read_sensor(self, stime: datetime) -> Decimal: f"current: {volume}" ) - # Update moving average of the rate - rate = volume_delta * Decimal(self._flow_rate_scale) / time_delta - self._flow_rate_sum += rate - self._flow_rates.append(rate) - if len(self._flow_rates) > IUVolume.SMA_WINDOW: - self._flow_rate_sum -= self._flow_rates.pop(0) - self._flow_rate_sma = ( - self._flow_rate_sum / len(self._flow_rates) - ).quantize(Decimal(10) ** -self._flow_rate_precision) + # Update moving average of the rate. Ignore initial reading. + if len(self._sensor_readings) > 1: + rate = volume_delta * Decimal(self._flow_rate_scale) / time_delta + self._flow_rate_sum += rate + self._flow_rates.append(rate) + if len(self._flow_rates) > IUVolume.SMA_WINDOW: + self._flow_rate_sum -= self._flow_rates.pop(0) + self._flow_rate_sma = ( + self._flow_rate_sum / len(self._flow_rates) + ).quantize(Decimal(10) ** -self._flow_rate_precision) # Update bookkeeping self._sensor_readings.append(IUVolumeSensorReading(stime, volume)) @@ -1201,6 +1202,9 @@ def sensor_state_change(event: HAEvent): self._start_volume = self._total_volume = None self._start_time = stime self._sensor_readings.clear() + self._flow_rates.clear() + self._flow_rate_sum = 0 + self._flow_rate_sma = None try: self._start_volume = self.read_sensor(stime)