Exemplo n.º 1
1
def checkFP():
    ## Tries to initialize the sensor
    try:
        f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)

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

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

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

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

        ## 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!')
            return -30
        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())
        return positionNumber
    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
Exemplo n.º 2
0
def delete():
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

        if (f.verifyPassword() == False):
            raise ValueError(
                'La Contraseña del sensor de huellas dactilares dada es incorrecta!'
            )

    except Exception as e:
        print('No se puedo inicializar el sensor de huellas dactilares!')
        print('Mensaje de exepcion: ' + str(e))
        exit(1)

    ## Gets some sensor information
    print('\tEdu Attendance v1.0')
    print('')
    print('Plantillas utilizada actualmente: ' + str(f.getTemplateCount()) +
          '/' + str(f.getStorageCapacity()))
    print('')
    try:

        if f.clearDatabase() == True:
            print('Plantillas actualmente: ' + str(f.getTemplateCount()) +
                  '/' + str(f.getStorageCapacity()))

    except Exception as e:
        print('Operacion fallida')
        print('Mensaje de exepcion: ' + str(e))
        exit(1)
Exemplo n.º 3
0
def register():
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
        if (f.verifyPassword() == False):
            raise ValueError(
                'La Contraseña del sensor de huellas dactilares dada es incorrecta!'
            )
    except Exception as e:
        print('No se puedo inicializar el sensor de huellas dactilares!')
        print('Mensaje de exepcion: ' + str(e))
        exit(1)

    ## Gets some sensor information
    print('\tEdu Attendance v1.0')
    print('')
    print('Plantillas utilizada actualmente: ' + str(f.getTemplateCount()) +
          '/' + str(f.getStorageCapacity()))
    print('')

    print("Registrar un Nuevo Usuario")
    new_name = input("Nombre: ")
    result = finger()
    sql = """INSERT INTO empleado ( nombre,id_huella,dato) VALUES ('%s','%s','%s')""" % (
        new_name, result[0], result[1])
    mysqlcursor.execute(sql)
    db.commit()
    db.rollback()
    print("Completado")
    lcd.lcd_display_string('Completado', 1)
    db.close()
class FingerPrintScan:
    def __init__(self):
        self.f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
        if (self.f.verifyPassword() == False):
            raise ValueError('The given fingerprint sensor password is wrong!')
        print('Currently used templates: ' + str(self.f.getTemplateCount()) +
              '/' + str(self.f.getStorageCapacity()))
        self.current_buffer = 0x01

    def scan_fingerprint(self):
        while (self.f.readImage() == False):
            pass

    def is_fingerprint_exist(self):
        result = self.f.searchTemplate()
        positionNumber = result[0]
        print(positionNumber)
        return positionNumber >= 0

    def get_template_id(self):
        result = self.f.searchTemplate()
        positionNumber = result[0]
        print(positionNumber)
        return positionNumber

    def save_fingerprint(self):
        self.f.createTemplate()
        return self.f.storeTemplate()

    def clear_all_fingerprint(self):
        for i in range(self.f.getTemplateCount()):
            if self.f.deleteTemplate(i):
                print('Template deleted - ' + str(i))

    def clear_fingerprint(self, start, end):
        for i in range(start, end):
            if self.f.deleteTemplate(i):
                print('Template deleted - ' + str(i))

    def save_to_char_buffer(self):
        self.f.convertImage(self.current_buffer)
        self.current_buffer = self.current_buffer + 1

    def save_as_image(self, file_name):
        imageDestination = os.getcwd() + '/' + file_name + '.png'
        self.f.downloadImage(imageDestination)
