Files
colony/colony/core/roles/role.py
T
2026-01-27 22:26:03 +01:00

59 lines
1.6 KiB
Python

import threading
from colony.core.context import RoleContext
from colony.core.logger.logging import get_logger
class Command:
def __init__(self, callback):
self.callback = callback
class Role:
CONTINUOUS = None
LOOP_SECONDS_WAIT = None
def __init__(self, commands, context: RoleContext):
self.commands = commands
self.context = context
self._stop_event = threading.Event()
self._thread = None
if self.CONTINUOUS and self.LOOP_SECONDS_WAIT is None:
raise NotImplementedError("You made this role to run continuously but have not set seconds to wait. Please set constant variable LOOP_SECONDS_WAIT. ")
self.logger = get_logger(self.__class__.__name__)
self.logger.info(f'{self.__class__.__name__} initialized and ready')
def __str__(self):
return self.__class__.__name__
def start(self):
if not self.CONTINUOUS:
return
self._thread = threading.Thread(target=self._run_loop, daemon=True, name=str(self))
self._thread.start()
def _run_loop(self):
while not self._stop_event.is_set():
self.loop()
self._stop_event.wait(self.LOOP_SECONDS_WAIT)
def loop(self):
if self.CONTINUOUS:
raise NotImplementedError("Continuous roles must implement loop()")
def stop(self):
self._stop_event.set()
def execute_local(self, name, *args, **kwargs):
command = self.commands.get(name)
if not command:
raise ValueError(f"No command {name}")
return command.callback(*args, **kwargs)