def main(route_json_path):
    route = Route(route_json_path, dry_run=True, start_map=None)

    keyboard_input = KeyboardInput()

    # Loop through the positions in our list one at a time
    while not route.is_complete():
        next_pose = route.get_next_waypoint()
        print(next_pose)

        if keyboard_input.check_hit():

            char = keyboard_input.get_char()

            # Skip the waypoint if n is pressed (ord == 110)
            if "n" == char:
                print("Skipping waypoint: ", next_pose.name)
                break

            # If the space bar is pressed, just wait until
            if " " == char:
                print("Pausing")
                pause(keyboard_input)

        # Wait for a second to make sure the ARK has time to accept the goal
        time.sleep(1.0)
 def __init__(self, servoKit):
     self.__kit = servoKit
     self.__keyboardInput = KeyboardInput("Steering Calibration")
     config_file = servoStatusFile = os.path.abspath(
         os.path.join(os.path.dirname(__file__),
                      "..")) + "/config/servo_status.json"
     self.__steering = Steering(self.__kit, config_file)
     self.__suspension = Suspension(self.__kit, config_file)
Esempio n. 3
0
    def run_one_with_input(self):
        ki = KeyboardInput()
        ki.add_to_window(game.env.unwrapped.viewer.window)

        def get_action():
            self.game.render()
            return ki.get_action()

        return self._run_one(get_action)
Esempio n. 4
0
    def run_with_input(self):
        ki = KeyboardInput()
        ki.add_to_window(game.env.unwrapped.viewer.window)

        def get_action():
            self.game.render()
            return ki.get_action()

        for loss, cumulative in self._run(get_action):
            yield loss, cumulative
Esempio n. 5
0
    def setup(self, sensitivities):
        self.sample_counter = 0

        data = self.h.read(64)
        self.organize_data(data)
        self.sum_panel_data(self.panel_data)
        self.keyboard_input = KeyboardInput(self.panel_values, sensitivities)

        self.pressed_on_frame = list(range(4))
        self.last_frame = list(range(4))
        self.led_frame = 0
        self.led_panel = 0
        self.led_segment = 0
        self.led_frame_data = 0
        self.led_data = []
        self.lights_counter = 0

        thread = threading.Thread(target=self.loop, daemon=True)
        thread.start()
 def calibrate_steering(self, index):
     waitForWheel = True
     keyboardInput = KeyboardInput("Calibrate Steering:")
     print(
         "Press Up/Down to test or w/z to adjust wheel delta, 0 to reset, q when done"
     )
     while waitForWheel:
         key = keyboardInput.readkey()
         if (key == 'w'):
             self.__steering.increment_position(index, 1)
             self.__steering.update_servos()
         elif (ord(key) == 16):
             self.__steering.move_servo_by(index, 1)
         elif (key == 'z'):
             self.__steering.decrement_position(index, 1)
             self.__steering.update_servos()
         elif (ord(key) == 17):
             self.__steering.move_servo_by(index, -1)
         elif (key == 'q'):
             self.__steering.save_servo_status()
             waitForWheel = False
         time.sleep(0.01)
Esempio n. 7
0
class TerminalMenu():
    __keyboardInput = KeyboardInput("J2Controller")
    keyPress = None

    def __init__(self):
        pass

    def menu(self):
        self.__keyboardInput.clear()
        print("J2 Controller")
        print("Press <Esc> or Ctrl-C to exit")
        print("c: Wheel Calibration")
        print("d: Test drive")
        print("--------------------")
        print("q: Quit")
        print("")
        keyPress = self.__keyboardInput.readkey()
        return keyPress
class ServoCalibration:
    __kit = None
    __looper = True
    __keyboardInput = None
    __steering = None
    __suspension = None

    def __init__(self, servoKit):
        self.__kit = servoKit
        self.__keyboardInput = KeyboardInput("Steering Calibration")
        config_file = servoStatusFile = os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         "..")) + "/config/servo_status.json"
        self.__steering = Steering(self.__kit, config_file)
        self.__suspension = Suspension(self.__kit, config_file)

    def menu(self):
        self.__keyboardInput.clear()
        print("J2 Controller Steering Calibration Menu:")
        print()
        print("c: Setup Wheel ports (On Adafruit PWM Board)")
        print("n: Setup Suspension ports (On Adafruit PWM Board)")
        print("w: Front left Wheel")
        print("e: Front right Wheel")
        print("s: Rear left Wheel")
        print("d: Rear right Wheel")
        print("o: Front Suspension")
        print("k: Rear Suspension")
        print("r: Save current status")
        print("t: Reset all to *_start angle in sttering_status.json")
        print("a: Set Actuation Angle")
        print("--------------------")
        print("q: Back")
        print("")
        self.waitForInput()

    def waitForInput(self):
        while self.__looper:
            keyp = self.__keyboardInput.readkey()
            if (keyp == 'q'):
                print("Saving...")
                self.__steering.save_servo_status()
                print("Quit")
                self.__looper = False
            elif (keyp == 'c'):
                print("Enter Port on which front_left steering motor is: ")
                self.__steering.set_steering_port(Steering.FRONT_LEFT_POS,
                                                  input())
                print("Enter Port on which front_right steering motor is: ")
                self.__steering.set_steering_port(Steering.FRONT_RIGHT_POS,
                                                  input())
                print("Enter Port on which rear_left steering motor is: ")
                self.__steering.set_steering_port(Steering.REAR_LEFT_POS,
                                                  input())
                print("Enter Port on which rear_right steering motor is: ")
                self.__steering.set_steering_port(Steering.REAR_RIGHT_POS,
                                                  input())
                self.__steering.save_servo_status()
            elif (keyp == 'w'):
                self.calibrate_steering(1)
            elif (keyp == 'e'):
                self.calibrate_steering(2)
            elif (keyp == 's'):
                self.calibrate_steering(3)
            elif (keyp == 'd'):
                self.calibrate_steering(4)
            elif (keyp == 'r'):
                self.__steering.save_servo_status()
                print("Saved to file", end='\r', flush=True)
            elif (keyp == 't'):
                self.__steering.move_servo_to(
                    Steering.FRONT_LEFT_POS,
                    self.__steering.servo_status.front_left_start)
                self.__steering.move_servo_to(
                    Steering.FRONT_RIGHT_POS,
                    self.__steering.servo_status.front_right_start)
                self.__steering.move_servo_to(
                    Steering.REAR_LEFT_POS,
                    self.__steering.servo_status.rear_left_start)
                self.__steering.move_servo_to(
                    Steering.REAR_RIGHT_POS,
                    self.__steering.servo_status.rear_right_start)
                print("\r\n Servos updated")
                print("\r\n Servo status")
                self.__steering.print_servo_stats()
            elif (keyp == 'a'):
                print("Set actuation degrees [180-270]: ")
                self.__steering.set_actuation_degrees(int(input()))
            time.sleep(0.01)

    def calibrate_steering(self, index):
        waitForWheel = True
        keyboardInput = KeyboardInput("Calibrate Steering:")
        print(
            "Press Up/Down to test or w/z to adjust wheel delta, 0 to reset, q when done"
        )
        while waitForWheel:
            key = keyboardInput.readkey()
            if (key == 'w'):
                self.__steering.increment_position(index, 1)
                self.__steering.update_servos()
            elif (ord(key) == 16):
                self.__steering.move_servo_by(index, 1)
            elif (key == 'z'):
                self.__steering.decrement_position(index, 1)
                self.__steering.update_servos()
            elif (ord(key) == 17):
                self.__steering.move_servo_by(index, -1)
            elif (key == 'q'):
                self.__steering.save_servo_status()
                waitForWheel = False
            time.sleep(0.01)
Esempio n. 9
0
kit = ServoKit(channels=16)

TRIGGER_1 = 7
TRIGGER_2_3 = 8
TRIGGER_4_5 = 3

