Here is complete code I use for exactly the same purpose. You will need to adjust eventually your start (now 30 minutes before sunset), end (randomly after 22:30) and frequency (15 minutes) preference. Also some other setup required:
- group.family - group of people for whom if not at home automation will trigger
- group.simulation_lights - group containing all lights that will be used by automation (not all at home)
Basically automation triggers every 15 minutes + random delay (up to 30 minutes) and changes the state of randomly selected light in group to opposite (so either turn on or off).
It is also supplemented by additional automation that at time 22:30+random (30 minutes) switches all lights off.
#############################################################################
## Turn on/off indoor lights randomly
#############################################################################
- id: 'Automatic light toggle'
alias: Random Away Lights
initial_state: True
hide_entity: False
trigger:
- platform: time_pattern
minutes: '/15'
condition:
- condition: state
entity_id: group.family
state: 'not_home'
- condition: sun
after: sunset
after_offset: '-00:30:00'
- condition: time
before: '22:00:00'
action:
- delay: "00:{{ '{:02}'.format(range(0,30) | random | int) }}:00"
# Selecting entity for toggling
- service: input_text.set_value
data_template:
entity_id: input_text.light_to_switch
value: "{{ state_attr('group.simulation_lights','entity_id') | random }}"
# Toggling entity state
- service: homeassistant.toggle
data_template:
entity_id: "{{states('input_text.light_to_switch')}}"
################################################################
## Stopping presence simulation randomly 22:30
################################################################
- id: 'Turning off all toggled lights'
alias: Turn off all lights
initial_state: True
hide_entity: False
trigger:
- platform: time
at: '22:30:00'
condition:
- condition: state
entity_id: group.family
state: 'not_home'
action:
- delay: '00:{{ range(15,59) | random | int }}:00'
- service: homeassistant.turn_off
entity_id: group.simulation_lights
Please note additional step of setting the input_text.light_to_switch to random value - you might move this step directly to last step, but I’m using it to record automation states elsewhere, so need to take a note of it…