mardi 8 novembre 2016

Python: UnboundLocalError: local variable 'Down' referenced before assignment

I am trying to use a variable DOWN as a flag that I went to set when my internet goes down. Then when internet service returns, I want it to email me a log file (checkfile.txt). However, it seems that no matter how I format or use it, I keep getting this error:

UnboundLocalError: local variable 'Down' referenced before assignment.

Here is the code...I know, it is not the most efficient or artful, but I am trying to teach myself:

import socket 
import RPi.GPIO as GPIO 
import time 
import datetime
import syslog 
PIN = 12 
LED = 23

def is_connected(REMOTE_SERVER):
 try:

      # see if we can resolve the host name -- tells us if there is a DNS listening
      host = socket.gethostbyname(REMOTE_SERVER)
      # connect to the host -- tells us if the host is actually reachable
      s = socket.create_connection((host, 80), 2)
      print ("Successful Test")
      return True
 except:
      pass
 return False 

def ResetRouter():
 GPIO.setwarnings(False)
 GPIO.setmode(GPIO.BCM) #this is changed from 'GPIO.BOARD' on previous version
 GPIO.setup(PIN, GPIO.OUT)
 GPIO.setup(LED, GPIO.OUT)
 GPIO.output(PIN,GPIO.HIGH) # turn on pin - turns off power on AC control
 GPIO.output(LED,GPIO.HIGH)
 print 'Connection down - resetting now ', datetime.datetime.now()
 fout = open ("checkfile.txt","a")
 s=str(datetime.datetime.now())
 fout.writelines ("Internet DOWN at ")
 fout.write(s)
 fout.write (' \n')
 fout.close()   
 time.sleep( 20 ) # sleep for 20 seconds
 GPIO.output(PIN,GPIO.LOW) # turn off pin
 GPIO.output(LED,GPIO.LOW)
 GPIO.cleanup() # cleanup - all pins low - ensures power is on


def main():

 if not (is_connected("www.google.com") and is_connected("www.cnn.com")):
      ResetRouter()
      print 'Resetting router at ',datetime.datetime.now()
      fout = open ("checkfile.txt","a")
      s=str(datetime.datetime.now())
      fout.writelines ("Resetting router at ")
      fout.write(s)
      fout.write (' \n')
      fout.close()
      Down = 1

 else:
      print 'Internet UP as of ',datetime.datetime.now()
      fout = open ("checkfile.txt","a")
      s=str(datetime.datetime.now())
      fout.writelines ("Internet UP at ")
      fout.write(s)
      fout.write (' \n')
      fout.close()
      if Down:
           fout= open("checkfile.txt","a")
           s=str(datetime.datetime.now())
           fout.writelines ("Internet RETURNED TO SERVICE at ")
           fout.write(s)
           fout.write (' \n')
           fout.close()
           Down = 0
if __name__ == "__main__":
 main()

Aucun commentaire:

Enregistrer un commentaire