This script allows to detect under voltage (on a Raspberry Pi) and report it via MQTT.
#!/bin/bash
#This script allows to detect whether there is a Power issue on the Raspberry Pi.
TOPIC=purnama/purnama/power
BROKER='Broker IPADDRESS'
LOCAL='192.168.42.1'
POWERFILE='test_power.txt'
NB_OCCURENCES='nb_failed.txt'
CLEAN_FAIL='fail.txt'
# wait 20 seconds to make sure connection is established
sleep 5
while true;
do
rm $POWERFILE
rm $NB_OCCURENCES
rm $CLEAN_FAIL
#echo "Files have been removed!"
my_date=`/bin/date "+%d.%m.%y - %H.%M.%S"`
#try to find if any under voltage is detected
dmesg | grep 'Under-voltage' > $POWERFILE
# reads the number of line of test_power.txt
wc -l $POWERFILE > $NB_OCCURENCES
#reads the 1st line of the file
FIRST_LINE=$(head -n 1 $NB_OCCURENCES)
echo $FIRST_LINE | sed 's_inet__' | sed -e 's/^[[:space:]]*//' > $NB_OCCURENCES
#echo $NB_OCCURENCES
# copy POWER_FAIL into a file
FAILED=$(head -n 1 $NB_OCCURENCES)
# removes any character after the first 'Space' encountered
echo "${FAILED%% *}" > $CLEAN_FAIL
# reads the first line of CLEAN_IP file
clean_fail=$(head -n 1 $CLEAN_FAIL)
#echo $clean_fail
if [ $clean_fail -gt 0 ]
then
echo "There is a voltage problem!"
mosquitto_pub -p 1883 -h $BROKER -t $TOPIC -m "Low"
mosquitto_pub -p 1883 -h $LOCAL -t $TOPIC -m "Low"
else
mosquitto_pub -p 1883 -h $BROKER -t $TOPIC -m "Ok"
mosquitto_pub -p 1883 -h $LOCAL -t $TOPIC -m "Ok"
fi
# wait 600 seconds before next ping
sleep 60
done
exit 0