Handle mismatched gas price units in energy cost sensor (#184292)

This commit is contained in:
Petar Petrov
2026-10-07 14:57:41 +02:00
committed by GitHub
parent d8e0155980
commit fcff2ca03c
2 changed files with 121 additions and 10 deletions
+37 -10
View File
@@ -1,7 +1,7 @@
"""Helper sensor for calculating utility costs."""
import asyncio
from collections.abc import Callable, Mapping
from collections.abc import Mapping
import copy
from dataclasses import dataclass
import logging
@@ -134,6 +134,10 @@ class EntityNotFoundError(HomeAssistantError):
"""When a referenced entity was not found."""
class PriceUnitMismatchError(HomeAssistantError):
"""When the price unit cannot be converted to the meter unit."""
class SensorManager:
"""Class to handle creation/removal of sensor data."""
@@ -382,6 +386,7 @@ class EnergyCostSensor(SensorEntity):
_wrong_state_class_reported = False
_wrong_unit_reported = False
_wrong_price_unit_reported = False
def __init__(
self,
@@ -497,6 +502,23 @@ class EnergyCostSensor(SensorEntity):
)
return
try:
converted_energy_price = self._convert_energy_price(
energy_price, energy_price_unit, energy_unit
)
except PriceUnitMismatchError:
if not self._wrong_price_unit_reported:
self._wrong_price_unit_reported = True
_LOGGER.warning(
"Not updating cost of %s: unit %s does not match price unit"
" per %s of %s",
energy_state.entity_id,
energy_unit,
energy_price_unit,
self._config["entity_energy_price"],
)
return
if (
state_class != SensorStateClass.TOTAL_INCREASING
and energy_state.attributes.get(SensorEntityStateAttribute.LAST_RESET)
@@ -522,10 +544,6 @@ class EnergyCostSensor(SensorEntity):
old_energy_value = float(self._last_energy_sensor_state.state)
cur_value = cast(float, self._attr_native_value)
converted_energy_price = self._convert_energy_price(
energy_price, energy_price_unit, energy_unit
)
self._attr_native_value = (
cur_value + (energy - old_energy_value) * converted_energy_price
)
@@ -566,17 +584,26 @@ class EnergyCostSensor(SensorEntity):
def _convert_energy_price(
self, energy_price: float, energy_price_unit: str | None, energy_unit: str
) -> float:
"""Convert the energy price to the correct unit."""
"""Convert the energy price to the correct unit.
Raises:
PriceUnitMismatchError: When the price unit cannot be converted to
the meter unit.
"""
if energy_price_unit is None:
return energy_price
converter: Callable[[float, str, str], float]
converter: type[unit_conversion.BaseUnitConverter]
if energy_unit in VALID_ENERGY_UNITS:
converter = unit_conversion.EnergyConverter.convert
converter = unit_conversion.EnergyConverter
else:
converter = unit_conversion.VolumeConverter.convert
converter = unit_conversion.VolumeConverter
return converter(energy_price, energy_unit, energy_price_unit)
if energy_price_unit not in converter.VALID_UNITS:
raise PriceUnitMismatchError
return converter.convert(energy_price, energy_unit, energy_price_unit)
@override
async def async_added_to_hass(self) -> None:
+84
View File
@@ -1125,6 +1125,90 @@ async def test_cost_sensor_handle_gas_kwh(
assert state.state == "50.0"
@pytest.mark.parametrize(
("usage_unit", "price_unit"),
[
pytest.param(
UnitOfVolume.CUBIC_METERS,
UnitOfEnergy.KILO_WATT_HOUR,
id="volume_usage_energy_price",
),
pytest.param(
UnitOfEnergy.KILO_WATT_HOUR,
UnitOfVolume.CUBIC_METERS,
id="energy_usage_volume_price",
),
],
)
async def test_cost_sensor_gas_price_unit_mismatch(
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
hass: HomeAssistant,
hass_storage: dict[str, Any],
caplog: pytest.LogCaptureFixture,
usage_unit: str,
price_unit: str,
) -> None:
"""Test a gas price unit that cannot be converted to the usage unit."""
energy_attributes = {
ATTR_UNIT_OF_MEASUREMENT: usage_unit,
ATTR_STATE_CLASS: SensorStateClass.TOTAL_INCREASING,
}
energy_data = data.EnergyManager.default_preferences()
energy_data["energy_sources"].append(
{
"type": "gas",
"stat_energy_from": "sensor.gas_consumption",
"stat_cost": None,
"entity_energy_price": "sensor.gas_price",
"number_energy_price": None,
}
)
hass_storage[data.STORAGE_KEY] = {
"version": 1,
"data": energy_data,
}
hass.states.async_set(
"sensor.gas_price", "0.5", {ATTR_UNIT_OF_MEASUREMENT: f"EUR/{price_unit}"}
)
hass.states.async_set("sensor.gas_consumption", 100, energy_attributes)
await setup_integration(hass)
state = hass.states.get("sensor.gas_consumption_cost")
assert state.state == "0.0"
hass.states.async_set("sensor.gas_consumption", 200, energy_attributes)
await hass.async_block_till_done()
state = hass.states.get("sensor.gas_consumption_cost")
assert state.state == "0.0"
assert (
f"Not updating cost of sensor.gas_consumption: unit {usage_unit} does not "
f"match price unit per {price_unit} of sensor.gas_price" in caplog.text
)
assert "Error while dispatching event" not in caplog.text
# Warned once only
caplog.clear()
hass.states.async_set("sensor.gas_consumption", 300, energy_attributes)
await hass.async_block_till_done()
assert "Not updating cost" not in caplog.text
assert "Error while dispatching event" not in caplog.text
# Usage since the last update is priced once the units match
hass.states.async_set(
"sensor.gas_price", "0.5", {ATTR_UNIT_OF_MEASUREMENT: f"EUR/{usage_unit}"}
)
hass.states.async_set("sensor.gas_consumption", 310, energy_attributes)
await hass.async_block_till_done()
state = hass.states.get("sensor.gas_consumption_cost")
assert state.state == "105.0"
@pytest.mark.parametrize(
("unit_system", "usage_unit", "growth"),
[