You will need a timer
# Example configuration.yaml entry
timer:
sonoff:
duration: '02:00:00'
If you want this switch to only ever be on for 2 hours no matter how it turns on, that is easy.
If you want this to only do the 2 hour timer if you push the button…but leave it on always if you turn it on by other means, that is a bit harder. You would have to find a way to detect how the switch changed state (button vs …)
I’m only going to show the first scenario for now.
- Create an automation that watches when the switch turns on, then start the timer. Then create an automation to handle the timer event.
# In automations
- alias: Sonoff Timer Start
trigger:
platform: state
entity_id: switch.sonoff_id
action:
# Start the timer if switch turns on.
# Cancel timer if it turns off before timer expired.
- service_template: >-
{% if trigger.to_state.state == 'on' %}
timer.start
{% else %}
timer.cancel
{% endif %}
data:
entity_id: timer.sonoff
- alias: Sonoff Timer Expire
trigger:
- platform: event
event_type: timer.finished
event_data:
entity_id: timer.sonoff
action:
- service: switch.turn_off
entity_id: switch.sonoff_id
For lovelace, just add the timer as an entity card. You should be able to pause this timer and the switch won’t turn off until the timer expires.
Making it so this only happens if you push the button…I’m not exactly sure the best way. I’m not sure how you have the sonoff integrated with Home Assistant.