Use EntityDescription - bme280 (#55184)

This commit is contained in:
Marc Mueller 2021-08-25 10:39:59 +02:00 committed by GitHub
parent 5e44498f1c
commit 4a03d8dc47
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 25 deletions

View File

@ -30,7 +30,7 @@ from .const import (
DEFAULT_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL,
DEFAULT_T_STANDBY, DEFAULT_T_STANDBY,
DOMAIN, DOMAIN,
SENSOR_TYPES, SENSOR_KEYS,
) )
CONFIG_SCHEMA = vol.Schema( CONFIG_SCHEMA = vol.Schema(
@ -54,7 +54,7 @@ CONFIG_SCHEMA = vol.Schema(
): vol.Coerce(float), ): vol.Coerce(float),
vol.Optional( vol.Optional(
CONF_MONITORED_CONDITIONS, default=DEFAULT_MONITORED CONF_MONITORED_CONDITIONS, default=DEFAULT_MONITORED
): vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), ): vol.All(cv.ensure_list, [vol.In(SENSOR_KEYS)]),
vol.Optional( vol.Optional(
CONF_OVERSAMPLING_TEMP, default=DEFAULT_OVERSAMPLING_TEMP CONF_OVERSAMPLING_TEMP, default=DEFAULT_OVERSAMPLING_TEMP
): vol.Coerce(int), ): vol.Coerce(int),

View File

@ -1,6 +1,9 @@
"""Constants for the BME280 component.""" """Constants for the BME280 component."""
from __future__ import annotations
from datetime import timedelta from datetime import timedelta
from homeassistant.components.sensor import SensorEntityDescription
from homeassistant.const import ( from homeassistant.const import (
DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_PRESSURE, DEVICE_CLASS_PRESSURE,
@ -26,11 +29,27 @@ DEFAULT_SCAN_INTERVAL = 300
SENSOR_TEMP = "temperature" SENSOR_TEMP = "temperature"
SENSOR_HUMID = "humidity" SENSOR_HUMID = "humidity"
SENSOR_PRESS = "pressure" SENSOR_PRESS = "pressure"
SENSOR_TYPES = { SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
SENSOR_TEMP: ["Temperature", TEMP_CELSIUS, DEVICE_CLASS_TEMPERATURE], SensorEntityDescription(
SENSOR_HUMID: ["Humidity", PERCENTAGE, DEVICE_CLASS_HUMIDITY], key=SENSOR_TEMP,
SENSOR_PRESS: ["Pressure", "mb", DEVICE_CLASS_PRESSURE], name="Temperature",
} native_unit_of_measurement=TEMP_CELSIUS,
device_class=DEVICE_CLASS_TEMPERATURE,
),
SensorEntityDescription(
key=SENSOR_HUMID,
name="Humidity",
native_unit_of_measurement=PERCENTAGE,
device_class=DEVICE_CLASS_HUMIDITY,
),
SensorEntityDescription(
key=SENSOR_PRESS,
name="Pressure",
native_unit_of_measurement="mb",
device_class=DEVICE_CLASS_PRESSURE,
),
)
SENSOR_KEYS: list[str] = [desc.key for desc in SENSOR_TYPES]
DEFAULT_MONITORED = [SENSOR_TEMP, SENSOR_HUMID, SENSOR_PRESS] DEFAULT_MONITORED = [SENSOR_TEMP, SENSOR_HUMID, SENSOR_PRESS]
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=3) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=3)
# SPI # SPI

View File

@ -6,7 +6,11 @@ from bme280spi import BME280 as BME280_spi # pylint: disable=import-error
from i2csense.bme280 import BME280 as BME280_i2c # pylint: disable=import-error from i2csense.bme280 import BME280 as BME280_i2c # pylint: disable=import-error
import smbus import smbus
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN, SensorEntity from homeassistant.components.sensor import (
DOMAIN as SENSOR_DOMAIN,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_SCAN_INTERVAL from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_SCAN_INTERVAL
from homeassistant.helpers.update_coordinator import ( from homeassistant.helpers.update_coordinator import (
CoordinatorEntity, CoordinatorEntity,
@ -98,38 +102,34 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
update_interval=scan_interval, update_interval=scan_interval,
) )
await coordinator.async_refresh() await coordinator.async_refresh()
entities = [] monitored_conditions = sensor_conf[CONF_MONITORED_CONDITIONS]
for condition in sensor_conf[CONF_MONITORED_CONDITIONS]: entities = [
entities.append( BME280Sensor(name, coordinator, description)
BME280Sensor( for description in SENSOR_TYPES
condition, if description.key in monitored_conditions
name, ]
coordinator,
)
)
async_add_entities(entities, True) async_add_entities(entities, True)
class BME280Sensor(CoordinatorEntity, SensorEntity): class BME280Sensor(CoordinatorEntity, SensorEntity):
"""Implementation of the BME280 sensor.""" """Implementation of the BME280 sensor."""
def __init__(self, sensor_type, name, coordinator): def __init__(self, name, coordinator, description: SensorEntityDescription):
"""Initialize the sensor.""" """Initialize the sensor."""
super().__init__(coordinator) super().__init__(coordinator)
self._attr_name = f"{name} {SENSOR_TYPES[sensor_type][0]}" self.entity_description = description
self.type = sensor_type self._attr_name = f"{name} {description.name}"
self._attr_native_unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self._attr_device_class = SENSOR_TYPES[sensor_type][2]
@property @property
def native_value(self): def native_value(self):
"""Return the state of the sensor.""" """Return the state of the sensor."""
if self.type == SENSOR_TEMP: sensor_type = self.entity_description.key
if sensor_type == SENSOR_TEMP:
temperature = round(self.coordinator.data.temperature, 1) temperature = round(self.coordinator.data.temperature, 1)
state = temperature state = temperature
elif self.type == SENSOR_HUMID: elif sensor_type == SENSOR_HUMID:
state = round(self.coordinator.data.humidity, 1) state = round(self.coordinator.data.humidity, 1)
elif self.type == SENSOR_PRESS: elif sensor_type == SENSOR_PRESS:
state = round(self.coordinator.data.pressure, 1) state = round(self.coordinator.data.pressure, 1)
return state return state