Template, time_pattern with condition fails


I’m creating a binary sensor that should be On during the most cost effective hours during the night (9pm-5am). This will be used in an automation that charges my electric bike during the cheapest hours at night.

I’m using the Nordpool integration as source; using the state attribute today to pick up the hourly rate between 9pm and midnight, and the state attribute tomorrow for the hourly rate between midnight and 5am.

The tomorrow attribute updates by the Nordpool integation around 1-2pm daily, and clears it sometime after midnight.

The following code works and updates the binary sensor at 8.40pm. And, it makes use of a Dropdown helper called input_select.nattladdning to set how many hours it should be charging (2,4 or 6).

  - trigger: 
      - platform: time_pattern
        hours: 20
        minutes: 40
      - name: "Nightly charge"
        state: >
          {% set hours_on = int(states('input_select.nattladdning')) %}
          {% set price_now = float(states('sensor.nordpool_kwh_se4_sek_3_095_0')) %}
          {% set nighprice = state_attr('sensor.nordpool_kwh_se4_sek_3_095_0', 'today')[21:]+ 
             state_attr('sensor.nordpool_kwh_se4_sek_3_095_0', 'tomorrow')[:5] %}
          {% set average_on = average((nighprice | sort())[int(hours_on-1)], 
                                      (nighprice | sort())[int(hours_on)]) | round(3) %}
          {% if price_now < average_on %}
          {% else %}
          {% endif %}

However; I would like to ensure this template survives a restart, and therefore I’d like to have it updated every 5th minute between 2pm and 11.45pm. It cannot update itself after midnight and before the ‘tomorrow’ prices has arrived.

The following code throws an error:

  - trigger: 
      - platform: time_pattern
        minutes: '/5'
      - condition: time
        after: '14:59:00'
        before: '23:59:00'

Logger: homeassistant.config
Source: config.py:929
First occurred: 08:02:43 (1 occurrences)
Last logged: 08:02:43

Invalid config for [template]: [condition] is an invalid option for [template]. Check: template->condition. (See /config/configuration.yaml, line 103).

Suggestions welcome…


You can’t use a condition in a Trigger-based Template Sensor.

The state value and attributes of a Trigger-based Template Sensor are restored after a restart.

The only way a restart affects your sensor is if it occurs at the time when it’s scheduled to trigger (20:40) thereby causing it to miss the trigger time.

If you want the Trigger-based Template Sensor to trigger at a specific time like 20:40 then it’s more common to use a Time Trigger rather than a Time Pattern Trigger.

  - trigger: 
      - platform: time
        at: '20:40:00'
1 Like