Skip to content

Commit

Permalink
Remove calculation of change from frontend (home-assistant#16477)
Browse files Browse the repository at this point in the history
  • Loading branch information
emontnemery committed May 11, 2023
1 parent d66ca04 commit 72403f4
Show file tree
Hide file tree
Showing 11 changed files with 55 additions and 170 deletions.
28 changes: 3 additions & 25 deletions src/components/chart/statistics-chart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,7 @@ import {
import type { HomeAssistant } from "../../types";
import "./ha-chart-base";

export type ExtendedStatisticType = StatisticType | "change";

export const supportedStatTypeMap: Record<
ExtendedStatisticType,
StatisticType
> = {
export const supportedStatTypeMap: Record<StatisticType, StatisticType> = {
mean: "mean",
min: "min",
max: "max",
Expand All @@ -46,15 +41,6 @@ export const supportedStatTypeMap: Record<
change: "sum",
};

export const statTypeMap: Record<ExtendedStatisticType, StatisticType> = {
mean: "mean",
min: "min",
max: "max",
sum: "sum",
state: "state",
change: "sum",
};

@customElement("statistics-chart")
class StatisticsChart extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
Expand All @@ -72,7 +58,7 @@ class StatisticsChart extends LitElement {

@property({ attribute: false }) public endTime?: Date;

@property({ type: Array }) public statTypes: Array<ExtendedStatisticType> = [
@property({ type: Array }) public statTypes: Array<StatisticType> = [
"sum",
"min",
"mean",
Expand Down Expand Up @@ -358,7 +344,7 @@ class StatisticsChart extends LitElement {
: this.statTypes;

sortedTypes.forEach((type) => {
if (statisticsHaveType(stats, statTypeMap[type])) {
if (statisticsHaveType(stats, type)) {
const band = drawBands && (type === "min" || type === "max");
statTypes.push(type);
statDataSets.push({
Expand Down Expand Up @@ -391,7 +377,6 @@ class StatisticsChart extends LitElement {
let prevDate: Date | null = null;
// Process chart data.
let firstSum: number | null | undefined = null;
let prevSum: number | null | undefined = null;
stats.forEach((stat) => {
const startDate = new Date(stat.start);
if (prevDate === startDate) {
Expand All @@ -408,13 +393,6 @@ class StatisticsChart extends LitElement {
} else {
val = (stat.sum || 0) - firstSum;
}
} else if (type === "change") {
if (prevSum === null || prevSum === undefined) {
prevSum = stat.sum;
return;
}
val = (stat.sum || 0) - prevSum;
prevSum = stat.sum;
} else {
val = stat[type];
}
Expand Down
58 changes: 10 additions & 48 deletions src/data/energy.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import {
addDays,
addHours,
addMilliseconds,
addMonths,
differenceInDays,
endOfToday,
endOfYesterday,
Expand Down Expand Up @@ -389,9 +387,6 @@ const getEnergyData = async (
const period =
dayDifference > 35 ? "month" : dayDifference > 2 ? "day" : "hour";

// Subtract 1 hour from start to get starting point data
const startMinHour = addHours(start, -1);

const lengthUnit = hass.config.unit_system.length || "";
const energyUnits: StatisticsUnitConfiguration = {
energy: "kWh",
Expand All @@ -402,26 +397,14 @@ const getEnergyData = async (
};

const _energyStats: Statistics | Promise<Statistics> = energyStatIds.length
? fetchStatistics(
hass!,
startMinHour,
end,
energyStatIds,
period,
energyUnits,
["sum"]
)
? fetchStatistics(hass!, start, end, energyStatIds, period, energyUnits, [
"change",
])
: {};
const _waterStats: Statistics | Promise<Statistics> = waterStatIds.length
? fetchStatistics(
hass!,
startMinHour,
end,
waterStatIds,
period,
waterUnits,
["sum"]
)
? fetchStatistics(hass!, start, end, waterStatIds, period, waterUnits, [
"change",
])
: {};

let statsCompare;
Expand All @@ -431,35 +414,27 @@ const getEnergyData = async (
let _waterStatsCompare: Statistics | Promise<Statistics> = {};

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);
if (energyStatIds.length) {
_energyStatsCompare = fetchStatistics(
hass!,
compareStartMinHour,
start,
endCompare,
energyStatIds,
period,
energyUnits,
["sum"]
["change"]
);
}
if (waterStatIds.length) {
_waterStatsCompare = fetchStatistics(
hass!,
compareStartMinHour,
start,
endCompare,
waterStatIds,
period,
waterUnits,
["sum"]
["change"]
);
}
}
Expand Down Expand Up @@ -522,19 +497,6 @@ const getEnergyData = async (
});
}

Object.values(stats).forEach((stat) => {
// if the start of the first value is after the requested period, we have the first data point, and should add a zero point
if (stat.length && new Date(stat[0].start) > startMinHour) {
stat.unshift({
...stat[0],
start: startMinHour.getTime(),
end: startMinHour.getTime(),
sum: 0,
state: 0,
});
}
});

const data: EnergyData = {
start,
end,
Expand Down
28 changes: 18 additions & 10 deletions src/data/recorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { computeStateName } from "../common/entity/compute_state_name";
import { HaDurationData } from "../components/ha-duration-input";
import { HomeAssistant } from "../types";

export type StatisticType = "state" | "sum" | "min" | "max" | "mean";
export type StatisticType = "change" | "state" | "sum" | "min" | "max" | "mean";

export interface Statistics {
[statisticId: string]: StatisticValue[];
Expand All @@ -11,6 +11,7 @@ export interface Statistics {
export interface StatisticValue {
start: number;
end: number;
change?: number | null;
last_reset?: number | null;
max?: number | null;
mean?: number | null;
Expand Down Expand Up @@ -91,6 +92,7 @@ export interface StatisticsUnitConfiguration {
}

const statisticTypes = [
"change",
"last_reset",
"max",
"mean",
Expand Down Expand Up @@ -196,18 +198,24 @@ export const clearStatistics = (hass: HomeAssistant, statistic_ids: string[]) =>
export const calculateStatisticSumGrowth = (
values: StatisticValue[]
): number | null => {
if (!values || values.length < 2) {
return null;
}
const endSum = values[values.length - 1].sum;
if (endSum === null || endSum === undefined) {
let growth: number | null = null;

if (!values) {
return null;
}
const startSum = values[0].sum;
if (startSum === null || startSum === undefined) {
return endSum;

for (const value of values) {
if (value.change === null || value.change === undefined) {
continue;
}
if (growth === null) {
growth = value.change;
} else {
growth += value.change;
}
}
return endSum - startSum;

return growth;
};

export const calculateStatisticsSumGrowth = (
Expand Down
39 changes: 5 additions & 34 deletions src/panels/lovelace/cards/energy/hui-energy-devices-graph-card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
ScatterDataPoint,
} from "chart.js";
import { getRelativePosition } from "chart.js/helpers";
import { addHours, differenceInDays } from "date-fns/esm";
import { differenceInDays } from "date-fns/esm";
import { UnsubscribeFunc } from "home-assistant-js-websocket";
import { css, CSSResultGroup, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
Expand Down Expand Up @@ -181,8 +181,6 @@ export class HuiEnergyDevicesGraphCard
const period =
dayDifference > 35 ? "month" : dayDifference > 2 ? "day" : "hour";

const startMinHour = addHours(energyData.start, -1);

const lengthUnit = this.hass.config.unit_system.length || "";
const units: StatisticsUnitConfiguration = {
energy: "kWh",
Expand All @@ -191,53 +189,26 @@ export class HuiEnergyDevicesGraphCard

const data = await fetchStatistics(
this.hass,
startMinHour,
energyData.start,
energyData.end,
devices,
period,
units,
["sum"]
["change"]
);

Object.values(data).forEach((stat) => {
// if the start of the first value is after the requested period, we have the first data point, and should add a zero point
if (stat.length && new Date(stat[0].start) > startMinHour) {
stat.unshift({
...stat[0],
start: startMinHour.getTime(),
end: startMinHour.getTime(),
sum: 0,
state: 0,
});
}
});

let compareData: Statistics | undefined;

if (energyData.startCompare && energyData.endCompare) {
const startCompareMinHour = addHours(energyData.startCompare, -1);
compareData = await fetchStatistics(
this.hass,
startCompareMinHour,
energyData.startCompare,
energyData.endCompare,
devices,
period,
units,
["sum"]
["change"]
);

Object.values(compareData).forEach((stat) => {
// if the start of the first value is after the requested period, we have the first data point, and should add a zero point
if (stat.length && new Date(stat[0].start) > startMinHour) {
stat.unshift({
...stat[0],
start: startCompareMinHour.getTime(),
end: startCompareMinHour.getTime(),
sum: 0,
state: 0,
});
}
});
}

const chartData: Array<ChartDataset<"bar", ParsedDataType<"bar">>["data"]> =
Expand Down
11 changes: 2 additions & 9 deletions src/panels/lovelace/cards/energy/hui-energy-gas-graph-card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,6 @@ export class HuiEnergyGasGraphCard
? rgb2hex(lab2rgb(modifiedColor))
: gasColor;

let prevValue: number | null = null;
let prevStart: number | null = null;

const gasConsumptionData: ScatterDataPoint[] = [];
Expand All @@ -355,24 +354,18 @@ export class HuiEnergyGasGraphCard
const stats = statistics[source.stat_energy_from];

for (const point of stats) {
if (point.sum === null || point.sum === undefined) {
continue;
}
if (prevValue === null || prevValue === undefined) {
prevValue = point.sum;
if (point.change === null || point.change === undefined) {
continue;
}
if (prevStart === point.start) {
continue;
}
const value = point.sum - prevValue;
const date = new Date(point.start);
gasConsumptionData.push({
x: date.getTime(),
y: value,
y: point.change,
});
prevStart = point.start;
prevValue = point.sum;
}
}

Expand Down
11 changes: 2 additions & 9 deletions src/panels/lovelace/cards/energy/hui-energy-solar-graph-card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,6 @@ export class HuiEnergySolarGraphCard
? rgb2hex(lab2rgb(modifiedColor))
: solarColor;

let prevValue: number | null = null;
let prevStart: number | null = null;

const solarProductionData: ScatterDataPoint[] = [];
Expand All @@ -375,24 +374,18 @@ export class HuiEnergySolarGraphCard
const stats = statistics[source.stat_energy_from];

for (const point of stats) {
if (point.sum === null || point.sum === undefined) {
continue;
}
if (prevValue === null || prevValue === undefined) {
prevValue = point.sum;
if (point.change === null || point.change === undefined) {
continue;
}
if (prevStart === point.start) {
continue;
}
const value = point.sum - prevValue;
const date = new Date(point.start);
solarProductionData.push({
x: date.getTime(),
y: value,
y: point.change,
});
prevStart = point.start;
prevValue = point.sum;
}
}

Expand Down
Loading

0 comments on commit 72403f4

Please sign in to comment.