Solved: How to pass entity state as automation variable for a script

I’m trying to reduce the nuber of similar scripts that multiple devices of a similar type are calling from automations. My idea was to merely pass entity_id of the target device and a state of a input_number, as variables to the script. I have tried several options, but so far I’m ending either with errors ir odd behaviour.

UPDATE: Problem solved. Below is a working example.

The following automation is calling a script, see below.

- alias: "Extend Front Shrubs Timer When Wet"
  trigger:
    - platform: time_pattern
      minutes: '/1'
  condition:
    condition: or
    conditions:
      - condition: template
        value_template: '{{as_timestamp(now().strftime("%Y-%m-%d %H:%M")) > as_timestamp(states.input_datetime.next_run_front_shrubs.state)}}'
      - condition: and
        conditions:
          - condition: template
            value_template: '{{as_timestamp(now().strftime("%Y-%m-%d %H:%M")) == as_timestamp(states.input_datetime.next_run_front_shrubs.state)}}'
          - condition: state
            entity_id: sensor.rain_sensor
            state: 'too wet'
  action:
    - service: script.turn_on
      entity_id: script.update_generic_next_run_timer
      data_template:
        variables:
          states_entity_timedelta_state: "{{states.sensor.time_delta_front_shrubs.state}}"
          entity: "input_datetime.next_run_front_shrubs"

The script is:

update_generic_next_run_timer:
  alias: "Update Generic Next Run Timer"
  sequence:
  - service: input_datetime.set_datetime
    data_template:
      entity_id: "{{entity}}"
      date: >
        {{(as_timestamp(now())+(states_entity_timedelta_state)|int) | timestamp_custom("%Y-%m-%d", true)}}
      time: >
        {{(as_timestamp(now())+(states_entity_timedelta_state)|int) | timestamp_custom("%H:%M:%S", true)}}

Currently, rather than adding 172800 seconds (as the repeat timer states.sensor.time_delta_front_shrubs.state is set for 48hrs), the script runs but instead it keeps adding one minute to the next run time. No square or curly brackets around the variable in the script part solved it.

1 Like

FYI, you can only run 1 script at a time. If you have automations firing this script simultaneously, one will override the other.

You’re right and I’ve come to discover this shortcoming in testing too. However, in real life I keep the irrigation times apart, as they each put considerable demand on water, so much so, that if there are two simultaneous irritations on, you’d be lucky to wash your hands inside the house. :joy:

1 Like