From 4c4fddee94162dd260b1fa0684afa9f5ac99048e Mon Sep 17 00:00:00 2001 From: karwosts <32912880+karwosts@users.noreply.github.com> Date: Sat, 2 Dec 2023 14:33:04 -0800 Subject: [PATCH] Fix for energy cards not refreshing hourly (#18854) --- src/data/energy.ts | 50 ++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/src/data/energy.ts b/src/data/energy.ts index 1da926bf0ffd..fe7bf3d1a418 100644 --- a/src/data/energy.ts +++ b/src/data/energy.ts @@ -581,6 +581,28 @@ const clearEnergyCollectionPreferences = (hass: HomeAssistant) => { }); }; +const scheduleHourlyRefresh = (collection: EnergyCollection) => { + if (collection._refreshTimeout) { + clearTimeout(collection._refreshTimeout); + } + + if (collection._active && (!collection.end || collection.end > new Date())) { + // The stats are created every hour + // Schedule a refresh for 20 minutes past the hour + // If the end is larger than the current time. + const nextFetch = new Date(); + if (nextFetch.getMinutes() >= 20) { + nextFetch.setHours(nextFetch.getHours() + 1); + } + nextFetch.setMinutes(20, 0, 0); + + collection._refreshTimeout = window.setTimeout( + () => collection.refresh(), + nextFetch.getTime() - Date.now() + ); + } +}; + export const getEnergyDataCollection = ( hass: HomeAssistant, options: { prefs?: EnergyPreferences; key?: string } = {} @@ -609,28 +631,7 @@ export const getEnergyDataCollection = ( collection.prefs = await getEnergyPreferences(hass); } - if (collection._refreshTimeout) { - clearTimeout(collection._refreshTimeout); - } - - if ( - collection._active && - (!collection.end || collection.end > new Date()) - ) { - // The stats are created every hour - // Schedule a refresh for 20 minutes past the hour - // If the end is larger than the current time. - const nextFetch = new Date(); - if (nextFetch.getMinutes() >= 20) { - nextFetch.setHours(nextFetch.getHours() + 1); - } - nextFetch.setMinutes(20, 0, 0); - - collection._refreshTimeout = window.setTimeout( - () => collection.refresh(), - nextFetch.getTime() - Date.now() - ); - } + scheduleHourlyRefresh(collection); return getEnergyData( hass, @@ -647,6 +648,11 @@ export const getEnergyDataCollection = ( collection.subscribe = (subscriber: (data: EnergyData) => void) => { const unsub = origSubscribe(subscriber); collection._active++; + + if (collection._refreshTimeout === undefined) { + scheduleHourlyRefresh(collection); + } + return () => { collection._active--; if (collection._active < 1) {