@@ -625,18 +625,25 @@ async def _energy_log_records_load_from_cache(self) -> bool: # noqa: PLR0912
625625 for log_record in log_data :
626626 log_fields = log_record .split (":" )
627627 if len (log_fields ) == 4 :
628- timestamp_energy_log = log_fields [2 ].split ("-" )
629- if len (timestamp_energy_log ) == 6 :
630- address = int (log_fields [0 ])
631- slot = int (log_fields [1 ])
632- pulses = int (log_fields [3 ])
628+ address = int (log_fields [0 ])
629+ slot = int (log_fields [1 ])
630+ pulses = int (log_fields [3 ])
631+ # Parse zero-padded timestamp, fallback to manual split
632+ try :
633+ timestamp = datetime .strptime (
634+ log_fields [2 ], "%Y-%m-%d-%H-%M-%S"
635+ ).replace (tzinfo = UTC )
636+ except ValueError :
637+ parts = log_fields [2 ].split ("-" )
638+ if len (parts ) != 6 :
639+ continue
633640 timestamp = datetime (
634- year = int (timestamp_energy_log [0 ]),
635- month = int (timestamp_energy_log [1 ]),
636- day = int (timestamp_energy_log [2 ]),
637- hour = int (timestamp_energy_log [3 ]),
638- minute = int (timestamp_energy_log [4 ]),
639- second = int (timestamp_energy_log [5 ]),
641+ year = int (parts [0 ]),
642+ month = int (parts [1 ]),
643+ day = int (parts [2 ]),
644+ hour = int (parts [3 ]),
645+ minute = int (parts [4 ]),
646+ second = int (parts [5 ]),
640647 tzinfo = UTC ,
641648 )
642649 if restored_logs .get (address ) is None :
@@ -696,15 +703,15 @@ async def _energy_log_records_save_to_cache(self) -> None:
696703 records : list [str ] = []
697704 for address , record in logs .items ():
698705 for slot , log in record .items ():
706+ ts = log .timestamp
699707 records .append (
700- f"{ address } :{ slot } :{ log .timestamp .year } "
701- f"-{ log .timestamp .month } -{ log .timestamp .day } "
702- f"-{ log .timestamp .hour } -{ log .timestamp .minute } "
703- f"-{ log .timestamp .second } :{ log .pulses } "
708+ f"{ address } :{ slot } :{ ts .strftime ('%Y-%m-%d-%H-%M-%S' )} :{ log .pulses } "
704709 )
705710 cached_logs = "|" .join (records )
706711 _LOGGER .debug ("Saving energy logrecords to cache for %s" , self ._mac_in_str )
707712 self ._set_cache (CACHE_ENERGY_COLLECTION , cached_logs )
713+ # Persist new cache entries to disk immediately
714+ await self .save_cache (trigger_only = True )
708715
709716 async def _energy_log_record_update_state (
710717 self ,
0 commit comments