Help needed with if elseif else statement formatting

Hello,

Here’s the thing; I’d like to set light brightness based on time in an automation.

## Motion sensor wc
- alias: WC Lights off when motion off
  trigger:
    - platform: state
      entity_id: binary_sensor.wc_pir
      to: 'off'
      for:
        minutes: 8
  action:
    - service: light.turn_on
      data:
        entity_id: light.wc_ylavalo
        brightness: 0
- alias: WC Lights on when motion on
  trigger:
    - platform: state
      entity_id: binary_sensor.wc_pir
      to: 'on'
  condition:
    condition: and
    conditions:
      - condition: template
        value_template: '{{ states.light.wc_ylavalo.attributes.brightness < 5 }}'
      - condition: numeric_state
        entity_id: sensor.wc_ldr
        below: 100
  action:
    - service: light.turn_on
      data:
        entity_id: light.wc_ylavalo
        brightness: >-
          {% if now().strftime('%H')| int >= 22 %}
            100
          {% elif now().strftime('%H')| int < 7 %}
            10
          {% elif now().strftime('%H')| int >= 7 %}
            255
          {% endif %}

I get the following error when triggering the automation above:
Invalid service data for light.turn_on: expected int for dictionary value @ data['brightness']. Got "{% if now().strftime('%H')| int >= 22 %}\n 100\n{% elif now().strftime('%H')| int < 7 %}\n 10\n{% elif now().strftime('%H')| int >= 7 %}\n 255\n{% endif %}"

The automation works fine without the if-elif-else block.

Any help is appreciated!

Br,
Mikko

Not sure, but i think you need data_template.

Thanks for your reply!

I’m not sure what you mean; data_template for what? Could you give me an example code?

Looking at the error message I think the interpreter does not recognise the if-else block at all and reads that as a string not as a peace of code…

Br,
Mikko

Sorry, sometimes i expect too much.

  action:
    - service: light.turn_on
      data_template:
        entity_id: light.wc_ylavalo
        brightness: >-
          {% if now().strftime('%H')| int >= 22 %}
            100
          {% elif now().strftime('%H')| int < 7 %}
            10
          {% elif now().strftime('%H')| int >= 7 %}
            255
          {% endif %}

With data the interpreter read every character ‘as is’, with data_template it renders the jinja in the template.
I think :grinning:

2 Likes

Thanks a lot! That did the trick! :slight_smile:

I’m not really ninja enough to master the jinja yet, it seems :smiley:

Seriously speaking, any pointers for a good cookbook to get on top of this stuff?

Br,
Mikko

2 Likes

Well like i said in my first reply, “Not sure”.
Sometimes it’s most trial and error and as time goes on, you get the ‘feeling’.

1 Like