I use the following code to detect when the wireless network connection has dropped, and to try and bring it back up. It lights an LED on pin 24 if the network is down.
The IP address 192.168.1.1 is the router. It's pinged 15 times, and if it errors more than 10 it's classed as faulty
The code was originally used for network throughput and error rates so there might be a bit of extracode.
Code: Select all
def checknetworking():
PingIPAddress = "192.168.1.1"
TTLTotal = 0
FailedCount=0
FaultyNetwork=1
print (str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) + " Checking Network")
while (FaultyNetwork > 0):
for x in range(0, 15):
cmd="ping -c 1 "+ PingIPAddress +" | grep 'time=' | cut -d ' ' -f 7 | cut -d ' ' -f1"
TTL = run_cmd(cmd)
TTL = TTL.replace("\n", "")
TTL = TTL.replace("time=", "")
if (TTL == ""):
TTL = "0"
FailedCount = FailedCount + 1
print (str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) + " Network Failed Count = " + str(FailedCount))
if (FailedCount < 10):
FaultyNetwork = 0
else:
print (str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) + " Network connection down! Attempting reconnection. Fault count = " + str(FaultyNetwork))
GPIO.output(24, True)
pdsWriteLog("No Networking" + str(FaultyNetwork) )
run_cmd("ifup --force wlan0")
sleep(10)
FailedCount = 0
#####################################################################