Fix gas energy graph units if stats added by external source (#11892)

This commit is contained in:
Pawel 2022-03-22 05:15:28 +01:00 committed by GitHub
parent 6bf2111a3c
commit ccf1fb573a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 43 additions and 1 deletions

View File

@ -12,7 +12,12 @@ import { subscribeOne } from "../common/util/subscribe-one";
import { HomeAssistant } from "../types";
import { ConfigEntry, getConfigEntries } from "./config_entries";
import { subscribeEntityRegistry } from "./entity_registry";
import { fetchStatistics, Statistics } from "./history";
import {
fetchStatistics,
Statistics,
StatisticsMetaData,
getStatisticMetadata,
} from "./history";
const energyCollectionKeys: (string | undefined)[] = [];
@ -136,6 +141,7 @@ export interface GasSourceTypeEnergyPreference {
entity_energy_from: string | null;
entity_energy_price: string | null;
number_energy_price: number | null;
unit_of_measurement?: string | null;
}
type EnergySource =
@ -271,6 +277,15 @@ const getEnergyData = async (
const consumptionStatIDs: string[] = [];
const statIDs: string[] = [];
const gasSources: GasSourceTypeEnergyPreference[] =
prefs.energy_sources.filter(
(source) => source.type === "gas"
) as GasSourceTypeEnergyPreference[];
const gasStatisticIdsWithMeta: StatisticsMetaData[] =
await getStatisticMetadata(
hass,
gasSources.map((source) => source.stat_energy_from)
);
for (const source of prefs.energy_sources) {
if (source.type === "solar") {
@ -280,6 +295,20 @@ const getEnergyData = async (
if (source.type === "gas") {
statIDs.push(source.stat_energy_from);
const entity = hass.states[source.stat_energy_from];
if (!entity) {
for (const statisticIdWithMeta of gasStatisticIdsWithMeta) {
if (
statisticIdWithMeta?.statistic_id === source.stat_energy_from &&
statisticIdWithMeta?.unit_of_measurement
) {
source.unit_of_measurement =
statisticIdWithMeta?.unit_of_measurement === "Wh"
? "kWh"
: statisticIdWithMeta?.unit_of_measurement;
}
}
}
if (source.stat_cost) {
statIDs.push(source.stat_cost);
}
@ -559,6 +588,9 @@ export const getEnergyGasUnit = (
? "kWh"
: entity.attributes.unit_of_measurement;
}
if (source.unit_of_measurement) {
return source.unit_of_measurement;
}
}
return undefined;
};

View File

@ -373,6 +373,15 @@ export const getStatisticIds = (
statistic_type,
});
export const getStatisticMetadata = (
hass: HomeAssistant,
statistic_ids?: string[]
) =>
hass.callWS<StatisticsMetaData[]>({
type: "recorder/get_statistics_metadata",
statistic_ids,
});
export const fetchStatistics = (
hass: HomeAssistant,
startTime: Date,

View File

@ -121,6 +121,7 @@ export class EnergyGasSettings extends LitElement {
showEnergySettingsGasDialog(this, {
unit: getEnergyGasUnitCategory(this.hass, this.preferences),
saveCallback: async (source) => {
delete source.unit_of_measurement;
await this._savePreferences({
...this.preferences,
energy_sources: this.preferences.energy_sources.concat(source),