Use entity descriptions classes in Forecast.Solar (#53553)

This commit is contained in:
Franck Nijhof 2021-07-27 17:45:47 +02:00 committed by GitHub
parent 72a98550b6
commit f1eb35b1a5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 31 additions and 40 deletions

View File

@ -13,7 +13,7 @@ from homeassistant.const import (
POWER_WATT, POWER_WATT,
) )
from .models import ForecastSolarSensor from .models import ForecastSolarSensorEntityDescription
DOMAIN = "forecast_solar" DOMAIN = "forecast_solar"
@ -24,32 +24,32 @@ CONF_DAMPING = "damping"
ATTR_ENTRY_TYPE: Final = "entry_type" ATTR_ENTRY_TYPE: Final = "entry_type"
ENTRY_TYPE_SERVICE: Final = "service" ENTRY_TYPE_SERVICE: Final = "service"
SENSORS: list[ForecastSolarSensor] = [ SENSORS: tuple[ForecastSolarSensorEntityDescription, ...] = (
ForecastSolarSensor( ForecastSolarSensorEntityDescription(
key="energy_production_today", key="energy_production_today",
name="Estimated Energy Production - Today", name="Estimated Energy Production - Today",
state=lambda estimate: estimate.energy_production_today / 1000, state=lambda estimate: estimate.energy_production_today / 1000,
device_class=DEVICE_CLASS_ENERGY, device_class=DEVICE_CLASS_ENERGY,
unit_of_measurement=ENERGY_KILO_WATT_HOUR, unit_of_measurement=ENERGY_KILO_WATT_HOUR,
), ),
ForecastSolarSensor( ForecastSolarSensorEntityDescription(
key="energy_production_tomorrow", key="energy_production_tomorrow",
name="Estimated Energy Production - Tomorrow", name="Estimated Energy Production - Tomorrow",
state=lambda estimate: estimate.energy_production_tomorrow / 1000, state=lambda estimate: estimate.energy_production_tomorrow / 1000,
device_class=DEVICE_CLASS_ENERGY, device_class=DEVICE_CLASS_ENERGY,
unit_of_measurement=ENERGY_KILO_WATT_HOUR, unit_of_measurement=ENERGY_KILO_WATT_HOUR,
), ),
ForecastSolarSensor( ForecastSolarSensorEntityDescription(
key="power_highest_peak_time_today", key="power_highest_peak_time_today",
name="Highest Power Peak Time - Today", name="Highest Power Peak Time - Today",
device_class=DEVICE_CLASS_TIMESTAMP, device_class=DEVICE_CLASS_TIMESTAMP,
), ),
ForecastSolarSensor( ForecastSolarSensorEntityDescription(
key="power_highest_peak_time_tomorrow", key="power_highest_peak_time_tomorrow",
name="Highest Power Peak Time - Tomorrow", name="Highest Power Peak Time - Tomorrow",
device_class=DEVICE_CLASS_TIMESTAMP, device_class=DEVICE_CLASS_TIMESTAMP,
), ),
ForecastSolarSensor( ForecastSolarSensorEntityDescription(
key="power_production_now", key="power_production_now",
name="Estimated Power Production - Now", name="Estimated Power Production - Now",
device_class=DEVICE_CLASS_POWER, device_class=DEVICE_CLASS_POWER,
@ -57,7 +57,7 @@ SENSORS: list[ForecastSolarSensor] = [
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
unit_of_measurement=POWER_WATT, unit_of_measurement=POWER_WATT,
), ),
ForecastSolarSensor( ForecastSolarSensorEntityDescription(
key="power_production_next_hour", key="power_production_next_hour",
state=lambda estimate: estimate.power_production_at_time( state=lambda estimate: estimate.power_production_at_time(
estimate.now() + timedelta(hours=1) estimate.now() + timedelta(hours=1)
@ -68,7 +68,7 @@ SENSORS: list[ForecastSolarSensor] = [
entity_registry_enabled_default=False, entity_registry_enabled_default=False,
unit_of_measurement=POWER_WATT, unit_of_measurement=POWER_WATT,
), ),
ForecastSolarSensor( ForecastSolarSensorEntityDescription(
key="power_production_next_12hours", key="power_production_next_12hours",
state=lambda estimate: estimate.power_production_at_time( state=lambda estimate: estimate.power_production_at_time(
estimate.now() + timedelta(hours=12) estimate.now() + timedelta(hours=12)
@ -79,7 +79,7 @@ SENSORS: list[ForecastSolarSensor] = [
entity_registry_enabled_default=False, entity_registry_enabled_default=False,
unit_of_measurement=POWER_WATT, unit_of_measurement=POWER_WATT,
), ),
ForecastSolarSensor( ForecastSolarSensorEntityDescription(
key="power_production_next_24hours", key="power_production_next_24hours",
state=lambda estimate: estimate.power_production_at_time( state=lambda estimate: estimate.power_production_at_time(
estimate.now() + timedelta(hours=24) estimate.now() + timedelta(hours=24)
@ -90,18 +90,18 @@ SENSORS: list[ForecastSolarSensor] = [
entity_registry_enabled_default=False, entity_registry_enabled_default=False,
unit_of_measurement=POWER_WATT, unit_of_measurement=POWER_WATT,
), ),
ForecastSolarSensor( ForecastSolarSensorEntityDescription(
key="energy_current_hour", key="energy_current_hour",
name="Estimated Energy Production - This Hour", name="Estimated Energy Production - This Hour",
state=lambda estimate: estimate.energy_current_hour / 1000, state=lambda estimate: estimate.energy_current_hour / 1000,
device_class=DEVICE_CLASS_ENERGY, device_class=DEVICE_CLASS_ENERGY,
unit_of_measurement=ENERGY_KILO_WATT_HOUR, unit_of_measurement=ENERGY_KILO_WATT_HOUR,
), ),
ForecastSolarSensor( ForecastSolarSensorEntityDescription(
key="energy_next_hour", key="energy_next_hour",
state=lambda estimate: estimate.sum_energy_production(1) / 1000, state=lambda estimate: estimate.sum_energy_production(1) / 1000,
name="Estimated Energy Production - Next Hour", name="Estimated Energy Production - Next Hour",
device_class=DEVICE_CLASS_ENERGY, device_class=DEVICE_CLASS_ENERGY,
unit_of_measurement=ENERGY_KILO_WATT_HOUR, unit_of_measurement=ENERGY_KILO_WATT_HOUR,
), ),
] )

View File

@ -6,16 +6,11 @@ from typing import Any, Callable
from forecast_solar.models import Estimate from forecast_solar.models import Estimate
from homeassistant.components.sensor import SensorEntityDescription
@dataclass @dataclass
class ForecastSolarSensor: class ForecastSolarSensorEntityDescription(SensorEntityDescription):
"""Represents an Forecast.Solar Sensor.""" """Describes a Forecast.Solar Sensor."""
key: str
name: str
device_class: str | None = None
entity_registry_enabled_default: bool = True
state: Callable[[Estimate], Any] | None = None state: Callable[[Estimate], Any] | None = None
state_class: str | None = None
unit_of_measurement: str | None = None

View File

@ -15,7 +15,7 @@ from homeassistant.helpers.update_coordinator import (
) )
from .const import ATTR_ENTRY_TYPE, DOMAIN, ENTRY_TYPE_SERVICE, SENSORS from .const import ATTR_ENTRY_TYPE, DOMAIN, ENTRY_TYPE_SERVICE, SENSORS
from .models import ForecastSolarSensor from .models import ForecastSolarSensorEntityDescription
async def async_setup_entry( async def async_setup_entry(
@ -26,35 +26,31 @@ async def async_setup_entry(
async_add_entities( async_add_entities(
ForecastSolarSensorEntity( ForecastSolarSensorEntity(
entry_id=entry.entry_id, coordinator=coordinator, sensor=sensor entry_id=entry.entry_id,
coordinator=coordinator,
entity_description=entity_description,
) )
for sensor in SENSORS for entity_description in SENSORS
) )
class ForecastSolarSensorEntity(CoordinatorEntity, SensorEntity): class ForecastSolarSensorEntity(CoordinatorEntity, SensorEntity):
"""Defines a Forcast.Solar sensor.""" """Defines a Forcast.Solar sensor."""
entity_description: ForecastSolarSensorEntityDescription
def __init__( def __init__(
self, self,
*, *,
entry_id: str, entry_id: str,
coordinator: DataUpdateCoordinator, coordinator: DataUpdateCoordinator,
sensor: ForecastSolarSensor, entity_description: ForecastSolarSensorEntityDescription,
) -> None: ) -> None:
"""Initialize Forcast.Solar sensor.""" """Initialize Forcast.Solar sensor."""
super().__init__(coordinator=coordinator) super().__init__(coordinator=coordinator)
self._sensor = sensor self.entity_description = entity_description
self.entity_id = f"{SENSOR_DOMAIN}.{entity_description.key}"
self.entity_id = f"{SENSOR_DOMAIN}.{sensor.key}" self._attr_unique_id = f"{entry_id}_{entity_description.key}"
self._attr_device_class = sensor.device_class
self._attr_entity_registry_enabled_default = (
sensor.entity_registry_enabled_default
)
self._attr_name = sensor.name
self._attr_state_class = sensor.state_class
self._attr_unique_id = f"{entry_id}_{sensor.key}"
self._attr_unit_of_measurement = sensor.unit_of_measurement
self._attr_device_info = { self._attr_device_info = {
ATTR_IDENTIFIERS: {(DOMAIN, entry_id)}, ATTR_IDENTIFIERS: {(DOMAIN, entry_id)},
@ -66,12 +62,12 @@ class ForecastSolarSensorEntity(CoordinatorEntity, SensorEntity):
@property @property
def state(self) -> StateType: def state(self) -> StateType:
"""Return the state of the sensor.""" """Return the state of the sensor."""
if self._sensor.state is None: if self.entity_description.state is None:
state: StateType | datetime = getattr( state: StateType | datetime = getattr(
self.coordinator.data, self._sensor.key self.coordinator.data, self.entity_description.key
) )
else: else:
state = self._sensor.state(self.coordinator.data) state = self.entity_description.state(self.coordinator.data)
if isinstance(state, datetime): if isinstance(state, datetime):
return state.isoformat() return state.isoformat()