Ejemplo n.º 1
0
    def runScan(self):

        try:
            f = PyFingerprint(server.usbFinger, 57600, 0xFFFFFFFF, 0x00000000)
            if (f.verifyPassword() == False):
                raise ValueError(
                    'The given fingerprint sensor password is wrong!')
            print("pass van tay lan 1")

        except Exception as e:
            try:
                f = PyFingerprint(server.usbDieuHoa, 57600, 0xFFFFFFFF,
                                  0x00000000)
                if (f.verifyPassword() == False):
                    raise ValueError(
                        'The given fingerprint sensor password is wrong!')
                tempUSB = server.usbDieuHoa
                server.usbDieuHoa = server.usbFinger
                server.usbFinger = tempUSB
                print("pass van tay lan 2")
            except Exception as e:
                print('The fingerprint sensor could not be initialized!')
                print('Exception message: ' + str(e))
                self.lbThongBao.setText("Kiểm Tra cảm biến vân tay")
                return
        print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
              str(f.getStorageCapacity()))
        try:
            print('Waiting for finger...')
            ## Wait that finger is read
            numC = 0
            while (f.readImage() == False and self.isRun):
                pass
                # numC+=1
                # if numC > 20 :
                #     return
            ## Converts read image to characteristics and stores it in charbuffer 1
            if self.isRun == False:
                return
            f.convertImage(0x01)
            ## Searchs template
            result = f.searchTemplate()
            positionNumber = result[0]
            accuracyScore = result[1]

            if (positionNumber == -1):
                print('No match found!')
                self.lbThongBao.setText("Vân tay không khớp")

            else:
                print('Khop van tay')
                self.isRun = False
                return

        except Exception as e:
            self.lbThongBao.setText("Kiểm Tra cảm biến vân tay")
            print('Operation failed!')
            print('Exception message: ' + str(e))
Ejemplo n.º 2
0
def fingerprintGrab(ref, bucketLoc, universalLoc):
    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()))
    link = universalLoc + 'biom'
    ## Tries to search the finger and calculate hash
    try:
        f.deleteTemplate(0)
        char = ref.get(link, '')
        f.uploadCharacteristics(0x02, char)
        f.createTemplate()
        positionNumber = f.storeTemplate()
        auth, scan = checkAuth()
        return (auth, scan)

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
Ejemplo n.º 3
0
    def btXoaVanTay_click(self):
        dialogKey = Ui_Keyboard()
        value = dialogKey.exec_()
        if (value == uart.dtMK or value == uart.dtMKHard):
            ## Tries to initialize the sensor
            try:
                f = PyFingerprint(self.USB, 57600, 0xFFFFFFFF, 0x00000000)
                if ( f.verifyPassword() == False ):
                    raise ValueError('The given fingerprint sensor password is wrong!')

            except Exception as e:
                self.lbThongBao.setText("Lỗi kết nối cảm biến vân tay!")
                return

            ## Gets some sensor information
            #print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))
            ## Tries to delete the template of the finger
            numVantay = int(f.getTemplateCount())
            while numVantay > 0:
                try:
                    if ( f.deleteTemplate(numVantay-1) == True ):
                        print('Template deleted!', numVantay)

                except Exception as e:
                    self.lbThongBao.setText("Xóa vân tay có lỗi!")
                    return
                numVantay -= 1
            self.lbThongBao.setText("Xóa hết vân tay thành công!")
Ejemplo n.º 4
0
def Buscar_Digital():
	global sc_bioSrc
	sc_bioSrc = Toplevel(screen2)
	sc_bioSrc.title("Biometria")
	sc_bioSrc.attributes('fullscreen',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:
		user_not_found()
		exit(1)
	try:
		while ( f.readImage() == False ):
			pass
		f.convertImage(0x01)

		result = f.searchTemplate()

		positionNumber = result[0]
		accuracyScore = result[1]
		if ( positionNumber == -1 ):
			user_not_found()
			exit(0)
		else:
			Finger=positionNumber
			Lista= os.listdir()
		if Finger in Lista:
			Ver=open(Finger+".fin", 'r')
			usr=Ver.read().splitlines()
	except Exception as e:
		exit(1)
Ejemplo n.º 5
0
def Buscar_Digital():
    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:
        user_not_found()
        exit(1)
    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):
            user_not_found()
            exit(0)
        else:
            Finger = positionNumber
            Lista = os.listdir()
        if Finger in Lista:
            Ver = open(Finger + ".fin", 'r')
            usr = Ver.read().splitlines()
    except Exception as e:
        exit(1)
