Ejemplo n.º 1
0
 def __init__(self, world_state: WorldState):
     super().__init__(world_state)
     self.type_of_pathfinder = ConfigService(
     ).config_dict["STRATEGY"]["pathfinder"]
     self.last_time_pathfinding_for_robot = {}
     self.last_frame = time.time()
     self.game_state = world_state.game_state
Ejemplo n.º 2
0
    def setUp(self):
        super().setUp()
        test_utils.setup()

        authorizer = Authorizer([], ['admin_user'], EmptyGroupProvider())
        self.admin_user = User('admin_user', {})
        self.config_service = ConfigService(authorizer, test_utils.temp_folder)
Ejemplo n.º 3
0
 def __init__(self, team_color: TeamColor):
     super().__init__(team_color)
     # It is our team so we use our player!
     for player_id in range(PLAYER_PER_TEAM):
         self.players[player_id] = OurPlayer(self, player_id)
         if (ConfigService().config_dict["GAME"]["type"] == "sim" and 0 <= player_id <= 5)\
                 or (ConfigService().config_dict["GAME"]["type"] == "real" and 1 <= player_id <= 6):
             self.available_players[player_id] = self.players[player_id]
Ejemplo n.º 4
0
 def __init__(self, world_state: WorldState):
     super().__init__(world_state)
     self.type_of_pathfinder = ConfigService(
     ).config_dict["STRATEGY"]["pathfinder"]
     self.pathfinder = self.get_pathfinder(self.type_of_pathfinder)
     self.last_time_pathfinding_for_robot = {}
     self.last_frame = time.time()
     self.last_path = None
     self.last_raw_path = None
     self.last_pose_goal = None
Ejemplo n.º 5
0
    def setUp(self):
        super().setUp()
        test_utils.setup()

        authorizer = Authorizer([], ['admin_user'], EmptyGroupProvider())
        self.admin_user = User('admin_user', {})
        self.config_service = ConfigService(authorizer, test_utils.temp_folder)

        for suffix in 'XYZ':
            _create_script_config_file('conf' + suffix, name='Conf ' + suffix)
class ConfigServiceLoadConfigForAdminTest(unittest.TestCase):
    def setUp(self):
        super().setUp()
        test_utils.setup()

        authorizer = Authorizer([], ['admin_user'], [], EmptyGroupProvider())
        self.admin_user = User('admin_user', {})
        self.config_service = ConfigService(authorizer, test_utils.temp_folder)

    def tearDown(self):
        super().tearDown()
        test_utils.cleanup()

    def test_load_config(self):
        _create_script_config_file('ConfX',
                                   script_path='my_script.sh',
                                   description='some desc')
        config = self.config_service.load_config('ConfX', self.admin_user)

        self.assertEqual(
            config, {
                'filename': 'ConfX.json',
                'config': {
                    'name': 'ConfX',
                    'script_path': 'my_script.sh',
                    'description': 'some desc'
                }
            })

    def test_load_config_when_name_different_from_filename(self):
        _create_script_config_file('ConfX', name='my conf x')
        config = self.config_service.load_config('my conf x', self.admin_user)

        self.assertEqual(
            config, {
                'filename': 'ConfX.json',
                'config': {
                    'name': 'my conf x',
                    'script_path': 'echo 123'
                }
            })

    def test_load_config_when_non_admin(self):
        _create_script_config_file('ConfX')
        user = User('user1', {})
        self.assertRaises(AdminAccessRequiredException,
                          self.config_service.load_config, 'ConfX', user)

    def test_load_config_when_not_exists(self):
        _create_script_config_file('ConfX', name='my conf x')
        config = self.config_service.load_config('ConfX', self.admin_user)
        self.assertIsNone(config)
Ejemplo n.º 7
0
    def setUp(self) -> None:
        super().setUp()
        test_utils.setup()

        authorizer = Authorizer([], ['admin_user', 'admin_non_editor'], [],
                                ['admin_user'], EmptyGroupProvider())
        self.admin_user = User('admin_user', {})
        self.config_service = ConfigService(authorizer, test_utils.temp_folder)

        for pair in [('script.py', b'123'), ('another.py', b'xyz'),
                     ('binary 1.bin', bytes.fromhex('300000004000000a')),
                     ('my_python', bytes.fromhex('7F454C46'))]:
            path = os.path.join(test_utils.temp_folder, pair[0])
            file_utils.write_file(path, pair[1], byte_content=True)
Ejemplo n.º 8
0
    def __init__(self):
        cfg = ConfigService()
        self.default_dt = cfg.config_dict["GAME"]["ai_timestamp"]
        ncameras = int(cfg.config_dict["IMAGE"]["number_of_camera"])

        # Transition model
        self.F = np.array([
            [1, 0, self.default_dt, 0, 0, 0],  # Position x
            [0, 1, 0, self.default_dt, 0, 0],  # Position y
            [0, 0, 1, 0, 0, 0],  # Speed x
            [0, 0, 0, 1, 0, 0],  # Speed y
            [0, 0, 0, 0, 1, self.default_dt],  # Orientation
            [0, 0, 0, 0, 0, 1]
        ])  # Speed w
        # Observation model
        self.H = [[1, 0, 0, 0, 0, 0] for _ in range(ncameras)]  # Position x
        self.H += [[0, 1, 0, 0, 0, 0] for _ in range(ncameras)]  # Position y
        self.H += [[0, 0, 0, 0, 1, 0] for _ in range(ncameras)]  # Orientation
        self.H = np.array(self.H)
        # Process covariance
        values = np.array([10**0, 10**0, 10**0, 10**0, 10**2, 10**(-1)])
        self.Q = np.diag(values)
        # Observation covariance
        values = [10**0 for _ in range(ncameras)]
        values += [10**0 for _ in range(ncameras)]
        values += [10**(-3) for _ in range(ncameras)]
        self.R = np.diag(values)  # Pose * ncameras
        # Initial state covariance
        self.P = 10**3 * np.eye(6)

        self.x = np.array([9999, 9999, 0, 0, 0, 0])
Ejemplo n.º 9
0
 def __init__(self, p_world_state: WorldState):
     super().__init__(p_world_state)
     is_simulation = ConfigService().config_dict["GAME"]["type"] == "sim"
     self.robot_motion = [
         RobotMotion(p_world_state, player_id, is_sim=is_simulation)
         for player_id in range(12)
     ]
Ejemplo n.º 10
0
    def __init__(self):
        """
        Initialise le coach de l'IA.

        :param mode_debug_active: (bool) indique si les commandes de debug sont actives
        :param pathfinder:  (str) indique le nom du pathfinder par défault
        :param is_simulation:   (bool) indique si en simulation (true) ou en vrai vie (false)
        """
        cfg = ConfigService()
        self.mode_debug_active = cfg.config_dict["DEBUG"][
            "using_debug"] == "true"
        self.is_simulation = cfg.config_dict["GAME"]["type"] == "sim"

        # init the states
        self.world_state = WorldState()

        # init the executors
        self.debug_executor = DebugExecutor(self.world_state)
        self.play_executor = PlayExecutor(self.world_state)
        self.module_executor = ModuleExecutor(self.world_state)
        self.motion_executor = MotionExecutor(self.world_state)
        self.robot_command_executor = CommandExecutor(self.world_state)

        # logging
        DebugInterface().add_log(
            1, "\nCoach initialized with \nmode_debug_active = " +
            str(self.mode_debug_active) + "\nis_simulation = " +
            str(self.is_simulation))
Ejemplo n.º 11
0
    def start_server(self,
                     port,
                     address,
                     *,
                     xsrf_protection=XSRF_PROTECTION_TOKEN):
        file_download_feature = FileDownloadFeature(
            UserFileStorage(b'some_secret'), test_utils.temp_folder)
        config = ServerConfig()
        config.port = port
        config.address = address
        config.xsrf_protection = xsrf_protection
        config.max_request_size_mb = 1

        authorizer = Authorizer(ANY_USER, [], [], EmptyGroupProvider())
        execution_service = MagicMock()
        execution_service.start_script.return_value = 3

        server.init(config,
                    None,
                    authorizer,
                    execution_service,
                    MagicMock(),
                    MagicMock(),
                    ConfigService(authorizer, self.conf_folder),
                    MagicMock(),
                    FileUploadFeature(UserFileStorage(b'cookie_secret'),
                                      test_utils.temp_folder),
                    file_download_feature,
                    'cookie_secret',
                    None,
                    self.conf_folder,
                    start_server=False)
        self.start_loop()
Ejemplo n.º 12
0
 def __init__(self):
     cfg = ConfigService()
     host = cfg.config_dict["COMMUNICATION"]["ui_debug_address"]
     port = int(cfg.config_dict["COMMUNICATION"]["ui_cmd_receiver_port"])
     self.packet_list = deque(maxlen=DEBUG_RECEIVE_BUFFER_SIZE)
     handler = self.get_udp_handler(self.packet_list)
     self.server = ThreadedUDPServer(host, port, handler)
