Exemple #1
0
def Key_Pressed():
    keypress = False
    keyboard.Events().start()
    if keyboard.Events().Press(''):
        keypress = True

    if keyboard.Events().Release(''):
        keypress = False

    return keypress
Exemple #2
0
def pipe_indevice_inaudio_ptt(iaq: Queue):
    global PYAUDIO
    global INPUT_DEVICE_NAME

    while True:
        with keyboard.Events() as events:
            for event in events:
                if str(event.key) == USER_PTT_BUTTON and isinstance(
                        event, keyboard.Events.Press):
                    break

        with keyboard.Events() as events:
            device_index = get_device_index(INPUT_DEVICE_NAME)
            device = PYAUDIO.get_device_info_by_index(device_index)
            sample_rate = int(device["defaultSampleRate"])

            stream = PYAUDIO.open(format=PYAUDIO.get_format_from_width(4),
                                  channels=1,
                                  rate=sample_rate,
                                  input=True,
                                  input_device_index=device_index)
            logging.info("Scanning Audio...")
            record_start_time = time.time()

            out_stream = PYAUDIO.open(
                format=PYAUDIO.get_format_from_width(4),
                channels=1,
                rate=44100,
                output=True,
                output_device_index=get_device_index(OUTPUT_DEVICE_NAME))
            frames = []
            for event in events:
                if str(event.key) == USER_PTT_BUTTON and isinstance(
                        event, keyboard.Events.Release):
                    record_end_time = time.time()
                    record_seconds = record_end_time - record_start_time
                    for i in range(0,
                                   int(sample_rate / 1024 * record_seconds)):
                        data = stream.read(1024)
                        out_stream.write(data)
                        frames.append(data)
                    stream.close()
                    break
            audio_data = spr.AudioData(b"".join(frames), sample_rate, 4)
            logging.info("Audio recognized. Queueing...")
            iaq.put(audio_data)

            # DEBUGGING...

            out_stream.close()
Exemple #3
0
def ask(Q):
    looped = 0
    loop = 1

    wnln(Q)
    while True:
        with keyboard.Events() as events:
            # Block for as much as possible
            event = events.get(1e6)
            if event.key == keyboard.KeyCode.from_char(
                    'y') or event.key == keyboard.Key.enter:
                wrep("YES")
                A = True
                break
            if event.key == keyboard.KeyCode.from_char('n'):
                wrep("NO:")
                A = False
                break
            else:
                wnln("\n")
                wrep(
                    f"no valid key detected use y [default] for YES , n for NO , [enter] for default"
                )
                continue
        break

    return A
def track_time(start_time):
    print(f'*****Start time**** {start_time}')
    report_info['Last_Start'] = f'{start_time:%Y.%m.%d %I:%M:%S %p}'
    movement = True
    while movement is True:
        with mouse.Events() as mouse_events, keyboard.Events(
        ) as keyboard_events:
            ms_event = mouse_events.get(timeout=delay / 2)
            kb_event = keyboard_events.get(timeout=delay / 2)
            if (ms_event is None) and (kb_event is None):
                print(f'You did not interact within {delay} seconds')
                end_time = datetime.datetime.now()
                print(f'End Time {end_time}')
                mouse_listener.stop()
                print(f'Stopped Listening to Mouse {mouse_listener.native_id}')
                keyboard_listener.stop()
                print(
                    f'Stopped Listening to Keyboard {keyboard_listener.native_id}'
                )
                movement = False
            else:
                event_time = datetime.datetime.now()
                if kb_event:
                    print(f'Received Keyboard event {event_time}')
                if ms_event:
                    print(f'Received Mouse event {event_time}')
                movement = True
                continue
        time_elapsed = (end_time -
                        start_time) - datetime.timedelta(seconds=delay)
        print(f'Time Elapsed {time_elapsed}')
        add_time(time_elapsed)
        return time_elapsed
