Advertisement
Guest User

Untitled

a guest
Jan 12th, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.50 KB | None | 0 0
  1. #!/usr/bin/python
  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. import tornado.web
  13. import tornado.websocket
  14. import tornado.ioloop
  15. from datetime import timedelta
  16. import threading, time, sys, socket, subprocess
  17. try:
  18.   import SocketServer as socketserver
  19. except ImportError:
  20.   import socketserver
  21. try:
  22.   import cymysql
  23. except ImportError:
  24.   print("ERROR: You must install cymysql Module: sudo apt-get install python-pip && sudo pip install cymysql")
  25.   exit()
  26.  
  27. #-------------------------------------------------------------------
  28. DEBUG = True
  29. #DEBUG = False
  30. WebSocketPort = 7070
  31. HID_device = '/dev/hidraw0'
  32.  
  33. # Specify Settings for MySQL
  34. mysqlHost = 'localhost'
  35. mysqlPort = '3306'
  36. mysqlLogin = 'root'
  37. mysqlPass = 'raspberry'
  38. mysqlENABLE = True
  39. #mysqlENABLE = False
  40. #-------------------------------------------------------------------
  41.  
  42. # thread docu: http://www.tutorialspoint.com/python/python_multithreading.htm
  43. # socketserver docu: https://docs.python.org/2/library/socketserver.html
  44. # tornado & serial docu: http://forums.lantronix.com/showthread.php?p=3131
  45. # psutil: https://github.com/giampaolo/psutil
  46.  
  47. #-------------------------------------------------------------------
  48. # Dictionary docu: http://www.tutorialspoint.com/python/python_dictionary.htm
  49. dictionary = {}
  50. dictionary['HID_running'] = False
  51. currentTools = {};
  52. #-------------------------------------------------------------------
  53.  
  54.  
  55. try:
  56.   DEBUG
  57. except NameError:
  58.   DEBUG = False
  59.  
  60. if DEBUG:
  61.   print("Enabling DEBUG mode!")
  62. else:
  63.   print("Disabling DEBUG mode!")
  64.  
  65.  
  66. def printD(message):
  67.   if DEBUG:
  68.     print(message)
  69.  
  70. #http://www.gossamer-threads.com/lists/python/python/375364
  71. def awk_it(instring,index,delimiter=" "):
  72.   try:
  73.     return [instring,instring.split(delimiter)[index-1]][max(0,min(1,index))]
  74.   except:
  75.     return ""
  76.  
  77. def Barcode_read():
  78.   ## Zeichenzuteilung
  79.     hid = { 4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: 'f', 10: 'g', 11: 'h', 12: 'i', 13: 'j', 14: 'k', 15: 'l', 16: 'm', 17: 'n', 18: 'o', 19: 'p', 20: 'q', 21: 'r', 22: 's', 23: 't', 24: 'u', 25: 'v', 26: 'w', 27: 'x', 28: 'z', 29: 'y', 30: '1', 31: '2', 32: '3', 33: '4', 34: '5', 35: '6', 36: '7', 37: '8', 38: '9', 39: '0', 44: ' ', 45: '-', 46: '=', 47: '[', 48: ']', 49: '\\', 51: ';' , 52: '\'', 53: '~', 54: ',', 55: '.', 56: '/'  }
  80.     hid2 = { 4: 'A', 5: 'B', 6: 'C', 7: 'D', 8: 'E', 9: 'F', 10: 'G', 11: 'H', 12: 'I', 13: 'J', 14: 'K', 15: 'L', 16: 'M', 17: 'N', 18: 'O', 19: 'P', 20: 'Q', 21: 'R', 22: 'S', 23: 'T', 24: 'U', 25: 'V', 26: 'W', 27: 'X', 28: 'Z', 29: 'Y', 30: '!', 31: '@', 32: '#', 33: '$', 34: '%', 35: '^', 36: '&', 37: '*', 38: '(', 39: ')', 44: ' ', 45: '_', 46: '+', 47: '{', 48: '}', 49: '|', 51: ':' , 52: '"', 53: '~', 54: '<', 55: '>', 56: '?'  }
  81.     ## Schnittstelle oeffnen
  82.     fp = open(HID_device, 'rb')
  83.     barcode = ""
  84.     shift = False
  85.     while dictionary['HID_running']:
  86.       ## HID-Schnittstelle lesen
  87.       buffer = fp.read(8)
  88.       for c in buffer:
  89.         if ord(c) > 0:
  90.             ##  40 = carriage return ;
  91.             ##  Signal Barcode Ende
  92.             if int(ord(c)) == 40:
  93.                 dictionary['HID_running'] = False
  94.                 return barcode
  95.                 break
  96.             ##  Wenn shift positiv ;
  97.             ##  hid2 Zeichensatz nutzen
  98.             if shift:
  99.                ## "2" signalisiert shift
  100.                if int(ord(c)) == 2 :
  101.                   shift = True
  102.                ## keine "2" -> weiter lesen
  103.                else:
  104.                   barcode += hid2[ int(ord(c)) ]
  105.                   shift = False
  106.             ##  Keine "2" gefunden ;
  107.             ##  hid Zeichensatz nutzen
  108.             else:
  109.                ## "2" gefunden ;
  110.                ## setze shift positiv
  111.                if int(ord(c)) == 2 :
  112.                   shift = True
  113.                ## keine "2" -> weiter lesen
  114.                else:
  115.                   barcode += hid[ int(ord(c)) ]
  116.        
  117.  
  118. def get_MySQL_Data(ID, Type="tool"):
  119.     con=result = None
  120.     con = cymysql.connect(host=mysqlHost, port=int(mysqlPort), user=mysqlLogin, passwd=mysqlPass)
  121.     cur = con.cursor()
  122.     cur.execute("USE werkzeugausgabe;")
  123.     con.commit()
  124.     if Type == "user":
  125.       cur.execute('SELECT name FROM users WHERE uid="%s";' % ID)
  126.     elif Type == "tool":
  127.       cur.execute('SELECT tid,name FROM tools WHERE tid="%s";' % ID)
  128.     con.commit()
  129.     result = cur.fetchall()
  130.     return result
  131.    
  132. def update_MySQL_Data(tid, anzahl, ausleiher):
  133.     con=result = None
  134.     con = cymysql.connect(host=mysqlHost, port=int(mysqlPort), user=mysqlLogin, passwd=mysqlPass)
  135.     cur = con.cursor()
  136.     cur.execute("USE werkzeugausgabe;")
  137.     con.commit()
  138.     cur.execute('SELECT anzahl FROM tools WHERE tid="%s";' % tid)
  139.     row = cur.fetchone()
  140.     if row:
  141.         rest_anzahl = int(row[0]) - int(anzahl)
  142.     cur.execute('SELECT last_log FROM tools WHERE tid="%s";' % tid)
  143.     row = cur.fetchone()
  144.     if row:
  145.         logid = int(row[0].split(";")[0]) + 1
  146.     cur.execute('UPDATE tools SET anzahl="%s", ausleiher="%s" WHERE tid="%s";' % (rest_anzahl, ausleiher, tid))
  147.     log = str(logid) + ";" + time.strftime("%d.%m.%Y %H:%M") + ";" + ausleiher + ";" + anzahl
  148.     cur.execute('UPDATE tools SET last_log="%s", log=CONCAT(log, "%s") WHERE tid="%s";' % (log, log, tid))
  149.     con.commit()
  150.  
  151. ### Parse request from webif
  152. #required format-> command:value
  153. def WebRequestHandler(requestlist):
  154.     returnlist = ""
  155.     for request in requestlist:
  156.         request =  request.strip()
  157.         requestsplit = request.split(':')
  158.         requestsplit.append("dummy")
  159.         command = requestsplit[0]
  160.         value = requestsplit[1]
  161.         if value == "dummy":
  162.             value = "0"
  163.         if command == "localping":
  164.             returnlist += "\n localping:ok"
  165.  
  166.         elif command == "ende":
  167.             dictionary['HID_running'] = False
  168.  
  169.         elif command == "get_user":
  170.             dictionary['HID_running'] = True
  171.             dictionary['UID'] = Barcode_read()
  172.             #verify data
  173.             data = get_MySQL_Data(dictionary['UID'], Type="user")
  174.             if not data:
  175.                 returnlist += "\n get_user:UNKNOWN_USER"
  176.             else:
  177.                 returnlist += "\n get_user:" + str(data[0][0])
  178.                
  179.  
  180.         elif command == "get_tool":
  181.             dictionary['HID_running'] = True
  182.             dictionary['TID'] = Barcode_read()
  183.             #verify data
  184.             data = get_MySQL_Data(dictionary['TID'], Type="tool")
  185.             if not data:
  186.                 returnlist += "\n get_tool:UNKNOWN_TOOL"
  187.             else:
  188.                 returnlist += "\n get_tool:" + str(data[0][0] + ";" +str(data[0][1]))
  189.                
  190.         elif command.find("write_database") != '-1':
  191.             i = 1
  192.             j = 0
  193.             valuesplit = value.split(',')
  194.             while i < len(valuesplit):
  195.                 toolstring = valuesplit[0].lstrip() + ";" + valuesplit[i]
  196.                 toolstringsplit = toolstring.split(';')
  197.                 update_MySQL_Data(toolstringsplit[1], toolstringsplit[2], toolstringsplit[0])
  198.                 i = i + 1
  199.     return returnlist
  200.  
  201.  
  202. ### WebSocket server tornado <-> WebInterface
  203. class WebSocketHandler(tornado.websocket.WebSocketHandler):
  204.     connections = []
  205.     # the client connected
  206.     def check_origin(self, origin):
  207.         return True
  208.     def open(self):
  209.         printD("New client connected")
  210.         self.write_message("You are connected")
  211.         self.connections.append(self)
  212.     # the client sent the message
  213.     def on_message(self, message):
  214.         printD("Message from WebIf: >>>"+message+"<<<")
  215.         requestlist = message.splitlines()
  216.         self.write_message(WebRequestHandler(requestlist))
  217.     # client disconnected
  218.     def on_close(self):
  219.         printD("Client disconnected")
  220.         self.connections.remove(self)
  221.  
  222. # start a new WebSocket Application
  223. # use "/" as the root, and the WebSocketHandler as our handler
  224. application = tornado.web.Application([
  225.     (r"/", WebSocketHandler),
  226. ])
  227.  
  228.  
  229. if __name__ == "__main__":
  230.     try:
  231.         # start the tornado webserver on port WebSocketPort
  232.         application.listen(WebSocketPort)
  233.         tornado.ioloop.IOLoop.instance().start()
  234.     except Exception, e1:
  235.         print("Error...: " + str(e1))
  236.     except KeyboardInterrupt:
  237.         print("Schliesse Programm..")
  238.         exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement