Use EntityDescription - ebox (#53565)

This commit is contained in:
Marc Mueller 2021-07-27 19:06:50 +02:00 committed by GitHub
parent 9e9165f4ac
commit a1e692798f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -7,13 +7,16 @@ from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import logging import logging
from typing import NamedTuple
from pyebox import EboxClient from pyebox import EboxClient
from pyebox.client import PyEboxError from pyebox.client import PyEboxError
import voluptuous as vol import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import ( from homeassistant.const import (
CONF_MONITORED_VARIABLES, CONF_MONITORED_VARIABLES,
CONF_NAME, CONF_NAME,
@ -38,81 +41,86 @@ SCAN_INTERVAL = timedelta(minutes=15)
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15) MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15)
class EboxSensorMetadata(NamedTuple): SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
"""Metadata for an individual ebox sensor.""" SensorEntityDescription(
key="usage",
name: str name="Usage",
unit_of_measurement: str
icon: str
SENSOR_TYPES = {
"usage": EboxSensorMetadata(
"Usage",
unit_of_measurement=PERCENTAGE, unit_of_measurement=PERCENTAGE,
icon="mdi:percent", icon="mdi:percent",
), ),
"balance": EboxSensorMetadata( SensorEntityDescription(
"Balance", key="balance",
name="Balance",
unit_of_measurement=PRICE, unit_of_measurement=PRICE,
icon="mdi:cash-usd", icon="mdi:cash-usd",
), ),
"limit": EboxSensorMetadata( SensorEntityDescription(
"Data limit", key="limit",
name="Data limit",
unit_of_measurement=DATA_GIGABITS, unit_of_measurement=DATA_GIGABITS,
icon="mdi:download", icon="mdi:download",
), ),
"days_left": EboxSensorMetadata( SensorEntityDescription(
"Days left", key="days_left",
name="Days left",
unit_of_measurement=TIME_DAYS, unit_of_measurement=TIME_DAYS,
icon="mdi:calendar-today", icon="mdi:calendar-today",
), ),
"before_offpeak_download": EboxSensorMetadata( SensorEntityDescription(
"Download before offpeak", key="before_offpeak_download",
name="Download before offpeak",
unit_of_measurement=DATA_GIGABITS, unit_of_measurement=DATA_GIGABITS,
icon="mdi:download", icon="mdi:download",
), ),
"before_offpeak_upload": EboxSensorMetadata( SensorEntityDescription(
"Upload before offpeak", key="before_offpeak_upload",
name="Upload before offpeak",
unit_of_measurement=DATA_GIGABITS, unit_of_measurement=DATA_GIGABITS,
icon="mdi:upload", icon="mdi:upload",
), ),
"before_offpeak_total": EboxSensorMetadata( SensorEntityDescription(
"Total before offpeak", key="before_offpeak_total",
name="Total before offpeak",
unit_of_measurement=DATA_GIGABITS, unit_of_measurement=DATA_GIGABITS,
icon="mdi:download", icon="mdi:download",
), ),
"offpeak_download": EboxSensorMetadata( SensorEntityDescription(
"Offpeak download", key="offpeak_download",
name="Offpeak download",
unit_of_measurement=DATA_GIGABITS, unit_of_measurement=DATA_GIGABITS,
icon="mdi:download", icon="mdi:download",
), ),
"offpeak_upload": EboxSensorMetadata( SensorEntityDescription(
"Offpeak Upload", key="offpeak_upload",
name="Offpeak Upload",
unit_of_measurement=DATA_GIGABITS, unit_of_measurement=DATA_GIGABITS,
icon="mdi:upload", icon="mdi:upload",
), ),
"offpeak_total": EboxSensorMetadata( SensorEntityDescription(
"Offpeak Total", key="offpeak_total",
name="Offpeak Total",
unit_of_measurement=DATA_GIGABITS, unit_of_measurement=DATA_GIGABITS,
icon="mdi:download", icon="mdi:download",
), ),
"download": EboxSensorMetadata( SensorEntityDescription(
"Download", key="download",
name="Download",
unit_of_measurement=DATA_GIGABITS, unit_of_measurement=DATA_GIGABITS,
icon="mdi:download", icon="mdi:download",
), ),
"upload": EboxSensorMetadata( SensorEntityDescription(
"Upload", key="upload",
name="Upload",
unit_of_measurement=DATA_GIGABITS, unit_of_measurement=DATA_GIGABITS,
icon="mdi:upload", icon="mdi:upload",
), ),
"total": EboxSensorMetadata( SensorEntityDescription(
"Total", key="total",
name="Total",
unit_of_measurement=DATA_GIGABITS, unit_of_measurement=DATA_GIGABITS,
icon="mdi:download", icon="mdi:download",
), ),
} )
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{ {
@ -142,9 +150,11 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
_LOGGER.error("Failed login: %s", exp) _LOGGER.error("Failed login: %s", exp)
raise PlatformNotReady from exp raise PlatformNotReady from exp
sensors = [] sensors = [
for variable in config[CONF_MONITORED_VARIABLES]: EBoxSensor(ebox_data, description, name)
sensors.append(EBoxSensor(ebox_data, variable, name)) for description in SENSOR_TYPES
if description.key in config[CONF_MONITORED_VARIABLES]
]
async_add_entities(sensors, True) async_add_entities(sensors, True)
@ -152,26 +162,24 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
class EBoxSensor(SensorEntity): class EBoxSensor(SensorEntity):
"""Implementation of a EBox sensor.""" """Implementation of a EBox sensor."""
def __init__(self, ebox_data, sensor_type, name): def __init__(
self,
ebox_data,
description: SensorEntityDescription,
name,
):
"""Initialize the sensor.""" """Initialize the sensor."""
self.type = sensor_type self.entity_description = description
metadata = SENSOR_TYPES[sensor_type] self._attr_name = f"{name} {description.name}"
self._attr_name = f"{name} {metadata.name}"
self._attr_unit_of_measurement = metadata.unit_of_measurement
self._attr_icon = metadata.icon
self.ebox_data = ebox_data self.ebox_data = ebox_data
self._state = None
@property
def state(self):
"""Return the state of the sensor."""
return self._state
async def async_update(self): async def async_update(self):
"""Get the latest data from EBox and update the state.""" """Get the latest data from EBox and update the state."""
await self.ebox_data.async_update() await self.ebox_data.async_update()
if self.type in self.ebox_data.data: if self.entity_description.key in self.ebox_data.data:
self._state = round(self.ebox_data.data[self.type], 2) self._attr_state = round(
self.ebox_data.data[self.entity_description.key], 2
)
class EBoxData: class EBoxData: