/app.py
Python | 176 lines | 121 code | 24 blank | 31 comment | 22 complexity | a4147b5e53939a0ffaa8cb7aa49a7049 MD5 | raw file
- #!/usr/bin/env python3
- from threading import Thread
- from multiprocessing import Queue
- from lib.MFRC522.MFRC522 import MFRC522
- from lib.BUZZ.Buzzer import Buzzer
- import time
- import socketserver
- import string
- import logging
- import signal
- logging.basicConfig(filename='/var/log/PCFastRelease.log',
- level=logging.DEBUG,
- format='%(asctime)s %(levelname)s: %(message)s',
- datefmt='%Y-%m-%d %H:%M:%S')
- def end_read(signal,frame=None):
- global continue_loop
- #logging.info("Stoping PCFastRelease")
- print ("Ctrl+C captured, ending read.")
- continue_loop = False
- GPIO.cleanup()
- print ("Shutdown Server")
- #logging.info("Call for Server Shutdown")
- print ("Call for Server Shutdown")
- server.shutdown()
- #time.sleep(3)
- print ("Call for Server Close")
- server.server_close()
- print ("Goodbuy")
- #logging.info("Goodbuy")
- #exit with code.
- if(signal==99):
- exit(10)
- else:
- exit(0)
- def NFCReader():
- global a
- global continue_loop
- LoopCount = 600
- buzzer = Buzzer()
- #play startup sound
- buzzer.play(3)
- ScanResult = None
- MIFAREReader = MFRC522()
- logging.info("Starting NFC reader thred")
- while continue_loop:
- LoopCount = LoopCount + 1
- (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
- if status == MIFAREReader.MI_OK:
- (ScanResult,uid) = MIFAREReader.MFRC522_Anticoll()
- else:
- ScanResult = None
- uid = None
- if ScanResult is None:
- if LoopCount >= 600:
- print("HeartBeat of NFCReader Loop")
- LoopCount = 0
-
- #logging.debug("NoneType returned by scaner no card present")
- elif (ScanResult is not None) and (uid is not None):
- #Now lets make sure that uid is usefull
- if (len(uid) == 5):
- print("Card Number "+str(uid[0])+" "+str(uid[1])+" "+str(uid[2])+" "+str(uid[3])+" and BCC "+str(uid[4]))
- #logging.info("Card Number "+str(uid[0])+" "+str(uid[1])+" "+str(uid[2])+" "+str(uid[3])+" and BCC "+str(uid[4]))
- #convert the card number to 8 digit hex and pad each block with 0 if needed
- uid = hex(uid[0])[2:].zfill(2)+hex(uid[1])[2:].zfill(2)+hex(uid[2])[2:].zfill(2)+hex(uid[3])[2:].zfill(2)
- print("Card Number "+str(uid))
- #logging.info("Card Number "+str(uid))
-
- a = uid
- #None the variables
- ScanResult = None
- uid = None
-
- #Put a sucsess beep here
- buzzer.play(1)
- #debounce for sucsesfull card read.
- time.sleep(4)
- else:
- print("Error uid is not 5 in length")
- buzzer.play(2)
- ScanResult = None
- uid = None
- print ("Shutdown NFC Reader")
- #logging.info("Shutdown NFC Reader")
-
- class MyTCPHandler(socketserver.BaseRequestHandler):
- """
- The request handler class for our server.
- It is instantiated once per connection to the server, and must
- override the handle() method to implement communication to the
- client.
- """
- def setup(self):
- print("{} connected:".format(self.client_address[0]))
- logging.debug("{} connected:".format(self.client_address[0]))
- self.request.sendall(bytes("Welcome to PCFastRelease v0.1\r\n", "utf-8"))
- self.handle()
-
- def handle(self):
- global a
- global continue_loop
- LoopCount = 1500
- self.request.settimeout(.2)
- #we set the value of a to blank so if this was offline we dont spit out a users jobs
- a = None
- while continue_loop:
- continue_loop = continue_loop + 1
- if LoopCount >= 1500:
- print("HeartBeat of SocketServer Loop")
- LoopCount = 0
- #This causes the loop to close connections
- try:
- self.data = self.request.recv(1024)
- except:
- self.data = None
- if self.data is not None:
- print("Data Received "+str(self.data.decode("utf-8")))
- if not self.data.decode("utf-8"):
- print("Finish")
- break
- if a is not None:
- print("Writing to Socket")
- #logging.info("User card detected with id "+str(a))
- self.request.sendall(bytes(a + "\r\n", "utf-8"))
- a = None
- if __name__ == "__main__":
- logging.info("Starting PCFastRelease Server")
- print("Starting PCFastRelease Server")
- HOST = "0.0.0.0"
- PORT = 4800
- a = None
- # Hook the SIGINT
- signal.signal(signal.SIGINT, end_read)
- signal.signal(signal.SIGTERM, end_read)
-
- continue_loop = True
- #start the thred that will look at incomming data from the card reader.
- ThreadNFCReader = Thread(target=NFCReader)
- ThreadNFCReader.start()
- print("NFCReader loop running in thread:", ThreadNFCReader.name)
- # Create the server
- try:
- server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
- except Exception as e:
- print("Error spawning server. Shutdown "+str(e))
- end_read(99)
- server.allow_reuse_address = True
- #start the server thread
- SocketThread = Thread(target=server.serve_forever)
- # Exit the server thread when the main thread terminates
- SocketThread.daemon = True
- try:
- SocketThread.start()
- except Exception as e:
- print("Error spawning Thred. Shutdown "+str(e))
- end_read(99)
- print("Server loop running in thread:", SocketThread.name)