REST = 60
FIRE_EVEN = 120
FIRE_ODD = 0

TRIGGER_WAIT = 1 / 5
kit.servo[TRIGGER_1].angle = REST
kit.servo[TRIGGER_2_3].angle = REST
kit.servo[TRIGGER_4_5].angle = REST
keyboardInput = KeyboardInput("Trigger Prototype")
keyPress = ''

while keyPress != 'q':
    keyboardInput.clear()
    print("Meteor Shooter")
    print("Press <Esc> or Ctrl-C to exit")
    print("1: Fire 1")
    print("2: Fire 2")
    print("3: Fire 3")
    print("4: Fire 4")
    print("5: Fire 5")
    print("--------------------")
    print("u: Up 3")
    print("n: Down 3")
    print("j: Zero 3")
Esempio n. 10
0
def get_samples(game, keyboard_input):
    keyboard_input.add_to_window(game.env.unwrapped.viewer.window)
    keyboard_actions = keyboard_input.get_action_loop()
    while True:
        game.render()
        action = next(keyboard_actions)
        state, reward, done = game.do_action(action)
        yield action, state, reward
        if keyboard_input.finished:
            return
        if done:
            game.reset()


if __name__ == '__main__':
    from ll import LunarLander
    from keyboard_input import KeyboardInput
    print(game.reset())
    for action, state, reward in get_samples(LunarLander(), KeyboardInput()):
        print(state, reward)
Esempio n. 11
0
import time
import threading

from gameboard import Gameboard
from terminal_renderer import TerminalRenderer
from keyboard_input import KeyboardInput
from player_manager import PlayerManager
from game_manager import GameManager

gboard = Gameboard()
renderer = TerminalRenderer(gboard)
inputer = KeyboardInput()
player = PlayerManager(gboard)
game = GameManager(gboard)

inputer.start()
game.start()


def game_loop():
    for i in range(25):
        nput = inputer.get_input()
        player.update(nput)
        game.update()
        renderer.render()
        time.sleep(.05)  # TODO: Calculate exact sleep time


thread = threading.Thread(target=game_loop)
thread.start()
thread.join()
Esempio n. 12
0
 def __init__(self):
     self.__keyboardInput = KeyboardInput("Keyboard Input Services")
Esempio n. 13
0
def main(route_json_path, start_map, start_waypoint_index):
    # Start autonomy
    while not ARK.start_autonomy() and not rospy.is_shutdown():
        rospy.loginfo("Failed to start autonomy. Retrying in 3 seconds...")
        rospy.sleep(3)

    rospy.loginfo("ARK autonomy started")

    route = Route(route_json_path,
                  start_map=start_map,
                  start_waypoint_index=start_waypoint_index)

    # Start a ROS node called "PositionCommander"
    rospy.init_node("PositionCommander", anonymous=True)

    # Get a handle to the topic the ARK uses to accept goal
    pub = rospy.Publisher("/ark_bridge/send_goal", SendGoal, queue_size=1)

    # Get a handle to the topic the ARK uses to accept goal
    cancel_goal_publisher = rospy.Publisher("/ark_bridge/cancel_goal",
                                            Empty,
                                            queue_size=1)

    # Get a handle to the topic the ARK uses to return its status
    rospy.Subscriber("/ark_bridge/path_planner_status", GoalStatusArray,
                     path_planner_status_callback)

    keyboard_input = KeyboardInput()
    filter_adjuster = LaserFilterAdjuster()

    # Loop through the positions in our list one at a time
    while not route.is_complete() and not rospy.is_shutdown():
        next_pose = route.get_next_waypoint()
        filter_adjuster.set_radius(next_pose.get_upper_lidar_threshold())

        rospy.loginfo("Moving to " + next_pose.name)

        # Get a message for the ark and send it to the new goal topic
        pub.publish(ARK.create_goal_message(next_pose))

        # Wait for a second to make sure the ARK has time to accept the goal
        rospy.sleep(1)

        # Loop until the ARK says it is done running a goal
        while (tracking_goal) and not rospy.is_shutdown():
            if keyboard_input.check_hit():

                char = keyboard_input.get_char()

                # Skip the waypoint if n is pressed (ord == 110)
                if "n" == char:
                    rospy.loginfo("Skipping waypoint: {}".format(
                        next_pose.name))
                    cancel_goal_publisher.publish(Empty())

                # If the space bar is pressed, just wait until
                elif " " == char:
                    rospy.loginfo("Pausing")
                    pause(keyboard_input)

                # Set the threshold to use for the lidars using (0-9)
                elif char.isdigit():
                    filter_adjuster.set_radius(int(char))
                    rospy.sleep(
                        1.0)  # sleep to allow the point clouds to update

                elif "w" == char:
                    filter_adjuster.increase_radius()
                    rospy.sleep(
                        1.0)  # sleep to allow the point clouds to update

                elif "s" == char:
                    filter_adjuster.decrease_radius()
                    rospy.sleep(
                        1.0)  # sleep to allow the point clouds to update

            rospy.sleep(1)

    rospy.loginfo("Route completed")

    # stop autonomy once the goal is reached
    ARK.stop_autonomy()
    rospy.loginfo("Autonomoy stopped")
Esempio n. 14
0
class PlatformInterface():
    def enumerate(self):
        devices = [d for d in hid.enumerate(self.USB_VID, self.USB_PID)]
        return devices

    def launch(self, serial, sensitivities):
        if serial == None:
            serial = '0'
        self.h = hid.device()
        try:
            self.h.open(self.USB_VID, self.USB_PID, serial_number=serial)
        except:
            return 0
        if self.h.get_product_string() == 'RE:Flex Dance Pad':
            self.is_running = True
            self.setup(sensitivities)
            return 1
        else:
            self.is_running = False
            return 0

    def assign_led_files(self, led_files):
        self.led_files = led_files
        self.led_sources = [
            LedProcessor.from_file(self.led_files[0], 90),
            LedProcessor.from_file(self.led_files[1], 180),
            LedProcessor.from_file(self.led_files[2], 0),
            LedProcessor.from_file(self.led_files[3], 270)
        ]

    def setup(self, sensitivities):
        self.sample_counter = 0

        data = self.h.read(64)
        self.organize_data(data)
        self.sum_panel_data(self.panel_data)
        self.keyboard_input = KeyboardInput(self.panel_values, sensitivities)

        self.pressed_on_frame = list(range(4))
        self.last_frame = list(range(4))
        self.led_frame = 0
        self.led_panel = 0
        self.led_segment = 0
        self.led_frame_data = 0
        self.led_data = []
        self.lights_counter = 0

        thread = threading.Thread(target=self.loop, daemon=True)
        thread.start()

    def loop(self):
        while self.is_running:
            data = self.h.read(64)
            self.organize_data(data)
            self.sum_panel_data(self.panel_data)
            self.keyboard_input.poll_keys(self.panel_values)
            self.sample_counter += 1

            self.update_led_frame()
            self.h.write(bytes(self.led_data))

    def update_led_frame(self):
        self.led_frame_data = 0
        if self.led_segment < 3:
            self.led_segment += 1
        else:
            self.led_segment = 0
            if self.led_panel < 3:
                self.led_panel += 1
            else:
                self.led_panel = 0
                if self.led_frame < 15:
                    self.led_frame += 1
                else:
                    self.led_frame = 0
        if self.led_frame != self.last_frame[self.led_panel]:
            self.lights_counter += 1
            if self.keyboard_input.is_pressed[self.led_panel]:
                self.pressed_on_frame[self.led_panel] = 1
            else:
                self.pressed_on_frame[self.led_panel] = 0
        self.last_frame[self.led_panel] = self.led_frame

        self.led_frame_data |= self.led_panel << 6
        self.led_frame_data |= self.led_segment << 4
        self.led_frame_data |= self.led_frame

        source = self.led_sources[self.led_panel]
        segment_data = source.get_segment_data(self.led_segment)
        if self.pressed_on_frame[self.led_panel]:
            self.led_data = [0, self.led_frame_data] + segment_data
        else:
            self.led_data = [0, self.led_frame_data] + [0 for i in range(63)]

    def sensor_rate(self):
        polling_rate = self.sample_counter
        self.sample_counter = 0
        return polling_rate

    def lights_rate(self):
        polling_rate = self.lights_counter // 4
        self.lights_counter = 0
        return polling_rate

    def stop_loop(self):
        self.is_running = False

    def sum_panel_data(self, panel_data):
        self.panel_values = []
        for panel in range(0, 4):
            self.panel_values.append(0)
            for sensor in range(0, 4):
                self.panel_values[panel] += self.panel_data[sensor + 4 *
                                                            (panel)]

    def organize_data(self, data):
        self.panel_data = []
        for i in range(0, 32):
            self.panel_data.append(0)
        data_index = 0
        for data_point in data:
            if data_index % 2 == 0:
                self.panel_data[data_index // 2] = data_point
            if data_index % 2 == 1:
                self.panel_data[data_index // 2] |= 0x0FFF & (data_point << 8)
            data_index += 1

    USB_VID = 0x0483  # Vendor ID for I/O Microcontroller
    USB_PID = 0x5750  # Product ID for I/O Microcontroller
    panel_data = []
Esempio n. 15
0
def MidiInit():
    # pygame inits
    mixer.pre_init(44100, -16, 2, 256)
    mixer.init()
    midi.init()

    # wypisywanie listy urządzeń wejściowych
    input_devices = [-1]
    print('[0] Klawiatura')
    for x in range(midi.get_count()):
        dev_info = midi.get_device_info(x)
        if dev_info[2] == 1:
            input_devices.append(x)
            print('[{}]'.format(len(input_devices) - 1),
                  dev_info[1].decode('utf-8'))

    default_device = len(input_devices) - 1

    # wybieranie urządzenia wejściowego
    try:
        dev = int(
            input("Wybierz urządzenie wejściowe [" + str(default_device) +
                  "]: "))
    except ValueError:
        dev = default_device
    if dev >= len(input_devices) or dev < 0:
        print('Nieprawidłowy numer urządzenia! Wybrano domyślne.')
        dev = default_device

    # inicjalizacja urzadzenia
    inputs = []
    dev_nr = input_devices[dev]
    if dev_nr == -1:
        inputs.append(KeyboardInput())
        inputs[0].start()
    else:
        inputs.append(midi.Input(dev_nr))

    # wypisywanie dostępnych sampli
    dirlist = listdir('./samples')
    samples = []
    for dirname in dirlist:
        if path.isdir('./samples/' + dirname):
            samples.append(dirname)
            print('[{}]'.format(len(samples) - 1), dirname)

    default_samples = len(samples) - 1

    # wybieranie sampli
    try:
        samples_nr = int(
            input("Wybierz sample dźwiękowe [" + str(default_samples) + "]: "))
    except ValueError:
        samples_nr = default_samples
    if samples_nr >= len(samples) or samples_nr < 0:
        samples_nr = default_samples

    samples_path = './samples/' + samples[samples_nr]

    # inicjalizacja plików dźwiękowych
    sounds = [{}, {}]
    for sample_name in listdir(samples_path):
        name, ext = path.splitext(sample_name)
        if ext == '.wav':
            try:
                it = int(name)
            except:
                continue
            sounds[0][it] = mixer.Sound(samples_path + '/' + sample_name)
            sounds[1][it] = mixer.Sound(sounds[0][it])

    # określanie pozostałych ustawień
    try:
        sustain = int(input('Podaj wartość sustain [200]: '))
    except ValueError:
        sustain = 200

    try:
        channels = int(
            input('Podaj ilość kanałów dźwiękowych [' + str(32) + ']: '))
    except ValueError:
        channels = 32

    mixer.set_num_channels(channels)

    return inputs, sounds, sustain