Count the number of lights on in Home Assistant

Recently I had a requirement for an automation and I needed to know the number of lights which were on in a particular room. Here’s the scenario.

If dark and motion is detected AND there are NO lights on, switch the LED uplighter on.

This was simply because no-one liked putting the big light (ceiling light) on, yet the controls for the lamps were on the opposite side of the lounge.

I added the following code in to my sensor.yaml

  - platform: template
    sensors:
      lounge_current_lights_on:
        friendly_name: 'Number of lights on in lounge'
        value_template: >
          {% set lights = [
            states.light.lounge_ceiling_light,
            states.light.lounge_side_lamp,
            states.light.lounge_tall_lamp_bulb,             
            states.light.lounge_leds        
            ] %}
          {{ lights | selectattr('state','eq','on') | list | count }}

If you don’t have a sensor.yaml, you can create a new file (called sensor.yaml) and add the following line to your configuration.yaml

You should replate the light entities with your own names obviously. You can also use switches here if you have, for example, a lamp plugged in to a smart plug. You’d simply use states.switch.side_lamp for example.

sensor: !include includes/sensor.yaml

Restart home assistant and you should then see a sensor.lounge_current_lights_on with a integer state.

As you turn a light on, that number should then increase.

To use the above in an automation, I wanted to say “if there’s already a light on, don’t do anything. If there are no lights on, put the uplights on. BUT, only if it’s dark” (using the lux from my sensor)

- id: 'lounge_motion_in_the_dark'
    alias: Lounge Motion In The Dark
    trigger:
    - platform: state
      entity_id: sensor.lounge_motion
      to: 'True'
    condition:
    - condition: numeric_state
      entity_id: sensor.lounge_lux
      below: '50'
    - condition: numeric_state
      entity_id: sensor.lounge_current_lights_on 
      below: '1'
    action:
    - type: turn_on
      device_id: xxxxxxxxxxxxxxxxx
      entity_id: light.lounge_leds
      domain: light
    mode: single

You may also like...

Leave a Reply

Your email address will not be published.