Now comes the simple part. After linking everything up, we start writing the code. For this project I also used Flask to write back-end. This caused many problems, but when you understand what happened, these problems are actually quiet to fix.
Let's look at the core of the program and read with the RFID reader. The library I used makes this really easy (maybe that's why it's called SimpleMFRC522;))
Just import and read like this:
from mfrc522 import SimpleMFRC522 reader = SimpleMFRC522 () id, test = reader.read ()
This causes a problem because "reader.read ()" is just a loop that checks if an RFID tag is close to the reader caused it to block the code. Nothing else can be processed while this loop is running. How do we fix this?
I created a class that imports "SimpleMFRC522" and makes a thread out of it.
from mfrc522 import SimpleMFRC522
# init stuff
# This is what is called when doing RFID (). start () self):
reader = SimpleMFRC522 ()
id, text = reader.read ()
RFID (). start ()
Now it goes into its own thread without blocking the rest of the code. If you want to read more about how the thread works, I strongly recommend that you read this Wikipedia article, it helped me understand the concept better.
Unlock the lock
Now that we can read the tags, we need to validate the owner of the tag, so we not only let everyone open our lock. This was pretty simple, just extract UserId which is on the tag and check it in our database.
def validate_user (remote_id):
user = db.get_data (& # 39; SELECT authorized, first_name from willy.User where user_id =% s & # 39 ;, remote_id, True)
unless user: raise IndexError
return ['authorized'] user ['first_name']
raise exception  @staticmethod
def validate_tag (remote_id):
return AuthUser.validate_user (remote_id)
in addition to IndexError:
Unlocking with web app was a bit more difficult because an authentication system is needed to log in a user.
And once they are logged in, they must send a JWT (JSON Web Token) with each request they send to make sure they do not change things that only admin should be able to.
def authenticate ():
token = request.headers.get ("Authorization") if not the token: return reply (exception = ApiExceptions.banned, socket = True) .send () token = token.split (& # 39; & # 39;)  payload = AuthUser.validate_jwt (token) on payload: pressure (payload ['id']) pressure (session) Try: # about session [payload['id']]: # current_user = AuthUser (** session [payload['id']]) # return f (* args, ** kwargs) auth_user = AuthUser.find_user_by_id (payload ['id']) about auth_user: current_user = auth_user return f (* args, ** kwargs) Other: return reply (exception = ApiExceptions.banned, socket = True) .send () except IndexError: return reply (exception = ApiExceptions.email_not_found) .send () except for ex: print ("error", e) return reply (exception = ApiExceptions.default) .send () otherwise: return answer (exception = ApiExceptions.banned, socket = True) .send ()