#####################################################
### Author: Christopher H. Taylor                 ###
### Platform: Raspberry Pi2 + PowerSwitch Tail II ###
### Date: 4/25/2015                               ###
#####################################################

#!/usr/bin/python
from time import sleep
import commands
import os.path
import RPi.GPIO as GPIO

# print GPIO.VERSION
GPIO.setmode(GPIO.BCM)
# GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)

# DECLARE GPIO PIN OUTPUT
PIN = 24

date = commands.getoutput('/bin/date');
LOG = "/var/log/connection.log"

if os.path.isfile(LOG) == False:
    commands.getoutput('touch ' + LOG);

fp = open(LOG, "a");
str = date + ' ' + 'CHECKING CONNECTION\n'
fp.write(str);

# TEST MINIMUM OF THREE SITES FOR CONNECTION FAILURE
t1 = commands.getoutput('/usr/bin/curl --connect-timeout 5 -s "http://www.kiwifoto.com/ip.phtml"');
t2 = commands.getoutput('/usr/bin/curl --connect-timeout 5 -s "http://www.google.com/"');
t3 = commands.getoutput('/usr/bin/curl --connect-timeout 5 -s "http://www.microsoft.com/"');

l1 = len(t1);
l2 = len(t2);
l3 = len(t3);

if l1 == 0 and l2 == 0 and l3 == 0:
    GPIO.setup(PIN, GPIO.OUT);

    date = commands.getoutput('date')
    str = date + ' ' + 'FAILURE - RESETTING MODEM\n'
    fp.write(str);

    print "internet connection tests failed...\n";
    print "powering modem off..\n";
    GPIO.output(PIN, False);
    sleep(15);
    print "powering modem on..\n";
    GPIO.output(PIN, True);
    sleep(30);

    # RESET ROUTER NOW
    foo = commands.getoutput('/usr/bin/curl "http://admin:*******@192.168.136.2/apply.cgi" -d "submit_button=Reboot&change_action=&action=Reboot&wait_time=5&rebootmode=1"');

    date = commands.getoutput('date')
    str = date + ' ' + 'RESET COMPLETE\n'
    fp.write(str);
else :
    date = commands.getoutput('date')
    str = date + ' ' + 'CONNECTION GOOD\n'
    fp.write(str);

str = '============================================\n'
fp.write(str);