WTH Scripts can only handle strings as parameters and have no "evaluate" function possible

I try to write a generic script to pass a value to a device by modbus.write_register.
The parameter should be the value that are written to the device.
I now can call the script with a fix value: this is working!

  - action: script.my_script_with_parameter_value_a
    data:
      value_a: 12

Now I try to call the script to set the actual value of an entity: this is not working!

  - action: script.my_script_with_parameter_value_a
    data:
      value_a: states('input_number.my_number_entity')

or

  - action: script.my_script_with_parameter_value_a
    data:
      value_a: {{ states('input_number.my_number_entity') }}

This is not working: I cannot evaluate the parameter even at the script side and also not at the calling side … :frowning:

→ An ‘eval’ or ‘evaluation’ function would be necessary, to evaluate/render a given string.

more details:

You need to quote single line templates.

  - action: script.my_script_with_parameter_value_a
    data:
      value_a: "{{ states('input_number.my_number_entity') }}"
1 Like

This is a bit above my pay grade, but if the parameter is a number don’t you need to add float or int when you use states etc. Which is what you’re asking for.

states('sensor.my_number_entity') | float(0)

or

states('sensor.my_number_entity') | int

Hi Tom, THANKS, This works!
Before testing again, I was quite sure that I also try this before
maybe I have another writing error in this test I do before … (?).

1 Like

Hi Jack, thanks for your hint.
Passing the value input to ‘int’ was done in the script itself: that worked fine.

No, there’s a miss conception here.

In order to use a state as a number, integer, or boolean, you need to specify that for use inside the template.

I.e. "{{ states(...) | float(0) + 1 }}"

If you’re just returning the state from a template, you do not need | float. because you aren’t perform math with that inside the template. After a template renders a value, it will always be a string. However Home assistant does a fancy little thing after the template resolves and before it puts the value in a field/variable. It takes the response and attempts to assign a type to it. So when the value goes into the field/variable, it’s properly typed.

e.g. if sensor.abc has a state of "4". The template "{{ states('sensor.abc') }}" will resolve as "4" (a string), but then it’s placed into the field or variable as 4 because HA identified it as a number.

This allows you to do things like:

field: "{{ states('sensor.abc') }}"
field2: "{{ field + 1 }}"

without running into typing issues.

TLDR:

field: "{{ states('sensor.abc') | float }}"

and

field: "{{ states('sensor.abc') | float(0) }}"

and

field: "{{ states('sensor.abc') }}"

all will yield a number to field.

2 Likes