ping_test.sh

This script allows to run PING command at regular interval, on a remote Raspberry Pi. The script reports the result of the command through MQTT.

#!/bin/bash
# This script allows to test whether the device has access to Internet
# By doing, at regular interval, a ping on  Google DNS 8.8.8.8
# For communication we use MQTT, sending message to the broker running at bubuoat.mine.nu

TOPIC=purnama/purnama/internet
BROKER='Broker IPADDRESS'
LOCAL='192.168.42.1'
WAN_OK='WAN Ok'
WAN_NOK='Ping failed. Internet connection lost'
# wait 20 seconds to make sure connection is established
sleep 20
while true;
do
my_date=`/bin/date "+%d.%m.%y - %H.%M.%S"`
ping -c 3 8.8.8.8 > /dev/null  # no output on screen 
#my_date=`/bin/date "+%d.%m.%y - %H.%M.%S"`
# test the return value of the last executed command
if [ $? -eq 0 ]  
then 
        echo "# $my_date $WAN_OK" >> /root/ping.log
         mosquitto_pub -p 1883 -h $BROKER -t $TOPIC -m "Up"
         mosquitto_pub -p 1883 -h $LOCAL -t $TOPIC -m "Up"
else 
        echo  "# $my_date $WAN_NOK" >> /root/ping.log
fi
my_date=`/bin/date "+%d.%m.%y - %H.%M.%S"`
ping -c 3 192.168.42.2 > /dev/null  # no output on screen (tries to ping a device inside the WIFI network to check that this network is still up)
#my_date=`/bin/date "+%d.%m.%y - %H.%M.%S"`
# test the return value of the last executed command
if [ $? -eq 0 ]  
then 
        echo "# $my_date Wireless OK!" >> /root/ping.log
         mosquitto_pub -p 1883 -h $BROKER -t $TOPIC -m "Wireless OK"
         mosquitto_pub -p 1883 -h $LOCAL -t $TOPIC -m "Wireless Ok"
else 
        echo  "# $my_date Ping failed. Need to reboot the Raspberry!" >> /root/ping.log
         mosquitto_pub -p 1883 -h $BROKER -t $TOPIC -m "Wifi NOK"
         mosquitto_pub -p 1883 -h $LOCAL -t $TOPIC -m "Wifi NOk"
fi
# wait 600 seconds before next ping
sleep 600
done
exit 0