Skip to content
Snippets Groups Projects
Unverified Commit 9afabc17 authored by epenet's avatar epenet Committed by GitHub
Browse files

Use attr in mqtt sensor (#81402)

parent d385a85c
No related branches found
No related tags found
No related merge requests found
"""Support for MQTT sensors.""" """Support for MQTT sensors."""
from __future__ import annotations from __future__ import annotations
from datetime import datetime, timedelta from datetime import timedelta
import functools import functools
import logging import logging
...@@ -30,7 +30,7 @@ from homeassistant.core import HomeAssistant, callback ...@@ -30,7 +30,7 @@ from homeassistant.core import HomeAssistant, callback
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.helpers.event import async_track_point_in_utc_time
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, StateType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from . import subscription from . import subscription
...@@ -171,7 +171,6 @@ class MqttSensor(MqttEntity, RestoreSensor): ...@@ -171,7 +171,6 @@ class MqttSensor(MqttEntity, RestoreSensor):
def __init__(self, hass, config, config_entry, discovery_data): def __init__(self, hass, config, config_entry, discovery_data):
"""Initialize the sensor.""" """Initialize the sensor."""
self._state = None
self._expiration_trigger = None self._expiration_trigger = None
expire_after = config.get(CONF_EXPIRE_AFTER) expire_after = config.get(CONF_EXPIRE_AFTER)
...@@ -201,7 +200,7 @@ class MqttSensor(MqttEntity, RestoreSensor): ...@@ -201,7 +200,7 @@ class MqttSensor(MqttEntity, RestoreSensor):
_LOGGER.debug("Skip state recovery after reload for %s", self.entity_id) _LOGGER.debug("Skip state recovery after reload for %s", self.entity_id)
return return
self._expired = False self._expired = False
self._state = last_sensor_data.native_value self._attr_native_value = last_sensor_data.native_value
self._expiration_trigger = async_track_point_in_utc_time( self._expiration_trigger = async_track_point_in_utc_time(
self.hass, self._value_is_expired, expiration_at self.hass, self._value_is_expired, expiration_at
...@@ -227,9 +226,13 @@ class MqttSensor(MqttEntity, RestoreSensor): ...@@ -227,9 +226,13 @@ class MqttSensor(MqttEntity, RestoreSensor):
"""Return the config schema.""" """Return the config schema."""
return DISCOVERY_SCHEMA return DISCOVERY_SCHEMA
def _setup_from_config(self, config): def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity.""" """(Re)Setup the entity."""
self._attr_device_class = config.get(CONF_DEVICE_CLASS)
self._attr_force_update = config[CONF_FORCE_UPDATE] self._attr_force_update = config[CONF_FORCE_UPDATE]
self._attr_native_unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT)
self._attr_state_class = config.get(CONF_STATE_CLASS)
self._template = MqttValueTemplate( self._template = MqttValueTemplate(
self._config.get(CONF_VALUE_TEMPLATE), entity=self self._config.get(CONF_VALUE_TEMPLATE), entity=self
).async_render_with_possible_json_value ).async_render_with_possible_json_value
...@@ -259,7 +262,7 @@ class MqttSensor(MqttEntity, RestoreSensor): ...@@ -259,7 +262,7 @@ class MqttSensor(MqttEntity, RestoreSensor):
self.hass, self._value_is_expired, expiration_at self.hass, self._value_is_expired, expiration_at
) )
payload = self._template(msg.payload, default=self._state) payload = self._template(msg.payload, default=self.native_value)
if payload is not None and self.device_class in ( if payload is not None and self.device_class in (
SensorDeviceClass.DATE, SensorDeviceClass.DATE,
...@@ -272,7 +275,7 @@ class MqttSensor(MqttEntity, RestoreSensor): ...@@ -272,7 +275,7 @@ class MqttSensor(MqttEntity, RestoreSensor):
elif self.device_class == SensorDeviceClass.DATE: elif self.device_class == SensorDeviceClass.DATE:
payload = payload.date() payload = payload.date()
self._state = payload self._attr_native_value = payload
def _update_last_reset(msg): def _update_last_reset(msg):
payload = self._last_reset_template(msg.payload) payload = self._last_reset_template(msg.payload)
...@@ -342,26 +345,6 @@ class MqttSensor(MqttEntity, RestoreSensor): ...@@ -342,26 +345,6 @@ class MqttSensor(MqttEntity, RestoreSensor):
self._expired = True self._expired = True
self.async_write_ha_state() self.async_write_ha_state()
@property
def native_unit_of_measurement(self) -> str | None:
"""Return the unit this state is expressed in."""
return self._config.get(CONF_UNIT_OF_MEASUREMENT)
@property
def native_value(self) -> StateType | datetime:
"""Return the state of the entity."""
return self._state
@property
def device_class(self) -> str | None:
"""Return the device class of the sensor."""
return self._config.get(CONF_DEVICE_CLASS)
@property
def state_class(self) -> str | None:
"""Return the state class of the sensor."""
return self._config.get(CONF_STATE_CLASS)
@property @property
def available(self) -> bool: def available(self) -> bool:
"""Return true if the device is available and value has not expired.""" """Return true if the device is available and value has not expired."""
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment