Python_script to turn lights on and off on a precise schedule

I’m currently working on some automation to make my house spooky for Halloween.

One thing I’m trying to do is make my lights pulsate in time with a soundtrack I’m going to play as kids approach my front door. So I have an automation which starts the sound playing (by triggering a script running on a second Raspberry Pi), and I wanted to time the lights to match the sound. As a result, I wanted my light timings to be somewhat precise (accurate to within a half second or so).

I tried doing this by using a series of light.turn_on and delay commands – but that didn’t work. I found that the delay commands were basically “delay for at least this many seconds” and not precise or repeatable enough.

So I tried writing my first python_script. And quickly found the many limitations of the sandbox. (Are the limitations documented somewhere? I couldn’t find this, and had to resort to trial and error.)

I figured I’d share the trick I eventually came up with, which seems to work:

def sleep_until(seconds, logger):
  global start_time
  while (time.time() - start_time) < seconds:
      time.sleep(0.2)"Slept until {}: {}".format(seconds, time.time()-start_time))

start_time = time.time()

# Now interleave waiting until the right time and turning lights on/off:
sleep_until(2, logger)
sleep_until(4, logger)
sleep_until(5, logger)

FWIW, is there a way of accessing the logger in a function without passing it in as a parameter? Seems like a quirk of the sandbox.

1 Like