Esempio n. 1
0
 def initFP(self,instIndex):
     self.instIndex = instIndex
     try:
         self.f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)
         if ( self.f.verifyPassword() == False ):
             raise ValueError('La contrasena del sensor de huella dactilar presento un error.')
     except Exception as e:
         print('The fingerprint sensor could not be initialized!')
         print('Exception message: ' + str(e))
         exit(1)
Esempio n. 2
0
def verify():
    import RPi.GPIO as GPIO
    import first
    import hashlib
    from pyfingerprint.pyfingerprint import PyFingerprint
    import time
    import doorlock 
    import serial
    import Triled
    import sqlwg
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    r, g, b = Triled.gpiolightconfig(21,20,16)
    GPIO.setup(r,GPIO.OUT), GPIO.setup(g,GPIO.OUT), GPIO.setup(b,GPIO.OUT)
    Triled.gpiolightout(21, 20, 16)

    ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)


    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

        if ( f.verifyPassword() == False ):
            raise ValueError('The given fingerprint sensor password is wrong!')

    except Exception as e:
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
        exit(1)

## Gets some sensor information
    tempcount= str(f.getTemplateCount())

    try:
        sqlwg.sqwrite("UPDATE gui set page ='fingerprint.html' WHERE id=1")
        print('Waiting for finger...')

    ## Wait that finger is read
        while ( f.readImage() == False ):
            Triled.redon(r)
            data = ser.readline().decode('utf-8')
            if data!= '' and data[0] == 'C':
                first.startpoint()
            elif data!= '' and data[0] == 'D':
                enroll()
            Triled.redoff(r)
            pass

    ## Converts read image to characteristics and stores it in charbuffer 1
        Triled.redoff(r)
        f.convertImage(0x01)

    ## Searchs template
        result = f.searchTemplate()

        positionNumber = result[0]
        accuracyScore = result[1]

        if ( positionNumber == -1 ):
            sqlwg.sqwrite("UPDATE gui set page ='denyaccess.html' WHERE id=1")
            print('No match found!')
            Triled.blueon(b)
            Triled.blueoff(b)
            Triled.redon(r)
            Triled.redoff(r)
            
            return 0
        else:
            sqlwg.sqwrite("UPDATE gui set page ='grantaccess.html' WHERE id=1")
            print('access Granted' )
            print('ID No: ' + str(positionNumber))
            doorlock.unlocklock()
            return 1
        exit(0)

    ## OPTIONAL stuff
    ##

    ## Loads the found template to charbuffer 1
        f.loadTemplate(positionNumber, 0x01)

    ## Downloads the characteristics of template loaded in charbuffer 1
        characterics = str(f.downloadCharacteristics(0x01)).encode('utf-8')

    

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(0)
Esempio n. 3
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import pymongo
from pyfingerprint.pyfingerprint import PyFingerprint


myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mydb = myclient["finger_DB"]
mycol = mydb["finger_array"]

try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

try:
    print('Waiting for finger....')
    
    while (f.readImage()== False ):
        pass

    f.convertImage(0x01)
Esempio n. 4
0
"""
PyFingerprint
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

"""

import time
from pyfingerprint.pyfingerprint import PyFingerprint

## Enrolls new finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 9600, 0xFFFFFFFF, 0x00000000)

    if (f.verifyPassword() == False):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
      str(f.getStorageCapacity()))

## Tries to enroll new finger
try:
Esempio n. 5
0
        print('sensor function is interrupted')
        print('exception message: ' + str(e))
        exit(1)


#####################################################
####### START ############

# 지문인식센서 초기화 하기(초기 값으로 설정)

try:
    print('sensor initianlize~!!!')
    lcdprint("*** SYSTEM ***")
    time.sleep(2)
    lcdprint2(" Finger sensor", "  Initialize   ")
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if (f.verifyPassword() == False):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('Exception message: ' + str(e))
    exit(1)

# 지문인식센서를 시작할 때

lcdprint2(" Finger print ", "  System  ")
time.sleep(3)
lcdprint(" system starts  ")
time.sleep(3)
flag = 0
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

@author: Bastian Raschke <*****@*****.**>
"""

import tempfile
from pyfingerprint.pyfingerprint import PyFingerprint


## Reads image and download it
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently stored templates: ' + str(f.getTemplateCount()))

## Tries to read image and download it
try:
    print('Waiting for finger...')
Esempio n. 7
0
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

@author: Bastian Raschke <*****@*****.**>
"""

import hashlib
from pyfingerprint.pyfingerprint import PyFingerprint


## Search for a finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently stored templates: ' + str(f.getTemplateCount()))

## Tries to search the finger and calculate hash
try:
    print('Waiting for finger...')
Esempio n. 8
0
def search_fingerprint():
    ## Tries to initialize the sensor
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
        #~ file1 =  open("loginstate.txt","a+")
        if (f.verifyPassword() == False):
            raise ValueError('The given fingerprint sensor password is wrong!')

    except Exception as e:
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
        #~ exit(1)
    ## Gets some sensor information
    print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
          str(f.getStorageCapacity()))
    ## Tries to search the finger and calculate hash
    try:
        print('Waiting for finger...')

        ## Wait that finger is read
        while (f.readImage() == False):
            pass

        ## Converts read image to characteristics and stores it in charbuffer 1
        f.convertImage(0x01)

        ## Searchs template
        result = f.searchTemplate()
        print(result)
        positionNumber = result[0]
        accuracyScore = result[1]

        if (positionNumber == -1):
            print('No match found!')
            #~ search_fingerprint()
        #~ exit(0)
        else:
            print('Found template at position #' + str(positionNumber))
            print('The accuracy score is: ' + str(accuracyScore))
        #~ file1.write(str(positionNumber)+'\n')
        url1 = "http://0.0.0.0:4310/login"
        data1 = {'userID': positionNumber}
        r1 = requests.post(url1, data1)
        url2 = "http://0.0.0.0:4311/exit"
        daya2 = {"mode": "1"}
        r2 = requests.post(url2, data2)
        ## OPTIONAL stuff
        ##
        ## Loads the found template to charbuffer 1
        f.loadTemplate(positionNumber, 0x01)
        print("1")
        print(result)
        ## Downloads the characteristics of template loaded in charbuffer 1
        characterics = str(f.downloadCharacteristics(0x01)).encode('utf-8')
        print("2")
        print(result)
        ## Hashes characteristics of template
        print('SHA-2 hash of template: ' +
              hashlib.sha256(characterics).hexdigest())
        time.sleep(1)

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
def enroll():

    ## Enrolls new finger
    ##

    ## Tries to initialize the sensor
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

        if (f.verifyPassword() == False):
            raise ValueError('The given fingerprint sensor password is wrong!')

    except Exception as e:
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
        exit(1)

    ## Gets some sensor information
    print('Currently stored templates: ' + str(f.getTemplateCount()))

    ## Tries to enroll new finger
    try:
        print('Waiting for finger...')

        ## Wait that finger is read
        while (f.readImage() == False):
            pass

        ## Converts read image to characteristics and stores it in charbuffer 1
        f.convertImage(0x01)

        ## Checks if finger is already enrolled
        result = f.searchTemplate()
        positionNumber = result[0]

        ## Gets new position number (the counting starts at 0, so we do not need to increment)
        #positionNumber = f.getTemplateCount()

        if (positionNumber >= 0):
            f.loadTemplate(positionNumber, 0x01)
            characterics = str(f.downloadCharacteristics(0x01))
            passhashes = hashlib.sha256(characterics).hexdigest()
            passhash = passhashes[0:32]
            print('Template already exists at position #' +
                  str(positionNumber))
            return passhash

        print('Remove finger...')
        time.sleep(2)

        print('Waiting for same finger again...')

        ## Wait that finger is read again
        while (f.readImage() == False):
            pass

        ## Converts read image to characteristics and stores it in charbuffer 2
        f.convertImage(0x02)

        ## Compares the charbuffers and creates a template
        f.createTemplate()

        ## Gets new position number (the counting starts at 0, so we do not need to increment)
        positionNumber = f.getTemplateCount()

        ## Saves template at new position number
        if (f.storeTemplate(positionNumber) == True):
            print('Finger enrolled successfully!')
            print('New template position #' + str(positionNumber))
            ## Hashes characteristics of template

            characterics = str(f.downloadCharacteristics(0x01))
            passhashes = hashlib.sha256(characterics).hexdigest()
            passhash = passhashes[0:32]
            ## Hashes characteristics of template
            print('SHA-2 hash of template: ' + passhash)
            return passhash

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

