Skip to content

Commit 557010f

Browse files
RoelandRoeland
authored andcommitted
make the update of the filtered hourprices treadsafe and remove stale data.
1 parent e604e67 commit 557010f

File tree

2 files changed

+23
-11
lines changed

2 files changed

+23
-11
lines changed

custom_components/entsoe/coordinator.py

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import logging
4+
import threading
45
from datetime import timedelta
56

67
import homeassistant.helpers.config_validation as cv
@@ -45,6 +46,7 @@ def __init__(
4546
self.today = None
4647
self.calculator_last_sync = None
4748
self.filtered_hourprices = []
49+
self.lock = threading.Lock()
4850

4951
# Check incase the sensor was setup using config flow.
5052
# This blow up if the template isnt valid.
@@ -239,19 +241,29 @@ def get_timestamped_prices(self, hourprices):
239241
# we could still optimize as not every calculator mode needs hourly updates
240242
def sync_calculator(self):
241243
now = dt.now()
242-
if (
243-
self.calculator_last_sync is None
244-
or self.calculator_last_sync.hour != now.hour
245-
):
246-
self.logger.debug("The calculator needs to be synced with the current time")
247-
if self.today.date() != now.date():
244+
with self.lock:
245+
if (
246+
self.calculator_last_sync is None
247+
or self.calculator_last_sync.hour != now.hour
248+
):
248249
self.logger.debug(
249-
"new day detected: update today and filtered hourprices"
250+
"The calculator needs to be synced with the current time"
250251
)
251-
self.today = now.replace(hour=0, minute=0, second=0, microsecond=0)
252-
self.filtered_hourprices = self._filter_calculated_hourprices(self.data)
252+
if self.today.date() != now.date():
253+
self.logger.debug(
254+
"new day detected: update today and filtered hourprices"
255+
)
256+
self.today = now.replace(hour=0, minute=0, second=0, microsecond=0)
257+
258+
# remove stale data
259+
self.data = {
260+
hour: price
261+
for hour, price in self.data.items()
262+
if hour >= self.today - timedelta(days=1)
263+
}
264+
self.filtered_hourprices = self._filter_calculated_hourprices(self.data)
253265

254-
self.calculator_last_sync = now
266+
self.calculator_last_sync = now
255267

256268
# ANALYSIS: filter the hourprices on which to apply the calculations based on the calculation_mode
257269
def _filter_calculated_hourprices(self, data):

custom_components/entsoe/manifest.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,5 @@
77
"iot_class": "cloud_polling",
88
"issue_tracker": "https://github.com/JaccoR/hass-entso-e/issues",
99
"requirements": ["requests"],
10-
"version": "0.6.3"
10+
"version": "0.6.4"
1111
}

0 commit comments

Comments
 (0)