Exemplo n.º 1
0
    def return_screenFour():  # Invokes the Screen Four
        try:  # Try to clear the user from DB that not enrolled its fingerprint
            conn = sqlite3.connect(
                "/home/pi/github/Projeto-Fechadura-Biometrica/User-Interface/optima.db"
            )
            cursor = conn.cursor()

            cursor.execute("""SELECT * FROM optima WHERE finger1 is ?""",
                           (None, ))

            row = cursor.fetchall()

            if len(row) != 0:
                index = row[0]
                index = index[0]
                cursor.execute("DELETE FROM optima WHERE member_id is ?",
                               (index, ))

            conn.commit()
            conn.close()

        except Exception as e:
            writeError("Tela05.py - return_screenFour() error", str(e))

        turnOff_led(LED_BLUE)
        gpio.cleanup()
        root.destroy()
        tela04.telaquatro()
Exemplo n.º 2
0
def initialize_sensor():
    try:
        uart = serial.Serial("/dev/ttyS0", baudrate=57600, timeout=1)
        f = adafruit_fingerprint.Adafruit_Fingerprint(uart)
        return f

    except Exception as e:
        writeError("Tela08.py - initialize_sensor() error", str(e))
        return None
Exemplo n.º 3
0
def initialize_sensor():
    try:
        uart = serial.Serial("/dev/ttyS0", baudrate=57600, timeout=1)
        sensor = adafruit_fingerprint.Adafruit_Fingerprint(uart)
        return sensor

    except Exception as e:
        writeError("Tela05.py - initialize_sensor() error", str(e))
        blink_led(LED_RED, 1)
        return None
Exemplo n.º 4
0
    def apagaIndex(*args):
        # This function deletes the indicated indexSensor when it's passed as argument
        try:
            uart = serial.Serial("/dev/ttyS0", baudrate=57600, timeout=1)
            sensor = adafruit_fingerprint.Adafruit_Fingerprint(uart)

            for index in args:
                sensor.delete_model(int(index))

        except Exception as e:
            writeError("Tela06.py - apagaIndex() error", str(e))
Exemplo n.º 5
0
        def connectSensor(self):
            # this function tries to connect the Fingerprint sensor e shows message of confirmation or not
            try:
                self.showMessage("Initializing sensor...")
                sensor = initialize_sensor()

                if sensor is not None:
                    self.showMessage("\nSensor Connected")
                else:
                    self.showMessage("\nSensor not Connected")
                    raise Exception("Sensor not connected")

                sleep(1)

                acendeLed(LED_BLUE)
                self.showMessage("\nWaiting for finger...")

                i = 0
                while sensor.get_image() != adafruit_fingerprint.OK:
                    if i == 1400:
                        fechar()
                    i += 1

                apagaLed(LED_BLUE)
                sleep(1)

                sensor.image_2_tz(1)

                if sensor.finger_search() != adafruit_fingerprint.OK:
                    self.showMessage("\nFinger not found!\n")
                    pisca_led(LED_RED)
                    del sensor
                    self.connectSensor()
                else:
                    nome = DBAcess(sensor.finger_id)
                    pisca_led(LED_GREEN)
                    self.showMessage("\nWelcome " + str(nome))
                    unlockDoor()
                    self.widget2.after(3000, fechar)

            except Exception as e:
                pisca_led(LED_RED)
                print(str(e))
                self.showMessage("\nError - " + str(e))
                sleep(2)
                writeError("Tela08.py - connectSensor() error", str(e))
                fechar()
Exemplo n.º 6
0
    def DBAcess(i):
        try:
            # this function connects optima DB and searches the user associated to fingerprint index,
            # salves the user's entry in Stream.txt file and returns first name and lastname user's as string
            conn = sqlite3.connect(
                "/home/pi/github/Projeto-Fechadura-Biometrica/User-Interface/optima.db"
            )
            cursor = conn.cursor()

            cursor.execute("""SELECT finger1, finger2, finger3 FROM optima;""")

            rows = cursor.fetchall()

            for row in rows:
                if i in row:
                    position = row.index(i)
                    break

            if position == 0:
                cursor.execute(
                    """SELECT first_name AS FIRST_NAME,
                                    last_name AS LAST_NAME,
                                    title AS TITLE
                                    FROM optima WHERE finger1 = ?""",
                    (str(i), ))
            elif position == 1:
                cursor.execute(
                    """SELECT first_name AS FIRST_NAME,
                                    last_name AS LAST_NAME,
                                    title AS TITLE
                                    FROM optima WHERE finger2 = ?""",
                    (str(i), ))
            elif position == 2:
                cursor.execute(
                    """SELECT first_name AS FIRST_NAME,
                                    last_name AS LAST_NAME,
                                    title AS TITLE
                                    FROM optima WHERE finger3 = ?""",
                    (str(i), ))

            rows = cursor.fetchall()
            conn.commit()
            conn.close()

            for row in rows:
                continue

            now = datetime.now()
            hora = now.strftime("%d/%m/%Y %H:%M:%S")
            with open(
                    '/home/pi/github/Projeto-Fechadura-Biometrica/User-Interface/Stream.txt',
                    'a') as arquivo:
                arquivo.writelines(
                    str(row[0]) + " " + str(row[1]) + " " + str(row[2]) + " " +
                    hora + " Entrada\n")

            with open(
                    '/home/pi/github/Projeto-Fechadura-Biometrica/User-Interface/Control.txt',
                    'a') as file_control:
                file_control.writelines(
                    str(row[0]) + " " + str(row[1]) + " " + str(row[2]) + "\n")

            return str(row[0] + " " + row[1])

        except UnboundLocalError as e:  # In case that it raises this exception
            writeError("Tela08.py - DBAccess() error", str(e))
Exemplo n.º 7
0
        def enroll_fingerprint(self):
            _user_finger = []
            try:
                self.prompt.delete(0.0, END)
                self.prompt.insert(END, "Initializing the Sensor...")
                self.prompt.update()

                # initializing sensor
                sensor = initialize_sensor()

                # verifies if sensor is connected
                if sensor is None:
                    self.prompt.insert(END, "\nSensor not Connected")
                    raise Exception("Sensor is not connected Error")

                else:
                    self.prompt.insert(END, "\nSensor Connected")

                self.prompt.update()

                for i in range(1, 4):  # The user will saves 3 fingers
                    self.prompt.insert(END, "\nEnrolling finger #" + str(i))
                    self.prompt.update()

                    sleep(1)

                    for j in range(1, 3):  # Read a finger twice
                        self.prompt.insert(END, "\nWaiting for finger...")
                        turnOn_led(LED_BLUE)
                        self.prompt.update()

                        while sensor.get_image() != adafruit_fingerprint.OK:
                            pass

                        self.prompt.insert(END, "\nRemove finger")
                        turnOff_led(LED_BLUE)
                        self.prompt.update()

                        sleep(2)

                        sensor.image_2_tz(j)  # creates a temporary template

                        while sensor.finger_search(
                        ) == adafruit_fingerprint.OK:
                            # verifies if the sensor already exist at the memory
                            self.prompt.insert(
                                END, "\nTemplate already exists at #" +
                                str(sensor.finger_id))
                            self.prompt.insert(
                                END, "\nPlease, Enroll other finger")
                            self.prompt.update()

                            sleep(2)
                            self.prompt.delete(3.0, END)

                            self.prompt.insert(END,
                                               "\nWaiting for another finger")
                            self.prompt.update()
                            turnOn_led(LED_BLUE)

                            while sensor.get_image(
                            ) != adafruit_fingerprint.OK:
                                pass

                            self.prompt.insert(END, "\nRemove finger")
                            self.prompt.update()
                            turnOff_led(LED_BLUE)

                            sensor.image_2_tz(j)

                    # creating a model
                    sensor.create_model()

                    # search for the first index without model
                    if sensor.read_templates() != adafruit_fingerprint.OK:
                        raise RuntimeError("Failed to read templates")

                    posnumber = 0

                    for pos in sensor.templates:
                        if posnumber == pos:
                            posnumber += 1
                        else:
                            continue

                    sensor.store_model(posnumber)
                    _user_finger.append(posnumber)

                    self.prompt.insert(
                        END,
                        "\nTemplate saves in index #" + str(posnumber) + "\n")
                    self.prompt.update()

                    self.prompt.delete(3.0, END)

            except Exception as e:
                writeError("Tela05.py - enroll_fingerprint() - sensor error",
                           str(e))

            try:
                conn = sqlite3.connect(
                    "/home/pi/github/Projeto-Fechadura-Biometrica/User-Interface/optima.db"
                )
                cursor = conn.cursor()

                cursor.execute(
                    """
                                UPDATE optima
                                SET finger1 = (?), finger2 = (?), finger3 = (?)
                                WHERE finger1 IS NULL """, (
                        _user_finger[0],
                        _user_finger[1],
                        _user_finger[2],
                    ))

                conn.commit()
                conn.close()
                self.prompt.insert(END, "\nUser successfully enrolled!!")
                self.prompt.update()

            except Exception as e:
                writeError("Tela05.py - enroll_fingerprint() - DB error",
                           str(e))

                if len(_user_finger) != 0:
                    for index in _user_finger:
                        sensor.delete_model(index)

                self.prompt.insert(
                    END,
                    "\nUser not enrolled, please click 'Enroll' and repeat")
                self.prompt.update()