This code has been changed from its original form for the course CPS410.

"""

import tempfile
from pyfingerprint.pyfingerprint import PyFingerprint

## Reads image and download it
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if (f.verifyPassword() == False):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
      str(f.getStorageCapacity()))

## Tries to read image and download it
try:
Esempio n. 11
0
PyFingerprint
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

"""

from pyfingerprint.pyfingerprint import PyFingerprint


## Deletes a finger from sensor
##


## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to delete the template of the finger
try:
    positionNumber = input('Please enter the template position you want to delete: ')
Esempio n. 12
0
class UtilFingerprint:

    #Realiza la coneccion con el fingerprint
    def __init__(self,instIndex):
       self.initFP(instIndex)

    #Realiza la coneccion con el fingerprint
    def initFP(self,instIndex):
        self.instIndex = instIndex
        try:
            self.f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)
            if ( self.f.verifyPassword() == False ):
                raise ValueError('La contrasena del sensor de huella dactilar presento un error.')
        except Exception as e:
            print('The fingerprint sensor could not be initialized!')
            print('Exception message: ' + str(e))
            exit(1)


    #Busca una huella en especifico
    def search(self,instIndex):
        self.initFP(instIndex)

        try:
            #Esperando a que sea leido el dedo
            while (self.instIndex.semaforo == False and self.f.readImage() == False ):
                pass

            if self.instIndex.semaforo == True:
                return 0
            
            #Convierte la imagen en caracteristicas 
            self.f.convertImage(0x01)

            #Se busca la imagen leida en las guardadas previamente
            result = self.f.searchTemplate()
            positionNumber = result[0]
            accuracyScore = result[1]
            
            self.instIndex.idUser = positionNumber
            self.instIndex.semaforo = True
            return positionNumber                     

        except Exception as e:
            print('Mensaje de Excepcion: ' + str(e))
            exit(1)

    #-------- Elimina una huella en el dispositivo --------
    def delete(self, positionNumber, instIndex):
        self.initFP(instIndex)
    
        try:
            if ( self.f.deleteTemplate(positionNumber) == True ):
                print('Template deleted!')
        except Exception as e:
            print('Operation failed!')
            print('Exception message: ' + str(e))
            exit(1)

    
    #---------- Verifica existencia de huella -----------
    def exist(self, instIndex):
        self.initFP(instIndex)
    
        try:
            print("Waiting for finger")

            #Escucha el fingerprint
            while self.instIndex.semaforo == False and self.f.readImage() == False:
                pass
 
            #Si se acaba el tiempo se elimina la ejecucion
            if self.instIndex.semaforo == True:
                self.instIndex.result = "timeout"
                return "timeout"

            #En caso de que se ingresara una huella se analiza
            self.f.convertImage(0x01)

            result = self.f.searchTemplate()
            positionNumber = result[0]
            self.instIndex.result = str(positionNumber)

            return str(positionNumber)+""# -1 quiere = No existe

        except Exception as e:
            print('Operation failed!')
            print('Exception message: ' + str(e))
            exit(1)


    #-------- Guarda una huella en el dispositivo --------
    def save(self, instIndex):
        self.initFP(instIndex)
    
        try:            
            #Se valida que la huella se registrara correctamente
            while (self.instIndex.semaforo == False and self.f.readImage() == False):
                pass
            
            #En caso de ser eliminado desde otra clase se termina el flujo
            if self.instIndex.semaforo == True:
                self.instIndex.result = "ERROR!, debe colocar el dedo en el dispositivo"
                return 0


            self.f.convertImage(0x02)

            if(self.f.compareCharacteristics() == 0):
                self.instIndex.result = "Las huellas no coinciden"
                return 0

            self.f.createTemplate()

            positionNumber = self.f.storeTemplate()
            #print ("La posicion de la huella es " + str(positionNumber))

            self.instIndex.idUser = positionNumber
            self.instIndex.result = "Realizado con exito."
            self.instIndex.semaforo = True

        except Exception as e:
            print('Operation failed!')
            print('Exception message: ' + str(e))
            exit(1)
Esempio n. 13
0
PyFingerprint
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

"""

import tempfile
from pyfingerprint.pyfingerprint import PyFingerprint


## Reads image and download it
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to read image and download it
try:
    print('Waiting for finger...')
Esempio n. 14
0
"""
PyFingerprint
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

"""
import sys
import hashlib
from pyfingerprint.pyfingerprint import PyFingerprint

## Search for a finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if (f.verifyPassword() == False):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
      str(f.getStorageCapacity()))

## Tries to search the finger and calculate hash
try:
def fp_search():
    """
    PyFingerprint
    Copyright (C) 2015 Bastian Raschke <*****@*****.**>
    All rights reserved.

    @author: Bastian Raschke <*****@*****.**>
    """

    ## Search for a finger
    ##

    ## Tries to initialize the sensor
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

        if (f.verifyPassword() == False):
            raise ValueError('The given fingerprint sensor password is wrong!')

    except Exception as e:
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
        exit(1)

    ## Gets some sensor information
    print('Currently stored templates: ' + str(f.getTemplateCount()))

    ## Tries to search the finger and calculate hash
    try:
        print('Waiting for finger...')

        ## Wait that finger is read
        while (f.readImage() == False):
            pass

        ## Converts read image to characteristics and stores it in charbuffer 1
        f.convertImage(0x01)

        ## Searchs template
        result = f.searchTemplate()

        positionNumber = result[0]
        accuracyScore = result[1]

        if (positionNumber == -1):
            print('No match found!')
            exit(0)
        else:
            print('Found template at position #' + str(positionNumber))
            print('The accuracy score is: ' + str(accuracyScore))

        ## OPTIONAL stuff
        ##

        ## Loads the found template to charbuffer 1
        f.loadTemplate(positionNumber, 0x01)

        ## Downloads the characteristics of template loaded in charbuffer 1
        characterics = str(f.downloadCharacteristics(0x01))

        ## Hashes characteristics of template
        print('SHA-2 hash of template: ' +
              hashlib.sha256(characterics).hexdigest())

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
Esempio n. 16
0
    def added(self):
        print('success')
        try:
            f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

            if (f.verifyPassword() == False):
                raise ValueError(
                    'The given fingerprint sensor password is wrong!')

        except Exception as e:
            print('The fingerprint sensor could not be initialized!')
            print('Exception message: ' + str(e))
            exit(1)

        ## Gets some sensor information
        print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
              str(f.getStorageCapacity()))

        ## Tries to enroll new finger
        try:
            print('Waiting for finger...')

            ## Wait that finger is read
            while (f.readImage() == False):
                pass

            ## Converts read image to characteristics and stores it in charbuffer 1
            f.convertImage(0x01)

            ## Checks if finger is already enrolled
            result = f.searchTemplate()
            positionNumber = result[0]

            if (positionNumber >= 0):
                print('Template already exists at position #' +
                      str(positionNumber))

            print('Remove finger...')
            time.sleep(2)

            print('Waiting for same finger again...')

            ## Wait that finger is read again
            while (f.readImage() == False):
                pass

            ## Converts read image to characteristics and stores it in charbuffer 2
            f.convertImage(0x02)

            ## Compares the charbuffers
            if (f.compareCharacteristics() == 0):
                raise Exception('Fingers do not match')

            ## Creates a template
            f.createTemplate()

            ## Saves template at new position number
            positionNumber = f.storeTemplate()
            print('Finger enrolled successfully!')
            print('New template position #' + str(positionNumber))
            df = pd.read_csv('hostel.csv')
            roll = self.nameEdit_2.text()
            yop = self.yearedit.text()
            x = df.shape[0]
            df.set_value(x, 'Rollnum', roll)
            df.set_value(x, 'fingerid', positionNumber)
            df.set_value(x, 'YoP', yop)
            df.to_csv('hostel.csv', encoding="utf-8", index=False)
            print('success')

        except Exception as e:
            print('Operation failed!')
            print('Exception message: ' + str(e))

        self.setupUi(AllInOne)
sys.stdout.close()

sys.stderr.flush()
sys.stderr.close()

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)
GPIO.output(17, GPIO.HIGH)
## Search for a finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if (f.verifyPassword() == False):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
#print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to search the finger and calculate hash
try:
    #print('Waiting for finger...')
Esempio n. 18
0
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

@author: Bastian Raschke <*****@*****.**>
"""

