예제 #1
0
    def __init__(self, config: dict, robot):
        self.side = config['side']
        if self.side in ['left', 'right']:
            dims = get_simulation_settings()['body_part_sizes']['touch_sensor_bar']
        else:
            dims = get_simulation_settings()['body_part_sizes']['touch_sensor_bar_rear']

        super(TouchSensor, self).__init__(config, robot, Dimensions(dims['width'], dims['height']), 'touch_sensor',
                                          driver_name='lego-ev3-touch')
예제 #2
0
    def __init__(self, update_world_cb, world_state: WorldState,
                 show_fullscreen: bool, show_maximized: bool,
                 use_second_screen_to_show_simulator: bool):

        instance_checker = InstanceChecker(self)
        instance_checker.check_for_unique_instance()

        self.update_callback = update_world_cb
        self.world_state = world_state

        self.current_screen_index = None
        self.set_screen_to_display_simulator_at_startup(
            use_second_screen_to_show_simulator)

        self.size = Dimensions(
            get_simulation_settings()['screen_settings']['screen_width'],
            get_simulation_settings()['screen_settings']['screen_height'])

        self.msg_counter = 0

        screen_title = get_simulation_settings(
        )['screen_settings']['screen_title']
        screen_info = screen_title + f'          version: {sim_version}      ev3dev2 api: {api_version}'

        scale = self.determine_scale(self.size.width, self.size.height)
        if DEBUG:
            print('starting simulation with scaling', scale)
            print('arcade version: ', _arcade.version.VERSION)

        super(Visualiser, self).__init__(
            self.size.width,
            self.size.height,
            screen_info,
            update_rate=1 / 30,
            fullscreen=show_fullscreen,
            resizable=True,
            screen=_arcade.get_screens()[self.current_screen_index])

        icon1 = pyglet.image.load(r'assets/images/body.png')
        self.set_icon(icon1)
        _arcade.set_background_color(
            get_simulation_settings()['screen_settings']['background_color'])

        self.sidebar = self._setup_sidebar()
        self.world_state.setup_pymunk_shapes(scale)
        self.world_state.setup_visuals(scale)

        if show_maximized:
            self.maximize()

        instance_checker.check_for_activation()
예제 #3
0
    def test_create_jobs_coast_center(self):
        coasting_sub = get_simulation_settings(
        )['motor_settings']['degree_coasting_subtraction']
        robot_sim = create_robot_sim()

        message_processor = MessageProcessor(0, robot_sim)
        message_processor.process_rotate_command(
            RotateCommand('ev3-ports:outB', 80, 200, 'coast'))

        for i in range(75):
            jobs = robot_sim.next_actuator_jobs()
            self.assertAlmostEqual(jobs[3][1], -2.667, 3)
            self.assertIsNone(jobs[0][1])
            self.assertIsNone(jobs[1][1])
            self.assertIsNone(jobs[2][1])

        ppf = 2.667 - coasting_sub
        for i in range(2):
            jobs = robot_sim.next_actuator_jobs()
            self.assertAlmostEqual(jobs[3][1], -ppf, 3)
            self.assertIsNone(jobs[0][1])
            self.assertIsNone(jobs[1][1])
            self.assertIsNone(jobs[2][1])
            ppf = max(ppf - coasting_sub, 0)

        jobs = robot_sim.next_actuator_jobs()
        self.assertEqual((jobs[0][1], jobs[1][1], jobs[2][1], jobs[3][1]),
                         (None, None, None, None))
예제 #4
0
    def test_process_sound_command(self):
        robot_sim = create_robot_sim()

        frames_per_second = get_simulation_settings(
        )['exec_settings']['frames_per_second']
        frames = int(5 * frames_per_second)

        message_processor = MessageProcessor(0, robot_sim)
        message_processor.process_sound_command(
            SoundCommand('A test is running at the moment!', 5, 'speak'))

        for i in range(frames - 1):
            soundJob = [
                i[1] for i in robot_sim.next_actuator_jobs()
                if i[0] == (0, 'speaker')
            ][0]
            self.assertIsNotNone(soundJob)

        message = [
            i[1] for i in robot_sim.next_actuator_jobs()
            if i[0] == (0, 'speaker')
        ][0]
        self.assertEqual(message, 'A test is \nrunning at\n the momen\nt!')

        jobs = robot_sim.next_actuator_jobs()
        self.assertEqual((jobs[0][1], jobs[1][1], jobs[2][1], jobs[3][1]),
                         (None, None, None, None))
