Random Light Schedule

Does this work? I thought you needed to ensure that hh, mm and ss were always two digits.
I do this:

- delay: "00:{{ '{:02}'.format(range(5, 11) | random | int) }}:00"

Apparently that’s up for debate because many people claim they are using it without the leading zero.

Maybe their random number has never been one digit long :rofl::sunglasses:

1 Like

murphy’s law right there!

My guess is that when HA see’s a time, it parses the time based on colons. If it parsed that way, it would work fine.

It seems to work and is used a couple times a day in various automations; and they are all working.

But I do agree yours is the proper solution to ensure it’s 2 digits for each field and I’ll happily update.

Thanks for sharing. Haven’t you got the state of the alarm panel under conditions in there twice unnecessarily?

  condition:
    - condition: state
      entity_id: alarm_control_panel.ha_alarm
      state: 'armed_away'

    - condition: sun
      after: sunset
  
  action:
    - delay: "00:{{ '{:02}'.format(range(1, 29) | random | int) }}:00"

    - condition: state
      entity_id: alarm_control_panel.ha_alarm
      state: 'armed_away'

    - service: homeassistant.toggle
1 Like

The second one is to ensure the light is turned on after the delay only if the alarm is still armed. During that delay if you disarm the light would still come on without that 2nd one.

Thanks a heap. Didn’t realise (after 2+ yrs of using HA), that you can have a condition after an action! Awesome. P.S If you can edit your code above, the time statement is no longer valid. It now needs to be:

trigger:
  - platform: time_pattern
    minutes: '/30'
1 Like

I thought I’s share what I have been using for a few months. I called it “Occupancy Simulator”.

occupancy_simulator.yaml (package)

input_boolean:
  enable_occupancy_simulator:
    name: Enable Occupancy Simulator

automation:
  - alias: Occupancy Simulator-Doorbell
    initial_state: 'on'
    trigger:
      - platform: event
        event_type: xiaomi_aqara.click
        event_data:
          entity_id: binary_sensor.switch_158d00018b3ede
          click_type: single
    condition:
      - condition: state
        entity_id: input_boolean.enable_occupancy_simulator
        state: 'on'
      - condition: state
        entity_id: sun.sun
        state: 'below_horizon'
      - condition: template
        value_template: "{{ is_state('device_tracker.davess7lan','not_home') and is_state('device_tracker.rowess7lan','not_home') }}"
    action:
      - delay: '00:00:{{ range(10,40) | random | int }}'
      - service: homeassistant.turn_on
        data:    
          entity_id: light.bedroom_lamp
          brightness: 200
      - delay: '00:0{{ range(9) | random | int }}:{{ range(10,58) | random | int }}'
      - service: homeassistant.turn_off
        data:    
          entity_id: light.bedroom_lamp

  - alias: Occupancy Simulator-Random Timed Lights (Sunset)
    initial_state: 'on'
    trigger:
      - platform: sun
        event: sunset
        offset: '00:15:00'
    condition:
      - condition: state
        entity_id: input_boolean.enable_occupancy_simulator
        state: 'on'
      - condition: template
        value_template: "{{ is_state('device_tracker.davess7lan','not_home') and is_state('device_tracker.rowess7lan','not_home') }}"
    action:
      - delay: '00:{{ range(10,40) | random | int }}:00'
      - service: homeassistant.turn_on
        data:    
          entity_id: light.kitchen_light_level
          brightness: 255
      - delay: '00:0{{ range(9) | random | int }}:{{ range(10,58) | random | int }}'
      - service: homeassistant.turn_on
        data:    
          entity_id: light.bedroom_lamp
          brightness: 255
      - delay: '00:0{{ range(9) | random | int }}:{{ range(10,58) | random | int }}'
      - service: homeassistant.turn_off
        data:    
          entity_id: light.kitchen_light_level
      - delay: '00:0{{ range(9) | random | int }}:{{ range(10,58) | random | int }}'
      - service: homeassistant.turn_off
        data:    
          entity_id: light.bedroom_lamp
      - delay: '00:0{{ range(9) | random | int }}:{{ range(10,58) | random | int }}'
      - service: homeassistant.turn_on
        data:    
          entity_id: light.kitchen_light_level
          brightness: 255
      - delay: '00:0{{ range(9) | random | int }}:{{ range(10,58) | random | int }}'
      - service: homeassistant.turn_off
        data:    
          entity_id: light.kitchen_light_level

  - alias: Occupancy Simulator-Random Timed Lights (Midnight)
    initial_state: 'on'
    trigger:
      - platform: time
        at: '00:00:00'
    condition:
      - condition: state
        entity_id: input_boolean.enable_occupancy_simulator
        state: 'on'
      - condition: template
        value_template: "{{ is_state('device_tracker.davess7lan','not_home') and is_state('device_tracker.rowess7lan','not_home') }}"
    action:
      - delay: '0{{ range(2) | random | int }}:{{ range(10,55) | random | int }}:00'
      - service: homeassistant.turn_on
        data:    
          entity_id: light.bedroom_lamp
          brightness: 255
      - delay: '00:0{{ range(9) | random | int }}:{{ range(10,58) | random | int }}'
      - service: homeassistant.turn_off
        data:    
          entity_id: light.bedroom_lamp
      - delay: '00:0{{ range(9) | random | int }}:{{ range(10,58) | random | int }}'
      - service: homeassistant.turn_on
        data:    
          entity_id: light.bedroom_lamp
          brightness: 255
      - delay: '00:0{{ range(9) | random | int }}:{{ range(10,58) | random | int }}'
      - service: homeassistant.turn_off
        data:    
          entity_id: light.bedroom_lamp

