Raspberry Pi – Auto reset with mail notification

SunnyBoyI have had some problems the last couple of months with the Raspberry Pi hanging without me noticing it. I had switched off the daily mails, because I wasn’t reading them anyhow and during the winter, the solar panels do not produce that much power, but it meant that I have had the Raspberry Pi not collect/send data for a couple of weeks once and for a couple of days another time. Not good.

So I wanted the Raspberry Pi to reset itself if it hangs and mail me if it does.
The first part is easy, the second part (the mail) turned out to be more difficult. Enough reason to document it.

You need to have setup mutt first. If you did not do that yet, see this page first.

Auto-reboot
I used the instructions on this page and this page.

Start with:
$ sudo modprobe bcm2708_wdog
$ sudo nano /etc/modules

Add the line “bcm2708_wdog” and save the file.

Install the watchdog deamon:
$ sudo apt-get install watchdog chkconfig
$ chkconfig watchdog on
$ sudo /etc/init.d/watchdog start
$ sudo nano /etc/watchdog.conf

Uncomment the line watchdog-device = /dev/watchdog
Uncomment the line with max-load-1
Safe the file.

Mail notification
Login to the Raspberry Pi using SSH
We will first create the bash file to send the mail:
$ cd /home/pi/bin
$ sudo nano mailIP

Add this in the mailIP file:
#!/bin/sh

mailreciever=YOURMAIL
today=$(date)
my_ip=`ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}'`
my_pi="Blue RaspberryPi has rebooted! "
message="Your Pi has rebooted at $today. Current IP address = $my_ip"
echo $message > message.txt
mutt -s "${my_pi}" ${mailreciever} < message.txt

save the file and make it executable using:
sudo chmod 0755 mailIP

Test the mailIP script first to see if you get a mail!
Now we want to make sure that the script gets run when the Raspberry Pi boots.

Edit /etc/rc.local:
$ sudo nano /etc/rc.local
Add this above the exit 0 line:
$ sudo /home/pi/bin/mailIP &
Make sure the rc.local can be executed:
sudo chmod 0755 /etc/rc.local

I had to put a copy of .muttrc in the /root folder for this to work:
$ sudo bash
# cp /home/pi/.muttrc /root

Testing
There are a number of ways you can test if this works:
$ sudo reboot
This simply reboots the Raspberry Pi. You should receive a mail after a couple of minutes.
Another test is to see if the wathcdog works. If you type:
$ : (){ :|:& };:
It will cause a kernel panic. The Raspberry Pi should recover from this automatically by rebooting and you should get a mail.