Need help with sunrise/sunset IF statement

Hi All,

I am fairly new and trying to create an automation that locks my doors when I leave (started by my pushing a button/toggle on lovelace) and then sets the lights depending if its day or night (using 2 different scenes).

Here is what I have created so far, would appreciate any help:

- id: '1573029871264'
  alias: Leave Home
  description: Leave Home
  trigger:
    - platform: sun
      event: sunset
    - platform: sun
      event: sunrise
  condition: []
  action:
      service_template: >-
      {% if trigger.event == 'sunset' %}
        - service: scene.turn_on
          entity_id: scene.all_on
      {% elif trigger.event == 'sunrise' %}
        - service: scene.turn_on
          entity_id: scene.all_off
      {% endif %}
  - device_id: 2fb1d65b43324b2dacf10aa6fbe81268
    domain: lock
    entity_id: lock.front_door_lock
    type: lock
  - device_id: 48342d0bd2b219709b70fd09ca5773da
    domain: lock
    entity_id: lock.garage_door_lock
    type: lock

You can’t use templating that way. YAML processing comes first, then at run time the template is evaluated. Try this:

- id: '1573029871264'
  alias: Leave Home
  description: Leave Home
  trigger:
    - platform: sun
      event: sunset
    - platform: sun
      event: sunrise
  condition: []
  action:
  - service: scene.turn_on
    data_template:
      entity_id: "scene.all_{{ 'on' if trigger.event == 'sunset' else 'off' }}"
  - device_id: 2fb1d65b43324b2dacf10aa6fbe81268
    domain: lock
    entity_id: lock.front_door_lock
    type: lock
  - device_id: 48342d0bd2b219709b70fd09ca5773da
    domain: lock
    entity_id: lock.garage_door_lock
    type: lock

Very interesting, I didn’t even think about appending a string like that. I messed around a bit and still cannot get the scenes to fire. Here is the updated YAML:

- id: '1573069571164'
  alias: Leave Home
  description: Leave Home
  trigger:
  - platform: sun
    event: sunset
  - platform: sun
    event: sunrise
  condition: []
  action:
  - service: scene.turn_on
    data_template:
      entity_id: "scene.{{ 'night_dim' if trigger.event == 'sunset' else 'all_off' }}"
  - device_id: 2fb1d65b43324b2dacf10aa6fbe81268
    domain: lock
    entity_id: lock.front_door_lock
    type: lock
  - device_id: 48342d0bd2b219709b70fd09ca5773da
    domain: lock
    entity_id: lock.garage_door_lock
    type: lock

Any ideas what may be missing? The scenes seem to work fine otherwise.

So you have scenes named scene.night_dim & scene.all_off, correct?

Hmm, wait a second. How are you triggering the automation? Are you triggering it manually? If so, then the trigger variable will not be defined, and hence it won’t work. This automation has to be triggered by the sunrise or sunset event to work properly.

Hey Phil,

So yes, those are the names of the scenes. If I trigger it manually to “test” it, everything works except for the lighting scene… that is problem #1.

The second issue is, as you said, the way in which I plan to trigger it. I had hoped to trigger this with a button on lovelace however, in its current state it looks to auto trigger based on the sun event. Which is obviously, very problematic.

Any thoughts how to turn this thing around?

There’s nothing problematic or wrong with the automation as written. It will work and do what it’s written to do. And like any automation that uses the trigger variable, you can’t test it by using the manual TRIGGER button, because again, the trigger variable doesn’t exist in that scenario.

But if you want it to do something else, then yes, that would definitely be a problem. :wink:

Maybe you need to describe exactly what you want the automation to do. It sounds, however, like maybe you don’t actually want an automation at all, but maybe a script instead.

Hey Phil,

I think you are right… maybe I should be looking down a different road (script vs automation). See it I still have a lot to learn, I did not realize they were different things.

Anyhow: I am trying to have a script that I can enable via a button/toggle/etc on lovelace. This Leave Home button would execute a script that then locks my door, arms my alarm, and adjust the lighting scene depending whether or not it is dark outside.

This was my latest YAML before I knew automation was not the way to go:

