koldfront

Turning lights on and off automatically #jukebox #automation

๐Ÿ•˜๏ธŽ - 2021-04-28

A while back I set up a system that triggered a door bell and a rotary light when Motion detected somebody at a gate.

This was straightforward to implement, as usb controlled relays are readily available, and a command line utility to control it, usbrelay, is only an "apt install usbrelay" away.

After setting that up, I started thinking about where I could use such relays at home.

The first idea was to automatically turn on and off the two lamps that are connected to the same power strip as my jukebox and stereo. If I turn the system on during the day, I have to turn off the lights, and when it gets dark, I have to turn them on again. Very work, much tedious.

This was quite easily solved - after writing a tiny pair of commands, sunrise and sunset, I could write a script that, depending on the time and the sun, switches the lights on or off accordingly:

#!/bin/sh

now=$(date +%T)
sunrise=$(sunrise)
sunset=$(sunset)

wanted=0
if expr "$now" \>= "$sunset" > /dev/null; then
    echo "After sunset, on"
    wanted=1
fi
if expr "$now" \<= "$sunrise" > /dev/null; then
    echo "Before sunrise, on"
    wanted=1
fi
if [ $wanted = 0 ]; then
    echo "Daytime, off"
fi

usbrelay 0_1=$wanted 2> /dev/null

Another shell script runs on boot - after ntpdate has set the time on the jukebox (it's a Raspberry Pi and doesn't have a battery) - from my crontab. It runs the handle_lights script above, to make sure the lights are in the correct state, and then it queues up the script to be run again at the next sunrise and sunset:

#!/bin/sh

handle_lights > /dev/null
echo handle_lights | at -M $(sunrise | sed 's/:..$//') + 2 minutes 2> /dev/null
echo handle_lights | at -M $(sunset | sed 's/:..$//') + 2 minutes 2> /dev/null

Originally I tried using systemd timers instead of at(1), because they disappear after a reboot, and I wouldn't have to worry about multiple runs when the jukebox is rebooted, but the timers kept firing early - like 10 seconds early when I specified AccuracySec=1s, so I gave up on that and I am using at now.

Add comment

To avoid spam many websites make you fill out a CAPTCHA, or log in via an account at a corporation such as Twitter, Facebook, Google or even Microsoft GitHub.

I have chosen to use a more old school method of spam prevention.

To post a comment here, you need to:

ยน Such as Thunderbird, Pan, slrn, tin or Gnus (part of Emacs).

Or, you can fill in this form:

+=