Adapt to removal of statistics state_unit_of_measurement (#13935)

* Adapt to removal of statistics state_unit_of_measurement

* Tweak
This commit is contained in:
Erik Montnemery 2022-10-01 18:55:05 +02:00 committed by GitHub
parent f768c5ef7f
commit 6393944a1b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 140 additions and 140 deletions

View File

@ -21,6 +21,7 @@ import {
numberFormatToLocale, numberFormatToLocale,
} from "../../common/number/format_number"; } from "../../common/number/format_number";
import { import {
getDisplayUnit,
getStatisticLabel, getStatisticLabel,
getStatisticMetadata, getStatisticMetadata,
Statistics, Statistics,
@ -258,8 +259,11 @@ class StatisticsChart extends LitElement {
if (!this.unit) { if (!this.unit) {
if (unit === undefined) { if (unit === undefined) {
unit = meta?.state_unit_of_measurement; unit = getDisplayUnit(this.hass, firstStat.statistic_id, meta);
} else if (unit !== meta?.state_unit_of_measurement) { } else if (
unit !== getDisplayUnit(this.hass, firstStat.statistic_id, meta)
) {
// Clear unit if not all statistics have same unit
unit = null; unit = null;
} }
} }

View File

@ -5,9 +5,12 @@ import { customElement, property, query, state } from "lit/decorators";
import memoizeOne from "memoize-one"; import memoizeOne from "memoize-one";
import { ensureArray } from "../../common/ensure-array"; import { ensureArray } from "../../common/ensure-array";
import { fireEvent } from "../../common/dom/fire_event"; import { fireEvent } from "../../common/dom/fire_event";
import { computeStateName } from "../../common/entity/compute_state_name";
import { stringCompare } from "../../common/string/compare"; import { stringCompare } from "../../common/string/compare";
import { getStatisticIds, StatisticsMetaData } from "../../data/recorder"; import {
getStatisticIds,
getStatisticLabel,
StatisticsMetaData,
} from "../../data/recorder";
import { PolymerChangedEvent } from "../../polymer-types"; import { PolymerChangedEvent } from "../../polymer-types";
import { HomeAssistant } from "../../types"; import { HomeAssistant } from "../../types";
import { documentationUrl } from "../../util/documentation-url"; import { documentationUrl } from "../../util/documentation-url";
@ -43,18 +46,11 @@ export class HaStatisticPicker extends LitElement {
public includeStatisticsUnitOfMeasurement?: string | string[]; public includeStatisticsUnitOfMeasurement?: string | string[];
/** /**
* Show only statistics displayed with these units of measurements. * Show only statistics with these unit classes.
* @attr include-display-unit-of-measurement * @attr include-unit-class
*/ */
@property({ attribute: "include-display-unit-of-measurement" }) @property({ attribute: "include-unit-class" })
public includeDisplayUnitOfMeasurement?: string | string[]; public includeUnitClass?: string | string[];
/**
* Show only statistics with these device classes.
* @attr include-device-classes
*/
@property({ attribute: "include-device-classes" })
public includeDeviceClasses?: string[];
/** /**
* Show only statistics on entities. * Show only statistics on entities.
@ -97,8 +93,7 @@ export class HaStatisticPicker extends LitElement {
( (
statisticIds: StatisticsMetaData[], statisticIds: StatisticsMetaData[],
includeStatisticsUnitOfMeasurement?: string | string[], includeStatisticsUnitOfMeasurement?: string | string[],
includeDisplayUnitOfMeasurement?: string | string[], includeUnitClass?: string | string[],
includeDeviceClasses?: string[],
entitiesOnly?: boolean entitiesOnly?: boolean
): Array<{ id: string; name: string; state?: HassEntity }> => { ): Array<{ id: string; name: string; state?: HassEntity }> => {
if (!statisticIds.length) { if (!statisticIds.length) {
@ -113,15 +108,18 @@ export class HaStatisticPicker extends LitElement {
} }
if (includeStatisticsUnitOfMeasurement) { if (includeStatisticsUnitOfMeasurement) {
const includeUnits = ensureArray(includeStatisticsUnitOfMeasurement); const includeUnits: (string | null)[] = ensureArray(
includeStatisticsUnitOfMeasurement
);
statisticIds = statisticIds.filter((meta) => statisticIds = statisticIds.filter((meta) =>
includeUnits.includes(meta.statistics_unit_of_measurement) includeUnits.includes(meta.statistics_unit_of_measurement)
); );
} }
if (includeDisplayUnitOfMeasurement) { if (includeUnitClass) {
const includeUnits = ensureArray(includeDisplayUnitOfMeasurement); const includeUnitClasses: (string | null)[] =
ensureArray(includeUnitClass);
statisticIds = statisticIds.filter((meta) => statisticIds = statisticIds.filter((meta) =>
includeUnits.includes(meta.state_unit_of_measurement) includeUnitClasses.includes(meta.unit_class)
); );
} }
@ -136,23 +134,16 @@ export class HaStatisticPicker extends LitElement {
if (!entitiesOnly) { if (!entitiesOnly) {
output.push({ output.push({
id: meta.statistic_id, id: meta.statistic_id,
name: meta.name || meta.statistic_id, name: getStatisticLabel(this.hass, meta.statistic_id, meta),
}); });
} }
return; return;
} }
if ( output.push({
!includeDeviceClasses || id: meta.statistic_id,
includeDeviceClasses.includes( name: getStatisticLabel(this.hass, meta.statistic_id, meta),
entityState!.attributes.device_class || "" state: entityState,
) });
) {
output.push({
id: meta.statistic_id,
name: computeStateName(entityState),
state: entityState,
});
}
}); });
if (!output.length) { if (!output.length) {
@ -203,8 +194,7 @@ export class HaStatisticPicker extends LitElement {
(this.comboBox as any).items = this._getStatistics( (this.comboBox as any).items = this._getStatistics(
this.statisticIds!, this.statisticIds!,
this.includeStatisticsUnitOfMeasurement, this.includeStatisticsUnitOfMeasurement,
this.includeDisplayUnitOfMeasurement, this.includeUnitClass,
this.includeDeviceClasses,
this.entitiesOnly this.entitiesOnly
); );
} else { } else {
@ -212,8 +202,7 @@ export class HaStatisticPicker extends LitElement {
(this.comboBox as any).items = this._getStatistics( (this.comboBox as any).items = this._getStatistics(
this.statisticIds!, this.statisticIds!,
this.includeStatisticsUnitOfMeasurement, this.includeStatisticsUnitOfMeasurement,
this.includeDisplayUnitOfMeasurement, this.includeUnitClass,
this.includeDeviceClasses,
this.entitiesOnly this.entitiesOnly
); );
}); });

View File

@ -32,11 +32,11 @@ class HaStatisticsPicker extends LitElement {
public includeStatisticsUnitOfMeasurement?: string[] | string; public includeStatisticsUnitOfMeasurement?: string[] | string;
/** /**
* Show only statistics displayed with these units of measurements. * Show only statistics with these unit classes.
* @attr include-display-unit-of-measurement * @attr include-unit-class
*/ */
@property({ attribute: "include-display-unit-of-measurement" }) @property({ attribute: "include-unit-class" })
public includeDisplayUnitOfMeasurement?: string[] | string; public includeUnitClass?: string | string[];
/** /**
* Ignore filtering of statistics type and units when only a single statistic is selected. * Ignore filtering of statistics type and units when only a single statistic is selected.
@ -58,12 +58,12 @@ class HaStatisticsPicker extends LitElement {
this.ignoreRestrictionsOnFirstStatistic && this.ignoreRestrictionsOnFirstStatistic &&
this._currentStatistics.length <= 1; this._currentStatistics.length <= 1;
const includeDisplayUnitCurrent = ignoreRestriction
? undefined
: this.includeDisplayUnitOfMeasurement;
const includeStatisticsUnitCurrent = ignoreRestriction const includeStatisticsUnitCurrent = ignoreRestriction
? undefined ? undefined
: this.includeStatisticsUnitOfMeasurement; : this.includeStatisticsUnitOfMeasurement;
const includeUnitClassCurrent = ignoreRestriction
? undefined
: this.includeUnitClass;
const includeStatisticTypesCurrent = ignoreRestriction const includeStatisticTypesCurrent = ignoreRestriction
? undefined ? undefined
: this.statisticTypes; : this.statisticTypes;
@ -75,8 +75,8 @@ class HaStatisticsPicker extends LitElement {
<ha-statistic-picker <ha-statistic-picker
.curValue=${statisticId} .curValue=${statisticId}
.hass=${this.hass} .hass=${this.hass}
.includeDisplayUnitOfMeasurement=${includeDisplayUnitCurrent}
.includeStatisticsUnitOfMeasurement=${includeStatisticsUnitCurrent} .includeStatisticsUnitOfMeasurement=${includeStatisticsUnitCurrent}
.includeUnitClass=${includeUnitClassCurrent}
.value=${statisticId} .value=${statisticId}
.statisticTypes=${includeStatisticTypesCurrent} .statisticTypes=${includeStatisticTypesCurrent}
.statisticIds=${this.statisticIds} .statisticIds=${this.statisticIds}
@ -89,10 +89,9 @@ class HaStatisticsPicker extends LitElement {
<div> <div>
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
.includeDisplayUnitOfMeasurement=${this
.includeDisplayUnitOfMeasurement}
.includeStatisticsUnitOfMeasurement=${this .includeStatisticsUnitOfMeasurement=${this
.includeStatisticsUnitOfMeasurement} .includeStatisticsUnitOfMeasurement}
.includeUnitClass=${this.includeUnitClass}
.statisticTypes=${this.statisticTypes} .statisticTypes=${this.statisticTypes}
.statisticIds=${this.statisticIds} .statisticIds=${this.statisticIds}
.label=${this.pickStatisticLabel} .label=${this.pickStatisticLabel}

View File

@ -600,20 +600,14 @@ export const getEnergySolarForecasts = (hass: HomeAssistant) =>
type: "energy/solar_forecast", type: "energy/solar_forecast",
}); });
export const ENERGY_GAS_VOLUME_UNITS = ["m³"]; const energyGasUnitClass = ["volume", "energy"] as const;
export const ENERGY_GAS_ENERGY_UNITS = ["kWh"]; export type EnergyGasUnitClass = typeof energyGasUnitClass[number];
export const ENERGY_GAS_UNITS = [
...ENERGY_GAS_VOLUME_UNITS,
...ENERGY_GAS_ENERGY_UNITS,
];
export type EnergyGasUnit = "volume" | "energy"; export const getEnergyGasUnitClass = (
export const getEnergyGasUnitCategory = (
prefs: EnergyPreferences, prefs: EnergyPreferences,
statisticsMetaData: Record<string, StatisticsMetaData> = {}, statisticsMetaData: Record<string, StatisticsMetaData> = {},
excludeSource?: string excludeSource?: string
): EnergyGasUnit | undefined => { ): EnergyGasUnitClass | undefined => {
for (const source of prefs.energy_sources) { for (const source of prefs.energy_sources) {
if (source.type !== "gas") { if (source.type !== "gas") {
continue; continue;
@ -622,29 +616,29 @@ export const getEnergyGasUnitCategory = (
continue; continue;
} }
const statisticIdWithMeta = statisticsMetaData[source.stat_energy_from]; const statisticIdWithMeta = statisticsMetaData[source.stat_energy_from];
if (statisticIdWithMeta) { if (
return ENERGY_GAS_VOLUME_UNITS.includes( energyGasUnitClass.includes(
statisticIdWithMeta.statistics_unit_of_measurement statisticIdWithMeta.unit_class as EnergyGasUnitClass
) )
? "volume" ) {
: "energy"; return statisticIdWithMeta.unit_class as EnergyGasUnitClass;
} }
} }
return undefined; return undefined;
}; };
export const getEnergyGasUnit = ( export const getEnergyGasUnit = (
hass: HomeAssistant,
prefs: EnergyPreferences, prefs: EnergyPreferences,
statisticsMetaData: Record<string, StatisticsMetaData> = {} statisticsMetaData: Record<string, StatisticsMetaData> = {}
): string | undefined => { ): string | undefined => {
for (const source of prefs.energy_sources) { const unitClass = getEnergyGasUnitClass(prefs, statisticsMetaData);
if (source.type !== "gas") { if (unitClass === undefined) {
continue; return undefined;
}
const statisticIdWithMeta = statisticsMetaData[source.stat_energy_from];
if (statisticIdWithMeta?.state_unit_of_measurement) {
return statisticIdWithMeta.state_unit_of_measurement;
}
} }
return undefined; return unitClass === "energy"
? "kWh"
: hass.config.unit_system.length === "km"
? "m³"
: "ft³";
}; };

View File

@ -20,13 +20,13 @@ export interface StatisticValue {
} }
export interface StatisticsMetaData { export interface StatisticsMetaData {
state_unit_of_measurement: string; statistics_unit_of_measurement: string | null;
statistics_unit_of_measurement: string;
statistic_id: string; statistic_id: string;
source: string; source: string;
name?: string | null; name?: string | null;
has_sum: boolean; has_sum: boolean;
has_mean: boolean; has_mean: boolean;
unit_class: string | null;
} }
export type StatisticsValidationResult = export type StatisticsValidationResult =
@ -254,7 +254,7 @@ export const adjustStatisticsSum = (
statistic_id: string, statistic_id: string,
start_time: string, start_time: string,
adjustment: number, adjustment: number,
adjustment_unit_of_measurement: string adjustment_unit_of_measurement: string | null
): Promise<void> => ): Promise<void> =>
hass.callWS({ hass.callWS({
type: "recorder/adjust_sum_statistics", type: "recorder/adjust_sum_statistics",
@ -275,3 +275,17 @@ export const getStatisticLabel = (
} }
return statisticsMetaData?.name || statisticsId; return statisticsMetaData?.name || statisticsId;
}; };
export const getDisplayUnit = (
hass: HomeAssistant,
statisticsId: string | undefined,
statisticsMetaData: StatisticsMetaData | undefined
): string | null | undefined => {
let unit: string | undefined;
if (statisticsId) {
unit = hass.states[statisticsId]?.attributes.unit_of_measurement;
}
return unit === undefined
? statisticsMetaData?.statistics_unit_of_measurement
: unit;
};

View File

@ -10,7 +10,7 @@ import {
EnergyPreferencesValidation, EnergyPreferencesValidation,
EnergyValidationIssue, EnergyValidationIssue,
GasSourceTypeEnergyPreference, GasSourceTypeEnergyPreference,
getEnergyGasUnitCategory, getEnergyGasUnitClass,
saveEnergyPreferences, saveEnergyPreferences,
} from "../../../../data/energy"; } from "../../../../data/energy";
import { import {
@ -133,7 +133,7 @@ export class EnergyGasSettings extends LitElement {
private _addSource() { private _addSource() {
showEnergySettingsGasDialog(this, { showEnergySettingsGasDialog(this, {
allowedGasUnitCategory: getEnergyGasUnitCategory( allowedGasUnitClass: getEnergyGasUnitClass(
this.preferences, this.preferences,
this.statsMetadata this.statsMetadata
), ),
@ -152,7 +152,7 @@ export class EnergyGasSettings extends LitElement {
ev.currentTarget.closest(".row").source; ev.currentTarget.closest(".row").source;
showEnergySettingsGasDialog(this, { showEnergySettingsGasDialog(this, {
source: { ...origSource }, source: { ...origSource },
allowedGasUnitCategory: getEnergyGasUnitCategory( allowedGasUnitClass: getEnergyGasUnitClass(
this.preferences, this.preferences,
this.statsMetadata, this.statsMetadata,
origSource.stat_energy_from origSource.stat_energy_from

View File

@ -14,8 +14,7 @@ import { EnergySettingsBatteryDialogParams } from "./show-dialogs-energy";
import "@material/mwc-button/mwc-button"; import "@material/mwc-button/mwc-button";
import "../../../../components/entity/ha-statistic-picker"; import "../../../../components/entity/ha-statistic-picker";
const energyUnits = ["kWh"]; const energyUnitClasses = ["energy"];
const energyDeviceClasses = ["energy"];
@customElement("dialog-energy-battery-settings") @customElement("dialog-energy-battery-settings")
export class DialogEnergyBatterySettings export class DialogEnergyBatterySettings
@ -67,8 +66,7 @@ export class DialogEnergyBatterySettings
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
.includeStatisticsUnitOfMeasurement=${energyUnits} .includeUnitClass=${energyUnitClasses}
.includeDeviceClasses=${energyDeviceClasses}
.value=${this._source.stat_energy_to} .value=${this._source.stat_energy_to}
.label=${this.hass.localize( .label=${this.hass.localize(
"ui.panel.config.energy.battery.dialog.energy_into_battery" "ui.panel.config.energy.battery.dialog.energy_into_battery"
@ -79,8 +77,7 @@ export class DialogEnergyBatterySettings
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
.includeStatisticsUnitOfMeasurement=${energyUnits} .includeUnitClass=${energyUnitClasses}
.includeDeviceClasses=${energyDeviceClasses}
.value=${this._source.stat_energy_from} .value=${this._source.stat_energy_from}
.label=${this.hass.localize( .label=${this.hass.localize(
"ui.panel.config.energy.battery.dialog.energy_out_of_battery" "ui.panel.config.energy.battery.dialog.energy_out_of_battery"

View File

@ -14,8 +14,7 @@ import "../../../../components/ha-radio";
import "../../../../components/ha-formfield"; import "../../../../components/ha-formfield";
import "../../../../components/entity/ha-entity-picker"; import "../../../../components/entity/ha-entity-picker";
const energyUnits = ["kWh"]; const energyUnitClasses = ["energy"];
const energyDeviceClasses = ["energy"];
@customElement("dialog-energy-device-settings") @customElement("dialog-energy-device-settings")
export class DialogEnergyDeviceSettings export class DialogEnergyDeviceSettings
@ -69,8 +68,7 @@ export class DialogEnergyDeviceSettings
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
.includeStatisticsUnitOfMeasurement=${energyUnits} .includeUnitClass=${energyUnitClasses}
.includeDeviceClasses=${energyDeviceClasses}
.label=${this.hass.localize( .label=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.device_consumption_energy" "ui.panel.config.energy.device_consumption.dialog.device_consumption_energy"
)} )}

View File

@ -5,9 +5,6 @@ import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/ha-dialog"; import "../../../../components/ha-dialog";
import { import {
emptyGasEnergyPreference, emptyGasEnergyPreference,
ENERGY_GAS_ENERGY_UNITS,
ENERGY_GAS_UNITS,
ENERGY_GAS_VOLUME_UNITS,
GasSourceTypeEnergyPreference, GasSourceTypeEnergyPreference,
} from "../../../../data/energy"; } from "../../../../data/energy";
import { HassDialog } from "../../../../dialogs/make-dialog-manager"; import { HassDialog } from "../../../../dialogs/make-dialog-manager";
@ -21,7 +18,10 @@ import "../../../../components/ha-radio";
import "../../../../components/ha-formfield"; import "../../../../components/ha-formfield";
import "../../../../components/ha-textfield"; import "../../../../components/ha-textfield";
import type { HaRadio } from "../../../../components/ha-radio"; import type { HaRadio } from "../../../../components/ha-radio";
import { getStatisticMetadata } from "../../../../data/recorder"; import {
getStatisticMetadata,
getDisplayUnit,
} from "../../../../data/recorder";
@customElement("dialog-energy-gas-settings") @customElement("dialog-energy-gas-settings")
export class DialogEnergyGasSettings export class DialogEnergyGasSettings
@ -38,7 +38,7 @@ export class DialogEnergyGasSettings
@state() private _pickableUnit?: string; @state() private _pickableUnit?: string;
@state() private _pickedDisplayUnit?: string; @state() private _pickedDisplayUnit?: string | null;
@state() private _error?: string; @state() private _error?: string;
@ -49,7 +49,11 @@ export class DialogEnergyGasSettings
this._source = params.source this._source = params.source
? { ...params.source } ? { ...params.source }
: emptyGasEnergyPreference(); : emptyGasEnergyPreference();
this._pickedDisplayUnit = params.metadata?.state_unit_of_measurement; this._pickedDisplayUnit = getDisplayUnit(
this.hass,
params.source?.stat_energy_from,
params.metadata
);
this._costs = this._source.entity_energy_price this._costs = this._source.entity_energy_price
? "entity" ? "entity"
: this._source.number_energy_price : this._source.number_energy_price
@ -75,9 +79,9 @@ export class DialogEnergyGasSettings
const pickableUnit = const pickableUnit =
this._pickableUnit || this._pickableUnit ||
(this._params.allowedGasUnitCategory === undefined (this._params.allowedGasUnitClass === undefined
? "ft³, m³, Wh, kWh or MWh" ? "ft³, m³, Wh, kWh or MWh"
: this._params.allowedGasUnitCategory === "energy" : this._params.allowedGasUnitClass === "energy"
? "Wh, kWh or MWh" ? "Wh, kWh or MWh"
: "ft³ or m³"); : "ft³ or m³");
@ -98,17 +102,12 @@ export class DialogEnergyGasSettings
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
.includeStatisticsUnitOfMeasurement=${this._params .includeUnitClass=${this._params.allowedGasUnitClass}
.allowedGasUnitCategory === undefined
? ENERGY_GAS_UNITS
: this._params.allowedGasUnitCategory === "energy"
? ENERGY_GAS_ENERGY_UNITS
: ENERGY_GAS_VOLUME_UNITS}
.value=${this._source.stat_energy_from} .value=${this._source.stat_energy_from}
.label=${`${this.hass.localize( .label=${`${this.hass.localize(
"ui.panel.config.energy.gas.dialog.gas_usage" "ui.panel.config.energy.gas.dialog.gas_usage"
)} (${ )} (${
this._params.allowedGasUnitCategory === undefined this._params.allowedGasUnitClass === undefined
? this.hass.localize( ? this.hass.localize(
"ui.panel.config.energy.gas.dialog.m3_or_kWh" "ui.panel.config.energy.gas.dialog.m3_or_kWh"
) )
@ -263,14 +262,12 @@ export class DialogEnergyGasSettings
private async _statisticChanged(ev: CustomEvent<{ value: string }>) { private async _statisticChanged(ev: CustomEvent<{ value: string }>) {
if (ev.detail.value) { if (ev.detail.value) {
const entity = this.hass.states[ev.detail.value]; const metadata = await getStatisticMetadata(this.hass, [ev.detail.value]);
if (entity?.attributes.unit_of_measurement) { this._pickedDisplayUnit = getDisplayUnit(
this._pickedDisplayUnit = entity.attributes.unit_of_measurement; this.hass,
} else { ev.detail.value,
this._pickedDisplayUnit = ( metadata[0]
await getStatisticMetadata(this.hass, [ev.detail.value]) );
)[0]?.state_unit_of_measurement;
}
} else { } else {
this._pickedDisplayUnit = undefined; this._pickedDisplayUnit = undefined;
} }

View File

@ -20,8 +20,7 @@ import "../../../../components/ha-formfield";
import type { HaRadio } from "../../../../components/ha-radio"; import type { HaRadio } from "../../../../components/ha-radio";
import "../../../../components/entity/ha-entity-picker"; import "../../../../components/entity/ha-entity-picker";
const energyUnits = ["kWh"]; const energyUnitClasses = ["energy"];
const energyDeviceClasses = ["energy"];
@customElement("dialog-energy-grid-flow-settings") @customElement("dialog-energy-grid-flow-settings")
export class DialogEnergyGridFlowSettings export class DialogEnergyGridFlowSettings
@ -93,8 +92,7 @@ export class DialogEnergyGridFlowSettings
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
.includeStatisticsUnitOfMeasurement=${energyUnits} .includeUnitClass=${energyUnitClasses}
.includeDeviceClasses=${energyDeviceClasses}
.value=${this._source[ .value=${this._source[
this._params.direction === "from" this._params.direction === "from"
? "stat_energy_from" ? "stat_energy_from"

View File

@ -22,8 +22,7 @@ import { showConfigFlowDialog } from "../../../../dialogs/config-flow/show-dialo
import { ConfigEntry, getConfigEntries } from "../../../../data/config_entries"; import { ConfigEntry, getConfigEntries } from "../../../../data/config_entries";
import { brandsUrl } from "../../../../util/brands-url"; import { brandsUrl } from "../../../../util/brands-url";
const energyUnits = ["kWh"]; const energyUnitClasses = ["energy"];
const energyDeviceClasses = ["energy"];
@customElement("dialog-energy-solar-settings") @customElement("dialog-energy-solar-settings")
export class DialogEnergySolarSettings export class DialogEnergySolarSettings
@ -79,8 +78,7 @@ export class DialogEnergySolarSettings
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
.includeStatisticsUnitOfMeasurement=${energyUnits} .includeUnitClass=${energyUnitClasses}
.includeDeviceClasses=${energyDeviceClasses}
.value=${this._source.stat_energy_from} .value=${this._source.stat_energy_from}
.label=${this.hass.localize( .label=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.solar_production_energy" "ui.panel.config.energy.solar.dialog.solar_production_energy"

View File

@ -2,7 +2,7 @@ import { fireEvent } from "../../../../common/dom/fire_event";
import { import {
BatterySourceTypeEnergyPreference, BatterySourceTypeEnergyPreference,
DeviceConsumptionEnergyPreference, DeviceConsumptionEnergyPreference,
EnergyGasUnit, EnergyGasUnitClass,
EnergyInfo, EnergyInfo,
FlowFromGridSourceEnergyPreference, FlowFromGridSourceEnergyPreference,
FlowToGridSourceEnergyPreference, FlowToGridSourceEnergyPreference,
@ -46,7 +46,7 @@ export interface EnergySettingsBatteryDialogParams {
export interface EnergySettingsGasDialogParams { export interface EnergySettingsGasDialogParams {
source?: GasSourceTypeEnergyPreference; source?: GasSourceTypeEnergyPreference;
allowedGasUnitCategory?: EnergyGasUnit; allowedGasUnitClass?: EnergyGasUnitClass;
metadata?: StatisticsMetaData; metadata?: StatisticsMetaData;
saveCallback: (source: GasSourceTypeEnergyPreference) => Promise<void>; saveCallback: (source: GasSourceTypeEnergyPreference) => Promise<void>;
} }

View File

@ -74,12 +74,6 @@ class HaPanelDevStatistics extends SubscribeMixin(LitElement) {
hidden: this.narrow, hidden: this.narrow,
width: "20%", width: "20%",
}, },
state_unit_of_measurement: {
title: "Display unit",
sortable: true,
filterable: true,
width: "10%",
},
statistics_unit_of_measurement: { statistics_unit_of_measurement: {
title: "Statistics unit", title: "Statistics unit",
sortable: true, sortable: true,
@ -220,12 +214,12 @@ class HaPanelDevStatistics extends SubscribeMixin(LitElement) {
this._data.push({ this._data.push({
statistic_id: statisticId, statistic_id: statisticId,
statistics_unit_of_measurement: "", statistics_unit_of_measurement: "",
state_unit_of_measurement: "",
source: "", source: "",
state: this.hass.states[statisticId], state: this.hass.states[statisticId],
issues: issues[statisticId], issues: issues[statisticId],
has_mean: false, has_mean: false,
has_sum: false, has_sum: false,
unit_class: null,
}); });
} }
}); });

View File

@ -23,6 +23,7 @@ import "../../../components/ha-svg-icon";
import { import {
adjustStatisticsSum, adjustStatisticsSum,
fetchStatistics, fetchStatistics,
getDisplayUnit,
StatisticValue, StatisticValue,
} from "../../../data/recorder"; } from "../../../data/recorder";
import type { DateTimeSelector, NumberSelector } from "../../../data/selector"; import type { DateTimeSelector, NumberSelector } from "../../../data/selector";
@ -59,7 +60,7 @@ export class DialogStatisticsFixUnsupportedUnitMetadata extends LitElement {
}; };
private _amountSelector = memoizeOne( private _amountSelector = memoizeOne(
(unit_of_measurement: string): NumberSelector => ({ (unit_of_measurement: string | undefined): NumberSelector => ({
number: { number: {
step: 0.01, step: 0.01,
unit_of_measurement, unit_of_measurement,
@ -135,7 +136,11 @@ export class DialogStatisticsFixUnsupportedUnitMetadata extends LitElement {
} else { } else {
const data = const data =
this._stats5min.length >= 2 ? this._stats5min : this._statsHour; this._stats5min.length >= 2 ? this._stats5min : this._statsHour;
const unit = this._params!.statistic.state_unit_of_measurement; const unit = getDisplayUnit(
this.hass,
this._params!.statistic.statistic_id,
this._params!.statistic
);
const rows: TemplateResult[] = []; const rows: TemplateResult[] = [];
for (let i = 1; i < data.length; i++) { for (let i = 1; i < data.length; i++) {
const stat = data[i]; const stat = data[i];
@ -192,6 +197,11 @@ export class DialogStatisticsFixUnsupportedUnitMetadata extends LitElement {
} }
private _renderAdjustStat() { private _renderAdjustStat() {
const unit = getDisplayUnit(
this.hass,
this._params!.statistic.statistic_id,
this._params!.statistic
);
return html` return html`
<div class="text-content"> <div class="text-content">
<b>Statistic:</b> ${this._params!.statistic.statistic_id} <b>Statistic:</b> ${this._params!.statistic.statistic_id}
@ -220,9 +230,7 @@ export class DialogStatisticsFixUnsupportedUnitMetadata extends LitElement {
<ha-selector-number <ha-selector-number
label="New Value" label="New Value"
.hass=${this.hass} .hass=${this.hass}
.selector=${this._amountSelector( .selector=${this._amountSelector(unit || undefined)}
this._params!.statistic.state_unit_of_measurement
)}
.value=${this._amount} .value=${this._amount}
.disabled=${this._busy} .disabled=${this._busy}
@value-changed=${(ev) => { @value-changed=${(ev) => {
@ -299,6 +307,11 @@ export class DialogStatisticsFixUnsupportedUnitMetadata extends LitElement {
} }
private async _fixIssue(): Promise<void> { private async _fixIssue(): Promise<void> {
const unit = getDisplayUnit(
this.hass,
this._params!.statistic.statistic_id,
this._params!.statistic
);
this._busy = true; this._busy = true;
try { try {
await adjustStatisticsSum( await adjustStatisticsSum(
@ -306,7 +319,7 @@ export class DialogStatisticsFixUnsupportedUnitMetadata extends LitElement {
this._params!.statistic.statistic_id, this._params!.statistic.statistic_id,
this._chosenStat!.start, this._chosenStat!.start,
this._amount! - this._origAmount!, this._amount! - this._origAmount!,
this._params!.statistic.state_unit_of_measurement unit || null
); );
} catch (err: any) { } catch (err: any) {
this._busy = false; this._busy = false;

View File

@ -315,8 +315,11 @@ class HuiEnergyDistrubutionCard
${formatNumber(gasUsage || 0, this.hass.locale, { ${formatNumber(gasUsage || 0, this.hass.locale, {
maximumFractionDigits: 1, maximumFractionDigits: 1,
})} })}
${getEnergyGasUnit(prefs, this._data.statsMetadata) || ${getEnergyGasUnit(
"m³"} this.hass,
prefs,
this._data.statsMetadata
) || "m³"}
</div> </div>
<svg width="80" height="30"> <svg width="80" height="30">
<path d="M40 0 v30" id="gas" /> <path d="M40 0 v30" id="gas" />

View File

@ -274,7 +274,8 @@ export class HuiEnergyGasGraphCard
) as GasSourceTypeEnergyPreference[]; ) as GasSourceTypeEnergyPreference[];
this._unit = this._unit =
getEnergyGasUnit(energyData.prefs, energyData.statsMetadata) || "m³"; getEnergyGasUnit(this.hass, energyData.prefs, energyData.statsMetadata) ||
"m³";
const datasets: ChartDataset<"bar", ScatterDataPoint[]>[] = []; const datasets: ChartDataset<"bar", ScatterDataPoint[]>[] = [];

View File

@ -130,7 +130,8 @@ export class HuiEnergySourcesTableCard
); );
const gasUnit = const gasUnit =
getEnergyGasUnit(this._data.prefs, this._data.statsMetadata) || ""; getEnergyGasUnit(this.hass, this._data.prefs, this._data.statsMetadata) ||
"";
const compare = this._data.statsCompare !== undefined; const compare = this._data.statsCompare !== undefined;

View File

@ -205,7 +205,7 @@ export class HuiStatisticsGraphCardEditor
...this._config, ...this._config,
stat_types: configured_stat_types, stat_types: configured_stat_types,
}; };
const displayUnit = this._metaDatas?.[0]?.state_unit_of_measurement; const unitClass = this._metaDatas?.[0]?.unit_class;
return html` return html`
<ha-form <ha-form
@ -223,7 +223,7 @@ export class HuiStatisticsGraphCardEditor
.pickedStatisticLabel=${this.hass!.localize( .pickedStatisticLabel=${this.hass!.localize(
"ui.panel.lovelace.editor.card.statistics-graph.picked_statistic" "ui.panel.lovelace.editor.card.statistics-graph.picked_statistic"
)} )}
.includeDisplayUnitOfMeasurement=${displayUnit} .includeUnitClass=${unitClass}
.ignoreRestrictionsOnFirstStatistic=${true} .ignoreRestrictionsOnFirstStatistic=${true}
.value=${this._configEntities} .value=${this._configEntities}
.configValue=${"entities"} .configValue=${"entities"}