def index_old():
    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))
        exit(1)

    try:
        print('Waiting for finger...')

        while (f.readImage() == False):
            pass

        f.convertImage(0x01)
        cr = f.downloadCharacteristics(0x01)
        #print(f.downloadCharacteristics(0x01))

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
    a = request.args.get('a', 0, type=int)
    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))
Ejemplo n.º 2
0
def search(status=2):  #0 = on time    1 = tardy    2 = absent
    ## 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):
            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))
            set_status(str(positionNumber), status)

            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))
Ejemplo n.º 3
0
def hash():
    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))
        return -10

    ## Gets some sensor information
    ## Tries to search the finger and calculate hash
    try:

        lcddeneme.yaz("Parmaginizi", "okutun")
        print('Parmağınızı okutun')

        ## 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):
            lcddeneme.yaz("Kayit", "Bulunamadi")
            print('Kayıt bulunamadı')
            time.sleep(2.5)
            return -10
        else:
            pass

        ## 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

        b = int(positionNumber)
        return b
    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        return -10
Ejemplo n.º 4
0
def techBinFingerPrint():
    try:
        f = PyFingerprint('/dev/ttyUSB1', 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))
    try:
        print('Waiting for finger...')

        while (f.readImage() == False):
            pass
        f.convertImage(0x01)

        result = f.searchTemplate()

        positionNumber = result[0]
        accuracyScore = result[1]
        if (positionNumber == -1):
            print('New user welcome...')
            #################################################
            print("Don't Remove finger...")
            time.sleep(2)

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

            while (f.readImage() == False):
                pass

            f.convertImage(0x02)

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

            f.createTemplate()

            positionNumber = f.storeTemplate()
            print('Finger enrolled successfully!')
            print('New template position #' + str(positionNumber))
            return str(positionNumber)
        else:
            print('Found template at position #' + str(positionNumber))
            return str(positionNumber)
        # print('The accuracy score is: ' + str(accuracyScore))

        f.loadTemplate(positionNumber, 0x01)

        characterics = str(f.downloadCharacteristics(0x01)).encode('utf-8')

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

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
Ejemplo n.º 5
0
def checkAuth():
    ## 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):
            pass

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

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

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

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
def register(id):
    #if current_user.is_authenticated:
    # return redirect(url_for('index'))
    try:
        f = PyFingerprint('COM6', 57600, 0xFFFFFFFF, 0x00000000)
        if (f.verifyPassword() == False):
            raise ValueError('The given fingerprint sensor password is wrong!')

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

    positionNumber = int(id)
    f.loadTemplate(positionNumber, 0x01)
    temm = f.downloadCharacteristics(0x01)
    tem = str(temm)

    form = RegistrationForm()
    if form.validate_on_submit():
        print("working")
        user = User(id=positionNumber,
                    phonenumber=form.phonenumber.data,
                    name=form.name.data,
                    email=form.email.data,
                    template=tem,
                    money=0)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations, you are now a registered user!')
        return render_template('booth_login_first.html')
    else:
        print(form.errors)
    return render_template('register.html', title='Register', form=form)
        ID = input("Please enter ID of student")
        url = 'http://172.16.190.254:5000/api/fingerprint/' + str(ID)
        r = requests.get(url)
        if(r.status_code == 200)
        print(r.text)
        response = r.json
        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)
        print("Input finger")
        scannedFinger = f.downloadCharacteristics(0x01)
        characteristics = str(f.downloadCharacteristics(0x01)).encode('utf-8')
        print(scannedFinger)
        result,score = findFinger(response)
        if (result != 0):
            print("Finger found!")
            print(result)
            print("With an accuracy score: "+ str(score))
except Exception as e:
    print('Operation failed!')
    print('Exception message: ' + str(e))
    exit(1)


def findFinger(response):
    for x in response:
Ejemplo n.º 8
0
    f.convertImage(0x01)

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

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

    while (f.readImage() == False):
        pass

    f.convertImage(0x02)

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

    characterics1 = f.downloadCharacteristics(0x01)
    #print(characterics1)
    characterics2 = f.downloadCharacteristics(0x02)
    #print(characterics2)

    f.createTemplate()

    characterics3 = f.downloadCharacteristics(0x01)
    print('*' * 200)
    print(characterics3)
    mydict = {"_id": enroll_id, "name": name, "finger_array": characterics3}
    x = mycol.insert_one(mydict)

    myquery = {"_id": 1}
    mydoc = mycol.find(myquery)
    for x in mydoc:
Ejemplo n.º 9
0
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
Ejemplo n.º 10
0
def hash():  
    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
    ## Tries to enroll new finger
    try:
        lcddeneme.yaz("Parmaginizi","okutun")
        print('Parmağınızı okutun')

        ## 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 ):
            lcddeneme.yaz("Parmak izi", "Zaten kayitli")
            print('Parmak izi Zaten kayıtlı')
            return -10
        lcddeneme.yaz("Parmaginizi","cekin")
        print('Parmağınızı çekin')
        time.sleep(2)
        lcddeneme.yaz("Parmaginizi","Tekrar okutun")
        print('Parmağınızı tekrar okutun')

        ## 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('Parmak izi Algılanamadı')
            return -10
        ## Creates a template
        f.createTemplate()

        ## Saves template at new position number
        positionNumber = f.storeTemplate()
        characterics = str(f.downloadCharacteristics(0x01)).encode('utf-8')
        b=int(positionNumber)
        return (b)
    except Exception as e:
        print('İşlem başarısız')
        print(str(e))
        return -10
