Automation Trigger from a python script

So I have been trying this automation for my door sensor and I am able to do it on a python script running on my raspberry pi with if statements etc, however doing the same in HA is proving difficult.

What I am trying to achieve is the following: when the door is opened and close rightaway, the lights should turn on. When the door is opened again for the second time and straightaway closed the lights should turn off.

This is what I have in my python script:

x = y = 0
     if door == opened:
        x += 1
    if door == closed:
        y += 1
    if x == 1 and y == 1:
        switch.lights_on
    if y == 2:
        x = y = 0
        switch.lights_off

Can the above be done in HA? or if there is a better way of doing it?

It can be done using a simple automation:

alias: 'door used as a toggle switch'
trigger:
  - platform: state
    entity_id: binary_sensor.your_door
    from: 'on'
    to: 'off'
condition:
  - condition: template
    value_template: "{{ now().timestamp() - states.binary_sensor.your_door.last_changed.timestamp() < 3 }}"
action:
  - service: light.toggle
    entity_id: light.your_light

How it works

  • It triggers whenever the door is closed.
  • It checks if the time difference between now and the last time when the door’s state changed (when it was opened) is less than 3 seconds.
  • If the condition is true, the light’s state is toggled.

That is a good solution thanks. So for the automation to work the door has to be opened within 3 seconds before closing it again? and the lights would turn on after 3 seconds?

It meets your requirement to open then promptly close the door. After opening the door, it must be closed within 3 seconds to serve as a trigger. If you leave the door open for more than 3 seconds and then close it, it will not execute the automation’s action.

I’ve tested it and confirmed it works. Try it for yourself.

1 Like

Thanks alot for your help

Also can the same be applied if I wanted the automation to be triggered as soon as the door was opened?

This will toggle the light every time the door is opened:

alias: 'door used as a toggle switch'
trigger:
  - platform: state
    entity_id: binary_sensor.your_door
    to: 'on'
action:
  - service: light.toggle
    entity_id: light.your_light

OK great makes sense. Thanks again