|
| 1 | +"""Base auto-entity class.""" |
| 2 | + |
| 3 | +from functools import cached_property |
| 4 | +from typing import Generic, TypeVar, cast |
| 5 | + |
| 6 | +from homeassistant.core import Event, EventStateChangedData, State, HomeAssistant |
| 7 | +from homeassistant.const import STATE_UNKNOWN, STATE_UNAVAILABLE |
| 8 | +from homeassistant.components.binary_sensor import BinarySensorDeviceClass |
| 9 | +from homeassistant.helpers.entity import Entity |
| 10 | +from homeassistant.helpers.device_registry import DeviceInfo |
| 11 | +from homeassistant.helpers.typing import StateType |
| 12 | +from homeassistant.components.sensor.const import SensorDeviceClass |
| 13 | +from homeassistant.helpers.event import async_track_state_change_event |
| 14 | + |
| 15 | +from custom_components.auto_areas.calculations import get_calculation |
| 16 | + |
| 17 | +from .auto_area import AutoArea |
| 18 | +from .const import DOMAIN, LOGGER, NAME, VERSION |
| 19 | + |
| 20 | +_TDeviceClass = TypeVar( |
| 21 | + "_TDeviceClass", BinarySensorDeviceClass, SensorDeviceClass) |
| 22 | +_TEntity = TypeVar("_TEntity", bound=Entity) |
| 23 | + |
| 24 | + |
| 25 | +class AutoEntity(Entity, Generic[_TEntity, _TDeviceClass]): |
| 26 | + """Set up an aggregated entity.""" |
| 27 | + |
| 28 | + def __init__(self, |
| 29 | + hass: HomeAssistant, |
| 30 | + auto_area: AutoArea, |
| 31 | + device_class: _TDeviceClass, |
| 32 | + name_prefix: str, |
| 33 | + prefix: str |
| 34 | + ) -> None: |
| 35 | + """Initialize sensor.""" |
| 36 | + super().__init__() |
| 37 | + self.hass = hass |
| 38 | + self.auto_area = auto_area |
| 39 | + self._device_class = device_class |
| 40 | + self._name_prefix = name_prefix |
| 41 | + self._prefix = prefix |
| 42 | + |
| 43 | + self.entity_ids: list[str] = self._get_sensor_entities() |
| 44 | + self.unsubscribe = None |
| 45 | + self.entity_states: dict[str, State] = {} |
| 46 | + self._aggregated_state: StateType = None |
| 47 | + |
| 48 | + LOGGER.info( |
| 49 | + "%s: Initialized %s sensor", |
| 50 | + self.auto_area.area_name, |
| 51 | + self.device_class |
| 52 | + ) |
| 53 | + |
| 54 | + def _get_sensor_entities(self) -> list[str]: |
| 55 | + """Retrieve all relevant entity ids for this sensor.""" |
| 56 | + return [ |
| 57 | + entity.entity_id |
| 58 | + for entity in self.auto_area.get_valid_entities() |
| 59 | + if entity.device_class == self.device_class |
| 60 | + or entity.original_device_class == self.device_class |
| 61 | + ] |
| 62 | + |
| 63 | + @cached_property |
| 64 | + def name(self): |
| 65 | + """Name of this entity.""" |
| 66 | + return f"{self._name_prefix}{self.auto_area.area_name}" |
| 67 | + |
| 68 | + @cached_property |
| 69 | + def unique_id(self) -> str: |
| 70 | + """Return a unique ID.""" |
| 71 | + return f"{self.auto_area.config_entry.entry_id}_aggregated_{self.device_class}" |
| 72 | + |
| 73 | + @cached_property |
| 74 | + def device_class(self) -> _TDeviceClass: |
| 75 | + """Return device class.""" |
| 76 | + return cast(_TDeviceClass, self._device_class) |
| 77 | + |
| 78 | + @cached_property |
| 79 | + def device_info(self) -> DeviceInfo: |
| 80 | + """Information about this device.""" |
| 81 | + return { |
| 82 | + "identifiers": {(DOMAIN, self.auto_area.config_entry.entry_id)}, |
| 83 | + "name": NAME, |
| 84 | + "model": VERSION, |
| 85 | + "manufacturer": NAME, |
| 86 | + "suggested_area": self.auto_area.area_name, |
| 87 | + } |
| 88 | + |
| 89 | + async def async_added_to_hass(self): |
| 90 | + """Start tracking sensors.""" |
| 91 | + LOGGER.debug( |
| 92 | + "%s: %s sensor entities: %s", |
| 93 | + self.auto_area.area_name, |
| 94 | + self.device_class, |
| 95 | + self.entity_ids, |
| 96 | + ) |
| 97 | + |
| 98 | + # Get all current states |
| 99 | + for entity_id in self.entity_ids: |
| 100 | + state = self.hass.states.get(entity_id) |
| 101 | + if state is not None: |
| 102 | + try: |
| 103 | + self.entity_states[entity_id] = state |
| 104 | + except ValueError: |
| 105 | + LOGGER.warning( |
| 106 | + "No initial state available for %s", entity_id |
| 107 | + ) |
| 108 | + |
| 109 | + self._aggregated_state = self._get_state() |
| 110 | + self.schedule_update_ha_state() |
| 111 | + |
| 112 | + # Subscribe to state changes |
| 113 | + self.unsubscribe = async_track_state_change_event( |
| 114 | + self.hass, |
| 115 | + self.entity_ids, |
| 116 | + self._handle_state_change, |
| 117 | + ) |
| 118 | + |
| 119 | + async def _handle_state_change(self, event: Event[EventStateChangedData]): |
| 120 | + """Handle state change of any tracked illuminance sensors.""" |
| 121 | + to_state = event.data.get("new_state") |
| 122 | + if to_state is None: |
| 123 | + return |
| 124 | + |
| 125 | + if to_state.state in [ |
| 126 | + STATE_UNKNOWN, |
| 127 | + STATE_UNAVAILABLE, |
| 128 | + ]: |
| 129 | + self.entity_states.pop(to_state.entity_id, None) |
| 130 | + else: |
| 131 | + try: |
| 132 | + to_state.state = float(to_state.state) # type: ignore |
| 133 | + self.entity_states[to_state.entity_id] = to_state |
| 134 | + except ValueError: |
| 135 | + self.entity_states.pop(to_state.entity_id, None) |
| 136 | + |
| 137 | + self._aggregated_state = self._get_state() |
| 138 | + |
| 139 | + LOGGER.debug( |
| 140 | + "%s: got state %s, %d entities", |
| 141 | + self.device_class, |
| 142 | + str(self.state), |
| 143 | + len(self.entity_states.values()) |
| 144 | + ) |
| 145 | + |
| 146 | + self.async_schedule_update_ha_state() |
| 147 | + |
| 148 | + async def async_will_remove_from_hass(self) -> None: |
| 149 | + """Clean up event listeners.""" |
| 150 | + if self.unsubscribe: |
| 151 | + self.unsubscribe() |
| 152 | + |
| 153 | + def _get_state(self) -> StateType | None: |
| 154 | + """Get the state of the sensor.""" |
| 155 | + calculate_state = get_calculation( |
| 156 | + self.auto_area.config_entry.options, |
| 157 | + self.device_class |
| 158 | + ) |
| 159 | + if calculate_state is None: |
| 160 | + LOGGER.error( |
| 161 | + "%s: %s unable to get state calculation method", |
| 162 | + self.auto_area.area_name, |
| 163 | + self.device_class |
| 164 | + ) |
| 165 | + return None |
| 166 | + |
| 167 | + return calculate_state(list(self.entity_states.values())) |
0 commit comments