Template sensor with delayed state change

Hello,

I have the following template sensor which tells me where my main power source is based on inverter data. I would like to run various automations based in this, but there is too much “noise” at the transition times where values often oscillate between the “old” and “new” sources.

{% if states('sensor.pv_power')|float > states('sensor.grid_power')|float
     and states('sensor.pv_power')|float > -(states('sensor.battery_power')|float) %}
      Solar
{% elif -(states('sensor.battery_power')|float) > states('sensor.grid_power')|float
      and -(states('sensor.battery_power')|float) > states('sensor.pv_power')|float %}
      Battery
{% else %}
      Grid
{% endif %}

I know that I can put a “for” delay in my automations, but there are several and maintaining them while I fine-tune what an acceptable delay should be seems tedious.

I am hoping that, like the binary sensor which has “delay_on” and “delay_off” directives, that there might be a “delay_change” directive for a template sensor. Of course there isn’t, but is there another way to include that delay?

The other thought I’ve had is to create three binary sensors with the necessary delays set there and have my automations use those. However, some are based on transition from one to the other (e.g. solar to battery, battery to grid) and binary sensors with delays don’t always seem to switch evenly to the point where I can use the transition from one state to the next reliably.

You could switch to trigger-based template sensor and use durations there instead of the automations.

template:
  - trigger:
    - platform: template
      id: Solar
      value_template: |
        {% set pv = states('sensor.pv_power')|float) %}
        {{ pv > states('sensor.grid_power')|float and
        pv > (-1 * states('sensor.battery_power')|float) }}
      for: "00:02:00"
    - platform: template
      id:  Battery
      value_template: |
        {% set neg_batt = -1 * states('sensor.battery_power')|float %}
        {{ neg_batt > states('sensor.grid_power')|float and 
        neg_batt > states('sensor.pv_power')|float %}
      for: "00:02:00"
    - platform: template
      id: Grid
      value_template: |
        {% set grid = states('sensor.grid_power')|float %}
        {{ grid > -1 * states('sensor.battery_power')|float or 
        grid > states('sensor.pv_power')|float }}
      for: "00:02:00"
    sensor:
      - name: Main Power Source
        state: "{{ trigger.id }}"
        availability: |
          {{ has_value('sensor.battery_power') and has_value('sensor.grid_power') 
          and has_value('sensor.pv_power') }}
1 Like