From 891762f79c1ac29aabb028e7850e9b7f4b903a23 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:06:52 +0100 Subject: [PATCH 01/24] Fix standard flake8 errors for `tools - F401 'ament_index_python.packages.get_package_share_directory' imported but unused --- tools/planner_benchmarking/metrics.py | 1 - tools/planner_benchmarking/process_data.py | 1 - 2 files changed, 2 deletions(-) diff --git a/tools/planner_benchmarking/metrics.py b/tools/planner_benchmarking/metrics.py index 8aecfbeaf61..deeadd4ed41 100644 --- a/tools/planner_benchmarking/metrics.py +++ b/tools/planner_benchmarking/metrics.py @@ -16,7 +16,6 @@ from geometry_msgs.msg import PoseStamped from nav2_simple_commander.robot_navigator import BasicNavigator import rclpy -from ament_index_python.packages import get_package_share_directory import math import os diff --git a/tools/planner_benchmarking/process_data.py b/tools/planner_benchmarking/process_data.py index eae02f3adf6..608e0dd730e 100644 --- a/tools/planner_benchmarking/process_data.py +++ b/tools/planner_benchmarking/process_data.py @@ -17,7 +17,6 @@ import math import os -from ament_index_python.packages import get_package_share_directory import pickle import seaborn as sns From c295f72dc5d64f3723325b3cef429639a65ac349 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:09:51 +0100 Subject: [PATCH 02/24] Fix flake8 tests for nav2_common - nav2_common/nav2_common/launch/__init__.py:15:1: F401 '.has_node_params.HasNodeParams' imported but unused - nav2_common/nav2_common/launch/__init__.py:16:1: F401 '.rewritten_yaml.RewrittenYaml' imported but unused - nav2_common/nav2_common/launch/__init__.py:17:1: F401 '.replace_string.ReplaceString' imported but unused - nav2_common/nav2_common/launch/__init__.py:18:1: F401 '.parse_multirobot_pose.ParseMultiRobotPose' imported but unused --- nav2_common/nav2_common/launch/__init__.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/nav2_common/nav2_common/launch/__init__.py b/nav2_common/nav2_common/launch/__init__.py index 7eba78e1928..d079ccd23b5 100644 --- a/nav2_common/nav2_common/launch/__init__.py +++ b/nav2_common/nav2_common/launch/__init__.py @@ -13,6 +13,13 @@ # limitations under the License. from .has_node_params import HasNodeParams -from .rewritten_yaml import RewrittenYaml -from .replace_string import ReplaceString from .parse_multirobot_pose import ParseMultiRobotPose +from .replace_string import ReplaceString +from .rewritten_yaml import RewrittenYaml + +__all__ = [ + "HasNodeParams", + "RewrittenYaml", + "ReplaceString", + "ParseMultiRobotPose", +] From 5c60e2cd7da42ea07dda82c0e8e4e8a4f3cb3ab0 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:11:04 +0100 Subject: [PATCH 03/24] Fix flake8 nav2_common linterr - nav2_common/nav2_common/launch/replace_string.py:97:100: E501 line too long (108 > 99 characters) --- nav2_common/nav2_common/launch/replace_string.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/nav2_common/nav2_common/launch/replace_string.py b/nav2_common/nav2_common/launch/replace_string.py index 9d0fe43f2b1..ed05cad81ef 100644 --- a/nav2_common/nav2_common/launch/replace_string.py +++ b/nav2_common/nav2_common/launch/replace_string.py @@ -94,6 +94,7 @@ def replace(self, input_file, output_file, replacements): line = line.replace(key, value) else: raise TypeError( - "A provided replacement pair is not a string. Both key and value should be strings." + "A provided replacement pair is not a string. Both key and value should be" + "strings." ) output_file.write(line) From 1c8e02daf3d185493288c7e3a3c03cf60928bba4 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:11:31 +0100 Subject: [PATCH 04/24] Fix flake8 nav2_common linter - nav2_common/nav2_common/launch/rewritten_yaml.py:142:16: E713 test for membership should be 'not in' --- nav2_common/nav2_common/launch/rewritten_yaml.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nav2_common/nav2_common/launch/rewritten_yaml.py b/nav2_common/nav2_common/launch/rewritten_yaml.py index c3956023feb..e95c7df0cf4 100644 --- a/nav2_common/nav2_common/launch/rewritten_yaml.py +++ b/nav2_common/nav2_common/launch/rewritten_yaml.py @@ -139,7 +139,7 @@ def add_params(self, yaml, param_rewrites): # add new total path parameters yaml_paths = self.pathify(yaml) for path in param_rewrites: - if not path in yaml_paths: + if yaml_paths not in path: new_val = self.convert(param_rewrites[path]) yaml_keys = path.split(".") if "ros__parameters" in yaml_keys: From 6d601f5285c1ce2df8bc0631e2bf9d8401501abb Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:12:09 +0100 Subject: [PATCH 05/24] Fix flake8 nav_common linter - nav2_common/nav2_common/launch/has_node_params.py:21:1: F401 'sys' imported but unused --- nav2_common/nav2_common/launch/has_node_params.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/nav2_common/nav2_common/launch/has_node_params.py b/nav2_common/nav2_common/launch/has_node_params.py index e7751ad2e97..863f1e116f5 100644 --- a/nav2_common/nav2_common/launch/has_node_params.py +++ b/nav2_common/nav2_common/launch/has_node_params.py @@ -18,8 +18,6 @@ import yaml import launch -import sys # delete this - class HasNodeParams(launch.Substitution): """ From 4eeb19af7168fe639f14861f058f209447eccd0f Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:13:41 +0100 Subject: [PATCH 06/24] Fix nav2_system_tests flake8 linter This came after using black as formatter. So respecting the previous code --- nav2_system_tests/src/system/test_multi_robot_launch.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nav2_system_tests/src/system/test_multi_robot_launch.py b/nav2_system_tests/src/system/test_multi_robot_launch.py index 243c9cbdd94..dfbb8dbd301 100755 --- a/nav2_system_tests/src/system/test_multi_robot_launch.py +++ b/nav2_system_tests/src/system/test_multi_robot_launch.py @@ -46,11 +46,11 @@ def generate_launch_description(): ) bringup_dir = get_package_share_directory("nav2_bringup") - robot1_params_file = os.path.join( - bringup_dir, "params/nav2_multirobot_params_1.yaml" # noqa: F841 + robot1_params_file = os.path.join( # noqa: F841 + bringup_dir, "params/nav2_multirobot_params_1.yaml" ) - robot2_params_file = os.path.join( - bringup_dir, "params/nav2_multirobot_params_2.yaml" # noqa: F841 + robot2_params_file = os.path.join( # noqa: F841 + bringup_dir, "params/nav2_multirobot_params_2.yaml" ) # Names and poses of the robots From 58b5cb2a00c362c944150a80819934fc46208326 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:15:58 +0100 Subject: [PATCH 07/24] Fix flake8-builtins linter --- tools/bt2img.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tools/bt2img.py b/tools/bt2img.py index 3fc1dbf4e32..c4043f4f4ee 100755 --- a/tools/bt2img.py +++ b/tools/bt2img.py @@ -198,16 +198,16 @@ def make_label(node): return label -def node_color(type): - if type in control_nodes: +def node_color(node_type): + if node_type in control_nodes: return "chartreuse4" - if type in action_nodes: + if node_type in action_nodes: return "cornflowerblue" - if type in condition_nodes: + if node_type in condition_nodes: return "yellow2" - if type in decorator_nodes: + if node_type in decorator_nodes: return "darkorange1" - if type in subtree_nodes: + if node_type in subtree_nodes: return "darkorchid1" # else it's unknown return "grey" From bebf54dca2157a9f82dff8056ff7108e7239efc2 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:17:28 +0100 Subject: [PATCH 08/24] Fix flake8-comprehensions linter --- nav2_common/nav2_common/launch/parse_multirobot_pose.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nav2_common/nav2_common/launch/parse_multirobot_pose.py b/nav2_common/nav2_common/launch/parse_multirobot_pose.py index fa36c0df82c..4867d52ae39 100644 --- a/nav2_common/nav2_common/launch/parse_multirobot_pose.py +++ b/nav2_common/nav2_common/launch/parse_multirobot_pose.py @@ -57,8 +57,8 @@ def value(self) -> Dict: get value of target argument """ args = self.__args - parsed_args = list() if len(args) == 0 else args.split(";") - multirobots = dict() + parsed_args = [] if len(args) == 0 else args.split(";") + multirobots = {} for arg in parsed_args: key_val = arg.strip().split("=") if len(key_val) != 2: From 62f2292ec68fa152418a0842b511f0b5a5b88f5b Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:24:52 +0100 Subject: [PATCH 09/24] Fix flake8-import-order linter for nav2_sumple_commander --- nav2_simple_commander/nav2_simple_commander/robot_navigator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nav2_simple_commander/nav2_simple_commander/robot_navigator.py b/nav2_simple_commander/nav2_simple_commander/robot_navigator.py index 6ea417f7b26..61956f7d563 100644 --- a/nav2_simple_commander/nav2_simple_commander/robot_navigator.py +++ b/nav2_simple_commander/nav2_simple_commander/robot_navigator.py @@ -26,9 +26,9 @@ from nav2_msgs.action import AssistedTeleop, BackUp, Spin from nav2_msgs.action import ComputePathThroughPoses, ComputePathToPose from nav2_msgs.action import ( + FollowGPSWaypoints, FollowPath, FollowWaypoints, - FollowGPSWaypoints, NavigateThroughPoses, NavigateToPose, ) From 10c78196af71f22b6a060fe371101cdbd5426704 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:25:10 +0100 Subject: [PATCH 10/24] Fix flake8-import-order linter for nav2_system_tests --- .../src/gps_navigation/dual_ekf_navsat.launch.py | 5 +++-- nav2_system_tests/src/gps_navigation/tester.py | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/nav2_system_tests/src/gps_navigation/dual_ekf_navsat.launch.py b/nav2_system_tests/src/gps_navigation/dual_ekf_navsat.launch.py index 852436615b4..6b0dd5c2b0b 100644 --- a/nav2_system_tests/src/gps_navigation/dual_ekf_navsat.launch.py +++ b/nav2_system_tests/src/gps_navigation/dual_ekf_navsat.launch.py @@ -11,10 +11,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -from launch import LaunchDescription -import launch_ros.actions import os + +from launch import LaunchDescription import launch.actions +import launch_ros.actions def generate_launch_description(): diff --git a/nav2_system_tests/src/gps_navigation/tester.py b/nav2_system_tests/src/gps_navigation/tester.py index 92051fe277e..526ed83b64b 100755 --- a/nav2_system_tests/src/gps_navigation/tester.py +++ b/nav2_system_tests/src/gps_navigation/tester.py @@ -21,11 +21,12 @@ from nav2_msgs.action import ComputePathToPose, FollowGPSWaypoints from nav2_msgs.srv import ManageLifecycleNodes from rcl_interfaces.srv import SetParameters -from rclpy.parameter import Parameter import rclpy + from rclpy.action import ActionClient from rclpy.node import Node +from rclpy.parameter import Parameter class GpsWaypointFollowerTest(Node): From 21a995db8fae74189ae311ec5f5ee3b2eaf31519 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:26:31 +0100 Subject: [PATCH 11/24] Fix flake8-import-order linter for nav2_common --- nav2_common/nav2_common/launch/has_node_params.py | 2 +- nav2_common/nav2_common/launch/parse_multirobot_pose.py | 5 +++-- nav2_common/nav2_common/launch/replace_string.py | 6 ++---- nav2_common/nav2_common/launch/rewritten_yaml.py | 9 +++------ 4 files changed, 9 insertions(+), 13 deletions(-) diff --git a/nav2_common/nav2_common/launch/has_node_params.py b/nav2_common/nav2_common/launch/has_node_params.py index 863f1e116f5..652f07a70fa 100644 --- a/nav2_common/nav2_common/launch/has_node_params.py +++ b/nav2_common/nav2_common/launch/has_node_params.py @@ -15,8 +15,8 @@ from typing import List from typing import Text -import yaml import launch +import yaml class HasNodeParams(launch.Substitution): diff --git a/nav2_common/nav2_common/launch/parse_multirobot_pose.py b/nav2_common/nav2_common/launch/parse_multirobot_pose.py index 4867d52ae39..65ed4a6e186 100644 --- a/nav2_common/nav2_common/launch/parse_multirobot_pose.py +++ b/nav2_common/nav2_common/launch/parse_multirobot_pose.py @@ -12,9 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -import yaml import sys -from typing import Text, Dict +from typing import Dict, Text + +import yaml class ParseMultiRobotPose: diff --git a/nav2_common/nav2_common/launch/replace_string.py b/nav2_common/nav2_common/launch/replace_string.py index ed05cad81ef..a2351587f02 100644 --- a/nav2_common/nav2_common/launch/replace_string.py +++ b/nav2_common/nav2_common/launch/replace_string.py @@ -12,11 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Dict -from typing import List -from typing import Text -from typing import Optional import tempfile +from typing import Dict, List, Optional, Text + import launch diff --git a/nav2_common/nav2_common/launch/rewritten_yaml.py b/nav2_common/nav2_common/launch/rewritten_yaml.py index e95c7df0cf4..49f9f2fb650 100644 --- a/nav2_common/nav2_common/launch/rewritten_yaml.py +++ b/nav2_common/nav2_common/launch/rewritten_yaml.py @@ -12,14 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Dict -from typing import List -from typing import Text -from typing import Optional - -import yaml import tempfile +from typing import Dict, List, Optional, Text + import launch +import yaml class DictItemReference: From 033f80f925a953c686608116acf7e9e693719a2d Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:34:53 +0100 Subject: [PATCH 12/24] Fix flake8-import-order linter for tools --- tools/bt2img.py | 1 + tools/planner_benchmarking/metrics.py | 16 ++++++---------- .../planning_benchmark_bringup.py | 2 +- tools/planner_benchmarking/process_data.py | 5 ++--- tools/smoother_benchmarking/metrics.py | 14 +++++--------- tools/smoother_benchmarking/process_data.py | 5 ++--- .../smoother_benchmark_bringup.py | 2 +- 7 files changed, 18 insertions(+), 27 deletions(-) diff --git a/tools/bt2img.py b/tools/bt2img.py index c4043f4f4ee..b649ab8580c 100755 --- a/tools/bt2img.py +++ b/tools/bt2img.py @@ -18,6 +18,7 @@ import argparse import xml.etree.ElementTree + import graphviz # pip3 install graphviz control_nodes = [ diff --git a/tools/planner_benchmarking/metrics.py b/tools/planner_benchmarking/metrics.py index deeadd4ed41..56f52e8decc 100644 --- a/tools/planner_benchmarking/metrics.py +++ b/tools/planner_benchmarking/metrics.py @@ -13,21 +13,17 @@ # See the License for the specific language governing permissions and # limitations under the License. -from geometry_msgs.msg import PoseStamped -from nav2_simple_commander.robot_navigator import BasicNavigator -import rclpy - +import glob import math import os import pickle -import glob +from random import randint, seed, uniform import time -import numpy as np - -from random import seed -from random import randint -from random import uniform +from geometry_msgs.msg import PoseStamped +from nav2_simple_commander.robot_navigator import BasicNavigator +import numpy as np +import rclpy from transforms3d.euler import euler2quat diff --git a/tools/planner_benchmarking/planning_benchmark_bringup.py b/tools/planner_benchmarking/planning_benchmark_bringup.py index e880492176e..36362466114 100644 --- a/tools/planner_benchmarking/planning_benchmark_bringup.py +++ b/tools/planner_benchmarking/planning_benchmark_bringup.py @@ -14,11 +14,11 @@ import os +from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import IncludeLaunchDescription from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.actions import Node -from ament_index_python.packages import get_package_share_directory def generate_launch_description(): diff --git a/tools/planner_benchmarking/process_data.py b/tools/planner_benchmarking/process_data.py index 608e0dd730e..f00ad2ccff6 100644 --- a/tools/planner_benchmarking/process_data.py +++ b/tools/planner_benchmarking/process_data.py @@ -13,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -import numpy as np import math - import os import pickle -import seaborn as sns import matplotlib.pylab as plt +import numpy as np +import seaborn as sns from tabulate import tabulate diff --git a/tools/smoother_benchmarking/metrics.py b/tools/smoother_benchmarking/metrics.py index 5dcf611d2c0..8d1bd7ea0ee 100644 --- a/tools/smoother_benchmarking/metrics.py +++ b/tools/smoother_benchmarking/metrics.py @@ -14,19 +14,15 @@ # See the License for the specific language governing permissions and # limitations under the License. -from geometry_msgs.msg import PoseStamped -from nav2_simple_commander.robot_navigator import BasicNavigator -import rclpy - import math import os import pickle -import numpy as np - -from random import seed -from random import randint -from random import uniform +from random import randint, seed, uniform +from geometry_msgs.msg import PoseStamped +from nav2_simple_commander.robot_navigator import BasicNavigator +import numpy as np +import rclpy from transforms3d.euler import euler2quat diff --git a/tools/smoother_benchmarking/process_data.py b/tools/smoother_benchmarking/process_data.py index efd616e1b93..621a364c22b 100644 --- a/tools/smoother_benchmarking/process_data.py +++ b/tools/smoother_benchmarking/process_data.py @@ -15,14 +15,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -import numpy as np import math - import os import pickle -import seaborn as sns import matplotlib.pylab as plt +import numpy as np +import seaborn as sns from tabulate import tabulate diff --git a/tools/smoother_benchmarking/smoother_benchmark_bringup.py b/tools/smoother_benchmarking/smoother_benchmark_bringup.py index aee119f9334..0cfcbfe1e7f 100644 --- a/tools/smoother_benchmarking/smoother_benchmark_bringup.py +++ b/tools/smoother_benchmarking/smoother_benchmark_bringup.py @@ -14,11 +14,11 @@ import os +from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import ExecuteProcess, IncludeLaunchDescription from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.actions import Node -from ament_index_python.packages import get_package_share_directory def generate_launch_description(): From ad85fac0c0a3a218dd352e817279fecbdbb6a251 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:37:15 +0100 Subject: [PATCH 13/24] Fix flake8-docstring linter --- nav2_common/nav2_common/launch/has_node_params.py | 2 +- .../nav2_common/launch/parse_multirobot_pose.py | 14 ++++---------- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/nav2_common/nav2_common/launch/has_node_params.py b/nav2_common/nav2_common/launch/has_node_params.py index 652f07a70fa..df395b5b056 100644 --- a/nav2_common/nav2_common/launch/has_node_params.py +++ b/nav2_common/nav2_common/launch/has_node_params.py @@ -21,7 +21,7 @@ class HasNodeParams(launch.Substitution): """ - Substitution that checks if a param file contains parameters for a node + Substitution that checks if a param file contains parameters for a node. Used in launch system """ diff --git a/nav2_common/nav2_common/launch/parse_multirobot_pose.py b/nav2_common/nav2_common/launch/parse_multirobot_pose.py index 65ed4a6e186..a08910491de 100644 --- a/nav2_common/nav2_common/launch/parse_multirobot_pose.py +++ b/nav2_common/nav2_common/launch/parse_multirobot_pose.py @@ -19,13 +19,11 @@ class ParseMultiRobotPose: - """ - Parsing argument using sys module - """ + """Parsing argument using sys module.""" def __init__(self, target_argument: Text): """ - Parse arguments for multi-robot's pose + Parse arguments for multi-robot's pose. for example, `ros2 launch nav2_bringup bringup_multirobot_launch.py @@ -43,9 +41,7 @@ def __init__(self, target_argument: Text): self.__args: Text = self.__parse_argument(target_argument) def __parse_argument(self, target_argument: Text) -> Text: - """ - get value of target argument - """ + """Get value of target argument.""" if len(sys.argv) > 4: argv = sys.argv[4:] for arg in argv: @@ -54,9 +50,7 @@ def __parse_argument(self, target_argument: Text) -> Text: return "" def value(self) -> Dict: - """ - get value of target argument - """ + """Get value of target argument.""" args = self.__args parsed_args = [] if len(args) == 0 else args.split(";") multirobots = {} From 36d70f0419876d096037ee3b5773be20d834edd0 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 17:55:08 +0100 Subject: [PATCH 14/24] Fix flake8-quotes linter for nav2_common --- nav2_common/nav2_common/launch/__init__.py | 8 ++--- .../nav2_common/launch/has_node_params.py | 8 ++--- .../launch/parse_multirobot_pose.py | 34 +++++++++---------- .../nav2_common/launch/replace_string.py | 12 +++---- .../nav2_common/launch/rewritten_yaml.py | 24 ++++++------- 5 files changed, 43 insertions(+), 43 deletions(-) diff --git a/nav2_common/nav2_common/launch/__init__.py b/nav2_common/nav2_common/launch/__init__.py index d079ccd23b5..61ea85dd793 100644 --- a/nav2_common/nav2_common/launch/__init__.py +++ b/nav2_common/nav2_common/launch/__init__.py @@ -18,8 +18,8 @@ from .rewritten_yaml import RewrittenYaml __all__ = [ - "HasNodeParams", - "RewrittenYaml", - "ReplaceString", - "ParseMultiRobotPose", + 'HasNodeParams', + 'RewrittenYaml', + 'ReplaceString', + 'ParseMultiRobotPose', ] diff --git a/nav2_common/nav2_common/launch/has_node_params.py b/nav2_common/nav2_common/launch/has_node_params.py index df395b5b056..41f005bbc50 100644 --- a/nav2_common/nav2_common/launch/has_node_params.py +++ b/nav2_common/nav2_common/launch/has_node_params.py @@ -51,12 +51,12 @@ def name(self) -> List[launch.Substitution]: def describe(self) -> Text: """Return a description of this substitution as a string.""" - return "" + return '' def perform(self, context: launch.LaunchContext) -> Text: yaml_filename = launch.utilities.perform_substitutions(context, self.name) - data = yaml.safe_load(open(yaml_filename, "r")) + data = yaml.safe_load(open(yaml_filename, 'r')) if self.__node_name in data.keys(): - return "True" - return "False" + return 'True' + return 'False' diff --git a/nav2_common/nav2_common/launch/parse_multirobot_pose.py b/nav2_common/nav2_common/launch/parse_multirobot_pose.py index a08910491de..bb1725d36de 100644 --- a/nav2_common/nav2_common/launch/parse_multirobot_pose.py +++ b/nav2_common/nav2_common/launch/parse_multirobot_pose.py @@ -45,33 +45,33 @@ def __parse_argument(self, target_argument: Text) -> Text: if len(sys.argv) > 4: argv = sys.argv[4:] for arg in argv: - if arg.startswith(target_argument + ":="): - return arg.replace(target_argument + ":=", "") - return "" + if arg.startswith(target_argument + ':='): + return arg.replace(target_argument + ':=', '') + return '' def value(self) -> Dict: """Get value of target argument.""" args = self.__args - parsed_args = [] if len(args) == 0 else args.split(";") + parsed_args = [] if len(args) == 0 else args.split(';') multirobots = {} for arg in parsed_args: - key_val = arg.strip().split("=") + key_val = arg.strip().split('=') if len(key_val) != 2: continue key = key_val[0].strip() val = key_val[1].strip() robot_pose = yaml.safe_load(val) - if "x" not in robot_pose: - robot_pose["x"] = 0.0 - if "y" not in robot_pose: - robot_pose["y"] = 0.0 - if "z" not in robot_pose: - robot_pose["z"] = 0.0 - if "roll" not in robot_pose: - robot_pose["roll"] = 0.0 - if "pitch" not in robot_pose: - robot_pose["pitch"] = 0.0 - if "yaw" not in robot_pose: - robot_pose["yaw"] = 0.0 + if 'x' not in robot_pose: + robot_pose['x'] = 0.0 + if 'y' not in robot_pose: + robot_pose['y'] = 0.0 + if 'z' not in robot_pose: + robot_pose['z'] = 0.0 + if 'roll' not in robot_pose: + robot_pose['roll'] = 0.0 + if 'pitch' not in robot_pose: + robot_pose['pitch'] = 0.0 + if 'yaw' not in robot_pose: + robot_pose['yaw'] = 0.0 multirobots[key] = robot_pose return multirobots diff --git a/nav2_common/nav2_common/launch/replace_string.py b/nav2_common/nav2_common/launch/replace_string.py index a2351587f02..076ac16f21f 100644 --- a/nav2_common/nav2_common/launch/replace_string.py +++ b/nav2_common/nav2_common/launch/replace_string.py @@ -57,18 +57,18 @@ def condition(self) -> Optional[launch.Condition]: def describe(self) -> Text: """Return a description of this substitution as a string.""" - return "" + return '' def perform(self, context: launch.LaunchContext) -> Text: yaml_filename = launch.utilities.perform_substitutions(context, self.name) if self.__condition is None or self.__condition.evaluate(context): - output_file = tempfile.NamedTemporaryFile(mode="w", delete=False) + output_file = tempfile.NamedTemporaryFile(mode='w', delete=False) replacements = self.resolve_replacements(context) try: - input_file = open(yaml_filename, "r") + input_file = open(yaml_filename, 'r') self.replace(input_file, output_file, replacements) except Exception as err: # noqa: B902 - print("ReplaceString substitution error: ", err) + print('ReplaceString substitution error: ', err) finally: input_file.close() output_file.close() @@ -92,7 +92,7 @@ def replace(self, input_file, output_file, replacements): line = line.replace(key, value) else: raise TypeError( - "A provided replacement pair is not a string. Both key and value should be" - "strings." + 'A provided replacement pair is not a string. Both key and value should be' + 'strings.' ) output_file.write(line) diff --git a/nav2_common/nav2_common/launch/rewritten_yaml.py b/nav2_common/nav2_common/launch/rewritten_yaml.py index 49f9f2fb650..77d765dda4a 100644 --- a/nav2_common/nav2_common/launch/rewritten_yaml.py +++ b/nav2_common/nav2_common/launch/rewritten_yaml.py @@ -85,13 +85,13 @@ def name(self) -> List[launch.Substitution]: def describe(self) -> Text: """Return a description of this substitution as a string.""" - return "" + return '' def perform(self, context: launch.LaunchContext) -> Text: yaml_filename = launch.utilities.perform_substitutions(context, self.name) - rewritten_yaml = tempfile.NamedTemporaryFile(mode="w", delete=False) + rewritten_yaml = tempfile.NamedTemporaryFile(mode='w', delete=False) param_rewrites, keys_rewrites = self.resolve_rewrites(context) - data = yaml.safe_load(open(yaml_filename, "r")) + data = yaml.safe_load(open(yaml_filename, 'r')) self.substitute_params(data, param_rewrites) self.add_params(data, param_rewrites) self.substitute_keys(data, keys_rewrites) @@ -129,7 +129,7 @@ def substitute_params(self, yaml, param_rewrites): if path in param_rewrites: # this is an absolute path (ex. 'key.keyA.keyB.val') rewrite_val = self.convert(param_rewrites[path]) - yaml_keys = path.split(".") + yaml_keys = path.split('.') yaml = self.updateYamlPathVals(yaml, yaml_keys, rewrite_val) def add_params(self, yaml, param_rewrites): @@ -138,8 +138,8 @@ def add_params(self, yaml, param_rewrites): for path in param_rewrites: if yaml_paths not in path: new_val = self.convert(param_rewrites[path]) - yaml_keys = path.split(".") - if "ros__parameters" in yaml_keys: + yaml_keys = path.split('.') + if 'ros__parameters' in yaml_keys: yaml = self.updateYamlPathVals(yaml, yaml_keys, new_val) def updateYamlPathVals(self, yaml, yaml_key_list, rewrite_val): @@ -178,13 +178,13 @@ def getYamlLeafKeys(self, yamlData): except AttributeError: return - def pathify(self, d, p=None, paths=None, joinchar="."): + def pathify(self, d, p=None, paths=None, joinchar='.'): if p is None: paths = {} - self.pathify(d, "", paths, joinchar=joinchar) + self.pathify(d, '', paths, joinchar=joinchar) return paths pn = p - if p != "": + if p != '': pn += joinchar if isinstance(d, dict): for k in d: @@ -200,14 +200,14 @@ def convert(self, text_value): if self.__convert_types: # try converting to int or float try: - return float(text_value) if "." in text_value else int(text_value) + return float(text_value) if '.' in text_value else int(text_value) except ValueError: pass # try converting to bool - if text_value.lower() == "true": + if text_value.lower() == 'true': return True - if text_value.lower() == "false": + if text_value.lower() == 'false': return False # nothing else worked so fall through and return text From 4484d6d79c4a93181f0f76af085e963b0e6213fb Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 18:11:03 +0100 Subject: [PATCH 15/24] Fix flake8-quotes linter for nav2_system_tests --- .../test_assisted_teleop_behavior_launch.py | 66 +++--- .../backup/test_backup_behavior_launch.py | 66 +++--- .../test_drive_on_heading_behavior_launch.py | 68 +++--- .../spin/test_spin_behavior_fake_launch.py | 132 ++++++------ .../spin/test_spin_behavior_launch.py | 66 +++--- .../wait/test_wait_behavior_launch.py | 66 +++--- .../costmap_filters/test_keepout_launch.py | 136 ++++++------ .../src/costmap_filters/test_speed_launch.py | 126 +++++------ .../src/costmap_filters/tester_node.py | 204 +++++++++--------- .../src/error_codes/test_error_codes.py | 88 ++++---- .../error_codes/test_error_codes_launch.py | 64 +++--- .../gps_navigation/dual_ekf_navsat.launch.py | 52 ++--- .../src/gps_navigation/test_case_py.launch.py | 86 ++++---- .../src/gps_navigation/tester.py | 48 ++--- .../localization/test_localization_launch.py | 52 ++--- .../planning/test_planner_costmaps_launch.py | 10 +- .../planning/test_planner_random_launch.py | 10 +- .../system/nav_through_poses_tester_node.py | 134 ++++++------ .../src/system/nav_to_pose_tester_node.py | 152 ++++++------- .../src/system/test_multi_robot_launch.py | 140 ++++++------ .../src/system/test_system_launch.py | 94 ++++---- .../src/system/test_wrong_init_pose_launch.py | 96 ++++----- .../test_system_failure_launch.py | 84 ++++---- .../src/system_failure/tester_node.py | 132 ++++++------ .../src/updown/test_updown_launch.py | 54 ++--- nav2_system_tests/src/updown/updownresults.py | 28 +-- .../src/waypoint_follower/tester.py | 68 +++--- 27 files changed, 1161 insertions(+), 1161 deletions(-) diff --git a/nav2_system_tests/src/behaviors/assisted_teleop/test_assisted_teleop_behavior_launch.py b/nav2_system_tests/src/behaviors/assisted_teleop/test_assisted_teleop_behavior_launch.py index 3d3846a3e9c..b262d36efbd 100755 --- a/nav2_system_tests/src/behaviors/assisted_teleop/test_assisted_teleop_behavior_launch.py +++ b/nav2_system_tests/src/behaviors/assisted_teleop/test_assisted_teleop_behavior_launch.py @@ -33,63 +33,63 @@ def generate_launch_description(): - map_yaml_file = os.getenv("TEST_MAP") - world = os.getenv("TEST_WORLD") + map_yaml_file = os.getenv('TEST_MAP') + world = os.getenv('TEST_WORLD') bt_navigator_xml = os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - os.getenv("BT_NAVIGATOR_XML"), + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + os.getenv('BT_NAVIGATOR_XML'), ) - bringup_dir = get_package_share_directory("nav2_bringup") - params_file = os.path.join(bringup_dir, "params/nav2_params.yaml") + bringup_dir = get_package_share_directory('nav2_bringup') + params_file = os.path.join(bringup_dir, 'params/nav2_params.yaml') # Replace the `use_astar` setting on the params file configured_params = RewrittenYaml( - source_file=params_file, root_key="", param_rewrites="", convert_types=True + source_file=params_file, root_key='', param_rewrites='', convert_types=True ) return LaunchDescription( [ - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), # Launch gazebo server for simulation ExecuteProcess( cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "--minimal_comms", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '--minimal_comms', world, ], - output="screen", + output='screen', ), # TODO(orduno) Launch the robot state publisher instead # using a local copy of TB3 urdf file Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "bringup_launch.py") + os.path.join(bringup_dir, 'launch', 'bringup_launch.py') ), launch_arguments={ - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": configured_params, - "bt_xml_file": bt_navigator_xml, - "use_composition": "False", - "autostart": "True", + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': configured_params, + 'bt_xml_file': bt_navigator_xml, + 'use_composition': 'False', + 'autostart': 'True', }.items(), ), ] @@ -99,10 +99,10 @@ def generate_launch_description(): def main(argv=sys.argv[1:]): ld = generate_launch_description() - testExecutable = os.getenv("TEST_EXECUTABLE") + testExecutable = os.getenv('TEST_EXECUTABLE') test1_action = ExecuteProcess( - cmd=[testExecutable], name="test_assisted_teleop_behavior_node", output="screen" + cmd=[testExecutable], name='test_assisted_teleop_behavior_node', output='screen' ) lts = LaunchTestService() @@ -112,5 +112,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/behaviors/backup/test_backup_behavior_launch.py b/nav2_system_tests/src/behaviors/backup/test_backup_behavior_launch.py index 780bb26e0bb..6f4a6c3c16e 100755 --- a/nav2_system_tests/src/behaviors/backup/test_backup_behavior_launch.py +++ b/nav2_system_tests/src/behaviors/backup/test_backup_behavior_launch.py @@ -33,63 +33,63 @@ def generate_launch_description(): - map_yaml_file = os.getenv("TEST_MAP") - world = os.getenv("TEST_WORLD") + map_yaml_file = os.getenv('TEST_MAP') + world = os.getenv('TEST_WORLD') bt_navigator_xml = os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - os.getenv("BT_NAVIGATOR_XML"), + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + os.getenv('BT_NAVIGATOR_XML'), ) - bringup_dir = get_package_share_directory("nav2_bringup") - params_file = os.path.join(bringup_dir, "params/nav2_params.yaml") + bringup_dir = get_package_share_directory('nav2_bringup') + params_file = os.path.join(bringup_dir, 'params/nav2_params.yaml') # Replace the `use_astar` setting on the params file configured_params = RewrittenYaml( - source_file=params_file, root_key="", param_rewrites="", convert_types=True + source_file=params_file, root_key='', param_rewrites='', convert_types=True ) return LaunchDescription( [ - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), # Launch gazebo server for simulation ExecuteProcess( cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "--minimal_comms", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '--minimal_comms', world, ], - output="screen", + output='screen', ), # TODO(orduno) Launch the robot state publisher instead # using a local copy of TB3 urdf file Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "bringup_launch.py") + os.path.join(bringup_dir, 'launch', 'bringup_launch.py') ), launch_arguments={ - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": configured_params, - "bt_xml_file": bt_navigator_xml, - "use_composition": "False", - "autostart": "True", + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': configured_params, + 'bt_xml_file': bt_navigator_xml, + 'use_composition': 'False', + 'autostart': 'True', }.items(), ), ] @@ -99,10 +99,10 @@ def generate_launch_description(): def main(argv=sys.argv[1:]): ld = generate_launch_description() - testExecutable = os.getenv("TEST_EXECUTABLE") + testExecutable = os.getenv('TEST_EXECUTABLE') test1_action = ExecuteProcess( - cmd=[testExecutable], name="test_backup_behavior_node", output="screen" + cmd=[testExecutable], name='test_backup_behavior_node', output='screen' ) lts = LaunchTestService() @@ -112,5 +112,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/behaviors/drive_on_heading/test_drive_on_heading_behavior_launch.py b/nav2_system_tests/src/behaviors/drive_on_heading/test_drive_on_heading_behavior_launch.py index 27801b9be41..8f23ce67b26 100755 --- a/nav2_system_tests/src/behaviors/drive_on_heading/test_drive_on_heading_behavior_launch.py +++ b/nav2_system_tests/src/behaviors/drive_on_heading/test_drive_on_heading_behavior_launch.py @@ -33,63 +33,63 @@ def generate_launch_description(): - map_yaml_file = os.getenv("TEST_MAP") - world = os.getenv("TEST_WORLD") + map_yaml_file = os.getenv('TEST_MAP') + world = os.getenv('TEST_WORLD') bt_navigator_xml = os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - os.getenv("BT_NAVIGATOR_XML"), + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + os.getenv('BT_NAVIGATOR_XML'), ) - bringup_dir = get_package_share_directory("nav2_bringup") - params_file = os.path.join(bringup_dir, "params/nav2_params.yaml") + bringup_dir = get_package_share_directory('nav2_bringup') + params_file = os.path.join(bringup_dir, 'params/nav2_params.yaml') # Replace the `use_astar` setting on the params file configured_params = RewrittenYaml( - source_file=params_file, root_key="", param_rewrites="", convert_types=True + source_file=params_file, root_key='', param_rewrites='', convert_types=True ) return LaunchDescription( [ - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), # Launch gazebo server for simulation ExecuteProcess( cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "--minimal_comms", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '--minimal_comms', world, ], - output="screen", + output='screen', ), # TODO(orduno) Launch the robot state publisher instead # using a local copy of TB3 urdf file Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "bringup_launch.py") + os.path.join(bringup_dir, 'launch', 'bringup_launch.py') ), launch_arguments={ - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": configured_params, - "bt_xml_file": bt_navigator_xml, - "use_composition": "False", - "autostart": "True", + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': configured_params, + 'bt_xml_file': bt_navigator_xml, + 'use_composition': 'False', + 'autostart': 'True', }.items(), ), ] @@ -99,12 +99,12 @@ def generate_launch_description(): def main(argv=sys.argv[1:]): ld = generate_launch_description() - testExecutable = os.getenv("TEST_EXECUTABLE") + testExecutable = os.getenv('TEST_EXECUTABLE') test1_action = ExecuteProcess( cmd=[testExecutable], - name="test_drive_on_heading_behavior_node", - output="screen", + name='test_drive_on_heading_behavior_node', + output='screen', ) lts = LaunchTestService() @@ -114,5 +114,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/behaviors/spin/test_spin_behavior_fake_launch.py b/nav2_system_tests/src/behaviors/spin/test_spin_behavior_fake_launch.py index 303e378783b..22b8327cd25 100755 --- a/nav2_system_tests/src/behaviors/spin/test_spin_behavior_fake_launch.py +++ b/nav2_system_tests/src/behaviors/spin/test_spin_behavior_fake_launch.py @@ -29,25 +29,25 @@ def generate_launch_description(): - bringup_dir = get_package_share_directory("nav2_bringup") + bringup_dir = get_package_share_directory('nav2_bringup') - namespace = LaunchConfiguration("namespace") - use_sim_time = LaunchConfiguration("use_sim_time") - autostart = LaunchConfiguration("autostart") - params_file = LaunchConfiguration("params_file") + namespace = LaunchConfiguration('namespace') + use_sim_time = LaunchConfiguration('use_sim_time') + autostart = LaunchConfiguration('autostart') + params_file = LaunchConfiguration('params_file') default_nav_through_poses_bt_xml = LaunchConfiguration( - "default_nav_through_poses_bt_xml" + 'default_nav_through_poses_bt_xml' ) - default_nav_to_pose_bt_xml = LaunchConfiguration("default_nav_to_pose_bt_xml") - map_subscribe_transient_local = LaunchConfiguration("map_subscribe_transient_local") + default_nav_to_pose_bt_xml = LaunchConfiguration('default_nav_to_pose_bt_xml') + map_subscribe_transient_local = LaunchConfiguration('map_subscribe_transient_local') # Create our own temporary YAML files that include substitutions param_substitutions = { - "use_sim_time": use_sim_time, - "default_nav_through_poses_bt_xml": default_nav_through_poses_bt_xml, - "default_nav_to_pose_bt_xml": default_nav_to_pose_bt_xml, - "autostart": autostart, - "map_subscribe_transient_local": map_subscribe_transient_local, + 'use_sim_time': use_sim_time, + 'default_nav_through_poses_bt_xml': default_nav_through_poses_bt_xml, + 'default_nav_to_pose_bt_xml': default_nav_to_pose_bt_xml, + 'autostart': autostart, + 'map_subscribe_transient_local': map_subscribe_transient_local, } configured_params = RewrittenYaml( @@ -57,7 +57,7 @@ def generate_launch_description(): convert_types=True, ) - lifecycle_nodes = ["behavior_server"] + lifecycle_nodes = ['behavior_server'] # Map fully qualified names to relative ones so the node's namespace can be prepended. # In case of the transforms (tf), currently, there doesn't seem to be a better alternative @@ -65,90 +65,90 @@ def generate_launch_description(): # https://github.com/ros/robot_state_publisher/pull/30 # TODO(orduno) Substitute with `PushNodeRemapping` # https://github.com/ros2/launch_ros/issues/56 - remappings = [("/tf", "tf"), ("/tf_static", "tf_static")] + remappings = [('/tf', 'tf'), ('/tf_static', 'tf_static')] return LaunchDescription( [ - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), DeclareLaunchArgument( - "namespace", default_value="", description="Top-level namespace" + 'namespace', default_value='', description='Top-level namespace' ), DeclareLaunchArgument( - "use_sim_time", - default_value="false", - description="Use simulation (Gazebo) clock if true", + 'use_sim_time', + default_value='false', + description='Use simulation (Gazebo) clock if true', ), DeclareLaunchArgument( - "autostart", - default_value="true", - description="Automatically startup the nav2 stack", + 'autostart', + default_value='true', + description='Automatically startup the nav2 stack', ), DeclareLaunchArgument( - "params_file", - default_value=os.path.join(bringup_dir, "params", "nav2_params.yaml"), - description="Full path to the ROS2 parameters file to use", + 'params_file', + default_value=os.path.join(bringup_dir, 'params', 'nav2_params.yaml'), + description='Full path to the ROS2 parameters file to use', ), DeclareLaunchArgument( - "default_nav_through_poses_bt_xml", + 'default_nav_through_poses_bt_xml', default_value=os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - "navigate_through_poses_w_replanning_and_recovery.xml", + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + 'navigate_through_poses_w_replanning_and_recovery.xml', ), - description="Full path to the behavior tree xml file to use", + description='Full path to the behavior tree xml file to use', ), DeclareLaunchArgument( - "default_nav_to_pose_bt_xml", + 'default_nav_to_pose_bt_xml', default_value=os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - "navigate_to_pose_w_replanning_and_recovery.xml", + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + 'navigate_to_pose_w_replanning_and_recovery.xml', ), - description="Full path to the behavior tree xml file to use", + description='Full path to the behavior tree xml file to use', ), DeclareLaunchArgument( - "map_subscribe_transient_local", - default_value="false", - description="Whether to set the map subscriber QoS to transient local", + 'map_subscribe_transient_local', + default_value='false', + description='Whether to set the map subscriber QoS to transient local', ), # TODO(orduno) Launch the robot state publisher instead # using a local copy of TB3 urdf file Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "map", "odom"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'map', 'odom'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ), Node( - package="nav2_behaviors", - executable="behavior_server", - name="behavior_server", - output="screen", + package='nav2_behaviors', + executable='behavior_server', + name='behavior_server', + output='screen', parameters=[configured_params], remappings=remappings, ), Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager_navigation", - output="screen", + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager_navigation', + output='screen', parameters=[ - {"use_sim_time": use_sim_time}, - {"autostart": autostart}, - {"node_names": lifecycle_nodes}, + {'use_sim_time': use_sim_time}, + {'autostart': autostart}, + {'node_names': lifecycle_nodes}, ], ), ] @@ -158,10 +158,10 @@ def generate_launch_description(): def main(argv=sys.argv[1:]): ld = generate_launch_description() - testExecutable = os.getenv("TEST_EXECUTABLE") + testExecutable = os.getenv('TEST_EXECUTABLE') test1_action = ExecuteProcess( - cmd=[testExecutable], name="test_spin_behavior_fake_node", output="screen" + cmd=[testExecutable], name='test_spin_behavior_fake_node', output='screen' ) lts = LaunchTestService() @@ -171,5 +171,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/behaviors/spin/test_spin_behavior_launch.py b/nav2_system_tests/src/behaviors/spin/test_spin_behavior_launch.py index 2059bc0fd9f..4552f51768d 100755 --- a/nav2_system_tests/src/behaviors/spin/test_spin_behavior_launch.py +++ b/nav2_system_tests/src/behaviors/spin/test_spin_behavior_launch.py @@ -33,63 +33,63 @@ def generate_launch_description(): - map_yaml_file = os.getenv("TEST_MAP") - world = os.getenv("TEST_WORLD") + map_yaml_file = os.getenv('TEST_MAP') + world = os.getenv('TEST_WORLD') bt_navigator_xml = os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - os.getenv("BT_NAVIGATOR_XML"), + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + os.getenv('BT_NAVIGATOR_XML'), ) - bringup_dir = get_package_share_directory("nav2_bringup") - params_file = os.path.join(bringup_dir, "params/nav2_params.yaml") + bringup_dir = get_package_share_directory('nav2_bringup') + params_file = os.path.join(bringup_dir, 'params/nav2_params.yaml') # Replace the `use_astar` setting on the params file configured_params = RewrittenYaml( - source_file=params_file, root_key="", param_rewrites="", convert_types=True + source_file=params_file, root_key='', param_rewrites='', convert_types=True ) return LaunchDescription( [ - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), # Launch gazebo server for simulation ExecuteProcess( cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "--minimal_comms", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '--minimal_comms', world, ], - output="screen", + output='screen', ), # TODO(orduno) Launch the robot state publisher instead # using a local copy of TB3 urdf file Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "bringup_launch.py") + os.path.join(bringup_dir, 'launch', 'bringup_launch.py') ), launch_arguments={ - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": configured_params, - "bt_xml_file": bt_navigator_xml, - "use_composition": "False", - "autostart": "True", + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': configured_params, + 'bt_xml_file': bt_navigator_xml, + 'use_composition': 'False', + 'autostart': 'True', }.items(), ), ] @@ -99,10 +99,10 @@ def generate_launch_description(): def main(argv=sys.argv[1:]): ld = generate_launch_description() - testExecutable = os.getenv("TEST_EXECUTABLE") + testExecutable = os.getenv('TEST_EXECUTABLE') test1_action = ExecuteProcess( - cmd=[testExecutable], name="test_spin_behavior_node", output="screen" + cmd=[testExecutable], name='test_spin_behavior_node', output='screen' ) lts = LaunchTestService() @@ -112,5 +112,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/behaviors/wait/test_wait_behavior_launch.py b/nav2_system_tests/src/behaviors/wait/test_wait_behavior_launch.py index 13c0cd86d5e..f4c4e5bc168 100755 --- a/nav2_system_tests/src/behaviors/wait/test_wait_behavior_launch.py +++ b/nav2_system_tests/src/behaviors/wait/test_wait_behavior_launch.py @@ -33,63 +33,63 @@ def generate_launch_description(): - map_yaml_file = os.getenv("TEST_MAP") - world = os.getenv("TEST_WORLD") + map_yaml_file = os.getenv('TEST_MAP') + world = os.getenv('TEST_WORLD') bt_navigator_xml = os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - os.getenv("BT_NAVIGATOR_XML"), + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + os.getenv('BT_NAVIGATOR_XML'), ) - bringup_dir = get_package_share_directory("nav2_bringup") - params_file = os.path.join(bringup_dir, "params/nav2_params.yaml") + bringup_dir = get_package_share_directory('nav2_bringup') + params_file = os.path.join(bringup_dir, 'params/nav2_params.yaml') # Replace the `use_astar` setting on the params file configured_params = RewrittenYaml( - source_file=params_file, root_key="", param_rewrites="", convert_types=True + source_file=params_file, root_key='', param_rewrites='', convert_types=True ) return LaunchDescription( [ - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), # Launch gazebo server for simulation ExecuteProcess( cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "--minimal_comms", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '--minimal_comms', world, ], - output="screen", + output='screen', ), # TODO(orduno) Launch the robot state publisher instead # using a local copy of TB3 urdf file Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "bringup_launch.py") + os.path.join(bringup_dir, 'launch', 'bringup_launch.py') ), launch_arguments={ - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": configured_params, - "bt_xml_file": bt_navigator_xml, - "use_composition": "False", - "autostart": "True", + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': configured_params, + 'bt_xml_file': bt_navigator_xml, + 'use_composition': 'False', + 'autostart': 'True', }.items(), ), ] @@ -99,10 +99,10 @@ def generate_launch_description(): def main(argv=sys.argv[1:]): ld = generate_launch_description() - testExecutable = os.getenv("TEST_EXECUTABLE") + testExecutable = os.getenv('TEST_EXECUTABLE') test1_action = ExecuteProcess( - cmd=[testExecutable], name="test_wait_behavior_node", output="screen" + cmd=[testExecutable], name='test_wait_behavior_node', output='screen' ) lts = LaunchTestService() @@ -112,5 +112,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/costmap_filters/test_keepout_launch.py b/nav2_system_tests/src/costmap_filters/test_keepout_launch.py index 188f2541144..dcace8aeb6d 100755 --- a/nav2_system_tests/src/costmap_filters/test_keepout_launch.py +++ b/nav2_system_tests/src/costmap_filters/test_keepout_launch.py @@ -36,29 +36,29 @@ def generate_launch_description(): - map_yaml_file = os.getenv("TEST_MAP") - filter_mask_file = os.getenv("TEST_MASK") - world = os.getenv("TEST_WORLD") + map_yaml_file = os.getenv('TEST_MAP') + filter_mask_file = os.getenv('TEST_MASK') + world = os.getenv('TEST_WORLD') bt_navigator_xml = os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - os.getenv("BT_NAVIGATOR_XML"), + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + os.getenv('BT_NAVIGATOR_XML'), ) - bringup_dir = get_package_share_directory("nav2_bringup") + bringup_dir = get_package_share_directory('nav2_bringup') script_dir = os.path.dirname(os.path.realpath(__file__)) - params_file = os.path.join(script_dir, "keepout_params.yaml") + params_file = os.path.join(script_dir, 'keepout_params.yaml') # Replace the `use_astar` setting on the params file param_substitutions = { - "planner_server.ros__parameters.GridBased.use_astar": os.getenv("ASTAR"), - "filter_mask_server.ros__parameters.yaml_filename": filter_mask_file, - "map_server.ros__parameters.yaml_filename": map_yaml_file, + 'planner_server.ros__parameters.GridBased.use_astar': os.getenv('ASTAR'), + 'filter_mask_server.ros__parameters.yaml_filename': filter_mask_file, + 'map_server.ros__parameters.yaml_filename': map_yaml_file, } configured_params = RewrittenYaml( source_file=params_file, - root_key="", + root_key='', param_rewrites=param_substitutions, convert_types=True, ) @@ -67,84 +67,84 @@ def generate_launch_description(): new_yaml = configured_params.perform(context) return LaunchDescription( [ - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), # Launch gazebo server for simulation ExecuteProcess( cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "--minimal_comms", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '--minimal_comms', world, ], - output="screen", + output='screen', ), # TODO(orduno) Launch the robot state publisher instead # using a local copy of TB3 urdf file Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ), Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager_filters", - output="screen", + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager_filters', + output='screen', parameters=[ { - "node_names": [ - "filter_mask_server", - "costmap_filter_info_server", + 'node_names': [ + 'filter_mask_server', + 'costmap_filter_info_server', ] }, - {"autostart": True}, + {'autostart': True}, ], ), # Nodes required for Costmap Filters configuration Node( - package="nav2_map_server", - executable="map_server", - name="filter_mask_server", - output="screen", + package='nav2_map_server', + executable='map_server', + name='filter_mask_server', + output='screen', parameters=[new_yaml], ), Node( - package="nav2_map_server", - executable="costmap_filter_info_server", - name="costmap_filter_info_server", - output="screen", + package='nav2_map_server', + executable='costmap_filter_info_server', + name='costmap_filter_info_server', + output='screen', parameters=[new_yaml], ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "bringup_launch.py") + os.path.join(bringup_dir, 'launch', 'bringup_launch.py') ), launch_arguments={ - "namespace": "", - "use_namespace": "False", - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": new_yaml, - "bt_xml_file": bt_navigator_xml, - "use_composition": "False", - "autostart": "True", + 'namespace': '', + 'use_namespace': 'False', + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': new_yaml, + 'bt_xml_file': bt_navigator_xml, + 'use_composition': 'False', + 'autostart': 'True', }.items(), ), Node( - package="nav2_costmap_2d", - executable="nav2_costmap_2d_cloud", - name="costmap_2d_cloud", - output="screen", - remappings=[("voxel_grid", "local_costmap/voxel_grid")], + package='nav2_costmap_2d', + executable='nav2_costmap_2d_cloud', + name='costmap_2d_cloud', + output='screen', + remappings=[('voxel_grid', 'local_costmap/voxel_grid')], ), ] ) @@ -155,17 +155,17 @@ def main(argv=sys.argv[1:]): test1_action = ExecuteProcess( cmd=[ - os.path.join(os.getenv("TEST_DIR"), "tester_node.py"), - "-t", - "keepout", - "-r", - "-2.0", - "-0.5", - "0.0", - "-0.5", + os.path.join(os.getenv('TEST_DIR'), 'tester_node.py'), + '-t', + 'keepout', + '-r', + '-2.0', + '-0.5', + '0.0', + '-0.5', ], - name="tester_node", - output="screen", + name='tester_node', + output='screen', ) lts = LaunchTestService() @@ -175,5 +175,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/costmap_filters/test_speed_launch.py b/nav2_system_tests/src/costmap_filters/test_speed_launch.py index 0e1ac61d710..95d6fb412f0 100755 --- a/nav2_system_tests/src/costmap_filters/test_speed_launch.py +++ b/nav2_system_tests/src/costmap_filters/test_speed_launch.py @@ -36,28 +36,28 @@ def generate_launch_description(): - map_yaml_file = os.getenv("TEST_MAP") - filter_mask_file = os.getenv("TEST_MASK") - world = os.getenv("TEST_WORLD") + map_yaml_file = os.getenv('TEST_MAP') + filter_mask_file = os.getenv('TEST_MASK') + world = os.getenv('TEST_WORLD') bt_navigator_xml = os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - os.getenv("BT_NAVIGATOR_XML"), + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + os.getenv('BT_NAVIGATOR_XML'), ) - bringup_dir = get_package_share_directory("nav2_bringup") - params_file = os.getenv("PARAMS_FILE") + bringup_dir = get_package_share_directory('nav2_bringup') + params_file = os.getenv('PARAMS_FILE') # Replace the `use_astar` setting on the params file param_substitutions = { - "planner_server.ros__parameters.GridBased.use_astar": os.getenv("ASTAR"), - "filter_mask_server.ros__parameters.yaml_filename": filter_mask_file, - "map_server.ros__parameters.yaml_filename": map_yaml_file, + 'planner_server.ros__parameters.GridBased.use_astar': os.getenv('ASTAR'), + 'filter_mask_server.ros__parameters.yaml_filename': filter_mask_file, + 'map_server.ros__parameters.yaml_filename': map_yaml_file, } configured_params = RewrittenYaml( source_file=params_file, - root_key="", + root_key='', param_rewrites=param_substitutions, convert_types=True, ) @@ -65,76 +65,76 @@ def generate_launch_description(): new_yaml = configured_params.perform(context) return LaunchDescription( [ - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), # Launch gazebo server for simulation ExecuteProcess( cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "--minimal_comms", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '--minimal_comms', world, ], - output="screen", + output='screen', ), # TODO(orduno) Launch the robot state publisher instead # using a local copy of TB3 urdf file Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ), Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager_filters", - output="screen", + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager_filters', + output='screen', parameters=[ { - "node_names": [ - "filter_mask_server", - "costmap_filter_info_server", + 'node_names': [ + 'filter_mask_server', + 'costmap_filter_info_server', ] }, - {"autostart": True}, + {'autostart': True}, ], ), # Nodes required for Costmap Filters configuration Node( - package="nav2_map_server", - executable="map_server", - name="filter_mask_server", - output="screen", + package='nav2_map_server', + executable='map_server', + name='filter_mask_server', + output='screen', parameters=[new_yaml], ), Node( - package="nav2_map_server", - executable="costmap_filter_info_server", - name="costmap_filter_info_server", - output="screen", + package='nav2_map_server', + executable='costmap_filter_info_server', + name='costmap_filter_info_server', + output='screen', parameters=[new_yaml], ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "bringup_launch.py") + os.path.join(bringup_dir, 'launch', 'bringup_launch.py') ), launch_arguments={ - "namespace": "", - "use_namespace": "False", - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": new_yaml, - "bt_xml_file": bt_navigator_xml, - "use_composition": "False", - "autostart": "True", + 'namespace': '', + 'use_namespace': 'False', + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': new_yaml, + 'bt_xml_file': bt_navigator_xml, + 'use_composition': 'False', + 'autostart': 'True', }.items(), ), ] @@ -146,17 +146,17 @@ def main(argv=sys.argv[1:]): test1_action = ExecuteProcess( cmd=[ - os.path.join(os.getenv("TEST_DIR"), "tester_node.py"), - "-t", - "speed", - "-r", - "-2.0", - "-0.5", - "0.0", - "-0.5", + os.path.join(os.getenv('TEST_DIR'), 'tester_node.py'), + '-t', + 'speed', + '-r', + '-2.0', + '-0.5', + '0.0', + '-0.5', ], - name="tester_node", - output="screen", + name='tester_node', + output='screen', ) lts = LaunchTestService() @@ -166,5 +166,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/costmap_filters/tester_node.py b/nav2_system_tests/src/costmap_filters/tester_node.py index 6092505d36e..da8ab82a20b 100755 --- a/nav2_system_tests/src/costmap_filters/tester_node.py +++ b/nav2_system_tests/src/costmap_filters/tester_node.py @@ -83,13 +83,13 @@ def __init__( test_type: TestType, initial_pose: Pose, goal_pose: Pose, - namespace: str = "", + namespace: str = '', ): - super().__init__(node_name="nav2_tester", namespace=namespace) + super().__init__(node_name='nav2_tester', namespace=namespace) self.initial_pose_pub = self.create_publisher( - PoseWithCovarianceStamped, "initialpose", 10 + PoseWithCovarianceStamped, 'initialpose', 10 ) - self.goal_pub = self.create_publisher(PoseStamped, "goal_pose", 10) + self.goal_pub = self.create_publisher(PoseStamped, 'goal_pose', 10) transient_local_qos = QoSProfile( durability=QoSDurabilityPolicy.TRANSIENT_LOCAL, @@ -107,13 +107,13 @@ def __init__( self.model_pose_sub = self.create_subscription( PoseWithCovarianceStamped, - "amcl_pose", + 'amcl_pose', self.poseCallback, transient_local_qos, ) self.clearing_ep_sub = self.create_subscription( PointCloud2, - "local_costmap/clearing_endpoints", + 'local_costmap/clearing_endpoints', self.clearingEndpointsCallback, transient_local_qos, ) @@ -126,57 +126,57 @@ def __init__( if self.test_type == TestType.KEEPOUT: self.plan_sub = self.create_subscription( - Path, "plan", self.planCallback, volatile_qos + Path, 'plan', self.planCallback, volatile_qos ) self.voxel_marked_sub = self.create_subscription( - PointCloud2, "voxel_marked_cloud", self.voxelMarkedCallback, 1 + PointCloud2, 'voxel_marked_cloud', self.voxelMarkedCallback, 1 ) self.voxel_unknown_sub = self.create_subscription( - PointCloud2, "voxel_unknown_cloud", self.voxelUnknownCallback, 1 + PointCloud2, 'voxel_unknown_cloud', self.voxelUnknownCallback, 1 ) self.cost_cloud_sub = self.create_subscription( - PointCloud2, "cost_cloud", self.dwbCostCloudCallback, 1 + PointCloud2, 'cost_cloud', self.dwbCostCloudCallback, 1 ) elif self.test_type == TestType.SPEED: self.speed_it = 0 # Expected chain of speed limits self.limits = [50.0, 0.0] - # Permissive array: all received speed limits must match to "limits" from above + # Permissive array: all received speed limits must match to 'limits' from above self.limit_passed = [False, False] self.plan_sub = self.create_subscription( - SpeedLimit, "speed_limit", self.speedLimitCallback, volatile_qos + SpeedLimit, 'speed_limit', self.speedLimitCallback, volatile_qos ) self.mask_received = False self.mask_sub = self.create_subscription( - OccupancyGrid, "filter_mask", self.maskCallback, transient_local_qos + OccupancyGrid, 'filter_mask', self.maskCallback, transient_local_qos ) self.initial_pose_received = False self.initial_pose = initial_pose self.goal_pose = goal_pose - self.action_client = ActionClient(self, NavigateToPose, "navigate_to_pose") + self.action_client = ActionClient(self, NavigateToPose, 'navigate_to_pose') def info_msg(self, msg: str): - self.get_logger().info("\033[1;37;44m" + msg + "\033[0m") + self.get_logger().info('\033[1;37;44m' + msg + '\033[0m') def warn_msg(self, msg: str): - self.get_logger().warn("\033[1;37;43m" + msg + "\033[0m") + self.get_logger().warn('\033[1;37;43m' + msg + '\033[0m') def error_msg(self, msg: str): - self.get_logger().error("\033[1;37;41m" + msg + "\033[0m") + self.get_logger().error('\033[1;37;41m' + msg + '\033[0m') def setInitialPose(self): msg = PoseWithCovarianceStamped() msg.pose.pose = self.initial_pose - msg.header.frame_id = "map" - self.info_msg("Publishing Initial Pose") + msg.header.frame_id = 'map' + self.info_msg('Publishing Initial Pose') self.initial_pose_pub.publish(msg) self.currentPose = self.initial_pose def getStampedPoseMsg(self, pose: Pose): msg = PoseStamped() - msg.header.frame_id = "map" + msg.header.frame_id = 'map' msg.pose = pose return msg @@ -194,27 +194,27 @@ def runNavigateAction(self, goal_pose: Optional[Pose] = None): goal_msg = NavigateToPose.Goal() goal_msg.pose = self.getStampedPoseMsg(self.goal_pose) - self.info_msg("Sending goal request...") + self.info_msg('Sending goal request...') send_goal_future = self.action_client.send_goal_async(goal_msg) rclpy.spin_until_future_complete(self, send_goal_future) goal_handle = send_goal_future.result() if not goal_handle.accepted: - self.error_msg("Goal rejected") + self.error_msg('Goal rejected') return False - self.info_msg("Goal accepted") + self.info_msg('Goal accepted') get_result_future = goal_handle.get_result_async() self.info_msg("Waiting for 'NavigateToPose' action to complete") rclpy.spin_until_future_complete(self, get_result_future) status = get_result_future.result().status if status != GoalStatus.STATUS_SUCCEEDED: - self.info_msg(f"Goal failed with status code: {status}") + self.info_msg(f'Goal failed with status code: {status}') return False - self.info_msg("Goal succeeded!") + self.info_msg('Goal succeeded!') return True def isInKeepout(self, x, y): @@ -228,50 +228,50 @@ def isInKeepout(self, x, y): # Checks that (x, y) position does not belong to a keepout zone. def checkKeepout(self, x, y): if not self.mask_received: - self.warn_msg("Filter mask was not received") + self.warn_msg('Filter mask was not received') elif self.isInKeepout(x, y): self.filter_test_result = False - self.error_msg(f"Pose ({x}, {y}) belongs to keepout zone") + self.error_msg(f'Pose ({x}, {y}) belongs to keepout zone') return False return True # Checks that currently received speed_limit is equal to the it-th item - # of expected speed "limits" array. - # If so, sets it-th item of permissive array "limit_passed" to be true. + # of expected speed 'limits' array. + # If so, sets it-th item of permissive array 'limit_passed' to be true. # Otherwise it will be remained to be false. # Also verifies that speed limit messages received no more than N-times - # (where N - is the length of "limits" array), - # otherwise sets overall "filter_test_result" to be false. + # (where N - is the length of 'limits' array), + # otherwise sets overall 'filter_test_result' to be false. def checkSpeed(self, it, speed_limit): if it >= len(self.limits): - self.error_msg("Got excess speed limit") + self.error_msg('Got excess speed limit') self.filter_test_result = False return if speed_limit == self.limits[it]: self.limit_passed[it] = True else: self.error_msg( - "Incorrect speed limit received: " + 'Incorrect speed limit received: ' + str(speed_limit) - + ", but should be: " + + ', but should be: ' + str(self.limits[it]) ) def poseCallback(self, msg): - self.info_msg("Received amcl_pose") + self.info_msg('Received amcl_pose') self.current_pose = msg.pose.pose self.initial_pose_received = True if self.test_type == TestType.KEEPOUT: if not self.checkKeepout( msg.pose.pose.position.x, msg.pose.pose.position.y ): - self.error_msg("Robot goes into keepout zone") + self.error_msg('Robot goes into keepout zone') def planCallback(self, msg): - self.info_msg("Received plan") + self.info_msg('Received plan') for pose in msg.poses: if not self.checkKeepout(pose.pose.position.x, pose.pose.position.y): - self.error_msg("Path plan intersects with keepout zone") + self.error_msg('Path plan intersects with keepout zone') return def clearingEndpointsCallback(self, msg): @@ -287,17 +287,17 @@ def voxelUnknownCallback(self, msg): self.voxel_unknown_received = True def dwbCostCloudCallback(self, msg): - self.info_msg("Received cost_cloud points") + self.info_msg('Received cost_cloud points') if len(msg.data) > 0: self.cost_cloud_received = True def speedLimitCallback(self, msg): - self.info_msg(f"Received speed limit: {msg.speed_limit}") + self.info_msg(f'Received speed limit: {msg.speed_limit}') self.checkSpeed(self.speed_it, msg.speed_limit) self.speed_it += 1 def maskCallback(self, msg): - self.info_msg("Received filter mask") + self.info_msg('Received filter mask') self.filter_mask = FilterMask(msg) self.mask_received = True @@ -305,10 +305,10 @@ def wait_for_filter_mask(self, timeout): start_time = time.time() while not self.mask_received: - self.info_msg("Waiting for filter mask to be received ...") + self.info_msg('Waiting for filter mask to be received ...') rclpy.spin_once(self, timeout_sec=1) if (time.time() - start_time) > timeout: - self.error_msg("Time out to waiting filter mask") + self.error_msg('Time out to waiting filter mask') return False return True @@ -320,14 +320,14 @@ def wait_for_pointcloud_subscribers(self, timeout): or not self.clearing_endpoints_received ): self.info_msg( - "Waiting for voxel_marked_cloud/voxel_unknown_cloud/\ - clearing_endpoints msg to be received ..." + 'Waiting for voxel_marked_cloud/voxel_unknown_cloud/\ + clearing_endpoints msg to be received ...' ) rclpy.spin_once(self, timeout_sec=1) if (time.time() - start_time) > timeout: self.error_msg( - "Time out to waiting for voxel_marked_cloud/voxel_unknown_cloud/\ - clearing_endpoints msgs" + 'Time out to waiting for voxel_marked_cloud/voxel_unknown_cloud/\ + clearing_endpoints msgs' ) return False return True @@ -340,104 +340,104 @@ def reachesGoal(self, timeout, distance): rclpy.spin_once(self, timeout_sec=1) if self.distanceFromGoal() < distance: goalReached = True - self.info_msg("*** GOAL REACHED ***") + self.info_msg('*** GOAL REACHED ***') return True elif timeout is not None: if (time.time() - start_time) > timeout: - self.error_msg("Robot timed out reaching its goal!") + self.error_msg('Robot timed out reaching its goal!') return False def distanceFromGoal(self): d_x = self.current_pose.position.x - self.goal_pose.position.x d_y = self.current_pose.position.y - self.goal_pose.position.y distance = math.sqrt(d_x * d_x + d_y * d_y) - self.info_msg(f"Distance from goal is: {distance}") + self.info_msg(f'Distance from goal is: {distance}') return distance def wait_for_node_active(self, node_name: str): # Waits for the node within the tester namespace to become active - self.info_msg(f"Waiting for {node_name} to become active") - node_service = f"{node_name}/get_state" + self.info_msg(f'Waiting for {node_name} to become active') + node_service = f'{node_name}/get_state' state_client = self.create_client(GetState, node_service) while not state_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{node_service} service not available, waiting...") + self.info_msg(f'{node_service} service not available, waiting...') req = GetState.Request() # empty request - state = "UNKNOWN" - while state != "active": - self.info_msg(f"Getting {node_name} state...") + state = 'UNKNOWN' + while state != 'active': + self.info_msg(f'Getting {node_name} state...') future = state_client.call_async(req) rclpy.spin_until_future_complete(self, future) if future.result() is not None: state = future.result().current_state.label - self.info_msg(f"Result of get_state: {state}") + self.info_msg(f'Result of get_state: {state}') else: self.error_msg( - "Exception while calling service: %r" % future.exception() + 'Exception while calling service: %r' % future.exception() ) time.sleep(5) def shutdown(self): - self.info_msg("Shutting down") + self.info_msg('Shutting down') self.action_client.destroy() - transition_service = "lifecycle_manager_navigation/manage_nodes" + transition_service = 'lifecycle_manager_navigation/manage_nodes' mgr_client = self.create_client(ManageLifecycleNodes, transition_service) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{transition_service} service not available, waiting...") + self.info_msg(f'{transition_service} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().SHUTDOWN future = mgr_client.call_async(req) try: - self.info_msg("Shutting down navigation lifecycle manager...") + self.info_msg('Shutting down navigation lifecycle manager...') rclpy.spin_until_future_complete(self, future) future.result() - self.info_msg("Shutting down navigation lifecycle manager complete.") + self.info_msg('Shutting down navigation lifecycle manager complete.') except Exception as e: # noqa: B902 - self.error_msg(f"Service call failed {e!r}") - transition_service = "lifecycle_manager_localization/manage_nodes" + self.error_msg(f'Service call failed {e!r}') + transition_service = 'lifecycle_manager_localization/manage_nodes' mgr_client = self.create_client(ManageLifecycleNodes, transition_service) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{transition_service} service not available, waiting...") + self.info_msg(f'{transition_service} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().SHUTDOWN future = mgr_client.call_async(req) try: - self.info_msg("Shutting down localization lifecycle manager...") + self.info_msg('Shutting down localization lifecycle manager...') rclpy.spin_until_future_complete(self, future) future.result() - self.info_msg("Shutting down localization lifecycle manager complete") + self.info_msg('Shutting down localization lifecycle manager complete') except Exception as e: # noqa: B902 - self.error_msg(f"Service call failed {e!r}") + self.error_msg(f'Service call failed {e!r}') def wait_for_initial_pose(self): self.initial_pose_received = False while not self.initial_pose_received: - self.info_msg("Setting initial pose") + self.info_msg('Setting initial pose') self.setInitialPose() - self.info_msg("Waiting for amcl_pose to be received") + self.info_msg('Waiting for amcl_pose to be received') rclpy.spin_once(self, timeout_sec=1) def test_RobotMovesToGoal(robot_tester): - robot_tester.info_msg("Setting goal pose") + robot_tester.info_msg('Setting goal pose') robot_tester.publishGoalPose() - robot_tester.info_msg("Waiting 60 seconds for robot to reach goal") + robot_tester.info_msg('Waiting 60 seconds for robot to reach goal') return robot_tester.reachesGoal(timeout=60, distance=0.5) # Tests that all received speed limits are correct: -# If overall "filter_test_result" is true -# checks that all items in "limit_passed" permissive array are also true. +# If overall 'filter_test_result' is true +# checks that all items in 'limit_passed' permissive array are also true. # In other words, it verifies that all speed limits are received -# exactly (by count and values) as expected by "limits" array. +# exactly (by count and values) as expected by 'limits' array. def test_SpeedLimitsAllCorrect(robot_tester): if not robot_tester.filter_test_result: return False for passed in robot_tester.limit_passed: if not passed: - robot_tester.error_msg("Did not meet one of the speed limit") + robot_tester.error_msg('Did not meet one of the speed limit') return False return True @@ -446,9 +446,9 @@ def run_all_tests(robot_tester): # set transforms to use_sim_time result = True if result: - robot_tester.wait_for_node_active("amcl") + robot_tester.wait_for_node_active('amcl') robot_tester.wait_for_initial_pose() - robot_tester.wait_for_node_active("bt_navigator") + robot_tester.wait_for_node_active('bt_navigator') result = robot_tester.wait_for_filter_mask(10) if result: result = robot_tester.runNavigateAction() @@ -469,9 +469,9 @@ def run_all_tests(robot_tester): # Add more tests here if desired if result: - robot_tester.info_msg("Test PASSED") + robot_tester.info_msg('Test PASSED') else: - robot_tester.error_msg("Test FAILED") + robot_tester.error_msg('Test FAILED') return result @@ -494,7 +494,7 @@ def get_tester(args): type_str = args.type init_x, init_y, final_x, final_y = args.robot[0] test_type = TestType.KEEPOUT # Default value - if type_str == "speed": + if type_str == 'speed': test_type = TestType.SPEED tester = NavTester( @@ -503,15 +503,15 @@ def get_tester(args): goal_pose=fwd_pose(float(final_x), float(final_y)), ) tester.info_msg( - "Starting tester, robot going from " + 'Starting tester, robot going from ' + init_x - + ", " + + ', ' + init_y - + " to " + + ' to ' + final_x - + ", " + + ', ' + final_y - + "." + + '.' ) return tester @@ -519,24 +519,24 @@ def get_tester(args): def main(argv=sys.argv[1:]): # The robot(s) positions from the input arguments parser = argparse.ArgumentParser( - description="System-level costmap filters tester node" + description='System-level costmap filters tester node' ) parser.add_argument( - "-t", - "--type", + '-t', + '--type', type=str, - action="store", - dest="type", - help="Type of costmap filter being tested.", + action='store', + dest='type', + help='Type of costmap filter being tested.', ) group = parser.add_mutually_exclusive_group(required=True) group.add_argument( - "-r", - "--robot", - action="append", + '-r', + '--robot', + action='append', nargs=4, - metavar=("init_x", "init_y", "final_x", "final_y"), - help="The robot starting and final positions.", + metavar=('init_x', 'init_y', 'final_x', 'final_y'), + help='The robot starting and final positions.', ) args, unknown = parser.parse_known_args() @@ -553,15 +553,15 @@ def main(argv=sys.argv[1:]): # stop and shutdown the nav stack to exit cleanly tester.shutdown() - tester.info_msg("Done Shutting Down.") + tester.info_msg('Done Shutting Down.') if not passed: - tester.info_msg("Exiting failed") + tester.info_msg('Exiting failed') exit(1) else: - tester.info_msg("Exiting passed") + tester.info_msg('Exiting passed') exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_system_tests/src/error_codes/test_error_codes.py b/nav2_system_tests/src/error_codes/test_error_codes.py index d8b8f1f927e..f023bbb27c1 100755 --- a/nav2_system_tests/src/error_codes/test_error_codes.py +++ b/nav2_system_tests/src/error_codes/test_error_codes.py @@ -35,7 +35,7 @@ def main(argv=sys.argv[1:]): # Set our demo's initial pose initial_pose = PoseStamped() - initial_pose.header.frame_id = "map" + initial_pose.header.frame_id = 'map' initial_pose.header.stamp = navigator.get_clock().now().to_msg() # Initial pose @@ -57,15 +57,15 @@ def main(argv=sys.argv[1:]): path.poses.append(goal_pose) path.poses.append(goal_pose1) - navigator._waitForNodeToActivate("controller_server") + navigator._waitForNodeToActivate('controller_server') follow_path = { - "unknown": FollowPath.Result().UNKNOWN, - "invalid_controller": FollowPath.Result().INVALID_CONTROLLER, - "tf_error": FollowPath.Result().TF_ERROR, - "invalid_path": FollowPath.Result().INVALID_PATH, - "patience_exceeded": FollowPath.Result().PATIENCE_EXCEEDED, - "failed_to_make_progress": FollowPath.Result().FAILED_TO_MAKE_PROGRESS, - "no_valid_control": FollowPath.Result().NO_VALID_CONTROL, + 'unknown': FollowPath.Result().UNKNOWN, + 'invalid_controller': FollowPath.Result().INVALID_CONTROLLER, + 'tf_error': FollowPath.Result().TF_ERROR, + 'invalid_path': FollowPath.Result().INVALID_PATH, + 'patience_exceeded': FollowPath.Result().PATIENCE_EXCEEDED, + 'failed_to_make_progress': FollowPath.Result().FAILED_TO_MAKE_PROGRESS, + 'no_valid_control': FollowPath.Result().NO_VALID_CONTROL, } for controller, error_code in follow_path.items(): @@ -77,13 +77,13 @@ def main(argv=sys.argv[1:]): assert ( navigator.result_future.result().result.error_code == error_code - ), "Follow path error code does not match" + ), 'Follow path error code does not match' else: - assert False, "Follow path was rejected" + assert False, 'Follow path was rejected' goal_pose = PoseStamped() - goal_pose.header.frame_id = "map" + goal_pose.header.frame_id = 'map' goal_pose.header.stamp = navigator.get_clock().now().to_msg() # Check compute path to pose error codes @@ -92,51 +92,51 @@ def main(argv=sys.argv[1:]): goal_pose.pose.orientation.z = 0.0 goal_pose.pose.orientation.w = 1.0 - navigator._waitForNodeToActivate("planner_server") + navigator._waitForNodeToActivate('planner_server') compute_path_to_pose = { - "unknown": ComputePathToPose.Result().UNKNOWN, - "invalid_planner": ComputePathToPose.Result().INVALID_PLANNER, - "tf_error": ComputePathToPose.Result().TF_ERROR, - "start_outside_map": ComputePathToPose.Result().START_OUTSIDE_MAP, - "goal_outside_map": ComputePathToPose.Result().GOAL_OUTSIDE_MAP, - "start_occupied": ComputePathToPose.Result().START_OCCUPIED, - "goal_occupied": ComputePathToPose.Result().GOAL_OCCUPIED, - "timeout": ComputePathToPose.Result().TIMEOUT, - "no_valid_path": ComputePathToPose.Result().NO_VALID_PATH, + 'unknown': ComputePathToPose.Result().UNKNOWN, + 'invalid_planner': ComputePathToPose.Result().INVALID_PLANNER, + 'tf_error': ComputePathToPose.Result().TF_ERROR, + 'start_outside_map': ComputePathToPose.Result().START_OUTSIDE_MAP, + 'goal_outside_map': ComputePathToPose.Result().GOAL_OUTSIDE_MAP, + 'start_occupied': ComputePathToPose.Result().START_OCCUPIED, + 'goal_occupied': ComputePathToPose.Result().GOAL_OCCUPIED, + 'timeout': ComputePathToPose.Result().TIMEOUT, + 'no_valid_path': ComputePathToPose.Result().NO_VALID_PATH, } for planner, error_code in compute_path_to_pose.items(): result = navigator._getPathImpl(initial_pose, goal_pose, planner) assert ( result.error_code == error_code - ), "Compute path to pose error does not match" + ), 'Compute path to pose error does not match' # Check compute path through error codes goal_pose1 = goal_pose goal_poses = [goal_pose, goal_pose1] compute_path_through_poses = { - "unknown": ComputePathThroughPoses.Result().UNKNOWN, - "invalid_planner": ComputePathThroughPoses.Result().INVALID_PLANNER, - "tf_error": ComputePathThroughPoses.Result().TF_ERROR, - "start_outside_map": ComputePathThroughPoses.Result().START_OUTSIDE_MAP, - "goal_outside_map": ComputePathThroughPoses.Result().GOAL_OUTSIDE_MAP, - "start_occupied": ComputePathThroughPoses.Result().START_OCCUPIED, - "goal_occupied": ComputePathThroughPoses.Result().GOAL_OCCUPIED, - "timeout": ComputePathThroughPoses.Result().TIMEOUT, - "no_valid_path": ComputePathThroughPoses.Result().NO_VALID_PATH, - "no_viapoints_given": ComputePathThroughPoses.Result().NO_VIAPOINTS_GIVEN, + 'unknown': ComputePathThroughPoses.Result().UNKNOWN, + 'invalid_planner': ComputePathThroughPoses.Result().INVALID_PLANNER, + 'tf_error': ComputePathThroughPoses.Result().TF_ERROR, + 'start_outside_map': ComputePathThroughPoses.Result().START_OUTSIDE_MAP, + 'goal_outside_map': ComputePathThroughPoses.Result().GOAL_OUTSIDE_MAP, + 'start_occupied': ComputePathThroughPoses.Result().START_OCCUPIED, + 'goal_occupied': ComputePathThroughPoses.Result().GOAL_OCCUPIED, + 'timeout': ComputePathThroughPoses.Result().TIMEOUT, + 'no_valid_path': ComputePathThroughPoses.Result().NO_VALID_PATH, + 'no_viapoints_given': ComputePathThroughPoses.Result().NO_VIAPOINTS_GIVEN, } for planner, error_code in compute_path_through_poses.items(): result = navigator._getPathThroughPosesImpl(initial_pose, goal_poses, planner) assert ( result.error_code == error_code - ), "Compute path through pose error does not match" + ), 'Compute path through pose error does not match' # Check compute path to pose error codes pose = PoseStamped() - pose.header.frame_id = "map" + pose.header.frame_id = 'map' pose.header.stamp = navigator.get_clock().now().to_msg() pose.pose.position.x = -1.00 @@ -151,24 +151,24 @@ def main(argv=sys.argv[1:]): a_path.poses.append(pose) a_path.poses.append(pose1) - navigator._waitForNodeToActivate("smoother_server") + navigator._waitForNodeToActivate('smoother_server') smoother = { - "invalid_smoother": SmoothPath.Result().INVALID_SMOOTHER, - "unknown": SmoothPath.Result().UNKNOWN, - "timeout": SmoothPath.Result().TIMEOUT, - "smoothed_path_in_collision": SmoothPath.Result().SMOOTHED_PATH_IN_COLLISION, - "failed_to_smooth_path": SmoothPath.Result().FAILED_TO_SMOOTH_PATH, - "invalid_path": SmoothPath.Result().INVALID_PATH, + 'invalid_smoother': SmoothPath.Result().INVALID_SMOOTHER, + 'unknown': SmoothPath.Result().UNKNOWN, + 'timeout': SmoothPath.Result().TIMEOUT, + 'smoothed_path_in_collision': SmoothPath.Result().SMOOTHED_PATH_IN_COLLISION, + 'failed_to_smooth_path': SmoothPath.Result().FAILED_TO_SMOOTH_PATH, + 'invalid_path': SmoothPath.Result().INVALID_PATH, } for smoother, error_code in smoother.items(): result = navigator._smoothPathImpl(a_path, smoother) - assert result.error_code == error_code, "Smoother error does not match" + assert result.error_code == error_code, 'Smoother error does not match' navigator.lifecycleShutdown() rclpy.shutdown() exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_system_tests/src/error_codes/test_error_codes_launch.py b/nav2_system_tests/src/error_codes/test_error_codes_launch.py index 6347ba08131..98a33d38d63 100755 --- a/nav2_system_tests/src/error_codes/test_error_codes_launch.py +++ b/nav2_system_tests/src/error_codes/test_error_codes_launch.py @@ -25,58 +25,58 @@ def generate_launch_description(): - params_file = os.path.join(os.getenv("TEST_DIR"), "error_code_param.yaml") + params_file = os.path.join(os.getenv('TEST_DIR'), 'error_code_param.yaml') - remappings = [("/tf", "tf"), ("/tf_static", "tf_static")] + remappings = [('/tf', 'tf'), ('/tf_static', 'tf_static')] - lifecycle_nodes = ["controller_server", "planner_server", "smoother_server"] + lifecycle_nodes = ['controller_server', 'planner_server', 'smoother_server'] load_nodes = GroupAction( actions=[ Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "map", "odom"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'map', 'odom'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "odom", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'odom', 'base_link'], ), Node( - package="nav2_controller", - executable="controller_server", - output="screen", + package='nav2_controller', + executable='controller_server', + output='screen', respawn_delay=2.0, parameters=[params_file], - remappings=remappings + [("cmd_vel", "cmd_vel_nav")], + remappings=remappings + [('cmd_vel', 'cmd_vel_nav')], ), Node( - package="nav2_planner", - executable="planner_server", - name="planner_server", - output="screen", + package='nav2_planner', + executable='planner_server', + name='planner_server', + output='screen', respawn_delay=2.0, parameters=[params_file], remappings=remappings, ), Node( - package="nav2_smoother", - executable="smoother_server", - name="smoother_server", - output="screen", + package='nav2_smoother', + executable='smoother_server', + name='smoother_server', + output='screen', respawn_delay=2.0, parameters=[params_file], remappings=remappings, ), Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager_navigation", - output="screen", - parameters=[{"autostart": True}, {"node_names": lifecycle_nodes}], + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager_navigation', + output='screen', + parameters=[{'autostart': True}, {'node_names': lifecycle_nodes}], ), ] ) @@ -91,9 +91,9 @@ def main(argv=sys.argv[1:]): ld = generate_launch_description() test_error_codes_action = ExecuteProcess( - cmd=[os.path.join(os.getenv("TEST_DIR"), "test_error_codes.py")], - name="test_error_codes", - output="screen", + cmd=[os.path.join(os.getenv('TEST_DIR'), 'test_error_codes.py')], + name='test_error_codes', + output='screen', ) lts = LaunchTestService() @@ -103,5 +103,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/gps_navigation/dual_ekf_navsat.launch.py b/nav2_system_tests/src/gps_navigation/dual_ekf_navsat.launch.py index 6b0dd5c2b0b..8cc64ec69e1 100644 --- a/nav2_system_tests/src/gps_navigation/dual_ekf_navsat.launch.py +++ b/nav2_system_tests/src/gps_navigation/dual_ekf_navsat.launch.py @@ -20,44 +20,44 @@ def generate_launch_description(): launch_dir = os.path.dirname(os.path.realpath(__file__)) - params_file = os.path.join(launch_dir, "dual_ekf_navsat_params.yaml") - os.environ["FILE_PATH"] = str(launch_dir) + params_file = os.path.join(launch_dir, 'dual_ekf_navsat_params.yaml') + os.environ['FILE_PATH'] = str(launch_dir) return LaunchDescription( [ launch.actions.DeclareLaunchArgument( - "output_final_position", default_value="false" + 'output_final_position', default_value='false' ), launch.actions.DeclareLaunchArgument( - "output_location", default_value="~/dual_ekf_navsat_example_debug.txt" + 'output_location', default_value='~/dual_ekf_navsat_example_debug.txt' ), launch_ros.actions.Node( - package="robot_localization", - executable="ekf_node", - name="ekf_filter_node_odom", - output="screen", - parameters=[params_file, {"use_sim_time": True}], - remappings=[("odometry/filtered", "odometry/local")], + package='robot_localization', + executable='ekf_node', + name='ekf_filter_node_odom', + output='screen', + parameters=[params_file, {'use_sim_time': True}], + remappings=[('odometry/filtered', 'odometry/local')], ), launch_ros.actions.Node( - package="robot_localization", - executable="ekf_node", - name="ekf_filter_node_map", - output="screen", - parameters=[params_file, {"use_sim_time": True}], - remappings=[("odometry/filtered", "odometry/global")], + package='robot_localization', + executable='ekf_node', + name='ekf_filter_node_map', + output='screen', + parameters=[params_file, {'use_sim_time': True}], + remappings=[('odometry/filtered', 'odometry/global')], ), launch_ros.actions.Node( - package="robot_localization", - executable="navsat_transform_node", - name="navsat_transform", - output="screen", - parameters=[params_file, {"use_sim_time": True}], + package='robot_localization', + executable='navsat_transform_node', + name='navsat_transform', + output='screen', + parameters=[params_file, {'use_sim_time': True}], remappings=[ - ("imu/data", "imu/data"), - ("gps/fix", "gps/fix"), - ("gps/filtered", "gps/filtered"), - ("odometry/gps", "odometry/gps"), - ("odometry/filtered", "odometry/global"), + ('imu/data', 'imu/data'), + ('gps/fix', 'gps/fix'), + ('gps/filtered', 'gps/filtered'), + ('odometry/gps', 'odometry/gps'), + ('odometry/filtered', 'odometry/global'), ], ), ] diff --git a/nav2_system_tests/src/gps_navigation/test_case_py.launch.py b/nav2_system_tests/src/gps_navigation/test_case_py.launch.py index cd90fdb6208..db949b7756e 100755 --- a/nav2_system_tests/src/gps_navigation/test_case_py.launch.py +++ b/nav2_system_tests/src/gps_navigation/test_case_py.launch.py @@ -33,79 +33,79 @@ def generate_launch_description(): - world = os.getenv("TEST_WORLD") + world = os.getenv('TEST_WORLD') launch_dir = os.path.dirname(os.path.realpath(__file__)) - params_file = os.path.join(launch_dir, "nav2_no_map_params.yaml") - bringup_dir = get_package_share_directory("nav2_bringup") + params_file = os.path.join(launch_dir, 'nav2_no_map_params.yaml') + bringup_dir = get_package_share_directory('nav2_bringup') configured_params = RewrittenYaml( - source_file=params_file, root_key="", param_rewrites="", convert_types=True + source_file=params_file, root_key='', param_rewrites='', convert_types=True ) return LaunchDescription( [ - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), # Launch gazebo server for simulation ExecuteProcess( cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "--minimal_comms", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '--minimal_comms', world, ], - output="screen", + output='screen', ), # TODO(orduno) Launch the robot state publisher instead # using a local copy of TB3 urdf file Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", + package='tf2_ros', + executable='static_transform_publisher', + output='screen', arguments=[ - "-0.32", - "0", - "0.068", - "0", - "0", - "0", - "base_link", - "imu_link", + '-0.32', + '0', + '0.068', + '0', + '0', + '0', + 'base_link', + 'imu_link', ], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "gps_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'gps_link'], ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "navigation_launch.py") + os.path.join(bringup_dir, 'launch', 'navigation_launch.py') ), launch_arguments={ - "use_sim_time": "True", - "params_file": configured_params, - "autostart": "True", + 'use_sim_time': 'True', + 'params_file': configured_params, + 'autostart': 'True', }.items(), ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(launch_dir, "dual_ekf_navsat.launch.py") + os.path.join(launch_dir, 'dual_ekf_navsat.launch.py') ), ), ] @@ -116,9 +116,9 @@ def main(argv=sys.argv[1:]): ld = generate_launch_description() test1_action = ExecuteProcess( - cmd=[os.path.join(os.getenv("TEST_DIR"), "tester.py")], - name="tester_node", - output="screen", + cmd=[os.path.join(os.getenv('TEST_DIR'), 'tester.py')], + name='tester_node', + output='screen', ) lts = LaunchTestService() @@ -128,5 +128,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/gps_navigation/tester.py b/nav2_system_tests/src/gps_navigation/tester.py index 526ed83b64b..5e765981ab2 100755 --- a/nav2_system_tests/src/gps_navigation/tester.py +++ b/nav2_system_tests/src/gps_navigation/tester.py @@ -31,16 +31,16 @@ class GpsWaypointFollowerTest(Node): def __init__(self): - super().__init__(node_name="nav2_gps_waypoint_tester", namespace="") + super().__init__(node_name='nav2_gps_waypoint_tester', namespace='') self.waypoints = None self.action_client = ActionClient( - self, FollowGPSWaypoints, "follow_gps_waypoints" + self, FollowGPSWaypoints, 'follow_gps_waypoints' ) self.goal_handle = None self.action_result = None self.param_cli = self.create_client( - SetParameters, "/waypoint_follower/set_parameters" + SetParameters, '/waypoint_follower/set_parameters' ) def setWaypoints(self, waypoints): @@ -54,7 +54,7 @@ def setWaypoints(self, waypoints): def run(self, block, cancel): # if not self.waypoints: - # rclpy.error_msg("Did not set valid waypoints before running test!") + # rclpy.error_msg('Did not set valid waypoints before running test!') # return False while not self.action_client.wait_for_server(timeout_sec=1.0): @@ -65,19 +65,19 @@ def run(self, block, cancel): action_request = FollowGPSWaypoints.Goal() action_request.gps_poses = self.waypoints - self.info_msg("Sending goal request...") + self.info_msg('Sending goal request...') send_goal_future = self.action_client.send_goal_async(action_request) try: rclpy.spin_until_future_complete(self, send_goal_future) self.goal_handle = send_goal_future.result() except Exception as e: # noqa: B902 - self.error_msg(f"Service call failed {e!r}") + self.error_msg(f'Service call failed {e!r}') if not self.goal_handle.accepted: - self.error_msg("Goal rejected") + self.error_msg('Goal rejected') return False - self.info_msg("Goal accepted") + self.info_msg('Goal accepted') if not block: return True @@ -93,39 +93,39 @@ def run(self, block, cancel): result = get_result_future.result().result self.action_result = result except Exception as e: # noqa: B902 - self.error_msg(f"Service call failed {e!r}") + self.error_msg(f'Service call failed {e!r}') if status != GoalStatus.STATUS_SUCCEEDED: - self.info_msg(f"Goal failed with status code: {status}") + self.info_msg(f'Goal failed with status code: {status}') return False if len(result.missed_waypoints) > 0: self.info_msg( - "Goal failed to process all waypoints," - " missed {0} wps.".format(len(result.missed_waypoints)) + 'Goal failed to process all waypoints,' + ' missed {0} wps.'.format(len(result.missed_waypoints)) ) return False - self.info_msg("Goal succeeded!") + self.info_msg('Goal succeeded!') return True def setStopFailureParam(self, value): req = SetParameters.Request() req.parameters = [ - Parameter("stop_on_failure", Parameter.Type.BOOL, value).to_parameter_msg() + Parameter('stop_on_failure', Parameter.Type.BOOL, value).to_parameter_msg() ] future = self.param_cli.call_async(req) rclpy.spin_until_future_complete(self, future) def shutdown(self): - self.info_msg("Shutting down") + self.info_msg('Shutting down') self.action_client.destroy() - self.info_msg("Destroyed follow_gps_waypoints action client") + self.info_msg('Destroyed follow_gps_waypoints action client') - transition_service = "lifecycle_manager_navigation/manage_nodes" + transition_service = 'lifecycle_manager_navigation/manage_nodes' mgr_client = self.create_client(ManageLifecycleNodes, transition_service) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{transition_service} service not available, waiting...") + self.info_msg(f'{transition_service} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().SHUTDOWN @@ -134,9 +134,9 @@ def shutdown(self): rclpy.spin_until_future_complete(self, future) future.result() except Exception as e: # noqa: B902 - self.error_msg(f"{transition_service} service call failed {e!r}") + self.error_msg(f'{transition_service} service call failed {e!r}') - self.info_msg(f"{transition_service} finished") + self.info_msg(f'{transition_service} finished') def cancel_goal(self): cancel_future = self.goal_handle.cancel_goal_async() @@ -212,15 +212,15 @@ def main(argv=sys.argv[1:]): result = not result test.shutdown() - test.info_msg("Done Shutting Down.") + test.info_msg('Done Shutting Down.') if not result: - test.info_msg("Exiting failed") + test.info_msg('Exiting failed') exit(1) else: - test.info_msg("Exiting passed") + test.info_msg('Exiting passed') exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_system_tests/src/localization/test_localization_launch.py b/nav2_system_tests/src/localization/test_localization_launch.py index bd687f55492..d638e02c4e8 100755 --- a/nav2_system_tests/src/localization/test_localization_launch.py +++ b/nav2_system_tests/src/localization/test_localization_launch.py @@ -26,42 +26,42 @@ def main(argv=sys.argv[1:]): - mapFile = os.getenv("TEST_MAP") - testExecutable = os.getenv("TEST_EXECUTABLE") - world = os.getenv("TEST_WORLD") + mapFile = os.getenv('TEST_MAP') + testExecutable = os.getenv('TEST_EXECUTABLE') + world = os.getenv('TEST_WORLD') launch_gazebo = launch.actions.ExecuteProcess( - cmd=["gzserver", "-s", "libgazebo_ros_init.so", "--minimal_comms", world], - output="screen", + cmd=['gzserver', '-s', 'libgazebo_ros_init.so', '--minimal_comms', world], + output='screen', ) link_footprint = launch_ros.actions.Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ) footprint_scan = launch_ros.actions.Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ) run_map_server = launch_ros.actions.Node( - package="nav2_map_server", - executable="map_server", - name="map_server", - output="screen", - parameters=[{"yaml_filename": mapFile}], + package='nav2_map_server', + executable='map_server', + name='map_server', + output='screen', + parameters=[{'yaml_filename': mapFile}], ) run_amcl = launch_ros.actions.Node( - package="nav2_amcl", executable="amcl", output="screen" + package='nav2_amcl', executable='amcl', output='screen' ) run_lifecycle_manager = launch_ros.actions.Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager", - output="screen", - parameters=[{"node_names": ["map_server", "amcl"]}, {"autostart": True}], + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager', + output='screen', + parameters=[{'node_names': ['map_server', 'amcl']}, {'autostart': True}], ) ld = LaunchDescription( [ @@ -75,7 +75,7 @@ def main(argv=sys.argv[1:]): ) test1_action = ExecuteProcess( - cmd=[testExecutable], name="test_localization_node", output="screen" + cmd=[testExecutable], name='test_localization_node', output='screen' ) lts = LaunchTestService() @@ -85,5 +85,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/planning/test_planner_costmaps_launch.py b/nav2_system_tests/src/planning/test_planner_costmaps_launch.py index 92f2e266ebf..09bd3d34eee 100755 --- a/nav2_system_tests/src/planning/test_planner_costmaps_launch.py +++ b/nav2_system_tests/src/planning/test_planner_costmaps_launch.py @@ -25,14 +25,14 @@ def main(argv=sys.argv[1:]): - testExecutable = os.getenv("TEST_EXECUTABLE") + testExecutable = os.getenv('TEST_EXECUTABLE') ld = LaunchDescription([]) test1_action = ExecuteProcess( - cmd=[testExecutable, "--ros-args -p use_sim_time:=True"], - name="test_planner_costmaps_node", - output="screen", + cmd=[testExecutable, '--ros-args -p use_sim_time:=True'], + name='test_planner_costmaps_node', + output='screen', ) lts = LaunchTestService() @@ -42,5 +42,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/planning/test_planner_random_launch.py b/nav2_system_tests/src/planning/test_planner_random_launch.py index c420b7e212e..a7747e513ab 100755 --- a/nav2_system_tests/src/planning/test_planner_random_launch.py +++ b/nav2_system_tests/src/planning/test_planner_random_launch.py @@ -25,14 +25,14 @@ def main(argv=sys.argv[1:]): - testExecutable = os.getenv("TEST_EXECUTABLE") + testExecutable = os.getenv('TEST_EXECUTABLE') ld = LaunchDescription([]) test1_action = ExecuteProcess( - cmd=[testExecutable, "--ros-args -p use_sim_time:=True"], - name="test_planner_random_node", - output="screen", + cmd=[testExecutable, '--ros-args -p use_sim_time:=True'], + name='test_planner_random_node', + output='screen', ) lts = LaunchTestService() @@ -42,5 +42,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/system/nav_through_poses_tester_node.py b/nav2_system_tests/src/system/nav_through_poses_tester_node.py index 964ce663838..5e587ad8fa9 100755 --- a/nav2_system_tests/src/system/nav_through_poses_tester_node.py +++ b/nav2_system_tests/src/system/nav_through_poses_tester_node.py @@ -37,10 +37,10 @@ class NavTester(Node): - def __init__(self, initial_pose: Pose, goal_pose: Pose, namespace: str = ""): - super().__init__(node_name="nav2_tester", namespace=namespace) + def __init__(self, initial_pose: Pose, goal_pose: Pose, namespace: str = ''): + super().__init__(node_name='nav2_tester', namespace=namespace) self.initial_pose_pub = self.create_publisher( - PoseWithCovarianceStamped, "initialpose", 10 + PoseWithCovarianceStamped, 'initialpose', 10 ) pose_qos = QoSProfile( @@ -51,35 +51,35 @@ def __init__(self, initial_pose: Pose, goal_pose: Pose, namespace: str = ""): ) self.model_pose_sub = self.create_subscription( - PoseWithCovarianceStamped, "amcl_pose", self.poseCallback, pose_qos + PoseWithCovarianceStamped, 'amcl_pose', self.poseCallback, pose_qos ) self.initial_pose_received = False self.initial_pose = initial_pose self.goal_pose = goal_pose self.action_client = ActionClient( - self, NavigateThroughPoses, "navigate_through_poses" + self, NavigateThroughPoses, 'navigate_through_poses' ) def info_msg(self, msg: str): - self.get_logger().info("\033[1;37;44m" + msg + "\033[0m") + self.get_logger().info('\033[1;37;44m' + msg + '\033[0m') def warn_msg(self, msg: str): - self.get_logger().warn("\033[1;37;43m" + msg + "\033[0m") + self.get_logger().warn('\033[1;37;43m' + msg + '\033[0m') def error_msg(self, msg: str): - self.get_logger().error("\033[1;37;41m" + msg + "\033[0m") + self.get_logger().error('\033[1;37;41m' + msg + '\033[0m') def setInitialPose(self): msg = PoseWithCovarianceStamped() msg.pose.pose = self.initial_pose - msg.header.frame_id = "map" - self.info_msg("Publishing Initial Pose") + msg.header.frame_id = 'map' + self.info_msg('Publishing Initial Pose') self.initial_pose_pub.publish(msg) self.currentPose = self.initial_pose def getStampedPoseMsg(self, pose: Pose): msg = PoseStamped() - msg.header.frame_id = "map" + msg.header.frame_id = 'map' msg.pose = pose return msg @@ -98,27 +98,27 @@ def runNavigateAction(self, goal_pose: Optional[Pose] = None): self.getStampedPoseMsg(self.goal_pose), ] - self.info_msg("Sending goal request...") + self.info_msg('Sending goal request...') send_goal_future = self.action_client.send_goal_async(goal_msg) rclpy.spin_until_future_complete(self, send_goal_future) goal_handle = send_goal_future.result() if not goal_handle.accepted: - self.error_msg("Goal rejected") + self.error_msg('Goal rejected') return False - self.info_msg("Goal accepted") + self.info_msg('Goal accepted') get_result_future = goal_handle.get_result_async() self.info_msg("Waiting for 'NavigateToPose' action to complete") rclpy.spin_until_future_complete(self, get_result_future) status = get_result_future.result().status if status != GoalStatus.STATUS_SUCCEEDED: - self.info_msg(f"Goal failed with status code: {status}") + self.info_msg(f'Goal failed with status code: {status}') return False - self.info_msg("Goal succeeded!") + self.info_msg('Goal succeeded!') return True def runFakeNavigateAction(self): @@ -131,27 +131,27 @@ def runFakeNavigateAction(self): goal_msg = NavigateThroughPoses.Goal() - self.info_msg("Sending goal request...") + self.info_msg('Sending goal request...') send_goal_future = self.action_client.send_goal_async(goal_msg) rclpy.spin_until_future_complete(self, send_goal_future) goal_handle = send_goal_future.result() if not goal_handle.accepted: - self.error_msg("Goal rejected") + self.error_msg('Goal rejected') return False - self.info_msg("Goal accepted") + self.info_msg('Goal accepted') get_result_future = goal_handle.get_result_async() self.info_msg("Waiting for 'NavigateToPose' action to complete") rclpy.spin_until_future_complete(self, get_result_future) status = get_result_future.result().status if status != GoalStatus.STATUS_SUCCEEDED: - self.info_msg(f"Goal failed with status code: {status}") + self.info_msg(f'Goal failed with status code: {status}') return False - self.info_msg("Goal succeeded!") + self.info_msg('Goal succeeded!') return True def runNavigatePreemptionAction(self, block): @@ -165,100 +165,100 @@ def runNavigatePreemptionAction(self, block): goal_msg = NavigateThroughPoses.Goal() goal_msg.poses = [self.getStampedPoseMsg(self.initial_pose)] - self.info_msg("Sending goal request...") + self.info_msg('Sending goal request...') send_goal_future = self.action_client.send_goal_async(goal_msg) rclpy.spin_until_future_complete(self, send_goal_future) goal_handle = send_goal_future.result() if not goal_handle.accepted: - self.error_msg("Goal rejected") + self.error_msg('Goal rejected') return False if not block: return True - self.info_msg("Goal accepted") + self.info_msg('Goal accepted') get_result_future = goal_handle.get_result_async() self.info_msg("Waiting for 'NavigateToPose' action to complete") rclpy.spin_until_future_complete(self, get_result_future) status = get_result_future.result().status if status != GoalStatus.STATUS_SUCCEEDED: - self.info_msg(f"Goal failed with status code: {status}") + self.info_msg(f'Goal failed with status code: {status}') return False - self.info_msg("Goal succeeded!") + self.info_msg('Goal succeeded!') return True def poseCallback(self, msg): - self.info_msg("Received amcl_pose") + self.info_msg('Received amcl_pose') self.current_pose = msg.pose.pose self.initial_pose_received = True def wait_for_node_active(self, node_name: str): # Waits for the node within the tester namespace to become active - self.info_msg(f"Waiting for {node_name} to become active") - node_service = f"{node_name}/get_state" + self.info_msg(f'Waiting for {node_name} to become active') + node_service = f'{node_name}/get_state' state_client = self.create_client(GetState, node_service) while not state_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{node_service} service not available, waiting...") + self.info_msg(f'{node_service} service not available, waiting...') req = GetState.Request() # empty request - state = "UNKNOWN" - while state != "active": - self.info_msg(f"Getting {node_name} state...") + state = 'UNKNOWN' + while state != 'active': + self.info_msg(f'Getting {node_name} state...') future = state_client.call_async(req) rclpy.spin_until_future_complete(self, future) if future.result() is not None: state = future.result().current_state.label - self.info_msg(f"Result of get_state: {state}") + self.info_msg(f'Result of get_state: {state}') else: self.error_msg( - f"Exception while calling service: {future.exception()!r}" + f'Exception while calling service: {future.exception()!r}' ) time.sleep(5) def shutdown(self): - self.info_msg("Shutting down") + self.info_msg('Shutting down') self.action_client.destroy() - transition_service = "lifecycle_manager_navigation/manage_nodes" + transition_service = 'lifecycle_manager_navigation/manage_nodes' mgr_client = self.create_client(ManageLifecycleNodes, transition_service) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{transition_service} service not available, waiting...") + self.info_msg(f'{transition_service} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().SHUTDOWN future = mgr_client.call_async(req) try: - self.info_msg("Shutting down navigation lifecycle manager...") + self.info_msg('Shutting down navigation lifecycle manager...') rclpy.spin_until_future_complete(self, future) future.result() - self.info_msg("Shutting down navigation lifecycle manager complete.") + self.info_msg('Shutting down navigation lifecycle manager complete.') except Exception as e: # noqa: B902 - self.error_msg(f"Service call failed {e!r}") - transition_service = "lifecycle_manager_localization/manage_nodes" + self.error_msg(f'Service call failed {e!r}') + transition_service = 'lifecycle_manager_localization/manage_nodes' mgr_client = self.create_client(ManageLifecycleNodes, transition_service) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{transition_service} service not available, waiting...") + self.info_msg(f'{transition_service} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().SHUTDOWN future = mgr_client.call_async(req) try: - self.info_msg("Shutting down localization lifecycle manager...") + self.info_msg('Shutting down localization lifecycle manager...') rclpy.spin_until_future_complete(self, future) future.result() - self.info_msg("Shutting down localization lifecycle manager complete") + self.info_msg('Shutting down localization lifecycle manager complete') except Exception as e: # noqa: B902 - self.error_msg(f"Service call failed {e!r}") + self.error_msg(f'Service call failed {e!r}') def wait_for_initial_pose(self): self.initial_pose_received = False while not self.initial_pose_received: - self.info_msg("Setting initial pose") + self.info_msg('Setting initial pose') self.setInitialPose() - self.info_msg("Waiting for amcl_pose to be received") + self.info_msg('Waiting for amcl_pose to be received') rclpy.spin_once(self, timeout_sec=1) @@ -266,9 +266,9 @@ def run_all_tests(robot_tester): # set transforms to use_sim_time result = True if result: - robot_tester.wait_for_node_active("amcl") + robot_tester.wait_for_node_active('amcl') robot_tester.wait_for_initial_pose() - robot_tester.wait_for_node_active("bt_navigator") + robot_tester.wait_for_node_active('bt_navigator') result = robot_tester.runNavigateAction() # Test empty navigation request result = result and not robot_tester.runFakeNavigateAction() @@ -279,9 +279,9 @@ def run_all_tests(robot_tester): # Add more tests here if desired if result: - robot_tester.info_msg("Test PASSED") + robot_tester.info_msg('Test PASSED') else: - robot_tester.error_msg("Test FAILED") + robot_tester.error_msg('Test FAILED') return result @@ -307,15 +307,15 @@ def get_testers(args): goal_pose=fwd_pose(float(final_x), float(final_y)), ) tester.info_msg( - "Starting tester, robot going from " + 'Starting tester, robot going from ' + init_x - + ", " + + ', ' + init_y - + " to " + + ' to ' + final_x - + ", " + + ', ' + final_y - + "." + + '.' ) testers.append(tester) return testers @@ -323,15 +323,15 @@ def get_testers(args): def main(argv=sys.argv[1:]): # The robot(s) positions from the input arguments - parser = argparse.ArgumentParser(description="System-level navigation tester node") + parser = argparse.ArgumentParser(description='System-level navigation tester node') group = parser.add_mutually_exclusive_group(required=True) group.add_argument( - "-r", - "--robot", - action="append", + '-r', + '--robot', + action='append', nargs=4, - metavar=("init_x", "init_y", "final_x", "final_y"), - help="The robot starting and final positions.", + metavar=('init_x', 'init_y', 'final_x', 'final_y'), + help='The robot starting and final positions.', ) args, unknown = parser.parse_known_args() @@ -353,15 +353,15 @@ def main(argv=sys.argv[1:]): # stop and shutdown the nav stack to exit cleanly tester.shutdown() - testers[0].info_msg("Done Shutting Down.") + testers[0].info_msg('Done Shutting Down.') if not passed: - testers[0].info_msg("Exiting failed") + testers[0].info_msg('Exiting failed') exit(1) else: - testers[0].info_msg("Exiting passed") + testers[0].info_msg('Exiting passed') exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_system_tests/src/system/nav_to_pose_tester_node.py b/nav2_system_tests/src/system/nav_to_pose_tester_node.py index 6fb119e980e..cbb2ac20e6b 100755 --- a/nav2_system_tests/src/system/nav_to_pose_tester_node.py +++ b/nav2_system_tests/src/system/nav_to_pose_tester_node.py @@ -38,12 +38,12 @@ class NavTester(Node): - def __init__(self, initial_pose: Pose, goal_pose: Pose, namespace: str = ""): - super().__init__(node_name="nav2_tester", namespace=namespace) + def __init__(self, initial_pose: Pose, goal_pose: Pose, namespace: str = ''): + super().__init__(node_name='nav2_tester', namespace=namespace) self.initial_pose_pub = self.create_publisher( - PoseWithCovarianceStamped, "initialpose", 10 + PoseWithCovarianceStamped, 'initialpose', 10 ) - self.goal_pub = self.create_publisher(PoseStamped, "goal_pose", 10) + self.goal_pub = self.create_publisher(PoseStamped, 'goal_pose', 10) pose_qos = QoSProfile( durability=QoSDurabilityPolicy.TRANSIENT_LOCAL, @@ -53,33 +53,33 @@ def __init__(self, initial_pose: Pose, goal_pose: Pose, namespace: str = ""): ) self.model_pose_sub = self.create_subscription( - PoseWithCovarianceStamped, "amcl_pose", self.poseCallback, pose_qos + PoseWithCovarianceStamped, 'amcl_pose', self.poseCallback, pose_qos ) self.initial_pose_received = False self.initial_pose = initial_pose self.goal_pose = goal_pose - self.action_client = ActionClient(self, NavigateToPose, "navigate_to_pose") + self.action_client = ActionClient(self, NavigateToPose, 'navigate_to_pose') def info_msg(self, msg: str): - self.get_logger().info("\033[1;37;44m" + msg + "\033[0m") + self.get_logger().info('\033[1;37;44m' + msg + '\033[0m') def warn_msg(self, msg: str): - self.get_logger().warn("\033[1;37;43m" + msg + "\033[0m") + self.get_logger().warn('\033[1;37;43m' + msg + '\033[0m') def error_msg(self, msg: str): - self.get_logger().error("\033[1;37;41m" + msg + "\033[0m") + self.get_logger().error('\033[1;37;41m' + msg + '\033[0m') def setInitialPose(self): msg = PoseWithCovarianceStamped() msg.pose.pose = self.initial_pose - msg.header.frame_id = "map" - self.info_msg("Publishing Initial Pose") + msg.header.frame_id = 'map' + self.info_msg('Publishing Initial Pose') self.initial_pose_pub.publish(msg) self.currentPose = self.initial_pose def getStampedPoseMsg(self, pose: Pose): msg = PoseStamped() - msg.header.frame_id = "map" + msg.header.frame_id = 'map' msg.pose = pose return msg @@ -97,17 +97,17 @@ def runNavigateAction(self, goal_pose: Optional[Pose] = None): goal_msg = NavigateToPose.Goal() goal_msg.pose = self.getStampedPoseMsg(self.goal_pose) - self.info_msg("Sending goal request...") + self.info_msg('Sending goal request...') send_goal_future = self.action_client.send_goal_async(goal_msg) rclpy.spin_until_future_complete(self, send_goal_future) goal_handle = send_goal_future.result() if not goal_handle.accepted: - self.error_msg("Goal rejected") + self.error_msg('Goal rejected') return False - self.info_msg("Goal accepted") + self.info_msg('Goal accepted') get_result_future = goal_handle.get_result_async() future_return = True @@ -116,17 +116,17 @@ def runNavigateAction(self, goal_pose: Optional[Pose] = None): rclpy.spin_until_future_complete(self, get_result_future) status = get_result_future.result().status if status != GoalStatus.STATUS_SUCCEEDED: - self.info_msg(f"Goal failed with status code: {status}") + self.info_msg(f'Goal failed with status code: {status}') return False if not future_return: return False - self.info_msg("Goal succeeded!") + self.info_msg('Goal succeeded!') return True def poseCallback(self, msg): - self.info_msg("Received amcl_pose") + self.info_msg('Received amcl_pose') self.current_pose = msg.pose.pose self.initial_pose_received = True @@ -138,90 +138,90 @@ def reachesGoal(self, timeout, distance): rclpy.spin_once(self, timeout_sec=1) if self.distanceFromGoal() < distance: goalReached = True - self.info_msg("*** GOAL REACHED ***") + self.info_msg('*** GOAL REACHED ***') return True elif timeout is not None: if (time.time() - start_time) > timeout: - self.error_msg("Robot timed out reaching its goal!") + self.error_msg('Robot timed out reaching its goal!') return False def distanceFromGoal(self): d_x = self.current_pose.position.x - self.goal_pose.position.x d_y = self.current_pose.position.y - self.goal_pose.position.y distance = math.sqrt(d_x * d_x + d_y * d_y) - self.info_msg(f"Distance from goal is: {distance}") + self.info_msg(f'Distance from goal is: {distance}') return distance def wait_for_node_active(self, node_name: str): # Waits for the node within the tester namespace to become active - self.info_msg(f"Waiting for {node_name} to become active") - node_service = f"{node_name}/get_state" + self.info_msg(f'Waiting for {node_name} to become active') + node_service = f'{node_name}/get_state' state_client = self.create_client(GetState, node_service) while not state_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{node_service} service not available, waiting...") + self.info_msg(f'{node_service} service not available, waiting...') req = GetState.Request() # empty request - state = "UNKNOWN" - while state != "active": - self.info_msg(f"Getting {node_name} state...") + state = 'UNKNOWN' + while state != 'active': + self.info_msg(f'Getting {node_name} state...') future = state_client.call_async(req) rclpy.spin_until_future_complete(self, future) if future.result() is not None: state = future.result().current_state.label - self.info_msg(f"Result of get_state: {state}") + self.info_msg(f'Result of get_state: {state}') else: self.error_msg( - f"Exception while calling service: {future.exception()!r}" + f'Exception while calling service: {future.exception()!r}' ) time.sleep(5) def shutdown(self): - self.info_msg("Shutting down") + self.info_msg('Shutting down') self.action_client.destroy() - transition_service = "lifecycle_manager_navigation/manage_nodes" + transition_service = 'lifecycle_manager_navigation/manage_nodes' mgr_client = self.create_client(ManageLifecycleNodes, transition_service) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{transition_service} service not available, waiting...") + self.info_msg(f'{transition_service} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().SHUTDOWN future = mgr_client.call_async(req) try: - self.info_msg("Shutting down navigation lifecycle manager...") + self.info_msg('Shutting down navigation lifecycle manager...') rclpy.spin_until_future_complete(self, future) future.result() - self.info_msg("Shutting down navigation lifecycle manager complete.") + self.info_msg('Shutting down navigation lifecycle manager complete.') except Exception as e: # noqa: B902 - self.error_msg(f"Service call failed {e!r}") - transition_service = "lifecycle_manager_localization/manage_nodes" + self.error_msg(f'Service call failed {e!r}') + transition_service = 'lifecycle_manager_localization/manage_nodes' mgr_client = self.create_client(ManageLifecycleNodes, transition_service) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{transition_service} service not available, waiting...") + self.info_msg(f'{transition_service} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().SHUTDOWN future = mgr_client.call_async(req) try: - self.info_msg("Shutting down localization lifecycle manager...") + self.info_msg('Shutting down localization lifecycle manager...') rclpy.spin_until_future_complete(self, future) future.result() - self.info_msg("Shutting down localization lifecycle manager complete") + self.info_msg('Shutting down localization lifecycle manager complete') except Exception as e: # noqa: B902 - self.error_msg(f"Service call failed {e!r}") + self.error_msg(f'Service call failed {e!r}') def wait_for_initial_pose(self): self.initial_pose_received = False while not self.initial_pose_received: - self.info_msg("Setting initial pose") + self.info_msg('Setting initial pose') self.setInitialPose() - self.info_msg("Waiting for amcl_pose to be received") + self.info_msg('Waiting for amcl_pose to be received') rclpy.spin_once(self, timeout_sec=1) def test_RobotMovesToGoal(robot_tester): - robot_tester.info_msg("Setting goal pose") + robot_tester.info_msg('Setting goal pose') robot_tester.publishGoalPose() - robot_tester.info_msg("Waiting 60 seconds for robot to reach goal") + robot_tester.info_msg('Waiting 60 seconds for robot to reach goal') return robot_tester.reachesGoal(timeout=60, distance=0.5) @@ -229,9 +229,9 @@ def run_all_tests(robot_tester): # set transforms to use_sim_time result = True if result: - robot_tester.wait_for_node_active("amcl") + robot_tester.wait_for_node_active('amcl') robot_tester.wait_for_initial_pose() - robot_tester.wait_for_node_active("bt_navigator") + robot_tester.wait_for_node_active('bt_navigator') result = robot_tester.runNavigateAction() if result: @@ -240,9 +240,9 @@ def run_all_tests(robot_tester): # Add more tests here if desired if result: - robot_tester.info_msg("Test PASSED") + robot_tester.info_msg('Test PASSED') else: - robot_tester.error_msg("Test FAILED") + robot_tester.error_msg('Test FAILED') return result @@ -270,15 +270,15 @@ def get_testers(args): goal_pose=fwd_pose(float(final_x), float(final_y)), ) tester.info_msg( - "Starting tester, robot going from " + 'Starting tester, robot going from ' + init_x - + ", " + + ', ' + init_y - + " to " + + ' to ' + final_x - + ", " + + ', ' + final_y - + "." + + '.' ) testers.append(tester) return testers @@ -292,15 +292,15 @@ def get_testers(args): goal_pose=fwd_pose(float(final_x), float(final_y)), ) tester.info_msg( - "Starting tester for " + 'Starting tester for ' + namespace - + " going from " + + ' going from ' + init_x - + ", " + + ', ' + init_y - + " to " + + ' to ' + final_x - + ", " + + ', ' + final_y ) testers.append(tester) @@ -309,9 +309,9 @@ def get_testers(args): def check_args(expect_failure: str): # Check if --expect_failure is True or False - if expect_failure != "True" and expect_failure != "False": + if expect_failure != 'True' and expect_failure != 'False': print( - "\033[1;37;41m" + " -e flag must be set to True or False only. " + "\033[0m" + '\033[1;37;41m' + ' -e flag must be set to True or False only. ' + '\033[0m' ) exit(1) else: @@ -320,25 +320,25 @@ def check_args(expect_failure: str): def main(argv=sys.argv[1:]): # The robot(s) positions from the input arguments - parser = argparse.ArgumentParser(description="System-level navigation tester node") - parser.add_argument("-e", "--expect_failure") + parser = argparse.ArgumentParser(description='System-level navigation tester node') + parser.add_argument('-e', '--expect_failure') group = parser.add_mutually_exclusive_group(required=True) group.add_argument( - "-r", - "--robot", - action="append", + '-r', + '--robot', + action='append', nargs=4, - metavar=("init_x", "init_y", "final_x", "final_y"), - help="The robot starting and final positions.", + metavar=('init_x', 'init_y', 'final_x', 'final_y'), + help='The robot starting and final positions.', ) group.add_argument( - "-rs", - "--robots", - action="append", + '-rs', + '--robots', + action='append', nargs=5, - metavar=("name", "init_x", "init_y", "final_x", "final_y"), + metavar=('name', 'init_x', 'init_y', 'final_x', 'final_y'), help="The robot's namespace and starting and final positions. " - + "Repeating the argument for multiple robots is supported.", + + 'Repeating the argument for multiple robots is supported.', ) args, unknown = parser.parse_known_args() @@ -362,15 +362,15 @@ def main(argv=sys.argv[1:]): # stop and shutdown the nav stack to exit cleanly tester.shutdown() - testers[0].info_msg("Done Shutting Down.") + testers[0].info_msg('Done Shutting Down.') if passed != expect_failure: - testers[0].info_msg("Exiting failed") + testers[0].info_msg('Exiting failed') exit(1) else: - testers[0].info_msg("Exiting passed") + testers[0].info_msg('Exiting passed') exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_system_tests/src/system/test_multi_robot_launch.py b/nav2_system_tests/src/system/test_multi_robot_launch.py index dfbb8dbd301..92f9a912dfd 100755 --- a/nav2_system_tests/src/system/test_multi_robot_launch.py +++ b/nav2_system_tests/src/system/test_multi_robot_launch.py @@ -34,43 +34,43 @@ def generate_launch_description(): - map_yaml_file = os.getenv("TEST_MAP") - world = os.getenv("TEST_WORLD") - urdf = os.getenv("TEST_URDF") - sdf = os.getenv("TEST_SDF") + map_yaml_file = os.getenv('TEST_MAP') + world = os.getenv('TEST_WORLD') + urdf = os.getenv('TEST_URDF') + sdf = os.getenv('TEST_SDF') bt_xml_file = os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - os.getenv("BT_NAVIGATOR_XML"), + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + os.getenv('BT_NAVIGATOR_XML'), ) - bringup_dir = get_package_share_directory("nav2_bringup") + bringup_dir = get_package_share_directory('nav2_bringup') robot1_params_file = os.path.join( # noqa: F841 - bringup_dir, "params/nav2_multirobot_params_1.yaml" + bringup_dir, 'params/nav2_multirobot_params_1.yaml' ) robot2_params_file = os.path.join( # noqa: F841 - bringup_dir, "params/nav2_multirobot_params_2.yaml" + bringup_dir, 'params/nav2_multirobot_params_2.yaml' ) # Names and poses of the robots robots = [ - {"name": "robot1", "x_pose": 0.0, "y_pose": 0.5, "z_pose": 0.01}, - {"name": "robot2", "x_pose": 0.0, "y_pose": -0.5, "z_pose": 0.01}, + {'name': 'robot1', 'x_pose': 0.0, 'y_pose': 0.5, 'z_pose': 0.01}, + {'name': 'robot2', 'x_pose': 0.0, 'y_pose': -0.5, 'z_pose': 0.01}, ] # Launch Gazebo server for simulation start_gazebo_cmd = ExecuteProcess( cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "-s", - "libgazebo_ros_factory.so", - "--minimal_comms", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '-s', + 'libgazebo_ros_factory.so', + '--minimal_comms', world, ], - output="screen", + output='screen', ) # Define commands for spawing the robots into Gazebo @@ -78,27 +78,27 @@ def generate_launch_description(): for robot in robots: spawn_robots_cmds.append( Node( - package="gazebo_ros", - executable="spawn_entity.py", - output="screen", + package='gazebo_ros', + executable='spawn_entity.py', + output='screen', arguments=[ - "-entity", - TextSubstitution(text=robot["name"]), - "-robot_namespace", - TextSubstitution(text=robot["name"]), - "-file", + '-entity', + TextSubstitution(text=robot['name']), + '-robot_namespace', + TextSubstitution(text=robot['name']), + '-file', TextSubstitution(text=sdf), - "-x", - TextSubstitution(text=str(robot["x_pose"])), - "-y", - TextSubstitution(text=str(robot["y_pose"])), - "-z", - TextSubstitution(text=str(robot["z_pose"])), + '-x', + TextSubstitution(text=str(robot['x_pose'])), + '-y', + TextSubstitution(text=str(robot['y_pose'])), + '-z', + TextSubstitution(text=str(robot['z_pose'])), ], ) ) - with open(urdf, "r") as infp: + with open(urdf, 'r') as infp: robot_description = infp.read() # Define commands for launching the robot state publishers @@ -106,14 +106,14 @@ def generate_launch_description(): for robot in robots: robot_state_pubs_cmds.append( Node( - package="robot_state_publisher", - executable="robot_state_publisher", - namespace=TextSubstitution(text=robot["name"]), - output="screen", + package='robot_state_publisher', + executable='robot_state_publisher', + namespace=TextSubstitution(text=robot['name']), + output='screen', parameters=[ - {"use_sim_time": True, "robot_description": robot_description} + {'use_sim_time': True, 'robot_description': robot_description} ], - remappings=[("/tf", "tf"), ("/tf_static", "tf_static")], + remappings=[('/tf', 'tf'), ('/tf_static', 'tf_static')], ) ) @@ -125,20 +125,20 @@ def generate_launch_description(): group = GroupAction( [ # Instances use the robot's name for namespace - PushROSNamespace(robot["name"]), + PushROSNamespace(robot['name']), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "bringup_launch.py") + os.path.join(bringup_dir, 'launch', 'bringup_launch.py') ), launch_arguments={ - "namespace": robot["name"], - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": params_file, - "bt_xml_file": bt_xml_file, - "autostart": "True", - "use_composition": "False", - "use_remappings": "True", + 'namespace': robot['name'], + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': params_file, + 'bt_xml_file': bt_xml_file, + 'autostart': 'True', + 'use_composition': 'False', + 'use_remappings': 'True', }.items(), ), ] @@ -147,10 +147,10 @@ def generate_launch_description(): ld = LaunchDescription() ld.add_action( - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), ) ld.add_action( - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), ) ld.add_action(start_gazebo_cmd) for spawn_robot in spawn_robots_cmds: @@ -169,24 +169,24 @@ def main(argv=sys.argv[1:]): # TODO(orduno) remove duplicated definition of robots on `generate_launch_description` test1_action = ExecuteProcess( cmd=[ - os.path.join(os.getenv("TEST_DIR"), os.getenv("TESTER")), - "-rs", - "robot1", - "0.0", - "0.5", - "1.0", - "0.5", - "-rs", - "robot2", - "0.0", - "-0.5", - "1.0", - "-0.5", - "-e", - "True", + os.path.join(os.getenv('TEST_DIR'), os.getenv('TESTER')), + '-rs', + 'robot1', + '0.0', + '0.5', + '1.0', + '0.5', + '-rs', + 'robot2', + '0.0', + '-0.5', + '1.0', + '-0.5', + '-e', + 'True', ], - name="tester_node", - output="screen", + name='tester_node', + output='screen', ) lts = LaunchTestService() @@ -196,5 +196,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/system/test_system_launch.py b/nav2_system_tests/src/system/test_system_launch.py index 833ea9230a9..5b0dd2625c0 100755 --- a/nav2_system_tests/src/system/test_system_launch.py +++ b/nav2_system_tests/src/system/test_system_launch.py @@ -36,36 +36,36 @@ def generate_launch_description(): - map_yaml_file = os.getenv("TEST_MAP") - world = os.getenv("TEST_WORLD") + map_yaml_file = os.getenv('TEST_MAP') + world = os.getenv('TEST_WORLD') bt_navigator_xml = os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - os.getenv("BT_NAVIGATOR_XML"), + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + os.getenv('BT_NAVIGATOR_XML'), ) - bringup_dir = get_package_share_directory("nav2_bringup") - params_file = os.path.join(bringup_dir, "params", "nav2_params.yaml") + bringup_dir = get_package_share_directory('nav2_bringup') + params_file = os.path.join(bringup_dir, 'params', 'nav2_params.yaml') # Replace the default parameter values for testing special features # without having multiple params_files inside the nav2 stack context = LaunchContext() param_substitutions = {} - if os.getenv("ASTAR") == "True": - param_substitutions.update({"use_astar": "True"}) + if os.getenv('ASTAR') == 'True': + param_substitutions.update({'use_astar': 'True'}) param_substitutions.update( - {"planner_server.ros__parameters.GridBased.plugin": os.getenv("PLANNER")} + {'planner_server.ros__parameters.GridBased.plugin': os.getenv('PLANNER')} ) param_substitutions.update( - {"controller_server.ros__parameters.FollowPath.plugin": os.getenv("CONTROLLER")} + {'controller_server.ros__parameters.FollowPath.plugin': os.getenv('CONTROLLER')} ) configured_params = RewrittenYaml( source_file=params_file, - root_key="", + root_key='', param_rewrites=param_substitutions, convert_types=True, ) @@ -74,46 +74,46 @@ def generate_launch_description(): return LaunchDescription( [ - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), # Launch gazebo server for simulation ExecuteProcess( cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "--minimal_comms", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '--minimal_comms', world, ], - output="screen", + output='screen', ), # TODO(orduno) Launch the robot state publisher instead # using a local copy of TB3 urdf file Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "bringup_launch.py") + os.path.join(bringup_dir, 'launch', 'bringup_launch.py') ), launch_arguments={ - "namespace": "", - "use_namespace": "False", - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": new_yaml, - "bt_xml_file": bt_navigator_xml, - "use_composition": "False", - "autostart": "True", + 'namespace': '', + 'use_namespace': 'False', + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': new_yaml, + 'bt_xml_file': bt_navigator_xml, + 'use_composition': 'False', + 'autostart': 'True', }.items(), ), ] @@ -125,17 +125,17 @@ def main(argv=sys.argv[1:]): test1_action = ExecuteProcess( cmd=[ - os.path.join(os.getenv("TEST_DIR"), os.getenv("TESTER")), - "-r", - "-2.0", - "-0.5", - "0.0", - "2.0", - "-e", - "True", + os.path.join(os.getenv('TEST_DIR'), os.getenv('TESTER')), + '-r', + '-2.0', + '-0.5', + '0.0', + '2.0', + '-e', + 'True', ], - name="tester_node", - output="screen", + name='tester_node', + output='screen', ) lts = LaunchTestService() @@ -145,5 +145,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/system/test_wrong_init_pose_launch.py b/nav2_system_tests/src/system/test_wrong_init_pose_launch.py index 74c41a3e1cb..d09cc549195 100755 --- a/nav2_system_tests/src/system/test_wrong_init_pose_launch.py +++ b/nav2_system_tests/src/system/test_wrong_init_pose_launch.py @@ -36,36 +36,36 @@ def generate_launch_description(): - map_yaml_file = os.getenv("TEST_MAP") - world = os.getenv("TEST_WORLD") + map_yaml_file = os.getenv('TEST_MAP') + world = os.getenv('TEST_WORLD') bt_navigator_xml = os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - os.getenv("BT_NAVIGATOR_XML"), + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + os.getenv('BT_NAVIGATOR_XML'), ) - bringup_dir = get_package_share_directory("nav2_bringup") - params_file = os.path.join(bringup_dir, "params", "nav2_params.yaml") + bringup_dir = get_package_share_directory('nav2_bringup') + params_file = os.path.join(bringup_dir, 'params', 'nav2_params.yaml') # Replace the default parameter values for testing special features # without having multiple params_files inside the nav2 stack context = LaunchContext() param_substitutions = {} - if os.getenv("ASTAR") == "True": - param_substitutions.update({"use_astar": "True"}) + if os.getenv('ASTAR') == 'True': + param_substitutions.update({'use_astar': 'True'}) param_substitutions.update( - {"planner_server.ros__parameters.GridBased.plugin": os.getenv("PLANNER")} + {'planner_server.ros__parameters.GridBased.plugin': os.getenv('PLANNER')} ) param_substitutions.update( - {"controller_server.ros__parameters.FollowPath.plugin": os.getenv("CONTROLLER")} + {'controller_server.ros__parameters.FollowPath.plugin': os.getenv('CONTROLLER')} ) configured_params = RewrittenYaml( source_file=params_file, - root_key="", + root_key='', param_rewrites=param_substitutions, convert_types=True, ) @@ -74,47 +74,47 @@ def generate_launch_description(): return LaunchDescription( [ - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), # Launch gazebo server for simulation ExecuteProcess( cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "--minimal_comms", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '--minimal_comms', world, ], - output="screen", + output='screen', ), # TODO(orduno) Launch the robot state publisher instead # using a local copy of TB3 urdf file Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "bringup_launch.py") + os.path.join(bringup_dir, 'launch', 'bringup_launch.py') ), launch_arguments={ - "namespace": "", - "use_namespace": "False", - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": new_yaml, - "bt_xml_file": bt_navigator_xml, - "use_composition": "False", - "autostart": "True", - "use_composition": "False", + 'namespace': '', + 'use_namespace': 'False', + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': new_yaml, + 'bt_xml_file': bt_navigator_xml, + 'use_composition': 'False', + 'autostart': 'True', + 'use_composition': 'False', }.items(), ), ] @@ -126,17 +126,17 @@ def main(argv=sys.argv[1:]): test1_action = ExecuteProcess( cmd=[ - os.path.join(os.getenv("TEST_DIR"), os.getenv("TESTER")), - "-r", - "-200000.0", - "-200000.0", - "0.0", - "2.0", - "-e", - "False", + os.path.join(os.getenv('TEST_DIR'), os.getenv('TESTER')), + '-r', + '-200000.0', + '-200000.0', + '0.0', + '2.0', + '-e', + 'False', ], - name="tester_node", - output="screen", + name='tester_node', + output='screen', ) lts = LaunchTestService() @@ -146,5 +146,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/system_failure/test_system_failure_launch.py b/nav2_system_tests/src/system_failure/test_system_failure_launch.py index cb252c6f784..01a7d50bc96 100755 --- a/nav2_system_tests/src/system_failure/test_system_failure_launch.py +++ b/nav2_system_tests/src/system_failure/test_system_failure_launch.py @@ -36,25 +36,25 @@ def generate_launch_description(): - map_yaml_file = os.getenv("TEST_MAP") - world = os.getenv("TEST_WORLD") + map_yaml_file = os.getenv('TEST_MAP') + world = os.getenv('TEST_WORLD') bt_navigator_xml = os.path.join( - get_package_share_directory("nav2_bt_navigator"), - "behavior_trees", - os.getenv("BT_NAVIGATOR_XML"), + get_package_share_directory('nav2_bt_navigator'), + 'behavior_trees', + os.getenv('BT_NAVIGATOR_XML'), ) - bringup_dir = get_package_share_directory("nav2_bringup") - params_file = os.path.join(bringup_dir, "params", "nav2_params.yaml") + bringup_dir = get_package_share_directory('nav2_bringup') + params_file = os.path.join(bringup_dir, 'params', 'nav2_params.yaml') # Replace the `use_astar` setting on the params file param_substitutions = { - "planner_server.ros__parameters.GridBased.use_astar": "False" + 'planner_server.ros__parameters.GridBased.use_astar': 'False' } configured_params = RewrittenYaml( source_file=params_file, - root_key="", + root_key='', param_rewrites=param_substitutions, convert_types=True, ) @@ -63,46 +63,46 @@ def generate_launch_description(): new_yaml = configured_params.perform(context) return LaunchDescription( [ - SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1"), - SetEnvironmentVariable("RCUTILS_LOGGING_USE_STDOUT", "1"), + SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'), + SetEnvironmentVariable('RCUTILS_LOGGING_USE_STDOUT', '1'), # Launch gazebo server for simulation ExecuteProcess( cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "--minimal_comms", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '--minimal_comms', world, ], - output="screen", + output='screen', ), # TODO(orduno) Launch the robot state publisher instead # using a local copy of TB3 urdf file Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "bringup_launch.py") + os.path.join(bringup_dir, 'launch', 'bringup_launch.py') ), launch_arguments={ - "namespace": "", - "use_namespace": "False", - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": new_yaml, - "bt_xml_file": bt_navigator_xml, - "use_composition": "False", - "autostart": "True", + 'namespace': '', + 'use_namespace': 'False', + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': new_yaml, + 'bt_xml_file': bt_navigator_xml, + 'use_composition': 'False', + 'autostart': 'True', }.items(), ), ] @@ -114,15 +114,15 @@ def main(argv=sys.argv[1:]): test1_action = ExecuteProcess( cmd=[ - os.path.join(os.getenv("TEST_DIR"), "tester_node.py"), - "-r", - "-2.0", - "-0.5", - "100.0", - "100.0", + os.path.join(os.getenv('TEST_DIR'), 'tester_node.py'), + '-r', + '-2.0', + '-0.5', + '100.0', + '100.0', ], - name="tester_node", - output="screen", + name='tester_node', + output='screen', ) lts = LaunchTestService() @@ -132,5 +132,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_system_tests/src/system_failure/tester_node.py b/nav2_system_tests/src/system_failure/tester_node.py index 592dcf975ee..765535c6e5b 100755 --- a/nav2_system_tests/src/system_failure/tester_node.py +++ b/nav2_system_tests/src/system_failure/tester_node.py @@ -37,12 +37,12 @@ class NavTester(Node): - def __init__(self, initial_pose: Pose, goal_pose: Pose, namespace: str = ""): - super().__init__(node_name="nav2_tester", namespace=namespace) + def __init__(self, initial_pose: Pose, goal_pose: Pose, namespace: str = ''): + super().__init__(node_name='nav2_tester', namespace=namespace) self.initial_pose_pub = self.create_publisher( - PoseWithCovarianceStamped, "initialpose", 10 + PoseWithCovarianceStamped, 'initialpose', 10 ) - self.goal_pub = self.create_publisher(PoseStamped, "goal_pose", 10) + self.goal_pub = self.create_publisher(PoseStamped, 'goal_pose', 10) pose_qos = QoSProfile( durability=QoSDurabilityPolicy.TRANSIENT_LOCAL, @@ -52,33 +52,33 @@ def __init__(self, initial_pose: Pose, goal_pose: Pose, namespace: str = ""): ) self.model_pose_sub = self.create_subscription( - PoseWithCovarianceStamped, "amcl_pose", self.poseCallback, pose_qos + PoseWithCovarianceStamped, 'amcl_pose', self.poseCallback, pose_qos ) self.initial_pose_received = False self.initial_pose = initial_pose self.goal_pose = goal_pose - self.action_client = ActionClient(self, NavigateToPose, "navigate_to_pose") + self.action_client = ActionClient(self, NavigateToPose, 'navigate_to_pose') def info_msg(self, msg: str): - self.get_logger().info("\033[1;37;44m" + msg + "\033[0m") + self.get_logger().info('\033[1;37;44m' + msg + '\033[0m') def warn_msg(self, msg: str): - self.get_logger().warn("\033[1;37;43m" + msg + "\033[0m") + self.get_logger().warn('\033[1;37;43m' + msg + '\033[0m') def error_msg(self, msg: str): - self.get_logger().error("\033[1;37;41m" + msg + "\033[0m") + self.get_logger().error('\033[1;37;41m' + msg + '\033[0m') def setInitialPose(self): msg = PoseWithCovarianceStamped() msg.pose.pose = self.initial_pose - msg.header.frame_id = "map" - self.info_msg("Publishing Initial Pose") + msg.header.frame_id = 'map' + self.info_msg('Publishing Initial Pose') self.initial_pose_pub.publish(msg) self.currentPose = self.initial_pose def getStampedPoseMsg(self, pose: Pose): msg = PoseStamped() - msg.header.frame_id = "map" + msg.header.frame_id = 'map' msg.pose = pose return msg @@ -96,31 +96,31 @@ def runNavigateAction(self, goal_pose: Optional[Pose] = None): goal_msg = NavigateToPose.Goal() goal_msg.pose = self.getStampedPoseMsg(self.goal_pose) - self.info_msg("Sending goal request...") + self.info_msg('Sending goal request...') send_goal_future = self.action_client.send_goal_async(goal_msg) rclpy.spin_until_future_complete(self, send_goal_future) goal_handle = send_goal_future.result() if not goal_handle.accepted: - self.error_msg("Goal rejected") + self.error_msg('Goal rejected') return False - self.info_msg("Goal accepted") + self.info_msg('Goal accepted') get_result_future = goal_handle.get_result_async() self.info_msg("Waiting for 'NavigateToPose' action to complete") rclpy.spin_until_future_complete(self, get_result_future) status = get_result_future.result().status if status != GoalStatus.STATUS_ABORTED: - self.info_msg(f"Goal failed with status code: {status}") + self.info_msg(f'Goal failed with status code: {status}') return False - self.info_msg("Goal failed, as expected!") + self.info_msg('Goal failed, as expected!') return True def poseCallback(self, msg): - self.info_msg("Received amcl_pose") + self.info_msg('Received amcl_pose') self.current_pose = msg.pose.pose self.initial_pose_received = True @@ -132,83 +132,83 @@ def reachesGoal(self, timeout, distance): rclpy.spin_once(self, timeout_sec=1) if self.distanceFromGoal() < distance: goalReached = True - self.info_msg("*** GOAL REACHED ***") + self.info_msg('*** GOAL REACHED ***') return True elif timeout is not None: if (time.time() - start_time) > timeout: - self.error_msg("Robot timed out reaching its goal!") + self.error_msg('Robot timed out reaching its goal!') return False def distanceFromGoal(self): d_x = self.current_pose.position.x - self.goal_pose.position.x d_y = self.current_pose.position.y - self.goal_pose.position.y distance = math.sqrt(d_x * d_x + d_y * d_y) - self.info_msg(f"Distance from goal is: {distance}") + self.info_msg(f'Distance from goal is: {distance}') return distance def wait_for_node_active(self, node_name: str): # Waits for the node within the tester namespace to become active - self.info_msg(f"Waiting for {node_name} to become active") - node_service = f"{node_name}/get_state" + self.info_msg(f'Waiting for {node_name} to become active') + node_service = f'{node_name}/get_state' state_client = self.create_client(GetState, node_service) while not state_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{node_service} service not available, waiting...") + self.info_msg(f'{node_service} service not available, waiting...') req = GetState.Request() # empty request - state = "UNKNOWN" - while state != "active": - self.info_msg(f"Getting {node_name} state...") + state = 'UNKNOWN' + while state != 'active': + self.info_msg(f'Getting {node_name} state...') future = state_client.call_async(req) rclpy.spin_until_future_complete(self, future) if future.result() is not None: state = future.result().current_state.label - self.info_msg(f"Result of get_state: {state}") + self.info_msg(f'Result of get_state: {state}') else: self.error_msg( - f"Exception while calling service: {future.exception()!r}" + f'Exception while calling service: {future.exception()!r}' ) time.sleep(5) def shutdown(self): - self.info_msg("Shutting down") + self.info_msg('Shutting down') self.action_client.destroy() - transition_service = "lifecycle_manager_navigation/manage_nodes" + transition_service = 'lifecycle_manager_navigation/manage_nodes' mgr_client = self.create_client(ManageLifecycleNodes, transition_service) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{transition_service} service not available, waiting...") + self.info_msg(f'{transition_service} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().SHUTDOWN future = mgr_client.call_async(req) try: - self.info_msg("Shutting down navigation lifecycle manager...") + self.info_msg('Shutting down navigation lifecycle manager...') rclpy.spin_until_future_complete(self, future) future.result() - self.info_msg("Shutting down navigation lifecycle manager complete.") + self.info_msg('Shutting down navigation lifecycle manager complete.') except Exception as e: # noqa: B902 - self.error_msg(f"Service call failed {e!r}") - transition_service = "lifecycle_manager_localization/manage_nodes" + self.error_msg(f'Service call failed {e!r}') + transition_service = 'lifecycle_manager_localization/manage_nodes' mgr_client = self.create_client(ManageLifecycleNodes, transition_service) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{transition_service} service not available, waiting...") + self.info_msg(f'{transition_service} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().SHUTDOWN future = mgr_client.call_async(req) try: - self.info_msg("Shutting down localization lifecycle manager...") + self.info_msg('Shutting down localization lifecycle manager...') rclpy.spin_until_future_complete(self, future) future.result() - self.info_msg("Shutting down localization lifecycle manager complete") + self.info_msg('Shutting down localization lifecycle manager complete') except Exception as e: # noqa: B902 - self.error_msg(f"Service call failed {e!r}") + self.error_msg(f'Service call failed {e!r}') def wait_for_initial_pose(self): self.initial_pose_received = False while not self.initial_pose_received: - self.info_msg("Setting initial pose") + self.info_msg('Setting initial pose') self.setInitialPose() - self.info_msg("Waiting for amcl_pose to be received") + self.info_msg('Waiting for amcl_pose to be received') rclpy.spin_once(self, timeout_sec=1) @@ -216,17 +216,17 @@ def run_all_tests(robot_tester): # set transforms to use_sim_time result = True if result: - robot_tester.wait_for_node_active("amcl") + robot_tester.wait_for_node_active('amcl') robot_tester.wait_for_initial_pose() - robot_tester.wait_for_node_active("bt_navigator") + robot_tester.wait_for_node_active('bt_navigator') result = robot_tester.runNavigateAction() # Add more tests here if desired if result: - robot_tester.info_msg("Test PASSED") + robot_tester.info_msg('Test PASSED') else: - robot_tester.error_msg("Test FAILED") + robot_tester.error_msg('Test FAILED') return result @@ -254,15 +254,15 @@ def get_testers(args): goal_pose=fwd_pose(float(final_x), float(final_y)), ) tester.info_msg( - "Starting tester, robot going from " + 'Starting tester, robot going from ' + init_x - + ", " + + ', ' + init_y - + " to " + + ' to ' + final_x - + ", " + + ', ' + final_y - + "." + + '.' ) testers.append(tester) return testers @@ -272,24 +272,24 @@ def get_testers(args): def main(argv=sys.argv[1:]): # The robot(s) positions from the input arguments - parser = argparse.ArgumentParser(description="System-level navigation tester node") + parser = argparse.ArgumentParser(description='System-level navigation tester node') group = parser.add_mutually_exclusive_group(required=True) group.add_argument( - "-r", - "--robot", - action="append", + '-r', + '--robot', + action='append', nargs=4, - metavar=("init_x", "init_y", "final_x", "final_y"), - help="The robot starting and final positions.", + metavar=('init_x', 'init_y', 'final_x', 'final_y'), + help='The robot starting and final positions.', ) group.add_argument( - "-rs", - "--robots", - action="append", + '-rs', + '--robots', + action='append', nargs=5, - metavar=("name", "init_x", "init_y", "final_x", "final_y"), + metavar=('name', 'init_x', 'init_y', 'final_x', 'final_y'), help="The robot's namespace and starting and final positions. " - + "Repeating the argument for multiple robots is supported.", + + 'Repeating the argument for multiple robots is supported.', ) args, unknown = parser.parse_known_args() @@ -311,15 +311,15 @@ def main(argv=sys.argv[1:]): # stop and shutdown the nav stack to exit cleanly tester.shutdown() - testers[0].info_msg("Done Shutting Down.") + testers[0].info_msg('Done Shutting Down.') if not passed: - testers[0].info_msg("Exiting failed") + testers[0].info_msg('Exiting failed') exit(1) else: - testers[0].info_msg("Exiting passed") + testers[0].info_msg('Exiting passed') exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_system_tests/src/updown/test_updown_launch.py b/nav2_system_tests/src/updown/test_updown_launch.py index 24fccf682e9..458779411b5 100755 --- a/nav2_system_tests/src/updown/test_updown_launch.py +++ b/nav2_system_tests/src/updown/test_updown_launch.py @@ -25,67 +25,67 @@ def generate_launch_description(): # Configuration parameters for the launch - launch_dir = os.path.join(get_package_share_directory("nav2_bringup"), "launch") + launch_dir = os.path.join(get_package_share_directory('nav2_bringup'), 'launch') map_yaml_file = os.path.join( - get_package_share_directory("nav2_system_tests"), "maps/map_circular.yaml" + get_package_share_directory('nav2_system_tests'), 'maps/map_circular.yaml' ) # Specify the actions start_tf_cmd_1 = Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "map", "odom"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'map', 'odom'], ) start_tf_cmd_2 = Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "odom", "base_footprint"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'odom', 'base_footprint'], ) start_tf_cmd_3 = Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_footprint", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'], ) start_tf_cmd_4 = Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "base_scan"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan'], ) nav2_bringup = launch.actions.IncludeLaunchDescription( - PythonLaunchDescriptionSource(os.path.join(launch_dir, "bringup_launch.py")), + PythonLaunchDescriptionSource(os.path.join(launch_dir, 'bringup_launch.py')), launch_arguments={ - "map": map_yaml_file, - "use_sim_time": "True", - "use_composition": "False", - "autostart": "False", + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'use_composition': 'False', + 'autostart': 'False', }.items(), ) start_test = launch.actions.ExecuteProcess( cmd=[ os.path.join( - get_package_prefix("nav2_system_tests"), - "lib/nav2_system_tests/test_updown", + get_package_prefix('nav2_system_tests'), + 'lib/nav2_system_tests/test_updown', ) ], cwd=[launch_dir], - output="screen", + output='screen', ) test_exit_event_handler = launch.actions.RegisterEventHandler( event_handler=launch.event_handlers.OnProcessExit( target_action=start_test, on_exit=launch.actions.EmitEvent( - event=launch.events.Shutdown(reason="Done!") + event=launch.events.Shutdown(reason='Done!') ), ) ) diff --git a/nav2_system_tests/src/updown/updownresults.py b/nav2_system_tests/src/updown/updownresults.py index 08833453099..6025094be1d 100755 --- a/nav2_system_tests/src/updown/updownresults.py +++ b/nav2_system_tests/src/updown/updownresults.py @@ -35,38 +35,38 @@ def main(): successful_bringup_count = 0 successful_shutdown_count = 0 for line in log.readlines(): - if line.startswith("======= START OF RUN:"): + if line.startswith('======= START OF RUN:'): test_successful = True shutdown_successful = False bringup_successful = False - if line.startswith("======== END OF RUN:"): + if line.startswith('======== END OF RUN:'): test_count += 1 - conclusion = "" + conclusion = '' if bringup_successful: successful_bringup_count += 1 - conclusion = " but bringup was successful" + conclusion = ' but bringup was successful' if shutdown_successful: successful_shutdown_count += 1 - conclusion = " but shutdown was successful" + conclusion = ' but shutdown was successful' if not test_successful: fail_count += 1 - print("Failure in test ", test_count, conclusion) + print('Failure in test ', test_count, conclusion) - if "[ERROR]" in line: + if '[ERROR]' in line: test_successful = False - if "The system is active" in line: + if 'The system is active' in line: bringup_successful = True - if "The system has been sucessfully shut down" in line: + if 'The system has been sucessfully shut down' in line: shutdown_successful = True - print("Number of tests: ", test_count) - print("Number of successes: ", test_count - fail_count) - print("Number of successful bringups", successful_bringup_count) - print("Number of successful shutdowns", successful_shutdown_count) + print('Number of tests: ', test_count) + print('Number of successes: ', test_count - fail_count) + print('Number of successful bringups', successful_bringup_count) + print('Number of successful shutdowns', successful_shutdown_count) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_system_tests/src/waypoint_follower/tester.py b/nav2_system_tests/src/waypoint_follower/tester.py index 1405feff075..7eb46457065 100755 --- a/nav2_system_tests/src/waypoint_follower/tester.py +++ b/nav2_system_tests/src/waypoint_follower/tester.py @@ -32,11 +32,11 @@ class WaypointFollowerTest(Node): def __init__(self): - super().__init__(node_name="nav2_waypoint_tester", namespace="") + super().__init__(node_name='nav2_waypoint_tester', namespace='') self.waypoints = None - self.action_client = ActionClient(self, FollowWaypoints, "follow_waypoints") + self.action_client = ActionClient(self, FollowWaypoints, 'follow_waypoints') self.initial_pose_pub = self.create_publisher( - PoseWithCovarianceStamped, "initialpose", 10 + PoseWithCovarianceStamped, 'initialpose', 10 ) self.initial_pose_received = False self.goal_handle = None @@ -50,29 +50,29 @@ def __init__(self): ) self.model_pose_sub = self.create_subscription( - PoseWithCovarianceStamped, "amcl_pose", self.poseCallback, pose_qos + PoseWithCovarianceStamped, 'amcl_pose', self.poseCallback, pose_qos ) self.param_cli = self.create_client( - SetParameters, "/waypoint_follower/set_parameters" + SetParameters, '/waypoint_follower/set_parameters' ) def setInitialPose(self, pose): self.init_pose = PoseWithCovarianceStamped() self.init_pose.pose.pose.position.x = pose[0] self.init_pose.pose.pose.position.y = pose[1] - self.init_pose.header.frame_id = "map" + self.init_pose.header.frame_id = 'map' self.publishInitialPose() time.sleep(5) def poseCallback(self, msg): - self.info_msg("Received amcl_pose") + self.info_msg('Received amcl_pose') self.initial_pose_received = True def setWaypoints(self, waypoints): self.waypoints = [] for wp in waypoints: msg = PoseStamped() - msg.header.frame_id = "map" + msg.header.frame_id = 'map' msg.pose.position.x = wp[0] msg.pose.position.y = wp[1] msg.pose.orientation.w = 1.0 @@ -89,19 +89,19 @@ def run(self, block, cancel): action_request = FollowWaypoints.Goal() action_request.poses = self.waypoints - self.info_msg("Sending goal request...") + self.info_msg('Sending goal request...') send_goal_future = self.action_client.send_goal_async(action_request) try: rclpy.spin_until_future_complete(self, send_goal_future) self.goal_handle = send_goal_future.result() except Exception as e: # noqa: B902 - self.error_msg(f"Service call failed {e!r}") + self.error_msg(f'Service call failed {e!r}') if not self.goal_handle.accepted: - self.error_msg("Goal rejected") + self.error_msg('Goal rejected') return False - self.info_msg("Goal accepted") + self.info_msg('Goal accepted') if not block: return True @@ -117,19 +117,19 @@ def run(self, block, cancel): result = get_result_future.result().result self.action_result = result except Exception as e: # noqa: B902 - self.error_msg(f"Service call failed {e!r}") + self.error_msg(f'Service call failed {e!r}') if status != GoalStatus.STATUS_SUCCEEDED: - self.info_msg(f"Goal failed with status code: {status}") + self.info_msg(f'Goal failed with status code: {status}') return False if len(self.action_result.missed_waypoints) > 0: self.info_msg( - "Goal failed to process all waypoints," - " missed {0} wps.".format(len(self.action_result.missed_waypoints)) + 'Goal failed to process all waypoints,' + ' missed {0} wps.'.format(len(self.action_result.missed_waypoints)) ) return False - self.info_msg("Goal succeeded!") + self.info_msg('Goal succeeded!') return True def publishInitialPose(self): @@ -138,21 +138,21 @@ def publishInitialPose(self): def setStopFailureParam(self, value): req = SetParameters.Request() req.parameters = [ - Parameter("stop_on_failure", Parameter.Type.BOOL, value).to_parameter_msg() + Parameter('stop_on_failure', Parameter.Type.BOOL, value).to_parameter_msg() ] future = self.param_cli.call_async(req) rclpy.spin_until_future_complete(self, future) def shutdown(self): - self.info_msg("Shutting down") + self.info_msg('Shutting down') self.action_client.destroy() - self.info_msg("Destroyed follow_waypoints action client") + self.info_msg('Destroyed follow_waypoints action client') - transition_service = "lifecycle_manager_navigation/manage_nodes" + transition_service = 'lifecycle_manager_navigation/manage_nodes' mgr_client = self.create_client(ManageLifecycleNodes, transition_service) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{transition_service} service not available, waiting...") + self.info_msg(f'{transition_service} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().SHUTDOWN @@ -161,14 +161,14 @@ def shutdown(self): rclpy.spin_until_future_complete(self, future) future.result() except Exception as e: # noqa: B902 - self.error_msg(f"{transition_service} service call failed {e!r}") + self.error_msg(f'{transition_service} service call failed {e!r}') - self.info_msg(f"{transition_service} finished") + self.info_msg(f'{transition_service} finished') - transition_service = "lifecycle_manager_localization/manage_nodes" + transition_service = 'lifecycle_manager_localization/manage_nodes' mgr_client = self.create_client(ManageLifecycleNodes, transition_service) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info_msg(f"{transition_service} service not available, waiting...") + self.info_msg(f'{transition_service} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().SHUTDOWN @@ -177,9 +177,9 @@ def shutdown(self): rclpy.spin_until_future_complete(self, future) future.result() except Exception as e: # noqa: B902 - self.error_msg(f"{transition_service} service call failed {e!r}") + self.error_msg(f'{transition_service} service call failed {e!r}') - self.info_msg(f"{transition_service} finished") + self.info_msg(f'{transition_service} finished') def cancel_goal(self): cancel_future = self.goal_handle.cancel_goal_async() @@ -211,9 +211,9 @@ def main(argv=sys.argv[1:]): retries = 2 while not test.initial_pose_received and retry_count <= retries: retry_count += 1 - test.info_msg("Setting initial pose") + test.info_msg('Setting initial pose') test.setInitialPose(starting_pose) - test.info_msg("Waiting for amcl_pose to be received") + test.info_msg('Waiting for amcl_pose to be received') rclpy.spin_once(test, timeout_sec=1.0) # wait for poseCallback result = test.run(True, False) @@ -263,15 +263,15 @@ def main(argv=sys.argv[1:]): result = not result test.shutdown() - test.info_msg("Done Shutting Down.") + test.info_msg('Done Shutting Down.') if not result: - test.info_msg("Exiting failed") + test.info_msg('Exiting failed') exit(1) else: - test.info_msg("Exiting passed") + test.info_msg('Exiting passed') exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() From 551ac226ec8ca42839495ec56524f5a62d130f94 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 21:15:34 +0100 Subject: [PATCH 16/24] Fix flake8-quotes linter for nav2_collision_monitor --- .../launch/collision_detector_node.launch.py | 86 +++++++++---------- .../launch/collision_monitor_node.launch.py | 86 +++++++++---------- 2 files changed, 86 insertions(+), 86 deletions(-) diff --git a/nav2_collision_monitor/launch/collision_detector_node.launch.py b/nav2_collision_monitor/launch/collision_detector_node.launch.py index b5c4b5f73a1..c16bec55a4d 100644 --- a/nav2_collision_monitor/launch/collision_detector_node.launch.py +++ b/nav2_collision_monitor/launch/collision_detector_node.launch.py @@ -32,51 +32,51 @@ def generate_launch_description(): # Environment - package_dir = get_package_share_directory("nav2_collision_monitor") + package_dir = get_package_share_directory('nav2_collision_monitor') # Constant parameters - lifecycle_nodes = ["collision_detector"] + lifecycle_nodes = ['collision_detector'] autostart = True - remappings = [("/tf", "tf"), ("/tf_static", "tf_static")] + remappings = [('/tf', 'tf'), ('/tf_static', 'tf_static')] # Launch arguments # 1. Create the launch configuration variables - namespace = LaunchConfiguration("namespace") - use_sim_time = LaunchConfiguration("use_sim_time") - params_file = LaunchConfiguration("params_file") - use_composition = LaunchConfiguration("use_composition") - container_name = LaunchConfiguration("container_name") - container_name_full = (namespace, "/", container_name) + namespace = LaunchConfiguration('namespace') + use_sim_time = LaunchConfiguration('use_sim_time') + params_file = LaunchConfiguration('params_file') + use_composition = LaunchConfiguration('use_composition') + container_name = LaunchConfiguration('container_name') + container_name_full = (namespace, '/', container_name) # 2. Declare the launch arguments declare_namespace_cmd = DeclareLaunchArgument( - "namespace", default_value="", description="Top-level namespace" + 'namespace', default_value='', description='Top-level namespace' ) declare_use_sim_time_cmd = DeclareLaunchArgument( - "use_sim_time", - default_value="True", - description="Use simulation (Gazebo) clock if true", + 'use_sim_time', + default_value='True', + description='Use simulation (Gazebo) clock if true', ) declare_params_file_cmd = DeclareLaunchArgument( - "params_file", + 'params_file', default_value=os.path.join( - package_dir, "params", "collision_monitor_params.yaml" + package_dir, 'params', 'collision_monitor_params.yaml' ), - description="Full path to the ROS2 parameters file to use for all launched nodes", + description='Full path to the ROS2 parameters file to use for all launched nodes', ) declare_use_composition_cmd = DeclareLaunchArgument( - "use_composition", - default_value="True", - description="Use composed bringup if True", + 'use_composition', + default_value='True', + description='Use composed bringup if True', ) declare_container_name_cmd = DeclareLaunchArgument( - "container_name", - default_value="nav2_container", - description="the name of conatiner that nodes will load in if use composition", + 'container_name', + default_value='nav2_container', + description='the name of conatiner that nodes will load in if use composition', ) configured_params = RewrittenYaml( @@ -88,28 +88,28 @@ def generate_launch_description(): # Declare node launching commands load_nodes = GroupAction( - condition=IfCondition(PythonExpression(["not ", use_composition])), + condition=IfCondition(PythonExpression(['not ', use_composition])), actions=[ - SetParameter("use_sim_time", use_sim_time), + SetParameter('use_sim_time', use_sim_time), PushROSNamespace( condition=IfCondition( - NotEqualsSubstitution(LaunchConfiguration("namespace"), "") + NotEqualsSubstitution(LaunchConfiguration('namespace'), '') ), namespace=namespace, ), Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager_collision_detector", - output="screen", + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager_collision_detector', + output='screen', emulate_tty=True, # https://github.com/ros2/launch/issues/188 - parameters=[{"autostart": autostart}, {"node_names": lifecycle_nodes}], + parameters=[{'autostart': autostart}, {'node_names': lifecycle_nodes}], remappings=remappings, ), Node( - package="nav2_collision_monitor", - executable="collision_detector", - output="screen", + package='nav2_collision_monitor', + executable='collision_detector', + output='screen', emulate_tty=True, # https://github.com/ros2/launch/issues/188 parameters=[configured_params], remappings=remappings, @@ -120,10 +120,10 @@ def generate_launch_description(): load_composable_nodes = GroupAction( condition=IfCondition(use_composition), actions=[ - SetParameter("use_sim_time", use_sim_time), + SetParameter('use_sim_time', use_sim_time), PushROSNamespace( condition=IfCondition( - NotEqualsSubstitution(LaunchConfiguration("namespace"), "") + NotEqualsSubstitution(LaunchConfiguration('namespace'), '') ), namespace=namespace, ), @@ -131,19 +131,19 @@ def generate_launch_description(): target_container=container_name_full, composable_node_descriptions=[ ComposableNode( - package="nav2_lifecycle_manager", - plugin="nav2_lifecycle_manager::LifecycleManager", - name="lifecycle_manager_collision_detector", + package='nav2_lifecycle_manager', + plugin='nav2_lifecycle_manager::LifecycleManager', + name='lifecycle_manager_collision_detector', parameters=[ - {"autostart": autostart}, - {"node_names": lifecycle_nodes}, + {'autostart': autostart}, + {'node_names': lifecycle_nodes}, ], remappings=remappings, ), ComposableNode( - package="nav2_collision_monitor", - plugin="nav2_collision_monitor::CollisionDetector", - name="collision_detector", + package='nav2_collision_monitor', + plugin='nav2_collision_monitor::CollisionDetector', + name='collision_detector', parameters=[configured_params], remappings=remappings, ), diff --git a/nav2_collision_monitor/launch/collision_monitor_node.launch.py b/nav2_collision_monitor/launch/collision_monitor_node.launch.py index fae3d967c9f..b00b43b2aa1 100644 --- a/nav2_collision_monitor/launch/collision_monitor_node.launch.py +++ b/nav2_collision_monitor/launch/collision_monitor_node.launch.py @@ -32,51 +32,51 @@ def generate_launch_description(): # Environment - package_dir = get_package_share_directory("nav2_collision_monitor") + package_dir = get_package_share_directory('nav2_collision_monitor') # Constant parameters - lifecycle_nodes = ["collision_monitor"] + lifecycle_nodes = ['collision_monitor'] autostart = True - remappings = [("/tf", "tf"), ("/tf_static", "tf_static")] + remappings = [('/tf', 'tf'), ('/tf_static', 'tf_static')] # Launch arguments # 1. Create the launch configuration variables - namespace = LaunchConfiguration("namespace") - use_sim_time = LaunchConfiguration("use_sim_time") - params_file = LaunchConfiguration("params_file") - use_composition = LaunchConfiguration("use_composition") - container_name = LaunchConfiguration("container_name") - container_name_full = (namespace, "/", container_name) + namespace = LaunchConfiguration('namespace') + use_sim_time = LaunchConfiguration('use_sim_time') + params_file = LaunchConfiguration('params_file') + use_composition = LaunchConfiguration('use_composition') + container_name = LaunchConfiguration('container_name') + container_name_full = (namespace, '/', container_name) # 2. Declare the launch arguments declare_namespace_cmd = DeclareLaunchArgument( - "namespace", default_value="", description="Top-level namespace" + 'namespace', default_value='', description='Top-level namespace' ) declare_use_sim_time_cmd = DeclareLaunchArgument( - "use_sim_time", - default_value="True", - description="Use simulation (Gazebo) clock if true", + 'use_sim_time', + default_value='True', + description='Use simulation (Gazebo) clock if true', ) declare_params_file_cmd = DeclareLaunchArgument( - "params_file", + 'params_file', default_value=os.path.join( - package_dir, "params", "collision_monitor_params.yaml" + package_dir, 'params', 'collision_monitor_params.yaml' ), - description="Full path to the ROS2 parameters file to use for all launched nodes", + description='Full path to the ROS2 parameters file to use for all launched nodes', ) declare_use_composition_cmd = DeclareLaunchArgument( - "use_composition", - default_value="True", - description="Use composed bringup if True", + 'use_composition', + default_value='True', + description='Use composed bringup if True', ) declare_container_name_cmd = DeclareLaunchArgument( - "container_name", - default_value="nav2_container", - description="the name of conatiner that nodes will load in if use composition", + 'container_name', + default_value='nav2_container', + description='the name of conatiner that nodes will load in if use composition', ) configured_params = ParameterFile( @@ -91,28 +91,28 @@ def generate_launch_description(): # Declare node launching commands load_nodes = GroupAction( - condition=IfCondition(PythonExpression(["not ", use_composition])), + condition=IfCondition(PythonExpression(['not ', use_composition])), actions=[ - SetParameter("use_sim_time", use_sim_time), + SetParameter('use_sim_time', use_sim_time), PushROSNamespace( condition=IfCondition( - NotEqualsSubstitution(LaunchConfiguration("namespace"), "") + NotEqualsSubstitution(LaunchConfiguration('namespace'), '') ), namespace=namespace, ), Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager_collision_monitor", - output="screen", + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager_collision_monitor', + output='screen', emulate_tty=True, # https://github.com/ros2/launch/issues/188 - parameters=[{"autostart": autostart}, {"node_names": lifecycle_nodes}], + parameters=[{'autostart': autostart}, {'node_names': lifecycle_nodes}], remappings=remappings, ), Node( - package="nav2_collision_monitor", - executable="collision_monitor", - output="screen", + package='nav2_collision_monitor', + executable='collision_monitor', + output='screen', emulate_tty=True, # https://github.com/ros2/launch/issues/188 parameters=[configured_params], remappings=remappings, @@ -123,10 +123,10 @@ def generate_launch_description(): load_composable_nodes = GroupAction( condition=IfCondition(use_composition), actions=[ - SetParameter("use_sim_time", use_sim_time), + SetParameter('use_sim_time', use_sim_time), PushROSNamespace( condition=IfCondition( - NotEqualsSubstitution(LaunchConfiguration("namespace"), "") + NotEqualsSubstitution(LaunchConfiguration('namespace'), '') ), namespace=namespace, ), @@ -134,19 +134,19 @@ def generate_launch_description(): target_container=container_name_full, composable_node_descriptions=[ ComposableNode( - package="nav2_lifecycle_manager", - plugin="nav2_lifecycle_manager::LifecycleManager", - name="lifecycle_manager_collision_monitor", + package='nav2_lifecycle_manager', + plugin='nav2_lifecycle_manager::LifecycleManager', + name='lifecycle_manager_collision_monitor', parameters=[ - {"autostart": autostart}, - {"node_names": lifecycle_nodes}, + {'autostart': autostart}, + {'node_names': lifecycle_nodes}, ], remappings=remappings, ), ComposableNode( - package="nav2_collision_monitor", - plugin="nav2_collision_monitor::CollisionMonitor", - name="collision_monitor", + package='nav2_collision_monitor', + plugin='nav2_collision_monitor::CollisionMonitor', + name='collision_monitor', parameters=[configured_params], remappings=remappings, ), From 5ab718e62badb7ef2377f7997c95d3287f7f81ff Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 21:19:06 +0100 Subject: [PATCH 17/24] Fix flake8-quotes linter for nav2_map_server --- .../launch/map_saver_server.launch.py | 28 +++++++++---------- .../test/component/test_map_saver_launch.py | 10 +++---- .../test/component/test_map_server_launch.py | 10 +++---- .../map_saver_node.launch.py | 8 +++--- .../map_server_node.launch.py | 8 +++--- 5 files changed, 32 insertions(+), 32 deletions(-) diff --git a/nav2_map_server/launch/map_saver_server.launch.py b/nav2_map_server/launch/map_saver_server.launch.py index 450a52b6336..aa3f2c4f7bc 100644 --- a/nav2_map_server/launch/map_saver_server.launch.py +++ b/nav2_map_server/launch/map_saver_server.launch.py @@ -20,7 +20,7 @@ def generate_launch_description(): # Parameters - lifecycle_nodes = ["map_saver"] + lifecycle_nodes = ['map_saver'] use_sim_time = True autostart = True save_map_timeout = 2.0 @@ -29,27 +29,27 @@ def generate_launch_description(): # Nodes launching commands start_map_saver_server_cmd = launch_ros.actions.Node( - package="nav2_map_server", - executable="map_saver_server", - output="screen", + package='nav2_map_server', + executable='map_saver_server', + output='screen', emulate_tty=True, # https://github.com/ros2/launch/issues/188 parameters=[ - {"save_map_timeout": save_map_timeout}, - {"free_thresh_default": free_thresh_default}, - {"occupied_thresh_default": occupied_thresh_default}, + {'save_map_timeout': save_map_timeout}, + {'free_thresh_default': free_thresh_default}, + {'occupied_thresh_default': occupied_thresh_default}, ], ) start_lifecycle_manager_cmd = launch_ros.actions.Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager", - output="screen", + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager', + output='screen', emulate_tty=True, # https://github.com/ros2/launch/issues/188 parameters=[ - {"use_sim_time": use_sim_time}, - {"autostart": autostart}, - {"node_names": lifecycle_nodes}, + {'use_sim_time': use_sim_time}, + {'autostart': autostart}, + {'node_names': lifecycle_nodes}, ], ) diff --git a/nav2_map_server/test/component/test_map_saver_launch.py b/nav2_map_server/test/component/test_map_saver_launch.py index 8b330f4c9f6..e33e03a9864 100755 --- a/nav2_map_server/test/component/test_map_saver_launch.py +++ b/nav2_map_server/test/component/test_map_saver_launch.py @@ -26,8 +26,8 @@ def main(argv=sys.argv[1:]): - launchFile = os.path.join(os.getenv("TEST_LAUNCH_DIR"), "map_saver_node.launch.py") - testExecutable = os.getenv("TEST_EXECUTABLE") + launchFile = os.path.join(os.getenv('TEST_LAUNCH_DIR'), 'map_saver_node.launch.py') + testExecutable = os.getenv('TEST_EXECUTABLE') ld = LaunchDescription( [ IncludeLaunchDescription(PythonLaunchDescriptionSource([launchFile])), @@ -35,15 +35,15 @@ def main(argv=sys.argv[1:]): ) test1_action = ExecuteProcess( cmd=[testExecutable], - name="test_map_saver_node", + name='test_map_saver_node', ) lts = LaunchTestService() lts.add_test_action(ld, test1_action) ls = LaunchService(argv=argv) ls.include_launch_description(ld) - os.chdir(os.getenv("TEST_LAUNCH_DIR")) + os.chdir(os.getenv('TEST_LAUNCH_DIR')) return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_map_server/test/component/test_map_server_launch.py b/nav2_map_server/test/component/test_map_server_launch.py index ebd5eb225ac..473feea97eb 100755 --- a/nav2_map_server/test/component/test_map_server_launch.py +++ b/nav2_map_server/test/component/test_map_server_launch.py @@ -26,8 +26,8 @@ def main(argv=sys.argv[1:]): - launchFile = os.path.join(os.getenv("TEST_LAUNCH_DIR"), "map_server_node.launch.py") - testExecutable = os.getenv("TEST_EXECUTABLE") + launchFile = os.path.join(os.getenv('TEST_LAUNCH_DIR'), 'map_server_node.launch.py') + testExecutable = os.getenv('TEST_EXECUTABLE') ld = LaunchDescription( [ IncludeLaunchDescription(PythonLaunchDescriptionSource([launchFile])), @@ -35,15 +35,15 @@ def main(argv=sys.argv[1:]): ) test1_action = ExecuteProcess( cmd=[testExecutable], - name="test_map_server_node", + name='test_map_server_node', ) lts = LaunchTestService() lts.add_test_action(ld, test1_action) ls = LaunchService(argv=argv) ls.include_launch_description(ld) - os.chdir(os.getenv("TEST_LAUNCH_DIR")) + os.chdir(os.getenv('TEST_LAUNCH_DIR')) return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_map_server/test/test_launch_files/map_saver_node.launch.py b/nav2_map_server/test/test_launch_files/map_saver_node.launch.py index 8d2d7044b26..a0ac0aeb8a0 100644 --- a/nav2_map_server/test/test_launch_files/map_saver_node.launch.py +++ b/nav2_map_server/test/test_launch_files/map_saver_node.launch.py @@ -29,10 +29,10 @@ def generate_launch_description(): ld = LaunchDescription() map_saver_server_cmd = launch_ros.actions.Node( - package="nav2_map_server", - executable="map_saver_server", - output="screen", - parameters=[os.path.join(os.getenv("TEST_DIR"), "map_saver_params.yaml")], + package='nav2_map_server', + executable='map_saver_server', + output='screen', + parameters=[os.path.join(os.getenv('TEST_DIR'), 'map_saver_params.yaml')], ) map_publisher_cmd = ExecuteProcess(cmd=[map_publisher]) diff --git a/nav2_map_server/test/test_launch_files/map_server_node.launch.py b/nav2_map_server/test/test_launch_files/map_server_node.launch.py index 41dbfa8116a..813abf7ea14 100644 --- a/nav2_map_server/test/test_launch_files/map_server_node.launch.py +++ b/nav2_map_server/test/test_launch_files/map_server_node.launch.py @@ -24,11 +24,11 @@ def generate_launch_description(): return LaunchDescription( [ launch_ros.actions.Node( - package="nav2_map_server", - executable="map_server", - output="screen", + package='nav2_map_server', + executable='map_server', + output='screen', parameters=[ - os.path.join(os.getenv("TEST_DIR"), "map_server_params.yaml") + os.path.join(os.getenv('TEST_DIR'), 'map_server_params.yaml') ], ) ] From 2dd174fdd5ffdcc86fe9c5f2ee73964afa1df923 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 21:21:32 +0100 Subject: [PATCH 18/24] Fix flake8-quotes linter for nav2_bringup --- nav2_bringup/launch/bringup_launch.py | 134 +++++----- .../cloned_multi_tb3_simulation_launch.py | 146 +++++------ nav2_bringup/launch/localization_launch.py | 156 ++++++------ nav2_bringup/launch/navigation_launch.py | 224 ++++++++--------- nav2_bringup/launch/rviz_launch.py | 62 ++--- nav2_bringup/launch/slam_launch.py | 78 +++--- nav2_bringup/launch/tb3_simulation_launch.py | 232 +++++++++--------- .../unique_multi_tb3_simulation_launch.py | 168 ++++++------- 8 files changed, 600 insertions(+), 600 deletions(-) diff --git a/nav2_bringup/launch/bringup_launch.py b/nav2_bringup/launch/bringup_launch.py index 6810028b00e..f39a0b8e887 100644 --- a/nav2_bringup/launch/bringup_launch.py +++ b/nav2_bringup/launch/bringup_launch.py @@ -34,20 +34,20 @@ def generate_launch_description(): # Get the launch directory - bringup_dir = get_package_share_directory("nav2_bringup") - launch_dir = os.path.join(bringup_dir, "launch") + bringup_dir = get_package_share_directory('nav2_bringup') + launch_dir = os.path.join(bringup_dir, 'launch') # Create the launch configuration variables - namespace = LaunchConfiguration("namespace") - use_namespace = LaunchConfiguration("use_namespace") - slam = LaunchConfiguration("slam") - map_yaml_file = LaunchConfiguration("map") - use_sim_time = LaunchConfiguration("use_sim_time") - params_file = LaunchConfiguration("params_file") - autostart = LaunchConfiguration("autostart") - use_composition = LaunchConfiguration("use_composition") - use_respawn = LaunchConfiguration("use_respawn") - log_level = LaunchConfiguration("log_level") + namespace = LaunchConfiguration('namespace') + use_namespace = LaunchConfiguration('use_namespace') + slam = LaunchConfiguration('slam') + map_yaml_file = LaunchConfiguration('map') + use_sim_time = LaunchConfiguration('use_sim_time') + params_file = LaunchConfiguration('params_file') + autostart = LaunchConfiguration('autostart') + use_composition = LaunchConfiguration('use_composition') + use_respawn = LaunchConfiguration('use_respawn') + log_level = LaunchConfiguration('log_level') # Map fully qualified names to relative ones so the node's namespace can be prepended. # In case of the transforms (tf), currently, there doesn't seem to be a better alternative @@ -55,7 +55,7 @@ def generate_launch_description(): # https://github.com/ros/robot_state_publisher/pull/30 # TODO(orduno) Substitute with `PushNodeRemapping` # https://github.com/ros2/launch_ros/issues/56 - remappings = [("/tf", "tf"), ("/tf_static", "tf_static")] + remappings = [('/tf', 'tf'), ('/tf_static', 'tf_static')] # Only it applys when `use_namespace` is True. # '' keyword shall be replaced by 'namespace' launch argument @@ -63,7 +63,7 @@ def generate_launch_description(): # User defined config file should contain '' keyword for the replacements. params_file = ReplaceString( source_file=params_file, - replacements={"": ("/", namespace)}, + replacements={'': ('/', namespace)}, condition=IfCondition(use_namespace), ) @@ -78,59 +78,59 @@ def generate_launch_description(): ) stdout_linebuf_envvar = SetEnvironmentVariable( - "RCUTILS_LOGGING_BUFFERED_STREAM", "1" + 'RCUTILS_LOGGING_BUFFERED_STREAM', '1' ) declare_namespace_cmd = DeclareLaunchArgument( - "namespace", default_value="", description="Top-level namespace" + 'namespace', default_value='', description='Top-level namespace' ) declare_use_namespace_cmd = DeclareLaunchArgument( - "use_namespace", - default_value="false", - description="Whether to apply a namespace to the navigation stack", + 'use_namespace', + default_value='false', + description='Whether to apply a namespace to the navigation stack', ) declare_slam_cmd = DeclareLaunchArgument( - "slam", default_value="False", description="Whether run a SLAM" + 'slam', default_value='False', description='Whether run a SLAM' ) declare_map_yaml_cmd = DeclareLaunchArgument( - "map", default_value="", description="Full path to map yaml file to load" + 'map', default_value='', description='Full path to map yaml file to load' ) declare_use_sim_time_cmd = DeclareLaunchArgument( - "use_sim_time", - default_value="false", - description="Use simulation (Gazebo) clock if true", + 'use_sim_time', + default_value='false', + description='Use simulation (Gazebo) clock if true', ) declare_params_file_cmd = DeclareLaunchArgument( - "params_file", - default_value=os.path.join(bringup_dir, "params", "nav2_params.yaml"), - description="Full path to the ROS2 parameters file to use for all launched nodes", + 'params_file', + default_value=os.path.join(bringup_dir, 'params', 'nav2_params.yaml'), + description='Full path to the ROS2 parameters file to use for all launched nodes', ) declare_autostart_cmd = DeclareLaunchArgument( - "autostart", - default_value="true", - description="Automatically startup the nav2 stack", + 'autostart', + default_value='true', + description='Automatically startup the nav2 stack', ) declare_use_composition_cmd = DeclareLaunchArgument( - "use_composition", - default_value="True", - description="Whether to use composed bringup", + 'use_composition', + default_value='True', + description='Whether to use composed bringup', ) declare_use_respawn_cmd = DeclareLaunchArgument( - "use_respawn", - default_value="False", - description="Whether to respawn if a node crashes. Applied when composition is disabled.", + 'use_respawn', + default_value='False', + description='Whether to respawn if a node crashes. Applied when composition is disabled.', ) declare_log_level_cmd = DeclareLaunchArgument( - "log_level", default_value="info", description="log level" + 'log_level', default_value='info', description='log level' ) # Specify the actions @@ -139,55 +139,55 @@ def generate_launch_description(): PushROSNamespace(condition=IfCondition(use_namespace), namespace=namespace), Node( condition=IfCondition(use_composition), - name="nav2_container", - package="rclcpp_components", - executable="component_container_isolated", - parameters=[configured_params, {"autostart": autostart}], - arguments=["--ros-args", "--log-level", log_level], + name='nav2_container', + package='rclcpp_components', + executable='component_container_isolated', + parameters=[configured_params, {'autostart': autostart}], + arguments=['--ros-args', '--log-level', log_level], remappings=remappings, - output="screen", + output='screen', ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(launch_dir, "slam_launch.py") + os.path.join(launch_dir, 'slam_launch.py') ), condition=IfCondition(slam), launch_arguments={ - "namespace": namespace, - "use_sim_time": use_sim_time, - "autostart": autostart, - "use_respawn": use_respawn, - "params_file": params_file, + 'namespace': namespace, + 'use_sim_time': use_sim_time, + 'autostart': autostart, + 'use_respawn': use_respawn, + 'params_file': params_file, }.items(), ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(launch_dir, "localization_launch.py") + os.path.join(launch_dir, 'localization_launch.py') ), - condition=IfCondition(PythonExpression(["not ", slam])), + condition=IfCondition(PythonExpression(['not ', slam])), launch_arguments={ - "namespace": namespace, - "map": map_yaml_file, - "use_sim_time": use_sim_time, - "autostart": autostart, - "params_file": params_file, - "use_composition": use_composition, - "use_respawn": use_respawn, - "container_name": "nav2_container", + 'namespace': namespace, + 'map': map_yaml_file, + 'use_sim_time': use_sim_time, + 'autostart': autostart, + 'params_file': params_file, + 'use_composition': use_composition, + 'use_respawn': use_respawn, + 'container_name': 'nav2_container', }.items(), ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(launch_dir, "navigation_launch.py") + os.path.join(launch_dir, 'navigation_launch.py') ), launch_arguments={ - "namespace": namespace, - "use_sim_time": use_sim_time, - "autostart": autostart, - "params_file": params_file, - "use_composition": use_composition, - "use_respawn": use_respawn, - "container_name": "nav2_container", + 'namespace': namespace, + 'use_sim_time': use_sim_time, + 'autostart': autostart, + 'params_file': params_file, + 'use_composition': use_composition, + 'use_respawn': use_respawn, + 'container_name': 'nav2_container', }.items(), ), ] diff --git a/nav2_bringup/launch/cloned_multi_tb3_simulation_launch.py b/nav2_bringup/launch/cloned_multi_tb3_simulation_launch.py index ecd6758c246..dbff594bc71 100644 --- a/nav2_bringup/launch/cloned_multi_tb3_simulation_launch.py +++ b/nav2_bringup/launch/cloned_multi_tb3_simulation_launch.py @@ -36,91 +36,91 @@ def generate_launch_description(): Launch arguments consist of robot name(which is namespace) and pose for initialization. Keep general yaml format for pose information. - ex) robots:="robot1={x: 1.0, y: 1.0, yaw: 1.5707}; robot2={x: 1.0, y: 1.0, yaw: 1.5707}" - ex) robots:="robot3={x: 1.0, y: 1.0, z: 1.0, roll: 0.0, pitch: 1.5707, yaw: 1.5707}; - robot4={x: 1.0, y: 1.0, z: 1.0, roll: 0.0, pitch: 1.5707, yaw: 1.5707}" + ex) robots:='robot1={x: 1.0, y: 1.0, yaw: 1.5707}; robot2={x: 1.0, y: 1.0, yaw: 1.5707}' + ex) robots:='robot3={x: 1.0, y: 1.0, z: 1.0, roll: 0.0, pitch: 1.5707, yaw: 1.5707}; + robot4={x: 1.0, y: 1.0, z: 1.0, roll: 0.0, pitch: 1.5707, yaw: 1.5707}' """ # Get the launch directory - bringup_dir = get_package_share_directory("nav2_bringup") - launch_dir = os.path.join(bringup_dir, "launch") + bringup_dir = get_package_share_directory('nav2_bringup') + launch_dir = os.path.join(bringup_dir, 'launch') # Simulation settings - world = LaunchConfiguration("world") - simulator = LaunchConfiguration("simulator") + world = LaunchConfiguration('world') + simulator = LaunchConfiguration('simulator') # On this example all robots are launched with the same settings - map_yaml_file = LaunchConfiguration("map") - params_file = LaunchConfiguration("params_file") - autostart = LaunchConfiguration("autostart") - rviz_config_file = LaunchConfiguration("rviz_config") - use_robot_state_pub = LaunchConfiguration("use_robot_state_pub") - use_rviz = LaunchConfiguration("use_rviz") - log_settings = LaunchConfiguration("log_settings", default="true") + map_yaml_file = LaunchConfiguration('map') + params_file = LaunchConfiguration('params_file') + autostart = LaunchConfiguration('autostart') + rviz_config_file = LaunchConfiguration('rviz_config') + use_robot_state_pub = LaunchConfiguration('use_robot_state_pub') + use_rviz = LaunchConfiguration('use_rviz') + log_settings = LaunchConfiguration('log_settings', default='true') # Declare the launch arguments declare_world_cmd = DeclareLaunchArgument( - "world", - default_value=os.path.join(bringup_dir, "worlds", "world_only.model"), - description="Full path to world file to load", + 'world', + default_value=os.path.join(bringup_dir, 'worlds', 'world_only.model'), + description='Full path to world file to load', ) declare_simulator_cmd = DeclareLaunchArgument( - "simulator", - default_value="gazebo", - description="The simulator to use (gazebo or gzserver)", + 'simulator', + default_value='gazebo', + description='The simulator to use (gazebo or gzserver)', ) declare_map_yaml_cmd = DeclareLaunchArgument( - "map", - default_value=os.path.join(bringup_dir, "maps", "turtlebot3_world.yaml"), - description="Full path to map file to load", + 'map', + default_value=os.path.join(bringup_dir, 'maps', 'turtlebot3_world.yaml'), + description='Full path to map file to load', ) declare_params_file_cmd = DeclareLaunchArgument( - "params_file", + 'params_file', default_value=os.path.join( - bringup_dir, "params", "nav2_multirobot_params_all.yaml" + bringup_dir, 'params', 'nav2_multirobot_params_all.yaml' ), - description="Full path to the ROS2 parameters file to use for all launched nodes", + description='Full path to the ROS2 parameters file to use for all launched nodes', ) declare_autostart_cmd = DeclareLaunchArgument( - "autostart", - default_value="false", - description="Automatically startup the stacks", + 'autostart', + default_value='false', + description='Automatically startup the stacks', ) declare_rviz_config_file_cmd = DeclareLaunchArgument( - "rviz_config", - default_value=os.path.join(bringup_dir, "rviz", "nav2_namespaced_view.rviz"), - description="Full path to the RVIZ config file to use.", + 'rviz_config', + default_value=os.path.join(bringup_dir, 'rviz', 'nav2_namespaced_view.rviz'), + description='Full path to the RVIZ config file to use.', ) declare_use_robot_state_pub_cmd = DeclareLaunchArgument( - "use_robot_state_pub", - default_value="True", - description="Whether to start the robot state publisher", + 'use_robot_state_pub', + default_value='True', + description='Whether to start the robot state publisher', ) declare_use_rviz_cmd = DeclareLaunchArgument( - "use_rviz", default_value="True", description="Whether to start RVIZ" + 'use_rviz', default_value='True', description='Whether to start RVIZ' ) # Start Gazebo with plugin providing the robot spawning service start_gazebo_cmd = ExecuteProcess( cmd=[ simulator, - "--verbose", - "-s", - "libgazebo_ros_init.so", - "-s", - "libgazebo_ros_factory.so", + '--verbose', + '-s', + 'libgazebo_ros_init.so', + '-s', + 'libgazebo_ros_factory.so', world, ], - output="screen", + output='screen', ) - robots_list = ParseMultiRobotPose("robots").value() + robots_list = ParseMultiRobotPose('robots').value() # Define commands for launching the navigation instances bringup_cmd_group = [] @@ -130,45 +130,45 @@ def generate_launch_description(): [ LogInfo( msg=[ - "Launching namespace=", + 'Launching namespace=', robot_name, - " init_pose=", + ' init_pose=', str(init_pose), ] ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(launch_dir, "rviz_launch.py") + os.path.join(launch_dir, 'rviz_launch.py') ), condition=IfCondition(use_rviz), launch_arguments={ - "namespace": TextSubstitution(text=robot_name), - "use_namespace": "True", - "rviz_config": rviz_config_file, + 'namespace': TextSubstitution(text=robot_name), + 'use_namespace': 'True', + 'rviz_config': rviz_config_file, }.items(), ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "tb3_simulation_launch.py") + os.path.join(bringup_dir, 'launch', 'tb3_simulation_launch.py') ), launch_arguments={ - "namespace": robot_name, - "use_namespace": "True", - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": params_file, - "autostart": autostart, - "use_rviz": "False", - "use_simulator": "False", - "headless": "False", - "use_robot_state_pub": use_robot_state_pub, - "x_pose": TextSubstitution(text=str(init_pose["x"])), - "y_pose": TextSubstitution(text=str(init_pose["y"])), - "z_pose": TextSubstitution(text=str(init_pose["z"])), - "roll": TextSubstitution(text=str(init_pose["roll"])), - "pitch": TextSubstitution(text=str(init_pose["pitch"])), - "yaw": TextSubstitution(text=str(init_pose["yaw"])), - "robot_name": TextSubstitution(text=robot_name), + 'namespace': robot_name, + 'use_namespace': 'True', + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': params_file, + 'autostart': autostart, + 'use_rviz': 'False', + 'use_simulator': 'False', + 'headless': 'False', + 'use_robot_state_pub': use_robot_state_pub, + 'x_pose': TextSubstitution(text=str(init_pose['x'])), + 'y_pose': TextSubstitution(text=str(init_pose['y'])), + 'z_pose': TextSubstitution(text=str(init_pose['z'])), + 'roll': TextSubstitution(text=str(init_pose['roll'])), + 'pitch': TextSubstitution(text=str(init_pose['pitch'])), + 'yaw': TextSubstitution(text=str(init_pose['yaw'])), + 'robot_name': TextSubstitution(text=robot_name), }.items(), ), ] @@ -192,28 +192,28 @@ def generate_launch_description(): # Add the actions to start gazebo, robots and simulations ld.add_action(start_gazebo_cmd) - ld.add_action(LogInfo(msg=["number_of_robots=", str(len(robots_list))])) + ld.add_action(LogInfo(msg=['number_of_robots=', str(len(robots_list))])) ld.add_action( - LogInfo(condition=IfCondition(log_settings), msg=["map yaml: ", map_yaml_file]) + LogInfo(condition=IfCondition(log_settings), msg=['map yaml: ', map_yaml_file]) ) ld.add_action( - LogInfo(condition=IfCondition(log_settings), msg=["params yaml: ", params_file]) + LogInfo(condition=IfCondition(log_settings), msg=['params yaml: ', params_file]) ) ld.add_action( LogInfo( condition=IfCondition(log_settings), - msg=["rviz config file: ", rviz_config_file], + msg=['rviz config file: ', rviz_config_file], ) ) ld.add_action( LogInfo( condition=IfCondition(log_settings), - msg=["using robot state pub: ", use_robot_state_pub], + msg=['using robot state pub: ', use_robot_state_pub], ) ) ld.add_action( - LogInfo(condition=IfCondition(log_settings), msg=["autostart: ", autostart]) + LogInfo(condition=IfCondition(log_settings), msg=['autostart: ', autostart]) ) for cmd in bringup_cmd_group: diff --git a/nav2_bringup/launch/localization_launch.py b/nav2_bringup/launch/localization_launch.py index f32b96700f0..42afb5c2cb5 100644 --- a/nav2_bringup/launch/localization_launch.py +++ b/nav2_bringup/launch/localization_launch.py @@ -31,20 +31,20 @@ def generate_launch_description(): # Get the launch directory - bringup_dir = get_package_share_directory("nav2_bringup") + bringup_dir = get_package_share_directory('nav2_bringup') - namespace = LaunchConfiguration("namespace") - map_yaml_file = LaunchConfiguration("map") - use_sim_time = LaunchConfiguration("use_sim_time") - autostart = LaunchConfiguration("autostart") - params_file = LaunchConfiguration("params_file") - use_composition = LaunchConfiguration("use_composition") - container_name = LaunchConfiguration("container_name") - container_name_full = (namespace, "/", container_name) - use_respawn = LaunchConfiguration("use_respawn") - log_level = LaunchConfiguration("log_level") + namespace = LaunchConfiguration('namespace') + map_yaml_file = LaunchConfiguration('map') + use_sim_time = LaunchConfiguration('use_sim_time') + autostart = LaunchConfiguration('autostart') + params_file = LaunchConfiguration('params_file') + use_composition = LaunchConfiguration('use_composition') + container_name = LaunchConfiguration('container_name') + container_name_full = (namespace, '/', container_name) + use_respawn = LaunchConfiguration('use_respawn') + log_level = LaunchConfiguration('log_level') - lifecycle_nodes = ["map_server", "amcl"] + lifecycle_nodes = ['map_server', 'amcl'] # Map fully qualified names to relative ones so the node's namespace can be prepended. # In case of the transforms (tf), currently, there doesn't seem to be a better alternative @@ -52,7 +52,7 @@ def generate_launch_description(): # https://github.com/ros/robot_state_publisher/pull/30 # TODO(orduno) Substitute with `PushNodeRemapping` # https://github.com/ros2/launch_ros/issues/56 - remappings = [("/tf", "tf"), ("/tf_static", "tf_static")] + remappings = [('/tf', 'tf'), ('/tf_static', 'tf_static')] configured_params = ParameterFile( RewrittenYaml( @@ -65,107 +65,107 @@ def generate_launch_description(): ) stdout_linebuf_envvar = SetEnvironmentVariable( - "RCUTILS_LOGGING_BUFFERED_STREAM", "1" + 'RCUTILS_LOGGING_BUFFERED_STREAM', '1' ) declare_namespace_cmd = DeclareLaunchArgument( - "namespace", default_value="", description="Top-level namespace" + 'namespace', default_value='', description='Top-level namespace' ) declare_map_yaml_cmd = DeclareLaunchArgument( - "map", default_value="", description="Full path to map yaml file to load" + 'map', default_value='', description='Full path to map yaml file to load' ) declare_use_sim_time_cmd = DeclareLaunchArgument( - "use_sim_time", - default_value="false", - description="Use simulation (Gazebo) clock if true", + 'use_sim_time', + default_value='false', + description='Use simulation (Gazebo) clock if true', ) declare_params_file_cmd = DeclareLaunchArgument( - "params_file", - default_value=os.path.join(bringup_dir, "params", "nav2_params.yaml"), - description="Full path to the ROS2 parameters file to use for all launched nodes", + 'params_file', + default_value=os.path.join(bringup_dir, 'params', 'nav2_params.yaml'), + description='Full path to the ROS2 parameters file to use for all launched nodes', ) declare_autostart_cmd = DeclareLaunchArgument( - "autostart", - default_value="true", - description="Automatically startup the nav2 stack", + 'autostart', + default_value='true', + description='Automatically startup the nav2 stack', ) declare_use_composition_cmd = DeclareLaunchArgument( - "use_composition", - default_value="False", - description="Use composed bringup if True", + 'use_composition', + default_value='False', + description='Use composed bringup if True', ) declare_container_name_cmd = DeclareLaunchArgument( - "container_name", - default_value="nav2_container", - description="the name of conatiner that nodes will load in if use composition", + 'container_name', + default_value='nav2_container', + description='the name of conatiner that nodes will load in if use composition', ) declare_use_respawn_cmd = DeclareLaunchArgument( - "use_respawn", - default_value="False", - description="Whether to respawn if a node crashes. Applied when composition is disabled.", + 'use_respawn', + default_value='False', + description='Whether to respawn if a node crashes. Applied when composition is disabled.', ) declare_log_level_cmd = DeclareLaunchArgument( - "log_level", default_value="info", description="log level" + 'log_level', default_value='info', description='log level' ) load_nodes = GroupAction( - condition=IfCondition(PythonExpression(["not ", use_composition])), + condition=IfCondition(PythonExpression(['not ', use_composition])), actions=[ - SetParameter("use_sim_time", use_sim_time), + SetParameter('use_sim_time', use_sim_time), Node( condition=IfCondition( - EqualsSubstitution(LaunchConfiguration("map"), "") + EqualsSubstitution(LaunchConfiguration('map'), '') ), - package="nav2_map_server", - executable="map_server", - name="map_server", - output="screen", + package='nav2_map_server', + executable='map_server', + name='map_server', + output='screen', respawn=use_respawn, respawn_delay=2.0, parameters=[configured_params], - arguments=["--ros-args", "--log-level", log_level], + arguments=['--ros-args', '--log-level', log_level], remappings=remappings, ), Node( condition=IfCondition( - NotEqualsSubstitution(LaunchConfiguration("map"), "") + NotEqualsSubstitution(LaunchConfiguration('map'), '') ), - package="nav2_map_server", - executable="map_server", - name="map_server", - output="screen", + package='nav2_map_server', + executable='map_server', + name='map_server', + output='screen', respawn=use_respawn, respawn_delay=2.0, - parameters=[configured_params, {"yaml_filename": map_yaml_file}], - arguments=["--ros-args", "--log-level", log_level], + parameters=[configured_params, {'yaml_filename': map_yaml_file}], + arguments=['--ros-args', '--log-level', log_level], remappings=remappings, ), Node( - package="nav2_amcl", - executable="amcl", - name="amcl", - output="screen", + package='nav2_amcl', + executable='amcl', + name='amcl', + output='screen', respawn=use_respawn, respawn_delay=2.0, parameters=[configured_params], - arguments=["--ros-args", "--log-level", log_level], + arguments=['--ros-args', '--log-level', log_level], remappings=remappings, ), Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager_localization", - output="screen", - arguments=["--ros-args", "--log-level", log_level], - parameters=[{"autostart": autostart}, {"node_names": lifecycle_nodes}], + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager_localization', + output='screen', + arguments=['--ros-args', '--log-level', log_level], + parameters=[{'autostart': autostart}, {'node_names': lifecycle_nodes}], ), ], ) @@ -177,17 +177,17 @@ def generate_launch_description(): load_composable_nodes = GroupAction( condition=IfCondition(use_composition), actions=[ - SetParameter("use_sim_time", use_sim_time), + SetParameter('use_sim_time', use_sim_time), LoadComposableNodes( target_container=container_name_full, condition=IfCondition( - EqualsSubstitution(LaunchConfiguration("map"), "") + EqualsSubstitution(LaunchConfiguration('map'), '') ), composable_node_descriptions=[ ComposableNode( - package="nav2_map_server", - plugin="nav2_map_server::MapServer", - name="map_server", + package='nav2_map_server', + plugin='nav2_map_server::MapServer', + name='map_server', parameters=[configured_params], remappings=remappings, ), @@ -196,16 +196,16 @@ def generate_launch_description(): LoadComposableNodes( target_container=container_name_full, condition=IfCondition( - NotEqualsSubstitution(LaunchConfiguration("map"), "") + NotEqualsSubstitution(LaunchConfiguration('map'), '') ), composable_node_descriptions=[ ComposableNode( - package="nav2_map_server", - plugin="nav2_map_server::MapServer", - name="map_server", + package='nav2_map_server', + plugin='nav2_map_server::MapServer', + name='map_server', parameters=[ configured_params, - {"yaml_filename": map_yaml_file}, + {'yaml_filename': map_yaml_file}, ], remappings=remappings, ), @@ -215,18 +215,18 @@ def generate_launch_description(): target_container=container_name_full, composable_node_descriptions=[ ComposableNode( - package="nav2_amcl", - plugin="nav2_amcl::AmclNode", - name="amcl", + package='nav2_amcl', + plugin='nav2_amcl::AmclNode', + name='amcl', parameters=[configured_params], remappings=remappings, ), ComposableNode( - package="nav2_lifecycle_manager", - plugin="nav2_lifecycle_manager::LifecycleManager", - name="lifecycle_manager_localization", + package='nav2_lifecycle_manager', + plugin='nav2_lifecycle_manager::LifecycleManager', + name='lifecycle_manager_localization', parameters=[ - {"autostart": autostart, "node_names": lifecycle_nodes} + {'autostart': autostart, 'node_names': lifecycle_nodes} ], ), ], diff --git a/nav2_bringup/launch/navigation_launch.py b/nav2_bringup/launch/navigation_launch.py index 53fd675702b..2f438c66e03 100644 --- a/nav2_bringup/launch/navigation_launch.py +++ b/nav2_bringup/launch/navigation_launch.py @@ -28,26 +28,26 @@ def generate_launch_description(): # Get the launch directory - bringup_dir = get_package_share_directory("nav2_bringup") + bringup_dir = get_package_share_directory('nav2_bringup') - namespace = LaunchConfiguration("namespace") - use_sim_time = LaunchConfiguration("use_sim_time") - autostart = LaunchConfiguration("autostart") - params_file = LaunchConfiguration("params_file") - use_composition = LaunchConfiguration("use_composition") - container_name = LaunchConfiguration("container_name") - container_name_full = (namespace, "/", container_name) - use_respawn = LaunchConfiguration("use_respawn") - log_level = LaunchConfiguration("log_level") + namespace = LaunchConfiguration('namespace') + use_sim_time = LaunchConfiguration('use_sim_time') + autostart = LaunchConfiguration('autostart') + params_file = LaunchConfiguration('params_file') + use_composition = LaunchConfiguration('use_composition') + container_name = LaunchConfiguration('container_name') + container_name_full = (namespace, '/', container_name) + use_respawn = LaunchConfiguration('use_respawn') + log_level = LaunchConfiguration('log_level') lifecycle_nodes = [ - "controller_server", - "smoother_server", - "planner_server", - "behavior_server", - "bt_navigator", - "waypoint_follower", - "velocity_smoother", + 'controller_server', + 'smoother_server', + 'planner_server', + 'behavior_server', + 'bt_navigator', + 'waypoint_follower', + 'velocity_smoother', ] # Map fully qualified names to relative ones so the node's namespace can be prepended. @@ -56,10 +56,10 @@ def generate_launch_description(): # https://github.com/ros/robot_state_publisher/pull/30 # TODO(orduno) Substitute with `PushNodeRemapping` # https://github.com/ros2/launch_ros/issues/56 - remappings = [("/tf", "tf"), ("/tf_static", "tf_static")] + remappings = [('/tf', 'tf'), ('/tf_static', 'tf_static')] # Create our own temporary YAML files that include substitutions - param_substitutions = {"autostart": autostart} + param_substitutions = {'autostart': autostart} configured_params = ParameterFile( RewrittenYaml( @@ -72,141 +72,141 @@ def generate_launch_description(): ) stdout_linebuf_envvar = SetEnvironmentVariable( - "RCUTILS_LOGGING_BUFFERED_STREAM", "1" + 'RCUTILS_LOGGING_BUFFERED_STREAM', '1' ) declare_namespace_cmd = DeclareLaunchArgument( - "namespace", default_value="", description="Top-level namespace" + 'namespace', default_value='', description='Top-level namespace' ) declare_use_sim_time_cmd = DeclareLaunchArgument( - "use_sim_time", - default_value="false", - description="Use simulation (Gazebo) clock if true", + 'use_sim_time', + default_value='false', + description='Use simulation (Gazebo) clock if true', ) declare_params_file_cmd = DeclareLaunchArgument( - "params_file", - default_value=os.path.join(bringup_dir, "params", "nav2_params.yaml"), - description="Full path to the ROS2 parameters file to use for all launched nodes", + 'params_file', + default_value=os.path.join(bringup_dir, 'params', 'nav2_params.yaml'), + description='Full path to the ROS2 parameters file to use for all launched nodes', ) declare_autostart_cmd = DeclareLaunchArgument( - "autostart", - default_value="true", - description="Automatically startup the nav2 stack", + 'autostart', + default_value='true', + description='Automatically startup the nav2 stack', ) declare_use_composition_cmd = DeclareLaunchArgument( - "use_composition", - default_value="False", - description="Use composed bringup if True", + 'use_composition', + default_value='False', + description='Use composed bringup if True', ) declare_container_name_cmd = DeclareLaunchArgument( - "container_name", - default_value="nav2_container", - description="the name of conatiner that nodes will load in if use composition", + 'container_name', + default_value='nav2_container', + description='the name of conatiner that nodes will load in if use composition', ) declare_use_respawn_cmd = DeclareLaunchArgument( - "use_respawn", - default_value="False", - description="Whether to respawn if a node crashes. Applied when composition is disabled.", + 'use_respawn', + default_value='False', + description='Whether to respawn if a node crashes. Applied when composition is disabled.', ) declare_log_level_cmd = DeclareLaunchArgument( - "log_level", default_value="info", description="log level" + 'log_level', default_value='info', description='log level' ) load_nodes = GroupAction( - condition=IfCondition(PythonExpression(["not ", use_composition])), + condition=IfCondition(PythonExpression(['not ', use_composition])), actions=[ - SetParameter("use_sim_time", use_sim_time), + SetParameter('use_sim_time', use_sim_time), Node( - package="nav2_controller", - executable="controller_server", - output="screen", + package='nav2_controller', + executable='controller_server', + output='screen', respawn=use_respawn, respawn_delay=2.0, parameters=[configured_params], - arguments=["--ros-args", "--log-level", log_level], - remappings=remappings + [("cmd_vel", "cmd_vel_nav")], + arguments=['--ros-args', '--log-level', log_level], + remappings=remappings + [('cmd_vel', 'cmd_vel_nav')], ), Node( - package="nav2_smoother", - executable="smoother_server", - name="smoother_server", - output="screen", + package='nav2_smoother', + executable='smoother_server', + name='smoother_server', + output='screen', respawn=use_respawn, respawn_delay=2.0, parameters=[configured_params], - arguments=["--ros-args", "--log-level", log_level], + arguments=['--ros-args', '--log-level', log_level], remappings=remappings, ), Node( - package="nav2_planner", - executable="planner_server", - name="planner_server", - output="screen", + package='nav2_planner', + executable='planner_server', + name='planner_server', + output='screen', respawn=use_respawn, respawn_delay=2.0, parameters=[configured_params], - arguments=["--ros-args", "--log-level", log_level], + arguments=['--ros-args', '--log-level', log_level], remappings=remappings, ), Node( - package="nav2_behaviors", - executable="behavior_server", - name="behavior_server", - output="screen", + package='nav2_behaviors', + executable='behavior_server', + name='behavior_server', + output='screen', respawn=use_respawn, respawn_delay=2.0, parameters=[configured_params], - arguments=["--ros-args", "--log-level", log_level], + arguments=['--ros-args', '--log-level', log_level], remappings=remappings, ), Node( - package="nav2_bt_navigator", - executable="bt_navigator", - name="bt_navigator", - output="screen", + package='nav2_bt_navigator', + executable='bt_navigator', + name='bt_navigator', + output='screen', respawn=use_respawn, respawn_delay=2.0, parameters=[configured_params], - arguments=["--ros-args", "--log-level", log_level], + arguments=['--ros-args', '--log-level', log_level], remappings=remappings, ), Node( - package="nav2_waypoint_follower", - executable="waypoint_follower", - name="waypoint_follower", - output="screen", + package='nav2_waypoint_follower', + executable='waypoint_follower', + name='waypoint_follower', + output='screen', respawn=use_respawn, respawn_delay=2.0, parameters=[configured_params], - arguments=["--ros-args", "--log-level", log_level], + arguments=['--ros-args', '--log-level', log_level], remappings=remappings, ), Node( - package="nav2_velocity_smoother", - executable="velocity_smoother", - name="velocity_smoother", - output="screen", + package='nav2_velocity_smoother', + executable='velocity_smoother', + name='velocity_smoother', + output='screen', respawn=use_respawn, respawn_delay=2.0, parameters=[configured_params], - arguments=["--ros-args", "--log-level", log_level], + arguments=['--ros-args', '--log-level', log_level], remappings=remappings - + [("cmd_vel", "cmd_vel_nav"), ("cmd_vel_smoothed", "cmd_vel")], + + [('cmd_vel', 'cmd_vel_nav'), ('cmd_vel_smoothed', 'cmd_vel')], ), Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager_navigation", - output="screen", - arguments=["--ros-args", "--log-level", log_level], - parameters=[{"autostart": autostart}, {"node_names": lifecycle_nodes}], + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager_navigation', + output='screen', + arguments=['--ros-args', '--log-level', log_level], + parameters=[{'autostart': autostart}, {'node_names': lifecycle_nodes}], ), ], ) @@ -214,66 +214,66 @@ def generate_launch_description(): load_composable_nodes = GroupAction( condition=IfCondition(use_composition), actions=[ - SetParameter("use_sim_time", use_sim_time), + SetParameter('use_sim_time', use_sim_time), LoadComposableNodes( target_container=container_name_full, composable_node_descriptions=[ ComposableNode( - package="nav2_controller", - plugin="nav2_controller::ControllerServer", - name="controller_server", + package='nav2_controller', + plugin='nav2_controller::ControllerServer', + name='controller_server', parameters=[configured_params], - remappings=remappings + [("cmd_vel", "cmd_vel_nav")], + remappings=remappings + [('cmd_vel', 'cmd_vel_nav')], ), ComposableNode( - package="nav2_smoother", - plugin="nav2_smoother::SmootherServer", - name="smoother_server", + package='nav2_smoother', + plugin='nav2_smoother::SmootherServer', + name='smoother_server', parameters=[configured_params], remappings=remappings, ), ComposableNode( - package="nav2_planner", - plugin="nav2_planner::PlannerServer", - name="planner_server", + package='nav2_planner', + plugin='nav2_planner::PlannerServer', + name='planner_server', parameters=[configured_params], remappings=remappings, ), ComposableNode( - package="nav2_behaviors", - plugin="behavior_server::BehaviorServer", - name="behavior_server", + package='nav2_behaviors', + plugin='behavior_server::BehaviorServer', + name='behavior_server', parameters=[configured_params], remappings=remappings, ), ComposableNode( - package="nav2_bt_navigator", - plugin="nav2_bt_navigator::BtNavigator", - name="bt_navigator", + package='nav2_bt_navigator', + plugin='nav2_bt_navigator::BtNavigator', + name='bt_navigator', parameters=[configured_params], remappings=remappings, ), ComposableNode( - package="nav2_waypoint_follower", - plugin="nav2_waypoint_follower::WaypointFollower", - name="waypoint_follower", + package='nav2_waypoint_follower', + plugin='nav2_waypoint_follower::WaypointFollower', + name='waypoint_follower', parameters=[configured_params], remappings=remappings, ), ComposableNode( - package="nav2_velocity_smoother", - plugin="nav2_velocity_smoother::VelocitySmoother", - name="velocity_smoother", + package='nav2_velocity_smoother', + plugin='nav2_velocity_smoother::VelocitySmoother', + name='velocity_smoother', parameters=[configured_params], remappings=remappings - + [("cmd_vel", "cmd_vel_nav"), ("cmd_vel_smoothed", "cmd_vel")], + + [('cmd_vel', 'cmd_vel_nav'), ('cmd_vel_smoothed', 'cmd_vel')], ), ComposableNode( - package="nav2_lifecycle_manager", - plugin="nav2_lifecycle_manager::LifecycleManager", - name="lifecycle_manager_navigation", + package='nav2_lifecycle_manager', + plugin='nav2_lifecycle_manager::LifecycleManager', + name='lifecycle_manager_navigation', parameters=[ - {"autostart": autostart, "node_names": lifecycle_nodes} + {'autostart': autostart, 'node_names': lifecycle_nodes} ], ), ], diff --git a/nav2_bringup/launch/rviz_launch.py b/nav2_bringup/launch/rviz_launch.py index 68361fc08c4..dee33f26d63 100644 --- a/nav2_bringup/launch/rviz_launch.py +++ b/nav2_bringup/launch/rviz_launch.py @@ -28,63 +28,63 @@ def generate_launch_description(): # Get the launch directory - bringup_dir = get_package_share_directory("nav2_bringup") + bringup_dir = get_package_share_directory('nav2_bringup') # Create the launch configuration variables - namespace = LaunchConfiguration("namespace") - use_namespace = LaunchConfiguration("use_namespace") - rviz_config_file = LaunchConfiguration("rviz_config") + namespace = LaunchConfiguration('namespace') + use_namespace = LaunchConfiguration('use_namespace') + rviz_config_file = LaunchConfiguration('rviz_config') # Declare the launch arguments declare_namespace_cmd = DeclareLaunchArgument( - "namespace", - default_value="navigation", + 'namespace', + default_value='navigation', description=( - "Top-level namespace. The value will be used to replace the " - " keyword on the rviz config file." + 'Top-level namespace. The value will be used to replace the ' + ' keyword on the rviz config file.' ), ) declare_use_namespace_cmd = DeclareLaunchArgument( - "use_namespace", - default_value="false", - description="Whether to apply a namespace to the navigation stack", + 'use_namespace', + default_value='false', + description='Whether to apply a namespace to the navigation stack', ) declare_rviz_config_file_cmd = DeclareLaunchArgument( - "rviz_config", - default_value=os.path.join(bringup_dir, "rviz", "nav2_default_view.rviz"), - description="Full path to the RVIZ config file to use", + 'rviz_config', + default_value=os.path.join(bringup_dir, 'rviz', 'nav2_default_view.rviz'), + description='Full path to the RVIZ config file to use', ) # Launch rviz start_rviz_cmd = Node( condition=UnlessCondition(use_namespace), - package="rviz2", - executable="rviz2", - arguments=["-d", rviz_config_file], - output="screen", + package='rviz2', + executable='rviz2', + arguments=['-d', rviz_config_file], + output='screen', ) namespaced_rviz_config_file = ReplaceString( source_file=rviz_config_file, - replacements={"": ("/", namespace)}, + replacements={'': ('/', namespace)}, ) start_namespaced_rviz_cmd = Node( condition=IfCondition(use_namespace), - package="rviz2", - executable="rviz2", + package='rviz2', + executable='rviz2', namespace=namespace, - arguments=["-d", namespaced_rviz_config_file], - output="screen", + arguments=['-d', namespaced_rviz_config_file], + output='screen', remappings=[ - ("/map", "map"), - ("/tf", "tf"), - ("/tf_static", "tf_static"), - ("/goal_pose", "goal_pose"), - ("/clicked_point", "clicked_point"), - ("/initialpose", "initialpose"), + ('/map', 'map'), + ('/tf', 'tf'), + ('/tf_static', 'tf_static'), + ('/goal_pose', 'goal_pose'), + ('/clicked_point', 'clicked_point'), + ('/initialpose', 'initialpose'), ], ) @@ -92,7 +92,7 @@ def generate_launch_description(): condition=UnlessCondition(use_namespace), event_handler=OnProcessExit( target_action=start_rviz_cmd, - on_exit=EmitEvent(event=Shutdown(reason="rviz exited")), + on_exit=EmitEvent(event=Shutdown(reason='rviz exited')), ), ) @@ -100,7 +100,7 @@ def generate_launch_description(): condition=IfCondition(use_namespace), event_handler=OnProcessExit( target_action=start_namespaced_rviz_cmd, - on_exit=EmitEvent(event=Shutdown(reason="rviz exited")), + on_exit=EmitEvent(event=Shutdown(reason='rviz exited')), ), ) diff --git a/nav2_bringup/launch/slam_launch.py b/nav2_bringup/launch/slam_launch.py index 702051b7b97..a806d260ce5 100644 --- a/nav2_bringup/launch/slam_launch.py +++ b/nav2_bringup/launch/slam_launch.py @@ -28,20 +28,20 @@ def generate_launch_description(): # Input parameters declaration - namespace = LaunchConfiguration("namespace") - params_file = LaunchConfiguration("params_file") - use_sim_time = LaunchConfiguration("use_sim_time") - autostart = LaunchConfiguration("autostart") - use_respawn = LaunchConfiguration("use_respawn") - log_level = LaunchConfiguration("log_level") + namespace = LaunchConfiguration('namespace') + params_file = LaunchConfiguration('params_file') + use_sim_time = LaunchConfiguration('use_sim_time') + autostart = LaunchConfiguration('autostart') + use_respawn = LaunchConfiguration('use_respawn') + log_level = LaunchConfiguration('log_level') # Variables - lifecycle_nodes = ["map_saver"] + lifecycle_nodes = ['map_saver'] # Getting directories and launch-files - bringup_dir = get_package_share_directory("nav2_bringup") - slam_toolbox_dir = get_package_share_directory("slam_toolbox") - slam_launch_file = os.path.join(slam_toolbox_dir, "launch", "online_sync_launch.py") + bringup_dir = get_package_share_directory('nav2_bringup') + slam_toolbox_dir = get_package_share_directory('slam_toolbox') + slam_launch_file = os.path.join(slam_toolbox_dir, 'launch', 'online_sync_launch.py') # Create our own temporary YAML files that include substitutions configured_params = ParameterFile( @@ -56,58 +56,58 @@ def generate_launch_description(): # Declare the launch arguments declare_namespace_cmd = DeclareLaunchArgument( - "namespace", default_value="", description="Top-level namespace" + 'namespace', default_value='', description='Top-level namespace' ) declare_params_file_cmd = DeclareLaunchArgument( - "params_file", - default_value=os.path.join(bringup_dir, "params", "nav2_params.yaml"), - description="Full path to the ROS2 parameters file to use for all launched nodes", + 'params_file', + default_value=os.path.join(bringup_dir, 'params', 'nav2_params.yaml'), + description='Full path to the ROS2 parameters file to use for all launched nodes', ) declare_use_sim_time_cmd = DeclareLaunchArgument( - "use_sim_time", - default_value="True", - description="Use simulation (Gazebo) clock if true", + 'use_sim_time', + default_value='True', + description='Use simulation (Gazebo) clock if true', ) declare_autostart_cmd = DeclareLaunchArgument( - "autostart", - default_value="True", - description="Automatically startup the nav2 stack", + 'autostart', + default_value='True', + description='Automatically startup the nav2 stack', ) declare_use_respawn_cmd = DeclareLaunchArgument( - "use_respawn", - default_value="False", - description="Whether to respawn if a node crashes. Applied when composition is disabled.", + 'use_respawn', + default_value='False', + description='Whether to respawn if a node crashes. Applied when composition is disabled.', ) declare_log_level_cmd = DeclareLaunchArgument( - "log_level", default_value="info", description="log level" + 'log_level', default_value='info', description='log level' ) # Nodes launching commands start_map_server = GroupAction( actions=[ - SetParameter("use_sim_time", use_sim_time), + SetParameter('use_sim_time', use_sim_time), Node( - package="nav2_map_server", - executable="map_saver_server", - output="screen", + package='nav2_map_server', + executable='map_saver_server', + output='screen', respawn=use_respawn, respawn_delay=2.0, - arguments=["--ros-args", "--log-level", log_level], + arguments=['--ros-args', '--log-level', log_level], parameters=[configured_params], ), Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager_slam", - output="screen", - arguments=["--ros-args", "--log-level", log_level], - parameters=[{"autostart": autostart}, {"node_names": lifecycle_nodes}], + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager_slam', + output='screen', + arguments=['--ros-args', '--log-level', log_level], + parameters=[{'autostart': autostart}, {'node_names': lifecycle_nodes}], ), ] ) @@ -116,20 +116,20 @@ def generate_launch_description(): # LaunchConfiguration, or it will be passed automatically to slam_toolbox and will not load # the default file has_slam_toolbox_params = HasNodeParams( - source_file=params_file, node_name="slam_toolbox" + source_file=params_file, node_name='slam_toolbox' ) start_slam_toolbox_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource(slam_launch_file), - launch_arguments={"use_sim_time": use_sim_time}.items(), + launch_arguments={'use_sim_time': use_sim_time}.items(), condition=UnlessCondition(has_slam_toolbox_params), ) start_slam_toolbox_cmd_with_params = IncludeLaunchDescription( PythonLaunchDescriptionSource(slam_launch_file), launch_arguments={ - "use_sim_time": use_sim_time, - "slam_params_file": params_file, + 'use_sim_time': use_sim_time, + 'slam_params_file': params_file, }.items(), condition=IfCondition(has_slam_toolbox_params), ) diff --git a/nav2_bringup/launch/tb3_simulation_launch.py b/nav2_bringup/launch/tb3_simulation_launch.py index 351dc1d8f79..6598ac94ba8 100644 --- a/nav2_bringup/launch/tb3_simulation_launch.py +++ b/nav2_bringup/launch/tb3_simulation_launch.py @@ -32,39 +32,39 @@ def generate_launch_description(): # Get the launch directory - bringup_dir = get_package_share_directory("nav2_bringup") - launch_dir = os.path.join(bringup_dir, "launch") + bringup_dir = get_package_share_directory('nav2_bringup') + launch_dir = os.path.join(bringup_dir, 'launch') # This checks that tb3 exists needed for the URDF. If not using TB3, its safe to remove. - _ = get_package_share_directory("turtlebot3_gazebo") + _ = get_package_share_directory('turtlebot3_gazebo') # Create the launch configuration variables - slam = LaunchConfiguration("slam") - namespace = LaunchConfiguration("namespace") - use_namespace = LaunchConfiguration("use_namespace") - map_yaml_file = LaunchConfiguration("map") - use_sim_time = LaunchConfiguration("use_sim_time") - params_file = LaunchConfiguration("params_file") - autostart = LaunchConfiguration("autostart") - use_composition = LaunchConfiguration("use_composition") - use_respawn = LaunchConfiguration("use_respawn") + slam = LaunchConfiguration('slam') + namespace = LaunchConfiguration('namespace') + use_namespace = LaunchConfiguration('use_namespace') + map_yaml_file = LaunchConfiguration('map') + use_sim_time = LaunchConfiguration('use_sim_time') + params_file = LaunchConfiguration('params_file') + autostart = LaunchConfiguration('autostart') + use_composition = LaunchConfiguration('use_composition') + use_respawn = LaunchConfiguration('use_respawn') # Launch configuration variables specific to simulation - rviz_config_file = LaunchConfiguration("rviz_config_file") - use_simulator = LaunchConfiguration("use_simulator") - use_robot_state_pub = LaunchConfiguration("use_robot_state_pub") - use_rviz = LaunchConfiguration("use_rviz") - headless = LaunchConfiguration("headless") - world = LaunchConfiguration("world") + rviz_config_file = LaunchConfiguration('rviz_config_file') + use_simulator = LaunchConfiguration('use_simulator') + use_robot_state_pub = LaunchConfiguration('use_robot_state_pub') + use_rviz = LaunchConfiguration('use_rviz') + headless = LaunchConfiguration('headless') + world = LaunchConfiguration('world') pose = { - "x": LaunchConfiguration("x_pose", default="-2.00"), - "y": LaunchConfiguration("y_pose", default="-0.50"), - "z": LaunchConfiguration("z_pose", default="0.01"), - "R": LaunchConfiguration("roll", default="0.00"), - "P": LaunchConfiguration("pitch", default="0.00"), - "Y": LaunchConfiguration("yaw", default="0.00"), + 'x': LaunchConfiguration('x_pose', default='-2.00'), + 'y': LaunchConfiguration('y_pose', default='-0.50'), + 'z': LaunchConfiguration('z_pose', default='0.01'), + 'R': LaunchConfiguration('roll', default='0.00'), + 'P': LaunchConfiguration('pitch', default='0.00'), + 'Y': LaunchConfiguration('yaw', default='0.00'), } - robot_name = LaunchConfiguration("robot_name") - robot_sdf = LaunchConfiguration("robot_sdf") + robot_name = LaunchConfiguration('robot_name') + robot_sdf = LaunchConfiguration('robot_sdf') # Map fully qualified names to relative ones so the node's namespace can be prepended. # In case of the transforms (tf), currently, there doesn't seem to be a better alternative @@ -72,192 +72,192 @@ def generate_launch_description(): # https://github.com/ros/robot_state_publisher/pull/30 # TODO(orduno) Substitute with `PushNodeRemapping` # https://github.com/ros2/launch_ros/issues/56 - remappings = [("/tf", "tf"), ("/tf_static", "tf_static")] + remappings = [('/tf', 'tf'), ('/tf_static', 'tf_static')] # Declare the launch arguments declare_namespace_cmd = DeclareLaunchArgument( - "namespace", default_value="", description="Top-level namespace" + 'namespace', default_value='', description='Top-level namespace' ) declare_use_namespace_cmd = DeclareLaunchArgument( - "use_namespace", - default_value="false", - description="Whether to apply a namespace to the navigation stack", + 'use_namespace', + default_value='false', + description='Whether to apply a namespace to the navigation stack', ) declare_slam_cmd = DeclareLaunchArgument( - "slam", default_value="False", description="Whether run a SLAM" + 'slam', default_value='False', description='Whether run a SLAM' ) declare_map_yaml_cmd = DeclareLaunchArgument( - "map", - default_value=os.path.join(bringup_dir, "maps", "turtlebot3_world.yaml"), - description="Full path to map file to load", + 'map', + default_value=os.path.join(bringup_dir, 'maps', 'turtlebot3_world.yaml'), + description='Full path to map file to load', ) declare_use_sim_time_cmd = DeclareLaunchArgument( - "use_sim_time", - default_value="true", - description="Use simulation (Gazebo) clock if true", + 'use_sim_time', + default_value='true', + description='Use simulation (Gazebo) clock if true', ) declare_params_file_cmd = DeclareLaunchArgument( - "params_file", - default_value=os.path.join(bringup_dir, "params", "nav2_params.yaml"), - description="Full path to the ROS2 parameters file to use for all launched nodes", + 'params_file', + default_value=os.path.join(bringup_dir, 'params', 'nav2_params.yaml'), + description='Full path to the ROS2 parameters file to use for all launched nodes', ) declare_autostart_cmd = DeclareLaunchArgument( - "autostart", - default_value="true", - description="Automatically startup the nav2 stack", + 'autostart', + default_value='true', + description='Automatically startup the nav2 stack', ) declare_use_composition_cmd = DeclareLaunchArgument( - "use_composition", - default_value="True", - description="Whether to use composed bringup", + 'use_composition', + default_value='True', + description='Whether to use composed bringup', ) declare_use_respawn_cmd = DeclareLaunchArgument( - "use_respawn", - default_value="False", - description="Whether to respawn if a node crashes. Applied when composition is disabled.", + 'use_respawn', + default_value='False', + description='Whether to respawn if a node crashes. Applied when composition is disabled.', ) declare_rviz_config_file_cmd = DeclareLaunchArgument( - "rviz_config_file", - default_value=os.path.join(bringup_dir, "rviz", "nav2_default_view.rviz"), - description="Full path to the RVIZ config file to use", + 'rviz_config_file', + default_value=os.path.join(bringup_dir, 'rviz', 'nav2_default_view.rviz'), + description='Full path to the RVIZ config file to use', ) declare_use_simulator_cmd = DeclareLaunchArgument( - "use_simulator", - default_value="True", - description="Whether to start the simulator", + 'use_simulator', + default_value='True', + description='Whether to start the simulator', ) declare_use_robot_state_pub_cmd = DeclareLaunchArgument( - "use_robot_state_pub", - default_value="True", - description="Whether to start the robot state publisher", + 'use_robot_state_pub', + default_value='True', + description='Whether to start the robot state publisher', ) declare_use_rviz_cmd = DeclareLaunchArgument( - "use_rviz", default_value="True", description="Whether to start RVIZ" + 'use_rviz', default_value='True', description='Whether to start RVIZ' ) declare_simulator_cmd = DeclareLaunchArgument( - "headless", default_value="True", description="Whether to execute gzclient)" + 'headless', default_value='True', description='Whether to execute gzclient)' ) declare_world_cmd = DeclareLaunchArgument( - "world", + 'world', # TODO(orduno) Switch back once ROS argument passing has been fixed upstream # https://github.com/ROBOTIS-GIT/turtlebot3_simulations/issues/91 # default_value=os.path.join(get_package_share_directory('turtlebot3_gazebo'), # worlds/turtlebot3_worlds/waffle.model') - default_value=os.path.join(bringup_dir, "worlds", "world_only.model"), - description="Full path to world model file to load", + default_value=os.path.join(bringup_dir, 'worlds', 'world_only.model'), + description='Full path to world model file to load', ) declare_robot_name_cmd = DeclareLaunchArgument( - "robot_name", default_value="turtlebot3_waffle", description="name of the robot" + 'robot_name', default_value='turtlebot3_waffle', description='name of the robot' ) declare_robot_sdf_cmd = DeclareLaunchArgument( - "robot_sdf", - default_value=os.path.join(bringup_dir, "worlds", "waffle.model"), - description="Full path to robot sdf file to spawn the robot in gazebo", + 'robot_sdf', + default_value=os.path.join(bringup_dir, 'worlds', 'waffle.model'), + description='Full path to robot sdf file to spawn the robot in gazebo', ) # Specify the actions start_gazebo_server_cmd = ExecuteProcess( condition=IfCondition(use_simulator), cmd=[ - "gzserver", - "-s", - "libgazebo_ros_init.so", - "-s", - "libgazebo_ros_factory.so", + 'gzserver', + '-s', + 'libgazebo_ros_init.so', + '-s', + 'libgazebo_ros_factory.so', world, ], cwd=[launch_dir], - output="screen", + output='screen', ) start_gazebo_client_cmd = ExecuteProcess( - condition=IfCondition(PythonExpression([use_simulator, " and not ", headless])), - cmd=["gzclient"], + condition=IfCondition(PythonExpression([use_simulator, ' and not ', headless])), + cmd=['gzclient'], cwd=[launch_dir], - output="screen", + output='screen', ) - urdf = os.path.join(bringup_dir, "urdf", "turtlebot3_waffle.urdf") - with open(urdf, "r") as infp: + urdf = os.path.join(bringup_dir, 'urdf', 'turtlebot3_waffle.urdf') + with open(urdf, 'r') as infp: robot_description = infp.read() start_robot_state_publisher_cmd = Node( condition=IfCondition(use_robot_state_pub), - package="robot_state_publisher", - executable="robot_state_publisher", - name="robot_state_publisher", + package='robot_state_publisher', + executable='robot_state_publisher', + name='robot_state_publisher', namespace=namespace, - output="screen", + output='screen', parameters=[ - {"use_sim_time": use_sim_time, "robot_description": robot_description} + {'use_sim_time': use_sim_time, 'robot_description': robot_description} ], remappings=remappings, ) start_gazebo_spawner_cmd = Node( - package="gazebo_ros", - executable="spawn_entity.py", - output="screen", + package='gazebo_ros', + executable='spawn_entity.py', + output='screen', arguments=[ - "-entity", + '-entity', robot_name, - "-file", + '-file', robot_sdf, - "-robot_namespace", + '-robot_namespace', namespace, - "-x", - pose["x"], - "-y", - pose["y"], - "-z", - pose["z"], - "-R", - pose["R"], - "-P", - pose["P"], - "-Y", - pose["Y"], + '-x', + pose['x'], + '-y', + pose['y'], + '-z', + pose['z'], + '-R', + pose['R'], + '-P', + pose['P'], + '-Y', + pose['Y'], ], ) rviz_cmd = IncludeLaunchDescription( - PythonLaunchDescriptionSource(os.path.join(launch_dir, "rviz_launch.py")), + PythonLaunchDescriptionSource(os.path.join(launch_dir, 'rviz_launch.py')), condition=IfCondition(use_rviz), launch_arguments={ - "namespace": namespace, - "use_namespace": use_namespace, - "rviz_config": rviz_config_file, + 'namespace': namespace, + 'use_namespace': use_namespace, + 'rviz_config': rviz_config_file, }.items(), ) bringup_cmd = IncludeLaunchDescription( - PythonLaunchDescriptionSource(os.path.join(launch_dir, "bringup_launch.py")), + PythonLaunchDescriptionSource(os.path.join(launch_dir, 'bringup_launch.py')), launch_arguments={ - "namespace": namespace, - "use_namespace": use_namespace, - "slam": slam, - "map": map_yaml_file, - "use_sim_time": use_sim_time, - "params_file": params_file, - "autostart": autostart, - "use_composition": use_composition, - "use_respawn": use_respawn, + 'namespace': namespace, + 'use_namespace': use_namespace, + 'slam': slam, + 'map': map_yaml_file, + 'use_sim_time': use_sim_time, + 'params_file': params_file, + 'autostart': autostart, + 'use_composition': use_composition, + 'use_respawn': use_respawn, }.items(), ) diff --git a/nav2_bringup/launch/unique_multi_tb3_simulation_launch.py b/nav2_bringup/launch/unique_multi_tb3_simulation_launch.py index e757cbfe941..2319def79ab 100644 --- a/nav2_bringup/launch/unique_multi_tb3_simulation_launch.py +++ b/nav2_bringup/launch/unique_multi_tb3_simulation_launch.py @@ -39,113 +39,113 @@ def generate_launch_description(): # Get the launch directory - bringup_dir = get_package_share_directory("nav2_bringup") - launch_dir = os.path.join(bringup_dir, "launch") + bringup_dir = get_package_share_directory('nav2_bringup') + launch_dir = os.path.join(bringup_dir, 'launch') # Names and poses of the robots robots = [ { - "name": "robot1", - "x_pose": 0.0, - "y_pose": 0.5, - "z_pose": 0.01, - "roll": 0.0, - "pitch": 0.0, - "yaw": 0.0, + 'name': 'robot1', + 'x_pose': 0.0, + 'y_pose': 0.5, + 'z_pose': 0.01, + 'roll': 0.0, + 'pitch': 0.0, + 'yaw': 0.0, }, { - "name": "robot2", - "x_pose": 0.0, - "y_pose": -0.5, - "z_pose": 0.01, - "roll": 0.0, - "pitch": 0.0, - "yaw": 0.0, + 'name': 'robot2', + 'x_pose': 0.0, + 'y_pose': -0.5, + 'z_pose': 0.01, + 'roll': 0.0, + 'pitch': 0.0, + 'yaw': 0.0, }, ] # Simulation settings - world = LaunchConfiguration("world") - simulator = LaunchConfiguration("simulator") + world = LaunchConfiguration('world') + simulator = LaunchConfiguration('simulator') # On this example all robots are launched with the same settings - map_yaml_file = LaunchConfiguration("map") + map_yaml_file = LaunchConfiguration('map') - autostart = LaunchConfiguration("autostart") - rviz_config_file = LaunchConfiguration("rviz_config") - use_robot_state_pub = LaunchConfiguration("use_robot_state_pub") - use_rviz = LaunchConfiguration("use_rviz") - log_settings = LaunchConfiguration("log_settings", default="true") + autostart = LaunchConfiguration('autostart') + rviz_config_file = LaunchConfiguration('rviz_config') + use_robot_state_pub = LaunchConfiguration('use_robot_state_pub') + use_rviz = LaunchConfiguration('use_rviz') + log_settings = LaunchConfiguration('log_settings', default='true') # Declare the launch arguments declare_world_cmd = DeclareLaunchArgument( - "world", - default_value=os.path.join(bringup_dir, "worlds", "world_only.model"), - description="Full path to world file to load", + 'world', + default_value=os.path.join(bringup_dir, 'worlds', 'world_only.model'), + description='Full path to world file to load', ) declare_simulator_cmd = DeclareLaunchArgument( - "simulator", - default_value="gazebo", - description="The simulator to use (gazebo or gzserver)", + 'simulator', + default_value='gazebo', + description='The simulator to use (gazebo or gzserver)', ) declare_map_yaml_cmd = DeclareLaunchArgument( - "map", - default_value=os.path.join(bringup_dir, "maps", "turtlebot3_world.yaml"), - description="Full path to map file to load", + 'map', + default_value=os.path.join(bringup_dir, 'maps', 'turtlebot3_world.yaml'), + description='Full path to map file to load', ) declare_robot1_params_file_cmd = DeclareLaunchArgument( - "robot1_params_file", + 'robot1_params_file', default_value=os.path.join( - bringup_dir, "params", "nav2_multirobot_params_1.yaml" + bringup_dir, 'params', 'nav2_multirobot_params_1.yaml' ), - description="Full path to the ROS2 parameters file to use for robot1 launched nodes", + description='Full path to the ROS2 parameters file to use for robot1 launched nodes', ) declare_robot2_params_file_cmd = DeclareLaunchArgument( - "robot2_params_file", + 'robot2_params_file', default_value=os.path.join( - bringup_dir, "params", "nav2_multirobot_params_2.yaml" + bringup_dir, 'params', 'nav2_multirobot_params_2.yaml' ), - description="Full path to the ROS2 parameters file to use for robot2 launched nodes", + description='Full path to the ROS2 parameters file to use for robot2 launched nodes', ) declare_autostart_cmd = DeclareLaunchArgument( - "autostart", - default_value="false", - description="Automatically startup the stacks", + 'autostart', + default_value='false', + description='Automatically startup the stacks', ) declare_rviz_config_file_cmd = DeclareLaunchArgument( - "rviz_config", - default_value=os.path.join(bringup_dir, "rviz", "nav2_namespaced_view.rviz"), - description="Full path to the RVIZ config file to use.", + 'rviz_config', + default_value=os.path.join(bringup_dir, 'rviz', 'nav2_namespaced_view.rviz'), + description='Full path to the RVIZ config file to use.', ) declare_use_robot_state_pub_cmd = DeclareLaunchArgument( - "use_robot_state_pub", - default_value="True", - description="Whether to start the robot state publisher", + 'use_robot_state_pub', + default_value='True', + description='Whether to start the robot state publisher', ) declare_use_rviz_cmd = DeclareLaunchArgument( - "use_rviz", default_value="True", description="Whether to start RVIZ" + 'use_rviz', default_value='True', description='Whether to start RVIZ' ) # Start Gazebo with plugin providing the robot spawning service start_gazebo_cmd = ExecuteProcess( cmd=[ simulator, - "--verbose", - "-s", - "libgazebo_ros_init.so", - "-s", - "libgazebo_ros_factory.so", + '--verbose', + '-s', + 'libgazebo_ros_init.so', + '-s', + 'libgazebo_ros_factory.so', world, ], - output="screen", + output='screen', ) # Define commands for launching the navigation instances @@ -157,66 +157,66 @@ def generate_launch_description(): [ IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(launch_dir, "rviz_launch.py") + os.path.join(launch_dir, 'rviz_launch.py') ), condition=IfCondition(use_rviz), launch_arguments={ - "namespace": TextSubstitution(text=robot["name"]), - "use_namespace": "True", - "rviz_config": rviz_config_file, + 'namespace': TextSubstitution(text=robot['name']), + 'use_namespace': 'True', + 'rviz_config': rviz_config_file, }.items(), ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(bringup_dir, "launch", "tb3_simulation_launch.py") + os.path.join(bringup_dir, 'launch', 'tb3_simulation_launch.py') ), launch_arguments={ - "namespace": robot["name"], - "use_namespace": "True", - "map": map_yaml_file, - "use_sim_time": "True", - "params_file": params_file, - "autostart": autostart, - "use_rviz": "False", - "use_simulator": "False", - "headless": "False", - "use_robot_state_pub": use_robot_state_pub, - "x_pose": TextSubstitution(text=str(robot["x_pose"])), - "y_pose": TextSubstitution(text=str(robot["y_pose"])), - "z_pose": TextSubstitution(text=str(robot["z_pose"])), - "roll": TextSubstitution(text=str(robot["roll"])), - "pitch": TextSubstitution(text=str(robot["pitch"])), - "yaw": TextSubstitution(text=str(robot["yaw"])), - "robot_name": TextSubstitution(text=robot["name"]), + 'namespace': robot['name'], + 'use_namespace': 'True', + 'map': map_yaml_file, + 'use_sim_time': 'True', + 'params_file': params_file, + 'autostart': autostart, + 'use_rviz': 'False', + 'use_simulator': 'False', + 'headless': 'False', + 'use_robot_state_pub': use_robot_state_pub, + 'x_pose': TextSubstitution(text=str(robot['x_pose'])), + 'y_pose': TextSubstitution(text=str(robot['y_pose'])), + 'z_pose': TextSubstitution(text=str(robot['z_pose'])), + 'roll': TextSubstitution(text=str(robot['roll'])), + 'pitch': TextSubstitution(text=str(robot['pitch'])), + 'yaw': TextSubstitution(text=str(robot['yaw'])), + 'robot_name': TextSubstitution(text=robot['name']), }.items(), ), LogInfo( condition=IfCondition(log_settings), - msg=["Launching ", robot["name"]], + msg=['Launching ', robot['name']], ), LogInfo( condition=IfCondition(log_settings), - msg=[robot["name"], " map yaml: ", map_yaml_file], + msg=[robot['name'], ' map yaml: ', map_yaml_file], ), LogInfo( condition=IfCondition(log_settings), - msg=[robot["name"], " params yaml: ", params_file], + msg=[robot['name'], ' params yaml: ', params_file], ), LogInfo( condition=IfCondition(log_settings), - msg=[robot["name"], " rviz config file: ", rviz_config_file], + msg=[robot['name'], ' rviz config file: ', rviz_config_file], ), LogInfo( condition=IfCondition(log_settings), msg=[ - robot["name"], - " using robot state pub: ", + robot['name'], + ' using robot state pub: ', use_robot_state_pub, ], ), LogInfo( condition=IfCondition(log_settings), - msg=[robot["name"], " autostart: ", autostart], + msg=[robot['name'], ' autostart: ', autostart], ), ] ) From 0c6a0bbe679315c79e0c287244b9f1ec17114fd6 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 21:24:04 +0100 Subject: [PATCH 19/24] Fix flake8-quotes linter for tools --- tools/bt2img.py | 176 +++++++++--------- tools/planner_benchmarking/metrics.py | 30 +-- .../planning_benchmark_bringup.py | 64 +++---- tools/planner_benchmarking/process_data.py | 26 +-- tools/smoother_benchmarking/metrics.py | 34 ++-- tools/smoother_benchmarking/process_data.py | 34 ++-- .../smoother_benchmark_bringup.py | 76 ++++---- 7 files changed, 220 insertions(+), 220 deletions(-) diff --git a/tools/bt2img.py b/tools/bt2img.py index b649ab8580c..b3c2b34eaf5 100755 --- a/tools/bt2img.py +++ b/tools/bt2img.py @@ -22,57 +22,57 @@ import graphviz # pip3 install graphviz control_nodes = [ - "Fallback", - "Parallel", - "ReactiveFallback", - "ReactiveSequence", - "Sequence", - "SequenceStar", - "BlackboardCheckInt", - "BlackboardCheckDouble", - "BlackboardCheckString", - "ForceFailure", - "ForceSuccess", - "Inverter", - "Repeat", - "Subtree", - "Timeout", - "RecoveryNode", - "PipelineSequence", - "RoundRobin", - "Control", + 'Fallback', + 'Parallel', + 'ReactiveFallback', + 'ReactiveSequence', + 'Sequence', + 'SequenceStar', + 'BlackboardCheckInt', + 'BlackboardCheckDouble', + 'BlackboardCheckString', + 'ForceFailure', + 'ForceSuccess', + 'Inverter', + 'Repeat', + 'Subtree', + 'Timeout', + 'RecoveryNode', + 'PipelineSequence', + 'RoundRobin', + 'Control', ] action_nodes = [ - "AlwaysFailure", - "AlwaysSuccess", - "SetBlackboard", - "ComputePathToPose", - "FollowPath", - "BackUp", - "Spin", - "Wait", - "ClearEntireCostmap", - "ReinitializeGlobalLocalization", - "Action", + 'AlwaysFailure', + 'AlwaysSuccess', + 'SetBlackboard', + 'ComputePathToPose', + 'FollowPath', + 'BackUp', + 'Spin', + 'Wait', + 'ClearEntireCostmap', + 'ReinitializeGlobalLocalization', + 'Action', ] condition_nodes = [ - "IsStuck", - "GoalReached", - "initialPoseReceived", - "GoalUpdated", - "DistanceTraveled", - "TimeExpired", - "TransformAvailable", - "Condition", + 'IsStuck', + 'GoalReached', + 'initialPoseReceived', + 'GoalUpdated', + 'DistanceTraveled', + 'TimeExpired', + 'TransformAvailable', + 'Condition', ] decorator_nodes = [ - "Decorator", - "RateController", - "DistanceController", - "SpeedController", + 'Decorator', + 'RateController', + 'DistanceController', + 'SpeedController', ] subtree_nodes = [ - "SubTree", + 'SubTree', ] global xml_tree @@ -87,57 +87,57 @@ def main(): dot = convert2dot(behavior_tree) if args.legend: legend = make_legend() - legend.format = "png" + legend.format = 'png' legend.render(args.legend) - dot.format = "png" + dot.format = 'png' if args.save_dot: - print(f"Saving dot to {args.save_dot}") + print(f'Saving dot to {args.save_dot}') args.save_dot.write(dot.source) dot.render(args.image_out, view=args.display) def parse_command_line(): parser = argparse.ArgumentParser( - description="Convert a behavior tree XML file to an image" + description='Convert a behavior tree XML file to an image' ) parser.add_argument( - "--behavior_tree", + '--behavior_tree', required=True, - help="the behavior tree XML file to convert to an image", + help='the behavior tree XML file to convert to an image', ) parser.add_argument( - "--image_out", + '--image_out', required=True, - help="The name of the output image file. Leave off the .png extension", + help='The name of the output image file. Leave off the .png extension', ) parser.add_argument( - "--display", - action="store_true", - help="If specified, opens the image in the default viewer", + '--display', + action='store_true', + help='If specified, opens the image in the default viewer', ) parser.add_argument( - "--save_dot", - type=argparse.FileType("w"), - help="Saves the intermediate dot source to the specified file", + '--save_dot', + type=argparse.FileType('w'), + help='Saves the intermediate dot source to the specified file', ) - parser.add_argument("--legend", help="Generate a legend image as well") + parser.add_argument('--legend', help='Generate a legend image as well') return parser.parse_args() def find_root_tree_name(xml_tree): - return xml_tree.getroot().get("main_tree_to_execute") + return xml_tree.getroot().get('main_tree_to_execute') def find_behavior_tree(xml_tree, tree_name): - trees = xml_tree.findall("BehaviorTree") + trees = xml_tree.findall('BehaviorTree') if len(trees) == 0: - raise RuntimeError("No behavior trees were found in the XML file") + raise RuntimeError('No behavior trees were found in the XML file') for tree in trees: - if tree_name == tree.get("ID"): + if tree_name == tree.get('ID'): return tree - raise RuntimeError(f"No behavior tree for name {tree_name} found in the XML file") + raise RuntimeError(f'No behavior tree for name {tree_name} found in the XML file') # Generate a dot description of the root of the behavior tree. @@ -145,7 +145,7 @@ def convert2dot(behavior_tree): dot = graphviz.Digraph() root = behavior_tree parent_dot_name = str(hash(root)) - dot.node(parent_dot_name, root.get("ID"), shape="box") + dot.node(parent_dot_name, root.get('ID'), shape='box') convert_subtree(dot, root, parent_dot_name) return dot @@ -154,15 +154,15 @@ def convert2dot(behavior_tree): # call this function on the children. Nodes are given an ID that is the hash # of the node to ensure each is unique. def convert_subtree(dot, parent_node, parent_dot_name): - if parent_node.tag == "SubTree": + if parent_node.tag == 'SubTree': add_sub_tree(dot, parent_dot_name, parent_node) else: add_nodes(dot, parent_dot_name, parent_node) def add_sub_tree(dot, parent_dot_name, parent_node): - root_tree_name = parent_node.get("ID") - dot.node(parent_dot_name, root_tree_name, shape="box") + root_tree_name = parent_node.get('ID') + dot.node(parent_dot_name, root_tree_name, shape='box') behavior_tree = find_behavior_tree(xml_tree, root_tree_name) convert_subtree(dot, behavior_tree, parent_dot_name) @@ -174,8 +174,8 @@ def add_nodes(dot, parent_dot_name, parent_node): str(hash(node)), label, color=node_color(node.tag), - style="filled", - shape="box", + style='filled', + shape='box', ) dot_name = str(hash(node)) dot.edge(parent_dot_name, dot_name) @@ -185,52 +185,52 @@ def add_nodes(dot, parent_dot_name, parent_node): # The node label contains the: # type, the name if provided, and the parameters. def make_label(node): - label = '< ' - label += '" - name = node.get("name") + label = "<
' + node.tag + "
" + label += "" + name = node.get('name') if name: - label += '" + label += "" for (param_name, value) in node.items(): label += ( - '" + "" ) - label += "
' + node.tag + '
' + name + "
' + name + '
' + param_name + "=" + value + "
' + param_name + '=' + value + '
>" + label += ' >' return label def node_color(node_type): if node_type in control_nodes: - return "chartreuse4" + return 'chartreuse4' if node_type in action_nodes: - return "cornflowerblue" + return 'cornflowerblue' if node_type in condition_nodes: - return "yellow2" + return 'yellow2' if node_type in decorator_nodes: - return "darkorange1" + return 'darkorange1' if node_type in subtree_nodes: - return "darkorchid1" + return 'darkorchid1' # else it's unknown - return "grey" + return 'grey' # creates a legend which can be provided with the other images. def make_legend(): - legend = graphviz.Digraph(graph_attr={"rankdir": "LR"}) - legend.attr(label="Legend") - legend.node("Unknown", shape="box", style="filled", color="grey") + legend = graphviz.Digraph(graph_attr={'rankdir': 'LR'}) + legend.attr(label='Legend') + legend.node('Unknown', shape='box', style='filled', color='grey') legend.node( - "Action", "Action Node", shape="box", style="filled", color="cornflowerblue" + 'Action', 'Action Node', shape='box', style='filled', color='cornflowerblue' ) legend.node( - "Condition", "Condition Node", shape="box", style="filled", color="yellow2" + 'Condition', 'Condition Node', shape='box', style='filled', color='yellow2' ) legend.node( - "Control", "Control Node", shape="box", style="filled", color="chartreuse4" + 'Control', 'Control Node', shape='box', style='filled', color='chartreuse4' ) return legend -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/tools/planner_benchmarking/metrics.py b/tools/planner_benchmarking/metrics.py index 56f52e8decc..0ae0f883efe 100644 --- a/tools/planner_benchmarking/metrics.py +++ b/tools/planner_benchmarking/metrics.py @@ -34,14 +34,14 @@ def getPlannerResults(navigator, initial_pose, goal_pose, planners): if path is not None and path.error_code == 0: results.append(path) else: - print(planner, "planner failed to produce the path") + print(planner, 'planner failed to produce the path') return results return results def getRandomStart(costmap, max_cost, side_buffer, time_stamp, res): start = PoseStamped() - start.header.frame_id = "map" + start.header.frame_id = 'map' start.header.stamp = time_stamp while True: row = randint(side_buffer, costmap.shape[0] - side_buffer) @@ -63,7 +63,7 @@ def getRandomStart(costmap, max_cost, side_buffer, time_stamp, res): def getRandomGoal(costmap, start, max_cost, side_buffer, time_stamp, res): goal = PoseStamped() - goal.header.frame_id = "map" + goal.header.frame_id = 'map' goal.header.stamp = time_stamp while True: row = randint(side_buffer, costmap.shape[0] - side_buffer) @@ -97,7 +97,7 @@ def main(): navigator = BasicNavigator() # Set map to use, other options: 100by100_15, 100by100_10 - map_path = os.getcwd() + "/" + glob.glob("**/100by100_20.yaml", recursive=True)[0] + map_path = os.getcwd() + '/' + glob.glob('**/100by100_20.yaml', recursive=True)[0] navigator.changeMap(map_path) time.sleep(2) @@ -106,7 +106,7 @@ def main(): costmap = np.asarray(costmap_msg.data) costmap.resize(costmap_msg.metadata.size_y, costmap_msg.metadata.size_x) - planners = ["Navfn", "ThetaStar", "SmacHybrid", "Smac2d", "SmacLattice"] + planners = ['Navfn', 'ThetaStar', 'SmacHybrid', 'Smac2d', 'SmacLattice'] max_cost = 210 side_buffer = 100 time_stamp = navigator.get_clock().now().to_msg() @@ -117,30 +117,30 @@ def main(): res = costmap_msg.metadata.resolution i = 0 while len(results) != random_pairs: - print("Cycle: ", i, "out of: ", random_pairs) + print('Cycle: ', i, 'out of: ', random_pairs) start = getRandomStart(costmap, max_cost, side_buffer, time_stamp, res) goal = getRandomGoal(costmap, start, max_cost, side_buffer, time_stamp, res) - print("Start", start) - print("Goal", goal) + print('Start', start) + print('Goal', goal) result = getPlannerResults(navigator, start, goal, planners) if len(result) == len(planners): results.append(result) i = i + 1 else: - print("One of the planners was invalid") + print('One of the planners was invalid') - print("Write Results...") - with open(os.getcwd() + "/results.pickle", "wb+") as f: + print('Write Results...') + with open(os.getcwd() + '/results.pickle', 'wb+') as f: pickle.dump(results, f, pickle.HIGHEST_PROTOCOL) - with open(os.getcwd() + "/costmap.pickle", "wb+") as f: + with open(os.getcwd() + '/costmap.pickle', 'wb+') as f: pickle.dump(costmap_msg, f, pickle.HIGHEST_PROTOCOL) - with open(os.getcwd() + "/planners.pickle", "wb+") as f: + with open(os.getcwd() + '/planners.pickle', 'wb+') as f: pickle.dump(planners, f, pickle.HIGHEST_PROTOCOL) - print("Write Complete") + print('Write Complete') exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/tools/planner_benchmarking/planning_benchmark_bringup.py b/tools/planner_benchmarking/planning_benchmark_bringup.py index 36362466114..506ba544183 100644 --- a/tools/planner_benchmarking/planning_benchmark_bringup.py +++ b/tools/planner_benchmarking/planning_benchmark_bringup.py @@ -22,61 +22,61 @@ def generate_launch_description(): - nav2_bringup_dir = get_package_share_directory("nav2_bringup") + nav2_bringup_dir = get_package_share_directory('nav2_bringup') config = os.path.join( - get_package_share_directory("nav2_bringup"), "params", "nav2_params.yaml" + get_package_share_directory('nav2_bringup'), 'params', 'nav2_params.yaml' ) - map_file = os.path.join(nav2_bringup_dir, "maps", "turtlebot3_world.yaml") - lifecycle_nodes = ["map_server", "planner_server"] + map_file = os.path.join(nav2_bringup_dir, 'maps', 'turtlebot3_world.yaml') + lifecycle_nodes = ['map_server', 'planner_server'] return LaunchDescription( [ Node( - package="nav2_map_server", - executable="map_server", - name="map_server", - output="screen", + package='nav2_map_server', + executable='map_server', + name='map_server', + output='screen', parameters=[ - {"use_sim_time": True}, - {"yaml_filename": map_file}, - {"topic_name": "map"}, + {'use_sim_time': True}, + {'yaml_filename': map_file}, + {'topic_name': 'map'}, ], ), Node( - package="nav2_planner", - executable="planner_server", - name="planner_server", - output="screen", + package='nav2_planner', + executable='planner_server', + name='planner_server', + output='screen', parameters=[config], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "map"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'map'], ), Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "odom"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'odom'], ), Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager", - output="screen", + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager', + output='screen', parameters=[ - {"use_sim_time": True}, - {"autostart": True}, - {"node_names": lifecycle_nodes}, + {'use_sim_time': True}, + {'autostart': True}, + {'node_names': lifecycle_nodes}, ], ), IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "rviz_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'rviz_launch.py') ), - launch_arguments={"namespace": "", "use_namespace": "False"}.items(), + launch_arguments={'namespace': '', 'use_namespace': 'False'}.items(), ), ] ) diff --git a/tools/planner_benchmarking/process_data.py b/tools/planner_benchmarking/process_data.py index f00ad2ccff6..299997774db 100644 --- a/tools/planner_benchmarking/process_data.py +++ b/tools/planner_benchmarking/process_data.py @@ -74,11 +74,11 @@ def plotResults(costmap, paths): data = np.where(data <= 253, 0, data) plt.figure(3) - ax = sns.heatmap(data, cmap="Greys", cbar=False) + ax = sns.heatmap(data, cmap='Greys', cbar=False) for i in range(0, len(coords), 2): ax.plot(coords[i], coords[i + 1], linewidth=0.7) - plt.axis("off") - ax.set_aspect("equal", "box") + plt.axis('off') + ax.set_aspect('equal', 'box') plt.show() @@ -126,14 +126,14 @@ def maxPathCost(paths, costmap, num_of_planners): def main(): - print("Read data") - with open(os.getcwd() + "/results.pickle", "rb") as f: + print('Read data') + with open(os.getcwd() + '/results.pickle', 'rb') as f: results = pickle.load(f) - with open(os.getcwd() + "/planners.pickle", "rb") as f: + with open(os.getcwd() + '/planners.pickle', 'rb') as f: planners = pickle.load(f) - with open(os.getcwd() + "/costmap.pickle", "rb") as f: + with open(os.getcwd() + '/costmap.pickle', 'rb') as f: costmap = pickle.load(f) paths = getPaths(results) @@ -159,11 +159,11 @@ def main(): # Generate table planner_table = [ [ - "Planner", - "Average path length (m)", - "Average Time (s)", - "Average cost", - "Max cost", + 'Planner', + 'Average path length (m)', + 'Average Time (s)', + 'Average cost', + 'Max cost', ] ] @@ -183,5 +183,5 @@ def main(): plotResults(costmap, paths) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/tools/smoother_benchmarking/metrics.py b/tools/smoother_benchmarking/metrics.py index 8d1bd7ea0ee..fa01be9754f 100644 --- a/tools/smoother_benchmarking/metrics.py +++ b/tools/smoother_benchmarking/metrics.py @@ -32,7 +32,7 @@ def getPlannerResults(navigator, initial_pose, goal_pose, planner): result = navigator._getPathImpl(initial_pose, goal_pose, planner, use_start=True) if result is None or result.error_code != 0: - print(planner, "planner failed to produce the path") + print(planner, 'planner failed to produce the path') return None return result @@ -44,14 +44,14 @@ def getSmootherResults(navigator, path, smoothers): if smoothed_result is not None: smoothed_results.append(smoothed_result) else: - print(smoother, "failed to smooth the path") + print(smoother, 'failed to smooth the path') return None return smoothed_results def getRandomStart(costmap, max_cost, side_buffer, time_stamp, res): start = PoseStamped() - start.header.frame_id = "map" + start.header.frame_id = 'map' start.header.stamp = time_stamp while True: row = randint(side_buffer, costmap.shape[0] - side_buffer) @@ -73,7 +73,7 @@ def getRandomStart(costmap, max_cost, side_buffer, time_stamp, res): def getRandomGoal(costmap, start, max_cost, side_buffer, time_stamp, res): goal = PoseStamped() - goal.header.frame_id = "map" + goal.header.frame_id = 'map' goal.header.stamp = time_stamp while True: row = randint(side_buffer, costmap.shape[0] - side_buffer) @@ -107,16 +107,16 @@ def main(): navigator = BasicNavigator() # Wait for planner and smoother to fully activate - print("Waiting for planner and smoother servers to activate") - navigator.waitUntilNav2Active("smoother_server", "planner_server") + print('Waiting for planner and smoother servers to activate') + navigator.waitUntilNav2Active('smoother_server', 'planner_server') # Get the costmap for start/goal validation costmap_msg = navigator.getGlobalCostmap() costmap = np.asarray(costmap_msg.data) costmap.resize(costmap_msg.metadata.size_y, costmap_msg.metadata.size_x) - planner = "SmacHybrid" - smoothers = ["simple_smoother", "constrained_smoother", "sg_smoother"] + planner = 'SmacHybrid' + smoothers = ['simple_smoother', 'constrained_smoother', 'sg_smoother'] max_cost = 210 side_buffer = 10 time_stamp = navigator.get_clock().now().to_msg() @@ -127,11 +127,11 @@ def main(): i = 0 res = costmap_msg.metadata.resolution while i < random_pairs: - print("Cycle: ", i, "out of: ", random_pairs) + print('Cycle: ', i, 'out of: ', random_pairs) start = getRandomStart(costmap, max_cost, side_buffer, time_stamp, res) goal = getRandomGoal(costmap, start, max_cost, side_buffer, time_stamp, res) - print("Start", start) - print("Goal", goal) + print('Start', start) + print('Goal', goal) result = getPlannerResults(navigator, start, goal, planner) if result is not None: smoothed_results = getSmootherResults(navigator, result.path, smoothers) @@ -140,21 +140,21 @@ def main(): results.append(smoothed_results) i += 1 - print("Write Results...") + print('Write Results...') benchmark_dir = os.getcwd() - with open(os.path.join(benchmark_dir, "results.pickle"), "wb") as f: + with open(os.path.join(benchmark_dir, 'results.pickle'), 'wb') as f: pickle.dump(results, f, pickle.HIGHEST_PROTOCOL) - with open(os.path.join(benchmark_dir, "costmap.pickle"), "wb") as f: + with open(os.path.join(benchmark_dir, 'costmap.pickle'), 'wb') as f: pickle.dump(costmap_msg, f, pickle.HIGHEST_PROTOCOL) smoothers.insert(0, planner) - with open(os.path.join(benchmark_dir, "methods.pickle"), "wb") as f: + with open(os.path.join(benchmark_dir, 'methods.pickle'), 'wb') as f: pickle.dump(smoothers, f, pickle.HIGHEST_PROTOCOL) - print("Write Complete") + print('Write Complete') exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/tools/smoother_benchmarking/process_data.py b/tools/smoother_benchmarking/process_data.py index 621a364c22b..4a422bc0037 100644 --- a/tools/smoother_benchmarking/process_data.py +++ b/tools/smoother_benchmarking/process_data.py @@ -129,7 +129,7 @@ def arcCenter(pt_prev, pt, pt_next): det = d1[0] * d2[1] - d1[1] * d2[0] if abs(det) < 1e-4: # straight line - return (float("inf"), float("inf")) + return (float('inf'), float('inf')) # circle center is at the intersection of mirror axes of the segments: # http://paulbourke.net/geometry/circlesphere/ @@ -162,7 +162,7 @@ def getPathCurvatures(paths): pm2[0] = path.poses[i - 2].pose.position.x pm2[1] = path.poses[i - 2].pose.position.y center = arcCenter(pm2, pm1, pm0) - if center[0] != float("inf"): + if center[0] != float('inf'): turning_rad = np.linalg.norm(pm1 - center) radiuses.append(turning_rad) curvatures.append(np.average(radiuses)) @@ -176,11 +176,11 @@ def plotResults(costmap, paths): data = np.where(data <= 253, 0, data) plt.figure(3) - ax = sns.heatmap(data, cmap="Greys", cbar=False) + ax = sns.heatmap(data, cmap='Greys', cbar=False) for i in range(0, len(coords), 2): ax.plot(coords[i], coords[i + 1], linewidth=0.7) - plt.axis("off") - ax.set_aspect("equal", "box") + plt.axis('off') + ax.set_aspect('equal', 'box') plt.show() @@ -229,17 +229,17 @@ def maxPathCost(paths, costmap, num_of_planners): def main(): # Read the data benchmark_dir = os.getcwd() - print("Read data") - with open(os.path.join(benchmark_dir, "results.pickle"), "rb") as f: + print('Read data') + with open(os.path.join(benchmark_dir, 'results.pickle'), 'rb') as f: results = pickle.load(f) - with open(os.path.join(benchmark_dir, "methods.pickle"), "rb") as f: + with open(os.path.join(benchmark_dir, 'methods.pickle'), 'rb') as f: smoothers = pickle.load(f) planner = smoothers[0] del smoothers[0] methods_num = len(smoothers) + 1 - with open(os.path.join(benchmark_dir, "costmap.pickle"), "rb") as f: + with open(os.path.join(benchmark_dir, 'costmap.pickle'), 'rb') as f: costmap = pickle.load(f) # Paths (planner and smoothers) @@ -281,13 +281,13 @@ def main(): # Generate table planner_table = [ [ - "Planner", - "Time (s)", - "Path length (m)", - "Average cost", - "Max cost", - "Path smoothness (x100)", - "Average turning rad (m)", + 'Planner', + 'Time (s)', + 'Path length (m)', + 'Average cost', + 'Max cost', + 'Path smoothness (x100)', + 'Average turning rad (m)', ] ] # for path planner @@ -323,5 +323,5 @@ def main(): exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/tools/smoother_benchmarking/smoother_benchmark_bringup.py b/tools/smoother_benchmarking/smoother_benchmark_bringup.py index 0cfcbfe1e7f..4d60e17e64a 100644 --- a/tools/smoother_benchmarking/smoother_benchmark_bringup.py +++ b/tools/smoother_benchmarking/smoother_benchmark_bringup.py @@ -22,78 +22,78 @@ def generate_launch_description(): - nav2_bringup_dir = get_package_share_directory("nav2_bringup") + nav2_bringup_dir = get_package_share_directory('nav2_bringup') benchmark_dir = os.getcwd() - metrics_py = os.path.join(benchmark_dir, "metrics.py") + metrics_py = os.path.join(benchmark_dir, 'metrics.py') config = os.path.join( - get_package_share_directory("nav2_bringup"), "params", "nav2_params.yaml" + get_package_share_directory('nav2_bringup'), 'params', 'nav2_params.yaml' ) - map_file = os.path.join(benchmark_dir, "maps", "smoothers_world.yaml") - lifecycle_nodes = ["map_server", "planner_server", "smoother_server"] + map_file = os.path.join(benchmark_dir, 'maps', 'smoothers_world.yaml') + lifecycle_nodes = ['map_server', 'planner_server', 'smoother_server'] static_transform_one = Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "map"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'map'], ) static_transform_two = Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "base_link", "odom"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'odom'], ) start_map_server_cmd = Node( - package="nav2_map_server", - executable="map_server", - name="map_server", - output="screen", + package='nav2_map_server', + executable='map_server', + name='map_server', + output='screen', parameters=[ - {"use_sim_time": True}, - {"yaml_filename": map_file}, - {"topic_name": "map"}, + {'use_sim_time': True}, + {'yaml_filename': map_file}, + {'topic_name': 'map'}, ], ) start_planner_server_cmd = Node( - package="nav2_planner", - executable="planner_server", - name="planner_server", - output="screen", + package='nav2_planner', + executable='planner_server', + name='planner_server', + output='screen', parameters=[config], ) start_smoother_server_cmd = Node( - package="nav2_smoother", - executable="smoother_server", - name="smoother_server", - output="screen", + package='nav2_smoother', + executable='smoother_server', + name='smoother_server', + output='screen', parameters=[config], ) start_lifecycle_manager_cmd = Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager", - output="screen", + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager', + output='screen', parameters=[ - {"use_sim_time": True}, - {"autostart": True}, - {"node_names": lifecycle_nodes}, + {'use_sim_time': True}, + {'autostart': True}, + {'node_names': lifecycle_nodes}, ], ) rviz_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "rviz_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'rviz_launch.py') ), - launch_arguments={"namespace": "", "use_namespace": "False"}.items(), + launch_arguments={'namespace': '', 'use_namespace': 'False'}.items(), ) metrics_cmd = ExecuteProcess( - cmd=["python3", "-u", metrics_py], cwd=[benchmark_dir], output="screen" + cmd=['python3', '-u', metrics_py], cwd=[benchmark_dir], output='screen' ) ld = LaunchDescription() From 57509a92e2c7ef9a27f11a5768d97c066093527c Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 21:28:44 +0100 Subject: [PATCH 20/24] Fix flake8-quotes linter for nav2_simple_commander --- .../launch/assisted_teleop_example_launch.py | 52 ++--- .../launch/follow_path_example_launch.py | 52 ++--- .../launch/inspection_demo_launch.py | 52 ++--- .../nav_through_poses_example_launch.py | 52 ++--- .../launch/nav_to_pose_example_launch.py | 52 ++--- .../launch/picking_demo_launch.py | 52 ++--- .../launch/recoveries_example_launch.py | 52 ++--- .../launch/security_demo_launch.py | 52 ++--- .../waypoint_follower_example_launch.py | 52 ++--- .../nav2_simple_commander/demo_inspection.py | 16 +- .../nav2_simple_commander/demo_picking.py | 50 ++--- .../nav2_simple_commander/demo_recoveries.py | 24 +-- .../nav2_simple_commander/demo_security.py | 20 +- .../example_assisted_teleop.py | 4 +- .../example_follow_path.py | 22 +-- .../example_nav_through_poses.py | 26 +-- .../example_nav_to_pose.py | 20 +- .../example_waypoint_follower.py | 24 +-- .../footprint_collision_checker.py | 4 +- .../nav2_simple_commander/line_iterator.py | 14 +- .../nav2_simple_commander/robot_navigator.py | 184 +++++++++--------- nav2_simple_commander/setup.py | 42 ++-- nav2_simple_commander/test/test_copyright.py | 4 +- nav2_simple_commander/test/test_flake8.py | 4 +- .../test/test_footprint_collision_checker.py | 2 +- .../test/test_line_iterator.py | 4 +- nav2_simple_commander/test/test_pep257.py | 4 +- 27 files changed, 468 insertions(+), 468 deletions(-) diff --git a/nav2_simple_commander/launch/assisted_teleop_example_launch.py b/nav2_simple_commander/launch/assisted_teleop_example_launch.py index f146ae24df6..3324b0ee4e1 100644 --- a/nav2_simple_commander/launch/assisted_teleop_example_launch.py +++ b/nav2_simple_commander/launch/assisted_teleop_example_launch.py @@ -30,72 +30,72 @@ def generate_launch_description(): - warehouse_dir = get_package_share_directory("aws_robomaker_small_warehouse_world") - nav2_bringup_dir = get_package_share_directory("nav2_bringup") - python_commander_dir = get_package_share_directory("nav2_simple_commander") + warehouse_dir = get_package_share_directory('aws_robomaker_small_warehouse_world') + nav2_bringup_dir = get_package_share_directory('nav2_bringup') + python_commander_dir = get_package_share_directory('nav2_simple_commander') - map_yaml_file = os.path.join(warehouse_dir, "maps", "005", "map.yaml") - world = os.path.join(python_commander_dir, "warehouse.world") + map_yaml_file = os.path.join(warehouse_dir, 'maps', '005', 'map.yaml') + world = os.path.join(python_commander_dir, 'warehouse.world') # Launch configuration variables - use_rviz = LaunchConfiguration("use_rviz") - headless = LaunchConfiguration("headless") + use_rviz = LaunchConfiguration('use_rviz') + headless = LaunchConfiguration('headless') # Declare the launch arguments declare_use_rviz_cmd = DeclareLaunchArgument( - "use_rviz", default_value="True", description="Whether to start RVIZ" + 'use_rviz', default_value='True', description='Whether to start RVIZ' ) declare_simulator_cmd = DeclareLaunchArgument( - "headless", default_value="False", description="Whether to execute gzclient)" + 'headless', default_value='False', description='Whether to execute gzclient)' ) # start the simulation start_gazebo_server_cmd = ExecuteProcess( - cmd=["gzserver", "-s", "libgazebo_ros_factory.so", world], + cmd=['gzserver', '-s', 'libgazebo_ros_factory.so', world], cwd=[warehouse_dir], - output="screen", + output='screen', ) start_gazebo_client_cmd = ExecuteProcess( - condition=IfCondition(PythonExpression(["not ", headless])), - cmd=["gzclient"], + condition=IfCondition(PythonExpression(['not ', headless])), + cmd=['gzclient'], cwd=[warehouse_dir], - output="screen", + output='screen', ) - urdf = os.path.join(nav2_bringup_dir, "urdf", "turtlebot3_waffle.urdf") + urdf = os.path.join(nav2_bringup_dir, 'urdf', 'turtlebot3_waffle.urdf') start_robot_state_publisher_cmd = Node( - package="robot_state_publisher", - executable="robot_state_publisher", - name="robot_state_publisher", - output="screen", + package='robot_state_publisher', + executable='robot_state_publisher', + name='robot_state_publisher', + output='screen', arguments=[urdf], ) # start the visualization rviz_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "rviz_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'rviz_launch.py') ), condition=IfCondition(use_rviz), - launch_arguments={"namespace": "", "use_namespace": "False"}.items(), + launch_arguments={'namespace': '', 'use_namespace': 'False'}.items(), ) # start navigation bringup_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "bringup_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'bringup_launch.py') ), - launch_arguments={"map": map_yaml_file}.items(), + launch_arguments={'map': map_yaml_file}.items(), ) # start the demo autonomy task demo_cmd = Node( - package="nav2_simple_commander", - executable="example_assisted_teleop", + package='nav2_simple_commander', + executable='example_assisted_teleop', emulate_tty=True, - output="screen", + output='screen', ) ld = LaunchDescription() diff --git a/nav2_simple_commander/launch/follow_path_example_launch.py b/nav2_simple_commander/launch/follow_path_example_launch.py index e789464ca74..b4fe9b586fd 100644 --- a/nav2_simple_commander/launch/follow_path_example_launch.py +++ b/nav2_simple_commander/launch/follow_path_example_launch.py @@ -29,72 +29,72 @@ def generate_launch_description(): - warehouse_dir = get_package_share_directory("aws_robomaker_small_warehouse_world") - nav2_bringup_dir = get_package_share_directory("nav2_bringup") - python_commander_dir = get_package_share_directory("nav2_simple_commander") + warehouse_dir = get_package_share_directory('aws_robomaker_small_warehouse_world') + nav2_bringup_dir = get_package_share_directory('nav2_bringup') + python_commander_dir = get_package_share_directory('nav2_simple_commander') - map_yaml_file = os.path.join(warehouse_dir, "maps", "005", "map.yaml") - world = os.path.join(python_commander_dir, "warehouse.world") + map_yaml_file = os.path.join(warehouse_dir, 'maps', '005', 'map.yaml') + world = os.path.join(python_commander_dir, 'warehouse.world') # Launch configuration variables - use_rviz = LaunchConfiguration("use_rviz") - headless = LaunchConfiguration("headless") + use_rviz = LaunchConfiguration('use_rviz') + headless = LaunchConfiguration('headless') # Declare the launch arguments declare_use_rviz_cmd = DeclareLaunchArgument( - "use_rviz", default_value="True", description="Whether to start RVIZ" + 'use_rviz', default_value='True', description='Whether to start RVIZ' ) declare_simulator_cmd = DeclareLaunchArgument( - "headless", default_value="False", description="Whether to execute gzclient)" + 'headless', default_value='False', description='Whether to execute gzclient)' ) # start the simulation start_gazebo_server_cmd = ExecuteProcess( - cmd=["gzserver", "-s", "libgazebo_ros_factory.so", world], + cmd=['gzserver', '-s', 'libgazebo_ros_factory.so', world], cwd=[warehouse_dir], - output="screen", + output='screen', ) start_gazebo_client_cmd = ExecuteProcess( - condition=IfCondition(PythonExpression(["not ", headless])), - cmd=["gzclient"], + condition=IfCondition(PythonExpression(['not ', headless])), + cmd=['gzclient'], cwd=[warehouse_dir], - output="screen", + output='screen', ) - urdf = os.path.join(nav2_bringup_dir, "urdf", "turtlebot3_waffle.urdf") + urdf = os.path.join(nav2_bringup_dir, 'urdf', 'turtlebot3_waffle.urdf') start_robot_state_publisher_cmd = Node( - package="robot_state_publisher", - executable="robot_state_publisher", - name="robot_state_publisher", - output="screen", + package='robot_state_publisher', + executable='robot_state_publisher', + name='robot_state_publisher', + output='screen', arguments=[urdf], ) # start the visualization rviz_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "rviz_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'rviz_launch.py') ), condition=IfCondition(use_rviz), - launch_arguments={"namespace": "", "use_namespace": "False"}.items(), + launch_arguments={'namespace': '', 'use_namespace': 'False'}.items(), ) # start navigation bringup_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "bringup_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'bringup_launch.py') ), - launch_arguments={"map": map_yaml_file}.items(), + launch_arguments={'map': map_yaml_file}.items(), ) # start the demo autonomy task demo_cmd = Node( - package="nav2_simple_commander", - executable="example_follow_path", + package='nav2_simple_commander', + executable='example_follow_path', emulate_tty=True, - output="screen", + output='screen', ) ld = LaunchDescription() diff --git a/nav2_simple_commander/launch/inspection_demo_launch.py b/nav2_simple_commander/launch/inspection_demo_launch.py index b6e4c502159..285f26099ea 100644 --- a/nav2_simple_commander/launch/inspection_demo_launch.py +++ b/nav2_simple_commander/launch/inspection_demo_launch.py @@ -29,72 +29,72 @@ def generate_launch_description(): - warehouse_dir = get_package_share_directory("aws_robomaker_small_warehouse_world") - nav2_bringup_dir = get_package_share_directory("nav2_bringup") - python_commander_dir = get_package_share_directory("nav2_simple_commander") + warehouse_dir = get_package_share_directory('aws_robomaker_small_warehouse_world') + nav2_bringup_dir = get_package_share_directory('nav2_bringup') + python_commander_dir = get_package_share_directory('nav2_simple_commander') - map_yaml_file = os.path.join(warehouse_dir, "maps", "005", "map.yaml") - world = os.path.join(python_commander_dir, "warehouse.world") + map_yaml_file = os.path.join(warehouse_dir, 'maps', '005', 'map.yaml') + world = os.path.join(python_commander_dir, 'warehouse.world') # Launch configuration variables - use_rviz = LaunchConfiguration("use_rviz") - headless = LaunchConfiguration("headless") + use_rviz = LaunchConfiguration('use_rviz') + headless = LaunchConfiguration('headless') # Declare the launch arguments declare_use_rviz_cmd = DeclareLaunchArgument( - "use_rviz", default_value="True", description="Whether to start RVIZ" + 'use_rviz', default_value='True', description='Whether to start RVIZ' ) declare_simulator_cmd = DeclareLaunchArgument( - "headless", default_value="False", description="Whether to execute gzclient)" + 'headless', default_value='False', description='Whether to execute gzclient)' ) # start the simulation start_gazebo_server_cmd = ExecuteProcess( - cmd=["gzserver", "-s", "libgazebo_ros_factory.so", world], + cmd=['gzserver', '-s', 'libgazebo_ros_factory.so', world], cwd=[warehouse_dir], - output="screen", + output='screen', ) start_gazebo_client_cmd = ExecuteProcess( - condition=IfCondition(PythonExpression(["not ", headless])), - cmd=["gzclient"], + condition=IfCondition(PythonExpression(['not ', headless])), + cmd=['gzclient'], cwd=[warehouse_dir], - output="screen", + output='screen', ) - urdf = os.path.join(nav2_bringup_dir, "urdf", "turtlebot3_waffle.urdf") + urdf = os.path.join(nav2_bringup_dir, 'urdf', 'turtlebot3_waffle.urdf') start_robot_state_publisher_cmd = Node( - package="robot_state_publisher", - executable="robot_state_publisher", - name="robot_state_publisher", - output="screen", + package='robot_state_publisher', + executable='robot_state_publisher', + name='robot_state_publisher', + output='screen', arguments=[urdf], ) # start the visualization rviz_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "rviz_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'rviz_launch.py') ), condition=IfCondition(use_rviz), - launch_arguments={"namespace": "", "use_namespace": "False"}.items(), + launch_arguments={'namespace': '', 'use_namespace': 'False'}.items(), ) # start navigation bringup_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "bringup_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'bringup_launch.py') ), - launch_arguments={"map": map_yaml_file}.items(), + launch_arguments={'map': map_yaml_file}.items(), ) # start the demo autonomy task demo_cmd = Node( - package="nav2_simple_commander", - executable="demo_inspection", + package='nav2_simple_commander', + executable='demo_inspection', emulate_tty=True, - output="screen", + output='screen', ) ld = LaunchDescription() diff --git a/nav2_simple_commander/launch/nav_through_poses_example_launch.py b/nav2_simple_commander/launch/nav_through_poses_example_launch.py index 139378b126d..e8b0fefba0b 100644 --- a/nav2_simple_commander/launch/nav_through_poses_example_launch.py +++ b/nav2_simple_commander/launch/nav_through_poses_example_launch.py @@ -29,72 +29,72 @@ def generate_launch_description(): - warehouse_dir = get_package_share_directory("aws_robomaker_small_warehouse_world") - nav2_bringup_dir = get_package_share_directory("nav2_bringup") - python_commander_dir = get_package_share_directory("nav2_simple_commander") + warehouse_dir = get_package_share_directory('aws_robomaker_small_warehouse_world') + nav2_bringup_dir = get_package_share_directory('nav2_bringup') + python_commander_dir = get_package_share_directory('nav2_simple_commander') - map_yaml_file = os.path.join(warehouse_dir, "maps", "005", "map.yaml") - world = os.path.join(python_commander_dir, "warehouse.world") + map_yaml_file = os.path.join(warehouse_dir, 'maps', '005', 'map.yaml') + world = os.path.join(python_commander_dir, 'warehouse.world') # Launch configuration variables - use_rviz = LaunchConfiguration("use_rviz") - headless = LaunchConfiguration("headless") + use_rviz = LaunchConfiguration('use_rviz') + headless = LaunchConfiguration('headless') # Declare the launch arguments declare_use_rviz_cmd = DeclareLaunchArgument( - "use_rviz", default_value="True", description="Whether to start RVIZ" + 'use_rviz', default_value='True', description='Whether to start RVIZ' ) declare_simulator_cmd = DeclareLaunchArgument( - "headless", default_value="False", description="Whether to execute gzclient)" + 'headless', default_value='False', description='Whether to execute gzclient)' ) # start the simulation start_gazebo_server_cmd = ExecuteProcess( - cmd=["gzserver", "-s", "libgazebo_ros_factory.so", world], + cmd=['gzserver', '-s', 'libgazebo_ros_factory.so', world], cwd=[warehouse_dir], - output="screen", + output='screen', ) start_gazebo_client_cmd = ExecuteProcess( - condition=IfCondition(PythonExpression(["not ", headless])), - cmd=["gzclient"], + condition=IfCondition(PythonExpression(['not ', headless])), + cmd=['gzclient'], cwd=[warehouse_dir], - output="screen", + output='screen', ) - urdf = os.path.join(nav2_bringup_dir, "urdf", "turtlebot3_waffle.urdf") + urdf = os.path.join(nav2_bringup_dir, 'urdf', 'turtlebot3_waffle.urdf') start_robot_state_publisher_cmd = Node( - package="robot_state_publisher", - executable="robot_state_publisher", - name="robot_state_publisher", - output="screen", + package='robot_state_publisher', + executable='robot_state_publisher', + name='robot_state_publisher', + output='screen', arguments=[urdf], ) # start the visualization rviz_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "rviz_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'rviz_launch.py') ), condition=IfCondition(use_rviz), - launch_arguments={"namespace": "", "use_namespace": "False"}.items(), + launch_arguments={'namespace': '', 'use_namespace': 'False'}.items(), ) # start navigation bringup_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "bringup_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'bringup_launch.py') ), - launch_arguments={"map": map_yaml_file}.items(), + launch_arguments={'map': map_yaml_file}.items(), ) # start the demo autonomy task demo_cmd = Node( - package="nav2_simple_commander", - executable="example_nav_through_poses", + package='nav2_simple_commander', + executable='example_nav_through_poses', emulate_tty=True, - output="screen", + output='screen', ) ld = LaunchDescription() diff --git a/nav2_simple_commander/launch/nav_to_pose_example_launch.py b/nav2_simple_commander/launch/nav_to_pose_example_launch.py index ee2c9a8552d..29aeddebd16 100644 --- a/nav2_simple_commander/launch/nav_to_pose_example_launch.py +++ b/nav2_simple_commander/launch/nav_to_pose_example_launch.py @@ -29,72 +29,72 @@ def generate_launch_description(): - warehouse_dir = get_package_share_directory("aws_robomaker_small_warehouse_world") - nav2_bringup_dir = get_package_share_directory("nav2_bringup") - python_commander_dir = get_package_share_directory("nav2_simple_commander") + warehouse_dir = get_package_share_directory('aws_robomaker_small_warehouse_world') + nav2_bringup_dir = get_package_share_directory('nav2_bringup') + python_commander_dir = get_package_share_directory('nav2_simple_commander') - map_yaml_file = os.path.join(warehouse_dir, "maps", "005", "map.yaml") - world = os.path.join(python_commander_dir, "warehouse.world") + map_yaml_file = os.path.join(warehouse_dir, 'maps', '005', 'map.yaml') + world = os.path.join(python_commander_dir, 'warehouse.world') # Launch configuration variables - use_rviz = LaunchConfiguration("use_rviz") - headless = LaunchConfiguration("headless") + use_rviz = LaunchConfiguration('use_rviz') + headless = LaunchConfiguration('headless') # Declare the launch arguments declare_use_rviz_cmd = DeclareLaunchArgument( - "use_rviz", default_value="True", description="Whether to start RVIZ" + 'use_rviz', default_value='True', description='Whether to start RVIZ' ) declare_simulator_cmd = DeclareLaunchArgument( - "headless", default_value="False", description="Whether to execute gzclient)" + 'headless', default_value='False', description='Whether to execute gzclient)' ) # start the simulation start_gazebo_server_cmd = ExecuteProcess( - cmd=["gzserver", "-s", "libgazebo_ros_factory.so", world], + cmd=['gzserver', '-s', 'libgazebo_ros_factory.so', world], cwd=[warehouse_dir], - output="screen", + output='screen', ) start_gazebo_client_cmd = ExecuteProcess( - condition=IfCondition(PythonExpression(["not ", headless])), - cmd=["gzclient"], + condition=IfCondition(PythonExpression(['not ', headless])), + cmd=['gzclient'], cwd=[warehouse_dir], - output="screen", + output='screen', ) - urdf = os.path.join(nav2_bringup_dir, "urdf", "turtlebot3_waffle.urdf") + urdf = os.path.join(nav2_bringup_dir, 'urdf', 'turtlebot3_waffle.urdf') start_robot_state_publisher_cmd = Node( - package="robot_state_publisher", - executable="robot_state_publisher", - name="robot_state_publisher", - output="screen", + package='robot_state_publisher', + executable='robot_state_publisher', + name='robot_state_publisher', + output='screen', arguments=[urdf], ) # start the visualization rviz_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "rviz_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'rviz_launch.py') ), condition=IfCondition(use_rviz), - launch_arguments={"namespace": "", "use_namespace": "False"}.items(), + launch_arguments={'namespace': '', 'use_namespace': 'False'}.items(), ) # start navigation bringup_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "bringup_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'bringup_launch.py') ), - launch_arguments={"map": map_yaml_file}.items(), + launch_arguments={'map': map_yaml_file}.items(), ) # start the demo autonomy task demo_cmd = Node( - package="nav2_simple_commander", - executable="example_nav_to_pose", + package='nav2_simple_commander', + executable='example_nav_to_pose', emulate_tty=True, - output="screen", + output='screen', ) ld = LaunchDescription() diff --git a/nav2_simple_commander/launch/picking_demo_launch.py b/nav2_simple_commander/launch/picking_demo_launch.py index 8d1872c64bc..8505b6bbc32 100644 --- a/nav2_simple_commander/launch/picking_demo_launch.py +++ b/nav2_simple_commander/launch/picking_demo_launch.py @@ -29,72 +29,72 @@ def generate_launch_description(): - warehouse_dir = get_package_share_directory("aws_robomaker_small_warehouse_world") - nav2_bringup_dir = get_package_share_directory("nav2_bringup") - python_commander_dir = get_package_share_directory("nav2_simple_commander") + warehouse_dir = get_package_share_directory('aws_robomaker_small_warehouse_world') + nav2_bringup_dir = get_package_share_directory('nav2_bringup') + python_commander_dir = get_package_share_directory('nav2_simple_commander') - map_yaml_file = os.path.join(warehouse_dir, "maps", "005", "map.yaml") - world = os.path.join(python_commander_dir, "warehouse.world") + map_yaml_file = os.path.join(warehouse_dir, 'maps', '005', 'map.yaml') + world = os.path.join(python_commander_dir, 'warehouse.world') # Launch configuration variables - use_rviz = LaunchConfiguration("use_rviz") - headless = LaunchConfiguration("headless") + use_rviz = LaunchConfiguration('use_rviz') + headless = LaunchConfiguration('headless') # Declare the launch arguments declare_use_rviz_cmd = DeclareLaunchArgument( - "use_rviz", default_value="True", description="Whether to start RVIZ" + 'use_rviz', default_value='True', description='Whether to start RVIZ' ) declare_simulator_cmd = DeclareLaunchArgument( - "headless", default_value="False", description="Whether to execute gzclient)" + 'headless', default_value='False', description='Whether to execute gzclient)' ) # start the simulation start_gazebo_server_cmd = ExecuteProcess( - cmd=["gzserver", "-s", "libgazebo_ros_factory.so", world], + cmd=['gzserver', '-s', 'libgazebo_ros_factory.so', world], cwd=[warehouse_dir], - output="screen", + output='screen', ) start_gazebo_client_cmd = ExecuteProcess( - condition=IfCondition(PythonExpression(["not ", headless])), - cmd=["gzclient"], + condition=IfCondition(PythonExpression(['not ', headless])), + cmd=['gzclient'], cwd=[warehouse_dir], - output="screen", + output='screen', ) - urdf = os.path.join(nav2_bringup_dir, "urdf", "turtlebot3_waffle.urdf") + urdf = os.path.join(nav2_bringup_dir, 'urdf', 'turtlebot3_waffle.urdf') start_robot_state_publisher_cmd = Node( - package="robot_state_publisher", - executable="robot_state_publisher", - name="robot_state_publisher", - output="screen", + package='robot_state_publisher', + executable='robot_state_publisher', + name='robot_state_publisher', + output='screen', arguments=[urdf], ) # start the visualization rviz_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "rviz_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'rviz_launch.py') ), condition=IfCondition(use_rviz), - launch_arguments={"namespace": "", "use_namespace": "False"}.items(), + launch_arguments={'namespace': '', 'use_namespace': 'False'}.items(), ) # start navigation bringup_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "bringup_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'bringup_launch.py') ), - launch_arguments={"map": map_yaml_file}.items(), + launch_arguments={'map': map_yaml_file}.items(), ) # start the demo autonomy task demo_cmd = Node( - package="nav2_simple_commander", - executable="demo_picking", + package='nav2_simple_commander', + executable='demo_picking', emulate_tty=True, - output="screen", + output='screen', ) ld = LaunchDescription() diff --git a/nav2_simple_commander/launch/recoveries_example_launch.py b/nav2_simple_commander/launch/recoveries_example_launch.py index 92347aa4a0d..638550c44e4 100644 --- a/nav2_simple_commander/launch/recoveries_example_launch.py +++ b/nav2_simple_commander/launch/recoveries_example_launch.py @@ -29,72 +29,72 @@ def generate_launch_description(): - warehouse_dir = get_package_share_directory("aws_robomaker_small_warehouse_world") - nav2_bringup_dir = get_package_share_directory("nav2_bringup") - python_commander_dir = get_package_share_directory("nav2_simple_commander") + warehouse_dir = get_package_share_directory('aws_robomaker_small_warehouse_world') + nav2_bringup_dir = get_package_share_directory('nav2_bringup') + python_commander_dir = get_package_share_directory('nav2_simple_commander') - map_yaml_file = os.path.join(warehouse_dir, "maps", "005", "map.yaml") - world = os.path.join(python_commander_dir, "warehouse.world") + map_yaml_file = os.path.join(warehouse_dir, 'maps', '005', 'map.yaml') + world = os.path.join(python_commander_dir, 'warehouse.world') # Launch configuration variables - use_rviz = LaunchConfiguration("use_rviz") - headless = LaunchConfiguration("headless") + use_rviz = LaunchConfiguration('use_rviz') + headless = LaunchConfiguration('headless') # Declare the launch arguments declare_use_rviz_cmd = DeclareLaunchArgument( - "use_rviz", default_value="True", description="Whether to start RVIZ" + 'use_rviz', default_value='True', description='Whether to start RVIZ' ) declare_simulator_cmd = DeclareLaunchArgument( - "headless", default_value="False", description="Whether to execute gzclient)" + 'headless', default_value='False', description='Whether to execute gzclient)' ) # start the simulation start_gazebo_server_cmd = ExecuteProcess( - cmd=["gzserver", "-s", "libgazebo_ros_factory.so", world], + cmd=['gzserver', '-s', 'libgazebo_ros_factory.so', world], cwd=[warehouse_dir], - output="screen", + output='screen', ) start_gazebo_client_cmd = ExecuteProcess( - condition=IfCondition(PythonExpression(["not ", headless])), - cmd=["gzclient"], + condition=IfCondition(PythonExpression(['not ', headless])), + cmd=['gzclient'], cwd=[warehouse_dir], - output="screen", + output='screen', ) - urdf = os.path.join(nav2_bringup_dir, "urdf", "turtlebot3_waffle.urdf") + urdf = os.path.join(nav2_bringup_dir, 'urdf', 'turtlebot3_waffle.urdf') start_robot_state_publisher_cmd = Node( - package="robot_state_publisher", - executable="robot_state_publisher", - name="robot_state_publisher", - output="screen", + package='robot_state_publisher', + executable='robot_state_publisher', + name='robot_state_publisher', + output='screen', arguments=[urdf], ) # start the visualization rviz_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "rviz_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'rviz_launch.py') ), condition=IfCondition(use_rviz), - launch_arguments={"namespace": "", "use_namespace": "False"}.items(), + launch_arguments={'namespace': '', 'use_namespace': 'False'}.items(), ) # start navigation bringup_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "bringup_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'bringup_launch.py') ), - launch_arguments={"map": map_yaml_file}.items(), + launch_arguments={'map': map_yaml_file}.items(), ) # start the demo autonomy task demo_cmd = Node( - package="nav2_simple_commander", - executable="demo_recoveries", + package='nav2_simple_commander', + executable='demo_recoveries', emulate_tty=True, - output="screen", + output='screen', ) ld = LaunchDescription() diff --git a/nav2_simple_commander/launch/security_demo_launch.py b/nav2_simple_commander/launch/security_demo_launch.py index 6cc72aff0f0..a958a75f734 100644 --- a/nav2_simple_commander/launch/security_demo_launch.py +++ b/nav2_simple_commander/launch/security_demo_launch.py @@ -29,72 +29,72 @@ def generate_launch_description(): - warehouse_dir = get_package_share_directory("aws_robomaker_small_warehouse_world") - nav2_bringup_dir = get_package_share_directory("nav2_bringup") - python_commander_dir = get_package_share_directory("nav2_simple_commander") + warehouse_dir = get_package_share_directory('aws_robomaker_small_warehouse_world') + nav2_bringup_dir = get_package_share_directory('nav2_bringup') + python_commander_dir = get_package_share_directory('nav2_simple_commander') - map_yaml_file = os.path.join(warehouse_dir, "maps", "005", "map.yaml") - world = os.path.join(python_commander_dir, "warehouse.world") + map_yaml_file = os.path.join(warehouse_dir, 'maps', '005', 'map.yaml') + world = os.path.join(python_commander_dir, 'warehouse.world') # Launch configuration variables - use_rviz = LaunchConfiguration("use_rviz") - headless = LaunchConfiguration("headless") + use_rviz = LaunchConfiguration('use_rviz') + headless = LaunchConfiguration('headless') # Declare the launch arguments declare_use_rviz_cmd = DeclareLaunchArgument( - "use_rviz", default_value="True", description="Whether to start RVIZ" + 'use_rviz', default_value='True', description='Whether to start RVIZ' ) declare_simulator_cmd = DeclareLaunchArgument( - "headless", default_value="False", description="Whether to execute gzclient)" + 'headless', default_value='False', description='Whether to execute gzclient)' ) # start the simulation start_gazebo_server_cmd = ExecuteProcess( - cmd=["gzserver", "-s", "libgazebo_ros_factory.so", world], + cmd=['gzserver', '-s', 'libgazebo_ros_factory.so', world], cwd=[warehouse_dir], - output="screen", + output='screen', ) start_gazebo_client_cmd = ExecuteProcess( - condition=IfCondition(PythonExpression(["not ", headless])), - cmd=["gzclient"], + condition=IfCondition(PythonExpression(['not ', headless])), + cmd=['gzclient'], cwd=[warehouse_dir], - output="screen", + output='screen', ) - urdf = os.path.join(nav2_bringup_dir, "urdf", "turtlebot3_waffle.urdf") + urdf = os.path.join(nav2_bringup_dir, 'urdf', 'turtlebot3_waffle.urdf') start_robot_state_publisher_cmd = Node( - package="robot_state_publisher", - executable="robot_state_publisher", - name="robot_state_publisher", - output="screen", + package='robot_state_publisher', + executable='robot_state_publisher', + name='robot_state_publisher', + output='screen', arguments=[urdf], ) # start the visualization rviz_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "rviz_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'rviz_launch.py') ), condition=IfCondition(use_rviz), - launch_arguments={"namespace": "", "use_namespace": "False"}.items(), + launch_arguments={'namespace': '', 'use_namespace': 'False'}.items(), ) # start navigation bringup_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "bringup_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'bringup_launch.py') ), - launch_arguments={"map": map_yaml_file}.items(), + launch_arguments={'map': map_yaml_file}.items(), ) # start the demo autonomy task demo_cmd = Node( - package="nav2_simple_commander", - executable="demo_security", + package='nav2_simple_commander', + executable='demo_security', emulate_tty=True, - output="screen", + output='screen', ) ld = LaunchDescription() diff --git a/nav2_simple_commander/launch/waypoint_follower_example_launch.py b/nav2_simple_commander/launch/waypoint_follower_example_launch.py index 9a315a4b443..f164035e3b9 100644 --- a/nav2_simple_commander/launch/waypoint_follower_example_launch.py +++ b/nav2_simple_commander/launch/waypoint_follower_example_launch.py @@ -29,72 +29,72 @@ def generate_launch_description(): - warehouse_dir = get_package_share_directory("aws_robomaker_small_warehouse_world") - nav2_bringup_dir = get_package_share_directory("nav2_bringup") - python_commander_dir = get_package_share_directory("nav2_simple_commander") + warehouse_dir = get_package_share_directory('aws_robomaker_small_warehouse_world') + nav2_bringup_dir = get_package_share_directory('nav2_bringup') + python_commander_dir = get_package_share_directory('nav2_simple_commander') - map_yaml_file = os.path.join(warehouse_dir, "maps", "005", "map.yaml") - world = os.path.join(python_commander_dir, "warehouse.world") + map_yaml_file = os.path.join(warehouse_dir, 'maps', '005', 'map.yaml') + world = os.path.join(python_commander_dir, 'warehouse.world') # Launch configuration variables - use_rviz = LaunchConfiguration("use_rviz") - headless = LaunchConfiguration("headless") + use_rviz = LaunchConfiguration('use_rviz') + headless = LaunchConfiguration('headless') # Declare the launch arguments declare_use_rviz_cmd = DeclareLaunchArgument( - "use_rviz", default_value="True", description="Whether to start RVIZ" + 'use_rviz', default_value='True', description='Whether to start RVIZ' ) declare_simulator_cmd = DeclareLaunchArgument( - "headless", default_value="False", description="Whether to execute gzclient)" + 'headless', default_value='False', description='Whether to execute gzclient)' ) # start the simulation start_gazebo_server_cmd = ExecuteProcess( - cmd=["gzserver", "-s", "libgazebo_ros_factory.so", world], + cmd=['gzserver', '-s', 'libgazebo_ros_factory.so', world], cwd=[warehouse_dir], - output="screen", + output='screen', ) start_gazebo_client_cmd = ExecuteProcess( - condition=IfCondition(PythonExpression(["not ", headless])), - cmd=["gzclient"], + condition=IfCondition(PythonExpression(['not ', headless])), + cmd=['gzclient'], cwd=[warehouse_dir], - output="screen", + output='screen', ) - urdf = os.path.join(nav2_bringup_dir, "urdf", "turtlebot3_waffle.urdf") + urdf = os.path.join(nav2_bringup_dir, 'urdf', 'turtlebot3_waffle.urdf') start_robot_state_publisher_cmd = Node( - package="robot_state_publisher", - executable="robot_state_publisher", - name="robot_state_publisher", - output="screen", + package='robot_state_publisher', + executable='robot_state_publisher', + name='robot_state_publisher', + output='screen', arguments=[urdf], ) # start the visualization rviz_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "rviz_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'rviz_launch.py') ), condition=IfCondition(use_rviz), - launch_arguments={"namespace": "", "use_namespace": "False"}.items(), + launch_arguments={'namespace': '', 'use_namespace': 'False'}.items(), ) # start navigation bringup_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource( - os.path.join(nav2_bringup_dir, "launch", "bringup_launch.py") + os.path.join(nav2_bringup_dir, 'launch', 'bringup_launch.py') ), - launch_arguments={"map": map_yaml_file}.items(), + launch_arguments={'map': map_yaml_file}.items(), ) # start the demo autonomy task demo_cmd = Node( - package="nav2_simple_commander", - executable="example_waypoint_follower", + package='nav2_simple_commander', + executable='example_waypoint_follower', emulate_tty=True, - output="screen", + output='screen', ) ld = LaunchDescription() diff --git a/nav2_simple_commander/nav2_simple_commander/demo_inspection.py b/nav2_simple_commander/nav2_simple_commander/demo_inspection.py index 198fe3d5a73..5f6d04769a0 100644 --- a/nav2_simple_commander/nav2_simple_commander/demo_inspection.py +++ b/nav2_simple_commander/nav2_simple_commander/demo_inspection.py @@ -46,7 +46,7 @@ def main(): # Set our demo's initial pose initial_pose = PoseStamped() - initial_pose.header.frame_id = "map" + initial_pose.header.frame_id = 'map' initial_pose.header.stamp = navigator.get_clock().now().to_msg() initial_pose.pose.position.x = 3.45 initial_pose.pose.position.y = 2.15 @@ -60,7 +60,7 @@ def main(): # Send our route inspection_points = [] inspection_pose = PoseStamped() - inspection_pose.header.frame_id = "map" + inspection_pose.header.frame_id = 'map' inspection_pose.header.stamp = navigator.get_clock().now().to_msg() inspection_pose.pose.orientation.z = 1.0 inspection_pose.pose.orientation.w = 0.0 @@ -78,19 +78,19 @@ def main(): feedback = navigator.getFeedback() if feedback and i % 5 == 0: print( - "Executing current waypoint: " + 'Executing current waypoint: ' + str(feedback.current_waypoint + 1) - + "/" + + '/' + str(len(inspection_points)) ) result = navigator.getResult() if result == TaskResult.SUCCEEDED: - print("Inspection of shelves complete! Returning to start...") + print('Inspection of shelves complete! Returning to start...') elif result == TaskResult.CANCELED: - print("Inspection of shelving was canceled. Returning to start...") + print('Inspection of shelving was canceled. Returning to start...') elif result == TaskResult.FAILED: - print("Inspection of shelving failed! Returning to start...") + print('Inspection of shelving failed! Returning to start...') # go back to start initial_pose.header.stamp = navigator.get_clock().now().to_msg() @@ -101,5 +101,5 @@ def main(): exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_simple_commander/nav2_simple_commander/demo_picking.py b/nav2_simple_commander/nav2_simple_commander/demo_picking.py index 6a87b99cdd5..48c0551c2cd 100644 --- a/nav2_simple_commander/nav2_simple_commander/demo_picking.py +++ b/nav2_simple_commander/nav2_simple_commander/demo_picking.py @@ -22,18 +22,18 @@ # Shelf positions for picking shelf_positions = { - "shelf_A": [-3.829, -7.604], - "shelf_B": [-3.791, -3.287], - "shelf_C": [-3.791, 1.254], - "shelf_D": [-3.24, 5.861], + 'shelf_A': [-3.829, -7.604], + 'shelf_B': [-3.791, -3.287], + 'shelf_C': [-3.791, 1.254], + 'shelf_D': [-3.24, 5.861], } # Shipping destination for picked products shipping_destinations = { - "recycling": [-0.205, 7.403], - "pallet_jack7": [-0.073, -8.497], - "conveyer_432": [6.217, 2.153], - "frieght_bay_3": [-6.349, 9.147], + 'recycling': [-0.205, 7.403], + 'pallet_jack7': [-0.073, -8.497], + 'conveyer_432': [6.217, 2.153], + 'frieght_bay_3': [-6.349, 9.147], } """ @@ -47,10 +47,10 @@ def main(): # Recieved virtual request for picking item at Shelf A and bring to # worker at the pallet jack 7 for shipping. This request would - # contain the shelf ID ("shelf_A") and shipping destination ("pallet_jack7") + # contain the shelf ID ('shelf_A') and shipping destination ('pallet_jack7') #################### - request_item_location = "shelf_C" - request_destination = "pallet_jack7" + request_item_location = 'shelf_C' + request_destination = 'pallet_jack7' #################### rclpy.init() @@ -59,7 +59,7 @@ def main(): # Set our demo's initial pose initial_pose = PoseStamped() - initial_pose.header.frame_id = "map" + initial_pose.header.frame_id = 'map' initial_pose.header.stamp = navigator.get_clock().now().to_msg() initial_pose.pose.position.x = 3.45 initial_pose.pose.position.y = 2.15 @@ -71,13 +71,13 @@ def main(): navigator.waitUntilNav2Active() shelf_item_pose = PoseStamped() - shelf_item_pose.header.frame_id = "map" + shelf_item_pose.header.frame_id = 'map' shelf_item_pose.header.stamp = navigator.get_clock().now().to_msg() shelf_item_pose.pose.position.x = shelf_positions[request_item_location][0] shelf_item_pose.pose.position.y = shelf_positions[request_item_location][1] shelf_item_pose.pose.orientation.z = 1.0 shelf_item_pose.pose.orientation.w = 0.0 - print(f"Received request for item picking at {request_item_location}.") + print(f'Received request for item picking at {request_item_location}.') navigator.goToPose(shelf_item_pose) # Do something during our route @@ -89,27 +89,27 @@ def main(): feedback = navigator.getFeedback() if feedback and i % 5 == 0: print( - "Estimated time of arrival at " + 'Estimated time of arrival at ' + request_item_location - + " for worker: " - + "{0:.0f}".format( + + ' for worker: ' + + '{0:.0f}'.format( Duration.from_msg(feedback.estimated_time_remaining).nanoseconds / 1e9 ) - + " seconds." + + ' seconds.' ) result = navigator.getResult() if result == TaskResult.SUCCEEDED: print( - "Got product from " + 'Got product from ' + request_item_location - + "! Bringing product to shipping destination (" + + '! Bringing product to shipping destination (' + request_destination - + ")..." + + ')...' ) shipping_destination = PoseStamped() - shipping_destination.header.frame_id = "map" + shipping_destination.header.frame_id = 'map' shipping_destination.header.stamp = navigator.get_clock().now().to_msg() shipping_destination.pose.position.x = shipping_destinations[ request_destination @@ -123,13 +123,13 @@ def main(): elif result == TaskResult.CANCELED: print( - f"Task at {request_item_location} was canceled. Returning to staging point..." + f'Task at {request_item_location} was canceled. Returning to staging point...' ) initial_pose.header.stamp = navigator.get_clock().now().to_msg() navigator.goToPose(initial_pose) elif result == TaskResult.FAILED: - print(f"Task at {request_item_location} failed!") + print(f'Task at {request_item_location} failed!') exit(-1) while not navigator.isTaskComplete(): @@ -138,5 +138,5 @@ def main(): exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_simple_commander/nav2_simple_commander/demo_recoveries.py b/nav2_simple_commander/nav2_simple_commander/demo_recoveries.py index c8b09e89a84..0313f956fff 100644 --- a/nav2_simple_commander/nav2_simple_commander/demo_recoveries.py +++ b/nav2_simple_commander/nav2_simple_commander/demo_recoveries.py @@ -33,7 +33,7 @@ def main(): # Set our demo's initial pose initial_pose = PoseStamped() - initial_pose.header.frame_id = "map" + initial_pose.header.frame_id = 'map' initial_pose.header.stamp = navigator.get_clock().now().to_msg() initial_pose.pose.position.x = 3.45 initial_pose.pose.position.y = 2.15 @@ -45,7 +45,7 @@ def main(): navigator.waitUntilNav2Active() goal_pose = PoseStamped() - goal_pose.header.frame_id = "map" + goal_pose.header.frame_id = 'map' goal_pose.header.stamp = navigator.get_clock().now().to_msg() goal_pose.pose.position.x = 6.13 goal_pose.pose.position.y = 1.90 @@ -59,12 +59,12 @@ def main(): feedback = navigator.getFeedback() if feedback and i % 5 == 0: print( - f"Estimated time of arrival to destination is: \ - {Duration.from_msg(feedback.estimated_time_remaining).nanoseconds / 1e9}" + f'Estimated time of arrival to destination is: \ + {Duration.from_msg(feedback.estimated_time_remaining).nanoseconds / 1e9}' ) # Robot hit a dead end, back it up - print("Robot hit a dead end, backing up...") + print('Robot hit a dead end, backing up...') navigator.backup(backup_dist=0.5, backup_speed=0.1) i = 0 @@ -72,10 +72,10 @@ def main(): i += 1 feedback = navigator.getFeedback() if feedback and i % 5 == 0: - print(f"Distance traveled: {feedback.distance_traveled}") + print(f'Distance traveled: {feedback.distance_traveled}') # Turn it around - print("Spinning robot around...") + print('Spinning robot around...') navigator.spin(spin_dist=3.14) i = 0 @@ -83,15 +83,15 @@ def main(): i += 1 feedback = navigator.getFeedback() if feedback and i % 5 == 0: - print(f"Spin angle traveled: {feedback.angular_distance_traveled}") + print(f'Spin angle traveled: {feedback.angular_distance_traveled}') result = navigator.getResult() if result == TaskResult.SUCCEEDED: - print("Dead end confirmed! Returning to start...") + print('Dead end confirmed! Returning to start...') elif result == TaskResult.CANCELED: - print("Recovery was canceled. Returning to start...") + print('Recovery was canceled. Returning to start...') elif result == TaskResult.FAILED: - print("Recovering from dead end failed! Returning to start...") + print('Recovering from dead end failed! Returning to start...') initial_pose.header.stamp = navigator.get_clock().now().to_msg() navigator.goToPose(initial_pose) @@ -101,5 +101,5 @@ def main(): exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_simple_commander/nav2_simple_commander/demo_security.py b/nav2_simple_commander/nav2_simple_commander/demo_security.py index 32ccc1138f8..24cc05feff2 100644 --- a/nav2_simple_commander/nav2_simple_commander/demo_security.py +++ b/nav2_simple_commander/nav2_simple_commander/demo_security.py @@ -48,7 +48,7 @@ def main(): # Set our demo's initial pose initial_pose = PoseStamped() - initial_pose.header.frame_id = "map" + initial_pose.header.frame_id = 'map' initial_pose.header.stamp = navigator.get_clock().now().to_msg() initial_pose.pose.position.x = 3.45 initial_pose.pose.position.y = 2.15 @@ -64,7 +64,7 @@ def main(): # Send our route route_poses = [] pose = PoseStamped() - pose.header.frame_id = "map" + pose.header.frame_id = 'map' pose.header.stamp = navigator.get_clock().now().to_msg() pose.pose.orientation.w = 1.0 for pt in security_route: @@ -81,19 +81,19 @@ def main(): feedback = navigator.getFeedback() if feedback and i % 5 == 0: print( - "Estimated time to complete current route: " - + "{0:.0f}".format( + 'Estimated time to complete current route: ' + + '{0:.0f}'.format( Duration.from_msg(feedback.estimated_time_remaining).nanoseconds / 1e9 ) - + " seconds." + + ' seconds.' ) # Some failure mode, must stop since the robot is clearly stuck if Duration.from_msg(feedback.navigation_time) > Duration( seconds=180.0 ): - print("Navigation has exceeded timeout of 180s, canceling request.") + print('Navigation has exceeded timeout of 180s, canceling request.') navigator.cancelTask() # If at end of route, reverse the route to restart @@ -101,15 +101,15 @@ def main(): result = navigator.getResult() if result == TaskResult.SUCCEEDED: - print("Route complete! Restarting...") + print('Route complete! Restarting...') elif result == TaskResult.CANCELED: - print("Security route was canceled, exiting.") + print('Security route was canceled, exiting.') exit(1) elif result == TaskResult.FAILED: - print("Security route failed! Restarting from other side...") + print('Security route failed! Restarting from other side...') exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_simple_commander/nav2_simple_commander/example_assisted_teleop.py b/nav2_simple_commander/nav2_simple_commander/example_assisted_teleop.py index 8806642da3d..564342e5417 100644 --- a/nav2_simple_commander/nav2_simple_commander/example_assisted_teleop.py +++ b/nav2_simple_commander/nav2_simple_commander/example_assisted_teleop.py @@ -31,7 +31,7 @@ def main(): # Set our demo's initial pose initial_pose = PoseStamped() - initial_pose.header.frame_id = "map" + initial_pose.header.frame_id = 'map' initial_pose.header.stamp = navigator.get_clock().now().to_msg() initial_pose.pose.position.x = 3.45 initial_pose.pose.position.y = 2.15 @@ -52,5 +52,5 @@ def main(): exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_simple_commander/nav2_simple_commander/example_follow_path.py b/nav2_simple_commander/nav2_simple_commander/example_follow_path.py index 3a3d6372c91..104083f34a7 100644 --- a/nav2_simple_commander/nav2_simple_commander/example_follow_path.py +++ b/nav2_simple_commander/nav2_simple_commander/example_follow_path.py @@ -30,7 +30,7 @@ def main(): # Set our demo's initial pose initial_pose = PoseStamped() - initial_pose.header.frame_id = "map" + initial_pose.header.frame_id = 'map' initial_pose.header.stamp = navigator.get_clock().now().to_msg() initial_pose.pose.position.x = 3.45 initial_pose.pose.position.y = 2.15 @@ -43,7 +43,7 @@ def main(): # Go to our demos first goal pose goal_pose = PoseStamped() - goal_pose.header.frame_id = "map" + goal_pose.header.frame_id = 'map' goal_pose.header.stamp = navigator.get_clock().now().to_msg() goal_pose.pose.position.x = -3.0 goal_pose.pose.position.y = -2.0 @@ -69,27 +69,27 @@ def main(): feedback = navigator.getFeedback() if feedback and i % 5 == 0: print( - "Estimated distance remaining to goal position: " - + "{0:.3f}".format(feedback.distance_to_goal) - + "\nCurrent speed of the robot: " - + "{0:.3f}".format(feedback.speed) + 'Estimated distance remaining to goal position: ' + + '{0:.3f}'.format(feedback.distance_to_goal) + + '\nCurrent speed of the robot: ' + + '{0:.3f}'.format(feedback.speed) ) # Do something depending on the return code result = navigator.getResult() if result == TaskResult.SUCCEEDED: - print("Goal succeeded!") + print('Goal succeeded!') elif result == TaskResult.CANCELED: - print("Goal was canceled!") + print('Goal was canceled!') elif result == TaskResult.FAILED: - print("Goal failed!") + print('Goal failed!') else: - print("Goal has an invalid return status!") + print('Goal has an invalid return status!') navigator.lifecycleShutdown() exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_simple_commander/nav2_simple_commander/example_nav_through_poses.py b/nav2_simple_commander/nav2_simple_commander/example_nav_through_poses.py index c82b71c0976..66023ec11a5 100644 --- a/nav2_simple_commander/nav2_simple_commander/example_nav_through_poses.py +++ b/nav2_simple_commander/nav2_simple_commander/example_nav_through_poses.py @@ -30,7 +30,7 @@ def main(): # Set our demo's initial pose initial_pose = PoseStamped() - initial_pose.header.frame_id = "map" + initial_pose.header.frame_id = 'map' initial_pose.header.stamp = navigator.get_clock().now().to_msg() initial_pose.pose.position.x = 3.45 initial_pose.pose.position.y = 2.15 @@ -57,7 +57,7 @@ def main(): # set our demo's goal poses goal_poses = [] goal_pose1 = PoseStamped() - goal_pose1.header.frame_id = "map" + goal_pose1.header.frame_id = 'map' goal_pose1.header.stamp = navigator.get_clock().now().to_msg() goal_pose1.pose.position.x = 1.5 goal_pose1.pose.position.y = 0.55 @@ -67,7 +67,7 @@ def main(): # additional goals can be appended goal_pose2 = PoseStamped() - goal_pose2.header.frame_id = "map" + goal_pose2.header.frame_id = 'map' goal_pose2.header.stamp = navigator.get_clock().now().to_msg() goal_pose2.pose.position.x = 1.5 goal_pose2.pose.position.y = -3.75 @@ -75,7 +75,7 @@ def main(): goal_pose2.pose.orientation.z = 0.707 goal_poses.append(goal_pose2) goal_pose3 = PoseStamped() - goal_pose3.header.frame_id = "map" + goal_pose3.header.frame_id = 'map' goal_pose3.header.stamp = navigator.get_clock().now().to_msg() goal_pose3.pose.position.x = -3.6 goal_pose3.pose.position.y = -4.75 @@ -101,12 +101,12 @@ def main(): feedback = navigator.getFeedback() if feedback and i % 5 == 0: print( - "Estimated time of arrival: " - + "{0:.0f}".format( + 'Estimated time of arrival: ' + + '{0:.0f}'.format( Duration.from_msg(feedback.estimated_time_remaining).nanoseconds / 1e9 ) - + " seconds." + + ' seconds.' ) # Some navigation timeout to demo cancellation @@ -116,7 +116,7 @@ def main(): # Some navigation request change to demo preemption if Duration.from_msg(feedback.navigation_time) > Duration(seconds=35.0): goal_pose4 = PoseStamped() - goal_pose4.header.frame_id = "map" + goal_pose4.header.frame_id = 'map' goal_pose4.header.stamp = navigator.get_clock().now().to_msg() goal_pose4.pose.position.x = -5.0 goal_pose4.pose.position.y = -4.75 @@ -127,18 +127,18 @@ def main(): # Do something depending on the return code result = navigator.getResult() if result == TaskResult.SUCCEEDED: - print("Goal succeeded!") + print('Goal succeeded!') elif result == TaskResult.CANCELED: - print("Goal was canceled!") + print('Goal was canceled!') elif result == TaskResult.FAILED: - print("Goal failed!") + print('Goal failed!') else: - print("Goal has an invalid return status!") + print('Goal has an invalid return status!') navigator.lifecycleShutdown() exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_simple_commander/nav2_simple_commander/example_nav_to_pose.py b/nav2_simple_commander/nav2_simple_commander/example_nav_to_pose.py index f9023696e4c..d7fb850d12b 100644 --- a/nav2_simple_commander/nav2_simple_commander/example_nav_to_pose.py +++ b/nav2_simple_commander/nav2_simple_commander/example_nav_to_pose.py @@ -30,7 +30,7 @@ def main(): # Set our demo's initial pose initial_pose = PoseStamped() - initial_pose.header.frame_id = "map" + initial_pose.header.frame_id = 'map' initial_pose.header.stamp = navigator.get_clock().now().to_msg() initial_pose.pose.position.x = 3.45 initial_pose.pose.position.y = 2.15 @@ -56,7 +56,7 @@ def main(): # Go to our demos first goal pose goal_pose = PoseStamped() - goal_pose.header.frame_id = "map" + goal_pose.header.frame_id = 'map' goal_pose.header.stamp = navigator.get_clock().now().to_msg() goal_pose.pose.position.x = -2.0 goal_pose.pose.position.y = -0.5 @@ -80,12 +80,12 @@ def main(): feedback = navigator.getFeedback() if feedback and i % 5 == 0: print( - "Estimated time of arrival: " - + "{0:.0f}".format( + 'Estimated time of arrival: ' + + '{0:.0f}'.format( Duration.from_msg(feedback.estimated_time_remaining).nanoseconds / 1e9 ) - + " seconds." + + ' seconds.' ) # Some navigation timeout to demo cancellation @@ -100,18 +100,18 @@ def main(): # Do something depending on the return code result = navigator.getResult() if result == TaskResult.SUCCEEDED: - print("Goal succeeded!") + print('Goal succeeded!') elif result == TaskResult.CANCELED: - print("Goal was canceled!") + print('Goal was canceled!') elif result == TaskResult.FAILED: - print("Goal failed!") + print('Goal failed!') else: - print("Goal has an invalid return status!") + print('Goal has an invalid return status!') navigator.lifecycleShutdown() exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_simple_commander/nav2_simple_commander/example_waypoint_follower.py b/nav2_simple_commander/nav2_simple_commander/example_waypoint_follower.py index 4bf50ad4627..30444658518 100644 --- a/nav2_simple_commander/nav2_simple_commander/example_waypoint_follower.py +++ b/nav2_simple_commander/nav2_simple_commander/example_waypoint_follower.py @@ -30,7 +30,7 @@ def main(): # Set our demo's initial pose initial_pose = PoseStamped() - initial_pose.header.frame_id = "map" + initial_pose.header.frame_id = 'map' initial_pose.header.stamp = navigator.get_clock().now().to_msg() initial_pose.pose.position.x = 3.45 initial_pose.pose.position.y = 2.15 @@ -57,7 +57,7 @@ def main(): # set our demo's goal poses to follow goal_poses = [] goal_pose1 = PoseStamped() - goal_pose1.header.frame_id = "map" + goal_pose1.header.frame_id = 'map' goal_pose1.header.stamp = navigator.get_clock().now().to_msg() goal_pose1.pose.position.x = 1.5 goal_pose1.pose.position.y = 0.55 @@ -67,7 +67,7 @@ def main(): # additional goals can be appended goal_pose2 = PoseStamped() - goal_pose2.header.frame_id = "map" + goal_pose2.header.frame_id = 'map' goal_pose2.header.stamp = navigator.get_clock().now().to_msg() goal_pose2.pose.position.x = 1.5 goal_pose2.pose.position.y = -3.75 @@ -75,7 +75,7 @@ def main(): goal_pose2.pose.orientation.z = 0.707 goal_poses.append(goal_pose2) goal_pose3 = PoseStamped() - goal_pose3.header.frame_id = "map" + goal_pose3.header.frame_id = 'map' goal_pose3.header.stamp = navigator.get_clock().now().to_msg() goal_pose3.pose.position.x = -3.6 goal_pose3.pose.position.y = -4.75 @@ -102,9 +102,9 @@ def main(): feedback = navigator.getFeedback() if feedback and i % 5 == 0: print( - "Executing current waypoint: " + 'Executing current waypoint: ' + str(feedback.current_waypoint + 1) - + "/" + + '/' + str(len(goal_poses)) ) now = navigator.get_clock().now() @@ -116,7 +116,7 @@ def main(): # Some follow waypoints request change to demo preemption if now - nav_start > Duration(seconds=35.0): goal_pose4 = PoseStamped() - goal_pose4.header.frame_id = "map" + goal_pose4.header.frame_id = 'map' goal_pose4.header.stamp = now.to_msg() goal_pose4.pose.position.x = -5.0 goal_pose4.pose.position.y = -4.75 @@ -129,18 +129,18 @@ def main(): # Do something depending on the return code result = navigator.getResult() if result == TaskResult.SUCCEEDED: - print("Goal succeeded!") + print('Goal succeeded!') elif result == TaskResult.CANCELED: - print("Goal was canceled!") + print('Goal was canceled!') elif result == TaskResult.FAILED: - print("Goal failed!") + print('Goal failed!') else: - print("Goal has an invalid return status!") + print('Goal has an invalid return status!') navigator.lifecycleShutdown() exit(0) -if __name__ == "__main__": +if __name__ == '__main__': main() diff --git a/nav2_simple_commander/nav2_simple_commander/footprint_collision_checker.py b/nav2_simple_commander/nav2_simple_commander/footprint_collision_checker.py index 3d281ecc746..5cf2f81794a 100644 --- a/nav2_simple_commander/nav2_simple_commander/footprint_collision_checker.py +++ b/nav2_simple_commander/nav2_simple_commander/footprint_collision_checker.py @@ -146,7 +146,7 @@ def worldToMapValidated(self, wx: float, wy: float): """ if self.costmap_ is None: raise ValueError( - "Costmap not specified, use setCostmap to specify the costmap first" + 'Costmap not specified, use setCostmap to specify the costmap first' ) return self.costmap_.worldToMapValidated(wx, wy) @@ -166,7 +166,7 @@ def pointCost(self, x: int, y: int): """ if self.costmap_ is None: raise ValueError( - "Costmap not specified, use setCostmap to specify the costmap first" + 'Costmap not specified, use setCostmap to specify the costmap first' ) return self.costmap_.getCostXY(x, y) diff --git a/nav2_simple_commander/nav2_simple_commander/line_iterator.py b/nav2_simple_commander/nav2_simple_commander/line_iterator.py index 27d8af07be9..9f6c092570a 100644 --- a/nav2_simple_commander/nav2_simple_commander/line_iterator.py +++ b/nav2_simple_commander/nav2_simple_commander/line_iterator.py @@ -50,22 +50,22 @@ def __init__(self, x0, y0, x1, y1, step_size=1.0): """ if type(x0) not in [int, float]: - raise TypeError("x0 must be a number (int or float)") + raise TypeError('x0 must be a number (int or float)') if type(y0) not in [int, float]: - raise TypeError("y0 must be a number (int or float)") + raise TypeError('y0 must be a number (int or float)') if type(x1) not in [int, float]: - raise TypeError("x1 must be a number (int or float)") + raise TypeError('x1 must be a number (int or float)') if type(y1) not in [int, float]: - raise TypeError("y1 must be a number (int or float)") + raise TypeError('y1 must be a number (int or float)') if type(step_size) not in [int, float]: - raise TypeError("step_size must be a number (int or float)") + raise TypeError('step_size must be a number (int or float)') if step_size <= 0: - raise ValueError("step_size must be a positive number") + raise ValueError('step_size must be a positive number') self.x0_ = x0 self.y0_ = y0 @@ -88,7 +88,7 @@ def __init__(self, x0, y0, x1, y1, step_size=1.0): else: self.valid_ = False raise ValueError( - "Line has zero length (All 4 points have same coordinates)" + 'Line has zero length (All 4 points have same coordinates)' ) def isValid(self): diff --git a/nav2_simple_commander/nav2_simple_commander/robot_navigator.py b/nav2_simple_commander/nav2_simple_commander/robot_navigator.py index 61956f7d563..a8ded664cd5 100644 --- a/nav2_simple_commander/nav2_simple_commander/robot_navigator.py +++ b/nav2_simple_commander/nav2_simple_commander/robot_navigator.py @@ -51,10 +51,10 @@ class TaskResult(Enum): class BasicNavigator(Node): - def __init__(self, node_name="basic_navigator", namespace=""): + def __init__(self, node_name='basic_navigator', namespace=''): super().__init__(node_name=node_name, namespace=namespace) self.initial_pose = PoseStamped() - self.initial_pose.header.frame_id = "map" + self.initial_pose.header.frame_id = 'map' self.goal_handle = None self.result_future = None self.feedback = None @@ -69,49 +69,49 @@ def __init__(self, node_name="basic_navigator", namespace=""): self.initial_pose_received = False self.nav_through_poses_client = ActionClient( - self, NavigateThroughPoses, "navigate_through_poses" + self, NavigateThroughPoses, 'navigate_through_poses' ) - self.nav_to_pose_client = ActionClient(self, NavigateToPose, "navigate_to_pose") + self.nav_to_pose_client = ActionClient(self, NavigateToPose, 'navigate_to_pose') self.follow_waypoints_client = ActionClient( - self, FollowWaypoints, "follow_waypoints" + self, FollowWaypoints, 'follow_waypoints' ) self.follow_gps_waypoints_client = ActionClient( - self, FollowGPSWaypoints, "follow_gps_waypoints" + self, FollowGPSWaypoints, 'follow_gps_waypoints' ) - self.follow_path_client = ActionClient(self, FollowPath, "follow_path") + self.follow_path_client = ActionClient(self, FollowPath, 'follow_path') self.compute_path_to_pose_client = ActionClient( - self, ComputePathToPose, "compute_path_to_pose" + self, ComputePathToPose, 'compute_path_to_pose' ) self.compute_path_through_poses_client = ActionClient( - self, ComputePathThroughPoses, "compute_path_through_poses" + self, ComputePathThroughPoses, 'compute_path_through_poses' ) - self.smoother_client = ActionClient(self, SmoothPath, "smooth_path") - self.spin_client = ActionClient(self, Spin, "spin") - self.backup_client = ActionClient(self, BackUp, "backup") + self.smoother_client = ActionClient(self, SmoothPath, 'smooth_path') + self.spin_client = ActionClient(self, Spin, 'spin') + self.backup_client = ActionClient(self, BackUp, 'backup') self.assisted_teleop_client = ActionClient( - self, AssistedTeleop, "assisted_teleop" + self, AssistedTeleop, 'assisted_teleop' ) self.localization_pose_sub = self.create_subscription( PoseWithCovarianceStamped, - "amcl_pose", + 'amcl_pose', self._amclPoseCallback, amcl_pose_qos, ) self.initial_pose_pub = self.create_publisher( - PoseWithCovarianceStamped, "initialpose", 10 + PoseWithCovarianceStamped, 'initialpose', 10 ) - self.change_maps_srv = self.create_client(LoadMap, "map_server/load_map") + self.change_maps_srv = self.create_client(LoadMap, 'map_server/load_map') self.clear_costmap_global_srv = self.create_client( - ClearEntireCostmap, "global_costmap/clear_entirely_global_costmap" + ClearEntireCostmap, 'global_costmap/clear_entirely_global_costmap' ) self.clear_costmap_local_srv = self.create_client( - ClearEntireCostmap, "local_costmap/clear_entirely_local_costmap" + ClearEntireCostmap, 'local_costmap/clear_entirely_local_costmap' ) self.get_costmap_global_srv = self.create_client( - GetCostmap, "global_costmap/get_costmap" + GetCostmap, 'global_costmap/get_costmap' ) self.get_costmap_local_srv = self.create_client( - GetCostmap, "local_costmap/get_costmap" + GetCostmap, 'local_costmap/get_costmap' ) def destroyNode(self): @@ -135,7 +135,7 @@ def setInitialPose(self, initial_pose): self.initial_pose = initial_pose self._setInitialPose() - def goThroughPoses(self, poses, behavior_tree=""): + def goThroughPoses(self, poses, behavior_tree=''): """Send a `NavThroughPoses` action request.""" self.debug("Waiting for 'NavigateThroughPoses' action server") while not self.nav_through_poses_client.wait_for_server(timeout_sec=1.0): @@ -145,7 +145,7 @@ def goThroughPoses(self, poses, behavior_tree=""): goal_msg.poses = poses goal_msg.behavior_tree = behavior_tree - self.info(f"Navigating with {len(goal_msg.poses)} goals....") + self.info(f'Navigating with {len(goal_msg.poses)} goals....') send_goal_future = self.nav_through_poses_client.send_goal_async( goal_msg, self._feedbackCallback ) @@ -153,13 +153,13 @@ def goThroughPoses(self, poses, behavior_tree=""): self.goal_handle = send_goal_future.result() if not self.goal_handle.accepted: - self.error(f"Goal with {len(poses)} poses was rejected!") + self.error(f'Goal with {len(poses)} poses was rejected!') return False self.result_future = self.goal_handle.get_result_async() return True - def goToPose(self, pose, behavior_tree=""): + def goToPose(self, pose, behavior_tree=''): """Send a `NavToPose` action request.""" self.debug("Waiting for 'NavigateToPose' action server") while not self.nav_to_pose_client.wait_for_server(timeout_sec=1.0): @@ -170,11 +170,11 @@ def goToPose(self, pose, behavior_tree=""): goal_msg.behavior_tree = behavior_tree self.info( - "Navigating to goal: " + 'Navigating to goal: ' + str(pose.pose.position.x) - + " " + + ' ' + str(pose.pose.position.y) - + "..." + + '...' ) send_goal_future = self.nav_to_pose_client.send_goal_async( goal_msg, self._feedbackCallback @@ -184,11 +184,11 @@ def goToPose(self, pose, behavior_tree=""): if not self.goal_handle.accepted: self.error( - "Goal to " + 'Goal to ' + str(pose.pose.position.x) - + " " + + ' ' + str(pose.pose.position.y) - + " was rejected!" + + ' was rejected!' ) return False @@ -204,7 +204,7 @@ def followWaypoints(self, poses): goal_msg = FollowWaypoints.Goal() goal_msg.poses = poses - self.info(f"Following {len(goal_msg.poses)} goals....") + self.info(f'Following {len(goal_msg.poses)} goals....') send_goal_future = self.follow_waypoints_client.send_goal_async( goal_msg, self._feedbackCallback ) @@ -212,7 +212,7 @@ def followWaypoints(self, poses): self.goal_handle = send_goal_future.result() if not self.goal_handle.accepted: - self.error(f"Following {len(poses)} waypoints request was rejected!") + self.error(f'Following {len(poses)} waypoints request was rejected!') return False self.result_future = self.goal_handle.get_result_async() @@ -227,7 +227,7 @@ def followGpsWaypoints(self, gps_poses): goal_msg = FollowGPSWaypoints.Goal() goal_msg.gps_poses = gps_poses - self.info(f"Following {len(goal_msg.gps_poses)} gps goals....") + self.info(f'Following {len(goal_msg.gps_poses)} gps goals....') send_goal_future = self.follow_gps_waypoints_client.send_goal_async( goal_msg, self._feedbackCallback ) @@ -236,7 +236,7 @@ def followGpsWaypoints(self, gps_poses): if not self.goal_handle.accepted: self.error( - f"Following {len(gps_poses)} gps waypoints request was rejected!" + f'Following {len(gps_poses)} gps waypoints request was rejected!' ) return False @@ -251,7 +251,7 @@ def spin(self, spin_dist=1.57, time_allowance=10): goal_msg.target_yaw = spin_dist goal_msg.time_allowance = Duration(sec=time_allowance) - self.info(f"Spinning to angle {goal_msg.target_yaw}....") + self.info(f'Spinning to angle {goal_msg.target_yaw}....') send_goal_future = self.spin_client.send_goal_async( goal_msg, self._feedbackCallback ) @@ -259,7 +259,7 @@ def spin(self, spin_dist=1.57, time_allowance=10): self.goal_handle = send_goal_future.result() if not self.goal_handle.accepted: - self.error("Spin request was rejected!") + self.error('Spin request was rejected!') return False self.result_future = self.goal_handle.get_result_async() @@ -274,7 +274,7 @@ def backup(self, backup_dist=0.15, backup_speed=0.025, time_allowance=10): goal_msg.speed = backup_speed goal_msg.time_allowance = Duration(sec=time_allowance) - self.info(f"Backing up {goal_msg.target.x} m at {goal_msg.speed} m/s....") + self.info(f'Backing up {goal_msg.target.x} m at {goal_msg.speed} m/s....') send_goal_future = self.backup_client.send_goal_async( goal_msg, self._feedbackCallback ) @@ -282,7 +282,7 @@ def backup(self, backup_dist=0.15, backup_speed=0.025, time_allowance=10): self.goal_handle = send_goal_future.result() if not self.goal_handle.accepted: - self.error("Backup request was rejected!") + self.error('Backup request was rejected!') return False self.result_future = self.goal_handle.get_result_async() @@ -303,13 +303,13 @@ def assistedTeleop(self, time_allowance=30): self.goal_handle = send_goal_future.result() if not self.goal_handle.accepted: - self.error("Assisted Teleop request was rejected!") + self.error('Assisted Teleop request was rejected!') return False self.result_future = self.goal_handle.get_result_async() return True - def followPath(self, path, controller_id="", goal_checker_id=""): + def followPath(self, path, controller_id='', goal_checker_id=''): """Send a `FollowPath` action request.""" self.debug("Waiting for 'FollowPath' action server") while not self.follow_path_client.wait_for_server(timeout_sec=1.0): @@ -320,7 +320,7 @@ def followPath(self, path, controller_id="", goal_checker_id=""): goal_msg.controller_id = controller_id goal_msg.goal_checker_id = goal_checker_id - self.info("Executing path...") + self.info('Executing path...') send_goal_future = self.follow_path_client.send_goal_async( goal_msg, self._feedbackCallback ) @@ -328,7 +328,7 @@ def followPath(self, path, controller_id="", goal_checker_id=""): self.goal_handle = send_goal_future.result() if not self.goal_handle.accepted: - self.error("Follow path was rejected!") + self.error('Follow path was rejected!') return False self.result_future = self.goal_handle.get_result_async() @@ -336,7 +336,7 @@ def followPath(self, path, controller_id="", goal_checker_id=""): def cancelTask(self): """Cancel pending task request of any type.""" - self.info("Canceling current task.") + self.info('Canceling current task.') if self.result_future: future = self.goal_handle.cancel_goal_async() rclpy.spin_until_future_complete(self, future) @@ -351,13 +351,13 @@ def isTaskComplete(self): if self.result_future.result(): self.status = self.result_future.result().status if self.status != GoalStatus.STATUS_SUCCEEDED: - self.debug(f"Task with failed with status code: {self.status}") + self.debug(f'Task with failed with status code: {self.status}') return True else: # Timed out, still processing, not complete yet return False - self.debug("Task succeeded!") + self.debug('Task succeeded!') return True def getFeedback(self): @@ -375,17 +375,17 @@ def getResult(self): else: return TaskResult.UNKNOWN - def waitUntilNav2Active(self, navigator="bt_navigator", localizer="amcl"): + def waitUntilNav2Active(self, navigator='bt_navigator', localizer='amcl'): """Block until the full navigation system is up and running.""" - if localizer != "robot_localization": # non-lifecycle node + if localizer != 'robot_localization': # non-lifecycle node self._waitForNodeToActivate(localizer) - if localizer == "amcl": + if localizer == 'amcl': self._waitForInitialPose() self._waitForNodeToActivate(navigator) - self.info("Nav2 is ready for use!") + self.info('Nav2 is ready for use!') return - def _getPathImpl(self, start, goal, planner_id="", use_start=False): + def _getPathImpl(self, start, goal, planner_id='', use_start=False): """ Send a `ComputePathToPose` action request. @@ -401,13 +401,13 @@ def _getPathImpl(self, start, goal, planner_id="", use_start=False): goal_msg.planner_id = planner_id goal_msg.use_start = use_start - self.info("Getting path...") + self.info('Getting path...') send_goal_future = self.compute_path_to_pose_client.send_goal_async(goal_msg) rclpy.spin_until_future_complete(self, send_goal_future) self.goal_handle = send_goal_future.result() if not self.goal_handle.accepted: - self.error("Get path was rejected!") + self.error('Get path was rejected!') return None self.result_future = self.goal_handle.get_result_async() @@ -416,12 +416,12 @@ def _getPathImpl(self, start, goal, planner_id="", use_start=False): return self.result_future.result().result - def getPath(self, start, goal, planner_id="", use_start=False): + def getPath(self, start, goal, planner_id='', use_start=False): """Send a `ComputePathToPose` action request.""" rtn = self._getPathImpl(start, goal, planner_id, use_start) if self.status != GoalStatus.STATUS_SUCCEEDED: - self.warn(f"Getting path failed with status code: {self.status}") + self.warn(f'Getting path failed with status code: {self.status}') return None if not rtn: @@ -429,7 +429,7 @@ def getPath(self, start, goal, planner_id="", use_start=False): else: return rtn.path - def _getPathThroughPosesImpl(self, start, goals, planner_id="", use_start=False): + def _getPathThroughPosesImpl(self, start, goals, planner_id='', use_start=False): """ Send a `ComputePathThroughPoses` action request. @@ -449,7 +449,7 @@ def _getPathThroughPosesImpl(self, start, goals, planner_id="", use_start=False) goal_msg.planner_id = planner_id goal_msg.use_start = use_start - self.info("Getting path...") + self.info('Getting path...') send_goal_future = self.compute_path_through_poses_client.send_goal_async( goal_msg ) @@ -457,7 +457,7 @@ def _getPathThroughPosesImpl(self, start, goals, planner_id="", use_start=False) self.goal_handle = send_goal_future.result() if not self.goal_handle.accepted: - self.error("Get path was rejected!") + self.error('Get path was rejected!') return None self.result_future = self.goal_handle.get_result_async() @@ -466,12 +466,12 @@ def _getPathThroughPosesImpl(self, start, goals, planner_id="", use_start=False) return self.result_future.result().result - def getPathThroughPoses(self, start, goals, planner_id="", use_start=False): + def getPathThroughPoses(self, start, goals, planner_id='', use_start=False): """Send a `ComputePathThroughPoses` action request.""" rtn = self.__getPathThroughPosesImpl(start, goals, planner_id, use_start) if self.status != GoalStatus.STATUS_SUCCEEDED: - self.warn(f"Getting path failed with status code: {self.status}") + self.warn(f'Getting path failed with status code: {self.status}') return None if not rtn: @@ -480,7 +480,7 @@ def getPathThroughPoses(self, start, goals, planner_id="", use_start=False): return rtn.path def _smoothPathImpl( - self, path, smoother_id="", max_duration=2.0, check_for_collision=False + self, path, smoother_id='', max_duration=2.0, check_for_collision=False ): """ Send a `SmoothPath` action request. @@ -497,13 +497,13 @@ def _smoothPathImpl( goal_msg.smoother_id = smoother_id goal_msg.check_for_collisions = check_for_collision - self.info("Smoothing path...") + self.info('Smoothing path...') send_goal_future = self.smoother_client.send_goal_async(goal_msg) rclpy.spin_until_future_complete(self, send_goal_future) self.goal_handle = send_goal_future.result() if not self.goal_handle.accepted: - self.error("Smooth path was rejected!") + self.error('Smooth path was rejected!') return None self.result_future = self.goal_handle.get_result_async() @@ -513,13 +513,13 @@ def _smoothPathImpl( return self.result_future.result().result def smoothPath( - self, path, smoother_id="", max_duration=2.0, check_for_collision=False + self, path, smoother_id='', max_duration=2.0, check_for_collision=False ): """Send a `SmoothPath` action request.""" rtn = self._smoothPathImpl(path, smoother_id, max_duration, check_for_collision) if self.status != GoalStatus.STATUS_SUCCEEDED: - self.warn(f"Getting path failed with status code: {self.status}") + self.warn(f'Getting path failed with status code: {self.status}') return None if not rtn: @@ -530,16 +530,16 @@ def smoothPath( def changeMap(self, map_filepath): """Change the current static map in the map server.""" while not self.change_maps_srv.wait_for_service(timeout_sec=1.0): - self.info("change map service not available, waiting...") + self.info('change map service not available, waiting...') req = LoadMap.Request() req.map_url = map_filepath future = self.change_maps_srv.call_async(req) rclpy.spin_until_future_complete(self, future) status = future.result().result if status != LoadMap.Response().RESULT_SUCCESS: - self.error("Change map request failed!") + self.error('Change map request failed!') else: - self.info("Change map request was successful!") + self.info('Change map request was successful!') return def clearAllCostmaps(self): @@ -551,7 +551,7 @@ def clearAllCostmaps(self): def clearLocalCostmap(self): """Clear local costmap.""" while not self.clear_costmap_local_srv.wait_for_service(timeout_sec=1.0): - self.info("Clear local costmaps service not available, waiting...") + self.info('Clear local costmaps service not available, waiting...') req = ClearEntireCostmap.Request() future = self.clear_costmap_local_srv.call_async(req) rclpy.spin_until_future_complete(self, future) @@ -560,7 +560,7 @@ def clearLocalCostmap(self): def clearGlobalCostmap(self): """Clear global costmap.""" while not self.clear_costmap_global_srv.wait_for_service(timeout_sec=1.0): - self.info("Clear global costmaps service not available, waiting...") + self.info('Clear global costmaps service not available, waiting...') req = ClearEntireCostmap.Request() future = self.clear_costmap_global_srv.call_async(req) rclpy.spin_until_future_complete(self, future) @@ -569,7 +569,7 @@ def clearGlobalCostmap(self): def getGlobalCostmap(self): """Get the global costmap.""" while not self.get_costmap_global_srv.wait_for_service(timeout_sec=1.0): - self.info("Get global costmaps service not available, waiting...") + self.info('Get global costmaps service not available, waiting...') req = GetCostmap.Request() future = self.get_costmap_global_srv.call_async(req) rclpy.spin_until_future_complete(self, future) @@ -578,7 +578,7 @@ def getGlobalCostmap(self): def getLocalCostmap(self): """Get the local costmap.""" while not self.get_costmap_local_srv.wait_for_service(timeout_sec=1.0): - self.info("Get local costmaps service not available, waiting...") + self.info('Get local costmaps service not available, waiting...') req = GetCostmap.Request() future = self.get_costmap_local_srv.call_async(req) rclpy.spin_until_future_complete(self, future) @@ -586,13 +586,13 @@ def getLocalCostmap(self): def lifecycleStartup(self): """Startup nav2 lifecycle system.""" - self.info("Starting up lifecycle nodes based on lifecycle_manager.") + self.info('Starting up lifecycle nodes based on lifecycle_manager.') for srv_name, srv_type in self.get_service_names_and_types(): - if srv_type[0] == "nav2_msgs/srv/ManageLifecycleNodes": - self.info(f"Starting up {srv_name}") + if srv_type[0] == 'nav2_msgs/srv/ManageLifecycleNodes': + self.info(f'Starting up {srv_name}') mgr_client = self.create_client(ManageLifecycleNodes, srv_name) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info(f"{srv_name} service not available, waiting...") + self.info(f'{srv_name} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().STARTUP future = mgr_client.call_async(req) @@ -605,18 +605,18 @@ def lifecycleStartup(self): self._waitForInitialPose() else: break - self.info("Nav2 is ready for use!") + self.info('Nav2 is ready for use!') return def lifecycleShutdown(self): """Shutdown nav2 lifecycle system.""" - self.info("Shutting down lifecycle nodes based on lifecycle_manager.") + self.info('Shutting down lifecycle nodes based on lifecycle_manager.') for srv_name, srv_type in self.get_service_names_and_types(): - if srv_type[0] == "nav2_msgs/srv/ManageLifecycleNodes": - self.info(f"Shutting down {srv_name}") + if srv_type[0] == 'nav2_msgs/srv/ManageLifecycleNodes': + self.info(f'Shutting down {srv_name}') mgr_client = self.create_client(ManageLifecycleNodes, srv_name) while not mgr_client.wait_for_service(timeout_sec=1.0): - self.info(f"{srv_name} service not available, waiting...") + self.info(f'{srv_name} service not available, waiting...') req = ManageLifecycleNodes.Request() req.command = ManageLifecycleNodes.Request().SHUTDOWN future = mgr_client.call_async(req) @@ -626,39 +626,39 @@ def lifecycleShutdown(self): def _waitForNodeToActivate(self, node_name): # Waits for the node within the tester namespace to become active - self.debug(f"Waiting for {node_name} to become active..") - node_service = f"{node_name}/get_state" + self.debug(f'Waiting for {node_name} to become active..') + node_service = f'{node_name}/get_state' state_client = self.create_client(GetState, node_service) while not state_client.wait_for_service(timeout_sec=1.0): - self.info(f"{node_service} service not available, waiting...") + self.info(f'{node_service} service not available, waiting...') req = GetState.Request() - state = "unknown" - while state != "active": - self.debug(f"Getting {node_name} state...") + state = 'unknown' + while state != 'active': + self.debug(f'Getting {node_name} state...') future = state_client.call_async(req) rclpy.spin_until_future_complete(self, future) if future.result() is not None: state = future.result().current_state.label - self.debug(f"Result of get_state: {state}") + self.debug(f'Result of get_state: {state}') time.sleep(2) return def _waitForInitialPose(self): while not self.initial_pose_received: - self.info("Setting initial pose") + self.info('Setting initial pose') self._setInitialPose() - self.info("Waiting for amcl_pose to be received") + self.info('Waiting for amcl_pose to be received') rclpy.spin_once(self, timeout_sec=1.0) return def _amclPoseCallback(self, msg): - self.debug("Received amcl pose") + self.debug('Received amcl pose') self.initial_pose_received = True return def _feedbackCallback(self, msg): - self.debug("Received action feedback message") + self.debug('Received action feedback message') self.feedback = msg.feedback return @@ -667,7 +667,7 @@ def _setInitialPose(self): msg.pose.pose = self.initial_pose.pose msg.header.frame_id = self.initial_pose.header.frame_id msg.header.stamp = self.initial_pose.header.stamp - self.info("Publishing Initial Pose") + self.info('Publishing Initial Pose') self.initial_pose_pub.publish(msg) return diff --git a/nav2_simple_commander/setup.py b/nav2_simple_commander/setup.py index 36da09385c1..4b49f89a450 100644 --- a/nav2_simple_commander/setup.py +++ b/nav2_simple_commander/setup.py @@ -4,35 +4,35 @@ from setuptools import setup -package_name = "nav2_simple_commander" +package_name = 'nav2_simple_commander' setup( name=package_name, - version="1.0.0", + version='1.0.0', packages=[package_name], data_files=[ - ("share/ament_index/resource_index/packages", ["resource/" + package_name]), - ("share/" + package_name, ["package.xml"]), - (os.path.join("share", package_name), glob("launch/*")), + ('share/ament_index/resource_index/packages', ['resource/' + package_name]), + ('share/' + package_name, ['package.xml']), + (os.path.join('share', package_name), glob('launch/*')), ], - install_requires=["setuptools"], + install_requires=['setuptools'], zip_safe=True, - maintainer="steve", - maintainer_email="stevenmacenski@gmail.com", - description="An importable library for writing mobile robot applications in python3", - license="Apache-2.0", - tests_require=["pytest"], + maintainer='steve', + maintainer_email='stevenmacenski@gmail.com', + description='An importable library for writing mobile robot applications in python3', + license='Apache-2.0', + tests_require=['pytest'], entry_points={ - "console_scripts": [ - "example_nav_to_pose = nav2_simple_commander.example_nav_to_pose:main", - "example_nav_through_poses = nav2_simple_commander.example_nav_through_poses:main", - "example_waypoint_follower = nav2_simple_commander.example_waypoint_follower:main", - "example_follow_path = nav2_simple_commander.example_follow_path:main", - "demo_picking = nav2_simple_commander.demo_picking:main", - "demo_inspection = nav2_simple_commander.demo_inspection:main", - "demo_security = nav2_simple_commander.demo_security:main", - "demo_recoveries = nav2_simple_commander.demo_recoveries:main", - "example_assisted_teleop = nav2_simple_commander.example_assisted_teleop:main", + 'console_scripts': [ + 'example_nav_to_pose = nav2_simple_commander.example_nav_to_pose:main', + 'example_nav_through_poses = nav2_simple_commander.example_nav_through_poses:main', + 'example_waypoint_follower = nav2_simple_commander.example_waypoint_follower:main', + 'example_follow_path = nav2_simple_commander.example_follow_path:main', + 'demo_picking = nav2_simple_commander.demo_picking:main', + 'demo_inspection = nav2_simple_commander.demo_inspection:main', + 'demo_security = nav2_simple_commander.demo_security:main', + 'demo_recoveries = nav2_simple_commander.demo_recoveries:main', + 'example_assisted_teleop = nav2_simple_commander.example_assisted_teleop:main', ], }, ) diff --git a/nav2_simple_commander/test/test_copyright.py b/nav2_simple_commander/test/test_copyright.py index f46f861db17..cc8ff03f79a 100644 --- a/nav2_simple_commander/test/test_copyright.py +++ b/nav2_simple_commander/test/test_copyright.py @@ -19,5 +19,5 @@ @pytest.mark.copyright @pytest.mark.linter def test_copyright(): - rc = main(argv=[".", "test"]) - assert rc == 0, "Found errors" + rc = main(argv=['.', 'test']) + assert rc == 0, 'Found errors' diff --git a/nav2_simple_commander/test/test_flake8.py b/nav2_simple_commander/test/test_flake8.py index ee79f31ac2f..26030113cce 100644 --- a/nav2_simple_commander/test/test_flake8.py +++ b/nav2_simple_commander/test/test_flake8.py @@ -20,6 +20,6 @@ @pytest.mark.linter def test_flake8(): rc, errors = main_with_errors(argv=[]) - assert rc == 0, "Found %d code style errors / warnings:\n" % len( + assert rc == 0, 'Found %d code style errors / warnings:\n' % len( errors - ) + "\n".join(errors) + ) + '\n'.join(errors) diff --git a/nav2_simple_commander/test/test_footprint_collision_checker.py b/nav2_simple_commander/test/test_footprint_collision_checker.py index bf441d2399c..070a7bc6e4b 100644 --- a/nav2_simple_commander/test/test_footprint_collision_checker.py +++ b/nav2_simple_commander/test/test_footprint_collision_checker.py @@ -147,5 +147,5 @@ def test_footprintCost(self): self.assertEqual(fcc_.footprintCost(footprint), LETHAL_OBSTACLE) -if __name__ == "__main__": +if __name__ == '__main__': unittest.main() diff --git a/nav2_simple_commander/test/test_line_iterator.py b/nav2_simple_commander/test/test_line_iterator.py index 07258a67394..1360c183e7d 100644 --- a/nav2_simple_commander/test/test_line_iterator.py +++ b/nav2_simple_commander/test/test_line_iterator.py @@ -21,7 +21,7 @@ class TestLineIterator(unittest.TestCase): def test_type_error(self): # Test if a type error raised when passing invalid arguements types - self.assertRaises(TypeError, LineIterator, 0, 0, "10", 10, "1") + self.assertRaises(TypeError, LineIterator, 0, 0, '10', 10, '1') def test_value_error(self): # Test if a value error raised when passing negative or zero step_size @@ -103,5 +103,5 @@ def test_clamp(self): lt.advance() -if __name__ == "__main__": +if __name__ == '__main__': unittest.main() diff --git a/nav2_simple_commander/test/test_pep257.py b/nav2_simple_commander/test/test_pep257.py index a2c3deb8eb3..b234a3840f4 100644 --- a/nav2_simple_commander/test/test_pep257.py +++ b/nav2_simple_commander/test/test_pep257.py @@ -19,5 +19,5 @@ @pytest.mark.linter @pytest.mark.pep257 def test_pep257(): - rc = main(argv=[".", "test"]) - assert rc == 0, "Found code style errors / warnings" + rc = main(argv=['.', 'test']) + assert rc == 0, 'Found code style errors / warnings' From e584911bf5f87fcbbfe1ec8a3db6f53b2678a989 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 21:40:29 +0100 Subject: [PATCH 21/24] Fix flake8-quotes linter for nav2_lifecycle --- .../test/launch_bond_test.py | 20 ++++++++--------- .../test/launch_lifecycle_test.py | 22 +++++++++---------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/nav2_lifecycle_manager/test/launch_bond_test.py b/nav2_lifecycle_manager/test/launch_bond_test.py index e3589583ab7..728a061001a 100755 --- a/nav2_lifecycle_manager/test/launch_bond_test.py +++ b/nav2_lifecycle_manager/test/launch_bond_test.py @@ -27,14 +27,14 @@ def generate_launch_description(): return LaunchDescription( [ Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager_test", - output="screen", + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager_test', + output='screen', parameters=[ - {"use_sim_time": False}, - {"autostart": False}, - {"node_names": ["bond_tester"]}, + {'use_sim_time': False}, + {'autostart': False}, + {'node_names': ['bond_tester']}, ], ), ] @@ -44,10 +44,10 @@ def generate_launch_description(): def main(argv=sys.argv[1:]): ld = generate_launch_description() - testExecutable = os.getenv("TEST_EXECUTABLE") + testExecutable = os.getenv('TEST_EXECUTABLE') test1_action = ExecuteProcess( - cmd=[testExecutable], name="test_bond_gtest", output="screen" + cmd=[testExecutable], name='test_bond_gtest', output='screen' ) lts = LaunchTestService() @@ -57,5 +57,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_lifecycle_manager/test/launch_lifecycle_test.py b/nav2_lifecycle_manager/test/launch_lifecycle_test.py index 6f575b5bd49..06582361858 100755 --- a/nav2_lifecycle_manager/test/launch_lifecycle_test.py +++ b/nav2_lifecycle_manager/test/launch_lifecycle_test.py @@ -27,15 +27,15 @@ def generate_launch_description(): return LaunchDescription( [ Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager_test", - output="screen", + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager_test', + output='screen', parameters=[ - {"use_sim_time": False}, - {"autostart": False}, - {"bond_timeout": 0.0}, - {"node_names": ["lifecycle_node_test"]}, + {'use_sim_time': False}, + {'autostart': False}, + {'bond_timeout': 0.0}, + {'node_names': ['lifecycle_node_test']}, ], ), ] @@ -45,10 +45,10 @@ def generate_launch_description(): def main(argv=sys.argv[1:]): ld = generate_launch_description() - testExecutable = os.getenv("TEST_EXECUTABLE") + testExecutable = os.getenv('TEST_EXECUTABLE') test1_action = ExecuteProcess( - cmd=[testExecutable], name="test_lifecycle_node_gtest", output="screen" + cmd=[testExecutable], name='test_lifecycle_node_gtest', output='screen' ) lts = LaunchTestService() @@ -58,5 +58,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) From cc213f4b82af1f480fbe27c3ca2a6b64e80ab69e Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 21:41:09 +0100 Subject: [PATCH 22/24] Fix flake8-quotes linter for nav2_costmap2d --- .../test/integration/costmap_tests_launch.py | 34 +++++++++---------- .../costmap_map_server.launch.py | 12 +++---- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/nav2_costmap_2d/test/integration/costmap_tests_launch.py b/nav2_costmap_2d/test/integration/costmap_tests_launch.py index e399378b8a2..692c4f9fcec 100755 --- a/nav2_costmap_2d/test/integration/costmap_tests_launch.py +++ b/nav2_costmap_2d/test/integration/costmap_tests_launch.py @@ -28,30 +28,30 @@ def main(argv=sys.argv[1:]): launchFile = os.path.join( - os.getenv("TEST_LAUNCH_DIR"), "costmap_map_server.launch.py" + os.getenv('TEST_LAUNCH_DIR'), 'costmap_map_server.launch.py' ) - testExecutable = os.getenv("TEST_EXECUTABLE") + testExecutable = os.getenv('TEST_EXECUTABLE') map_to_odom = launch_ros.actions.Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "map", "odom"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'map', 'odom'], ) odom_to_base_link = launch_ros.actions.Node( - package="tf2_ros", - executable="static_transform_publisher", - output="screen", - arguments=["0", "0", "0", "0", "0", "0", "odom", "base_link"], + package='tf2_ros', + executable='static_transform_publisher', + output='screen', + arguments=['0', '0', '0', '0', '0', '0', 'odom', 'base_link'], ) lifecycle_manager = launch_ros.actions.Node( - package="nav2_lifecycle_manager", - executable="lifecycle_manager", - name="lifecycle_manager", - output="screen", - parameters=[{"node_names": ["map_server"]}, {"autostart": True}], + package='nav2_lifecycle_manager', + executable='lifecycle_manager', + name='lifecycle_manager', + output='screen', + parameters=[{'node_names': ['map_server']}, {'autostart': True}], ) ld = LaunchDescription( @@ -64,7 +64,7 @@ def main(argv=sys.argv[1:]): ) test1_action = ExecuteProcess( - cmd=[testExecutable], name="costmap_tests", output="screen" + cmd=[testExecutable], name='costmap_tests', output='screen' ) lts = LaunchTestService() @@ -74,5 +74,5 @@ def main(argv=sys.argv[1:]): return lts.run(ls) -if __name__ == "__main__": +if __name__ == '__main__': sys.exit(main()) diff --git a/nav2_costmap_2d/test/test_launch_files/costmap_map_server.launch.py b/nav2_costmap_2d/test/test_launch_files/costmap_map_server.launch.py index eee156440bf..622d55e0745 100644 --- a/nav2_costmap_2d/test/test_launch_files/costmap_map_server.launch.py +++ b/nav2_costmap_2d/test/test_launch_files/costmap_map_server.launch.py @@ -21,15 +21,15 @@ def generate_launch_description(): - mapFile = os.getenv("TEST_MAP") + mapFile = os.getenv('TEST_MAP') return LaunchDescription( [ launch_ros.actions.Node( - package="nav2_map_server", - executable="map_server", - name="map_server", - output="screen", - parameters=[{"yaml_filename": mapFile}], + package='nav2_map_server', + executable='map_server', + name='map_server', + output='screen', + parameters=[{'yaml_filename': mapFile}], ) ] ) From 66502df7c4c29a2250e5d00e28c740d7ef3202a0 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 21:44:00 +0100 Subject: [PATCH 23/24] Fix flake8-quotes linter for nav2_smac_planner --- .../generate_motion_primitives.py | 74 +++++++++---------- .../lattice_primitives/lattice_generator.py | 18 ++--- .../tests/test_lattice_generator.py | 14 ++-- .../tests/test_trajectory_generator.py | 4 +- .../tests/trajectory_visualizer.py | 46 ++++++------ .../trajectory_generator.py | 24 +++--- 6 files changed, 90 insertions(+), 90 deletions(-) diff --git a/nav2_smac_planner/lattice_primitives/generate_motion_primitives.py b/nav2_smac_planner/lattice_primitives/generate_motion_primitives.py index 7806c9aeb39..d19ef987ece 100644 --- a/nav2_smac_planner/lattice_primitives/generate_motion_primitives.py +++ b/nav2_smac_planner/lattice_primitives/generate_motion_primitives.py @@ -41,26 +41,26 @@ def handle_arg_parsing(): """ parser = argparse.ArgumentParser( - description="Generate motionprimitives " "for Nav2's State " "Lattice Planner" + description="Generate motionprimitives for Nav2's State Lattice Planner" ) parser.add_argument( - "--config", + '--config', type=Path, - default="./config.json", - help="The config file containing the " "parameters to be used", + default='./config.json', + help='The config file containing the ' 'parameters to be used', ) parser.add_argument( - "--output", + '--output', type=Path, - default="./output.json", - help="The output file containing the " "trajectory data", + default='./output.json', + help='The output file containing the ' 'trajectory data', ) parser.add_argument( - "--visualizations", + '--visualizations', type=Path, - default="./visualizations", - help="The output folder where the " - "visualizations of the trajectories will be saved", + default='./visualizations', + help='The output folder where the ' + 'visualizations of the trajectories will be saved', ) return parser.parse_args() @@ -124,21 +124,21 @@ def create_header(config: dict, minimal_set_trajectories: dict) -> dict: """ header_dict = { - "version": constants.VERSION, - "date_generated": datetime.today().strftime("%Y-%m-%d"), - "lattice_metadata": {}, - "primitives": [], + 'version': constants.VERSION, + 'date_generated': datetime.today().strftime('%Y-%m-%d'), + 'lattice_metadata': {}, + 'primitives': [], } for key, value in config.items(): - header_dict["lattice_metadata"][key] = value + header_dict['lattice_metadata'][key] = value heading_angles = create_heading_angle_list(minimal_set_trajectories) adjusted_heading_angles = [ angle + 2 * np.pi if angle < 0 else angle for angle in heading_angles ] - header_dict["lattice_metadata"]["heading_angles"] = adjusted_heading_angles + header_dict['lattice_metadata']['heading_angles'] = adjusted_heading_angles return header_dict @@ -174,33 +174,33 @@ def write_to_json( ): traj_info = {} - traj_info["trajectory_id"] = idx - traj_info["start_angle_index"] = heading_lookup[ + traj_info['trajectory_id'] = idx + traj_info['start_angle_index'] = heading_lookup[ trajectory.parameters.start_angle ] - traj_info["end_angle_index"] = heading_lookup[ + traj_info['end_angle_index'] = heading_lookup[ trajectory.parameters.end_angle ] - traj_info["left_turn"] = bool(trajectory.parameters.left_turn) - traj_info["trajectory_radius"] = trajectory.parameters.turning_radius - traj_info["trajectory_length"] = round( + traj_info['left_turn'] = bool(trajectory.parameters.left_turn) + traj_info['trajectory_radius'] = trajectory.parameters.turning_radius + traj_info['trajectory_length'] = round( trajectory.parameters.total_length, 5 ) - traj_info["arc_length"] = round(trajectory.parameters.arc_length, 5) - traj_info["straight_length"] = round( + traj_info['arc_length'] = round(trajectory.parameters.arc_length, 5) + traj_info['straight_length'] = round( trajectory.parameters.start_straight_length + trajectory.parameters.end_straight_length, 5, ) - traj_info["poses"] = trajectory.path.to_output_format() + traj_info['poses'] = trajectory.path.to_output_format() - output_dict["primitives"].append(traj_info) + output_dict['primitives'].append(traj_info) idx += 1 - output_dict["lattice_metadata"]["number_of_trajectories"] = idx + output_dict['lattice_metadata']['number_of_trajectories'] = idx - with open(output_path, "w") as output_file: - json.dump(output_dict, output_file, indent="\t") + with open(output_path, 'w') as output_file: + json.dump(output_dict, output_file, indent='\t') def save_visualizations( @@ -223,14 +223,14 @@ def save_visualizations( for start_angle in minimal_set_trajectories.keys(): for trajectory in minimal_set_trajectories[start_angle]: - plt.plot(trajectory.path.xs, trajectory.path.ys, "b") + plt.plot(trajectory.path.xs, trajectory.path.ys, 'b') plt.grid(True) - plt.axis("square") + plt.axis('square') left_x, right_x = plt.xlim() left_y, right_y = plt.ylim() - output_path = visualizations_folder / "all_trajectories.png" + output_path = visualizations_folder / 'all_trajectories.png' plt.savefig(output_path) plt.clf() @@ -242,18 +242,18 @@ def save_visualizations( continue for trajectory in minimal_set_trajectories[start_angle]: - plt.plot(trajectory.path.xs, trajectory.path.ys, "b") + plt.plot(trajectory.path.xs, trajectory.path.ys, 'b') plt.xlim(left_x, right_x) plt.ylim(left_y, right_y) plt.grid(True) - output_path = visualizations_folder / f"{angle_in_deg}.png" + output_path = visualizations_folder / f'{angle_in_deg}.png' plt.savefig(output_path) plt.clf() -if __name__ == "__main__": +if __name__ == '__main__': args = handle_arg_parsing() config = read_config(args.config) @@ -261,7 +261,7 @@ def save_visualizations( start = time.time() lattice_gen = LatticeGenerator(config) minimal_set_trajectories = lattice_gen.run() - print(f"Finished Generating. Took {time.time() - start} seconds") + print(f'Finished Generating. Took {time.time() - start} seconds') write_to_json(args.output, minimal_set_trajectories, config) save_visualizations(args.visualizations, minimal_set_trajectories) diff --git a/nav2_smac_planner/lattice_primitives/lattice_generator.py b/nav2_smac_planner/lattice_primitives/lattice_generator.py index 8892c24321d..185cc0f839f 100644 --- a/nav2_smac_planner/lattice_primitives/lattice_generator.py +++ b/nav2_smac_planner/lattice_primitives/lattice_generator.py @@ -53,13 +53,13 @@ class Flip(Enum): def __init__(self, config: dict): """Init the lattice generator from the user supplied config.""" self.trajectory_generator = TrajectoryGenerator(config) - self.grid_resolution = config["grid_resolution"] - self.turning_radius = config["turning_radius"] - self.stopping_threshold = config["stopping_threshold"] - self.num_of_headings = config["num_of_headings"] - self.headings = self._get_heading_discretization(config["num_of_headings"]) + self.grid_resolution = config['grid_resolution'] + self.turning_radius = config['turning_radius'] + self.stopping_threshold = config['stopping_threshold'] + self.num_of_headings = config['num_of_headings'] + self.headings = self._get_heading_discretization(config['num_of_headings']) - self.motion_model = self.MotionModel[config["motion_model"].upper()] + self.motion_model = self.MotionModel[config['motion_model'].upper()] self.DISTANCE_THRESHOLD = 0.5 * self.grid_resolution self.ROTATION_THRESHOLD = 0.5 * (2 * np.pi / self.num_of_headings) @@ -209,7 +209,7 @@ def _is_minimal_trajectory( # difference. If they are within threshold then this # trajectory can be composed from a previous trajectory for prior_end_pose in prior_end_poses.intersection( - (left_bb, bottom_bb, right_bb, top_bb), objects="raw" + (left_bb, bottom_bb, right_bb, top_bb), objects='raw' ): if ( self._point_to_line_distance(p1, p2, prior_end_pose[:-1]) @@ -369,7 +369,7 @@ def _flip_angle(self, angle: float, flip_type: Flip) -> float: angle_idx - (self.num_of_headings / 2) ) % self.num_of_headings else: - raise Exception(f"Unsupported flip type: {flip_type}") + raise Exception(f'Unsupported flip type: {flip_type}') return self.headings[int(heading_idx)] @@ -566,7 +566,7 @@ def _handle_motion_model(self, spanning_set: dict) -> dict: return omni_spanning_set else: - print("No handling implemented for Motion Model: " + f"{self.motion_model}") + print('No handling implemented for Motion Model: ' + f'{self.motion_model}') raise NotImplementedError def _add_in_place_turns(self, spanning_set: dict) -> dict: diff --git a/nav2_smac_planner/lattice_primitives/tests/test_lattice_generator.py b/nav2_smac_planner/lattice_primitives/tests/test_lattice_generator.py index ca3f06866ac..30a7a24eb2a 100644 --- a/nav2_smac_planner/lattice_primitives/tests/test_lattice_generator.py +++ b/nav2_smac_planner/lattice_primitives/tests/test_lattice_generator.py @@ -17,7 +17,7 @@ from lattice_generator import LatticeGenerator import numpy as np -MOTION_MODEL = "ackermann" +MOTION_MODEL = 'ackermann' TURNING_RADIUS = 0.5 GRID_RESOLUTION = 0.05 STOPPING_THRESHOLD = 5 @@ -29,11 +29,11 @@ class TestLatticeGenerator(unittest.TestCase): def setUp(self) -> None: config = { - "motion_model": MOTION_MODEL, - "turning_radius": TURNING_RADIUS, - "grid_resolution": GRID_RESOLUTION, - "stopping_threshold": STOPPING_THRESHOLD, - "num_of_headings": NUM_OF_HEADINGS, + 'motion_model': MOTION_MODEL, + 'turning_radius': TURNING_RADIUS, + 'grid_resolution': GRID_RESOLUTION, + 'stopping_threshold': STOPPING_THRESHOLD, + 'num_of_headings': NUM_OF_HEADINGS, } lattice_gen = LatticeGenerator(config) @@ -88,5 +88,5 @@ def test_output_angles_in_correct_range(self): self.assertLessEqual(angle, 2 * np.pi) -if __name__ == "__main__": +if __name__ == '__main__': unittest.main() diff --git a/nav2_smac_planner/lattice_primitives/tests/test_trajectory_generator.py b/nav2_smac_planner/lattice_primitives/tests/test_trajectory_generator.py index 917cf845faf..ea3f51930fa 100644 --- a/nav2_smac_planner/lattice_primitives/tests/test_trajectory_generator.py +++ b/nav2_smac_planner/lattice_primitives/tests/test_trajectory_generator.py @@ -25,7 +25,7 @@ class TestTrajectoryGenerator(unittest.TestCase): """Contains the unit tests for the TrajectoryGenerator.""" def setUp(self) -> None: - config = {"turning_radius": TURNING_RADIUS} + config = {'turning_radius': TURNING_RADIUS} self.trajectory_generator = TrajectoryGenerator(config) def test_generate_trajectory_only_arc(self): @@ -246,5 +246,5 @@ def test_generate_trajectory_parallel_lines_not_coincident(self): self.assertEqual(trajectory, None) -if __name__ == "__main__": +if __name__ == '__main__': unittest.main() diff --git a/nav2_smac_planner/lattice_primitives/tests/trajectory_visualizer.py b/nav2_smac_planner/lattice_primitives/tests/trajectory_visualizer.py index 595c631afa2..9187d0b1e46 100644 --- a/nav2_smac_planner/lattice_primitives/tests/trajectory_visualizer.py +++ b/nav2_smac_planner/lattice_primitives/tests/trajectory_visualizer.py @@ -30,7 +30,7 @@ import numpy as np -def plot_arrow(x, y, yaw, length=1.0, fc="r", ec="k"): +def plot_arrow(x, y, yaw, length=1.0, fc='r', ec='k'): """Plot arrow.""" plt.arrow( x, @@ -53,68 +53,68 @@ def read_trajectories_data(file_path): cur_file_path = Path(__file__) -trajectory_file_path = cur_file_path.parent.parent / "output.json" +trajectory_file_path = cur_file_path.parent.parent / 'output.json' trajectory_data = read_trajectories_data(trajectory_file_path) min_x = min( [ - min([pose[0] for pose in primitive["poses"]]) - for primitive in trajectory_data["primitives"] + min([pose[0] for pose in primitive['poses']]) + for primitive in trajectory_data['primitives'] ] ) max_x = max( [ - max([pose[0] for pose in primitive["poses"]]) - for primitive in trajectory_data["primitives"] + max([pose[0] for pose in primitive['poses']]) + for primitive in trajectory_data['primitives'] ] ) min_y = min( [ - min([pose[1] for pose in primitive["poses"]]) - for primitive in trajectory_data["primitives"] + min([pose[1] for pose in primitive['poses']]) + for primitive in trajectory_data['primitives'] ] ) max_y = max( [ - max([pose[1] for pose in primitive["poses"]]) - for primitive in trajectory_data["primitives"] + max([pose[1] for pose in primitive['poses']]) + for primitive in trajectory_data['primitives'] ] ) -heading_angles = trajectory_data["lattice_metadata"]["heading_angles"] +heading_angles = trajectory_data['lattice_metadata']['heading_angles'] -for primitive in trajectory_data["primitives"]: - arrow_length = (primitive["arc_length"] + primitive["straight_length"]) / len( - primitive["poses"] +for primitive in trajectory_data['primitives']: + arrow_length = (primitive['arc_length'] + primitive['straight_length']) / len( + primitive['poses'] ) if arrow_length == 0: - arrow_length = max_x / len(primitive["poses"]) + arrow_length = max_x / len(primitive['poses']) - xs = np.array([pose[0] for pose in primitive["poses"]]) - ys = np.array([pose[1] for pose in primitive["poses"]]) + xs = np.array([pose[0] for pose in primitive['poses']]) + ys = np.array([pose[1] for pose in primitive['poses']]) lengths = np.sqrt((xs[1:] - xs[:-1]) ** 2 + (ys[1:] - ys[:-1]) ** 2) - print("Distances between points: ", lengths) + print('Distances between points: ', lengths) - for x, y, yaw in primitive["poses"]: + for x, y, yaw in primitive['poses']: plot_arrow(x, y, yaw, length=arrow_length) plt.scatter(xs, ys) plt.grid(True) - plt.axis("square") + plt.axis('square') left_x, right_x = plt.xlim() left_y, right_y = plt.ylim() plt.xlim(1.2 * min_x, 1.2 * max_x) plt.ylim(1.2 * min_y, 1.2 * max_y) - start_angle = np.rad2deg(heading_angles[primitive["start_angle_index"]]) - end_angle = np.rad2deg(heading_angles[primitive["end_angle_index"]]) + start_angle = np.rad2deg(heading_angles[primitive['start_angle_index']]) + end_angle = np.rad2deg(heading_angles[primitive['end_angle_index']]) plt.title(f"Trajectory ID: {primitive['trajectory_id']}") - plt.figtext(0.7, 0.9, f"Start: {start_angle}\nEnd: {end_angle}") + plt.figtext(0.7, 0.9, f'Start: {start_angle}\nEnd: {end_angle}') plt.show() diff --git a/nav2_smac_planner/lattice_primitives/trajectory_generator.py b/nav2_smac_planner/lattice_primitives/trajectory_generator.py index 46f33b18522..bd47d055cdf 100644 --- a/nav2_smac_planner/lattice_primitives/trajectory_generator.py +++ b/nav2_smac_planner/lattice_primitives/trajectory_generator.py @@ -27,7 +27,7 @@ class TrajectoryGenerator: def __init__(self, config: dict): """Init TrajectoryGenerator using the user supplied config.""" - self.turning_radius = config["turning_radius"] + self.turning_radius = config['turning_radius'] def _get_arc_point( self, trajectory_params: TrajectoryParameters, t: float @@ -399,8 +399,8 @@ def _calculate_trajectory_params( else: logger.debug( - "No trajectory possible for equivalent start and " - + f"end angles that also passes through p = {x2, y2}" + 'No trajectory possible for equivalent start and ' + + f'end angles that also passes through p = {x2, y2}' ) return None @@ -413,8 +413,8 @@ def _calculate_trajectory_params( arc_start_point, intersection_point, start_angle ): logger.debug( - "No trajectory possible since intersection point occurs " - + "before start point on line 1" + 'No trajectory possible since intersection point occurs ' + + 'before start point on line 1' ) return None @@ -422,8 +422,8 @@ def _calculate_trajectory_params( # the angle of line 2 if not self._is_dir_vec_correct(intersection_point, arc_end_point, end_angle): logger.debug( - "No trajectory possible since intersection point occurs " - + "after end point on line 2" + 'No trajectory possible since intersection point occurs ' + + 'after end point on line 2' ) return None @@ -451,8 +451,8 @@ def _calculate_trajectory_params( # line 1 must be greater than the minimum valid distance if dist_a < min_valid_distance or dist_b < min_valid_distance: logger.debug( - "No trajectory possible where radius is larger than " - + "minimum turning radius" + 'No trajectory possible where radius is larger than ' + + 'minimum turning radius' ) return None @@ -505,8 +505,8 @@ def perp_line1(x): if radius < self.turning_radius: logger.debug( - "Calculated circle radius is smaller than allowed turning " - + f"radius: r = {radius}, min_radius = {self.turning_radius}" + 'Calculated circle radius is smaller than allowed turning ' + + f'radius: r = {radius}, min_radius = {self.turning_radius}' ) return None @@ -562,7 +562,7 @@ def generate_trajectory( if trajectory_params is None: return None - logger.debug("Trajectory found") + logger.debug('Trajectory found') trajectory_path = self._create_path(trajectory_params, primitive_resolution) From e17b1969b6071913125812b7ec08355f1eeb02b1 Mon Sep 17 00:00:00 2001 From: Ignacio Vizzo Date: Sun, 5 Nov 2023 22:44:59 +0100 Subject: [PATCH 24/24] Fix linter... again --- nav2_common/nav2_common/launch/rewritten_yaml.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nav2_common/nav2_common/launch/rewritten_yaml.py b/nav2_common/nav2_common/launch/rewritten_yaml.py index 77d765dda4a..c28dc88cc00 100644 --- a/nav2_common/nav2_common/launch/rewritten_yaml.py +++ b/nav2_common/nav2_common/launch/rewritten_yaml.py @@ -136,7 +136,7 @@ def add_params(self, yaml, param_rewrites): # add new total path parameters yaml_paths = self.pathify(yaml) for path in param_rewrites: - if yaml_paths not in path: + if not path in yaml_paths: # noqa: E713 new_val = self.convert(param_rewrites[path]) yaml_keys = path.split('.') if 'ros__parameters' in yaml_keys: