Easy Home Assistant Random Timer

AS regular readers know I live mainly in Spain and have a home in the UK, visited less frequently. As I demonstrated previously I initially put a few light controls in the UK using Sonoff as a Zigbee coordinator, the downside being that not all of my stuff is Sonoff – indeed some of my lights are WiFi not Zigbee for that matter. This last trip I replaced the Sonoff coordinator (NSPanel Pro) with the rather nice SMlight SLZB-06 Zigbee Ethernet Lan adaptor giving wide Zigbee access in our small UK base.

As I didn’t want to complicate matters with another unattended Raspberry Pi over there, I took the initiative (as I use Zerotier VPN) to create, here in Spain, a second Zigbee2MQTT instance on my Spanish RPI5 (Docker), talking to the UK SMLight coordinator and hence my Zigbee lights and sensors over there.

That left me with a number of choices for random lighting in our absense to make the place look busy. As I’m now standardising on Home Assistant (HA) here to give me access to both countries on my phone from the local Spanish pub and Spanish home of course, I initially left one UK light on a timer inside the (cheap AliExpress) Zigbee switch device controlling the light. Number of issues with that including remote administration and far more importantly no random aspect.

What I wanted/require is a number of lights coming on at different times and for different periods, all with a random aspect, some of which times may overlap. EASY I thought – do that in Home Assistant with an automation, I thought – except that I then went off to “Claude AI” for answers – the first 3 or 4 suggestions were just utter rubbish and the AI quickly apologised.

Let me waste a few seconds of your time – none of what you will see here will work.

automation:
  - alias: "Turn on croft-hall-minir4 and uk-athom-1 at scheduled times"
    trigger:
      - platform: time_pattern
        minutes: "/1"
    condition:
      - condition: or
        conditions:
          - condition: and
            conditions:
              - condition: time
                after: "20:50:00"
                before: "23:10:00"
              - condition: template
                value_template: >
                  {% set times = [('21:00', 'croft-hall-minir4'), ('22:00', 'croft-hall-minir4'), ('23:00', 'croft-hall-minir4'),
                                  ('21:30', 'uk-athom-1'), ('22:30', 'uk-athom-1'), ('23:30', 'uk-athom-1')] %}
                  {% for time, device in times %}
                    {% set random_minutes = range(0, 10) | random %}
                    {% if now().strftime('%H:%M') == (time | as_datetime + timedelta(minutes=random_minutes)).strftime('%H:%M') %}
                      {{ true }}
                    {% endif %}
                  {% endfor %}
    action:
      - choose:
          - conditions:
              - condition: template
                value_template: "{{ now().strftime('%H') in ['21', '22', '23'] and now().strftime('%M')|int < 15 }}"
            sequence:
              - service: switch.turn_on
                target:
                  entity_id: >
                    {% if now().strftime('%H:%M')|float < 21.5 or now().strftime('%H:%M')|float >= 23 %}
                      switch.croft_hall_minir4
                    {% else %}
                      switch.uk_athom_1
                    {% endif %}
      - delay:
          minutes: 15
      - service: switch.turn_off
        target:
          entity_id: 
            - switch.croft_hall_minir4
            - switch.uk_athom_1

The above didn’t work but firstly – Claude insisted on making code to put in the configuration.yaml file, ignoring the ADD INTEGRATION tool in HA – so that first line comes out. The first ‘-‘ comes out and the whole lot needs shifting left, no big deal but then the code simply would not work – 2 lights, on and off at different times with a random element – ALL THAT CODE….

Shortly thereafter, Claude decided the random element should go in a separate SENSOR entry, again configuration.yaml – these days we tend to use a sensors.yaml file for that. It then gave me a new automation. When that didn’t work, CLAUDE decided we should split each device timer into separate automations – and from there the whole thing became a farce – nothing worked and this was getting more complicated by the minute. I’ve seriously missed out hours of experiments all of which ultimately failed.

Enough history – I decided to go back to my time-tested trial and error programming without help – and remembering the split method from my Node-Red days. I wondered if maybe I could simply create a number of unique IDs in one automation – including on/off in the split – then I got ambitious and wondered – maybe, just maybe I could include the entity name in the ID. Would this work? I was VERY skeptical – THEN it hit me but what if some lights are “lights” and others “switches”? At that point I remembered that you can use light.on/off and switch.on/off commands OR just use homeassistant on/off to cover both.

You’ve been patient enough – this WORKS and it’s all mine.

alias: "petes-random-lighting"
trigger:
  - id: 'on-1-switch.t34_smart_plug_3_switch_1'
    platform: time
    at: "10:04:00"
  - id: 'off-1-switch.t34_smart_plug_3_switch_1'
    platform: time
    at: "10:06:00"
  - id: 'on-1-switch.t34_smart_plug_2_switch_1'
    platform: time
    at: "10:05:00"
  - id: 'off-1-switch.t34_smart_plug_2_switch_1'
    platform: time
    at: "10:07:00"
action:
  - delay:
      minutes: "{{ range(0,1)|random }}"
  - service: "homeassistant.turn_{{ trigger.id.split('-')[0] }}"
    target:
      entity_id: "{{ trigger.id.split('-')[2] }}"
	  

So, as many IDs as you need as long as the total ID string is unique… one of my entities might be for example “switch.t34_smart_plug_3_switch_1” and I need to be able to turn it on at random then off at random – I do that for testing with 2 unique IDs – number 1 turns the light on – the next one turns it off – and because I include dashes in the ID (I could have used another otherwise-unused character) I can use SPLIT to create the actual command in the action area which also calls inline random number code (note for testing I used 0,1 – you’ll likely want 0,15 for up to 15 minutes delay to start and end times). In the code here I’m handling 2 separate devices at different, possibly overlapping times. Finally the services I call are built-in homeassistant.turn_on and homeassistant.turn_off as required and as extracted from the ID. The target is also extracted from the ID. My start times, end times and delays were simply kept short to make testing bearable – adjust carefully as needed and add as many ID pairs as needed.

Simple? I think so – if you have a better way, do let me know. I plan to control 3 separate lights and maybe have them come on twice a night at different times and for different periods….

Ultimately I’ll add in the proviso not to do any of this if one of us is IN the UK residence (phone GPS detection which I already use in Spain).

I hope this saves someone lots of wasted time trawling the web.

One thought on “Easy Home Assistant Random Timer

Leave a Reply

Your email address will not be published. Required fields are marked *

Leave the field below empty!


The maximum upload file size: 512 MB. You can upload: image, audio, video, document, spreadsheet, interactive, text, archive, code, other. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here