Can anyone help me understand what’s going wrong with my template sensor please?
I’m monitoring my local tides and trying to record when the most recent spring or neaps happened. In principle this isn’t hard, I just compute the tidal range and keep yesterday’s, today’s and tomorrow’s in sensors. When I see an increasing range become a decreasing range it is a Spring and I record the date in an attribute. The reverse for a Neap. If it is continually rising or falling I try to retain the old Spring/Neap status and date. This isn’t working and at various times the “when” status gets reset and I don’t understand why. It all works in the template testing window. This is what I’ve got:
- name: tide_range_trend
unique_id: tide_range_trend
state: >
{% if states('sensor.tide_range_today')|float(0)>states('sensor.tide_range_yesterday')|float(0) %}
{% set st="+" %}
{% elif states('sensor.tide_range_today')|float(0)<states('sensor.tide_range_yesterday')|float(0) %}
{% set st="-" %}
{% else %}
{% set st=" " %}
{% endif %}
{% if states('sensor.tide_range_today')|float(0)>states('sensor.tide_range_tom')|float(0) %}
{% set nd="-" %}
{% elif states('sensor.tide_range_today')|float(0)<states('sensor.tide_range_tom')|float(0) %}
{% set nd="+" %}
{% else %}
{% set nd=" " %}
{% endif %}
{{st~nd}}
attributes:
when: >
{% set last = state_attr('sensor.tide_range_trend','when') %}
{% if states('sensor.tide_range_trend') == "+-" or states('sensor.tide_range_trend') == "-+" %}
{{states('sensor.tide_next')}} ## this is the date_time of the middle tide
{% else %}
{{last }}
{% endif %}
event: >
{% set last = state_attr('sensor.tide_range_trend','event') %}
{% if states('sensor.tide_range_trend') == "+-" %}
Springs
{% elif states('sensor.tide_range_trend') == "-+" %}
Neaps
{% else %}
{{last }}
{% endif %}