- id: '1573069561164'
  alias: Leave Home
  description: Leave Home
  trigger:
  - platform: sun
    event: sunset
  - platform: sun
    event: sunrise
  condition: []
  action:
  - service: scene.turn_on
    data_template:
      entity_id: "scene.{{ 'night_dim' if trigger.event == 'sunset' else 'all_off' }}"
  - device_id: 2fb1d64b43324b2dacf10aa6fbe81268
    domain: lock
    entity_id: lock.front_door_lock
    type: lock
  - device_id: 48342d0bd2b229709b70fd09ca5773da
    domain: lock
    entity_id: lock.garage_door_lock
    type: lock
    - timeout: '60'
    wait_template: ''
  - service: alarm_control_panel.alarm_arm_away

So this would lock 2 doors, then pause for 60 seconds and finally arm my alarm away. Then the lights would set to “night_dim” if it’s equal to or greater than sunset or “all_off” if its equal to or greater than sunrise.

That is the goal.

FYI, a script is just a sequence of steps that you can run via a service call (which you can do, e.g., from a UI “button”), whereas an automation is a sequence of steps together with a trigger, and optionally a condition, that automatically decides when to run the sequence (aka action.)

This might be what you’re looking for:

script:
  leave_home:
    alias: Leave Home
    sequence:
    - service_template: >
        {% if is_state('sun.sun', 'below_horizon') %}
          scene.night_dim
        {% else %}
          scene.all_off
        {% endif %}
    - device_id: 2fb1d64b43324b2dacf10aa6fbe81268
      domain: lock
      entity_id: lock.front_door_lock
      type: lock
    - device_id: 48342d0bd2b229709b70fd09ca5773da
      domain: lock
      entity_id: lock.garage_door_lock
      type: lock
    - delay:
        minutes: 1
    - service: alarm_control_panel.alarm_arm_away

This seems to be throwing the following error:

Error executing service <ServiceCall script.leave_home (c:727211df4e6246ddb03ce50fee41b2fe)>
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/core.py", line 1244, in _safe_execute
    await self._execute_service(handler, service_call)
  File "/usr/src/homeassistant/homeassistant/core.py", line 1261, in _execute_service
    await handler.func(service_call)
  File "/usr/src/homeassistant/homeassistant/components/script/__init__.py", line 142, in service_handler
    await script.async_turn_on(variables=service.data, context=service.context)
  File "/usr/src/homeassistant/homeassistant/components/script/__init__.py", line 214, in async_turn_on
    raise err
  File "/usr/src/homeassistant/homeassistant/components/script/__init__.py", line 209, in async_turn_on
    await self.script.async_run(kwargs.get(ATTR_VARIABLES), context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 190, in async_run
    await self._handle_action(action, variables, context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 274, in _handle_action
    await self._actions[_determine_action(action)](action, variables, context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 357, in _async_call_service
    context=context,
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 97, in async_call_from_config
    domain, service_name, service_data, blocking=blocking, context=context
  File "/usr/src/homeassistant/homeassistant/core.py", line 1211, in async_call
    raise ServiceNotFound(domain, service) from None
homeassistant.exceptions.ServiceNotFound: Unable to find service scene/night_dim

I think this is because the scenes generally need to be called like this:

- service: scene.turn_on
  entity_id: scene.night_dim

However, unsure how to properly integrate this syntax into your provided script.

Oops, sorry, my bad. A scene apparently can be called like this:

- scene: scene.blah

But I tried to use that in a service_template, which, of course, is wrong. Try this:

script:
  leave_home:
    alias: Leave Home
    sequence:
    - service: scene.turn_on
      data_template:
        entity_id: >
          {% if is_state('sun.sun', 'below_horizon') %}
            scene.night_dim
          {% else %}
            scene.all_off
          {% endif %}
    - device_id: 2fb1d64b43324b2dacf10aa6fbe81268
      domain: lock
      entity_id: lock.front_door_lock
      type: lock
    - device_id: 48342d0bd2b229709b70fd09ca5773da
      domain: lock
      entity_id: lock.garage_door_lock
      type: lock
    - delay:
        minutes: 1
    - service: alarm_control_panel.alarm_arm_away

This did the trick! Thanks a lot for your help, much appreciated.

1 Like