Using the sun

I got my first Zigbee motion sensor to turn on a light switch and it works fine except for when I add a condition to qualify the action with it being between sunset and sunrise as a proxy for being dark.

What have I got wrong in the “condition: sun” portion in the code below?

- id: '1636250203748'
  alias: Turn study lights on when motion is detected and it is dark
  description: ''
  trigger:
  - type: motion
    platform: device
    device_id: cc71456d3dd69dd86e60dc67ba8351d7
    entity_id: binary_sensor.ikea_motion_sensor_1_occupancy
    domain: binary_sensor
  condition:
  - condition: sun
    before: sunrise
    after: sunset
  action:
  - type: turn_on
    device_id: 60704822069c11eb91f509337561fe4a
    entity_id: switch.treatlife4_toggle2
    domain: switch
  mode: single

And if you want to wait until after dusk - you can use the elevation of the sun:

condition:
  condition: numeric_state
  entity_id: sun.sun
  value_template: '{{ state.attributes.elevation }}'
  below: -1.0

Using -1 as the angle below horizon - or some other angle that represents after dusk.

I tried the 2nd solution and it worked. I’m still mystified why mine did not work since it was created from the GUI.

Thanks

Once I got the basic automation working, I was going to try and implement an offset of some sort so thanks in advance for your coding suggestion.

Conditions are “and” by default so unless you put the “or” statement then both conditions have to be true to pass.

So when you factor home assistant works from midnight to midnight then your original condition is basically saying the time has to be between sunset and midnight AND midnight and sunrise and obviously any given time can’t be both.

That’s why adding “or” will work but as suggested by others, using “below_horizon” is basically exactly the same statement but easier to understand.

The GUI doesn’t stop you creating things that won’t work, it just ensures you create valid YAML.

Your condition is a commonly made mistake, one that’s even mentioned in the docs. It can’t be both before sunrise and after sunset.

Without the notion described by @rossk of midnight as the datum, I thought before sunrise AND after sunset meant when the sun was below the horizon. And it even explains @123’s first example which had me scratching my head.

And great point, @Tinkerer, about being syntactically correct but not meeting logical intent

Thanks everyone.