I have am input_boolean in the GUI to turn it on/off and it only switches lights if my girlfriend and I are both not_home. If someone presses the doorbell, it starts a light switching sequence, likewise at a random time after sunset and again after midnight.

1 Like

What type of doorbell are you using?

I’m using a Xiaomi wireless button (round type) for the doorbell button and the Xiaomi Gateway to produce the chime sound. As well as making the chime sound, automations pause any playing media and send notifications to phone’s with a camera snapshot

1 Like

Hmm… Can this be wired or is it only available with battery?

The wireless buttons are battery powered / wireless however I’m sure you could very easily open one up and hard-wire it. It wouldn’t take much to do. Simply solder some wires to the circuit board in place of the button switch so you can wire it to the switch of your choice and solder a power supply in place of the battery. I’m actually looking at wiring some external switches to them myself, but I’ll likely leave them as battery powered, at least to begin with. I have had them over a year and the batteries are still going strong

I was going to use the door bell wires, need to check the voltage first and see what options I have…

I have been looking to expand my ‘away’ lighting automation, and ran across this post (along with many others). I tried a solution similar to jwelter (et.al.), but found that ALL of my lights were on at times due to the random toggle code. I was looking more for something that would turn a random light from a group on for a random time, turn it off, wait a random time, and turn on another random light from the group, turn it off, and so on. I also wanted this to occur only at night and only when I had enabled the automation to run (i.e., when I am away). I didn’t need anything fancy like presence detection, since I can always access my system through nabu casa if I forget to enable it before I leave.

The problem I had with jwelter’s solution was that I could not turn the light I just turned on off, because I didn’t know which one it was, and it’s way too cumbersome to create, assign, and store a variable (IMO). So I ended up with something similar to rebelnme, passing the chosen random light to a script via a parameter, which I could then reuse to turn the light back off. I also rely on the repeat:until loop mechanism to handle the automation, rather than having it trigger using a time pattern.

Just putting this out there to hopefully give a little back to this awesome community. Please let me know if you see anything that is incorrect, or could be improved.

Here is the Automation:

  # Automate Lights While Away
  - id: automate_lights_while_away_atm
    alias: Automate Lights While Away (ATM)
    description: Automate Lights While Away
    trigger:
      - platform: state
        entity_id: input_boolean.away_mode_lights_enable_ib
        to: 'on'
      - platform: state
        entity_id: sun.sun
        to: 'below_horizon'
    condition:
      - condition: state  
        entity_id: input_boolean.away_mode_lights_enable_ib
        state: 'on'
      - condition: state
        entity_id: sun.sun
        state: 'below_horizon'
    action:
      - service: script.automate_lights_while_away_scr
      # ATM Will Wait Here Until Script Ends
      # Turn Everything Off When Script Ends
      - service: homeassistant.turn_off
        entity_id: group.away_automation_light_grp

Here are the two Scripts:

  # Automate Lights While Away
  automate_lights_while_away_scr:
    alias: Automate Lights While Away (SCR)
    sequence:
        repeat:
          sequence:
            - service: script.automate_lights_while_away_sub_scr
              data_template: 
                eid: "{{ state_attr('group.away_automation_light_grp','entity_id') | random }}"
                mins: "{{ range(30, 120) | random }}"
            - delay: 
                minutes: "{{ range(5, 20) | random }}"
          until:
            - condition: template
              value_template: "{{ is_state('input_boolean.away_mode_lights_enable_ib','off') or is_state('sun.sun','above_horizon') }}"

  # Automate Lights While Away (Sub)
  automate_lights_while_away_sub_scr:
    alias: Automate Lights While Away Sub (SCR)
    sequence:
      - service: switch.turn_on
        data_template:
          entity_id: "{{ eid }}"
      - delay:
          minutes: "{{ mins }}"
      - service: switch.turn_off
        data_template:
          entity_id: "{{ eid }}"

The Group is defined as usual.

Note that I had considerable trouble with the Until Condition in the Repeat in the first script. I believe there might be a bug in the implementation of the repeat:until code, or either the documenation that says Conditions are defined as per the Docs is incorrect. I was never able to successfully create an OR conditions statement. I worked around it using a condition template (which turned out to be easier anyway). YMMV.

3 Likes

Hi,

I think you can simplify this by using toggle.

Off the list of lights you have in the random away group select one at random, as you are doing, and toggle it. Then wait a random period of time and repeat. You get rid of the inner script. You also get the same random behavior of both the turn on, and turn off in your scripts.

