I have a template sensor that calculates the number of days until my next garbage day. I didn’t notice it had started failing until today because today is the day I put out organics. I’m pretty sure it was not failing during the 0.114 versions.
Anyway, here is the YAML for the failing sensor:
sensor:
- platform: template
sensors:
garbage_collection_countdown:
friendly_name_template: Days until next collection
unit_of_measurement: "days"
value_template: >
{%- set oneDayInSeconds = 60 * 60 * 24 -%}
{%- set currentTimestamp = as_timestamp(states('sensor.date_time')) -%}
{%- set garbage = state_attr('calendar.garbage_collection', 'start_time') -%}
{%- set organics = state_attr('calendar.organics_collection', 'start_time') -%}
{%- set next = as_timestamp([garbage, organics] | min) -%}
{{ (((next - currentTimestamp) / oneDayInSeconds) + 1) | int }}
This template worked perfectly in the template dev tool, but when loaded as a sensor, it yields this error in the logs:
2020-09-29 09:40:57 ERROR (MainThread) [homeassistant.helpers.entity] Update for sensor.garbage_collection_countdown fails
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 278, in async_update_ha_state
await self.async_device_update()
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 469, in async_device_update
await self.async_update() # type: ignore
File "/usr/src/homeassistant/homeassistant/components/template/template_entity.py", line 299, in async_update
self._async_update()
TypeError: 'NoneType' object is not callable
After much playing around and refactoring and reloading to try and figure out what was giving me the error, I found that this works:
{%- set next = as_timestamp([garbage, organics] | min) -%}
{%- set delta = next | float - currentTimestamp | float -%}
{%- set days = delta / oneDayInSeconds -%}
{{ (days + 1) | int }}
The real effective difference here is that I have converted my timestamp
values to float
before the arithmetic. I don’t know why this seems to be necessary now. Can anyone shed some light on this mystery?