Blueprints with Pyscript

Do you want to use the new Blueprints feature, but still prefer writing your logic in pyscript?

@service to the rescue!

Here’s a pyscript and the matching blueprint to perform the “Motion Activated Lights” blueprint included with Home Assistant.

Blueprint:

blueprint:
  name: Motion-activated Light with Pyscript
  description: Turn on a light when motion is detected with Pyscript.
  domain: automation
  # source_url: https://github.com/home-assistant/core/blob/c3d8b1323cad863221731f36f226c92d8f44cfd8/homeassistant/components/automation/blueprints/motion_light.yaml
  input:
    motion_entity:
      name: Motion Sensor
      selector:
        entity:
          domain: binary_sensor
          device_class: motion
    light_target:
      name: Light
      selector:
        target:
          entity:
            domain: light
    no_motion_wait:
      name: Wait time
      description: Time to leave the light on after last motion is detected.
      default: 120
      selector:
        number:
          min: 0
          max: 3600
          unit_of_measurement: seconds

# If motion is detected within the delay,
# we restart the script.
mode: restart
max_exceeded: silent

trigger:
  platform: state
  entity_id: !input motion_entity
  from: "off"
  to: "on"

action:
  - service: pyscript.blueprint_motion_activated_light
    data:
      light_target: !input light_target
      no_motion_wait: !input no_motion_wait
      motion_entity: !input motion_entity


Pyscript:

@service
def blueprint_motion_activated_light(light_target, motion_entity, no_motion_wait):
    # Make sure this service call only runs once per light_target
    service_hash = f'blueprint_motion_activated_light_{hash(repr(sorted(light_target.items())))}'
    task.unique(service_hash)

    # Perform the automation
    light.turn_on(**light_target)
    task.wait_until(state_trigger=f"{motion_entity} == 'off'", state_hold=int(no_motion_wait))
    light.turn_off(**light_target)
5 Likes

Hey @swiftlyfalling. Thanks for his example. Very cool!

Been struggling with something similar and hoping maybe you have a pointer.
I’m looking to handle all my motion sensors logic in pyscript without a blueprint but having trouble figuring out the decorator to use that will fire for any “binary_sensor” event.

What I’m looking to do is shown here but using switches.

I can’t seem to figure out a generic catch-all for the motion sensors.
Any pointers? Thanks!