1 """Support for esphome sensors."""
3 from __future__
import annotations
5 from datetime
import date, datetime
8 from aioesphomeapi
import (
12 SensorStateClass
as EsphomeSensorStateClass,
16 from aioesphomeapi.model
import LastResetType
29 from .entity
import EsphomeEntity, platform_async_setup_entry
30 from .enum_mapper
import EsphomeEnumMapper
34 hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
36 """Set up esphome sensors based on a config entry."""
42 entity_type=EsphomeSensor,
43 state_type=SensorState,
49 info_type=TextSensorInfo,
50 entity_type=EsphomeTextSensor,
51 state_type=TextSensorState,
55 _STATE_CLASSES: EsphomeEnumMapper[EsphomeSensorStateClass, SensorStateClass |
None] = (
58 EsphomeSensorStateClass.NONE:
None,
59 EsphomeSensorStateClass.MEASUREMENT: SensorStateClass.MEASUREMENT,
60 EsphomeSensorStateClass.TOTAL_INCREASING: SensorStateClass.TOTAL_INCREASING,
61 EsphomeSensorStateClass.TOTAL: SensorStateClass.TOTAL,
68 """A sensor implementation for esphome."""
72 """Set attrs from static info."""
78 if unit_of_measurement := static_info.unit_of_measurement:
81 SensorDeviceClass, static_info.device_class
83 if not (state_class := static_info.state_class):
86 state_class == EsphomeSensorStateClass.MEASUREMENT
87 and static_info.last_reset_type == LastResetType.AUTO
93 self.
_attr_state_class_attr_state_class = _STATE_CLASSES.from_esphome(state_class)
97 """Return the state of the entity."""
98 if not self.
_has_state_has_state
or (state := self.
_state_state).missing_state:
100 state_float = state.state
101 if not math.isfinite(state_float):
104 return dt_util.utc_from_timestamp(state_float)
105 return f
"{state_float:.{self._static_info.accuracy_decimals}f}"
109 """A text sensor implementation for ESPHome."""
113 """Set attrs from static info."""
117 SensorDeviceClass, static_info.device_class
122 """Return the state of the entity."""
123 if not self.
_has_state_has_state
or (state := self.
_state_state).missing_state:
125 state_str = state.state
127 if device_class
is SensorDeviceClass.TIMESTAMP:
128 return dt_util.parse_datetime(state_str)
130 device_class
is SensorDeviceClass.DATE
131 and (value := dt_util.parse_datetime(state_str))
is not None
datetime|str|None native_value(self)
_attr_native_unit_of_measurement
None _on_static_info_update(self, EntityInfo static_info)
str|datetime|date|None native_value(self)
None _on_static_info_update(self, EntityInfo static_info)
SensorDeviceClass|None device_class(self)
str|None device_class(self)
None platform_async_setup_entry(HomeAssistant hass, ESPHomeConfigEntry entry, AddEntitiesCallback async_add_entities, *type[_InfoT] info_type, type[_EntityT] entity_type, type[_StateT] state_type)
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)