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

fix: negative measurements when loading recent data #26

Merged
merged 2 commits into from
Oct 26, 2024
Merged
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
24 changes: 20 additions & 4 deletions custom_components/aigues_barcelona/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,16 +205,31 @@ async def _async_import_statistics(self, consumptions) -> None:
consumptions, key=lambda x: datetime.fromisoformat(x["datetime"])
)

# TODO: Hay que cargar datos historicos para actualizar sum_total desde el primer registro.
# Conforme tengamos más datos para representar, aparecerá el fallo para depurar.
# Retrieve the last stored value of accumulatedConsumption
last_stored_value = 0.0
all_ids = await get_db_instance(self.hass).async_add_executor_job(
list_statistic_ids, self.hass
)
for stat_id in all_ids:
if stat_id["statistic_id"] == self.internal_sensor_id:
if stat_id.get("sum") and (
last_stored_value is None or stat_id["sum"] > last_stored_value
):
last_stored_value = stat_id["sum"]

stats = list()
sum_total = 0.0
sum_total = last_stored_value
for metric in consumptions:
start_ts = datetime.fromisoformat(metric["datetime"])
start_ts = start_ts.replace(minute=0, second=0, microsecond=0) # required
# Calculate deltaConsumption
deltaConsumption = metric["accumulatedConsumption"] - last_stored_value
# Ensure deltaConsumption is positive before adding to sum_total
if deltaConsumption < 0:
_LOGGER.warn(f"Negative deltaConsumption detected: {deltaConsumption}")
deltaConsumption = 0
# round: fixes decimal with 20 digits precision
sum_total = round(sum_total + metric["deltaConsumption"], 4)
sum_total = round(sum_total + deltaConsumption, 4)
stats.append(
{
"start": start_ts,
Expand All @@ -224,6 +239,7 @@ async def _async_import_statistics(self, consumptions) -> None:
# "last_reset": start_ts,
}
)
last_stored_value = metric["accumulatedConsumption"]
metadata = {
"has_mean": False,
"has_sum": True,
Expand Down
Loading