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)
 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
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()
Exemplo n.º 4
0
 def __init__(self):
     try:
         self.f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)
         if self.f.verifyPassword() == False:
             raise ValueError(
                 'The given fingerprint sensor password is wrong!')
     except Exception as e:
         logger.exception(
             'The fingerprint sensor could not be initialized!')
Exemplo n.º 5
0
 def __init__(self):
     # Set fingerprint sensor to ttyUSB0 with buadrate 57600
     self.fingerprintSensor = PyFingerprint('/dev/ttyUSB0', 57600,
                                            0xFFFFFFFF, 0x00000000)
     # Flag for checking sensor available
     self.fingerprintSensorValid = False
     self.fingerprintTemplateValid = False
     self.fingerprintCharValid = False
     self.verify()
Exemplo n.º 6
0
def finger():
    try:
        f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
    except Exception:
        print('The fingerprint sensor could not be initialized!')
        print('')
        main_menu()
    else:
        print('Currently used templates: ' + str(f.getTemplateCount()))
        print('')
        print_grab()
Exemplo n.º 7
0
    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"})
Exemplo n.º 8
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.º 9
0
def search():
    # Search for a finger
    print('\tEdu Attendance v1.0')
    print("")
    print("Esperando su Huella...")
    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)

    while True:
        try:
            # Wait that finger is read
            prnt = f.readImage()

            if (prnt != False):
                # Converts read image to characteristics and stores it in charbuffer 1
                f.convertImage(0x01)
                ## Searchs template

                result = f.searchTemplate()

                positionNumber = result[0]

                f.loadTemplate(positionNumber, 0x01)
                mysqlcursor.execute(
                    "Select nombre FROM docente WHERE id_bio = ('%i')" %
                    (positionNumber))
                nombre = mysqlcursor.fetchone()
                sname = nombre[0]
                print("Bienvenido " + sname)

                break

        except Exception as e:
            print('No se Encontraron Coincidencias')
            print('Scanea de Nuevo!')

            time.sleep(2)
Exemplo n.º 10
0
def initFP():
    # list avaiable COM devices
    coms = None
    coms = list(lsp.comports())
    if coms == None:
        print("No COM ports available!")
        return
    f = None
    found = False
    # cycle through the different COM devices
    for com in coms:
        try:
            f = PyFingerprint(com.device, BAUDRATE)
            if (f.verifyPassword() == False):
                raise ValueError('The fingerprint sensor password is wrong.')
            else:
                print(com.device, ': Connected to fingerprint sensor')
                found = True
                break
        except Exception:
            print(com.device, ': Not connected to fingerprint sensor')

    return [f, found]
Exemplo n.º 11
0
Copyright (C) 2015 Bastian Raschke <*****@*****.**>

All rights reserved.

"""

import time

from pyfingerprint import PyFingerprint

# Inicializando o leitor

try:

    f = PyFingerprint('COM4', 115200, 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)

f.setSecurityLevel(5)
Exemplo n.º 12
0
def enroll():
    mylcd.lcd_clear()
    mylcd.lcd_display_string('Enter Password:'******'4209':
        mylcd.lcd_clear()
        mylcd.lcd_display_string('Enter ID Number', 1)
        r = raw_input("Enter ID Number: ")
        mylcd.lcd_display_string(r, 2, 2)
        sleep(2)
        ## GETTING INFORMATION FROM DATABASE
        conn = sqlite3.connect('/home/pi/attendance/app.db')
        curs = conn.cursor()
        db_val = curs.execute(
            'SELECT rollnum from finger_store where rollnum in (values(?))',
            [r])
        coun = (len(list(db_val)))
        if coun >= 1:
            mylcd.lcd_clear()
            mylcd.lcd_display_string('ID Number Already', 1)
            mylcd.lcd_display_string('Taken', 2, 2)
            sleep(2)
            conn.commit()
            conn.close()
        else:
            conn.commit()
            conn.close()
            ## Enrolls new finger
            ##

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

                if (f.verifyPassword() == False):
                    mylcd.lcd_clear()
                    mylcd.lcd_display_string('Contact Admin', 1)
                    sleep(2)
                    raise ValueError(
                        'The given fingerprint sensor password is wrong!')

            except Exception as e:
                mylcd.lcd_clear()
                mylcd.lcd_display_string('Contact Admin', 1)
                sleep(2)
                print('The fingerprint sensor could not be initialized!')
                print('Exception message: ' + str(e))
                startChoice()

            ## Gets some sensor information
            mylcd.lcd_clear()
            mylcd.lcd_display_string('Currently used', 1)
            mylcd.lcd_display_string('templates: ', 2)
            mylcd.lcd_display_string(str(f.getTemplateCount()), 2, 13)
            sleep(2)
            print('Currently used templates: ' + str(f.getTemplateCount()))

            ## Tries to enroll new finger
            try:
                mylcd.lcd_clear()
                mylcd.lcd_display_string('Waiting for Finger', 2, 2)

                ## 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):
                    mylcd.lcd_clear()
                    mylcd.lcd_display_string('Template already', 1)
                    mylcd.lcd_display_string('exists at  ', 2)
                    mylcd.lcd_display_string('position # ', 3)
                    mylcd.lcd_display_string(str(positionNumber), 3, 13)
                    sleep(3)
                    print('Template already exists at position #' +
                          str(positionNumber))
                    startChoice()
                else:
                    mylcd.lcd_clear()
                    mylcd.lcd_display_string('Remove finger...', 2, 2)
                    print('Remove finger...')
                    time.sleep(2)

                    mylcd.lcd_clear()
                    mylcd.lcd_display_string('Waiting for same', 2)
                    mylcd.lcd_display_string(' finger again', 3)
                    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):
                        mylcd.lcd_clear()
                        mylcd.lcd_display_string('Fingers not matched', 2)
                        sleep(2)
                        raise Exception('Fingers do not match')
                    ## Creates a template
                    f.createTemplate()

                    ## Saves template at new position number
                    positionNumber = f.storeTemplate()
                    ## 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
                    cre_hash = hashlib.sha256(characterics).hexdigest()
                    conn = sqlite3.connect('/home/pi/attendance/app.db')
                    curs = conn.cursor()
                    curs.execute(
                        'INSERT INTO finger_store(rollnum, hashval, id) values(?, ?, ?)',
                        (r, cre_hash, positionNumber))
                    conn.commit()
                    conn.close()
                    mylcd.lcd_clear()
                    mylcd.lcd_display_string('Finger enrolled', 2)
                    mylcd.lcd_display_string('Successfully!', 3, 2)
                    sleep(2)
                    print('New template position #' + str(positionNumber))
                    startChoice()

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

    else:
        mylcd.lcd_clear()
        mylcd.lcd_display_string('Your Not Authorized!', 2)
        sleep(2)
Exemplo n.º 13
0
def finger():
    ## Search for a finger
    ##

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

        if (f.verifyPassword() == False):
            raise ValueError('The given fingerprint sensor password is wrong!')
            startChoice()
    except Exception as e:
        print('The fingerprint sensor could not be initialized!')
        print('Exception message: ' + str(e))
        startChoice()

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

    ## Tries to search the finger and calculate hash
    try:
        mylcd.lcd_clear()
        mylcd.lcd_display_string('Waiting for finger..', 2)

        ## 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):
            mylcd.lcd_clear()
            mylcd.lcd_display_string('No match found!')
            sleep(2)
            mylcd.lcd_clear()
            startChoice()
        else:
            mylcd.lcd_clear()
            today_name = datetime.date.today()
            if calendar.day_name[today_name.weekday()] != ('Sunday'
                                                           or 'Saturday'):
                ## Generating TIME VALUES
                now = datetime.datetime.now()
                my_time_string_10 = "10:30:00"
                my_time_string_12 = "12:30:00"
                my_time_string_13 = "13:29:59"
                my_time_string_14 = "14:30:00"
                my_time_string_16 = "16:00:01"
                time_10 = datetime.datetime.strptime(my_time_string_10,
                                                     "%H:%M:%S")
                time_12 = datetime.datetime.strptime(my_time_string_12,
                                                     "%H:%M:%S")
                time_13 = datetime.datetime.strptime(my_time_string_13,
                                                     "%H:%M:%S")
                time_14 = datetime.datetime.strptime(my_time_string_14,
                                                     "%H:%M:%S")
                time_16 = datetime.datetime.strptime(my_time_string_16,
                                                     "%H:%M:%S")

                # I am supposing that the date must be the same as now
                time_10 = now.replace(hour=time_10.time().hour,
                                      minute=time_10.time().minute,
                                      second=time_10.time().second,
                                      microsecond=0)
                time_12 = now.replace(hour=time_12.time().hour,
                                      minute=time_12.time().minute,
                                      second=time_12.time().second,
                                      microsecond=0)
                time_13 = now.replace(hour=time_13.time().hour,
                                      minute=time_13.time().minute,
                                      second=time_13.time().second,
                                      microsecond=0)
                time_14 = now.replace(hour=time_14.time().hour,
                                      minute=time_14.time().minute,
                                      second=time_14.time().second,
                                      microsecond=0)
                time_16 = now.replace(hour=time_16.time().hour,
                                      minute=time_16.time().minute,
                                      second=time_16.time().second,
                                      microsecond=0)

                print('Found template at position #' + str(positionNumber))
                mylcd.lcd_display_string('PLEASE WAIT', 2, 3)

                ## Create Hash Value for finger
                ##

                ## 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')
                val_hash = hashlib.sha256(characterics).hexdigest()
                ## Hashes characteristics of template
                print('SHA-2 hash of template: ' + val_hash)

                ## GETTING INFORMATION FROM DATABASE
                conn = sqlite3.connect(
                    '/home/pi/Desktop/pro/attendance-20180412T122709Z-001/attendance/app.db'
                )
                curs = conn.cursor()
                db_val = curs.execute(
                    'SELECT rollnum, hashval from finger_store where hashval in (values(?))',
                    [val_hash])
                for row in db_val:
                    ext_id = row[0]
                    mylcd.lcd_clear()
                    mylcd.lcd_display_string("YOUR ID NUMBER:", 2, 2)
                    mylcd.lcd_display_string(ext_id, 3, 3)
                    sleep(2)
                    mylcd.lcd_clear()
                conn.commit()
                conn.close()

                con = sqlite3.connect(
                    '/home/pi/Desktop/pro/attendance-20180412T122709Z-001/attendance/app.db'
                )
                curs2 = con.cursor()
                curs2.execute(
                    'SELECT date from attendance where (date, rollnum) in (values(?, ?))',
                    (datetime.date.today(), ext_id))
                d = curs2.fetchone()
                con.close()

                if d == None:
                    con = sqlite3.connect(
                        '/home/pi/Desktop/pro/attendance-20180412T122709Z-001/attendance/app.db'
                    )
                    c = con.cursor()
                    c.execute(
                        'INSERT INTO attendance (rollnum,date) values(?, ?)',
                        (ext_id, datetime.date.today()))
                    con.commit()
                    con.close()
                ## GETTING INFORMATION FROM DATABASE
                con = sqlite3.connect(
                    '/home/pi/Desktop/pro/attendance-20180412T122709Z-001/attendance/app.db'
                )
                curs2 = con.cursor()
                curs2.execute(
                    'SELECT status,statusexit,statusnoon,statusnoonexit from attendance where (date, rollnum) in (values(?, ?))',
                    (datetime.date.today(), ext_id))
                row = curs2.fetchall()
                for all in row:
                    status1 = all[0]
                    status2 = all[1]
                    status3 = all[2]
                    status4 = all[3]
                con.close()

                if status1 == 'absent':
                    if now < time_10:
                        con = sqlite3.connect(
                            '/home/pi/Desktop/pro/attendance-20180412T122709Z-001/attendance/app.db'
                        )
                        c = con.cursor()
                        c.execute(
                            'UPDATE attendance Set status = ? where (rollnum, date) in (values(?, ?))',
                            ('present', ext_id, datetime.date.today()))
                        con.commit()
                        con.close()
                        mylcd.lcd_display_string("Attendance Success for", 1)
                        mylcd.lcd_display_string(" this Morining", 2)
                        sleep(2)
                        mylcd.lcd_clear()
                        mylcd.lcd_display_string("Dont forgot to ", 1)
                        mylcd.lcd_display_string("comeback after 12:30 PM", 2)
                        sleep(2)
                        mylcd.lcd_clear()
                    elif (now >= time_10) and (now <= time_13):
                        mylcd.lcd_display_string("Sorry, You are Late today",
                                                 1)
                        sleep(2)
                        mylcd.lcd_clear()
                        mylcd.lcd_display_string("Come Afternoon ", 2)
                        mylcd.lcd_display_string("or Tomorrow", 3)
                        sleep(2)
                        mylcd.lcd_clear()
                    elif now > time_13:
                        if status3 == 'absent':
                            if now <= time_14:
                                con = sqlite3.connect(
                                    '/home/pi/Desktop/pro/attendance-20180412T122709Z-001/attendance/app.db'
                                )
                                c = con.cursor()
                                c.execute(
                                    'UPDATE attendance Set statusnoon = ? where (rollnum, date) in (values(?, ?))',
                                    ('present', ext_id, datetime.date.today()))
                                con.commit()
                                con.close()
                                mylcd.lcd_display_string(
                                    "Attendance Success ", 1)
                                mylcd.lcd_display_string(
                                    "for this Afternoon", 2)
                                sleep(2)
                                mylcd.lcd_clear()
                                mylcd.lcd_display_string("Dont forgot to  ", 1)
                                mylcd.lcd_display_string("comeback after", 2)
                                mylcd.lcd_display_string("04:00 PM ", 3)
                                sleep(3)
                                mylcd.lcd_clear()
                            elif now > time_14:
                                mylcd.lcd_display_string(
                                    "Sorry, You are Late", 2)
                                sleep(2)
                                mylcd.lcd_clear()
                                mylcd.lcd_display_string(
                                    "Please Come Early ", 1)
                                mylcd.lcd_display_string("Tomorrow", 2, 2)
                                sleep(2)
                                mylcd.lcd_clear()
                        elif status3 == 'present':
                            if now < time_16:
                                mylcd.lcd_display_string(
                                    "You're leaving Early", 1)
                                mylcd.lcd_display_string("Please come back", 2)
                                mylcd.lcd_display_string("after 4 PM", 3)
                                sleep(3)
                                mylcd.lcd_clear()
                            elif now >= time_16:
                                if status4 == 'present':
                                    mylcd.lcd_display_string(
                                        "Thought you were", 1)
                                    mylcd.lcd_display_string(
                                        "already in your home!", 2)
                                    sleep(2)
                                    mylcd.lcd_clear()
                                else:
                                    con = sqlite3.connect(
                                        '/home/pi/Desktop/pro/attendance-20180412T122709Z-001/attendance/app.db'
                                    )
                                    c = con.cursor()
                                    c.execute(
                                        'UPDATE attendance Set statusnoonexit = ? where (rollnum, date) in (values(?, ?))',
                                        ('present', ext_id,
                                         datetime.date.today()))
                                    con.commit()
                                    con.close()
                                    mylcd.lcd_display_string(
                                        "Attendance Success,", 2)
                                    mylcd.lcd_display_string(
                                        " Happy Day!", 3, 2)
                                    sleep(2)
                                    mylcd.lcd_clear()
                elif status1 == 'present':
                    if now < time_12:
                        mylcd.lcd_display_string("Not the time to", 2)
                        mylcd.lcd_display_string("leave", 3, 2)
                        sleep(2)
                        mylcd.lcd_clear()
                    elif (now >= time_12) and (now <= time_13):
                        con = sqlite3.connect(
                            '/home/pi/Desktop/pro/attendance-20180412T122709Z-001/attendance/app.db'
                        )
                        c = con.cursor()
                        c.execute(
                            'UPDATE attendance Set statusexit = ? where (rollnum, date) in (values(?, ?))',
                            ('present', ext_id, datetime.date.today()))
                        con.commit()
                        con.close()
                        mylcd.lcd_display_string("Attendance Success", 1)
                        mylcd.lcd_display_string("Now Go and", 2, 2)
                        mylcd.lcd_display_string("have your LUNCH :)", 3)
                        sleep(3)
                        mylcd.lcd_clear()
                    elif now > time_13:
                        if status3 == 'absent':
                            if now <= time_14:
                                con = sqlite3.connect(
                                    '/home/pi/Desktop/pro/attendance-20180412T122709Z-001/attendance/app.db'
                                )
                                c = con.cursor()
                                c.execute(
                                    'UPDATE attendance Set statusnoon = ? where (rollnum, date) in (values(?, ?))',
                                    ('present', ext_id, datetime.date.today()))
                                con.commit()
                                con.close()
                                mylcd.lcd_display_string(
                                    "Attendance Success ", 1)
                                mylcd.lcd_display_string(
                                    "for this Afternoon", 2)
                                sleep(2)
                                mylcd.lcd_clear()
                                mylcd.lcd_display_string("Dont forgot to  ", 1)
                                mylcd.lcd_display_string("comeback after", 2)
                                mylcd.lcd_display_string("04:00 PM ", 3)
                                sleep(3)
                                mylcd.lcd_clear()
                            elif now > time_14:
                                mylcd.lcd_display_string(
                                    "Sorry, You are Late", 2)
                                sleep(2)
                                mylcd.lcd_clear()
                                mylcd.lcd_display_string(
                                    "Please Come Early ", 1)
                                mylcd.lcd_display_string("Tomorrow", 2, 2)
                                sleep(2)
                                mylcd.lcd_clear()
                        elif status3 == 'present':
                            if now < time_16:
                                mylcd.lcd_display_string(
                                    "You're leaving Early", 1)
                                mylcd.lcd_display_string("Please come back", 2)
                                mylcd.lcd_display_string("after 4 PM", 3)
                                sleep(3)
                                mylcd.lcd_clear()
                            elif now >= time_16:
                                if status4 == 'present':
                                    mylcd.lcd_display_string(
                                        "Thought you were", 1)
                                    mylcd.lcd_display_string(
                                        "already in your home!", 2)
                                    sleep(2)
                                    mylcd.lcd_clear()
                                else:
                                    con = sqlite3.connect(
                                        '/home/pi/Desktop/pro/attendance-20180412T122709Z-001/attendance/app.db'
                                    )
                                    c = con.cursor()
                                    c.execute(
                                        'UPDATE attendance Set statusnoonexit = ? where (rollnum, date) in (values(?, ?))',
                                        ('present', ext_id,
                                         datetime.date.today()))
                                    con.commit()
                                    con.close()
                                    mylcd.lcd_display_string(
                                        "Attendance Success,", 2)
                                    mylcd.lcd_display_string(
                                        " Happy Day!", 3, 2)
                                    sleep(2)
                                    mylcd.lcd_clear()
            else:
                while True:
                    mylcd.lcd_clear()
                    mylcd.lcd_display_string('Today is a holiday', 2, 2)
                    mylcd.lcd_clear()
                    mylcd.lcd_display_string('So no ATTENDANCE, Enjoy!', 3, 2)
            startChoice()
    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        startChoice()
All rights reserved.

"""

import hashlib
from pyfingerprint import PyFingerprint
import io
import sys

chr = input()

digital = list(map(int, chr.split(" ")))

## Tries to initialize the sensor
try:
    f = PyFingerprint('COM4', 115200, 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)

# Tenta registrar digital
try:
    print('Aproxime o dedo...')

    ## Wait that finger is read
    while (f.readImage() == False):
Exemplo n.º 15
0
"""
from flask import Flask, session, redirect, url_for, escape, request, render_template, flash
import sqlite3
import sys
import pyfingerprint
import I2C_LCD_driver
import time
import hashlib
from pyfingerprint import PyFingerprint

## Enrolls new finger
##

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

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

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

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

## Tries to enroll new finger
try:
    print('Waiting for finger...')
Exemplo n.º 16
0
class FingerprintController:

    f = None
    RESULT_ERROR = -1
    RESULT_TEMPLATE_ALREADY_EXISTS = -2
    RESULT_FINGER_DO_NOT_MATCH = -3
    RESULT_NO_MATCH = -4

    def __init__(self):
        try:
            self.f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)
            if self.f.verifyPassword() == False:
                raise ValueError(
                    'The given fingerprint sensor password is wrong!')
        except Exception as e:
            logger.exception(
                'The fingerprint sensor could not be initialized!')

    def __del__(self):
        del self.f

    def exists_user(self, username):
        return models.exists_user(username, models.session_factory())

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

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

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

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

            if positionNumber >= 0:
                logger.warn('Template already exists at position #{}',
                            str(positionNumber))
                return self.RESULT_TEMPLATE_ALREADY_EXISTS

            return 0

        except Exception as e:
            logger.exception('Error while adding a user (step1).')
            return self.RESULT_ERROR

    def add_user_step2(self, username):
        try:
            print('Waiting for finger...')

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

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

            ## Compares the charbuffers
            if self.f.compareCharacteristics() == 0:
                return self.RESULT_FINGER_DO_NOT_MATCH

            ## Creates a template
            self.f.createTemplate()

            ## Saves template at new position number
            template_index = self.f.storeTemplate()
            logger.info(
                'Finger enrolled successfully. New template position #{}',
                str(template_index))

            ## save user in DB
            models.add_user(username, template_index, models.session_factory())
            return 0

        except Exception as e:
            logger.exception('Error while adding a user (step2).')
            return self.RESULT_ERROR

    def delete_user(self, username):
        user = models.get_user_by_name(username, models.session_factory())
        if None == user:
            logger.info('User \"{}\" does not exists and can not be deleted.',
                        username)
            return
        position = user.template
        models.delete_user(username, models.session_factory())
        self.f.deleteTemplate(position)
        logger.info('User \"{}\" with template position #{} deleted.',
                    username, str(position))

    def search_user(self):
        try:
            logger.info('Waiting for finger...')

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

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

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

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

            if positionNumber == -1:
                logger.warn('No fingerprint match found')
                return self.RESULT_NO_MATCH
            else:
                logger.info(
                    'Found template at position #{} with accuracy score of {}',
                    str(positionNumber), str(accuracyScore))
                return positionNumber

        except Exception as e:
            logger.exception(
                'Error while searching for a fingerprint template.')
            return self.RESULT_ERROR

    def delete_database(self):
        self.f.deleteDatabase()
PyFingerprint
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

"""

from pyfingerprint import PyFingerprint


## Deletes a finger from sensor
##


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

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

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

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

## Tries to delete the template of the finger
try:
    positionNumber = input('Please enter the template position you want to delete: ')
Exemplo n.º 18
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.º 19
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tempfile
from pyfingerprint import PyFingerprint

## Reads image and download it
##
## Tries to initialize the sensor

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

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

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

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

## Tries to read image and download it
try:
    print('Waiting for finger...')

    ## Wait that finger is read
    while (f.readImage() == False):
Exemplo n.º 20
0
def deletefromdatabase():
    conn = sqlite3.connect(
        '/home/pi/Desktop/Biometric-Attendance-System-using-Python-and-Raspberry-pi-3-/attendance/app.db'
    )
    curs = conn.cursor()
    curs.execute("DELETE FROM finger_store WHERE id = 'positionNumber'")
    conn.commit()
    conn.close()


## Deletes a finger from sensor
##

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

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

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

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

## Tries to delete the template of the finger
try:
Exemplo n.º 21
0
"""
PyFingerprint
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

"""

import hashlib
from pyfingerprint import PyFingerprint

## Search for a finger
##

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

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

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

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

## Tries to search the finger and calculate hash
try:
def checkFP():
    # Enrolls new finger
    ##
    # return 8
    # Tries to initialize the sensor
    try:
        f = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)

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

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

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

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

        ## 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()
        print('Finger enrolled successfully!')
        print('New template position #' + str(positionNumber))
        return positionNumber

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        exit(1)
Exemplo n.º 23
0

def connectdb():
    conn = sqlite3.connect(DATABASE_FILE, isolation_level=None)
    return conn


def querydb(conn, query, v=tuple()):
    c = conn.cursor()
    c.row_factory = dict_factory
    c.execute(query, v)
    return c.fetchall()


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

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

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


class MFRC522_Thread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self._stopevent = threading.Event()
        self.Check_Register = threading.Event()
        self.MIFAREReader = MFRC522.MFRC522()
Exemplo n.º 24
0
def finger():
    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)

    ## Tries to enroll new finger
    while True:
        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)

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

                print('Fingers do not match', str(positionNumber))

            ## Creates a template
            f.createTemplate()

            ## Saves template at new position number

            positionNumber = f.storeTemplate()

            f.loadTemplate(positionNumber, 0x01)
            char_store = str(f.downloadCharacteristics(0x01))
            char_store1 = char_store.translate("")

            var = ''
            for x in char_store1:
                var += x

            return positionNumber, var

            break

        except Exception as e:
            print('Error')
            print('Scanea de Nuevo!')

            time.sleep(2)
Exemplo n.º 25
0
def attendance():
    print('\tEdu Attendance v1.0')
    print('')
    lcdprint('Esperando su Huella..', 2)
    print("Esperando su Huella...")

    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)

    while True:
        try:
            ## Wait that finger is read
            prnt = f.readImage()

            if (prnt != False):

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

                result = f.searchTemplate()
                positionNumber = f.storeTemplate()
                f.loadTemplate(positionNumber, 0x01)

                positionNumber = result[0]
                mysqlcursor.execute(
                    "Select nombre FROM empleado WHERE id_huella = ('%i')" %
                    (positionNumber))
                nombre = mysqlcursor.fetchone()
                sname = nombre[0]
                print("Bienvenido " + sname)

                while True:
                    menuIS()
                    op = input("Ingrese una Opcion")
                    if op == "1":
                        new_status = 'Ingreso'
                        new_fecha = datetime.datetime.now()
                        sql = """INSERT INTO asistencia(id_empleado,estado,fecha) VALUES 
                        ((SELECT id_empleado FROM empleado WHERE id_bio='%i'),'%s','%s')""" % (
                            positionNumber, new_status, new_fecha)
                        mysqlcursor.execute(sql)
                        db.commit()
                        db.rollback()
                        print("Completado!")
                        db.close()
                        break
                    elif op == "2":
                        new_status = 'Salida'
                        new_fecha = datetime.datetime.now()
                        sql = """INSERT INTO asistencia(id_docente,estado,fecha) VALUES 
                                                ((SELECT id_docente FROM docente WHERE id_bio='%i'),'%s','%s')""" % (
                            positionNumber, new_status, new_fecha)
                        mysqlcursor.execute(sql)
                        db.commit()
                        db.rollback()
                        print("Completado!")
                        db.close()
                        break
                    else:
                        print("Ingrese una Opcion Correcta")
                    break

                break

        except Exception as e:
            print('No se Encontraron Coincidencias')
            print('Scanea de Nuevo!')

            time.sleep(2)
Exemplo n.º 26
0
class Fingerprint:
    def __init__(self):
        # Set fingerprint sensor to ttyUSB0 with buadrate 57600
        self.fingerprintSensor = PyFingerprint('/dev/ttyUSB0', 57600,
                                               0xFFFFFFFF, 0x00000000)
        # Flag for checking sensor available
        self.fingerprintSensorValid = False
        self.fingerprintTemplateValid = False
        self.fingerprintCharValid = False
        self.verify()

    def verify(self):
        # Verify fingerprintsensor
        try:
            if (self.fingerprintSensor.verifyPassword() is False):
                print('Fingerprint password is wrong!')

            self.fingerprintSensorValid = True
            print('Fingerprint sensor is available!')
        except Exception as e:
            print('Something wrong : ' + str(e))

        print('-' * LINEWIDTH)

    def createTemplate(self):
        if (self.fingerprintSensorValid):
            try:
                time.sleep(2)
                print('Waiting for finger...')
                # wait for finger
                while (self.fingerprintSensor.readImage() is False):
                    pass
                print('Finger read.')
                print('Start convert fingerprint image...')
                self.fingerprintSensor.convertImage(0x01)
                print('Converted.')
                time.sleep(2)
                # double check
                # waiting for finger remove
                while (self.fingerprintSensor.readImage()):
                    pass
                print('Waiting for finger...')
                # wait for finger
                while (self.fingerprintSensor.readImage() is False):
                    pass
                print('Finger read.')
                print('Start convert fingerprint image...')
                self.fingerprintSensor.convertImage(0x02)
                print('Converted.')
                print('Create fingerprint template...')
                self.fingerprintSensor.createTemplate()
                print('Created.')
                print('Download fingerprint template...')
                self.fingerprintTemplate = self.fingerprintSensor.downloadCharacteristics(
                )
                self.fingerprintTemplateValid = True
            except Exception as e:
                print('Something wrong : ' + str(e))
        print('-' * LINEWIDTH)

    def scanOneTime(self):
        if (self.fingerprintSensorValid):
            try:
                self.fingerprintCharValid = False
                print('Waiting for finger...')
                # wait for finger
                startTime = time.time()
                timeout = False
                while (self.fingerprintSensor.readImage() is False
                       and timeout is False):
                    if time.time() - startTime > 20:
                        timeout = True
                print('Finger read.')
                # print('Start convert fingerprint image...')
                self.fingerprintSensor.convertImage(0x01)
                # print('Converted.')
                # print('Download fingerprint characteristic...')
                self.fingerprintChar = self.fingerprintSensor.downloadCharacteristics(
                )
                self.fingerprintCharValid = True
                self.fingerptintCompare = False
                self.fingerptintCompareValid = False
                self.userID = 0
            except Exception as e:
                print('Something wrong : ' + str(e))
        print('-' * LINEWIDTH)

    def fetchAllFingerprint(self):
        # fetch all fingerprint from web database
        fetchEndPoint = "htt]://203.154.59.215:8080/api/data/fingerprint"
        res = urllib2.urlopen(fetchEndPoint)
        content = res.content
        pass

    def compare(self):
        if self.fingerprintCharValid:
            # upload template to address 0x02
            self.fingerprintSensor.uploadCharacteristics(
                0x02, self.fingerprintTemplate)
            score = self.fingerprintSensor.compareCharacteristics()
            if score > 0:
                self.fingerptintCompare = True
                self.userID = 1111111111111
            self.fingerptintCompareValid = True

    def downloadImage(self):
        if (self.fingerprintSensorValid):
            try:
                print('Waiting for finger...')
                # wait for finger
                while (self.fingerprintSensor.readImage() is False):
                    pass

                # save fingerprint image
                print('Saving fingerprint image...')
                self.fingerprintSensor.downloadImage(
                    '/home/pi/healthios/img/fingerprint_img.png')
                print('Fingerprint saved!')
            except Exception as e:
                print('Something wrong : ' + str(e))
        print('-' * LINEWIDTH)
D4 = 24
D5 = 25
D6 = 8
D7 = 7

gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
gpio.setup(RS, gpio.OUT)
gpio.setup(EN, gpio.OUT)
gpio.setup(D4, gpio.OUT)
gpio.setup(D5, gpio.OUT)
gpio.setup(D6, gpio.OUT)
gpio.setup(D7, gpio.OUT)

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('Exception message: ' + str(e))
    exit(1)


def begin():
    lcdcmd(0x33)
    lcdcmd(0x32)
    lcdcmd(0x06)
    lcdcmd(0x0C)
    lcdcmd(0x28)
Exemplo n.º 28
0
# -*- coding: utf-8 -*-
"""
PyFingerprint
Copyright (C) 2015 Bastian Raschke <*****@*****.**>
All rights reserved.

"""

from pyfingerprint import PyFingerprint

## Deletes a finger from sensor
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/serial0', 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()))

for i in xrange(f.getTemplateCount()):
    assert f.deleteTemplate(i)
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.º 30
0
             if line:
                 if (line.find("MoneyBox") !=-1):
                     print 'found! ',line.rstrip()
                     MoneyBox = serial_ports[i]
                     i=i+1
                 else:
                     print 'Not found'
             else:
                 print 'Not found'
                 
                 
         if ((FingerPrint == None) and (i<len(serial_ports))):   
             sys.stdout.write('Searching %s for FingerPrint... ' % serial_ports[i])
             sys.stdout.flush()
             ser.close() 
             f = PyFingerprint(str(serial_ports[i]), BAUDRATE, 0xFFFFFFFF, 0x00000000)
             
             if f:
                 try:
                     if (f.verifyPassword() == True):
                         print 'OK!'
                         FingerPrint = str(serial_ports[i])
                     else:
                         print 'password error!'
                     del f
                 except Exception as e:
                     print 'Not found'
             else:
                 print 'ERROR'
 
     else:
Exemplo n.º 31
0
"""

import hashlib
from pyfingerprint import PyFingerprint
import io
import sys

chr = input().split("lplplp")
digital = list(map(int, chr[0].split(",")))

digital1 = list(map(int, chr[1].split(" ")))

# Tries to initialize the sensor
try:
    f = PyFingerprint('COM4', 115200, 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)

# Tenta registrar digital
try:
    f.uploadCharacteristics(0x01, digital)
    f.uploadCharacteristics(0x02, digital1)

    print(f.compareCharacteristics())
Exemplo n.º 32
0
while ((FingerPrint == None) and (i<len(serial_ports))):
    try:
        sys.stdout.write('Checking  %s ' % serial_ports[i])
        ser = serial.Serial(str(serial_ports[i]),baudrate=BAUDRATE,timeout=TIME_OUT)
    except Exception as e:
        ser = None
        print(str(e))  
    if ser:
        print 'OK' 
        if ser.is_open:
            ser.close()   
            if ((FingerPrint == None) and (i<len(serial_ports))):   
                sys.stdout.write('Searching %s for FingerPrint... ' % serial_ports[i])
                sys.stdout.flush()
                
                f = PyFingerprint(str(serial_ports[i]), BAUDRATE, 0xFFFFFFFF, 0x00000000)
                
                if f:
                    try:
                        if (f.verifyPassword() == True):
                            print 'OK!'
                            FingerPrint = str(serial_ports[i])
                        else:
                            print 'password error!'
                        del f
                    except Exception as e:
                        print 'Not found'
                else:
                    print 'ERROR'
    
        else: