Ejemplo n.º 1
0
from pyfingerprint.pyfingerprint import PyFingerprint

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

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

    print("Clearin database...")
    f.clearDatabase()

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)
class GUI_signup():
    from Mysqsl_module import Connector as consql

    def __init__(self, clear: bool):

        self.id_user = -1
        self.checked = False

        self.reader = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF,
                                    0x00000000)

        if clear:
            self.reader.clearDatabase()

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

        options = [
            'User name:', 'User password:'******'Check in time:', 'Departure time:'
        ]
        self.txtWidgets = {}

        self.gui = Tk(className='Sign up a new fingerprint')

        self.gui.geometry("700x600+450+70")
        self.gui.config(bg="#3465A4")

        self.photo = getImage(os.path.dirname(__file__) + "/reader.gif")
        self.gui.iconphoto(False, self.photo)

        r = 0
        for op in options:
            lbl = Label(text=op, relief=RIDGE)
            lbl.grid(row=r, column=0, padx=10, pady=10)
            lbl.config(width=20, height=2)
            txt = Text(bg="white",
                       relief=SUNKEN,
                       width=50,
                       height=2,
                       fg="black")

            txt.grid(row=r, column=1)
            self.txtWidgets.update({op: txt})
            r += 1

        self.txtVarAction = StringVar()
        self.lblAction = Label(bg="#3465A4",
                               fg="white",
                               textvariable=self.txtVarAction)
        self.lblAction.grid(row=r, column=0, padx=10, pady=20)
        self.txtVarAction.set("Not reading finger yet")
        r += 1

        self.lblImageFinger = Label(bg="#729FCF", fg="black")
        self.lblImageFinger['image'] = self.photo
        self.lblImageFinger.grid(row=r, column=0, padx=10, pady=10)

        self.btnReadFinger = Button(text="Read fingerprint",
                                    command=self.startFingerPrint)
        self.btnReadFinger.grid(row=r + 1, column=0, padx=10)
        self.btnReadFinger.config(width=20, height=2)

        btnStore = Button(text="Store data in database",
                          command=self.storageDatabase)
        btnStore.grid(row=r, column=1)

    def storageDatabase(self):

        for txts in self.txtWidgets.values():

            if not txts.get(1.0, 'end').strip():
                messagebox.showerror(message="All data files must be typed",
                                     title="Values empty")
                return

        if self.id_user == -1:
            messagebox.showerror(
                message="You must scan your finger to get your id",
                title="Not scanned finger yet")
            return

        msg, flag = self.consql.exeProcedure('Insert_user', [
            self.id_user, self.txtWidgets['User name:'].get(
                1.0, 'end').strip(), self.txtWidgets['User password:'******'end').strip(), self.txtWidgets['Check in time:'].get(
                        1.0, 'end').strip(),
            self.txtWidgets['Departure time:'].get(1.0, 'end').strip()
        ], (0, 1))

        if flag == 0:
            messagebox.showerror(title='Error in insertion', message=msg)
        else:
            self.id_user = -1
            self.lblImageFinger['image'] = self.photo
            messagebox.showinfo(title='All is ok', message=msg)

    def startFingerPrint(self):
        threading.Thread(target=self.readFingerPrint,
                         args=("Thread Reader")).start()

    def readFingerPrint(self, *argss):

        try:

            print('Waiting for finger...')
            self.txtVarAction.set("Waiting for finger...")

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

            self.reader.convertImage(0x01)

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

            if (positionNumber >= 0):
                print('Template already exists at position #' +
                      str(positionNumber))
                self.txtVarAction.set("Template already\nexists")
                return

            print('Remove finger...')
            self.txtVarAction.set("Remove finger...")
            time.sleep(2)

            print('Waiting for same finger again...')
            self.txtVarAction.set('Waiting for same finger again...')

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

            print('Downloading image (this take a while)...')
            self.txtVarAction.set('Downloading image\n(this take a while)...')

            imagePath = os.path.dirname(__file__) + "/fingerprint.bmp"
            self.reader.downloadImage(imagePath)

            self.reader.convertImage(0x02)

            if (self.reader.compareCharacteristics() == 0):
                print('Fingers do not match')
                self.txtVarAction.set('Fingers do not match')
                return

            self.reader.createTemplate()

            self.id_user = self.reader.storeTemplate() + 1

            print('The image was saved to "' + imagePath + '".')
            print('Finger enrolled successfully!')

            self.txtVarAction.set('Finger enrolled successfully!')

            self.fingerImage = getImage(imagePath)
            self.lblImageFinger['image'] = self.fingerImage
            print('New template position #' + str(self.id_user - 1))

        except Exception as e:
            print('Operation failed!')
            self.txtVarAction.set('Operation failed!')
            print('Exception message: ' + str(e))
            return

    def run(self):
        self.gui.mainloop()
Ejemplo n.º 3
0
class fingerprint_sensor:
    def __init__(self):
        # Sensor Initialisation
        try:
            self.f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF,
                                   0x00000000)

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

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

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

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

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

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

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

            time.sleep(2)

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

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

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

            # Creates a template
            self.f.createTemplate()

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

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

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

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

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

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

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

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

            positionNumber = result[0]

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

            return match_flag

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

    def Clear_Sensor(self):
        # Deleting the database
        self.f.clearDatabase()
Ejemplo n.º 4
0
class Fingerprint:
    sensor = None
    client = paho.Client("sensor")
    abort = False
    #cont = 0

    def message(self, client, userdata, message):
        print(message.topic)
        if message.topic == "enroll/begin":
            self.abort = True

    def __init__(self):
        """

        :rtype:
        """
        try:
            self.sensor = PyFingerprint('/dev/ttyS0', 57600, 0xFFFFFFFF, 0x00000000)
            self.client.connect("localhost")
            # self.client.subscribe("enroll/begin")
            # self.client.on_message = self.message
            if not self.sensor.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))
            exit(1)

    def search(self):
        try:
            print('Waiting for finger...')
            # Event waiting
            self.client.publish("search/waiting", "Coloque su dedo indice")

            # Wait until a finger is read
            while not self.sensor.readImage() and self.abort is False:
                pass
            # If not abort
            if self.abort is True:
                return
            else:
                self.client.connect("localhost")
                # Event processing
                self.client.publish("search/processing", "")

                # Converts read image to characteristics and stores it in char buffer 1
                self.sensor.convertImage(0x01)

                # Search for template in Ox01
                result = self.sensor.searchTemplate()

                # Position of the template found, if not found it's -1
                position_number = result[0]

                # Accuracy of the search
                accuracy_score = result[1]

                if position_number == -1:
                    # Send signal to monitor app, to communicate has not been found.
                    print('No match found!')
                    # Event notFound
                    self.client.publish("search/notFound", "Not Found")
                else:
                    # Send signal to monitor app to communicate user found
                    # Send signal to Api to store Assistance.
                    # Event found
                    datos = marcar_asistencia(position_number)

                    if not datos is False:
                        self.client.publish("search/found", json.dumps(datos))
                        return
                    else:
                        # Arroja getitem
                        self.client.publish("search/error", "Operacion Fallida")
                        print('Found template at position #' + str(position_number))
                        print('The accuracy score is: ' + str(accuracy_score))
        except IOError as e:
            print("Cachado hijueputa")
            print(e.message)
        except Exception as e:
            print('Operation failed!')
            print('Exception message: ' + str(e))
            # Event Error
            self.client.publish("search/error", "Operacion Fallida")

    def timer(self):
	if self.abort:
	   self.abort = False
        self.abort = True

    def enroll(self, identificacion):
        try:
            self.abort = False
            print("Enroll: Waiting for finger...")
            self.client.connect("localhost")
            # Event waiting No 1
            self.client.publish("enroll/waiting", "Coloque su dedo indice")
            #cont = 0
            # Block until finger is detected
            timer_thread = threading.Timer(10.00, self.timer)
            timer_thread.start()
            while not self.sensor.readImage() and not self.abort:
                pass
            if self.abort:
                print("Abrete")
                # self.client.publish("search/finished", "")
                #self.abort = False
		return
            
	    #self.abort = False
	    # Event processing No 1
            self.client.publish("enroll/processing", "")
            # Convert image to buffer for search if exists
            self.sensor.convertImage(0x01)

            # Store result of search, -1 if not found.
            result = self.sensor.searchTemplate()

            # Check if template exists
            if not result[0] == -1:
                # Send signal to monitor app
                print("Fingerprint exists..")
                # Event existe huella
                self.client.publish("enroll/exist", "Existe registro de la huella")
                return

                # Send signal to remove finger
            print('Remove finger...')
            #time.sleep(2)

            # Send signal to put same finger
            print('Waiting for same finger again...')
            # Event waiting No 2
            self.client.publish("enroll/waiting", "Vuelva a colocar su dedo indice")

	    timer_thread.cancel()
            timer = threading.Timer(10.00, self.timer)
            timer.start()
            # Block until finger is detected
            while not self.sensor.readImage() and not self.abort:
                pass

            if self.abort:
                #self.abort = False
		timer.cancel()
		return
            # Event processing No 2
            self.client.publish("enroll/processing", "")

            # Convert image to characteristic in char_buffer 0x02
            self.sensor.convertImage(0x02)

            if self.sensor.compareCharacteristics() == 0:
                # Send signal that Fingers do not match and must restart process
                # Event Huellas distintas --- raise Exception('Fingers do not match') ---
                self.client.publish("enroll/distint", "Huellas distintas")
                return

            # Create template to store
            self.sensor.createTemplate()

            # Store and retrieve position
            position = self.sensor.storeTemplate()

            registro(position, identificacion)
            # Send signal to show success in monitor
            print('Finger enrolled successfully!')
            # Event Operacion existosa
            self.client.publish("enroll/successful", "Operacion exitosa")
            # Send signal to backend for storing position
            print('New template position #' + str(position))
	    timer_thread.cancel()
	    timer.cancel()
	    self.abort = False
        except Exception as e:
            print(str(e))

    def delete(self, position):
        try:
            result = self.sensor.deleteTemplate(int(position))
            if result:
                # Consumir evento en el test.py
                eliminar(int(position))
                # Send signal to backend that has been deleted correctly.
                print('Template deleted!')

        except Exception as e:
            print(str(e))

    def clear_database(self):
        self.sensor.clearDatabase()