import sys import serial import logging import konfig import time from mysql.connector import connect, Error from time import sleep Log_Format = "%(levelname)s %(module)s:%(lineno)d %(asctime)s - %(message)s" logging.basicConfig(stream=sys.stdout, format = Log_Format, level=logging.INFO) logger = logging.getLogger() comeTimeID = 0 def checksum(data): checksum = 0; len = int(data[1:3]) if(len < 99): for i in range(1, len+3): checksum = checksum ^ ord(data[i:i+1]) #print(str(i)+":"+str(data[i:i+1])+" "+hex(ord(data[i:i+1]))) return checksum & 0xFF; def writeCmd(cmd,data): length = str(len(data)+1).zfill(2) msg = '#'+ length + cmd + data cs = str(checksum(str.encode(msg))).zfill(3) #print("Len: "+str(len(data)+1)) #print("MEssage: "+msg+" CS: "+cs) con.write(str.encode(msg+cs+"\n")) def getMaID(id): comeTimeID = 0 try: with connect(**konfig.datenbank()) as connection: with connection.cursor() as cursor: cursor.execute("SELECT id FROM user WHERE rfid = '"+str(id[0:8])+"';") maid = cursor.fetchone() connection.commit() if maid == None: writeCmd('M',"NeuerTag "+str(id[0:8])) logger.warning("Employee not found rfID: %s",str(id[0:8])) else: cursor.execute("SELECT id FROM zeiten WHERE ma_id = "+maid[0]+" AND DATE(kommen) = DATE(NOW()) AND gehen = '1990-01-01 00:00:00';") cometime = cursor.fetchone() connection.commit() if cometime == None: writeCmd('C',"") cursor.execute("INSERT INTO zeiten (kommen, gehen, ma_id) VALUES (NOW(), '1990-01-01 00:00:00', "+maid[0]+")") connection.commit() else: writeCmd('G',"") return str(cometime[0]) except: writeCmd('M',"Datenbankverbindung\n\rfehlgeschlagen") logger.warning("DB connection failed!") #con = serial.Serial("COM7",115200,timeout=2,parity=serial.PARITY_NONE, dsrdtr=False) #con.write('#') #con.write('\n') #sleep(2) #writeCmd("T",str(int(time.time()))) #print(con.read_all()) con = None while True: try: if(con == None): con = serial.Serial("COM7",115200,timeout=2,parity=serial.PARITY_NONE, dsrdtr=False) print("Reconnecting") sleep(2) writeCmd("T",str(int(time.time()))) line=con.readline() if len(line) > 10: logger.info("MSG: "+str(line)+" "+str(line[3:4])) if(line[3:4] == b'I'): logger.info("TAG!") cometimeID = getMaID(line[4:4+8]) elif(line[3:4] == b'P'): logger.info("PAUSE!") pause = str(line(4,4+3)) if(cometimeID != None): try: with connect(**konfig.datenbank()) as connection: with connection.cursor() as cursor: cursor.execute("UPDATE zeiten SET gehen = NOW(), pause_mins="+pause+" WHERE id = "+cometimeID) maid = cursor.fetchone() connection.commit() writeCmd('P',"") except: writeCmd('M',"Eintragen\n\rfehlgeschlagen") logger.warning("Could not update entry with Go time") except: if(not(con == None)): con.close() con = None logger.warning("Disconnecting") time.sleep(2)