Automation that triggers everytime a light changes state

Hi,

I want to create an automation, that fires everytime, a light changes its state. Therefore I tried to use a template trigger, wich simply evaluates the number of lights, that are on. Basically it seems to work, but unfortunately, when the number of lights changes from 0 to some value >0 and not, when it changes for example from 1 to 2. I think it is because a template trigger only fires, when it changes from false to true, so I have to find a condition, which works here.

For me it is important, to have a flexible solution, that keeps on working, when a new light is added, or an entity id changes so I do not want to hardcode all my lights into the automation trigger.

alias: light state changed
description: ''
trigger:
  - platform: template
    value_template: >-
      {{(states.light|selectattr("state","eq","on")|list|length)}}

Are there any ideas?

Thank you in advance
GW

Hi, I would try to define a sensor that holds the number of lights that are on as its state. And then trigger on any state change of that sensor. You can use the same value_template to define the state of the sensor.

1 Like

Wow, sounds dead simple. Thank you!

The one drawback of the proposed solution is it doesn’t report which light turned on only that the number of lights that are on has changed. If you do not need to know which light turned on, then this drawback is unimportant and the proposal will suit your needs.

If you do need to know which one just turned on, there’s a solution posted here:

So if you do need to know which light just turned on, let me know and I can help you adapt the other solution for your needs.

I have the same question, but a different problem.

I have an entity name that is created by a template in a blueprint. It is in a template because I am generating the entity name within the blueprint itself, therefore I only know the name of the entity when the blueprint runs, IE it has to be a template. I want to trigger on that every time the entity changes.

It’s a blueprint, so I am not able to create a sensor or anything outside of the scope of the blueprint. Well I could generate a sensor probably, but it would also have a templated name.

So back to the original question. Is there a way to get a template trigger to trigger on any change? How to pull a statement together to get a true on any change. Any ideas?

Would I have to build 2 numbers and do the comparison myself?