Skip to content

Commit

Permalink
Add unique ID to energy sensors (home-assistant#70378)
Browse files Browse the repository at this point in the history
  • Loading branch information
frenck authored Apr 27, 2022
1 parent 3f50278 commit 5c1be2f
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 14 deletions.
17 changes: 15 additions & 2 deletions homeassistant/components/energy/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
split_entity_id,
valid_entity_id,
)
from homeassistant.helpers.entity import EntityCategory
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.typing import ConfigType, DiscoveryInfoType
Expand Down Expand Up @@ -210,7 +210,7 @@ class EnergyCostSensor(SensorEntity):
utility.
"""

_attr_entity_category = EntityCategory.SYSTEM
_attr_entity_registry_visible_default = False
_wrong_state_class_reported = False
_wrong_unit_reported = False

Expand Down Expand Up @@ -416,3 +416,16 @@ def update_config(self, config: dict) -> None:
def native_unit_of_measurement(self) -> str | None:
"""Return the units of measurement."""
return self.hass.config.currency

@property
def unique_id(self) -> str | None:
"""Return the unique ID of the sensor."""
entity_registry = er.async_get(self.hass)
if registry_entry := entity_registry.async_get(
self._config[self._adapter.entity_energy_key]
):
prefix = registry_entry.id
else:
prefix = self._config[self._adapter.entity_energy_key]

return f"{prefix}_{self._adapter.source_type}_{self._adapter.entity_id_suffix}"
78 changes: 66 additions & 12 deletions tests/components/energy/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
STATE_UNKNOWN,
VOLUME_CUBIC_METERS,
)
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util

Expand Down Expand Up @@ -187,10 +188,12 @@ def _compile_statistics(_):
assert state.attributes[ATTR_STATE_CLASS] == SensorStateClass.TOTAL
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == "EUR"

# # Unique ID temp disabled
# # entity_registry = er.async_get(hass)
# # entry = entity_registry.async_get(cost_sensor_entity_id)
# # assert entry.unique_id == "energy_energy_consumption cost"
entity_registry = er.async_get(hass)
entry = entity_registry.async_get(cost_sensor_entity_id)
assert entry
postfix = "cost" if flow_type == "flow_from" else "compensation"
assert entry.unique_id == f"{usage_sensor_entity_id}_grid_{postfix}"
assert entry.hidden_by is er.RegistryEntryHider.INTEGRATION

# Energy use bumped to 10 kWh
hass.states.async_set(
Expand Down Expand Up @@ -392,10 +395,12 @@ def _compile_statistics(_):
assert state.attributes[ATTR_STATE_CLASS] == SensorStateClass.TOTAL
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == "EUR"

# # Unique ID temp disabled
# # entity_registry = er.async_get(hass)
# # entry = entity_registry.async_get(cost_sensor_entity_id)
# # assert entry.unique_id == "energy_energy_consumption cost"
entity_registry = er.async_get(hass)
entry = entity_registry.async_get(cost_sensor_entity_id)
assert entry
postfix = "cost" if flow_type == "flow_from" else "compensation"
assert entry.unique_id == f"{usage_sensor_entity_id}_grid_{postfix}"
assert entry.hidden_by is er.RegistryEntryHider.INTEGRATION

# Energy use bumped to 10 kWh
hass.states.async_set(
Expand Down Expand Up @@ -597,10 +602,12 @@ def _compile_statistics(_):
assert state.attributes[ATTR_STATE_CLASS] == SensorStateClass.TOTAL
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == "EUR"

# # Unique ID temp disabled
# # entity_registry = er.async_get(hass)
# # entry = entity_registry.async_get(cost_sensor_entity_id)
# # assert entry.unique_id == "energy_energy_consumption cost"
entity_registry = er.async_get(hass)
entry = entity_registry.async_get(cost_sensor_entity_id)
assert entry
postfix = "cost" if flow_type == "flow_from" else "compensation"
assert entry.unique_id == f"{usage_sensor_entity_id}_grid_{postfix}"
assert entry.hidden_by is er.RegistryEntryHider.INTEGRATION

# Energy use bumped to 10 kWh
hass.states.async_set(
Expand Down Expand Up @@ -1018,3 +1025,50 @@ async def test_cost_sensor_state_class_measurement_no_reset(

state = hass.states.get("sensor.energy_consumption_cost")
assert state.state == STATE_UNKNOWN


async def test_inherit_source_unique_id(hass, hass_storage, setup_integration):
"""Test sensor inherits unique ID from source."""
energy_data = data.EnergyManager.default_preferences()
energy_data["energy_sources"].append(
{
"type": "gas",
"stat_energy_from": "sensor.gas_consumption",
"entity_energy_from": "sensor.gas_consumption",
"stat_cost": None,
"entity_energy_price": None,
"number_energy_price": 0.5,
}
)

hass_storage[data.STORAGE_KEY] = {
"version": 1,
"data": energy_data,
}

now = dt_util.utcnow()
entity_registry = er.async_get(hass)
source_entry = entity_registry.async_get_or_create(
"sensor", "test", "123456", suggested_object_id="gas_consumption"
)

hass.states.async_set(
"sensor.gas_consumption",
100,
{
ATTR_UNIT_OF_MEASUREMENT: VOLUME_CUBIC_METERS,
ATTR_STATE_CLASS: SensorStateClass.TOTAL_INCREASING,
},
)

with patch("homeassistant.util.dt.utcnow", return_value=now):
await setup_integration(hass)

state = hass.states.get("sensor.gas_consumption_cost")
assert state
assert state.state == "0.0"

entry = entity_registry.async_get("sensor.gas_consumption_cost")
assert entry
assert entry.unique_id == f"{source_entry.id}_gas_cost"
assert entry.hidden_by is er.RegistryEntryHider.INTEGRATION

0 comments on commit 5c1be2f

Please sign in to comment.