I’m trying to create a script that checks the state on multiple devices before triggering each.
Reason for this is that some of my IR devices use the same command for on/off so using
switch.tv_power off will just turn it on when it’s already turned off.
Tried this, but it only continues to the next item if the condition is met. So, if it checks TV and TV is already off, it stops the script at that point instead of checking and switching the other devices.
Example from script.yaml
bed_time:
alias: "Bed Time"
sequence:
#Check TV State
- condition: state
entity_id: switch.tv_power
state: 'on'
- service: homeassistant.turn_off
data:
entity_id: switch.tv_power
#Check RGB State
- condition: state
entity_id: switch.rgb_power
state: 'on'
- service: homeassistant.turn_off
data:
entity_id: switch.rgb_power
#Check AMP State
- condition: state
entity_id: switch.amp_power
state: 'on'
- service: homeassistant.turn_off
data:
entity_id: switch.amp_power
#Check Lamp State
- condition: state
entity_id: switch.pc_lamp
state: 'on'
- service: homeassistant.turn_off
data:
entity_id: switch.pc_lamp
#Check Screen State
- condition: state
entity_id: switch.pc_screen
state: 'on'
- service: homeassistant.turn_off
data:
entity_id: switch.pc_screen
Should I rather create separate scripts for each, and run them all via a automation, or am I on the right track here?
When a condition does not turn true, the script will finish
Separate scripts triggered by an automation would work. It would also be possible I think to accomplish this with a single automation given sufficient templating jujitsu.
Rather than script, have you tried a template/conditional switch. You can have a switch based on any other switch/sensor state. I’ve also seen boolean used for a similar purpose. See example below or the original documentation:
I see so if my above sample would allow for turning on/off multiple switches it would suffice. Let me see what I can try later with that notion in mind. Obviously a dash goes in front of children in YAML so that’s always a fun challenge.
I think you could pass a for loop to the entity_id field that prints out a list of the entities that are currently on. For example, I was able to use this to get a list of all of my lights that are currently on:
{% for state in states.light -%}
{%- if state.state == 'on' %} {{ state.entity_id }} {% endif -%}
{%- endfor -%}
Of course, you’d have to change that first line to iterate on state in states.switch. Try this out in the templates section of the developer tools. If you use that for loop for your entity id, and just call homeassistant.turn_off once, all of your switches should turn off. Of course this could be problematic because it will turn off ALL of your switches, which may not be what you want.
I tried to do this with a group like this: {% for state in states.group.living_room -%} but it didn’t work, and I have no idea why.