from pyfingerprint.pyfingerprint import PyFingerprint


## Deletes a finger from sensor
##


## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently stored templates: ' + str(f.getTemplateCount()))

## Tries to delete the template of the finger
try:
    positionNumber = raw_input('Please enter the template position you want to delete: ')
Esempio n. 19
0
def enroll_fingerprint():
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

        if (f.verifyPassword() == False):
            raise ValueError('The given fingerprint sensor password is wrong!')

    except Exception as e:
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
        exit(1)

    ## Gets some sensor information
    print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
          str(f.getStorageCapacity()))

    ## Tries to enroll new finger
    try:
        print('Waiting for finger...')

        ## Wait that finger is read
        while (f.readImage() == False):
            pass

        ## Converts read image to characteristics and stores it in charbuffer 1
        f.convertImage(0x01)

        ## Checks if finger is already enrolled
        result = f.searchTemplate()
        positionNumber = result[0]

        if (positionNumber >= 0):
            print('Template already exists at position #' +
                  str(positionNumber))
            #post msg to website
            url1 = "http://0.0.0.0:4310/register"
            data1 = {'positionNumber': positionNumber, "goToSignUp": 0}
            r = requests.post(url1, data1)
            url2 = "http://0.0.0.0:4311/exit"
            daya2 = {"mode": "1"}
            r2 = requests.post(url2, data2)
            #call search
            exit(0)

        print('Remove finger...')
        time.sleep(2)

        print('Waiting for same finger again...')

        ## Wait that finger is read again
        while (f.readImage() == False):
            pass

        ## Converts read image to characteristics and stores it in charbuffer 2
        f.convertImage(0x02)

        ## Compares the charbuffers
        if (f.compareCharacteristics() == 0):
            #~ raise Exception('Fingers do not match')
            enroll_fingerprint()

        ## Creates a template
        f.createTemplate()

        ## Saves template at new position number
        positionNumber = f.storeTemplate()
        print('Finger enrolled successfully!')
        print('New template position #' + str(positionNumber))

        #post msg to website:success
        url1 = "http://0.0.0.0:4310/register"
        data1 = {'positionNumber': positionNumber, "goToSignUp": 1}
        r1 = requests.post(url1, data1)
        url2 = "http://0.0.0.0:4311/exit"
        daya2 = {"mode": "1"}
        r2 = requests.post(url2, data2)
        exit(0)
    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
Esempio n. 20
0
PyFingerprint
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

"""

import time
from pyfingerprint.pyfingerprint import PyFingerprint


## Enrolls new finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to enroll new finger
try:
    print('Waiting for finger...')
    def enroll_worker(self):
        try:
            f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
            if (f.verifyPassword() == False):
                raise ValueError(
                    'The given fingerprint sensor password is wrong!')

        except Exception as e:
            self.controller.view.msgText1.set('ERROR')
            print('The fingerprint sensor could not be initialized!')
            print('Exception message: ' + str(e))
            exit(1)

        ## Gets some sensor information
        print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
              str(f.getStorageCapacity()))

        ## Tries to enroll new finger
        try:
            self.controller.view.statusText.set('Status: OK')
            self.controller.view.msgText1.set('Waiting for finger...')
            print('Waiting for finger...')

            ## Wait that finger is read
            while (f.readImage() == False):
                pass

            ## Converts read image to characteristics and stores it in charbuffer 1
            f.convertImage(0x01)

            ## Checks if finger is already enrolled
            result = f.searchTemplate()
            positionNumber = result[0]

            if (positionNumber >= 0):
                self.controller.view.msgText1.set('Remove finger...')
                self.controller.view.statusText.set(
                    'Status: Template already exists at position #' +
                    str(positionNumber))
                print('Template already exists at position #' +
                      str(positionNumber))
                exit(0)
            self.controller.view.msgText1.set('Remove finger...')
            print('Remove finger...')
            time.sleep(2)

            for _ in range(4):

                self.controller.view.msgText1.set(
                    'Waiting for same finger again...')

                print('Waiting for same finger again...')

                ## Wait that finger is read again
                while (f.readImage() == False):
                    pass

                ## Converts read image to characteristics and stores it in charbuffer 2
                f.convertImage(0x02)

                ## Compares the charbuffers
                if (f.compareCharacteristics() == 0):
                    self.controller.view.msgText1.set('An error ocurr')
                    self.controller.view.statusText.set(
                        'Status: Fingers do not match')
                    raise Exception('Fingers do not match')

                ## Creates a template
                f.createTemplate()

                self.controller.view.msgText1.set('Remove finger...')
                print('Remove finger...')
                time.sleep(2)

            ## Saves template at new position number
            positionNumber = f.storeTemplate()

            self.controller.view.msgText1.set(
                'Finger enrolled successfully! Pos: ' + str(positionNumber))
            self.controller.view.statusText.set('Status: Finish')
            print('Finger enrolled successfully!')
            print('New template position #' + str(positionNumber))
            self.controller.template_number = positionNumber
            self.controller.employee_to_DB()

        except Exception as e:
            print('Operation failed!')
            print('Exception message: ' + str(e))
            exit(1)
Esempio n. 22
0
"""
PyFingerprint
Copyright (C) 2017 Philipp Meisberger <*****@*****.**>
All rights reserved.

"""

from pyfingerprint.pyfingerprint import PyFingerprint


## Generates a 32-bit random number
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Tries to generate a 32-bit random number
try:
    print(f.generateRandomNumber())

except Exception as e:
    print('Operation failed!')
Esempio n. 23
0
All rights reserved.

"""

## Statut :
## Code : OK
## Langue : OK

from pyfingerprint.pyfingerprint import PyFingerprint

## Initialisation du capteur
try:
    ## Windows
    #f = PyFingerprint('COM10', 57600, 0xFFFFFFFF, 0x00000000)
    ## Debian
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError("Mot de passe du capteur d'empreinte digitale incorrect")

except Exception as e:
    print("Impossible d'initialiser le capteur d'empreinte digitale")
    print("Message d'erreur : " + str(e))
    exit(1)

## Affiche les données sur le capteur
print("Bienvenue sur le module d'index d'emplacement du capteur d'empreinte digitale")
print("Emplacements utilisés dans le capteur: " + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Affiche l'index d'emplacement du capteur d'empreinte digitale
try:
def run():
    ## Tries to initialize the sensor
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

        if (f.verifyPassword() == False):
            raise ValueError('The given fingerprint sensor password is wrong!')

    except Exception as e:
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
        exit(1)

    ## Gets some sensor information
    print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
          str(f.getStorageCapacity()))

    ## Tries to search the finger and calculate hash
    try:
        msg = messagebox.showinfo("Enroll", "Press OK when Finger Ready")

        print('Waiting for finger...')

        ## Wait that finger is read
        while (f.readImage() == False):
            pass

        ## Converts read image to characteristics and stores it in charbuffer 1
        f.convertImage(0x01)

        ## Searchs template
        result = f.searchTemplate()

        positionNumber = result[0]
        accuracyScore = result[1]
        temp = positionNumber
        if (positionNumber == -1):
            print('No match found! Try again')
            run()
        else:
            print('Found template at position #' + str(positionNumber))
            print('The accuracy score is: ' + str(accuracyScore))
            c.execute(
                "SELECT firstname, lastname FROM students WHERE templateid = ?",
                str(temp))
            result = c.fetchall()
            print(result)
            #for row in c:
            #    print(row)
            #print(c)
            print("User logged in")

        ## OPTIONAL stuff
        ##

        ## Loads the found template to charbuffer 1
        f.loadTemplate(positionNumber, 0x01)

        ## Downloads the characteristics of template loaded in charbuffer 1
        characterics = str(f.downloadCharacteristics(0x01)).encode('utf-8')

        ## Hashes characteristics of template
        print('SHA-2 hash of template: ' +
              hashlib.sha256(characterics).hexdigest())

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
def enroll(ref, firstName, lastName, licNo, lmv):
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

        if (f.verifyPassword() == False):
            raise ValueError('The given fingerprint sensor password is wrong!')

    except Exception as e:
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
        exit(1)


## Gets some sensor information
#print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))
    f.deleteTemplate(0)
    ## Tries to enroll new finger
    try:
        print('Waiting for finger...')

        ## Wait that finger is read
        while (f.readImage() == False):
            pass

    ## Converts read image to characteristics and stores it in charbuffer 1
        f.convertImage(0x01)

        ## Checks if finger is already enrolled
        result = f.searchTemplate()
        positionNumber = result[0]
        if (positionNumber >= 0):
            print('Template already exists at position #' +
                  str(positionNumber))
            exit(0)

        print('Remove finger...')
        time.sleep(2)

        print('Waiting for same finger again...')

        ## Wait that finger is read again
        while (f.readImage() == False):
            pass

    ## Converts read image to characteristics and stores it in charbuffer 2
        f.convertImage(0x02)

        ## Compares the charbuffers
        if (f.compareCharacteristics() == 0):
            raise Exception('Fingers do not match')

    ## Creates a template
        f.createTemplate()

        ## Saves template at new position number
        positionNumber = f.storeTemplate()
        f.loadTemplate(positionNumber, 0x01)

        scan = f.downloadCharacteristics(0x01)
        f.deleteTemplate(positionNumber)
        print('Finger scanned successfully!')

        data = {
            'Name': firstName,
            'LastName': lastName,
            'LicenseNo': licNo,
            'LMV': lmv,
            'biom': scan
        }
        driverBucketId = ref.post('/DrivingLicense/details', data)
    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
Esempio n. 26
0
##########################################################
#             |Fingerprint R307 Manage Menu|             #
#                                                        #
#  Start date of project is                              #
#                           09.10.2017                   #
#                                      Create by Luki    #
##########################################################

import tempfile
import hashlib
from pyfingerprint.pyfingerprint import PyFingerprint

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if (f.verifyPassword() == False):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

print 'What you want to do ?'
print 'For Index of FingerPrints press: [1]'
print 'For Search FingerPrint press: [2]'
print 'For Adding FingerPrint press: [3]'
print 'For Deleting FingerPrint press: [4]'
print 'For Download Image of FingerPrint press: [5]'
"""
PyFingerprint
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

"""

import hashlib
from pyfingerprint.pyfingerprint import PyFingerprint

## Search for a finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if (f.verifyPassword() == False):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
      str(f.getStorageCapacity()))

## Tries to search the finger and calculate hash
try:
Esempio n. 28
0
def enroll():
    import RPi.GPIO as GPIO
    import serial
    ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    import first
    import Triled
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    r, g, b = Triled.gpiolightconfig(21,20,16)
    GPIO.setup(r,GPIO.OUT), GPIO.setup(g,GPIO.OUT), GPIO.setup(b,GPIO.OUT)
    Triled.gpiolightout(21, 20, 16)

    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

        if ( f.verifyPassword() == False ):
            raise ValueError('The given fingerprint sensor password is wrong!')

    except Exception as e:
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
        exit(1)

## Gets some sensor information
    tempstored= str(f.getTemplateCount()) 
    tempstore = str(f.getStorageCapacity())

## Tries to enroll new finger
    try:
        print("Finger enrollment")
        print (tempstored + "/"+ tempstore +" slots used" )
        Triled.redon(r)
        code = '222444'
        count = 0 
        value =''
        print('Enter secure code')
        while count<6:
            data = ser.readline().decode('utf-8')
            if data!= '' and data[0] != 'A' and data[0] != 'B' and data[0] != 'C' and data[0] != 'D':
                print(data)
                count = count +1
                value = value + str(data[0])
            elif data != '' and data[0] == 'D':
                count = count - 1
                value =  value[0:count]
                if count< 0:
                    count= 0
        
        if code != value:
            print('incorrect code')
            Triled.redoff(r)
            Triled.redon(r)
            Triled.redoff(r)
            Triled.redon(r)
            Triled.redoff(r)
            first.startpoint()
        else:
            Triled.redoff(r)
            print('Waiting for finger...')
            Triled.blueon(b)

    ## Wait that finger is read
        while ( f.readImage() == False ):
            data = ser.readline().decode('utf-8')
            if data!= '' and data[0] == 'C':
                Triled.blueoff(b)
                first.startpoint()
            pass
        Triled.blueoff(b)
    ## Converts read image to characteristics and stores it in charbuffer 1
        f.convertImage(0x01)

    ## Checks if finger is already enrolled
        result = f.searchTemplate()
        positionNumber = result[0]

        if ( positionNumber >= 0 ):
            print('Template already exists at position #' + str(positionNumber))
            first.startpoint()

        print('Remove finger...')
        

        print('Waiting for same finger again...')
        Triled.blueon(b)

        ## Wait that finger is read again
        while ( f.readImage() == False ):
            data = ser.readline().decode('utf-8')
            if data!= '' and data[0] == 'C':
                first.startpoint()
            pass
        Triled.blueoff(b)
    ## Converts read image to characteristics and stores it in charbuffer 2
        f.convertImage(0x02)

    ## Compares the charbuffers
        if ( f.compareCharacteristics() == 0 ):
            print('Fingers do not match')
            first.startpoint()

    ## Creates a template
        f.createTemplate()

    ## Saves template at new position number
        positionNumber = f.storeTemplate()
        print('Finger enrolled successfully!')
        print('New template position #' + str(positionNumber))

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(0)
def index():
    a = request.args.get('a', 0, type=int)
    try:
        f = PyFingerprint('COM6', 57600, 0xFFFFFFFF, 0x00000000)
        if (f.verifyPassword() == False):
            raise ValueError('The given fingerprint sensor password is wrong!')

    except Exception as e:
        del f
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
        #exit(1)

    try:
        if a == 1:
            print('Waiting for finger...')
            while (f.readImage() == False):
                pass

            f.convertImage(0x01)
            result = f.searchTemplate()
            positionNumber = result[0]

            if (positionNumber >= 0):
                print('Template already exists at position #' +
                      str(positionNumber))
                return jsonify(result='1')
                #return render_template('recharge.html')
                #exit(0)
            return jsonify(result="Put your same finger on the sensor again !")
        if a == 2:
            print('Remove finger...')
            #time.sleep(2)

            print('Waiting for same finger again...')

            ## Wait that finger is read again
            while (f.readImage() == False):
                pass

            ## Converts read image to characteristics and stores it in charbuffer 2
            f.convertImage(0x02)

            ## Compares the charbuffers
            if (f.compareCharacteristics() == 0):
                raise Exception('Fingers do not match')

            ## Creates a template
            f.createTemplate()

            ## Saves template at new position number
            positionNumber = f.storeTemplate()
            print('Finger enrolled successfully!')
            print('New template position #' + str(positionNumber))
            return jsonify(result="Completed", id=str(positionNumber))

    except Exception as e:
        del f
        #f.__del__()
        print('Operation failed!')
        print('Exception message: ' + str(e))
        #exit(1)

    if a == 1:
        return jsonify(result="Put your same finger on the sensor again !")
    elif a == 2:
        return jsonify(result="Completed")

    return jsonify(result=str(cr))
Esempio n. 30
0
def enroll_user():

    # Intenta inicializar el sensor

    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

        if (f.verifyPassword() == False):
            raise ValueError(
                'La contraseña proporcionada para el sensor es erronea!')

    except Exception as e:
        print('El sensor de huellas dactilares no se pudo inicializar!')
        print('Mensaje de excepcion: ' + str(e))
        exit(1)

    # Intenta ingresar nuevos datos al sensor
    try:
        send_instructions('Ponga el dedo en el sensor')

        # Espera a que la imagen sea leída
        while (f.readImage() == False):
            pass

        # Convierte la imagen leída a características y la almacena en el buffer 1
        f.convertImage(0x01)

        # Se obtienen las características de la base de datos
        characteristics_data = retrieve_characteristics()
        for characteristic in characteristics_data:
            # Si la lista llega vacía, quiere decir que la información que llegó corresponde al votante que no tiene la
            # huella registrada, así que se omite esta prueba
            if len(characteristic) == 0:
                pass
            else:
                # Se sube una por una las listas con las características al buffer 2 para luego
                # compararlas con la imagen adquirida
                f.uploadCharacteristics(0x02, characteristic)

                compare_characteristics_payload = f.compareCharacteristics()

                # Umbral de decision para la aceptación de huellas dactilares
                if compare_characteristics_payload > 20:
                    send_instructions(
                        'La huella ya se encuentra registrada en la base de datos'
                    )
                    return jsonify(
                        value='',
                        error=
                        'La huella ya se encuentra registrada en la base de datos'
                    )

        send_instructions('Quite el dedo del sensor')
        time.sleep(2)

        send_instructions('Ponga el dedo en el sensor nuevamente')

        # Espera a que la imagen del dedo sea leída nuevamente
        while (f.readImage() == False):
            pass

        # Convierte la imagen leída a características y la almacena en el buffer 2
        f.convertImage(0x02)

        # Compara los buffers 1 y 2
        if (f.compareCharacteristics() == 0):
            # Si las huellas no son iguales se retorna un error
            send_instructions('Las huellas no corresponden')
            return jsonify(value='', error='Las huellas no corresponden')

        # Se crea la plantilla comparando la informacion almacenada en los buffers 1 y 2
        f.createTemplate()

        # Descarga las características almacenadas en el buffer 1, correspondientes a la plantilla recíen creada
        characteristics = f.downloadCharacteristics(0x01)

        send_instructions('Huella registrada correctamente!')
        return jsonify(
            # Se La lista(vector) que contiene las características de la huella
            value=characteristics,
            error='')

    except Exception as e:
        print('Operacion fallida!')
        print('Mensaje de excepción: ' + str(e))
        exit(1)
def authenticate():

    far = [[0, 50, 100], [20, 0, 60], [150, 40, 0]]
    station_names = [
        'Uttara North', 'Uttara Centre', 'Uttara South', 'Pallabi',
        'Mirpur 11', 'Mirpur-10', 'Kazipara', 'Shewrapara', 'Agargaon',
        'Bijoy Sarani', 'Farmgate', 'Karwan Bazar', 'Shahbag',
        'Dhaka University', 'Bangladesh Secretariat', 'Motijheel'
    ]

    data = request.get_json()

    try:
        f = PyFingerprint('COM6', 57600, 0xFFFFFFFF, 0x00000000)

        if (f.verifyPassword() == False):
            raise ValueError('The given fingerprint sensor password is wrong!')

    except Exception as e:
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
        data = {'s': 'Exception message: ' + str(e), 'bool_found': '0'}
        return json.dumps(data)

    try:

        data = request.get_json()
        chrr = json.loads(data)
        chr = chrr["tem"]
        c = list()
        for i in range(0, len(chr)):
            c.append(int(chr[i]))

        f.uploadCharacteristics(0x01, chr)
        result = f.searchTemplate()

        positionNumber = result[0]
        accuracyScore = result[1]

        if (positionNumber == -1):
            #del f
            #f.__del__()
            print("ok1")
            data = {'s': 'No match found!', 'bool_found': '0'}
            #f.loadTemplate(0, 0x01)
            #result = f.searchTemplate()
            print("ok2")
            print('No match found!')
            data = {'s': 'No match found!', 'bool_found': '0'}
            # exit(0)
        else:
            #f.__del__()
            #del f
            print("first else")
            if (chrr["entry_exit"] == 0):
                f.loadTemplate(0, 0x01)
                result = f.searchTemplate()
                f.__del__()
                u = User.query.filter_by(id=positionNumber).first()

                exit_station_number = int(chrr["station_number"])
                exit_station_name = station_names[exit_station_number]
                exit_time = chrr["scaned_time"]
                date = chrr["date"]
                entry_station_name = station_names[u.start_station]

                db_start_station = int(u.start_station)

                try:

                    fa = int(
                        u.money) - far[db_start_station][exit_station_number]
                    u.money = fa
                    print(far)
                    info = User_travel_history(
                        date=str(date),
                        entry_station=entry_station_name,
                        exit_station=exit_station_name,
                        entry_time=u.entry_time,
                        fare=str(far[db_start_station][exit_station_number]),
                        exit_time=exit_time,
                        human=u)
                    db.session.add(info)
                    db.session.commit()
                    #print("hi")
                    print('Found template')
                    data = {
                        's':
                        'Found template at position #' + str(positionNumber),
                        'bool_found': '1'
                    }
                    # print('The accuracy score is: ' + str(accuracyScore))
                except Exception as e:
                    print('Exception message: ' + str(e))
                    data = {'s': 'No match found!', 'bool_found': '0'}

            if (chrr["entry_exit"] == 1):
                f.loadTemplate(0, 0x01)
                result = f.searchTemplate()
                f.__del__()
                u = User.query.filter_by(id=positionNumber).first()
                if (u.money > 70):
                    u.start_station = int(chrr["station_number"])
                    u.entry_time = chrr["scaned_time"]
                    db.session.commit()
                    data = {'s': 'Enough money', 'bool_found': '1'}
                else:
                    data = {'s': 'Insufficent balance !', 'bool_found': '0'}

        #f.loadTemplate(0, 0x01)
        #result = f.searchTemplate()

        #f.__del__()

    except Exception as e:
        f.__del__()
        print('Operation failed!')
        print('Exception message: ' + str(e))
        data = {'s': 'No match found!', 'bool_found': '0'}

    return json.dumps(data)
Esempio n. 32
0
import time
from pyfingerprint.pyfingerprint import PyFingerprint

from tkinter import *

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))
  
class Application:
    def __init__(self, master=None):
        self.fontePadrao = ("Arial", "10")
        self.primeiroContainer = Frame(master)
        self.primeiroContainer["pady"] = 10
        self.primeiroContainer.pack()
  
        self.segundoContainer = Frame(master)
        self.segundoContainer["padx"] = 20
        self.segundoContainer.pack()
  
Esempio n. 33
0
import config
from pyfingerprint.pyfingerprint import PyFingerprint

try:
    port = config.figerScanPort
    f = PyFingerprint(port, 57600, 0xFFFFFFFF, 0x00000000)

    if (f.verifyPassword() == False):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
      str(f.getStorageCapacity()))

## Tries to delete the template of the finger
try:
    positionNumber = input(
        'Please enter the template position you want to delete: ')
    positionNumber = int(positionNumber)

    if (f.deleteTemplate(positionNumber) == True):
        print('Template deleted!')

except Exception as e:
    print('Operation failed!')
    print('Exception message: ' + str(e))
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from time import time, gmtime, strftime, sleep
from guizero import App, Picture, Waffle, Text,TextBox, Window, warn, info, PushButton, yesno
from pyfingerprint.pyfingerprint import PyFingerprint
import multiprocessing
import csv

# initialise fingerprint module
f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

#search for ID in a file when user logins
#this is to avoid duplicate login
def searchID(IDD):
    stat = False # flag to check the search status
    print(IDD)
    remFile = open('remdata.csv', 'r') # open the file in read mode
    csvReader = csv.reader(remFile) # pass file to csv reader
    #print(csvReader)
    data = list(csvReader) # convert the contents to a list
    print(data)
    for i in data: #iterate through the list
        # update attendance text with the number of logins in the file
        attendance_text.value = str(len(i)) +' out of ' + str(f.getTemplateCount()) 
        for j in range(len(i)):
            if i[j] == IDD: # if user ID is found, stat is true
                stat = True
     
    # close the file
    remFile.close()
    return stat       
Esempio n. 35
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2, urllib
import hashlib
from pyfingerprint.pyfingerprint import PyFingerprint

## Search for a finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if (f.verifyPassword() == False):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
      str(f.getStorageCapacity()))

## Tries to search the finger and calculate hash
try:
    print('Waiting for finger...')

    ## Wait that finger is read
    while (f.readImage() == False):
import time
import RPi.GPIO as GPIO
ser = serial.Serial('/dev/ttyACM0', 9600)

import hashlib
from pyfingerprint.pyfingerprint import PyFingerprint

control = [5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10]
servo = 22
GPIO.setmode(GPIO.BOARD)
GPIO.setup(servo, GPIO.OUT)
p = GPIO.PWM(servo, 50)  # 50hz frequency
p.start(2.5)  # starting duty cycle ( it set the servo to 0 degree )
## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if (f.verifyPassword() == False):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
      str(f.getStorageCapacity()))

while 1:
    ## Tries to search the finger and calculate hash
Esempio n. 37
0
class Fingerprint(KeyboardAbstractBaseClass):
    name = 'Fingerprint Reader'
    def readFingerprint(self):
        logger.debug("readFingerprint() started for %s",self.__timeout)
        while (not self._shutdown and self.__active):
            try:
                ## Warten bis ein Finger erkannt wurde.
                ## Falls zwischendurch DoorPi beendet wird (multithreading!) oder der Sensor deaktiviert wird - Abbruch
                if (self._shutdown or not self.__active):
                    return None
                ## Falls der Sensor nicht permanent aktiv ist und das Aktivitätsintervall überschritten ist - Abbruch
                if (self.__timeout > 0 and (time.time() > self.__timeout)):
                    self.__active = False
                    return None
                if (self.__sensor.readImage() == True):
                    ## Characteristics aus dem gelesenen Fingerabdruck auslesen und hinterlegen
                    self.__sensor.convertImage(0x01)
                    ## Datenbank nach diesen Characteristics durchsuchen
                    result = self.__sensor.searchTemplate()
                    positionNumber = result[0]
                    accuracyScore = result[1]
                    ## Input-Pin entsprechend der gefundenen Position aktivieren
                    self.last_key = positionNumber
                    self.last_key_time = time.time()
                    logger.debug('Found template at position #' + str(positionNumber))
                    logger.debug('The accuracy score is: ' + str(accuracyScore))

                    ## Finger entweder gar nicht oder nicht exakt genug erkannt.
                    if (positionNumber == -1) or (accuracyScore < self.__security):
                        ## Finger unbekannt - Event auslösen
                        doorpi.DoorPi().event_handler('OnFingerprintFoundUnknown', __name__)
                    else:
                        ## Finger bekannt - Event auslösen
                        doorpi.DoorPi().event_handler('OnFingerprintFoundKnown', __name__)
                        ## Dem Finger zugeordnete Events auslösen
                        if (self.last_key in self._InputPins):
                            self._fire_OnKeyDown(self.last_key, __name__)
                            self._fire_OnKeyPressed(self.last_key, __name__)
                            self._fire_OnKeyUp(self.last_key, __name__)

            except Exception as ex:
                logger.exception(ex)

    def __init__(self, input_pins, output_pins, keyboard_name, conf_pre, conf_post, *args, **kwargs):
        self.keyboard_name = keyboard_name
        self._InputPins = map(int, input_pins)
        self._OutputPins = map(int, output_pins)
        self.last_key = ""
        self.last_key_time = 0
        self.__active = False
        self.__timeout = 0

        ## Spezielle Handler für (Un-)bekannte Finger registrieren
        doorpi.DoorPi().event_handler.register_event('OnFingerprintFoundUnknown', __name__)
        doorpi.DoorPi().event_handler.register_event('OnFingerprintFoundKnown', __name__)
        ## Config-Einträge lesen, falls dort vorhanden.
        section_name = conf_pre + 'keyboard' + conf_post
        self.__port = doorpi.DoorPi().config.get(section_name, 'port', "/dev/ttyAMA0")
        self.__baudrate = doorpi.DoorPi().config.get_int(section_name, 'baudrate', 57600)
        self.__sensoraddr = doorpi.DoorPi().config.get(section_name, 'address', 0xFFFFFFFF)
        self.__password = doorpi.DoorPi().config.get(section_name, 'password', 0x00000000)
        self.__security = doorpi.DoorPi().config.get_int(section_name, 'security', 70)
        self.__ontime = doorpi.DoorPi().config.get_int(section_name, 'ontime', False)

        ## Sensor initialisieren
        try:
            self.__sensor = PyFingerprint(self.__port, self.__baudrate, self.__sensoraddr, self.__password)
            if (self.__sensor.verifyPassword() == False):
                logger.warning('The given fingerprint sensor password is wrong!')

            logger.debug('Currently used templates: ' + str(self.__sensor.getTemplateCount()) + '/' + str(self.__sensor.getStorageCapacity()))

            ## Events für hinterlegte InputPins registrieren (damit diese auch ausgelöst werden)
            for input_pin in self._InputPins:
                self._register_EVENTS_for_pin(input_pin, __name__)

            ## Dauerbetrieb oder nur auf Kommando? (ontime ist null)
            if self.__ontime < 1:
                self.__active = True
                logger.debug('ontime =0 ! Running permanently')
                ## Thread für den eigtl Lesevorgang starten
                self._shutdown = False
                self._thread = threading.Thread(target = self.readFingerprint)
                self._thread.daemon = True
                self._thread.start()
                self.register_destroy_action()

        except Exception as ex:
                logger.exception(ex)


    def destroy(self):
        if self.is_destroyed: return
        self._shutdown = True
        doorpi.DoorPi().event_handler.unregister_source(__name__, True)
        self.__destroyed = True

    def status_input(self, tag):
        return (tag == self.last_key)

    def set_output(self, pin, value, log_output = True):
        parsed_pin = doorpi.DoorPi().parse_string("!" + str(pin) + "!")
        if parsed_pin != "!" + str(pin) + "!":
            pin = parsed_pin
            logger.debug("out(parsed pin = %s)", parsed_pin)

        pin = int(pin)
        value = str(value).lower() in HIGH_LEVEL
        log_output = str(log_output).lower() in HIGH_LEVEL

        if pin not in self._OutputPins:
            return False

        if log_output:
            logger.debug("out(pin = %s, value = %s, log_output = %s)", pin, value, log_output)

        ## Aktivieren oder deaktivieren?
        old_state = self.__active
        self.__active = (value > 0)
        ## Timeout-Intervall anpassen (Bei 0 stoppt der Vorgang sowohl dadurch als auch da active false wird)
        self.__timeout = time.time() + self.__ontime

        ## Falls noch kein Lesevorgang läuft, diesen ggf. starten
        if self.__active and self.__active != old_state:
            ## Thread für den eigtl Lesevorgang starten
            self._shutdown = False
            self._thread = threading.Thread(target = self.readFingerprint)
            self._thread.daemon = True
            self._thread.start()
            self.register_destroy_action()

        return True
Esempio n. 38
0
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

@author: Bastian Raschke <*****@*****.**>
"""

import time
from pyfingerprint.pyfingerprint import PyFingerprint


## Enrolls new finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently stored templates: ' + str(f.getTemplateCount()))

## Tries to enroll new finger
try:
    print('Waiting for finger...')
Esempio n. 39
0
class FingerprintThread(threading.Thread):
    template = None

    def __init__(self, app):
        super().__init__(daemon=True)

        self.app = app
        self.f = None
        self._mode = None
        self._continue = threading.Event()

        # Default mode SEARCH
        self.set_mode(SEARCH)

        self.start()

    def set_mode(self, mode):
        self._mode = mode
        self._continue.set()

    def delete_template(self, positionNumber):
        # wait readImage
        self._continue.clear()
        time.sleep(0.5)

        b = self.f.deleteTemplate(int(positionNumber))
        if b:
            print('FingerprintThread:Template deleted!')

        # continue readImage
        self._continue.set()
        return b

    def run(self):
        try:
            self.f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF,
                                   0x00000000)

            if not self.f.verifyPassword():
                raise ValueError(
                    'The given fingerprint sensor password is wrong!')

        except Exception as e:
            print('The fingerprint sensor could not be initialized!')
            print('Exception message: ' + str(e))

        print('Currently used templates: ' + str(self.f.getTemplateCount()) +
              '/' + str(self.f.getStorageCapacity()))

        # REGISTER sequence
        sequence = 1

        while True:  # mainloop forever
            retry = 0
            while True:  # retry
                print('Waiting for finger...')
                retry += 1
                try:
                    while not self.f.readImage():
                        print('looping .readImage()')
                        self._continue.wait()
                        time.sleep(0.5)
                    break

                except Exception as e:
                    print('PyFingerprint:{}, try {} of 3'.format(e, retry))
                    if retry == 3:
                        raise Exception(
                            'PyFingerprint: Failed to read image 3 times, exiting.'
                        )
                    # delay 2 seconds before next try
                    time.sleep(2)
            # end while retry == 3

            position_number = None

            if self._mode == SEARCH:
                self.f.convertImage(1)
                FingerprintThread.template = self.f.searchTemplate()
                position_number = FingerprintThread.template[0]

            elif self._mode == REGISTER:
                if sequence == 1:
                    self.f.convertImage(1)
                    FingerprintThread.template = self.f.searchTemplate()

                    # Checks if finger is already enrolled
                    positionNumber = FingerprintThread.template[0]
                    if positionNumber < 0:
                        # OK, no event, continue with sequence 2
                        position_number = None
                        sequence += 1
                    else:
                        # event state=-1 - finger allready enrolled
                        position_number = -1

                elif sequence == 2:
                    self.f.convertImage(2)
                    if self.f.compareCharacteristics():
                        self.f.createTemplate()
                        position_number = self.f.storeTemplate()
                    else:
                        # event state=-2 - .compareCharacteristics failed
                        position_number = -2

                    # Reset MODE
                    sequence = 1

            if position_number is not None:
                self.app.event_generate('<<FINGERPRINT>>',
                                        when='tail',
                                        state=position_number)

                if self._mode == REGISTER:
                    # wait until set_mode(...) is called
                    self._continue.clear()
                    self._continue.wait()

            # Delay before next finger scan
            time.sleep(2)
Esempio n. 40
0
"""
PyFingerprint
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

