PageRenderTime 33ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/app.py

https://gitlab.com/JonW/PCFastRelease-NanoPi
Python | 176 lines | 121 code | 24 blank | 31 comment | 22 complexity | a4147b5e53939a0ffaa8cb7aa49a7049 MD5 | raw file
  1. #!/usr/bin/env python3
  2. from threading import Thread
  3. from multiprocessing import Queue
  4. from lib.MFRC522.MFRC522 import MFRC522
  5. from lib.BUZZ.Buzzer import Buzzer
  6. import time
  7. import socketserver
  8. import string
  9. import logging
  10. import signal
  11. logging.basicConfig(filename='/var/log/PCFastRelease.log',
  12. level=logging.DEBUG,
  13. format='%(asctime)s %(levelname)s: %(message)s',
  14. datefmt='%Y-%m-%d %H:%M:%S')
  15. def end_read(signal,frame=None):
  16. global continue_loop
  17. #logging.info("Stoping PCFastRelease")
  18. print ("Ctrl+C captured, ending read.")
  19. continue_loop = False
  20. GPIO.cleanup()
  21. print ("Shutdown Server")
  22. #logging.info("Call for Server Shutdown")
  23. print ("Call for Server Shutdown")
  24. server.shutdown()
  25. #time.sleep(3)
  26. print ("Call for Server Close")
  27. server.server_close()
  28. print ("Goodbuy")
  29. #logging.info("Goodbuy")
  30. #exit with code.
  31. if(signal==99):
  32. exit(10)
  33. else:
  34. exit(0)
  35. def NFCReader():
  36. global a
  37. global continue_loop
  38. LoopCount = 600
  39. buzzer = Buzzer()
  40. #play startup sound
  41. buzzer.play(3)
  42. ScanResult = None
  43. MIFAREReader = MFRC522()
  44. logging.info("Starting NFC reader thred")
  45. while continue_loop:
  46. LoopCount = LoopCount + 1
  47. (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
  48. if status == MIFAREReader.MI_OK:
  49. (ScanResult,uid) = MIFAREReader.MFRC522_Anticoll()
  50. else:
  51. ScanResult = None
  52. uid = None
  53. if ScanResult is None:
  54. if LoopCount >= 600:
  55. print("HeartBeat of NFCReader Loop")
  56. LoopCount = 0
  57. #logging.debug("NoneType returned by scaner no card present")
  58. elif (ScanResult is not None) and (uid is not None):
  59. #Now lets make sure that uid is usefull
  60. if (len(uid) == 5):
  61. print("Card Number "+str(uid[0])+" "+str(uid[1])+" "+str(uid[2])+" "+str(uid[3])+" and BCC "+str(uid[4]))
  62. #logging.info("Card Number "+str(uid[0])+" "+str(uid[1])+" "+str(uid[2])+" "+str(uid[3])+" and BCC "+str(uid[4]))
  63. #convert the card number to 8 digit hex and pad each block with 0 if needed
  64. 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)
  65. print("Card Number "+str(uid))
  66. #logging.info("Card Number "+str(uid))
  67. a = uid
  68. #None the variables
  69. ScanResult = None
  70. uid = None
  71. #Put a sucsess beep here
  72. buzzer.play(1)
  73. #debounce for sucsesfull card read.
  74. time.sleep(4)
  75. else:
  76. print("Error uid is not 5 in length")
  77. buzzer.play(2)
  78. ScanResult = None
  79. uid = None
  80. print ("Shutdown NFC Reader")
  81. #logging.info("Shutdown NFC Reader")
  82. class MyTCPHandler(socketserver.BaseRequestHandler):
  83. """
  84. The request handler class for our server.
  85. It is instantiated once per connection to the server, and must
  86. override the handle() method to implement communication to the
  87. client.
  88. """
  89. def setup(self):
  90. print("{} connected:".format(self.client_address[0]))
  91. logging.debug("{} connected:".format(self.client_address[0]))
  92. self.request.sendall(bytes("Welcome to PCFastRelease v0.1\r\n", "utf-8"))
  93. self.handle()
  94. def handle(self):
  95. global a
  96. global continue_loop
  97. LoopCount = 1500
  98. self.request.settimeout(.2)
  99. #we set the value of a to blank so if this was offline we dont spit out a users jobs
  100. a = None
  101. while continue_loop:
  102. continue_loop = continue_loop + 1
  103. if LoopCount >= 1500:
  104. print("HeartBeat of SocketServer Loop")
  105. LoopCount = 0
  106. #This causes the loop to close connections
  107. try:
  108. self.data = self.request.recv(1024)
  109. except:
  110. self.data = None
  111. if self.data is not None:
  112. print("Data Received "+str(self.data.decode("utf-8")))
  113. if not self.data.decode("utf-8"):
  114. print("Finish")
  115. break
  116. if a is not None:
  117. print("Writing to Socket")
  118. #logging.info("User card detected with id "+str(a))
  119. self.request.sendall(bytes(a + "\r\n", "utf-8"))
  120. a = None
  121. if __name__ == "__main__":
  122. logging.info("Starting PCFastRelease Server")
  123. print("Starting PCFastRelease Server")
  124. HOST = "0.0.0.0"
  125. PORT = 4800
  126. a = None
  127. # Hook the SIGINT
  128. signal.signal(signal.SIGINT, end_read)
  129. signal.signal(signal.SIGTERM, end_read)
  130. continue_loop = True
  131. #start the thred that will look at incomming data from the card reader.
  132. ThreadNFCReader = Thread(target=NFCReader)
  133. ThreadNFCReader.start()
  134. print("NFCReader loop running in thread:", ThreadNFCReader.name)
  135. # Create the server
  136. try:
  137. server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
  138. except Exception as e:
  139. print("Error spawning server. Shutdown "+str(e))
  140. end_read(99)
  141. server.allow_reuse_address = True
  142. #start the server thread
  143. SocketThread = Thread(target=server.serve_forever)
  144. # Exit the server thread when the main thread terminates
  145. SocketThread.daemon = True
  146. try:
  147. SocketThread.start()
  148. except Exception as e:
  149. print("Error spawning Thred. Shutdown "+str(e))
  150. end_read(99)
  151. print("Server loop running in thread:", SocketThread.name)