Use EntityDescription - bbox (#55064)

This commit is contained in:
Marc Mueller 2021-08-23 22:24:32 +02:00 committed by GitHub
parent 90f7131328
commit a84f1284c0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,4 +1,6 @@
"""Support for Bbox Bouygues Modem Router.""" """Support for Bbox Bouygues Modem Router."""
from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import logging import logging
@ -6,7 +8,11 @@ import pybbox
import requests import requests
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 (
ATTR_ATTRIBUTION, ATTR_ATTRIBUTION,
CONF_MONITORED_VARIABLES, CONF_MONITORED_VARIABLES,
@ -26,36 +32,52 @@ DEFAULT_NAME = "Bbox"
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
# Sensor types are defined like so: Name, unit, icon SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
SENSOR_TYPES = { SensorEntityDescription(
"down_max_bandwidth": [ key="down_max_bandwidth",
"Maximum Download Bandwidth", name="Maximum Download Bandwidth",
DATA_RATE_MEGABITS_PER_SECOND, native_unit_of_measurement=DATA_RATE_MEGABITS_PER_SECOND,
"mdi:download", icon="mdi:download",
], ),
"up_max_bandwidth": [ SensorEntityDescription(
"Maximum Upload Bandwidth", key="up_max_bandwidth",
DATA_RATE_MEGABITS_PER_SECOND, name="Maximum Upload Bandwidth",
"mdi:upload", native_unit_of_measurement=DATA_RATE_MEGABITS_PER_SECOND,
], icon="mdi:upload",
"current_down_bandwidth": [ ),
"Currently Used Download Bandwidth", SensorEntityDescription(
DATA_RATE_MEGABITS_PER_SECOND, key="current_down_bandwidth",
"mdi:download", name="Currently Used Download Bandwidth",
], native_unit_of_measurement=DATA_RATE_MEGABITS_PER_SECOND,
"current_up_bandwidth": [ icon="mdi:download",
"Currently Used Upload Bandwidth", ),
DATA_RATE_MEGABITS_PER_SECOND, SensorEntityDescription(
"mdi:upload", key="current_up_bandwidth",
], name="Currently Used Upload Bandwidth",
"uptime": ["Uptime", None, "mdi:clock"], native_unit_of_measurement=DATA_RATE_MEGABITS_PER_SECOND,
"number_of_reboots": ["Number of reboot", None, "mdi:restart"], icon="mdi:upload",
} ),
SensorEntityDescription(
key="number_of_reboots",
name="Number of reboot",
icon="mdi:restart",
),
)
SENSOR_TYPES_UPTIME: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="uptime",
name="Uptime",
icon="mdi:clock",
),
)
SENSOR_KEYS: list[str] = [desc.key for desc in (*SENSOR_TYPES, *SENSOR_TYPES_UPTIME)]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{ {
vol.Required(CONF_MONITORED_VARIABLES): vol.All( vol.Required(CONF_MONITORED_VARIABLES): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)] cv.ensure_list, [vol.In(SENSOR_KEYS)]
), ),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
} }
@ -75,14 +97,21 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
name = config[CONF_NAME] name = config[CONF_NAME]
sensors = [] monitored_variables = config[CONF_MONITORED_VARIABLES]
for variable in config[CONF_MONITORED_VARIABLES]: entities: list[BboxSensor | BboxUptimeSensor] = [
if variable == "uptime": BboxSensor(bbox_data, name, description)
sensors.append(BboxUptimeSensor(bbox_data, variable, name)) for description in SENSOR_TYPES
else: if description.key in monitored_variables
sensors.append(BboxSensor(bbox_data, variable, name)) ]
entities.extend(
[
BboxUptimeSensor(bbox_data, name, description)
for description in SENSOR_TYPES_UPTIME
if description.key in monitored_variables
]
)
add_entities(sensors, True) add_entities(entities, True)
class BboxUptimeSensor(SensorEntity): class BboxUptimeSensor(SensorEntity):
@ -91,11 +120,10 @@ class BboxUptimeSensor(SensorEntity):
_attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION} _attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION}
_attr_device_class = DEVICE_CLASS_TIMESTAMP _attr_device_class = DEVICE_CLASS_TIMESTAMP
def __init__(self, bbox_data, sensor_type, name): def __init__(self, bbox_data, name, description: SensorEntityDescription):
"""Initialize the sensor.""" """Initialize the sensor."""
self._attr_name = f"{name} {SENSOR_TYPES[sensor_type][0]}" self.entity_description = description
self._attr_native_unit_of_measurement = SENSOR_TYPES[sensor_type][1] self._attr_name = f"{name} {description.name}"
self._attr_icon = SENSOR_TYPES[sensor_type][2]
self.bbox_data = bbox_data self.bbox_data = bbox_data
def update(self): def update(self):
@ -112,34 +140,33 @@ class BboxSensor(SensorEntity):
_attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION} _attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION}
def __init__(self, bbox_data, sensor_type, name): def __init__(self, bbox_data, name, description: SensorEntityDescription):
"""Initialize the sensor.""" """Initialize the sensor."""
self.type = sensor_type self.entity_description = description
self._attr_name = f"{name} {SENSOR_TYPES[sensor_type][0]}" self._attr_name = f"{name} {description.name}"
self._attr_native_unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self._attr_icon = SENSOR_TYPES[sensor_type][2]
self.bbox_data = bbox_data self.bbox_data = bbox_data
def update(self): def update(self):
"""Get the latest data from Bbox and update the state.""" """Get the latest data from Bbox and update the state."""
self.bbox_data.update() self.bbox_data.update()
if self.type == "down_max_bandwidth": sensor_type = self.entity_description.key
if sensor_type == "down_max_bandwidth":
self._attr_native_value = round( self._attr_native_value = round(
self.bbox_data.data["rx"]["maxBandwidth"] / 1000, 2 self.bbox_data.data["rx"]["maxBandwidth"] / 1000, 2
) )
elif self.type == "up_max_bandwidth": elif sensor_type == "up_max_bandwidth":
self._attr_native_value = round( self._attr_native_value = round(
self.bbox_data.data["tx"]["maxBandwidth"] / 1000, 2 self.bbox_data.data["tx"]["maxBandwidth"] / 1000, 2
) )
elif self.type == "current_down_bandwidth": elif sensor_type == "current_down_bandwidth":
self._attr_native_value = round( self._attr_native_value = round(
self.bbox_data.data["rx"]["bandwidth"] / 1000, 2 self.bbox_data.data["rx"]["bandwidth"] / 1000, 2
) )
elif self.type == "current_up_bandwidth": elif sensor_type == "current_up_bandwidth":
self._attr_native_value = round( self._attr_native_value = round(
self.bbox_data.data["tx"]["bandwidth"] / 1000, 2 self.bbox_data.data["tx"]["bandwidth"] / 1000, 2
) )
elif self.type == "number_of_reboots": elif sensor_type == "number_of_reboots":
self._attr_native_value = self.bbox_data.router_infos["device"][ self._attr_native_value = self.bbox_data.router_infos["device"][
"numberofboots" "numberofboots"
] ]