Add easier solution for loops in automations/scripts

If I would need to do something like this with native HA automations (I do this with AppDaemon and there it is “easy” to do something like this), I would create or look for a song and then play that song on repeat as long as ther is an intruder and stop it when the alarm system has been disarmed instead of sending ao many TTS.

1 Like

now remember this thread. I do what you want, I think, using 3 scripts:

  sound_bite:
    alias: Sound bite
    sequence:
      - service: media_player.play_media
        data_template:
          entity_id: >
            {{states('sensor.sound_bite_player')}}
          media_content_id: >
            {{states('sensor.sound_bite')}}
          media_content_type: 'music'

  play_sound_bite:
    alias: Play sound bite
    sequence:
      - service: script.sound_bite
      - delay:
          seconds: >
           {{state_attr(states('sensor.sound_bite_player'),'media_duration')|int}}
      - condition: state
        entity_id: input_boolean.loop_sound_bite
        state: 'on'
      - service: script.play_sound_bite_loop

  play_sound_bite_loop:
    alias: Play sound bite loop
    sequence:
      - service: script.sound_bite
      - delay:
          seconds: >
           {{state_attr(states('sensor.sound_bite_player'),'media_duration')|int}}
      - condition: state
        entity_id: input_boolean.loop_sound_bite
        state: 'on'
      - service: script.play_sound_bite

broadcast is easy, just create a group with all you media_players, and select that group in the top script.
I do that setting an input_select:

      sound_bite_player:
        friendly_name: Sound bite player
        value_template: >
          {% set state = states('input_select.sound_bite_player') %}
          {% if state in ['Hub','Woonkamer','Hobbykamer','Hall','Master bedroom','Office','Dorm 1','Dorm 2'] %}
            media_player.googlehome_{{(state)|lower|replace(' ','_')}}
          {% elif state == 'Gym' %} media_player.chromecastaudio_gym
          {% elif state == 'TheBoss' %} media_player.theboss
          {% else %} group.broadcast
          {% endif %}
        icon_template: >
           {% set mapper =
             {'Hub':'tablet-dashboard',
              'Woonkamer':'sofa',
              'Hobbykamer':'xbox',
              'Hall':'transit-transfer',
              'Master bedroom':'human-male-female',
              'Gym':'dumbbell',
              'Office':'desktop-mac',
              'Dorm 1':'human-child',
              'Dorm 2':'human-child',
              'TheBoss':'cellphone-iphone'} %}
           {% set state = states('input_select.sound_bite_player') %}
           {% set prefix = 'mdi:' %}
           {{[prefix,mapper[state]]|join if state in mapper else [prefix,'radio-tower']|join}}

as long as input_boolean.loop_sound_bite is ‘on’ this loops…

I also found this thread for other reasons than flashing a light. @Erlend is correct many other reasons…

And like Erland you have also overlooked to describe these “many other reasons”.

Nevertheless, in 0.113 it will contain the means to loop in a script so now it will be easier to flash a light … or do all those other things that have been alluded to but not actually described.

Perhaps its due to the type of users of HA. With an IT background we prefer to simplify problems instead of frivolous details. But, since you seem so concerned with the unimportant. I needed to loop a service call to set the volume on my Roku TV via 100x volume down calls and 30 volume up calls as Roku API has no volume set function. See Volume_Down Multiple times in one service call

Glad to see development has listened regardless and looking forward to cleaning up my code, but ideally my hack would be implemented in the Roku automatic setup for setting volume.

For someone who claims to have an IT background, it’s surprising that you said this in your other post:

but I don’t really understand yaml and how this coding language works TBH.

You have just described your own use of looping as “unimportant”.

Looping was always possible using python_script and I provided a simple example earlier in this thread consisting of four lines of python.

Here is a simple example of how to use the new repeat feature in a script (introduced in 0.113). It repeats (loops) a sequence 5 times. The sequence simply increments counter.test then waits 2 seconds.

#script:
  increment_by_5:
    sequence:
      repeat:
        count: 5
        sequence:
          - service: counter.increment
            entity_id: counter.test
          - delay: '00:00:02'

In an automation, you can call the script like this:

  action:
    service: script.increment_by_5

For more information, refer to the Script Syntax documentation.


Here is the same thing as a python_script:

increment_by_5.py

for i in range(5):
  hass.services.call('counter', 'increment', {'entity_id':'counter.test'}, False)
  time.sleep(2)

In an automation, you can call the python_script like this:

  action:
    service: python_script.increment_by_5

@123 You seem to want to argue (says the guy responding :stuck_out_tongue: , perhaps another IT trait?) with every person who has shown thier desire for this feature, isn’t that the point of a feature request thread & poll? Just because somebody can’t list three edge cases doesn’t mean there isn’t enough to justify it’s integration into HA. Is my use case not a perfect example?

@123 For someone who claims to have an IT background, it’s surprising that you said this in your other post:

but I don’t really understand yaml and how this coding language works TBH.

Ask me to script deployment of a High Availablility Galara SQL Cluster, sure, no problem, write a bash script to monitor it? Yeah ok. Deploy a Windows Domain, OK! Do I need to know everything to have an IT background?

I struggle with YAML formatting (read the forum and you will see I’m not alone). I generally use the UI to generate configs, then edit them via CLI, then use an online formatter to make it work. I suspect many users “limp” along fine in a similar fashion. I have no desire/time to perfect my understanding of YAML just for HA.

@123 You have just described your own use of looping as “unimportant”.

What I described was the “unimportant” details of WHY I desired the feature. My comment was simply mean’t to show my vote/desire to see it implemented, I didn’t feel it was necessary to go into details as to why.

@123 Looping was always possible using python_script and I provided a simple example earlier in this thread consisting of four lines of python.

