From afc7fef0144f4257cc7d3b40e21616d3b82e020e Mon Sep 17 00:00:00 2001 From: Javier Izquierdo Hernandez Date: Tue, 29 Sep 2026 11:15:15 +0200 Subject: [PATCH 01/12] Migrate wobsocket and gazebo --- .../comms/__init__.py | 2 +- .../comms/consumer.py | 129 ++++++++++++++++++ .../libs/process_utils.py | 9 +- robotics_application_manager/libs/server.py | 85 +++++++----- .../manager/docker_thread/docker_thread.py | 35 +++-- .../manager/launcher/launcher_gzsim.py | 10 +- .../manager/launcher/launcher_interface.py | 10 +- .../manager/launcher/launcher_robot.py | 8 +- .../manager/launcher/launcher_ros2_gz_api.py | 6 +- .../manager/launcher/launcher_scene.py | 8 +- .../launcher/launcher_state_monitor.py | 4 +- .../manager/launcher/launcher_tools.py | 12 +- .../manager/launcher/launcher_web_gui.py | 20 ++- .../manager/manager.py | 105 +++++++------- 14 files changed, 302 insertions(+), 141 deletions(-) create mode 100644 robotics_application_manager/comms/consumer.py diff --git a/robotics_application_manager/comms/__init__.py b/robotics_application_manager/comms/__init__.py index 939cc1a..808cda8 100644 --- a/robotics_application_manager/comms/__init__.py +++ b/robotics_application_manager/comms/__init__.py @@ -5,7 +5,7 @@ between the manager backend and client applications. """ -from .new_consumer import ManagerConsumer +from .consumer import ManagerConsumer from .consumer_message import ManagerConsumerMessageException, ManagerConsumerMessage from .thread import ThreadWithLoggedException, WebsocketServerThread from .websocket_server import WebsocketServer diff --git a/robotics_application_manager/comms/consumer.py b/robotics_application_manager/comms/consumer.py new file mode 100644 index 0000000..4a20c20 --- /dev/null +++ b/robotics_application_manager/comms/consumer.py @@ -0,0 +1,129 @@ +""" +WebSocket consumer module for the Robotics Application Manager (RAM). + +Handles client connections, message processing, and communication with manager queue. +""" + +import json +import logging +from queue import Queue +from uuid import uuid4 +from datetime import datetime + +from .consumer_message import ( + ManagerConsumerMessageException, + ManagerConsumerMessage, +) +from .websocket_server import WebsocketServer +from robotics_application_manager import LogManager +from websockets.asyncio.server import serve +import asyncio + +class ManagerConsumer: + """ + Websocket server consumer for new Robotics Application Manager aka: RAM. + + Supports single client connection to RAM + TODO: Better handling of single client connections, closing and redirecting + """ + + def __init__(self, host, port, process_callback): + """ + Initialize the ManagerConsumer with host, port, and manager_queue. + + Args: + host (str): The host address for the WebSocket server. + port (int): The port number for the WebSocket server. + manager_queue (Queue): The queue for communication with the manager. + """ + self.host = host + self.port = port + self.client = None + self.process_callback = process_callback + self.server_task = None + + # Configurar el logger de websocket_server para salida a consola + ws_logger = logging.getLogger("websocket_server.websocket_server") + ws_logger.propagate = False + ws_logger.setLevel(logging.INFO) + ws_logger.handlers.clear() + ws_formatter = logging.Formatter( + "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] " + "(%(name)s) %(message)s", + "%H:%M:%S", + ) + ws_console_handler = logging.StreamHandler() + ws_console_handler.setFormatter(ws_formatter) + ws_logger.addHandler(ws_console_handler) + + # Use the __await__ method to make the class awaitable + def __await__(self): + # Call ls the constructor and returns the instance + return self.create().__await__() + + # A method that creates an instance of the class asynchronously + async def create(self): + self.server = await serve(self.manage_conection, self.host, self.port) + return self + + async def manage_conection(self, websocket): + if self.client is not None: + await websocket.close() + return + + try: + self.client = websocket # Register client + LogManager.logger.info(f"client connected: {self.client}") + + await self.process_msg(websocket) + finally: + now = datetime.now() + time_str = now.strftime("%H:%M:%S") + LogManager.logger.info(f"Client disconnected {time_str}: {self.client}") + message = ManagerConsumerMessage(id=str(uuid4()), command="disconnect") + await self.send_message(message) + self.client = None + + async def process_msg(self, websocket): + while True: + async for raw_msg in websocket: + try: + json_msg = json.loads(raw_msg) + await self.process_callback(ManagerConsumerMessage(**json_msg)) + except Exception as e: + ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) + await self.send_message(ex) + LogManager.logger.error(e, exc_info=True) + + async def send_message(self, message_data, command=None): + """ + Send a message to the connected client. + + Args: + message_data: The message data to send, can be a ManagerConsumerMessage, + ManagerConsumerMessageException, or other data. + command (str, optional): The command associated with the message, + used if message_data is not a ManagerConsumerMessage. + """ + if self.client is not None and self.server is not None: + if isinstance(message_data, ManagerConsumerMessage): + message = message_data + elif isinstance(message_data, ManagerConsumerMessageException): + message = message_data.consumer_message() + else: + message = ManagerConsumerMessage( + id=str(uuid4()), command=command, data=message_data + ) + + await self.client.send(str(message)) + + def start(self): + """Start the WebSocket server in a separate thread.""" + self.server_task = asyncio.create_task(self.server.serve_forever()) + + async def stop(self): + """Stop the WebSocket server gracefully.""" + await self.server.close() + if self.server_task is not None: + self.server_task.cancel() + await self.server_task diff --git a/robotics_application_manager/libs/process_utils.py b/robotics_application_manager/libs/process_utils.py index 56126d9..49da0a3 100644 --- a/robotics_application_manager/libs/process_utils.py +++ b/robotics_application_manager/libs/process_utils.py @@ -8,7 +8,7 @@ import subprocess import zipfile import base64 - +import importlib import psutil from robotics_application_manager import LogManager @@ -17,10 +17,9 @@ def get_class(kls): parts = kls.split(".") module = ".".join(parts[:-1]) - m = __import__(module) - for comp in parts[1:]: - m = getattr(m, comp) - return m + m = importlib.import_module(module) + imp_class = getattr(m,parts[-1]) + return imp_class def get_class_from_file(file_path: str, class_name: str): diff --git a/robotics_application_manager/libs/server.py b/robotics_application_manager/libs/server.py index 7bb488c..a836397 100644 --- a/robotics_application_manager/libs/server.py +++ b/robotics_application_manager/libs/server.py @@ -1,56 +1,77 @@ import threading import json -from websocket_server import WebsocketServer +from websockets.asyncio.server import serve +import asyncio from robotics_application_manager import LogManager -class Server(threading.Thread): +class Server: def __init__( self, port, callback, ): - super().__init__() + self.port = port self.update_callback = callback - self.server = WebsocketServer(port=port, host="127.0.0.1") - self.server.set_fn_new_client(self.on_open) - self.server.set_fn_client_left(self.on_close) - self.server.set_fn_message_received(self.on_message) - self.current_client = None + self.client = None self.client_lock = threading.Lock() # Used to avoid concurrency problems self._stop = threading.Event() LogManager.logger.info("Server Launched") - def run(self) -> None: - try: - while not self._stop.is_set(): - self.server.run_forever() - except Exception as ex: - LogManager.logger.exception(ex) + # Use the __await__ method to make the class awaitable + def __await__(self): + # Call ls the constructor and returns the instance + return self.create().__await__() - def stop(self) -> None: - self._stop.set() - self.server.shutdown_gracefully() + # A method that creates an instance of the class asynchronously + async def create(self): + self.server = await serve(self.manage_conection, "127.0.0.1", self.port) + return self - def send(self, data): + async def manage_conection(self, websocket): with self.client_lock: - if self.current_client is not None: - self.server.send_message(self.current_client, data) + if self.client is not None: + await websocket.close() + return - def on_message(self, client, server, message): - payload = json.loads(message) - self.update_callback(payload) - LogManager.logger.debug(f"Message received from template: {message[:30]}") + try: + with self.client_lock: + self.client = websocket # Register client + LogManager.logger.info(f"Client connected: {self.client}") - def on_close(self, client, server): - LogManager.logger.info("Connection with client closed") - with self.client_lock: - if client == self.current_client: - self.current_client = None + await self.process_msg(websocket) + finally: + LogManager.logger.info("Connection with client closed") + await self.send_message(message) + with self.client_lock: + self.client = None - def on_open(self, client, server): - LogManager.logger.info(f"New client connected {client}") + async def process_msg(self, websocket): + while True: + async for raw_msg in websocket: + try: + json_msg = json.loads(raw_msg) + LogManager.logger.debug(f"Message received from template: {raw_msg[:30]}") + await self.update_callback(json_msg) + except Exception as e: + ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) + await self.send_message(ex) + LogManager.logger.error(e, exc_info=True) + + async def send(self, data): with self.client_lock: - self.current_client = client + if self.client is not None: + await self.client.send(data) + + def start(self): + """Start the WebSocket server in a separate thread.""" + self.server_task = asyncio.create_task(self.server.serve_forever()) + + async def stop(self): + """Stop the WebSocket server gracefully.""" + await self.server.close() + if self.server_task is not None: + self.server_task.cancel() + await self.server_task diff --git a/robotics_application_manager/manager/docker_thread/docker_thread.py b/robotics_application_manager/manager/docker_thread/docker_thread.py index 27ba677..9b97099 100644 --- a/robotics_application_manager/manager/docker_thread/docker_thread.py +++ b/robotics_application_manager/manager/docker_thread/docker_thread.py @@ -10,23 +10,36 @@ class DockerThread(threading.Thread): """Threaded Docker Thread Class""" - def __init__(self, cmd, shell=True): + def __init__(self, cmd, shell=True, debug=False): threading.Thread.__init__(self) self.cmd = cmd self.process = None self.shell = shell + self.debug = debug def run(self): - self.process = subprocess.Popen( - self.cmd, - shell=self.shell, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - start_new_session=True, - bufsize=1024, - universal_newlines=True, - executable="/bin/bash", - ) + if self.debug: + self.process = subprocess.Popen( + self.cmd, + shell=self.shell, + stdout=sys.stdout, + stderr=sys.stdout, + start_new_session=True, + bufsize=1024, + universal_newlines=True, + executable="/bin/bash", + ) + else: + self.process = subprocess.Popen( + self.cmd, + shell=self.shell, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + start_new_session=True, + bufsize=1024, + universal_newlines=True, + executable="/bin/bash", + ) self.process.communicate() def terminate(self): diff --git a/robotics_application_manager/manager/launcher/launcher_gzsim.py b/robotics_application_manager/manager/launcher/launcher_gzsim.py index e375100..f0e7207 100644 --- a/robotics_application_manager/manager/launcher/launcher_gzsim.py +++ b/robotics_application_manager/manager/launcher/launcher_gzsim.py @@ -13,11 +13,11 @@ from typing import List, Any from robotics_application_manager import LogManager -from gz.msgs10.world_control_pb2 import WorldControl -from gz.msgs10.world_reset_pb2 import WorldReset -from gz.msgs10.entity_pb2 import Entity -from gz.msgs10.boolean_pb2 import Boolean -from gz.transport13 import Node +from gz.msgs.world_control_pb2 import WorldControl +from gz.msgs.world_reset_pb2 import WorldReset +from gz.msgs.entity_pb2 import Entity +from gz.msgs.boolean_pb2 import Boolean +from gz.transport import Node class LauncherGzsim(ILauncher): diff --git a/robotics_application_manager/manager/launcher/launcher_interface.py b/robotics_application_manager/manager/launcher/launcher_interface.py index 7654eee..01a9a82 100644 --- a/robotics_application_manager/manager/launcher/launcher_interface.py +++ b/robotics_application_manager/manager/launcher/launcher_interface.py @@ -5,6 +5,12 @@ class ILauncher(BaseModel): + def __await__(self): + return self.create().__await__() + + async def create(self): + return self + def run(self, callback: callable): raise NotImplemented("Launcher must implement run method") @@ -17,8 +23,8 @@ def terminate(self): def died(self, callback): raise NotImplemented("Launcher must implement run method") - def from_config(cls, config): - obj = cls(**config) + async def from_config(cls, config): + obj = await cls(**config) return obj @staticmethod diff --git a/robotics_application_manager/manager/launcher/launcher_robot.py b/robotics_application_manager/manager/launcher/launcher_robot.py index f5cb89d..a53374d 100644 --- a/robotics_application_manager/manager/launcher/launcher_robot.py +++ b/robotics_application_manager/manager/launcher/launcher_robot.py @@ -46,7 +46,7 @@ class LauncherRobot(BaseModel): entity: str = "" start_pose: Optional[list] = [] - def run(self, entity="", start_pose=None, extra_config=None): + async def run(self, entity="", start_pose=None, extra_config=None): """Run the robot launcher with an optional start pose.""" self.entity = entity @@ -58,7 +58,7 @@ def run(self, entity="", start_pose=None, extra_config=None): for module in worlds[self.type][str(self.ros_version)]: module["launch_file"] = self.launch_file_path - launcher = self.launch_module(module, extra_config) + launcher = await self.launch_module(module, extra_config) self.launchers.append(launcher) LogManager.logger.info(self.launchers) @@ -70,7 +70,7 @@ def terminate(self): launcher.terminate() self.launchers = [] - def launch_module(self, configuration, extra_config=None): + async def launch_module(self, configuration, extra_config=None): """Launch a robot module based on the provided configuration.""" def process_terminated(name, exit_code): @@ -86,7 +86,7 @@ def process_terminated(name, exit_code): f"Launcher{class_from_module(launcher_module_name)}" ) launcher_class = get_class(launcher_module) - launcher = launcher_class.from_config(launcher_class, configuration) + launcher = await launcher_class.from_config(launcher_class, configuration) launcher.run(self.entity, self.start_pose, extra_config, process_terminated) return launcher diff --git a/robotics_application_manager/manager/launcher/launcher_ros2_gz_api.py b/robotics_application_manager/manager/launcher/launcher_ros2_gz_api.py index e941443..4ae071f 100644 --- a/robotics_application_manager/manager/launcher/launcher_ros2_gz_api.py +++ b/robotics_application_manager/manager/launcher/launcher_ros2_gz_api.py @@ -11,9 +11,9 @@ from robotics_application_manager.manager.docker_thread import DockerThread import subprocess from robotics_application_manager import LogManager -from gz.transport13 import Node -from gz.msgs10.empty_pb2 import Empty -from gz.msgs10.scene_pb2 import Scene +from gz.transport import Node +from gz.msgs.empty_pb2 import Empty +from gz.msgs.scene_pb2 import Scene import logging diff --git a/robotics_application_manager/manager/launcher/launcher_scene.py b/robotics_application_manager/manager/launcher/launcher_scene.py index 61cd650..9b4565e 100644 --- a/robotics_application_manager/manager/launcher/launcher_scene.py +++ b/robotics_application_manager/manager/launcher/launcher_scene.py @@ -55,10 +55,10 @@ class LauncherScene(BaseModel): ros_version: int = get_ros_version() launchers: Optional[ILauncher] = [] - def run(self): + async def run(self): for module in worlds[self.type][str(self.ros_version)]: module["launch_file"] = self.launch_file_path - launcher = self.launch_module(module) + launcher = await self.launch_module(module) self.launchers.append(launcher) def terminate(self): @@ -68,7 +68,7 @@ def terminate(self): launcher.terminate() self.launchers = [] - def launch_module(self, configuration): + async def launch_module(self, configuration): def process_terminated(name, exit_code): LogManager.logger.info( f"LauncherEngine: {name} exited with code {exit_code}" @@ -79,7 +79,7 @@ def process_terminated(name, exit_code): launcher_module_name = configuration["module"] launcher_module = f"{self.module}.launcher_{launcher_module_name}.Launcher{class_from_module(launcher_module_name)}" launcher_class = get_class(launcher_module) - launcher = launcher_class.from_config(launcher_class, configuration) + launcher = await launcher_class.from_config(launcher_class, configuration) launcher.run(process_terminated) return launcher diff --git a/robotics_application_manager/manager/launcher/launcher_state_monitor.py b/robotics_application_manager/manager/launcher/launcher_state_monitor.py index 94208d6..406dd30 100644 --- a/robotics_application_manager/manager/launcher/launcher_state_monitor.py +++ b/robotics_application_manager/manager/launcher/launcher_state_monitor.py @@ -15,10 +15,10 @@ def __init__(self, type, module, file, consumer): self.consumer = consumer self.server = FileWatchdog("/tmp/tree_state", self.update) - def update(self, data): + async def update(self, data): LogManager.logger.debug(f"Sending update to client") if self.consumer is not None: - self.consumer.send_message({"update": data}, command="update") + await self.consumer.send_message({"update": data}, command="update") def run(self, config_file, callback): self.server.start() diff --git a/robotics_application_manager/manager/launcher/launcher_tools.py b/robotics_application_manager/manager/launcher/launcher_tools.py index 3000042..3f190d2 100644 --- a/robotics_application_manager/manager/launcher/launcher_tools.py +++ b/robotics_application_manager/manager/launcher/launcher_tools.py @@ -71,7 +71,7 @@ class LauncherTools(BaseModel): tools_config: Optional[dict] = None launchers: Optional[ILauncher] = [] - def run(self, consumer): + async def run(self, consumer): for tool in self.tools: if tool == "simulator": if self.world_type is None or self.world_type == "physical": @@ -80,7 +80,7 @@ def run(self, consumer): module = tools[tool] if module["module"] is None: continue - launcher = self.launch_module(tool, module, consumer) + launcher = await self.launch_module(tool, module, consumer) self.launchers.append(launcher) def terminate(self): @@ -90,7 +90,7 @@ def terminate(self): launcher.terminate() self.launchers = [] - def launch_module(self, name, configuration, consumer): + async def launch_module(self, name, configuration, consumer): def process_terminated(name, exit_code): LogManager.logger.info( f"LauncherEngine: {name} exited with code {exit_code}" @@ -109,7 +109,7 @@ def process_terminated(name, exit_code): if self.tools_config is not None and name in self.tools_config: config = self.tools_config[name] - launcher = launcher_class.from_config(launcher_class, configuration) + launcher = await launcher_class.from_config(launcher_class, configuration) launcher.run(config, process_terminated) return launcher @@ -125,10 +125,10 @@ def reset(self, robot_entities=[]): for launcher in self.launchers: launcher.reset(robot_entities) - def pass_msg(self, data): + async def pass_msg(self, data): for launcher in self.launchers: if launcher.acceptsMsgs: - launcher.get_msg(data) + await launcher.get_msg(data) def launch_command(self, configuration): pass diff --git a/robotics_application_manager/manager/launcher/launcher_web_gui.py b/robotics_application_manager/manager/launcher/launcher_web_gui.py index 00f9306..0fc0540 100644 --- a/robotics_application_manager/manager/launcher/launcher_web_gui.py +++ b/robotics_application_manager/manager/launcher/launcher_web_gui.py @@ -13,19 +13,25 @@ class LauncherWebGui: def __init__(self, type, module, internal_port, consumer): self.internal_port = internal_port self.consumer = consumer - self.server = Server(self.internal_port, self.update) - def update(self, data): + def __await__(self): + return self.create().__await__() + + async def create(self): + self.server = await Server(self.internal_port, self.update) + return self + + async def update(self, data): LogManager.logger.debug(f"Sending update to client") if self.consumer is not None: - self.consumer.send_message({"update": data}, command="update") + await self.consumer.send_message({"update": data}, command="update") def run(self, config_file, callback): self.server.start() self.running = True - def get_msg(self, data): - self.server.send(data) + async def get_msg(self, data): + await self.server.send(data) def is_running(self): return self.running @@ -46,6 +52,6 @@ def reset(self, robot_entities=[]): def died(self): pass - def from_config(cls, config): - obj = cls(**config) + async def from_config(cls, config): + obj = await cls(**config) return obj diff --git a/robotics_application_manager/manager/manager.py b/robotics_application_manager/manager/manager.py index 9b5a44c..0dd5750 100644 --- a/robotics_application_manager/manager/manager.py +++ b/robotics_application_manager/manager/manager.py @@ -23,10 +23,11 @@ import zipfile import jedi import traceback +import asyncio from queue import Queue from uuid import uuid4 -from transitions import Machine +from transitions.extensions import AsyncMachine from robotics_application_manager.comms import ( ManagerConsumerMessageException, ManagerConsumer, @@ -211,7 +212,7 @@ def __init__(self, host: str, port: int): host (str): The host address to listen to. port (int): The port number to listen to. """ - self.machine = Machine( + self.machine = AsyncMachine( model=self, states=Manager.states, transitions=Manager.transitions, @@ -220,8 +221,7 @@ def __init__(self, host: str, port: int): after_state_change=self.state_change, ) self.ros_version = subprocess.check_output(["bash", "-c", "echo $ROS_DISTRO"]) - self.queue = Queue() - self.consumer = ManagerConsumer(host, port, self.queue) + self.consumer = None self.scene_launcher = None self.world_type = None self.robot_launchers = [] @@ -230,6 +230,8 @@ def __init__(self, host: str, port: int): self.application_processes = [] self.running = True self.linter = Lint() + self.host = host + self.port = port # Creates workspace directories worlds_dir = "/workspace/worlds" @@ -242,7 +244,7 @@ def __init__(self, host: str, port: int): if not os.path.isdir(binaries_dir): os.makedirs(binaries_dir) - def state_change(self, event): + async def state_change(self, event): """ Handle actions to be performed after a state change in the state machine. @@ -251,9 +253,9 @@ def state_change(self, event): """ LogManager.logger.info(f"State changed to {self.state}") if self.consumer is not None: - self.consumer.send_message({"state": self.state}, command="state-changed") + await self.consumer.send_message({"state": self.state}, command="state-changed") - def update(self, data): + async def update(self, data): """ Send an update message to the client with the provided data. @@ -262,9 +264,9 @@ def update(self, data): """ LogManager.logger.debug("Sending update to client") if self.consumer is not None: - self.consumer.send_message({"update": data}, command="update") + await self.consumer.send_message({"update": data}, command="update") - def update_bt_studio(self, data): + async def update_bt_studio(self, data): """ Send an update message to the client for BT Studio with the provided data. @@ -273,9 +275,9 @@ def update_bt_studio(self, data): """ LogManager.logger.debug("Sending update to client") if self.consumer is not None: - self.consumer.send_message({"update": data}, command="update") + await self.consumer.send_message({"update": data}, command="update") - def on_connect(self, event): + async def on_connect(self, event): """ Triggered when the application transitions to the 'connected' state. @@ -289,7 +291,7 @@ def on_connect(self, event): - `ros_version`: The current ROS (Robot Operating System) distribution version. - `gpu_avaliable`: Boolean indicating whether GPU acceleration is available. """ - self.consumer.send_message( + await self.consumer.send_message( { "robotics_backend_version": subprocess.check_output( ["bash", "-c", "echo $IMAGE_TAG"] @@ -300,7 +302,7 @@ def on_connect(self, event): command="introspection", ) - def on_launch_world(self, event): + async def on_launch_world(self, event): """ Handle the 'launch' event, transitioning the application from 'connected' to 'ready' state. @@ -396,19 +398,19 @@ def make_unique(cfgs, key, param=None): self.robot_configs.append(robot_cfg) LogManager.logger.info(str(robot_launcher)) - self.scene_launcher.run() + await self.scene_launcher.run() robots_data = zip(self.robot_launchers, self.robot_configs) entities = [] for launcher, cfg in robots_data: - launcher.run(cfg["entity"], cfg["start_pose"], cfg["extra_config"]) + await launcher.run(cfg["entity"], cfg["start_pose"], cfg["extra_config"]) entities.append(cfg["entity"]) self.scene_launcher.wait_robots_spawn(entities) LogManager.logger.info("Launch transition finished") - def prepare_custom_world(self, cfg_dict): + async def prepare_custom_world(self, cfg_dict): """ Prepare and extract a custom world from a base64-encoded zip file. @@ -445,7 +447,7 @@ def prepare_custom_world(self, cfg_dict): '/bin/bash -c "cd /workspace/worlds; source /opt/ros/humble/setup.bash; colcon build --symlink-install; source install/setup.bash; cd ../.."' ) - def on_prepare_tools(self, event): + async def on_prepare_tools(self, event): LogManager.logger.info("Tools transition started") @@ -457,7 +459,7 @@ def on_prepare_tools(self, event): world_type=self.world_type, tools=tools, tools_config=config ) - self.tools_launcher.run(self.consumer) + await self.tools_launcher.run(self.consumer) LogManager.logger.info("Tools transition finished") def write_to_tool_terminal(self, msg): @@ -481,7 +483,7 @@ def write_to_tool_terminal(self, msg): with open(i, "w") as console: console.write(msg) - def on_style_check_application(self, event): + async def on_style_check_application(self, event): """ Handle the 'style_check' event. @@ -527,7 +529,7 @@ def on_style_check_application(self, event): self.write_to_tool_terminal(errors + "\n\n") raise Exception(errors) - def on_code_analysis(self, event): + async def on_code_analysis(self, event): """ Handle the 'code_analysis' event. @@ -592,7 +594,7 @@ def on_code_analysis(self, event): command="code-analysis", ) - def on_code_format(self, event): + async def on_code_format(self, event): """ Handle the 'code_format' event. @@ -764,7 +766,7 @@ def on_change_style(self, event): except Exception as e: LogManager.logger.exception(f"Error refreshing GTK applications: {e}") - def on_run_application(self, event): + async def on_run_application(self, event): """ Handle the 'run_application' event. @@ -886,7 +888,7 @@ def on_run_application(self, event): LogManager.logger.info("Run application transition finished") - def on_terminate_application(self, event): + async def on_terminate_application(self, event): """ Handle the 'terminate_application' event. @@ -901,19 +903,18 @@ def on_terminate_application(self, event): stop_process_and_children(process) except Exception: LogManager.logger.exception("No application running") - print(traceback.format_exc()) if len(self.application_processes) > 0: self.pause_sim() - self.reset_sim() + await self.reset_sim() self.application_processes = [] - def on_terminate_tools(self, event): + async def on_terminate_tools(self, event): self.tools_launcher.terminate() self.tools_launcher = None - def on_terminate_world(self, event): + async def on_terminate_world(self, event): """ Handle the 'terminate_world' event. @@ -932,7 +933,7 @@ def on_terminate_world(self, event): launcher.terminate() self.robot_launchers = [] - def on_disconnect(self, event): + async def on_disconnect(self, event): """ Handle the 'disconnect' event. @@ -966,17 +967,17 @@ def on_disconnect(self, event): except Exception as e: LogManager.logger.exception("Exception terminating scene launcher") - def process_message(self, message): + async def process_message(self, message): if message.command == "gui": if self.tools_launcher is not None: - self.tools_launcher.pass_msg(message.data) + await self.tools_launcher.pass_msg(message.data) return - self.trigger(message.command, data=message.data or None) + await self.trigger(message.command, data=message.data or None) response = {"message": f"Exercise state changed to {self.state}"} - self.consumer.send_message(message.response(response)) + await self.consumer.send_message(message.response(response)) - def on_pause(self, msg): + async def on_pause(self, msg): if len(self.application_processes) > 0: for process in self.application_processes: proc = psutil.Process(process.pid) @@ -993,9 +994,9 @@ def on_pause(self, msg): "Application process was None during pause. Calling termination." ) self.pause_sim() - self.reset_sim() + await self.reset_sim() - def on_resume(self, msg): + async def on_resume(self, msg): """ Resume the application process if it exists, otherwise reset the simulation. @@ -1017,7 +1018,7 @@ def on_resume(self, msg): LogManager.logger.warning( "Application process was None during resume. Calling termination." ) - self.reset_sim() + await self.reset_sim() def pause_sim(self): try: @@ -1033,7 +1034,7 @@ def unpause_sim(self): self.write_to_tool_terminal(f"{e}\n\n") raise Exception("Failed to start simulator") - def reset_sim(self): + async def reset_sim(self): """ Reset the simulation environment and relaunch the robot if applicable. @@ -1056,27 +1057,28 @@ def reset_sim(self): robots_data = zip(self.robot_launchers, self.robot_configs) for launcher, cfg in robots_data: - launcher.run(cfg["entity"], cfg["start_pose"], cfg["extra_config"]) + await launcher.run(cfg["entity"], cfg["start_pose"], cfg["extra_config"]) - def start(self): + async def start(self): """ Start the RAM. RAM must be run in main thread to be able to handle signaling other processes, for instance ROS launcher. """ + self.consumer = await ManagerConsumer(self.host, self.port, self.process_message) LogManager.logger.info( - f"Starting RAM consumer in {self.consumer.server}:{self.consumer.port}" + f"Starting RAM consumer in {self.host}:{self.port}" ) self.consumer.start() - def signal_handler(sign, frame): + async def signal_handler(sign, frame): print("\nprogram exiting gracefully") self.running = False try: - self.consumer.stop() + await self.consumer.stop() except Exception as e: LogManager.logger.exception("Exception stopping consumer") @@ -1111,22 +1113,7 @@ def signal_handler(sign, frame): signal.signal(signal.SIGINT, signal_handler) while self.running: - message = None - try: - if self.queue.empty(): - time.sleep(0.1) - else: - message = self.queue.get() - self.process_message(message) - except Exception as e: - if message is not None: - ex = ManagerConsumerMessageException(id=message.id, message=str(e)) - else: - ex = ManagerConsumerMessageException( - id=str(uuid4()), message=str(e) - ) - self.consumer.send_message(ex) - LogManager.logger.error(e, exc_info=True) + await asyncio.sleep(1) if __name__ == "__main__": @@ -1140,4 +1127,4 @@ def signal_handler(sign, frame): args = parser.parse_args() RAM = Manager(args.host, args.port) - RAM.start() + asyncio.run(RAM.start()) From 77136f05255f0407cae8aa65ed25d1da3b69d44d Mon Sep 17 00:00:00 2001 From: Javier Izquierdo Hernandez Date: Tue, 29 Sep 2026 20:06:37 +0200 Subject: [PATCH 02/12] Working mostly --- .../comms/__init__.py | 3 +- .../comms/consumer.py | 89 ++- .../comms/new_consumer.py | 151 ----- robotics_application_manager/comms/thread.py | 5 - .../comms/websocket_server.py | 537 ------------------ robotics_application_manager/libs/server.py | 34 +- .../manager/launcher/launcher_console.py | 4 +- .../manager/launcher/launcher_gzsim.py | 4 +- .../manager/launcher/launcher_interface.py | 4 +- .../manager/launcher/launcher_robot.py | 6 +- .../launcher/launcher_robot_ros2_api.py | 4 +- .../manager/launcher/launcher_ros2_api.py | 4 +- .../manager/launcher/launcher_ros2_gz_api.py | 4 +- .../manager/launcher/launcher_rviz.py | 4 +- .../manager/launcher/launcher_scene.py | 6 +- .../manager/launcher/launcher_tools.py | 6 +- .../manager/launcher/launcher_web_gui.py | 8 +- .../manager/manager.py | 40 +- 18 files changed, 107 insertions(+), 806 deletions(-) delete mode 100644 robotics_application_manager/comms/new_consumer.py delete mode 100644 robotics_application_manager/comms/websocket_server.py diff --git a/robotics_application_manager/comms/__init__.py b/robotics_application_manager/comms/__init__.py index 808cda8..efa404f 100644 --- a/robotics_application_manager/comms/__init__.py +++ b/robotics_application_manager/comms/__init__.py @@ -7,5 +7,4 @@ from .consumer import ManagerConsumer from .consumer_message import ManagerConsumerMessageException, ManagerConsumerMessage -from .thread import ThreadWithLoggedException, WebsocketServerThread -from .websocket_server import WebsocketServer +from .thread import ThreadWithLoggedException diff --git a/robotics_application_manager/comms/consumer.py b/robotics_application_manager/comms/consumer.py index 4a20c20..0e150f0 100644 --- a/robotics_application_manager/comms/consumer.py +++ b/robotics_application_manager/comms/consumer.py @@ -14,9 +14,9 @@ ManagerConsumerMessageException, ManagerConsumerMessage, ) -from .websocket_server import WebsocketServer from robotics_application_manager import LogManager from websockets.asyncio.server import serve +from websockets.exceptions import ConnectionClosedOK import asyncio class ManagerConsumer: @@ -26,8 +26,8 @@ class ManagerConsumer: Supports single client connection to RAM TODO: Better handling of single client connections, closing and redirecting """ - def __init__(self, host, port, process_callback): + """ Initialize the ManagerConsumer with host, port, and manager_queue. @@ -43,10 +43,10 @@ def __init__(self, host, port, process_callback): self.server_task = None # Configurar el logger de websocket_server para salida a consola - ws_logger = logging.getLogger("websocket_server.websocket_server") - ws_logger.propagate = False - ws_logger.setLevel(logging.INFO) - ws_logger.handlers.clear() + self.ws_logger = logging.getLogger("websocket_server.websocket_server") + self.ws_logger.propagate = False + self.ws_logger.setLevel(logging.INFO) + self.ws_logger.handlers.clear() ws_formatter = logging.Formatter( "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] " "(%(name)s) %(message)s", @@ -54,7 +54,7 @@ def __init__(self, host, port, process_callback): ) ws_console_handler = logging.StreamHandler() ws_console_handler.setFormatter(ws_formatter) - ws_logger.addHandler(ws_console_handler) + self.ws_logger.addHandler(ws_console_handler) # Use the __await__ method to make the class awaitable def __await__(self): @@ -63,7 +63,7 @@ def __await__(self): # A method that creates an instance of the class asynchronously async def create(self): - self.server = await serve(self.manage_conection, self.host, self.port) + self.server = await serve(self.manage_conection, self.host, self.port, start_serving=False, max_size=None, logger=self.ws_logger) return self async def manage_conection(self, websocket): @@ -76,54 +76,51 @@ async def manage_conection(self, websocket): LogManager.logger.info(f"client connected: {self.client}") await self.process_msg(websocket) + except ConnectionClosedOK as e: + pass finally: now = datetime.now() time_str = now.strftime("%H:%M:%S") LogManager.logger.info(f"Client disconnected {time_str}: {self.client}") - message = ManagerConsumerMessage(id=str(uuid4()), command="disconnect") - await self.send_message(message) self.client = None async def process_msg(self, websocket): - while True: - async for raw_msg in websocket: - try: - json_msg = json.loads(raw_msg) - await self.process_callback(ManagerConsumerMessage(**json_msg)) - except Exception as e: - ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) - await self.send_message(ex) - LogManager.logger.error(e, exc_info=True) + async for raw_msg in websocket: + try: + json_msg = json.loads(raw_msg) + await self.process_callback(ManagerConsumerMessage(**json_msg)) + except Exception as e: + ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) + await self.send_message(ex) + LogManager.logger.error(e, exc_info=True) async def send_message(self, message_data, command=None): - """ - Send a message to the connected client. - - Args: - message_data: The message data to send, can be a ManagerConsumerMessage, - ManagerConsumerMessageException, or other data. - command (str, optional): The command associated with the message, - used if message_data is not a ManagerConsumerMessage. - """ - if self.client is not None and self.server is not None: - if isinstance(message_data, ManagerConsumerMessage): - message = message_data - elif isinstance(message_data, ManagerConsumerMessageException): - message = message_data.consumer_message() - else: - message = ManagerConsumerMessage( - id=str(uuid4()), command=command, data=message_data - ) - - await self.client.send(str(message)) - - def start(self): + """ + Send a message to the connected client. + + Args: + message_data: The message data to send, can be a ManagerConsumerMessage, + ManagerConsumerMessageException, or other data. + command (str, optional): The command associated with the message, + used if message_data is not a ManagerConsumerMessage. + """ + if self.client is not None and self.server is not None: + if isinstance(message_data, ManagerConsumerMessage): + message = message_data + elif isinstance(message_data, ManagerConsumerMessageException): + message = message_data.consumer_message() + else: + message = ManagerConsumerMessage( + id=str(uuid4()), command=command, data=message_data + ) + + await self.client.send(str(message)) + + async def start(self): """Start the WebSocket server in a separate thread.""" - self.server_task = asyncio.create_task(self.server.serve_forever()) + await self.server.start_serving() async def stop(self): """Stop the WebSocket server gracefully.""" - await self.server.close() - if self.server_task is not None: - self.server_task.cancel() - await self.server_task + self.server.close() + await self.server.wait_closed() diff --git a/robotics_application_manager/comms/new_consumer.py b/robotics_application_manager/comms/new_consumer.py deleted file mode 100644 index 0f2568c..0000000 --- a/robotics_application_manager/comms/new_consumer.py +++ /dev/null @@ -1,151 +0,0 @@ -""" -WebSocket consumer module for the Robotics Application Manager (RAM). - -Handles client connections, message processing, and communication with manager queue. -""" - -import json -import logging -from queue import Queue -from uuid import uuid4 -from datetime import datetime - -from .consumer_message import ( - ManagerConsumerMessageException, - ManagerConsumerMessage, -) -from .websocket_server import WebsocketServer -from robotics_application_manager import LogManager - - -class ManagerConsumer: - """ - Websocket server consumer for new Robotics Application Manager aka: RAM. - - Supports single client connection to RAM - TODO: Better handling of single client connections, closing and redirecting - """ - - def __init__(self, host, port, manager_queue: Queue): - """ - Initialize the ManagerConsumer with host, port, and manager_queue. - - Args: - host (str): The host address for the WebSocket server. - port (int): The port number for the WebSocket server. - manager_queue (Queue): The queue for communication with the manager. - """ - self.host = host - self.port = port - self.server = WebsocketServer(host=host, port=port, loglevel=logging.INFO) - - # Configurar el logger de websocket_server para salida a consola - ws_logger = logging.getLogger("websocket_server.websocket_server") - ws_logger.propagate = False - ws_logger.setLevel(logging.INFO) - ws_logger.handlers.clear() - ws_formatter = logging.Formatter( - "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] " - "(%(name)s) %(message)s", - "%H:%M:%S", - ) - ws_console_handler = logging.StreamHandler() - ws_console_handler.setFormatter(ws_formatter) - ws_logger.addHandler(ws_console_handler) - - self.server.set_fn_new_client(self.handle_client_new) - self.server.set_fn_client_left(self.handle_client_disconnect) - self.server.set_fn_message_received(self.handle_message_received) - self.client = None - self.manager_queue = manager_queue - - def handle_client_new(self, client, server): - """ - Handle a new client connection event. - - Args: - client: The client object representing the connected client. - server: The WebSocket server instance. - """ - LogManager.logger.info(f"client connected: {client}") - self.client = client - self.server.deny_new_connections() - - def handle_client_disconnect(self, client, server): - """ - Handle a client disconnection event. - - Args: - client: The client object representing the disconnected client. - server: The WebSocket server instance. - """ - if client is None: - return - LogManager.logger.info(f"client disconnected: {client}") - now = datetime.now() - time_string = now.strftime("%H:%M:%S") - print(time_string) - message = ManagerConsumerMessage( - **{"id": str(uuid4()), "command": "disconnect"} - ) - self.manager_queue.put(message) - self.client = None - self.server.allow_new_connections() - - def handle_message_received(self, client, server, websocket_message): - """ - Handle a message received from a client. - - Args: - client: The client object that sent the message. - server: The WebSocket server instance. - websocket_message (str): The message received from the client. - """ - LogManager.logger.info( - f"message received length: {len(websocket_message)} from client {client}" - ) - LogManager.logger.info( - f"message received: {websocket_message} from client {client}" - ) - message = None - try: - s = json.loads(websocket_message) - message = ManagerConsumerMessage(**s) - self.manager_queue.put(message) - except Exception as e: - if message is not None: - ex = ManagerConsumerMessageException(id=message.id, message=str(e)) - else: - ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) - self.server.send_message(client, str(ex)) - raise e - - def send_message(self, message_data, command=None): - """ - Send a message to the connected client. - - Args: - message_data: The message data to send, can be a ManagerConsumerMessage, - ManagerConsumerMessageException, or other data. - command (str, optional): The command associated with the message, - used if message_data is not a ManagerConsumerMessage. - """ - if self.client is not None and self.server is not None: - if isinstance(message_data, ManagerConsumerMessage): - message = message_data - elif isinstance(message_data, ManagerConsumerMessageException): - message = message_data.consumer_message() - else: - message = ManagerConsumerMessage( - id=str(uuid4()), command=command, data=message_data - ) - - self.server.send_message(self.client, str(message)) - - def start(self): - """Start the WebSocket server in a separate thread.""" - self.server.run_forever(threaded=True) - - def stop(self): - """Stop the WebSocket server gracefully.""" - self.server.shutdown_gracefully() diff --git a/robotics_application_manager/comms/thread.py b/robotics_application_manager/comms/thread.py index 4477895..33a2d54 100644 --- a/robotics_application_manager/comms/thread.py +++ b/robotics_application_manager/comms/thread.py @@ -37,8 +37,3 @@ def run(self): finally: del self._target, self._args, self._kwargs - -class WebsocketServerThread(ThreadWithLoggedException): - """Dummy wrapper to make debug messages a bit more readable""" - - pass diff --git a/robotics_application_manager/comms/websocket_server.py b/robotics_application_manager/comms/websocket_server.py deleted file mode 100644 index 0a67118..0000000 --- a/robotics_application_manager/comms/websocket_server.py +++ /dev/null @@ -1,537 +0,0 @@ -# Author: Johan Hanssen Seferidis -# License: MIT -# From https://github.com/Pithikos/python-websocket-server -# To fix OPCODE_CONTINUATION we have to apply this pacth https://github.com/Pithikos/python-websocket-server/pull/70/files. That is why we use this instead of the package - -import sys -import struct -import ssl -from base64 import b64encode -from hashlib import sha1 -import logging -from socket import error as SocketError -import errno -import threading -from socketserver import ThreadingMixIn, TCPServer, StreamRequestHandler - -from .thread import WebsocketServerThread - -logger = logging.getLogger(__name__) -logging.basicConfig() - -""" -+-+-+-+-+-------+-+-------------+-------------------------------+ - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -+-+-+-+-+-------+-+-------------+-------------------------------+ -|F|R|R|R| opcode|M| Payload len | Extended payload length | -|I|S|S|S| (4) |A| (7) | (16/64) | -|N|V|V|V| |S| | (if payload len==126/127) | -| |1|2|3| |K| | | -+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + -| Extended payload length continued, if payload len == 127 | -+ - - - - - - - - - - - - - - - +-------------------------------+ -| Payload Data continued ... | -+---------------------------------------------------------------+ -""" - -FIN = 0x80 -OPCODE = 0x0F -MASKED = 0x80 -PAYLOAD_LEN = 0x7F -PAYLOAD_LEN_EXT16 = 0x7E -PAYLOAD_LEN_EXT64 = 0x7F - -OPCODE_CONTINUATION = 0x0 -OPCODE_TEXT = 0x1 -OPCODE_BINARY = 0x2 -OPCODE_CLOSE_CONN = 0x8 -OPCODE_PING = 0x9 -OPCODE_PONG = 0xA - -CLOSE_STATUS_NORMAL = 1000 -DEFAULT_CLOSE_REASON = bytes("", encoding="utf-8") - - -class API: - def run_forever(self, threaded=False): - return self._run_forever(threaded) - - def new_client(self, client, server): - pass - - def client_left(self, client, server): - pass - - def message_received(self, client, server, message): - pass - - def set_fn_new_client(self, fn): - self.new_client = fn - - def set_fn_client_left(self, fn): - self.client_left = fn - - def set_fn_message_received(self, fn): - self.message_received = fn - - def send_message(self, client, msg): - self._unicast(client, msg) - - def send_message_to_all(self, msg): - self._multicast(msg) - - def deny_new_connections( - self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON - ): - self._deny_new_connections(status, reason) - - def allow_new_connections(self): - self._allow_new_connections() - - def shutdown_gracefully( - self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON - ): - self._shutdown_gracefully(status, reason) - - def shutdown_abruptly(self): - self._shutdown_abruptly() - - def disconnect_clients_gracefully( - self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON - ): - self._disconnect_clients_gracefully(status, reason) - - def disconnect_clients_abruptly(self): - self._disconnect_clients_abruptly() - - -class WebsocketServer(ThreadingMixIn, TCPServer, API): - """ - A websocket server waiting for clients to connect. - - Args: - port(int): Port to bind to - host(str): Hostname or IP to listen for connections. By default 127.0.0.1 - is being used. To accept connections from any client, you should use - 0.0.0.0. - loglevel: Logging level from logging module to use for logging. By default - warnings and errors are being logged. - - Properties: - clients(list): A list of connected clients. A client is a dictionary - like below. - { - 'id' : id, - 'handler' : handler, - 'address' : (addr, port) - } - """ - - allow_reuse_address = True - daemon_threads = True # comment to keep threads alive until finished - - def __init__( - self, host="127.0.0.1", port=0, loglevel=logging.WARNING, key=None, cert=None - ): - logger.setLevel(loglevel) - TCPServer.__init__(self, (host, port), WebSocketHandler) - self.host = host - self.port = self.socket.getsockname()[1] - - self.key = key - self.cert = cert - - self.clients = [] - self.id_counter = 0 - self.thread = None - - self._deny_clients = False - - def _run_forever(self, threaded): - cls_name = self.__class__.__name__ - try: - logger.info("Listening on port %d for clients.." % self.port) - if threaded: - self.daemon = True - self.thread = WebsocketServerThread( - target=super().serve_forever, daemon=True, logger=logger - ) - logger.info(f"Starting {cls_name} on thread {self.thread.getName()}.") - self.thread.start() - else: - self.thread = threading.current_thread() - logger.info(f"Starting {cls_name} on main thread.") - super().serve_forever() - except KeyboardInterrupt: - self.server_close() - logger.info("Server terminated.") - except Exception as e: - logger.error(str(e), exc_info=True) - sys.exit(1) - - def _message_received_(self, handler, msg): - self.message_received(self.handler_to_client(handler), self, msg) - - def _ping_received_(self, handler, msg): - handler.send_pong(msg) - - def _pong_received_(self, handler, msg): - pass - - def _new_client_(self, handler): - if self._deny_clients: - status = self._deny_clients["status"] - reason = self._deny_clients["reason"] - handler.send_close(status, reason) - self._terminate_client_handler(handler) - return - - self.id_counter += 1 - client = { - "id": self.id_counter, - "handler": handler, - "address": handler.client_address, - } - self.clients.append(client) - self.new_client(client, self) - - def _client_left_(self, handler): - client = self.handler_to_client(handler) - self.client_left(client, self) - if client in self.clients: - self.clients.remove(client) - - def _unicast(self, receiver_client, msg): - receiver_client["handler"].send_message(msg) - - def _multicast(self, msg): - for client in self.clients: - self._unicast(client, msg) - - def handler_to_client(self, handler): - for client in self.clients: - if client["handler"] == handler: - return client - - def _terminate_client_handler(self, handler): - handler.keep_alive = False - handler.finish() - handler.connection.close() - - def _terminate_client_handlers(self): - """ - Ensures request handler for each client is terminated correctly - """ - for client in self.clients: - self._terminate_client_handler(client["handler"]) - - def _shutdown_gracefully( - self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON - ): - """ - Send a CLOSE handshake to all connected clients before terminating server - """ - self.keep_alive = False - self._disconnect_clients_gracefully(status, reason) - self.server_close() - self.shutdown() - - def _shutdown_abruptly(self): - """ - Terminate server without sending a CLOSE handshake - """ - self.keep_alive = False - self._disconnect_clients_abruptly() - self.server_close() - self.shutdown() - - def _disconnect_clients_gracefully( - self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON - ): - """ - Terminate clients gracefully without shutting down the server - """ - for client in self.clients: - client["handler"].send_close(status, reason) - self._terminate_client_handlers() - - def _disconnect_clients_abruptly(self): - """ - Terminate clients abruptly (no CLOSE handshake) without shutting down the server - """ - self._terminate_client_handlers() - - def _deny_new_connections(self, status, reason): - self._deny_clients = { - "status": status, - "reason": reason, - } - - def _allow_new_connections(self): - self._deny_clients = False - - -class WebSocketHandler(StreamRequestHandler): - def __init__(self, socket, addr, server): - self.server = server - assert not hasattr(self, "_send_lock"), "_send_lock already exists" - self._send_lock = threading.Lock() - if server.key and server.cert: - try: - socket = ssl.wrap_socket( - socket, server_side=True, certfile=server.cert, keyfile=server.key - ) - except: # Not sure which exception it throws if the key/cert isn't found - logger.warning( - "SSL not available (are the paths {} and {} correct for the key and cert?)".format( - server.key, server.cert - ) - ) - StreamRequestHandler.__init__(self, socket, addr, server) - - def setup(self): - StreamRequestHandler.setup(self) - self.keep_alive = True - self.handshake_done = False - self.valid_client = False - self.fragment_opcode = 0 - self.fragment_payload_buf = bytearray() - - def handle(self): - while self.keep_alive: - if not self.handshake_done: - self.handshake() - elif self.valid_client: - self.read_next_message() - - def read_bytes(self, num): - return self.rfile.read(num) - - def read_next_message(self): - try: - b1, b2 = self.read_bytes(2) - except SocketError as e: # to be replaced with ConnectionResetError for py3 - if e.errno == errno.ECONNRESET: - logger.info("Client closed connection.") - self.keep_alive = 0 - return - b1, b2 = 0, 0 - except ValueError as e: - b1, b2 = 0, 0 - - fin = b1 & FIN - opcode = b1 & OPCODE - masked = b2 & MASKED - payload_length = b2 & PAYLOAD_LEN - - if opcode == OPCODE_CLOSE_CONN: - logger.info("Client asked to close connection.") - self.keep_alive = 0 - return - if not masked: - logger.warning("Client must always be masked.") - self.keep_alive = 0 - return - if opcode == OPCODE_BINARY: - logger.warning("Binary frames are not supported.") - return - # else: - # logger.warning("Unknown opcode %#x." % opcode) - # self.keep_alive = 0 - # return - - if payload_length == 126: - payload_length = struct.unpack(">H", self.rfile.read(2))[0] - elif payload_length == 127: - payload_length = struct.unpack(">Q", self.rfile.read(8))[0] - - masks = self.read_bytes(4) - payload = bytearray() - - for message_byte in self.read_bytes(payload_length): - message_byte ^= masks[len(payload) % 4] - payload.append(message_byte) - - if fin and opcode != OPCODE_CONTINUATION: # simple msg - if opcode == OPCODE_PING: - self.server._ping_received_(self, payload.decode("utf8")) - elif opcode == OPCODE_PONG: - self.server._pong_received_(self, payload.decode("utf8")) - elif opcode == OPCODE_TEXT: - self.server._message_received_(self, payload.decode("utf8")) - return - - if not fin and opcode: # fragment msg start - self.fragment_opcode = opcode - self.fragment_payload_buf = payload - return - - # "not opcode" is the same as "opcode == OPCODE_CONTINUATION" - if not fin and not opcode: # fragment msg ing - self.fragment_payload_buf.extend(payload) - return - - if fin and opcode == OPCODE_CONTINUATION: # fragment msg end - if self.fragment_opcode == OPCODE_TEXT: - self.server._message_received_( - self, (self.fragment_payload_buf + payload).decode("utf8") - ) - elif self.fragment_opcode == OPCODE_BINARY: - pass - return - - def send_message(self, message): - self.send_text(message) - - def send_pong(self, message): - self.send_text(message, OPCODE_PONG) - - def send_close(self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON): - """ - Send CLOSE to client - - Args: - status: Status as defined in https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1 - reason: Text with reason of closing the connection - """ - if status < CLOSE_STATUS_NORMAL or status > 1015: - raise Exception(f"CLOSE status must be between 1000 and 1015, got {status}") - - header = bytearray() - payload = struct.pack("!H", status) + reason - payload_length = len(payload) - assert ( - payload_length <= 125 - ), "We only support short closing reasons at the moment" - - # Send CLOSE with status & reason - header.append(FIN | OPCODE_CLOSE_CONN) - header.append(payload_length) - with self._send_lock: - self.request.send(header + payload) - - def send_text(self, message, opcode=OPCODE_TEXT): - """ - Important: Fragmented(=continuation) messages are not supported since - their usage cases are limited - when we don't know the payload length. - """ - - # Validate message - if isinstance(message, bytes): - message = try_decode_UTF8( - message - ) # this is slower but ensures we have UTF-8 - if not message: - logger.warning("Can't send message, message is not valid UTF-8") - return False - elif not isinstance(message, str): - logger.warning( - "Can't send message, message has to be a string or bytes. Got %s" - % type(message) - ) - return False - - header = bytearray() - payload = encode_to_UTF8(message) - payload_length = len(payload) - - # Normal payload - if payload_length <= 125: - header.append(FIN | opcode) - header.append(payload_length) - - # Extended payload - elif payload_length >= 126 and payload_length <= 65535: - header.append(FIN | opcode) - header.append(PAYLOAD_LEN_EXT16) - header.extend(struct.pack(">H", payload_length)) - - # Huge extended payload - elif payload_length < 18446744073709551616: - header.append(FIN | opcode) - header.append(PAYLOAD_LEN_EXT64) - header.extend(struct.pack(">Q", payload_length)) - - else: - raise Exception("Message is too big. Consider breaking it into chunks.") - return - - with self._send_lock: - self.request.send(header + payload) - - def read_http_headers(self): - headers = {} - # first line should be HTTP GET - http_get = self.rfile.readline().decode().strip() - assert http_get.upper().startswith("GET") - # remaining should be headers - while True: - header = self.rfile.readline().decode().strip() - if not header: - break - head, value = header.split(":", 1) - headers[head.lower().strip()] = value.strip() - return headers - - def handshake(self): - headers = self.read_http_headers() - - try: - assert headers["upgrade"].lower() == "websocket" - except AssertionError: - self.keep_alive = False - return - - try: - key = headers["sec-websocket-key"] - except KeyError: - logger.warning("Client tried to connect but was missing a key") - self.keep_alive = False - return - - response = self.make_handshake_response(key) - with self._send_lock: - self.handshake_done = self.request.send(response.encode()) - self.valid_client = True - self.server._new_client_(self) - - @classmethod - def make_handshake_response(cls, key): - return ( - "HTTP/1.1 101 Switching Protocols\r\n" - "Upgrade: websocket\r\n" - "Connection: Upgrade\r\n" - "Sec-WebSocket-Accept: %s\r\n" - "\r\n" % cls.calculate_response_key(key) - ) - - @classmethod - def calculate_response_key(cls, key): - GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" - hash = sha1(key.encode() + GUID.encode()) - response_key = b64encode(hash.digest()).strip() - return response_key.decode("ASCII") - - def finish(self): - self.server._client_left_(self) - - -def encode_to_UTF8(data): - try: - return data.encode("UTF-8") - except UnicodeEncodeError as e: - logger.error("Could not encode data to UTF-8 -- %s" % e) - return False - except Exception as e: - raise (e) - return False - - -def try_decode_UTF8(data): - try: - return data.decode("utf-8") - except UnicodeDecodeError: - return False - except Exception as e: - raise (e) diff --git a/robotics_application_manager/libs/server.py b/robotics_application_manager/libs/server.py index a836397..eb9c1c7 100644 --- a/robotics_application_manager/libs/server.py +++ b/robotics_application_manager/libs/server.py @@ -13,6 +13,7 @@ def __init__( port, callback, ): + self.host = "127.0.0.1" self.port = port self.update_callback = callback self.client = None @@ -27,7 +28,7 @@ def __await__(self): # A method that creates an instance of the class asynchronously async def create(self): - self.server = await serve(self.manage_conection, "127.0.0.1", self.port) + self.server = await serve(self.manage_conection, self.host, self.port, start_serving=False) return self async def manage_conection(self, websocket): @@ -42,36 +43,33 @@ async def manage_conection(self, websocket): LogManager.logger.info(f"Client connected: {self.client}") await self.process_msg(websocket) + except: + pass finally: LogManager.logger.info("Connection with client closed") - await self.send_message(message) with self.client_lock: self.client = None async def process_msg(self, websocket): - while True: - async for raw_msg in websocket: - try: - json_msg = json.loads(raw_msg) - LogManager.logger.debug(f"Message received from template: {raw_msg[:30]}") - await self.update_callback(json_msg) - except Exception as e: - ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) - await self.send_message(ex) - LogManager.logger.error(e, exc_info=True) + async for raw_msg in websocket: + try: + json_msg = json.loads(raw_msg) + await self.update_callback(json_msg) + except Exception as e: + ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) + await self.send_message(ex) + LogManager.logger.error(e, exc_info=True) async def send(self, data): with self.client_lock: if self.client is not None: await self.client.send(data) - def start(self): + async def start(self): """Start the WebSocket server in a separate thread.""" - self.server_task = asyncio.create_task(self.server.serve_forever()) + await self.server.start_serving() async def stop(self): """Stop the WebSocket server gracefully.""" - await self.server.close() - if self.server_task is not None: - self.server_task.cancel() - await self.server_task + self.server.close() + await self.server.wait_closed() diff --git a/robotics_application_manager/manager/launcher/launcher_console.py b/robotics_application_manager/manager/launcher/launcher_console.py index 6848118..f72823c 100644 --- a/robotics_application_manager/manager/launcher/launcher_console.py +++ b/robotics_application_manager/manager/launcher/launcher_console.py @@ -17,7 +17,7 @@ class LauncherConsole(ILauncher): threads: List[Any] = [] console_vnc: Any = Vnc_server() - def run(self, config_file, callback): + async def run(self, config_file, callback): DRI_PATH = self.get_dri_path() ACCELERATION_ENABLED = False @@ -52,7 +52,7 @@ def reset(self, robot_entities=[]): def is_running(self): return self.running - def terminate(self): + async def terminate(self): LogManager.logger.info(f"Terminating console tool") self.console_vnc.terminate() for thread in self.threads[:]: diff --git a/robotics_application_manager/manager/launcher/launcher_gzsim.py b/robotics_application_manager/manager/launcher/launcher_gzsim.py index f0e7207..67029c1 100644 --- a/robotics_application_manager/manager/launcher/launcher_gzsim.py +++ b/robotics_application_manager/manager/launcher/launcher_gzsim.py @@ -31,7 +31,7 @@ class LauncherGzsim(ILauncher): acceptsMsgs: bool = False gz_vnc: Any = Vnc_server() - def run(self, config_file, callback): + async def run(self, config_file, callback): DRI_PATH = self.get_dri_path() ACCELERATION_ENABLED = self.check_device(DRI_PATH) @@ -72,7 +72,7 @@ def check_device(self, device_path): def is_running(self): return self.running - def terminate(self): + async def terminate(self): LogManager.logger.info(f"Terminating gz tool") self.gz_vnc.terminate() for thread in self.threads[:]: diff --git a/robotics_application_manager/manager/launcher/launcher_interface.py b/robotics_application_manager/manager/launcher/launcher_interface.py index 01a9a82..cf284e4 100644 --- a/robotics_application_manager/manager/launcher/launcher_interface.py +++ b/robotics_application_manager/manager/launcher/launcher_interface.py @@ -11,13 +11,13 @@ def __await__(self): async def create(self): return self - def run(self, callback: callable): + async def run(self, callback: callable): raise NotImplemented("Launcher must implement run method") def is_running(self): raise NotImplemented("Launcher must implement run method") - def terminate(self): + async def terminate(self): raise NotImplemented("Launcher must implement run method") def died(self, callback): diff --git a/robotics_application_manager/manager/launcher/launcher_robot.py b/robotics_application_manager/manager/launcher/launcher_robot.py index a53374d..cd0b93d 100644 --- a/robotics_application_manager/manager/launcher/launcher_robot.py +++ b/robotics_application_manager/manager/launcher/launcher_robot.py @@ -62,12 +62,12 @@ async def run(self, entity="", start_pose=None, extra_config=None): self.launchers.append(launcher) LogManager.logger.info(self.launchers) - def terminate(self): + async def terminate(self): """Terminate all robot launchers and clear the launchers list.""" LogManager.logger.info("Terminating robots launchers") if self.launchers: for launcher in self.launchers: - launcher.terminate() + await launcher.terminate() self.launchers = [] async def launch_module(self, configuration, extra_config=None): @@ -88,7 +88,7 @@ def process_terminated(name, exit_code): launcher_class = get_class(launcher_module) launcher = await launcher_class.from_config(launcher_class, configuration) - launcher.run(self.entity, self.start_pose, extra_config, process_terminated) + await launcher.run(self.entity, self.start_pose, extra_config, process_terminated) return launcher def launch_command(self, configuration): diff --git a/robotics_application_manager/manager/launcher/launcher_robot_ros2_api.py b/robotics_application_manager/manager/launcher/launcher_robot_ros2_api.py index ed642b9..81787f6 100644 --- a/robotics_application_manager/manager/launcher/launcher_robot_ros2_api.py +++ b/robotics_application_manager/manager/launcher/launcher_robot_ros2_api.py @@ -21,7 +21,7 @@ class LauncherRobotRos2Api(ILauncher): launch_file: str threads: List[Any] = [] - def run(self, entity, robot_pose, extra_config, callback): + async def run(self, entity, robot_pose, extra_config, callback): DRI_PATH = self.get_dri_path() ACCELERATION_ENABLED = self.check_device(DRI_PATH) @@ -41,7 +41,7 @@ def run(self, entity, robot_pose, extra_config, callback): exercise_launch_thread.start() self.threads.append(exercise_launch_thread) - def terminate(self): + async def terminate(self): LogManager.logger.info(f"Terminating robot launcher") for thread in self.threads[:]: if thread.is_alive(): diff --git a/robotics_application_manager/manager/launcher/launcher_ros2_api.py b/robotics_application_manager/manager/launcher/launcher_ros2_api.py index 1688604..5ca5516 100644 --- a/robotics_application_manager/manager/launcher/launcher_ros2_api.py +++ b/robotics_application_manager/manager/launcher/launcher_ros2_api.py @@ -21,7 +21,7 @@ class LauncherRos2Api(ILauncher): launch_file: str threads: List[Any] = [] - def run(self, callback): + async def run(self, callback): DRI_PATH = self.get_dri_path() ACCELERATION_ENABLED = self.check_device(DRI_PATH) @@ -41,7 +41,7 @@ def run(self, callback): exercise_launch_thread.start() self.threads.append(exercise_launch_thread) - def terminate(self): + async def terminate(self): LogManager.logger.info(f"Terminating world launcher") for thread in self.threads[:]: if thread.is_alive(): diff --git a/robotics_application_manager/manager/launcher/launcher_ros2_gz_api.py b/robotics_application_manager/manager/launcher/launcher_ros2_gz_api.py index 4ae071f..eeadadd 100644 --- a/robotics_application_manager/manager/launcher/launcher_ros2_gz_api.py +++ b/robotics_application_manager/manager/launcher/launcher_ros2_gz_api.py @@ -23,7 +23,7 @@ class LauncherRos2GzApi(ILauncher): launch_file: str threads: List[Any] = [] - def run(self, callback): + async def run(self, callback): DRI_PATH = self.get_dri_path() ACCELERATION_ENABLED = self.check_device(DRI_PATH) @@ -43,7 +43,7 @@ def run(self, callback): exercise_launch_thread.start() self.threads.append(exercise_launch_thread) - def terminate(self): + async def terminate(self): LogManager.logger.info(f"Terminating world launcher") for thread in self.threads[:]: if thread.is_alive(): diff --git a/robotics_application_manager/manager/launcher/launcher_rviz.py b/robotics_application_manager/manager/launcher/launcher_rviz.py index d08c05e..36fdd33 100644 --- a/robotics_application_manager/manager/launcher/launcher_rviz.py +++ b/robotics_application_manager/manager/launcher/launcher_rviz.py @@ -26,7 +26,7 @@ class LauncherRviz(ILauncher): threads: List[Any] = [] vnc: Any = Vnc_server() - def run(self, config_file, callback): + async def run(self, config_file, callback): """ Launches an RViz instance with a specific display configuration. @@ -72,7 +72,7 @@ def reset(self, robot_entities=[]): def is_running(self): return self.running - def terminate(self): + async def terminate(self): LogManager.logger.info(f"Terminating rviz tool") self.vnc.terminate() for thread in self.threads[:]: diff --git a/robotics_application_manager/manager/launcher/launcher_scene.py b/robotics_application_manager/manager/launcher/launcher_scene.py index 9b4565e..00daefb 100644 --- a/robotics_application_manager/manager/launcher/launcher_scene.py +++ b/robotics_application_manager/manager/launcher/launcher_scene.py @@ -61,11 +61,11 @@ async def run(self): launcher = await self.launch_module(module) self.launchers.append(launcher) - def terminate(self): + async def terminate(self): LogManager.logger.info("Terminating scenes launchers") if self.launchers: for launcher in self.launchers: - launcher.terminate() + await launcher.terminate() self.launchers = [] async def launch_module(self, configuration): @@ -80,7 +80,7 @@ def process_terminated(name, exit_code): launcher_module = f"{self.module}.launcher_{launcher_module_name}.Launcher{class_from_module(launcher_module_name)}" launcher_class = get_class(launcher_module) launcher = await launcher_class.from_config(launcher_class, configuration) - launcher.run(process_terminated) + await launcher.run(process_terminated) return launcher def launch_command(self, configuration): diff --git a/robotics_application_manager/manager/launcher/launcher_tools.py b/robotics_application_manager/manager/launcher/launcher_tools.py index 3f190d2..bede222 100644 --- a/robotics_application_manager/manager/launcher/launcher_tools.py +++ b/robotics_application_manager/manager/launcher/launcher_tools.py @@ -83,11 +83,11 @@ async def run(self, consumer): launcher = await self.launch_module(tool, module, consumer) self.launchers.append(launcher) - def terminate(self): + async def terminate(self): LogManager.logger.info("Terminating tools launchers") for launcher in self.launchers: if launcher.is_running(): - launcher.terminate() + await launcher.terminate() self.launchers = [] async def launch_module(self, name, configuration, consumer): @@ -110,7 +110,7 @@ def process_terminated(name, exit_code): config = self.tools_config[name] launcher = await launcher_class.from_config(launcher_class, configuration) - launcher.run(config, process_terminated) + await launcher.run(config, process_terminated) return launcher def pause(self): diff --git a/robotics_application_manager/manager/launcher/launcher_web_gui.py b/robotics_application_manager/manager/launcher/launcher_web_gui.py index 0fc0540..3a3719a 100644 --- a/robotics_application_manager/manager/launcher/launcher_web_gui.py +++ b/robotics_application_manager/manager/launcher/launcher_web_gui.py @@ -26,8 +26,8 @@ async def update(self, data): if self.consumer is not None: await self.consumer.send_message({"update": data}, command="update") - def run(self, config_file, callback): - self.server.start() + async def run(self, config_file, callback): + await self.server.start() self.running = True async def get_msg(self, data): @@ -36,8 +36,8 @@ async def get_msg(self, data): def is_running(self): return self.running - def terminate(self): - self.server.stop() + async def terminate(self): + await self.server.stop() self.running = False def pause(self): diff --git a/robotics_application_manager/manager/manager.py b/robotics_application_manager/manager/manager.py index 0dd5750..e6751f1 100644 --- a/robotics_application_manager/manager/manager.py +++ b/robotics_application_manager/manager/manager.py @@ -30,6 +30,7 @@ from transitions.extensions import AsyncMachine from robotics_application_manager.comms import ( ManagerConsumerMessageException, + ManagerConsumerMessage, ManagerConsumer, ) from robotics_application_manager.libs import ( @@ -448,9 +449,7 @@ async def prepare_custom_world(self, cfg_dict): ) async def on_prepare_tools(self, event): - LogManager.logger.info("Tools transition started") - cfg_dict = event.kwargs.get("data", {}) tools = cfg_dict["tools"] config = cfg_dict["config"] @@ -831,7 +830,7 @@ async def on_run_application(self, event): if needs_compile: compile_process = subprocess.Popen( [ - "cd /workspace/code && source /opt/ros/humble/setup.bash && colcon build && source install/setup.bash && cd ../.." + "cd /workspace/code && source /opt/ros/lyrical/setup.bash && colcon build && source install/setup.bash && cd ../.." ], stdin=open("/dev/pts/" + console_fd, "r"), stdout=open("/dev/pts/" + console_fd, "w"), @@ -843,7 +842,9 @@ async def on_run_application(self, event): ) returncode = compile_process.wait() if returncode != 0: - raise Exception("Failed to compile") + # raise Exception("Failed to compile") + LogManager.logger.info("Failed to compile") + return for entrypoint in entrypoints: if not os.path.isfile(entrypoint): @@ -911,7 +912,7 @@ async def on_terminate_application(self, event): async def on_terminate_tools(self, event): - self.tools_launcher.terminate() + await self.tools_launcher.terminate() self.tools_launcher = None async def on_terminate_world(self, event): @@ -925,12 +926,12 @@ async def on_terminate_world(self, event): event: The event object associated with the termination request. """ if self.scene_launcher is not None: - self.scene_launcher.terminate() + await self.scene_launcher.terminate() self.scene_launcher = None self.world_type = None for launcher in self.robot_launchers: - launcher.terminate() + await launcher.terminate() self.robot_launchers = [] async def on_disconnect(self, event): @@ -940,7 +941,7 @@ async def on_disconnect(self, event): This method stops all running processes, terminates launchers, and restarts the script. """ - + LogManager.logger.info("-------------------Disconnecting--------------------------") try: for process in self.application_processes: stop_process_and_children(process) @@ -950,20 +951,20 @@ async def on_disconnect(self, event): if self.tools_launcher: try: - self.tools_launcher.terminate() + await self.tools_launcher.terminate() except Exception as e: LogManager.logger.exception("Exception terminating tools launcher") try: for launcher in self.robot_launchers: - launcher.terminate() + await launcher.terminate() self.robot_launchers = [] except Exception as e: LogManager.logger.exception("Exception terminating robot launcher") if self.scene_launcher: try: - self.scene_launcher.terminate() + await self.scene_launcher.terminate() except Exception as e: LogManager.logger.exception("Exception terminating scene launcher") @@ -974,6 +975,7 @@ async def process_message(self, message): return await self.trigger(message.command, data=message.data or None) + response = {"message": f"Exercise state changed to {self.state}"} await self.consumer.send_message(message.response(response)) @@ -1044,7 +1046,7 @@ async def reset_sim(self): """ for robot_launcher in self.robot_launchers: - robot_launcher.terminate() + await robot_launcher.terminate() try: entities = [] @@ -1071,17 +1073,16 @@ async def start(self): f"Starting RAM consumer in {self.host}:{self.port}" ) - self.consumer.start() + await self.consumer.start() async def signal_handler(sign, frame): - print("\nprogram exiting gracefully") + LogManager.logger.info("Program exiting gracefully") self.running = False try: await self.consumer.stop() except Exception as e: LogManager.logger.exception("Exception stopping consumer") - try: for process in self.application_processes: stop_process_and_children(process) @@ -1091,23 +1092,22 @@ async def signal_handler(sign, frame): if self.tools_launcher: try: - self.tools_launcher.terminate() + await self.tools_launcher.terminate() except Exception as e: LogManager.logger.exception("Exception terminating tools launcher") try: for launcher in self.robot_launchers: - launcher.terminate() + await launcher.terminate() self.robot_launchers = [] except Exception as e: LogManager.logger.exception("Exception terminating robot launcher") if self.scene_launcher: try: - self.scene_launcher.terminate() + await self.scene_launcher.terminate() except Exception as e: LogManager.logger.exception("Exception terminating scene launcher") - exit() signal.signal(signal.SIGINT, signal_handler) @@ -1121,7 +1121,7 @@ async def signal_handler(sign, frame): parser = argparse.ArgumentParser() parser.add_argument( - "host", type=str, help="Host to listen to (0.0.0.0 or all hosts)" + "host", type=str, help="Host to listen to (0.0.0.0 or all hosts)" ) parser.add_argument("port", type=int, help="Port to listen to") args = parser.parse_args() From d54ed59195f7a174558168a4a87e58133d73fd78 Mon Sep 17 00:00:00 2001 From: Javier Izquierdo Hernandez Date: Wed, 7 Oct 2026 18:28:26 +0200 Subject: [PATCH 03/12] Add RAS base --- robotics_application_manager/libs/server.py | 12 ++- .../manager/manager.py | 2 +- robotics_application_services/main.py | 40 ++++++++++ .../routers/__init__.py | 0 robotics_application_services/routers/ssh.py | 78 +++++++++++++++++++ 5 files changed, 127 insertions(+), 5 deletions(-) create mode 100644 robotics_application_services/main.py create mode 100644 robotics_application_services/routers/__init__.py create mode 100644 robotics_application_services/routers/ssh.py diff --git a/robotics_application_manager/libs/server.py b/robotics_application_manager/libs/server.py index eb9c1c7..089430e 100644 --- a/robotics_application_manager/libs/server.py +++ b/robotics_application_manager/libs/server.py @@ -3,9 +3,12 @@ from websockets.asyncio.server import serve import asyncio +from uuid import uuid4 from robotics_application_manager import LogManager - +from robotics_application_manager.comms import ( + ManagerConsumerMessageException, +) class Server: def __init__( @@ -28,7 +31,7 @@ def __await__(self): # A method that creates an instance of the class asynchronously async def create(self): - self.server = await serve(self.manage_conection, self.host, self.port, start_serving=False) + self.server = await serve(self.manage_conection, self.host, self.port, start_serving=False,ping_interval=None, ping_timeout=None) return self async def manage_conection(self, websocket): @@ -43,7 +46,8 @@ async def manage_conection(self, websocket): LogManager.logger.info(f"Client connected: {self.client}") await self.process_msg(websocket) - except: + except Exception as e: + LogManager.logger.info(f"Client disconnected: {str(e)}") pass finally: LogManager.logger.info("Connection with client closed") @@ -57,7 +61,7 @@ async def process_msg(self, websocket): await self.update_callback(json_msg) except Exception as e: ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) - await self.send_message(ex) + await self.send(ex.consumer_message()) LogManager.logger.error(e, exc_info=True) async def send(self, data): diff --git a/robotics_application_manager/manager/manager.py b/robotics_application_manager/manager/manager.py index e6751f1..3222dcf 100644 --- a/robotics_application_manager/manager/manager.py +++ b/robotics_application_manager/manager/manager.py @@ -1126,5 +1126,5 @@ async def signal_handler(sign, frame): parser.add_argument("port", type=int, help="Port to listen to") args = parser.parse_args() - RAM = Manager(args.host, args.port) + RAM = Manager(args.host, 7165) asyncio.run(RAM.start()) diff --git a/robotics_application_services/main.py b/robotics_application_services/main.py new file mode 100644 index 0000000..97c2dd2 --- /dev/null +++ b/robotics_application_services/main.py @@ -0,0 +1,40 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from contextlib import asynccontextmanager +from uvicorn import run +import argparse + +from .routers import ssh + +@asynccontextmanager +async def lifespan(app: FastAPI): + # On launch + yield + # On end + + +app = FastAPI(lifespan=lifespan) + +app.include_router(ssh.router) + +origins = ["*"] + +app.add_middleware( + CORSMiddleware, + allow_origins=origins, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "host", type=str, help="Host to listen to (0.0.0.0 or all hosts)" + ) + parser.add_argument("port", type=int, help="Port to listen to") + args = parser.parse_args() + project = args.project + + run(app, host="0.0.0.0", port=8000) diff --git a/robotics_application_services/routers/__init__.py b/robotics_application_services/routers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/robotics_application_services/routers/ssh.py b/robotics_application_services/routers/ssh.py new file mode 100644 index 0000000..8db4d24 --- /dev/null +++ b/robotics_application_services/routers/ssh.py @@ -0,0 +1,78 @@ +from fastapi import APIRouter +from fastapi.websockets import WebSocket, WebSocketDisconnect, WebSocketState +import json +import os +import asyncio +import asyncssh +import subprocess + +router = APIRouter( + tags=["ssh"], + responses={404: {"description": "Not found"}}, +) + + +@router.websocket("/console") +async def terminal_endpoint(websocket: WebSocket): + await websocket.accept() + try: + init_cols = int(websocket.query_params.get("cols") or 80) + init_rows = int(websocket.query_params.get("rows") or 24) + user = "root" + await ssh_shell( + websocket, user, 8081, "jderobot", init_cols, init_rows, setting.val + ) + except Exception as e: + pass + + if websocket.client_state != WebSocketState.DISCONNECTED: + await websocket.close() + + +async def ssh_shell( + ws: WebSocket, + user: str, + port: int, + passwd: str, + init_cols: int = 80, + init_rows: int = 24, + workspace: str = "/", +): + subprocess.run(["/usr/sbin/sshd"]) + async with asyncssh.connect( + "localhost", port=port, username=user, password=passwd, known_hosts=None + ) as conn: + async with conn.create_process( + term_type="xterm-color", + term_size=(init_cols, init_rows), + stderr=asyncssh.STDOUT, + ) as process: + process.stdin.write(f"cd {workspace};clear;\n") + + async def ws_to_ssh(): + while True: + raw = await ws.receive() + if raw.get("text"): + data = raw["text"] + process.stdin.write(data) + await process.stdin.drain() + elif raw.get("bytes"): + data = raw["bytes"] + msg = json.loads(data.decode("utf-8")) + if "resize" in msg: + cols = int(msg["resize"].get("cols", init_cols)) + rows = int(msg["resize"].get("rows", init_rows)) + process.change_terminal_size(cols, rows) + elif raw["type"] == "websocket.disconnect": + raise UserWarning("ws-to-ssh ws disconnect") + + async def ssh_to_ws(): + while True: + data = await process.stdout.read(4096) + if not data: + raise UserWarning("ssh-to-ws process close") + await ws.send_text(data) + + async with asyncio.TaskGroup() as tg: + tg.create_task(ws_to_ssh()) + tg.create_task(ssh_to_ws()) From f239580dbbfb07ac372ba178c40b26bda096d5d2 Mon Sep 17 00:00:00 2001 From: Javier Izquierdo Hernandez Date: Tue, 3 Nov 2026 13:21:00 +0100 Subject: [PATCH 04/12] Remove guardrails --- .../manager/launcher/launcher_scene.py | 2 ++ .../manager/launcher/launcher_tools.py | 14 -------------- 2 files changed, 2 insertions(+), 14 deletions(-) diff --git a/robotics_application_manager/manager/launcher/launcher_scene.py b/robotics_application_manager/manager/launcher/launcher_scene.py index 00daefb..81bfe68 100644 --- a/robotics_application_manager/manager/launcher/launcher_scene.py +++ b/robotics_application_manager/manager/launcher/launcher_scene.py @@ -56,6 +56,8 @@ class LauncherScene(BaseModel): launchers: Optional[ILauncher] = [] async def run(self): + if self.type is None or self.type == str(None): + return for module in worlds[self.type][str(self.ros_version)]: module["launch_file"] = self.launch_file_path launcher = await self.launch_module(module) diff --git a/robotics_application_manager/manager/launcher/launcher_tools.py b/robotics_application_manager/manager/launcher/launcher_tools.py index bede222..6f85b4d 100644 --- a/robotics_application_manager/manager/launcher/launcher_tools.py +++ b/robotics_application_manager/manager/launcher/launcher_tools.py @@ -44,18 +44,6 @@ "file": "/tmp/tree_state", "consumer": None, }, - "webcam": { - "type": "module", - "module": None, - "internal_port": 2303, - "consumer": None, - }, - "video": { - "type": "module", - "module": None, - "internal_port": 2303, - "consumer": None, - }, } simulator = { @@ -74,8 +62,6 @@ class LauncherTools(BaseModel): async def run(self, consumer): for tool in self.tools: if tool == "simulator": - if self.world_type is None or self.world_type == "physical": - continue tool = simulator[self.world_type]["tool"] module = tools[tool] if module["module"] is None: From 4feb1944eb440c947d6cd932885df9912badb2e1 Mon Sep 17 00:00:00 2001 From: Javier Izquierdo Hernandez Date: Tue, 3 Nov 2026 20:51:55 +0100 Subject: [PATCH 05/12] Working ssh console --- .../manager/launcher/launcher_console.py | 132 +++++++++++++----- .../manager/launcher/launcher_tools.py | 2 +- 2 files changed, 97 insertions(+), 37 deletions(-) diff --git a/robotics_application_manager/manager/launcher/launcher_console.py b/robotics_application_manager/manager/launcher/launcher_console.py index f72823c..0437414 100644 --- a/robotics_application_manager/manager/launcher/launcher_console.py +++ b/robotics_application_manager/manager/launcher/launcher_console.py @@ -1,45 +1,106 @@ from .launcher_interface import ILauncher -from robotics_application_manager.manager.docker_thread import DockerThread -from robotics_application_manager.manager.vnc import Vnc_server -from robotics_application_manager.libs import check_gpu_acceleration from robotics_application_manager import LogManager -import os -import stat from typing import List, Any +from websockets.asyncio.server import serve +from websockets.exceptions import ConnectionClosedOK +from robotics_application_manager import LogManager +import json +import asyncio +import asyncssh +import subprocess + +async def ssh_shell( + ws, + user: str, + port: int, + passwd: str, + init_cols: int = 80, + init_rows: int = 24, + workspace: str = "/", +): + subprocess.run(["/usr/sbin/sshd"]) + async with asyncssh.connect( + "localhost", port=port, username=user, password=passwd, known_hosts=None + ) as conn: + async with conn.create_process( + term_type="xterm-color", + term_size=(init_cols, init_rows), + stderr=asyncssh.STDOUT, + ) as process: + process.stdin.write(f"cd {workspace};clear;\n") + + async def ws_to_ssh(): + try: + async for raw in ws: + if type(raw) == str: + process.stdin.write(raw) + await process.stdin.drain() + elif type(raw) == bytes: + data = raw + msg = json.loads(data.decode("utf-8")) + if "resize" in msg: + cols = int(msg["resize"].get("cols", init_cols)) + rows = int(msg["resize"].get("rows", init_rows)) + process.change_terminal_size(cols, rows) + # elif raw["type"] == "websocket.disconnect": + # raise UserWarning("ws-to-ssh ws disconnect") + except: + raise UserWarning("ws-to-ssh ws disconnect") + + async def ssh_to_ws(): + while True: + data = await process.stdout.read(4096) + if not data: + raise UserWarning("ssh-to-ws process close") + await ws.send(data) + async with asyncio.TaskGroup() as tg: + tg.create_task(ws_to_ssh()) + tg.create_task(ssh_to_ws()) -class LauncherConsole(ILauncher): - display: str + + +class LauncherConsole: internal_port: int external_port: int running: bool = False acceptsMsgs: bool = False - threads: List[Any] = [] - console_vnc: Any = Vnc_server() - async def run(self, config_file, callback): - DRI_PATH = self.get_dri_path() - ACCELERATION_ENABLED = False - - if ACCELERATION_ENABLED: - self.console_vnc.start_vnc_gpu( - self.display, self.internal_port, self.external_port, DRI_PATH - ) - # Write display config and start the console - console_cmd = f"export VGL_DISPLAY={DRI_PATH}; export DISPLAY={self.display}; vglrun xterm -fullscreen -sb -fa 'Monospace' -fs 10 -bg black -fg white" - else: - self.console_vnc.start_vnc( - self.display, self.internal_port, self.external_port - ) - # Write display config and start the console - console_cmd = f"export DISPLAY={self.display};xterm -geometry 100x10+0+0 -fa 'Monospace' -fs 10 -bg black -fg white" - - console_thread = DockerThread(console_cmd) - console_thread.start() - self.threads.append(console_thread) + def __init__(self, type, module, internal_port, external_port): + self.internal_port = internal_port + self.external_port = external_port + self.client = None + def __await__(self): + return self.create().__await__() + + async def create(self): + self.server = await serve(self.manage_conection, "127.0.0.1", self.external_port, start_serving=False) + return self + + async def run(self, config_file, callback): + LogManager.logger.info(f"Console started") + await self.server.start_serving() self.running = True + async def manage_conection(self, websocket): + if self.client is not None: + await websocket.close() + return + + try: + self.client = websocket # Register client + LogManager.logger.info(f"Client connected: {self.client}") + # init_cols = int(websocket.query_params.get("cols") or 80) + # init_rows = int(websocket.query_params.get("rows") or 24) + user = "root" + await ssh_shell(websocket, user, self.internal_port, "jderobot") + except ConnectionClosedOK as e: + pass + finally: + LogManager.logger.info("Connection with client closed") + self.client = None + def pause(self): pass @@ -53,14 +114,13 @@ def is_running(self): return self.running async def terminate(self): - LogManager.logger.info(f"Terminating console tool") - self.console_vnc.terminate() - for thread in self.threads[:]: - if thread.is_alive(): - thread.terminate() - thread.join() - self.threads.remove(thread) + self.server.close() + await self.server.wait_closed() self.running = False def died(self): pass + + async def from_config(cls, config): + obj = await cls(**config) + return obj diff --git a/robotics_application_manager/manager/launcher/launcher_tools.py b/robotics_application_manager/manager/launcher/launcher_tools.py index 6f85b4d..84b1fc9 100644 --- a/robotics_application_manager/manager/launcher/launcher_tools.py +++ b/robotics_application_manager/manager/launcher/launcher_tools.py @@ -8,8 +8,8 @@ tools = { "console": { + "type": "module", "module": "console", - "display": ":1", "external_port": 6082, "internal_port": 5901, }, From 614b4ac71ece966f28c26c223082127db54c679b Mon Sep 17 00:00:00 2001 From: Javier Izquierdo Hernandez Date: Sat, 7 Nov 2026 08:47:43 +0100 Subject: [PATCH 06/12] Clean manager and add ras --- .../manager/lint/linter.py | 8 +- .../manager/manager.py | 338 +----------------- robotics_application_services/__init__.py | 0 robotics_application_services/main.py | 12 +- .../routers/format.py | 116 ++++++ robotics_application_services/routers/ssh.py | 78 ---- 6 files changed, 123 insertions(+), 429 deletions(-) create mode 100644 robotics_application_services/__init__.py create mode 100644 robotics_application_services/routers/format.py delete mode 100644 robotics_application_services/routers/ssh.py diff --git a/robotics_application_manager/manager/lint/linter.py b/robotics_application_manager/manager/lint/linter.py index 9f91de3..60f4414 100644 --- a/robotics_application_manager/manager/lint/linter.py +++ b/robotics_application_manager/manager/lint/linter.py @@ -100,10 +100,10 @@ def evaluate_code( str: The cleaned and formatted pylint output. """ try: - code = re.sub(r"from HAL import HAL", "from hal import HAL", code) - code = re.sub(r"from GUI import GUI", "from gui import GUI", code) - code = re.sub(r"from MAP import MAP", "from map import MAP", code) - code = re.sub(r"\nimport cv2\n", "\nfrom cv2 import cv2\n", code) + # code = re.sub(r"from HAL import HAL", "from hal import HAL", code) + # code = re.sub(r"from GUI import GUI", "from gui import GUI", code) + # code = re.sub(r"from MAP import MAP", "from map import MAP", code) + # code = re.sub(r"\nimport cv2\n", "\nfrom cv2 import cv2\n", code) # Avoids EOF error when iterative code is empty (which prevents other errors from showing) loop_regex = ( diff --git a/robotics_application_manager/manager/manager.py b/robotics_application_manager/manager/manager.py index 3222dcf..c860661 100644 --- a/robotics_application_manager/manager/manager.py +++ b/robotics_application_manager/manager/manager.py @@ -148,59 +148,6 @@ class Manager: "dest": "=", "before": "on_style_check_application", }, - # Code analysis - { - "trigger": "code_analysis", - "source": [ - "idle", - "connected", - "paused", - "world_ready", - "tools_ready", - ], - "dest": "=", - "before": "on_code_analysis", - }, - # Code analysis - { - "trigger": "code_format", - "source": [ - "idle", - "connected", - "paused", - "world_ready", - "tools_ready", - ], - "dest": "=", - "before": "on_code_format", - }, - # Code analysis - { - "trigger": "code_autocomplete", - "source": [ - "idle", - "connected", - "paused", - "world_ready", - "tools_ready", - ], - "dest": "=", - "before": "on_code_autocomplete", - }, - # Theme change - { - "trigger": "change_style", - "source": [ - "idle", - "connected", - "paused", - "world_ready", - "tools_ready", - "application_running", - ], - "dest": "=", - "before": "on_change_style", - }, ] def __init__(self, host: str, port: int): @@ -482,289 +429,6 @@ def write_to_tool_terminal(self, msg): with open(i, "w") as console: console.write(msg) - async def on_style_check_application(self, event): - """ - Handle the 'style_check' event. - - Does not change the state and returns the current state. - - It uses the linter to check if the style of the code is correct, if there - are errors it writes them in all the consoles and raises the errors. - - Parameters: - event (Event): Has the fields code (user code), exercise_id and type (bt-studio or robotics-academy) . - - Raises: - Exception: with the errors found in the linter - """ - # TODO: redo - - # Extract app config - app_cfg = event.kwargs.get("data", {}) - try: - if app_cfg["type"] == "bt-studio": - return - except Exception: - pass - - exercise_id = app_cfg["exercise_id"] - code = app_cfg["code"] - - # Make code backwards compatible - code = code.replace("from GUI import GUI", "import GUI") - code = code.replace("from HAL import HAL", "import HAL") - - # Create executable app - errors = self.linter.evaluate_code( - code, - exercise_id, - self.ros_version, - py_lint_source="pylint_checker_style.py", - ) - - if errors == "": - errors = "No errors found" - - self.write_to_tool_terminal(errors + "\n\n") - raise Exception(errors) - - async def on_code_analysis(self, event): - """ - Handle the 'code_analysis' event. - - Does not change the state and returns the current state. - It uses pylint to check for the errors and warnings in the code. - - Parameters: - event (Event): Has the fields code (user code) and disable_errors (disable errors id for pylint) . - - Returns: - Sends the output of the pylint command in the code-analysis event for the frontend. - """ - # Extract app config - app_cfg = event.kwargs.get("data", {}) - code_string = app_cfg["code"] - disable_error_ids = app_cfg["disable_errors"] - - # if code string is empty - if not code_string: - LogManager.logger.info("User code not found") - return - - # Save the code string to a temporary file - with tempfile.NamedTemporaryFile(suffix=".py", delete=False) as temp_file: - temp_file.write(code_string.encode("utf-8")) - temp_file_path = temp_file.name - - # terminal command - command = [ - "pylint", - "--output-format=json", - ] + [temp_file_path] - # '--extension-pkg-whitelist=cv2' - - # Add the disable option for specific error IDs - if disable_error_ids: - disable_str = ",".join(disable_error_ids) - command.append(f"--disable={disable_str}") - - # run the command - result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - - # Decode the results - pylint_output = result.stdout.decode("utf-8") - pylint_errors = result.stderr.decode("utf-8") - - # Parse the JSON output if pylint output is not empty - try: - pylint_json = json.loads(pylint_output) if pylint_output else [] - except json.JSONDecodeError as e: - LogManager.logger.info(f"Failed to parse JSON: {str(e)}") - - # Clean up the temporary file after Pylint run - if os.path.exists(temp_file_path): - os.remove(temp_file_path) - - if pylint_errors: - LogManager.logger.info("Found errors in code") - - self.consumer.send_message( - {"pylint_output": pylint_json, "pylint_errors": pylint_errors}, - command="code-analysis", - ) - - async def on_code_format(self, event): - """ - Handle the 'code_format' event. - - Does not change the state and returns the current state. - It uses the black formatter to format the user code. - - Parameters: - event (Event): Has the fields code (user code). - - Returns: - Sends the output of the black format in - the code-format event for the frontend. - """ - # Extract app config - app_cfg = event.kwargs.get("data", {}) - code = app_cfg["code"] - - # if code string is empty - if not code: - LogManager.logger.info("User code not found") - return - - try: - # Format the code with Black - formatted_code = black.format_str(code, mode=black.Mode()) - self.consumer.send_message( - { - "formatted_code": formatted_code, - }, - command="code-format", - ) - except Exception as e: - LogManager.logger.info("Error formating code" + str(e)) - - def on_code_autocomplete(self, event): - """ - Handle the 'code_autocomplete' event. - - Does not change the state and returns the current state. - It uses jedi to find the possible autocompletions in the user code - given the cursor position. - - Parameters: - event (Event): Has the fields code (user code), line and col . - - Returns: - Sends the possible completions in - the code-autocomplete event for the frontend. - """ - # Extract app config - app_cfg = event.kwargs.get("data", {}) - code = app_cfg["code"] - line = app_cfg["line"] - col = app_cfg["col"] - - jedi.settings.add_bracket_after_function = True - - # if code string is empty - if not code: - LogManager.logger.info("User code not found") - return - - if not line or not col: - LogManager.logger.info("User code position not found") - return - - script = jedi.Script(code, path="/workspace/code/academy.py") - - try: - completions = script.complete(line, col) - serialized_completions = serialize_completions(completions) - - self.consumer.send_message( - { - "completions": serialized_completions, - }, - command="code-autocomplete", - ) - except Exception as e: - LogManager.logger.info("Error formating code" + str(e)) - - def on_change_style(self, event): - """ - Handle the 'change_style' event. - - This method changes the GTK theme and xterm colors without restarting. - - Parameters: - event (Event): Has the field 'theme' (dark or light) in data. - """ - app_cfg = event.kwargs.get("data", {}) - theme = app_cfg.get("theme", "dark") - LogManager.logger.info(f"Changing style to {theme}") - - if theme == "dark": - # Xterm dark theme: background black, foreground white - xterm_cmd = "\033]11;black\007\033]10;white\007" - gtk_theme = "Adwaita-dark" - else: - # Xterm light theme: background white, foreground black - xterm_cmd = "\033]11;white\007\033]10;black\007" - gtk_theme = "Adwaita" - - # Apply xterm theme to all active pseudoterminals - try: - self.write_to_tool_terminal(xterm_cmd) - except Exception as e: - LogManager.logger.exception(f"Error changing xterm style: {e}") - - # Update GTK settings for new windows - # Write ~/.gtkrc-2.0 - gtkrc_path = os.path.expanduser("~/.gtkrc-2.0") - try: - with open(gtkrc_path, "w") as f: - f.write(f'gtk-theme-name="{gtk_theme}"\n') - except Exception as e: - LogManager.logger.exception(f"Error writing {gtkrc_path}: {e}") - - # Write ~/.config/gtk-3.0/settings.ini - gtk3_dir = os.path.expanduser("~/.config/gtk-3.0") - gtk3_path = os.path.join(gtk3_dir, "settings.ini") - try: - os.makedirs(gtk3_dir, exist_ok=True) - with open(gtk3_path, "w") as f: - f.write("[Settings]\n") - f.write(f"gtk-theme-name={gtk_theme}\n") - except Exception as e: - LogManager.logger.exception(f"Error writing {gtk3_path}: {e}") - - # Send a signal to force GTK applications to reload their theme - try: - # Also write to lxsession config which is what LXDE actually uses - lxde_conf_dir = os.path.expanduser("~/.config/lxsession/LXDE") - lxde_conf_path = os.path.join(lxde_conf_dir, "desktop.conf") - os.makedirs(lxde_conf_dir, exist_ok=True) - - # Read existing or create new - conf_lines = [] - if os.path.exists(lxde_conf_path): - with open(lxde_conf_path, "r") as f: - conf_lines = f.readlines() - - # Ensure GTK section exists and update theme name - gtk_section_found = False - for i, line in enumerate(conf_lines): - if line.strip() == "[GTK]": - gtk_section_found = True - elif gtk_section_found and line.startswith("sNet/ThemeName="): - conf_lines[i] = f"sNet/ThemeName={gtk_theme}\\n" - break - else: - if not gtk_section_found: - conf_lines.append("[GTK]\\n") - conf_lines.append(f"sNet/ThemeName={gtk_theme}\\n") - - with open(lxde_conf_path, "w") as f: - f.writelines(conf_lines) - - # Reload window manager (Openbox) and LXPanel - subprocess.run( - [ - "bash", - "-c", - "export DISPLAY=:1; lxpanelctl restart; openbox --reconfigure", - ], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - ) - except Exception as e: - LogManager.logger.exception(f"Error refreshing GTK applications: {e}") - async def on_run_application(self, event): """ Handle the 'run_application' event. @@ -872,7 +536,7 @@ async def on_run_application(self, event): command, stdin=open("/dev/pts/" + console_fd, "r"), stdout=open("/dev/pts/" + console_fd, "w"), - stderr=sys.stdout, + stderr=open("/dev/pts/" + console_fd, "w"), bufsize=1024, universal_newlines=True, shell=shell, diff --git a/robotics_application_services/__init__.py b/robotics_application_services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/robotics_application_services/main.py b/robotics_application_services/main.py index 97c2dd2..106095c 100644 --- a/robotics_application_services/main.py +++ b/robotics_application_services/main.py @@ -4,7 +4,7 @@ from uvicorn import run import argparse -from .routers import ssh +from routers import format @asynccontextmanager async def lifespan(app: FastAPI): @@ -15,7 +15,7 @@ async def lifespan(app: FastAPI): app = FastAPI(lifespan=lifespan) -app.include_router(ssh.router) +app.include_router(format.router) origins = ["*"] @@ -29,12 +29,4 @@ async def lifespan(app: FastAPI): if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument( - "host", type=str, help="Host to listen to (0.0.0.0 or all hosts)" - ) - parser.add_argument("port", type=int, help="Port to listen to") - args = parser.parse_args() - project = args.project - run(app, host="0.0.0.0", port=8000) diff --git a/robotics_application_services/routers/format.py b/robotics_application_services/routers/format.py new file mode 100644 index 0000000..c85e397 --- /dev/null +++ b/robotics_application_services/routers/format.py @@ -0,0 +1,116 @@ +from fastapi import APIRouter, HTTPException, File +from fastapi.responses import FileResponse +import json +import os +from pydantic import BaseModel +import black + +router = APIRouter( + prefix="/format" + tags=["formatters"], + responses={404: {"description": "Not found"}}, +) + +class FileItem(BaseModel): + content: str + +@router.post("/black", response_model=FileItem) +async def format(item: FileItem): + """ + Handle the 'code_format' event. + + Does not change the state and returns the current state. + It uses the black formatter to format the user code. + + Parameters: + event (Event): Has the fields code (user code). + + Returns: + Sends the output of the black format in + the code-format event for the frontend. + """ + code = item.content + + # if code string is empty + if not code: + raise HTTPException(status_code=404, detail="User code not found") + + try: + # Format the code with Black + formatted_code = black.format_str(code, mode=black.Mode()) + return {"content": formatted_code} + except Exception as e: + raise HTTPException(status_code=404, detail="Error formating code" + str(e)) + +@router.post("/clang", response_model=FileItem) +async def clang(item: FileItem): + """ + Parameters: + event (Event): Has the fields code (user code). + + Returns: + Sends the output of the black format in + the code-format event for the frontend. + """ + code = item.content + + # if code string is empty + if not code: + raise HTTPException(status_code=404, detail="User code not found") + + command = f"echo '{code}' | clang-format -style=file" + + try: + # Format the code with Clang + ret = subprocess.run(command, capture_output=True, text=True, shell=True) + formatted_code = ret.stdout + return {"content": formatted_code} + except Exception as e: + raise HTTPException(status_code=404, detail="Error formating code" + str(e)) + + +# async def on_style_check_application(self, event): +# """ +# Handle the 'style_check' event. + +# Does not change the state and returns the current state. + +# It uses the linter to check if the style of the code is correct, if there +# are errors it writes them in all the consoles and raises the errors. + +# Parameters: +# event (Event): Has the fields code (user code), exercise_id and type (bt-studio or robotics-academy) . + +# Raises: +# Exception: with the errors found in the linter +# """ +# # TODO: redo + +# # Extract app config +# app_cfg = event.kwargs.get("data", {}) +# try: +# if app_cfg["type"] == "bt-studio": +# return +# except Exception: +# pass + +# exercise_id = app_cfg["exercise_id"] +# code = app_cfg["code"] + +# # Make code backwards compatible +# code = code.replace("from GUI import GUI", "import GUI") +# code = code.replace("from HAL import HAL", "import HAL") + +# # Create executable app +# errors = self.linter.evaluate_code( +# code, +# exercise_id, +# self.ros_version, +# py_lint_source="pylint_checker_style.py", +# ) + +# if errors == "": +# errors = "No errors found" + +# self.write_to_tool_terminal(errors + "\n\n") +# raise Exception(errors) \ No newline at end of file diff --git a/robotics_application_services/routers/ssh.py b/robotics_application_services/routers/ssh.py deleted file mode 100644 index 8db4d24..0000000 --- a/robotics_application_services/routers/ssh.py +++ /dev/null @@ -1,78 +0,0 @@ -from fastapi import APIRouter -from fastapi.websockets import WebSocket, WebSocketDisconnect, WebSocketState -import json -import os -import asyncio -import asyncssh -import subprocess - -router = APIRouter( - tags=["ssh"], - responses={404: {"description": "Not found"}}, -) - - -@router.websocket("/console") -async def terminal_endpoint(websocket: WebSocket): - await websocket.accept() - try: - init_cols = int(websocket.query_params.get("cols") or 80) - init_rows = int(websocket.query_params.get("rows") or 24) - user = "root" - await ssh_shell( - websocket, user, 8081, "jderobot", init_cols, init_rows, setting.val - ) - except Exception as e: - pass - - if websocket.client_state != WebSocketState.DISCONNECTED: - await websocket.close() - - -async def ssh_shell( - ws: WebSocket, - user: str, - port: int, - passwd: str, - init_cols: int = 80, - init_rows: int = 24, - workspace: str = "/", -): - subprocess.run(["/usr/sbin/sshd"]) - async with asyncssh.connect( - "localhost", port=port, username=user, password=passwd, known_hosts=None - ) as conn: - async with conn.create_process( - term_type="xterm-color", - term_size=(init_cols, init_rows), - stderr=asyncssh.STDOUT, - ) as process: - process.stdin.write(f"cd {workspace};clear;\n") - - async def ws_to_ssh(): - while True: - raw = await ws.receive() - if raw.get("text"): - data = raw["text"] - process.stdin.write(data) - await process.stdin.drain() - elif raw.get("bytes"): - data = raw["bytes"] - msg = json.loads(data.decode("utf-8")) - if "resize" in msg: - cols = int(msg["resize"].get("cols", init_cols)) - rows = int(msg["resize"].get("rows", init_rows)) - process.change_terminal_size(cols, rows) - elif raw["type"] == "websocket.disconnect": - raise UserWarning("ws-to-ssh ws disconnect") - - async def ssh_to_ws(): - while True: - data = await process.stdout.read(4096) - if not data: - raise UserWarning("ssh-to-ws process close") - await ws.send_text(data) - - async with asyncio.TaskGroup() as tg: - tg.create_task(ws_to_ssh()) - tg.create_task(ssh_to_ws()) From 51f958f15e1be1e042198fe0ef3eb2f6704e9f40 Mon Sep 17 00:00:00 2001 From: Javier Izquierdo Hernandez Date: Mon, 9 Nov 2026 10:43:52 +0100 Subject: [PATCH 07/12] Fix typo --- robotics_application_services/routers/format.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/robotics_application_services/routers/format.py b/robotics_application_services/routers/format.py index c85e397..920d5a4 100644 --- a/robotics_application_services/routers/format.py +++ b/robotics_application_services/routers/format.py @@ -6,7 +6,7 @@ import black router = APIRouter( - prefix="/format" + prefix="/format", tags=["formatters"], responses={404: {"description": "Not found"}}, ) From af05689e320a3e2a674ce36ac8667f7ce0db18a6 Mon Sep 17 00:00:00 2001 From: Javier Izquierdo Hernandez Date: Mon, 9 Nov 2026 15:12:23 +0100 Subject: [PATCH 08/12] Remove pass --- robotics_application_manager/libs/server.py | 1 - 1 file changed, 1 deletion(-) diff --git a/robotics_application_manager/libs/server.py b/robotics_application_manager/libs/server.py index 089430e..913249f 100644 --- a/robotics_application_manager/libs/server.py +++ b/robotics_application_manager/libs/server.py @@ -48,7 +48,6 @@ async def manage_conection(self, websocket): await self.process_msg(websocket) except Exception as e: LogManager.logger.info(f"Client disconnected: {str(e)}") - pass finally: LogManager.logger.info("Connection with client closed") with self.client_lock: From 0cdb23da204cdc133dbccb82176dddf8defd10ec Mon Sep 17 00:00:00 2001 From: Javier Izquierdo Hernandez Date: Tue, 10 Nov 2026 12:38:25 +0100 Subject: [PATCH 09/12] Fix conexion issues --- .../comms/consumer.py | 18 ++- .../manager/launcher/launcher_console.py | 117 ++++++++++-------- .../manager/launcher/launcher_gzsim.py | 10 +- .../manager/launcher/launcher_tools.py | 6 +- .../manager/manager.py | 2 +- 5 files changed, 79 insertions(+), 74 deletions(-) diff --git a/robotics_application_manager/comms/consumer.py b/robotics_application_manager/comms/consumer.py index 0e150f0..d42bd14 100644 --- a/robotics_application_manager/comms/consumer.py +++ b/robotics_application_manager/comms/consumer.py @@ -14,7 +14,6 @@ ManagerConsumerMessageException, ManagerConsumerMessage, ) -from robotics_application_manager import LogManager from websockets.asyncio.server import serve from websockets.exceptions import ConnectionClosedOK import asyncio @@ -43,7 +42,7 @@ def __init__(self, host, port, process_callback): self.server_task = None # Configurar el logger de websocket_server para salida a consola - self.ws_logger = logging.getLogger("websocket_server.websocket_server") + self.ws_logger = logging.getLogger("commsmanager.websocket") self.ws_logger.propagate = False self.ws_logger.setLevel(logging.INFO) self.ws_logger.handlers.clear() @@ -68,20 +67,19 @@ async def create(self): async def manage_conection(self, websocket): if self.client is not None: + self.ws_logger.info("Client is already connected") await websocket.close() return try: self.client = websocket # Register client - LogManager.logger.info(f"client connected: {self.client}") - - await self.process_msg(websocket) - except ConnectionClosedOK as e: + self.ws_logger.info(f"Client connected: {self.client}") + + await self.process_msg(self.client) + except Exception as e: pass finally: - now = datetime.now() - time_str = now.strftime("%H:%M:%S") - LogManager.logger.info(f"Client disconnected {time_str}: {self.client}") + self.ws_logger.info(f"Client disconnected") self.client = None async def process_msg(self, websocket): @@ -92,7 +90,7 @@ async def process_msg(self, websocket): except Exception as e: ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) await self.send_message(ex) - LogManager.logger.error(e, exc_info=True) + self.ws_logger.error(e, exc_info=True) async def send_message(self, message_data, command=None): """ diff --git a/robotics_application_manager/manager/launcher/launcher_console.py b/robotics_application_manager/manager/launcher/launcher_console.py index 0437414..0be4799 100644 --- a/robotics_application_manager/manager/launcher/launcher_console.py +++ b/robotics_application_manager/manager/launcher/launcher_console.py @@ -9,56 +9,6 @@ import asyncssh import subprocess -async def ssh_shell( - ws, - user: str, - port: int, - passwd: str, - init_cols: int = 80, - init_rows: int = 24, - workspace: str = "/", -): - subprocess.run(["/usr/sbin/sshd"]) - async with asyncssh.connect( - "localhost", port=port, username=user, password=passwd, known_hosts=None - ) as conn: - async with conn.create_process( - term_type="xterm-color", - term_size=(init_cols, init_rows), - stderr=asyncssh.STDOUT, - ) as process: - process.stdin.write(f"cd {workspace};clear;\n") - - async def ws_to_ssh(): - try: - async for raw in ws: - if type(raw) == str: - process.stdin.write(raw) - await process.stdin.drain() - elif type(raw) == bytes: - data = raw - msg = json.loads(data.decode("utf-8")) - if "resize" in msg: - cols = int(msg["resize"].get("cols", init_cols)) - rows = int(msg["resize"].get("rows", init_rows)) - process.change_terminal_size(cols, rows) - # elif raw["type"] == "websocket.disconnect": - # raise UserWarning("ws-to-ssh ws disconnect") - except: - raise UserWarning("ws-to-ssh ws disconnect") - - async def ssh_to_ws(): - while True: - data = await process.stdout.read(4096) - if not data: - raise UserWarning("ssh-to-ws process close") - await ws.send(data) - - async with asyncio.TaskGroup() as tg: - tg.create_task(ws_to_ssh()) - tg.create_task(ssh_to_ws()) - - class LauncherConsole: internal_port: int @@ -70,14 +20,68 @@ def __init__(self, type, module, internal_port, external_port): self.internal_port = internal_port self.external_port = external_port self.client = None + self.task_group = None def __await__(self): return self.create().__await__() async def create(self): - self.server = await serve(self.manage_conection, "127.0.0.1", self.external_port, start_serving=False) + self.server = await serve( + self.manage_conection, "127.0.0.1", self.external_port, start_serving=False + ) return self + async def ssh_shell( + self, + ws, + user: str, + port: int, + passwd: str, + init_cols: int = 80, + init_rows: int = 24, + workspace: str = "/", + ): + subprocess.run(["/usr/sbin/sshd"]) + async with asyncssh.connect( + "localhost", port=port, username=user, password=passwd, known_hosts=None + ) as conn: + async with conn.create_process( + term_type="xterm-color", + term_size=(init_cols, init_rows), + stderr=asyncssh.STDOUT, + ) as process: + process.stdin.write(f"cd {workspace};clear;\n") + + async def ws_to_ssh(): + try: + async for raw in ws: + if type(raw) == str: + process.stdin.write(raw) + await process.stdin.drain() + elif type(raw) == bytes: + data = raw + msg = json.loads(data.decode("utf-8")) + if "resize" in msg: + cols = int(msg["resize"].get("cols", init_cols)) + rows = int(msg["resize"].get("rows", init_rows)) + process.change_terminal_size(cols, rows) + except: + # raise UserWarning("ws-to-ssh ws disconnect") + return + + async def ssh_to_ws(): + while True: + data = await process.stdout.read(4096) + if not data: + # raise UserWarning("ssh-to-ws process close") + return + await ws.send(data) + + async with asyncio.TaskGroup() as tg: + self.task_group = tg + tg.create_task(ws_to_ssh()) + tg.create_task(ssh_to_ws()) + async def run(self, config_file, callback): LogManager.logger.info(f"Console started") await self.server.start_serving() @@ -85,16 +89,16 @@ async def run(self, config_file, callback): async def manage_conection(self, websocket): if self.client is not None: - await websocket.close() - return + await websocket.close() + return try: - self.client = websocket # Register client + self.client = websocket # Register client LogManager.logger.info(f"Client connected: {self.client}") # init_cols = int(websocket.query_params.get("cols") or 80) # init_rows = int(websocket.query_params.get("rows") or 24) user = "root" - await ssh_shell(websocket, user, self.internal_port, "jderobot") + await self.ssh_shell(websocket, user, self.internal_port, "jderobot") except ConnectionClosedOK as e: pass finally: @@ -114,9 +118,12 @@ def is_running(self): return self.running async def terminate(self): + assert self.task_group is not None + self.task_group._abort() self.server.close() await self.server.wait_closed() self.running = False + LogManager.logger.info(f"Terminating console") def died(self): pass diff --git a/robotics_application_manager/manager/launcher/launcher_gzsim.py b/robotics_application_manager/manager/launcher/launcher_gzsim.py index 67029c1..ced13a7 100644 --- a/robotics_application_manager/manager/launcher/launcher_gzsim.py +++ b/robotics_application_manager/manager/launcher/launcher_gzsim.py @@ -35,24 +35,22 @@ async def run(self, config_file, callback): DRI_PATH = self.get_dri_path() ACCELERATION_ENABLED = self.check_device(DRI_PATH) + LogManager.logger.info(f"Gz: {config_file}") if config_file is None: config_file = "/opt/jderobot/Launchers/visualization/default.config" - # Configure browser screen width and height for gz GUI - gzclient_config_cmds = f"sed -i 's/.*<\/width>/{self.width}<\/width>/; s/.*<\/height>/{self.height}<\/height>/' {config_file};" - if ACCELERATION_ENABLED: # Starts xserver, x11vnc and novnc self.gz_vnc.start_vnc_gpu( self.display, self.internal_port, self.external_port, DRI_PATH ) # Write display config and start gzclient - gzclient_cmd = f"export DISPLAY={self.display}; {gzclient_config_cmds} export VGL_DISPLAY={DRI_PATH}; vglrun gz sim -g -v4 --gui-config {config_file}" + gzclient_cmd = f"export DISPLAY={self.display}; export VGL_DISPLAY={DRI_PATH}; vglrun gz sim -g -v4 --gui-config {config_file}" else: # Starts xserver, x11vnc and novnc self.gz_vnc.start_vnc(self.display, self.internal_port, self.external_port) # Write display config and start gzclient - gzclient_cmd = f"export DISPLAY={self.display}; {gzclient_config_cmds} gz sim -g -v4 --gui-config {config_file}" + gzclient_cmd = f"export DISPLAY={self.display}; gz sim -g -v4 --gui-config {config_file}" gzclient_thread = DockerThread(gzclient_cmd) gzclient_thread.start() @@ -73,7 +71,6 @@ def is_running(self): return self.running async def terminate(self): - LogManager.logger.info(f"Terminating gz tool") self.gz_vnc.terminate() for thread in self.threads[:]: if thread.is_alive(): @@ -81,6 +78,7 @@ async def terminate(self): thread.join() self.threads.remove(thread) self.running = False + LogManager.logger.info(f"Terminating gz tool") def died(self): pass diff --git a/robotics_application_manager/manager/launcher/launcher_tools.py b/robotics_application_manager/manager/launcher/launcher_tools.py index 84b1fc9..163fac9 100644 --- a/robotics_application_manager/manager/launcher/launcher_tools.py +++ b/robotics_application_manager/manager/launcher/launcher_tools.py @@ -62,8 +62,10 @@ class LauncherTools(BaseModel): async def run(self, consumer): for tool in self.tools: if tool == "simulator": - tool = simulator[self.world_type]["tool"] - module = tools[tool] + module = tools[simulator[self.world_type]["tool"]] + else: + module = tools[tool] + if module["module"] is None: continue launcher = await self.launch_module(tool, module, consumer) diff --git a/robotics_application_manager/manager/manager.py b/robotics_application_manager/manager/manager.py index c860661..bf66e39 100644 --- a/robotics_application_manager/manager/manager.py +++ b/robotics_application_manager/manager/manager.py @@ -239,6 +239,7 @@ async def on_connect(self, event): - `ros_version`: The current ROS (Robot Operating System) distribution version. - `gpu_avaliable`: Boolean indicating whether GPU acceleration is available. """ + LogManager.logger.info("-------------------Connecting--------------------------") await self.consumer.send_message( { "robotics_backend_version": subprocess.check_output( @@ -575,7 +576,6 @@ async def on_terminate_application(self, event): self.application_processes = [] async def on_terminate_tools(self, event): - await self.tools_launcher.terminate() self.tools_launcher = None From d4790537cee99654749bb8873253d05da398ebe8 Mon Sep 17 00:00:00 2001 From: Javier Izquierdo Hernandez Date: Wed, 11 Nov 2026 12:53:21 +0100 Subject: [PATCH 10/12] Fix missing humble update --- robotics_application_manager/manager/manager.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/robotics_application_manager/manager/manager.py b/robotics_application_manager/manager/manager.py index bf66e39..ab8d7a4 100644 --- a/robotics_application_manager/manager/manager.py +++ b/robotics_application_manager/manager/manager.py @@ -393,7 +393,7 @@ async def prepare_custom_world(self, cfg_dict): zip_ref.close() os.system( - '/bin/bash -c "cd /workspace/worlds; source /opt/ros/humble/setup.bash; colcon build --symlink-install; source install/setup.bash; cd ../.."' + '/bin/bash -c "cd /workspace/worlds; source /opt/ros/lyrical/setup.bash; colcon build --symlink-install; source install/setup.bash; cd ../.."' ) async def on_prepare_tools(self, event): From d65a849a7acf126b5c7d6eabaf3fbfb30443ad80 Mon Sep 17 00:00:00 2001 From: Javier Izquierdo Hernandez Date: Mon, 16 Nov 2026 09:57:15 +0100 Subject: [PATCH 11/12] Clean threads properly --- .../manager/docker_thread/docker_thread.py | 6 +- .../manager/launcher/launcher_console.py | 7 + .../manager/launcher/launcher_gzsim.py | 5 +- .../manager/vnc/vnc_server.py | 140 ++++-------------- 4 files changed, 40 insertions(+), 118 deletions(-) diff --git a/robotics_application_manager/manager/docker_thread/docker_thread.py b/robotics_application_manager/manager/docker_thread/docker_thread.py index 9b97099..974c5de 100644 --- a/robotics_application_manager/manager/docker_thread/docker_thread.py +++ b/robotics_application_manager/manager/docker_thread/docker_thread.py @@ -5,6 +5,7 @@ import os import signal import sys +import psutil class DockerThread(threading.Thread): @@ -40,12 +41,13 @@ def run(self): universal_newlines=True, executable="/bin/bash", ) + self.process_group = os.getpgid(self.process.pid) self.process.communicate() def terminate(self): """Terminates the thread and the process""" if self.process: try: - os.killpg(os.getpgid(self.process.pid), signal.SIGTERM) + os.killpg(self.process_group, signal.SIGTERM) except ProcessLookupError as error: - print(f"{self.process.pid}: Process already terminated {error}") + print(f"{self.process_group}/{self.process.pid}: Process {self.cmd} already terminated {error}") diff --git a/robotics_application_manager/manager/launcher/launcher_console.py b/robotics_application_manager/manager/launcher/launcher_console.py index 0be4799..e54ed0b 100644 --- a/robotics_application_manager/manager/launcher/launcher_console.py +++ b/robotics_application_manager/manager/launcher/launcher_console.py @@ -123,6 +123,13 @@ async def terminate(self): self.server.close() await self.server.wait_closed() self.running = False + subprocess.call( + "pkill -9 ssh-agent", + shell=True, + stdout=subprocess.PIPE, + bufsize=1024, + universal_newlines=True, + ) LogManager.logger.info(f"Terminating console") def died(self): diff --git a/robotics_application_manager/manager/launcher/launcher_gzsim.py b/robotics_application_manager/manager/launcher/launcher_gzsim.py index ced13a7..e27345f 100644 --- a/robotics_application_manager/manager/launcher/launcher_gzsim.py +++ b/robotics_application_manager/manager/launcher/launcher_gzsim.py @@ -73,9 +73,8 @@ def is_running(self): async def terminate(self): self.gz_vnc.terminate() for thread in self.threads[:]: - if thread.is_alive(): - thread.terminate() - thread.join() + thread.terminate() + thread.join() self.threads.remove(thread) self.running = False LogManager.logger.info(f"Terminating gz tool") diff --git a/robotics_application_manager/manager/vnc/vnc_server.py b/robotics_application_manager/manager/vnc/vnc_server.py index c554299..f0e9801 100755 --- a/robotics_application_manager/manager/vnc/vnc_server.py +++ b/robotics_application_manager/manager/vnc/vnc_server.py @@ -19,22 +19,8 @@ class Vnc_server: threads: List[Any] = [] running: bool = False - def start_vnc(self, display, internal_port, external_port): - """Start a VNC and noVNC server session. - - Args: - display (str): X display identifier. - internal_port (int): Port for the VNC server. - external_port (int): Port for the noVNC server. - """ - # Start X and VNC servers - turbovnc_cmd = ( - f"export TVNC_WM=startlxde && " - f"/opt/TurboVNC/bin/vncserver {display} " - f"-geometry '1920x1080' -noreset " - f"-SecurityTypes None -rfbport {internal_port}" - ) - turbovnc_thread = DockerThread(turbovnc_cmd) + def start(self, display, internal_port, external_port, vnc_cmd): + turbovnc_thread = DockerThread(vnc_cmd) turbovnc_thread.start() self.threads.append(turbovnc_thread) wait_for_xserver(display) @@ -45,18 +31,11 @@ def start_vnc(self, display, internal_port, external_port): certs = "--cert /etc/certs/cert.pem --key /etc/certs/privkey.pem" # Start noVNC with default port 6080 listening to VNC server on 5900 - if self.get_ros_version() == "2": - novnc_cmd = ( - f"/noVNC/utils/novnc_proxy --listen {external_port} " - f"--vnc localhost:{internal_port} " - f"{certs}" - ) - else: - novnc_cmd = ( - f"/noVNC/utils/launch.sh --listen {external_port} " - f"--vnc localhost:{internal_port} " - f"{certs}" - ) + novnc_cmd = ( + f"/noVNC/utils/novnc_proxy --listen {external_port} " + f"--vnc localhost:{internal_port} " + f"{certs}" + ) novnc_thread = DockerThread(novnc_cmd) novnc_thread.start() @@ -66,6 +45,23 @@ def start_vnc(self, display, internal_port, external_port): self.wait_for_port("localhost", internal_port) self.wait_for_port("localhost", external_port) + def start_vnc(self, display, internal_port, external_port): + """Start a VNC and noVNC server session. + + Args: + display (str): X display identifier. + internal_port (int): Port for the VNC server. + external_port (int): Port for the noVNC server. + """ + # Start X and VNC servers + turbovnc_cmd = ( + f"export TVNC_WM=startlxde && " + f"/opt/TurboVNC/bin/vncserver {display} " + f"-geometry '1920x1080' -noreset " + f"-SecurityTypes None -rfbport {internal_port}" + ) + self.start(display, internal_port, external_port, turbovnc_cmd) + def start_vnc_gpu(self, display, internal_port, external_port, dri_path): """Start a GPU-accelerated VNC and noVNC server session. @@ -83,37 +79,7 @@ def start_vnc_gpu(self, display, internal_port, external_port, dri_path): f"-geometry '1920x1080' -vgl -noreset " f"-SecurityTypes None -rfbport {internal_port}" ) - turbovnc_thread = DockerThread(turbovnc_cmd) - turbovnc_thread.start() - self.threads.append(turbovnc_thread) - wait_for_xserver(display) - - certs = "" - - if os.path.isfile("/etc/certs/cert.pem"): - certs = "--cert /etc/certs/cert.pem --key /etc/certs/privkey.pem" - - # Start noVNC with default port 6080 listening to VNC server on 5900 - if self.get_ros_version() == "2": - novnc_cmd = ( - f"/noVNC/utils/novnc_proxy --listen {external_port} " - f"--vnc localhost:{internal_port} " - f"{certs}" - ) - else: - novnc_cmd = ( - f"/noVNC/utils/launch.sh --listen {external_port} " - f"--vnc localhost:{internal_port} " - f"{certs}" - ) - - novnc_thread = DockerThread(novnc_cmd) - novnc_thread.start() - self.threads.append(novnc_thread) - self.running = True - - self.wait_for_port("localhost", internal_port) - self.wait_for_port("localhost", external_port) + self.start(display, internal_port, external_port, turbovnc_cmd) def wait_for_port(self, host, port, timeout=120): """Wait for a TCP port on a host to become available within a timeout period. @@ -154,59 +120,7 @@ def is_running(self): def terminate(self): """Terminate all running threads and stop the VNC server.""" for thread in self.threads[:]: - if thread.is_alive(): - thread.terminate() - thread.join() + thread.terminate() + thread.join() self.threads.remove(thread) self.running = False - - def get_ros_version(self): - """Get the current ROS version from the environment. - - Returns: - str: The ROS version as a string. - """ - output = subprocess.check_output(["bash", "-c", "echo $ROS_VERSION"]) - return output.decode("utf-8").strip() - - def create_desktop_icon(self): - """Create a desktop icon to launch a terminal application.""" - try: - desktop_dir = os.path.expanduser("~/Desktop") - if not os.path.exists(desktop_dir): - os.makedirs(desktop_dir) - desktop_path = os.path.join(desktop_dir, "terminal_launcher.desktop") - with open(desktop_path, "w") as f: - f.write("""[Desktop Entry] - Name=Open Terminal - Exec=xterm - Icon=utilities-terminal - Type=Application - Encoding=UTF-8 - Terminal=false - Categories=None;""") - os.chmod(desktop_path, 0o755) - except Exception as err: - print(err) - - def create_gzclient_icon(self): - """Create a desktop icon to launch the Gazebo client application.""" - desktop_dir = os.path.expanduser("~/Desktop") - if not os.path.exists(desktop_dir): - os.makedirs(desktop_dir) - desktop_path = os.path.join(desktop_dir, "gzclient_launcher.desktop") - - try: - with open(desktop_path, "w") as f: - f.write("""[Desktop Entry] - Name=Gazebo Client - Exec=gzclient - Icon=gazebo - Type=Application - Encoding=UTF-8 - Terminal=false - Categories=None;""") - os.chmod(desktop_path, 0o755) - print("Icono de gzclient creado con éxito en el escritorio.") - except Exception as e: - print(f"Error al crear el icono de gzclient: {e}") From 8a0b1d97594a67c9bf1bd1559fcb4d2c47192181 Mon Sep 17 00:00:00 2001 From: Javier Izquierdo Hernandez Date: Mon, 16 Nov 2026 10:36:09 +0100 Subject: [PATCH 12/12] Linter --- .../comms/consumer.py | 38 +++++++++------- robotics_application_manager/comms/thread.py | 1 - .../libs/process_utils.py | 2 +- robotics_application_manager/libs/server.py | 38 +++++++++------- .../manager/docker_thread/docker_thread.py | 44 ++++++++++--------- .../manager/launcher/launcher_robot.py | 4 +- .../manager/launcher/launcher_scene.py | 2 +- .../manager/manager.py | 18 +++++--- robotics_application_services/main.py | 1 + .../routers/format.py | 5 ++- 10 files changed, 91 insertions(+), 62 deletions(-) diff --git a/robotics_application_manager/comms/consumer.py b/robotics_application_manager/comms/consumer.py index d42bd14..52d0639 100644 --- a/robotics_application_manager/comms/consumer.py +++ b/robotics_application_manager/comms/consumer.py @@ -18,6 +18,7 @@ from websockets.exceptions import ConnectionClosedOK import asyncio + class ManagerConsumer: """ Websocket server consumer for new Robotics Application Manager aka: RAM. @@ -25,8 +26,8 @@ class ManagerConsumer: Supports single client connection to RAM TODO: Better handling of single client connections, closing and redirecting """ - def __init__(self, host, port, process_callback): + def __init__(self, host, port, process_callback): """ Initialize the ManagerConsumer with host, port, and manager_queue. @@ -62,19 +63,26 @@ def __await__(self): # A method that creates an instance of the class asynchronously async def create(self): - self.server = await serve(self.manage_conection, self.host, self.port, start_serving=False, max_size=None, logger=self.ws_logger) + self.server = await serve( + self.manage_conection, + self.host, + self.port, + start_serving=False, + max_size=None, + logger=self.ws_logger, + ) return self async def manage_conection(self, websocket): if self.client is not None: - self.ws_logger.info("Client is already connected") - await websocket.close() - return + self.ws_logger.info("Client is already connected") + await websocket.close() + return try: - self.client = websocket # Register client + self.client = websocket # Register client self.ws_logger.info(f"Client connected: {self.client}") - + await self.process_msg(self.client) except Exception as e: pass @@ -83,14 +91,14 @@ async def manage_conection(self, websocket): self.client = None async def process_msg(self, websocket): - async for raw_msg in websocket: - try: - json_msg = json.loads(raw_msg) - await self.process_callback(ManagerConsumerMessage(**json_msg)) - except Exception as e: - ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) - await self.send_message(ex) - self.ws_logger.error(e, exc_info=True) + async for raw_msg in websocket: + try: + json_msg = json.loads(raw_msg) + await self.process_callback(ManagerConsumerMessage(**json_msg)) + except Exception as e: + ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) + await self.send_message(ex) + self.ws_logger.error(e, exc_info=True) async def send_message(self, message_data, command=None): """ diff --git a/robotics_application_manager/comms/thread.py b/robotics_application_manager/comms/thread.py index 33a2d54..1232872 100644 --- a/robotics_application_manager/comms/thread.py +++ b/robotics_application_manager/comms/thread.py @@ -36,4 +36,3 @@ def run(self): ) finally: del self._target, self._args, self._kwargs - diff --git a/robotics_application_manager/libs/process_utils.py b/robotics_application_manager/libs/process_utils.py index 49da0a3..46a2b07 100644 --- a/robotics_application_manager/libs/process_utils.py +++ b/robotics_application_manager/libs/process_utils.py @@ -18,7 +18,7 @@ def get_class(kls): parts = kls.split(".") module = ".".join(parts[:-1]) m = importlib.import_module(module) - imp_class = getattr(m,parts[-1]) + imp_class = getattr(m, parts[-1]) return imp_class diff --git a/robotics_application_manager/libs/server.py b/robotics_application_manager/libs/server.py index 913249f..2968daf 100644 --- a/robotics_application_manager/libs/server.py +++ b/robotics_application_manager/libs/server.py @@ -10,6 +10,7 @@ ManagerConsumerMessageException, ) + class Server: def __init__( self, @@ -31,37 +32,44 @@ def __await__(self): # A method that creates an instance of the class asynchronously async def create(self): - self.server = await serve(self.manage_conection, self.host, self.port, start_serving=False,ping_interval=None, ping_timeout=None) + self.server = await serve( + self.manage_conection, + self.host, + self.port, + start_serving=False, + ping_interval=None, + ping_timeout=None, + ) return self async def manage_conection(self, websocket): with self.client_lock: - if self.client is not None: - await websocket.close() - return + if self.client is not None: + await websocket.close() + return try: with self.client_lock: - self.client = websocket # Register client + self.client = websocket # Register client LogManager.logger.info(f"Client connected: {self.client}") await self.process_msg(websocket) except Exception as e: - LogManager.logger.info(f"Client disconnected: {str(e)}") + LogManager.logger.info(f"Client disconnected: {str(e)}") finally: LogManager.logger.info("Connection with client closed") with self.client_lock: - self.client = None + self.client = None async def process_msg(self, websocket): - async for raw_msg in websocket: - try: - json_msg = json.loads(raw_msg) - await self.update_callback(json_msg) - except Exception as e: - ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) - await self.send(ex.consumer_message()) - LogManager.logger.error(e, exc_info=True) + async for raw_msg in websocket: + try: + json_msg = json.loads(raw_msg) + await self.update_callback(json_msg) + except Exception as e: + ex = ManagerConsumerMessageException(id=str(uuid4()), message=str(e)) + await self.send(ex.consumer_message()) + LogManager.logger.error(e, exc_info=True) async def send(self, data): with self.client_lock: diff --git a/robotics_application_manager/manager/docker_thread/docker_thread.py b/robotics_application_manager/manager/docker_thread/docker_thread.py index 974c5de..4a3fec5 100644 --- a/robotics_application_manager/manager/docker_thread/docker_thread.py +++ b/robotics_application_manager/manager/docker_thread/docker_thread.py @@ -20,27 +20,27 @@ def __init__(self, cmd, shell=True, debug=False): def run(self): if self.debug: - self.process = subprocess.Popen( - self.cmd, - shell=self.shell, - stdout=sys.stdout, - stderr=sys.stdout, - start_new_session=True, - bufsize=1024, - universal_newlines=True, - executable="/bin/bash", - ) + self.process = subprocess.Popen( + self.cmd, + shell=self.shell, + stdout=sys.stdout, + stderr=sys.stdout, + start_new_session=True, + bufsize=1024, + universal_newlines=True, + executable="/bin/bash", + ) else: - self.process = subprocess.Popen( - self.cmd, - shell=self.shell, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - start_new_session=True, - bufsize=1024, - universal_newlines=True, - executable="/bin/bash", - ) + self.process = subprocess.Popen( + self.cmd, + shell=self.shell, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + start_new_session=True, + bufsize=1024, + universal_newlines=True, + executable="/bin/bash", + ) self.process_group = os.getpgid(self.process.pid) self.process.communicate() @@ -50,4 +50,6 @@ def terminate(self): try: os.killpg(self.process_group, signal.SIGTERM) except ProcessLookupError as error: - print(f"{self.process_group}/{self.process.pid}: Process {self.cmd} already terminated {error}") + print( + f"{self.process_group}/{self.process.pid}: Process {self.cmd} already terminated {error}" + ) diff --git a/robotics_application_manager/manager/launcher/launcher_robot.py b/robotics_application_manager/manager/launcher/launcher_robot.py index cd0b93d..5995e37 100644 --- a/robotics_application_manager/manager/launcher/launcher_robot.py +++ b/robotics_application_manager/manager/launcher/launcher_robot.py @@ -88,7 +88,9 @@ def process_terminated(name, exit_code): launcher_class = get_class(launcher_module) launcher = await launcher_class.from_config(launcher_class, configuration) - await launcher.run(self.entity, self.start_pose, extra_config, process_terminated) + await launcher.run( + self.entity, self.start_pose, extra_config, process_terminated + ) return launcher def launch_command(self, configuration): diff --git a/robotics_application_manager/manager/launcher/launcher_scene.py b/robotics_application_manager/manager/launcher/launcher_scene.py index 81bfe68..04f54e3 100644 --- a/robotics_application_manager/manager/launcher/launcher_scene.py +++ b/robotics_application_manager/manager/launcher/launcher_scene.py @@ -57,7 +57,7 @@ class LauncherScene(BaseModel): async def run(self): if self.type is None or self.type == str(None): - return + return for module in worlds[self.type][str(self.ros_version)]: module["launch_file"] = self.launch_file_path launcher = await self.launch_module(module) diff --git a/robotics_application_manager/manager/manager.py b/robotics_application_manager/manager/manager.py index ab8d7a4..2ebda7c 100644 --- a/robotics_application_manager/manager/manager.py +++ b/robotics_application_manager/manager/manager.py @@ -201,7 +201,9 @@ async def state_change(self, event): """ LogManager.logger.info(f"State changed to {self.state}") if self.consumer is not None: - await self.consumer.send_message({"state": self.state}, command="state-changed") + await self.consumer.send_message( + {"state": self.state}, command="state-changed" + ) async def update(self, data): """ @@ -239,7 +241,9 @@ async def on_connect(self, event): - `ros_version`: The current ROS (Robot Operating System) distribution version. - `gpu_avaliable`: Boolean indicating whether GPU acceleration is available. """ - LogManager.logger.info("-------------------Connecting--------------------------") + LogManager.logger.info( + "-------------------Connecting--------------------------" + ) await self.consumer.send_message( { "robotics_backend_version": subprocess.check_output( @@ -605,7 +609,9 @@ async def on_disconnect(self, event): This method stops all running processes, terminates launchers, and restarts the script. """ - LogManager.logger.info("-------------------Disconnecting--------------------------") + LogManager.logger.info( + "-------------------Disconnecting--------------------------" + ) try: for process in self.application_processes: stop_process_and_children(process) @@ -732,10 +738,10 @@ async def start(self): RAM must be run in main thread to be able to handle signaling other processes, for instance ROS launcher. """ - self.consumer = await ManagerConsumer(self.host, self.port, self.process_message) - LogManager.logger.info( - f"Starting RAM consumer in {self.host}:{self.port}" + self.consumer = await ManagerConsumer( + self.host, self.port, self.process_message ) + LogManager.logger.info(f"Starting RAM consumer in {self.host}:{self.port}") await self.consumer.start() diff --git a/robotics_application_services/main.py b/robotics_application_services/main.py index 106095c..659fa48 100644 --- a/robotics_application_services/main.py +++ b/robotics_application_services/main.py @@ -6,6 +6,7 @@ from routers import format + @asynccontextmanager async def lifespan(app: FastAPI): # On launch diff --git a/robotics_application_services/routers/format.py b/robotics_application_services/routers/format.py index 920d5a4..6afd318 100644 --- a/robotics_application_services/routers/format.py +++ b/robotics_application_services/routers/format.py @@ -11,9 +11,11 @@ responses={404: {"description": "Not found"}}, ) + class FileItem(BaseModel): content: str + @router.post("/black", response_model=FileItem) async def format(item: FileItem): """ @@ -42,6 +44,7 @@ async def format(item: FileItem): except Exception as e: raise HTTPException(status_code=404, detail="Error formating code" + str(e)) + @router.post("/clang", response_model=FileItem) async def clang(item: FileItem): """ @@ -113,4 +116,4 @@ async def clang(item: FileItem): # errors = "No errors found" # self.write_to_tool_terminal(errors + "\n\n") -# raise Exception(errors) \ No newline at end of file +# raise Exception(errors)