@@ -640,7 +640,7 @@ async def _energy_log_records_load_from_cache(self) -> bool: # noqa: PLR0912
640640
641641 # Sort and prune the records loaded from cache
642642 sorted_logs : dict [int , dict [int , tuple [datetime , int ]]] = {}
643- skip_before = datetime .now (tz = UTC ) - timedelta (hours = DAY_IN_HOURS )
643+ skip_before = datetime .now (tz = UTC ) - timedelta (hours = MAX_LOG_HOURS )
644644 sorted_addresses = sorted (restored_logs .keys (), reverse = True )
645645 for address in sorted_addresses :
646646 sorted_slots = sorted (restored_logs [address ].keys (), reverse = True )
@@ -687,18 +687,17 @@ async def _energy_log_records_save_to_cache(self) -> None:
687687 logs : dict [int , dict [int , PulseLogRecord ]] = (
688688 self ._energy_counters .get_pulse_logs ()
689689 )
690- cached_logs = ""
691- # logs is already sorted in reverse
690+ # Efficiently serialize newest-first (logs is already sorted)
691+ records : list [ str ] = []
692692 for address , record in logs .items ():
693- for slot in record :
694- log = record [slot ]
695- if cached_logs != "" :
696- cached_logs += "|"
697- cached_logs += f"{ address } :{ slot } :{ log .timestamp .year } "
698- cached_logs += f"-{ log .timestamp .month } -{ log .timestamp .day } "
699- cached_logs += f"-{ log .timestamp .hour } -{ log .timestamp .minute } "
700- cached_logs += f"-{ log .timestamp .second } :{ log .pulses } "
701-
693+ for slot , log in record .items ():
694+ records .append (
695+ f"{ address } :{ slot } :{ log .timestamp .year } "
696+ f"-{ log .timestamp .month } -{ log .timestamp .day } "
697+ f"-{ log .timestamp .hour } -{ log .timestamp .minute } "
698+ f"-{ log .timestamp .second } :{ log .pulses } "
699+ )
700+ cached_logs = "|" .join (records )
702701 _LOGGER .debug ("Saving energy logrecords to cache for %s" , self ._mac_in_str )
703702 self ._set_cache (CACHE_ENERGY_COLLECTION , cached_logs )
704703
@@ -722,16 +721,20 @@ async def _energy_log_record_update_state(
722721 log_cache_record += f"-{ timestamp .hour } -{ timestamp .minute } "
723722 log_cache_record += f"-{ timestamp .second } :{ pulses } "
724723 if (cached_logs := self ._get_cache (CACHE_ENERGY_COLLECTION )) is not None :
725- if log_cache_record not in cached_logs :
724+ entries = cached_logs .split ("|" ) if cached_logs else []
725+ if log_cache_record not in entries :
726726 _LOGGER .debug (
727727 "Adding logrecord (%s, %s) to cache of %s" ,
728728 str (address ),
729729 str (slot ),
730730 self ._mac_in_str ,
731731 )
732- self ._set_cache (
733- CACHE_ENERGY_COLLECTION , log_cache_record + "|" + cached_logs
732+ new_cache = (
733+ f"{ log_cache_record } |{ cached_logs } "
734+ if cached_logs
735+ else log_cache_record
734736 )
737+ self ._set_cache (CACHE_ENERGY_COLLECTION , new_cache )
735738 return True
736739
737740 _LOGGER .debug (
0 commit comments