Skip to content

Commit

Permalink
add rviz command
Browse files Browse the repository at this point in the history
  • Loading branch information
PonomarevDA committed Nov 23, 2024
1 parent 24e8d2b commit 208d656
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 12 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.vscode/
logs_and_video/
rviz/
*.pyc
downloads*
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,12 @@ With RVIZ you can visualise the vehicle orientation, vectors of the applied forc

<img src="https://github.com/ZilantRobotics/innopolis_vtol_dynamics/wiki/assets/welcome/use_case_2_rviz.gif" alt="drawing" width="800"/>

How to run:

```bash
./scripts/sim.py rviz vtol_T_300
```

**Tool 3. 3D-simulator**

> 3D-simulator demo is in process...
Expand Down
26 changes: 24 additions & 2 deletions scripts/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,30 @@
import yaml
from mode import SimMode

REPO_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
VEHICLES_DIR = os.path.join(REPO_DIR, "configs", "vehicles")

@dataclass
class SimCommand:
name: str
alias: Optional[str]
mode: SimMode
info: Optional[str]
sim_config: Optional[str] = None
args: Optional[list] = None

def check(self, command: str) -> bool:
if isinstance(command, str):
name = command
elif isinstance(command, list):
name = command[0]
else:
raise ValueError("The 'name' argument must be a string or a list of strings.")

def check(self, name: str) -> bool:
return name in [self.name, self.alias]
res = name in [self.name, self.alias]
if res:
self.args = command[1:]
return res

@staticmethod
def create_from_yaml_file(file_path: str):
Expand Down Expand Up @@ -43,3 +57,11 @@ def create_list_from_directory(dir_with_yaml_files) -> list:
if cmd is not None:
commands.append(cmd)
return commands

COMMANDS = [
SimCommand(name="build", alias='b', mode=None, info="Build the Docker image"),
SimCommand(name="kill", alias='', mode=None, info="Kill the running Docker container"),
SimCommand(name="monitor", alias='', mode=None, info="Just monitor"),
SimCommand(name="rviz", alias='', mode=None, info="Run RVIZ"),
*SimCommand.create_list_from_directory(dir_with_yaml_files=VEHICLES_DIR)
]
48 changes: 38 additions & 10 deletions scripts/sim.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@
import time
import logging
import datetime
import subprocess
from typing import Optional
from pathlib import Path
from argparse import ArgumentParser, RawTextHelpFormatter
from autopilot_tools.configurator import AutopilotConfigurator

from command import SimCommand
from command import SimCommand, COMMANDS
from docker_wrapper import DockerWrapper
from model import SimModel

Expand All @@ -35,28 +36,24 @@
LOG_PATH = os.path.join(LOGS_DIR, LOG_FILENAME)
ISSUES_URL = "https://github.com/ZilantRobotics/innopolis_vtol_dynamics/issues"

COMMANDS = [
SimCommand(name="build", alias='b', mode=None, info="Build the Docker image"),
SimCommand(name="kill", alias='', mode=None, info="Kill the running Docker container"),
SimCommand(name="monitor", alias='', mode=None, info="Just monitor"),
*SimCommand.create_list_from_directory(dir_with_yaml_files=VEHICLES_DIR)
]

logger = logging.getLogger(__name__)

class SimCommander:
def __init__(self, model: SimModel) -> None:
assert isinstance(model, SimModel)
self._model = model
self.command = None

def __del__(self):
self._kill()
if self.command.name not in ['rviz']:
self._kill()

def execute(self,
command: SimCommand,
need_upload_firmware: bool,
need_load_parameters: bool) -> None:
assert isinstance(command, SimCommand)
self.command = command

if command.name == "kill":
self._kill()
Expand All @@ -66,6 +63,10 @@ def execute(self,
self._build()
sys.exit(0)

if command.name == "rviz":
SimCommander._rviz(command.args)
sys.exit(0)

if need_upload_firmware or need_load_parameters:
config_path = f"{VEHICLES_DIR}/{command.name}.yaml"
AutopilotConfigurator.configure_with_yaml_file(config_path,
Expand Down Expand Up @@ -102,6 +103,33 @@ def _kill(self) -> None:
def _build(self) -> None:
DockerWrapper.build(self._model.full_image_name)

@staticmethod
def _rviz(args: list) -> None:
rviz_dir = "rviz"
repo_url = "[email protected]:PonomarevDA/rviz_docker.git"
if not os.path.exists(rviz_dir) or not os.listdir(rviz_dir):
logger.info("Cloning repository from %s into %s...", repo_url, rviz_dir)
try:
subprocess.run(["git", "clone", repo_url, rviz_dir], check=True)
except subprocess.CalledProcessError:
logger.critical("Failed to clone repository from %s. Exiting.", repo_url)
sys.exit(1)
if not os.path.exists(rviz_dir):
logger.critical("The directory 'rviz' does not exist after cloning. Exiting.")
sys.exit(1)

scripts = ['build.sh', 'run.sh']
for script in scripts:
script_path = os.path.join(rviz_dir, script)
if not os.path.isfile(script_path):
print(f"Error: {script_path} not found. Exiting.")
sys.exit(1)
try:
subprocess.run(["bash", script_path, *args], check=True)
except subprocess.CalledProcessError:
logger.critical("Script %s failed. Exiting.", script)
sys.exit(1)

class SimView:
def __init__(self, model: SimModel) -> None:
assert isinstance(model, SimModel)
Expand Down Expand Up @@ -148,7 +176,7 @@ def main():

command_help = f'{"Command":<36} {"Alias":<10} {"Info"}\n'
command_help += '\n'.join([f"{cmd.name:<36} {cmd.alias:<10} {cmd.info}" for cmd in COMMANDS])
parser.add_argument('command', help=command_help)
parser.add_argument('command', help=command_help, nargs='+')

upload_help = "upload the required firmware"
parser.add_argument("--upload", help=upload_help, default=False, action='store_true')
Expand Down

0 comments on commit 208d656

Please sign in to comment.