Switching a light on, based on how much daylight today has

Hi,

I would want to do the following:
I have a switch that turns a light on or off. Now I want to have it that this light is always on for as much time as it takes so that the room its in always gets 12 hours of “daylight” during that day.
Meaning I somehow need to combine the amount of actual daylight and turn on the light in addition to that in the mornings.

In pseudo code:

if daylight_time < 12h:
  time to turn on the lights = time of dawn - 12h
  time to turn them off again  = starting time of daylight

And then have an automation that just uses those times to flip the switch.

This is for a chicken coop in the wintertime and will turn on/off a special light that simulates sunlight.

I’ve already found: GitHub - pnbruckner/ha-sun2: Home Assistant Sun2 Sensor which already should give me all the information I need. But I can’t figure out how to “stitch” all of this together in the right places.

I’m pretty sure that this is possible, but I’m a bit lost on what would be the best way to achieve it.

Do you want it balanced so it’s on in the morning and evening or just the morning?

trigger:
  - alias:  Trigger 6hr before solar noon 
    platform: template
    value_template: |
      {% set noon = states('sensor.sun_solar_noon')|as_datetime%}
      {{ now() >= noon - timedelta(hours=6) }}
    id: 'on'
  - alias:  Trigger 6hr after solar noon 
    platform: template
    value_template: |
      {% set noon = states('sensor.sun_solar_noon')|as_datetime %}
      {{ now() >= noon + timedelta(hours=6) }}
    id: 'off'
condition:
  - alias: "Test: Don't run if today is already going to be more than 12 hours"
    condition: template
    value_template: "{{ states('sensor.sun_daylight') | float < 12 }}"
action:      
  - service: light.turn_{{ trigger.id }}
    target:
      entity_id: light.coop_day_light

You could add additional triggers for sunrise and sunset to turn it off then back on if you don’t want the light to stay on throughout the day.

1 Like

Thank you. That’s makes perfect sense and helped me a lot.

I want to only turn the light on in the morning so I went with this which also should make sure (correct me if I’m wrong please :slight_smile: ) that the light is always on for at least 30 minutes and not less.

alias: Light Coop
description: ""
trigger:
  - alias: Trigger 12hr before sunset
    platform: template
    value_template: |
      {% set sunset = states('sensor.home_sun_setting')|as_datetime%}
      {{ now() >= sunset - timedelta(hours=12, minutes=30) }}
    id: "on"
  - platform: sun
    event: sunrise
    offset: "00:30:00"
    id: "off"
condition:
  - alias: "Test: Don't run if today is already going to be more than 12 hours"
    condition: template
    value_template: "{{ states('sensor.home_sun_daylight') | float < 12 }}"
action:
  - type: toggle
    device_id: id
    entity_id: id
    domain: switch
1 Like