Skip to content

Commit

Permalink
Remaster sensor ID generation
Browse files Browse the repository at this point in the history
  • Loading branch information
Limych committed May 8, 2021
1 parent 523dda8 commit a4587d0
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 16 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,14 @@ I put a lot of work into making this repo and component available and updated to
> **_Note_**:\
> You can use groups of entities as a data source. These groups will be automatically expanded to individual entities.
**unique_id**\
_(string) (Optional)_\
An ID that uniquely identifies this sensor. Set this to a unique value to allow customization through the UI.
> **_Note_**:\
> If you used the component version 1.4.0 or earlier, you can specify the special value `__legacy__`, so that no duplicates of already existing sensors are created.\
> The use of this special value in newly created sensors is not recommended.

**name**:\
_(string) (Optional)_\
Name to use in the frontend.\
Expand Down
2 changes: 1 addition & 1 deletion custom_components/average/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
# Base component constants
NAME = "Average Sensor"
DOMAIN = "average"
VERSION = "1.7.4.dev0"
VERSION = "2.0.0-alpha"
ISSUE_URL = "https://github.com/Limych/ha-average/issues"

STARTUP_MESSAGE = f"""
Expand Down
2 changes: 1 addition & 1 deletion custom_components/average/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"domain": "average",
"name": "Average Sensor",
"version": "1.7.4.dev0",
"version": "2.0.0-alpha",
"documentation": "https://github.com/Limych/ha-average",
"issue_tracker": "https://github.com/Limych/ha-average/issues",
"dependencies": [
Expand Down
38 changes: 26 additions & 12 deletions custom_components/average/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
ATTR_UNIT_OF_MEASUREMENT,
CONF_ENTITIES,
CONF_NAME,
CONF_UNIQUE_ID,
DEVICE_CLASS_TEMPERATURE,
EVENT_HOMEASSISTANT_START,
STATE_UNAVAILABLE,
Expand Down Expand Up @@ -78,6 +79,7 @@ def check_period_keys(conf):
PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_ENTITIES): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_START): cv.template,
vol.Optional(CONF_END): cv.template,
Expand All @@ -98,20 +100,27 @@ async def async_setup_platform(
# Print startup message
_LOGGER.info(STARTUP_MESSAGE)

name = config.get(CONF_NAME)
start = config.get(CONF_START)
end = config.get(CONF_END)
duration = config.get(CONF_DURATION)
entities = config.get(CONF_ENTITIES)
precision = config.get(CONF_PRECISION)
undef = config.get(CONF_PROCESS_UNDEF_AS)

for template in [start, end]:
if template is not None:
template.hass = hass

async_add_entities(
[AverageSensor(hass, name, start, end, duration, entities, precision, undef)]
[
AverageSensor(
hass,
config.get(CONF_UNIQUE_ID),
config.get(CONF_NAME),
start,
end,
config.get(CONF_DURATION),
config.get(CONF_ENTITIES),
config.get(CONF_PRECISION),
config.get(CONF_PROCESS_UNDEF_AS),
)
]
)


Expand All @@ -123,6 +132,7 @@ class AverageSensor(Entity):
def __init__(
self,
hass: HomeAssistant,
unique_id: Optional[str],
name: str,
start,
end,
Expand Down Expand Up @@ -151,12 +161,16 @@ def __init__(
self.count = 0
self.min_value = self.max_value = None

self._unique_id = str(
sha1(
";".join(
[str(start), str(duration), str(end), ",".join(self.sources)]
).encode("utf-8")
).hexdigest()
self._unique_id = (
str(
sha1(
";".join(
[str(start), str(duration), str(end), ",".join(self.sources)]
).encode("utf-8")
).hexdigest()
)
if unique_id == "__legacy__"
else unique_id
)

@property
Expand Down
5 changes: 5 additions & 0 deletions info.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
{% if prerelease %}
### NB!: This is a Beta version!
{% endif %}
{% if (version_installed.split(".")[0:2] | join | int) < 20 %}
### ATTENTION! Breaking changes!

The mechanism for specifying the unique ID of sensors has been changed. To prevent duplicate sensors from being created, add option `unique_id: __legacy__` to the settings of already available sensors. For more information, see the component's documentation.
{% endif %}

_This sensor allows you to calculate the average state for one or more sensors over a specified period. Or just the average current state for one or more sensors, if you do not need historical data._

Expand Down
34 changes: 32 additions & 2 deletions tests/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
check_period_keys,
)

TEST_UNIQUE_ID = "test_id"
TEST_NAME = "test_name"
TEST_ENTITY_IDS = ["sensor.test_monitored"]
TEST_VALUES = [3, 11.16, -17, 4.29, -29, -16.8, 8, 5, -4.7, 5, -15]
Expand All @@ -47,6 +48,7 @@ def default_sensor(hass: HomeAssistant):
"""Create an AverageSensor with default values."""
entity = AverageSensor(
hass,
TEST_UNIQUE_ID,
TEST_NAME,
None,
Template("{{ now() }}"),
Expand Down Expand Up @@ -134,7 +136,7 @@ async def test_setup_platform(hass: HomeAssistant):
assert async_add_entities.called


async def test_entity_initialization(default_sensor):
async def test_entity_initialization(hass: HomeAssistant, default_sensor):
"""Test sensor initialization."""
expected_attributes = {
"available_sources": 0,
Expand All @@ -143,15 +145,43 @@ async def test_entity_initialization(default_sensor):
"sources": ["sensor.test_monitored"],
}

assert default_sensor.unique_id == TEST_UNIQUE_ID
assert default_sensor.name == TEST_NAME
assert default_sensor.unique_id == "2ef66732fb7155dce84ad53afe910beba59cfad4"
assert default_sensor.should_poll is True
assert default_sensor.available is False
assert default_sensor.state == STATE_UNAVAILABLE
assert default_sensor.unit_of_measurement is None
assert default_sensor.icon is None
assert default_sensor.state_attributes == expected_attributes

entity = AverageSensor(
hass,
None,
TEST_NAME,
None,
Template("{{ now() }}"),
timedelta(minutes=3),
TEST_ENTITY_IDS,
2,
None,
)

assert entity.unique_id is None

entity = AverageSensor(
hass,
"__legacy__",
TEST_NAME,
None,
Template("{{ now() }}"),
timedelta(minutes=3),
TEST_ENTITY_IDS,
2,
None,
)

assert entity.unique_id == "2ef66732fb7155dce84ad53afe910beba59cfad4"


async def test_async_setup_platform(hass: HomeAssistant):
"""Test platform setup."""
Expand Down

0 comments on commit a4587d0

Please sign in to comment.