Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate Statistic Card with Energy Date Picker #23794

Merged
merged 4 commits into from
Feb 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 101 additions & 10 deletions src/panels/lovelace/cards/hui-statistic-card.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntity, UnsubscribeFunc } from "home-assistant-js-websocket";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
Expand All @@ -9,6 +9,7 @@ import { formatNumber } from "../../../common/number/format_number";
import "../../../components/ha-alert";
import "../../../components/ha-card";
import "../../../components/ha-state-icon";
import { getEnergyDataCollection } from "../../../data/energy";
import type { StatisticsMetaData } from "../../../data/recorder";
import {
fetchStatistic,
Expand All @@ -31,6 +32,8 @@ import type {
import type { HuiErrorCard } from "./hui-error-card";
import type { EntityCardConfig, StatisticCardConfig } from "./types";

export const PERIOD_ENERGY = "energy_date_selection";

@customElement("hui-statistic-card")
export class HuiStatisticCard extends LitElement implements LovelaceCard {
public static async getConfigElement(): Promise<LovelaceCardEditor> {
Expand Down Expand Up @@ -70,15 +73,52 @@ export class HuiStatisticCard extends LitElement implements LovelaceCard {

@state() private _error?: string;

private _energySub?: UnsubscribeFunc;

@state() private _energyStart?: Date;

@state() private _energyEnd?: Date;

private _interval?: number;

private _footerElement?: HuiErrorCard | LovelaceHeaderFooter;

public disconnectedCallback() {
super.disconnectedCallback();
this._unsubscribeEnergy();
clearInterval(this._interval);
}

public connectedCallback() {
super.connectedCallback();
if (this._config?.period === PERIOD_ENERGY) {
this._subscribeEnergy();
} else {
this._setFetchStatisticTimer();
}
}

private _subscribeEnergy() {
if (!this._energySub) {
this._energySub = getEnergyDataCollection(this.hass!, {
key: this._config?.collection_key,
}).subscribe((data) => {
this._energyStart = data.start;
this._energyEnd = data.end;
this._fetchStatistic();
});
}
}

private _unsubscribeEnergy() {
if (this._energySub) {
this._energySub();
this._energySub = undefined;
}
this._energyStart = undefined;
this._energyEnd = undefined;
}

public setConfig(config: StatisticCardConfig): void {
if (!config.entity) {
throw new Error("Entity must be specified");
Expand All @@ -99,8 +139,6 @@ export class HuiStatisticCard extends LitElement implements LovelaceCard {

this._config = config;
this._error = undefined;
this._fetchStatistic();
this._fetchMetadata();

if (this._config.footer) {
this._footerElement = createHeaderFooterElement(this._config.footer);
Expand Down Expand Up @@ -174,7 +212,9 @@ export class HuiStatisticCard extends LitElement implements LovelaceCard {
if (
changedProps.has("_value") ||
changedProps.has("_metadata") ||
changedProps.has("_error")
changedProps.has("_error") ||
changedProps.has("_energyStart") ||
changedProps.has("_energyEnd")
) {
return true;
}
Expand All @@ -184,6 +224,46 @@ export class HuiStatisticCard extends LitElement implements LovelaceCard {
return true;
}

protected willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
if (!this._config || !changedProps.has("_config")) {
return;
}
const oldConfig = changedProps.get("_config") as
| StatisticCardConfig
| undefined;

if (this.hass) {
if (this._config.period === PERIOD_ENERGY && !this._energySub) {
this._subscribeEnergy();
return;
}
if (this._config.period !== PERIOD_ENERGY && this._energySub) {
this._unsubscribeEnergy();
this._setFetchStatisticTimer();
return;
}
if (
this._config.period === PERIOD_ENERGY &&
this._energySub &&
changedProps.has("_config") &&
oldConfig?.collection_key !== this._config.collection_key
) {
this._unsubscribeEnergy();
this._subscribeEnergy();
}
}

if (
changedProps.has("_config") &&
oldConfig?.entity !== this._config.entity
) {
this._fetchMetadata().then(() => {
this._setFetchStatisticTimer();
});
}
}
Comment on lines +236 to +264
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This logic seems off. If you have this._config.period === PERIOD_ENERGY and change the entity, I think this._setFetchStatisticTimer() will be called

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that's ok/intended.

_setFetchStatisticTimer fetches the statistic, and then schedules the timer only if period !== PERIOD_ENERGY. If it is using energy mode it will continue being subscribed to the energy callback.

To be honest I'm not even sure if anything in this function even really matters... it looks like changing anything in the config destroys the entire card element and rebuilds a new one from scratch. Like every time I touch the config I see disconnectedCallback and firstUpdated in hui-statistic-card being called again. I didn't think that was supposed to happen, seems odd. Of course would still like to get it to be correct, but that surprised me.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recreating the card makes sense to me to avoid all this. But now I wonder why we bother with this update logic in all the cards. Perhaps custom things like config-template-card trigger this.
Anyway, approving this since it works.


protected firstUpdated() {
this._fetchStatistic();
this._fetchMetadata();
Expand All @@ -210,20 +290,31 @@ export class HuiStatisticCard extends LitElement implements LovelaceCard {
}
}

private _setFetchStatisticTimer() {
this._fetchStatistic();
// statistics are created every hour
clearInterval(this._interval);
if (this._config?.period !== PERIOD_ENERGY) {
this._interval = window.setInterval(
() => this._fetchStatistic(),
5 * 1000 * 60
);
}
}

private async _fetchStatistic() {
if (!this.hass || !this._config) {
return;
}
clearInterval(this._interval);
this._interval = window.setInterval(
() => this._fetchStatistic(),
5 * 1000 * 60
);
try {
const stats = await fetchStatistic(
this.hass,
this._config.entity,
this._config.period
this._energyStart && this._energyEnd
? { fixed_period: { start: this._energyStart, end: this._energyEnd } }
: typeof this._config?.period === "object"
? this._config?.period
: {}
);
this._value = stats[this._config!.stat_type];
this._error = undefined;
Expand Down
12 changes: 7 additions & 5 deletions src/panels/lovelace/cards/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -379,11 +379,13 @@ export interface StatisticsGraphCardConfig extends EnergyCardBaseConfig {
export interface StatisticCardConfig extends LovelaceCardConfig {
name?: string;
entities: (EntityConfig | string)[];
period: {
fixed_period?: { start: string; end: string };
calendar?: { period: string; offset: number };
rolling_window?: { duration: HaDurationData; offset: HaDurationData };
};
period:
| {
fixed_period?: { start: string; end: string };
calendar?: { period: string; offset: number };
rolling_window?: { duration: HaDurationData; offset: HaDurationData };
}
| "energy_date_selection";
stat_type: keyof Statistic;
theme?: string;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const cardConfigStruct = assign(
period: optional(any()),
theme: optional(string()),
footer: optional(headerFooterConfigStructs),
collection_key: optional(string()),
})
);

Expand Down
Loading