Advertisement
Guest User

Verleih.py

a guest
Jan 11th, 2016
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.79 KB | None | 0 0
  1. #!/usr/bin/python2
  2. # -*- coding: utf-8 -*-
  3. #
  4. # ACHTUNG: Script ist fuer python2
  5. #
  6. # Starts tornado and Socket for Reading/Writing <-> WebInterface
  7. #
  8. # DONT use CTRL+Z to terminate script, else Port is blocked
  9. #
  10. ###
  11. from __future__ import print_function
  12. from subprocess import Popen
  13. import threading, time, sys, os.path
  14. try:
  15.     import SocketServer as socketserver
  16. except ImportError:
  17.     import socketserver
  18. try:
  19.     import cymysql
  20. except ImportError:
  21.     print("ERROR: You must install cymysql Module: sudo apt-get install python-pip && sudo pip install cymysql")
  22.     exit()
  23.  
  24. #-------------------------------------------------------------------
  25. DEBUG = True
  26. #DEBUG = False
  27.  
  28. HID_device = '/dev/hidraw0'
  29. HID_Script = 'barcode.py'
  30.  
  31. SocketHost = "0.0.0.0"
  32. SocketPort = 7060
  33.  
  34. WebSocket_Script = 'websocket.py'
  35.  
  36. # Specify Settings for MySQL
  37. mysqlHost = 'localhost'
  38. mysqlPort = '3306'
  39. mysqlLogin = 'root'
  40. mysqlPass = 'raspberry'
  41. mysqlENABLE = True
  42. #mysqlENABLE = False
  43. #-------------------------------------------------------------------
  44.  
  45. # thread docu: http://www.tutorialspoint.com/python/python_multithreading.htm
  46. # socketserver docu: https://docs.python.org/2/library/socketserver.html
  47. # tornado & serial docu: http://forums.lantronix.com/showthread.php?p=3131
  48. # psutil: https://github.com/giampaolo/psutil
  49.  
  50. #-------------------------------------------------------------------
  51. # Dictionary docu: http://www.tutorialspoint.com/python/python_dictionary.htm
  52. dictionary = {}
  53. dictionary['processing'] = None
  54. dictionary['HID_process'] = None
  55. dictionary['WS_process'] = None
  56. currentTools = {};
  57. #-------------------------------------------------------------------
  58.  
  59.  
  60. try:
  61.     DEBUG
  62. except NameError:
  63.     DEBUG = False
  64.  
  65. if DEBUG:
  66.     print("Enabling DEBUG mode!")
  67. else:
  68.     print("Disabling DEBUG mode!")
  69.  
  70.  
  71. def printD(message):
  72.     if DEBUG:
  73.         print(message)
  74.  
  75. def signal_handler(signal, frame):
  76.     print('Script Interrupted! (Control-C)')
  77.     kill_subProcesses()
  78.     sys.exit()
  79.        
  80. #http://www.gossamer-threads.com/lists/python/python/375364
  81. def awk_it(instring,index,delimiter=" "):
  82.     try:
  83.         return [instring,instring.split(delimiter)[index-1]][max(0,min(1,index))]
  84.     except:
  85.         return ""
  86.  
  87. def check_pid(pid):        
  88.     """ Check For the existence of a unix pid. """
  89.     if os.path.exists("/proc/%d"%pid):
  90.         return True
  91.     else:
  92.         return False
  93.  
  94.        
  95. def TimedProcessCheck():
  96.     global timedCheck
  97.     pid1, pid2 = (dictionary['HID_process'].pid, dictionary['WS_process'].pid)
  98.     if check_pid(pid1) == False:
  99.         dictionary['HID_process'] = Popen('python '+ HID_Script +' '+ HID_device, shell=True)
  100.     if check_pid(pid2) == False:
  101.         dictionary['WS_process'] = Popen('python '+ WebSocket_Script, shell=True)
  102.     timedCheck = threading.Timer( 2.0, TimedProcessCheck )
  103.     timedCheck.start()
  104.  
  105. def kill_subProcesses():
  106.     try:
  107.         if timedCheck: timedCheck.cancel()
  108.         dictionary['HID_process'].terminate()
  109.         dictionary['WS_process'].terminate()
  110.     except:
  111.         pass
  112.  
  113. def get_MySQL_Data(ID, Type="tool"):
  114.     con=result = None
  115.     con = cymysql.connect(host=mysqlHost, port=int(mysqlPort), user=mysqlLogin, passwd=mysqlPass)
  116.     cur = con.cursor()
  117.     cur.execute("USE werkzeugausgabe;")
  118.     con.commit()
  119.     if Type == "user":
  120.         cur.execute('SELECT name FROM users WHERE uid="%s";' % ID)
  121.     elif Type == "tool":
  122.         cur.execute('SELECT tid,name FROM tools WHERE tid="%s";' % ID)
  123.     con.commit()
  124.     result = cur.fetchall()
  125.     return result
  126.  
  127. def update_MySQL_Data(tid, anzahl, ausleiher):
  128.     con=result = None
  129.     con = cymysql.connect(host=mysqlHost, port=int(mysqlPort), user=mysqlLogin, passwd=mysqlPass)
  130.     cur = con.cursor()
  131.     cur.execute("USE werkzeugausgabe;")
  132.     con.commit()
  133.     cur.execute('SELECT anzahl FROM tools WHERE tid="%s";' % tid)
  134.     row = cur.fetchone()
  135.     if row:
  136.         anzahl = int(row[0]) - int(anzahl)
  137.     cur.execute('UPDATE tools SET anzahl="%s", ausleiher="%s" WHERE tid="%s";' % (anzahl, ausleiher, tid))
  138.     con.commit()
  139.  
  140.  
  141. ### Parse data from WebSocket or SocketServer
  142. #required format-> command:value
  143. def RequestHandler(requestlist):
  144.     returnlist = ""
  145.     for request in requestlist:
  146.         request =  request.strip()
  147.         requestsplit = request.split(':')
  148.         requestsplit.append("dummy")
  149.         command = requestsplit[0]
  150.         value = requestsplit[1]
  151.         if value == "dummy":
  152.             value = "0"
  153.         if command == "localping":
  154.             returnlist += "\n localping:ok"
  155.  
  156.         elif command == "BARCODE":
  157.             BARCODE = ':'.join(requestsplit[1:])
  158.             #verify data
  159.             if dictionary['processing'] == "get_user":
  160.                 data = get_MySQL_Data(BARCODE, Type="user")
  161.                 if not data:
  162.                     returnlist += "\n get_user:UNKNOWN_USER"
  163.                 else:
  164.                     returnlist += "\n get_user:" + str(data[0][0])
  165.             elif dictionary['processing'] == "get_tool":
  166.                 data = get_MySQL_Data(BARCODE, Type="tool")
  167.                 if not data:
  168.                     returnlist += "\n get_tool:UNKNOWN_TOOL"
  169.                 else:
  170.                     returnlist += "\n get_tool:" + str(data[0][0] + ";" +str(data[0][1]))
  171.  
  172.         elif command == "get_user":
  173.             dictionary['processing'] = command
  174.             returnlist += "\n get_user:OK"
  175.  
  176.         elif command == "get_tool":
  177.             dictionary['processing'] = command
  178.             returnlist += "\n get_tool:OK"
  179.                
  180.         elif command.find("write_database") != '-1':
  181.             i = 1
  182.             j = 0
  183.             valuesplit = value.split(',')
  184.             while i < len(valuesplit):
  185.                 toolstring = valuesplit[0].lstrip() + ";" + valuesplit[i]
  186.                 toolstringsplit = toolstring.split(';')
  187.                 update_MySQL_Data(toolstringsplit[1], toolstringsplit[2], toolstringsplit[0])
  188.                 i = i + 1
  189.     return returnlist
  190.  
  191. #socket server <- barcode scanner (only one way)
  192. class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
  193.     def handle(self):
  194.         # self.rfile is a file-like object created by the handler;
  195.         # we can now use e.g. readline() instead of raw recv() calls
  196.         self.data = self.rfile.readline().strip()
  197.         printD("SocketRequest: {}".format(self.data))
  198.         try:
  199.             self.wfile.write(RequestHandler(self.data))
  200.         except Exception as error:
  201.             print("Error in ThreadedTCPRequestHandler: " + str(error))
  202.         except (KeyboardInterrupt, SystemExit):
  203.             sys.exit()
  204.  
  205. class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
  206.     pass
  207.  
  208.  
  209. if __name__ == "__main__":
  210.     try:
  211.         # Start Child Processes for Scripts
  212.         dictionary['HID_process'] = Popen('python '+ HID_Script +' '+ HID_device, shell=True)
  213.         dictionary['WS_process'] = Popen('python '+ WebSocket_Script, shell=True)
  214.         # Start Process-Check-Timer to check that Script are still running
  215.         timedCheck = threading.Timer( 2.0, TimedProcessCheck )
  216.         timedCheck.start()
  217.         # Start a thread with the server - that thread will then start one more thread for each request
  218.         socket_server = ThreadedTCPServer((SocketHost, SocketPort), ThreadedTCPRequestHandler)
  219.         ip, port = socket_server.server_address
  220.         socket_server_thread = threading.Thread(target=socket_server.serve_forever)
  221.         socket_server_thread.start()
  222.         signal.signal(signal.SIGINT, signal_handler)
  223.         signal.signal(signal.SIGTERM, signal_handler)
  224.     except Exception, e1:
  225.         print("Error...: " + str(e1))
  226.     except KeyboardInterrupt:
  227.         print("Schliesse Programm..")
  228.         raise SystemExit("Exiting")
  229.         sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement