Binary sensor template with sun elevation not working

I’m playing around with some automatic lights and use the following binary sensor template (and an automation) to turn the lights on/off.

- platform: template
  sensors:
    automatisk_lys:
      friendly_name: 'Automatisk lys'
      value_template: >-
        {{ is_state('group.all_devices', 'home')
           and is_state('sun.sun', 'below_horizon') }}

The sensor works nicely, but I would like to turn on the light some time before the sun goes down.
I’m thinking I could use the following instead of sun.sun - below_horizon, but having trouble integrating the following code in my template:

{{ states.sun.sun.attributes.elevation|float < 5 }}

No mather what I do I end up with a binary sensor that have the value “off” so any help would be appreciated.

{{ is_state('group.all_devices', 'home') and states.sun.sun.attributes.elevation|float < 5 }}

doesn’t work?

I think it does :slight_smile:
I was trying with is_state() in from of the code snippet among other things.

It worked like a charm and now I’m trying to make it better :slight_smile:

I have a lux sensor (sensor.outside_main_door_ms_luminance) and trying to incorporate it.
The goal is to make check is someone is home and sun elevation is below 4 or luminance is below 200 outside (for rainy days), but i can’t get it to work.

I’m using this code:

    {{ is_state('group.all_devices', 'home')
       and states.sun.sun.attributes.elevation|float < 4
       or states.sensor.outside_main_door_ms_luminance|float < 200 }}

You’re missing the state at the end of your luminance sensor and you should write the or conditions in brackets.

{{ is_state('group.all_devices', 'home')
       and (states.sun.sun.attributes.elevation|float < 4
       or states.sensor.outside_main_door_ms_luminance.state|float < 200) }}

I’ve been using this code for at while and it works great.
One thing I’ve noticed is that if the “sensor.stue_lys” value is “unavailable” the sensor template value is “on”
Is it possible to ignore this value if the sensor is “unavailable”?
I plan to have a few light sensors indoor and want to make the automation “failsafe”.

- platform: template
  sensors:
    tillad_automatisk_lys:
      friendly_name: 'Tillad automatisk lys'
      value_template: >-
        {{ (states.sun.sun.attributes.elevation|float < 4)
           or (states.sensor.stue_lys.state|float < 40) }}
      icon_template: 'mdi:brightness-auto'

You could use this:

or (states.sensor.stue_lys.state|float(40) < 40) }}

Then if states.sensor.stue_lys.state is None, or ‘unavailable’, or basically anything other than something that can be interpreted as a float, the result of the float filter will be the default value of 40, which when compared to 40 will, of course, not be less, so the result of this expression will be False, effectively “ignoring” sensor.stue_lys.

Works like a charm. Thanks :slight_smile:

1 Like