Skip to content
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
64 changes: 59 additions & 5 deletions src/data/energy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import {
addDays,
addHours,
addMilliseconds,
addMonths,
differenceInDays,
endOfToday,
endOfYesterday,
Expand All @@ -14,9 +17,9 @@ import { ConfigEntry, getConfigEntries } from "./config_entries";
import { subscribeEntityRegistry } from "./entity_registry";
import {
fetchStatistics,
getStatisticMetadata,
Statistics,
StatisticsMetaData,
getStatisticMetadata,
} from "./history";

const energyCollectionKeys: (string | undefined)[] = [];
Expand Down Expand Up @@ -232,19 +235,24 @@ export const energySourcesByType = (prefs: EnergyPreferences) =>
export interface EnergyData {
start: Date;
end?: Date;
startCompare?: Date;
endCompare?: Date;
prefs: EnergyPreferences;
info: EnergyInfo;
stats: Statistics;
statsCompare: Statistics;
co2SignalConfigEntry?: ConfigEntry;
co2SignalEntity?: string;
fossilEnergyConsumption?: FossilEnergyConsumption;
fossilEnergyConsumptionCompare?: FossilEnergyConsumption;
}

const getEnergyData = async (
hass: HomeAssistant,
prefs: EnergyPreferences,
start: Date,
end?: Date
end?: Date,
compare?: boolean
): Promise<EnergyData> => {
const [configEntries, entityRegistryEntries, info] = await Promise.all([
getConfigEntries(hass, { domain: "co2signal" }),
Expand Down Expand Up @@ -350,6 +358,8 @@ const getEnergyData = async (
}

const dayDifference = differenceInDays(end || new Date(), start);
const period =
dayDifference > 35 ? "month" : dayDifference > 2 ? "day" : "hour";
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

😬


// Subtract 1 hour from start to get starting point data
const startMinHour = addHours(start, -1);
Expand All @@ -359,10 +369,34 @@ const getEnergyData = async (
startMinHour,
end,
statIDs,
dayDifference > 35 ? "month" : dayDifference > 2 ? "day" : "hour"
period
);

let statsCompare;
let startCompare;
let endCompare;
if (compare) {
if (dayDifference > 27 && dayDifference < 32) {
// When comparing a month, we want to start at the begining of the month
startCompare = addMonths(start, -1);
} else {
startCompare = addDays(start, (dayDifference + 1) * -1);
}

const compareStartMinHour = addHours(startCompare, -1);
endCompare = addMilliseconds(start, -1);

statsCompare = await fetchStatistics(
hass!,
compareStartMinHour,
endCompare,
statIDs,
period
);
}

let fossilEnergyConsumption: FossilEnergyConsumption | undefined;
let fossilEnergyConsumptionCompare: FossilEnergyConsumption | undefined;

if (co2SignalEntity !== undefined) {
fossilEnergyConsumption = await getFossilEnergyConsumption(
Expand All @@ -373,6 +407,16 @@ const getEnergyData = async (
end,
dayDifference > 35 ? "month" : dayDifference > 2 ? "day" : "hour"
);
if (compare) {
fossilEnergyConsumptionCompare = await getFossilEnergyConsumption(
hass!,
startCompare,
consumptionStatIDs,
co2SignalEntity,
endCompare,
dayDifference > 35 ? "month" : dayDifference > 2 ? "day" : "hour"
);
}
}

Object.values(stats).forEach((stat) => {
Expand All @@ -388,15 +432,19 @@ const getEnergyData = async (
}
});

const data = {
const data: EnergyData = {
start,
end,
startCompare,
endCompare,
info,
prefs,
stats,
statsCompare,
co2SignalConfigEntry,
co2SignalEntity,
fossilEnergyConsumption,
fossilEnergyConsumptionCompare,
};

return data;
Expand All @@ -405,9 +453,11 @@ const getEnergyData = async (
export interface EnergyCollection extends Collection<EnergyData> {
start: Date;
end?: Date;
compare?: boolean;
prefs?: EnergyPreferences;
clearPrefs(): void;
setPeriod(newStart: Date, newEnd?: Date): void;
setCompare(compare: boolean): void;
_refreshTimeout?: number;
_updatePeriodTimeout?: number;
_active: number;
Expand Down Expand Up @@ -478,7 +528,8 @@ export const getEnergyDataCollection = (
hass,
collection.prefs,
collection.start,
collection.end
collection.end,
collection.compare
);
}
) as EnergyCollection;
Expand Down Expand Up @@ -534,6 +585,9 @@ export const getEnergyDataCollection = (
collection._updatePeriodTimeout = undefined;
}
};
collection.setCompare = (compare: boolean) => {
collection.compare = compare;
};
return collection;
};

Expand Down
9 changes: 3 additions & 6 deletions src/panels/energy/ha-panel-energy.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import "@polymer/app-layout/app-header/app-header";
import "@polymer/app-layout/app-toolbar/app-toolbar";
import "@material/mwc-tab";
import "@material/mwc-tab-bar";
import {
css,
CSSResultGroup,
Expand All @@ -12,14 +10,13 @@ import {
} from "lit";
import { customElement, property, state } from "lit/decorators";
import "../../components/ha-menu-button";
import { LovelaceConfig } from "../../data/lovelace";
import "../../layouts/ha-app-layout";

import { haStyle } from "../../resources/styles";
import "../lovelace/views/hui-view";
import { HomeAssistant } from "../../types";
import { Lovelace } from "../lovelace/types";
import { LovelaceConfig } from "../../data/lovelace";
import "../lovelace/components/hui-energy-period-selector";
import { Lovelace } from "../lovelace/types";
import "../lovelace/views/hui-view";

const LOVELACE_CONFIG: LovelaceConfig = {
views: [
Expand Down
5 changes: 5 additions & 0 deletions src/panels/energy/strategies/energy-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ export class EnergyStrategy {
});
}

view.cards!.push({
type: "energy-compare",
collection_key: "energy_dashboard",
});

// Only include if we have a grid source.
if (hasGrid) {
view.cards!.push({
Expand Down
106 changes: 106 additions & 0 deletions src/panels/lovelace/cards/energy/hui-energy-compare-card.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { differenceInDays, endOfDay } from "date-fns";
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
import { differenceInDays, endOfDay } from "date-fns";
import { differenceInDays, endOfDay } from "date-fns/esm";

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It should already use that as it has:

  "main": "index.js",
  "module": "esm/index.js",

in package.json?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Oh. Well I just fixed it everywhere else 😅

import { UnsubscribeFunc } from "home-assistant-js-websocket";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import { formatDate } from "../../../../common/datetime/format_date";
import { EnergyData, getEnergyDataCollection } from "../../../../data/energy";
import { SubscribeMixin } from "../../../../mixins/subscribe-mixin";
import { HomeAssistant } from "../../../../types";
import { LovelaceCard } from "../../types";
import { EnergyCardBaseConfig } from "../types";

@customElement("hui-energy-compare-card")
export class HuiEnergyCompareCard
extends SubscribeMixin(LitElement)
implements LovelaceCard
{
@property({ attribute: false }) public hass!: HomeAssistant;

@state() private _config?: EnergyCardBaseConfig;

@state() private _start?: Date;

@state() private _end?: Date;

@state() private _startCompare?: Date;

@state() private _endCompare?: Date;

public getCardSize(): Promise<number> | number {
return 1;
}

public setConfig(config: EnergyCardBaseConfig): void {
this._config = config;
}

protected hassSubscribeRequiredHostProps = ["_config"];

public hassSubscribe(): UnsubscribeFunc[] {
return [
getEnergyDataCollection(this.hass, {
key: this._config!.collection_key,
}).subscribe((data) => this._update(data)),
];
}

protected render(): TemplateResult {
if (!this._startCompare || !this._endCompare) {
return html``;
}

const dayDifference = differenceInDays(
this._endCompare,
this._startCompare
);

return html`
<ha-alert dismissable @alert-dismissed-clicked=${this._stopCompare}>
You are comparing the period
<b
>${formatDate(this._start!, this.hass.locale)}${dayDifference > 0
? ` -
${formatDate(this._end || endOfDay(new Date()), this.hass.locale)}`
: ""}</b
>
with period
<b
>${formatDate(this._startCompare, this.hass.locale)}${dayDifference >
0
? ` -
${formatDate(this._endCompare, this.hass.locale)}`
: ""}</b
>
</ha-alert>
`;
}

private _update(data: EnergyData): void {
this._start = data.start;
this._end = data.end;
this._startCompare = data.startCompare;
this._endCompare = data.endCompare;
}

private _stopCompare(): void {
const energyCollection = getEnergyDataCollection(this.hass, {
key: this._config!.collection_key,
});
energyCollection.setCompare(false);
energyCollection.refresh();
}

static get styles(): CSSResultGroup {
return css`
mwc-button {
width: max-content;
}
`;
}
}

declare global {
interface HTMLElementTagNameMap {
"hui-energy-compare-card": HuiEnergyCompareCard;
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { html, LitElement, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import { HomeAssistant } from "../../../../types";
import { LovelaceCard } from "../../types";
import { EnergyDevicesGraphCardConfig } from "../types";
import { EnergyCardBaseConfig } from "../types";
import "../../components/hui-energy-period-selector";

@customElement("hui-energy-date-selection-card")
Expand All @@ -12,13 +12,13 @@ export class HuiEnergyDateSelectionCard
{
@property({ attribute: false }) public hass!: HomeAssistant;

@state() private _config?: EnergyDevicesGraphCardConfig;
@state() private _config?: EnergyCardBaseConfig;

public getCardSize(): Promise<number> | number {
return 1;
}

public setConfig(config: EnergyDevicesGraphCardConfig): void {
public setConfig(config: EnergyCardBaseConfig): void {
this._config = config;
}

Expand All @@ -34,10 +34,6 @@ export class HuiEnergyDateSelectionCard
></hui-energy-period-selector>
`;
}

static get styles(): CSSResultGroup {
return css``;
}
}

declare global {
Expand Down
Loading