automate_lights_while_away_scr:
    alias: Automate Lights While Away (SCR)
    sequence:
        repeat:
          sequence:
            - service: homeassistant.toggle
              data:
                entity_id: "{{ state_attr('group.indoor_random_away_lights','entity_id') | random }}"
         
            - delay: 
                minutes: "{{ range(5, 20) | random }}"
          until:
            - condition: template
              value_template: "{{ is_state('input_boolean.away_mode_lights_enable_ib','off') or is_state('sun.sun','above_horizon') }}"

I tried that initially, but found that the toggle would often turn ON several lights in a row before turning one of them back off again. At one time, the entire group was on! As I explained in my post, that’s not the behavior I was really after, which led me to the solution I posted. After reviewing about 20 different posts by folks looking for an away light automation solution, I ultimately had to come up with my own to fit my particular needs and desires. It is a little more complex that yours, but has slightly different behaviors.

The problem trying to adapt your solution directly was that using the random selection template in the service call itself, you couldn’t use the same entity_id again to turn it back off, which is what I wanted. I would need to store that entity_id either in a variable (which would cause a change to config and a restart and a lot of other machinations to accomplish), or pass it as a parameter to another script, like rebelnme did. I considered the second option easier in my case.

Thanks for sharing your solution, it was one of the ones that helped me the most.

Cheers.

Makes sense, I’ve not noticed them all getting turned on but certainly it is random and could happen.

I think your problem can be solved by looking at the group’s members and if a certain threshold is on, then toggle on the “on” list and not the full list.

This is what I’ve come up with, the benefit is you can set the max lights on which helps the illusion of people being home. I expanded the logic for debugging and to make it easier to modify. I also adapted to use expand as we know the group we’re working with so no need to iterate over all the states.

    - service: homeassistant.toggle
      data:
        entity_id: >-
          {% set group_id = 'group.indoor_random_away_lights' %} 
          {% set max_on = 3 %}    
          {% set lights_on_count = expand(group_id) | selectattr('state', 'eq', 'on')| list | length %}
          {% if lights_on_count > max_on %}
            {% set lights_on_entities = expand(group_id) | selectattr('state', 'eq', 'on')| map(attribute='entity_id') | list %}
            {{ lights_on_entities | random }}
          {% else %}
            {% set group_lights_entities =  expand(group_id) | map(attribute='entity_id') | list %}
            {{ group_lights_entities | random }}
          {% endif %}
    
3 Likes

The following describes a method for randomizing various automation events to be employed while on vacation to give the appearance of being home. This method requires no YAML coding and uses only Home Assistant UI elements. This method is based on using the Random helper that creates a new random integer every 30 seconds.

  1. Create a toggle switch helper labeled “Vacation Mode” to be used as a condition for various automations. For automations to be employed when away on vacation, check to see if the switch is on. For each automation to be run when not on vacation, instantiate a condition that the switch is off. (Defining helpers is done by entering Settings>Devices and Services and then selecting the Helpers menu item at the top of the page.)
  2. Create a “Random Sensor” helper with a significant name such as “Random_000-999”, setting its min/max values as desired (0 and 999 in this example). A larger random range provides finer granularity of choices for average time between events. Do NOT select the random binary sensor.
  3. For a vacation-enabled random event, create an automation as follows:
    a. Make a trigger based on “Random_000-999” greater than X and less than Y. Select the range for the desired average frequency of the event as determined by the formula: avg_interval = random_range / ( 2 * event_range)
    So, for a random range of 1000 values, an event range of ten values provides an average interval of once every 50 minutes. Actual intervals will of course vary.
    b. You may overlap events if some percentage of time you wish them to occur together, or use non-overlapping event ranges for completely independent events.
    c. Set the combination of conditions as desired, but be sure to include a check for Vacation Mode switch being ON. For instance, add conditions for after sunset and before a desired stop time.
    d. For lights going off and on at random intervals, use the toggle action so that regardless of current state, a change will occur when the random number falls within the desired event range.
  4. For other automations that are NOT to be executed in vacation mode, be sure to include a condition that the switch is in the OFF state.

Note that the condition “after sunset” is active until midnight. At midnight, a new day begins and the sun’s condition is “before sunrise” and not “after sunset”. If you wish the random events to continue occurring after midnight, you’ll need additional logic. To run all night, create a “State” condition based on the entity “Sun” being in the state “Below Horizon”. To terminate the random lighting, you can add a separate automation that turns everything off at a certain time when on vacation regardless of the state of the “Sun” sensor. This can be done with a group of actions at a single fixed time, a set of automations for different fixed times, or randomized turn-off automations at random times. (Note that the last option does not guarantee that everything will eventually go off.)

Finally, be aware that the log will record an event every 30 seconds each time the random helper changes state to a new value. This can lead to an annoying collection of events to sort through should you ever need to search the log. To prevent this, you may suppress the random event logging by adding some YAML to your configuration file, as shown below, and then restart HA:

logbook:
exclude: (indent two spaces)
entities: (indent four spaces)
“- sensor.random_000_999” (indent six spaces; use your random sensor’s name)

1 Like