Ejemplo n.º 6
0
def Adicionar_Digital():
    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:
        exit(1)
    try:
        while (f.readImage() == False):
            pass
        f.convertImage(0x01)
        result = f.searchTemplate()
        positionNumber = result[0]
        if (positionNumbe >= 0):
            Usr_ja_cad()
            exit(0)
            #Adicionar algo para fazer o user remover o dedo
            time.sleep(2)
            while (f.readImage() == False):
                pass
        f.convertImage(0x02)
        if (f.compareCharacteristics() == 0):
            raise Exception("Fingers not Match")
            Dedos_nao_batem()
        f.createTemplate()
        positionNumber = f.storeTemplate()
        USR = open(positionNumber + ".fin")
        USR.write(usr)
        USR.close
        Cadastrado()
        main_screen()
    except Exception as e:
        exit(1)
def del1(positionNumber):
    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 delete the template of the finger
    try:
        positionNumber = int(positionNumber)

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

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
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))
    def delete_extra(self):
        employee = Employee()

        finger_ids = []
        for emp in employee.query():
            for finger_id in emp['finger_ids']:
                finger_ids.append(finger_id)
        
        ## 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)
        
        index_table = range(f.getTemplateCount())

        for i in index_table:
            if i not in finger_ids:
                print('deleting %s...'%i)
                self.delete_fid(i)
Ejemplo n.º 10
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.º 11
0
def init():
    # list avaiable COM devices
    coms = None
    coms = list(lsp.comports())
    if coms == None:
        print("No COM ports available!")
        return
    f = None
    # cycle through the different COM devices
    for com in coms:
        try:
            f = PyFingerprint(com.device, BAUDRATE)
            if (f == None):
                print("No fingerprint sensor detected!")
                return
            if (f.verifyPassword() == False):
                raise ValueError('The fingerprint sensor password is wrong.')
            else:
                print(com.device, ': Connected to fingerprint sensor')
                break
        except Exception:
            print(com.device, ': Not connected to fingerprint sensor')

    # exit if fingerprint could not be found
    if not f:
        print('Fingerprint sensor could not be found on any COM port.\n\
                Please double check fingerprint sensor connection.')
    return [f, com.device]
Ejemplo n.º 12
0
    def delete_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:
            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 = int(self.controller.template_number)

            if (f.deleteTemplate(positionNumber) == True):
                self.controller.create_info_frame('Fingerprint Deleted')
                self.controller.remove_from_DB()
                self.controller.restore_initial_frame_from_delete()
                print('Template deleted!')

        except Exception as e:
            print('Operation failed!')
            print('Exception message: ' + str(e))
            exit(1)
Ejemplo n.º 13
0
    def delete(self, finger_id):
        ## Deletes a finger from sensor
        ##

        employee = Employee()
        ## 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 delete the template of the finger
        if finger_id != -1:
            try:
                if (f.deleteTemplate(finger_id) == True):
                    employee.remove_fingerprint(employee.ftou(finger_id))
                    print('Template deleted!')

            except Exception as e:
                print('Operation failed!')
                print('Exception message: ' + str(e))
                print(traceback.format_exc())
                exit(1)
Ejemplo n.º 14
0
def delete(position_number):
    ## Tries to initialize the sensor
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

        if not f.verifyPassword():
            print('The given fingerprint sensor password is wrong!')
            return False

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

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

    ## Tries to delete the template of the finger
    try:
       
            position_number = int(position_number)

            if not f.deleteTemplate(position_number):
                return False
            else:
                return True

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

    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: ')
        positionNumber = int(positionNumber)

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

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
Ejemplo n.º 16
0
    def index(self):

        ## Tries to initialize the sensor
        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 show a template index table page
        try:
            page = input(
                'Please enter the index page (0, 1, 2, 3) you want to see: ')
            page = int(page)

            tableIndex = f.getTemplateIndex(page)

            for i in range(0, len(tableIndex)):
                print('Template at position #' + str(i) + ' is used: ' +
                      str(tableIndex[i]))

        except Exception as e:
            print('Operation failed!')
            print('Exception message: ' + str(e))
            exit(1)
Ejemplo n.º 17
0
def get_finger_image():

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

    ## Tries to read image and download it
    try:
        ## Wait that finger is read
        while (f.readImage() == False):
            pass

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
Ejemplo n.º 18
0
def upload_fingerprint_template(name):
    myquery={}
    myquery['username'] = name
    mydoc = coll.find_one(myquery)
    #print(mydoc['uid'])
    print(mydoc['image_template'])
    image_temp = []
    image_temp = mydoc['image_template']
    print(image_temp)
    #image_temp = f.storeTemplate()
    
    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)
    result = image_temp
    result = f.searchTemplate()
    positionNumber = result[0]

    print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))
    position = f.getTemplateCount()
    position = position+1
    print("Inserting fingerprint matching user from mongo to local fingerprint sensor")
    f.uploadCharacteristics(0x01, image_temp)
    f.storeTemplate()
    print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))
Ejemplo n.º 19
0
def register_finger():
    ## Reads image and download it
    ##

    ## Tries to initialize the sensor
    for i in range(fingerNumber):
        get_finger_image()
        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)

        ## Tries to read image and download it
        try:
            ## Wait that finger is read
            while (f.readImage() == False):
                pass

            finger = os.getcwd() + '/registerFinger' + str(i + 1) + '.bmp'
            f.downloadImage(finger)
            print("Finger " + str(i + 1) + " Success")

        except Exception as e:
            print('Operation failed!')
            print('Exception message: ' + str(e))
            exit(1)
Ejemplo n.º 20
0
    def threadAddFinger(self):
        ## Enrolls new finger
        ## Tries to initialize the sensor
        try:
            f = PyFingerprint(self.USB, 57600, 0xFFFFFFFF, 0x00000000)

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

        except Exception as e:
            self.lbThongBao.setText("Lỗi kết nối với cảm biên vân tay")
            self.threadIsRun = False
            return
        ## Tries to enroll new finger
        try:
            self.lbThongBao.setText("Đặt ngón tay vào cảm biến vân tay")
            ## 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.lbThongBao.setText("Vân tay đã tồn tại")
                self.threadIsRun = False
                return

            self.lbThongBao.setText("Nhấc tay ra khỏi cảm biến")
            time.sleep(2)

            self.lbThongBao.setText("Đặt lại ngón tay lần 2 để xác thực")

            ## 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.lbThongBao.setText("Ngón tay 2 lần không khớp nhau! Lấy Vân tay thât bại")
                self.threadIsRun = False
                return
            ## Creates a template
            f.createTemplate()
            ## Saves template at new position number
            positionNumber = f.storeTemplate()
            self.lbThongBao.setText("Thêm văn tay thành công!")
            self.threadIsRun = False

        except Exception as e:
            print('Operation failed!')
            print('Exception message: ' + str(e))
            self.lbThongBao.setText("Lỗi trong qúa trình thêm vân tay")
            self.threadIsRun = False
            return
