Skip to content

Commit 7ad4660

Browse files
committed
energy_log_update(): check if the timestamp of the log is recent
1 parent 05caf1c commit 7ad4660

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

plugwise_usb/nodes/circle.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
)
2525
from ..connection import StickController
2626
from ..constants import (
27+
DAY_IN_HOURS,
2728
DEFAULT_CONS_INTERVAL,
2829
MAX_TIME_DRIFT,
2930
MINIMAL_POWER_UPDATE,
@@ -582,7 +583,14 @@ async def energy_log_update(self, address: int | None) -> tuple[bool, bool]:
582583
if log_timestamp is None or log_pulses is None:
583584
self._energy_counters.add_empty_log(response.log_address, _slot)
584585
empty_log = True
585-
elif await self._energy_log_record_update_state(
586+
continue
587+
elif not self._check_timestamp_is_recent(address, _slot, log_timestamp):
588+
# Don't store an old log-record, store am empty record instead
589+
self._energy_counters.add_empty_log(response.log_address, _slot)
590+
empty_log = True
591+
continue
592+
593+
if await self._energy_log_record_update_state(
586594
response.log_address,
587595
_slot,
588596
log_timestamp.replace(tzinfo=UTC),
@@ -611,6 +619,25 @@ async def energy_log_update(self, address: int | None) -> tuple[bool, bool]:
611619

612620
return result, empty_log
613621

622+
def _check_timestamp_is_recent(self, address, slot, timestamp) -> bool:
623+
"""Check if the timestamp of the received log-record is recent.
624+
625+
A timestamp from within the last 24 hours is considered recent.
626+
"""
627+
if (
628+
(datetime.now(tz=UTC) - timestamp.replace(tzinfo=UTC)).total_seconds()
629+
// 3600
630+
) > DAY_IN_HOURS:
631+
_LOGGER.warning(
632+
"EnergyLog from Node %s | address %s | slot %s | timestamp %s is outdated, ignoring...",
633+
self._mac_in_str,
634+
address,
635+
slot,
636+
timestamp,
637+
)
638+
return False
639+
return True
640+
614641
async def _energy_log_records_load_from_cache(self) -> bool:
615642
"""Load energy_log_record from cache."""
616643
if (cache_data := self._get_cache(CACHE_ENERGY_COLLECTION)) is None:

0 commit comments

Comments
 (0)