Ejemplo n.º 13
0
    def setUp(self):
        super().setUp()
        test_utils.setup()

        self.user = User('ConfigServiceTest',
                         {AUTH_USERNAME: '******'})
        self.config_service = ConfigService(AnyUserAuthorizer(),
                                            test_utils.temp_folder)
Ejemplo n.º 14
0
 def __init__(self):
     super().__init__()
     nb_cameras = int(
         ConfigService().config_dict["IMAGE"]["number_of_camera"])
     self.last_camera_frame = [empty_camera for _ in range(nb_cameras)]
     self.last_new_packet = None
     self.new_image_flag = False
     self.time = time.time()
Ejemplo n.º 15
0
class PathfinderModule(Executor):
    def __init__(self, world_state: WorldState):
        super().__init__(world_state)
        self.type_of_pathfinder = ConfigService(
        ).config_dict["STRATEGY"]["pathfinder"]
        self.last_time_pathfinding_for_robot = {}
        self.last_frame = time.time()
        self.game_state = world_state.game_state

    def exec(self):

        callback = partial(pathfind_ai_commands,
                           self.type_of_pathfinder.lower(), self.game_state)
        paths = [
            callback(player) for player in list(
                self.ws.game_state.my_team.available_players.values())
        ]

        for path in paths:
            if path is not None:
                self.draw_path(path)

    def draw_path(self, path, pid=0):

        points = []
        for idx, path_element in enumerate(path.points):
            x = path_element.x
            y = path_element.y
            points.append((x, y))
            if self.type_of_pathfinder.lower() == "path_part":
                if idx == 0:
                    pass
                else:
                    self.ws.debug_interface.add_line(points[idx - 1],
                                                     points[idx],
                                                     timeout=0.1)

        #    print(points)
        #self.ws.debug_interface.add_multi_line(points)
        self.ws.debug_interface.add_multiple_points(
            points[1:],
            COLOR_ID_MAP[pid],
            width=5,
            link="path - " + str(pid),
            timeout=DEFAULT_PATH_TIMEOUT)
Ejemplo n.º 16
0
    def __init__(self):
        """ Constructeur de la classe, établis les propriétés de bases et
        construit les objets qui sont toujours necéssaire à son fonctionnement
        correct.
        """
        # config
        self.cfg = ConfigService()

        # time
        self.last_frame_number = 0
        self.time_stamp = None  # time.time()
        self.last_camera_time = time.time()
        self.time_of_last_loop = time.time()
        self.ai_timestamp = float(self.cfg.config_dict["GAME"]["ai_timestamp"])

        # thread
        self.ia_running_thread = None
        self.thread_terminate = threading.Event()

        # Communication
        self.robot_command_sender = None
        self.vision = None
        self.referee_command_receiver = None
        self.uidebug_command_sender = None
        self.uidebug_command_receiver = None
        self.uidebug_vision_sender = None
        self.uidebug_robot_monitor = None
        # because this thing below is a callable! can be used without being set
        self.vision_redirection_routine = lambda *args: None
        self.vision_routine = self._sim_vision  # self._normal_vision # self._test_vision self._redirected_vision
        self._choose_vision_routines()

        # Debug
        self.incoming_debug = []
        self.debug = DebugInterface()
        self.outgoing_debug = self.debug.debug_state
        self._init_communication()

        # Game elements
        self.reference_transfer_object = None
        self.game = None
        self.ai_coach = None
        self.referee = None
        self.team_color_service = None

        self._create_game_world()

        # VISION
        self.image_transformer = ImageTransformerFactory.get_image_transformer(
        )

        # ia couplage
        self.ia_coach_mainloop = None
        self.ia_coach_initializer = None

        # for testing purposes
        self.frame_number = 0
Ejemplo n.º 17
0
 def __init__(self, team, id):
     self.id = id
     self.team = team
     self.pose = Pose()
     self.velocity = Pose()
     self.kf = EnemyKalmanFilter()
     self.update = self._update
     if ConfigService().config_dict["IMAGE"]["kalman"] == "true":
         self.update = self._kalman_update
Ejemplo n.º 18
0
 def __init__(self):
     super().__init__()
     nb_cameras = int(
         ConfigService().config_dict["IMAGE"]["number_of_camera"])
     self.last_new_packet = None
     self.new_image_flag = False
     self.time = time.time()
     self.cameras = [CameraPacket(cam_nb) for cam_nb in range(nb_cameras)]
     self.last_camera_frame = self._create_kalman_image()