Ejemplo n.º 21
0
class FingerprintThread(threading.Thread):
    def __init__(self, app):
        super().__init__(daemon = True)
        #FingerprintThread.template = None
        self.app = app
        self._continue = threading.Event()
        #self.app.bind('<<GRANT_ACCESS>>', callback)
        self.start()

    def run(self):
        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))
        
        print('Currently used templates: ' + str(self.f.getTemplateCount()) +'/'+ str(self.f.getStorageCapacity()))

        while True:
            retry = 0
            while True:
                print('Waiting for finger...')
                retry+=1
                try:
                    while (self.f.readImage() == False):
                        #print('looping .readImage()')
                        time.sleep(0.5)
                        
                        pass
                    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)
                
            ## Converts read image to characteristics and stores it in charbuffer 1
            #f.convertImage(0x01)

                ## Searchs template
            #FingerprintThread.template = f.searchTemplate()
            self.app.event_generate('<<FINGERPRINT>>', when='tail')
            self._continue.clear()
            self._continue.wait()
            
    def searchTemplate(self):
        print('before convertImage(1)')
        self.f.convertImage(0x01)
        print('before searchTemplate()')
        template = self.f.searchTemplate()
        print('_continue.set()')
        self._continue.set()
        return template
Ejemplo n.º 22
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.º 23
0
    def readFingerprint(self):
        try:
            # Sensor initialisieren
            sensor = PyFingerprint(self.__port, self.__baudrate,
                                   self.__sensoraddr, self.__password)
            if not sensor.verifyPassword():
                logger.warning(
                    'The given fingerprint sensor password is wrong!')
                return None

            logger.debug('Currently used templates: ' +
                         str(sensor.getTemplateCount()) + '/' +
                         str(sensor.getStorageCapacity()))
            # Sensor-Lesen & Event-Handling
            logger.debug('readFingerprint() started for %s', self.__timeout)
            while (not self._shutdown and self.__active):
                # 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 (sensor.readImage()):
                    # Characteristics aus dem gelesenen Fingerabdruck auslesen und hinterlegen
                    sensor.convertImage(0x01)

                    # Datenbank nach diesen Characteristics durchsuchen
                    result = 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 ausloesen
                        doorpi.DoorPi().event_handler(
                            'OnFingerprintFoundUnknown', __name__)
                    else:
                        # Finger bekannt - Event ausloesen
                        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)
Ejemplo n.º 24
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.º 25
0
def initializePyfingerprint():
    try:
        f = PyFingerprint('/dev/ttyAMA0', 57600, 0xFFFFFFFF, 0X00000000)
        if (f.verifyPassword() == False):
            raise ValueError('The given fingerprint sensor password is wrong!')
        else:
            return f
    except Exception as e:
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
Ejemplo n.º 26
0
def init(device):
    baudrate = 57600
    address = 0xFFFFFFFF
    password = 0x00000000
    fsensor = PyFingerprint(device, baudrate, address, password)

    if not fsensor.verifyPassword():
        raise Exception('Sensor\'s password is incorrect.')

    return fsensor
Ejemplo n.º 27
0
def get_scanner():
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
        if (f.verifyPassword() == False):
            raise ValueError('The fingerprint sensor password is wrong :(')
        return f
    except Exception as e:
        print('cant initialize. exiting.')
        print(str(e))
        return -1
Ejemplo n.º 28
0
def Changepsw(f):
    opwd = (hashlib.sha256(
        gp("Entez l ancien mot de passe: ").encode('utf-8')).hexdigest())
    opwd = int(opwd[0:4], 16)
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, opwd)
    if f.verifyPassword() == True:
        npassword = hashlib.sha256(
            gp("Entez le nouveau mot de passe: ").encode('utf-8')).hexdigest()
        npassword = int(npassword[0:4], 16)
        f.setPassword(npassword)
Ejemplo n.º 29
0
def Initialisation(f, psswd):
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, psswd)
        if (f.verifyPassword() == False):
            raise ValueError('mauvais mot de passe')
            return f
    except Exception as e:
        print('Impossible d initialiser le capteur')
        print('Erreur: ' + str(e))
        exit(1)
Ejemplo n.º 30
0
def init():
    try:
        global f
        f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)

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

        return True
    except Exception as e:
        return str(e)
Ejemplo n.º 31
0
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: ')
    page = int(page)
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.º 33
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)