Creating "advanced" Lovelace cards

How to get the number of turned on lights onto a card in Lovelace?
Thanks in advance for any pointers @Petro31

Hey, Are you using custom button card or did you just want to place this anywhere in the UI? There’s a solution for both.

Doesn’t really matter, but I have a feeling the custom button card is the place to start. It’s a nice feature rich card to start with :smiley:

Have you installed the card yet? If not, do you have HACS?

I have it installed through HACS yes. Started playing with it yesterday. Just not sure how to calculate the values to get a number for actual turned on lights in a room.
You could do a JavaScript loop I guess, but that seems clunky.

That’s exactly what I do. It’s hard to follow in my code because I use lovelace_gen which builds my UI for me. Either way, I provide a list of entities to the following loop and it counts which ones are my desired state.

Here’s a close approximation to what I do:

entity_ids = [ 'light.livingroom', 'light.diningroom' ];
on_states = [ 'on', 'open' ];
name = 'light';
var count = 0;
entity_ids.forEach(entity_id => {
  var stateobj = states[entity_id];
  if (stateobj !== undefined)
    if (on_states.includes(stateobj.state))
      count = count + 1;
});
var name = (count > 1) ? name + 's' : name;
return `${count} ${name}`

If you want to see exactly what I do, its in this file starting at line 364. But be warned, it has jinja mixed in because lovelace_gen uses jinja. The jinja creates the code for me based on a configuration. So it’s hard to read because it’s a mix of jinja and js but the end product after lovelace_gen executes is JS.

Super, thanks!
Only thing with this solution is that you have to add this loop to every card right? Plus if the entities in a room changes, you need to update your card aswell?

No way to make it “global”?

the custom button card has templates. You can use templates to reuse code. Or you can use lovelace_gen and have the code generated for you, but this is a harder path to follow.

Yeah I had a look at lovelace_gen and it seems like really nice stuff, but Im having a hard time wrapping my head around how I would actually use it.
And that mix of jinja and javascript in the same code…holy crap thats messing up my head. :frowning: This will take longer than I expected.

Yes, that’s why I was originally going to suggest not using templates in the button card. But you at least seemed to understand the JS so it might be worth just using JS and custom:button-card templates

Haha yeah but damn I wish I devoted more time to javascript back when I took a short course now :smiley:
Thanks for trying to help!