Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- #
- # ACHTUNG: Script ist fuer python2
- #
- # Starts tornado and Socket for Reading/Writing <-> WebInterface
- #
- # DONT use CTRL+Z to terminate script, else Port is blocked
- #
- ###
- from __future__ import print_function
- import tornado.web
- import tornado.websocket
- import tornado.ioloop
- from datetime import timedelta
- import threading, time, sys, socket, subprocess
- try:
- import SocketServer as socketserver
- except ImportError:
- import socketserver
- try:
- import cymysql
- except ImportError:
- print("ERROR: You must install cymysql Module: sudo apt-get install python-pip && sudo pip install cymysql")
- exit()
- #-------------------------------------------------------------------
- DEBUG = True
- #DEBUG = False
- WebSocketPort = 7070
- HID_device = '/dev/hidraw0'
- # Specify Settings for MySQL
- mysqlHost = 'localhost'
- mysqlPort = '3306'
- mysqlLogin = 'root'
- mysqlPass = 'raspberry'
- mysqlENABLE = True
- #mysqlENABLE = False
- #-------------------------------------------------------------------
- # thread docu: http://www.tutorialspoint.com/python/python_multithreading.htm
- # socketserver docu: https://docs.python.org/2/library/socketserver.html
- # tornado & serial docu: http://forums.lantronix.com/showthread.php?p=3131
- # psutil: https://github.com/giampaolo/psutil
- #-------------------------------------------------------------------
- # Dictionary docu: http://www.tutorialspoint.com/python/python_dictionary.htm
- dictionary = {}
- dictionary['HID_running'] = False
- currentTools = {};
- #-------------------------------------------------------------------
- try:
- DEBUG
- except NameError:
- DEBUG = False
- if DEBUG:
- print("Enabling DEBUG mode!")
- else:
- print("Disabling DEBUG mode!")
- def printD(message):
- if DEBUG:
- print(message)
- #http://www.gossamer-threads.com/lists/python/python/375364
- def awk_it(instring,index,delimiter=" "):
- try:
- return [instring,instring.split(delimiter)[index-1]][max(0,min(1,index))]
- except:
- return ""
- def Barcode_read():
- ## Zeichenzuteilung
- 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: '/' }
- 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: '?' }
- ## Schnittstelle oeffnen
- fp = open(HID_device, 'rb')
- barcode = ""
- shift = False
- while dictionary['HID_running']:
- ## HID-Schnittstelle lesen
- buffer = fp.read(8)
- for c in buffer:
- if ord(c) > 0:
- ## 40 = carriage return ;
- ## Signal Barcode Ende
- if int(ord(c)) == 40:
- dictionary['HID_running'] = False
- return barcode
- break
- ## Wenn shift positiv ;
- ## hid2 Zeichensatz nutzen
- if shift:
- ## "2" signalisiert shift
- if int(ord(c)) == 2 :
- shift = True
- ## keine "2" -> weiter lesen
- else:
- barcode += hid2[ int(ord(c)) ]
- shift = False
- ## Keine "2" gefunden ;
- ## hid Zeichensatz nutzen
- else:
- ## "2" gefunden ;
- ## setze shift positiv
- if int(ord(c)) == 2 :
- shift = True
- ## keine "2" -> weiter lesen
- else:
- barcode += hid[ int(ord(c)) ]
- def get_MySQL_Data(ID, Type="tool"):
- con=result = None
- con = cymysql.connect(host=mysqlHost, port=int(mysqlPort), user=mysqlLogin, passwd=mysqlPass)
- cur = con.cursor()
- cur.execute("USE werkzeugausgabe;")
- con.commit()
- if Type == "user":
- cur.execute('SELECT name FROM users WHERE uid="%s";' % ID)
- elif Type == "tool":
- cur.execute('SELECT tid,name FROM tools WHERE tid="%s";' % ID)
- con.commit()
- result = cur.fetchall()
- return result
- def update_MySQL_Data(tid, anzahl, ausleiher):
- con=result = None
- con = cymysql.connect(host=mysqlHost, port=int(mysqlPort), user=mysqlLogin, passwd=mysqlPass)
- cur = con.cursor()
- cur.execute("USE werkzeugausgabe;")
- con.commit()
- cur.execute('SELECT anzahl FROM tools WHERE tid="%s";' % tid)
- row = cur.fetchone()
- if row:
- rest_anzahl = int(row[0]) - int(anzahl)
- cur.execute('SELECT last_log FROM tools WHERE tid="%s";' % tid)
- row = cur.fetchone()
- if row:
- logid = int(row[0].split(";")[0]) + 1
- cur.execute('UPDATE tools SET anzahl="%s", ausleiher="%s" WHERE tid="%s";' % (rest_anzahl, ausleiher, tid))
- log = str(logid) + ";" + time.strftime("%d.%m.%Y %H:%M") + ";" + ausleiher + ";" + anzahl
- cur.execute('UPDATE tools SET last_log="%s", log=CONCAT(log, "%s") WHERE tid="%s";' % (log, log, tid))
- con.commit()
- ### Parse request from webif
- #required format-> command:value
- def WebRequestHandler(requestlist):
- returnlist = ""
- for request in requestlist:
- request = request.strip()
- requestsplit = request.split(':')
- requestsplit.append("dummy")
- command = requestsplit[0]
- value = requestsplit[1]
- if value == "dummy":
- value = "0"
- if command == "localping":
- returnlist += "\n localping:ok"
- elif command == "ende":
- dictionary['HID_running'] = False
- elif command == "get_user":
- dictionary['HID_running'] = True
- dictionary['UID'] = Barcode_read()
- #verify data
- data = get_MySQL_Data(dictionary['UID'], Type="user")
- if not data:
- returnlist += "\n get_user:UNKNOWN_USER"
- else:
- returnlist += "\n get_user:" + str(data[0][0])
- elif command == "get_tool":
- dictionary['HID_running'] = True
- dictionary['TID'] = Barcode_read()
- #verify data
- data = get_MySQL_Data(dictionary['TID'], Type="tool")
- if not data:
- returnlist += "\n get_tool:UNKNOWN_TOOL"
- else:
- returnlist += "\n get_tool:" + str(data[0][0] + ";" +str(data[0][1]))
- elif command.find("write_database") != '-1':
- i = 1
- j = 0
- valuesplit = value.split(',')
- while i < len(valuesplit):
- toolstring = valuesplit[0].lstrip() + ";" + valuesplit[i]
- toolstringsplit = toolstring.split(';')
- update_MySQL_Data(toolstringsplit[1], toolstringsplit[2], toolstringsplit[0])
- i = i + 1
- return returnlist
- ### WebSocket server tornado <-> WebInterface
- class WebSocketHandler(tornado.websocket.WebSocketHandler):
- connections = []
- # the client connected
- def check_origin(self, origin):
- return True
- def open(self):
- printD("New client connected")
- self.write_message("You are connected")
- self.connections.append(self)
- # the client sent the message
- def on_message(self, message):
- printD("Message from WebIf: >>>"+message+"<<<")
- requestlist = message.splitlines()
- self.write_message(WebRequestHandler(requestlist))
- # client disconnected
- def on_close(self):
- printD("Client disconnected")
- self.connections.remove(self)
- # start a new WebSocket Application
- # use "/" as the root, and the WebSocketHandler as our handler
- application = tornado.web.Application([
- (r"/", WebSocketHandler),
- ])
- if __name__ == "__main__":
- try:
- # start the tornado webserver on port WebSocketPort
- application.listen(WebSocketPort)
- tornado.ioloop.IOLoop.instance().start()
- except Exception, e1:
- print("Error...: " + str(e1))
- except KeyboardInterrupt:
- print("Schliesse Programm..")
- exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement