Advertisement
Guest User

Untitled

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