Ejemplo n.º 19
0
 def get_image_transformer():
     type_of_image_transformer = ConfigService(
     ).config_dict["IMAGE"]["kalman"]
     if type_of_image_transformer == "true":
         return KalmanImageTransformer()
     elif type_of_image_transformer == "false":
         return SingularPacketImageTransformer()
     else:
         raise TypeError("Tentative de création d'un RobotCommandSender de "
                         "mauvais type.")
Ejemplo n.º 20
0
 def setUp(self):
     config_service = ConfigService().load_file("config/sim_standard.cfg")
     self.game_state = GameState()
     self.game = Game()
     self.game.set_referee(Referee())
     self.game.ball = Ball()
     game_world = ReferenceTransferObject(self.game)
     game_world.set_team_color_svc(TeamColorService(TeamColor.YELLOW_TEAM))
     self.game_state.set_reference(game_world)
     self.game_state.game.ball.set_position(Position(100, 0), 0)
Ejemplo n.º 21
0
    def __init__(self, ball: 'Ball'):
        self.ball = ball
        self.debug_interface = DebugInterface()
        cfg = ConfigService()

        if cfg.config_dict["GAME"]["our_side"] == "positive":
            self.our_side = FieldSide.POSITIVE
            self.constant = positive_side_constant
        else:
            self.our_side = FieldSide.NEGATIVE
            self.constant = negative_side_constant
Ejemplo n.º 22
0
 def __init__(self, id: int):
     assert 0 <= id <= int(ConfigService().config_dict["IMAGE"]["number_of_camera"]), "Creating CameraPacket " \
                                                                                      "class with wrong id!"
     self.camera_id = id
     self.timestamp = 0
     self.t_capture = 0
     self.frame_number = 0
     self.ball = None
     self.robots_blue = [None for _ in range(PLAYER_PER_TEAM)]
     self.robots_yellow = [None for _ in range(PLAYER_PER_TEAM)]
     self.packet = None
Ejemplo n.º 23
0
    def __init__(self, ball: Ball):
        self.ball = ball

        cfg = ConfigService()
        if cfg.config_dict["GAME"]["terrain_type"] == "normal":
            self.constant = normal
        elif cfg.config_dict["GAME"]["terrain_type"] == "small":
            self.constant = small
        else:
            print("ERREUR lors de la création de l'objet field\n Mauvais terrain_type en config - normal choisi\n")
            self.constant = normal
Ejemplo n.º 24
0
def main():
    tool_utils.validate_web_imports_exist(os.getcwd())

    logging_conf_file = os.path.join(CONFIG_FOLDER, 'logging.json')
    with open(logging_conf_file, 'rt') as f:
        log_config = json.load(f)
        file_utils.prepare_folder(os.path.join('logs'))

        logging.config.dictConfig(log_config)

    file_utils.prepare_folder(CONFIG_FOLDER)
    file_utils.prepare_folder(TEMP_FOLDER)

    migrations.migrate.migrate(TEMP_FOLDER, CONFIG_FOLDER)

    server_config = server_conf.from_json(SERVER_CONF_PATH)

    secret = get_secret(TEMP_FOLDER)

    config_service = ConfigService(CONFIG_FOLDER)

    alerts_service = AlertsService(server_config.get_alerts_config())
    alerts_service = alerts_service

    execution_logs_path = os.path.join('logs', 'processes')
    log_name_creator = LogNameCreator(
        server_config.logging_config.filename_pattern,
        server_config.logging_config.date_format)
    execution_logging_service = ExecutionLoggingService(
        execution_logs_path, log_name_creator)

    existing_ids = [
        entry.id for entry in execution_logging_service.get_history_entries()
    ]
    id_generator = IdGenerator(existing_ids)

    execution_service = ExecutionService(id_generator)

    execution_logging_initiator = ExecutionLoggingInitiator(
        execution_service, execution_logging_service)
    execution_logging_initiator.start()

    user_file_storage = UserFileStorage(secret)
    file_download_feature = FileDownloadFeature(user_file_storage, TEMP_FOLDER)
    file_download_feature.subscribe(execution_service)
    file_upload_feature = FileUploadFeature(user_file_storage, TEMP_FOLDER)

    alerter_feature = FailAlerterFeature(execution_service, alerts_service)
    alerter_feature.start()

    server.init(server_config, execution_service, execution_logging_service,
                config_service, alerts_service, file_upload_feature,
                file_download_feature, secret)
Ejemplo n.º 25
0
    def setUp(self):
        config_service = ConfigService().load_file("config/sim_standard.cfg")
        self.game = Game()
        self.referee = Referee
        self.game.set_referee(self.referee)
        self.tcsvc = TeamColorService(TeamColor.BLUE_TEAM)
        self.game.set_our_team_color(self.tcsvc.OUR_TEAM_COLOR)
        self.game_world_OK = ReferenceTransferObject(self.game)
        self.game_world_OK.set_team_color_svc(self.tcsvc)

        self.GameStateManager1 = GameState()
        self.GameStateManager2 = GameState()
        self.GameStateManager1.set_reference(self.game_world_OK)
