-
Notifications
You must be signed in to change notification settings - Fork 131
Allow user to pass custom options to SITL autopilot executable #3933
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Shono1
wants to merge
7
commits into
bluerobotics:master
Choose a base branch
from
wpi-automata:sitl-options-pr
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+134
−18
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1ccf2cd
core: Added api endpoints for storing autopilot execution arguments t…
Shono1 2ebb4bd
core: Added endpoint for getting arguments to be passed to autopilot …
Shono1 6ee2805
core: User can specify custom arguments in ardupilot settings JSON file
Shono1 d4b15a6
Apply suggestion from @sourcery-ai[bot]
Shono1 27503b7
Implemented sourcery feedback to sanitize user input to endpoint argu…
Shono1 fa4bd88
Merge branch 'sitl-options-pr' of github.com:wpi-automata/BlueOS into…
Shono1 8acb612
Condense else-if to elif and correct comment
Shono1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| import asyncio | ||
| import json | ||
| import os | ||
| import pathlib | ||
| import subprocess | ||
|
|
@@ -24,6 +25,7 @@ | |
| from mavlink_proxy.Manager import Manager as MavlinkManager | ||
| from settings import Settings | ||
| from typedefs import ( | ||
| EndpointDefinition, | ||
| Firmware, | ||
| FlightController, | ||
| FlightControllerFlags, | ||
|
|
@@ -438,6 +440,7 @@ async def start_manual_board(self, board: FlightController) -> None: | |
| self.ardupilot_subprocess = None | ||
| await self.start_mavlink_manager(self.master_endpoint) | ||
|
|
||
| # pylint: disable=too-many-locals | ||
| async def start_sitl(self) -> None: | ||
| self._current_board = BoardDetector.detect_sitl() | ||
| if not self.firmware_manager.is_firmware_installed(self._current_board): | ||
|
|
@@ -451,26 +454,52 @@ async def start_sitl(self) -> None: | |
| firmware_path = self.firmware_manager.firmware_path(self._current_board.platform) | ||
| self.firmware_manager.validate_firmware(firmware_path, self._current_board.platform) | ||
|
|
||
| # ArduPilot SITL binary will bind TCP port 5760 (server) and the mavlink router will connect to it as a client | ||
| master_endpoint = Endpoint( | ||
| name="Master", | ||
| owner=self.settings.app_name, | ||
| connection_type=EndpointType.TCPClient, | ||
| place="127.0.0.1", | ||
| argument=5760, | ||
| protected=True, | ||
| ) | ||
| if "exec_arguments" not in self.configuration or str(firmware_path) not in self.configuration["exec_arguments"]: | ||
| with open(pathlib.Path(__file__).parent.resolve() / "default_arguments.json", "r", encoding="utf-8") as f: | ||
| default_config = json.load(f) | ||
| logger.warning(f"Setting defaults parameters for SITL to {default_config}") | ||
| self.set_exec_arguments(str(firmware_path), "SITL", default_config["SITL"]) | ||
| # Refresh configuration, as user may have changed settings since restart | ||
| self.settings.load() | ||
| self.configuration = deepcopy(self.settings.content) | ||
| arguments = self.configuration["exec_arguments"][str(firmware_path)]["SITL"] | ||
|
|
||
| # ArduPilot SITL binary will bind TCP port specified by user (or default to port 5760) and the mavlink router will connect to it as a client | ||
| default_endpoint_args = EndpointDefinition() | ||
|
|
||
| endpoint_config = arguments.get("endpoint") | ||
| if endpoint_config is None: | ||
| logger.warning("Using default endpoint for SITL because none was provided in settings.json.") | ||
| master_endpoint_args = default_endpoint_args | ||
| elif not isinstance(endpoint_config, dict): | ||
| logger.warning( | ||
| "Invalid endpoint configuration type '%s'; falling back to default endpoint for SITL.", | ||
| type(endpoint_config).__name__, | ||
| ) | ||
| master_endpoint_args = default_endpoint_args | ||
| else: | ||
| # Start with defaults, override only known fields, ignore unknown keys | ||
| arg_dict = EndpointDefinition().dict() | ||
| for key, value in endpoint_config.items(): | ||
| if key in default_endpoint_args: | ||
| arg_dict[key] = self._sanitize_endpoint_argument(key, value) | ||
| else: | ||
| logger.debug("Ignoring unknown endpoint field '%s' in settings.json.", key) | ||
| master_endpoint_args = EndpointDefinition(**arg_dict) | ||
|
|
||
| master_endpoint = Endpoint(**master_endpoint_args.dict()) | ||
|
Comment on lines
+470
to
+490
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this could be a function |
||
|
|
||
| arg_list = [str(firmware_path)] | ||
| for k, v in arguments.items(): | ||
| if k == "endpoint": | ||
| continue | ||
| arg_list.append(str(k)) | ||
| if v != "": | ||
| arg_list.append(str(v)) | ||
|
Comment on lines
+492
to
+498
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. here we could also use a function |
||
|
|
||
| # pylint: disable=consider-using-with | ||
| self.ardupilot_subprocess = subprocess.Popen( | ||
| [ | ||
| firmware_path, | ||
| "--model", | ||
| self.current_sitl_frame.value, | ||
| "--base-port", | ||
| str(master_endpoint.argument), | ||
| "--home", | ||
| "-27.563,-48.459,0.0,270.0", | ||
| ], | ||
| arg_list, | ||
| shell=False, | ||
| encoding="utf-8", | ||
| errors="ignore", | ||
|
|
@@ -479,6 +508,17 @@ async def start_sitl(self) -> None: | |
|
|
||
| await self.start_mavlink_manager(master_endpoint) | ||
|
|
||
| def _sanitize_endpoint_argument(self, key: str, value: str) -> int | bool | str: | ||
| if key == "argument": | ||
| return int(value) | ||
| if key == "protected": | ||
| if value == "True": | ||
| return True | ||
| if value == "False": | ||
| return False | ||
| raise ValueError("Invalid value for 'protected' argument of endpoint") | ||
| return value | ||
|
|
||
| async def start_mavlink_manager(self, device: Endpoint) -> None: | ||
| for endpoint in self.autopilot_default_endpoints: | ||
| try: | ||
|
|
@@ -518,6 +558,31 @@ def get_preferred_board(self) -> FlightController: | |
| raise NoPreferredBoardSet("Preferred board not set yet.") | ||
| return FlightController(**preferred_board) | ||
|
|
||
| def set_exec_arguments(self, firmware_name: str, board: str, settings: dict[str, str]) -> None: | ||
| self.settings.load() | ||
| self.configuration = deepcopy(self.settings.content) | ||
| try: | ||
| if "exec_arguments" not in self.configuration: | ||
| self.configuration["exec_arguments"] = {} | ||
| if firmware_name not in self.configuration["exec_arguments"]: | ||
| self.configuration["exec_arguments"][firmware_name] = {} | ||
| self.configuration["exec_arguments"][firmware_name][board] = settings | ||
| self.settings.save(self.configuration) | ||
| logger.info("Execution arguments set.") | ||
| except Exception as e: | ||
| logger.error("Error while saving execution arguments") | ||
| logger.error(repr(e)) | ||
|
|
||
| def get_exec_arguments(self, firmware_name: str, board: str) -> Any: | ||
| self.settings.load() | ||
| self.configuration = deepcopy(self.settings.content) | ||
| try: | ||
| return self.configuration["exec_arguments"][firmware_name][board] | ||
| except Exception as e: | ||
| logger.error("Error while getting execution arguments") | ||
| logger.error(repr(e)) | ||
| return None | ||
|
|
||
| def get_board_to_be_used(self, boards: List[FlightController]) -> FlightController: | ||
| """Check if preferred board exists and is connected. If so, use it, otherwise, choose by priority.""" | ||
| try: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| { | ||
| "SITL" : { | ||
| "endpoint" : { | ||
| "name" : "Master", | ||
| "owner" : "Ardupilot Manager", | ||
| "connection_type" : "tcpout", | ||
| "place" : "127.0.0.1", | ||
| "argument" : "5760", | ||
| "protected" : "True" | ||
| }, | ||
| "--model" : "vectored", | ||
| "--home" : "-27.563,-48.459,0.0,270.0" | ||
| }, | ||
| "Linux" : { | ||
| "endpoint" : { | ||
| "name" : "Master", | ||
| "owner" : "Ardupilot Manager", | ||
| "connection_type" : "udpin", | ||
| "place" : "127.0.0.1", | ||
| "argument" : "8852", | ||
| "protected" : "True" | ||
| }, | ||
| "use_defaults" : "True" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.