def fprint():
    ## 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))
    

    ## 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()

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

        if ( positionNumber == -1 ):
            print('No match found!')

        else:
            print('Found template at position #' + str(positionNumber))
            print('The accuracy score is: ' + str(accuracyScore))
            return True
            '''if(s_mode==0):
                s_mode=1
                DC=1./18.*(120)+2
                pwm.ChangeDutyCycle(DC)
            else:
                s_mode=0
                DC=1./18.*(60)+2
                pwm.ChangeDutyCycle(DC)'''

        ## 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))
Ejemplo n.º 12
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))
Ejemplo n.º 13
0
class Biometric:
    def __init__(self):
        self.initialize()
        return

    def initialize(self):
        self.f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
        if not self.f.verifyPassword():
            raise ValueError('The given fingerprint sensor password is wrong!')

    def getSureHash(self):
        hash1 = self.getFPrintHash()
        hash2 = self.getFPrintHash()
        hash3 = self.getFPrintHash()
        hash4 = self.getFPrintHash()
        return self.most_frequent()

    def most_frequent(self, List):
        counter = 0
        num = List[0]

        for i in List:
            curr_frequency = List.count(i)
            if (curr_frequency > counter):
                counter = curr_frequency
                num = i

        return num

    def getFPrintHash(self):
        # Wait that finger is read
        while not self.f.readImage():
            pass

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

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

        if positionNumber >= 0:
            return self.getHash(positionNumber)

        time.sleep(2)

        # Wait that finger is read again
        while not self.f.readImage():
            pass

        # Converts read image to characteristics and stores it in charbuffer 2
        self.f.convertImage(0x02)
        # Compares the charbuffers
        if self.f.compareCharacteristics() == 0:
            raise Exception('Fingers do not match')
        # Creates a template
        self.f.createTemplate()
        # Saves template at new position number
        positionNumber = self.f.storeTemplate()
        return self.getHash(positionNumber)

    def getHash(self, positionNumber):
        # Loads the found template to charbuffer 1
        self.f.loadTemplate(positionNumber, 0x01)
        # Downloads the characteristics of template loaded in charbuffer 1
        characterics = str(
            self.f.downloadCharacteristics(0x01)).encode('utf-8')
        # Hashes characteristics of template
        fprint_hash = hashlib.sha256(str(positionNumber)).hexdigest()
        return fprint_hash
Ejemplo n.º 14
0
    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, FINGERPRINT_CHARBUFFER1)

    ## Downloads the characteristics of template loaded in charbuffer 1
    characterics = str(
        f.downloadCharacteristics(FINGERPRINT_CHARBUFFER1)).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)
Ejemplo n.º 15
0
def search():
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

        if (f.verifyPassword() == False):
            GPIO.output(BLUE, 1)
            sleep(1)
            GPIO.output(BLUE, 0)
            raise ValueError('The given fingerprint sensor password is wrong!')

    except Exception as e:
        GPIO.output(BLUE, 1)
        sleep(1)
        GPIO.output(BLUE, 0)
        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

        print('Downloading image (this take a while)...')

        if (os.path.isfile('/home/pi/webapp/static/fingerprint.bmp')):
            os.remove('/home/pi/webapp/static/fingerprint.bmp')

        imageDestination = '/home/pi/webapp/static/fingerprint.bmp'
        f.downloadImage(imageDestination)
        print('The image was saved to "' + imageDestination + '".')

        ## 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):
            GPIO.output(RED, 1)
            sleep(1)
            GPIO.output(RED, 0)
            print('No match found!')
            return 0
        else:
            GPIO.output(GREEN, 1)
            sleep(1)
            GPIO.output(GREEN, 0)
            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)).encode('utf-8')

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

        return 1

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
Ejemplo n.º 16
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)
Ejemplo n.º 17
0
class Plugin(plugin.PluginProto):
 PLUGIN_ID = 208
 PLUGIN_NAME = "ID - Serial Fingerprint Module (EXPERIMENTAL)"
 PLUGIN_VALUENAME1 = "ID"

 def __init__(self,taskindex): # general init
  plugin.PluginProto.__init__(self,taskindex)
  self.dtype = rpieGlobals.DEVICE_TYPE_SER
  self.vtype = rpieGlobals.SENSOR_TYPE_SINGLE
  self.valuecount = 1
  self.senddataoption = True
  self.recdataoption = False
  self.timeroption = True
  self.timeroptional = True
  self.formulaoption = True
  self.fp = None
  self.readinprogress=0
  self.initialized=False
  self.initcount = 0

 def webform_load(self): # create html page for settings
  choice1 = self.taskdevicepluginconfig[0]
  options = rpiSerial.serial_portlist()
  if len(options)>0:
   webserver.addHtml("<tr><td>Serial Device:<td>")
   webserver.addSelector_Head("p208_addr",False)
   for o in range(len(options)):
    webserver.addSelector_Item(options[o],options[o],(str(options[o])==str(choice1)),False)
   webserver.addSelector_Foot()
   webserver.addFormNote("Address of the FPM serial port")
  else:
   webserver.addFormNote("No serial ports found")
  options = ["None", "Valid", "Position","SHA2"]
  optionvalues = [0, 1, 2,3]
  webserver.addFormSelector("Indicator1","plugin_208_ind0",len(options),options,optionvalues,None,self.taskdevicepluginconfig[1])
  webserver.addFormSelector("Indicator2","plugin_208_ind1",len(options),options,optionvalues,None,self.taskdevicepluginconfig[2])
  webserver.addFormSelector("Indicator3","plugin_208_ind2",len(options),options,optionvalues,None,self.taskdevicepluginconfig[3])
  if self.enabled and self.initialized:
   try:
    webserver.addFormNote("Stored fingerprints: "+ str(self.fp.getTemplateCount())+"/"+str(self.fp.getStorageCapacity()))
   except:
    pass
  webserver.addHtml("<tr><td><a href='/finger'>Management page</a>")
  return True

 def webform_save(self,params): # process settings post reply
  try:
   self.taskdevicepluginconfig[0] = str(webserver.arg("p208_addr",params)).strip()
   for v in range(0,3):
    par = webserver.arg("plugin_208_ind"+str(v),params)
    if par == "":
     par = -1
    else:
     par=int(par)
    if str(self.taskdevicepluginconfig[v+1])!=str(par):
     self.uservar[v] = 0
    self.taskdevicepluginconfig[v+1] = par
    if int(par)>0 and self.valuecount!=v+1:
     self.valuecount = (v+1)
   if self.valuecount == 1:
    self.vtype = rpieGlobals.SENSOR_TYPE_SINGLE
   elif self.valuecount == 2:
    self.vtype = rpieGlobals.SENSOR_TYPE_DUAL
   elif self.valuecount == 3:
    self.vtype = rpieGlobals.SENSOR_TYPE_TRIPLE
  except Exception as e:
   misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,str(e))
  return True

 def plugin_init(self,enableplugin=None):
  plugin.PluginProto.plugin_init(self,enableplugin)
  self.taskdevicepluginconfig[0] = str(self.taskdevicepluginconfig[0]).strip()
  self.readinprogress=0
  self.initialized=False
  try:
   if self.initcount > 2:
    self.initcount = 0
    self.enabled = False
  except:
   self.initcount = 0
  if self.valuecount == 1:
    self.vtype = rpieGlobals.SENSOR_TYPE_SINGLE
  elif self.valuecount == 2:
    self.vtype = rpieGlobals.SENSOR_TYPE_DUAL
  elif self.valuecount == 3:
    self.vtype = rpieGlobals.SENSOR_TYPE_TRIPLE
  if self.enabled and self.taskdevicepluginconfig[0]!="" and self.taskdevicepluginconfig[0]!="0":
   time.sleep(0.5)
   try:
    if self.fp is not None:
     self.fp.__del__()
   except:
    pass
   try:
    time.sleep(2)
    self.fp = PyFingerprint(self.taskdevicepluginconfig[0],57600,0xFFFFFFFF,0)
    time.sleep(0.5)
    if self.fp.verifyPassword()==False:
     misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"FPM password wrong")
     self.fp = None
    self.initialized = True
    misc.addLog(rpieGlobals.LOG_LEVEL_INFO,"FPM initialized")
   except Exception as e:
    self.fp = None
    self.initialized = False
    misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"FPM init error: "+str(e))
   if self.initialized==False:
    self.initcount += 1
    time.sleep(3)
    self.plugin_init()

 def plugin_read(self): # deal with data processing at specified time interval
  result = False
#  nochange = (self.interval>0)
  change = False
  if self.initialized and self.readinprogress==0 and self.enabled:
   self.readinprogress = 1
   misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,"FPM scan")
   if self.interval>0 and self.interval<2:
    scantime = 0.8
   else:
    scantime = 2
   pos = -1
   try:
#    print("readimg") #debug
    st = time.time()
    readok = True
    while (self.fp.readImage() == False):
     if time.time()-st>=scantime:
      readok = False
      break
    self.fp.convertImage(0x01)
    result = self.fp.searchTemplate()
    pos = result[0]
    score = result[1]
   except Exception as e:
    pass
   value = "0"
   if readok:
    for v in range(0,3):
     vtype = int(self.taskdevicepluginconfig[v+1])
     if vtype == 1:
      if pos>-1:
       value = 1
      else:
       value = 0
     elif vtype == 2:
      value = pos
     elif vtype == 3:
      if pos>-1:
       value = "0"
       try:
        self.fp.loadTemplate(pos,0x01)
        chars = str(self.fp.downloadCharacteristics(0x01)).encode('utf-8')
        value = hashlib.sha256(chars).hexdigest()
       except:
        value = "0"
     if vtype in [1,2,3]:
      if str(self.uservar[v]) != str(value):
       self.set_value(v+1,value,False)
       change = True
   if change:
    self.plugin_senddata()
   if readok==False and self.interval==0:
    misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,"FPM read failed")
   self._lastdataservetime = rpieTime.millis()
   result = True
   self.readinprogress = 0
  return result
Ejemplo n.º 18
0
def Scanfinger():

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

        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()))

    try:
        print('Scan Finger...')
        lcd_string("Scan Finger:", LCD_LINE_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)

        ## Searchs template
        result = f.searchTemplate()

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

        if (positionNumber == -1):
            print('No match found!')
            lcd_string('Finger Not Found', LCD_LINE_3)
            lcd_string('ERROR: ', LCD_LINE_2)
            time.sleep(5)
            #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)).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)

    return (positionNumber)
def enroll():
    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)

        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))
        ## 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')

        char = (hashlib.sha256(characterics).hexdigest())
    ## Hashes characteristics of template
    ##  print(char)

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
    return (char)
Ejemplo n.º 20
0
class User():
    def __init__(self):
        self.finger = None
        self.digit = None
        self.FLAG = True
        self.inserted_password = ''
        self.cnt_ENTER = 0
        self.cnt_OUT = 0
        self.data_flag = 'active'
        self.positive_flag = ''
        self.camera_flag = 'active'
        #self.CamThreadFlag = True
    def ResetButtonCallback(self, channel):
        diode.resetAll()
        self.cnt_ENTER = 0
        self.cnt_OUT = 0
        self.FLAG = True
        self.digit = None
        self.inserted_password = ''
        self.data_flag = 'active'
        self.positive_flag = ''
        lcd.lcd_clear()
        lcd2.lcd_clear()
        #GPIO.cleanup()
    def CameraButtonCallback(self, channel):
        self.camera_flag = 'off'
        self.CamThreadFlag = False

    def fingerprint_init(self):

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

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

        except Exception as e:
            lcd.lcd_display_string('Error', 1)
            print(e)
            exit(0)

    def add_user_fingerprint(self, user_id):
        try:
            lcd.lcd_clear()
            lcd.lcd_display_string('Adding user..', 1)
            lcd.lcd_display_string('Place finger..', 2)

            while (self.finger.readImage() == False):
                pass

            self.finger.convertImage(0x01)

            result = self.finger.searchTemplate()
            positionNumber = result[0]

            if (positionNumber >= 0):
                lcd.lcd_clear()
                lcd.lcd_display_string('Pattern already', 1)
                lcd.lcd_display_string('exist', 2)

            lcd.lcd_clear()
            lcd.lcd_display_string('Authrization..', 1)
            lcd.lcd_display_string('Please wait..', 2)
            time.sleep(2)

            while (self.finger.readImage() == False):
                pass

            self.finger.convertImage(0x02)

            if (self.finger.compareCharacteristics() == 0):
                lcd.lcd_display_string('Finger patterns', 1)
                lcd.lcd_display_string('do not match', 2)

            self.finger.createTemplate()

            positionNumber = self.finger.storeTemplate()

            lcd.lcd_clear()
            lcd.lcd_display_string('Authrization', 1)
            lcd.lcd_display_string('Complete', 2)
            self.finger.loadTemplate(positionNumber, 0x01)
            characterics = str(
                self.finger.downloadCharacteristics(0x01)).encode('utf-8')
            Char = hashlib.sha256(characterics).hexdigest()
            database.send_data("update users set user_fingerprint = '" + Char +
                               "', pattern_position = " + str(positionNumber) +
                               " where user_id = " + str(user_id))
            time.sleep(1)
            lcd.lcd_clear()
            lcd.lcd_display_string('User added', 1)
            lcd.lcd_display_string('Finger enrolled', 2)
            time.sleep(1.5)
            lcd.lcd_clear()
            lcd2.lcd_clear()

        except Exception as e:
            lcd.lcd_clear()
            lcd.lcd_display_string('Error', 1)
            print(e)

    def counter_OUT(self):
        self.cnt_OUT += 1
        if self.cnt_OUT == 1:
            diode.setRedDiode_OUT()
            time.sleep(1.5)
            diode.resetRedDiode_OUT()
        elif self.cnt_OUT == 2:
            diode.blinkRedDiode_OUT()
        elif self.cnt_OUT == 3:
            diode.setAlarm()
            time.sleep(0.1)
            diode.resetAlarm()
            lcd2.lcd_display_string('AUTHORIZATION', 1)
            lcd2.lcd_display_string('FAILED !!!', 2)
            self.FLAG = False

    def counter_ENTER(self):
        self.cnt_ENTER += 1
        if self.cnt_ENTER == 1:
            diode.setRedDiode_OUT()
            time.sleep(1.5)
            diode.resetRedDiode_OUT()
        elif self.cnt_ENTER == 2:
            diode.blinkRedDiode_OUT()
            #time.sleep(1.5)
        elif self.cnt_ENTER == 3:
            diode.setAlarm()
            time.sleep(0.1)
            diode.resetAlarm()
            lcd2.lcd_display_string('AUTHORIZATION', 1)
            lcd2.lcd_display_string('FAILED !!!', 2)
            self.FLAG = False

    def positive(self):
        if self.positive_flag == 'OUT':
            diode.setGreenDiode_OUT()
            diode.resetRedDiode_OUT()
            time.sleep(1.5)
            diode.resetGreenDiode_OUT()
        elif self.positive_flag == 'ENTER':
            diode.setGreenDiode_ENTER()
            diode.resetRedDiode_ENTER()
            time.sleep(1.5)
            diode.resetGreenDiode_ENTER()

    def residence_time(self, user_id):
        time_in = database.get_data(
            "select time_in from usertime where user_id = " + str(user_id))
        time_out = database.get_data(
            "select time_out from usertime where user_id = " + str(user_id))
        if ((time_in is not None) and (time_out is not None)):
            res_time = (time_out - time_in)
            database.send_data("update usertime set residence_time = '" +
                               str(res_time) + "' where user_id = " +
                               str(user_id))

    def add_delete_user(self):
        try:
            while self.FLAG:
                lcd2.lcd_display_string('Insert password:'******'#':
                        if self.inserted_password[0] == 'A':
                            DoesAddCodeExists = database.get_data(
                                "select count(create_acc_code) from usercode where create_acc_code = '"
                                + self.inserted_password + "'")
                            if DoesAddCodeExists == 1:
                                can_be_added = database.get_data(
                                    "select users.availability from users where users.user_id = (select usercode.user_id from usercode where create_acc_code = '"
                                    + self.inserted_password +
                                    "' and users.user_id = usercode.user_id)")
                                if can_be_added == 1:
                                    user_code_quantity = database.get_data(
                                        "select count(user_id) as quantity from usercode where create_acc_code = '"
                                        + self.inserted_password + "'")
                                    if user_code_quantity == 1:
                                        expire_date = database.get_data(
                                            "select expire_date from usercode where create_acc_code = '"
                                            + self.inserted_password + "'")
                                        current_date = datetime.datetime.strptime(
                                            time.strftime(
                                                '%Y-%m-%d %H:%M:%S',
                                                time.localtime()),
                                            '%Y-%m-%d %H:%M:%S')
                                        if current_date < expire_date:
                                            user_id = database.get_data(
                                                "select users.user_id from users where users.user_id = (select usercode.user_id from usercode where usercode.create_acc_code = '"
                                                + self.inserted_password +
                                                "' and users.user_id = usercode.user_id)"
                                            )
                                            database.send_data(
                                                "update usercode set create_acc_code = null where create_acc_code = '"
                                                + self.inserted_password + "'")
                                            lcd2.lcd_clear()
                                            lcd2.lcd_display_string(
                                                'Code correct!', 1)
                                            time.sleep(1.5)
                                            lcd2.lcd_clear()
                                            lcd2.lcd_display_string(
                                                'Add your', 1)
                                            lcd2.lcd_display_string(
                                                'finger pattern', 2)
                                            self.data_flag = 'off'
                                            self.add_user_fingerprint(user_id)
                                            self.FLAG = False

                                        else:
                                            lcd2.lcd_clear()
                                            lcd2.lcd_display_string(
                                                'Code expired!', 1)
                                            self.inserted_password = ''
                                            self.data_flag = 'active'
                                            self.digit = None
                                            time.sleep(2)
                                            lcd2.lcd_clear()

                                    else:
                                        lcd2.lcd_clear()
                                        lcd2.lcd_display_string(
                                            'Wrong password', 1)
                                        self.inserted_password = ''
                                        self.digit = None
                                        time.sleep(2)

                                else:
                                    lcd2.lcd_clear()
                                    lcd2.lcd_display_string('User cannot', 1)
                                    lcd2.lcd_display_string('be added', 2)
                                    self.inserted_password = ''
                                    self.digit = None
                                    time.sleep(1.5)
                                    lcd2.lcd_clear()

                            else:
                                lcd2.lcd_clear()
                                lcd2.lcd_display_string('This password', 1)
                                lcd2.lcd_display_string('not exists', 2)

                        elif self.inserted_password[0] == 'D':
                            DoesDeleteCodeExists = database.get_data(
                                "select count(delete_acc_code) from usercode where delete_acc_code = '"
                                + self.inserted_password + "'")
                            if DoesDeleteCodeExists == 1:
                                getUserID = database.get_data(
                                    "select user_id from usercode where delete_acc_code = '"
                                    + self.inserted_password + "'")
                                can_be_deleted = database.get_data(
                                    "select availability from users where user_id = "
                                    + str(getUserID))
                                if can_be_deleted == 0:
                                    positionNumber = database.get_data(
                                        "select pattern_position from users where user_id = "
                                        + str(getUserID))
                                    if (self.finger.deleteTemplate(
                                            positionNumber) == True):
                                        database.send_data(
                                            "call delete_user(" +
                                            str(getUserID) + ")")
                                        lcd2.lcd_clear()
                                        lcd2.lcd_display_string(
                                            'User has been', 1)
                                        lcd2.lcd_display_string('deleted', 2)
                                        self.inserted_password = ''
                                        self.digit = None
                                        time.sleep(1.5)
                                        lcd2.lcd_clear()
                                else:
                                    lcd2.lcd_clear()
                                    lcd2.lcd_display_string('User cannot', 1)
                                    lcd2.lcd_display_string('be deleted', 2)
                                    self.inserted_password = ''
                                    self.digit = None
                                    time.sleep(1.5)
                                    lcd2.lcd_clear()

                            else:
                                lcd2.lcd_display_string('Password not', 1)
                                lcd2.lcd_display_string('recognized', 2)

                        elif self.inserted_password[0] == 'B':
                            user_id = database.get_data(
                                "select user_id from users where user_exit_password = '******'")
                            if user_id >= 1:
                                lcd2.lcd_clear()
                                lcd2.lcd_display_string('Password correct', 1)
                                time_out_date = datetime.datetime.strptime(
                                    time.strftime('%Y-%m-%d %H:%M:%S',
                                                  time.localtime()),
                                    '%Y-%m-%d %H:%M:%S')
                                database.send_data(
                                    "update usertime set time_out = '" +
                                    str(time_out_date) + "' where user_id = " +
                                    str(user_id))
                                self.positive_flag = 'OUT'
                                self.positive()
                                self.residence_time(user_id)
                                self.data_flag = 'off'
                                self.FLAG = False

                            else:
                                lcd2.lcd_clear()
                                lcd2.lcd_display_string('Wrong password', 1)
                                self.counter_OUT()
                                time.sleep(1.5)
                                self.digit = None
                                self.inserted_password = ''

                        else:
                            lcd2.lcd_clear()
                            lcd2.lcd_display_string('Password not', 1)
                            lcd2.lcd_display_string('recognized', 2)

                    if self.digit == 'C':
                        index1 = len(self.inserted_password) - 1
                        index2 = len(self.inserted_password) - 2
                        _char1 = self.inserted_password[index1]
                        _char2 = self.inserted_password[index2]
                        self.inserted_password = self.inserted_password.replace(
                            _char1, '', 1)
                        self.inserted_password = self.inserted_password.replace(
                            _char2, '', 1)
                    if self.data_flag == 'active':
                        lcd2.lcd_clear()
                        lcd2.lcd_display_string('insert password', 1)
                        lcd2.lcd_display_string(self.inserted_password, 2)

        except Exception as e:
            lcd.lcd_clear()
            lcd2.lcd_clear()
            lcd.lcd_display_string('Error occured', 1)
            lcd2.lcd_display_string('Error occured', 1)
            print(e)

    def check_user(self):
        while True:
            try:
                while (self.finger.readImage() == False):
                    pass

                lcd.lcd_clear()
                lcd.lcd_display_string('Verifying..', 1)

                self.finger.convertImage(0x01)

                result = self.finger.searchTemplate()
                positionNumber = result[0]

                if positionNumber == -1:
                    lcd.lcd_clear()
                    lcd.lcd_display_string('Given pattern', 1)
                    lcd.lcd_display_string('does not exists', 2)
                    self.counter_ENTER()
                    #exit(0)
                else:
                    lcd.lcd_clear()
                    lcd.lcd_display_string('Welcome', 1)
                    EnterToRoomDate = datetime.datetime.strptime(
                        time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
                        '%Y-%m-%d %H:%M:%S')
                    database.send_data(
                        "update usertime set time_in = '" +
                        str(EnterToRoomDate) +
                        "' where user_id = (select user_id from users where pattern_position = "
                        + str(positionNumber) +
                        " and usertime.user_id = users.user_id)")
                    self.positive_flag = 'ENTER'
                    self.positive()
                    lcd.lcd_clear()

            except Exception as e:
                lcd.lcd_clear()
                lcd.lcd_display_string('Error', 1)
                print(e)
Ejemplo n.º 21
0
"""
este programa imprime todas as fingerprint characteristics armazenadas no sensor de fingerprint
"""


from pyfingerprint.pyfingerprint import PyFingerprint

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyAMA0', 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:
    templates = f.getTemplateIndex(0)
    for i in range(0, len(templates)):
        if(templates[i]):
            f.loadTemplate(i)
            print(f.downloadCharacteristics())

except Exception as e:
    print('Operation failed!')
    print('Exception message: ' + str(e))
    exit(1)
Ejemplo n.º 22
0
class fingerprint_sensor:
    def __init__(self):
        # Sensor Initialisation
        try:
            self.f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF,
                                   0x00000000)

            if (self.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))

    def enrollment(self):
        try:
            print('Waiting for finger...')

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

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

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

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

            time.sleep(2)

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

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

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

            # Creates a template
            self.f.createTemplate()

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

            # Exports the template to a temporaryfile
            template = self.f.downloadCharacteristics()
            temp_file = open("template.txt", "w+")
            for item in template:
                temp_file.write(str(item) + "\n")
            temp_file.close()
            return os.path.abspath('temp_file.txt')

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

    def authentication(self, file_path):
        try:
            match_flag = 0
            # Uploading the template to the sensor
            temp_file = open(file_path, "r")
            template = []
            for x in temp_file:
                template.append(int(x))
            temp_file.close()
            self.f.uploadCharacteristics(characteristicsData=template)
            Index_template = self.f.storeTemplate()

            # Tries to search the finger
            print('Waiting for finger...')

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

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

            # Searches template
            result = self.f.searchTemplate()

            positionNumber = result[0]

            if (positionNumber == -1):
                print('No match found!')
                match_flag = 0
            elif (positionNumber == Index_template):
                print('Matched')
                match_flag = 1

            return match_flag

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

    def Clear_Sensor(self):
        # Deleting the database
        self.f.clearDatabase()
Ejemplo n.º 23
0
                ## 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
                positions.append(f.storeTemplate())
                signatures.append(
                    hashlib.sha256(
                        str(f.downloadCharacteristics(0x01)).encode(
                            'utf-8')).hexdigest())

            except Exception as e:
                attempt += 1
                mylcd.lcd_clear()
                mylcd.lcd_display_string('     ERROR!     ', 1)
                time.sleep(1)
                print('Exception message: ' + str(e))
                mylcd.lcd_clear()
                mylcd.lcd_display_string(str(e)[:16], 1)
                mylcd.lcd_display_string(str(e)[16:], 2)
                print('Try again...')

        if (len(signatures) == 2):
            dfStudent.iloc[row, 3] = signatures[0]
Ejemplo n.º 24
0
class Fingerprint:
    _shed_Job: Union[schedule.Job, None] = None
    _sensor: Sensor
    _plugin_manager: PluginManager
    err_str: str = "OK"
    _access_check: Union[threading.Thread, None] = None
    _access_check_stop: bool
    wakupPin: Union[Pin.Pin, None]

    currentFinger: BinarySensor
    currentError: BinarySensor


    level1: Switch
    level2: Switch
    level3: Switch

    def __init__(self, client: mclient.Client, opts: conf.BasicConfig, logger: logging.Logger, device_id: str):
        from gpiozero.pins.native import NativeFactory
        from gpiozero import Device
        Device.pin_factory = NativeFactory()

        self._config = conf.PluginConfig(opts, PluginLoader.getConfigKey())
        self.__client = client
        self.__logger = logger.getChild("Fingerprint")
        self._finger = PyFingerprint(
            self._config["serial"],
            57600,
            0xFFFFFFFF,
            self._config.get("password", 0x00000000)
            )
        
        if not self._finger.verifyPassword():
            self.err_str = "PASSWD"
        
        if self._config.get("WAKEUP", 0) is not 0:
            self.wakupPin = Pin.Pin(pin=self._config.get("WAKEUP", 0), direction=Pin.PinDirection.IN_PULL_LOW)
            self.wakupPin.set_detect(self.wakeup, Pin.PinEventEdge.BOTH)
        else:
            self.wakeup(None, threadsleep=False)
        

    def register(self):
        t = ad.Topics.get_std_devInf()

        self.currentFinger = BinarySensor(
            self.__logger,
            self._plugin_manager,
            self._config["name"],
            binary_sensor_type=ad.BinarySensorDeviceClasses.PRESENCE,
            value_template="{{ value_json.dedected }}",
            json_attributes=True,
            icon="mdi:fingerprint"
        )
        self.currentFinger.register()
        self.currentFinger.turn(
            {
                "dedected": False,
                "fingerID": -1,
                "confidency": 0,
                "hash": None
            }
        )
        self.currentError = BinarySensor(
            self.__logger,
            self._plugin_manager,
            "{} Error".format(self._config["name"]),
            ad.BinarySensorDeviceClasses.PROBLEM,
            json_attributes=True,
            value_template="{{ value_json.is_error }}"
        )
        self.currentError.register()
        self.update_error_sensor()

        self.level1 = Switch(
            self.__logger,
            self._plugin_manager,
            self.level1_callback,
            "{} Level1".format(self._config["name"]),
            icon="mdi:shield-lock"
        )
        self.level1.register()
        self.level1.turn(self._config.get("allow_level1", False))

        self.level2 = Switch(
            self.__logger,
            self._plugin_manager,
            self.level2_callback,
            "{} Level2".format(self._config["name"]),
            icon="mdi:shield-lock"
        )
        self.level2.register()
        self.level2.turn(self._config.get("allow_level2", False))

        self.level3 = Switch(
            self.__logger,
            self._plugin_manager,
            self.level3_callback,
            "{} Level3".format(self._config["name"]),
            icon="mdi:shield-lock"
        )
        self.level3.register()
        self.level3.turn(self._config.get("allow_level3", False))


    def level1_callback(self, message:str, state_requested=False):
        self._config["allow_level1"] = True if message == "ON" else False
        self.send_update()

    def level2_callback(self, message:str, state_requested=False):
        self._config["allow_level2"] = True if message == "ON" else False
        self.send_update()

    def level3_callback(self, message:str, state_requested=False):
        self._config["allow_level3"] = True if message == "ON" else False
        self.send_update()

    def update_error_sensor(self):
        try:
            self.currentFinger.turn(
                {
                    "is_error": self.err_str != "OK",
                    "msg": self.err_str
                }
            )
        except:pass

    def set_pluginManager(self, pm):
        self._plugin_manager = pm

    def stop(self):
        pass

    def sendStates(self):
        self.send_update(True)

    def send_update(self, force=False):
        # Send Error Messeges
        self.update_error_sensor()

        # if resend requested, null fingerprint
        if force:
            self.currentFinger.turn(
                {
                    "dedected": False,
                    "fingerID": -1,
                    "confidency": 0,
                    "hash": None
                }
            )
        
        # Update the Authorisation Levels to Home Assistant
        self.level1.turn(self._config.get("allow_level1", False))
        self.level2.turn(self._config.get("allow_level2", False))
        self.level3.turn(self._config.get("allow_level3", False))
    
    def access_thread(self):
        while not self._access_check_stop:
            try:
                img = self._finger.readImage()
                if not img:
                    sleep(0.1)
                    continue
                self._finger.convertImage(FINGERPRINT_CHARBUFFER1)
                res = self._finger.searchTemplate()
                
                optional = {}
                # Extra Exception handling, because this stuff is optional
                try:
                    if res[0] > -1:
                        self._finger.loadTemplate(res[0], FINGERPRINT_CHARBUFFER1)
                        characterics = str(self._finger.downloadCharacteristics(FINGERPRINT_CHARBUFFER1)).encode('utf-8')

                        optional = {
                            "sha256": hashlib.sha256(characterics).hexdigest(),
                            "capacity": self._finger.getStorageCapacity(),
                            "stored": self._finger.getTemplateCount(),
                            "security": self._finger.getSecurityLevel()
                        }

                except Exception as e:
                    self.err_str = str(e)
                    self.update_error_sensor()

                #Tell homeassistant about the new fingerprint
                required = {
                        "dedected": res[0] > -1,
                        "fingerID": res[0],
                        "confidency": res[1],
                        "hash": hex
                    }
                required.update(optional)
                self.currentFinger.turn( required )

                #Wait some time
                sleep( 5.0 if res[0] > -1 else 0.25 )

                #Clear the fingerprint message
                self.currentFinger.turn(
                    {
                        "dedected": False,
                        "fingerID": -1,
                        "confidency": 0,
                        "hash": None
                    }
                )

            except Exception as e:
                self.__logger.exception("access_thread()")
                self.err_str = str(e)
                self.update_error_sensor()

    def stop_access_thread(self):
        self._access_check_stop = True
        if self._access_check is not None:
            self._access_check.join()
            self._access_check = None
        if self._shed_Job is not None:
            schedule.cancel_job(self._shed_Job)
            self._shed_Job = None


    def wakeup(self, device, threadsleep:bool=True):
        if self._access_check is not None and self._access_check.is_alive():
            return

        if self._shed_Job is not None:
            schedule.cancel_job(self._shed_Job)
        if threadsleep:
            job = schedule.every(self._config.get("WAKEUP_active_secs", 120)).seconds
            job.do(self.stop_access_thread)
            self._shed_Job = job
        self._access_check_stop = False
        self._access_check = threading.Thread(target=self.access_thread, name="FingerAccess", daemon=False)
        self._access_check.start()
Ejemplo n.º 25
0
    ## 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)
    def Finger():
        continue_reading = True

        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!')
            Pinlbl = Label(top2,
                           text="Finger Not Deteted",
                           font=myfont,
                           width=16)
            Pinlbl.grid(row=0, column=3)
            Pinlbl.configure(bg='#ff7700')
            print('Exception message: ' + str(e))
            continue_reading = False

            ## 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...')
                Pinlbl = Label(top2,
                               text="Waiting For Finger",
                               font=myfont,
                               width=16)
                Pinlbl.grid(row=0, column=3)
                Pinlbl.configure(bg='#ff7700')

                ## 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]

                lockstatus = SendtoServer("/scan/fingerprint/1", 1, 2,
                                          {'FingerPrint': str(positionNumber)})
                print(lockstatus)

                if lockstatus['status'] == 3:
                    Pinlbl = Label(top2,
                                   text="Access Danied",
                                   font=myfont,
                                   width=16)
                    Pinlbl.grid(row=0, column=3)
                    Pinlbl.configure(bg='#ff7700')
                    print("Access Denied, YOU SHALL NOT PASS!")
                    print(positionNumber)
                    continue_reading = False
                else:
                    print("Access Granted")
                    Pinlbl = Label(top2,
                                   text="Access Granted",
                                   font=myfont,
                                   width=16)
                    Pinlbl.grid(row=0, column=3)
                    Pinlbl.configure(bg='#ff7700')
                    GPIO.output(Relay, GPIO.HIGH)  #Turn on Relay
                    time.sleep(5)  #Wait 5 Seconds
                    GPIO.output(Relay, GPIO.LOW)  #Turn off Relay
                    continue_reading = False

                ## 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))
                continue_reading = False
Ejemplo n.º 27
0
    def predict(self):

        try:
            f = PyFingerprint(self.com, self.port, 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):
                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:
                with open('./data_log.csv', 'r') as file:
                    self.rows = csv.DictReader(file)
                    for row in self.rows:
                        if row['positionnumber'] == str(positionNumber):
                            print('Name :', row['empolynumber'])

                    #print('\nName : ', self.data_empoly[positionNumber])
                    #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)).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 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
Ejemplo n.º 29
0
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)

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

    # Convert list of characteristics to string
    mystring = json.dumps(mychar)

    # Define new IOTA transaction
    pt = iota.ProposedTransaction(
        address=iota.Address(addr),
        message=iota.TryteString.from_unicode(mystring),
        tag=iota.Tag(b'HOTELIOTA'),
        value=0)

    # Print waiting message
    print("\nSending transaction...Please wait...")

    # Send transaction to the tangle
Ejemplo n.º 30
0
    ## 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)
Ejemplo n.º 31
0
def enroll():
    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))

    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))
            return

        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)

        ch1 = str(f.downloadCharacteristics(0x01)).encode('utf-8')
        ch2 = str(f.downloadCharacteristics(0x02)).encode('utf-8')
        hash1 = hashlib.sha256(ch1).hexdigest()
        hash2 = hashlib.sha256(ch2).hexdigest()
        print(hash1)
        print(hash2)
        ## Compares the charbuffers
        acur = f.compareCharacteristics()
        print(acur)
        if (acur == 0):
            raise Exception('Fingers do not match')

    ## Creates a template
        f.createTemplate()

        ## Saves template at new position number
        name = input('Enter name of the person')

        positionNumber = f.storeTemplate()
        print(hash1)
        print(hash2)
        print('Finger enrolled successfully!')
        print('New template position #' + str(positionNumber))

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
Ejemplo n.º 32
0
    ## 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))
    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())
    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
Ejemplo n.º 33
0
    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)).encode('utf-8')

    if(hashlib.sha256(characterics).hexdigest() == "0eff012f344875834a7fe838ab79ba60a9f30999eb586d39d34bde07aca55414"):
        print("Es igual")
    else:
        print("No es igual")


    ## 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)