@author: Bastian Raschke <*****@*****.**>
"""

from pyfingerprint.pyfingerprint import PyFingerprint


# Shows the template index table

# Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

    if (f.verifyPassword() == False):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

# Gets some sensor information
print('Currently stored templates: ' + str(f.getTemplateCount()))

# Tries to show a template index table page
try:
    page = raw_input(
Esempio n. 41
0
import hashlib
from pyfingerprint.pyfingerprint import PyFingerprint

## Search for a finger

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/serial0', 9600, 0xFFFFFFFF, 0x00000000)

    if (f.verifyPassword() == False):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)


def Attendance_Mark():
    ## Gets some sensor information
    #print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

    ## Tries to search the finger and calculate hash
    try:
        #print('Waiting for finger...')

        ## Wait that finger is read
        while (f.readImage() == False):
            pass

        ## Converts read image to characteristics and stores it in charbuffer 1
def pam_sm_authenticate(pamh, flags, argv):
    """
    PAM service function for user authentication.

    @param pamh
    @param flags
    @param argv

    @return int
    """

    ## The authentication service should return [PAM_AUTH_ERROR] if the user has a null authentication token
    flags = pamh.PAM_DISALLOW_NULL_AUTHTOK

    ## Initialize authentication progress
    try:
        ## Tries to get user which is asking for permission
        userName = pamh.ruser

        ## Fallback
        if ( userName == None ):
            userName = pamh.get_user()

        ## Be sure the user is set
        if ( userName == None ):
            raise UserUnknownException('The user is not known!')

        # Checks if path/file is readable
        if ( os.access(CONFIG_FILE, os.R_OK) == False ):
            raise Exception('The configuration file "' + CONFIG_FILE + '" is not readable!')

        configParser = ConfigParser.ConfigParser()
        configParser.read(CONFIG_FILE)

        ## Log the user
        auth_log('The user "' + userName + '" is asking for permission for service "' + str(pamh.service) + '".', syslog.LOG_DEBUG)

        ## Checks if the the user was added in configuration
        if ( configParser.has_option('Users', userName) == False ):
            raise Exception('The user was not added!')

        ## Tries to get user information (template position, fingerprint hash)
        userData = configParser.get('Users', userName).split(',')

        ## Validates user information
        if ( len(userData) != 2 ):
            raise InvalidUserCredentials('The user information of "' + userName + '" is invalid!')

        expectedPositionNumber = int(userData[0])
        expectedFingerprintHash = userData[1]

    except UserUnknownException as e:
        auth_log(str(e), syslog.LOG_ERR)
        return pamh.PAM_USER_UNKNOWN

    except InvalidUserCredentials as e:
        auth_log(str(e), syslog.LOG_ERR)
        return pamh.PAM_AUTH_ERR

    except Exception as e:
        auth_log(str(e), syslog.LOG_ERR)
        return pamh.PAM_IGNORE

    ## Initialize fingerprint sensor
    try:
        ## Gets sensor connection values
        port = configParser.get('PyFingerprint', 'port')
        baudRate = int(configParser.get('PyFingerprint', 'baudRate'), 10)
        address = int(configParser.get('PyFingerprint', 'address'), 16)
        password = int(configParser.get('PyFingerprint', 'password'), 16)

        ## Tries to init PyFingerprint
        fingerprint = PyFingerprint(port, baudRate, address, password)

        if ( fingerprint.verifyPassword() == False ):
            raise Exception('The given fingerprint sensor password is wrong!')

    except Exception as e:
        auth_log('The fingerprint sensor could not be initialized: ' + str(e), syslog.LOG_ERR)
        showPAMTextMessage(pamh, 'Sensor initialization failed!', True)
        return pamh.PAM_IGNORE

    if ( showPAMTextMessage(pamh, 'Waiting for finger...') == False ):
        return pamh.PAM_CONV_ERR

    ## Authentication progress
    try:
        ## Tries to read fingerprint
        while ( fingerprint.readImage() == False ):
            pass

        fingerprint.convertImage(0x01)

        ## Gets position of template
        result = fingerprint.searchTemplate()
        positionNumber = result[0]

        ## Checks if the template position is invalid
        if ( positionNumber == -1 ):
            raise Exception('No match found!')

        ## Checks if the template position is correct
        if ( positionNumber != expectedPositionNumber ):
            raise Exception('The template position of the found match is not equal to the stored one!')

        ## Gets characteristics
        fingerprint.loadTemplate(positionNumber, 0x01)
        characterics = fingerprint.downloadCharacteristics(0x01)

        ## Calculates hash of template
        fingerprintHash = hashlib.sha256(str(characterics)).hexdigest()

        ## Checks if the calculated hash is equal to expected hash from user
        if ( fingerprintHash == expectedFingerprintHash ):
            auth_log('Access granted!')
            showPAMTextMessage(pamh, 'Access granted!')
            return pamh.PAM_SUCCESS
        else:
            auth_log('The found match is not assigned to user!', syslog.LOG_WARNING)
            showPAMTextMessage(pamh, 'Access denied!', True)
            return pamh.PAM_AUTH_ERR

    except Exception as e:
        auth_log('Fingerprint read failed: ' + str(e), syslog.LOG_CRIT)
        showPAMTextMessage(pamh, 'Access denied!', True)
        return pamh.PAM_AUTH_ERR

    ## Denies for default
    return pamh.PAM_AUTH_ERR
def finger():
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

        if ( f.verifyPassword() == False ):
            raise ValueError('The given fingerprint sensor password is wrong!')

    except Exception as e:
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
        exit(1)

    ## Gets some sensor information
    print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

    ## Tries to enroll new finger
    while 1:
        disp.clear()
        disp.display()
        draw.rectangle((0,0,width,height), outline=0, fill=0)  
        draw.text((x, top + 10),       'Welcome to Enroll' ,  font=font, fill=255)
        draw.text((x, top + 35),       'Waiting for finger...' ,  font=font, fill=255)
        print('Waiting for finger...')
        disp.image(image)
        disp.display()
        time.sleep(.1)


        ## Wait that finger is read
        while ( f.readImage() == False ):
            pass

        ## Converts read image to characteristics and stores it in charbuffer 1
        f.convertImage(0x01)

        ## Checks if finger is already enrolled
        result = f.searchTemplate()
        positionNumber = result[0]

        if ( positionNumber >= 0 ):
            disp.clear()
            disp.display()
            draw.rectangle((0,0,width,height), outline=0, fill=0)   
            draw.text((x, top + 40),'Finger already exists' ,  font=font, fill=255)
            disp.image(image)
            disp.display()
            time.sleep(1)

            print('Template already exists at position #' + str(positionNumber))
            os.system("python ~/Desktop/fingerprint/main.py")
        disp.clear()
        disp.display()
        draw.rectangle((0,0,width,height), outline=0, fill=0)
        draw.text((x, top + 40),       'Remove finger' ,  font=font, fill=255)
        disp.image(image)
        disp.display()
        time.sleep(.1)
        print('Remove finger...')
        time.sleep(2)

        disp.clear()
        disp.display()
        draw.rectangle((0,0,width,height), outline=0, fill=0)
    
        draw.text((x, top + 35),       'Waiting for same' ,  font=font, fill=255)
        draw.text((x, top + 43),       'finger again' ,  font=font, fill=255)
        disp.image(image)
        disp.display()
        

        print('Waiting for same finger again...')
        time.sleep(.1)
        

        ## Wait that finger is read again
        while ( f.readImage() == False ):
            pass

        ## Converts read image to characteristics and stores it in charbuffer 2
        f.convertImage(0x02)

        ## Compares the charbuffers
        if ( f.compareCharacteristics() == 0 ):
            disp.clear()
            disp.display()
            draw.rectangle((0,0,width,height), outline=0, fill=0)   
            draw.text((x, top + 35),       'Fingers do not match' ,  font=font, fill=255)
            disp.image(image)
            disp.display()
            time.sleep(2)
            disp.clear()
            disp.display()
            draw.rectangle((0,0,width,height), outline=0, fill=0)   
            # os.system("python ~/Desktop/fingerprint/main.py")

        ## Creates a template
        f.createTemplate()



        ## Saves template at new position number
        positionNumber = f.storeTemplate()
        print('tihis is code ' , code)
        sql_enroll(code, positionNumber)

           #     print("Wrong Input")
        disp.clear()
        disp.display()
        draw.rectangle((0,0,width,height), outline=0, fill=0)
        draw.text((x, top + 26),        'Employee Number:' ,  font=font, fill=255)
        draw.text((x, top + 36),       code  ,  font=font, fill=255)
        draw.text((x, top + 46),        'Employee add suceess' ,  font=font, fill=255)
        disp.image(image)
        disp.display()
        GPIO.cleanup()
        time.sleep(2)
        os.system("python main.py")    
Esempio n. 44
0
"""
PyFingerprint
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

"""

from pyfingerprint.pyfingerprint import PyFingerprint


## Shows the template index table
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to show a template index table page
try:
    page = input('Please enter the index page (0, 1, 2, 3) you want to see: ')
Esempio n. 45
0
PyFingerprint
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

"""

import hashlib
from pyfingerprint.pyfingerprint import PyFingerprint


## Search for a finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to search the finger and calculate hash
try:
    print('Waiting for finger...')