Use attributes in rest base entity (#77903)

This commit is contained in:
epenet 2022-09-07 09:40:52 +02:00 committed by GitHub
parent fce28d4848
commit a82484d7a7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,10 +1,12 @@
"""The base entity for the rest component."""
from __future__ import annotations
from abc import abstractmethod
from typing import Any
from homeassistant.core import callback
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.template import Template
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from .data import RestData
@ -15,31 +17,22 @@ class RestEntity(Entity):
def __init__(
self,
coordinator: DataUpdateCoordinator[Any],
coordinator: DataUpdateCoordinator[Any] | None,
rest: RestData,
resource_template,
force_update,
resource_template: Template | None,
force_update: bool,
) -> None:
"""Create the entity that may have a coordinator."""
self.coordinator = coordinator
self._coordinator = coordinator
self.rest = rest
self._resource_template = resource_template
self._force_update = force_update
self._attr_should_poll = not coordinator
self._attr_force_update = force_update
@property
def force_update(self):
"""Force update."""
return self._force_update
@property
def should_poll(self) -> bool:
"""Poll only if we do not have a coordinator."""
return not self.coordinator
@property
def available(self):
def available(self) -> bool:
"""Return the availability of this sensor."""
if self.coordinator and not self.coordinator.last_update_success:
if self._coordinator and not self._coordinator.last_update_success:
return False
return self.rest.data is not None
@ -47,9 +40,9 @@ class RestEntity(Entity):
"""When entity is added to hass."""
await super().async_added_to_hass()
self._update_from_rest_data()
if self.coordinator:
if self._coordinator:
self.async_on_remove(
self.coordinator.async_add_listener(self._handle_coordinator_update)
self._coordinator.async_add_listener(self._handle_coordinator_update)
)
@callback
@ -58,10 +51,10 @@ class RestEntity(Entity):
self._update_from_rest_data()
self.async_write_ha_state()
async def async_update(self):
async def async_update(self) -> None:
"""Get the latest data from REST API and update the state."""
if self.coordinator:
await self.coordinator.async_request_refresh()
if self._coordinator:
await self._coordinator.async_request_refresh()
return
if self._resource_template is not None:
@ -70,5 +63,5 @@ class RestEntity(Entity):
self._update_from_rest_data()
@abstractmethod
def _update_from_rest_data(self):
def _update_from_rest_data(self) -> None:
"""Update state from the rest data."""