I have a daemon that monitors various things using the GPIO ports. I have used python to write the code for this using the RPi.GPIO module.
I would like to ensure that the daemon is always running, i.e., restart it after a crash and start it when the system boots (crucially before any user logs in -- this Pi runs headless). There is a little flashing LED that tells me its running, but that's not ideal.
I have read about using MONIT for this purpose but I'm having a few issues. My attempts so far have mainly been around this solution:
https://stackoverflow.com/questions/23454344/use-monit-monitor-a-python-program
This is my bash wrapper file, its called /home/pi/UPSalarm/UPSalarm.bash
#!/bin/bash
PIDFILE=/var/run/UPSalarm.pid
case $1 in
start)
#source /home
#Launch script
sudo python /home/pi/UPSAlarm/UPSalarm.py 2>/dev/null &
# store PID value
echo $! > ${PIDFILE}
;;
stop)
kill `cat ${PIDFILE}`
# Proccess killed, now remove PID
rm ${PIDFILE}
;;
*)
echo "usage: scraper {start|stop}" ;;
esac
exit 0`
This is my monit rule
check process UPSalarm with pidfile /var/run/UPSalarm.pid
start = "/home/pi/UPSalarm/UPSalarm start"
stop = "/home/pi/UPSalarm/UPSalarm stop"
I have two problems: firstly, I get the wrong PID number in UPSalarm.pid. I am wondering if I get a PID number for sudo? This is why I have posted the question here; I need sudo because I need access to the GPIO ports. Secondly, it doesn't work. Thirdly, I am not sure what source does in the bash file?
I know monit has great documentation, but a worked example for python really would be helpful, I've been stuck for a good few days.
The following websites were also helpful: https://www.the-hawkes.de/monitor-your-raspberrypi-with-monit.html (for setting up monit) https://mmonit.com/monit/documentation/monit.html
And these two questions are related but don't solve my problem: https://raspberrypi.stackexchange.com/questions/9938/monitoring-a-python-script-running-in-a-screen-session-with-monit How to restart the Python script automatically if it is killed or dies