import asyncio import json import logging from spade.agent import Message from spade.behaviour import CyclicBehaviour from spade_bdi.bdi import BDIAgent from control_backend.core.config import settings class BeliefSetter(CyclicBehaviour): """ This is the behaviour that the BDI agent runs. This behaviour waits for incoming message and processes it based on sender. Currently, it only waits for messages containing beliefs from BeliefCollector and adds these to its KB. """ agent: BDIAgent logger = logging.getLogger("BDI/Belief Setter") async def run(self): msg = await self.receive(timeout=0.1) if msg: self.logger.info(f"Received message {msg.body}") self._process_message(msg) await asyncio.sleep(1) def _process_message(self, message: Message): sender = message.sender.node # removes host from jid and converts to str self.logger.debug("Sender: %s", sender) match sender: case settings.agent_settings.belief_collector_agent_name: self.logger.debug("Processing message from belief collector.") self._process_belief_message(message) case _: pass def _process_belief_message(self, message: Message): if not message.body: return match message.thread: case "beliefs": try: beliefs: dict[str, list[list[str]]] = json.loads(message.body) self._set_beliefs(beliefs) except json.JSONDecodeError as e: self.logger.error("Could not decode beliefs into JSON format: %s", e) case _: pass def _set_beliefs(self, beliefs: dict[str, list[list[str]]]): if self.agent.bdi is None: self.logger.warning("Cannot set beliefs, since agent's BDI is not yet initialized.") return for belief, arguments_list in beliefs.items(): for arguments in arguments_list: self.agent.bdi.set_belief(belief, *arguments) self.logger.info("Set belief %s with arguments %s", belief, arguments)