Commit 11568606 authored by Neil Alvin Hernandez's avatar Neil Alvin Hernandez

Initial commit

parents
import RPi.GPIO as GPIO
import sqlite3 as lite
import requests
import time
import datetime
import readline
import os
import sys
dbdir = "/home/pi/dbs/dbcopy.db"
tstile = 18
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(tstile,GPIO.OUT)
GPIO.output(tstile,GPIO.LOW)
def latchhigh():
GPIO.cleanup(tstile)
time.sleep(1)
GPIO.setup(tstile,GPIO.OUT)
GPIO.output(tstile,GPIO.HIGH)
def latchlow():
GPIO.setup(tstile,GPIO.OUT)
GPIO.output(tstile,GPIO.LOW)
def checkpass(passes):
val = len(passes.rstrip())
if val == 0 or passes == "None":
return True
else:
return False
def verifypass(category,passes,timenow):
condb = None
passes = passes.replace("\n","x")
passes = passes.replace(" ",",")
passes = passes.replace("xx",",,,")
passes = passes.replace(",,,",",")
passes = "".join(passes).split(',')
condb = lite.connect(dbdir)
cursor = condb.cursor()
for items in passes:
cursor.execute("SELECT * FROM passes where pass_code = ?",(items,))
rows = cursor.fetchall()
for row in rows:
v_from = datetime.datetime.strptime(str(row[2]),"%Y-%m-%d %H:%M:%S")
v_to = datetime.datetime.strptime(str(row[3]),"%Y-%m-%d %H:%M:%S")
if timenow >= v_from and timenow <= v_to:
if categorywithpass(passes,category,timenow):
return True
else:
return False
else:
return False
condb.close()
def categorywithpass(passes,category,timenow):
condb = None
condb = lite.connect(dbdir)
cursor = condb.cursor()
for items in passes:
cursor.execute("SELECT * FROM allowed_category where pass_code = ?",(items,))
rows = cursor.fetchall()
for row in rows:
a_cat = row[0]
dt_from = datetime.datetime.strptime(str(row[2]),"%Y-%m-%d %H:%M:%S")
dt_to = datetime.datetime.strptime(str(row[3]),"%Y-%m-%d %H:%M:%S")
if category == a_cat:
if timenow >= dt_from and timenow <= dt_to:
return True
else:
return False
def categorynopass(category,timenow):
ondb = None
condb = lite.connect(dbdir)
cursor = condb.cursor()
cursor.execute("SELECT * FROM allowed_category where category = ?",(category,))
rows = cursor.fetchall()
for row in rows:
a_cat = row[0]
dt_from = datetime.datetime.strptime(str(row[2]),"%Y-%m-%d %H:%M:%S")
dt_to = datetime.datetime.strptime(str(row[3]),"%Y-%m-%d %H:%M:%S")
if category == a_cat:
if timenow >= dt_from and timenow <= dt_to:
return True
else:
return False
def savetransact(v_id,timenow):
logtype = "IN"
is_upload = 0
condb=lite.connect(dbdir)
cursor = condb.cursor()
cursor.execute("INSERT into transactions(visitor_idnum,timestamp,logtype,is_upload) VALUES(?,?,?,?)",[qrcode,timenow,logtype,is_upload])
condb.commit()
condb.close()
def verifyqrcode():
global timenow,qrcode
condb = None
qrcode = raw_input("Awaiting Barcode:")
scannedqr = str(qrcode)
capqrcode = scannedqr.upper()
finddrop = capqrcode.find('DROP')
findtruncate = capqrcode.find('TRUNCATE')
finddelete = capqrcode.find('DELETE')
timenow = datetime.datetime.now()
try:
if finddrop > -1 or findtruncate > -1 or finddelete > -1 or qrcode == "":
print ("Not allowed access!!")
else:
condb = lite.connect(dbdir)
cursor = condb.cursor()
cursor.execute("SELECT * FROM visitor WHERE qrcode = ?",(qrcode,))
rows = cursor.fetchall()
for row in rows:
idnum = qrcode
wlistblist = str(row[8]).upper()
category = str(row[2])
passes = str(row[9])
if wlistblist == "WHITELISTED":
print ("WHITELISTED!!")
latchhigh()
savetransact(qrcode,timenow)
elif wlistblist == "BLACKLISTED":
print ("BLACKLISTED!!")
latchlow()
else:
if checkpass(passes) is False:
if verifypass(category,passes,timenow):
if categorywithpass(passes,category,timenow):
latchhigh()
savetransact(qrcode,timenow)
else:
latchlow()
else:
latchlow()
else:
if categorynopass(category,timenow):
latchhigh()
savetransact(qrcode,timenow)
else:
latchlow()
except lite.Error, e:
if condb:
condb.rollback()
print ("Error %s", e.args[0])
finally:
if condb:
condb.close()
#Main function execution
while True:
verifyqrcode()
import requests
from websocket import create_connection
import sqlite3 as lite
import sys
import os
import json
import ast
dbdir = "/home/pi/dbs/dbcopy.db"
REALTIMESERVER_IP = '172.16.200.252:7099'
ROOM_NAME = 'TurnstileEvents'
macAddress = os.popen("cat /sys/class/net/eth0/address").read()
macAddress = macAddress.replace('\n', '').replace('\r', '')
SETTINGS_UPDATE_BASE_URL = "http://172.16.200.252:8010/api/turnstile/settings/"+str(macAddress)+"/"
DB_BASE_URL = "http://172.16.200.252:8010/api/visitors/?last_id="
API_BASE_URL = ""
test_dev_api = "http://devapi.interpol.oneberrysystem.com/api/visitors/?last_id="
user = "admin"
pword = "password123"
######Function for acquiring visitor latest ID for API_BASE_URL post request######
def dbquery():
condb = None
try:
condb = lite.connect("dbcopy.db")
with condb:
cursor = condb.cursor()
for item in cursor.execute("SELECT * FROM visitor WHERE id = (SELECT MAX(id) FROM visitor)"):
idval = item[0]
return idval
else:
idval = 0
return 0
condb.commit()
except lite.Error, e:
if condb:
condb.rollback()
print("Error %s", e.args[0])
sys.exit(1)
finally:
if condb:
condb.close()
def acquiredata():
print(API_BASE_URL)
print ("=================================================================================================================")
print ("==========================================Database syncing data==================================================")
print ("=================================================================================================================")
req = requests.get(DB_BASE_URL, auth=(user, pword), timeout=10000)
i = req.json()
for idx,data in enumerate(i):
idnum = (i[idx]['id'])
company_name = (i[idx]['company_name'])
category = (i[idx]['category'])
visitor_id = (i[idx]['visitor_id'])
first_name = (i[idx]['first_name'])
last_name = (i[idx]['last_name'])
email = (i[idx]['email'])
qrcode = (i[idx]['qrcode'])
white_black_listed = (i[idx]['white_black_listed'])
passes = (i[idx]['passes'])
active_badge = (int(i[idx]['active_badge']))
try:
condb = lite.connect("dbcopy.db")
with condb:
cursor = condb.cursor()
cursor.execute("INSERT or REPLACE INTO visitor VALUES (?,?,?,?,?,?,?,?,?,?,?)",[idnum,company_name,category,visitor_id,first_name,last_name,email,qrcode,white_black_listed,passes,active_badge])
condb.commit()
except lite.Error, e:
if condb:
condb.rollback()
print ("Error %s", e.args[0])
sys.exit(1)
finally:
if condb:
condb.close()
def updatesettings():
print (SETTINGS_UPDATE_BASE_URL)
condb = None
upreq = requests.get(SETTINGS_UPDATE_BASE_URL,auth=(user, pword), timeout=3)
updata = upreq.json()
turnstile_id = updata["turnstile_id"]
turnstile_name = updata["turnstile_name"]
description = updata["description"]
turnstile_mac = updata["mac_address"]
turnstile_ip = updata["ip_address"]
server_time = updata["server_time"]
server_time = server_time.replace("T"," ")
print(server_time)
passes = updata["passes"]
allowed_category = updata["category"]
os.system("sudo timedatectl set-time '"+str(server_time)+"'")
try:
condb = lite.connect(dbdir)
cursor = condb.cursor()
cursor.execute("DELETE from settings")
cursor.execute("DELETE from allowed_category")
cursor.execute("DELETE from passes")
cursor.execute("REPLACE INTO settings VALUES (?,?,?,?,?)",[turnstile_id,turnstile_name,description,turnstile_mac,turnstile_ip])
for idx,data in enumerate(passes):
pass_name = updata["passes"][idx]["pass_name"]
code = updata["passes"][idx]["code"]
valid_from = updata["passes"][idx]["valid_from"]
valid_from = valid_from.replace("T"," ")
valid_to = updata["passes"][idx]["valid_to"]
valid_to = valid_to.replace("T"," ")
cursor.execute("REPLACE INTO passes VALUES (?,?,?,?)",[pass_name,code,valid_from,valid_to])
for idx,data in enumerate(allowed_category):
category = updata["category"][idx]["turnstile_category__name"]
pass_code = updata["category"][idx]["pass_code"]
category = str(category).upper()
cat_valid_from = updata["category"][idx]["valid_from"]
cat_valid_from = cat_valid_from.replace("T"," ")
cat_valid_to = updata["category"][idx]["valid_to"]
cat_valid_to = cat_valid_to.replace("T"," ")
cursor.execute("REPLACE INTO allowed_category VALUES (?,?,?,?)",[category,pass_code,cat_valid_from,cat_valid_to])
condb.commit()
print("DONE!!!")
except lite.Error, e:
if condb:
condb.rollback()
print ("Error %s", e.args[0])
finally:
if condb:
condb.close()
print("Updating turnstile settings, passes and allowed_category settings....")
updatesettings()
print("DONE!!!")
print("\nDatabase syncing running on background....")
ws = create_connection("ws://"+REALTIMESERVER_IP+"/ws/realtimeserver/"+ROOM_NAME+"/")
while True:
try:
condb = None
result = ws.recv()
json_data = json.loads(result)
events = json_data["events"]
if events == "TURNSTILE NEW DATA":
API_BASE_URL = "http://172.16.200.252:8010/api/visitors/?last_id="+str(dbquery())+""
test_dev_api = "http://devapi.interpol.oneberrysystem.com/api/visitors/?last_id="+str(dbquery())+""
acquiredata()
print ("=================================================================================================================")
print ("============================================Done syncing new data================================================")
print ("=================================================================================================================")
elif events == "REBOOT " + macAddress:
os.system("sudo reboot now")
elif events == "REBOOT ALL":
os.system("sudo reboot now")
else:
converted_data = json_data['events'].decode('utf-8')
convert_to = json.loads(converted_data)
visitor_id = convert_to["visitor_id"]
active_badge = int(convert_to["active_badge"])
category = str(convert_to["category_id"]).upper()
passes = convert_to["passes"]
white_black_listed = convert_to["white_black_listed"]
condb = lite.connect(dbdir)
cursor = condb.cursor()
cursor.execute("UPDATE visitor SET category = ?, white_black_listed = ?, passes = ?, active_badge = ? WHERE visitor_id = ?",(category,white_black_listed,passes,active_badge,visitor_id))
condb.commit()
condb.close()
except Exception as e:
print ("Error "+str(e))
ws.close()
ws = create_connection("ws://"+REALTIMESERVER_IP+"/ws/realtimeserver/"+ROOM_NAME+"/")
pass
acquiredata()
\ No newline at end of file
import RPi.GPIO as GPIO
import sqlite3 as lite
import requests
import time
import datetime
import readline
import os
import sys
dbdir = "/home/pi/dbs/dbcopy.db"
tstile = 18
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(tstile,GPIO.OUT)
GPIO.output(tstile,GPIO.LOW)
def latchhigh():
GPIO.cleanup(tstile)
time.sleep(1)
GPIO.setup(tstile,GPIO.OUT)
GPIO.output(tstile,GPIO.HIGH)
def latchlow():
GPIO.setup(tstile,GPIO.OUT)
GPIO.output(tstile,GPIO.LOW)
def checkpass(passes):
val = len(passes.rstrip())
if val == 0 or passes == "None":
return True
else:
return False
def verifypass(category,passes,timenow):
condb = None
passes = passes.replace("\n","x")
passes = passes.replace(" ",",")
passes = passes.replace("xx",",,,")
passes = passes.replace(",,,",",")
passes = "".join(passes).split(',')
condb = lite.connect(dbdir)
cursor = condb.cursor()
for items in passes:
cursor.execute("SELECT * FROM passes where pass_code = ?",(items,))
rows = cursor.fetchall()
for row in rows:
v_from = datetime.datetime.strptime(str(row[2]),"%Y-%m-%d %H:%M:%S")
v_to = datetime.datetime.strptime(str(row[3]),"%Y-%m-%d %H:%M:%S")
if timenow >= v_from and timenow <= v_to:
if categorywithpass(passes,category,timenow):
return True
else:
return False
else:
return False
condb.close()
def categorywithpass(passes,category,timenow):
condb = None
condb = lite.connect(dbdir)
cursor = condb.cursor()
for items in passes:
cursor.execute("SELECT * FROM allowed_category where pass_code = ?",(items,))
rows = cursor.fetchall()
for row in rows:
a_cat = row[0]
dt_from = datetime.datetime.strptime(str(row[2]),"%Y-%m-%d %H:%M:%S")
dt_to = datetime.datetime.strptime(str(row[3]),"%Y-%m-%d %H:%M:%S")
if category == a_cat:
if timenow >= dt_from and timenow <= dt_to:
return True
else:
return False
def categorynopass(category,timenow):
ondb = None
condb = lite.connect(dbdir)
cursor = condb.cursor()
cursor.execute("SELECT * FROM allowed_category where category = ?",(category,))
rows = cursor.fetchall()
for row in rows:
a_cat = row[0]
dt_from = datetime.datetime.strptime(str(row[2]),"%Y-%m-%d %H:%M:%S")
dt_to = datetime.datetime.strptime(str(row[3]),"%Y-%m-%d %H:%M:%S")
if category == a_cat:
if timenow >= dt_from and timenow <= dt_to:
return True
def savetransact(v_id,timenow):
logtype = "IN"
is_upload = 0
condb=lite.connect(dbdir)
cursor = condb.cursor()
cursor.execute("INSERT into transactions(visitor_idnum,timestamp,logtype,is_upload) VALUES(?,?,?,?)",[qrcode,timenow,logtype,is_upload])
condb.commit()
condb.close()
def verifyqrcode():
global timenow,qrcode
condb = None
qrcode = raw_input("Awaiting Barcode:")
scannedqr = str(qrcode)
capqrcode = scannedqr.upper()
finddrop = capqrcode.find('DROP')
findtruncate = capqrcode.find('TRUNCATE')
finddelete = capqrcode.find('DELETE')
timenow = datetime.datetime.now()
try:
if finddrop > -1 or findtruncate > -1 or finddelete > -1 or qrcode == "":
print ("Not allowed access!!")
else:
condb = lite.connect(dbdir)
cursor = condb.cursor()
cursor.execute("SELECT * FROM visitor WHERE qrcode = ?",(qrcode,))
rows = cursor.fetchall()
for row in rows:
idnum = qrcode
wlistblist = str(row[8]).upper()
category = str(row[2])
passes = str(row[9])
active_badge = row[10]
if active_badge == 1:
if wlistblist == "WHITELISTED":
latchhigh()
savetransact(qrcode,timenow)
elif wlistblist == "BLACKLISTED":
latchlow()
else:
if categorynopass(category,timenow):
latchhigh()
savetransact(qrcode,timenow)
except lite.Error, e:
if condb:
condb.rollback()
print ("Error %s", e.args[0])
finally:
if condb:
condb.close()
#Main function execution
while True:
verifyqrcode()
\ No newline at end of file
import RPi.GPIO as GPIO
import sqlite3 as lite
import requests
import time
import datetime
import readline
import os
import sys
dbdir = "/home/pi/dbs/dbcopy.db"
tstile = 18
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(tstile,GPIO.OUT)
GPIO.output(tstile,GPIO.LOW)
def latchhigh():
GPIO.cleanup(tstile)
time.sleep(1)
GPIO.setup(tstile,GPIO.OUT)
GPIO.output(tstile,GPIO.HIGH)
def latchlow():
GPIO.setup(tstile,GPIO.OUT)
GPIO.output(tstile,GPIO.LOW)
def checkpass(passes):
val = len(passes.rstrip())
if val == 0 or passes == "None":
return True
else:
return False
def verifypass(category,passes,timenow):
condb = None
passes = passes.replace("\n","x")
passes = passes.replace(" ",",")
passes = passes.replace("xx",",,,")
passes = passes.replace(",,,",",")
passes = "".join(passes).split(',')
condb = lite.connect(dbdir)
cursor = condb.cursor()
for items in passes:
cursor.execute("SELECT * FROM passes where pass_code = ?",(items,))
rows = cursor.fetchall()
for row in rows:
v_from = datetime.datetime.strptime(str(row[2]),"%Y-%m-%d %H:%M:%S")
v_to = datetime.datetime.strptime(str(row[3]),"%Y-%m-%d %H:%M:%S")
if timenow >= v_from and timenow <= v_to:
if categorywithpass(passes,category,timenow):
return True
condb.close()
def categorywithpass(passes,category,timenow):
condb = None
condb = lite.connect(dbdir)
cursor = condb.cursor()
for items in passes:
cursor.execute("SELECT * FROM allowed_category where pass_code = ?",(items,))
rows = cursor.fetchall()
for row in rows:
a_cat = row[0]
dt_from = datetime.datetime.strptime(str(row[2]),"%Y-%m-%d %H:%M:%S")
dt_to = datetime.datetime.strptime(str(row[3]),"%Y-%m-%d %H:%M:%S")
if category == a_cat:
if timenow >= dt_from and timenow <= dt_to:
return True
def categorynopass(category,timenow):
ondb = None
condb = lite.connect(dbdir)
cursor = condb.cursor()
cursor.execute("SELECT * FROM allowed_category where category = ?",(category,))
rows = cursor.fetchall()
for row in rows:
a_cat = row[0]
dt_from = datetime.datetime.strptime(str(row[2]),"%Y-%m-%d %H:%M:%S")
dt_to = datetime.datetime.strptime(str(row[3]),"%Y-%m-%d %H:%M:%S")
if category == a_cat:
if timenow >= dt_from and timenow <= dt_to:
return True
def savetransact(v_id,timenow):
logtype = "IN"
is_upload = 0
condb=lite.connect(dbdir)
cursor = condb.cursor()
cursor.execute("INSERT into transactions(visitor_idnum,timestamp,logtype,is_upload) VALUES(?,?,?,?)",[qrcode,timenow,logtype,is_upload])
condb.commit()
condb.close()
def verifyqrcode():
global timenow,qrcode
condb = None
qrcode = raw_input("Awaiting Barcode:")
scannedqr = str(qrcode)
capqrcode = scannedqr.upper()
finddrop = capqrcode.find('DROP')
findtruncate = capqrcode.find('TRUNCATE')
finddelete = capqrcode.find('DELETE')
timenow = datetime.datetime.now()
try:
if finddrop > -1 or findtruncate > -1 or finddelete > -1 or qrcode == "":
print ("Not allowed access!!")
else:
condb = lite.connect(dbdir)
cursor = condb.cursor()
cursor.execute("SELECT * FROM visitor WHERE qrcode = ?",(qrcode,))
rows = cursor.fetchall()
for row in rows:
idnum = qrcode
wlistblist = str(row[8]).upper()
category = str(row[2])
passes = str(row[9])
active_badge = row[10]
if active_badge == 1:
if wlistblist == "WHITELISTED":
latchhigh()
savetransact(qrcode,timenow)
elif wlistblist == "BLACKLISTED":
latchlow()
else:
if checkpass(passes) is False:
if verifypass(category,passes,timenow):
latchhigh()
savetransact(qrcode,timenow)
else:
latchlow()
else:
if categorynopass(category,timenow):
latchhigh()
savetransact(qrcode,timenow)
else:
latchlow()
except lite.Error, e:
if condb:
condb.rollback()
print ("Error %s", e.args[0])
finally:
if condb:
condb.close()
#Main function execution
while True:
verifyqrcode()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment