diff --git a/adf_core_python/core/agent/agent.py b/adf_core_python/core/agent/agent.py index bdf45c6..6c8275b 100644 --- a/adf_core_python/core/agent/agent.py +++ b/adf_core_python/core/agent/agent.py @@ -2,7 +2,7 @@ import time as _time from abc import abstractmethod from threading import Event -from typing import Any, Callable, NoReturn +from typing import Any, Callable, NoReturn, Optional from bitarray import bitarray from rcrs_core.commands.AKClear import AKClear @@ -24,10 +24,10 @@ from rcrs_core.connection.URN import Entity as EntityURN from rcrs_core.messages.AKAcknowledge import AKAcknowledge from rcrs_core.messages.AKConnect import AKConnect -from rcrs_core.messages.controlMessageFactory import ControlMessageFactory from rcrs_core.messages.KAConnectError import KAConnectError from rcrs_core.messages.KAConnectOK import KAConnectOK from rcrs_core.messages.KASense import KASense +from rcrs_core.messages.controlMessageFactory import ControlMessageFactory from rcrs_core.worldmodel.changeSet import ChangeSet from rcrs_core.worldmodel.entityID import EntityID from rcrs_core.worldmodel.worldmodel import WorldModel @@ -79,6 +79,7 @@ CommunicationModule, ) from adf_core_python.core.config.config import Config +from adf_core_python.core.gateway.gateway_agent import GatewayAgent from adf_core_python.core.launcher.config_key import ConfigKey from adf_core_python.core.logger.logger import get_agent_logger, get_logger @@ -94,6 +95,7 @@ def __init__( module_config: ModuleConfig, develop_data: DevelopData, finish_post_connect_event: Event, + gateway_agent: Optional[GatewayAgent], ) -> None: self.name = name self.connect_request_id = None @@ -124,6 +126,8 @@ def __init__( self._message_manager: MessageManager = MessageManager() self._communication_module: CommunicationModule = StandardCommunicationModule() + self._gateway_agent: Optional[GatewayAgent] = gateway_agent + def get_entity_id(self) -> EntityID: return self.agent_id @@ -146,14 +150,20 @@ def post_connect(self) -> None: self._ignore_time: int = int( self.config.get_value("kernel.agents.ignoreuntil", 3) ) + self._scenario_info: ScenarioInfo = ScenarioInfo(self.config, self._mode) self._world_info: WorldInfo = WorldInfo(self.world_model) self._agent_info = AgentInfo(self, self.world_model) + + if isinstance(self._gateway_agent, GatewayAgent): + self._gateway_agent.set_initialize_data( + self._agent_info, self._world_info, self._scenario_info + ) + self.logger = get_agent_logger( f"{self.__class__.__module__}.{self.__class__.__qualname__}", self._agent_info, ) - self.logger.debug(f"agent_config: {self.config}") def update_step_info( @@ -193,6 +203,12 @@ def update_step_info( self._agent_info.set_change_set(change_set) self._world_info.set_change_set(change_set) + if ( + isinstance(self._gateway_agent, GatewayAgent) + and self._gateway_agent.is_initialized() + ): + self._gateway_agent.update() + self._message_manager.refresh() self._communication_module.receive(self, self._message_manager) @@ -288,9 +304,11 @@ def handler_sense(self, msg: Any) -> None: if herad_command.urn == CommandURN.AK_SPEAK: heard_commands.append( AKSpeak( - herad_command.components[ - ComponentControlMessageID.AgentID - ].entityID, + EntityID( + herad_command.components[ + ComponentControlMessageID.AgentID + ].entityID + ), herad_command.components[ ComponentControlMessageID.Time ].intValue, diff --git a/adf_core_python/core/agent/communication/message_manager.py b/adf_core_python/core/agent/communication/message_manager.py index f318b1a..fc16479 100644 --- a/adf_core_python/core/agent/communication/message_manager.py +++ b/adf_core_python/core/agent/communication/message_manager.py @@ -234,7 +234,7 @@ def register_message_class( """ if index >= self.MAX_MESSAGE_CLASS_COUNT: raise ValueError( - f"Possible index values are 0 to {self.MAX_MESSAGE_CLASS_COUNT-1}" + f"Possible index values are 0 to {self.MAX_MESSAGE_CLASS_COUNT - 1}" ) self.__message_classes[index] = message_class diff --git a/adf_core_python/core/agent/info/scenario_info.py b/adf_core_python/core/agent/info/scenario_info.py index 85bf7da..29f4244 100644 --- a/adf_core_python/core/agent/info/scenario_info.py +++ b/adf_core_python/core/agent/info/scenario_info.py @@ -1,4 +1,4 @@ -from enum import Enum +from enum import IntEnum from typing import TypeVar from adf_core_python.core.config.config import Config @@ -6,7 +6,7 @@ T = TypeVar("T") -class Mode(Enum): +class Mode(IntEnum): NON_PRECOMPUTE = 0 PRECOMPUTED = 1 PRECOMPUTATION = 2 diff --git a/adf_core_python/core/agent/module/module_manager.py b/adf_core_python/core/agent/module/module_manager.py index bb6855e..18346aa 100644 --- a/adf_core_python/core/agent/module/module_manager.py +++ b/adf_core_python/core/agent/module/module_manager.py @@ -1,7 +1,7 @@ from __future__ import annotations import importlib -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Optional from adf_core_python.core.component.action.extend_action import ExtendAction from adf_core_python.core.component.communication.channel_subscriber import ( @@ -11,7 +11,13 @@ MessageCoordinator, ) from adf_core_python.core.component.module.abstract_module import AbstractModule -from adf_core_python.core.logger.logger import get_logger +from adf_core_python.core.gateway.component.module.gateway_abstract_module import ( + GatewayAbstractModule, +) +from adf_core_python.core.gateway.gateway_agent import GatewayAgent +from adf_core_python.core.gateway.gateway_module import GatewayModule +from adf_core_python.core.gateway.module_dict import ModuleDict +from adf_core_python.core.logger.logger import get_agent_logger if TYPE_CHECKING: from adf_core_python.core.agent.config.module_config import ModuleConfig @@ -29,12 +35,14 @@ def __init__( scenario_info: ScenarioInfo, module_config: ModuleConfig, develop_data: DevelopData, + gateway_agent: Optional[GatewayAgent] = None, ) -> None: self._agent_info = agent_info self._world_info = world_info self._scenario_info = scenario_info self._module_config = module_config self._develop_data = develop_data + self._gateway_agent = gateway_agent self._modules: dict[str, AbstractModule] = {} self._actions: dict[str, ExtendAction] = {} @@ -43,38 +51,79 @@ def __init__( self._channel_subscribers: dict[str, Any] = {} self._message_coordinators: dict[str, Any] = {} - def get_module(self, module_name: str, default_module_name: str) -> AbstractModule: - class_name = self._module_config.get_value(module_name) - if class_name is None: - get_logger("ModuleManager").warning( - f"Module key {module_name} not found in config, using default module {default_module_name}" - ) - class_name = default_module_name + self._module_dict: ModuleDict = ModuleDict() - module_class: type = self._load_module(class_name) + self._logger = get_agent_logger( + f"{self.__class__.__module__}.{self.__class__.__qualname__}", + self._agent_info, + ) + def get_module( + self, module_name: str, default_module_class_name: str + ) -> AbstractModule: instance = self._modules.get(module_name) if instance is not None: return instance - if issubclass(module_class, AbstractModule): - instance = module_class( - self._agent_info, - self._world_info, - self._scenario_info, - self, - self._develop_data, - ) - self._modules[module_name] = instance - return instance + class_name = self._module_config.get_value(module_name) + if class_name is not None: + try: + module_class: type = self._load_module(class_name) + if issubclass(module_class, AbstractModule): + instance = module_class( + self._agent_info, + self._world_info, + self._scenario_info, + self, + self._develop_data, + ) + self._modules[module_name] = instance + return instance + except ModuleNotFoundError: + self._logger.warning( + f"Module {module_name} not found in python. " + f"If gateway flag is active, using module {module_name} in java" + ) + + if isinstance(self._gateway_agent, GatewayAgent): + gateway_module = GatewayModule(self._gateway_agent) + java_class_name = gateway_module.initialize(module_name, "") + class_name = self._module_dict[java_class_name] + if class_name is not None: + module_class = self._load_module(class_name) + if issubclass(module_class, GatewayAbstractModule): + instance = module_class( + self._agent_info, + self._world_info, + self._scenario_info, + self, + self._develop_data, + gateway_module, + ) + self._modules[module_name] = instance + return instance + + class_name = default_module_class_name + if class_name is not None: + module_class = self._load_module(class_name) + if issubclass(module_class, AbstractModule): + instance = module_class( + self._agent_info, + self._world_info, + self._scenario_info, + self, + self._develop_data, + ) + self._modules[module_name] = instance + return instance raise RuntimeError(f"Module {class_name} is not a subclass of AbstractModule") def get_extend_action( - self, action_name: str, default_action_name: str + self, action_name: str, default_action_class_name: str ) -> ExtendAction: class_name = self._module_config.get_value_or_default( - action_name, default_action_name + action_name, default_action_class_name ) action_class: type = self._load_module(class_name) diff --git a/adf_core_python/core/agent/office/office.py b/adf_core_python/core/agent/office/office.py index 98911f8..97fcf6e 100644 --- a/adf_core_python/core/agent/office/office.py +++ b/adf_core_python/core/agent/office/office.py @@ -1,4 +1,5 @@ from threading import Event +from typing import Optional from adf_core_python.core.agent.agent import Agent from adf_core_python.core.agent.config.module_config import ModuleConfig @@ -7,6 +8,7 @@ from adf_core_python.core.agent.module.module_manager import ModuleManager from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData from adf_core_python.core.component.tactics.tactics_center import TacticsCenter +from adf_core_python.core.gateway.gateway_agent import GatewayAgent from adf_core_python.core.logger.logger import get_agent_logger @@ -21,6 +23,7 @@ def __init__( module_config: ModuleConfig, develop_data: DevelopData, finish_post_connect_event: Event, + gateway_agent: Optional[GatewayAgent], ) -> None: super().__init__( is_precompute, @@ -31,6 +34,7 @@ def __init__( module_config, develop_data, finish_post_connect_event, + gateway_agent, ) self._tactics_center = tactics_center self._team_name = team_name diff --git a/adf_core_python/core/agent/office/office_ambulance.py b/adf_core_python/core/agent/office/office_ambulance.py index 6bec530..f746fd5 100644 --- a/adf_core_python/core/agent/office/office_ambulance.py +++ b/adf_core_python/core/agent/office/office_ambulance.py @@ -1,4 +1,5 @@ from threading import Event +from typing import Optional from rcrs_core.connection.URN import Entity as EntityURN @@ -6,6 +7,7 @@ from adf_core_python.core.agent.develop.develop_data import DevelopData from adf_core_python.core.agent.office.office import Office from adf_core_python.core.component.tactics.tactics_center import TacticsCenter +from adf_core_python.core.gateway.gateway_agent import GatewayAgent class OfficeAmbulance(Office): @@ -19,6 +21,7 @@ def __init__( module_config: ModuleConfig, develop_data: DevelopData, finish_post_connect_event: Event, + gateway_agent: Optional[GatewayAgent], ) -> None: super().__init__( tactics_center, @@ -29,6 +32,7 @@ def __init__( module_config, develop_data, finish_post_connect_event, + gateway_agent, ) def precompute(self) -> None: diff --git a/adf_core_python/core/agent/office/office_fire.py b/adf_core_python/core/agent/office/office_fire.py index 16b93cd..6128edd 100644 --- a/adf_core_python/core/agent/office/office_fire.py +++ b/adf_core_python/core/agent/office/office_fire.py @@ -1,4 +1,5 @@ from threading import Event +from typing import Optional from rcrs_core.connection.URN import Entity as EntityURN @@ -6,6 +7,7 @@ from adf_core_python.core.agent.develop.develop_data import DevelopData from adf_core_python.core.agent.office.office import Office from adf_core_python.core.component.tactics.tactics_center import TacticsCenter +from adf_core_python.core.gateway.gateway_agent import GatewayAgent class OfficeFire(Office): @@ -19,6 +21,7 @@ def __init__( module_config: ModuleConfig, develop_data: DevelopData, finish_post_connect_event: Event, + gateway_agent: Optional[GatewayAgent], ) -> None: super().__init__( tactics_center, @@ -29,6 +32,7 @@ def __init__( module_config, develop_data, finish_post_connect_event, + gateway_agent, ) def get_requested_entities(self) -> list[EntityURN]: diff --git a/adf_core_python/core/agent/office/office_police.py b/adf_core_python/core/agent/office/office_police.py index 4b2ca8b..9717ac2 100644 --- a/adf_core_python/core/agent/office/office_police.py +++ b/adf_core_python/core/agent/office/office_police.py @@ -1,4 +1,5 @@ from threading import Event +from typing import Optional from rcrs_core.connection.URN import Entity as EntityURN @@ -6,6 +7,7 @@ from adf_core_python.core.agent.develop.develop_data import DevelopData from adf_core_python.core.agent.office.office import Office from adf_core_python.core.component.tactics.tactics_center import TacticsCenter +from adf_core_python.core.gateway.gateway_agent import GatewayAgent class OfficePolice(Office): @@ -19,6 +21,7 @@ def __init__( module_config: ModuleConfig, develop_data: DevelopData, finish_post_connect_event: Event, + gateway_agent: Optional[GatewayAgent], ) -> None: super().__init__( tactics_center, @@ -29,6 +32,7 @@ def __init__( module_config, develop_data, finish_post_connect_event, + gateway_agent, ) def get_requested_entities(self) -> list[EntityURN]: diff --git a/adf_core_python/core/agent/platoon/platoon.py b/adf_core_python/core/agent/platoon/platoon.py index 8a66099..2f2781c 100644 --- a/adf_core_python/core/agent/platoon/platoon.py +++ b/adf_core_python/core/agent/platoon/platoon.py @@ -1,4 +1,5 @@ from threading import Event +from typing import Optional from adf_core_python.core.agent.action.action import Action from adf_core_python.core.agent.agent import Agent @@ -8,6 +9,7 @@ from adf_core_python.core.agent.module.module_manager import ModuleManager from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData from adf_core_python.core.component.tactics.tactics_agent import TacticsAgent +from adf_core_python.core.gateway.gateway_agent import GatewayAgent from adf_core_python.core.logger.logger import get_agent_logger @@ -22,6 +24,7 @@ def __init__( module_config: ModuleConfig, develop_data: DevelopData, finish_post_connect_event: Event, + gateway_agent: Optional[GatewayAgent], ) -> None: super().__init__( is_precompute, @@ -32,6 +35,7 @@ def __init__( module_config, develop_data, finish_post_connect_event, + gateway_agent, ) self._tactics_agent = tactics_agent self._team_name = team_name @@ -40,6 +44,7 @@ def __init__( self._data_storage_name = data_storage_name self._module_config = module_config self._develop_data = develop_data + self._gateway_agent = gateway_agent def post_connect(self) -> None: super().post_connect() @@ -56,6 +61,7 @@ def post_connect(self) -> None: self._scenario_info, self._module_config, self._develop_data, + self._gateway_agent, ) self._message_manager.set_channel_subscriber( diff --git a/adf_core_python/core/agent/platoon/platoon_ambulance.py b/adf_core_python/core/agent/platoon/platoon_ambulance.py index 169d208..0daad4a 100644 --- a/adf_core_python/core/agent/platoon/platoon_ambulance.py +++ b/adf_core_python/core/agent/platoon/platoon_ambulance.py @@ -1,4 +1,5 @@ from threading import Event +from typing import Optional from rcrs_core.connection.URN import Entity as EntityURN @@ -6,6 +7,7 @@ from adf_core_python.core.agent.develop.develop_data import DevelopData from adf_core_python.core.agent.platoon.platoon import Platoon from adf_core_python.core.component.tactics.tactics_agent import TacticsAgent +from adf_core_python.core.gateway.gateway_agent import GatewayAgent class PlatoonAmbulance(Platoon): @@ -19,6 +21,7 @@ def __init__( module_config: ModuleConfig, develop_data: DevelopData, finish_post_connect_event: Event, + gateway_agent: Optional[GatewayAgent], ): super().__init__( tactics_agent, @@ -29,6 +32,7 @@ def __init__( module_config, develop_data, finish_post_connect_event, + gateway_agent, ) def get_requested_entities(self) -> list[EntityURN]: diff --git a/adf_core_python/core/agent/platoon/platoon_fire.py b/adf_core_python/core/agent/platoon/platoon_fire.py index 3071eef..8debf99 100644 --- a/adf_core_python/core/agent/platoon/platoon_fire.py +++ b/adf_core_python/core/agent/platoon/platoon_fire.py @@ -1,4 +1,5 @@ from threading import Event +from typing import Optional from rcrs_core.connection.URN import Entity as EntityURN @@ -6,6 +7,7 @@ from adf_core_python.core.agent.develop.develop_data import DevelopData from adf_core_python.core.agent.platoon.platoon import Platoon from adf_core_python.core.component.tactics.tactics_agent import TacticsAgent +from adf_core_python.core.gateway.gateway_agent import GatewayAgent class PlatoonFire(Platoon): @@ -19,6 +21,7 @@ def __init__( module_config: ModuleConfig, develop_data: DevelopData, finish_post_connect_event: Event, + gateway_agent: Optional[GatewayAgent], ): super().__init__( tactics_agent, @@ -29,6 +32,7 @@ def __init__( module_config, develop_data, finish_post_connect_event, + gateway_agent, ) def get_requested_entities(self) -> list[EntityURN]: diff --git a/adf_core_python/core/agent/platoon/platoon_police.py b/adf_core_python/core/agent/platoon/platoon_police.py index 6df9440..441602f 100644 --- a/adf_core_python/core/agent/platoon/platoon_police.py +++ b/adf_core_python/core/agent/platoon/platoon_police.py @@ -1,4 +1,5 @@ from threading import Event +from typing import Optional from rcrs_core.connection.URN import Entity as EntityURN @@ -6,6 +7,7 @@ from adf_core_python.core.agent.develop.develop_data import DevelopData from adf_core_python.core.agent.platoon.platoon import Platoon from adf_core_python.core.component.tactics.tactics_agent import TacticsAgent +from adf_core_python.core.gateway.gateway_agent import GatewayAgent class PlatoonPolice(Platoon): @@ -19,6 +21,7 @@ def __init__( module_config: ModuleConfig, develop_data: DevelopData, finish_post_connect_event: Event, + gateway_agent: Optional[GatewayAgent], ): super().__init__( tactics_agent, @@ -29,6 +32,7 @@ def __init__( module_config, develop_data, finish_post_connect_event, + gateway_agent, ) def get_requested_entities(self) -> list[EntityURN]: diff --git a/adf_core_python/core/component/module/complex/ambulance_target_allocator.py b/adf_core_python/core/component/module/complex/ambulance_target_allocator.py index 2c36e74..7359e68 100644 --- a/adf_core_python/core/component/module/complex/ambulance_target_allocator.py +++ b/adf_core_python/core/component/module/complex/ambulance_target_allocator.py @@ -1,18 +1,23 @@ -from abc import abstractmethod +from __future__ import annotations -from rcrs_core.worldmodel.entityID import EntityID +from abc import abstractmethod +from typing import TYPE_CHECKING -from adf_core_python.core.agent.communication.message_manager import MessageManager -from adf_core_python.core.agent.develop.develop_data import DevelopData -from adf_core_python.core.agent.info.agent_info import AgentInfo -from adf_core_python.core.agent.info.scenario_info import ScenarioInfo -from adf_core_python.core.agent.info.world_info import WorldInfo -from adf_core_python.core.agent.module.module_manager import ModuleManager -from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData from adf_core_python.core.component.module.complex.target_allocator import ( TargetAllocator, ) +if TYPE_CHECKING: + from rcrs_core.worldmodel.entityID import EntityID + + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + class AmbulanceTargetAllocator(TargetAllocator): def __init__( @@ -32,17 +37,21 @@ def get_result(self) -> dict[EntityID, EntityID]: pass @abstractmethod - def calculate(self) -> TargetAllocator: + def calculate(self) -> AmbulanceTargetAllocator: pass - def resume(self, precompute_data: PrecomputeData) -> TargetAllocator: + def precompute(self, precompute_data: PrecomputeData) -> AmbulanceTargetAllocator: + super().precompute(precompute_data) + return self + + def resume(self, precompute_data: PrecomputeData) -> AmbulanceTargetAllocator: super().resume(precompute_data) return self - def prepare(self) -> TargetAllocator: + def prepare(self) -> AmbulanceTargetAllocator: super().prepare() return self - def update_info(self, message_manager: MessageManager) -> TargetAllocator: + def update_info(self, message_manager: MessageManager) -> AmbulanceTargetAllocator: super().update_info(message_manager) return self diff --git a/adf_core_python/core/component/module/complex/fire_target_allocator.py b/adf_core_python/core/component/module/complex/fire_target_allocator.py index a537ef6..9e35373 100644 --- a/adf_core_python/core/component/module/complex/fire_target_allocator.py +++ b/adf_core_python/core/component/module/complex/fire_target_allocator.py @@ -1,18 +1,23 @@ -from abc import abstractmethod +from __future__ import annotations -from rcrs_core.worldmodel.entityID import EntityID +from abc import abstractmethod +from typing import TYPE_CHECKING -from adf_core_python.core.agent.communication.message_manager import MessageManager -from adf_core_python.core.agent.develop.develop_data import DevelopData -from adf_core_python.core.agent.info.agent_info import AgentInfo -from adf_core_python.core.agent.info.scenario_info import ScenarioInfo -from adf_core_python.core.agent.info.world_info import WorldInfo -from adf_core_python.core.agent.module.module_manager import ModuleManager -from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData from adf_core_python.core.component.module.complex.target_allocator import ( TargetAllocator, ) +if TYPE_CHECKING: + from rcrs_core.worldmodel.entityID import EntityID + + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + class FireTargetAllocator(TargetAllocator): def __init__( @@ -32,17 +37,21 @@ def get_result(self) -> dict[EntityID, EntityID]: pass @abstractmethod - def calculate(self) -> TargetAllocator: + def calculate(self) -> FireTargetAllocator: pass - def resume(self, precompute_data: PrecomputeData) -> TargetAllocator: + def precompute(self, precompute_data: PrecomputeData) -> FireTargetAllocator: + super().precompute(precompute_data) + return self + + def resume(self, precompute_data: PrecomputeData) -> FireTargetAllocator: super().resume(precompute_data) return self - def prepare(self) -> TargetAllocator: + def prepare(self) -> FireTargetAllocator: super().prepare() return self - def update_info(self, message_manager: MessageManager) -> TargetAllocator: + def update_info(self, message_manager: MessageManager) -> FireTargetAllocator: super().update_info(message_manager) return self diff --git a/adf_core_python/core/component/module/complex/police_target_allocator.py b/adf_core_python/core/component/module/complex/police_target_allocator.py index 8403d8f..bf31d15 100644 --- a/adf_core_python/core/component/module/complex/police_target_allocator.py +++ b/adf_core_python/core/component/module/complex/police_target_allocator.py @@ -1,18 +1,23 @@ -from abc import abstractmethod +from __future__ import annotations -from rcrs_core.worldmodel.entityID import EntityID +from abc import abstractmethod +from typing import TYPE_CHECKING -from adf_core_python.core.agent.communication.message_manager import MessageManager -from adf_core_python.core.agent.develop.develop_data import DevelopData -from adf_core_python.core.agent.info.agent_info import AgentInfo -from adf_core_python.core.agent.info.scenario_info import ScenarioInfo -from adf_core_python.core.agent.info.world_info import WorldInfo -from adf_core_python.core.agent.module.module_manager import ModuleManager -from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData from adf_core_python.core.component.module.complex.target_allocator import ( TargetAllocator, ) +if TYPE_CHECKING: + from rcrs_core.worldmodel.entityID import EntityID + + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + class PoliceTargetAllocator(TargetAllocator): def __init__( @@ -32,17 +37,21 @@ def get_result(self) -> dict[EntityID, EntityID]: pass @abstractmethod - def calculate(self) -> TargetAllocator: + def calculate(self) -> PoliceTargetAllocator: pass - def resume(self, precompute_data: PrecomputeData) -> TargetAllocator: + def precompute(self, precompute_data: PrecomputeData) -> PoliceTargetAllocator: + super().precompute(precompute_data) + return self + + def resume(self, precompute_data: PrecomputeData) -> PoliceTargetAllocator: super().resume(precompute_data) return self - def prepare(self) -> TargetAllocator: + def prepare(self) -> PoliceTargetAllocator: super().prepare() return self - def update_info(self, message_manager: MessageManager) -> TargetAllocator: + def update_info(self, message_manager: MessageManager) -> PoliceTargetAllocator: super().update_info(message_manager) return self diff --git a/adf_core_python/core/component/module/complex/target_allocator.py b/adf_core_python/core/component/module/complex/target_allocator.py index 2548a2d..55869c9 100644 --- a/adf_core_python/core/component/module/complex/target_allocator.py +++ b/adf_core_python/core/component/module/complex/target_allocator.py @@ -1,9 +1,7 @@ from __future__ import annotations from abc import abstractmethod -from typing import TYPE_CHECKING, Generic, TypeVar - -from rcrs_core.entities.entity import Entity +from typing import TYPE_CHECKING from adf_core_python.core.component.module.abstract_module import AbstractModule @@ -18,10 +16,8 @@ from adf_core_python.core.agent.module.module_manager import ModuleManager from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData -T = TypeVar("T", bound=Entity) - -class TargetAllocator(AbstractModule, Generic[T]): +class TargetAllocator(AbstractModule): def __init__( self, agent_info: AgentInfo, @@ -39,21 +35,21 @@ def get_result(self) -> dict[EntityID, EntityID]: pass @abstractmethod - def calculate(self) -> TargetAllocator[T]: + def calculate(self) -> TargetAllocator: pass - def precompute(self, precompute_data: PrecomputeData) -> TargetAllocator[T]: + def precompute(self, precompute_data: PrecomputeData) -> TargetAllocator: super().precompute(precompute_data) return self - def resume(self, precompute_data: PrecomputeData) -> TargetAllocator[T]: + def resume(self, precompute_data: PrecomputeData) -> TargetAllocator: super().resume(precompute_data) return self - def prepare(self) -> TargetAllocator[T]: + def prepare(self) -> TargetAllocator: super().prepare() return self - def update_info(self, message_manager: MessageManager) -> TargetAllocator[T]: + def update_info(self, message_manager: MessageManager) -> TargetAllocator: super().update_info(message_manager) return self diff --git a/adf_core_python/core/gateway/__init__.py b/adf_core_python/core/gateway/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/adf_core_python/core/gateway/component/__init__.py b/adf_core_python/core/gateway/component/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/adf_core_python/core/gateway/component/module/__init__.py b/adf_core_python/core/gateway/component/module/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/adf_core_python/core/gateway/component/module/algorithm/__init__.py b/adf_core_python/core/gateway/component/module/algorithm/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/adf_core_python/core/gateway/component/module/algorithm/gateway_clustering.py b/adf_core_python/core/gateway/component/module/algorithm/gateway_clustering.py new file mode 100644 index 0000000..6518770 --- /dev/null +++ b/adf_core_python/core/gateway/component/module/algorithm/gateway_clustering.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import json +from typing import TYPE_CHECKING + +from rcrs_core.worldmodel.entityID import EntityID + +from adf_core_python.core.component.module.algorithm.clustering import Clustering +from adf_core_python.core.gateway.component.module.gateway_abstract_module import ( + GatewayAbstractModule, +) + +if TYPE_CHECKING: + from rcrs_core.entities.entity import Entity + + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + from adf_core_python.core.gateway.gateway_module import GatewayModule + + +class GatewayClustering(GatewayAbstractModule, Clustering): + def __init__( + self, + agent_info: AgentInfo, + world_info: WorldInfo, + scenario_info: ScenarioInfo, + module_manager: ModuleManager, + develop_data: DevelopData, + gateway_module: GatewayModule, + ) -> None: + super().__init__( + agent_info, + world_info, + scenario_info, + module_manager, + develop_data, + gateway_module, + ) + + def precompute(self, precompute_data: PrecomputeData) -> GatewayClustering: + super().precompute(precompute_data) + return self + + def resume(self, precompute_data: PrecomputeData) -> GatewayClustering: + super().resume(precompute_data) + return self + + def prepare(self) -> GatewayClustering: + super().prepare() + return self + + def update_info(self, message_manager: MessageManager) -> GatewayClustering: + super().update_info(message_manager) + return self + + def calculate(self) -> GatewayClustering: + super().calculate() + return self + + def get_cluster_number(self) -> int: + result = self._gateway_module.execute("getClusterNumber") + return int(result.get_value_or_default("ClusterNumber", "0")) + + def get_cluster_index(self, entity_id: EntityID) -> int: + arguments: dict[str, str] = {"EntityID": str(entity_id.get_value())} + result = self._gateway_module.execute("getClusterIndex(EntityID)", arguments) + return int(result.get_value_or_default("ClusterIndex", "0")) + + def get_cluster_entities(self, cluster_index: int) -> list[Entity]: + arguments: dict[str, str] = {"Index": str(cluster_index)} + result = self._gateway_module.execute("getClusterEntities(int)", arguments) + json_str = result.get_value_or_default("EntityIDs", "[]") + entity_ids: list[int] = json.loads(json_str) + entities: list[Entity] = [] + for entity_id in entity_ids: + entities.append(self._world_info.get_entity(EntityID(entity_id))) + return entities + + def get_cluster_entity_ids(self, cluster_index: int) -> list[EntityID]: + arguments: dict[str, str] = {"Index": str(cluster_index)} + result = self._gateway_module.execute("getClusterEntityIDs(int)", arguments) + json_str = result.get_value_or_default("EntityIDs", "[]") + raw_entity_ids: list[int] = json.loads(json_str) + entity_ids: list[EntityID] = [] + for entity_id in raw_entity_ids: + entity_ids.append(EntityID(entity_id)) + return entity_ids diff --git a/adf_core_python/core/gateway/component/module/algorithm/gateway_path_planning.py b/adf_core_python/core/gateway/component/module/algorithm/gateway_path_planning.py new file mode 100644 index 0000000..7d3b218 --- /dev/null +++ b/adf_core_python/core/gateway/component/module/algorithm/gateway_path_planning.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +import json +from typing import TYPE_CHECKING + +from rcrs_core.worldmodel.entityID import EntityID + +from adf_core_python.core.component.module.algorithm.path_planning import PathPlanning +from adf_core_python.core.gateway.component.module.gateway_abstract_module import ( + GatewayAbstractModule, +) + +if TYPE_CHECKING: + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + from adf_core_python.core.gateway.gateway_module import GatewayModule + + +class GatewayPathPlanning(GatewayAbstractModule, PathPlanning): + def __init__( + self, + agent_info: AgentInfo, + world_info: WorldInfo, + scenario_info: ScenarioInfo, + module_manager: ModuleManager, + develop_data: DevelopData, + gateway_module: GatewayModule, + ) -> None: + super().__init__( + agent_info, + world_info, + scenario_info, + module_manager, + develop_data, + gateway_module, + ) + + def precompute(self, precompute_data: PrecomputeData) -> GatewayPathPlanning: + super().precompute(precompute_data) + return self + + def resume(self, precompute_data: PrecomputeData) -> GatewayPathPlanning: + super().resume(precompute_data) + return self + + def prepare(self) -> GatewayPathPlanning: + super().prepare() + return self + + def update_info(self, message_manager: MessageManager) -> GatewayPathPlanning: + super().update_info(message_manager) + return self + + def calculate(self) -> GatewayPathPlanning: + super().calculate() + return self + + def get_path( + self, from_entity_id: EntityID, to_entity_id: EntityID + ) -> list[EntityID]: + arguments: dict[str, str] = { + "From": str(from_entity_id.get_value()), + "To": str(to_entity_id.get_value()), + } + result = self._gateway_module.execute( + "getResult(EntityID, EntityID)", arguments + ) + json_str = result.get_value_or_default("Result", "[]") + raw_entity_ids: list[int] = json.loads(json_str) + entity_ids: list[EntityID] = [] + for entity_id in raw_entity_ids: + entity_ids.append(EntityID(entity_id)) + return entity_ids + + def get_distance(self, from_entity_id: EntityID, to_entity_id: EntityID) -> float: + arguments: dict[str, str] = { + "From": str(from_entity_id.get_value()), + "To": str(to_entity_id.get_value()), + } + result = self._gateway_module.execute( + "getDistance(EntityID, EntityID)", arguments + ) + return float(result.get_value_or_default("Result", "0.0")) diff --git a/adf_core_python/core/gateway/component/module/complex/__init__.py b/adf_core_python/core/gateway/component/module/complex/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/adf_core_python/core/gateway/component/module/complex/gateway_ambulance_target_allocator.py b/adf_core_python/core/gateway/component/module/complex/gateway_ambulance_target_allocator.py new file mode 100644 index 0000000..f570436 --- /dev/null +++ b/adf_core_python/core/gateway/component/module/complex/gateway_ambulance_target_allocator.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from adf_core_python.core.component.module.complex.ambulance_target_allocator import ( + AmbulanceTargetAllocator, +) +from adf_core_python.core.gateway.component.module.complex.gateway_target_allocator import ( + GatewayTargetAllocator, +) + +if TYPE_CHECKING: + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + from adf_core_python.core.gateway.gateway_module import GatewayModule + + +class GatewayAmbulanceTargetAllocator(GatewayTargetAllocator, AmbulanceTargetAllocator): + def __init__( + self, + agent_info: AgentInfo, + world_info: WorldInfo, + scenario_info: ScenarioInfo, + module_manager: ModuleManager, + develop_data: DevelopData, + gateway_module: GatewayModule, + ) -> None: + super().__init__( + agent_info, + world_info, + scenario_info, + module_manager, + develop_data, + gateway_module, + ) + + def precompute( + self, precompute_data: PrecomputeData + ) -> GatewayAmbulanceTargetAllocator: + super().precompute(precompute_data) + return self + + def resume( + self, precompute_data: PrecomputeData + ) -> GatewayAmbulanceTargetAllocator: + super().resume(precompute_data) + return self + + def prepare(self) -> GatewayAmbulanceTargetAllocator: + super().prepare() + return self + + def update_info( + self, message_manager: MessageManager + ) -> GatewayAmbulanceTargetAllocator: + super().update_info(message_manager) + return self + + def calculate(self) -> GatewayAmbulanceTargetAllocator: + super().calculate() + return self diff --git a/adf_core_python/core/gateway/component/module/complex/gateway_fire_target_allocator.py b/adf_core_python/core/gateway/component/module/complex/gateway_fire_target_allocator.py new file mode 100644 index 0000000..69fb643 --- /dev/null +++ b/adf_core_python/core/gateway/component/module/complex/gateway_fire_target_allocator.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from adf_core_python.core.component.module.complex.fire_target_allocator import ( + FireTargetAllocator, +) +from adf_core_python.core.gateway.component.module.complex.gateway_target_allocator import ( + GatewayTargetAllocator, +) + +if TYPE_CHECKING: + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + from adf_core_python.core.gateway.gateway_module import GatewayModule + + +class GatewayFireTargetAllocator(GatewayTargetAllocator, FireTargetAllocator): + def __init__( + self, + agent_info: AgentInfo, + world_info: WorldInfo, + scenario_info: ScenarioInfo, + module_manager: ModuleManager, + develop_data: DevelopData, + gateway_module: GatewayModule, + ) -> None: + super().__init__( + agent_info, + world_info, + scenario_info, + module_manager, + develop_data, + gateway_module, + ) + + def precompute(self, precompute_data: PrecomputeData) -> GatewayFireTargetAllocator: + super().precompute(precompute_data) + return self + + def resume(self, precompute_data: PrecomputeData) -> GatewayFireTargetAllocator: + super().resume(precompute_data) + return self + + def prepare(self) -> GatewayFireTargetAllocator: + super().prepare() + return self + + def update_info( + self, message_manager: MessageManager + ) -> GatewayFireTargetAllocator: + super().update_info(message_manager) + return self + + def calculate(self) -> GatewayFireTargetAllocator: + super().calculate() + return self diff --git a/adf_core_python/core/gateway/component/module/complex/gateway_human_detector.py b/adf_core_python/core/gateway/component/module/complex/gateway_human_detector.py new file mode 100644 index 0000000..7fc6fe7 --- /dev/null +++ b/adf_core_python/core/gateway/component/module/complex/gateway_human_detector.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from rcrs_core.entities.human import Human + +from adf_core_python.core.component.module.complex.human_detector import ( + HumanDetector, +) +from adf_core_python.core.gateway.component.module.complex.gateway_target_detector import ( + GatewayTargetDetector, +) + +if TYPE_CHECKING: + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + from adf_core_python.core.gateway.gateway_module import GatewayModule + + +class GatewayHumanDetector(GatewayTargetDetector[Human], HumanDetector): + def __init__( + self, + agent_info: AgentInfo, + world_info: WorldInfo, + scenario_info: ScenarioInfo, + module_manager: ModuleManager, + develop_data: DevelopData, + gateway_module: GatewayModule, + ) -> None: + super().__init__( + agent_info, + world_info, + scenario_info, + module_manager, + develop_data, + gateway_module, + ) + + def precompute(self, precompute_data: PrecomputeData) -> GatewayHumanDetector: + super().precompute(precompute_data) + return self + + def resume(self, precompute_data: PrecomputeData) -> GatewayHumanDetector: + super().resume(precompute_data) + return self + + def prepare(self) -> GatewayHumanDetector: + super().prepare() + return self + + def update_info(self, message_manager: MessageManager) -> GatewayHumanDetector: + super().update_info(message_manager) + return self + + def calculate(self) -> GatewayHumanDetector: + super().calculate() + return self diff --git a/adf_core_python/core/gateway/component/module/complex/gateway_police_target_allocator.py b/adf_core_python/core/gateway/component/module/complex/gateway_police_target_allocator.py new file mode 100644 index 0000000..bacc0bb --- /dev/null +++ b/adf_core_python/core/gateway/component/module/complex/gateway_police_target_allocator.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from adf_core_python.core.component.module.complex.police_target_allocator import ( + PoliceTargetAllocator, +) +from adf_core_python.core.gateway.component.module.complex.gateway_target_allocator import ( + GatewayTargetAllocator, +) + +if TYPE_CHECKING: + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + from adf_core_python.core.gateway.gateway_module import GatewayModule + + +class GatewayPoliceTargetAllocator(GatewayTargetAllocator, PoliceTargetAllocator): + def __init__( + self, + agent_info: AgentInfo, + world_info: WorldInfo, + scenario_info: ScenarioInfo, + module_manager: ModuleManager, + develop_data: DevelopData, + gateway_module: GatewayModule, + ) -> None: + super().__init__( + agent_info, + world_info, + scenario_info, + module_manager, + develop_data, + gateway_module, + ) + + def precompute( + self, precompute_data: PrecomputeData + ) -> GatewayPoliceTargetAllocator: + super().precompute(precompute_data) + return self + + def resume(self, precompute_data: PrecomputeData) -> GatewayPoliceTargetAllocator: + super().resume(precompute_data) + return self + + def prepare(self) -> GatewayPoliceTargetAllocator: + super().prepare() + return self + + def update_info( + self, message_manager: MessageManager + ) -> GatewayPoliceTargetAllocator: + super().update_info(message_manager) + return self + + def calculate(self) -> GatewayPoliceTargetAllocator: + super().calculate() + return self diff --git a/adf_core_python/core/gateway/component/module/complex/gateway_road_detector.py b/adf_core_python/core/gateway/component/module/complex/gateway_road_detector.py new file mode 100644 index 0000000..da275b9 --- /dev/null +++ b/adf_core_python/core/gateway/component/module/complex/gateway_road_detector.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from rcrs_core.entities.road import Road + +from adf_core_python.core.agent.communication.message_manager import MessageManager +from adf_core_python.core.component.module.complex.road_detector import RoadDetector +from adf_core_python.core.gateway.component.module.complex.gateway_target_detector import ( + GatewayTargetDetector, +) + +if TYPE_CHECKING: + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + from adf_core_python.core.gateway.gateway_module import GatewayModule + + +class GatewayRoadDetector(GatewayTargetDetector[Road], RoadDetector): + def __init__( + self, + agent_info: AgentInfo, + world_info: WorldInfo, + scenario_info: ScenarioInfo, + module_manager: ModuleManager, + develop_data: DevelopData, + gateway_module: GatewayModule, + ) -> None: + super().__init__( + agent_info, + world_info, + scenario_info, + module_manager, + develop_data, + gateway_module, + ) + + def precompute(self, precompute_data: PrecomputeData) -> GatewayRoadDetector: + super().precompute(precompute_data) + return self + + def resume(self, precompute_data: PrecomputeData) -> GatewayRoadDetector: + super().resume(precompute_data) + return self + + def prepare(self) -> GatewayRoadDetector: + super().prepare() + return self + + def update_info(self, message_manager: MessageManager) -> GatewayRoadDetector: + super().update_info(message_manager) + return self + + def calculate(self) -> GatewayRoadDetector: + super().calculate() + return self diff --git a/adf_core_python/core/gateway/component/module/complex/gateway_search.py b/adf_core_python/core/gateway/component/module/complex/gateway_search.py new file mode 100644 index 0000000..bf37e2c --- /dev/null +++ b/adf_core_python/core/gateway/component/module/complex/gateway_search.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from adf_core_python.core.component.module.complex.search import Search +from adf_core_python.core.gateway.component.module.complex.gateway_target_detector import ( + GatewayTargetDetector, +) + +if TYPE_CHECKING: + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + from adf_core_python.core.gateway.gateway_module import GatewayModule + + +class GatewaySearch(GatewayTargetDetector, Search): + def __init__( + self, + agent_info: AgentInfo, + world_info: WorldInfo, + scenario_info: ScenarioInfo, + module_manager: ModuleManager, + develop_data: DevelopData, + gateway_module: GatewayModule, + ) -> None: + super().__init__( + agent_info, + world_info, + scenario_info, + module_manager, + develop_data, + gateway_module, + ) + + def precompute(self, precompute_data: PrecomputeData) -> GatewaySearch: + super().precompute(precompute_data) + return self + + def resume(self, precompute_data: PrecomputeData) -> GatewaySearch: + super().resume(precompute_data) + return self + + def prepare(self) -> GatewaySearch: + super().prepare() + return self + + def update_info(self, message_manager: MessageManager) -> GatewaySearch: + super().update_info(message_manager) + return self + + def calculate(self) -> GatewaySearch: + super().calculate() + return self diff --git a/adf_core_python/core/gateway/component/module/complex/gateway_target_allocator.py b/adf_core_python/core/gateway/component/module/complex/gateway_target_allocator.py new file mode 100644 index 0000000..98649a4 --- /dev/null +++ b/adf_core_python/core/gateway/component/module/complex/gateway_target_allocator.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from rcrs_core.worldmodel.entityID import EntityID + +from adf_core_python.core.component.module.complex.target_allocator import ( + TargetAllocator, +) +from adf_core_python.core.gateway.component.module.gateway_abstract_module import ( + GatewayAbstractModule, +) + +if TYPE_CHECKING: + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + from adf_core_python.core.gateway.gateway_module import GatewayModule + + +class GatewayTargetAllocator(GatewayAbstractModule, TargetAllocator): + def __init__( + self, + agent_info: AgentInfo, + world_info: WorldInfo, + scenario_info: ScenarioInfo, + module_manager: ModuleManager, + develop_data: DevelopData, + gateway_module: GatewayModule, + ) -> None: + super().__init__( + agent_info, + world_info, + scenario_info, + module_manager, + develop_data, + gateway_module, + ) + + def precompute(self, precompute_data: PrecomputeData) -> GatewayTargetAllocator: + super().precompute(precompute_data) + return self + + def resume(self, precompute_data: PrecomputeData) -> GatewayTargetAllocator: + super().resume(precompute_data) + return self + + def prepare(self) -> GatewayTargetAllocator: + super().prepare() + return self + + def update_info(self, message_manager: MessageManager) -> GatewayTargetAllocator: + super().update_info(message_manager) + return self + + def calculate(self) -> GatewayTargetAllocator: + super().calculate() + return self + + def get_result(self) -> dict[EntityID, EntityID]: + response = self._gateway_module.execute("getResult") + response_keys = response.get_all_keys() + result: dict[EntityID, EntityID] = {} + for key in response_keys: + result[EntityID(int(key))] = EntityID( + int(response.get_value_or_default(key, "-1")) + ) + + return result diff --git a/adf_core_python/core/gateway/component/module/complex/gateway_target_detector.py b/adf_core_python/core/gateway/component/module/complex/gateway_target_detector.py new file mode 100644 index 0000000..a58b25f --- /dev/null +++ b/adf_core_python/core/gateway/component/module/complex/gateway_target_detector.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from typing import Optional, Generic, TypeVar, TYPE_CHECKING + +from rcrs_core.entities.entity import Entity +from rcrs_core.worldmodel.entityID import EntityID + +from adf_core_python.core.component.module.complex.target_detector import TargetDetector +from adf_core_python.core.gateway.component.module.gateway_abstract_module import ( + GatewayAbstractModule, +) + +if TYPE_CHECKING: + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + from adf_core_python.core.gateway.gateway_module import GatewayModule + +T = TypeVar("T", bound=Entity) + + +class GatewayTargetDetector(GatewayAbstractModule, TargetDetector, Generic[T]): + def __init__( + self, + agent_info: AgentInfo, + world_info: WorldInfo, + scenario_info: ScenarioInfo, + module_manager: ModuleManager, + develop_data: DevelopData, + gateway_module: GatewayModule, + ) -> None: + super().__init__( + agent_info, + world_info, + scenario_info, + module_manager, + develop_data, + gateway_module, + ) + + def precompute(self, precompute_data: PrecomputeData) -> GatewayTargetDetector[T]: + super().precompute(precompute_data) + return self + + def resume(self, precompute_data: PrecomputeData) -> GatewayTargetDetector[T]: + super().resume(precompute_data) + return self + + def prepare(self) -> GatewayTargetDetector[T]: + super().prepare() + return self + + def update_info(self, message_manager: MessageManager) -> GatewayTargetDetector[T]: + super().update_info(message_manager) + return self + + def calculate(self) -> GatewayTargetDetector[T]: + super().calculate() + return self + + def get_target_entity_id(self) -> Optional[EntityID]: + result = self._gateway_module.execute("getTarget") + entity_id_str = result.get_value_or_default("EntityID", "-1") + if entity_id_str == "-1": + return None + return EntityID(int(entity_id_str)) diff --git a/adf_core_python/core/gateway/component/module/gateway_abstract_module.py b/adf_core_python/core/gateway/component/module/gateway_abstract_module.py new file mode 100644 index 0000000..857977b --- /dev/null +++ b/adf_core_python/core/gateway/component/module/gateway_abstract_module.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from adf_core_python.core.component.module.abstract_module import AbstractModule + +if TYPE_CHECKING: + from adf_core_python.core.agent.communication.message_manager import MessageManager + from adf_core_python.core.agent.develop.develop_data import DevelopData + from adf_core_python.core.agent.info.agent_info import AgentInfo + from adf_core_python.core.agent.info.scenario_info import ScenarioInfo + from adf_core_python.core.agent.info.world_info import WorldInfo + from adf_core_python.core.agent.module.module_manager import ModuleManager + from adf_core_python.core.agent.precompute.precompute_data import PrecomputeData + from adf_core_python.core.gateway.gateway_module import GatewayModule + + +class GatewayAbstractModule(AbstractModule): + def __init__( + self, + agent_info: AgentInfo, + world_info: WorldInfo, + scenario_info: ScenarioInfo, + module_manager: ModuleManager, + develop_data: DevelopData, + gateway_module: GatewayModule, + ) -> None: + super().__init__( + agent_info, world_info, scenario_info, module_manager, develop_data + ) + self._gateway_module = gateway_module + + def precompute(self, precompute_data: PrecomputeData) -> GatewayAbstractModule: + super().precompute(precompute_data) + self._gateway_module.execute("precompute") + return self + + def resume(self, precompute_data: PrecomputeData) -> GatewayAbstractModule: + super().resume(precompute_data) + self._gateway_module.execute("resume") + return self + + def prepare(self) -> GatewayAbstractModule: + super().prepare() + self._gateway_module.execute("preparate") + return self + + def update_info(self, message_manager: MessageManager) -> GatewayAbstractModule: + super().update_info(message_manager) + self._gateway_module.execute("updateInfo") + return self + + def calculate(self) -> GatewayAbstractModule: + self._gateway_module.execute("calc") + return self diff --git a/adf_core_python/core/gateway/gateway_agent.py b/adf_core_python/core/gateway/gateway_agent.py new file mode 100644 index 0000000..036c49a --- /dev/null +++ b/adf_core_python/core/gateway/gateway_agent.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +from typing import Optional, TYPE_CHECKING, Callable + +from rcrs_core.connection import RCRSProto_pb2 + +from adf_core_python.core.agent.info.agent_info import AgentInfo +from adf_core_python.core.agent.info.scenario_info import ScenarioInfo +from adf_core_python.core.agent.info.world_info import WorldInfo +from adf_core_python.core.gateway.message.am_agent import AMAgent +from adf_core_python.core.gateway.message.am_update import AMUpdate +from adf_core_python.core.gateway.message.ma_exec_response import MAExecResponse +from adf_core_python.core.gateway.message.ma_module_response import ( + MAModuleResponse, +) +from adf_core_python.core.gateway.message.moduleMessageFactory import ( + ModuleMessageFactory, +) +from adf_core_python.core.logger.logger import get_logger + +if TYPE_CHECKING: + from adf_core_python.core.gateway.gateway_launcher import GatewayLauncher + from adf_core_python.core.gateway.gateway_module import GatewayModule + + +class GatewayAgent: + def __init__(self, gateway_launcher: GatewayLauncher) -> None: + self._gateway_launcher = gateway_launcher + self.send_msg: Optional[Callable] = None + self._is_initialized = False + self._agent_info: Optional[AgentInfo] = None + self._world_info: Optional[WorldInfo] = None + self._scenario_info: Optional[ScenarioInfo] = None + self._gateway_modules: dict[str, GatewayModule] = {} + self._logger = get_logger(__name__) + + def get_module_count(self) -> int: + return len(self._gateway_modules) + + def add_gateway_module(self, gateway_module: GatewayModule) -> None: + self._gateway_modules[gateway_module.get_module_id()] = gateway_module + + def is_initialized(self) -> bool: + return self._is_initialized + + def set_initialize_data( + self, agent_info: AgentInfo, world_info: WorldInfo, scenario_info: ScenarioInfo + ) -> None: + self._agent_info = agent_info + self._world_info = world_info + self._scenario_info = scenario_info + + def initialize(self) -> None: + if self.send_msg is None: + raise RuntimeError("send_msg is None") + if ( + self._agent_info is None + or self._world_info is None + or self._scenario_info is None + ): + raise RuntimeError( + "Required variables is None, " + "You must exec set_initialized_data() before calling initialize()" + ) + + am_agent = AMAgent() + self.send_msg( + am_agent.write( + self._agent_info.get_entity_id(), + list(self._world_info.get_world_model().get_entities()), + self._scenario_info.get_config().config, + int(self._scenario_info.get_mode()), + ) + ) + self._is_initialized = True + + def update(self) -> None: + if self.send_msg is None: + raise RuntimeError("send_msg is None") + if self._agent_info is None or self._world_info is None: + raise RuntimeError( + "Required variables is None, " + "You must exec set_initialized_data() before calling update()" + ) + + am_update = AMUpdate() + self.send_msg( + am_update.write( + self._agent_info.get_time(), + self._world_info.get_change_set(), + self._agent_info.get_heard_commands(), + ) + ) + + def set_send_msg(self, connection_send_func: Callable) -> None: + self.send_msg = connection_send_func + + def message_received(self, msg: RCRSProto_pb2) -> None: + c_msg = ModuleMessageFactory().make_message(msg) + if isinstance(c_msg, MAModuleResponse): + if c_msg.module_id is None or c_msg.class_name is None: + raise RuntimeError("Failed to receive message") + + self._gateway_modules[c_msg.module_id].set_gateway_class_name( + c_msg.class_name + ) + self._gateway_modules[c_msg.module_id].set_is_initialized(True) + if isinstance(c_msg, MAExecResponse): + if c_msg.module_id is None: + raise RuntimeError("Failed to receive message") + + self._gateway_modules[c_msg.module_id].set_execute_response(c_msg.result) + self._gateway_modules[c_msg.module_id].set_is_executed(True) diff --git a/adf_core_python/core/gateway/gateway_launcher.py b/adf_core_python/core/gateway/gateway_launcher.py new file mode 100644 index 0000000..e320d24 --- /dev/null +++ b/adf_core_python/core/gateway/gateway_launcher.py @@ -0,0 +1,45 @@ +import socket + +from structlog import BoundLogger + +from adf_core_python.core.gateway.gateway_agent import GatewayAgent +from adf_core_python.core.launcher.connect.connection import Connection + + +class GatewayLauncher: + def __init__(self, host: str, port: int, logger: BoundLogger) -> None: + self.host = host + self.port = port + self.logger = logger + pass + + def make_connection(self) -> Connection: + return Connection(self.host, self.port) + + def connect(self, gateway_agent: GatewayAgent) -> None: + self.logger.info( + f"{gateway_agent.__class__.__name__} connecting to {self.host}:{self.port}" + ) + connection = self.make_connection() + try: + connection.connect() + # ソケットが使用しているPORT番号を取得 + if connection.socket is not None: + self.logger.info( + f"Connected to {self.host}:{self.port} on port {connection.socket.getsockname()[1]}" + ) + except socket.timeout: + self.logger.warning(f"Connection to {self.host}:{self.port} timed out") + return + except socket.error as e: + self.logger.error(f"Failed to connect to {self.host}:{self.port}") + self.logger.error(e) + return + + connection.message_received(gateway_agent.message_received) + gateway_agent.set_send_msg(connection.send_msg) + + try: + connection.parse_message_from_kernel() + except Exception as e: + self.logger.error(f"Failed to connect agent: {self.host}:{self.port} {e}") diff --git a/adf_core_python/core/gateway/gateway_module.py b/adf_core_python/core/gateway/gateway_module.py new file mode 100644 index 0000000..e79b239 --- /dev/null +++ b/adf_core_python/core/gateway/gateway_module.py @@ -0,0 +1,83 @@ +import uuid +from typing import Optional + +from rcrs_core.config.config import Config + +from adf_core_python.core.gateway.gateway_agent import GatewayAgent +from adf_core_python.core.gateway.message.am_exec import AMExec +from adf_core_python.core.gateway.message.am_module import AMModule + + +class GatewayModule: + def __init__(self, gateway_agent: GatewayAgent): + self._gateway_agent = gateway_agent + self._module_id: str = str(uuid.uuid4()) + self._is_initialized = False + self._is_executed = False + self._gateway_class_name: str = "" + self._result: Optional[Config] = None + self._gateway_agent.add_gateway_module(self) + + def get_module_id(self) -> str: + return self._module_id + + def get_gateway_class_name(self) -> str: + return self._gateway_class_name + + def set_gateway_class_name(self, gateway_class_name: str) -> None: + self._gateway_class_name = gateway_class_name + + def get_is_initialized(self) -> bool: + return self._is_initialized + + def set_is_initialized(self, is_initialized: bool) -> None: + self._is_initialized = is_initialized + + def initialize(self, module_name: str, default_class_name: str) -> str: + if not self._gateway_agent.is_initialized(): + self._gateway_agent.initialize() + if self._gateway_agent.send_msg is None: + raise RuntimeError("send_msg is None") + + am_module = AMModule() + self._gateway_agent.send_msg( + am_module.write( + self._module_id, + module_name, + default_class_name, + ) + ) + + while not self.get_is_initialized(): + pass + + return self.get_gateway_class_name() + + def get_execute_response(self) -> Config: + return self._result + + def set_execute_response(self, result: Config) -> None: + self._result = result + + def get_is_executed(self) -> bool: + return self._is_executed + + def set_is_executed(self, _is_executed: bool) -> None: + self._is_executed = _is_executed + + def execute( + self, method_name: str, args: Optional[dict[str, str]] = None + ) -> Config: + if args is None: + args = {} + if self._gateway_agent.send_msg is None: + raise RuntimeError("send_msg is None") + + am_exec = AMExec() + self._gateway_agent.send_msg(am_exec.write(self._module_id, method_name, args)) + + while not self.get_is_executed(): + pass + + self.set_is_executed(False) + return self.get_execute_response() diff --git a/adf_core_python/core/gateway/message/__init__.py b/adf_core_python/core/gateway/message/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/adf_core_python/core/gateway/message/am_agent.py b/adf_core_python/core/gateway/message/am_agent.py new file mode 100644 index 0000000..3d6bc8d --- /dev/null +++ b/adf_core_python/core/gateway/message/am_agent.py @@ -0,0 +1,55 @@ +from typing import Any + +from rcrs_core.connection import RCRSProto_pb2 +from rcrs_core.entities.entity import Entity +from rcrs_core.messages.message import Message +from rcrs_core.worldmodel.entityID import EntityID + +from adf_core_python.core.gateway.message.urn.urn import ( + ModuleMSG, + ComponentModuleMSG, +) + + +class AMAgent(Message): + def __init__(self) -> None: + super().__init__(ModuleMSG.AM_AGENT) + + def read(self) -> None: + pass + + def write( + self, + agent_id: EntityID, + entities: list[Entity], + config: dict[str, Any], + mode: int, + ) -> Any: + entity_proto_list = [] + for entity in entities: + entity_proto = RCRSProto_pb2.EntityProto() + entity_proto.urn = entity.get_urn() + entity_proto.entityID = entity.get_id().get_value() + + property_proto_list = [] + for k, v in entity.get_properties().items(): + property_proto_list.append(v.to_property_proto()) + entity_proto.properties.extend(property_proto_list) + entity_proto_list.append(entity_proto) + + entity_list_proto = RCRSProto_pb2.EntityListProto() + entity_list_proto.entities.extend(entity_proto_list) + + config_proto = RCRSProto_pb2.ConfigProto() + for key, value in config.items(): + config_proto.data[str(key)] = str(value) + + msg = RCRSProto_pb2.MessageProto() + msg.urn = self.get_urn() + msg.components[ComponentModuleMSG.AgentID].entityID = agent_id.get_value() + msg.components[ComponentModuleMSG.Entities].entityList.CopyFrom( + entity_list_proto + ) + msg.components[ComponentModuleMSG.Config].config.CopyFrom(config_proto) + msg.components[ComponentModuleMSG.Mode].intValue = mode + return msg diff --git a/adf_core_python/core/gateway/message/am_exec.py b/adf_core_python/core/gateway/message/am_exec.py new file mode 100644 index 0000000..9bd36be --- /dev/null +++ b/adf_core_python/core/gateway/message/am_exec.py @@ -0,0 +1,30 @@ +from abc import ABC +from typing import Any + +from rcrs_core.connection import RCRSProto_pb2 +from rcrs_core.messages.message import Message + +from adf_core_python.core.gateway.message.urn.urn import ( + ModuleMSG, + ComponentModuleMSG, +) + + +class AMExec(Message, ABC): + def __init__(self) -> None: + super().__init__(ModuleMSG.AM_EXEC) + + def read(self) -> None: + pass + + def write(self, module_id: str, method_name: str, arguments: dict[str, str]) -> Any: + msg = RCRSProto_pb2.MessageProto() + msg.urn = self.get_urn() + msg.components[ComponentModuleMSG.ModuleID].stringValue = module_id + msg.components[ComponentModuleMSG.MethodName].stringValue = method_name + config_proto = RCRSProto_pb2.ConfigProto() + for key, value in arguments.items(): + config_proto.data[key] = value + msg.components[ComponentModuleMSG.Arguments].config.CopyFrom(config_proto) + + return msg diff --git a/adf_core_python/core/gateway/message/am_module.py b/adf_core_python/core/gateway/message/am_module.py new file mode 100644 index 0000000..0dd26bc --- /dev/null +++ b/adf_core_python/core/gateway/message/am_module.py @@ -0,0 +1,33 @@ +from typing import Any + +from rcrs_core.connection import RCRSProto_pb2 +from rcrs_core.messages.message import Message + +from adf_core_python.core.gateway.message.urn.urn import ( + ModuleMSG, + ComponentModuleMSG, +) + + +class AMModule(Message): + def __init__(self) -> None: + super().__init__(ModuleMSG.AM_MODULE) + + def read(self) -> None: + pass + + def write( + self, + module_id: str, + module_name: str, + default_class_name: str, + ) -> Any: + msg = RCRSProto_pb2.MessageProto() + msg.urn = self.get_urn() + msg.components[ComponentModuleMSG.ModuleID].stringValue = module_id + msg.components[ComponentModuleMSG.ModuleName].stringValue = module_name + msg.components[ + ComponentModuleMSG.DefaultClassName + ].stringValue = default_class_name + + return msg diff --git a/adf_core_python/core/gateway/message/am_update.py b/adf_core_python/core/gateway/message/am_update.py new file mode 100644 index 0000000..0988920 --- /dev/null +++ b/adf_core_python/core/gateway/message/am_update.py @@ -0,0 +1,38 @@ +from abc import ABC +from typing import Any + +from rcrs_core.commands.Command import Command +from rcrs_core.connection import RCRSProto_pb2 +from rcrs_core.messages.message import Message +from rcrs_core.worldmodel.changeSet import ChangeSet + +from adf_core_python.core.gateway.message.urn.urn import ( + ModuleMSG, + ComponentModuleMSG, +) + + +class AMUpdate(Message, ABC): + def __init__(self) -> None: + super().__init__(ModuleMSG.AM_UPDATE) + + def read(self) -> None: + pass + + def write(self, time: int, changed: ChangeSet, heard: list[Command]) -> Any: + msg = RCRSProto_pb2.MessageProto() + msg.urn = self.get_urn() + msg.components[ComponentModuleMSG.Time].intValue = time + msg.components[ComponentModuleMSG.Changed].changeSet.CopyFrom( + changed.to_change_set_proto() + ) + message_list_proto = RCRSProto_pb2.MessageListProto() + message_proto_list = [] + if heard is not None: + for h in heard: + message_proto_list.append(h.prepare_cmd()) + message_list_proto.commands.extend(message_proto_list) + msg.components[ComponentModuleMSG.Heard].commandList.CopyFrom( + message_list_proto + ) + return msg diff --git a/adf_core_python/core/gateway/message/ma_exec_response.py b/adf_core_python/core/gateway/message/ma_exec_response.py new file mode 100644 index 0000000..8c68fbc --- /dev/null +++ b/adf_core_python/core/gateway/message/ma_exec_response.py @@ -0,0 +1,28 @@ +from abc import ABC + +from rcrs_core.config.config import Config +from rcrs_core.connection import RCRSProto_pb2 +from rcrs_core.messages.message import Message + +from adf_core_python.core.gateway.message.urn.urn import ( + ModuleMSG, + ComponentModuleMSG, +) + + +class MAExecResponse(Message, ABC): + def __init__(self, data: RCRSProto_pb2) -> None: + super().__init__(ModuleMSG.MA_EXEC_RESPONSE) + self.module_id = None + self.result = Config() + self.data = data + self.read() + + def read(self) -> None: + self.module_id = self.data.components[ComponentModuleMSG.ModuleID].stringValue + result = self.data.components[ComponentModuleMSG.Result].config + for key, value in result.data.items(): + self.result.set_value(key, value) + + def write(self) -> None: + pass diff --git a/adf_core_python/core/gateway/message/ma_module_response.py b/adf_core_python/core/gateway/message/ma_module_response.py new file mode 100644 index 0000000..c680419 --- /dev/null +++ b/adf_core_python/core/gateway/message/ma_module_response.py @@ -0,0 +1,26 @@ +from abc import ABC +from typing import Optional + +from rcrs_core.connection import RCRSProto_pb2 +from rcrs_core.messages.message import Message + +from adf_core_python.core.gateway.message.urn.urn import ( + ModuleMSG, + ComponentModuleMSG, +) + + +class MAModuleResponse(Message, ABC): + def __init__(self, data: RCRSProto_pb2) -> None: + super().__init__(ModuleMSG.MA_MODULE_RESPONSE) + self.module_id: Optional[str] = None + self.class_name: Optional[str] = None + self.data = data + self.read() + + def read(self) -> None: + self.module_id = self.data.components[ComponentModuleMSG.ModuleID].stringValue + self.class_name = self.data.components[ComponentModuleMSG.ClassName].stringValue + + def write(self) -> None: + pass diff --git a/adf_core_python/core/gateway/message/moduleMessageFactory.py b/adf_core_python/core/gateway/message/moduleMessageFactory.py new file mode 100644 index 0000000..6fac9d8 --- /dev/null +++ b/adf_core_python/core/gateway/message/moduleMessageFactory.py @@ -0,0 +1,24 @@ +from typing import Optional + +from rcrs_core.connection import RCRSProto_pb2 + +from adf_core_python.core.gateway.message.ma_exec_response import MAExecResponse +from adf_core_python.core.gateway.message.ma_module_response import ( + MAModuleResponse, +) +from adf_core_python.core.gateway.message.urn.urn import ModuleMSG + + +class ModuleMessageFactory: + def __init__(self) -> None: + pass + + def make_message( + self, msg: RCRSProto_pb2 + ) -> Optional[MAModuleResponse | MAExecResponse]: + if msg.urn == ModuleMSG.MA_MODULE_RESPONSE: + return MAModuleResponse(msg) + elif msg.urn == ModuleMSG.MA_EXEC_RESPONSE: + return MAExecResponse(msg) + + return None diff --git a/adf_core_python/core/gateway/message/urn/__init__.py b/adf_core_python/core/gateway/message/urn/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/adf_core_python/core/gateway/message/urn/urn.py b/adf_core_python/core/gateway/message/urn/urn.py new file mode 100644 index 0000000..d38e435 --- /dev/null +++ b/adf_core_python/core/gateway/message/urn/urn.py @@ -0,0 +1,27 @@ +from enum import IntEnum + + +class ModuleMSG(IntEnum): + AM_AGENT = 0x0301 + AM_MODULE = 0x0302 + MA_MODULE_RESPONSE = 0x0303 + AM_UPDATE = 0x0304 + AM_EXEC = 0x0305 + MA_EXEC_RESPONSE = 0x0306 + + +class ComponentModuleMSG(IntEnum): + AgentID = 0x0401 + Entities = 0x0402 + Config = 0x0403 + Mode = 0x0404 + ModuleID = 0x0405 + ModuleName = 0x0406 + DefaultClassName = 0x0407 + ClassName = 0x0408 + Time = 0x0409 + Changed = 0x040A + Heard = 0x040B + MethodName = 0x040C + Arguments = 0x040D + Result = 0x040E diff --git a/adf_core_python/core/gateway/module_dict.py b/adf_core_python/core/gateway/module_dict.py new file mode 100644 index 0000000..7f668c6 --- /dev/null +++ b/adf_core_python/core/gateway/module_dict.py @@ -0,0 +1,32 @@ +from typing import Optional + + +class ModuleDict: + def __init__(self, module_dict: Optional[dict[str, str]] = None): + self.module_dict: dict[str, str] = { + "adf_core_python.component.module.algorithm.Clustering": "adf_core_python.core.gateway.component.module.complex.gateway_clustering.GatewayClustering", + "adf_core_python.component.module.algorithm.DynamicClustering": "adf_core_python.core.gateway.component.module.complex.gateway_clustering.GatewayClustering", + "adf_core_python.component.module.algorithm.StaticClustering": "adf_core_python.core.gateway.component.module.complex.gateway_clustering.GatewayClustering", + "adf_core_python.component.module.algorithm.PathPlanning": "adf_core_python.core.gateway.component.module.complex.gateway_path_planning.GatewayPathPlanning", + "adf_core_python.component.module.complex.TargetDetector": "adf_core_python.core.gateway.component.module.complex.gateway_target_detector.GatewayTargetDetector", + "adf_core_python.component.module.complex.HumanDetector": "adf_core_python.core.gateway.component.module.complex.gateway_human_detector.GatewayHumanDetector", + "adf_core_python.component.module.complex.RoadDetector": "adf_core_python.core.gateway.component.module.complex.gateway_road_detector.GatewayRoadDetector", + "adf_core_python.component.module.complex.Search": "adf_core_python.core.gateway.component.module.complex.gateway_search.GatewaySearch", + "adf_core_python.component.module.complex.TargetAllocator": "adf_core_python.core.gateway.component.module.complex.gateway_target_allocator.GatewayTargetAllocator", + "adf_core_python.component.module.complex.AmbulanceTargetAllocator": "adf_core_python.core.gateway.component.module.complex.gateway_ambulance_target_allocator.GatewayAmbulanceTargetAllocator", + "adf_core_python.component.module.complex.FireTargetAllocator": "adf_core_python.core.gateway.component.module.complex.gateway_fire_target_allocator.GatewayFireTargetAllocator", + "adf_core_python.component.module.complex.PoliceTargetAllocator": "adf_core_python.core.gateway.component.module.complex.gateway_fire_target_allocator.GatewayPoliceTargetAllocator", + } + if module_dict is not None: + for key, value in module_dict.items(): + self.module_dict[key] = value + + def __getitem__(self, key: str) -> Optional[str]: + if not isinstance(key, str): + raise TypeError("TypeError: Key must be a string") + return self.module_dict.get(key) + + def __setitem__(self, key: str, value: str) -> None: + if not isinstance(key, str): + raise TypeError("TypeError: Key must be a string") + self.module_dict[key] = value diff --git a/adf_core_python/core/launcher/agent_launcher.py b/adf_core_python/core/launcher/agent_launcher.py index f6f0787..63f31bc 100644 --- a/adf_core_python/core/launcher/agent_launcher.py +++ b/adf_core_python/core/launcher/agent_launcher.py @@ -1,8 +1,10 @@ import importlib import threading +from typing import Optional from adf_core_python.core.component.abstract_loader import AbstractLoader from adf_core_python.core.config.config import Config +from adf_core_python.core.gateway.gateway_launcher import GatewayLauncher from adf_core_python.core.launcher.config_key import ConfigKey from adf_core_python.core.launcher.connect.component_launcher import ComponentLauncher from adf_core_python.core.launcher.connect.connector import Connector @@ -55,17 +57,34 @@ def init_connector(self) -> None: self.connectors.append(ConnectorPoliceOffice()) def launch(self) -> None: - host: str = self.config.get_value(ConfigKey.KEY_KERNEL_HOST, "localhost") - port: int = self.config.get_value(ConfigKey.KEY_KERNEL_PORT, 27931) - self.logger.info(f"Start agent launcher (host: {host}, port: {port})") + kernel_host: str = self.config.get_value(ConfigKey.KEY_KERNEL_HOST, "localhost") + kernel_port: int = self.config.get_value(ConfigKey.KEY_KERNEL_PORT, 27931) + self.logger.info( + f"Start agent launcher (host: {kernel_host}, port: {kernel_port})" + ) component_launcher: ComponentLauncher = ComponentLauncher( - host, port, self.logger + kernel_host, kernel_port, self.logger ) + gateway_launcher: Optional[GatewayLauncher] = None + gateway_flag: bool = self.config.get_value(ConfigKey.KEY_GATEWAY_FLAG, False) + if gateway_flag: + gateway_host: str = self.config.get_value( + ConfigKey.KEY_GATEWAY_HOST, "localhost" + ) + gateway_port: int = self.config.get_value(ConfigKey.KEY_GATEWAY_PORT, 27941) + self.logger.info( + f"Start gateway launcher (host: {gateway_host}, port: {gateway_port})" + ) + + gateway_launcher = GatewayLauncher(gateway_host, gateway_port, self.logger) + connector_thread_list: list[threading.Thread] = [] for connector in self.connectors: - threads = connector.connect(component_launcher, self.config, self.loader) + threads = connector.connect( + component_launcher, gateway_launcher, self.config, self.loader + ) self.agent_thread_list.extend(threads) def connect() -> None: diff --git a/adf_core_python/core/launcher/config_key.py b/adf_core_python/core/launcher/config_key.py index 591876e..8253f47 100644 --- a/adf_core_python/core/launcher/config_key.py +++ b/adf_core_python/core/launcher/config_key.py @@ -24,3 +24,7 @@ class ConfigKey: KEY_POLICE_OFFICE_COUNT: Final[str] = "adf.team.office.police.count" # adf-core-python KEY_PRECOMPUTE_DATA_DIR: Final[str] = "adf.agent.precompute.dir_name" + # Gateway + KEY_GATEWAY_HOST: Final[str] = "gateway.host" + KEY_GATEWAY_PORT: Final[str] = "gateway.port" + KEY_GATEWAY_FLAG: Final[str] = "adf.gateway.flag" diff --git a/adf_core_python/core/launcher/connect/connector.py b/adf_core_python/core/launcher/connect/connector.py index e517a84..a36a04c 100644 --- a/adf_core_python/core/launcher/connect/connector.py +++ b/adf_core_python/core/launcher/connect/connector.py @@ -1,8 +1,10 @@ import threading from abc import ABC, abstractmethod +from typing import Optional from adf_core_python.core.component.abstract_loader import AbstractLoader from adf_core_python.core.config.config import Config +from adf_core_python.core.gateway.gateway_launcher import GatewayLauncher from adf_core_python.core.launcher.connect.component_launcher import ComponentLauncher @@ -14,6 +16,7 @@ def __init__(self) -> None: def connect( self, component_launcher: ComponentLauncher, + gateway_launcher: Optional[GatewayLauncher], config: Config, loader: AbstractLoader, ) -> dict[threading.Thread, threading.Event]: diff --git a/adf_core_python/core/launcher/connect/connector_ambulance_center.py b/adf_core_python/core/launcher/connect/connector_ambulance_center.py index 132a985..ac99bf7 100644 --- a/adf_core_python/core/launcher/connect/connector_ambulance_center.py +++ b/adf_core_python/core/launcher/connect/connector_ambulance_center.py @@ -1,4 +1,5 @@ import threading +from typing import Optional from adf_core_python.core.agent.config.module_config import ModuleConfig from adf_core_python.core.agent.develop.develop_data import DevelopData @@ -8,6 +9,8 @@ TacticsAmbulanceCenter, ) from adf_core_python.core.config.config import Config +from adf_core_python.core.gateway.gateway_agent import GatewayAgent +from adf_core_python.core.gateway.gateway_launcher import GatewayLauncher from adf_core_python.core.launcher.config_key import ConfigKey from adf_core_python.core.launcher.connect.component_launcher import ComponentLauncher from adf_core_python.core.launcher.connect.connector import Connector @@ -22,6 +25,7 @@ def __init__(self) -> None: def connect( self, component_launcher: ComponentLauncher, + gateway_launcher: Optional[GatewayLauncher], config: Config, loader: AbstractLoader, ) -> dict[threading.Thread, threading.Event]: @@ -57,7 +61,19 @@ def connect( finish_post_connect_event = threading.Event() request_id: int = component_launcher.generate_request_id() - thread = threading.Thread( + + gateway_agent: Optional[GatewayAgent] = None + if isinstance(gateway_launcher, GatewayLauncher): + gateway_agent = GatewayAgent(gateway_launcher) + if isinstance(gateway_agent, GatewayAgent): + gateway_thread = threading.Thread( + target=gateway_launcher.connect, + args=(gateway_agent,), + ) + gateway_thread.daemon = True + gateway_thread.start() + + component_thread = threading.Thread( target=component_launcher.connect, args=( OfficeAmbulance( @@ -69,11 +85,12 @@ def connect( module_config, develop_data, finish_post_connect_event, + gateway_agent, ), request_id, ), name=f"AmbulanceCenterAgent-{request_id}", ) - threads[thread] = finish_post_connect_event + threads[component_thread] = finish_post_connect_event return threads diff --git a/adf_core_python/core/launcher/connect/connector_ambulance_team.py b/adf_core_python/core/launcher/connect/connector_ambulance_team.py index d2aa8c0..b354c7c 100644 --- a/adf_core_python/core/launcher/connect/connector_ambulance_team.py +++ b/adf_core_python/core/launcher/connect/connector_ambulance_team.py @@ -1,4 +1,5 @@ import threading +from typing import Optional from adf_core_python.core.agent.config.module_config import ModuleConfig from adf_core_python.core.agent.develop.develop_data import DevelopData @@ -8,6 +9,8 @@ TacticsAmbulanceTeam, ) from adf_core_python.core.config.config import Config +from adf_core_python.core.gateway.gateway_agent import GatewayAgent +from adf_core_python.core.gateway.gateway_launcher import GatewayLauncher from adf_core_python.core.launcher.config_key import ConfigKey from adf_core_python.core.launcher.connect.component_launcher import ComponentLauncher from adf_core_python.core.launcher.connect.connector import Connector @@ -22,6 +25,7 @@ def __init__(self) -> None: def connect( self, component_launcher: ComponentLauncher, + gateway_launcher: Optional[GatewayLauncher], config: Config, loader: AbstractLoader, ) -> dict[threading.Thread, threading.Event]: @@ -57,7 +61,19 @@ def connect( finish_post_connect_event = threading.Event() request_id: int = component_launcher.generate_request_id() - thread = threading.Thread( + + gateway_agent: Optional[GatewayAgent] = None + if isinstance(gateway_launcher, GatewayLauncher): + gateway_agent = GatewayAgent(gateway_launcher) + if isinstance(gateway_agent, GatewayAgent): + gateway_thread = threading.Thread( + target=gateway_launcher.connect, + args=(gateway_agent,), + ) + gateway_thread.daemon = True + gateway_thread.start() + + component_thread = threading.Thread( target=component_launcher.connect, args=( PlatoonAmbulance( @@ -69,11 +85,12 @@ def connect( module_config, develop_data, finish_post_connect_event, + gateway_agent, ), request_id, ), name=f"AmbulanceTeam-{request_id}", ) - threads[thread] = finish_post_connect_event + threads[component_thread] = finish_post_connect_event return threads diff --git a/adf_core_python/core/launcher/connect/connector_fire_brigade.py b/adf_core_python/core/launcher/connect/connector_fire_brigade.py index 747f503..6e5fda3 100644 --- a/adf_core_python/core/launcher/connect/connector_fire_brigade.py +++ b/adf_core_python/core/launcher/connect/connector_fire_brigade.py @@ -1,4 +1,5 @@ import threading +from typing import Optional from adf_core_python.core.agent.config.module_config import ModuleConfig from adf_core_python.core.agent.develop.develop_data import DevelopData @@ -8,6 +9,8 @@ TacticsFireBrigade, ) from adf_core_python.core.config.config import Config +from adf_core_python.core.gateway.gateway_agent import GatewayAgent +from adf_core_python.core.gateway.gateway_launcher import GatewayLauncher from adf_core_python.core.launcher.config_key import ConfigKey from adf_core_python.core.launcher.connect.component_launcher import ComponentLauncher from adf_core_python.core.launcher.connect.connector import Connector @@ -22,6 +25,7 @@ def __init__(self) -> None: def connect( self, component_launcher: ComponentLauncher, + gateway_launcher: Optional[GatewayLauncher], config: Config, loader: AbstractLoader, ) -> dict[threading.Thread, threading.Event]: @@ -53,9 +57,21 @@ def connect( precompute_data_dir: str = f"{config.get_value(ConfigKey.KEY_PRECOMPUTE_DATA_DIR, 'precompute')}/fire_brigade" - request_id: int = component_launcher.generate_request_id() finish_post_connect_event = threading.Event() - thread = threading.Thread( + request_id: int = component_launcher.generate_request_id() + + gateway_agent: Optional[GatewayAgent] = None + if isinstance(gateway_launcher, GatewayLauncher): + gateway_agent = GatewayAgent(gateway_launcher) + if isinstance(gateway_agent, GatewayAgent): + gateway_thread = threading.Thread( + target=gateway_launcher.connect, + args=(gateway_agent,), + ) + gateway_thread.daemon = True + gateway_thread.start() + + component_thread = threading.Thread( target=component_launcher.connect, args=( PlatoonFire( @@ -67,11 +83,12 @@ def connect( module_config, develop_data, finish_post_connect_event, + gateway_agent, ), request_id, ), name=f"FireBrigadeAgent-{request_id}", ) - threads[thread] = finish_post_connect_event + threads[component_thread] = finish_post_connect_event return threads diff --git a/adf_core_python/core/launcher/connect/connector_fire_station.py b/adf_core_python/core/launcher/connect/connector_fire_station.py index 8f099ee..2263167 100644 --- a/adf_core_python/core/launcher/connect/connector_fire_station.py +++ b/adf_core_python/core/launcher/connect/connector_fire_station.py @@ -1,4 +1,5 @@ import threading +from typing import Optional from adf_core_python.core.agent.config.module_config import ModuleConfig from adf_core_python.core.agent.develop.develop_data import DevelopData @@ -8,6 +9,8 @@ TacticsFireStation, ) from adf_core_python.core.config.config import Config +from adf_core_python.core.gateway.gateway_agent import GatewayAgent +from adf_core_python.core.gateway.gateway_launcher import GatewayLauncher from adf_core_python.core.launcher.config_key import ConfigKey from adf_core_python.core.launcher.connect.component_launcher import ComponentLauncher from adf_core_python.core.launcher.connect.connector import Connector @@ -22,6 +25,7 @@ def __init__(self) -> None: def connect( self, component_launcher: ComponentLauncher, + gateway_launcher: Optional[GatewayLauncher], config: Config, loader: AbstractLoader, ) -> dict[threading.Thread, threading.Event]: @@ -53,9 +57,21 @@ def connect( precompute_data_dir: str = f"{config.get_value(ConfigKey.KEY_PRECOMPUTE_DATA_DIR, 'precompute')}/fire_station" - request_id: int = component_launcher.generate_request_id() finish_post_connect_event = threading.Event() - thread = threading.Thread( + request_id: int = component_launcher.generate_request_id() + + gateway_agent: Optional[GatewayAgent] = None + if isinstance(gateway_launcher, GatewayLauncher): + gateway_agent = GatewayAgent(gateway_launcher) + if isinstance(gateway_agent, GatewayAgent): + gateway_thread = threading.Thread( + target=gateway_launcher.connect, + args=(gateway_agent,), + ) + gateway_thread.daemon = True + gateway_thread.start() + + component_thread = threading.Thread( target=component_launcher.connect, args=( OfficeFire( @@ -67,11 +83,12 @@ def connect( module_config, develop_data, finish_post_connect_event, + gateway_agent, ), request_id, ), name=f"FireStationAgent-{request_id}", ) - threads[thread] = finish_post_connect_event + threads[component_thread] = finish_post_connect_event return threads diff --git a/adf_core_python/core/launcher/connect/connector_police_force.py b/adf_core_python/core/launcher/connect/connector_police_force.py index e17fe76..e2d379b 100644 --- a/adf_core_python/core/launcher/connect/connector_police_force.py +++ b/adf_core_python/core/launcher/connect/connector_police_force.py @@ -1,4 +1,5 @@ import threading +from typing import Optional from adf_core_python.core.agent.config.module_config import ModuleConfig from adf_core_python.core.agent.develop.develop_data import DevelopData @@ -8,6 +9,8 @@ TacticsPoliceForce, ) from adf_core_python.core.config.config import Config +from adf_core_python.core.gateway.gateway_agent import GatewayAgent +from adf_core_python.core.gateway.gateway_launcher import GatewayLauncher from adf_core_python.core.launcher.config_key import ConfigKey from adf_core_python.core.launcher.connect.component_launcher import ComponentLauncher from adf_core_python.core.launcher.connect.connector import Connector @@ -22,6 +25,7 @@ def __init__(self) -> None: def connect( self, component_launcher: ComponentLauncher, + gateway_launcher: Optional[GatewayLauncher], config: Config, loader: AbstractLoader, ) -> dict[threading.Thread, threading.Event]: @@ -53,9 +57,21 @@ def connect( precompute_data_dir: str = f"{config.get_value(ConfigKey.KEY_PRECOMPUTE_DATA_DIR, 'precompute')}/police_force" - request_id: int = component_launcher.generate_request_id() finish_post_connect_event = threading.Event() - thread = threading.Thread( + request_id: int = component_launcher.generate_request_id() + + gateway_agent: Optional[GatewayAgent] = None + if isinstance(gateway_launcher, GatewayLauncher): + gateway_agent = GatewayAgent(gateway_launcher) + if isinstance(gateway_agent, GatewayAgent): + gateway_thread = threading.Thread( + target=gateway_launcher.connect, + args=(gateway_agent,), + ) + gateway_thread.daemon = True + gateway_thread.start() + + component_thread = threading.Thread( target=component_launcher.connect, args=( PlatoonPolice( @@ -67,11 +83,12 @@ def connect( module_config, develop_data, finish_post_connect_event, + gateway_agent, ), request_id, ), name=f"PoliceForceAgent-{request_id}", ) - threads[thread] = finish_post_connect_event + threads[component_thread] = finish_post_connect_event return threads diff --git a/adf_core_python/core/launcher/connect/connector_police_office.py b/adf_core_python/core/launcher/connect/connector_police_office.py index 52c3aac..1d26a92 100644 --- a/adf_core_python/core/launcher/connect/connector_police_office.py +++ b/adf_core_python/core/launcher/connect/connector_police_office.py @@ -1,4 +1,5 @@ import threading +from typing import Optional from adf_core_python.core.agent.config.module_config import ModuleConfig from adf_core_python.core.agent.develop.develop_data import DevelopData @@ -8,6 +9,8 @@ TacticsPoliceOffice, ) from adf_core_python.core.config.config import Config +from adf_core_python.core.gateway.gateway_agent import GatewayAgent +from adf_core_python.core.gateway.gateway_launcher import GatewayLauncher from adf_core_python.core.launcher.config_key import ConfigKey from adf_core_python.core.launcher.connect.component_launcher import ComponentLauncher from adf_core_python.core.launcher.connect.connector import Connector @@ -22,6 +25,7 @@ def __init__(self) -> None: def connect( self, component_launcher: ComponentLauncher, + gateway_launcher: Optional[GatewayLauncher], config: Config, loader: AbstractLoader, ) -> dict[threading.Thread, threading.Event]: @@ -55,9 +59,21 @@ def connect( precompute_data_dir: str = f"{config.get_value(ConfigKey.KEY_PRECOMPUTE_DATA_DIR, 'precompute')}/police_office" - request_id: int = component_launcher.generate_request_id() finish_post_connect_event = threading.Event() - thread = threading.Thread( + request_id: int = component_launcher.generate_request_id() + + gateway_agent: Optional[GatewayAgent] = None + if isinstance(gateway_launcher, GatewayLauncher): + gateway_agent = GatewayAgent(gateway_launcher) + if isinstance(gateway_agent, GatewayAgent): + gateway_thread = threading.Thread( + target=gateway_launcher.connect, + args=(gateway_agent,), + ) + gateway_thread.daemon = True + gateway_thread.start() + + component_thread = threading.Thread( target=component_launcher.connect, args=( OfficePolice( @@ -69,11 +85,12 @@ def connect( module_config, develop_data, finish_post_connect_event, + gateway_agent, ), request_id, ), name=f"PoliceOfficeAgent-{request_id}", ) - threads[thread] = finish_post_connect_event + threads[component_thread] = finish_post_connect_event return threads diff --git a/adf_core_python/implement/action/default_extend_action_clear.py b/adf_core_python/implement/action/default_extend_action_clear.py index d23c8d1..b3e3bb0 100644 --- a/adf_core_python/implement/action/default_extend_action_clear.py +++ b/adf_core_python/implement/action/default_extend_action_clear.py @@ -541,7 +541,7 @@ def _is_intersecting_blockades( if line1.intersects(line2): return True - for i in range(0, len(apexes1) - 2, 2): + for i in range(0, len(apexes2) - 2, 2): line1 = LineString([(apexes1[-2], apexes1[-1]), (apexes1[0], apexes1[1])]) line2 = LineString( [(apexes2[i], apexes2[i + 1]), (apexes2[i + 2], apexes2[i + 3])] diff --git a/adf_core_python/implement/tactics/default_tactics_ambulance_team.py b/adf_core_python/implement/tactics/default_tactics_ambulance_team.py index 83d0cdf..2ae7158 100644 --- a/adf_core_python/implement/tactics/default_tactics_ambulance_team.py +++ b/adf_core_python/implement/tactics/default_tactics_ambulance_team.py @@ -39,18 +39,19 @@ def initialize( message_manager, develop_data, ) + self._search: Search = cast( Search, module_manager.get_module( "DefaultTacticsAmbulanceTeam.Search", - "adf_core_python.core.component.module.complex.search.Search", + "adf_core_python.implement.module.complex.default_search.DefaultSearch", ), ) self._human_detector: HumanDetector = cast( HumanDetector, module_manager.get_module( "DefaultTacticsAmbulanceTeam.HumanDetector", - "adf_core_python.core.component.module.complex.human_detector.HumanDetector", + "adf_core_python.implement.module.complex.default_human_detector.DefaultHumanDetector", ), ) self._action_transport = module_manager.get_extend_action( @@ -61,6 +62,7 @@ def initialize( "DefaultTacticsAmbulanceTeam.ExtendActionMove", "adf_core_python.implement.action.default_extend_action_move.DefaultExtendActionMove", ) + self.register_module(self._search) self.register_module(self._human_detector) self.register_action(self._action_transport) diff --git a/adf_core_python/implement/tactics/default_tactics_fire_brigade.py b/adf_core_python/implement/tactics/default_tactics_fire_brigade.py index d0f8512..e4e09ec 100644 --- a/adf_core_python/implement/tactics/default_tactics_fire_brigade.py +++ b/adf_core_python/implement/tactics/default_tactics_fire_brigade.py @@ -44,14 +44,14 @@ def initialize( Search, module_manager.get_module( "DefaultTacticsFireBrigade.Search", - "adf_core_python.core.component.module.complex.search.Search", + "adf_core_python.implement.module.complex.default_search.DefaultSearch", ), ) self._human_detector: HumanDetector = cast( HumanDetector, module_manager.get_module( "DefaultTacticsFireBrigade.HumanDetector", - "adf_core_python.core.component.module.complex.human_detector.HumanDetector", + "adf_core_python.implement.module.complex.default_human_detector.DefaultHumanDetector", ), ) self._action_rescue = module_manager.get_extend_action( @@ -62,6 +62,7 @@ def initialize( "DefaultTacticsAmbulanceTeam.ExtendActionMove", "adf_core_python.implement.action.default_extend_action_move.DefaultExtendActionMove", ) + self.register_module(self._search) self.register_module(self._human_detector) self.register_action(self._action_rescue) diff --git a/adf_core_python/implement/tactics/default_tactics_police_force.py b/adf_core_python/implement/tactics/default_tactics_police_force.py index 63836a3..bec3434 100644 --- a/adf_core_python/implement/tactics/default_tactics_police_force.py +++ b/adf_core_python/implement/tactics/default_tactics_police_force.py @@ -47,7 +47,7 @@ def initialize( Search, module_manager.get_module( "DefaultTacticsPoliceForce.Search", - "adf_core_python.core.component.module.complex.search.Search", + "adf_core_python.implement.module.complex.default_search.DefaultSearch", ), ) self._road_detector: RoadDetector = cast( @@ -65,6 +65,7 @@ def initialize( "DefaultTacticsPoliceForce.ExtendActionMove", "adf_core_python.implement.action.default_extend_action_move.DefaultExtendActionMove", ) + self.register_module(self._search) self.register_module(self._road_detector) self.register_action(self._action_ext_clear) diff --git a/adf_core_python/launcher.py b/adf_core_python/launcher.py index bd2025d..89cb927 100644 --- a/adf_core_python/launcher.py +++ b/adf_core_python/launcher.py @@ -78,6 +78,11 @@ def __init__( help="precompute flag", ) parser.add_argument("--debug", action="store_true", help="debug flag") + parser.add_argument( + "--java", + action="store_true", + help="using java module flag", + ) args = parser.parse_args() config_map = { @@ -91,6 +96,7 @@ def __init__( ConfigKey.KEY_POLICE_OFFICE_COUNT: args.policeoffice, ConfigKey.KEY_PRECOMPUTE: args.precompute, ConfigKey.KEY_DEBUG_FLAG: args.debug, + ConfigKey.KEY_GATEWAY_FLAG: args.java, } for key, value in config_map.items(): diff --git a/config/launcher.yaml b/config/launcher.yaml index 7702d17..7423a6c 100644 --- a/config/launcher.yaml +++ b/config/launcher.yaml @@ -2,6 +2,10 @@ kernel: host: localhost port: 27931 +gateway: + host: localhost + port: 27941 + team: name: AIT-Rescue @@ -35,3 +39,6 @@ adf: count: 5 police: count: 5 + + gateway: + flag: false diff --git a/java/.gitattributes b/java/.gitattributes new file mode 100644 index 0000000..f91f646 --- /dev/null +++ b/java/.gitattributes @@ -0,0 +1,12 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + +# Binary files should be left untouched +*.jar binary + diff --git a/java/.gitignore b/java/.gitignore new file mode 100644 index 0000000..4158e07 --- /dev/null +++ b/java/.gitignore @@ -0,0 +1,7 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build + +!lib \ No newline at end of file diff --git a/java/gradle/libs.versions.toml b/java/gradle/libs.versions.toml new file mode 100644 index 0000000..81f6352 --- /dev/null +++ b/java/gradle/libs.versions.toml @@ -0,0 +1,12 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format + +[versions] +commons-math3 = "3.6.1" +guava = "33.2.1-jre" +junit-jupiter = "5.10.3" + +[libraries] +commons-math3 = { module = "org.apache.commons:commons-math3", version.ref = "commons-math3" } +guava = { module = "com.google.guava:guava", version.ref = "guava" } +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit-jupiter" } diff --git a/java/gradle/wrapper/gradle-wrapper.jar b/java/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/java/gradle/wrapper/gradle-wrapper.jar differ diff --git a/java/gradle/wrapper/gradle-wrapper.properties b/java/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..df97d72 --- /dev/null +++ b/java/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/java/gradlew b/java/gradlew new file mode 100755 index 0000000..f5feea6 --- /dev/null +++ b/java/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/java/gradlew.bat b/java/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/java/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/java/lib/build.gradle b/java/lib/build.gradle new file mode 100644 index 0000000..3aae4e5 --- /dev/null +++ b/java/lib/build.gradle @@ -0,0 +1,53 @@ +plugins { + id('java-library') + id('com.google.protobuf') version "0.9.4" +} + +repositories { + mavenCentral() + + maven { + url = 'https://sourceforge.net/projects/jsi/files/m2_repo' + } + maven { + url = 'https://repo.enonic.com/public/' + } + maven { + url 'https://jitpack.io' + } +} + +dependencies { + implementation 'com.github.roborescue:rcrs-server:master-SNAPSHOT' + implementation 'com.github.roborescue:adf-core-java:master-SNAPSHOT' + + // PrecomputeData + implementation 'com.fasterxml.jackson.core:jackson-annotations:2.13.0' + implementation 'com.fasterxml.jackson.core:jackson-core:2.13.0' + implementation 'com.fasterxml.jackson.core:jackson-databind:2.18.1' + implementation 'org.msgpack:jackson-dataformat-msgpack:0.9.0' + implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.18.1' + + // Protobuf + implementation 'com.google.protobuf:protobuf-java:3.19.1' + + // Annotation + implementation 'jakarta.annotation:jakarta.annotation-api:3.0.0' + + // Logger + implementation 'org.apache.logging.log4j:log4j-core:2.24.2' + implementation 'org.apache.logging.log4j:log4j-api:2.24.2' + + testImplementation libs.junit.jupiter + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/java/lib/src/main/java/adf_core_python/Main.java b/java/lib/src/main/java/adf_core_python/Main.java new file mode 100644 index 0000000..d6fbd5f --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/Main.java @@ -0,0 +1,10 @@ +package adf_core_python; + +import adf_core_python.gateway.Gateway; + +public class Main { + public static void main(String[] args) { + Gateway gateway = new Gateway(27941); + gateway.start(); + } +} diff --git a/java/lib/src/main/java/adf_core_python/agent/Agent.java b/java/lib/src/main/java/adf_core_python/agent/Agent.java new file mode 100644 index 0000000..07c9f0a --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/agent/Agent.java @@ -0,0 +1,116 @@ +package adf_core_python.agent; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.config.ModuleConfig; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.AbstractModule; +import adf_core_python.gateway.mapper.AbstractMapper; +import adf_core_python.gateway.mapper.MapperDict; +import jakarta.annotation.Nonnull; +import jakarta.annotation.Nullable; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import rescuecore2.config.Config; +import rescuecore2.messages.Command; +import rescuecore2.standard.entities.StandardEntityURN; +import rescuecore2.standard.entities.StandardWorldModel; +import rescuecore2.worldmodel.ChangeSet; +import rescuecore2.worldmodel.Entity; +import rescuecore2.worldmodel.EntityID; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Objects; + +public class Agent { + private final AgentInfo agentInfo; + private final WorldInfo worldInfo; + private final ScenarioInfo scenarioInfo; + private final ModuleManager moduleManager; + private final DevelopData developData; + private final PrecomputeData precomputeData; + private final MessageManager messageManager; + private final HashMap modules = new HashMap<>(); + private final MapperDict mapperDict; + private final Logger logger; + + public Agent(EntityID entityID, Collection entities, ScenarioInfo scenarioInfo, DevelopData developData, ModuleConfig moduleConfig) { + StandardWorldModel worldModel = new StandardWorldModel(); + worldModel.addEntities(entities); + worldModel.index(); + + this.agentInfo = new AgentInfo(entityID, worldModel); + this.worldInfo = new WorldInfo(worldModel); + this.scenarioInfo = scenarioInfo; + this.developData = developData; + this.moduleManager = new ModuleManager(this.agentInfo, this.worldInfo, this.scenarioInfo, moduleConfig, this.developData); + + String dataStorageName = ""; + StandardEntityURN agentURN = Objects.requireNonNull(this.worldInfo.getEntity(this.agentInfo.getID())).getStandardURN(); + if (agentURN == StandardEntityURN.AMBULANCE_TEAM || agentURN == StandardEntityURN.AMBULANCE_CENTRE) { + dataStorageName = "ambulance.bin"; + } + if (agentURN == StandardEntityURN.FIRE_BRIGADE || agentURN == StandardEntityURN.FIRE_STATION) { + dataStorageName = "fire.bin"; + } + if (agentURN == StandardEntityURN.POLICE_FORCE || agentURN == StandardEntityURN.POLICE_OFFICE) { + dataStorageName = "police.bin"; + } + + this.precomputeData = new PrecomputeData(dataStorageName); + this.messageManager = new MessageManager(); + + this.mapperDict = new MapperDict(); + + logger = LogManager.getLogger(this.getClass()); + logger.debug("New Agent Created (EntityID: {}, All Entities: {})", this.agentInfo.getID(), this.worldInfo.getAllEntities()); + } + + public Class registerModule(@Nonnull String moduleID, @Nonnull String moduleName, @Nullable String defaultClassName) { + AbstractModule abstractModule = moduleManager.getModule(moduleName, defaultClassName); + if (abstractModule == null) return null; + Class clazz = abstractModule.getClass(); + while (clazz.getSuperclass() != null) { + if (mapperDict.getMapper(clazz) != null) { + Class mapperClass = mapperDict.getMapper(clazz); + try { + Constructor constructor = mapperClass.getConstructor(clazz, precomputeData.getClass(), messageManager.getClass()); + AbstractMapper mapperInstance = constructor.newInstance(abstractModule, precomputeData, messageManager); + modules.put(moduleID, mapperInstance); + logger.debug("Registered Human Detector (ModuleID: {}, Instance: {})", moduleID, modules.get(moduleID)); + return mapperInstance.getTargetClass(); + } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | + InvocationTargetException e) { + throw new RuntimeException(e); + } + } + clazz = clazz.getSuperclass(); + } + return null; + } + + public void update(int time, ChangeSet changed, Collection heard) { + agentInfo.recordThinkStartTime(); + agentInfo.setTime(time); + agentInfo.setHeard(heard); + agentInfo.setChanged(changed); + worldInfo.setTime(time); + worldInfo.merge(changed); + worldInfo.setChanged(changed); + logger.debug("Agent Update (Time: {}, Changed: {}, Heard: {})", agentInfo.getTime(), agentInfo.getChanged(), agentInfo.getHeard()); + } + + public Config execModuleMethod(String moduleID, String methodName, Config arguments) { + logger.debug("Executing Method (MethodName: {}, Arguments: {}", methodName, arguments); + Config result = modules.get(moduleID).execMethod(methodName, arguments); + logger.debug("Executed Method Result (MethodName: {}, Result: {}", methodName, result); + return result; + } +} diff --git a/java/lib/src/main/java/adf_core_python/agent/config/ModuleConfig.java b/java/lib/src/main/java/adf_core_python/agent/config/ModuleConfig.java new file mode 100644 index 0000000..3232d7a --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/agent/config/ModuleConfig.java @@ -0,0 +1,39 @@ +package adf_core_python.agent.config; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +public class ModuleConfig { + private static final String DEFAULT_CONFIG_FILE_NAME = "../config/module.yaml"; + private final JsonNode rootNode; + + public ModuleConfig() { + this(DEFAULT_CONFIG_FILE_NAME); + } + + public ModuleConfig(String configFileName) { + try { + String yamlString = Files.readString(Paths.get(configFileName)); + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + rootNode = mapper.readTree(yamlString); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public String getValue(String moduleName) { + String[] keys = moduleName.split("\\."); + JsonNode moduleNode = rootNode; + for (String key : keys) { + if (moduleNode.has(key)) { + moduleNode = moduleNode.get(key); + } + } + return moduleNode.asText(); + } +} diff --git a/java/lib/src/main/java/adf_core_python/agent/develop/DevelopData.java b/java/lib/src/main/java/adf_core_python/agent/develop/DevelopData.java new file mode 100644 index 0000000..00652e6 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/agent/develop/DevelopData.java @@ -0,0 +1,40 @@ +package adf_core_python.agent.develop; + +import jakarta.annotation.Nonnull; + +import java.util.List; +import java.util.Map; + +public class DevelopData { + private boolean developFlag = false; + + private Map intValues; + private Map doubleValues; + private Map stringValues; + private Map boolValues; + + private Map> intLists; + private Map> doubleLists; + private Map> stringLists; + private Map> boolLists; + + @Nonnull + public Integer getInteger(@Nonnull String name, int defaultValue) { + if (this.developFlag) { + Integer value = this.intValues.get(name); + if (value == null) { + String rawData = this.stringValues.get(name); + if (rawData != null && !rawData.equals("")) { + value = Integer.valueOf(rawData); + } + if (value != null) { + this.intValues.put(name, value); + } + } + if (value != null) { + return value; + } + } + return defaultValue; + } +} diff --git a/java/lib/src/main/java/adf_core_python/agent/info/AgentInfo.java b/java/lib/src/main/java/adf_core_python/agent/info/AgentInfo.java new file mode 100644 index 0000000..e0d63d1 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/agent/info/AgentInfo.java @@ -0,0 +1,119 @@ +package adf_core_python.agent.info; + +import adf.core.agent.action.Action; +import jakarta.annotation.Nonnull; +import jakarta.annotation.Nullable; +import rescuecore2.messages.Command; +import rescuecore2.standard.entities.*; +import rescuecore2.worldmodel.ChangeSet; +import rescuecore2.worldmodel.EntityID; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +public class AgentInfo { + private final EntityID entityID; + private final StandardWorldModel worldModel; + private int time; + private ChangeSet changed; + private Collection heard; + private long thinkStartTime; + + private Map actionHistory; + + public AgentInfo(@Nonnull EntityID entityID, @Nonnull StandardWorldModel worldModel) { + this.entityID = entityID; + this.worldModel = worldModel; + this.time = 0; + this.actionHistory = new HashMap<>(); + recordThinkStartTime(); + } + + public int getTime() { + return this.time; + } + + public void setTime(int time) { + this.time = time; + } + + @Nullable + public Collection getHeard() { + return this.heard; + } + + public void setHeard(Collection heard) { + this.heard = heard; + } + + @Nonnull + public EntityID getID() { + return this.entityID; + } + + public StandardEntity me() { + return this.worldModel.getEntity(this.getID()); + } + + public double getX() { + return this.worldModel.getEntity(this.entityID).getLocation(this.worldModel).first(); + } + + public double getY() { + return this.worldModel.getEntity(this.entityID).getLocation(this.worldModel).second(); + } + + public EntityID getPosition() { + StandardEntity entity = this.worldModel.getEntity(this.getID()); + return entity instanceof Human ? ((Human) entity).getPosition() : entity.getID(); + } + + @Nonnull + public Area getPositionArea() { + return (Area) this.worldModel.getEntity(this.getPosition()); + } + + @Nullable + public ChangeSet getChanged() { + return this.changed; + } + + public void setChanged(ChangeSet changed) { + this.changed = changed; + } + + @Nullable + public Human someoneOnBoard() { + + for (StandardEntity next : this.worldModel + .getEntitiesOfType(StandardEntityURN.CIVILIAN)) { + Human human = (Human) next; + if (human.getPosition().equals(this.entityID)) { + return human; + } + } + + return null; + } + + @Nullable + public Action getExecutedAction(int time) { + if (time > 0) + return this.actionHistory.get(time); + return this.actionHistory.get(this.getTime() + time); + } + + + public void setExecutedAction(int time, @Nullable Action action) { + this.actionHistory.put(time > 0 ? time : this.getTime() + time, action); + } + + public void recordThinkStartTime() { + this.thinkStartTime = System.currentTimeMillis(); + } + + public long getThinkTimeMillis() { + return (System.currentTimeMillis() - this.thinkStartTime); + } +} diff --git a/java/lib/src/main/java/adf_core_python/agent/module/ModuleManager.java b/java/lib/src/main/java/adf_core_python/agent/module/ModuleManager.java new file mode 100644 index 0000000..abc0621 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/agent/module/ModuleManager.java @@ -0,0 +1,427 @@ +package adf_core_python.agent.module; + +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf.core.component.centralized.CommandExecutor; +import adf.core.component.centralized.CommandPicker; +import adf.core.component.communication.ChannelSubscriber; +import adf.core.component.communication.CommunicationMessage; +import adf.core.component.communication.MessageCoordinator; +import adf.core.component.extaction.ExtAction; +import adf_core_python.agent.config.ModuleConfig; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.component.module.AbstractModule; +import jakarta.annotation.Nonnull; +import jakarta.annotation.Nullable; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import rescuecore2.config.NoSuchConfigOptionException; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; + +public class ModuleManager { + private final Logger logger; + private Map moduleMap; + private Map actionMap; + private Map> executorMap; + private Map pickerMap; + private Map channelSubscriberMap; + private Map messageCoordinatorMap; + private AgentInfo agentInfo; + private WorldInfo worldInfo; + private ScenarioInfo scenarioInfo; + private ModuleConfig moduleConfig; + private DevelopData developData; + + public ModuleManager(@Nonnull AgentInfo agentInfo, @Nonnull WorldInfo worldInfo, @Nonnull ScenarioInfo scenarioInfo, @Nonnull ModuleConfig moduleConfig, @Nonnull DevelopData developData) { + this.agentInfo = agentInfo; + this.worldInfo = worldInfo; + this.scenarioInfo = scenarioInfo; + this.moduleConfig = moduleConfig; + this.developData = developData; + this.moduleMap = new HashMap<>(); + this.actionMap = new HashMap<>(); + this.executorMap = new HashMap<>(); + this.pickerMap = new HashMap<>(); + this.channelSubscriberMap = new HashMap<>(1); + this.messageCoordinatorMap = new HashMap<>(1); + + logger = LogManager.getLogger(this.getClass()); + } + + @SuppressWarnings("unchecked") + @Nullable + public final T + getModule(@Nonnull String moduleName, @Nullable String defaultClassName) { + String className = moduleName; + try { + className = this.moduleConfig.getValue(moduleName); + } catch (NoSuchConfigOptionException ignored) { + } + + try { + Class moduleClass; + try { + moduleClass = Class.forName(className); + } catch (ClassNotFoundException | NullPointerException e) { + logger.warn("Module " + moduleName + " not found. Using default class " + defaultClassName); + className = defaultClassName; + moduleClass = Class.forName(className); + } + + AbstractModule instance = this.moduleMap.get(className); + if (instance != null) { + return (T) instance; + } + + if (AbstractModule.class.isAssignableFrom(moduleClass)) { + instance = this.getModule((Class) moduleClass); + this.moduleMap.put(className, instance); + return (T) instance; + } + + } catch (ClassNotFoundException | NullPointerException e) { + return null; + } + + throw new IllegalArgumentException( + "Module name is not found : " + className); + } + + + @Nonnull + public final T + getModule(@Nonnull String moduleName) { + return this.getModule(moduleName, ""); + } + + + @Nonnull + private AbstractModule getModule(@Nonnull Class moduleClass) { + try { + Constructor constructor = moduleClass.getConstructor( + AgentInfo.class, WorldInfo.class, ScenarioInfo.class, + ModuleManager.class, DevelopData.class); + AbstractModule instance = constructor.newInstance(this.agentInfo, + this.worldInfo, this.scenarioInfo, this, this.developData); + this.moduleMap.put(moduleClass.getCanonicalName(), instance); + return instance; + } catch (NoSuchMethodException | InstantiationException + | IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + + @SuppressWarnings("unchecked") + @Nonnull + public final ExtAction getExtAction(String actionName, + String defaultClassName) { + String className = actionName; + try { + className = this.moduleConfig.getValue(actionName); + } catch (NoSuchConfigOptionException ignored) { + } + + try { + Class actionClass; + try { + actionClass = Class.forName(className); + } catch (ClassNotFoundException | NullPointerException e) { + className = defaultClassName; + actionClass = Class.forName(className); + } + + ExtAction instance = this.actionMap.get(className); + if (instance != null) { + return instance; + } + + if (ExtAction.class.isAssignableFrom(actionClass)) { + instance = this.getExtAction((Class) actionClass); + this.actionMap.put(className, instance); + return instance; + } + } catch (ClassNotFoundException | NullPointerException e) { + throw new RuntimeException(e); + } + throw new IllegalArgumentException( + "ExtAction name is not found : " + className); + } + + + @Nonnull + public final ExtAction getExtAction(String actionName) { + return getExtAction(actionName, ""); + } + + + @Nonnull + private ExtAction getExtAction(Class actionClass) { + try { + Constructor constructor = actionClass.getConstructor( + AgentInfo.class, WorldInfo.class, ScenarioInfo.class, + ModuleManager.class, DevelopData.class); + ExtAction instance = constructor.newInstance(this.agentInfo, + this.worldInfo, this.scenarioInfo, this, this.developData); + this.actionMap.put(actionClass.getCanonicalName(), instance); + return instance; + } catch (NoSuchMethodException | InstantiationException + | IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + + @SuppressWarnings("unchecked") + @Nonnull + public final > E + getCommandExecutor(String executorName, String defaultClassName) { + String className = executorName; + try { + className = this.moduleConfig.getValue(executorName); + } catch (NoSuchConfigOptionException ignored) { + } + + try { + Class actionClass; + try { + actionClass = Class.forName(className); + } catch (ClassNotFoundException | NullPointerException e) { + className = defaultClassName; + actionClass = Class.forName(className); + } + + CommandExecutor< + CommunicationMessage> instance = this.executorMap.get(className); + if (instance != null) { + return (E) instance; + } + + if (CommandExecutor.class.isAssignableFrom(actionClass)) { + instance = this.getCommandExecutor( + (Class>) actionClass); + this.executorMap.put(className, instance); + return (E) instance; + } + } catch (ClassNotFoundException | NullPointerException e) { + throw new RuntimeException(e); + } + + throw new IllegalArgumentException( + "CommandExecutor name is not found : " + className); + } + + + @Nonnull + public final > E + getCommandExecutor(String executorName) { + return getCommandExecutor(executorName, ""); + } + + + @SuppressWarnings("unchecked") + @Nonnull + private > E + getCommandExecutor(Class actionClass) { + try { + Constructor constructor = actionClass.getConstructor(AgentInfo.class, + WorldInfo.class, ScenarioInfo.class, ModuleManager.class, + DevelopData.class); + E instance = constructor.newInstance(this.agentInfo, this.worldInfo, + this.scenarioInfo, this, this.developData); + this.executorMap.put(actionClass.getCanonicalName(), + (CommandExecutor) instance); + return instance; + } catch (NoSuchMethodException | InstantiationException + | IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + + @SuppressWarnings("unchecked") + @Nonnull + public final CommandPicker getCommandPicker(String pickerName, + String defaultClassName) { + String className = pickerName; + try { + className = this.moduleConfig.getValue(pickerName); + } catch (NoSuchConfigOptionException ignored) { + } + + try { + Class actionClass; + try { + actionClass = Class.forName(className); + } catch (ClassNotFoundException | NullPointerException e) { + className = defaultClassName; + actionClass = Class.forName(className); + } + + CommandPicker instance = this.pickerMap.get(className); + if (instance != null) { + return instance; + } + + if (CommandPicker.class.isAssignableFrom(actionClass)) { + instance = this.getCommandPicker((Class) actionClass); + this.pickerMap.put(className, instance); + return instance; + } + } catch (ClassNotFoundException | NullPointerException e) { + throw new RuntimeException(e); + } + + throw new IllegalArgumentException( + "CommandExecutor name is not found : " + className); + } + + + @Nonnull + public final CommandPicker getCommandPicker(String pickerName) { + return getCommandPicker(pickerName, ""); + } + + + @Nonnull + private CommandPicker getCommandPicker(Class actionClass) { + try { + Constructor constructor = actionClass.getConstructor( + AgentInfo.class, WorldInfo.class, ScenarioInfo.class, + ModuleManager.class, DevelopData.class); + CommandPicker instance = constructor.newInstance(this.agentInfo, + this.worldInfo, this.scenarioInfo, this, this.developData); + this.pickerMap.put(actionClass.getCanonicalName(), instance); + return instance; + } catch (NoSuchMethodException | InstantiationException + | IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + + @SuppressWarnings("unchecked") + public final ChannelSubscriber getChannelSubscriber(String subscriberName, + String defaultClassName) { + String className = subscriberName; + try { + className = this.moduleConfig.getValue(subscriberName); + } catch (NoSuchConfigOptionException ignored) { + } + + try { + Class actionClass; + try { + actionClass = Class.forName(className); + } catch (ClassNotFoundException | NullPointerException e) { + className = defaultClassName; + actionClass = Class.forName(className); + } + + ChannelSubscriber instance = this.channelSubscriberMap.get(className); + if (instance != null) { + return instance; + } + + if (ChannelSubscriber.class.isAssignableFrom(actionClass)) { + instance = this + .getChannelSubscriber((Class) actionClass); + this.channelSubscriberMap.put(className, instance); + return instance; + } + } catch (ClassNotFoundException | NullPointerException e) { + throw new RuntimeException(e); + } + + throw new IllegalArgumentException( + "channelSubscriber name is not found : " + className); + } + + + public final ChannelSubscriber getChannelSubscriber(String subscriberName) { + return getChannelSubscriber(subscriberName, ""); + } + + + public final ChannelSubscriber + getChannelSubscriber(Class subsClass) { + try { + Constructor constructor = subsClass.getConstructor(); + ChannelSubscriber instance = constructor.newInstance(); + this.channelSubscriberMap.put(subsClass.getCanonicalName(), instance); + return instance; + } catch (NoSuchMethodException | InstantiationException + | IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + + @SuppressWarnings("unchecked") + public final MessageCoordinator getMessageCoordinator(String coordinatorName, + String defaultClassName) { + String className = coordinatorName; + try { + className = this.moduleConfig.getValue(coordinatorName); + } catch (NoSuchConfigOptionException ignored) { + } + + try { + Class actionClass; + try { + actionClass = Class.forName(className); + } catch (ClassNotFoundException | NullPointerException e) { + className = defaultClassName; + actionClass = Class.forName(className); + } + + MessageCoordinator instance = this.messageCoordinatorMap.get(className); + if (instance != null) { + return instance; + } + + if (MessageCoordinator.class.isAssignableFrom(actionClass)) { + instance = this + .getMessageCoordinator((Class) actionClass); + this.messageCoordinatorMap.put(className, instance); + return instance; + } + } catch (ClassNotFoundException | NullPointerException e) { + throw new RuntimeException(e); + } + + throw new IllegalArgumentException( + "channelSubscriber name is not found : " + className); + } + + + public final MessageCoordinator + getMessageCoordinator(String coordinatorName) { + return getMessageCoordinator(coordinatorName, ""); + } + + + public final MessageCoordinator + getMessageCoordinator(Class subsClass) { + try { + Constructor constructor = subsClass.getConstructor(); + MessageCoordinator instance = constructor.newInstance(); + this.messageCoordinatorMap.put(subsClass.getCanonicalName(), instance); + return instance; + } catch (NoSuchMethodException | InstantiationException + | IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + + @Nonnull + public ModuleConfig getModuleConfig() { + return this.moduleConfig; + } +} diff --git a/java/lib/src/main/java/adf_core_python/agent/precompute/PreData.java b/java/lib/src/main/java/adf_core_python/agent/precompute/PreData.java new file mode 100644 index 0000000..847b4f7 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/agent/precompute/PreData.java @@ -0,0 +1,56 @@ +package adf_core_python.agent.precompute; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public final class PreData { + + public Map intValues; + public Map doubleValues; + public Map stringValues; + public Map idValues; + public Map boolValues; + + public Map> intLists; + public Map> doubleLists; + public Map> stringLists; + public Map> idLists; + public Map> boolLists; + + public boolean isReady; + public String readyID; + + public PreData() { + this.intValues = new HashMap<>(); + this.doubleValues = new HashMap<>(); + this.stringValues = new HashMap<>(); + this.idValues = new HashMap<>(); + this.boolValues = new HashMap<>(); + this.intLists = new HashMap<>(); + this.doubleLists = new HashMap<>(); + this.stringLists = new HashMap<>(); + this.idLists = new HashMap<>(); + this.boolLists = new HashMap<>(); + this.isReady = false; + this.readyID = ""; + } + + + public PreData copy() { + PreData preData = new PreData(); + preData.intValues = new HashMap<>(this.intValues); + preData.doubleValues = new HashMap<>(this.doubleValues); + preData.stringValues = new HashMap<>(this.stringValues); + preData.idValues = new HashMap<>(this.idValues); + preData.boolValues = new HashMap<>(this.boolValues); + preData.intLists = new HashMap<>(this.intLists); + preData.doubleLists = new HashMap<>(this.doubleLists); + preData.stringLists = new HashMap<>(this.stringLists); + preData.idLists = new HashMap<>(this.idLists); + preData.boolLists = new HashMap<>(this.boolLists); + preData.isReady = this.isReady; + preData.readyID = this.readyID; + return preData; + } +} diff --git a/java/lib/src/main/java/adf_core_python/agent/precompute/PrecomputeData.java b/java/lib/src/main/java/adf_core_python/agent/precompute/PrecomputeData.java new file mode 100644 index 0000000..d838c68 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/agent/precompute/PrecomputeData.java @@ -0,0 +1,400 @@ +package adf_core_python.agent.precompute; + +import adf.core.agent.info.WorldInfo; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.msgpack.jackson.dataformat.MessagePackFactory; +import rescuecore2.worldmodel.EntityID; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public final class PrecomputeData { + + public static final String DEFAULT_FILE_NAME = "data.bin"; + public static final File PRECOMP_DATA_DIR = new File("precomp_data"); + + private final String fileName; + + private PreData data; + + public PrecomputeData() { + this(DEFAULT_FILE_NAME); + } + + + public PrecomputeData(String name) { + this.fileName = name; + this.init(); + } + + + private PrecomputeData(String name, PreData precomputeDatas) { + this.fileName = name; + this.data = precomputeDatas; + } + + + public static void removeData(String name) { + if (!PRECOMP_DATA_DIR.exists()) { + return; + } + + File file = new File(PRECOMP_DATA_DIR, name); + if (!file.exists()) { + return; + } + + file.delete(); + } + + + public static void removeData() { + removeData(DEFAULT_FILE_NAME); + } + + + public PrecomputeData copy() { + return new PrecomputeData(this.fileName, this.data.copy()); + } + + + private void init() { + this.data = this.read(this.fileName); + if (this.data == null) { + this.data = new PreData(); + } + } + + + private PreData read(String name) { + try { + if (!PRECOMP_DATA_DIR.exists()) { + if (!PRECOMP_DATA_DIR.mkdir()) { + return null; + } + } + + File readFile = new File(PRECOMP_DATA_DIR, name); + if (!readFile.exists()) { + return null; + } + + FileInputStream fis = new FileInputStream(readFile); + BufferedInputStream bis = new BufferedInputStream(fis); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + byte[] binary = new byte[1024]; + while (true) { + int len = bis.read(binary); + if (len < 0) { + break; + } + bout.write(binary, 0, len); + } + + binary = bout.toByteArray(); + ObjectMapper om = new ObjectMapper(new MessagePackFactory()); + PreData ds = om.readValue(binary, PreData.class); + bis.close(); + fis.close(); + return ds; + } catch (IOException e) { + return null; + } + } + + + public boolean write() { + try { + if (!PRECOMP_DATA_DIR.exists()) { + if (!PRECOMP_DATA_DIR.mkdir()) { + return false; + } + } + ObjectMapper om = new ObjectMapper(new MessagePackFactory()); + byte[] binary = om.writeValueAsBytes(this.data); + FileOutputStream fos = new FileOutputStream( + new File(PRECOMP_DATA_DIR, this.fileName)); + fos.write(binary); + fos.close(); + return true; + } catch (IOException e) { + e.printStackTrace(); + ; + return false; + } + } + + + public Integer setInteger(String name, int value) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.intValues.put(callClassName + ":" + name, value); + } + + + public Double setDouble(String name, double value) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.doubleValues.put(callClassName + ":" + name, value); + } + + + public Boolean setBoolean(String name, boolean value) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.boolValues.put(callClassName + ":" + name, value); + } + + + public String setString(String name, String value) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.stringValues.put(callClassName + ":" + name, value); + } + + + public EntityID setEntityID(String name, EntityID value) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + Integer id = this.data.idValues.put(callClassName + ":" + name, + value.getValue()); + return id == null ? null : new EntityID(id); + } + + + public List setIntegerList(String name, List list) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.intLists.put(callClassName + ":" + name, list); + } + + + public List setDoubleList(String name, List list) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.doubleLists.put(callClassName + ":" + name, list); + } + + + public List setStringList(String name, List list) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.stringLists.put(callClassName + ":" + name, list); + } + + + public List setEntityIDList(String name, List list) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + List cvtList = new ArrayList<>(); + for (EntityID id : list) { + cvtList.add(id.getValue()); + } + + cvtList = this.data.idLists.put(callClassName + ":" + name, cvtList); + return cvtList == null ? null + : cvtList.stream().map(EntityID::new).collect(Collectors.toList()); + } + + + public List setBooleanList(String name, List list) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.boolLists.put(callClassName + ":" + name, list); + } + + + public boolean setReady(boolean isReady, WorldInfo worldInfo) { + this.data.isReady = isReady; + this.data.readyID = makeReadyID(worldInfo); + return (this.data.isReady + && this.data.readyID.equals(this.makeReadyID(worldInfo))); + } + + + public Integer getInteger(String name) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.intValues.get(callClassName + ":" + name); + } + + + public Double getDouble(String name) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.doubleValues.get(callClassName + ":" + name); + } + + + public Boolean getBoolean(String name) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.boolValues.get(callClassName + ":" + name); + } + + + public String getString(String name) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.stringValues.get(callClassName + ":" + name); + } + + + public EntityID getEntityID(String name) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + Integer id = this.data.idValues.get(callClassName + ":" + name); + return id == null ? null : new EntityID(id); + } + + + public List getIntegerList(String name) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.intLists.get(callClassName + ":" + name); + } + + + public List getDoubleList(String name) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.doubleLists.get(callClassName + ":" + name); + } + + + public List getStringList(String name) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.stringLists.get(callClassName + ":" + name); + } + + + public List getEntityIDList(String name) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + List cvtList = this.data.idLists.get(callClassName + ":" + name); + return cvtList == null ? null + : cvtList.stream().map(EntityID::new).collect(Collectors.toList()); + } + + + public List getBooleanList(String name) { + StackTraceElement[] stackTraceElements = Thread.currentThread() + .getStackTrace(); + if (stackTraceElements.length == 0) { + return null; + } + + String callClassName = stackTraceElements[2].getClassName(); + return this.data.boolLists.get(callClassName + ":" + name); + } + + + public boolean isReady(WorldInfo worldInfo) { + return (this.data.isReady + && this.data.readyID.equals(this.makeReadyID(worldInfo))); + } + + + private String makeReadyID(WorldInfo worldInfo) { + return "" + worldInfo.getBounds().getX() + worldInfo.getBounds().getY() + + worldInfo.getAllEntities().size(); + } +} diff --git a/java/lib/src/main/java/adf_core_python/component/extaction/ExtAction.java b/java/lib/src/main/java/adf_core_python/component/extaction/ExtAction.java new file mode 100644 index 0000000..0dad82a --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/extaction/ExtAction.java @@ -0,0 +1,137 @@ +package adf_core_python.component.extaction; + +import adf.core.agent.action.Action; +import adf.core.agent.communication.MessageManager; +import adf.core.agent.develop.DevelopData; +import adf.core.agent.info.AgentInfo; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf.core.agent.module.ModuleManager; +import adf.core.agent.precompute.PrecomputeData; +import rescuecore2.worldmodel.EntityID; + +abstract public class ExtAction { + + protected ScenarioInfo scenarioInfo; + protected AgentInfo agentInfo; + protected WorldInfo worldInfo; + protected ModuleManager moduleManager; + protected DevelopData developData; + protected Action result; + private int countPrecompute; + private int countResume; + private int countPreparate; + private int countUpdateInfo; + private int countUpdateInfoCurrentTime; + + public ExtAction(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + this.worldInfo = wi; + this.agentInfo = ai; + this.scenarioInfo = si; + this.moduleManager = moduleManager; + this.developData = developData; + this.result = null; + this.countPrecompute = 0; + this.countResume = 0; + this.countPreparate = 0; + this.countUpdateInfo = 0; + this.countUpdateInfoCurrentTime = 0; + } + + + public abstract ExtAction setTarget(EntityID targets); + + + /** + * @param targets target + * @return ExtAction + * @deprecated {@link #setTarget(EntityID)} + */ + @Deprecated + public ExtAction setTarget(EntityID... targets) { + if (targets != null && targets.length > 0) { + return this.setTarget(targets[0]); + } + return this; + } + + + public abstract ExtAction calc(); + + + public Action getAction() { + return result; + } + + + public ExtAction precompute(PrecomputeData precomputeData) { + this.countPrecompute++; + return this; + } + + + public ExtAction resume(PrecomputeData precomputeData) { + this.countResume++; + return this; + } + + + public ExtAction preparate() { + this.countPreparate++; + return this; + } + + + public ExtAction updateInfo(MessageManager messageManager) { + if (this.countUpdateInfoCurrentTime != this.agentInfo.getTime()) { + this.countUpdateInfo = 0; + this.countUpdateInfoCurrentTime = this.agentInfo.getTime(); + } + this.countUpdateInfo++; + return this; + } + + + public int getCountPrecompute() { + return this.countPrecompute; + } + + + public int getCountResume() { + return this.countResume; + } + + + public int getCountPreparate() { + return this.countPreparate; + } + + + public int getCountUpdateInfo() { + if (this.countUpdateInfoCurrentTime != this.agentInfo.getTime()) { + this.countUpdateInfo = 0; + this.countUpdateInfoCurrentTime = this.agentInfo.getTime(); + } + return this.countUpdateInfo; + } + + + public void resetCountPrecompute() { + this.countPrecompute = 0; + } + + + public void resetCountResume() { + this.countResume = 0; + } + + + public void resetCountPreparate() { + this.countPreparate = 0; + } + + + public void resetCountUpdateInfo() { + this.countUpdateInfo = 0; + } +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/AbstractModule.java b/java/lib/src/main/java/adf_core_python/component/module/AbstractModule.java new file mode 100644 index 0000000..830ca29 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/AbstractModule.java @@ -0,0 +1,138 @@ +package adf_core_python.component.module; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; + +import java.util.ArrayList; +import java.util.List; + +public abstract class AbstractModule { + + private final List subModules = new ArrayList<>(); + protected AgentInfo agentInfo; + protected WorldInfo worldInfo; + protected ScenarioInfo scenarioInfo; + protected ModuleManager moduleManager; + protected DevelopData developData; + + private int countPrecompute; + private int countResume; + private int countPreparate; + private int countUpdateInfo; + private int countUpdateInfoCurrentTime; + + public AbstractModule(AgentInfo agentInfo, WorldInfo worldInfo, ScenarioInfo scenarioInfo, ModuleManager moduleManager, DevelopData developData) { + this.agentInfo = agentInfo; + this.worldInfo = worldInfo; + this.scenarioInfo = scenarioInfo; + this.moduleManager = moduleManager; + this.developData = developData; + this.countPrecompute = 0; + this.countResume = 0; + this.countPreparate = 0; + this.countUpdateInfo = 0; + this.countUpdateInfoCurrentTime = 0; + } + + + protected void registerModule(AbstractModule module) { + subModules.add(module); + } + + + protected boolean unregisterModule(AbstractModule module) { + return subModules.remove(module); + } + + + public AbstractModule precompute(PrecomputeData precomputeData) { + this.countPrecompute++; + for (AbstractModule abstractModule : subModules) { + abstractModule.precompute(precomputeData); + } + return this; + } + + + public AbstractModule resume(PrecomputeData precomputeData) { + this.countResume++; + for (AbstractModule abstractModule : subModules) { + abstractModule.resume(precomputeData); + } + return this; + } + + + public AbstractModule preparate() { + this.countPreparate++; + for (AbstractModule abstractModule : subModules) { + abstractModule.preparate(); + } + return this; + } + + + public AbstractModule updateInfo(MessageManager messageManager) { + if (this.countUpdateInfoCurrentTime != this.agentInfo.getTime()) { + this.countUpdateInfo = 0; + this.countUpdateInfoCurrentTime = this.agentInfo.getTime(); + } + for (AbstractModule abstractModule : subModules) { + abstractModule.updateInfo(messageManager); + } + this.countUpdateInfo++; + return this; + } + + + public abstract AbstractModule calc(); + + + public int getCountPrecompute() { + return this.countPrecompute; + } + + + public int getCountResume() { + return this.countResume; + } + + + public int getCountPreparate() { + return this.countPreparate; + } + + + public int getCountUpdateInfo() { + if (this.countUpdateInfoCurrentTime != this.agentInfo.getTime()) { + this.countUpdateInfo = 0; + this.countUpdateInfoCurrentTime = this.agentInfo.getTime(); + } + return this.countUpdateInfo; + } + + + public void resetCountPrecompute() { + this.countPrecompute = 0; + } + + + public void resetCountResume() { + this.countResume = 0; + } + + + public void resetCountPreparate() { + this.countPreparate = 0; + } + + + public void resetCountUpdateInfo() { + this.countUpdateInfo = 0; + } +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/algorithm/Clustering.java b/java/lib/src/main/java/adf_core_python/component/module/algorithm/Clustering.java new file mode 100644 index 0000000..aba296d --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/algorithm/Clustering.java @@ -0,0 +1,86 @@ +package adf_core_python.component.module.algorithm; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.AbstractModule; +import rescuecore2.standard.entities.StandardEntity; +import rescuecore2.worldmodel.EntityID; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public abstract class Clustering extends AbstractModule { + + public Clustering(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } + + + public abstract int getClusterNumber(); + + public abstract int getClusterIndex(StandardEntity entity); + + public abstract int getClusterIndex(EntityID id); + + public abstract Collection getClusterEntities(int index); + + public abstract Collection getClusterEntityIDs(int index); + + + public List> getAllClusterEntities() { + int number = this.getClusterNumber(); + List> result = new ArrayList<>(number); + for (int i = 0; i < number; i++) { + result.add(i, this.getClusterEntities(i)); + } + return result; + } + + + public List> getAllClusterEntityIDs() { + int number = this.getClusterNumber(); + List> result = new ArrayList<>(number); + for (int i = 0; i < number; i++) { + result.add(i, this.getClusterEntityIDs(i)); + } + return result; + } + + + @Override + public Clustering precompute(PrecomputeData precomputeData) { + super.precompute(precomputeData); + return this; + } + + + @Override + public Clustering resume(PrecomputeData precomputeData) { + super.resume(precomputeData); + return this; + } + + + @Override + public Clustering preparate() { + super.preparate(); + return this; + } + + + @Override + public Clustering updateInfo(MessageManager messageManager) { + super.updateInfo(messageManager); + return this; + } + + + @Override + public abstract Clustering calc(); +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/algorithm/DynamicClustering.java b/java/lib/src/main/java/adf_core_python/component/module/algorithm/DynamicClustering.java new file mode 100644 index 0000000..208d200 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/algorithm/DynamicClustering.java @@ -0,0 +1,14 @@ +package adf_core_python.component.module.algorithm; + +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; + +public abstract class DynamicClustering extends Clustering { + + public DynamicClustering(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/algorithm/PathPlanning.java b/java/lib/src/main/java/adf_core_python/component/module/algorithm/PathPlanning.java new file mode 100644 index 0000000..6101ac0 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/algorithm/PathPlanning.java @@ -0,0 +1,101 @@ +package adf_core_python.component.module.algorithm; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.AbstractModule; +import rescuecore2.misc.Pair; +import rescuecore2.worldmodel.EntityID; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +public abstract class PathPlanning extends AbstractModule { + + public PathPlanning(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } + + + public abstract List getResult(); + + public abstract PathPlanning setFrom(EntityID id); + + public abstract PathPlanning setDestination(Collection targets); + + + public PathPlanning setDestination(EntityID... targets) { + return this.setDestination(Arrays.asList(targets)); + } + + + @Override + public PathPlanning precompute(PrecomputeData precomputeData) { + super.precompute(precomputeData); + return this; + } + + + @Override + public PathPlanning resume(PrecomputeData precomputeData) { + super.resume(precomputeData); + return this; + } + + + @Override + public PathPlanning preparate() { + super.preparate(); + return this; + } + + + @Override + public PathPlanning updateInfo(MessageManager messageManager) { + super.updateInfo(messageManager); + return this; + } + + + @Override + public abstract PathPlanning calc(); + + + public double getDistance() { + double sum = 0.0; + List path = getResult(); + if (path == null || path.size() <= 1) { + return sum; + } + + Pair prevPoint = null; + for (EntityID id : path) { + Pair point = worldInfo.getLocation(worldInfo.getEntity(id)); + if (prevPoint != null) { + int x = prevPoint.first() - point.first(); + int y = prevPoint.second() - point.second(); + sum += x * x + y * y; + } + prevPoint = point; + } + + return Math.sqrt(sum); + } + + + // Alias + public double getDistance(EntityID from, EntityID dest) { + return this.setFrom(from).setDestination(dest).calc().getDistance(); + } + + + public List getResult(EntityID from, EntityID dest) { + return this.setFrom(from).setDestination(dest).calc().getResult(); + } +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/algorithm/StaticClustering.java b/java/lib/src/main/java/adf_core_python/component/module/algorithm/StaticClustering.java new file mode 100644 index 0000000..b9647da --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/algorithm/StaticClustering.java @@ -0,0 +1,14 @@ +package adf_core_python.component.module.algorithm; + +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; + +public abstract class StaticClustering extends Clustering { + + public StaticClustering(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/complex/AmbulanceTargetAllocator.java b/java/lib/src/main/java/adf_core_python/component/module/complex/AmbulanceTargetAllocator.java new file mode 100644 index 0000000..41f2e7b --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/complex/AmbulanceTargetAllocator.java @@ -0,0 +1,47 @@ +package adf_core_python.component.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; +import rescuecore2.worldmodel.EntityID; + +import java.util.Map; + +public abstract class AmbulanceTargetAllocator extends TargetAllocator { + + public AmbulanceTargetAllocator(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } + + + @Override + public abstract Map getResult(); + + @Override + public abstract AmbulanceTargetAllocator calc(); + + + @Override + public AmbulanceTargetAllocator resume(PrecomputeData precomputeData) { + super.resume(precomputeData); + return this; + } + + + @Override + public AmbulanceTargetAllocator preparate() { + super.preparate(); + return this; + } + + + @Override + public AmbulanceTargetAllocator updateInfo(MessageManager messageManager) { + super.updateInfo(messageManager); + return this; + } +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/complex/BuildingDetector.java b/java/lib/src/main/java/adf_core_python/component/module/complex/BuildingDetector.java new file mode 100644 index 0000000..34567c8 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/complex/BuildingDetector.java @@ -0,0 +1,49 @@ +package adf_core_python.component.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; +import rescuecore2.standard.entities.Building; + +public abstract class BuildingDetector extends TargetDetector { + + public BuildingDetector(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } + + + @Override + public BuildingDetector precompute(PrecomputeData precomputeData) { + super.precompute(precomputeData); + return this; + } + + + @Override + public BuildingDetector resume(PrecomputeData precomputeData) { + super.resume(precomputeData); + return this; + } + + + @Override + public BuildingDetector preparate() { + super.preparate(); + return this; + } + + + @Override + public BuildingDetector updateInfo(MessageManager messageManager) { + super.updateInfo(messageManager); + return this; + } + + + @Override + public abstract BuildingDetector calc(); +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/complex/FireTargetAllocator.java b/java/lib/src/main/java/adf_core_python/component/module/complex/FireTargetAllocator.java new file mode 100644 index 0000000..65c757e --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/complex/FireTargetAllocator.java @@ -0,0 +1,47 @@ +package adf_core_python.component.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; +import rescuecore2.worldmodel.EntityID; + +import java.util.Map; + +public abstract class FireTargetAllocator extends TargetAllocator { + + public FireTargetAllocator(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } + + + @Override + public abstract Map getResult(); + + @Override + public abstract FireTargetAllocator calc(); + + + @Override + public FireTargetAllocator resume(PrecomputeData precomputeData) { + super.resume(precomputeData); + return this; + } + + + @Override + public FireTargetAllocator preparate() { + super.preparate(); + return this; + } + + + @Override + public FireTargetAllocator updateInfo(MessageManager messageManager) { + super.updateInfo(messageManager); + return this; + } +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/complex/HumanDetector.java b/java/lib/src/main/java/adf_core_python/component/module/complex/HumanDetector.java new file mode 100644 index 0000000..e99db72 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/complex/HumanDetector.java @@ -0,0 +1,49 @@ +package adf_core_python.component.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; +import rescuecore2.standard.entities.Human; + +public abstract class HumanDetector extends TargetDetector { + + public HumanDetector(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } + + + @Override + public HumanDetector precompute(PrecomputeData precomputeData) { + super.precompute(precomputeData); + return this; + } + + + @Override + public HumanDetector resume(PrecomputeData precomputeData) { + super.resume(precomputeData); + return this; + } + + + @Override + public HumanDetector preparate() { + super.preparate(); + return this; + } + + + @Override + public HumanDetector updateInfo(MessageManager messageManager) { + super.updateInfo(messageManager); + return this; + } + + + @Override + public abstract HumanDetector calc(); +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/complex/PoliceTargetAllocator.java b/java/lib/src/main/java/adf_core_python/component/module/complex/PoliceTargetAllocator.java new file mode 100644 index 0000000..846dc06 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/complex/PoliceTargetAllocator.java @@ -0,0 +1,47 @@ +package adf_core_python.component.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; +import rescuecore2.worldmodel.EntityID; + +import java.util.Map; + +public abstract class PoliceTargetAllocator extends TargetAllocator { + + public PoliceTargetAllocator(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } + + + @Override + public abstract Map getResult(); + + @Override + public abstract PoliceTargetAllocator calc(); + + + @Override + public PoliceTargetAllocator resume(PrecomputeData precomputeData) { + super.resume(precomputeData); + return this; + } + + + @Override + public PoliceTargetAllocator preparate() { + super.preparate(); + return this; + } + + + @Override + public PoliceTargetAllocator updateInfo(MessageManager messageManager) { + super.updateInfo(messageManager); + return this; + } +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/complex/RoadDetector.java b/java/lib/src/main/java/adf_core_python/component/module/complex/RoadDetector.java new file mode 100644 index 0000000..9f6acac --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/complex/RoadDetector.java @@ -0,0 +1,49 @@ +package adf_core_python.component.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; +import rescuecore2.standard.entities.Road; + +public abstract class RoadDetector extends TargetDetector { + + public RoadDetector(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } + + + @Override + public RoadDetector precompute(PrecomputeData precomputeData) { + super.precompute(precomputeData); + return this; + } + + + @Override + public RoadDetector resume(PrecomputeData precomputeData) { + super.resume(precomputeData); + return this; + } + + + @Override + public RoadDetector preparate() { + super.preparate(); + return this; + } + + + @Override + public RoadDetector updateInfo(MessageManager messageManager) { + super.updateInfo(messageManager); + return this; + } + + + @Override + public abstract RoadDetector calc(); +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/complex/Search.java b/java/lib/src/main/java/adf_core_python/component/module/complex/Search.java new file mode 100644 index 0000000..13173bb --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/complex/Search.java @@ -0,0 +1,49 @@ +package adf_core_python.component.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; +import rescuecore2.standard.entities.Area; + +public abstract class Search extends TargetDetector { + + public Search(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } + + + @Override + public Search precompute(PrecomputeData precomputeData) { + super.precompute(precomputeData); + return this; + } + + + @Override + public Search resume(PrecomputeData precomputeData) { + super.resume(precomputeData); + return this; + } + + + @Override + public Search preparate() { + super.preparate(); + return this; + } + + + @Override + public Search updateInfo(MessageManager messageManager) { + super.updateInfo(messageManager); + return this; + } + + + @Override + public abstract Search calc(); +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/complex/TargetAllocator.java b/java/lib/src/main/java/adf_core_python/component/module/complex/TargetAllocator.java new file mode 100644 index 0000000..3a85b34 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/complex/TargetAllocator.java @@ -0,0 +1,54 @@ +package adf_core_python.component.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.AbstractModule; +import rescuecore2.worldmodel.EntityID; + +import java.util.Map; + +public abstract class TargetAllocator extends AbstractModule { + + public TargetAllocator(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } + + + public abstract Map getResult(); + + @Override + public abstract TargetAllocator calc(); + + + @Override + public final TargetAllocator precompute(PrecomputeData precomputeData) { + super.precompute(precomputeData); + return this; + } + + + @Override + public TargetAllocator resume(PrecomputeData precomputeData) { + super.resume(precomputeData); + return this; + } + + + @Override + public TargetAllocator preparate() { + super.preparate(); + return this; + } + + + @Override + public TargetAllocator updateInfo(MessageManager messageManager) { + super.updateInfo(messageManager); + return this; + } +} diff --git a/java/lib/src/main/java/adf_core_python/component/module/complex/TargetDetector.java b/java/lib/src/main/java/adf_core_python/component/module/complex/TargetDetector.java new file mode 100644 index 0000000..bddd091 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/component/module/complex/TargetDetector.java @@ -0,0 +1,54 @@ +package adf_core_python.component.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.ScenarioInfo; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.agent.info.AgentInfo; +import adf_core_python.agent.module.ModuleManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.AbstractModule; +import rescuecore2.standard.entities.StandardEntity; +import rescuecore2.worldmodel.EntityID; + +public abstract class TargetDetector + extends AbstractModule { + + public TargetDetector(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { + super(ai, wi, si, moduleManager, developData); + } + + + public abstract EntityID getTarget(); + + @Override + public abstract TargetDetector calc(); + + + @Override + public TargetDetector precompute(PrecomputeData precomputeData) { + super.precompute(precomputeData); + return this; + } + + + @Override + public TargetDetector resume(PrecomputeData precomputeData) { + super.resume(precomputeData); + return this; + } + + + @Override + public TargetDetector preparate() { + super.preparate(); + return this; + } + + + @Override + public TargetDetector updateInfo(MessageManager messageManager) { + super.updateInfo(messageManager); + return this; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/Coordinator.java b/java/lib/src/main/java/adf_core_python/gateway/Coordinator.java new file mode 100644 index 0000000..309e92d --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/Coordinator.java @@ -0,0 +1,132 @@ +package adf_core_python.gateway; + +import adf.core.agent.info.ScenarioInfo; +import adf_core_python.agent.Agent; +import adf_core_python.agent.config.ModuleConfig; +import adf_core_python.agent.develop.DevelopData; +import adf_core_python.gateway.message.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import rescuecore2.config.Config; +import rescuecore2.messages.Command; +import rescuecore2.messages.Message; +import rescuecore2.messages.protobuf.RCRSProto; +import rescuecore2.messages.protobuf.RCRSProto.MessageProto; +import rescuecore2.misc.EncodingTools; +import rescuecore2.worldmodel.ChangeSet; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.util.Collection; +import java.util.HashMap; + +public class Coordinator extends Thread { + private final InputStream inputStream; + private final OutputStream outputStream; + private final HashMap changeSetTemp = new HashMap<>(); + private final HashMap> heardTemp = new HashMap<>(); + private boolean running = true; + private Agent agent; + + public Coordinator(Socket socket) { + try { + socket.setSoTimeout(1000); + socket.setReuseAddress(true); + inputStream = socket.getInputStream(); + outputStream = socket.getOutputStream(); + } catch (IOException e) { + throw new RuntimeException(e); + } + Logger logger = LogManager.getLogger(this.getClass()); + logger.info("Connected from {} on {}", socket.getRemoteSocketAddress(), socket.getLocalSocketAddress()); + } + + @Override + public void run() { + while (running) { + RCRSProto.MessageProto messageProto = receiveMessage(); + if (messageProto == null) continue; + try { + Message message = ModuleControlMessageFactory.makeMessage(messageProto.getUrn(), messageProto); + handleMessage(message); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + + private void handleMessage(Message message) { + if (message instanceof AMAgent amAgent) { + ScenarioInfo.Mode mode = ScenarioInfo.Mode.NON_PRECOMPUTE; + switch (amAgent.getMode()) { + case 1: + mode = ScenarioInfo.Mode.PRECOMPUTED; + break; + case 2: + mode = ScenarioInfo.Mode.PRECOMPUTATION_PHASE; + break; + } + agent = new Agent(amAgent.getAgentID(), amAgent.getEntities(), new ScenarioInfo(amAgent.getConfig(), mode), new DevelopData(), new ModuleConfig()); + } else if (message instanceof AMModule amModule) { + if (agent == null) { + throw new IllegalStateException("Agent not found. Make sure agent has been registered."); + } + Class clazz = agent.registerModule(amModule.getModuleID(), amModule.getModuleName(), amModule.getDefaultClassName()); + String class_name = ""; + if (clazz != null) { + class_name = clazz.getName(); + } + MAModuleResponse maModuleResponse = new MAModuleResponse(amModule.getModuleID(), class_name); + sendMessage(maModuleResponse); + } else if (message instanceof AMUpdate amUpdate) { + if (agent == null) { + changeSetTemp.put(amUpdate.getTime(), amUpdate.getChanged()); + heardTemp.put(amUpdate.getTime(), amUpdate.getHeard()); + return; + } + if (!changeSetTemp.isEmpty() && !heardTemp.isEmpty()) { + for (int i = 1; i < amUpdate.getTime(); i++) { + agent.update(i, changeSetTemp.get(i), heardTemp.get(i)); + } + changeSetTemp.clear(); + heardTemp.clear(); + } + agent.update(amUpdate.getTime(), amUpdate.getChanged(), amUpdate.getHeard()); + } else if (message instanceof AMExec amExec) { + Config result = agent.execModuleMethod(amExec.getModuleID(), amExec.getMethodName(), amExec.getArguments()); + MAExecResponse maExecResponse = new MAExecResponse(amExec.getModuleID(), result); + sendMessage(maExecResponse); + } + } + + private MessageProto receiveMessage() { + try { + int size = EncodingTools.readInt32(inputStream); + byte[] bytes = inputStream.readNBytes(size); + return MessageProto.parseFrom(bytes); + } catch (IOException ignored) { + } + return null; + } + + private void sendMessage(MessageProto messageProto) { + try { + byte[] bytes = messageProto.toByteArray(); + EncodingTools.writeInt32(bytes.length, outputStream); + outputStream.write(bytes); + outputStream.flush(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void sendMessage(Message message) { + sendMessage(message.toMessageProto()); + } + + public void shutdown() { + running = false; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/Gateway.java b/java/lib/src/main/java/adf_core_python/gateway/Gateway.java new file mode 100644 index 0000000..2e97b29 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/Gateway.java @@ -0,0 +1,48 @@ +package adf_core_python.gateway; + +import rescuecore2.registry.Registry; +import rescuecore2.standard.entities.StandardEntityFactory; +import rescuecore2.standard.entities.StandardPropertyFactory; +import rescuecore2.standard.messages.StandardMessageFactory; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.ArrayList; + +public class Gateway extends Thread { + private final int port; + private final ArrayList coordinators; + private boolean running = true; + + public Gateway(int port) { + this.port = port; + this.coordinators = new ArrayList<>(); + + Registry.SYSTEM_REGISTRY.registerFactory(StandardEntityFactory.INSTANCE); + Registry.SYSTEM_REGISTRY.registerFactory(StandardMessageFactory.INSTANCE); + Registry.SYSTEM_REGISTRY.registerFactory(StandardPropertyFactory.INSTANCE); + } + + @Override + public void run() { + try (ServerSocket serverSocket = new ServerSocket(port)) { + serverSocket.setReuseAddress(true); + while (running) { + Socket socket = serverSocket.accept(); + Coordinator coordinator = new Coordinator(socket); + coordinator.start(); + coordinators.add(coordinator); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void shutdown() { + running = false; + for (Coordinator coordinator : coordinators) { + coordinator.shutdown(); + } + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/AbstractMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/AbstractMapper.java new file mode 100644 index 0000000..3a27ca9 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/AbstractMapper.java @@ -0,0 +1,21 @@ +package adf_core_python.gateway.mapper; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import rescuecore2.config.Config; + +public abstract class AbstractMapper { + protected Class targetClass; + protected Logger logger; + + public AbstractMapper() { + this.targetClass = Object.class; + logger = LogManager.getLogger(this.getClass()); + } + + public Class getTargetClass() { + return targetClass; + } + + public abstract Config execMethod(String methodName, Config arguments); +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/MapperDict.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/MapperDict.java new file mode 100644 index 0000000..28e50f3 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/MapperDict.java @@ -0,0 +1,51 @@ +package adf_core_python.gateway.mapper; + +import adf_core_python.component.module.AbstractModule; +import adf_core_python.component.module.algorithm.Clustering; +import adf_core_python.component.module.algorithm.DynamicClustering; +import adf_core_python.component.module.algorithm.PathPlanning; +import adf_core_python.component.module.algorithm.StaticClustering; +import adf_core_python.component.module.complex.*; +import adf_core_python.gateway.mapper.module.AbstractModuleMapper; +import adf_core_python.gateway.mapper.module.algorithm.ClusteringMapper; +import adf_core_python.gateway.mapper.module.algorithm.DynamicClusteringMapper; +import adf_core_python.gateway.mapper.module.algorithm.PathPlanningMapper; +import adf_core_python.gateway.mapper.module.algorithm.StaticClusteringMapper; +import adf_core_python.gateway.mapper.module.complex.*; + +import java.util.HashMap; + +public class MapperDict { + private final HashMap, Class> mapperDict; + + public MapperDict() { + mapperDict = new HashMap<>(); + registerMapper(Clustering.class, ClusteringMapper.class); + registerMapper(DynamicClustering.class, DynamicClusteringMapper.class); + registerMapper(StaticClustering.class, StaticClusteringMapper.class); + + registerMapper(PathPlanning.class, PathPlanningMapper.class); + + registerMapper(TargetDetector.class, TargetDetectorMapper.class); + registerMapper(HumanDetector.class, HumanDetectorMapper.class); + registerMapper(RoadDetector.class, RoadDetectorMapper.class); + registerMapper(BuildingDetector.class, BuildingDetectorMapper.class); + + registerMapper(Search.class, SearchMapper.class); + + registerMapper(TargetAllocator.class, TargetAllocatorMapper.class); + registerMapper(AmbulanceTargetAllocator.class, AmbulanceTargetAllocatorMapper.class); + registerMapper(FireTargetAllocator.class, FireTargetAllocatorMapper.class); + registerMapper(PoliceTargetAllocator.class, PoliceTargetAllocatorMapper.class); + + registerMapper(AbstractModule.class, AbstractModuleMapper.class); + } + + public void registerMapper(Class component, Class mapper) { + mapperDict.put(component, mapper); + } + + public Class getMapper(Class component) { + return mapperDict.get(component); + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/AbstractModuleMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/AbstractModuleMapper.java new file mode 100644 index 0000000..984d801 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/AbstractModuleMapper.java @@ -0,0 +1,64 @@ +package adf_core_python.gateway.mapper.module; + +import adf.core.agent.communication.MessageManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.AbstractModule; +import adf_core_python.gateway.mapper.AbstractMapper; +import rescuecore2.config.Config; + +public class AbstractModuleMapper extends AbstractMapper { + protected final AbstractModule abstractModule; + private final PrecomputeData precomputeData; + private final MessageManager messageManager; + + public AbstractModuleMapper(AbstractModule abstractModule, PrecomputeData precomputeData, MessageManager messageManager) { + super(); + this.targetClass = AbstractModule.class; + this.abstractModule = abstractModule; + this.precomputeData = precomputeData; + this.messageManager = messageManager; + } + + @Override + public Config execMethod(String methodName, Config arguments) { + switch (methodName) { + case "precompute": + execPrecompute(); + break; + case "resume": + execResume(); + break; + case "preparate": + execPreparate(); + break; + case "updateInfo": + execUpdateInfo(); + break; + case "calc": + execCalc(); + break; + } + + return new Config(); + } + + public void execPrecompute() { + abstractModule.precompute(precomputeData); + } + + public void execResume() { + abstractModule.resume(precomputeData); + } + + public void execPreparate() { + abstractModule.preparate(); + } + + public void execUpdateInfo() { + abstractModule.updateInfo(messageManager); + } + + public void execCalc() { + abstractModule.calc(); + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/algorithm/ClusteringMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/algorithm/ClusteringMapper.java new file mode 100644 index 0000000..a063c20 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/algorithm/ClusteringMapper.java @@ -0,0 +1,133 @@ +package adf_core_python.gateway.mapper.module.algorithm; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.algorithm.Clustering; +import adf_core_python.gateway.mapper.module.AbstractModuleMapper; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import rescuecore2.config.Config; +import rescuecore2.standard.entities.StandardEntity; +import rescuecore2.worldmodel.EntityID; + +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +public class ClusteringMapper extends AbstractModuleMapper { + private final WorldInfo worldInfo; + + public ClusteringMapper(Clustering clustering, PrecomputeData precomputeData, MessageManager messageManager, WorldInfo worldInfo) { + super(clustering, precomputeData, messageManager); + this.targetClass = Clustering.class; + this.worldInfo = worldInfo; + } + + @Override + public Config execMethod(String methodName, Config arguments) { + Config result = super.execMethod(methodName, arguments); + if (methodName.equals("getClusterNumber")) { + result = execGetClusterNumber(); + } + if (methodName.equals("getClusterIndex(StandardEntity)")) { + result = execGetClusterIndex(worldInfo.getEntity(new EntityID(arguments.getIntValue("EntityID")))); + } + if (methodName.equals("getClusterIndex(EntityID)")) { + result = execGetClusterIndex(new EntityID(arguments.getIntValue("EntityID"))); + } + if (methodName.equals("getClusterEntities(int)")) { + result = execGetClusterEntities(arguments.getIntValue("Index")); + } + if (methodName.equals("getClusterEntityIDs(int)")) { + result = execGetClusterEntityIDs(arguments.getIntValue("Index")); + } + if (methodName.equals("getAllClusterEntities")) { + result = execGetAllClusterEntities(); + } + if (methodName.equals("getAllClusterEntityIDs")) { + result = execGetAllClusterEntityIDs(); + } + return result; + } + + private Config execGetClusterNumber() { + Clustering clustering = (Clustering) abstractModule; + int clusterNumber = clustering.getClusterNumber(); + Config result = new Config(); + result.setIntValue("ClusterNumber", clusterNumber); + return result; + } + + private Config execGetClusterIndex(StandardEntity standardEntity) { + Clustering clustering = (Clustering) abstractModule; + int clusterIndex = clustering.getClusterIndex(standardEntity); + Config result = new Config(); + result.setIntValue("ClusterIndex", clusterIndex); + return result; + } + + private Config execGetClusterIndex(EntityID entityID) { + Clustering clustering = (Clustering) abstractModule; + int clusterIndex = clustering.getClusterIndex(entityID); + Config result = new Config(); + result.setIntValue("ClusterIndex", clusterIndex); + return result; + } + + private Config execGetClusterEntities(int index) { + Clustering clustering = (Clustering) abstractModule; + Collection entities = clustering.getClusterEntities(index); + ObjectMapper objectMapper = new ObjectMapper(); + String jsonStr = ""; + try { + jsonStr = objectMapper.writeValueAsString(entities.stream().map(e -> e.getID().getValue()).toArray()); + } catch (JsonProcessingException ignored) { + } + Config result = new Config(); + result.setValue("EntityIDs", jsonStr); + return result; + } + + private Config execGetClusterEntityIDs(int index) { + Clustering clustering = (Clustering) abstractModule; + Collection entities = clustering.getClusterEntityIDs(index); + ObjectMapper objectMapper = new ObjectMapper(); + String jsonStr = ""; + try { + jsonStr = objectMapper.writeValueAsString(entities.stream().map(EntityID::getValue).toArray()); + } catch (JsonProcessingException ignored) { + } + Config result = new Config(); + result.setValue("EntityIDs", jsonStr); + return result; + } + + private Config execGetAllClusterEntities() { + Clustering clustering = (Clustering) abstractModule; + List> allClusterEntities = clustering.getAllClusterEntities(); + ObjectMapper objectMapper = new ObjectMapper(); + String jsonStr = ""; + try { + jsonStr = objectMapper.writeValueAsString(allClusterEntities.stream().map(e -> e.stream().map(f -> f.getID().getValue()).collect(Collectors.toList())).toArray()); + } catch (JsonProcessingException ignored) { + } + Config result = new Config(); + result.setValue("EntityIDs", jsonStr); + return result; + } + + private Config execGetAllClusterEntityIDs() { + Clustering clustering = (Clustering) abstractModule; + List> allClusterEntityIDs = clustering.getAllClusterEntityIDs(); + ObjectMapper objectMapper = new ObjectMapper(); + String jsonStr = ""; + try { + jsonStr = objectMapper.writeValueAsString(allClusterEntityIDs.stream().map(e -> e.stream().map(EntityID::getValue).collect(Collectors.toList())).toArray()); + } catch (JsonProcessingException ignored) { + } + Config result = new Config(); + result.setValue("EntityIDs", jsonStr); + return result; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/algorithm/DynamicClusteringMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/algorithm/DynamicClusteringMapper.java new file mode 100644 index 0000000..3dfdb43 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/algorithm/DynamicClusteringMapper.java @@ -0,0 +1,12 @@ +package adf_core_python.gateway.mapper.module.algorithm; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.algorithm.DynamicClustering; + +public class DynamicClusteringMapper extends ClusteringMapper { + public DynamicClusteringMapper(DynamicClustering dynamicClustering, PrecomputeData precomputeData, MessageManager messageManager, WorldInfo worldInfo) { + super(dynamicClustering, precomputeData, messageManager, worldInfo); + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/algorithm/PathPlanningMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/algorithm/PathPlanningMapper.java new file mode 100644 index 0000000..3bfb84f --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/algorithm/PathPlanningMapper.java @@ -0,0 +1,108 @@ +package adf_core_python.gateway.mapper.module.algorithm; + +import adf.core.agent.communication.MessageManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.algorithm.PathPlanning; +import adf_core_python.gateway.mapper.module.AbstractModuleMapper; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import rescuecore2.config.Config; +import rescuecore2.worldmodel.EntityID; + +import java.util.Collection; +import java.util.List; + +public class PathPlanningMapper extends AbstractModuleMapper { + public PathPlanningMapper(PathPlanning pathPlanning, PrecomputeData precomputeData, MessageManager messageManager) { + super(pathPlanning, precomputeData, messageManager); + } + + @Override + public Config execMethod(String methodName, Config arguments) { + Config result = super.execMethod(methodName, arguments); + if (methodName.equals("getResult")) { + result = execGetResult(); + } + if (methodName.equals("setFrom(EntityID)")) { + execSetFrom(new EntityID(arguments.getIntValue("EntityID"))); + } + if (methodName.equals("setDestination(Collection)")) { + ObjectMapper objectMapper = new ObjectMapper(); + Collection targets; + try { + targets = objectMapper.readValue(arguments.getValue("Targets"), new TypeReference>() { + }); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + execSetDestination(targets); + } + if (methodName.equals("getDistance")) { + result = execGetDistance(); + } + if (methodName.equals("getDistance(EntityID, EntityID)")) { + result = execGetDistance(new EntityID(arguments.getIntValue("From")), new EntityID(arguments.getIntValue("Dest"))); + } + if (methodName.equals("getResult(EntityID, EntityID)")) { + result = execGetResult(new EntityID(arguments.getIntValue("From")), new EntityID(arguments.getIntValue("Dest"))); + } + return result; + } + + private Config execGetResult() { + PathPlanning pathPlanning = (PathPlanning) abstractModule; + List entityIDs = pathPlanning.getResult(); + ObjectMapper objectMapper = new ObjectMapper(); + String jsonStr; + try { + jsonStr = objectMapper.writeValueAsString(entityIDs); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + Config result = new Config(); + result.setValue("EntityIDs", jsonStr); + return result; + } + + private void execSetFrom(EntityID entityID) { + PathPlanning pathPlanning = (PathPlanning) abstractModule; + pathPlanning.setFrom(entityID); + } + + private void execSetDestination(Collection targets) { + PathPlanning pathPlanning = (PathPlanning) abstractModule; + pathPlanning.setDestination(targets); + } + + private Config execGetDistance() { + PathPlanning pathPlanning = (PathPlanning) abstractModule; + Double distance = pathPlanning.getDistance(); + Config result = new Config(); + result.setValue("Distance", String.valueOf(distance)); + return result; + } + + private Config execGetDistance(EntityID from, EntityID dest) { + PathPlanning pathPlanning = (PathPlanning) abstractModule; + Double distance = pathPlanning.getDistance(from, dest); + Config result = new Config(); + result.setValue("Distance", String.valueOf(distance)); + return result; + } + + private Config execGetResult(EntityID from, EntityID dest) { + PathPlanning pathPlanning = (PathPlanning) abstractModule; + List entityIDs = pathPlanning.getResult(from, dest); + Config result = new Config(); + ObjectMapper objectMapper = new ObjectMapper(); + String jsonStr; + try { + jsonStr = objectMapper.writeValueAsString(entityIDs.stream().map(EntityID::getValue).toArray()); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + result.setValue("Result", String.valueOf(jsonStr)); + return result; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/algorithm/StaticClusteringMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/algorithm/StaticClusteringMapper.java new file mode 100644 index 0000000..daeaec3 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/algorithm/StaticClusteringMapper.java @@ -0,0 +1,12 @@ +package adf_core_python.gateway.mapper.module.algorithm; + +import adf.core.agent.communication.MessageManager; +import adf.core.agent.info.WorldInfo; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.algorithm.StaticClustering; + +public class StaticClusteringMapper extends ClusteringMapper { + public StaticClusteringMapper(StaticClustering staticClustering, PrecomputeData precomputeData, MessageManager messageManager, WorldInfo worldInfo) { + super(staticClustering, precomputeData, messageManager, worldInfo); + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/AmbulanceTargetAllocatorMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/AmbulanceTargetAllocatorMapper.java new file mode 100644 index 0000000..e7beb49 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/AmbulanceTargetAllocatorMapper.java @@ -0,0 +1,12 @@ +package adf_core_python.gateway.mapper.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.complex.AmbulanceTargetAllocator; + +public class AmbulanceTargetAllocatorMapper extends TargetAllocatorMapper { + public AmbulanceTargetAllocatorMapper(AmbulanceTargetAllocator ambulanceTargetAllocator, PrecomputeData precomputeData, MessageManager messageManager) { + super(ambulanceTargetAllocator, precomputeData, messageManager); + this.targetClass = AmbulanceTargetAllocator.class; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/BuildingDetectorMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/BuildingDetectorMapper.java new file mode 100644 index 0000000..448dd1c --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/BuildingDetectorMapper.java @@ -0,0 +1,12 @@ +package adf_core_python.gateway.mapper.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.complex.BuildingDetector; + +public class BuildingDetectorMapper extends TargetDetectorMapper { + public BuildingDetectorMapper(BuildingDetector buildingDetector, PrecomputeData precomputeData, MessageManager messageManager) { + super(buildingDetector, precomputeData, messageManager); + this.targetClass = BuildingDetector.class; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/FireTargetAllocatorMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/FireTargetAllocatorMapper.java new file mode 100644 index 0000000..235d3fa --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/FireTargetAllocatorMapper.java @@ -0,0 +1,12 @@ +package adf_core_python.gateway.mapper.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.complex.FireTargetAllocator; + +public class FireTargetAllocatorMapper extends TargetAllocatorMapper { + public FireTargetAllocatorMapper(FireTargetAllocator fireTargetAllocator, PrecomputeData precomputeData, MessageManager messageManager) { + super(fireTargetAllocator, precomputeData, messageManager); + this.targetClass = FireTargetAllocator.class; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/HumanDetectorMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/HumanDetectorMapper.java new file mode 100644 index 0000000..2db6fed --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/HumanDetectorMapper.java @@ -0,0 +1,12 @@ +package adf_core_python.gateway.mapper.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.complex.HumanDetector; + +public class HumanDetectorMapper extends TargetDetectorMapper { + public HumanDetectorMapper(HumanDetector humanDetector, PrecomputeData precomputeData, MessageManager messageManager) { + super(humanDetector, precomputeData, messageManager); + this.targetClass = HumanDetector.class; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/PoliceTargetAllocatorMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/PoliceTargetAllocatorMapper.java new file mode 100644 index 0000000..5092b72 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/PoliceTargetAllocatorMapper.java @@ -0,0 +1,12 @@ +package adf_core_python.gateway.mapper.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.complex.PoliceTargetAllocator; + +public class PoliceTargetAllocatorMapper extends TargetAllocatorMapper { + public PoliceTargetAllocatorMapper(PoliceTargetAllocator policeTargetAllocator, PrecomputeData precomputeData, MessageManager messageManager) { + super(policeTargetAllocator, precomputeData, messageManager); + this.targetClass = PoliceTargetAllocator.class; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/RoadDetectorMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/RoadDetectorMapper.java new file mode 100644 index 0000000..4945c38 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/RoadDetectorMapper.java @@ -0,0 +1,12 @@ +package adf_core_python.gateway.mapper.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.complex.RoadDetector; + +public class RoadDetectorMapper extends TargetDetectorMapper { + public RoadDetectorMapper(RoadDetector roadDetector, PrecomputeData precomputeData, MessageManager messageManager) { + super(roadDetector, precomputeData, messageManager); + this.targetClass = RoadDetector.class; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/SearchMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/SearchMapper.java new file mode 100644 index 0000000..94f42db --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/SearchMapper.java @@ -0,0 +1,11 @@ +package adf_core_python.gateway.mapper.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.complex.Search; + +public class SearchMapper extends TargetDetectorMapper { + public SearchMapper(Search search, PrecomputeData precomputeData, MessageManager messageManager) { + super(search, precomputeData, messageManager); + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/TargetAllocatorMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/TargetAllocatorMapper.java new file mode 100644 index 0000000..78ba9d2 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/TargetAllocatorMapper.java @@ -0,0 +1,34 @@ +package adf_core_python.gateway.mapper.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.complex.TargetAllocator; +import adf_core_python.gateway.mapper.module.AbstractModuleMapper; +import rescuecore2.config.Config; +import rescuecore2.worldmodel.EntityID; + +import java.util.Map; + +public class TargetAllocatorMapper extends AbstractModuleMapper { + public TargetAllocatorMapper(TargetAllocator targetAllocator, PrecomputeData precomputeData, MessageManager messageManager) { + super(targetAllocator, precomputeData, messageManager); + this.targetClass = TargetAllocator.class; + } + + @Override + public Config execMethod(String methodName, Config arguments) { + Config result = super.execMethod(methodName, arguments); + if (methodName.equals("getResult")) { + result = execGetResult(); + } + return result; + } + + public Config execGetResult() { + TargetAllocator targetAllocator = (TargetAllocator) abstractModule; + Map result = targetAllocator.getResult(); + Config response = new Config(); + result.forEach((k, v) -> response.setValue(String.valueOf(k.getValue()), String.valueOf(v.getValue()))); + return response; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/TargetDetectorMapper.java b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/TargetDetectorMapper.java new file mode 100644 index 0000000..e0bb851 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/mapper/module/complex/TargetDetectorMapper.java @@ -0,0 +1,35 @@ +package adf_core_python.gateway.mapper.module.complex; + +import adf.core.agent.communication.MessageManager; +import adf_core_python.agent.precompute.PrecomputeData; +import adf_core_python.component.module.complex.TargetDetector; +import adf_core_python.gateway.mapper.module.AbstractModuleMapper; +import rescuecore2.config.Config; +import rescuecore2.worldmodel.EntityID; + +public class TargetDetectorMapper extends AbstractModuleMapper { + public TargetDetectorMapper(TargetDetector targetDetector, PrecomputeData precomputeData, MessageManager messageManager) { + super(targetDetector, precomputeData, messageManager); + this.targetClass = TargetDetector.class; + } + + @Override + public Config execMethod(String methodName, Config arguments) { + Config result = super.execMethod(methodName, arguments); + if (methodName.equals("getTarget")) { + result = execGetTarget(); + } + return result; + } + + public Config execGetTarget() { + TargetDetector targetDetector = (TargetDetector) abstractModule; + EntityID entityID = targetDetector.getTarget(); + Config result = new Config(); + result.setIntValue("EntityID", -1); + if (entityID != null) { + result.setIntValue("EntityID", entityID.getValue()); + } + return result; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/message/AMAgent.java b/java/lib/src/main/java/adf_core_python/gateway/message/AMAgent.java new file mode 100644 index 0000000..a7e34a5 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/message/AMAgent.java @@ -0,0 +1,71 @@ +package adf_core_python.gateway.message; + +import adf_core_python.gateway.message.urn.ModuleMessageComponentURN; +import adf_core_python.gateway.message.urn.ModuleMessageURN; +import rescuecore2.config.Config; +import rescuecore2.messages.AbstractMessage; +import rescuecore2.messages.components.ConfigComponent; +import rescuecore2.messages.components.EntityIDComponent; +import rescuecore2.messages.components.EntityListComponent; +import rescuecore2.messages.components.IntComponent; +import rescuecore2.messages.protobuf.RCRSProto; +import rescuecore2.worldmodel.Entity; +import rescuecore2.worldmodel.EntityID; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; + +public class AMAgent extends AbstractMessage { + private final EntityIDComponent agentID; + private final EntityListComponent entities; + private final ConfigComponent config; + private final IntComponent mode; + + public AMAgent(EntityID agentID, Collection entities, Config config, int mode) { + this(); + this.agentID.setValue(agentID); + this.entities.setEntities(entities); + this.config.setConfig(config); + this.mode.setValue(mode); + } + + public AMAgent(InputStream inputStream) throws IOException { + this(); + read(inputStream); + } + + public AMAgent(RCRSProto.MessageProto messageProto) { + this(); + fromMessageProto(messageProto); + } + + private AMAgent() { + super(ModuleMessageURN.AM_AGENT); + this.agentID = new EntityIDComponent(ModuleMessageComponentURN.AgentID); + this.entities = new EntityListComponent(ModuleMessageComponentURN.Entities); + this.config = new ConfigComponent(ModuleMessageComponentURN.Config); + this.mode = new IntComponent(ModuleMessageComponentURN.Mode); + addMessageComponent(agentID); + addMessageComponent(entities); + addMessageComponent(config); + addMessageComponent(mode); + } + + public EntityID getAgentID() { + return this.agentID.getValue(); + } + + public List getEntities() { + return this.entities.getEntities(); + } + + public Config getConfig() { + return this.config.getConfig(); + } + + public int getMode() { + return this.mode.getValue(); + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/message/AMExec.java b/java/lib/src/main/java/adf_core_python/gateway/message/AMExec.java new file mode 100644 index 0000000..199f97d --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/message/AMExec.java @@ -0,0 +1,57 @@ +package adf_core_python.gateway.message; + +import adf_core_python.gateway.message.urn.ModuleMessageComponentURN; +import adf_core_python.gateway.message.urn.ModuleMessageURN; +import rescuecore2.config.Config; +import rescuecore2.messages.AbstractMessage; +import rescuecore2.messages.components.ConfigComponent; +import rescuecore2.messages.components.StringComponent; +import rescuecore2.messages.protobuf.RCRSProto; + +import java.io.IOException; +import java.io.InputStream; + +public class AMExec extends AbstractMessage { + private final StringComponent moduleID; + private final StringComponent methodName; + private final ConfigComponent arguments; + + public AMExec(String moduleID, String methodName, Config arguments) { + this(); + this.moduleID.setValue(moduleID); + this.methodName.setValue(methodName); + this.arguments.setConfig(arguments); + } + + public AMExec(InputStream inputStream) throws IOException { + this(); + read(inputStream); + } + + public AMExec(RCRSProto.MessageProto messageProto) { + this(); + fromMessageProto(messageProto); + } + + private AMExec() { + super(ModuleMessageURN.AM_MODULE); + this.moduleID = new StringComponent(ModuleMessageComponentURN.ModuleID); + this.methodName = new StringComponent(ModuleMessageComponentURN.MethodName); + this.arguments = new ConfigComponent(ModuleMessageComponentURN.Arguments); + addMessageComponent(moduleID); + addMessageComponent(methodName); + addMessageComponent(arguments); + } + + public String getModuleID() { + return this.moduleID.getValue(); + } + + public String getMethodName() { + return this.methodName.getValue(); + } + + public Config getArguments() { + return this.arguments.getConfig(); + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/message/AMModule.java b/java/lib/src/main/java/adf_core_python/gateway/message/AMModule.java new file mode 100644 index 0000000..a597897 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/message/AMModule.java @@ -0,0 +1,55 @@ +package adf_core_python.gateway.message; + +import adf_core_python.gateway.message.urn.ModuleMessageComponentURN; +import adf_core_python.gateway.message.urn.ModuleMessageURN; +import rescuecore2.messages.AbstractMessage; +import rescuecore2.messages.components.StringComponent; +import rescuecore2.messages.protobuf.RCRSProto; + +import java.io.IOException; +import java.io.InputStream; + +public class AMModule extends AbstractMessage { + private final StringComponent moduleID; + private final StringComponent moduleName; + private final StringComponent defaultClassName; + + public AMModule(String moduleID, String moduleName, String defaultClassName) { + this(); + this.moduleID.setValue(moduleID); + this.moduleName.setValue(moduleName); + this.defaultClassName.setValue(defaultClassName); + } + + public AMModule(InputStream inputStream) throws IOException { + this(); + read(inputStream); + } + + public AMModule(RCRSProto.MessageProto messageProto) { + this(); + fromMessageProto(messageProto); + } + + private AMModule() { + super(ModuleMessageURN.AM_MODULE); + this.moduleID = new StringComponent(ModuleMessageComponentURN.ModuleID); + this.moduleName = new StringComponent(ModuleMessageComponentURN.ModuleName); + this.defaultClassName = new StringComponent(ModuleMessageComponentURN.DefaultClassName); + addMessageComponent(moduleID); + addMessageComponent(moduleName); + addMessageComponent(defaultClassName); + } + + public String getModuleID() { + return this.moduleID.getValue(); + } + + public String getModuleName() { + return this.moduleName.getValue(); + } + + public String getDefaultClassName() { + return this.defaultClassName.getValue(); + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/message/AMUpdate.java b/java/lib/src/main/java/adf_core_python/gateway/message/AMUpdate.java new file mode 100644 index 0000000..ab3b03e --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/message/AMUpdate.java @@ -0,0 +1,61 @@ +package adf_core_python.gateway.message; + +import adf_core_python.gateway.message.urn.ModuleMessageComponentURN; +import adf_core_python.gateway.message.urn.ModuleMessageURN; +import rescuecore2.messages.AbstractMessage; +import rescuecore2.messages.Command; +import rescuecore2.messages.components.ChangeSetComponent; +import rescuecore2.messages.components.CommandListComponent; +import rescuecore2.messages.components.IntComponent; +import rescuecore2.messages.protobuf.RCRSProto; +import rescuecore2.worldmodel.ChangeSet; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; + +public class AMUpdate extends AbstractMessage { + private final IntComponent time; + private final ChangeSetComponent changed; + private final CommandListComponent heard; + + public AMUpdate(int time, ChangeSet changed, Collection heard) { + this(); + this.time.setValue(time); + this.changed.setChangeSet(changed); + this.heard.setCommands(heard); + } + + public AMUpdate(InputStream inputStream) throws IOException { + this(); + read(inputStream); + } + + public AMUpdate(RCRSProto.MessageProto messageProto) { + this(); + fromMessageProto(messageProto); + } + + private AMUpdate() { + super(ModuleMessageURN.AM_UPDATE); + this.time = new IntComponent(ModuleMessageComponentURN.Time); + this.changed = new ChangeSetComponent(ModuleMessageComponentURN.Changed); + this.heard = new CommandListComponent(ModuleMessageComponentURN.Heard); + addMessageComponent(this.time); + addMessageComponent(this.changed); + addMessageComponent(this.heard); + } + + public int getTime() { + return this.time.getValue(); + } + + public ChangeSet getChanged() { + return this.changed.getChangeSet(); + } + + public List getHeard() { + return this.heard.getCommands(); + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/message/MAExecResponse.java b/java/lib/src/main/java/adf_core_python/gateway/message/MAExecResponse.java new file mode 100644 index 0000000..e648838 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/message/MAExecResponse.java @@ -0,0 +1,49 @@ +package adf_core_python.gateway.message; + +import adf_core_python.gateway.message.urn.ModuleMessageComponentURN; +import adf_core_python.gateway.message.urn.ModuleMessageURN; +import rescuecore2.config.Config; +import rescuecore2.messages.AbstractMessage; +import rescuecore2.messages.components.ConfigComponent; +import rescuecore2.messages.components.StringComponent; +import rescuecore2.messages.protobuf.RCRSProto; + +import java.io.IOException; +import java.io.InputStream; + +public class MAExecResponse extends AbstractMessage { + private final StringComponent moduleID; + private final ConfigComponent result; + + public MAExecResponse(String moduleID, Config result) { + this(); + this.moduleID.setValue(moduleID); + this.result.setConfig(result); + } + + public MAExecResponse(InputStream inputStream) throws IOException { + this(); + read(inputStream); + } + + public MAExecResponse(RCRSProto.MessageProto messageProto) { + this(); + fromMessageProto(messageProto); + } + + private MAExecResponse() { + super(ModuleMessageURN.MA_EXEC_RESPONSE); + this.moduleID = new StringComponent(ModuleMessageComponentURN.ModuleID); + this.result = new ConfigComponent(ModuleMessageComponentURN.Result); + addMessageComponent(moduleID); + addMessageComponent(result); + } + + public String getModuleID() { + return this.moduleID.getValue(); + } + + public Config getResult() { + return this.result.getConfig(); + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/message/MAModuleResponse.java b/java/lib/src/main/java/adf_core_python/gateway/message/MAModuleResponse.java new file mode 100644 index 0000000..d568a61 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/message/MAModuleResponse.java @@ -0,0 +1,47 @@ +package adf_core_python.gateway.message; + +import adf_core_python.gateway.message.urn.ModuleMessageComponentURN; +import adf_core_python.gateway.message.urn.ModuleMessageURN; +import rescuecore2.messages.AbstractMessage; +import rescuecore2.messages.components.StringComponent; +import rescuecore2.messages.protobuf.RCRSProto; + +import java.io.IOException; +import java.io.InputStream; + +public class MAModuleResponse extends AbstractMessage { + private final StringComponent moduleID; + private final StringComponent className; + + public MAModuleResponse(String moduleID, String className) { + this(); + this.moduleID.setValue(moduleID); + this.className.setValue(className); + } + + public MAModuleResponse(InputStream inputStream) throws IOException { + this(); + read(inputStream); + } + + public MAModuleResponse(RCRSProto.MessageProto messageProto) { + this(); + fromMessageProto(messageProto); + } + + private MAModuleResponse() { + super(ModuleMessageURN.MA_MODULE_RESPONSE); + this.moduleID = new StringComponent(ModuleMessageComponentURN.ModuleID); + this.className = new StringComponent(ModuleMessageComponentURN.ClassName); + addMessageComponent(moduleID); + addMessageComponent(className); + } + + public String getModuleID() { + return this.moduleID.getValue(); + } + + public String getClassName() { + return this.className.getValue(); + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/message/ModuleControlMessageFactory.java b/java/lib/src/main/java/adf_core_python/gateway/message/ModuleControlMessageFactory.java new file mode 100644 index 0000000..3952131 --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/message/ModuleControlMessageFactory.java @@ -0,0 +1,42 @@ +package adf_core_python.gateway.message; + +import adf_core_python.gateway.message.urn.ModuleMessageURN; +import rescuecore2.messages.Message; +import rescuecore2.messages.protobuf.RCRSProto.MessageProto; + +import java.io.IOException; +import java.io.InputStream; + +public class ModuleControlMessageFactory { + public static Message makeMessage(int urn, InputStream inputStream) throws IOException { + return makeMessage(ModuleMessageURN.fromInt(urn), inputStream); + } + + public static Message makeMessage(ModuleMessageURN urn, InputStream inputStream) throws IOException { + switch (urn) { + case AM_AGENT -> new AMAgent(inputStream); + case AM_MODULE -> new AMModule(inputStream); + case MA_MODULE_RESPONSE -> new MAModuleResponse(inputStream); + case AM_UPDATE -> new AMUpdate(inputStream); + case AM_EXEC -> new AMExec(inputStream); + } + return null; + } + + public static Message makeMessage(int urn, MessageProto messageProto) throws IOException { + return makeMessage(ModuleMessageURN.fromInt(urn), messageProto); + } + + public static Message makeMessage(ModuleMessageURN urn, MessageProto messageProto) { + if (urn.equals(ModuleMessageURN.AM_AGENT)) { + return new AMAgent(messageProto); + } else if (urn.equals(ModuleMessageURN.AM_MODULE)) { + return new AMModule(messageProto); + } else if (urn.equals(ModuleMessageURN.AM_UPDATE)) { + return new AMUpdate(messageProto); + } else if (urn.equals(ModuleMessageURN.AM_EXEC)) { + return new AMExec(messageProto); + } + return null; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/message/urn/ModuleMessageComponentURN.java b/java/lib/src/main/java/adf_core_python/gateway/message/urn/ModuleMessageComponentURN.java new file mode 100644 index 0000000..868439c --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/message/urn/ModuleMessageComponentURN.java @@ -0,0 +1,52 @@ +package adf_core_python.gateway.message.urn; + +import rescuecore2.URN; + +import java.util.Map; + +public enum ModuleMessageComponentURN implements URN { + AgentID(0x0400 | 1, "Agent ID"), + Entities(0x0400 | 2, "Entities"), + Config(0x0400 | 3, "Entities"), + Mode(0x0400 | 4, "Entities"), + ModuleID(0x0400 | 5, "Module ID"), + ModuleName(0x0400 | 6, "Module Name"), + DefaultClassName(0x0400 | 7, "Default Class Name"), + ClassName(0x0400 | 8, "Class Name"), + Time(0x0400 | 9, "Time"), + Changed(0x0400 | 10, "Changed"), + Heard(0x0400 | 11, "Heard"), + MethodName(0x0400 | 12, "Method Name"), + Arguments(0x0400 | 13, "Arguments"), + Result(0x0400 | 14, "Result"); + + + public static final Map MAP = URN.generateMap(ModuleMessageComponentURN.class); + public static final Map MAP_STR = URN + .generateMapStr(ModuleMessageComponentURN.class); + private final int urnId; + private final String urnStr; + + ModuleMessageComponentURN(int urnId, String urnStr) { + this.urnId = urnId; + this.urnStr = urnStr; + } + + public static ModuleMessageComponentURN fromInt(int urnId) { + return MAP.get(urnId); + } + + public static ModuleMessageComponentURN fromString(String urnStr) { + return MAP_STR.get(urnStr); + } + + @Override + public int getURNId() { + return urnId; + } + + @Override + public String getURNStr() { + return urnStr; + } +} diff --git a/java/lib/src/main/java/adf_core_python/gateway/message/urn/ModuleMessageURN.java b/java/lib/src/main/java/adf_core_python/gateway/message/urn/ModuleMessageURN.java new file mode 100644 index 0000000..8c90a4e --- /dev/null +++ b/java/lib/src/main/java/adf_core_python/gateway/message/urn/ModuleMessageURN.java @@ -0,0 +1,42 @@ +package adf_core_python.gateway.message.urn; + +import rescuecore2.URN; + +import java.util.Map; + +public enum ModuleMessageURN implements URN { + AM_AGENT(0x0300 | 1, "urn:adf_core_python.gateway.messages:am_agent"), + AM_MODULE(0x0300 | 2, "urn:adf_core_python.gateway.messages:am_module"), + MA_MODULE_RESPONSE(0x0300 | 3, "urn:adf_core_python.gateway.messages:am_module_response"), + AM_UPDATE(0x0300 | 4, "urn:adf_core_python.gateway.messages:am_update"), + AM_EXEC(0x0300 | 5, "urn:adf_core_python.gateway.messages:am_exec"), + MA_EXEC_RESPONSE(0x0300 | 6, "urn:adf_core_python.gateway.messages:am_exec_response"); + + public static final Map MAP = URN.generateMap(ModuleMessageURN.class); + public static final Map MAP_STR = URN.generateMapStr(ModuleMessageURN.class); + private final int urnId; + private final String urnStr; + + private ModuleMessageURN(int urnId, String urnStr) { + this.urnId = urnId; + this.urnStr = urnStr; + } + + public static ModuleMessageURN fromInt(int s) { + return MAP.get(s); + } + + public static ModuleMessageURN fromString(String urn) { + return MAP_STR.get(urn); + } + + @Override + public int getURNId() { + return urnId; + } + + @Override + public String getURNStr() { + return urnStr; + } +} diff --git a/java/lib/src/main/resources/log4j2.xml b/java/lib/src/main/resources/log4j2.xml new file mode 100644 index 0000000..893c33d --- /dev/null +++ b/java/lib/src/main/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/java/lib/src/test/java/org/example/LibraryTest.java b/java/lib/src/test/java/org/example/LibraryTest.java new file mode 100644 index 0000000..01e3af0 --- /dev/null +++ b/java/lib/src/test/java/org/example/LibraryTest.java @@ -0,0 +1,14 @@ +/* + * This source file was generated by the Gradle 'init' task + */ +package org.example; + +import org.junit.jupiter.api.Test; + +class LibraryTest { + @Test + void someLibraryMethodReturnsTrue() { +// Library classUnderTest = new Library(); +// assertTrue(classUnderTest.someLibraryMethod(), "someLibraryMethod should return 'true'"); + } +} diff --git a/java/settings.gradle b/java/settings.gradle new file mode 100644 index 0000000..2e78246 --- /dev/null +++ b/java/settings.gradle @@ -0,0 +1,14 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * For more detailed information on multi-project builds, please refer to https://docs.gradle.org/8.10.2/userguide/multi_project_builds.html in the Gradle documentation. + */ + +plugins { + // Apply the foojay-resolver plugin to allow automatic download of JDKs + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0' +} + +rootProject.name = 'adf-core-python' +include('lib') diff --git a/poetry.lock b/poetry.lock index 11eee0e..1b520aa 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,4 +1,4 @@ -# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand. +# This file is automatically @generated by Poetry 1.8.4 and should not be changed by hand. [[package]] name = "accessible-pygments" @@ -939,7 +939,7 @@ rtree = "*" type = "git" url = "https://github.com/adf-python/rcrs-core-python" reference = "HEAD" -resolved_reference = "aa661b19c98f82d8d648317f386c2f9d2c26a8fc" +resolved_reference = "42a20e312de20ea46f1e0622a82f41e81fc3514f" [[package]] name = "requests" @@ -1029,6 +1029,11 @@ files = [ {file = "scikit_learn-1.5.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f60021ec1574e56632be2a36b946f8143bf4e5e6af4a06d85281adc22938e0dd"}, {file = "scikit_learn-1.5.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:394397841449853c2290a32050382edaec3da89e35b3e03d6cc966aebc6a8ae6"}, {file = "scikit_learn-1.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:57cc1786cfd6bd118220a92ede80270132aa353647684efa385a74244a41e3b1"}, + {file = "scikit_learn-1.5.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e9a702e2de732bbb20d3bad29ebd77fc05a6b427dc49964300340e4c9328b3f5"}, + {file = "scikit_learn-1.5.2-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:b0768ad641981f5d3a198430a1d31c3e044ed2e8a6f22166b4d546a5116d7908"}, + {file = "scikit_learn-1.5.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:178ddd0a5cb0044464fc1bfc4cca5b1833bfc7bb022d70b05db8530da4bb3dd3"}, + {file = "scikit_learn-1.5.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f7284ade780084d94505632241bf78c44ab3b6f1e8ccab3d2af58e0e950f9c12"}, + {file = "scikit_learn-1.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:b7b0f9a0b1040830d38c39b91b3a44e1b643f4b36e36567b80b7c6bd2202a27f"}, {file = "scikit_learn-1.5.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:757c7d514ddb00ae249832fe87100d9c73c6ea91423802872d9e74970a0e40b9"}, {file = "scikit_learn-1.5.2-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:52788f48b5d8bca5c0736c175fa6bdaab2ef00a8f536cda698db61bd89c551c1"}, {file = "scikit_learn-1.5.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:643964678f4b5fbdc95cbf8aec638acc7aa70f5f79ee2cdad1eec3df4ba6ead8"},