custom-components / pyscript

Pyscript adds rich Python scripting to HASS
Apache License 2.0
874 stars 46 forks source link

Feature Request: time_active as a function #431

Open MizterB opened 1 year ago

MizterB commented 1 year ago

Would it be possible to expose the time_active decorator as a boolean function that can be called inside of other functions?

My example use case is an on/off timer. I'd like to have it trigger at the specified trigger times, but would also like it to trigger on startup, in case the trigger time occurred while HA is offline.

To keep things simple/clean, I'd prefer to have a single timer function, rather than one for "off" and another for "on". I'm thinking something that looks like this.

time_on = "sunset"
time_off = "22:45:00"
@time_trigger("startup", kwargs={"id": "startup"})
@time_trigger(f"once({time_on})", kwargs={"id": "time_on"})
@time_trigger(f"once({time_off})", kwargs={"id": "time_off"})
def my_example(trigger_time=None, id=None):
    if id == "startup":
        # EXAMPLE LOGIC HERE
        if (time_active(f"range({time_on}, {time_off})")):
            light.example.turn_on()
        else:
            light.example.turn_off()
    elif id == "time_on":
        light.example.turn_on()
    elif id == "time_off":
        light.example.turn_off()

Of course, if I'm missing an obvious way to solve this and keep it simple, I'm open to other suggestions as well!