DoorsOfDurin/main.py

94 lines
2.8 KiB
Python
Raw Normal View History

2020-06-24 19:28:00 +00:00
# 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
2020-08-03 20:24:03 +00:00
import lock
2020-06-24 19:28:00 +00:00
class DoorLock():
def __init__(self):
# initialize card reader
self.reader = SimpleMFRC522()
self.key = b'Mellon!'
self.key += b' ' * (48 - len(self.key))
2020-06-24 19:28:00 +00:00
def check_authorization(self, reader_id, reader_data):
2020-06-24 19:28:00 +00:00
# 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]
2020-06-24 19:28:00 +00:00
if reader_id == user_card_id:
print("card id match found")
if reader_data.encode() == self.key:
2020-06-24 19:28:00 +00:00
print("user {} with card_id {} authorized".format(name, hex(reader_id)))
return True, db_id
else:
print("incorrect key phrase")
2020-06-24 19:28:00 +00:00
# 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
2020-08-03 20:24:03 +00:00
# not implemented yet
2020-06-24 19:28:00 +00:00
print("Unlocking door!\n\n")
2020-08-03 20:24:03 +00:00
lock.unlock()
2020-06-24 19:28:00 +00:00
def release_the_kraken(self):
# TODO notify that authentication failed
# not implemented yet
print("Release the Kraken!")
def run_authorization(self):
try:
while True:
2020-08-03 20:24:03 +00:00
print("Hold card in front of reader..")
2020-06-24 19:28:00 +00:00
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()
2020-06-24 19:28:00 +00:00
time.sleep(1.5)
finally:
2020-08-03 20:24:03 +00:00
GPIO.cleanup()
2020-06-24 19:28:00 +00:00
if __name__ == "__main__":
# create database with some users
2020-08-03 20:24:03 +00:00
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)
2020-06-24 19:28:00 +00:00
doors_of_durin = DoorLock()
data = bytearray([0]*16)
data = 'Mellon!'
2020-06-24 19:28:00 +00:00
#write_success = doors_of_durin.reader.write(data)
doors_of_durin.run_authorization()
2020-08-03 20:24:03 +00:00
pass