Skip to content

Instantly share code, notes, and snippets.

@xioustic xioustic/ping_alert.sh
Last active Aug 26, 2018

Embed
What would you like to do?
#!/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
You can’t perform that action at this time.