Exemplo n.º 5
0
class FingerprintController(object):
    def __init__(self):
        self.sensor = None
        self.lcd = None
        self.cur_state = None

    def connect(self, dev):
        logging.info("Attempting to open serial device %s", dev)
        self.sensor = PyFingerprint(dev, 57600, 0xFFFFFFFF, 0x00000000)
        if not self.sensor.verifyPassword():
            raise ValueError('The given fingerprint sensor password is wrong!')
        logging.info("Serial device opened")
        logging.info(
            "Currently used templates: %s/%s" %
            (self.sensor.getTemplateCount(), self.sensor.getStorageCapacity()))

        self.lcd = LCD()

        self.send_update_packet({"status": "idle"})

    def send_update_packet(self, data):
        logging.info("=> %s" % data)
        resp = requests.post(url=API_UPDATE_SELF_STATE,
                             data={
                                 "token": ID_TOKEN,
                                 "state": json.dumps(data),
                             })
        logging.info("  <= %s", resp.json())

    def request_mode(self):
        try:
            logging.info("Requesting state...")
            data = requests.post(url=API_SELF_STATE,
                                 data={
                                     "token": ID_TOKEN,
                                 },
                                 timeout=10)
            logging.info("Received response: %s", data)
            data = data.json()
            return data['state']
        except KeyboardInterrupt:
            sys.exit(0)
        except:
            logging.exception("Failed requesting state, idling...")
            return 'idle'

    def loop_forever(self):
        funcs = {
            'enroll': self.state_enroll,
            'auth': self.state_auth,
            'idle': self.state_idle,
        }

        while True:
            mode = self.request_mode()
            action = funcs.get(mode, None)

            if not action:
                logging.warning("Ignoring invalid mode from server: %s", mode)
                self.state_idle()
                continue

            logging.info("Performing action '%s'", mode)

            try:
                action()
                if mode != 'idle':
                    time.sleep(5)
            except Exception as ex:
                self.send_update_packet({
                    "status": "general_error",
                    "message": ex.message
                })

    def state_idle(self):
        self.lcd.setText("Waiting...")
        self.lcd.setRGB(255, 150, 0)

        time.sleep(1)

    def state_enroll(self):
        self.send_update_packet({"status": "enroll_wait"})

        self.lcd.setRGB(0, 255, 0)
        self.lcd.setText("Place finger on the sensor.")

        while not self.sensor.readImage():
            pass

        self.sensor.convertImage(0x01)

        result = self.sensor.searchTemplate()
        position_num = result[0]

        if position_num >= 0:
            self.send_update_packet({
                "status": "enroll_fail",
                "reason": "Fingerprint already enrolled."
            })
            return

        self.lcd.setText("Lift finger off the sensor.")

        self.send_update_packet({"status": "enroll_lift"})
        time.sleep(2)

        self.lcd.setText("Place your\nfinger again.")

        self.send_update_packet({"status": "enroll_wait2"})

        while not self.sensor.readImage():
            pass

        self.sensor.convertImage(0x02)

        if not self.sensor.compareCharacteristics():
            self.lcd.setRGB(255, 0, 0)
            self.lcd.setText("Fingerprints do not match.")
            self.send_update_packet({
                "status": "enroll_fail",
                "reason": "Fingerprints do not match."
            })
            return

        self.sensor.createTemplate()
        characteristics = self.sensor.downloadCharacteristics(0x01)
        hash = hashlib.sha256(str(characteristics).encode('utf-8')).hexdigest()

        position_num = self.sensor.storeTemplate()

        self.lcd.setText("Fingerprint added!")
        self.send_update_packet({"status": "enroll_success", "hash": hash})

    def state_auth(self):
        self.send_update_packet({"status": "auth_wait"})

        self.lcd.setRGB(0, 255, 0)
        self.lcd.setText("Place finger on the sensor.")

        while not self.sensor.readImage():
            pass

        self.sensor.convertImage(0x01)

        result = self.sensor.searchTemplate()

        position_num = result[0]
        accuracy = result[1]

        if position_num == -1:
            self.lcd.setRGB(255, 0, 0)
            self.lcd.setText("Unknown\nfingerprint!")
            self.send_update_packet({
                "status": "auth_fail",
                "reason": "Unknown fingerprint!"
            })
            return

        self.lcd.setText("Successfully\nauthenticated!")
        logging.info("Found template at position #%d, score %d", position_num,
                     accuracy)
        self.send_update_packet({"status": "auth_success"})
Exemplo n.º 6
0
## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)

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

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

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

## Tries to delete the template of the finger
try:
    positionNumber = input(
        'Please enter the template position you want to delete: ')
    positionNumber = int(positionNumber)
    if (f.deleteTemplate(positionNumber) == True):
        deletefromdatabase()
        print('Template deleted!')

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