Use EntityDescription - tibber (#53569)

This commit is contained in:
Marc Mueller 2021-07-27 20:13:48 +02:00 committed by GitHub
parent 13443310fe
commit f599c5a39e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,11 +2,11 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
from dataclasses import dataclass
from datetime import timedelta from datetime import timedelta
from enum import Enum from enum import Enum
import logging import logging
from random import randrange from random import randrange
from typing import NamedTuple
import aiohttp import aiohttp
@ -20,6 +20,7 @@ from homeassistant.components.sensor import (
DEVICE_CLASS_VOLTAGE, DEVICE_CLASS_VOLTAGE,
STATE_CLASS_MEASUREMENT, STATE_CLASS_MEASUREMENT,
SensorEntity, SensorEntity,
SensorEntityDescription,
) )
from homeassistant.const import ( from homeassistant.const import (
ELECTRIC_CURRENT_AMPERE, ELECTRIC_CURRENT_AMPERE,
@ -58,140 +59,158 @@ class ResetType(Enum):
NEVER = "never" NEVER = "never"
class TibberSensorMetadata(NamedTuple): @dataclass
"""Metadata for an individual Tibber sensor.""" class TibberSensorEntityDescription(SensorEntityDescription):
"""Describes Tibber sensor entity."""
name: str
device_class: str
unit: str | None = None
state_class: str | None = None
reset_type: ResetType | None = None reset_type: ResetType | None = None
RT_SENSOR_MAP: dict[str, TibberSensorMetadata] = { RT_SENSOR_MAP: dict[str, TibberSensorEntityDescription] = {
"averagePower": TibberSensorMetadata( "averagePower": TibberSensorEntityDescription(
"average power", key="averagePower",
name="average power",
device_class=DEVICE_CLASS_POWER, device_class=DEVICE_CLASS_POWER,
unit=POWER_WATT, unit_of_measurement=POWER_WATT,
), ),
"power": TibberSensorMetadata( "power": TibberSensorEntityDescription(
"power", key="power",
name="power",
device_class=DEVICE_CLASS_POWER, device_class=DEVICE_CLASS_POWER,
unit=POWER_WATT, unit_of_measurement=POWER_WATT,
), ),
"powerProduction": TibberSensorMetadata( "powerProduction": TibberSensorEntityDescription(
"power production", key="powerProduction",
name="power production",
device_class=DEVICE_CLASS_POWER, device_class=DEVICE_CLASS_POWER,
unit=POWER_WATT, unit_of_measurement=POWER_WATT,
), ),
"minPower": TibberSensorMetadata( "minPower": TibberSensorEntityDescription(
"min power", key="minPower",
name="min power",
device_class=DEVICE_CLASS_POWER, device_class=DEVICE_CLASS_POWER,
unit=POWER_WATT, unit_of_measurement=POWER_WATT,
), ),
"maxPower": TibberSensorMetadata( "maxPower": TibberSensorEntityDescription(
"max power", key="maxPower",
name="max power",
device_class=DEVICE_CLASS_POWER, device_class=DEVICE_CLASS_POWER,
unit=POWER_WATT, unit_of_measurement=POWER_WATT,
), ),
"accumulatedConsumption": TibberSensorMetadata( "accumulatedConsumption": TibberSensorEntityDescription(
"accumulated consumption", key="accumulatedConsumption",
name="accumulated consumption",
device_class=DEVICE_CLASS_ENERGY, device_class=DEVICE_CLASS_ENERGY,
unit=ENERGY_KILO_WATT_HOUR, unit_of_measurement=ENERGY_KILO_WATT_HOUR,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
reset_type=ResetType.DAILY, reset_type=ResetType.DAILY,
), ),
"accumulatedConsumptionLastHour": TibberSensorMetadata( "accumulatedConsumptionLastHour": TibberSensorEntityDescription(
"accumulated consumption current hour", key="accumulatedConsumptionLastHour",
name="accumulated consumption current hour",
device_class=DEVICE_CLASS_ENERGY, device_class=DEVICE_CLASS_ENERGY,
unit=ENERGY_KILO_WATT_HOUR, unit_of_measurement=ENERGY_KILO_WATT_HOUR,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
reset_type=ResetType.HOURLY, reset_type=ResetType.HOURLY,
), ),
"accumulatedProduction": TibberSensorMetadata( "accumulatedProduction": TibberSensorEntityDescription(
"accumulated production", key="accumulatedProduction",
name="accumulated production",
device_class=DEVICE_CLASS_ENERGY, device_class=DEVICE_CLASS_ENERGY,
unit=ENERGY_KILO_WATT_HOUR, unit_of_measurement=ENERGY_KILO_WATT_HOUR,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
reset_type=ResetType.DAILY, reset_type=ResetType.DAILY,
), ),
"accumulatedProductionLastHour": TibberSensorMetadata( "accumulatedProductionLastHour": TibberSensorEntityDescription(
"accumulated production current hour", key="accumulatedProductionLastHour",
name="accumulated production current hour",
device_class=DEVICE_CLASS_ENERGY, device_class=DEVICE_CLASS_ENERGY,
unit=ENERGY_KILO_WATT_HOUR, unit_of_measurement=ENERGY_KILO_WATT_HOUR,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
reset_type=ResetType.HOURLY, reset_type=ResetType.HOURLY,
), ),
"lastMeterConsumption": TibberSensorMetadata( "lastMeterConsumption": TibberSensorEntityDescription(
"last meter consumption", key="lastMeterConsumption",
name="last meter consumption",
device_class=DEVICE_CLASS_ENERGY, device_class=DEVICE_CLASS_ENERGY,
unit=ENERGY_KILO_WATT_HOUR, unit_of_measurement=ENERGY_KILO_WATT_HOUR,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
), ),
"lastMeterProduction": TibberSensorMetadata( "lastMeterProduction": TibberSensorEntityDescription(
"last meter production", key="lastMeterProduction",
name="last meter production",
device_class=DEVICE_CLASS_ENERGY, device_class=DEVICE_CLASS_ENERGY,
unit=ENERGY_KILO_WATT_HOUR, unit_of_measurement=ENERGY_KILO_WATT_HOUR,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
), ),
"voltagePhase1": TibberSensorMetadata( "voltagePhase1": TibberSensorEntityDescription(
"voltage phase1", key="voltagePhase1",
name="voltage phase1",
device_class=DEVICE_CLASS_VOLTAGE, device_class=DEVICE_CLASS_VOLTAGE,
unit=ELECTRIC_POTENTIAL_VOLT, unit_of_measurement=ELECTRIC_POTENTIAL_VOLT,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
), ),
"voltagePhase2": TibberSensorMetadata( "voltagePhase2": TibberSensorEntityDescription(
"voltage phase2", key="voltagePhase2",
name="voltage phase2",
device_class=DEVICE_CLASS_VOLTAGE, device_class=DEVICE_CLASS_VOLTAGE,
unit=ELECTRIC_POTENTIAL_VOLT, unit_of_measurement=ELECTRIC_POTENTIAL_VOLT,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
), ),
"voltagePhase3": TibberSensorMetadata( "voltagePhase3": TibberSensorEntityDescription(
"voltage phase3", key="voltagePhase3",
name="voltage phase3",
device_class=DEVICE_CLASS_VOLTAGE, device_class=DEVICE_CLASS_VOLTAGE,
unit=ELECTRIC_POTENTIAL_VOLT, unit_of_measurement=ELECTRIC_POTENTIAL_VOLT,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
), ),
"currentL1": TibberSensorMetadata( "currentL1": TibberSensorEntityDescription(
"current L1", key="currentL1",
name="current L1",
device_class=DEVICE_CLASS_CURRENT, device_class=DEVICE_CLASS_CURRENT,
unit=ELECTRIC_CURRENT_AMPERE, unit_of_measurement=ELECTRIC_CURRENT_AMPERE,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
), ),
"currentL2": TibberSensorMetadata( "currentL2": TibberSensorEntityDescription(
"current L2", key="currentL2",
name="current L2",
device_class=DEVICE_CLASS_CURRENT, device_class=DEVICE_CLASS_CURRENT,
unit=ELECTRIC_CURRENT_AMPERE, unit_of_measurement=ELECTRIC_CURRENT_AMPERE,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
), ),
"currentL3": TibberSensorMetadata( "currentL3": TibberSensorEntityDescription(
"current L3", key="currentL3",
name="current L3",
device_class=DEVICE_CLASS_CURRENT, device_class=DEVICE_CLASS_CURRENT,
unit=ELECTRIC_CURRENT_AMPERE, unit_of_measurement=ELECTRIC_CURRENT_AMPERE,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
), ),
"signalStrength": TibberSensorMetadata( "signalStrength": TibberSensorEntityDescription(
"signal strength", key="signalStrength",
name="signal strength",
device_class=DEVICE_CLASS_SIGNAL_STRENGTH, device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
unit=SIGNAL_STRENGTH_DECIBELS, unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
), ),
"accumulatedReward": TibberSensorMetadata( "accumulatedReward": TibberSensorEntityDescription(
"accumulated reward", key="accumulatedReward",
name="accumulated reward",
device_class=DEVICE_CLASS_MONETARY, device_class=DEVICE_CLASS_MONETARY,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
reset_type=ResetType.DAILY, reset_type=ResetType.DAILY,
), ),
"accumulatedCost": TibberSensorMetadata( "accumulatedCost": TibberSensorEntityDescription(
"accumulated cost", key="accumulatedCost",
name="accumulated cost",
device_class=DEVICE_CLASS_MONETARY, device_class=DEVICE_CLASS_MONETARY,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
reset_type=ResetType.DAILY, reset_type=ResetType.DAILY,
), ),
"powerFactor": TibberSensorMetadata( "powerFactor": TibberSensorEntityDescription(
"power factor", key="powerFactor",
name="power factor",
device_class=DEVICE_CLASS_POWER_FACTOR, device_class=DEVICE_CLASS_POWER_FACTOR,
unit=PERCENTAGE, unit_of_measurement=PERCENTAGE,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
), ),
} }
@ -358,31 +377,33 @@ class TibberSensorRT(TibberSensor):
"""Representation of a Tibber sensor for real time consumption.""" """Representation of a Tibber sensor for real time consumption."""
_attr_should_poll = False _attr_should_poll = False
entity_description: TibberSensorEntityDescription
def __init__(self, tibber_home, metadata: TibberSensorMetadata, initial_state): def __init__(
self,
tibber_home,
description: TibberSensorEntityDescription,
initial_state,
):
"""Initialize the sensor.""" """Initialize the sensor."""
super().__init__(tibber_home) super().__init__(tibber_home)
self.entity_description = description
self._model = "Tibber Pulse" self._model = "Tibber Pulse"
self._device_name = f"{self._model} {self._home_name}" self._device_name = f"{self._model} {self._home_name}"
self._metadata = metadata
self._attr_device_class = metadata.device_class self._attr_name = f"{description.name} {self._home_name}"
self._attr_name = f"{metadata.name} {self._home_name}"
self._attr_state = initial_state self._attr_state = initial_state
self._attr_unique_id = f"{self._tibber_home.home_id}_rt_{metadata.name}" self._attr_unique_id = f"{self._tibber_home.home_id}_rt_{description.name}"
if metadata.name in ("accumulated cost", "accumulated reward"): if description.name in ("accumulated cost", "accumulated reward"):
self._attr_unit_of_measurement = tibber_home.currency self._attr_unit_of_measurement = tibber_home.currency
else: if description.reset_type == ResetType.NEVER:
self._attr_unit_of_measurement = metadata.unit
self._attr_state_class = metadata.state_class
if metadata.reset_type == ResetType.NEVER:
self._attr_last_reset = dt_util.utc_from_timestamp(0) self._attr_last_reset = dt_util.utc_from_timestamp(0)
elif metadata.reset_type == ResetType.DAILY: elif description.reset_type == ResetType.DAILY:
self._attr_last_reset = dt_util.as_utc( self._attr_last_reset = dt_util.as_utc(
dt_util.now().replace(hour=0, minute=0, second=0, microsecond=0) dt_util.now().replace(hour=0, minute=0, second=0, microsecond=0)
) )
elif metadata.reset_type == ResetType.HOURLY: elif description.reset_type == ResetType.HOURLY:
self._attr_last_reset = dt_util.as_utc( self._attr_last_reset = dt_util.as_utc(
dt_util.now().replace(minute=0, second=0, microsecond=0) dt_util.now().replace(minute=0, second=0, microsecond=0)
) )
@ -407,11 +428,17 @@ class TibberSensorRT(TibberSensor):
@callback @callback
def _set_state(self, state, timestamp): def _set_state(self, state, timestamp):
"""Set sensor state.""" """Set sensor state."""
if state < self._attr_state and self._metadata.reset_type == ResetType.DAILY: if (
state < self._attr_state
and self.entity_description.reset_type == ResetType.DAILY
):
self._attr_last_reset = dt_util.as_utc( self._attr_last_reset = dt_util.as_utc(
timestamp.replace(hour=0, minute=0, second=0, microsecond=0) timestamp.replace(hour=0, minute=0, second=0, microsecond=0)
) )
if state < self._attr_state and self._metadata.reset_type == ResetType.HOURLY: if (
state < self._attr_state
and self.entity_description.reset_type == ResetType.HOURLY
):
self._attr_last_reset = dt_util.as_utc( self._attr_last_reset = dt_util.as_utc(
timestamp.replace(minute=0, second=0, microsecond=0) timestamp.replace(minute=0, second=0, microsecond=0)
) )
@ -457,10 +484,9 @@ class TibberRtDataHandler:
timestamp, timestamp,
) )
else: else:
sensor_meta = RT_SENSOR_MAP[sensor_type]
entity = TibberSensorRT( entity = TibberSensorRT(
self._tibber_home, self._tibber_home,
sensor_meta, RT_SENSOR_MAP[sensor_type],
state, state,
) )
new_entities.append(entity) new_entities.append(entity)