Select multiple random entities from group

Hey,

Let’s say I have the following group:

lights:
  name: Lights
  entities:
    - light.bedroom
    - light.kitchen
    - light.hall
    - light.parlor

…and the following script:

random_lights:
  alias: "Random Lights"
  sequence:
  - condition: state
    entity_id: sun.sun
    state: 'below_horizon'
  - delay: '{{ (range(0, 2) | random) ~ ":" ~ (range(0, 60) | random) ~ ":" ~  (range(0, 60) | random) }}'
  - service: light.turn_on
    entity_id: group.lights
  - delay: '{{ (range(0, 2) | random) ~ ":" ~ (range(0, 60) | random) ~ ":" ~  (range(0, 60) | random) }}'
  - service: light.turn_off
    entity_id: group.lights

The thing is I don’t want the whole group to turn on, but only certain randomly selected lights. The array of the selected lights shall be 1 to 4 elements long, this is also random.

How can I achive this?

Have you found a way to achieve this @7h30n3 ?

No luck so far.

@7h30n3 @shlomki

Do you want to turn on a different light each time then turn it off then turn another on and so on? The following script should help choosing a light to turn on (could run it again after some random time to turn on another light). If you have the possibility of setting a group outside HA that would include these lights it would be easier than turning all the lights in the HA group on or off (as it would modify the state of each individual item and add some lag).

- service: light.turn_on
  data_template:
    entity_id: 'light.{{["bedroom","kitchen","hall","parlor"]|random}}'

Thanks :slight_smile: I know this way already, but I wanted a more elegant solution of including all of these lights in a group, instead of a list in a script.
Thanks for the help!

I think that you might want to reconsider sending on/off commands to light groups. If you want to include the lights in a group and then turn the group on/off it would be advisable to do the group outside HA as all the lights in a group would be switched by HA individually and it will take a significant amount of time (Rpi is probably not suited for this). Should you have more than 8-10 light bulbs that you want to include in a group and switch the group, then it will take 2 to 10 seconds to switch all the lights in the group. Add some other tasks that HA need to perform in the same time and you’ll start hating it.

At least, from what I’m familiar with, for MiLight and Hue, you can set the groups outside HA so you would end with group 1 that includes lights 1,3,5,7; group 2 that includes lights 2, 4, 6, 8 and group 3 including lights 1,2,3,4,5,6,7 (in HA each group would appear as individual lights). The advantage is that turning all the lights in any of the groups on or off would be instantly as opposed to using HA groups.

You can pick a random entity_id from a group like this:

{{ states.group.lights.attributes.entity_id | random }}
1 Like