mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 11:33:11 -04:00
Add fixed costs to the energy dashboard (#192947)
This commit is contained in:
@@ -38,6 +38,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
)
|
||||
hass.data[DOMAIN] = {
|
||||
"cost_sensors": {},
|
||||
"fixed_cost_sensors": {},
|
||||
}
|
||||
|
||||
return True
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import asyncio
|
||||
from collections import Counter
|
||||
from collections.abc import Awaitable, Callable
|
||||
import math
|
||||
from typing import Any, Literal, NotRequired, TypedDict, override
|
||||
|
||||
import probatio
|
||||
@@ -24,7 +25,7 @@ from .const import (
|
||||
)
|
||||
|
||||
STORAGE_VERSION = 1
|
||||
STORAGE_MINOR_VERSION = 5
|
||||
STORAGE_MINOR_VERSION = 6
|
||||
STORAGE_KEY = DOMAIN
|
||||
|
||||
|
||||
@@ -294,6 +295,20 @@ class DeviceConsumption(TypedDict):
|
||||
included_in_stat: NotRequired[str]
|
||||
|
||||
|
||||
class FixedCostType(TypedDict):
|
||||
"""Dictionary holding a fixed cost, like a standing charge."""
|
||||
|
||||
id: str
|
||||
type: Literal["grid", "gas", "water"]
|
||||
name: str
|
||||
|
||||
# Charged at the start of each period, exactly one of these is set
|
||||
number_amount: float | None # Fixed amount ($)
|
||||
entity_amount: str | None # entity_id providing the amount ($)
|
||||
|
||||
period: Literal["day", "month", "year"]
|
||||
|
||||
|
||||
class EnergyPreferences(TypedDict):
|
||||
"""Dictionary holding the energy data."""
|
||||
|
||||
@@ -301,6 +316,7 @@ class EnergyPreferences(TypedDict):
|
||||
device_consumption: list[DeviceConsumption]
|
||||
device_consumption_water: NotRequired[list[DeviceConsumption]]
|
||||
device_consumption_gas: NotRequired[list[DeviceConsumption]]
|
||||
fixed_costs: NotRequired[list[FixedCostType]]
|
||||
|
||||
|
||||
class EnergyPreferencesUpdate(EnergyPreferences, total=False):
|
||||
@@ -832,6 +848,52 @@ DEVICE_CONSUMPTION_SCHEMA = probatio.Schema(
|
||||
)
|
||||
|
||||
|
||||
def _fixed_cost_entity_id(value: str) -> str:
|
||||
"""Validate the amount of a fixed cost comes from an entity."""
|
||||
if not valid_entity_id(value):
|
||||
raise probatio.Invalid("Fixed cost amount must be an entity")
|
||||
return value
|
||||
|
||||
|
||||
def _fixed_cost_finite_amount(value: float) -> float:
|
||||
"""Validate the fixed amount of a fixed cost is a finite number."""
|
||||
if not math.isfinite(value):
|
||||
raise probatio.Invalid("Fixed cost amount must be a finite number")
|
||||
return value
|
||||
|
||||
|
||||
def _fixed_cost_ensure_single_amount(val: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Ensure a fixed cost has exactly one amount."""
|
||||
if (val["number_amount"] is None) == (val["entity_amount"] is None):
|
||||
raise probatio.Invalid(
|
||||
"Define either an entity or a fixed number for the amount"
|
||||
)
|
||||
return val
|
||||
|
||||
|
||||
FIXED_COST_SCHEMA = probatio.All(
|
||||
probatio.Schema(
|
||||
{
|
||||
probatio.Required("id"): probatio.All(str, probatio.Length(min=1)),
|
||||
probatio.Required("type"): probatio.In(("grid", "gas", "water")),
|
||||
probatio.Required("name"): probatio.All(str, probatio.Length(min=1)),
|
||||
probatio.Optional("number_amount", default=None): probatio.Any(
|
||||
None, probatio.All(probatio.Coerce(float), _fixed_cost_finite_amount)
|
||||
),
|
||||
probatio.Optional("entity_amount", default=None): probatio.Any(
|
||||
None, probatio.All(str, _fixed_cost_entity_id)
|
||||
),
|
||||
probatio.Required("period"): probatio.In(("day", "month", "year")),
|
||||
}
|
||||
),
|
||||
_fixed_cost_ensure_single_amount,
|
||||
)
|
||||
|
||||
FIXED_COSTS_SCHEMA = probatio.All(
|
||||
[FIXED_COST_SCHEMA], _generate_unique_value_validator("id")
|
||||
)
|
||||
|
||||
|
||||
def _migrate_legacy_grid_to_unified(
|
||||
old_grid: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -940,6 +1002,9 @@ class _EnergyPreferencesStore(storage.Store[EnergyPreferences]):
|
||||
for source in data.get("energy_sources", []):
|
||||
source.pop("cost_adjustment_day", None)
|
||||
|
||||
if old_major_version == 1 and old_minor_version < 6:
|
||||
data.setdefault("fixed_costs", [])
|
||||
|
||||
return data
|
||||
|
||||
|
||||
@@ -1007,6 +1072,7 @@ class EnergyManager:
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
async def async_update(self, update: EnergyPreferencesUpdate) -> None:
|
||||
@@ -1021,6 +1087,7 @@ class EnergyManager:
|
||||
"device_consumption",
|
||||
"device_consumption_water",
|
||||
"device_consumption_gas",
|
||||
"fixed_costs",
|
||||
):
|
||||
if key in update:
|
||||
data[key] = update[key]
|
||||
|
||||
@@ -4,7 +4,9 @@ import asyncio
|
||||
from collections.abc import Mapping
|
||||
import copy
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
import logging
|
||||
import math
|
||||
from typing import Any, Final, Literal, Self, cast, override
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
@@ -18,12 +20,16 @@ from homeassistant.components.sensor import (
|
||||
)
|
||||
from homeassistant.components.sensor.recorder import reset_detected # pylint: disable=home-assistant-component-root-import
|
||||
from homeassistant.const import (
|
||||
EVENT_CORE_CONFIG_UPDATE,
|
||||
EntityStateAttribute,
|
||||
Platform,
|
||||
UnitOfEnergy,
|
||||
UnitOfPower,
|
||||
UnitOfVolume,
|
||||
)
|
||||
from homeassistant.core import (
|
||||
CALLBACK_TYPE,
|
||||
Event,
|
||||
HomeAssistant,
|
||||
State,
|
||||
callback,
|
||||
@@ -33,13 +39,16 @@ from homeassistant.core import (
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.event import async_track_state_change_event
|
||||
from homeassistant.helpers.event import (
|
||||
async_track_point_in_utc_time,
|
||||
async_track_state_change_event,
|
||||
)
|
||||
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
||||
from homeassistant.util import dt as dt_util, unit_conversion
|
||||
from homeassistant.util import dt as dt_util, slugify, unit_conversion
|
||||
from homeassistant.util.unit_system import METRIC_SYSTEM
|
||||
|
||||
from .const import BATTERY_CHARGE_DIRECTIONS, BATTERY_DIRECTIONS, DOMAIN
|
||||
from .data import EnergyManager, PowerConfig, async_get_manager
|
||||
from .data import EnergyManager, FixedCostType, PowerConfig, async_get_manager
|
||||
from .helpers import generate_power_sensor_entity_id, generate_power_sensor_unique_id
|
||||
|
||||
SUPPORTED_STATE_CLASSES = {
|
||||
@@ -75,7 +84,9 @@ async def async_setup_platform(
|
||||
discovery_info: DiscoveryInfoType | None = None,
|
||||
) -> None:
|
||||
"""Set up the energy sensors."""
|
||||
sensor_manager = SensorManager(await async_get_manager(hass), async_add_entities)
|
||||
sensor_manager = SensorManager(
|
||||
hass, await async_get_manager(hass), async_add_entities
|
||||
)
|
||||
await sensor_manager.async_start()
|
||||
|
||||
|
||||
@@ -142,13 +153,18 @@ class SensorManager:
|
||||
"""Class to handle creation/removal of sensor data."""
|
||||
|
||||
def __init__(
|
||||
self, manager: EnergyManager, async_add_entities: AddEntitiesCallback
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
manager: EnergyManager,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Initialize sensor manager."""
|
||||
self.hass = hass
|
||||
self.manager = manager
|
||||
self.async_add_entities = async_add_entities
|
||||
self.current_entities: dict[tuple[str, str | None, str], EnergyCostSensor] = {}
|
||||
self.current_power_entities: dict[str, EnergyPowerSensor] = {}
|
||||
self.current_fixed_cost_entities: dict[str, EnergyFixedCostSensor] = {}
|
||||
|
||||
async def async_start(self) -> None:
|
||||
"""Start."""
|
||||
@@ -159,9 +175,10 @@ class SensorManager:
|
||||
|
||||
async def _process_manager_data(self) -> None:
|
||||
"""Process manager data."""
|
||||
to_add: list[EnergyCostSensor | EnergyPowerSensor] = []
|
||||
to_add: list[_ManagedSensor] = []
|
||||
to_remove = dict(self.current_entities)
|
||||
power_to_remove = dict(self.current_power_entities)
|
||||
fixed_cost_to_remove = dict(self.current_fixed_cost_entities)
|
||||
|
||||
async def finish() -> None:
|
||||
if to_add:
|
||||
@@ -176,6 +193,10 @@ class SensorManager:
|
||||
self.current_power_entities.pop(power_key)
|
||||
await _async_remove_if_added(power_entity)
|
||||
|
||||
for fixed_cost_id, fixed_cost_entity in fixed_cost_to_remove.items():
|
||||
self.current_fixed_cost_entities.pop(fixed_cost_id)
|
||||
await self._async_remove_fixed_cost_sensor(fixed_cost_entity)
|
||||
|
||||
# This guard is for the optional typing of EnergyManager.data.
|
||||
# In practice, data is always set to default preferences in async_update
|
||||
# before listeners are called, so this case should never happen.
|
||||
@@ -211,6 +232,14 @@ class SensorManager:
|
||||
power_to_remove,
|
||||
)
|
||||
|
||||
for fixed_cost in self.manager.data.get("fixed_costs", []):
|
||||
if (sensor := fixed_cost_to_remove.pop(fixed_cost["id"], None)) is not None:
|
||||
sensor.update_config(fixed_cost)
|
||||
continue
|
||||
sensor = EnergyFixedCostSensor(fixed_cost)
|
||||
self.current_fixed_cost_entities[fixed_cost["id"]] = sensor
|
||||
to_add.append(sensor)
|
||||
|
||||
await finish()
|
||||
|
||||
@callback
|
||||
@@ -218,7 +247,7 @@ class SensorManager:
|
||||
self,
|
||||
adapter: SourceAdapter,
|
||||
config: Mapping[str, Any],
|
||||
to_add: list[EnergyCostSensor | EnergyPowerSensor],
|
||||
to_add: list[_ManagedSensor],
|
||||
to_remove: dict[tuple[str, str | None, str], EnergyCostSensor],
|
||||
) -> None:
|
||||
"""Process sensor data."""
|
||||
@@ -256,7 +285,7 @@ class SensorManager:
|
||||
def _process_grid_export_sensor(
|
||||
self,
|
||||
config: Mapping[str, Any],
|
||||
to_add: list[EnergyCostSensor | EnergyPowerSensor],
|
||||
to_add: list[_ManagedSensor],
|
||||
to_remove: dict[tuple[str, str | None, str], EnergyCostSensor],
|
||||
) -> None:
|
||||
"""Process grid export compensation sensor (unified format).
|
||||
@@ -306,7 +335,7 @@ class SensorManager:
|
||||
def _process_power_sensor_data(
|
||||
self,
|
||||
energy_source: Mapping[str, Any],
|
||||
to_add: list[EnergyCostSensor | EnergyPowerSensor],
|
||||
to_add: list[_ManagedSensor],
|
||||
to_remove: dict[str, EnergyPowerSensor],
|
||||
) -> None:
|
||||
"""Process power sensor data for battery and grid sources."""
|
||||
@@ -332,11 +361,24 @@ class SensorManager:
|
||||
or any(power_key in power_config for _, power_key in BATTERY_DIRECTIONS)
|
||||
)
|
||||
|
||||
async def _async_remove_fixed_cost_sensor(
|
||||
self, entity: EnergyFixedCostSensor
|
||||
) -> None:
|
||||
"""Remove the sensor of a deleted fixed cost, with its registry entry."""
|
||||
entity_registry = er.async_get(self.hass)
|
||||
if entity_id := entity_registry.async_get_entity_id(
|
||||
Platform.SENSOR, DOMAIN, cast(str, entity.unique_id)
|
||||
):
|
||||
entity_registry.async_remove(entity_id)
|
||||
# Wait for it, so the same fixed cost can be added again right away
|
||||
if entity.hass is not None:
|
||||
await entity.async_remove(force_remove=True)
|
||||
|
||||
def _create_or_keep_power_sensor(
|
||||
self,
|
||||
source_type: str,
|
||||
power_config: PowerConfig,
|
||||
to_add: list[EnergyCostSensor | EnergyPowerSensor],
|
||||
to_add: list[_ManagedSensor],
|
||||
to_remove: dict[str, EnergyPowerSensor],
|
||||
) -> None:
|
||||
"""Create a power sensor or keep an existing one."""
|
||||
@@ -988,3 +1030,302 @@ class EnergyPowerSensor(SensorEntity):
|
||||
"""Handle source sensor state changes."""
|
||||
self._update_state()
|
||||
self.async_write_ha_state()
|
||||
|
||||
|
||||
def _period_start(now: datetime, period: str) -> datetime:
|
||||
"""Return the local start of the period that contains now."""
|
||||
day = dt_util.as_local(now).date()
|
||||
if period == "month":
|
||||
day = day.replace(day=1)
|
||||
elif period == "year":
|
||||
day = day.replace(month=1, day=1)
|
||||
return dt_util.start_of_local_day(day)
|
||||
|
||||
|
||||
def _next_period_start(start: datetime, period: str) -> datetime:
|
||||
"""Return the local start of the period after the one that contains start."""
|
||||
day = dt_util.as_local(start).date()
|
||||
if period == "day":
|
||||
day += timedelta(days=1)
|
||||
elif period == "month":
|
||||
day = (day.replace(day=28) + timedelta(days=4)).replace(day=1)
|
||||
else:
|
||||
day = day.replace(year=day.year + 1, month=1, day=1)
|
||||
return dt_util.start_of_local_day(day)
|
||||
|
||||
|
||||
def _previous_period_start(start: datetime, period: str) -> datetime:
|
||||
"""Return the local start of the period before the one that contains start."""
|
||||
day = dt_util.as_local(start).date()
|
||||
if period == "day":
|
||||
day -= timedelta(days=1)
|
||||
elif period == "month":
|
||||
day = (day.replace(day=1) - timedelta(days=1)).replace(day=1)
|
||||
else:
|
||||
day = day.replace(year=day.year - 1, month=1, day=1)
|
||||
return dt_util.start_of_local_day(day)
|
||||
|
||||
|
||||
def _same_period_in_local_time(start: datetime) -> datetime:
|
||||
"""Return the start of the same calendar day in the local time zone."""
|
||||
return dt_util.start_of_local_day(start.date())
|
||||
|
||||
|
||||
def _parse_restored_datetime(value: Any) -> datetime | None:
|
||||
"""Parse a restored datetime."""
|
||||
return dt_util.parse_datetime(value) if isinstance(value, str) else None
|
||||
|
||||
|
||||
@dataclass
|
||||
class EnergyFixedCostSensorExtraStoredData(SensorExtraStoredData):
|
||||
"""Data to continue the total and know which periods are already charged."""
|
||||
|
||||
last_reset: datetime
|
||||
last_charged: datetime
|
||||
period: str
|
||||
|
||||
@override
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
"""Return a dict representation of the data."""
|
||||
data = super().as_dict()
|
||||
data["last_reset"] = self.last_reset.isoformat()
|
||||
data["last_charged"] = self.last_charged.isoformat()
|
||||
data["period"] = self.period
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
@override
|
||||
def from_dict(cls, restored: dict[str, Any]) -> Self | None:
|
||||
"""Initialize the data from a dict, if it has a total and its periods."""
|
||||
if (
|
||||
(extra := SensorExtraStoredData.from_dict(restored)) is None
|
||||
or not isinstance(extra.native_value, (int, float))
|
||||
or (last_reset := _parse_restored_datetime(restored.get("last_reset")))
|
||||
is None
|
||||
or (last_charged := _parse_restored_datetime(restored.get("last_charged")))
|
||||
is None
|
||||
or (period := restored.get("period")) not in ("day", "month", "year")
|
||||
):
|
||||
return None
|
||||
return cls(
|
||||
extra.native_value,
|
||||
extra.native_unit_of_measurement,
|
||||
last_reset,
|
||||
last_charged,
|
||||
period,
|
||||
)
|
||||
|
||||
|
||||
class EnergyFixedCostSensor(RestoreSensor):
|
||||
"""Add a fixed cost, like a standing charge, at the start of each period."""
|
||||
|
||||
_attr_entity_registry_visible_default = False
|
||||
_attr_has_entity_name = True
|
||||
_attr_should_poll = False
|
||||
_attr_device_class = SensorDeviceClass.MONETARY
|
||||
_attr_state_class = SensorStateClass.TOTAL
|
||||
|
||||
def __init__(self, config: FixedCostType) -> None:
|
||||
"""Initialize the sensor."""
|
||||
super().__init__()
|
||||
self._config = config
|
||||
self._attr_unique_id = f"fixed_cost_{config['id']}"
|
||||
self._attr_name = config["name"]
|
||||
self.entity_id = f"sensor.{slugify(config['name'])}_fixed_cost"
|
||||
# The start of the last period that was charged, in the local time zone
|
||||
self._last_charged: datetime
|
||||
self._unsub_charge: CALLBACK_TYPE | None = None
|
||||
self._unsub_amount_entity: CALLBACK_TYPE | None = None
|
||||
# SensorManager awaits add_finished; async_on_remove resolves it on the
|
||||
# abort path too, since add_to_platform_abort fires on-remove callbacks.
|
||||
self.add_finished: asyncio.Future[None] = (
|
||||
asyncio.get_running_loop().create_future()
|
||||
)
|
||||
self.async_on_remove(lambda: _set_result_unless_done(self.add_finished))
|
||||
|
||||
@override
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Restore the total and charge the periods that are due."""
|
||||
if (restored := await self.async_get_last_sensor_data()) is not None:
|
||||
self._attr_native_value = restored.native_value
|
||||
self._attr_last_reset = restored.last_reset
|
||||
self._last_charged = _same_period_in_local_time(restored.last_charged)
|
||||
if restored.period != self._config["period"]:
|
||||
self._async_period_changed(restored.period)
|
||||
else:
|
||||
# Start a new cycle at 0 instead of dropping a lost total. The first
|
||||
# state of a cycle is the zero point of the statistics, so charges
|
||||
# are only added after it.
|
||||
self._attr_native_value = 0.0
|
||||
self._attr_last_reset = dt_util.utcnow()
|
||||
# The current period is due
|
||||
self._last_charged = _previous_period_start(
|
||||
dt_util.utcnow(), self._config["period"]
|
||||
)
|
||||
|
||||
self.hass.data[DOMAIN]["fixed_cost_sensors"][self._config["id"]] = (
|
||||
self.entity_id
|
||||
)
|
||||
self._async_track_amount_entity()
|
||||
self.async_on_remove(
|
||||
self.hass.bus.async_listen(
|
||||
EVENT_CORE_CONFIG_UPDATE, self._async_core_config_updated
|
||||
)
|
||||
)
|
||||
self.async_on_remove(self._async_unsubscribe)
|
||||
# Runs after the platform writes the restored or zero state
|
||||
self._async_schedule_charge(dt_util.utcnow())
|
||||
_set_result_unless_done(self.add_finished)
|
||||
|
||||
@callback
|
||||
def _async_unsubscribe(self) -> None:
|
||||
"""Stop the timer and the amount entity listener."""
|
||||
if self._unsub_charge is not None:
|
||||
self._unsub_charge()
|
||||
self._unsub_charge = None
|
||||
if self._unsub_amount_entity is not None:
|
||||
self._unsub_amount_entity()
|
||||
self._unsub_amount_entity = None
|
||||
|
||||
@callback
|
||||
def _async_track_amount_entity(self) -> None:
|
||||
"""Charge a period that is due once the amount entity has a valid state."""
|
||||
if self._unsub_amount_entity is not None:
|
||||
self._unsub_amount_entity()
|
||||
self._unsub_amount_entity = None
|
||||
if (entity_id := self._config["entity_amount"]) is not None:
|
||||
self._unsub_amount_entity = async_track_state_change_event(
|
||||
self.hass, entity_id, self._async_charge
|
||||
)
|
||||
|
||||
@callback
|
||||
def _async_core_config_updated(self, event: Event) -> None:
|
||||
"""Move the next charge to the period start in a new time zone."""
|
||||
if "time_zone" not in event.data:
|
||||
return
|
||||
self._last_charged = _same_period_in_local_time(self._last_charged)
|
||||
self._async_charge()
|
||||
|
||||
@callback
|
||||
def _async_schedule_charge(self, point_in_time: datetime) -> None:
|
||||
"""Charge the periods that are due at a point in time."""
|
||||
if self._unsub_charge is not None:
|
||||
self._unsub_charge()
|
||||
self._unsub_charge = async_track_point_in_utc_time(
|
||||
self.hass, self._async_charge, point_in_time
|
||||
)
|
||||
|
||||
def _amount(self) -> float | None:
|
||||
"""Return the amount to charge per period, if it is known."""
|
||||
if (number_amount := self._config["number_amount"]) is not None:
|
||||
return number_amount
|
||||
if (
|
||||
state := self.hass.states.get(cast(str, self._config["entity_amount"]))
|
||||
) is None:
|
||||
return None
|
||||
currency = self.hass.config.currency
|
||||
# The amount is added as is, so it is not charged in any other unit
|
||||
if state.attributes.get(EntityStateAttribute.UNIT_OF_MEASUREMENT) not in (
|
||||
currency,
|
||||
f"{currency}/{self._config['period']}",
|
||||
):
|
||||
return None
|
||||
try:
|
||||
amount = float(state.state)
|
||||
except ValueError:
|
||||
return None
|
||||
return amount if math.isfinite(amount) else None
|
||||
|
||||
@callback
|
||||
def _async_charge(self, _: Any = None) -> None:
|
||||
"""Charge every period that started since the last charge."""
|
||||
period = self._config["period"]
|
||||
current = _period_start(dt_util.utcnow(), period)
|
||||
periods = 0
|
||||
start = self._last_charged
|
||||
while (start := _next_period_start(start, period)) <= current:
|
||||
periods += 1
|
||||
if periods and (amount := self._amount()) is not None:
|
||||
self._attr_native_value = cast(float, self.native_value) + amount * periods
|
||||
self._last_charged = current
|
||||
self.async_write_ha_state()
|
||||
self._async_schedule_charge(_next_period_start(current, period))
|
||||
|
||||
@callback
|
||||
def update_config(self, config: FixedCostType) -> None:
|
||||
"""Update the config."""
|
||||
old_config = self._config
|
||||
self._config = config
|
||||
self._attr_name = config["name"]
|
||||
# Only a sensor that is added has a timer, not a disabled one
|
||||
if self._unsub_charge is not None:
|
||||
self._async_config_changed(old_config)
|
||||
|
||||
@callback
|
||||
def _async_config_changed(self, old_config: FixedCostType) -> None:
|
||||
"""Apply a changed config to the added sensor."""
|
||||
if self._config["entity_amount"] != old_config["entity_amount"]:
|
||||
self._async_track_amount_entity()
|
||||
if (old_period := old_config["period"]) != self._config["period"]:
|
||||
self._async_period_changed(old_period)
|
||||
self._async_charge()
|
||||
self.async_write_ha_state()
|
||||
|
||||
@callback
|
||||
def _async_period_changed(self, old_period: str) -> None:
|
||||
"""Move the last charged period to the new period length."""
|
||||
now = dt_util.utcnow()
|
||||
period = self._config["period"]
|
||||
if self._last_charged >= _period_start(now, old_period):
|
||||
# The current period of the new length counts as charged
|
||||
self._last_charged = _period_start(now, period)
|
||||
else:
|
||||
# The amount was not known yet, the current period is still due
|
||||
self._last_charged = _previous_period_start(now, period)
|
||||
|
||||
@callback
|
||||
@override
|
||||
def async_entity_id_changed(self, old_entity_id: str) -> None:
|
||||
"""Update the entity ID stored for the frontend."""
|
||||
super().async_entity_id_changed(old_entity_id)
|
||||
self.hass.data[DOMAIN]["fixed_cost_sensors"][self._config["id"]] = (
|
||||
self.entity_id
|
||||
)
|
||||
|
||||
@override
|
||||
async def async_will_remove_from_hass(self) -> None:
|
||||
"""Handle removing from hass."""
|
||||
self.hass.data[DOMAIN]["fixed_cost_sensors"].pop(self._config["id"])
|
||||
await super().async_will_remove_from_hass()
|
||||
|
||||
@property
|
||||
@override
|
||||
def extra_restore_state_data(self) -> SensorExtraStoredData:
|
||||
"""Return the total together with its cycle and the last charged period."""
|
||||
return EnergyFixedCostSensorExtraStoredData(
|
||||
self.native_value,
|
||||
self.native_unit_of_measurement,
|
||||
cast(datetime, self.last_reset),
|
||||
self._last_charged,
|
||||
self._config["period"],
|
||||
)
|
||||
|
||||
@override
|
||||
async def async_get_last_sensor_data(
|
||||
self,
|
||||
) -> EnergyFixedCostSensorExtraStoredData | None:
|
||||
"""Return the restored data, if it is complete."""
|
||||
if (restored_last_extra_data := await self.async_get_last_extra_data()) is None:
|
||||
return None
|
||||
return EnergyFixedCostSensorExtraStoredData.from_dict(
|
||||
restored_last_extra_data.as_dict()
|
||||
)
|
||||
|
||||
@property
|
||||
@override
|
||||
def native_unit_of_measurement(self) -> str | None:
|
||||
"""Return the units of measurement."""
|
||||
return self.hass.config.currency
|
||||
|
||||
|
||||
type _ManagedSensor = EnergyCostSensor | EnergyPowerSensor | EnergyFixedCostSensor
|
||||
|
||||
@@ -71,6 +71,10 @@
|
||||
"description": "The following entities do not have an expected unit of measurement {price_units}:",
|
||||
"title": "[%key:component::energy::issues::entity_unexpected_unit_energy::title%]"
|
||||
},
|
||||
"entity_unexpected_unit_fixed_cost": {
|
||||
"description": "The following entities do not have an expected unit of measurement. Use {currency}, or {currency} per period of the fixed cost, such as {currency}/day for a daily fixed cost:",
|
||||
"title": "[%key:component::energy::issues::entity_unexpected_unit_energy::title%]"
|
||||
},
|
||||
"entity_unexpected_unit_gas": {
|
||||
"description": "The following entities do not have an expected unit of measurement (either of {energy_units} for an energy sensor or either of {gas_units} for a gas sensor):",
|
||||
"title": "[%key:component::energy::issues::entity_unexpected_unit_energy::title%]"
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from collections.abc import Mapping, Sequence
|
||||
import dataclasses
|
||||
import functools
|
||||
import math
|
||||
|
||||
from homeassistant.components import recorder, sensor
|
||||
from homeassistant.const import (
|
||||
@@ -37,6 +38,7 @@ ENERGY_PRICE_UNITS = tuple(
|
||||
f"/{unit}" for units in ENERGY_USAGE_UNITS.values() for unit in units
|
||||
)
|
||||
ENERGY_UNIT_ERROR = "entity_unexpected_unit_energy"
|
||||
FIXED_COST_UNIT_ERROR = "entity_unexpected_unit_fixed_cost"
|
||||
ENERGY_PRICE_UNIT_ERROR = "entity_unexpected_unit_energy_price"
|
||||
POWER_UNIT_ERROR = "entity_unexpected_unit_power"
|
||||
GAS_USAGE_DEVICE_CLASSES = (
|
||||
@@ -114,6 +116,8 @@ def _get_placeholders(hass: HomeAssistant, issue_type: str) -> dict[str, str] |
|
||||
return {
|
||||
"price_units": ", ".join(f"{currency}{unit}" for unit in WATER_PRICE_UNITS),
|
||||
}
|
||||
if issue_type == FIXED_COST_UNIT_ERROR:
|
||||
return {"currency": currency}
|
||||
if issue_type == VOLUME_FLOW_RATE_UNIT_ERROR:
|
||||
return {
|
||||
"flow_rate_units": ", ".join(
|
||||
@@ -170,6 +174,7 @@ class EnergyPreferencesValidation:
|
||||
device_consumption_gas: list[ValidationIssues] = dataclasses.field(
|
||||
default_factory=list
|
||||
)
|
||||
fixed_costs: list[ValidationIssues] = dataclasses.field(default_factory=list)
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
"""Return dictionary version."""
|
||||
@@ -190,6 +195,10 @@ class EnergyPreferencesValidation:
|
||||
[dataclasses.asdict(issue) for issue in issues.issues.values()]
|
||||
for issues in self.device_consumption_gas
|
||||
],
|
||||
"fixed_costs": [
|
||||
[dataclasses.asdict(issue) for issue in issues.issues.values()]
|
||||
for issues in self.fixed_costs
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -434,6 +443,46 @@ def _async_validate_cost_stat(
|
||||
issues.add_issue(hass, "entity_state_class_measurement_no_last_reset", stat_id)
|
||||
|
||||
|
||||
@callback
|
||||
def _async_validate_fixed_cost_entity(
|
||||
hass: HomeAssistant, entity_id: str, period: str, issues: ValidationIssues
|
||||
) -> None:
|
||||
"""Validate the entity holding the amount of a fixed cost."""
|
||||
if (state := hass.states.get(entity_id)) is None:
|
||||
issues.add_issue(hass, "entity_not_defined", entity_id)
|
||||
return
|
||||
|
||||
try:
|
||||
amount = float(state.state)
|
||||
except ValueError:
|
||||
amount = math.nan
|
||||
if not math.isfinite(amount):
|
||||
issues.add_issue(hass, "entity_state_non_numeric", entity_id, state.state)
|
||||
return
|
||||
|
||||
currency = hass.config.currency
|
||||
unit = state.attributes.get(EntityStateAttribute.UNIT_OF_MEASUREMENT)
|
||||
# The amount is added as is, so the unit must be the currency itself
|
||||
if unit not in (currency, f"{currency}/{period}"):
|
||||
issues.add_issue(hass, FIXED_COST_UNIT_ERROR, entity_id, unit)
|
||||
|
||||
|
||||
@callback
|
||||
def _async_validate_fixed_cost(
|
||||
hass: HomeAssistant, fixed_cost: data.FixedCostType, issues: ValidationIssues
|
||||
) -> None:
|
||||
"""Validate the amount entity and the sensor of a fixed cost."""
|
||||
if (entity_id := fixed_cost["entity_amount"]) is not None:
|
||||
_async_validate_fixed_cost_entity(hass, entity_id, fixed_cost["period"], issues)
|
||||
|
||||
if (
|
||||
sensor_entity_id := hass.data[DOMAIN]["fixed_cost_sensors"].get(
|
||||
fixed_cost["id"]
|
||||
)
|
||||
) is not None and not recorder.is_entity_recorded(hass, sensor_entity_id):
|
||||
issues.add_issue(hass, "recorder_untracked", sensor_entity_id)
|
||||
|
||||
|
||||
@callback
|
||||
def _async_validate_auto_generated_cost_entity(
|
||||
hass: HomeAssistant, energy_entity_id: str, issues: ValidationIssues
|
||||
@@ -972,6 +1021,15 @@ async def async_validate(hass: HomeAssistant) -> EnergyPreferencesValidation:
|
||||
)
|
||||
)
|
||||
|
||||
for fixed_cost in manager.data.get("fixed_costs", []):
|
||||
fixed_cost_result = ValidationIssues()
|
||||
result.fixed_costs.append(fixed_cost_result)
|
||||
validate_calls.append(
|
||||
functools.partial(
|
||||
_async_validate_fixed_cost, hass, fixed_cost, fixed_cost_result
|
||||
)
|
||||
)
|
||||
|
||||
# Fetch the needed statistics metadata
|
||||
statistics_metadata.update(
|
||||
await recorder.get_instance(hass).async_add_executor_job(
|
||||
|
||||
@@ -23,6 +23,7 @@ from .const import DOMAIN
|
||||
from .data import (
|
||||
DEVICE_CONSUMPTION_SCHEMA,
|
||||
ENERGY_SOURCE_SCHEMA,
|
||||
FIXED_COSTS_SCHEMA,
|
||||
EnergyManager,
|
||||
EnergyPreferencesUpdate,
|
||||
async_get_manager,
|
||||
@@ -128,6 +129,7 @@ def ws_get_prefs(
|
||||
probatio.Optional("device_consumption"): [DEVICE_CONSUMPTION_SCHEMA],
|
||||
probatio.Optional("device_consumption_water"): [DEVICE_CONSUMPTION_SCHEMA],
|
||||
probatio.Optional("device_consumption_gas"): [DEVICE_CONSUMPTION_SCHEMA],
|
||||
probatio.Optional("fixed_costs"): FIXED_COSTS_SCHEMA,
|
||||
}
|
||||
)
|
||||
@websocket_api.async_response
|
||||
@@ -162,6 +164,7 @@ async def ws_info(
|
||||
msg["id"],
|
||||
{
|
||||
"cost_sensors": hass.data[DOMAIN]["cost_sensors"],
|
||||
"fixed_cost_sensors": hass.data[DOMAIN]["fixed_cost_sensors"],
|
||||
"solar_forecast_domains": list(forecast_platforms),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -8,10 +8,12 @@ import pytest
|
||||
from homeassistant.components.energy.data import (
|
||||
BATTERY_SOURCE_SCHEMA,
|
||||
ENERGY_SOURCE_SCHEMA,
|
||||
FIXED_COSTS_SCHEMA,
|
||||
FLOW_FROM_GRID_SOURCE_SCHEMA,
|
||||
FLOW_TO_GRID_SOURCE_SCHEMA,
|
||||
GAS_SOURCE_SCHEMA,
|
||||
POWER_CONFIG_SCHEMA,
|
||||
STORAGE_MINOR_VERSION,
|
||||
WATER_SOURCE_SCHEMA,
|
||||
EnergyManager,
|
||||
)
|
||||
@@ -184,7 +186,7 @@ async def test_energy_preferences_migration_from_version_1_4(
|
||||
|
||||
assert manager.data is not None
|
||||
assert manager.data["energy_sources"] == [grid_source, gas_source]
|
||||
assert hass_storage["energy"]["minor_version"] == 5
|
||||
assert hass_storage["energy"]["minor_version"] == STORAGE_MINOR_VERSION
|
||||
assert hass_storage["energy"]["data"]["energy_sources"] == [
|
||||
grid_source,
|
||||
gas_source,
|
||||
@@ -1618,3 +1620,168 @@ async def test_battery_power_config_directions_sets_stat_rate(
|
||||
|
||||
assert manager.data is not None
|
||||
assert manager.data["energy_sources"][0]["stat_rate"] == stat_rate
|
||||
|
||||
|
||||
async def test_energy_preferences_migration_from_version_1_5(
|
||||
hass: HomeAssistant, hass_storage: dict[str, Any]
|
||||
) -> None:
|
||||
"""Test that fixed_costs is added when migrating from v1.5 to v1.6."""
|
||||
hass_storage["energy"] = {
|
||||
"version": 1,
|
||||
"minor_version": 5,
|
||||
"key": "energy",
|
||||
"data": {
|
||||
"energy_sources": [],
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
},
|
||||
}
|
||||
|
||||
manager = EnergyManager(hass)
|
||||
await manager.async_initialize()
|
||||
|
||||
assert manager.data is not None
|
||||
assert manager.data["fixed_costs"] == []
|
||||
assert hass_storage["energy"]["minor_version"] == STORAGE_MINOR_VERSION
|
||||
|
||||
|
||||
async def test_energy_preferences_update_fixed_costs(hass: HomeAssistant) -> None:
|
||||
"""Test fixed costs are stored on update."""
|
||||
manager = EnergyManager(hass)
|
||||
await manager.async_initialize()
|
||||
fixed_costs = [
|
||||
{
|
||||
"id": "standing_charge",
|
||||
"type": "grid",
|
||||
"name": "Standing charge",
|
||||
"number_amount": 0.62,
|
||||
"entity_amount": None,
|
||||
"period": "day",
|
||||
}
|
||||
]
|
||||
|
||||
await manager.async_update({"fixed_costs": fixed_costs})
|
||||
|
||||
assert manager.data is not None
|
||||
assert manager.data["fixed_costs"] == fixed_costs
|
||||
assert manager.data["energy_sources"] == []
|
||||
|
||||
|
||||
FIXED_COST = {
|
||||
"id": "standing_charge",
|
||||
"type": "grid",
|
||||
"name": "Standing charge",
|
||||
"number_amount": 0.62,
|
||||
"entity_amount": None,
|
||||
"period": "day",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("fixed_costs", "expected"),
|
||||
[
|
||||
pytest.param([FIXED_COST], [FIXED_COST], id="number_amount"),
|
||||
pytest.param(
|
||||
[
|
||||
{
|
||||
"id": "gas_standing_charge",
|
||||
"type": "gas",
|
||||
"name": "Gas standing charge",
|
||||
"entity_amount": "sensor.gas_standing_charge",
|
||||
"period": "month",
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"id": "gas_standing_charge",
|
||||
"type": "gas",
|
||||
"name": "Gas standing charge",
|
||||
"number_amount": None,
|
||||
"entity_amount": "sensor.gas_standing_charge",
|
||||
"period": "month",
|
||||
}
|
||||
],
|
||||
id="entity_amount",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
FIXED_COST,
|
||||
{
|
||||
**FIXED_COST,
|
||||
"id": "tax_rebate",
|
||||
"name": "Energy tax rebate",
|
||||
"number_amount": "-0.4561",
|
||||
"period": "year",
|
||||
},
|
||||
{**FIXED_COST, "id": "water", "type": "water"},
|
||||
],
|
||||
[
|
||||
FIXED_COST,
|
||||
{
|
||||
**FIXED_COST,
|
||||
"id": "tax_rebate",
|
||||
"name": "Energy tax rebate",
|
||||
"number_amount": -0.4561,
|
||||
"period": "year",
|
||||
},
|
||||
{**FIXED_COST, "id": "water", "type": "water"},
|
||||
],
|
||||
id="several_with_negative_amount",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_fixed_costs_schema_valid(
|
||||
fixed_costs: list[dict[str, Any]], expected: list[dict[str, Any]]
|
||||
) -> None:
|
||||
"""Test valid fixed costs pass validation."""
|
||||
assert FIXED_COSTS_SCHEMA(fixed_costs) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("fixed_costs", "message"),
|
||||
[
|
||||
pytest.param(
|
||||
[{**FIXED_COST, "number_amount": None}],
|
||||
"Define either an entity or a fixed number for the amount",
|
||||
id="no_amount",
|
||||
),
|
||||
pytest.param(
|
||||
[{**FIXED_COST, "entity_amount": "sensor.standing_charge"}],
|
||||
"Define either an entity or a fixed number for the amount",
|
||||
id="both_amounts",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{
|
||||
**FIXED_COST,
|
||||
"number_amount": None,
|
||||
"entity_amount": "external:standing_charge",
|
||||
}
|
||||
],
|
||||
"entity_amount",
|
||||
id="external_statistic_amount",
|
||||
),
|
||||
pytest.param(
|
||||
[FIXED_COST, {**FIXED_COST, "name": "Another"}],
|
||||
"Cannot specify standing_charge more than once",
|
||||
id="duplicate_id",
|
||||
),
|
||||
pytest.param(
|
||||
[{**FIXED_COST, "number_amount": "nan"}], "number_amount", id="nan"
|
||||
),
|
||||
pytest.param(
|
||||
[{**FIXED_COST, "number_amount": "inf"}], "number_amount", id="infinity"
|
||||
),
|
||||
pytest.param([{**FIXED_COST, "type": "solar"}], "type", id="solar_type"),
|
||||
pytest.param([{**FIXED_COST, "period": "week"}], "period", id="week_period"),
|
||||
pytest.param([{**FIXED_COST, "name": ""}], "name", id="empty_name"),
|
||||
pytest.param([{**FIXED_COST, "id": ""}], "id", id="empty_id"),
|
||||
],
|
||||
)
|
||||
async def test_fixed_costs_schema_invalid(
|
||||
fixed_costs: list[dict[str, Any]], message: str
|
||||
) -> None:
|
||||
"""Test invalid fixed costs are rejected."""
|
||||
with pytest.raises(probatio.Invalid, match=message):
|
||||
FIXED_COSTS_SCHEMA(fixed_costs)
|
||||
|
||||
@@ -3883,3 +3883,648 @@ async def test_power_sensor_battery_measurement_switch(
|
||||
assert hass.states.get(BATTERY_DIRECTIONS_NET_POWER).state == "unavailable"
|
||||
assert hass.states.get(total_net_power).state == "0.0"
|
||||
assert manager.data["energy_sources"][0]["stat_rate"] == total_net_power
|
||||
|
||||
|
||||
FIXED_COST = {
|
||||
"id": "standing_charge",
|
||||
"type": "grid",
|
||||
"name": "Standing charge",
|
||||
"number_amount": 0.62,
|
||||
"entity_amount": None,
|
||||
"period": "day",
|
||||
}
|
||||
FIXED_COST_ENTITY_ID = "sensor.standing_charge_fixed_cost"
|
||||
FIXED_COST_AMOUNT_ATTRIBUTES = {ATTR_UNIT_OF_MEASUREMENT: "EUR"}
|
||||
# The start of the day of the frozen time, in Europe/Amsterdam
|
||||
FIXED_COST_TODAY = "2022-04-19T00:00:00+02:00"
|
||||
|
||||
|
||||
async def _setup_fixed_costs(
|
||||
hass: HomeAssistant,
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass_storage: dict[str, Any],
|
||||
*fixed_costs: dict[str, Any],
|
||||
) -> None:
|
||||
await hass.config.async_set_time_zone("Europe/Amsterdam")
|
||||
energy_data = data.EnergyManager.default_preferences()
|
||||
energy_data["fixed_costs"] = list(fixed_costs)
|
||||
hass_storage[data.STORAGE_KEY] = {"version": 1, "data": energy_data}
|
||||
await setup_integration(hass)
|
||||
# Run the charge that is due once the sensor is added
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
async def _move_to(
|
||||
hass: HomeAssistant, freezer: FrozenDateTimeFactory, time: str
|
||||
) -> None:
|
||||
freezer.move_to(time)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
def _fixed_cost_total(hass: HomeAssistant) -> float:
|
||||
return float(hass.states.get(FIXED_COST_ENTITY_ID).state)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("period", "next_period_start"),
|
||||
[
|
||||
("day", "2022-04-19 22:00:00+00:00"),
|
||||
("month", "2022-04-30 22:00:00+00:00"),
|
||||
# Midnight in winter time
|
||||
("year", "2022-12-31 23:00:00+00:00"),
|
||||
],
|
||||
)
|
||||
async def test_fixed_cost_sensor_charges_at_period_start(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
entity_registry: er.EntityRegistry,
|
||||
frozen_time: FrozenDateTimeFactory,
|
||||
period: str,
|
||||
next_period_start: str,
|
||||
) -> None:
|
||||
"""Test a fixed cost is charged for the current period and each new one."""
|
||||
await _setup_fixed_costs(
|
||||
hass, setup_integration, hass_storage, {**FIXED_COST, "period": period}
|
||||
)
|
||||
|
||||
state = hass.states.get(FIXED_COST_ENTITY_ID)
|
||||
assert state.state == "0.62"
|
||||
assert state.attributes == {
|
||||
ATTR_FRIENDLY_NAME: "Standing charge",
|
||||
ATTR_DEVICE_CLASS: SensorDeviceClass.MONETARY,
|
||||
ATTR_STATE_CLASS: SensorStateClass.TOTAL,
|
||||
ATTR_UNIT_OF_MEASUREMENT: "EUR",
|
||||
ATTR_LAST_RESET: dt_util.utcnow().isoformat(),
|
||||
}
|
||||
entry = entity_registry.async_get(FIXED_COST_ENTITY_ID)
|
||||
assert entry.unique_id == "fixed_cost_standing_charge"
|
||||
assert entry.hidden_by is er.RegistryEntryHider.INTEGRATION
|
||||
assert hass.data[DOMAIN]["fixed_cost_sensors"] == {
|
||||
"standing_charge": FIXED_COST_ENTITY_ID
|
||||
}
|
||||
|
||||
next_start = dt_util.parse_datetime(next_period_start)
|
||||
await _move_to(hass, frozen_time, next_start - timedelta(seconds=1))
|
||||
assert _fixed_cost_total(hass) == pytest.approx(0.62)
|
||||
|
||||
await _move_to(hass, frozen_time, next_start)
|
||||
assert _fixed_cost_total(hass) == pytest.approx(1.24)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_first_charge_in_statistics(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test the first charge is added after the zero point of the statistics."""
|
||||
now = dt_util.utcnow()
|
||||
|
||||
def _compile_statistics(_):
|
||||
with session_scope(hass=hass) as session:
|
||||
return compile_statistics(
|
||||
hass, session, now, now + timedelta(seconds=1), {}
|
||||
).platform_stats
|
||||
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, FIXED_COST)
|
||||
await async_wait_recording_done(hass)
|
||||
|
||||
all_statistics = await hass.loop.run_in_executor(None, _compile_statistics, hass)
|
||||
statistics = get_statistics_for_entity(all_statistics, FIXED_COST_ENTITY_ID)
|
||||
assert statistics["stat"]["sum"] == pytest.approx(0.62)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_daylight_saving_time(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
frozen_time: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test a daily charge follows local midnight when the clocks change."""
|
||||
frozen_time.move_to("2022-03-26 12:00:00+00:00")
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, FIXED_COST)
|
||||
assert _fixed_cost_total(hass) == pytest.approx(0.62)
|
||||
|
||||
await _move_to(hass, frozen_time, "2022-03-26 23:00:00+00:00")
|
||||
assert _fixed_cost_total(hass) == pytest.approx(1.24)
|
||||
|
||||
# The clocks go forward, so the next midnight is an hour earlier in UTC
|
||||
await _move_to(hass, frozen_time, "2022-03-27 21:59:59+00:00")
|
||||
assert _fixed_cost_total(hass) == pytest.approx(1.24)
|
||||
|
||||
await _move_to(hass, frozen_time, "2022-03-27 22:00:00+00:00")
|
||||
assert _fixed_cost_total(hass) == pytest.approx(1.86)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_negative_amount(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test a negative fixed cost, like a tax rebate, lowers the total."""
|
||||
await _setup_fixed_costs(
|
||||
hass,
|
||||
setup_integration,
|
||||
hass_storage,
|
||||
{**FIXED_COST, "number_amount": -0.4561},
|
||||
)
|
||||
|
||||
assert _fixed_cost_total(hass) == pytest.approx(-0.4561)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("last_charged", "expected_total"),
|
||||
[
|
||||
pytest.param(FIXED_COST_TODAY, 10.0, id="charged_today"),
|
||||
pytest.param("2022-04-17T00:00:00+02:00", 11.24, id="missed_two_days"),
|
||||
],
|
||||
)
|
||||
async def test_fixed_cost_sensor_restore(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
last_charged: str | None,
|
||||
expected_total: float,
|
||||
) -> None:
|
||||
"""Test the total continues and only periods that are due are charged."""
|
||||
mock_restore_cache_with_extra_data(
|
||||
hass,
|
||||
[
|
||||
(
|
||||
State(FIXED_COST_ENTITY_ID, "10.0"),
|
||||
{
|
||||
"native_value": 10.0,
|
||||
"native_unit_of_measurement": "EUR",
|
||||
"last_reset": "2022-01-01T00:00:00+00:00",
|
||||
"last_charged": last_charged,
|
||||
"period": "day",
|
||||
},
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, FIXED_COST)
|
||||
|
||||
state = hass.states.get(FIXED_COST_ENTITY_ID)
|
||||
assert float(state.state) == pytest.approx(expected_total)
|
||||
assert state.attributes[ATTR_LAST_RESET] == "2022-01-01T00:00:00+00:00"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"extra_data",
|
||||
[
|
||||
pytest.param(
|
||||
{
|
||||
"native_value": 10.0,
|
||||
"native_unit_of_measurement": "EUR",
|
||||
"last_charged": FIXED_COST_TODAY,
|
||||
},
|
||||
id="no_last_reset",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"native_value": "abc",
|
||||
"native_unit_of_measurement": "EUR",
|
||||
"last_reset": "2022-01-01T00:00:00+00:00",
|
||||
"last_charged": FIXED_COST_TODAY,
|
||||
},
|
||||
id="non_numeric_total",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"native_value": 10.0,
|
||||
"native_unit_of_measurement": "EUR",
|
||||
"last_reset": "2022-01-01T00:00:00+00:00",
|
||||
"last_charged": "yesterday",
|
||||
},
|
||||
id="invalid_last_charged",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"native_value": 10.0,
|
||||
"native_unit_of_measurement": "EUR",
|
||||
"last_reset": "2022-01-01T00:00:00+00:00",
|
||||
"last_charged": None,
|
||||
"period": "day",
|
||||
},
|
||||
id="no_last_charged",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"native_value": 10.0,
|
||||
"native_unit_of_measurement": "EUR",
|
||||
"last_reset": "2022-01-01T00:00:00+00:00",
|
||||
"last_charged": FIXED_COST_TODAY,
|
||||
},
|
||||
id="no_period",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_fixed_cost_sensor_restore_invalid(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
extra_data: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test incomplete restore data starts a new cycle."""
|
||||
mock_restore_cache_with_extra_data(
|
||||
hass, [(State(FIXED_COST_ENTITY_ID, "10.0"), extra_data)]
|
||||
)
|
||||
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, FIXED_COST)
|
||||
|
||||
state = hass.states.get(FIXED_COST_ENTITY_ID)
|
||||
assert state.state == "0.62"
|
||||
assert state.attributes[ATTR_LAST_RESET] == dt_util.utcnow().isoformat()
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_saves_restore_data(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test the total is stored with its cycle and the last charged period."""
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, FIXED_COST)
|
||||
|
||||
[stored_state] = restore_state.async_get(hass).async_get_stored_states()
|
||||
|
||||
assert json_loads(json_bytes(stored_state.extra_data.as_dict())) == {
|
||||
"native_value": 0.62,
|
||||
"native_unit_of_measurement": "EUR",
|
||||
"last_reset": dt_util.utcnow().isoformat(),
|
||||
"last_charged": "2022-04-19T00:00:00+02:00",
|
||||
"period": "day",
|
||||
}
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_entity_amount(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
frozen_time: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test an amount entity is charged once it has a valid state."""
|
||||
await _setup_fixed_costs(
|
||||
hass,
|
||||
setup_integration,
|
||||
hass_storage,
|
||||
{**FIXED_COST, "number_amount": None, "entity_amount": "sensor.amount"},
|
||||
)
|
||||
assert _fixed_cost_total(hass) == 0
|
||||
|
||||
hass.states.async_set("sensor.amount", "unavailable", FIXED_COST_AMOUNT_ATTRIBUTES)
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == 0
|
||||
|
||||
hass.states.async_set("sensor.amount", "0.5", FIXED_COST_AMOUNT_ATTRIBUTES)
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == pytest.approx(0.5)
|
||||
|
||||
# A new amount is charged from the next period
|
||||
hass.states.async_set("sensor.amount", "0.7", FIXED_COST_AMOUNT_ATTRIBUTES)
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == pytest.approx(0.5)
|
||||
|
||||
await _move_to(hass, frozen_time, "2022-04-19 22:00:00+00:00")
|
||||
assert _fixed_cost_total(hass) == pytest.approx(1.2)
|
||||
|
||||
# Unknown at the period start, so charged once the amount is known
|
||||
hass.states.async_set("sensor.amount", "nan", FIXED_COST_AMOUNT_ATTRIBUTES)
|
||||
await _move_to(hass, frozen_time, "2022-04-20 22:00:00+00:00")
|
||||
assert _fixed_cost_total(hass) == pytest.approx(1.2)
|
||||
|
||||
hass.states.async_set("sensor.amount", "0.8", FIXED_COST_AMOUNT_ATTRIBUTES)
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == pytest.approx(2.0)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_entity_amount_unit(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test an amount in another unit is charged once the unit is corrected."""
|
||||
hass.states.async_set(
|
||||
"sensor.amount", "30", {ATTR_UNIT_OF_MEASUREMENT: "EUR/month"}
|
||||
)
|
||||
await _setup_fixed_costs(
|
||||
hass,
|
||||
setup_integration,
|
||||
hass_storage,
|
||||
{**FIXED_COST, "number_amount": None, "entity_amount": "sensor.amount"},
|
||||
)
|
||||
assert _fixed_cost_total(hass) == 0
|
||||
|
||||
hass.states.async_set("sensor.amount", "1", {ATTR_UNIT_OF_MEASUREMENT: "EUR/day"})
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == pytest.approx(1)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_entity_amount_unknown_for_days(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
frozen_time: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test every period since the fixed cost was added waits for the amount."""
|
||||
await _setup_fixed_costs(
|
||||
hass,
|
||||
setup_integration,
|
||||
hass_storage,
|
||||
{**FIXED_COST, "number_amount": None, "entity_amount": "sensor.amount"},
|
||||
)
|
||||
await _move_to(hass, frozen_time, "2022-04-20 22:00:00+00:00")
|
||||
assert _fixed_cost_total(hass) == 0
|
||||
|
||||
hass.states.async_set("sensor.amount", "0.5", FIXED_COST_AMOUNT_ATTRIBUTES)
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == pytest.approx(1.5)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_update_config(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
frozen_time: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test a changed fixed cost applies from the next period."""
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, FIXED_COST)
|
||||
manager = await async_get_manager(hass)
|
||||
|
||||
await manager.async_update(
|
||||
{"fixed_costs": [{**FIXED_COST, "name": "Network fee", "number_amount": 0.7}]}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
state = hass.states.get(FIXED_COST_ENTITY_ID)
|
||||
assert float(state.state) == pytest.approx(0.62)
|
||||
assert state.attributes[ATTR_FRIENDLY_NAME] == "Network fee"
|
||||
|
||||
await _move_to(hass, frozen_time, "2022-04-19 22:00:00+00:00")
|
||||
assert _fixed_cost_total(hass) == pytest.approx(1.32)
|
||||
|
||||
# The current month counts as charged, the next one starts on May 1
|
||||
await manager.async_update(
|
||||
{"fixed_costs": [{**FIXED_COST, "number_amount": 0.7, "period": "month"}]}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
await _move_to(hass, frozen_time, "2022-04-20 22:00:00+00:00")
|
||||
assert _fixed_cost_total(hass) == pytest.approx(1.32)
|
||||
|
||||
await _move_to(hass, frozen_time, "2022-04-30 22:00:00+00:00")
|
||||
assert _fixed_cost_total(hass) == pytest.approx(2.02)
|
||||
|
||||
# The days since the start of the month are not charged again
|
||||
await _move_to(hass, frozen_time, "2022-05-10 12:00:00+00:00")
|
||||
await manager.async_update(
|
||||
{"fixed_costs": [{**FIXED_COST, "number_amount": 0.7, "period": "day"}]}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == pytest.approx(2.02)
|
||||
|
||||
await _move_to(hass, frozen_time, "2022-05-10 22:00:00+00:00")
|
||||
assert _fixed_cost_total(hass) == pytest.approx(2.72)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_period_change_while_amount_unknown(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test a period change keeps the current period due until it is charged."""
|
||||
fixed_cost = {**FIXED_COST, "number_amount": None, "entity_amount": "sensor.amount"}
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, fixed_cost)
|
||||
manager = await async_get_manager(hass)
|
||||
|
||||
await manager.async_update({"fixed_costs": [{**fixed_cost, "period": "month"}]})
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == 0
|
||||
|
||||
hass.states.async_set("sensor.amount", "5", FIXED_COST_AMOUNT_ATTRIBUTES)
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == pytest.approx(5)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_restore_with_other_period(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test a period changed while the sensor was not running is not charged again."""
|
||||
mock_restore_cache_with_extra_data(
|
||||
hass,
|
||||
[
|
||||
(
|
||||
State(FIXED_COST_ENTITY_ID, "10.0"),
|
||||
{
|
||||
"native_value": 10.0,
|
||||
"native_unit_of_measurement": "EUR",
|
||||
"last_reset": "2022-01-01T00:00:00+00:00",
|
||||
"last_charged": "2022-04-01T00:00:00+02:00",
|
||||
"period": "month",
|
||||
},
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, FIXED_COST)
|
||||
|
||||
assert _fixed_cost_total(hass) == pytest.approx(10.0)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_amount_entity_replaced(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test a period that waited for its amount entity is charged with a number."""
|
||||
fixed_cost = {**FIXED_COST, "number_amount": None, "entity_amount": "sensor.amount"}
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, fixed_cost)
|
||||
manager = await async_get_manager(hass)
|
||||
assert _fixed_cost_total(hass) == 0
|
||||
|
||||
await manager.async_update({"fixed_costs": [FIXED_COST]})
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == pytest.approx(0.62)
|
||||
|
||||
hass.states.async_set("sensor.amount", "0.5", FIXED_COST_AMOUNT_ATTRIBUTES)
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == pytest.approx(0.62)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_time_zone_change_east(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
frozen_time: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test a time zone where the next day already started charges that day."""
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, FIXED_COST)
|
||||
await hass.config.async_update(time_zone="America/Los_Angeles")
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == pytest.approx(0.62)
|
||||
|
||||
# 20:00 on April 19 in Los Angeles, 05:00 on April 20 in Amsterdam
|
||||
await _move_to(hass, frozen_time, "2022-04-20 03:00:00+00:00")
|
||||
assert _fixed_cost_total(hass) == pytest.approx(0.62)
|
||||
|
||||
await hass.config.async_update(time_zone="Europe/Amsterdam")
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == pytest.approx(1.24)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_restore_in_other_time_zone(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test a day charged in another time zone is not charged again."""
|
||||
mock_restore_cache_with_extra_data(
|
||||
hass,
|
||||
[
|
||||
(
|
||||
State(FIXED_COST_ENTITY_ID, "10.0"),
|
||||
{
|
||||
"native_value": 10.0,
|
||||
"native_unit_of_measurement": "EUR",
|
||||
"last_reset": "2022-01-01T00:00:00+00:00",
|
||||
"last_charged": FIXED_COST_TODAY,
|
||||
"period": "day",
|
||||
},
|
||||
)
|
||||
],
|
||||
)
|
||||
await hass.config.async_set_time_zone("America/Los_Angeles")
|
||||
energy_data = data.EnergyManager.default_preferences()
|
||||
energy_data["fixed_costs"] = [FIXED_COST]
|
||||
hass_storage[data.STORAGE_KEY] = {"version": 1, "data": energy_data}
|
||||
await setup_integration(hass)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert _fixed_cost_total(hass) == pytest.approx(10.0)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_time_zone_change(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
frozen_time: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test the next charge moves to midnight in a new time zone."""
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, FIXED_COST)
|
||||
|
||||
await hass.config.async_update(currency="USD")
|
||||
await hass.config.async_update(time_zone="America/New_York")
|
||||
await hass.async_block_till_done()
|
||||
assert _fixed_cost_total(hass) == pytest.approx(0.62)
|
||||
|
||||
await _move_to(hass, frozen_time, "2022-04-19 22:00:00+00:00")
|
||||
assert _fixed_cost_total(hass) == pytest.approx(0.62)
|
||||
|
||||
await _move_to(hass, frozen_time, "2022-04-20 04:00:00+00:00")
|
||||
assert _fixed_cost_total(hass) == pytest.approx(1.24)
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_rename(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
entity_registry: er.EntityRegistry,
|
||||
) -> None:
|
||||
"""Test the entity ID for the frontend follows a renamed sensor."""
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, FIXED_COST)
|
||||
|
||||
entity_registry.async_update_entity(
|
||||
FIXED_COST_ENTITY_ID, new_entity_id="sensor.network_fee"
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.data[DOMAIN]["fixed_cost_sensors"] == {
|
||||
"standing_charge": "sensor.network_fee"
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"amount",
|
||||
[
|
||||
{"number_amount": 0.62, "entity_amount": None},
|
||||
{"number_amount": None, "entity_amount": "sensor.amount"},
|
||||
],
|
||||
)
|
||||
async def test_fixed_cost_sensor_removed(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
entity_registry: er.EntityRegistry,
|
||||
amount: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test deleting a fixed cost removes its sensor and registry entry."""
|
||||
await _setup_fixed_costs(
|
||||
hass, setup_integration, hass_storage, {**FIXED_COST, **amount}
|
||||
)
|
||||
manager = await async_get_manager(hass)
|
||||
|
||||
await manager.async_update({"fixed_costs": []})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(FIXED_COST_ENTITY_ID) is None
|
||||
assert entity_registry.async_get(FIXED_COST_ENTITY_ID) is None
|
||||
assert hass.data[DOMAIN]["fixed_cost_sensors"] == {}
|
||||
|
||||
# The same fixed cost can be added again right away
|
||||
await manager.async_update({"fixed_costs": [{**FIXED_COST, **amount}]})
|
||||
assert hass.data[DOMAIN]["fixed_cost_sensors"] == {
|
||||
"standing_charge": FIXED_COST_ENTITY_ID
|
||||
}
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_disabled_after_added(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
entity_registry: er.EntityRegistry,
|
||||
frozen_time: FrozenDateTimeFactory,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test a fixed cost sensor disabled while running is left alone."""
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, FIXED_COST)
|
||||
manager = await async_get_manager(hass)
|
||||
entity_registry.async_update_entity(
|
||||
FIXED_COST_ENTITY_ID, disabled_by=er.RegistryEntryDisabler.USER
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
await manager.async_update({"fixed_costs": [{**FIXED_COST, "name": "Fee"}]})
|
||||
await _move_to(hass, frozen_time, "2022-04-19 22:00:00+00:00")
|
||||
|
||||
assert hass.states.get(FIXED_COST_ENTITY_ID) is None
|
||||
assert "while it is disabled" not in caplog.text
|
||||
|
||||
|
||||
async def test_fixed_cost_sensor_disabled(
|
||||
setup_integration: Callable[[HomeAssistant], Coroutine[Any, Any, None]],
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
entity_registry: er.EntityRegistry,
|
||||
) -> None:
|
||||
"""Test a disabled fixed cost sensor can be updated and deleted."""
|
||||
entity_registry.async_get_or_create(
|
||||
"sensor",
|
||||
DOMAIN,
|
||||
"fixed_cost_standing_charge",
|
||||
suggested_object_id="standing_charge_fixed_cost",
|
||||
disabled_by=er.RegistryEntryDisabler.USER,
|
||||
)
|
||||
await _setup_fixed_costs(hass, setup_integration, hass_storage, FIXED_COST)
|
||||
manager = await async_get_manager(hass)
|
||||
assert hass.states.get(FIXED_COST_ENTITY_ID) is None
|
||||
|
||||
await manager.async_update({"fixed_costs": [{**FIXED_COST, "name": "Fee"}]})
|
||||
await hass.async_block_till_done()
|
||||
assert hass.states.get(FIXED_COST_ENTITY_ID) is None
|
||||
|
||||
await manager.async_update({"fixed_costs": []})
|
||||
await hass.async_block_till_done()
|
||||
assert entity_registry.async_get(FIXED_COST_ENTITY_ID) is None
|
||||
|
||||
@@ -29,6 +29,7 @@ async def test_validation_empty_config(hass: HomeAssistant) -> None:
|
||||
"energy_sources": [],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -97,6 +98,7 @@ async def test_validation(
|
||||
"energy_sources": [[], [], []],
|
||||
"device_consumption": [[]],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -125,6 +127,7 @@ async def test_validation_device_consumption_entity_missing(
|
||||
]
|
||||
],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -148,6 +151,7 @@ async def test_validation_device_consumption_stat_missing(
|
||||
]
|
||||
],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -173,6 +177,7 @@ async def test_validation_device_consumption_entity_unavailable(
|
||||
]
|
||||
],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -198,6 +203,7 @@ async def test_validation_device_consumption_entity_non_numeric(
|
||||
]
|
||||
],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -231,6 +237,7 @@ async def test_validation_device_consumption_entity_unexpected_unit(
|
||||
]
|
||||
],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -256,6 +263,7 @@ async def test_validation_device_consumption_recorder_not_tracked(
|
||||
]
|
||||
],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -289,6 +297,7 @@ async def test_validation_device_consumption_no_last_reset(
|
||||
]
|
||||
],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -326,6 +335,7 @@ async def test_validation_solar(
|
||||
],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -372,6 +382,7 @@ async def test_validation_home(
|
||||
"energy_sources": [issues],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -425,6 +436,7 @@ async def test_validation_battery(
|
||||
],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -682,6 +694,7 @@ async def test_validation_grid(
|
||||
],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -747,6 +760,7 @@ async def test_validation_grid_external_cost_compensation(
|
||||
],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -814,6 +828,7 @@ async def test_validation_grid_price_not_exist(
|
||||
],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -877,6 +892,7 @@ async def test_validation_grid_auto_cost_entity_errors(
|
||||
"energy_sources": [[]],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -941,6 +957,7 @@ async def test_validation_grid_price_errors(
|
||||
],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -1078,6 +1095,7 @@ async def test_validation_gas(
|
||||
],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -1174,6 +1192,7 @@ async def test_validation_gas_price_unit_mismatch(
|
||||
"energy_sources": [expected_issues],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -1218,6 +1237,7 @@ async def test_validation_gas_price_not_exist(
|
||||
],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -1253,6 +1273,7 @@ async def test_validation_gas_no_costs_tracking(
|
||||
"energy_sources": [[]],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -1301,6 +1322,7 @@ async def test_validation_grid_no_costs_tracking(
|
||||
"energy_sources": [[]],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -1435,6 +1457,7 @@ async def test_validation_water(
|
||||
],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -1470,6 +1493,7 @@ async def test_validation_water_no_costs_tracking(
|
||||
"energy_sources": [[]],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -1485,6 +1509,7 @@ async def test_validation_device_consumption_water_entity_missing(
|
||||
"energy_sources": [],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [
|
||||
[
|
||||
{
|
||||
@@ -1523,6 +1548,7 @@ async def test_validation_device_consumption_water_entity_unexpected_unit(
|
||||
"energy_sources": [],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [
|
||||
[
|
||||
{
|
||||
@@ -1582,6 +1608,7 @@ async def test_validation_device_consumption_water_valid_units(
|
||||
"energy_sources": [],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [[], [], []],
|
||||
}
|
||||
|
||||
@@ -1599,6 +1626,7 @@ async def test_validation_device_consumption_water_recorder_not_tracked(
|
||||
"energy_sources": [],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [
|
||||
[
|
||||
{
|
||||
@@ -1635,6 +1663,7 @@ async def test_validation_device_consumption_gas_entity_missing(
|
||||
},
|
||||
]
|
||||
],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -1671,6 +1700,7 @@ async def test_validation_device_consumption_gas_entity_unexpected_unit(
|
||||
}
|
||||
]
|
||||
],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -1707,6 +1737,7 @@ async def test_validation_device_consumption_gas_valid_units(
|
||||
"energy_sources": [],
|
||||
"device_consumption": [],
|
||||
"device_consumption_gas": [[], [], []],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
@@ -1732,5 +1763,173 @@ async def test_validation_device_consumption_gas_recorder_not_tracked(
|
||||
}
|
||||
]
|
||||
],
|
||||
"fixed_costs": [],
|
||||
"device_consumption_water": [],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("unit", ["EUR", "EUR/day"])
|
||||
async def test_validation_fixed_cost(
|
||||
hass: HomeAssistant, mock_energy_manager: EnergyManager, unit: str
|
||||
) -> None:
|
||||
"""Test validating fixed costs with a number and an entity amount."""
|
||||
hass.states.async_set(
|
||||
"sensor.standing_charge", "0.62", {"unit_of_measurement": unit}
|
||||
)
|
||||
await mock_energy_manager.async_update(
|
||||
{
|
||||
"fixed_costs": [
|
||||
{
|
||||
"id": "number",
|
||||
"type": "grid",
|
||||
"name": "Network fee",
|
||||
"number_amount": 5.99,
|
||||
"entity_amount": None,
|
||||
"period": "month",
|
||||
},
|
||||
{
|
||||
"id": "entity",
|
||||
"type": "gas",
|
||||
"name": "Standing charge",
|
||||
"number_amount": None,
|
||||
"entity_amount": "sensor.standing_charge",
|
||||
"period": "day",
|
||||
},
|
||||
]
|
||||
}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (await validate.async_validate(hass)).as_dict()["fixed_costs"] == [[], []]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("state", "unit", "expected"),
|
||||
[
|
||||
pytest.param(
|
||||
None,
|
||||
None,
|
||||
{
|
||||
"type": "entity_not_defined",
|
||||
"affected_entities": {("sensor.standing_charge", None)},
|
||||
"translation_placeholders": None,
|
||||
},
|
||||
id="missing",
|
||||
),
|
||||
pytest.param(
|
||||
"unavailable",
|
||||
"EUR",
|
||||
{
|
||||
"type": "entity_state_non_numeric",
|
||||
"affected_entities": {("sensor.standing_charge", "unavailable")},
|
||||
"translation_placeholders": None,
|
||||
},
|
||||
id="unavailable",
|
||||
),
|
||||
pytest.param(
|
||||
"nan",
|
||||
"EUR",
|
||||
{
|
||||
"type": "entity_state_non_numeric",
|
||||
"affected_entities": {("sensor.standing_charge", "nan")},
|
||||
"translation_placeholders": None,
|
||||
},
|
||||
id="not_a_number",
|
||||
),
|
||||
pytest.param(
|
||||
"0.62",
|
||||
"EUR/month",
|
||||
{
|
||||
"type": "entity_unexpected_unit_fixed_cost",
|
||||
"affected_entities": {("sensor.standing_charge", "EUR/month")},
|
||||
"translation_placeholders": {"currency": "EUR"},
|
||||
},
|
||||
id="unit_of_another_period",
|
||||
),
|
||||
pytest.param(
|
||||
"0.62",
|
||||
"kEUR/day",
|
||||
{
|
||||
"type": "entity_unexpected_unit_fixed_cost",
|
||||
"affected_entities": {("sensor.standing_charge", "kEUR/day")},
|
||||
"translation_placeholders": {"currency": "EUR"},
|
||||
},
|
||||
id="unit_ending_with_the_currency",
|
||||
),
|
||||
pytest.param(
|
||||
"0.62",
|
||||
None,
|
||||
{
|
||||
"type": "entity_unexpected_unit_fixed_cost",
|
||||
"affected_entities": {("sensor.standing_charge", None)},
|
||||
"translation_placeholders": {"currency": "EUR"},
|
||||
},
|
||||
id="no_unit",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_validation_fixed_cost_entity_errors(
|
||||
hass: HomeAssistant,
|
||||
mock_energy_manager: EnergyManager,
|
||||
state: str | None,
|
||||
unit: str | None,
|
||||
expected: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test validating the amount entity of a fixed cost."""
|
||||
if state is not None:
|
||||
hass.states.async_set(
|
||||
"sensor.standing_charge", state, {"unit_of_measurement": unit}
|
||||
)
|
||||
await mock_energy_manager.async_update(
|
||||
{
|
||||
"fixed_costs": [
|
||||
{
|
||||
"id": "entity",
|
||||
"type": "grid",
|
||||
"name": "Standing charge",
|
||||
"number_amount": None,
|
||||
"entity_amount": "sensor.standing_charge",
|
||||
"period": "day",
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (await validate.async_validate(hass)).as_dict()["fixed_costs"] == [
|
||||
[expected]
|
||||
]
|
||||
|
||||
|
||||
async def test_validation_fixed_cost_sensor_not_recorded(
|
||||
hass: HomeAssistant,
|
||||
mock_energy_manager: EnergyManager,
|
||||
mock_is_entity_recorded: dict[str, bool],
|
||||
) -> None:
|
||||
"""Test validating a fixed cost sensor that is not recorded."""
|
||||
mock_is_entity_recorded["sensor.network_fee_fixed_cost"] = False
|
||||
await mock_energy_manager.async_update(
|
||||
{
|
||||
"fixed_costs": [
|
||||
{
|
||||
"id": "number",
|
||||
"type": "grid",
|
||||
"name": "Network fee",
|
||||
"number_amount": 5.99,
|
||||
"entity_amount": None,
|
||||
"period": "month",
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (await validate.async_validate(hass)).as_dict()["fixed_costs"] == [
|
||||
[
|
||||
{
|
||||
"type": "recorder_untracked",
|
||||
"affected_entities": {("sensor.network_fee_fixed_cost", None)},
|
||||
"translation_placeholders": None,
|
||||
}
|
||||
]
|
||||
]
|
||||
|
||||
@@ -58,6 +58,7 @@ async def test_validation_gas_flow_rate_valid(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -111,6 +112,7 @@ async def test_validation_gas_flow_rate_wrong_unit(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -162,6 +164,7 @@ async def test_validation_gas_flow_rate_wrong_state_class(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -210,6 +213,7 @@ async def test_validation_gas_flow_rate_entity_missing(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -243,6 +247,7 @@ async def test_validation_gas_without_flow_rate(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -286,6 +291,7 @@ async def test_validation_water_flow_rate_valid(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -339,6 +345,7 @@ async def test_validation_water_flow_rate_wrong_unit(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -392,6 +399,7 @@ async def test_validation_water_flow_rate_wrong_state_class(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -440,6 +448,7 @@ async def test_validation_water_flow_rate_entity_missing(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -473,6 +482,7 @@ async def test_validation_water_without_flow_rate(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -539,6 +549,7 @@ async def test_validation_gas_flow_rate_different_units(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -583,6 +594,7 @@ async def test_validation_gas_flow_rate_recorder_untracked(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -627,4 +639,5 @@ async def test_validation_water_flow_rate_recorder_untracked(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ async def test_validation_grid_power_valid(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -91,6 +92,7 @@ async def test_validation_grid_power_wrong_unit(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -168,6 +170,7 @@ async def test_validation_home_power(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -209,6 +212,7 @@ async def test_validation_grid_power_wrong_state_class(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -246,6 +250,7 @@ async def test_validation_grid_power_entity_missing(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -279,6 +284,7 @@ async def test_validation_grid_power_entity_unavailable(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -320,6 +326,7 @@ async def test_validation_grid_power_entity_non_numeric(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -363,6 +370,7 @@ async def test_validation_grid_power_wrong_device_class(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -410,6 +418,7 @@ async def test_validation_grid_power_different_units(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -444,6 +453,7 @@ async def test_validation_grid_power_external_statistics(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -478,6 +488,7 @@ async def test_validation_grid_power_recorder_untracked(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -185,6 +185,24 @@ async def test_save_preferences(
|
||||
"name": "Gas Meter",
|
||||
}
|
||||
],
|
||||
"fixed_costs": [
|
||||
{
|
||||
"id": "standing_charge",
|
||||
"type": "grid",
|
||||
"name": "Standing charge",
|
||||
"number_amount": 0.62,
|
||||
"entity_amount": None,
|
||||
"period": "day",
|
||||
},
|
||||
{
|
||||
"id": "gas_standing_charge",
|
||||
"type": "gas",
|
||||
"name": "Gas standing charge",
|
||||
"number_amount": None,
|
||||
"entity_amount": "sensor.gas_standing_charge",
|
||||
"period": "month",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
await client.send_json({"id": 6, "type": "energy/save_prefs", **new_prefs})
|
||||
@@ -217,6 +235,10 @@ async def test_save_preferences(
|
||||
"sensor.return_to_grid_offpeak_compensation"
|
||||
),
|
||||
},
|
||||
"fixed_cost_sensors": {
|
||||
"standing_charge": "sensor.standing_charge_fixed_cost",
|
||||
"gas_standing_charge": "sensor.gas_standing_charge_fixed_cost",
|
||||
},
|
||||
"solar_forecast_domains": ["some_domain"],
|
||||
}
|
||||
|
||||
@@ -374,6 +396,7 @@ async def test_validate(
|
||||
"device_consumption": [],
|
||||
"device_consumption_water": [],
|
||||
"device_consumption_gas": [],
|
||||
"fixed_costs": [],
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user