I’m working on streamlining some of the automations used in the HASwitchPlate project. I ran across this post by @petro which suggests that a for loop might be used to fire multiple actions with a single service_template.
I’ve been trying variations on the following theme:
- service_template: >
{% for page_num in range(1,10) %}{% for button_num in range(1,4) %} -mqtt.publish
data_template:
topic: 'hasp/plate01/command/p[{{ page_num }}].b[{{ button_num }}].txt'
payload: '"{% if button_num == 1 %}{{states.input_text.hasp_plate01_pagebutton1label.state}}{% elif button_num == 2 %}{{states.input_text.hasp_plate01_pagebutton2label.state}}{% else %}{{states.input_text.hasp_plate01_pagebutton3label.state}}{%- endif %}"'
{% endfor %}{% endfor %}
The output in the template editor looks approximately correct in the sense that it’s constructing what I would think should be the right number of service calls with the correct MQTT payload, but a Configuration Check fails, usually with something along the lines of
Error loading /home/homeassistant/.homeassistant/configuration.yaml: while scanning for the next token
found character '%' that cannot start any token
in "/home/homeassistant/.homeassistant/packages/plate01/hasp_plate01_p0_pages.yaml", line 110, column 2
Where line 110, column 2 is the beginning % of the for loop.
I guess my major question here is - is this even possible? Am I barking up the right tree here?
Since I just had a tussle with the service_template functionality I would advice you to go the route I took in a recent post and put the logic in a python script instead.
The python script approach is doable but challenging as my desire is to keep this in the realm of Hass automations wherever possible for ease of deployment via packages.
Your for loop under the service template will not work. Jinja cannot return complex objects like lists, dictionaries, json objects, etc. This means you cannot have a ‘loop’ for executing services. You’ll have to create them one by one or use a custom script.
I recommend appdeamon for what you are trying to do. It would be very simple.
That is kind of what I had expected. Thanks for the fast response @petro! I’m just going to leave them as they are because I really want to prevent adding more complexity to the installation process for users of the HASP project. As it stands there is a single shell script which can be used to pull in the complete package without additional configuration. AppDaemon, python scripts, etc bring a lot more complexity for the user for first-time setup, so a huge godawful automation is preferrable based on that requirement.
A custom component is pretty far out of my skillset at the moment, but if a skilled developer wants some hardware to help develop a component we might be able to work something out. PM sent