Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from __future__ import print_function
- import hashlib
- import MFRC522
- import mysql.connector as mariadb
- import RPi.GPIO as gpio
- import signal
- import sys
- import time
- # Database variables
- connection = None
- cursor = None
- DB_USER = "****" # Omitted
- DB_PASS = "*****" # Omitted
- DB_NAME = "****************" # Omitted
- # RFID-Reader Variable
- MIFAREReader = None
- # Defining keypad constants
- matrix = [["1", "2", "3", "A"],
- ["4", "5", "6", "B"],
- ["7", "8", "9", "C"],
- ["*", "0", "#", "D"]]
- # No GPIO numbering because MFRC522 uses BCM
- columns = [32, 36, 38, 40]
- rows = [12, 16, 18, 11]
- # Lockout variables
- FailedCount = 0
- PenaltyTime = 0
- TerminalLocked = False
- class bc:
- # Console color constants
- PINK = '\033[95m'
- BLUE = '\033[94m'
- GREEN = '\033[92m'
- YELLOW = '\033[93m'
- RED = '\033[91m'
- WHITE = '\033[0m'
- BOLD = '\033[1m'
- UNDERLINE = '\033[4m'
- def getKey():
- # Returns pressed key or nothing
- for j in range(len(columns)):
- gpio.output(columns[j], 0)
- for i in range(len(rows)):
- if gpio.input(rows[i]) == 0:
- while gpio.input(rows[i]) == 0:
- pass
- time.sleep(0.2)
- return matrix[i][j]
- gpio.output(columns[j], 1)
- return False
- # Cleaning up and exiting
- def over():
- cursor.close()
- connection.close()
- gpio.cleanup()
- sys.exit()
- # CTRL-C handler
- def signal_handler(sig, frame):
- print("\nCtrl-C has been pressed. Quitting...")
- over()
- # Calls log procedure and exits
- def log_access(args):
- # Call procedure and commit
- cursor.callproc("log_access", args)
- connection.commit()
- # Quit if last argument is true
- if args[3]:
- over()
- # Access status output
- def access_msg(msg, success):
- if success:
- print("{}\nAccess granted{}".format(bc.GREEN, bc.WHITE))
- else:
- print("{}\nAccess denied{}".format(bc.RED, bc.WHITE))
- print(msg)
- def failhandler():
- global FailedCount
- global PenaltyTime
- global TerminalLocked
- # Increment failed count and penaltytime
- FailedCount = FailedCount + 1
- PenaltyTime = PenaltyTime + 5
- # Check how many attempts failed so far
- if FailedCount > 2:
- print("Too many failed attempts, terminal is locked")
- print("Please ask an administrator to unlock")
- TerminalLocked = True
- else:
- print("Please try again in {} seconds".format(PenaltyTime))
- time.sleep(PenaltyTime)
- print("Now you can try again")
- def init():
- global cursor
- global connection
- global MIFAREReader
- # Initiate RFID-Reader Library
- MIFAREReader = MFRC522.MFRC522()
- # Activating GPIO outputs for keypad
- for i in range(4):
- gpio.setup(columns[i], gpio.OUT)
- gpio.output(columns[i], 1)
- gpio.setup(rows[i], gpio.IN, pull_up_down=gpio.PUD_UP)
- # Connecting to database and creating cursor object
- connection = mariadb.connect(
- user=DB_USER, password=DB_PASS, database=DB_NAME)
- cursor = connection.cursor()
- # Registering CTRL-C handler
- signal.signal(signal.SIGINT, signal_handler)
- def md5encode(in_string):
- m = hashlib.md5()
- m.update(in_string)
- return m.hexdigest()
- # Initialize script
- init()
- # Retrieves rooms into list and prints them to console
- cursor.execute("SELECT idRaum, bezeichnung FROM raum ORDER BY idRaum")
- rooms = cursor.fetchall()
- while True:
- while True:
- # Ask user for a room
- print("Which room do you want to enter? ")
- for room in rooms:
- print("{} - {}".format(room[0], room[1]))
- in_raum = ""
- while True:
- # Retrieve keypress
- lastKey = getKey()
- # If a key has been pressed
- if lastKey:
- if lastKey == "*":
- # An asterisk exits the script
- over()
- if lastKey == "#":
- # A pound finishes the entry
- break
- else:
- # All other keys append to the entry
- in_raum = in_raum + lastKey
- sys.stdout.write(lastKey)
- sys.stdout.flush()
- # Evaluate if users chosen room exists
- cursor.execute("SELECT NULL FROM raum WHERE idRaum=%s", (in_raum,))
- cursor.fetchone()
- if cursor.rowcount == -1:
- print("There is no such room!")
- else:
- break
- # Retrieve room using list comprehension
- room = [r[1] for r in rooms if r[0] == int(in_raum)][0]
- print("Entering room: {}".format(room))
- sys.stdout.write("Enter keycode or scan your card: ")
- sys.stdout.flush()
- in_keycode = ""
- while True:
- # Retrieve latest keypad-key
- lastKey = getKey()
- # If any key has been pressed
- if lastKey:
- if lastKey == "*":
- # Delay probably no longer needed
- # Needs testing
- # time.sleep(0.2)
- break
- elif lastKey == "#":
- # If '#' has been pressed (input finished)
- if TerminalLocked:
- print("Terminal is locked")
- else:
- in_keycode = md5encode(in_keycode)
- # Check if keypad-entry is enabled for chosen room
- cursor.execute("""SELECT NULL FROM raum
- WHERE sicherheitslevel = 1
- AND idraum=%s;""", (in_raum,))
- cursor.fetchone()
- if cursor.rowcount == -1:
- access_msg("Only Administrators may enter this room", False)
- # Log failed attempt
- log_access([in_raum, in_keycode, None, False])
- else:
- # Check if code exists in database
- cursor.execute("SELECT NULL FROM keycode WHERE `code`=%s",
- (in_keycode,))
- cursor.fetchone()
- if cursor.rowcount == -1:
- access_msg("Wrong keycode!", False)
- # Log failed attempt
- log_access([in_raum, in_keycode, None, False])
- failhandler()
- else:
- # Retrieve employee info
- cursor.execute("""SELECT CONCAT(m.vorname, ' ', m.nachname)
- FROM mitarbeiter m INNER JOIN keycode k
- ON m.idkeycode = k.idkeycode
- AND k.`code`=%s;""", (in_keycode,))
- access_msg("Welcome, {}".format(cursor.fetchone()[0]),
- True)
- # Log successful attempt
- log_access([in_raum, in_keycode, None, True])
- in_keycode = ""
- else:
- # A number has been pressed
- # Output asterisk to console
- sys.stdout.write('*')
- sys.stdout.flush()
- # Append the new number to the keycode string
- in_keycode = in_keycode + lastKey
- # Delay probably no longer needed
- # Needs testing
- # time.sleep(0.2)
- # Prepare RFID-Scanner for reading
- status = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
- (status, uid) = MIFAREReader.MFRC522_Anticoll()
- if status == MIFAREReader.MI_OK:
- # This is the default key
- key = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
- # Select the tag
- MIFAREReader.MFRC522_SelectTag(uid)
- # Authenticate using block 8, the default key and the UID
- status = MIFAREReader.MFRC522_Auth(
- MIFAREReader.PICC_AUTHENT1A, 8, key, uid)
- if status == MIFAREReader.MI_OK:
- # Read Block 8 of RFID into variable
- card_content = MIFAREReader.MFRC522_Read(8)
- # Remove zero padded bytes from string
- # card_content = card_content.split(b'\0', 1)[0]
- card_content = card_content.partition(b'\0')[0]
- # Hash the RFID
- card_content = md5encode(card_content)
- MIFAREReader.MFRC522_StopCrypto1()
- # Search for card in database
- cursor.execute("SELECT NULL FROM transponder WHERE rfid=%s",
- (card_content,))
- cursor.fetchone()
- if cursor.rowcount == -1:
- if TerminalLocked:
- print("Terminal is locked")
- else:
- access_msg("This card is not registered in the system!",
- False)
- # Log failed attempt
- log_access([in_raum, None, card_content, False])
- failhandler()
- else:
- # Retrieve employee info
- cursor.execute("""SELECT CONCAT(m.vorname, ' ', m.nachname)
- FROM mitarbeiter m INNER JOIN transponder t
- ON m.idTransponder = t.idTransponder
- WHERE t.rfid=%s;""", (card_content,))
- access_msg("Welcome, {}".format(cursor.fetchone()[0]), True)
- if TerminalLocked:
- print("You have unlocked the terminal for the technicians")
- TerminalLocked = False
- # Log successful attempt
- log_access([in_raum, None, card_content, True])
- over()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement