Exemple #1
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))
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))
Exemple #3
0
def login():
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

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

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

    print('Currently used templates: ' + str(f.getTemplateCount()) + '/' +
          str(f.getStorageCapacity()))
    time.sleep(1)
    try:
        while (f.readImage() == False):
            pass
        f.convertImage(0x01)
        result = f.searchTemplate()  ## Searchs template
        positionNumber = result[0]
        accuracyScore = result[1]
        temp = positionNumber
        if (positionNumber == -1):
            print('No match found! Try again')
            login()
        else:
            print('Found template at position #' + str(positionNumber))
            print('The accuracy score is: ' + str(accuracyScore))
        f.loadTemplate(positionNumber, 0x01)
        if (positionNumber == -1):
            print('No match found! Try again')
            login()
        else:
            result = 1
            return (result)

    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)
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))
def pam_sm_authenticate(pamh, flags, argv):
    """
    PAM service function for user authentication.

    @param pamh
    @param flags
    @param argv

    @return int
    """

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        fingerprint.convertImage(0x01)

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

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

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

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

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

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

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

    ## Denies for default
    return pamh.PAM_AUTH_ERR
    def Finger():
        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
Exemple #8
0
        finger.convertImage(0x02)
    
        if ( finger.compareCharacteristics() == 0 ):
            lcd.lcd_display_string('Finger patterns',1)
            lcd.lcd_display_string('do not match',2)
            exit(0)
    
    
        finger.createTemplate()
    
        positionNumber = finger.storeTemplate()
    
        lcd.lcd_clear()
        lcd.lcd_display_string('Authrization',1)
        lcd.lcd_display_string('Complete',2)
        finger.loadTemplate(positionNumber, 0x01)
        characterics = str(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)
Exemple #9
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)
Exemple #10
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
def authenticate():

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

    data = request.get_json()

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

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

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

    try:

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

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

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

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

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

                db_start_station = int(u.start_station)

                try:

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

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

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

        #f.__del__()

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

    return json.dumps(data)
def enroll(ref, firstName, lastName, licNo, lmv):
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

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

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


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

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

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

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

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

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

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

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

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

    ## Creates a template
        f.createTemplate()

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

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

        data = {
            'Name': firstName,
            'LastName': lastName,
            'LicenseNo': licNo,
            'LMV': lmv,
            'biom': scan
        }
        driverBucketId = ref.post('/DrivingLicense/details', data)
    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
def fp_search():
    """
    PyFingerprint
    Copyright (C) 2015 Bastian Raschke <*****@*****.**>
    All rights reserved.

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

    ## Search for a finger
    ##

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

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

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

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

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

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

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

        ## Searchs template
        result = f.searchTemplate()

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

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

        ## OPTIONAL stuff
        ##

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

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

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

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

    ## Enrolls new finger
    ##

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
def login():
    #first = input("Enter fullname: ")
    #last = input("Enter password: "******"SELECT * FROM students WHERE firstname = ? and lastname = ? ", (first, last, )):
    #n1, pw1 = row
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

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

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

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

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

        #print('Waiting for finger...')

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

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

        ## Searchs template
        result = f.searchTemplate()

        positionNumber = result[0]
        accuracyScore = result[1]
        temp = positionNumber
        if (positionNumber == -1):
            print('No match found! Try again')
            login()
        else:
            print('Found template at position #' + str(positionNumber))
            print('The accuracy score is: ' + str(accuracyScore))

            #for row in c:
            #    print(row)
            #print(c)
            print("User logged in")

        ## OPTIONAL stuff
        ##

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

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

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

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

    # https://stackoverflow.com/questions/11853167/parameter-unsupported-when-inserting-int-in-sqlite/21082534
    c.execute("SELECT firstname, lastname from students WHERE templateid = ?",
              (temp, ))
    print(c.fetchone())
    #''.join(
    #name = str(c.fetchone()[0])
    #print(name)

    choose_quiz = input(
        "Choose Quiz: \n1. Electronic Principles\n"
        "2. Electronic Principles 2\n3. Electronic Principles 3\n")
    if choose_quiz == '1':
        Quiz1.run_quiz1()
        from Quiz1 import percentage
        print("Score passed from Quiz 1 is: ", percentage)
        #c.execute("SELECT * FROM students WHERE fullname = ? and password = ? ", (user_name, user_pw,))
        c.execute("UPDATE students set q1 = ? WHERE templateid = ?",
                  (percentage, positionNumber))
        main_menu()
        #break
    elif choose_quiz == '2':
        Quiz2.run_quiz2()
        from Quiz2 import percentage
        print("Score passed from Quiz 2 is: ", percentage)
        c.execute("UPDATE students set q2 = ? WHERE templateid = ?",
                  (percentage, positionNumber))
        main_menu()
        #break
    elif choose_quiz == '3':
        Quiz3.run_quiz3()
        from Quiz3 import percentage
        print("Score passed from Quiz 3 is: ", percentage)
        c.execute("UPDATE students set q3 = ? WHERE templateid = ?",
                  (percentage, positionNumber))
        main_menu()
        #break
    else:
        print("User not found in database: Try again\n")
        main()
def searchFingerprint(queue):
    queryRFID(queue)
    tries = 0
    while tries < 3:
        tries += 1
        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))
            os.system("sudo shutdown -r now")
            # 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...')
            queue.put('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!')
                queue.put('Sorry No match found')
                beepReject()
                # exit(0)
            else:
                # cross-check the hash of
                f.loadTemplate(positionNumber, 0x01)
                ## Downloads the characteristics of template loaded in charbuffer 1
                characterics = str(
                    f.downloadCharacteristics(0x01)).encode('utf-8')
                hash = hashlib.sha256(characterics).hexdigest()

                find_Student_And_Record_Attendance(hash, queue)
                # queue.put('Attendance Taken...')
                # print('Found template at position #' + str(positionNumber))
                # print('The accuracy score is: ' + str(accuracyScore))
                tries = 4

        except Exception as e:
            pass
            # print('Operation failed!')
            # print('Exception message-testing: ' + str(e))
            # exit(1)
        time.sleep(2)
    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 run():
    ## Tries to initialize the sensor
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

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

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

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

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

        print('Waiting for finger...')

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

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

        ## Searchs template
        result = f.searchTemplate()

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

        ## OPTIONAL stuff
        ##

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

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

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

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
Exemple #19
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
Exemple #20
0
def verify():
    import RPi.GPIO as GPIO
    import first
    import hashlib
    from pyfingerprint.pyfingerprint import PyFingerprint
    import time
    import doorlock 
    import serial
    import Triled
    import sqlwg
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    r, g, b = Triled.gpiolightconfig(21,20,16)
    GPIO.setup(r,GPIO.OUT), GPIO.setup(g,GPIO.OUT), GPIO.setup(b,GPIO.OUT)
    Triled.gpiolightout(21, 20, 16)

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


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

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

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

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

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

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

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

    ## Searchs template
        result = f.searchTemplate()

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

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

    ## OPTIONAL stuff
    ##

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

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

    

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(0)
Exemple #21
0
"""
este programa compara a digital do leitor com a de algum template gravado no leitor
"""
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:
    i = int(input('Please enter the template position you want to compare: '))
    f.loadTemplate(i, 2)  # carrega no charbuffer2 o template i
    print('Now, provide your fingerprint...')
    while (not f.readImage()):
        pass
    f.convertImage(1)  # carrega no charbuffer1 o template lido
    print('The matching score between the two templates is',
          f.compareCharacteristics())

except Exception as e:
    print('Operation failed!')
    print('Exception message: ' + str(e))
    exit(1)
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))
Exemple #23
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()
"""
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)
Exemple #25
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)
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)
Exemple #27
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
Exemple #28
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)
Exemple #29
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)
    ## 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)
Exemple #31
0
    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))
    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
Exemple #32
0
def fingerscan ():
    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('cam bien van tay chua duoc lap dat vui long kiem tra lai!')
        print('Exception message: ' + str(e))
        exit(1)

    ## Tries to enroll new finger
    try:
        print('Dat van tay cua ban vao...')

        ## 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('van tay da duoc luu voi id #' + str(positionNumber))
            return -1,0

        print('xin cho...')
        time.sleep(2)

        print('xac nhan lai van tay...')

        ## 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 ):
            print('van tay khong trung')
            return -1,0
        ## Creates a template
        f.createTemplate()

        ## Saves template at new position number
        positionNumber = f.storeTemplate()
    
        print('dang ki van tay thanh cong!')
        
    
        f.loadTemplate(positionNumber, 0x01)
        char_store = str (f.downloadCharacteristics(0x01))
        char_store1= char_store.translate(str.maketrans('','', ',[]'))
    
        return positionNumber, char_store1
        
    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)