Hi,
I use a Raspberry Pi as an internet watchdog but I'm not entirely convinced I have the code right.
This is supposed to check for the presence of a web site, and wait for up to four minutes for a response.
However, I don't think the timeout bit is working correctly. I think that if it can't access the site it's trying to then it errors straight away.
Here's the full script I'm using. I've part pinched it from the internet and tweaked it a bit.
This is the part of the code in question.
Have I got something wrong here, specifically in the timeout bit?
I'm (clearly) not a Python programmer, just someone who finds code and attempts to tweak it!
Thanks for any advice/suggestions.
I use a Raspberry Pi as an internet watchdog but I'm not entirely convinced I have the code right.
This is supposed to check for the presence of a web site, and wait for up to four minutes for a response.
However, I don't think the timeout bit is working correctly. I think that if it can't access the site it's trying to then it errors straight away.
Here's the full script I'm using. I've part pinched it from the internet and tweaked it a bit.
Code:
import urllib2
import RPi.GPIO as GPIO
import time
RELAY = 21 #RELAY PIN, physical pin 40
ALIVE = 20 #LED PIN to flash LED on live internet, physical pin 38
CHECK_EVERY = 10 #Seconds
GPIO.setmode(GPIO.BCM)
GPIO.setup(RELAY, GPIO.OUT)
GPIO.setup(ALIVE, GPIO.OUT)
# Force both outputs low
GPIO.output(RELAY, GPIO.LOW)
GPIO.output(ALIVE, GPIO.LOW)
def flash_ok():
GPIO.output(ALIVE, GPIO.HIGH)
time.sleep(0.2)
GPIO.output(ALIVE, GPIO.LOW)
def internet_on():
try:
response=urllib2.urlopen('https://www.website.com', timeout=240)
flash_ok()
return True
except urllib2.URLError as err: pass
return False
def reboot_router():
print "Rebooting Router"
GPIO.output(RELAY, GPIO.HIGH)
time.sleep(10) #Energise relay for ten seconds
GPIO.output(RELAY, GPIO.LOW)
time.sleep(240) #Wait for four minutes for router to reboot
while True:
if not internet_on():
reboot_router()
time.sleep(CHECK_EVERY)
GPIO.cleanup()
This is the part of the code in question.
Code:
def internet_on():
try:
response=urllib2.urlopen('https://www.website.com', timeout=240)
flash_ok()
return True
except urllib2.URLError as err: pass
return False
I'm (clearly) not a Python programmer, just someone who finds code and attempts to tweak it!
Thanks for any advice/suggestions.