Fix date/datetime support for templates (#61088)
Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
This commit is contained in:
parent
5b8f8772d2
commit
1ed490ce62
2 changed files with 229 additions and 2 deletions
|
@ -1,6 +1,8 @@
|
||||||
"""Allows the creation of a sensor that breaks out state_attributes."""
|
"""Allows the creation of a sensor that breaks out state_attributes."""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, datetime
|
||||||
|
import logging
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
|
@ -12,6 +14,7 @@ from homeassistant.components.sensor import (
|
||||||
ENTITY_ID_FORMAT,
|
ENTITY_ID_FORMAT,
|
||||||
PLATFORM_SCHEMA,
|
PLATFORM_SCHEMA,
|
||||||
STATE_CLASSES_SCHEMA,
|
STATE_CLASSES_SCHEMA,
|
||||||
|
SensorDeviceClass,
|
||||||
SensorEntity,
|
SensorEntity,
|
||||||
)
|
)
|
||||||
from homeassistant.const import (
|
from homeassistant.const import (
|
||||||
|
@ -32,6 +35,7 @@ from homeassistant.core import HomeAssistant, callback
|
||||||
from homeassistant.exceptions import TemplateError
|
from homeassistant.exceptions import TemplateError
|
||||||
from homeassistant.helpers import config_validation as cv, template
|
from homeassistant.helpers import config_validation as cv, template
|
||||||
from homeassistant.helpers.entity import async_generate_entity_id
|
from homeassistant.helpers.entity import async_generate_entity_id
|
||||||
|
from homeassistant.util import dt as dt_util
|
||||||
|
|
||||||
from .const import (
|
from .const import (
|
||||||
CONF_ATTRIBUTE_TEMPLATES,
|
CONF_ATTRIBUTE_TEMPLATES,
|
||||||
|
@ -85,6 +89,7 @@ LEGACY_SENSOR_SCHEMA = vol.All(
|
||||||
}
|
}
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def extra_validation_checks(val):
|
def extra_validation_checks(val):
|
||||||
|
@ -179,6 +184,32 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _async_parse_date_datetime(
|
||||||
|
value: str, entity_id: str, device_class: SensorDeviceClass | str | None
|
||||||
|
) -> datetime | date | None:
|
||||||
|
"""Parse datetime."""
|
||||||
|
if device_class == SensorDeviceClass.TIMESTAMP:
|
||||||
|
if (parsed_timestamp := dt_util.parse_datetime(value)) is None:
|
||||||
|
_LOGGER.warning("%s rendered invalid timestamp: %s", entity_id, value)
|
||||||
|
return None
|
||||||
|
|
||||||
|
if parsed_timestamp.tzinfo is None:
|
||||||
|
_LOGGER.warning(
|
||||||
|
"%s rendered timestamp without timezone: %s", entity_id, value
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
return parsed_timestamp
|
||||||
|
|
||||||
|
# Date device class
|
||||||
|
if (parsed_date := dt_util.parse_date(value)) is not None:
|
||||||
|
return parsed_date
|
||||||
|
|
||||||
|
_LOGGER.warning("%s rendered invalid date %s", entity_id, value)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
class SensorTemplate(TemplateEntity, SensorEntity):
|
class SensorTemplate(TemplateEntity, SensorEntity):
|
||||||
"""Representation of a Template Sensor."""
|
"""Representation of a Template Sensor."""
|
||||||
|
|
||||||
|
@ -227,7 +258,20 @@ class SensorTemplate(TemplateEntity, SensorEntity):
|
||||||
@callback
|
@callback
|
||||||
def _update_state(self, result):
|
def _update_state(self, result):
|
||||||
super()._update_state(result)
|
super()._update_state(result)
|
||||||
self._attr_native_value = None if isinstance(result, TemplateError) else result
|
if isinstance(result, TemplateError):
|
||||||
|
self._attr_native_value = None
|
||||||
|
return
|
||||||
|
|
||||||
|
if result is None or self.device_class not in (
|
||||||
|
SensorDeviceClass.DATE,
|
||||||
|
SensorDeviceClass.TIMESTAMP,
|
||||||
|
):
|
||||||
|
self._attr_native_value = result
|
||||||
|
return
|
||||||
|
|
||||||
|
self._attr_native_value = _async_parse_date_datetime(
|
||||||
|
result, self.entity_id, self.device_class
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class TriggerSensorEntity(TriggerEntity, SensorEntity):
|
class TriggerSensorEntity(TriggerEntity, SensorEntity):
|
||||||
|
@ -237,7 +281,7 @@ class TriggerSensorEntity(TriggerEntity, SensorEntity):
|
||||||
extra_template_keys = (CONF_STATE,)
|
extra_template_keys = (CONF_STATE,)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def native_value(self) -> str | None:
|
def native_value(self) -> str | datetime | date | None:
|
||||||
"""Return state of the sensor."""
|
"""Return state of the sensor."""
|
||||||
return self._rendered.get(CONF_STATE)
|
return self._rendered.get(CONF_STATE)
|
||||||
|
|
||||||
|
@ -245,3 +289,20 @@ class TriggerSensorEntity(TriggerEntity, SensorEntity):
|
||||||
def state_class(self) -> str | None:
|
def state_class(self) -> str | None:
|
||||||
"""Sensor state class."""
|
"""Sensor state class."""
|
||||||
return self._config.get(CONF_STATE_CLASS)
|
return self._config.get(CONF_STATE_CLASS)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _process_data(self) -> None:
|
||||||
|
"""Process new data."""
|
||||||
|
super()._process_data()
|
||||||
|
|
||||||
|
if (
|
||||||
|
state := self._rendered.get(CONF_STATE)
|
||||||
|
) is None or self.device_class not in (
|
||||||
|
SensorDeviceClass.DATE,
|
||||||
|
SensorDeviceClass.TIMESTAMP,
|
||||||
|
):
|
||||||
|
return
|
||||||
|
|
||||||
|
self._rendered[CONF_STATE] = _async_parse_date_datetime(
|
||||||
|
state, self.entity_id, self.device_class
|
||||||
|
)
|
||||||
|
|
|
@ -1094,3 +1094,169 @@ async def test_trigger_entity_available(hass):
|
||||||
|
|
||||||
state = hass.states.get("sensor.maybe_available")
|
state = hass.states.get("sensor.maybe_available")
|
||||||
assert state.state == "unavailable"
|
assert state.state == "unavailable"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_trigger_entity_device_class_parsing_works(hass):
|
||||||
|
"""Test trigger entity device class parsing works."""
|
||||||
|
assert await async_setup_component(
|
||||||
|
hass,
|
||||||
|
"template",
|
||||||
|
{
|
||||||
|
"template": [
|
||||||
|
{
|
||||||
|
"trigger": {"platform": "event", "event_type": "test_event"},
|
||||||
|
"sensor": [
|
||||||
|
{
|
||||||
|
"name": "Date entity",
|
||||||
|
"state": "{{ now().date() }}",
|
||||||
|
"device_class": "date",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Timestamp entity",
|
||||||
|
"state": "{{ now() }}",
|
||||||
|
"device_class": "timestamp",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
await hass.async_block_till_done()
|
||||||
|
|
||||||
|
now = dt_util.now()
|
||||||
|
|
||||||
|
with patch("homeassistant.util.dt.now", return_value=now):
|
||||||
|
hass.bus.async_fire("test_event")
|
||||||
|
await hass.async_block_till_done()
|
||||||
|
|
||||||
|
date_state = hass.states.get("sensor.date_entity")
|
||||||
|
assert date_state is not None
|
||||||
|
assert date_state.state == now.date().isoformat()
|
||||||
|
|
||||||
|
ts_state = hass.states.get("sensor.timestamp_entity")
|
||||||
|
assert ts_state is not None
|
||||||
|
assert ts_state.state == now.isoformat(timespec="seconds")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_trigger_entity_device_class_errors_works(hass):
|
||||||
|
"""Test trigger entity device class errors works."""
|
||||||
|
assert await async_setup_component(
|
||||||
|
hass,
|
||||||
|
"template",
|
||||||
|
{
|
||||||
|
"template": [
|
||||||
|
{
|
||||||
|
"trigger": {"platform": "event", "event_type": "test_event"},
|
||||||
|
"sensor": [
|
||||||
|
{
|
||||||
|
"name": "Date entity",
|
||||||
|
"state": "invalid",
|
||||||
|
"device_class": "date",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Timestamp entity",
|
||||||
|
"state": "invalid",
|
||||||
|
"device_class": "timestamp",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
await hass.async_block_till_done()
|
||||||
|
|
||||||
|
now = dt_util.now()
|
||||||
|
|
||||||
|
with patch("homeassistant.util.dt.now", return_value=now):
|
||||||
|
hass.bus.async_fire("test_event")
|
||||||
|
await hass.async_block_till_done()
|
||||||
|
|
||||||
|
date_state = hass.states.get("sensor.date_entity")
|
||||||
|
assert date_state is not None
|
||||||
|
assert date_state.state == STATE_UNKNOWN
|
||||||
|
|
||||||
|
ts_state = hass.states.get("sensor.timestamp_entity")
|
||||||
|
assert ts_state is not None
|
||||||
|
assert ts_state.state == STATE_UNKNOWN
|
||||||
|
|
||||||
|
|
||||||
|
async def test_entity_device_class_parsing_works(hass):
|
||||||
|
"""Test entity device class parsing works."""
|
||||||
|
now = dt_util.now()
|
||||||
|
|
||||||
|
with patch("homeassistant.util.dt.now", return_value=now):
|
||||||
|
assert await async_setup_component(
|
||||||
|
hass,
|
||||||
|
"template",
|
||||||
|
{
|
||||||
|
"template": [
|
||||||
|
{
|
||||||
|
"sensor": [
|
||||||
|
{
|
||||||
|
"name": "Date entity",
|
||||||
|
"state": "{{ now().date() }}",
|
||||||
|
"device_class": "date",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Timestamp entity",
|
||||||
|
"state": "{{ now() }}",
|
||||||
|
"device_class": "timestamp",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
await hass.async_block_till_done()
|
||||||
|
|
||||||
|
date_state = hass.states.get("sensor.date_entity")
|
||||||
|
assert date_state is not None
|
||||||
|
assert date_state.state == now.date().isoformat()
|
||||||
|
|
||||||
|
ts_state = hass.states.get("sensor.timestamp_entity")
|
||||||
|
assert ts_state is not None
|
||||||
|
assert ts_state.state == now.isoformat(timespec="seconds")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_entity_device_class_errors_works(hass):
|
||||||
|
"""Test entity device class errors works."""
|
||||||
|
assert await async_setup_component(
|
||||||
|
hass,
|
||||||
|
"template",
|
||||||
|
{
|
||||||
|
"template": [
|
||||||
|
{
|
||||||
|
"sensor": [
|
||||||
|
{
|
||||||
|
"name": "Date entity",
|
||||||
|
"state": "invalid",
|
||||||
|
"device_class": "date",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Timestamp entity",
|
||||||
|
"state": "invalid",
|
||||||
|
"device_class": "timestamp",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
await hass.async_block_till_done()
|
||||||
|
|
||||||
|
now = dt_util.now()
|
||||||
|
|
||||||
|
with patch("homeassistant.util.dt.now", return_value=now):
|
||||||
|
hass.bus.async_fire("test_event")
|
||||||
|
await hass.async_block_till_done()
|
||||||
|
|
||||||
|
date_state = hass.states.get("sensor.date_entity")
|
||||||
|
assert date_state is not None
|
||||||
|
assert date_state.state == STATE_UNKNOWN
|
||||||
|
|
||||||
|
ts_state = hass.states.get("sensor.timestamp_entity")
|
||||||
|
assert ts_state is not None
|
||||||
|
assert ts_state.state == STATE_UNKNOWN
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue