Skip to content

Instantly share code, notes, and snippets.

@xioustic
Last active August 26, 2018 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xioustic/3993d370fea409231b82ed9db7460ec0 to your computer and use it in GitHub Desktop.
Save xioustic/3993d370fea409231b82ed9db7460ec0 to your computer and use it in GitHub Desktop.
#!/bin/bash
# requires 'sox' package for 'play'
# alarm parameters
ALARM_DURATION=.8
SINE_LOW=300
SINE_HIGH=3000
# target IP to watch
IP=192.168.86.119
# time to wait for ping success (seconds)
PING_TIMEOUT=1
# time to wait between attempts (seconds)
WAIT_TIME=2
# how long before we consider the ip departed
SEEN_THRESHOLD_SECS=20
# initial globals
LAST_SEEN=0
PRESENT=100
# https://stackoverflow.com/questions/51473733/convert-seconds-to-days-hour-min-sec
convertsecs2dhms () {
# use $((...)) for arithmetic
d=$((${1}/(60*60*24)))
h=$(((${1}%(60*60*24))/(60*60)))
m=$(((${1}%(60*60))/60))
s=$((${1}%60))
echo -n ${d}d ${h}h ${m}m ${s}s
}
sound_alarm_arrive() {
play --no-show-progress --null --channels 1 synth $ALARM_DURATION sine ${SINE_LOW}-${SINE_HIGH}
}
sound_alarm_left() {
play --no-show-progress --null --channels 1 synth $ALARM_DURATION sine ${SINE_HIGH}-${SINE_LOW}
}
while true; do
# ping test
timeout $PING_TIMEOUT ping -c 1 $IP > /dev/null
PING_RESULT=$?
if [ $PING_RESULT -eq 0 ]; then
# successful ping
LAST_SEEN=$(date +%s)
if [ $PRESENT -eq 100 ]; then
echo initially present
PRESENT=1
fi
elif [ $PRESENT -eq 100 ]; then
echo initially away
PRESENT=0
fi
# calculate seconds since last seen
TIME_SINCE_LAST_SEEN=$(expr $(date +%s) - $LAST_SEEN)
PRETTY_TIME_SINCE_LAST_SEEN=$(convertsecs2dhms $TIME_SINCE_LAST_SEEN)
#echo $PRETTY_TIME_SINCE_LAST_SEEN
echo $(date) \($IP\): Last Seen ${PRETTY_TIME_SINCE_LAST_SEEN} ago
if [ $TIME_SINCE_LAST_SEEN -gt $SEEN_THRESHOLD_SECS ] && [ $PRESENT -eq 1 ]; then
# we think they're home but we haven't seen then beyond threshold
echo Sounding alarm. they just left
sound_alarm_left
PRESENT=0
fi
# if time since last seen is under threshold and current state is not present, we sound alarm
if [ $TIME_SINCE_LAST_SEEN -lt $SEEN_THRESHOLD_SECS ] && [ $PRESENT -eq 0 ]; then
echo Sounding alarm, they just showed up
sound_alarm_arrive
PRESENT=1
fi
sleep $WAIT_TIME
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment