Calculate Estimated Luminance in Home Assistant

Calculate Estimated Luminance in Home Assistant

The motivation

On the one hand, I wanted to switch the motion-sensor lights based on whether it was dark enough. If it's bright, don't turn them on.

On the other hand, I didn't want to buy a separate hardware (brightness sensor) for $10 for this function, so I figured out something else instead.

The Home Assistant knows by default where the sun is, and you can get the current weather (sunny, overcast, rainy, etc.) from an external provider.

So it was a given that I would write a template for this, since the Home Assistant can do everything :)

How it works?

This template sensor calculates the approximate light in lux (LX) based on two factors:

Height of the sun: Uses the elevation angle (degrees) of the sun. If this is negative (night), the base luminance is 0; otherwise it is scaled linearly (height × 1000).

Weather conditions: The base value is adjusted using multiples of predefined conditions (e.g. 1.0 for "sunny", 0.4 for "cloud"). If the weather conditions are not known, an omission of up to 0.5 is used.

The final luminance base is the product of lux (from height) and the weather factor, rounded to the nearest integer.

Note: It has been optimized to use with OpenWeatherMap.

Copy and paste the code below in your configuration.yaml file:

template:
  - sensor:
      - name: "Estimated Luminance"
        unit_of_measurement: "lx"
        state: >
          {% set elevation = state_attr('sun.sun', 'elevation') | float %}
          {% set weather = states('weather.openweathermap') %}
          {% set base_lux = 0 if elevation < 0 else elevation * 1000 %}
          {% set weather_factor = {
            'sunny': 1.0,
            'clear-night': 0.05,
            'partlycloudy': 0.7,
            'cloudy': 0.4,
            'rainy': 0.2,
            'pouring': 0.15,
            'snowy': 0.3,
            'fog': 0.2
          }[weather] if weather in [
            'sunny', 'clear-night', 'partlycloudy', 'cloudy', 'rainy', 'pouring', 'snowy', 'fog'
          ] else 0.5 %}
          {{ (base_lux * weather_factor) | round(0) }}

Remember to restart your Home Assistant after saving the file.

The entity will be "sensor.estimated_luminance", you can use it in your automation.

It will look like this (it's night when I write this article)

I hope it was useful for You. :)

If you found this article useful and would like to show your appreciation, please consider making a small donation via PayPal. Your support will allow me to continue creating valuable content and make my blog even better. Thank you for your contribution!

Comments