|
5 | 5 | from datetime import datetime
|
6 | 6 | from typing import Any
|
7 | 7 |
|
| 8 | +import voluptuous as vol |
8 | 9 | from homeassistant.components.sensor import (
|
9 | 10 | SensorDeviceClass,
|
10 | 11 | SensorEntity,
|
|
20 | 21 | STATE_UNKNOWN,
|
21 | 22 | )
|
22 | 23 | from homeassistant.core import Event, EventStateChangedData, HomeAssistant, callback
|
| 24 | +from homeassistant.helpers import device_registry as dr |
23 | 25 | from homeassistant.helpers import entity_platform
|
24 | 26 | from homeassistant.helpers import entity_registry as er
|
25 | 27 | from homeassistant.helpers.device import async_device_info_to_link_from_entity
|
|
49 | 51 | SENSOR_TYPE_TO_ATTR = {v: k for k, v in SENSOR_TYPES.items()}
|
50 | 52 |
|
51 | 53 |
|
| 54 | +@callback |
| 55 | +def async_add_to_device( |
| 56 | + hass: HomeAssistant, entry: ConfigEntry, entity_id: str |
| 57 | +) -> str | None: |
| 58 | + """Add our config entry to the tracked entity's device.""" |
| 59 | + registry = er.async_get(hass) |
| 60 | + device_registry = dr.async_get(hass) |
| 61 | + device_id = None |
| 62 | + |
| 63 | + if ( |
| 64 | + not (source_device := registry.async_get(entity_id)) |
| 65 | + or not (device_id := source_device.device_id) |
| 66 | + or not (device_registry.async_get(device_id)) |
| 67 | + ): |
| 68 | + return device_id |
| 69 | + |
| 70 | + device_registry.async_update_device(device_id, add_config_entry_id=entry.entry_id) |
| 71 | + |
| 72 | + return device_id |
| 73 | + |
| 74 | + |
52 | 75 | async def async_setup_entry(
|
53 | 76 | hass: HomeAssistant,
|
54 | 77 | config_entry: ConfigEntry,
|
55 | 78 | async_add_entities: AddConfigEntryEntitiesCallback,
|
56 | 79 | ) -> None:
|
57 | 80 | """Initialize min/max/mean config entry."""
|
58 | 81 | registry = er.async_get(hass)
|
59 |
| - entity_id = er.async_validate_entity_id( |
60 |
| - registry, config_entry.options[CONF_ENTITY_ID] |
61 |
| - ) |
| 82 | + try: |
| 83 | + entity_id = er.async_validate_entity_id( |
| 84 | + registry, config_entry.options[CONF_ENTITY_ID] |
| 85 | + ) |
| 86 | + except vol.Invalid: |
| 87 | + # The entity is identified by an unknown entity registry ID |
| 88 | + LOGGER.error( |
| 89 | + "Failed to setup periodic_min_max for unknown entity %s", |
| 90 | + config_entry.options[CONF_ENTITY_ID], |
| 91 | + ) |
| 92 | + return False |
| 93 | + |
62 | 94 | sensor_type = config_entry.options[CONF_TYPE]
|
63 | 95 |
|
| 96 | + async_add_to_device(hass, config_entry, entity_id) |
| 97 | + |
64 | 98 | async_add_entities(
|
65 | 99 | [
|
66 | 100 | PeriodicMinMaxSensor(
|
|
0 commit comments