Skip to content

Commit eb07f21

Browse files
committed
energy_log_update(): check if the timestamp of the log is recent
1 parent 4fcad5c commit eb07f21

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,
@@ -581,7 +582,14 @@ async def energy_log_update(self, address: int | None) -> tuple[bool, bool]:
581582
if log_timestamp is None or log_pulses is None:
582583
self._energy_counters.add_empty_log(response.log_address, _slot)
583584
empty_log = True
584-
elif await self._energy_log_record_update_state(
585+
continue
586+
elif not self._check_timestamp_is_recent(address, _slot, log_timestamp):
587+
# Don't store an old log-record, store am empty record instead
588+
self._energy_counters.add_empty_log(response.log_address, _slot)
589+
empty_log = True
590+
continue
591+
592+
if await self._energy_log_record_update_state(
585593
response.log_address,
586594
_slot,
587595
log_timestamp.replace(tzinfo=UTC),
@@ -610,6 +618,25 @@ async def energy_log_update(self, address: int | None) -> tuple[bool, bool]:
610618

611619
return result, empty_log
612620

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

0 commit comments

Comments
 (0)