cfpi_watchdog Service


I have a Raspberry Pi Zero W running a project that involves taking pictures of "Raffy" the cat-who-owns-me, triggered by motion as he (Raffy) enters the kitchen through the cat flap. (much, much, more on that topic to come, later...).

I was originally making use of the linux package: watchdog daemon

sudo apt-get watchdog

This service once installed allows you to monitor the up/down status of an interface or a ping request to an ip address and if they are down, after a certain period of time, reboot the system, Raspberry Pi in this scenario.

This is useful, if the Pi drops off my 2.4 GHz WLAN and fails to rejoin within 60 seconds, the Pi reboots and we should be good to carry on.

I did not find the functionality to execute a script after "fail condition A" and if this did not remediate the problem perform a restart at "fail condition B".

TLDR; The Point! Get to the point please

I wrote a python script to perform the same functionality (more or less).


#!/usr/bin/env python3

import os
import datetime
from time import sleep
from syslog import syslog

def set_wlan0_down_up():
    os.system('sudo ip link set wlan0 down')
    os.system('sudo ip link set wlan0 up')

address = ''
action1_attempt_count = 4
action2_attempt_count = 8

failed_pings = 0

while True:
    response = os.system('ping -c 1 ' + address)
#    print(response)
    if response != 0:
        failed_pings += 1
        syslog(f"ping {address} failure: {failed_pings}")
    if failed_pings == action1_attempt_count:
        syslog(f"4x pings {address} failed, bouncing wlan0")
    if failed_pings == action2_attempt_count:
        syslog(f"8x pings {address} failed, rebooting CatFlapPi")
    if response == 0 and failed_pings != 0:
        syslog(f"ping {address} success, after {failed_pings} failures, " \
            "reset failed ping count to 0")
        failed_pings = 0
  • This script pings an address, "" in this example
  • every 30 seconds
  • If 4x pings fail, the wlan0 interface will be set down
  • 5 seconds later it will be set up
  • hopefully this restores the ability for the Pi to ping the address
  • if not, and pings continue to fail, after 8 consecutive failures
  • the Pi will reboot

I set this script up as a systemd service.

Description=diy Watchdog service for resetting wi-fi and rebooting CatFlapPi

ExecStart=/usr/bin/python3 /home/pi/cat_flap_pi/


My notes on how to setup the python script as a service:
Raspbian Service creation from python script