Exemple #5
0
def download_faces(start=START, end=END):
    print(
        "Type (s) to save and (d) to delete and (q) to quit.  Always type enter afterwards."
    )
    with open('faceexp-comparison-data-train-public.csv') as csvfile:
        spamreader = csv.reader(csvfile)
        for i, row in enumerate(spamreader):
            if i < start:
                continue
            if i >= end and end != -1:
                break
            np_row = np.array(row[0:15])
            np_row = np_row.reshape((3, 5))
            for data in np_row:
                try:
                    response = requests.get(data[0])
                    img = Image.open(BytesIO(response.content))
                    img = img.crop((float(data[1]) * img.width,
                                    float(data[3]) * img.height,
                                    float(data[2]) * img.width,
                                    float(data[4]) * img.height))
                    img.show()
                    with keyboard.Events() as events:
                        for event in events:
                            if event.key == keyboard.Key.esc or event.key.char == 'q':
                                return
                            if event.key.char == 's':
                                print("SAVED")
                                break
                            if event.key.char == 'd':
                                break
                except:
                    continue
                img.close()
Exemple #6
0
 def run(self):
     with keyboard.Events() as events:
         while True:
             if not self.is_set:
                 time.sleep(0.2)
                 event = events.get()
                 print('Received event {}'.format(event))
                 if event is None:
                     self.run_instances += 1
                     self.files.append(
                         f"dataset\\dino_run_{self.run_instances}.png")
                     self.labels.append('Run')
                     img = ImageGrab.grab()
                     img = img.crop(self.coords)
                     img.save(f"dataset\\dino_run_{self.run_instances}.png")
                 else:
                     if event.key == Key.space:
                         self.jump_instances += 1
                         self.files.append(
                             f"dataset\\dino_jump_{self.jump_instances}.png"
                         )
                         self.labels.append('Jump')
                         img = ImageGrab.grab()
                         img = img.crop(self.coords)
                         img.save(
                             f"dataset\\dino_jump_{self.jump_instances}.png"
                         )
Exemple #7
0
def moveEvents(game, drawer, secs):
    while game.playing:
        # The event listener will be running in this block
        with keyboard.Events() as events:
            # Block at most one second
            event = events.get(secs * 100)
            if event is not None and isinstance(event, keyboard.Events.Press):
                if event.key == keyboard.Key.left:
                    game.changeMoveOfSnake(Move.Movement.LEFT)
                elif event.key == keyboard.Key.up:
                    game.changeMoveOfSnake(Move.Movement.UP)
                elif event.key == keyboard.Key.right:
                    game.changeMoveOfSnake(Move.Movement.RIGHT)
                elif event.key == keyboard.Key.down:
                    game.changeMoveOfSnake(Move.Movement.DOWN)
                elif event.key == keyboard.Key.backspace:
                    print("reset")
                    drawer.reset()
                elif event.key == keyboard.Key.esc:
                    print("stop")
                    game.stop()
                else:
                    print("event.key : " + str(event.key))

    print("stop moveEvents")
Exemple #8
0
 def wait_for_code(code):
     with keyboard.Events() as events:
         while True:
             event = events.get(0.01)
             if event is not None:
                 if event.key == code:
                     return
Exemple #9
0
    def _choose_action(self, game):
        """Reads an action from keyboard inputs.

        Parameters
        ----------
        game : Game
            The current game state. Unused.

        Returns
        -------
        Action
            The action to take.
        """
        with keyboard.Events() as events:
            for event in events:
                time.sleep(0.1)  # Add a small delay between reads to avoid multiple moves per key.
                if event.key == keyboard.Key.left:
                    return Action.LEFT
                elif event.key == keyboard.Key.right:
                    return Action.RIGHT
                elif event.key == keyboard.Key.up:
                    return Action.UP
                elif event.key == keyboard.Key.down:
                    return Action.DOWN
                elif event.key == keyboard.Key.esc:
                    return Action.QUIT
Exemple #10
0
def kb_track_time(start_time):
    print(f'*****Keyboard Start time***** {start_time}')
    report_info['Last_Start'] = f'{start_time:%Y.%m.%d %I:%M:%S %p}'
    keyboard_listener = keyboard.Listener()
    keyboard_listener.start()
    keyboard_listener.wait()
    print(f'Listening for keyboard {keyboard_listener.native_id}')
    movement = True
    while movement is True:
        with keyboard.Events() as keyboard_events:
            kb_event = keyboard_events.get(timeout=delay)
            if kb_event is None:
                print(
                    f'You did not interact with the keyboard within {delay} seconds'
                )
                end_time = datetime.datetime.now()
                print(f'End Time {end_time}')
                keyboard_listener.stop()
                print(
                    f'Stopped Listening to Keyboard {keyboard_listener.native_id}'
                )
                movement = False
            else:
                event_time = datetime.datetime.now()
                # if kb_event:
                #     print(f'Received Keyboard event {event_time}')
                movement = True
                continue
        time_elapsed = (end_time -
                        start_time) - datetime.timedelta(seconds=delay)
        print(f'Time Elapsed {time_elapsed}')
        # add_time(time_elapsed)
        return time_elapsed
Exemple #11
0
def update_tts_ptt():
    global VTTS_PTT_BUTTON

    with keyboard.Events() as events:
        for event in events:
            if isinstance(event, keyboard.Events.Press):
                VTTS_PTT_BUTTON = event.key
                tk_tts_ptt_button.configure(text=str(event.key),
                                            command=update_tts_ptt)
                return
Exemple #12
0
def getch_non_blocking(timeout=1e6):

    from pynput import keyboard
    with keyboard.Events() as events:
        try:
            event = events.get(timeout)
            if hasattr(event.key, 'char'):
                return event.key.char
        except:
            pass
        return None
Exemple #13
0
 def run(self, shared_queue):
     while (self.running):
         end_time = time.perf_counter() + self.push_queue_delay
         keys = []
         while time.perf_counter() < end_time:
             with keyboard.Events() as events:
                 event = events.get(self.push_queue_delay)
                 if isinstance(event, keyboard.Events.Press):
                     keys.append("{}".format(event.key))
         shared_queue.put(keys)
         self.log(logging.info,
                  "send keys to ConcentrationEvaluator: {}".format(keys))
Exemple #14
0
def getTextCoordsCT():
	# The event listener will be running in this block
	with keyboard.Events() as events:
		for event in events:
			if event.key == keyboard.Key.esc:
				break
			elif event.key == keyboard.Key.space:
				#print('Received event {}'.format(event))
				print(pyautogui.position())
				x, y = pyautogui.position()
				root.setvar(name = "ctLatValue", value = x) 
				root.setvar(name = "ctLonValue", value = y) 
				break
Exemple #15
0
def wait_keyboard(expected_keys):
    from pynput import keyboard

    with keyboard.Events() as events:
        while True:
            event = events.get()
            if isinstance(event, keyboard.Events.Press):
                continue
            name = str(getattr(event.key, "name", event.key))
            if name in expected_keys:
                return name
            else:
                print("Unexpected input", name)
Exemple #16
0
def ipt():
    with keyboard.Events() as events:
        event = events.get()
        if event.key == keyboard.KeyCode.from_char('w'):
            return 'w'

        if event.key == keyboard.KeyCode.from_char('a'):
            return 'a'

        if event.key == keyboard.KeyCode.from_char('s'):
            return 's'

        if event.key == keyboard.KeyCode.from_char('d'):
            return 'd'
Exemple #17
0
def play_sequence(runningThread):
    if (len(config.currentPreset['mouseSeq']['recordedEvents']) > 0):
        threading.Thread(target=play_recorded_mouse_sequence).start()
        try:
            with keyboard.Events() as events:
                while config.state == config.PLAYING_MOUSE_SEQ:
                    # Block at most 0.01 second
                    event = events.get(timeout=0.01)
                    if event is not None and event.key == keyboard.Key.esc:
                        break
                raise keyboard.Listener.StopException()
        except keyboard.Listener.StopException:
            # we need to raise these exceptions because of a listener.stop() bug with Xorg
            pass
def keyboard_joystick(s):
    with keyboard.Events() as events:
        event = events.get(1e6)
        if event.key == keyboard.KeyCode.from_char('w'):
            s.write(arc_test_string_fwd.encode())
            return 0
        if event.key == keyboard.KeyCode.from_char('s'):
            s.write(arc_test_string_bkw.encode())
            return 0
        if event.key == keyboard.KeyCode.from_char('a'):
            s.write(arc_test_string_ccw.encode())
            return 0
        if event.key == keyboard.KeyCode.from_char('d'):
            s.write(arc_test_string_cw.encode())
            return 0
def move_mouse():
    pyautogui.FAILSAFE = False

    while True:
        with keyboard.Events() as events:
            # Block at most one second
            event = events.get(0.5)
            if event is not None:
                print('Interrompido!')
                break
            else:
                move = random.randint(-10, 10)
                pyautogui.move(move, move, duration=.03)
                pyautogui.move(-move, move, duration=.03)
                pyautogui.move(-move, -move, duration=.03)
                pyautogui.move(move, -move, duration=.03)
Exemple #20
0
    def act(self, state):
        from pynput import keyboard
        with keyboard.Events() as events:
            # Block for as much as possible
            input_key = events.get(1000000).key

        if input_key == keyboard.KeyCode.from_char('w'):
            return Action.SPEED_UP
        elif input_key == keyboard.KeyCode.from_char('s'):
            return Action.SLOW_DOWN
        elif input_key == keyboard.KeyCode.from_char('a'):
            return Action.TURN_LEFT
        elif input_key == keyboard.KeyCode.from_char('d'):
            return Action.TURN_RIGHT
        else:
            return Action.CHANGE_NOTHING
Exemple #21
0
def play_kbm_map(runningThread):
    if (len(config.currentPreset['kbmMap']) > 0):
        try:
            with keyboard.Events() as events:
                while config.state == config.PLAYING_KBM_CONNECTIONS:
                    # Block at most 0.01 second
                    event = events.get(timeout=0.01)
                    if event is not None:
                        if type(event) == keyboard.Events.Press:
                            on_playing_press(event.key)
                        elif type(event) == keyboard.Events.Release:
                            on_playing_release(event.key)
                raise keyboard.Listener.StopException()
        except keyboard.Listener.StopException:
            # we need to raise these exceptions because of a listener.stop() bug with Xorg
            pass
Exemple #22
0
def person(batch: int) -> Tensor:
    from pynput import keyboard
    d = {
        keyboard.Key.right: 0,
        keyboard.Key.down: 1,
        keyboard.Key.left: 2,
        keyboard.Key.up: 3
    }
    action = None
    while action == None and States.running:
        with keyboard.Events() as events:
            event = events.get()
            if event.__class__ == keyboard.Events.Press:
                if event.key in d:
                    action = d[event.key]
    if action == None:
        return tensor([0 for _ in range(batch)])
    return tensor([action for _ in range(batch)])
Exemple #23
0
def assumerole():
  # anotheraccountresponse = stsclient.assume_role(
  #   RoleArn="arn:aws:iam::689020024752:role/OrganizationAccountAccessRole",
  #   RoleSessionName='master_to_acess_VLG',
  # )
  # credentials=anotheraccountresponse['Credentials']
  # print(credentials)

  # access_key_id='ASIA2A3GLG6YDUYYZQTN',
  # secret_access_key='Nk5rDwkQqXbIp4y7P5NrKWrawB7OWb7NuWGN4q7S',
  # session_token='FwoGZXIvYXdzEBkaDIr2maYtueXJzK53wyK3Ab4LDVJAAqWtAE7dOmnyAAyOL9iTYB4Uv/TvzUEfUySkhs1ZyoLx/EFRsMELw9VbZ7JX8YOnU1/o94P1S8rVsudR8s1FJXOzp+I4QCPeLspk8xFyqhf4XGwaxF97LSNODDZbG4kj/BXVEeuUyNGfQXqrbzMep45LKgMCfeEOTVbexm6rtD7llnDyHs65dwOdw5H7GwNYaTYs7z5m8p5ur0CXw5kWa75jSqr8u0qFewLGFZRkvDv7byj5r8L/BTItKiJGeQ3Lvq+YAOuxu3p6X4e8/fAebjOXhI1TDPd8Fx4hxol7ls/U3nYhzLig',
  
  # iamclient = boto3.client(
  #   'iam',
  #   aws_access_key_id= 'ASIA2A3GLG6YDUYYZQTN',
  #   aws_secret_access_key= 'Nk5rDwkQqXbIp4y7P5NrKWrawB7OWb7NuWGN4q7S',
  #   aws_session_token= 'FwoGZXIvYXdzEBkaDIr2maYtueXJzK53wyK3Ab4LDVJAAqWtAE7dOmnyAAyOL9iTYB4Uv/TvzUEfUySkhs1ZyoLx/EFRsMELw9VbZ7JX8YOnU1/o94P1S8rVsudR8s1FJXOzp+I4QCPeLspk8xFyqhf4XGwaxF97LSNODDZbG4kj/BXVEeuUyNGfQXqrbzMep45LKgMCfeEOTVbexm6rtD7llnDyHs65dwOdw5H7GwNYaTYs7z5m8p5ur0CXw5kWa75jSqr8u0qFewLGFZRkvDv7byj5r8L/BTItKiJGeQ3Lvq+YAOuxu3p6X4e8/fAebjOXhI1TDPd8Fx4hxol7ls/U3nYhzLig',
  # )

  # Userresponse = iamclient.create_user(
  #   UserName='******',
  # )
  # print(Userresponse)

  with keyboard.Events() as events:
    x=2
    while x==2:
      event = events.get(30.0)
      if event is None:
        print("sss")
        iamclient = boto3.client(
        'iam',
        aws_access_key_id= 'ASIA2A3GLG6YLVZDBIUK',
        aws_secret_access_key= 'ZPUUrQqSVCYQ8p6C4BUPxeAxTYllL9WJXhTpVCop',
        aws_session_token= 'FwoGZXIvYXdzEGkaDApsoCvMOLX2WSGqpiK3AW7Pe9I+lUELFGDS+lrbK5wmEtYg6i4kFH8ZBBsVc7Q2LzPKQL5ZSkE76EqyY+hIlcUGefpqYioV44yT4i8htSiPFmcnHVKBydqYYR+t3K68qn2sTDTihVAOwuhCsWO1go0PYRK8bsULqmDoYBYDFn1wSkmHlysAQo5gUnkz6SZ9yJMlSLndjWkLD0oH20QNfDgSCkvQnmtJaeo+NXnIC18SlEvNT2Ftv3iGqharyo83DfY9pqDTNCj0gYyABjItJk7WPpf138ueJpym0ybAbpLM9zeZ1fOJua7jx+kEFsVS59U0SSRK+SY+A6Et',
        )
        response = iamclient.detach_role_policy(
            RoleName='OrganizationAccountAccessRole',
            PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess'
        )
        print("deleted")
        break
      else:
        print('Received event {}'.format(event))
def main():
    while True:
        time_offset = 30
        with keyboard.Events() as events:
            counter = 0
            future = time.time() + time_offset
            # Block at most one second
            for event in events:
                if time.time() < future:
                    counter += 1
                    #print('event happened')
                else:
                    print(counter)
                    send_data_to_server(counter)
                    counter = 0
                    future = time.time() + time_offset
            event = events.get(time_offset)
            if event is None:
                print('nope')
Exemple #25
0
def start_recording(runningThread):
    global mainThread
    mainThread = runningThread
    try:
        with keyboard.Events() as events:
            while config.state == config.RECORDING_KBM_CONNECTIONS:
                # Block at most 0.01 second
                event = events.get(timeout=0.01)
                if event is not None:
                    if type(event) == keyboard.Events.Press:
                        try:
                            on_recording_press(event.key)
                        except mouse.Listener.StopException:
                            pass
            raise keyboard.Listener.StopException()
    except keyboard.Listener.StopException:
        # we need to raise these exceptions because of a listener.stop() bug with Xorg
        pass
    mainThread = None
Exemple #26
0
    def custom_action(self, robot_x, robot_y, goal_x, goal_y, Map):
        action = '_'
        
        if self.canDoAction():
            action = self.doAction()
            return action
        
        while action[0] == '_':
            with keyboard.Events() as events:
                event = events.get(1e6)
                if hasattr(event.key,'char'):
                    action = event.key.char

        if action.lower()=='w':
            self.moveUp()
        elif action.lower()=='s':
            self.moveDown()
        elif action.lower()=='d':
            self.moveRight()
        elif action.lower()=='a':
            self.moveLeft()
Exemple #27
0
def test(game, model, n_games, verbose=1):
    # Train
    # Reseting the win counter
    win_cnt = 0
    # We want to keep track of the progress of the AI over time, so we save its win count history
    win_hist = []
    flag = 0
    model = model.to(device)
    # Epochs is the number of games we play
    for e in range(n_games):
        # Resetting the game
        game.reset()
        game_over = False
        # get tensorflow running first to acquire cudnn handle
        input_t = game.observe()
        if e == 0:
            paused = True
            flag = 1
            print(
                'Training is paused. Press p once game is loaded and is ready to be played.'
            )
        else:
            paused = False
        counting = 0
        win_cnt = 0
        total_count = 0
        while not game_over:
            if not paused:
                # The learner is acting on the last observed game screen
                # input_t is a vector containing representing the game screen
                input_tm1 = input_t
                """
                We want to avoid that the learner settles on a local minimum.
                Imagine you are eating in an exotic restaurant. After some experimentation you find 
                that Penang Curry with fried Tempeh tastes well. From this day on, you are settled, and the only Asian 
                food you are eating is Penang Curry. How can your friends convince you that there is better Asian food?
                It's simple: Sometimes, they just don't let you choose but order something random from the menu.
                Maybe you'll like it.
                The chance that your friends order for you is epsilon
                """

                # Choose yourself
                # q contains the expected rewards for the actions
                print("begin predict q value")
                input_tm1 = torch.Tensor(input_tm1).float()
                with torch.no_grad():
                    q = model(input_tm1)
                # We pick the action with the highest expected reward
                print('q values=' + str(q[0]))
                action = np.argmax(q[0])
                counting += 1
                # apply action, get rewards and new state
                input_t, reward, game_over = game.act(action)
                total_count += 1
                # If we managed to catch the fruit we add 1 to our win counter
                if reward == 1:
                    win_cnt += 1
                """
                The experiences < s, a, r, s’ > we make during gameplay are our training data.
                Here we first save the last experience, and then load a batch of experiences to train our model
                """

            keys = []
            if flag == 1:
                with keyboard.Events() as events:
                    print("choose to pause or continue")
                    for event in events:
                        if event.key == keyboard.Key.alt_l:
                            keys.append("C")
                            print("continue")
                            break
                if 'C' in keys:
                    print('unpausing!')
                    paused = False
                    time.sleep(1)
                flag = 0
            if counting == 5:
                game_over = True
        if verbose > 0:
            print("Game {:03d}/{:03d} | Win count {}".format(
                e, n_games, win_cnt))
        win_hist.append(win_cnt / total_count)
    return win_hist
Exemple #28
0
def train(game, model, target_net, epochs, verbose=1):
    # Train
    # Reseting the win counter
    win_cnt = 0
    # We want to keep track of the progress of the AI over time, so we save its win count history
    win_hist = []
    # Epochs is the number of games we play
    flag = 0
    model = model.to(device)
    optimizer = optim.Adam(model.parameters(), lr=1e-3)
    for e in range(epochs):
        loss_total = 0.
        epsilon = 4 / ((e + 1)**(1 / 2))
        # Resetting the game
        game.reset()
        game_over = False
        # get tensorflow running first to acquire cudnn handle
        input_t = game.observe()
        if e == 0:
            paused = True
            flag = 1
            print(
                'Training is paused. Press alt.l once game is loaded and is ready to be played.'
            )
        else:
            paused = False
        counting = 0
        win_cnt = 0
        total_count = 0
        while not game_over:
            if not paused:
                # The learner is acting on the last observed game screen
                # input_t is a vector containing representing the game screen
                input_tm1 = input_t
                """
                We want to avoid that the learner settles on a local minimum.
                Imagine you are eating in an exotic restaurant. After some experimentation you find 
                that Penang Curry with fried Tempeh tastes well. From this day on, you are settled, and the only Asian 
                food you are eating is Penang Curry. How can your friends convince you that there is better Asian food?
                It's simple: Sometimes, they just don't let you choose but order something random from the menu.
                Maybe you'll like it.
                The chance that your friends order for you is epsilon
                """
                if np.random.rand() <= epsilon:
                    # Eat something random from the menu
                    action = int(np.random.randint(0, num_actions, size=1))
                    print(action)
                    print('random action')
                else:
                    # Choose yourself
                    # q contains the expected rewards for the actions
                    input_tm1 = torch.from_numpy(input_tm1).float()
                    q = model(input_tm1)
                    # We pick the action with the highest expected reward
                    action = np.argmax(q.data.cpu().numpy())
                counting += 1
                # apply action, get rewards and new state
                input_t, reward = game.act(action)
                total_count += 1
                # If we managed to catch the fruit we add 1 to our win counter
                if reward > 0:
                    win_cnt += 1
                """
                The experiences < s, a, r, s’ > we make during gameplay are our training data.
                Here we first save the last experience, and then load a batch of experiences to train our model
                """

                # store experience
                game.remember([input_tm1, action, reward, input_t])

                # Load batch of experiences
                inputs, targets = game.get_batch(model,
                                                 target_net,
                                                 batch_size=batch_size,
                                                 game_over=game_over)

                # train model on experiences
                inputs = torch.from_numpy(inputs).float()
                targets = torch.from_numpy(targets).float()
                pred = model(inputs)
                loss = creterion(pred, targets)
                optimizer.zero_grad()
                loss.backward()
                optimizer.step()

                # print(loss)
                loss_total += loss

            # menu control
            keys = []
            if flag == 1:
                with keyboard.Events() as events:
                    print("choose to pause or continue")
                    for event in events:
                        if event.key == keyboard.Key.alt_l:
                            print("continue action")
                            keys.append("C")
                            break
                        if event.key == keyboard.Key.ctrl_l:
                            keys.append("P")
                            print("stop train, wait for ready")
                            break
                    if 'C' in keys:
                        print("continue")
                        paused = False
                        time.sleep(1)
                flag = 0
            if counting == 5:
                game_over = True
                target_net.load_state_dict(model.state_dict())
        if verbose > 0:
            print("Epoch {:03d}/{:03d} | Loss {:.4f} | Win count {}".format(
                e, epochs, loss_total, win_cnt))
        if e % 500 == 0:
            save_model(model, e)
        win_hist.append(win_cnt / total_count)
    return win_hist
Exemple #29
0
mouse = Mouse_controller()


def ms_click():
    print('开始连点')
    while True:
        time.sleep(0.1)
        mouse.click(Button.left)
        if event.key == keyboard.Key.backspace:  # 防止退出后线程还在
            print('连点结束')
            break


print('press enter to start,\nand press backspace to stop,\nand press esc to quit.')

# The event listener will be running in this block
t = threading.Thread(target=ms_click)

with keyboard.Events() as events:
    for event in events:
        if event.key == keyboard.Key.esc:
            print('Received event {}'.format(event))
            sys.exit()
        elif event.key == keyboard.Key.enter:
            print('Received event {}'.format(event))
            t.start()
        else:
            print('Received event {}'.format(event))
# 程序开始后,按enter开始连点,按删除键停止,按esc退出程序
# 注意只按一次啊,这是开的线程,按多了就是多个线程,自己等死吧
def main():
    #"""
    # Setttings for configuring our pinging to the motors.
    settings_set = {}

    # Get the port name through a system call
    raw_port_command = os.popen("ls /dev/ttyUSB*")
    raw_ports = raw_port_command.read()
    port_list_raw = raw_ports.split()
    port_list = []

    # Real motors, and matches the launch file simple_l_arm_controller_manager.launch
    # port_list = {port}
    settings = {
        'baudrate': 1000000,
        'minID': 1,
        'maxID': 40,
        'updateRate': 20,
        'diagnosticsRate': 1
    }

    # Get Port List without /dev/
    for raw_port in port_list_raw:
        port = raw_port.replace('/dev/', '')
        settings_set[port] = settings
        port_list.append(port)

    manager = RobotManager(port_list, settings_set)

    idict_x = manager.ports_by_name["ttyUSB0"].proxy.get_feedback(12)
    current_pos_x = idict_x["position"]

    idict_y = manager.ports_by_name["ttyUSB0"].proxy.get_feedback(11)
    current_pos_y = idict_y["position"]

    coordinates = {"x": current_pos_x, "y": current_pos_y}

    manager.ports_by_name["ttyUSB0"].proxy.set_torque_enabled(12, [1])
    manager.ports_by_name["ttyUSB0"].proxy.set_torque_enabled(11, [1])
    manager.ports_by_name["ttyUSB0"].proxy.set_torque_enabled(13, [1])
    manager.ports_by_name["ttyUSB0"].proxy.set_torque_enabled(14, [1])
    manager.ports_by_name["ttyUSB0"].proxy.set_torque_enabled(15, [1])
    manager.ports_by_name["ttyUSB0"].proxy.set_torque_enabled(1, [1])
    manager.ports_by_name["ttyUSB0"].proxy.set_torque_enabled(2, [1])
    manager.ports_by_name["ttyUSB0"].proxy.set_torque_enabled(3, [1])
    manager.ports_by_name["ttyUSB0"].proxy.set_torque_enabled(4, [1])
    manager.ports_by_name["ttyUSB0"].proxy.set_torque_enabled(5, [1])

    dict_all = {}

    for idx in range(1, 5):
        tmp_dict = manager.ports_by_name["ttyUSB0"].proxy.get_feedback(idx)
        dict_all[str(idx)] = tmp_dict["position"]

    for idx in range(11, 15):
        tmp_dict = manager.ports_by_name["ttyUSB0"].proxy.get_feedback(idx)
        dict_all[str(idx)] = tmp_dict["position"]

    increment = 0.5

    with keyboard.Events() as events:
        while True:
            event = events.get(1e6)
            if event.key == keyboard.KeyCode.from_char('d'):
                if coordinates["x"] >= 360:
                    coordinates["x"] = 0
                if (coordinates["x"] + 1) != 30:
                    coordinates["x"] += increment
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    11, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    12, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    13, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    14, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    15, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    1, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    2, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    3, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    4, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    5, coordinates["x"])
            elif event.key == keyboard.KeyCode.from_char('a'):
                if coordinates["x"] <= 0:
                    coordinates["x"] = 360
                if (coordinates["x"] - 1) != 330:
                    coordinates["x"] -= increment
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    11, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    12, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    13, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    14, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    15, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    1, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    2, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    3, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    4, coordinates["x"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    5, coordinates["x"])
            elif event.key == keyboard.KeyCode.from_char('s'):
                if coordinates["y"] <= 0:
                    coordinates["y"] = 360
                if (coordinates["y"] - 1) != 330:
                    coordinates["y"] -= increment
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    11, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    12, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    13, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    14, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    15, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    1, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    2, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    3, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    4, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    5, coordinates["y"])
            elif event.key == keyboard.KeyCode.from_char('w'):
                if coordinates["y"] >= 360:
                    coordinates["y"] = 0
                if (coordinates["y"] + 1) != 30:
                    coordinates["y"] += increment
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    11, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    12, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    13, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    14, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    15, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    1, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    2, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    3, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    4, coordinates["y"])
                manager.ports_by_name["ttyUSB0"].proxy.set_goal_position(
                    5, coordinates["y"])
            print("X Coordiate: %s, Y Coordinate: %s" %
                  (coordinates["x"], coordinates["y"]))
            for idx in range(0, 4):
                tmp_dict = manager.ports_by_name["ttyUSB0"].proxy.get_feedback(
                    idx + 1)
                dict_all[str(idx)] = tmp_dict["position"]

            for idx in range(10, 14):
                tmp_dict = manager.ports_by_name["ttyUSB0"].proxy.get_feedback(
                    idx + 1)
                dict_all[str(idx)] = tmp_dict["position"]

            for idx in dict_all:
                print("Coordinate %s: %s ::: " % (idx, dict_all[idx]))