예제 #5
0
    def test_create_jobs_coast_left(self):
        coasting_sub = get_simulation_settings(
        )['motor_settings']['distance_coasting_subtraction']
        robot_sim = create_robot_sim()

        message_processor = MessageProcessor(0, robot_sim)
        message_processor.process_rotate_command(
            RotateCommand('ev3-ports:outA', 80, 200, 'coast'))

        frames_check = (200 / 80) * 30  # (1000/100) * 30 # distance * fps
        distance_in_mm = 200 / 360 * wheel_circumference
        dpf = distance_in_mm / frames_check

        for i in range(75):
            jobs = robot_sim.next_actuator_jobs()
            self.assertAlmostEqual(jobs[1][1], dpf, 3)
            self.assertIsNone(jobs[0][1])
            self.assertIsNone(jobs[2][1])
            self.assertIsNone(jobs[3][1])

        ppf = dpf - coasting_sub
        for i in range(2):
            jobs = robot_sim.next_actuator_jobs()
            self.assertAlmostEqual(jobs[1][1], ppf, 3)
            self.assertIsNone(jobs[0][1])
            self.assertIsNone(jobs[3][1])
            self.assertIsNone(jobs[2][1])
            ppf = max(ppf - coasting_sub, 0)

        jobs = robot_sim.next_actuator_jobs()
        self.assertEqual((jobs[0][1], jobs[1][1], jobs[2][1], jobs[3][1]),
                         (None, None, None, None))
    def test_serialize_deserialize(self):
        server_thread = threading.Thread(target=self.run_fake_server)
        server_thread.start()

        msg_length = get_simulation_settings()['exec_settings']['message_size']
        from ev3dev2simulator.connection.ClientSocket import get_client_socket
        sock = get_client_socket()

        command = RotateCommand('test_port', 500.0, 100.0, 'hold')
        sock.send_command(command)

        ser = sock._serialize(command)
        unpadded = (
            b'{"type": "RotateCommand", "address": "test_port", "speed": 500.0, "distance": 100.0, '
            b'"stop_action": "hold"}')

        expected = unpadded.ljust(msg_length, b'#')
        self.assertEqual(ser, expected)

        ser = b'{"value": 15}'
        deser = sock._deserialize(ser)
        self.assertEqual(deser, 15)

        sock.client.send(str.encode('close_test_server'))
        sock.client.close()
        server_thread.join()
예제 #7
0
    def run(self):
        """
        Listen for incoming connections. When a connection is established spawn a ClientSocketHandler
        to manage it. Multiple connections can be established at the same time.
        """

        port = get_simulation_settings()['exec_settings']['socket_port']

        for robot_sim in self.word_simulator.robot_simulators:
            for brick in robot_sim.robot.get_bricks():
                sock = ClientSocketHandler(robot_sim, brick.brick, brick.name)
                sock.setDaemon(True)
                sock.start()
                self.brick_sockets[(robot_sim.robot.name, brick.name)] = sock

        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind(('localhost', port))
        server.listen(5)
        server.setblocking(False)
        server.settimeout(1)

        print('Listening for connections...')
        self.handle_sockets(server)
        print('Closing server')
예제 #8
0
 def __init__(self, comm):
     get_client_socket(
     )  # this is not used for Bluetooth, but to force a connection to the simulator (startup
     # sequence)
     self.port = int(
         get_simulation_settings()['exec_settings']['bluetooth_port'])
     self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
예제 #9
0
 def setup_visuals(self, scale):
     img_cfg = get_simulation_settings()['image_paths']
     src_list = [
         img_cfg[f'led_{color}'] for color in
         ['amber', 'black', 'red', 'green', 'orange', 'yellow']
     ]
     self.init_sprite_with_list(src_list, scale, 1)
예제 #10
0
 def __init__(self, config, robot):
     dims = get_simulation_settings()['body_part_sizes']['wheel']
     super().__init__(config,
                      robot,
                      Dimensions(dims['width'], dims['height']),
                      'motor',
                      driver_name='lego-ev3-l-motor')
예제 #11
0
    def test_process_sound_command(self):
        d = {
            'type': 'SoundCommand',
            'message': 'A tests is running at the moment!',
            'duration': 2,
            'soundType': 'speak'
        }

        frames_per_second = get_simulation_settings(
        )['exec_settings']['frames_per_second']
        frames = int(2 * frames_per_second)

        server = create_client_socket_handler()
        server.message_handler._process_sound_command(d)

        for i in range(frames):
            sound_job = [
                i[1] for i in server.robot_sim.next_actuator_jobs()
                if i[0] == (0, 'speaker')
            ][0]
            self.assertIsNotNone(sound_job)
        sound_job = [
            i[1] for i in server.robot_sim.next_actuator_jobs()
            if i[0] == (0, 'speaker')
        ][0]
        self.assertIsNone(sound_job)
예제 #12
0
    def __init__(self):
        load_config(None)
        port = get_simulation_settings()['exec_settings']['socket_port']

        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.connect(('localhost', port))

        time.sleep(1)
예제 #13
0
 def __init__(self, config, robot):
     dims = get_simulation_settings()['body_part_sizes']['arm']
     super(Arm, self).__init__(config,
                               robot,
                               Dimensions(dims['width'], dims['height']),
                               'arm',
                               driver_name='lego-ev3-m-motor')
     self.side_bar_arm = ArmLarge()
예제 #14
0
 def setup_visuals(self, scale):
     if self.side == 'left':
         img = 'touch_sensor_left'
     elif self.side == 'right':
         img = 'touch_sensor_right'
     else:
         img = 'touch_sensor_rear'
     vis_conf = get_simulation_settings()
     self.init_sprite(vis_conf['image_paths'][img], scale)
예제 #15
0
 def setup_visuals(self, x, y, width, height):
     self.center_x = x
     self.center_y = y
     self.rotate_x = x
     self.rotate_y = y + self.sweep_length
     vis_conf = get_simulation_settings()
     self.init_texture(vis_conf['image_paths']['arm_large'], width, height)
     self.side_bar_ground.create_shape(x, y - 70, width, 10)
     self.rotate(20)
예제 #16
0
 def __init__(self, config, robot):
     dims = get_simulation_settings(
     )['body_part_sizes']['ultrasonic_sensor_bottom']
     super(UltrasonicSensorBottom, self).__init__(config,
                                                  robot,
                                                  dims['width'],
                                                  dims['height'],
                                                  'ultrasonic_sensor',
                                                  driver_name='lego-ev3-us')
    def test_coast_frames_required(self):
        coasting_sub = get_simulation_settings()['motor_settings']['distance_coasting_subtraction']
        creator = MotorCommandProcessor()

        frames = creator._coast_frames_required(20, coasting_sub)
        self.assertEqual(frames, int(round((20 / coasting_sub))), 5)

        frames = creator._coast_frames_required(-20, coasting_sub)
        self.assertEqual(frames, int(round((20 / coasting_sub))), 5)
 def __init__(self, config, robot):
     dims = get_simulation_settings(
     )['body_part_sizes']['ultrasonic_sensor_top']
     super(UltrasonicSensor,
           self).__init__(config,
                          robot,
                          Dimensions(dims['width'], dims['height']),
                          'ultrasonic_sensor',
                          driver_name='lego-ev3-us')
     self.sensor_half_height = 22.5
예제 #19
0
    def on_draw(self):
        """
        Render the simulation.
        """

        _arcade.start_render()

        for obstacle_list in self.world_state.static_obstacles:
            for shape in obstacle_list.get_shapes():
                if shape.line_width == 1:
                    shape.draw()
                else:
                    print(shape)
        self.world_state.sprite_list.draw()

        for robot in self.world_state.get_robots():
            robot.get_sprites().draw()

            if DEBUG:
                for sprite in robot.get_sprites():
                    sprite.draw_hit_box(color=RED, line_thickness=5)
                    if robot.debug_shapes is not None:
                        for shape in robot.debug_shapes:
                            shape.draw()
                    robot.debug_shapes.clear()

            if robot.is_falling() and self.msg_counter <= 0:
                self.msg_counter = get_simulation_settings(
                )['exec_settings']['frames_per_second'] * 3

        for robot in self.world_state.get_robots():
            self.sidebar.add_robot_info(robot.name, robot.values, robot.sounds)

        self.sidebar.draw()
        if self.msg_counter > 0:
            self.msg_counter -= 1
            _arcade.draw_text(get_simulation_settings()['screen_settings']
                              ['falling_message'],
                              self._msg_x,
                              self.size.height - 100,
                              _arcade.color.RADICAL_RED,
                              14,
                              anchor_x="center")
 def __init__(self, robot_sim: RobotSimulator, brick_id: int, brick_name: str):
     threading.Thread.__init__(self)
     self.message_handler = MessageHandler(MessageProcessor(brick_id, robot_sim))
     self.client = None
     self.brick_id = brick_id
     self.is_running = True
     self.is_connected = False
     self.brick_name = brick_name
     self.robot_sim = robot_sim
     self.message_size = get_simulation_settings()['exec_settings']['message_size']
예제 #21
0
    def __init__(self):
        cfg = get_simulation_settings()

        self.distance_coasting_sub = float(
            cfg['motor_settings']['distance_coasting_subtraction'])
        self.degree_coasting_sub = float(
            cfg['motor_settings']['degree_coasting_subtraction'])

        self.frames_per_second = int(cfg['exec_settings']['frames_per_second'])
        self.wheel_circumference = float(
            cfg['wheel_settings']['circumference'])
예제 #22
0
    def __init__(self, brick: int, robot, center_x: int, center_y: int):
        config = {
            'brick': brick,
            'x_offset': center_x,
            'y_offset': center_y,
            'port': 'speaker'
        }

        dims = get_simulation_settings()['body_part_sizes']['speaker']
        super(Speaker, self).__init__(config, robot, dims['width'],
                                      dims['height'], 'speaker')
예제 #23
0
    def _setup_sidebar(self):
        sidebar_width = get_simulation_settings(
        )['screen_settings']['side_bar_width']
        sidebar = Sidebar(
            Point(self.size.width - sidebar_width, self.size.height - 70),
            Dimensions(sidebar_width, self.size.height))
        for robot in self.world_state.get_robots():
            sidebar.init_robot(robot.name, robot.sensors, robot.bricks,
                               robot.side_bar_sprites)

        return sidebar
예제 #24
0
    def __init__(self):
        load_config(None)
        port = int(get_simulation_settings()['exec_settings']['socket_port'])

        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.client.settimeout(0.1)

        self.client.connect(('localhost', port))
        self.lock = threading.Lock()

        time.sleep(1)
예제 #25
0
    def __init__(self, world_state: WorldState):
        self.world_state = world_state
        self.robot_simulators = []
        self.should_reset = False
        for robot in world_state.robots:
            robot_sim = RobotSimulator(robot)
            self.robot_simulators.append(robot_sim)

        self.world_state.space.add_default_collision_handler()

        self.space_step_size = float(
            get_simulation_settings()['exec_settings']['frames_per_second'])
예제 #26
0
 def setup_visuals(self, x, y, width, height):
     """
     Setup the visuals of the robot arm and add a bottom border to it.
     """
     self.center_x = x
     self.center_y = y
     self.rotate_x = x
     self.rotate_y = y + self.sweep_length
     vis_conf = get_simulation_settings()
     self.init_texture(vis_conf['image_paths']['arm_large'], width, height)
     self.side_bar_ground.create_shape(x, y - 70, width, 10)
     self.angle = 0
     self.rotate(20)
예제 #27
0
    def _serialize(message: Any) -> bytes:
        """
        Serialize the given message so it can be send via a stream channel.
        :param message: to be serialized.
        :return: bytes representing the message.
        """

        obj_dict = message.serialize()

        jsn = json.dumps(obj_dict)
        jsn = jsn.ljust(
            get_simulation_settings()['exec_settings']['message_size'], '#')

        return str.encode(jsn)
예제 #28
0
    def __init__(self, brick: int, robot, side, brick_x_offset,
                 brick_y_offset):
        offset_x = -20 if side == 'left' else 20
        config = {
            'brick': brick,
            'name': f'led_{side}',
            'x_offset': brick_x_offset,
            'y_offset': brick_y_offset,
        }

        dims = get_simulation_settings()['body_part_sizes']['led']
        super().__init__(config, robot, dims['width'], dims['height'], 'led',
                         offset_x, -32.5)
        self.old_texture_index = 1
    def __init__(self, brick_id: int, robot_sim: robot_simulator):
        cfg = get_simulation_settings()

        self.brick_id = brick_id

        self.distance_coasting_sub = float(
            cfg['motor_settings']['distance_coasting_subtraction'])
        self.degree_coasting_sub = float(
            cfg['motor_settings']['degree_coasting_subtraction'])
        self.frames_per_second = int(cfg['exec_settings']['frames_per_second'])

        self.robot_sim = robot_sim
        self.command_processor = MotorCommandProcessor()
        self.led_cache = {k: None for k in LEDS.values()}
예제 #30
0
    def __init__(self, address: str):
        self.address = address
        if address is None:
            raise RuntimeError('created connector with None as address')

        self.client_socket = get_client_socket()

        self.wait_time = 0.008
        self.frame_time = 1 / int(
            get_simulation_settings()['exec_settings']['frames_per_second'])
        self.last_request_time = 0

        self.value_cache = None
        self.delta_sum = 0