Passing variables in automation/scripts

With some examples found I made an automation to do:

  1. When motion is detected
  2. Turn on light
  3. When there is no motion for 30 seconds
  4. Turn off light

Below is the script. But I was wondering how can I make the script part generic, so I could reuse the script for my lights in different hallways. Is it possible to pass the binary_sensor used for motion and the light as a parameter/variable to the scripts?

  • alias: “Turn on hall lights when there is movement”
    trigger:
    • platform: state
      entity_id: binary_sensor.bg_to_sensor_sensor_35_0
      state: ‘on’
      action:
      service: homeassistant.turn_on
      entity_id: script.timed_lamp

timed_lamp:
alias: “Turn on light and set timer”
sequence:
# Cancel ev. old timers
- service: script.turn_off
data:
entity_id: script.timer_off
- service: homeassistant.turn_on
data:
entity_id: switch.bg_to_light_switch_7_0
# Set new timer
- service: script.turn_on
data:
entity_id: script.timer_off

timer_off:
alias: “Turn off light after 30 seconds”
sequence:
- delay:
seconds: 30
- service_template: >
{%- if not is_state(“binary_sensor.bg_to_sensor_sensor_35_0”, ‘off’) -%}
script.turn_on
{% else %}
homeassistant.turn_off
{% endif %}
data_template:
entity_id: >
{%- if not is_state(“binary_sensor.bg_to_sensor_sensor_35_0”, ‘off’) -%}
script.timer_off_restart
{% else %}
switch.bg_to_light_switch_7_0
{% endif %}

timer_off_restart:
alias: “Turn off light after 1 minutes (restart)”
sequence:
# Cancel current script
- service: script.turn_off
data:
entity_id: script.timer_off
# Set new timer
- service: script.turn_on
data:
entity_id: script.timer_off

I don’t know how to do this in yaml, but appdaemon makes it very easy, if you are willing to use Python to do your automations, rather than yaml.

I haven’t done much in python, but also don’t have much experience with yaml :slight_smile:

Appdeamon seems to do what I want. I will take a look at. Thank you