DoorsOfDurin/main.py

94 lines
2.8 KiB
Python

# Setting up raspi for card reader
# https://pimylifeup.com/raspberry-pi-rfid-rc522/
#
from database import *
import time
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
import lock
class DoorLock():
def __init__(self):
# initialize card reader
self.reader = SimpleMFRC522()
self.key = b'Mellon!'
self.key += b' ' * (48 - len(self.key))
def check_authorization(self, reader_id, reader_data):
# open database
conn = create_connection(database)
# check if id is in the database
with conn:
users = select_all_users(conn)
for user in users:
db_id = user[0]
name = user[1]
user_card_id = user[2]
if reader_id == user_card_id:
print("card id match found")
if reader_data.encode() == self.key:
print("user {} with card_id {} authorized".format(name, hex(reader_id)))
return True, db_id
else:
print("incorrect key phrase")
# if no match was found in the database: deny entry
print("You shall not pass!")
print("could not authorize card_id {}".format(reader_id))
return False, None
def unlock_door(self):
# TODO send command to open door lock
# not implemented yet
print("Unlocking door!\n\n")
lock.unlock()
def release_the_kraken(self):
# TODO notify that authentication failed
# not implemented yet
print("Release the Kraken!")
def run_authorization(self):
try:
while True:
print("Hold card in front of reader..")
uid, data = self.reader.read()
print("card read: \n uid = {}\ndata = {}\n".format(hex(uid), data))
authorized, db_id = self.check_authorization(uid, data)
if authorized:
conn = create_connection(database)
register_access(conn, db_id)
self.unlock_door()
else:
print("authentication failed")
self.release_the_kraken()
time.sleep(1.5)
finally:
GPIO.cleanup()
if __name__ == "__main__":
# create database with some users
conn = setup_db()
with conn:
create_user(conn, 'Simon', 141405954844, 0, str(datetime.utcnow()), str(datetime.utcnow()))
create_user(conn, 'Valentin', 154921302, 0, str(datetime.utcnow()), str(datetime.utcnow()))
users = select_all_users(conn)
doors_of_durin = DoorLock()
data = bytearray([0]*16)
data = 'Mellon!'
#write_success = doors_of_durin.reader.write(data)
doors_of_durin.run_authorization()
pass