Home Assistant Unofficial Reference 2024.12.1
entity.py
Go to the documentation of this file.
1 """The base entity for the rest component."""
2 
3 from __future__ import annotations
4 
5 from abc import abstractmethod
6 from typing import Any
7 
8 from homeassistant.core import callback
9 from homeassistant.helpers.entity import Entity
10 from homeassistant.helpers.template import Template
11 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
12 
13 from .data import RestData
14 
15 
17  """A class for entities using DataUpdateCoordinator or rest data directly."""
18 
19  def __init__(
20  self,
21  coordinator: DataUpdateCoordinator[Any] | None,
22  rest: RestData,
23  resource_template: Template | None,
24  force_update: bool,
25  ) -> None:
26  """Create the entity that may have a coordinator."""
27  self._coordinator_coordinator = coordinator
28  self.restrest = rest
29  self._resource_template_resource_template = resource_template
30  self._attr_should_poll_attr_should_poll = not coordinator
31  self._attr_force_update_attr_force_update = force_update
32 
33  @property
34  def available(self) -> bool:
35  """Return the availability of this sensor."""
36  if self._coordinator_coordinator and not self._coordinator_coordinator.last_update_success:
37  return False
38  return self.restrest.data is not None
39 
40  async def async_added_to_hass(self) -> None:
41  """When entity is added to hass."""
42  await super().async_added_to_hass()
43  self._update_from_rest_data_update_from_rest_data()
44  if self._coordinator_coordinator:
45  self.async_on_removeasync_on_remove(
46  self._coordinator_coordinator.async_add_listener(self._handle_coordinator_update_handle_coordinator_update)
47  )
48 
49  @callback
50  def _handle_coordinator_update(self) -> None:
51  """Handle updated data from the coordinator."""
52  self._update_from_rest_data_update_from_rest_data()
53  self.async_write_ha_stateasync_write_ha_state()
54 
55  async def async_update(self) -> None:
56  """Get the latest data from REST API and update the state."""
57  if self._coordinator_coordinator:
58  await self._coordinator_coordinator.async_request_refresh()
59  return
60 
61  if self._resource_template_resource_template is not None:
62  self.restrest.set_url(self._resource_template_resource_template.async_render(parse_result=False))
63  await self.restrest.async_update()
64  self._update_from_rest_data_update_from_rest_data()
65 
66  @abstractmethod
67  def _update_from_rest_data(self) -> None:
68  """Update state from the rest data."""
None __init__(self, DataUpdateCoordinator[Any]|None coordinator, RestData rest, Template|None resource_template, bool force_update)
Definition: entity.py:25
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
None async_add_listener(HomeAssistant hass, Callable[[], None] listener)
Definition: __init__.py:82