Ejemplo n.º 26
0
    def setUp(self):
        super().setUp()

        self.socket = None

        application = tornado.web.Application(
            [(r'/scripts/([^/]*)', ScriptConfigSocket)],
            login_url='/login.html',
            cookie_secret='12345')
        application.auth = TornadoAuth(None)
        application.authorizer = Authorizer(ANY_USER, [], [],
                                            EmptyGroupProvider())
        application.identification = IpBasedIdentification(
            TrustedIpValidator(['127.0.0.1']), None)
        application.config_service = ConfigService(application.authorizer,
                                                   test_utils.temp_folder)

        server = httpserver.HTTPServer(application)
        socket, self.port = testing.bind_unused_port()
        server.add_socket(socket)

        test_utils.setup()

        for dir in ['x', 'y', 'z']:
            for file in range(1, 4):
                filename = dir + str(file) + '.txt'
                test_utils.create_file(
                    os.path.join('test1_files', dir, filename))

        test1_files_path = os.path.join(test_utils.temp_folder, 'test1_files')
        test_utils.write_script_config(
            {
                'name':
                'Test script 1',
                'script_path':
                'ls',
                'parameters': [
                    test_utils.create_script_param_config('text 1',
                                                          required=True),
                    test_utils.create_script_param_config(
                        'list 1', type='list', allowed_values=['A', 'B', 'C']),
                    test_utils.create_script_param_config(
                        'file 1',
                        type='server_file',
                        file_dir=test1_files_path),
                    test_utils.create_script_param_config(
                        'list 2',
                        type='list',
                        values_script='ls ' + test1_files_path + '/${file 1}')
                ]
            }, 'test_script_1')
Ejemplo n.º 27
0
    def __init__(self, p_world_state: WorldState):
        """
        initialise le PlayExecutor

        :param p_world_state: (WorldState) instance du worldstate
        """
        super().__init__(p_world_state)
        cfg = ConfigService()
        self.auto_play = SimpleAutoPlay(self.ws)
        self.ws.play_state.autonomous_flag = cfg.config_dict["GAME"][
            "autonomous_play"] == "true"
        self.last_time = 0
        self.last_available_players = {}
        self.goalie_id = -1
Ejemplo n.º 28
0
    def __init__(self, team_color: TeamColor):
        assert isinstance(team_color, TeamColor)
        self.players = {}
        self.available_players = {}
        for player_id in range(PLAYER_PER_TEAM):
            self.players[player_id] = Player(self, player_id)
            if player_id < 6:
                self.players[player_id].in_play = True
                self.available_players[player_id] = self.players[player_id]

        self.team_color = team_color
        self.score = 0
        self.update_player = self._update_player
        if ConfigService().config_dict["IMAGE"]["kalman"] == "true":
            self.update_player = self._kalman_update
Ejemplo n.º 29
0
    def get_pathfinder(self, type_of_pathfinder):
        assert isinstance(type_of_pathfinder, str)
        assert type_of_pathfinder.lower() in ["rrt", "astar", "path_part"]

        if type_of_pathfinder.lower() == "astar":
            return AsPathManager(
                self.ws,
                ConfigService().config_dict["GAME"]["type"] == "sim")
        elif type_of_pathfinder.lower() == "rrt":
            return PathfinderRRT(self.ws)
        elif type_of_pathfinder.lower() == "path_part":
            return PathPartitionner(self.ws)
        else:
            raise TypeError("Couldn't init a pathfinder with the type of ",
                            type_of_pathfinder, "!")
Ejemplo n.º 30
0
 def _create_teams(self):
     cfg = ConfigService()
     if cfg.config_dict["GAME"]["our_color"] == "blue":
         self.our_team_color == TeamColor.BLUE
         self.blue_team = OurTeam(TeamColor.BLUE)
         self.friends = self.blue_team
         self.yellow_team = Team(TeamColor.YELLOW)
         self.enemies = self.yellow_team
     elif cfg.config_dict["GAME"]["our_color"] == "yellow":
         self.our_team_color == TeamColor.YELLOW
         self.yellow_team = OurTeam(TeamColor.YELLOW)
         self.friends = self.yellow_team
         self.blue_team = Team(TeamColor.BLUE)
         self.enemies = self.blue_team
     else:
         raise ValueError("Config file contains wrong colors!")