|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | import logging |
| 4 | +import threading |
4 | 5 | from datetime import timedelta |
5 | 6 |
|
6 | 7 | import homeassistant.helpers.config_validation as cv |
@@ -45,6 +46,7 @@ def __init__( |
45 | 46 | self.today = None |
46 | 47 | self.calculator_last_sync = None |
47 | 48 | self.filtered_hourprices = [] |
| 49 | + self.lock = threading.Lock() |
48 | 50 |
|
49 | 51 | # Check incase the sensor was setup using config flow. |
50 | 52 | # This blow up if the template isnt valid. |
@@ -239,19 +241,29 @@ def get_timestamped_prices(self, hourprices): |
239 | 241 | # we could still optimize as not every calculator mode needs hourly updates |
240 | 242 | def sync_calculator(self): |
241 | 243 | 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 | + ): |
248 | 249 | self.logger.debug( |
249 | | - "new day detected: update today and filtered hourprices" |
| 250 | + "The calculator needs to be synced with the current time" |
250 | 251 | ) |
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) |
253 | 265 |
|
254 | | - self.calculator_last_sync = now |
| 266 | + self.calculator_last_sync = now |
255 | 267 |
|
256 | 268 | # ANALYSIS: filter the hourprices on which to apply the calculations based on the calculation_mode |
257 | 269 | def _filter_calculated_hourprices(self, data): |
|
0 commit comments