Teach sensor device trigger about entity registry ids (#94988)

This commit is contained in:
Erik Montnemery 2023-06-22 11:13:54 +02:00 committed by GitHub
parent 3863c561a6
commit 5884afd485
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 238 additions and 84 deletions

View File

@ -1,7 +1,10 @@
"""Provides device triggers for sensors."""
import voluptuous as vol
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.components.device_automation import (
DEVICE_TRIGGER_BASE_SCHEMA,
async_get_entity_registry_entry_or_raise,
)
from homeassistant.components.device_automation.exceptions import (
InvalidDeviceAutomationConfig,
)
@ -136,7 +139,7 @@ ENTITY_TRIGGERS = {
TRIGGER_SCHEMA = vol.All(
DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_ENTITY_ID): cv.entity_id_or_uuid,
vol.Required(CONF_TYPE): vol.In(
[
CONF_APPARENT_POWER,
@ -251,7 +254,7 @@ async def async_get_triggers(
**automation,
"platform": "device",
"device_id": device_id,
"entity_id": entry.entity_id,
"entity_id": entry.id,
"domain": DOMAIN,
}
for automation in templates
@ -264,8 +267,10 @@ async def async_get_trigger_capabilities(
hass: HomeAssistant, config: ConfigType
) -> dict[str, vol.Schema]:
"""List trigger capabilities."""
try:
unit_of_measurement = get_unit_of_measurement(hass, config[CONF_ENTITY_ID])
entry = async_get_entity_registry_entry_or_raise(hass, config[CONF_ENTITY_ID])
unit_of_measurement = get_unit_of_measurement(hass, entry.entity_id)
except HomeAssistantError:
unit_of_measurement = None

View File

@ -84,6 +84,10 @@ async def test_get_triggers(
device = device_registry.async_get_device(
identifiers={(DECONZ_DOMAIN, "d0:cf:5e:ff:fe:71:a4:3a")}
)
entity_registry = er.async_get(hass)
battery_sensor_entry = entity_registry.async_get(
"sensor.tradfri_on_off_switch_battery"
)
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device.id
@ -141,7 +145,7 @@ async def test_get_triggers(
{
CONF_DEVICE_ID: device.id,
CONF_DOMAIN: SENSOR_DOMAIN,
ATTR_ENTITY_ID: "sensor.tradfri_on_off_switch_battery",
ATTR_ENTITY_ID: battery_sensor_entry.id,
CONF_PLATFORM: "device",
CONF_TYPE: ATTR_BATTERY_LEVEL,
"metadata": {"secondary": True},
@ -193,6 +197,7 @@ async def test_get_triggers_for_alarm_event(
identifiers={(DECONZ_DOMAIN, "00:00:00:00:00:00:00:00")}
)
entity_registry = er.async_get(hass)
bat_entity = entity_registry.async_get("sensor.keypad_battery")
low_bat_entity = entity_registry.async_get("binary_sensor.keypad_low_battery")
tamper_entity = entity_registry.async_get("binary_sensor.keypad_tampered")
@ -236,7 +241,7 @@ async def test_get_triggers_for_alarm_event(
{
CONF_DEVICE_ID: device.id,
CONF_DOMAIN: SENSOR_DOMAIN,
ATTR_ENTITY_ID: "sensor.keypad_battery",
ATTR_ENTITY_ID: bat_entity.id,
CONF_PLATFORM: "device",
CONF_TYPE: ATTR_BATTERY_LEVEL,
"metadata": {"secondary": True},

View File

@ -101,7 +101,7 @@ async def test_enumerate_remote(hass: HomeAssistant, utcnow) -> None:
{
"device_id": device.id,
"domain": "sensor",
"entity_id": bat_sensor.entity_id,
"entity_id": bat_sensor.id,
"platform": "device",
"type": "battery_level",
"metadata": {"secondary": True},
@ -150,7 +150,7 @@ async def test_enumerate_button(hass: HomeAssistant, utcnow) -> None:
{
"device_id": device.id,
"domain": "sensor",
"entity_id": bat_sensor.entity_id,
"entity_id": bat_sensor.id,
"platform": "device",
"type": "battery_level",
"metadata": {"secondary": True},
@ -198,7 +198,7 @@ async def test_enumerate_doorbell(hass: HomeAssistant, utcnow) -> None:
{
"device_id": device.id,
"domain": "sensor",
"entity_id": bat_sensor.entity_id,
"entity_id": bat_sensor.id,
"platform": "device",
"type": "battery_level",
"metadata": {"secondary": True},

View File

@ -5,6 +5,7 @@ from homeassistant.components import automation, hue
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.hue.v1 import device_trigger
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from .conftest import setup_platform
@ -15,7 +16,9 @@ from tests.common import async_get_device_automations
REMOTES_RESPONSE = {"7": HUE_TAP_REMOTE_1, "8": HUE_DIMMER_REMOTE_1}
async def test_get_triggers(hass: HomeAssistant, mock_bridge_v1, device_reg) -> None:
async def test_get_triggers(
hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_bridge_v1, device_reg
) -> None:
"""Test we get the expected triggers from a hue remote."""
mock_bridge_v1.mock_sensor_responses.append(REMOTES_RESPONSE)
await setup_platform(hass, mock_bridge_v1, ["sensor", "binary_sensor"])
@ -49,6 +52,9 @@ async def test_get_triggers(hass: HomeAssistant, mock_bridge_v1, device_reg) ->
hue_dimmer_device = device_reg.async_get_device(
{(hue.DOMAIN, "00:17:88:01:10:3e:3a:dc")}
)
hue_bat_sensor = entity_registry.async_get(
"sensor.hue_dimmer_switch_1_battery_level"
)
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, hue_dimmer_device.id
)
@ -58,7 +64,7 @@ async def test_get_triggers(hass: HomeAssistant, mock_bridge_v1, device_reg) ->
"domain": "sensor",
"device_id": hue_dimmer_device.id,
"type": "battery_level",
"entity_id": "sensor.hue_dimmer_switch_1_battery_level",
"entity_id": hue_bat_sensor.id,
"metadata": {"secondary": True},
}
expected_triggers = [

View File

@ -7,6 +7,7 @@ from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.hue.v2.device import async_setup_devices
from homeassistant.components.hue.v2.hue_event import async_setup_hue_events
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .conftest import setup_platform
@ -47,7 +48,11 @@ async def test_hue_event(
async def test_get_triggers(
hass: HomeAssistant, mock_bridge_v2, v2_resources_test_data, device_reg
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_bridge_v2,
v2_resources_test_data,
device_reg,
) -> None:
"""Test we get the expected triggers from a hue remote."""
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
@ -57,6 +62,9 @@ async def test_get_triggers(
hue_wall_switch_device = device_reg.async_get_device(
{(hue.DOMAIN, "3ff06175-29e8-44a8-8fe7-af591b0025da")}
)
hue_bat_sensor = entity_registry.async_get(
"sensor.wall_switch_with_2_controls_battery"
)
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, hue_wall_switch_device.id
)
@ -66,7 +74,7 @@ async def test_get_triggers(
"domain": "sensor",
"device_id": hue_wall_switch_device.id,
"type": "battery_level",
"entity_id": "sensor.wall_switch_with_2_controls_battery",
"entity_id": hue_bat_sensor.id,
"metadata": {"secondary": True},
}

View File

@ -93,6 +93,7 @@ async def test_get_triggers(
platform.init()
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
sensor_entries: dict[SensorDeviceClass, er.RegistryEntry] = {}
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
@ -101,7 +102,7 @@ async def test_get_triggers(
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
for device_class in SensorDeviceClass:
entity_registry.async_get_or_create(
sensor_entries[device_class] = entity_registry.async_get_or_create(
DOMAIN,
"test",
platform.ENTITIES[device_class].unique_id,
@ -114,7 +115,7 @@ async def test_get_triggers(
"domain": DOMAIN,
"type": trigger["type"],
"device_id": device_entry.id,
"entity_id": platform.ENTITIES[device_class].entity_id,
"entity_id": sensor_entries[device_class].id,
"metadata": {"secondary": False},
}
for device_class in SensorDeviceClass
@ -152,7 +153,7 @@ async def test_get_triggers_hidden_auxiliary(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_registry.async_get_or_create(
entity_entry = entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
@ -167,7 +168,7 @@ async def test_get_triggers_hidden_auxiliary(
"domain": DOMAIN,
"type": trigger,
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
"entity_id": entity_entry.id,
"metadata": {"secondary": True},
}
for trigger in ["value"]
@ -203,7 +204,7 @@ async def test_get_triggers_no_unit_or_stateclass(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_registry.async_get_or_create(
entity_entry = entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
@ -217,7 +218,7 @@ async def test_get_triggers_no_unit_or_stateclass(
"domain": DOMAIN,
"type": trigger,
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
"entity_id": entity_entry.id,
"metadata": {"secondary": False},
}
for trigger in trigger_types
@ -298,8 +299,22 @@ async def test_get_trigger_capabilities(
assert capabilities == expected_capabilities
async def test_get_trigger_capabilities_none(
hass: HomeAssistant, enable_custom_integrations: None
@pytest.mark.parametrize(
("set_state", "device_class_reg", "device_class_state", "unit_reg", "unit_state"),
[
(False, SensorDeviceClass.BATTERY, None, PERCENTAGE, None),
(True, None, SensorDeviceClass.BATTERY, None, PERCENTAGE),
],
)
async def test_get_trigger_capabilities_legacy(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
set_state,
device_class_reg,
device_class_state,
unit_reg,
unit_state,
) -> None:
"""Test we get the expected capabilities from a sensor trigger."""
platform = getattr(hass.components, f"test.{DOMAIN}")
@ -307,6 +322,71 @@ async def test_get_trigger_capabilities_none(
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_id = entity_registry.async_get_or_create(
DOMAIN,
"test",
platform.ENTITIES["battery"].unique_id,
device_id=device_entry.id,
original_device_class=device_class_reg,
unit_of_measurement=unit_reg,
).entity_id
if set_state:
hass.states.async_set(
entity_id,
None,
{"device_class": device_class_state, "unit_of_measurement": unit_state},
)
expected_capabilities = {
"extra_fields": [
{
"description": {"suffix": PERCENTAGE},
"name": "above",
"optional": True,
"type": "float",
},
{
"description": {"suffix": PERCENTAGE},
"name": "below",
"optional": True,
"type": "float",
},
{"name": "for", "optional": True, "type": "positive_time_period_dict"},
]
}
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert len(triggers) == 1
for trigger in triggers:
trigger["entity_id"] = entity_registry.async_get(trigger["entity_id"]).entity_id
capabilities = await async_get_device_automation_capabilities(
hass, DeviceAutomationType.TRIGGER, trigger
)
assert capabilities == expected_capabilities
async def test_get_trigger_capabilities_none(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
enable_custom_integrations: None,
) -> None:
"""Test we get the expected capabilities from a sensor trigger."""
platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init()
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
entry_none = entity_registry.async_get_or_create(
DOMAIN,
"test",
platform.ENTITIES["none"].unique_id,
)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
@ -316,14 +396,14 @@ async def test_get_trigger_capabilities_none(
"platform": "device",
"device_id": "8770c43885354d5fa27604db6817f63f",
"domain": "sensor",
"entity_id": "sensor.beer",
"entity_id": "01234567890123456789012345678901",
"type": "is_battery_level",
},
{
"platform": "device",
"device_id": "8770c43885354d5fa27604db6817f63f",
"domain": "sensor",
"entity_id": platform.ENTITIES["none"].entity_id,
"entity_id": entry_none.id,
"type": "is_battery_level",
},
]
@ -338,17 +418,13 @@ async def test_get_trigger_capabilities_none(
async def test_if_fires_not_on_above_below(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
calls,
caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None,
) -> None:
"""Test for value triggers firing."""
platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init()
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
sensor1 = platform.ENTITIES["battery"]
entry = entity_registry.async_get_or_create(DOMAIN, "test", "5678")
assert await async_setup_component(
hass,
@ -360,7 +436,7 @@ async def test_if_fires_not_on_above_below(
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": sensor1.entity_id,
"entity_id": entry.id,
"type": "battery_level",
},
"action": {"service": "test.automation"},
@ -372,15 +448,15 @@ async def test_if_fires_not_on_above_below(
async def test_if_fires_on_state_above(
hass: HomeAssistant, calls, enable_custom_integrations: None
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
calls,
enable_custom_integrations: None,
) -> None:
"""Test for value triggers firing."""
platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init()
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
entry = entity_registry.async_get_or_create(DOMAIN, "test", "5678")
sensor1 = platform.ENTITIES["battery"]
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
@ -392,7 +468,7 @@ async def test_if_fires_on_state_above(
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": sensor1.entity_id,
"entity_id": entry.id,
"type": "battery_level",
"above": 10,
},
@ -416,31 +492,30 @@ async def test_if_fires_on_state_above(
},
)
await hass.async_block_till_done()
assert hass.states.get(sensor1.entity_id).state == STATE_UNKNOWN
assert len(calls) == 0
hass.states.async_set(sensor1.entity_id, 9)
hass.states.async_set(entry.entity_id, 9)
await hass.async_block_till_done()
assert len(calls) == 0
hass.states.async_set(sensor1.entity_id, 11)
hass.states.async_set(entry.entity_id, 11)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["some"] == "bat_low device - {} - 9 - 11 - None".format(
sensor1.entity_id
assert (
calls[0].data["some"] == f"bat_low device - {entry.entity_id} - 9 - 11 - None"
)
async def test_if_fires_on_state_below(
hass: HomeAssistant, calls, enable_custom_integrations: None
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
calls,
enable_custom_integrations: None,
) -> None:
"""Test for value triggers firing."""
platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init()
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
entry = entity_registry.async_get_or_create(DOMAIN, "test", "5678")
sensor1 = platform.ENTITIES["battery"]
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
@ -452,7 +527,7 @@ async def test_if_fires_on_state_below(
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": sensor1.entity_id,
"entity_id": entry.id,
"type": "battery_level",
"below": 10,
},
@ -476,31 +551,30 @@ async def test_if_fires_on_state_below(
},
)
await hass.async_block_till_done()
assert hass.states.get(sensor1.entity_id).state == STATE_UNKNOWN
assert len(calls) == 0
hass.states.async_set(sensor1.entity_id, 11)
hass.states.async_set(entry.entity_id, 11)
await hass.async_block_till_done()
assert len(calls) == 0
hass.states.async_set(sensor1.entity_id, 9)
hass.states.async_set(entry.entity_id, 9)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["some"] == "bat_low device - {} - 11 - 9 - None".format(
sensor1.entity_id
assert (
calls[0].data["some"] == f"bat_low device - {entry.entity_id} - 11 - 9 - None"
)
async def test_if_fires_on_state_between(
hass: HomeAssistant, calls, enable_custom_integrations: None
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
calls,
enable_custom_integrations: None,
) -> None:
"""Test for value triggers firing."""
platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init()
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
entry = entity_registry.async_get_or_create(DOMAIN, "test", "5678")
sensor1 = platform.ENTITIES["battery"]
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
@ -512,7 +586,7 @@ async def test_if_fires_on_state_between(
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": sensor1.entity_id,
"entity_id": entry.id,
"type": "battery_level",
"above": 10,
"below": 20,
@ -537,43 +611,41 @@ async def test_if_fires_on_state_between(
},
)
await hass.async_block_till_done()
assert hass.states.get(sensor1.entity_id).state == STATE_UNKNOWN
assert len(calls) == 0
hass.states.async_set(sensor1.entity_id, 9)
hass.states.async_set(entry.entity_id, 9)
await hass.async_block_till_done()
assert len(calls) == 0
hass.states.async_set(sensor1.entity_id, 11)
hass.states.async_set(entry.entity_id, 11)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["some"] == "bat_low device - {} - 9 - 11 - None".format(
sensor1.entity_id
assert (
calls[0].data["some"] == f"bat_low device - {entry.entity_id} - 9 - 11 - None"
)
hass.states.async_set(sensor1.entity_id, 21)
hass.states.async_set(entry.entity_id, 21)
await hass.async_block_till_done()
assert len(calls) == 1
hass.states.async_set(sensor1.entity_id, 19)
hass.states.async_set(entry.entity_id, 19)
await hass.async_block_till_done()
assert len(calls) == 2
assert calls[1].data["some"] == "bat_low device - {} - 21 - 19 - None".format(
sensor1.entity_id
assert (
calls[1].data["some"] == f"bat_low device - {entry.entity_id} - 21 - 19 - None"
)
async def test_if_fires_on_state_change_with_for(
hass: HomeAssistant, calls, enable_custom_integrations: None
async def test_if_fires_on_state_legacy(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
calls,
enable_custom_integrations: None,
) -> None:
"""Test for triggers firing with delay."""
platform = getattr(hass.components, f"test.{DOMAIN}")
"""Test for value triggers firing."""
entry = entity_registry.async_get_or_create(DOMAIN, "test", "5678")
platform.init()
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
sensor1 = platform.ENTITIES["battery"]
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
@ -585,7 +657,66 @@ async def test_if_fires_on_state_change_with_for(
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": sensor1.entity_id,
"entity_id": entry.entity_id,
"type": "battery_level",
"above": 10,
},
"action": {
"service": "test.automation",
"data_template": {
"some": "bat_low {{ trigger.%s }}"
% "}} - {{ trigger.".join(
(
"platform",
"entity_id",
"from_state.state",
"to_state.state",
"for",
)
)
},
},
}
]
},
)
await hass.async_block_till_done()
assert len(calls) == 0
hass.states.async_set(entry.entity_id, 9)
await hass.async_block_till_done()
assert len(calls) == 0
hass.states.async_set(entry.entity_id, 11)
await hass.async_block_till_done()
assert len(calls) == 1
assert (
calls[0].data["some"] == f"bat_low device - {entry.entity_id} - 9 - 11 - None"
)
async def test_if_fires_on_state_change_with_for(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
calls,
enable_custom_integrations: None,
) -> None:
"""Test for triggers firing with delay."""
entry = entity_registry.async_get_or_create(DOMAIN, "test", "5678")
hass.states.async_set(entry.entity_id, STATE_UNKNOWN, {"device_class": "battery"})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": entry.id,
"type": "battery_level",
"above": 10,
"for": {"seconds": 5},
@ -610,11 +741,10 @@ async def test_if_fires_on_state_change_with_for(
},
)
await hass.async_block_till_done()
assert hass.states.get(sensor1.entity_id).state == STATE_UNKNOWN
assert len(calls) == 0
hass.states.async_set(sensor1.entity_id, 10)
hass.states.async_set(sensor1.entity_id, 11)
hass.states.async_set(entry.entity_id, 10)
hass.states.async_set(entry.entity_id, 11)
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
@ -623,5 +753,5 @@ async def test_if_fires_on_state_change_with_for(
await hass.async_block_till_done()
assert (
calls[0].data["some"]
== f"turn_off device - {sensor1.entity_id} - 10 - 11 - 0:00:05"
== f"turn_off device - {entry.entity_id} - 10 - 11 - 0:00:05"
)