My Raspberry Pi cameras have been running well for a while now, but I’ve had one camera that seems to be having issues. I did have some issues earlier with two camera and believe it was due to using cheap Micro Center SD cards and having the Wi-Fi monitoring script write to the card every 5 minutes. I used new cards and did not include the Wi-Fi monitoring script. All was well until a couple of weeks ago, when one camera, that is closest to my Wi-Fi router, would not show up in Blue Iris. I unplugged it and plug it in to hard reboot it, but it still would not come back up.
I finally pulled it out to take a look at it but it seemed to work just fine. It may be that the CD Card was not seated properly, but uncertain why it worked then did not work. If and only if the last state and current state are different, will it update the state file and create a log entry. Below is my resulting script. This is much better than my original version. It is easier to view the log and see when the Wi-Fi went down and when it reconnected.
#!/bin/bash
# Shell script to monitor Wi-Fi status and operating conditions
# and attempt Wi-Fi restart if down
IWCONFIG="/usr/sbin/iwconfig wlan0"
# The IP for the server you wish to ping (8.8.8.8 is a public Google DNS server)
SERVER=192.168.1.1
LOGFILE="/var/log/wifi.log"
STATEFILE="/var/log/wifistate.txt"
DATE=`date`
I=$((`cat /sys/class/thermal/thermal_zone0/temp`/100))
TEMP="Temp="$(($I/10))"."$(($I%10))" C"
STATUS=`$IWCONFIG | grep level | awk '{$1=$1};1'`
STATUS+=" "
STATUS+=`$IWCONFIG | grep Rate | awk '{$1=$1};1'`
CURRENTSTATE=""
LASTSTATE=""
if [ -f ${STATEFILE} ]; then
LASTSTATE=$(cat ${STATEFILE})
fi
# Only send two pings, sending output to /dev/null
ping -c2 ${SERVER} > /dev/null
# If the return code from ping ($?) is not 0 (meaning there was an error)
if [ $? = 0 ]
then
CURRENTSTATE="UP"
UPDOWN="\033[32m UP \033[0m"
else
CURRENTSTATE="DOWN"
UPDOWN="\033[31mDOWN \033[0m"
STATUS+=" Attempting wlan0 restart"
# Restart the wireless interface
sh -c 'ifconfig wlan0 down; sleep 5; ifconfig wlan0 up'
fi
if [ "$CURRENTSTATE" != "$LASTSTATE" ]; then
echo -e $CURRENTSTATE > $STATEFILE
echo -e "WiFi @ $DATE: $UPDOWN $TEMP $STATUS" >> ${LOGFILE}
fi
echo -e "WiFi @ $DATE: $UPDOWN $TEMP $STATUS"
# Check daemon
# Name of the daemon to check
DAEMON_NAME="mediamtx"
LOGFILE="/var/log/mediamtx.log"
STATEFILE="/var/log/mediamtxstate.txt"
STATUS=""
CURRENTSTATE=""
LASTSTATE=""
if [ -f ${STATEFILE} ]; then
LASTSTATE=$(cat ${STATEFILE})
fi
# Check if the daemon is running
if pgrep -x "$DAEMON_NAME" > /dev/null; then
CURRENTSTATE="RUNNING"
STATUS="$DAEMON_NAME is running"
else
CURRENTSTATE="NOT RUNNING"
STATUS="$DAEMON_NAME is not running, restarting..."
# Use appropriate command to restart the daemon
sudo systemctl restart "$DAEMON_NAME"
fi
if [ "$CURRENTSTATE" != "$LASTSTATE" ]; then
echo -e $CURRENTSTATE > $STATEFILE
echo -e "MediaMTX @ $DATE: $STATUS" >> ${LOGFILE}
fi
echo -e "MediaMTX @ $DATE: $STATUS"
