Skip to content

Commit

Permalink
make the update of the filtered hourprices treadsafe and remove stale…
Browse files Browse the repository at this point in the history
… data.
  • Loading branch information
Roeland authored and Roeland committed Oct 12, 2024
1 parent e604e67 commit 557010f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
32 changes: 22 additions & 10 deletions custom_components/entsoe/coordinator.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import logging
import threading
from datetime import timedelta

import homeassistant.helpers.config_validation as cv
Expand Down Expand Up @@ -45,6 +46,7 @@ def __init__(
self.today = None
self.calculator_last_sync = None
self.filtered_hourprices = []
self.lock = threading.Lock()

# Check incase the sensor was setup using config flow.
# This blow up if the template isnt valid.
Expand Down Expand Up @@ -239,19 +241,29 @@ def get_timestamped_prices(self, hourprices):
# we could still optimize as not every calculator mode needs hourly updates
def sync_calculator(self):
now = dt.now()
if (
self.calculator_last_sync is None
or self.calculator_last_sync.hour != now.hour
):
self.logger.debug("The calculator needs to be synced with the current time")
if self.today.date() != now.date():
with self.lock:
if (
self.calculator_last_sync is None
or self.calculator_last_sync.hour != now.hour
):
self.logger.debug(
"new day detected: update today and filtered hourprices"
"The calculator needs to be synced with the current time"
)
self.today = now.replace(hour=0, minute=0, second=0, microsecond=0)
self.filtered_hourprices = self._filter_calculated_hourprices(self.data)
if self.today.date() != now.date():
self.logger.debug(
"new day detected: update today and filtered hourprices"
)
self.today = now.replace(hour=0, minute=0, second=0, microsecond=0)

# remove stale data
self.data = {
hour: price
for hour, price in self.data.items()
if hour >= self.today - timedelta(days=1)
}
self.filtered_hourprices = self._filter_calculated_hourprices(self.data)

self.calculator_last_sync = now
self.calculator_last_sync = now

# ANALYSIS: filter the hourprices on which to apply the calculations based on the calculation_mode
def _filter_calculated_hourprices(self, data):
Expand Down
2 changes: 1 addition & 1 deletion custom_components/entsoe/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/JaccoR/hass-entso-e/issues",
"requirements": ["requests"],
"version": "0.6.3"
"version": "0.6.4"
}

0 comments on commit 557010f

Please sign in to comment.