I’m wondering how to turn off light after a delay, at the same time as using the constrain_xxx_time?
Let me take the MotionLights sample and configure it like this:
Downstairs Night Light:
module: motion_lights
class: MotionLights
constrain_start_time: '20:00:00'
constrain_end_time: '04:29:59'
sensor: binary_sensor.downstairs_sensor_26_0
delay: '300'
entity_off: scene.downstairs_off
entity_on: scene.downstairs_dim
If we have motion at 21:00:00, the light will be turned on and the light_off callback will be scheduled to run 300 seconds later, everything is great.
The relevant motion function in the MotionLights class looks like this:
def motion(self, entity, attribute, old, new, kwargs):
if new == "on":
if "entity_on" in self.args:
self.log("Motion detected: turning {} on".format(self.args["entity_on"]))
self.turn_on(self.args["entity_on"])
if "delay" in self.args:
delay = self.args["delay"]
else:
delay = 60
self.cancel_timer(self.handle)
self.handle = self.run_in(self.light_off, delay)
But what about if we have motion 200 seconds before the constrain_end_time? If I understood the documentation correctly, the light will be turned on as before but the scheduled light_off callback will never be executed since it is after the constrain_end_time and the light will stay on…
I could scheduled a light_off one second before the constrain_end_time:
constrain_end = datetime.datetime.strptime(self.args["constrain_end_time"], '%H:%M:%S').time()
off_time = datetime.datetime.combine(datetime.date.today(), constrain_end)
# We need to run before constrain_end_time so let us decrement the time a bit
off_time -= datetime.timedelta(seconds=1)
try:
self.run_at(self.pond_off, off_time)
except ValueError:
# We get a ValueError if start time is in the past, so add a day
off_time += datetime.timedelta(days=1)
self.run_at(self.pond_off, off_time)
But, do I really need to add the above code to all my Apps that use both timer and constrain_xxx_time? And I guess I still have a fraction of a second window left where it could fail?
Any suggestions are welcome…