Streamlining Automation with Variable Scripts

I’ve been diving into the world of smart home automation, and one thing I’ve noticed is how powerful it can be to streamline processes across multiple devices. Recently, I’ve been working on a project where I wanted to control my smart shutters from various automations without having to write separate scripts for each scenario. The goal was to create a single, reusable script that could handle different shutter positions based on the automation triggering it.

Initially, I set up an automation that would trigger at sunset, aiming to close my shutters to a specific position. The automation looked something like this:

alias: “Close at sunset” description: “” trigger: - platform: numeric_state entity_id: sun.sun attribute: elevation below: -7 condition: action: - service: script.shutters_down data: position_var: 50 mode: single

And the corresponding script:

alias: “Close Shutters” sequence: - device_id: 3f19442a537d7684d75abfe15a93c437 domain: cover entity_id: 01fb8df83d85318698294eacaed0f8c3 type: set_position position: {{ position_var | float }}

The idea was to pass a variable position value from the automation to the script, allowing me to reuse the same script for different shutter positions. However, I ran into an issue where the script wouldn’t accept the variable, throwing an error about the value not being one of the expected options. After some troubleshooting, I realized the problem was with how the variable was being passed and parsed within the script.

Through some research and experimentation, I discovered that using template variables directly in the script wasn’t the most reliable approach. Instead, I found that using input_number entities to store the desired position values and referencing those in the script worked much more smoothly. Here’s how I adjusted the script:

position: {{states(‘input_number.shutter_position’) | float }}

This change allowed me to dynamically set the shutter position based on the input number value, which I could then update from different automations. It was a bit of a learning curve, but the end result was a much cleaner and more flexible setup.

Reflecting on this experience, I’ve come to appreciate how important it is to understand how variables and templates work within Home Assistant scripts. It’s also been a great reminder of the value of the community in troubleshooting and finding creative solutions to challenges. If anyone has tips or alternative approaches for handling dynamic values in scripts, I’d love to hear them!

Happy automating! :rocket: