Use EntityDescription - luftdaten (#55676)

* Use EntityDescription - luftdaten

* Fix name attribute

* Remove default values

* Move SensorTypes back to __init__
This commit is contained in:
Marc Mueller 2021-09-03 22:34:01 +02:00 committed by GitHub
parent fbf812a845
commit 3c0a34dd01
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 62 additions and 90 deletions

View File

@ -1,10 +1,13 @@
"""Support for Luftdaten stations."""
from __future__ import annotations
import logging
from luftdaten import Luftdaten
from luftdaten.exceptions import LuftdatenError
import voluptuous as vol
from homeassistant.components.sensor import SensorEntityDescription
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import (
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
@ -47,49 +50,53 @@ SENSOR_TEMPERATURE = "temperature"
TOPIC_UPDATE = f"{DOMAIN}_data_update"
SENSORS = {
SENSOR_TEMPERATURE: [
"Temperature",
"mdi:thermometer",
TEMP_CELSIUS,
DEVICE_CLASS_TEMPERATURE,
],
SENSOR_HUMIDITY: [
"Humidity",
"mdi:water-percent",
PERCENTAGE,
DEVICE_CLASS_HUMIDITY,
],
SENSOR_PRESSURE: [
"Pressure",
"mdi:arrow-down-bold",
PRESSURE_HPA,
DEVICE_CLASS_PRESSURE,
],
SENSOR_PRESSURE_AT_SEALEVEL: [
"Pressure at sealevel",
"mdi:download",
PRESSURE_HPA,
DEVICE_CLASS_PRESSURE,
],
SENSOR_PM10: [
"PM10",
"mdi:thought-bubble",
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
None,
],
SENSOR_PM2_5: [
"PM2.5",
"mdi:thought-bubble-outline",
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
None,
],
}
SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key=SENSOR_TEMPERATURE,
name="Temperature",
native_unit_of_measurement=TEMP_CELSIUS,
device_class=DEVICE_CLASS_TEMPERATURE,
),
SensorEntityDescription(
key=SENSOR_HUMIDITY,
name="Humidity",
icon="mdi:water-percent",
native_unit_of_measurement=PERCENTAGE,
device_class=DEVICE_CLASS_HUMIDITY,
),
SensorEntityDescription(
key=SENSOR_PRESSURE,
name="Pressure",
icon="mdi:arrow-down-bold",
native_unit_of_measurement=PRESSURE_HPA,
device_class=DEVICE_CLASS_PRESSURE,
),
SensorEntityDescription(
key=SENSOR_PRESSURE_AT_SEALEVEL,
name="Pressure at sealevel",
icon="mdi:download",
native_unit_of_measurement=PRESSURE_HPA,
device_class=DEVICE_CLASS_PRESSURE,
),
SensorEntityDescription(
key=SENSOR_PM10,
name="PM10",
icon="mdi:thought-bubble",
native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
),
SensorEntityDescription(
key=SENSOR_PM2_5,
name="PM2.5",
icon="mdi:thought-bubble-outline",
native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
),
)
SENSOR_KEYS: list[str] = [desc.key for desc in SENSOR_TYPES]
SENSOR_SCHEMA = vol.Schema(
{
vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSORS)): vol.All(
cv.ensure_list, [vol.In(SENSORS)]
vol.Optional(CONF_MONITORED_CONDITIONS, default=SENSOR_KEYS): vol.All(
cv.ensure_list, [vol.In(SENSOR_KEYS)]
)
}
)
@ -174,7 +181,7 @@ async def async_setup_entry(hass, config_entry):
luftdaten = LuftDatenData(
Luftdaten(config_entry.data[CONF_SENSOR_ID], hass.loop, session),
config_entry.data.get(CONF_SENSORS, {}).get(
CONF_MONITORED_CONDITIONS, list(SENSORS)
CONF_MONITORED_CONDITIONS, SENSOR_KEYS
),
)
await luftdaten.async_update()

View File

@ -1,7 +1,5 @@
"""Support for Luftdaten sensors."""
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.components.sensor import SensorEntity, SensorEntityDescription
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_LATITUDE,
@ -16,87 +14,54 @@ from . import (
DATA_LUFTDATEN_CLIENT,
DEFAULT_ATTRIBUTION,
DOMAIN,
SENSORS,
SENSOR_TYPES,
TOPIC_UPDATE,
)
from .const import ATTR_SENSOR_ID
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up a Luftdaten sensor based on a config entry."""
luftdaten = hass.data[DOMAIN][DATA_LUFTDATEN_CLIENT][entry.entry_id]
sensors = []
for sensor_type in luftdaten.sensor_conditions:
try:
name, icon, unit, device_class = SENSORS[sensor_type]
except KeyError:
_LOGGER.debug("Unknown sensor value type: %s", sensor_type)
continue
entities = [
LuftdatenSensor(luftdaten, description, entry.data[CONF_SHOW_ON_MAP])
for description in SENSOR_TYPES
if description.key in luftdaten.sensor_conditions
]
sensors.append(
LuftdatenSensor(
luftdaten,
sensor_type,
name,
icon,
unit,
device_class,
entry.data[CONF_SHOW_ON_MAP],
)
)
async_add_entities(sensors, True)
async_add_entities(entities, True)
class LuftdatenSensor(SensorEntity):
"""Implementation of a Luftdaten sensor."""
def __init__(self, luftdaten, sensor_type, name, icon, unit, device_class, show):
_attr_should_poll = False
def __init__(self, luftdaten, description: SensorEntityDescription, show):
"""Initialize the Luftdaten sensor."""
self.entity_description = description
self._async_unsub_dispatcher_connect = None
self.luftdaten = luftdaten
self._icon = icon
self._name = name
self._data = None
self.sensor_type = sensor_type
self._unit_of_measurement = unit
self._show_on_map = show
self._attrs = {}
self._attr_device_class = device_class
@property
def icon(self):
"""Return the icon."""
return self._icon
@property
def native_value(self):
"""Return the state of the device."""
if self._data is not None:
try:
return self._data[self.sensor_type]
return self._data[self.entity_description.key]
except KeyError:
return None
@property
def native_unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
@property
def should_poll(self):
"""Disable polling."""
return False
@property
def unique_id(self) -> str:
"""Return a unique, friendly identifier for this entity."""
if self._data is not None:
try:
return f"{self._data['sensor_id']}_{self.sensor_type}"
return f"{self._data['sensor_id']}_{self.entity_description.key}"
except KeyError:
return None