Outdoor illuminance template sensor

Optional: Multiple Weather Condition Sensors
If your primary weather source goes “unavailable” sometimes, you can modify a few lines of code to add one or more backup sensors.

current_condition: original lines

{%- set factors = namespace(condition='',sun='') %}

{#- Retrieve the current condition and normalize the value #}
{%- set current_condition = states("weather.accuweather") %}
{%- set current_condition = current_condition|lower|replace("partly cloudy w/ ","")|replace("mostly cloudy w/ ","")|replace("freezing","")|replace("and","")|replace(" ", "")|replace("-", " ")|replace("_", " ")|replace("(","")|replace(")","") %}

current_condition: new lines (with 2 backup condition sensors)

{%- set factors = namespace(condition='',sun='',current_condition='') %}

{#- Retrieve the current condition and normalize the value #}
{%- set weather_sensors = [
  "weather.accuweather",
  "sensor.openweathermap_condition",
  "sensor.cc_climacell_weather_condition"
] %}
{%- for sensor in weather_sensors if states(sensor) not in ["unknown","unavailable"] and factors.current_condition == "" %}
  {%- set factors.current_condition = states(sensor) %}
{%- endfor %}
{%- set current_condition = factors.current_condition|lower|replace("partly cloudy w/ ","")|replace("mostly cloudy w/ ","")|replace("freezing","")|replace("and","")|replace(" ", "")|replace("-", " ")|replace("_", " ")|replace("(","")|replace(")","") %}

A small change to the line that does normalizes the current_conditions variable (with lots of replace() filters. The |replace(" ", "") needs to be moved so it is the last replace on that line. I ran into a situation this morning where the condition was “mostly cloudy”, instead of “mostlycloudy” like I expected.

I believe that this line of code is incorrect, if I comment it out the template runs, but otherwise it always returns a value of 10. I believe the issue is after the assignment you cannot reference factors.current_condition as that does not exist. It just needs to be current_condition = current_condition…
So the corrected line is:

{%- set current_condition = current_condition|lower|replace("partly cloudy w/ ","")|replace("mostly cloudy w/ ","")|replace("freezing","")|replace("and","")|replace("-", " ")|replace("_", " ")|replace("(","")|replace(")","")|replace(" ", "") %}

Thanks!

1 Like

Oops! I just realized what the problem was. Here is the correct line of code:

{%- set current_condition = current_condition|lower|replace("partly cloudy w/ ","")|replace("mostly cloudy w/ ","")|replace("freezing","")|replace("and","")|replace("-", " ")|replace("_", " ")|replace("(","")|replace(")","")|replace(" ", "") %}

I mistakenly left a code fragment which was intended for the Optional: Multiple Weather Condition Sensors. Sorry about that. (factors.current_condition should have just been current_condition.)

{%- set current_condition = factors.current_condition|lower|replace("partly cloudy w/ ","")|replace("mostly cloudy w/ ","")|replace("freezing","")|replace("and","")|replace("-", " ")|replace("_", " ")|replace("(","")|replace(")","")|replace(" ", "") %}

Yep, HA has been, and continues to be, a moving target. FYI, just released updates to my custom integration to deal with changes through 0.117. I don’t use it anymore myself (since I got a light sensor a while ago) so can’t be sure it’s 100% right, but it does appear to work again (and at least doesn’t crash anymore.) Having said that seems like you’ve gone beyond what I did anyway.

2 Likes

For some reason my HA didn’t like that so I used:

          {#- Compute Sun Factor #}
          {%- set right_now = now() | as_timestamp %}

instead.

1 Like

Also @BrianHanifin you seem to have updated to:

{%- elif right_now <= sunrise_end %}
  {%- set factors.sun = ((right_now - sunrise_begin) / (60*60*60)) * 10 %}
{%- else %}
  {%- set factors.sun = ((sunset_end - right_now) / (60*60*60)) * 10 %}
{%- endif %}

But the original post doesn’t reflect that. Can you confirm the code in Post 1 is actually correct?
It shows /(6060) not (6060*60))*10
Also I have to use now() as the other function doesn’t work and gives log errors

I had problems with

{%- set right_now = states.sensor.time.last_updated.timestamp() %}

at first too, because I apparently did not have a time sensor in my config yet. I updated to include the following in sensors.yaml, which fixed the problem for me. (@BrianHanifin, maybe update the OP to reflect this dependency)

- platform: time_date
  display_options:
    - 'time'

Is there a reason to not use now()?

I don’t believe there is.

It’s odd because the original code did use (now) but for some unexplained reason he switched it.

That was a mistake which I made early in development. I didn’t fully understand the math then, but I have been updating the code in the first post with any changes as I go. For example I just switched to now() | as_timestamp() per your suggestion.

1 Like

At the bottom of this post is a link to a snapshot of my personal variation on this sensor. To make it easier for me to troubleshoot the code I have broke the 3 pieces of data out into attributes of the sensor. I am including this for the benefit of advanced users.

You can see the 3 attributes in the below screenshot.

My preferred weather source becomes unavailable after I hit their limit for the day. So the current_condition attribute automatically fails over the the next weather provider in the list of weather_sensors. This is more complexity than most people will need, so use this as a reference and replace that code to your current weather condition from a single sensor.

1 Like

This is great work guys. I am going to use it to turn on some lights gradually from a darker area of the house first then the other areas slightly later. I was using Dawn and Dusk plus offsets, then a sunlight percentage calculation which didn’t quite hit the mark. Going to monitor the values to see what triggers to use.
Thanks again a keep up the good work.
P.S. I used the example from BrianHanifin’s post #43 and it seems to be working.

2 Likes

I have just started to try and get useful information out of this script (which works great BTW)

Here is my automation:

  - id: '1505977024304'
    alias: Turn Lounge Light On Elevation < 25° & after 4PM
    trigger:
    - platform: state
      from: 'on'
      entity_id: 'binary_sensor.sun_above_25'
      to: 'off'
    - platform: time
      at: '16:00:00'
    condition:
    - condition: and
      conditions:
      - condition: time
        after: '16:00:00'
      - condition: and
        conditions:
        - condition: or
          conditions:
          - "{{ (states('sensor.illuminance') | float < 7500 ) and (states('sensor.estimated_illuminance') | float < 10000) }}"
          - condition: state
            entity_id: 'binary_sensor.sun_above_25'
            state: 'off'
    - condition: state
      entity_id: 'input_boolean.homeandawayauto'
      state: 'on'
    action:
    - service: script.turn_on
      data:
        entity_id: script.loungenormal

So I want the lights in the lounge room to go on if the sun is below 25° and after 4PM. So I am using Phil Bruckners sun2 binary sensor that switches off at 25°

In Summer though, I don’t want it to switch on unless it’s low light outside. So I use this script to provide sensor.illuminance with a local weather provider in Australia (BOM) and I also use Phil Bruckners illuminance with met.no but I set a different illuminance for both . With the local one < 7500 and the met.no one <10000
(I also have a global overide input_boolean for when we are not home)
Initial testing seems to give the desired result…

1 Like

Hello Guys !

Any of you in Europe ? Which weather data provider do you use ? Did you find any accurate ?
I’ve tested all the ones I could find (DarkSky, OpenWeatherMap,… and the national MeteoFrance) but I’ve never been convinced by the data accuracy.

I’ve ended using a Philips Hue outdoor sensor looking at the sky to get an illuminance sensor, and this is perfect.

1 Like

I’m in Europe (Scotland) David. I use OpenWeather, AccuWeather and Met Office (The latter being UK). Sounds like you have the best solution and no guessing required!

2 Likes

This is nice - Thanks @BrianHanifin.

For others coming to this thread, and uses OpenWeatherMap, I just realized that OWM have got a thing called “Weather Codes”, which somehow put different descriptive weather conditions into categories. :+1:

So instead of using an exhaust dictionary, chances are you could use those weather codes to simplify (or enhance, depends on how you look at this thing) your template sensor!

Other weather services might (or should) have something similar. So… Happy coding!

1 Like

2021.05.x Users: Update Sun2 Component

If you see the following error, you need to update to the latest version of the Sun2 component.

Platform error sensor.sun2 - cannot import name ‘AstralError’ from ‘astral’ (/usr/local/lib/python3.8/site-packages/astral/init.py)

@pnbruckner updated his sun2 component to work with the new version of the library that Home Assistant began using recently.

2 Likes

Potentially dumb question, but I can’t quite pick apart the maths:

Is there a way for me to bring forward the time that the sunset starts to lower the lux level of the sensor? If so, as an example, which part of the sensor would I need to amend to start the lux level dropping 2 hours before sunset?