import serial, time, datetime, struct
import struct           #Convert between strings and binary data
import sys
import requests
import os
import binascii
#import mysql.connector as mariadb
#cnx = mariadb.connect(user='monitor', password='', database='fingerdb', host='localhost')
#cnx=mysql.connector.connect(user='root',password='',host='localhost',database='fingerdb')       # connect to MySql database
#cur=cnx.cursor()

ser = serial.Serial("/dev/ttyS0", baudrate = 57600, timeout = 2) #serial.Serial('/dev/ttyUSB0',57600)     port =  # serial communication in Linux
#ser = serial.Serial("COM6", baudrate=9600, timeout=1)   #serial communication in Windows

pack = [0xef01, 0xffffffff, 0x1]        # Header, Address and Package Identifier

def readPacket():       # Function to read the Acknowledge packet
        time.sleep(1)
        w = ser.inWaiting()
        ret = []
        if w >= 9:
                s = ser.read(9)         # Partial read to get length
                ret.extend(struct.unpack('!HIBH', s))
                ln = ret[-1]

                time.sleep(1)
                w = ser.inWaiting()
                if w >= ln:
                        s = ser.read(ln)
                        form = '!' + 'B' * (ln - 2) + 'H'       # Specifying byte size
                        ret.extend(struct.unpack(form, s))
        return ret

def readPacket1():      # Function to read the Acknowledge packet
        time.sleep(1)
        w = ser.inWaiting()
        ret = []
        form = 'B' * 700
        s = ser.read(700)
        t=binascii.hexlify(s)   # convert to hex
        u=t[24:]
        ser.write(u)
        if store(idno):
                print 'store error'
                sys.exit(0)
                print "Enrolled successfully at id %d"%j
 #       cur.execute("insert into fingertb(name,finger) values('%s','%s')" %(name,u) )     # upadate database
 #       cnx.commit()
 #       v=binascii.unhexlify(u)
#        form1='B'*688
 #       ret1=[]
  #      ret1.extend(struct.unpack(form1, v))
 #       ret.extend(struct.unpack(form, s))

def writePacket(data):          # Function to write the Command Packet
        pack2 = pack + [(len(data) + 2)]
        a = sum(pack2[-2:] + data)
        pack_str = '!HIBH' + 'B' * len(data) + 'H'
        l = pack2 + data + [a]
        s = struct.pack(pack_str, *l)
        ser.write(s)


def verifyFinger():     # Verify Module?s handshaking password
        data = [0x13, 0x0, 0, 0, 0]
        writePacket(data)
        s = readPacket()
        return s[4]

def genImg():   # Detecting finger and store the detected finger image in ImageBuffer
        data = [0x1]
        writePacket(data)
        s = readPacket()
        return s[4]

def img2Tz(buf):        # Generate character file from the original finger image in ImageBuffer and store the file in CharBuffer1 or CharBuffer2.
        data = [0x2, buf]
        writePacket(data)
        s = readPacket()
        return s[4]

def regModel():         # Combine information of character files from CharBuffer1 and CharBuffer2 and generate a template which is stroed back in both CharBuffer1 and CharBuffer2.
        data = [0x5]
        writePacket(data)
        s = readPacket()
        return s[4]

def DownChar(buf):      # download character file or template from upper computer to the specified buffer of Module
        data = [0x9,buf]
        writePacket(data)
        s = readPacket1()

def store(id):          # store the template of specified buffer (Buffer1 Buffer2) at the designated location of Flash library
        data = [0x6, 0x1, 0x0, id]
        writePacket(data)
        s = readPacket()
        return s[4:-1]

d=open("classreg.dat","r")
classID=(d.readline())
classID=classID[0:6]
lecturer=(d.readline())
lecturer=lecturer[0:len(lecturer)-1]
day=(d.readline())
day=day[0:len(day)-1]
ctime=(d.readline())
ctime=ctime[0:len(ctime)-1]
venue=(d.readline())
venue=venue[0:len(venue)-1]
d.close()
currentDT = datetime.datetime.now()

print(currentDT.strftime("%c"))
print("\n") 
print("Registration for class: " + classID +"\n")
print("lecturer: "+ lecturer+"\n")
print("Day: "+ day +"\n")
print("Time: "+ctime+"\n")
print("Venue: "+venue+"\n")

print ("Type done to exit")
name=raw_input("Enter name : ")
idno=int(raw_input('enter the store id'))
while (name!='done'):
    #while True:

        if verifyFinger():
                print 'Verification Error'
                sys.exit(0)

        print 'Put finger',
        sys.stdout.flush()

        time.sleep(1)
        while genImg():
                time.sleep(0.1)
                print '.',
                sys.stdout.flush()

        print ''
        sys.stdout.flush()

        if img2Tz(1):
                print 'Conversion Error'
                sys.exit(0)

        print 'Put finger again',
        sys.stdout.flush()

        time.sleep(1)
        while genImg():
                time.sleep(0.1)
                print '.',
                sys.stdout.flush()

        print ''
        sys.stdout.flush()

        if img2Tz(2):
                print 'Conversion Error'
                sys.exit(0)
        
        r = store(id)
        print 'Search result', r
        if r[0] == 0 :
                currentDT = datetime.datetime.now()
                print (str(currentDT) + ' studentid: '+ str(r[2]))
                b=str(currentDT)   
                b = b[0:10]
                print(b)
                f = open("Reg_" + str(b)+".txt", "a")
                f.write("\n"+ currentDT.strftime("%c") +","+ classID + "," + str(r[2]))
                f.close()
                print 'Registration Successful'
                #response=requests.get(http://192.168.0.143/newSTIC/APIs/sensor.php?request=3&fingertid=str(r[2])&tattend=currentDT.strftime("%c"))
                f = open("Reg_" + str(b)+".txt", "r")
                for x in f:
                        print(x)
                f.close()
                continue   #sys.exit(0)

        else:
                print 'Registration Fail'
                continue   #sys.exit(1)
        f = open("Reg_" + str(b)+".txt", "r")
        for x in f:
                print(x)
        f.close()

        #if regModel():
        #        print 'Template Error'
        #        sys.exit(0)

        #if DownChar(1):
        #        print 'Template Error'
        #        sys.exit(0)

        name=raw_input("Enter name : ")
        idno=int(raw_input('enter the store id'))