Exemplo n.º 8
0
        def enabledb(self):
            """Inserts the data input by user in DB"""
            # get info by user on entry input
            p_first_name = self.firstname.get()
            p_last_name = self.lastname.get()
            p_title = self.title.get()
            p_password = self.password.get()
            p_admin = self.var.get()

            pfirstname = p_first_name.casefold()
            plastname = p_last_name.casefold()

            # Exception Handling to verify there are copies
            try:
                if(pfirstname == "") and (plastname == ""):
                    self.msg["text"] = "Please, Type a valid data"
                    raise Exception("InvalidAttributeError")
                
                # escreve valores no banco
                conn = sqlite3.connect('optima.db')
                cursor = conn.cursor()

                if p_admin == 1:
                    p_password = p_password.encode('utf-8')
                    p_password = hashlib.sha256(p_password).hexdigest()
                    
                    cursor.execute("""
                        INSERT INTO optima (first_name, last_name, title, admin, senhas)
                        VALUES (?, ?, ?, ?, ?)
                        """, (pfirstname, plastname, p_title, p_admin, p_password,))
                    
                else:
                    cursor.execute("""
                        INSERT INTO optima (first_name, last_name, title, admin)
                        VALUES (?, ?, ?, ?)
                        """, (pfirstname, plastname, p_title, p_admin,))
                    
                conn.commit()
                conn.close()
                root.destroy()

                # creating custom logger
                logger = logging.getLogger(__name__)
                # handler setting
                f_handler = logging.FileHandler('logs/datalog.txt')
                f_handler.setLevel(logging.DEBUG)
                # setting format
                f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -- %(message)s',
                                             '%d/%m/%Y %H:%M:%S')
                f_handler.setFormatter(f_format)
                # Add loggers to the handler
                logger.addHandler(f_handler)

                if p_admin == 1:
                    logger.info("First Name: %s \tLast Name: %s \tTitle: %s \tAdmin:YES",
                                p_first_name, p_last_name, p_title)
                    
                if p_admin == 0:
                    logger.info("First Name: %s \tLast Name: %s \tTitle: %s \tAdmin:NO",
                                p_first_name, p_last_name, p_title)

                tela05.telacinco()

            except sqlite3.Error as e:  # se o python levantar uma excecao - ocorre esse loop
                writeError("enabledb function - tela04.py", str(e))
                
                erro = ' '.join(e.args)
                erro = erro.split(" ")
                
                if erro[0] == 'UNIQUE':
                    self.msg["text"] = "Name already enrolled. Input new data."
                    
                else:
                    print(str(e))
                    self.msg["text"] = ' '.join(erro)
                
                self.botaoLoad["state"] = DISABLED
                self.botaoFingerprint["state"] = DISABLED
                
                if p_admin == 1:
                    self.check.toggle()
                
                self.firstname.delete(0, END)
                self.lastname.delete(0, END)
                self.password.delete(0, END)
                self.title.delete(0, END)
                    
                del p_first_name
                del p_last_name
                del p_title
                del p_password
                del p_admin
                
                self.botaoFingerprint["state"] = NORMAL
                self.botaoLoad["state"] = NORMAL
            
            except Exception as e:
                writeError("Tela04.py - enabledb() error", str(e))