import RPi.GPIO as GPIO #This program must be executed as root. from subprocess import check_output from re import search import csv import datetime import threading from time import sleep #Define file name here! fileName = '/home/pi/Desktop/db.csv' #Define timeout here! #timeoutSecs = 5 * 60 #5 minutes timeoutSecs = 5 #Define number of alarm seconds here! cycles = 5 def readIWList(): storage = [] #now = datetime.datetime.strptime(str(datetime.datetime.utcnow()), "%Y-%m-%d %H:%M:%S.%f") now = datetime.datetime.utcnow() output = check_output("iwlist wlan0 scan |egrep ' - Address: '", shell=True) #Dependency: IWList for i in output.splitlines(True): arrayElement = search('([0-9A-F]{2}([:-]|$)){6}', i).group() #RegExp to obtain the MAC Address storage.append([arrayElement, now, 0]) #Dirty bit defaults to clean return storage def writeFile(storage, file): with open (file, 'wb') as db: dbfile = csv.writer(db, delimiter='\t', quotechar='"') for j in storage: dbfile.writerow(j); def readFile(file): storage = [] with open(file, 'rb') as db: dbfile = csv.reader(db, delimiter='\t', quotechar='"') for dbrow in dbfile: then = datetime.datetime.strptime(dbrow[1], "%Y-%m-%d %H:%M:%S.%f") #Date reconversion storage.append([dbrow[0], then, dbrow[2]]) return storage def compareTime(time): now = datetime.datetime.utcnow() #Timeout is defined, in seconds, at the beginning of the file. timeout = datetime.timedelta(seconds = timeoutSecs) val = 0 if ( abs(now - time) > timeout ): #print "Timeout: " + str(abs(now - time)) return 1 return val def buttonPressed(): #print "Button pressed." storage = readIWList() file = readFile(fileName) for x in file: for y in storage: if x[0] == y[0]: file.remove(x) #print "Removed " + x[0] + " from the list." for y in storage: file.append(y) writeFile(file, fileName) def cyclicProcess(): file = readFile(fileName) for x in file: if int(x[2]) == 0: if compareTime(x[1]) == 1: x[2] = 1 #Mark dirty bit, timeout achieved #print "Timeout achieved for " + str(x[0]) isAlarmTriggered = False storage = readIWList() for x in file: for y in storage: if x[0] == y[0]: if x[2] == 1: isAlarmTriggered = True file.remove(x) #print "Removed " + x[0] + " from the list." if isAlarmTriggered: buzzAlarm() #print "Alarm activated!" writeFile(file, fileName) threading.Timer(timeoutSecs, cyclicProcess,()).start() def buzzAlarm(): for n in xrange(0, cycles): GPIO.output(18, 1) sleep(0.5) GPIO.output(18, 0) sleep(0.5) #def main(): GPIO.setmode(GPIO.BCM) GPIO.setup(24, GPIO.IN) GPIO.setup(18, GPIO.OUT) threading.Timer(timeoutSecs, cyclicProcess,()).start() try: while True: sleep(0.1) if GPIO.input(24): buttonPressed() except: GPIO.cleanup() #Resets the GPIO ports.