From fcff2ca03c76f192d7f4454f97089571a42a4de4 Mon Sep 17 00:00:00 2001 From: Petar Petrov Date: Wed, 7 Oct 2026 15:57:41 +0300 Subject: [PATCH] Handle mismatched gas price units in energy cost sensor (#184292) --- homeassistant/components/energy/sensor.py | 47 ++++++++++--- tests/components/energy/test_sensor.py | 84 +++++++++++++++++++++++ 2 files changed, 121 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/energy/sensor.py b/homeassistant/components/energy/sensor.py index 3d3bac397414..d9b1ffc3d227 100644 --- a/homeassistant/components/energy/sensor.py +++ b/homeassistant/components/energy/sensor.py @@ -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: diff --git a/tests/components/energy/test_sensor.py b/tests/components/energy/test_sensor.py index 42f356ce30c9..85a99743febd 100644 --- a/tests/components/energy/test_sensor.py +++ b/tests/components/energy/test_sensor.py @@ -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"), [