Rule for a switch with a selectable timeout

I recently build a rule for switch that is supposed to automtically turn off after a selectable amount of time.
The remaining time should be visible in the UI and the timeout had to be changeable during the countdown.
I am super happy how readable and compact the code got so I thought I’ll share it.

Items

Switch	MySwitch		      "Switch"
Number	MySwitch_Timout       "Timeout [%d min]"
Number	MySwitch_Time_left    "Time left [%d min]"

Rule

from HABApp import Rule
from HABApp.openhab.events import ItemCommandEvent
from HABApp.openhab.items import NumberItem, SwitchItem


class SwitchTimeout(Rule):
    def __init__(self):
        super().__init__()
        
        self.sw = SwitchItem.get_item('MySwitch')
        self.sw.listen_event(self.sw_command, ItemCommandEvent)
        
        self.start = NumberItem.get_item('MySwitch_Timout')
        self.time_left = NumberItem.get_item('MySwitch_Time_left')
        watcher = self.time_left.watch_change(60)
        watcher.listen_event(self.time_left_const)
        
    def time_left_const(self, event):
        if self.time_left <= 0:
            return None
        
        if self.time_left == 1:
            self.sw.off()
            return None
        
        self.time_left.oh_post_update(self.time_left - 1)

    def sw_command(self, event: ItemCommandEvent):
        if event.value == 'ON':
            self.time_left.oh_post_update(self.start)
        else:
            self.time_left.oh_post_update(0)


SwitchTimeout()
2 Likes