I’d rather not introduce python scripts into a setup that doesn’t utilize them currently, while my solution of pasting code repeatedly was ugly, since I was able to split configs, it was bearable. But, I’m pulling the latest docker HA image to hopefully test the new “repeat/loop” config. Thank you for your example configuration, it will save me time “limping” along with my clean up of my code <3

@123 The new feature works Amazing! Could you explain how I could make the “Count” an argument that could be passed when calling the script for the “VolumeUp” portion of my setup? I currently utilize individual scripts for each volume setting, but that is less than ideal. If not, I’ll try and figure it out and post back!

I got it, not to hard.

w/ Count as Argument:

  volup:
    sequence:
      repeat:
        count: '{{ count }}'
        sequence:
          - service: media_player.volume_up
            entity_id: media_player.freesoftwareservers

I want to make it clear that looping was always available in Home Assistant, using either python_script or automations based on timer events. In addition, the number one, most frequently requested application of looping is … flashing a light. That’s why I asked that someone provide a few other real-world home automation applications for repeating the same thing over and over. I thank you for offering at least one other application … and it’s a good example.

python_script is just another integration. Everything in Home Assistant is an integration: Template Sensors, scripts, REST, etc.

Glad to hear it. Sounds like you’re more comfortable with YAML than you indicated.

1 Like

Since you asked, I posted another use case here. Though with a heavy helping of sarcasm.

It’s quite surprising how many people opted to use that torturous script-calling-a-script technique, to do looping, when a 3-line python_script achieves the same thing with less effort. :man_shrugging:

Anyway, now they can loop using a single script (with 8 lines).

Now that looping is supported natively in HA’s scripting language (starting in 0.113.0, with most bugs fixed in 0.113.2 :sweat_smile:), would you consider marking this topic as solved? E.g., find an appropriate reply and click image

Thanks!

Hi all,

I’m a software engineer who enjoys using Hassio for my home stuff (and to drive me wife up the wall - it seems). There have been numerous occasions where I wish I could just drop a loop statement around an action. I would like to do this with out having to resort to scripts. Why not just add it to the automatons UI? I read through the reasoning that has been given by the committers of this project, and all the criticism that goes against implementing a loop. However, I can not understand why it would be a ‘bad pattern’. Surely you are just giving what the users are asking for? Is there some other (technical/performance) reason why there is so much resistance to this? In my current use case, I am using AlexTT’s Alexa integrations to notify me of smoke detector triggers from a sonoff smoke alarm. I can easily set everything I need using the UI automation page. I just can’t repeat the alarm without getting my hands dirty with scripts. There is an alert feature, but I can’t see easily, how I can get that to call the Alexa notify service. Admittedly, I haven’t given any serious amount of time yet in working it out, but the fact I have to, seems a little unfriendly. Sorry if this comes across as a moan, I just want to provide some feedback and collect some understanding around this resistance towards making the integrations page a little more user friendly. For the record, I love using Hassio and thank the comitters for their work.

What kind of software engineer did you say you were?

The Automation Editor doesn’t implement everything that scripting offers. Someone has to volunteer their time to add it. It’s not “resistance” but due to lack of a volunteer developer’s time or interest. If you have the requisite skills you may wish to try to enhance the Editor. Otherwise, you’ll have to wait until someone else improves it or just “get your hands dirty” with manually-created scripts.

1 Like

First, the action part of an automation is exactly the same as the sequence part of a script. Both can do exactly the same things.

Second, looping is now available (again, for both automations and scripts.)

Third, as @123 mentions, the UI editors tend to lag a bit behind what can be done in YAML. That’s just the nature of the beast. The UI will get there.

Fourth,

I wonder what you’re referring to. I have never seen any of that. My guess is it’s very old because I had no trouble adding native looping to the scripting language and getting it approved by the main developers of this project.

And lastly,

No problem. Feedback is (almost :wink:) always appreciated! :slightly_smiling_face:

“What kind of software engineer did you say you were?” (spicy). One that does his best not do use scripts, and looks to avoid reinventing the wheel. I’m sorry if I offended you with my comment about scripts - that was not my intention. I just avoid them, if I can help it and use existing functionality (where it exists) to save time. Hassio, on the most part does this for me - that’s why I use it.

1 Like

Thank you pnbrunkner for the useful reply :-). I had no idea you can now use a loop in an automation (around an action?). That makes me very happy as I can probably pull off this use case without too much time away from the family. @123 asked me what sort of engineer I was - a better answer from me would of been one that is on a tight time budget given by wife! I really do love using Hassio. I’m not committing at the moment, but I am tempted to have a go (when/if time allows).

No need for apologies; I’m not offended. By leading with “I’m a software engineer” you must admit the last thing one would expect a software engineer to carp about is getting “hands dirty” with a script … unless, perhaps, you’re actually a software architect :wink:

Historically, everything in Home Assistant has been configured via text files (using YAML). The same scripting syntax is used in an automation’s action or in the body of a standalone script. UI-based editors were eventually introduced (for composing automations and scripts) but have always been slightly behind the curve. They don’t allow one to use everything that’s available in scripting thereby they produce results that are, to be polite, limited.

I was under the impression you already knew it was now possible (as of 0.113) to create actions/scripts containing loops and you were only displeased with the inability to create them with the Automation/Script Editors. Eventually the editors will be enhanced but, for now, you’ll have to dust off your favorite text editor and manually compose loops (using repeat).

If you use VS Code, there’s an extension called Home Assistant Config Helper that performs validation, text completion, etc (helps avoid making common syntax errors).

FWIW, the name “hassio” was discarded many months ago and recently got a second name change to “Home Assistant OS”. For future reference, here’s a table comparing the feature sets of the four official installation methods.