diff --git a/.github/ISSUE_TEMPLATE/navigator.yaml b/.github/ISSUE_TEMPLATE/navigator.yaml index 8e528b706..a3617fae6 100644 --- a/.github/ISSUE_TEMPLATE/navigator.yaml +++ b/.github/ISSUE_TEMPLATE/navigator.yaml @@ -7,26 +7,6 @@ body: attributes: value: | Hey, thanks for taking the time to add this software issue! - - type: input - id: assignee - attributes: - label: Assignee - description: > - Does this issue need to be completed by a specific person on the team? - If so, mention them below. - placeholder: ex. @torvalds is already working on this task! - validations: - required: false - - type: input - id: deadline - attributes: - label: Deadline - description: > - Does this task need a deadline? _If this task is related to a competition, - it should have a deadline._ - placeholder: ex. 2023-12-25 - validations: - required: false - type: textarea id: description attributes: diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index a510eb91b..de7c09a7a 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -31,19 +31,20 @@ jobs: - name: Configure catkin workspace folder structure run: | mkdir -p $GITHUB_WORKSPACE/catkin_ws/src + sudo apt reinstall python3-pip - name: Check out code from GitHub uses: actions/checkout@v3.0.2 with: submodules: recursive path: catkin_ws/src/mil - name: Setup ROS Noetic - uses: ros-tooling/setup-ros@v0.3 + uses: ros-tooling/setup-ros@v0.7 with: required-ros-distributions: noetic - name: Install pip dependencies run: | cd $GITHUB_WORKSPACE/catkin_ws/src/mil - pip install -r requirements.txt + pip3 install -r requirements.txt # We want to run a full test suite in CI - this includes the BlueView # tests! - name: Install BlueView Sonar SDK diff --git a/.github/workflows/gh_pages.yaml b/.github/workflows/gh_pages.yaml index b54342c28..39b70c62a 100644 --- a/.github/workflows/gh_pages.yaml +++ b/.github/workflows/gh_pages.yaml @@ -20,7 +20,7 @@ jobs: # Wait for the CI to finish so we can download the docs artifact - name: Wait for CI - uses: lewagon/wait-on-check-action@v1.0.0 + uses: lewagon/wait-on-check-action@v1.3.3 if: github.event.action != 'closed' with: ref: ${{ github.event.pull_request.head.ref }} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d2f0e2009..79a11871a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -11,41 +11,41 @@ ci: repos: - repo: https://github.com/adrienverge/yamllint.git - rev: v1.32.0 + rev: v1.33.0 hooks: - id: yamllint - repo: https://github.com/psf/black - rev: 23.3.0 + rev: 24.1.1 hooks: - id: black - repo: https://github.com/pre-commit/mirrors-clang-format - rev: v16.0.4 + rev: v17.0.6 hooks: - id: clang-format - repo: https://github.com/PyCQA/autoflake - rev: v2.1.1 + rev: v2.2.1 hooks: - id: autoflake args: [--remove-all-unused-imports, --ignore-init-module-imports] - repo: https://github.com/shellcheck-py/shellcheck-py - rev: v0.9.0.5 + rev: v0.9.0.6 hooks: - id: shellcheck exclude: ^docker|deprecated|NaviGator/simulation/VRX args: [--severity=warning, --exclude=SC1090] - repo: https://github.com/scop/pre-commit-shfmt - rev: v3.6.0-2 + rev: v3.7.0-4 hooks: - id: shfmt exclude: ^docker|deprecated|NaviGator/simulation/VRX - - repo: https://github.com/charliermarsh/ruff-pre-commit + - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. - rev: 'v0.0.270' + rev: 'v0.2.0' hooks: - id: ruff args: [--fix, --exit-non-zero-on-fix] - repo: https://github.com/codespell-project/codespell - rev: v2.2.4 + rev: v2.2.6 hooks: - id: codespell args: @@ -73,11 +73,12 @@ repos: - id: prettier-package-xml - id: sort-package-xml - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.5.0 hooks: - id: check-added-large-files - id: check-case-conflict - id: check-merge-conflict + exclude_types: [markdown, rst] - id: check-executables-have-shebangs - id: check-symlinks - id: check-json diff --git a/NaviGator/gnc/navigator_msg_multiplexer/nodes/ogrid_arbiter.py b/NaviGator/gnc/navigator_msg_multiplexer/nodes/ogrid_arbiter.py index ac8fffd4f..eb425ec7a 100755 --- a/NaviGator/gnc/navigator_msg_multiplexer/nodes/ogrid_arbiter.py +++ b/NaviGator/gnc/navigator_msg_multiplexer/nodes/ogrid_arbiter.py @@ -493,10 +493,7 @@ def publish(self, timer_event): ) print(e) fprint( - "w: {}, h: {}".format( - global_ogrid.info.width, - global_ogrid.info.height, - ), + f"w: {global_ogrid.info.width}, h: {global_ogrid.info.height}", msg_color="red", ) diff --git a/NaviGator/gnc/navigator_path_planner/nodes/path_planner.py b/NaviGator/gnc/navigator_path_planner/nodes/path_planner.py index ba33ca850..1f6ff6793 100755 --- a/NaviGator/gnc/navigator_path_planner/nodes/path_planner.py +++ b/NaviGator/gnc/navigator_path_planner/nodes/path_planner.py @@ -1070,7 +1070,7 @@ def reevaluate_plan(self) -> None: def action_check(self, _: rospy.timer.TimerEvent) -> None: """ Manages action preempting. Serves as the callback to a Timer operating - opereating every self.revisit_period seconds. + operating every self.revisit_period seconds. """ if self.preempted or not self.move_server.is_active(): return diff --git a/NaviGator/gnc/navigator_thrust_mapper/navigator_thrust_mapper/thruster_map.py b/NaviGator/gnc/navigator_thrust_mapper/navigator_thrust_mapper/thruster_map.py index 588679455..2fc19700a 100644 --- a/NaviGator/gnc/navigator_thrust_mapper/navigator_thrust_mapper/thruster_map.py +++ b/NaviGator/gnc/navigator_thrust_mapper/navigator_thrust_mapper/thruster_map.py @@ -166,15 +166,11 @@ def from_urdf( if find != -1 and find + len(transmission_suffix) == len(transmission.name): if len(transmission.joints) != 1: raise Exception( - "Transmission {} does not have 1 joint".format( - transmission.name, - ), + f"Transmission {transmission.name} does not have 1 joint", ) if len(transmission.actuators) != 1: raise Exception( - "Transmission {} does not have 1 actuator".format( - transmission.name, - ), + f"Transmission {transmission.name} does not have 1 actuator", ) t_ratio = transmission.actuators[0].mechanicalReduction @@ -195,9 +191,7 @@ def from_urdf( joint = t_joint if joint is None: rospy.logerr( - "Transmission joint {} not found".format( - transmission.joints[0].name, - ), + f"Transmission joint {transmission.joints[0].name} not found", ) try: trans = buff.lookup_transform( @@ -217,9 +211,7 @@ def from_urdf( joints.append(joint.name) if limit != -1 and joint.limit.effort != limit: raise Exception( - "Thruster {} had a different limit, cannot proceed".format( - joint.name, - ), + f"Thruster {joint.name} had a different limit, cannot proceed", ) limit = joint.limit.effort limit_tuple = (limit, -limit) diff --git a/NaviGator/hardware_drivers/navigator_kill_board/navigator_kill_board/constants.py b/NaviGator/hardware_drivers/navigator_kill_board/navigator_kill_board/constants.py index 83663e034..d5eaef7e4 100644 --- a/NaviGator/hardware_drivers/navigator_kill_board/navigator_kill_board/constants.py +++ b/NaviGator/hardware_drivers/navigator_kill_board/navigator_kill_board/constants.py @@ -17,6 +17,7 @@ The computer can also command a kill (for example, if ROS notices a criticaly low battery) by sending the COMPUTER.KILL.REQUEST and undone with COMPUTER.CLEAR.REQUEST """ + constants = { "TIMEOUT_SECONDS": 8.0, # How often board must be pinged to not set HEARTBERAT_REMOTE True # Note: not official documented, this is just a guess diff --git a/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/battery_voltage.py b/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/battery_voltage.py index 6c25b9169..c10b13c91 100644 --- a/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/battery_voltage.py +++ b/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/battery_voltage.py @@ -27,9 +27,9 @@ def _check_voltage(self, msg): if not self._raised or self._severity != severity: self.broadcaster.raise_alarm( severity=severity, - problem_description="battery critcaly low" - if severity == 2 - else "battery low", + problem_description=( + "battery critcaly low" if severity == 2 else "battery low" + ), parameters={"voltage": voltage}, ) diff --git a/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/kill.py b/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/kill.py index a3f7a612b..547c56fa8 100644 --- a/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/kill.py +++ b/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/kill.py @@ -28,10 +28,7 @@ def _online_bagger_cb(self, status, result): rospy.loginfo(f"KILL BAG WRITTEN TO {result.filename}") else: rospy.logwarn( - "KILL BAG {}, status: {}".format( - TerminalState.to_string(status), - result.status, - ), + f"KILL BAG {TerminalState.to_string(status)}, status: {result.status}", ) def _kill_task_cb(self, status, result): @@ -39,10 +36,7 @@ def _kill_task_cb(self, status, result): rospy.loginfo("Killed task success!") return rospy.logwarn( - "Killed task failed ({}): {}".format( - TerminalState.to_string(status), - result.result, - ), + f"Killed task failed ({TerminalState.to_string(status)}): {result.result}", ) def raised(self, alarm): diff --git a/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/odom_kill.py b/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/odom_kill.py index 2bc5e6c43..d0fa63afd 100755 --- a/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/odom_kill.py +++ b/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/odom_kill.py @@ -51,9 +51,7 @@ def check_continuity(self, odom): self._raised = True # Avoid raising multiple times rospy.logwarn("ODOM DISCONTINUITY DETECTED") self.ab.raise_alarm( - problem_description="ODOM DISCONTINUITY DETECTED. JUMPED {} METERS".format( - jump, - ), + problem_description=f"ODOM DISCONTINUITY DETECTED. JUMPED {jump} METERS", severity=5, ) self.last_position = position diff --git a/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/thruster_fault.py b/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/thruster_fault.py index a89612632..ce89ac3a0 100644 --- a/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/thruster_fault.py +++ b/NaviGator/mission_control/navigator_alarm/navigator_alarm_handlers/thruster_fault.py @@ -65,9 +65,7 @@ def _check_faults(self, msg, topic): return self.broadcaster.raise_alarm( severity=5, - problem_description="{} thrusters have faults".format( - len(self._raised_alarms), - ), + problem_description=f"{len(self._raised_alarms)} thrusters have faults", parameters={ t: self._get_fault_codes(k) for t, k in self._raised_alarms.items() }, diff --git a/NaviGator/mission_control/navigator_launch/launch/vrx/vrx_master.launch b/NaviGator/mission_control/navigator_launch/launch/vrx/vrx_master.launch index 944df5bfa..377f824de 100644 --- a/NaviGator/mission_control/navigator_launch/launch/vrx/vrx_master.launch +++ b/NaviGator/mission_control/navigator_launch/launch/vrx/vrx_master.launch @@ -7,6 +7,7 @@ + @@ -30,5 +31,4 @@ - diff --git a/NaviGator/mission_control/navigator_launch/launch/vrx/vrx_tf.launch b/NaviGator/mission_control/navigator_launch/launch/vrx/vrx_tf.launch index f46bcca90..a9bdd66e8 100644 --- a/NaviGator/mission_control/navigator_launch/launch/vrx/vrx_tf.launch +++ b/NaviGator/mission_control/navigator_launch/launch/vrx/vrx_tf.launch @@ -1,5 +1,8 @@ + + true + @@ -11,9 +14,10 @@ - - - - + + + + + diff --git a/NaviGator/mission_control/navigator_missions/launch/mission_params.yaml b/NaviGator/mission_control/navigator_missions/launch/mission_params.yaml index 7b44edc7e..c4ee5940c 100644 --- a/NaviGator/mission_control/navigator_missions/launch/mission_params.yaml +++ b/NaviGator/mission_control/navigator_missions/launch/mission_params.yaml @@ -157,14 +157,14 @@ dock_shape_1: param: /mission/identify_dock/shape_1 options: [CIRCLE, TRIANGLE, CROSS, ANY] description: > - The shape of the first bay to dock in during the dentify + The shape of the first bay to dock in during the identify Symbols and Dock mission. If set to ANY, mission should dock based on the color parameter and set this parameter during the mission dock_color_1: param: /mission/identify_dock/color_1 options: [RED, GREEN, BLUE, ANY] description: > - The color of the first bay to dock in during the dentify Symbols and Dock + The color of the first bay to dock in during the identify Symbols and Dock mission. If set to ANY, mission should dock based on the shape parameter and set this parameter during the mission @@ -174,7 +174,7 @@ dock_shape_2: description: > # yamllint disable-line rule:line-length The shape of the second bay to dock in during the - dentify Symbols and Dock mission. If set to ANY, + identify Symbols and Dock mission. If set to ANY, mission should dock based on the color parameter and set this parameter during the mission dock_color_2: @@ -183,6 +183,6 @@ dock_color_2: description: > # yamllint disable-line rule:line-length The color of the second bay to dock in during the - dentify Symbols and Dock mission. + identify Symbols and Dock mission. If set to ANY, mission should dock based on the shape parameter and set this parameter during the mission diff --git a/NaviGator/mission_control/navigator_missions/navigator_missions/constant_velocity.py b/NaviGator/mission_control/navigator_missions/navigator_missions/constant_velocity.py index 5ae078c90..a0ce42a26 100644 --- a/NaviGator/mission_control/navigator_missions/navigator_missions/constant_velocity.py +++ b/NaviGator/mission_control/navigator_missions/navigator_missions/constant_velocity.py @@ -66,7 +66,7 @@ def decode_parameters(cls, parameters): return parsed async def run(self, args): - # Publish a velocity of zero for a while to stabalize navigator + # Publish a velocity of zero for a while to stabilize navigator self.send_feedback("Switching trajectory to constant") await self.change_trajectory("constant") await self.nh.sleep(0.1) diff --git a/NaviGator/mission_control/navigator_missions/navigator_missions/demonstrate_navigation.py b/NaviGator/mission_control/navigator_missions/navigator_missions/demonstrate_navigation.py index 6c53d35a4..599a388cc 100644 --- a/NaviGator/mission_control/navigator_missions/navigator_missions/demonstrate_navigation.py +++ b/NaviGator/mission_control/navigator_missions/navigator_missions/demonstrate_navigation.py @@ -68,7 +68,7 @@ async def run(self, parameters): _, closest_reds = await self.get_sorted_objects("red_cylinder", 1) _, closest_greens = await self.get_sorted_objects("green_cylinder", 1) - # Rename the totems for their symantic name + # Rename the totems for their semantic name green_close = closest_greens[0] red_close = closest_reds[0] @@ -83,7 +83,7 @@ async def run(self, parameters): _, closest_reds = await self.get_sorted_objects("red_cylinder", 2) _, closest_greens = await self.get_sorted_objects("green_cylinder", 2) - # Rename the totems for their symantic name + # Rename the totems for their semantic name green_far = closest_greens[1] red_far = closest_reds[1] diff --git a/NaviGator/mission_control/navigator_missions/navigator_missions/detect_deliver_2016.py b/NaviGator/mission_control/navigator_missions/navigator_missions/detect_deliver_2016.py index bc95612b0..dee540de0 100644 --- a/NaviGator/mission_control/navigator_missions/navigator_missions/detect_deliver_2016.py +++ b/NaviGator/mission_control/navigator_missions/navigator_missions/detect_deliver_2016.py @@ -153,9 +153,7 @@ async def do_circle(): await self.nh.sleep(0.25) continue fprint( - "Shape ({}found, using normal to look at other 3 shapes if needed".format( - res[0], - ), + f"Shape ({res[0]}found, using normal to look at other 3 shapes if needed", title="DETECT DELIVER", msg_color="green", ) @@ -240,10 +238,7 @@ async def search_sides(self, moves): self.shape_pose = found_pose return fprint( - "Saw (Shape={}, Color={}) on this side".format( - shape_color[0], - shape_color[1], - ), + f"Saw (Shape={shape_color[0]}, Color={shape_color[1]}) on this side", title="DETECT DELIVER", msg_color="green", ) @@ -287,10 +282,7 @@ def select_backup_shape(self): self.shape_pose = point_normal if self.Shape == shape or self.Color == color: fprint( - "Correct shape not found, resorting to shape={} color={}".format( - shape, - color, - ), + f"Correct shape not found, resorting to shape={shape} color={color}", title="DETECT DELIVER", msg_color="yellow", ) @@ -430,9 +422,7 @@ async def shoot_and_align_forest(self): move = await self.align_to_target() if move.failure_reason != "": fprint( - "Error Aligning with target = {}. Ending mission :(".format( - move.failure_reason, - ), + f"Error Aligning with target = {move.failure_reason}. Ending mission :(", title="DETECT DELIVER", msg_color="red", ) @@ -479,9 +469,7 @@ async def shoot_and_align(self): move = await self.align_to_target() if move.failure_reason != "": fprint( - "Error Aligning with target = {}. Ending mission :(".format( - move.failure_reason, - ), + f"Error Aligning with target = {move.failure_reason}. Ending mission :(", title="DETECT DELIVER", msg_color="red", ) diff --git a/NaviGator/mission_control/navigator_missions/navigator_missions/identify_dock.py b/NaviGator/mission_control/navigator_missions/navigator_missions/identify_dock.py index 28419f6b6..6d2203826 100644 --- a/NaviGator/mission_control/navigator_missions/navigator_missions/identify_dock.py +++ b/NaviGator/mission_control/navigator_missions/navigator_missions/identify_dock.py @@ -150,10 +150,7 @@ async def check_bays(self): def update_shape(self, shape_res, normal_res, tf): print_good( - "Found (Shape={}, Color={} in a bay".format( - shape_res.Shape, - shape_res.Color, - ), + f"Found (Shape={shape_res.Shape}, Color={shape_res.Color} in a bay", ) self.identified_shapes[(shape_res.Shape, shape_res.Color)] = self.get_shape_pos( normal_res, diff --git a/NaviGator/mission_control/navigator_missions/navigator_missions/move.py b/NaviGator/mission_control/navigator_missions/navigator_missions/move.py index 03017c09b..a9debd213 100755 --- a/NaviGator/mission_control/navigator_missions/navigator_missions/move.py +++ b/NaviGator/mission_control/navigator_missions/navigator_missions/move.py @@ -149,9 +149,7 @@ async def run(self, args): "yl": "yaw_left", "yr": "yaw_right", } - command = ( - command if command not in shorthand.keys() else shorthand[command] - ) + command = shorthand.get(command, command) movement = getattr(self.move, command) trans_move = command[:3] != "yaw" diff --git a/NaviGator/mission_control/navigator_missions/navigator_missions/navigation.py b/NaviGator/mission_control/navigator_missions/navigator_missions/navigation.py index 9b977b0bf..7812e5108 100644 --- a/NaviGator/mission_control/navigator_missions/navigator_missions/navigation.py +++ b/NaviGator/mission_control/navigator_missions/navigator_missions/navigation.py @@ -187,9 +187,7 @@ async def explore_closest_until(self, is_done, filter_and_sort): ) if classification_index != -1: self.send_feedback( - "{} identified. Canceling investigation".format( - move_id_tuple[1], - ), + f"{move_id_tuple[1]} identified. Canceling investigation", ) move_task.cancel() diff --git a/NaviGator/mission_control/navigator_missions/navigator_missions/pose_editor.py b/NaviGator/mission_control/navigator_missions/navigator_missions/pose_editor.py index 5f25f36ab..d2b1855cd 100644 --- a/NaviGator/mission_control/navigator_missions/navigator_missions/pose_editor.py +++ b/NaviGator/mission_control/navigator_missions/navigator_missions/pose_editor.py @@ -341,9 +341,7 @@ def as_MoveGoal(self, move_type=MoveGoal.DRIVE, **kwargs): for key in kwargs: if not hasattr(MoveGoal, key): fprint( - "MoveGoal msg doesn't have a field called '{}' you tried to set via kwargs.".format( - key, - ), + f"MoveGoal msg doesn't have a field called '{key}' you tried to set via kwargs.", title="POSE_EDITOR", msg_color="red", ) diff --git a/NaviGator/mission_control/navigator_missions/vrx_missions/dock.py b/NaviGator/mission_control/navigator_missions/vrx_missions/dock.py index 23d7cdfb3..44a3cacae 100644 --- a/NaviGator/mission_control/navigator_missions/vrx_missions/dock.py +++ b/NaviGator/mission_control/navigator_missions/vrx_missions/dock.py @@ -607,7 +607,7 @@ async def prepare_for_docking(self): # This function looks at the two squares in front of the boat # and it gets the middle pixel between the two squares. # If the middle pixel is for some reason not in the middle of our camera... - # adjust the boat postiion before docking + # adjust the boat position before docking print("prepare for landing!") img = await self.front_left_camera_sub.get_next_message() diff --git a/NaviGator/mission_control/navigator_missions/vrx_missions/vrx.py b/NaviGator/mission_control/navigator_missions/vrx_missions/vrx.py index d629df644..91514c01d 100644 --- a/NaviGator/mission_control/navigator_missions/vrx_missions/vrx.py +++ b/NaviGator/mission_control/navigator_missions/vrx_missions/vrx.py @@ -29,145 +29,143 @@ class Vrx(NaviGatorMission): nh: NodeHandle - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - @staticmethod - async def init(): - if hasattr(Vrx, "_vrx_init"): + @classmethod + async def setup(cls): + if hasattr(cls, "_cls_init"): return - Vrx.from_lla = Vrx.nh.get_service_client("/fromLL", FromLL) - Vrx.to_lla = Vrx.nh.get_service_client("/toLL", ToLL) - Vrx.task_info_sub = Vrx.nh.subscribe("/vrx/task/info", Task) - await Vrx.task_info_sub.setup() - Vrx.scan_dock_color_sequence = Vrx.nh.get_service_client( + cls.from_lla = cls.nh.get_service_client("/fromLL", FromLL) + cls.to_lla = cls.nh.get_service_client("/toLL", ToLL) + cls.task_info_sub = cls.nh.subscribe("/vrx/task/info", Task) + cls.scan_dock_color_sequence = cls.nh.get_service_client( "/vrx/scan_dock_deliver/color_sequence", ColorSequence, ) - Vrx.fire_ball = Vrx.nh.advertise("/wamv/shooters/ball_shooter/fire", Empty) - Vrx.station_keep_goal = Vrx.nh.subscribe( + cls.fire_ball = cls.nh.advertise("/wamv/shooters/ball_shooter/fire", Empty) + cls.station_keep_goal = cls.nh.subscribe( "/vrx/station_keeping/goal", GeoPoseStamped, ) - Vrx.wayfinding_path_sub = Vrx.nh.subscribe("/vrx/wayfinding/waypoints", GeoPath) - Vrx.station_keeping_pose_error = Vrx.nh.subscribe( + cls.wayfinding_path_sub = cls.nh.subscribe("/vrx/wayfinding/waypoints", GeoPath) + cls.station_keeping_pose_error = cls.nh.subscribe( "/vrx/station_keeping/pose_error", Float64, ) - Vrx.station_keeping_rms_error = Vrx.nh.subscribe( + cls.station_keeping_rms_error = cls.nh.subscribe( "/vrx/station_keeping/rms_error", Float64, ) - Vrx.wayfinding_min_errors = Vrx.nh.subscribe( + cls.wayfinding_min_errors = cls.nh.subscribe( "/vrx/wayfinding/min_errors", Float64MultiArray, ) - Vrx.wayfinding_mean_error = Vrx.nh.subscribe( + cls.wayfinding_mean_error = cls.nh.subscribe( "/vrx/wayfinding/mean_error", Float64, ) - Vrx.perception_landmark = Vrx.nh.advertise( + cls.perception_landmark = cls.nh.advertise( "/vrx/perception/landmark", GeoPoseStamped, ) await asyncio.gather( - Vrx.fire_ball.setup(), - Vrx.station_keep_goal.setup(), - Vrx.wayfinding_path_sub.setup(), - Vrx.station_keeping_pose_error.setup(), - Vrx.station_keeping_rms_error.setup(), - Vrx.wayfinding_min_errors.setup(), - Vrx.wayfinding_mean_error.setup(), - Vrx.perception_landmark.setup(), + cls.task_info_sub.setup(), + cls.fire_ball.setup(), + cls.station_keep_goal.setup(), + cls.wayfinding_path_sub.setup(), + cls.station_keeping_pose_error.setup(), + cls.station_keeping_rms_error.setup(), + cls.wayfinding_min_errors.setup(), + cls.wayfinding_mean_error.setup(), + cls.perception_landmark.setup(), ) - Vrx.animal_landmarks = Vrx.nh.subscribe("/vrx/wildlife/animals/poses", GeoPath) - Vrx.beacon_landmark = Vrx.nh.get_service_client("beaconLocator", AcousticBeacon) - Vrx.circle_animal = Vrx.nh.get_service_client("/choose_animal", ChooseAnimal) - Vrx.set_long_waypoint = Vrx.nh.get_service_client( + cls.animal_landmarks = cls.nh.subscribe("/vrx/wildlife/animals/poses", GeoPath) + cls.beacon_landmark = cls.nh.get_service_client("beaconLocator", AcousticBeacon) + cls.circle_animal = cls.nh.get_service_client("/choose_animal", ChooseAnimal) + cls.set_long_waypoint = cls.nh.get_service_client( "/set_long_waypoint", MoveToWaypoint, ) - Vrx.yolo_objects = Vrx.nh.subscribe("/yolov7/detections", Detection2DArray) - Vrx.tf_listener = axros_tf.TransformListener(Vrx.nh) - await Vrx.tf_listener.setup() - Vrx.database_response = Vrx.nh.get_service_client( + cls.yolo_objects = cls.nh.subscribe("/yolov7/detections", Detection2DArray) + cls.tf_listener = axros_tf.TransformListener(cls.nh) + await cls.tf_listener.setup() + cls.database_response = cls.nh.get_service_client( "/database/requests", ObjectDBQuery, ) - Vrx.get_two_closest_cones = Vrx.nh.get_service_client( + cls.get_two_closest_cones = cls.nh.get_service_client( "/get_two_closest_cones", TwoClosestCones, ) await asyncio.gather( - Vrx.animal_landmarks.setup(), - Vrx.yolo_objects.setup(), + cls.animal_landmarks.setup(), + cls.yolo_objects.setup(), ) - Vrx.pcodar_reset = Vrx.nh.get_service_client("/pcodar/reset", Trigger) + cls.pcodar_reset = cls.nh.get_service_client("/pcodar/reset", Trigger) - Vrx.front_left_camera_info_sub = None - Vrx.front_left_camera_sub = None - Vrx.front_right_camera_info_sub = None - Vrx.front_right_camera_sub = None + cls.front_left_camera_info_sub = None + cls.front_left_camera_sub = None + cls.front_right_camera_info_sub = None + cls.front_right_camera_sub = None - Vrx._vrx_init = True + cls._cls_init = True - @staticmethod - async def shutdown(): + @classmethod + async def shutdown(cls): + return await asyncio.gather( - Vrx.task_info_sub.shutdown(), - Vrx.animal_landmarks.shutdown(), - Vrx.yolo_objects.shutdown(), - Vrx.fire_ball.shutdown(), - Vrx.station_keep_goal.shutdown(), - Vrx.wayfinding_path_sub.shutdown(), - Vrx.station_keeping_pose_error.shutdown(), - Vrx.station_keeping_rms_error.shutdown(), - Vrx.wayfinding_min_errors.shutdown(), - Vrx.wayfinding_mean_error.shutdown(), - Vrx.perception_landmark.shutdown(), + cls.task_info_sub.shutdown(), + cls.animal_landmarks.shutdown(), + cls.yolo_objects.shutdown(), + cls.fire_ball.shutdown(), + cls.station_keep_goal.shutdown(), + cls.wayfinding_path_sub.shutdown(), + cls.station_keeping_pose_error.shutdown(), + cls.station_keeping_rms_error.shutdown(), + cls.wayfinding_min_errors.shutdown(), + cls.wayfinding_mean_error.shutdown(), + cls.perception_landmark.shutdown(), ) def cleanup(self): pass - @staticmethod - async def init_front_left_camera(): - if Vrx.front_left_camera_sub is None: - Vrx.front_left_camera_sub = Vrx.nh.subscribe( + @classmethod + async def init_front_left_camera(cls): + if cls.front_left_camera_sub is None: + cls.front_left_camera_sub = cls.nh.subscribe( "/wamv/sensors/cameras/front_left_camera/image_raw", Image, ) - if Vrx.front_left_camera_info_sub is None: - Vrx.front_left_camera_info_sub = Vrx.nh.subscribe( + if cls.front_left_camera_info_sub is None: + cls.front_left_camera_info_sub = cls.nh.subscribe( "/wamv/sensors/cameras/front_left_camera/camera_info", CameraInfo, ) await asyncio.gather( - Vrx.front_left_camera_sub.setup(), - Vrx.front_left_camera_info_sub.setup(), + cls.front_left_camera_sub.setup(), + cls.front_left_camera_info_sub.setup(), ) - @staticmethod - async def init_front_right_camera(): - if Vrx.front_right_camera_sub is None: - Vrx.front_right_camera_sub = Vrx.nh.subscribe( + @classmethod + async def init_front_right_camera(cls): + if cls.front_right_camera_sub is None: + cls.front_right_camera_sub = cls.nh.subscribe( "/wamv/sensors/cameras/front_right_camera/image_raw", Image, ) - if Vrx.front_right_camera_info_sub is None: - Vrx.front_right_camera_info_sub = Vrx.nh.subscribe( + if cls.front_right_camera_info_sub is None: + cls.front_right_camera_info_sub = cls.nh.subscribe( "/wamv/sensors/cameras/front_right_camera/camera_info", CameraInfo, ) await asyncio.gather( - Vrx.front_right_camera_sub.setup(), - Vrx.front_right_camera_info_sub.setup(), + cls.front_right_camera_sub.setup(), + cls.front_right_camera_info_sub.setup(), ) async def geo_pose_to_enu_pose(self, geo): diff --git a/NaviGator/mission_control/navigator_missions/vrx_missions/vrx_navigation.py b/NaviGator/mission_control/navigator_missions/vrx_missions/vrx_navigation.py index 3086e39b5..7ef98c064 100644 --- a/NaviGator/mission_control/navigator_missions/vrx_missions/vrx_navigation.py +++ b/NaviGator/mission_control/navigator_missions/vrx_missions/vrx_navigation.py @@ -151,9 +151,7 @@ async def explore_closest_until(self, is_done, filter_and_sort): ) if classification_index != -1: self.send_feedback( - "{} identified. Canceling investigation".format( - move_id_tuple[1], - ), + f"{move_id_tuple[1]} identified. Canceling investigation", ) move_id_tuple[0].cancel() await self.nh.sleep(1.0) diff --git a/NaviGator/mission_control/navigator_missions/vrx_missions/vrx_perception.py b/NaviGator/mission_control/navigator_missions/vrx_missions/vrx_perception.py index f1483416f..2b1ef6d50 100644 --- a/NaviGator/mission_control/navigator_missions/vrx_missions/vrx_perception.py +++ b/NaviGator/mission_control/navigator_missions/vrx_missions/vrx_perception.py @@ -79,11 +79,7 @@ async def run(self, parameters): ) elif objects[key] != new_objects[key]: self.send_feedback( - "{} changed from {} to {}".format( - key, - objects[key], - new_objects[key], - ), + f"{key} changed from {objects[key]} to {new_objects[key]}", ) await self.announce_object( key, diff --git a/NaviGator/mission_control/navigator_missions/vrx_missions/vrx_wayfinding_2.py b/NaviGator/mission_control/navigator_missions/vrx_missions/vrx_wayfinding_2.py index 60496d0b8..966f38be0 100644 --- a/NaviGator/mission_control/navigator_missions/vrx_missions/vrx_wayfinding_2.py +++ b/NaviGator/mission_control/navigator_missions/vrx_missions/vrx_wayfinding_2.py @@ -5,6 +5,7 @@ from .vrx import Vrx ___author___ = "Alex Perez" +# Optimized by Daniel Parra class VrxWayfinding2(Vrx): @@ -42,12 +43,18 @@ async def run(self, parameters): poses = poses[:start_pose_index] path = path[1:] - # self.send_feedback('Sorted poses' + str(poses)) await self.wait_for_task_such_that(lambda task: task.state in ["running"]) # do movements for index in path: self.send_feedback(f"Going to {poses[index]}") - # Go to goal + P = 0.85 + part_way_point = [x * P for x in poses[index][0][:-1]] + part_way_point.append(poses[index][0][-1]) + self.send_feedback( + f"\nPartway:\n{part_way_point}\nEndPoint:\n{poses[index][0]}", + ) + + await self.send_trajectory_without_path([part_way_point, poses[index][1]]) await self.send_trajectory_without_path(poses[index]) diff --git a/NaviGator/satellite/rviz_satellite/src/aerialmap_display.cpp b/NaviGator/satellite/rviz_satellite/src/aerialmap_display.cpp index 22a307f76..bf5ec8b20 100644 --- a/NaviGator/satellite/rviz_satellite/src/aerialmap_display.cpp +++ b/NaviGator/satellite/rviz_satellite/src/aerialmap_display.cpp @@ -416,7 +416,7 @@ void AerialMapDisplay::assembleScene() // determine location of this tile, flipping y in the process const double x = (tile.x() - loader_->centerTileX()) * tile_w + origin_x; const double y = -(tile.y() - loader_->centerTileY()) * tile_h + origin_y; - // don't re-use any ids + // don't reuse any ids const std::string name_suffix = std::to_string(tile.x()) + "_" + std::to_string(tile.y()) + "_" + std::to_string(map_id_) + "_" + std::to_string(scene_id_); diff --git a/NaviGator/scripts/bash_aliases.sh b/NaviGator/scripts/bash_aliases.sh index 216b1ff80..de6da5f4b 100755 --- a/NaviGator/scripts/bash_aliases.sh +++ b/NaviGator/scripts/bash_aliases.sh @@ -18,7 +18,7 @@ nthrust() { topic="/$1_motor/cmd" publishers=$(rostopic info "$topic" | grep Publishers) if [ "$publishers" != "Publishers: None" ]; then - echo "Somone is already publishing to $topic. Perhaps you need to kill thrust mapper?" + echo "Someone is already publishing to $topic. Perhaps you need to kill thrust mapper?" return 1 fi rostopic pub "$topic" "roboteq_msgs/Command" "setpoint: $2" -r100 diff --git a/NaviGator/simulation/navigator_gazebo/test/test_sim_integration.py b/NaviGator/simulation/navigator_gazebo/test/test_sim_integration.py index 3cb7ab8a7..46e20b856 100755 --- a/NaviGator/simulation/navigator_gazebo/test/test_sim_integration.py +++ b/NaviGator/simulation/navigator_gazebo/test/test_sim_integration.py @@ -71,10 +71,7 @@ def test_odom(self): rospy.sleep(0.1) self.assertTrue( len(self.odom_pos_msg) == 3 and len(self.odom_ori_msg) == 4, - msg="POS, ORI: {}, {}".format( - len(self.odom_pos_msg), - len(self.odom_ori_msg), - ), + msg=f"POS, ORI: {len(self.odom_pos_msg)}, {len(self.odom_ori_msg)}", ) initial_pos = [-1.2319, 0.0, 0.0] initial_ori = [0.0, 0.0, 0.0, 1.0] @@ -100,10 +97,7 @@ def test_absodom(self): rospy.sleep(0.1) self.assertTrue( len(self.absodom_pos_msg) == 3 and len(self.absodom_ori_msg) == 4, - msg="POS, ORI: {}, {}".format( - len(self.absodom_pos_msg), - len(self.absodom_ori_msg), - ), + msg=f"POS, ORI: {len(self.absodom_pos_msg)}, {len(self.absodom_ori_msg)}", ) initial_pos = [743789.637462, -5503821.36715, 3125622.10477] initial_ori = [0.0, 0.0, 0.0, 1.0] @@ -122,25 +116,13 @@ def verify_pos_ori(self, pos, initial_pos, ori, initial_ori, topic): actual, initial, places=0, - msg=( - "Error: {} position is: {} should be {}".format( - topic, - actual, - initial, - ) - ), + msg=(f"Error: {topic} position is: {actual} should be {initial}"), ) for actual, initial in zip(ori, initial_ori): self.assertEqual( actual, initial, - msg=( - "Error: {} orientation is: {} should be {}".format( - topic, - actual, - initial, - ) - ), + msg=(f"Error: {topic} orientation is: {actual} should be {initial}"), ) def cam_info_right_cb(self, msg): @@ -229,10 +211,7 @@ def verify_not_empty(self, data_lists, num_topics): self.assertEqual( len(data_lists), num_topics, - msg="Number of topics is {}, should be {}".format( - len(data_lists), - num_topics, - ), + msg=f"Number of topics is {len(data_lists)}, should be {num_topics}", ) for data_list in data_lists: self.assertNotEqual(len(data_list), 0, msg="data is empty") @@ -243,13 +222,7 @@ def verify_info(self, res_info, initial_info, topic): self.assertNotEqual( actual_dim, initial_dim, - msg=( - "Error: {} is: {} shouldn't be {}".format( - topic, - actual_dim, - initial_dim, - ) - ), + msg=(f"Error: {topic} is: {actual_dim} shouldn't be {initial_dim}"), ) diff --git a/NaviGator/utils/navigator_msgs/srv/GetDockBays.srv b/NaviGator/utils/navigator_msgs/srv/GetDockBays.srv index 9a39764bd..7081b1b07 100644 --- a/NaviGator/utils/navigator_msgs/srv/GetDockBays.srv +++ b/NaviGator/utils/navigator_msgs/srv/GetDockBays.srv @@ -2,4 +2,4 @@ geometry_msgs/Point[3] bays #The positions in ENU frame of the center of the three bays 0=left, 1=center, 2=right geometry_msgs/Vector3 normal #Vector or normal pointing away from plane of dock back bool success #False if an error occurred getting dock bays -string error #Descripion of error if success=false +string error #Description of error if success=false diff --git a/NaviGator/utils/navigator_robotx_comms/nodes/robotx_comms_client.py b/NaviGator/utils/navigator_robotx_comms/nodes/robotx_comms_client.py index d8583f010..59e6139e3 100755 --- a/NaviGator/utils/navigator_robotx_comms/nodes/robotx_comms_client.py +++ b/NaviGator/utils/navigator_robotx_comms/nodes/robotx_comms_client.py @@ -559,10 +559,7 @@ def connect(self) -> None: """ if not self.connected: rospy.loginfo( - "Attempting Connection to TD Server at {}:{}".format( - self.tcp_ip, - self.tcp_port, - ), + f"Attempting Connection to TD Server at {self.tcp_ip}:{self.tcp_port}", ) while not self.connected and not rospy.is_shutdown(): # recreate socket diff --git a/NaviGator/utils/navigator_tools/navigator_tools/object_database_helper.py b/NaviGator/utils/navigator_tools/navigator_tools/object_database_helper.py index 0798c78e0..5cb8762cb 100644 --- a/NaviGator/utils/navigator_tools/navigator_tools/object_database_helper.py +++ b/NaviGator/utils/navigator_tools/navigator_tools/object_database_helper.py @@ -1,4 +1,3 @@ -"""Use the DBHelper class to interface with the Database without having to deal with ROS things.""" import asyncio import sys import time @@ -14,10 +13,29 @@ class DBHelper: - """DBHelper class.""" + """ + Use the DBHelper class to interface with the Database without having to deal with ROS things. + + Attributes: + found (bool): checks whether the object is what the user has been looking for. + nh (axros.NodeHandle): processes database requests. + position (int): the current position of the object. + rot (): one of the dimensional values. + new_object_subscriber (): an object that is being called from the database. + ensuring_objects (bool): a variable state for the object. + ensuring_object_dep (): a list of objects being used for storage. + ensuring_object_cb (): this is considered when it is an "ensuring_objects". + looking_for (): a setter variable to which a name is being assigned. + is_found (bool): determines whether the object is found or not. + """ def __init__(self, nh): - """Initialize the DB helper class.""" + """ + Initialize the DB helper class. + + Args: + nh(NodeHandle): NodeHandle object + """ self.found = set() self.nh = nh self.position = None @@ -30,7 +48,12 @@ def __init__(self, nh): self.is_found = False async def init_(self, navigator=None): - """Initialize the axros parts of the DBHelper.""" + """ + Initialize the axros parts of the DBHelper. + + Args: + navigator (NaviGator | None): Base NaviGator object + """ # self._sub_database = yield self.nh.subscribe('/database/objects', PerceptionObjectArray, self.object_cb) self._database = self.nh.get_service_client("/database/requests", ObjectDBQuery) self.navigator = navigator @@ -43,21 +66,37 @@ async def init_(self, navigator=None): return self def _odom_cb(self, odom): + """ + Sets the position and the rot values. + + Args: + odom (object): Odom + """ self.position, self.rot = nt.odometry_to_numpy(odom)[0] async def get_object_by_id(self, my_id): + """ + Retrieves the object with the associated "my_id". + + Args: + my_id (int): an "id" of the object is passed in. + + Returns: + An individual object is being returned with a unique id. + """ print(my_id) req = ObjectDBQueryRequest() req.name = "all" resp = await self._database(req) - ans = [obj for obj in resp.objects if obj.id == my_id][0] + ans = next(obj for obj in resp.objects if obj.id == my_id) return ans async def begin_observing(self, cb): """ Get notified when a new object is added to the database. - cb : The callback that is called when a new object is added to the database + Args: + cb : The callback that is called when a new object is added to the database. """ self.new_object_subscriber = cb req = ObjectDBQueryRequest() @@ -78,6 +117,12 @@ async def begin_observing(self, cb): self.new_object_subscriber(o) async def get_unknown_and_low_conf(self): + """ + Gets unknown objects that are of low confidence. + + Returns: + Objects that meet certain criteria. + """ req = ObjectDBQueryRequest() req.name = "all" resp = await self._database(req) @@ -91,9 +136,21 @@ async def get_unknown_and_low_conf(self): return m def set_looking_for(self, name): + """ + Setting to a name that is being looked for. + + Args: + name (string): name of the object. + """ self.looking_for = name - def is_found_func(self): + def is_found_func(self) -> bool: + """ + Determines whether the object is being found or not. + + Returns: + The existence of the object is returned. + """ if self.is_found: self.looking_for = None self.is_found = False @@ -101,7 +158,12 @@ def is_found_func(self): return False def object_cb(self, perception_objects): - """Callback for the object database.""" + """ + Callback for the object database. + + Args: + perception_objects (object): a list of objects that are passed. + """ self.total_num = len(perception_objects.objects) for o in perception_objects.objects: if o.name == self.looking_for: @@ -120,12 +182,23 @@ def object_cb(self, perception_objects): self.ensuring_object_cb(missings_objs) def remove_found(self, name): - """Remove an object that has been listed as found.""" + """ + Remove an object that has been listed as found. + + Args: + name (string): a name of the object is being passed in. + """ self.found.remove(name) def ensure_object_permanence(self, object_dep, cb): - """Ensure that all the objects in the object_dep list remain in the database. - Call the callback if this isn't true.""" + """ + Ensure that all the objects in the object_dep list remain in the database. + Call the callback if this isn't true. + + Args: + object_dep: a new object is passed in order to be set. + cb : The callback that is called when a new object is added to the database. + """ if object_dep is None or cb is None: return self.ensuring_objects = True @@ -133,10 +206,21 @@ def ensure_object_permanence(self, object_dep, cb): self.ensuring_object_dep = object_dep def stop_ensuring_object_permanence(self): - """Stop ensuring that objects remain in the database.""" + """ + Stop ensuring that objects remain in the database. + """ self.ensuring_objects = False - def _wait_for_position(self, timeout=10): + def _wait_for_position(self, timeout=10) -> bool: + """ + A possible position is being stored in a variable. + + Args: + timeout (int): time limit to retrieve something. + + Returns: + bool: Determines whether the position is found within the time limit. + """ count = 0 while self.position is None: if self.navigator is not None: @@ -148,7 +232,15 @@ def _wait_for_position(self, timeout=10): return True async def get_closest_object(self, objects): - """Get the closest mission.""" + """ + Get the closest mission. + + Args: + objects (object): a list of objects are being passed in. + + Returns: + A object with the closest mission / distance is returned. + """ pobjs = [] for obj in objects: req = ObjectDBQueryRequest() @@ -171,6 +263,15 @@ async def get_closest_object(self, objects): return min_obj async def _dist(self, x): + """ + Finds the distance of the object keeping into account its current position. + + Args: + x (object): a specific object is being passed in order to retrieve its position. + + Returns: + the distance between the two objects is being returned. + """ if self.position is None: success = asyncio.create_task(self._wait_for_position) if not success: @@ -188,7 +289,18 @@ async def get_object( thresh=50, thresh_strict=50, ): - """Get an object from the database.""" + """ + Get an object from the database. + + Args: + object_name (string): the name of the object is passed in. + volume_only (bool): determines whether it is volume-based or not. + thresh (int): a maximum distance is passed in. + thresh_strict(int): a more strict maximum distance is passed in. + + Returns: + closest_potential_object (object): returns the object that is within the closest range. + """ if volume_only: req = ObjectDBQueryRequest() req.name = object_name @@ -233,6 +345,15 @@ async def get_object( return closest_potential_object def wait_for_additional_objects(self, timeout=60): + """ + Returns true/false whether additional objects are being passed in. + + Args: + timeout (int): maximum time limit of 60 seconds to run the program. + + Returns: + (bool): determines whether additional objects are added. + """ num_items = self.num_items start = time.time() while timeout < time.time() - start: @@ -241,14 +362,36 @@ def wait_for_additional_objects(self, timeout=60): return False def set_color(self, color, name): - """Set the color of an object in the database.""" + """ + Sets the color of an object in the database. + + Args: + color: the new color of the object is passed in. + name: the name of the object is passed in. + """ raise NotImplementedError def set_fake_position(self, pos): - """Set the position of a fake perception object.""" + """ + Sets the position of a fake perception object. + + Args: + pos (int): the new position of the object is passed in. + """ raise NotImplementedError async def get_objects_in_radius(self, pos, radius, objects="all"): + """ + Retrieves the objects that are present within the radius. + + Args: + pos (int): the position of the object is passed in. + radius (int): the radius of the object is passed in. + objects (object): this is a list of all the objects that needs to be compared. + + Returns: + ans (object): returns the objects that are present within the radius. + """ req = ObjectDBQueryRequest() req.name = "all" resp = await self._database(req) diff --git a/NaviGator/utils/navigator_tools/nodes/estimated_object_setter.py b/NaviGator/utils/navigator_tools/nodes/estimated_object_setter.py index 99845b004..57d4b7c01 100755 --- a/NaviGator/utils/navigator_tools/nodes/estimated_object_setter.py +++ b/NaviGator/utils/navigator_tools/nodes/estimated_object_setter.py @@ -24,7 +24,7 @@ async def main(name, lla): name = "_".join(txt.title() for txt in name.split("_")) point = await convert.request(CoordinateConversionRequest(frame="lla", point=lla)) - await db(ObjectDBQueryRequest(cmd="{}={p[0]}, {p[1]}".format(name, p=point.enu))) + await db(ObjectDBQueryRequest(cmd=f"{name}={point.enu[0]}, {point.enu[1]}")) if __name__ == "__main__": diff --git a/NaviGator/utils/navigator_tools/nodes/navigator_status_tui b/NaviGator/utils/navigator_tools/nodes/navigator_status_tui index 3efa0a5d1..0fc39eb3b 100755 --- a/NaviGator/utils/navigator_tools/nodes/navigator_status_tui +++ b/NaviGator/utils/navigator_tools/nodes/navigator_status_tui @@ -35,7 +35,7 @@ class nav_tui: self.panel.hide() panel.update_panels() self.rate = rospy.Rate(2) # Fixed rate for while loop to update at: 2 hz - # The following are default field initalizations for various values that that will be overwritten + # The following are default field initializations for various values that that will be overwritten self.voltage = 0 self.wrench = None self.LAT = None @@ -214,15 +214,13 @@ class nav_tui: if len(self.decode_fault_status(self.FL_fault)) == 0: self.window.addstr(5, self.x / 2 - 7, "No faults", curses.color_pair(3)) else: - n = 0 - for fault in self.decode_fault_status(self.FL_fault): + for n, fault in enumerate(self.decode_fault_status(self.FL_fault)): self.window.addstr( 5 + n, self.x / 2 - 7, "%s" % fault, curses.color_pair(1), ) - n += 1 self.window.addstr(14, self.x / 2 - 7, "Back Left", color) if len(self.decode_fault_status(self.BL_fault)) == 0: diff --git a/NaviGator/utils/remote_control/navigator_emergency_control/nodes/navigator_emergency.py b/NaviGator/utils/remote_control/navigator_emergency_control/nodes/navigator_emergency.py index 8077b4601..49b799fa4 100755 --- a/NaviGator/utils/remote_control/navigator_emergency_control/nodes/navigator_emergency.py +++ b/NaviGator/utils/remote_control/navigator_emergency_control/nodes/navigator_emergency.py @@ -67,8 +67,7 @@ def reset(self) -> None: def check_for_timeout(self, joy: Joy): """ - Consists of several procedures that reference parameters that are retrieved from the "Joy" object in - order to determine the state of the controller or whether it is a timeout phase. + This checks for a particular duration when the controller times out. Args: joy (Joy): The Joy message. @@ -95,7 +94,7 @@ def check_for_timeout(self, joy: Joy): def joy_recieved(self, joy: Joy) -> None: """ - Button elements are being assigned and simplied to readable names. The + Button elements are being assigned and simplified to readable names. The number of deployments or retractions for thrusters are being updated based on several conditions. Moreover, additional settings are changed based on the state of the controller and the activation of potential alarms or switches. diff --git a/NaviGator/utils/voltage_gui/src/voltage_gui.py b/NaviGator/utils/voltage_gui/src/voltage_gui.py index 932dbc22b..79e6a0e85 100644 --- a/NaviGator/utils/voltage_gui/src/voltage_gui.py +++ b/NaviGator/utils/voltage_gui/src/voltage_gui.py @@ -184,7 +184,7 @@ def resizeFont(self) -> None: # done threshFont = QtGui.QFont("Times", (self.fontSize) / 3, QtGui.QFont.Bold) self.labelThresh.setFont(threshFont) - # Sets the text of the thrshold info box + # Sets the text of the threshold info box def initThresh(self) -> None: """ Sets the text of the threshold info box diff --git a/SubjuGator/command/subjugator_alarm/alarm_handlers/kill.py b/SubjuGator/command/subjugator_alarm/alarm_handlers/kill.py index 4781a760a..4055694d8 100644 --- a/SubjuGator/command/subjugator_alarm/alarm_handlers/kill.py +++ b/SubjuGator/command/subjugator_alarm/alarm_handlers/kill.py @@ -101,10 +101,7 @@ def _bag_done_cb(self, status, result): rospy.loginfo(f"KILL BAG WRITTEN TO {result.filename}") else: rospy.logwarn( - "KILL BAG {}, status: {}".format( - TerminalState.to_string(status), - result.status, - ), + f"KILL BAG {TerminalState.to_string(status)}, status: {result.status}", ) def bagger_dump(self): diff --git a/SubjuGator/command/subjugator_alarm/alarm_handlers/odom_kill.py b/SubjuGator/command/subjugator_alarm/alarm_handlers/odom_kill.py index 4a7638909..90a8e817b 100644 --- a/SubjuGator/command/subjugator_alarm/alarm_handlers/odom_kill.py +++ b/SubjuGator/command/subjugator_alarm/alarm_handlers/odom_kill.py @@ -101,9 +101,7 @@ def check_continuity(self, new_odom_msg: Odometry): # True if 'continuous' if jump > self.MAX_JUMP: rospy.logerr("ODOM DISCONTINUITY DETECTED") self.ab.raise_alarm( - problem_description="ODOM DISCONTINUITY DETECTED JUMPED {} METERS".format( - jump, - ), + problem_description=f"ODOM DISCONTINUITY DETECTED JUMPED {jump} METERS", severity=5, ) self.odom_discontinuity = True @@ -120,9 +118,7 @@ def need_kill(self): if odom_loss: rospy.logerr_throttle( 1, - "LOST ODOM FOR {} SECONDS".format( - (rospy.Time.now() - self.last_time).to_sec(), - ), + f"LOST ODOM FOR {(rospy.Time.now() - self.last_time).to_sec()} SECONDS", ) self.ab.raise_alarm( problem_description="LOST ODOM FOR {} SECONDS".format( diff --git a/SubjuGator/command/subjugator_keyboard_control/teleop_twist_keyboard.py b/SubjuGator/command/subjugator_keyboard_control/teleop_twist_keyboard.py index ea5c7bedb..870df6ac7 100755 --- a/SubjuGator/command/subjugator_keyboard_control/teleop_twist_keyboard.py +++ b/SubjuGator/command/subjugator_keyboard_control/teleop_twist_keyboard.py @@ -141,9 +141,7 @@ def wait_for_subscribers(self): while not rospy.is_shutdown() and self.publisher.get_num_connections() == 0: if i == 4: print( - "Waiting for subscriber to connect to {}".format( - self.publisher.name, - ), + f"Waiting for subscriber to connect to {self.publisher.name}", ) rospy.sleep(0.5) i += 1 diff --git a/SubjuGator/command/subjugator_launch/config/passive_sonar.yaml b/SubjuGator/command/subjugator_launch/config/passive_sonar.yaml index 9901f9703..e55aec3da 100644 --- a/SubjuGator/command/subjugator_launch/config/passive_sonar.yaml +++ b/SubjuGator/command/subjugator_launch/config/passive_sonar.yaml @@ -3,7 +3,7 @@ dist_h: 2.286e-02 # speed of sound in water v_sound: 1482 -# target Frquency in Hz +# target Frequency in Hz triggering/target_frequency: 30000 # tolerance around target frequerncy in Hz triggering/frequency_tolerance: 100 diff --git a/SubjuGator/command/subjugator_launch/launch/subsystems/nav_box.launch b/SubjuGator/command/subjugator_launch/launch/subsystems/nav_box.launch index eb5e1bc31..3dee6ee81 100644 --- a/SubjuGator/command/subjugator_launch/launch/subsystems/nav_box.launch +++ b/SubjuGator/command/subjugator_launch/launch/subsystems/nav_box.launch @@ -42,10 +42,10 @@ scale: - - [0.993770963897068, 0.00105871125374563, 7.659410525291767e-05] - - [0.00105871125374563, 0.9996814868251349, -0.0011040738267441828] - - [7.659410525291767e-05, -0.001104073826744163, 1.0065910531028952] - shift: [1.2551999807772446e-06, -1.1666595150804588e-06, 6.895773090438596e-08] + - [0.9991765357958566, 0.006242798579443988, -0.008472478269327878] + - [0.006242798579443957, 1.0016179705091928, 0.0059841151097914345] + - [-0.008472478269327836, 0.0059841151097913, 0.999354597532967] + shift: [7.889247409445414e-06, 4.879179471165382e-06, 7.46017199298374e-06] diff --git a/SubjuGator/command/subjugator_missions/subjugator_missions/arm_torpedos.py b/SubjuGator/command/subjugator_missions/subjugator_missions/arm_torpedos.py index aad130049..7a88e8908 100644 --- a/SubjuGator/command/subjugator_missions/subjugator_missions/arm_torpedos.py +++ b/SubjuGator/command/subjugator_missions/subjugator_missions/arm_torpedos.py @@ -170,9 +170,7 @@ async def fire(self, target: str): ) self.print_good( - "{} locked. Firing torpedoes. Hit confirmed, good job Commander.".format( - target, - ), + f"{target} locked. Firing torpedoes. Hit confirmed, good job Commander.", ) sub_pos = await self.tx_pose() print("Current Sub Position: ", sub_pos) diff --git a/SubjuGator/command/subjugator_missions/subjugator_missions/pose_editor.py b/SubjuGator/command/subjugator_missions/subjugator_missions/pose_editor.py index 6eafca064..ee2562491 100644 --- a/SubjuGator/command/subjugator_missions/subjugator_missions/pose_editor.py +++ b/SubjuGator/command/subjugator_missions/subjugator_missions/pose_editor.py @@ -617,8 +617,8 @@ def as_PoseTwist( def as_PoseTwistStamped( self, - linear: Sequence[int] = [0, 0, 0], - angular: Sequence[int] = [0, 0, 0], + linear: Sequence[float] = [0, 0, 0], + angular: Sequence[float] = [0, 0, 0], ) -> PoseTwistStamped: """ Returns a :class:`~mil_msgs.msg.PoseTwist` message class with the pose @@ -639,8 +639,8 @@ def as_PoseTwistStamped( def as_MoveToGoal( self, - linear: Sequence[int] = [0, 0, 0], - angular: Sequence[int] = [0, 0, 0], + linear: Sequence[float] = [0, 0, 0], + angular: Sequence[float] = [0, 0, 0], **kwargs, ) -> MoveToGoal: return MoveToGoal( diff --git a/SubjuGator/command/subjugator_missions/subjugator_missions/start_gate.py b/SubjuGator/command/subjugator_missions/subjugator_missions/start_gate.py index f395bd1e0..0886298e1 100644 --- a/SubjuGator/command/subjugator_missions/subjugator_missions/start_gate.py +++ b/SubjuGator/command/subjugator_missions/subjugator_missions/start_gate.py @@ -160,9 +160,7 @@ def find_gate( p2 = rosmsg_to_numpy(o2.pose.position) if distance.euclidean(p, p2) > max_distance_away: fprint( - "Poles too far away. Distance {}".format( - distance.euclidean(p, p2), - ), + f"Poles too far away. Distance {distance.euclidean(p, p2)}", ) continue if distance.euclidean(p, p2) < min_distance_away: @@ -180,10 +178,7 @@ def find_gate( continue if abs(line[0]) < 1 and abs(line[1]) < 1: fprint( - "Objects on top of one another. x {}, y {}".format( - line[0], - line[1], - ), + f"Objects on top of one another. x {line[0]}, y {line[1]}", ) continue return (p, p2) diff --git a/SubjuGator/command/subjugator_missions/subjugator_missions/sub_singleton.py b/SubjuGator/command/subjugator_missions/subjugator_missions/sub_singleton.py index 693fc3bd7..8e498fc4d 100644 --- a/SubjuGator/command/subjugator_missions/subjugator_missions/sub_singleton.py +++ b/SubjuGator/command/subjugator_missions/subjugator_missions/sub_singleton.py @@ -599,7 +599,7 @@ async def start_search_in_cone( distance_tol: float = 10, speed: float = 0.5, clear: bool = False, - c_func: Callable = None, + c_func: Callable | None = None, ): if clear: print("SONAR_OBJECTS: clearing pointcloud") diff --git a/SubjuGator/drivers/magnetic_compensation/sub8_magnetic_hardsoft_compensation/scripts/generate_config b/SubjuGator/drivers/magnetic_compensation/sub8_magnetic_hardsoft_compensation/scripts/generate_config index 5d12dad06..342292350 100755 --- a/SubjuGator/drivers/magnetic_compensation/sub8_magnetic_hardsoft_compensation/scripts/generate_config +++ b/SubjuGator/drivers/magnetic_compensation/sub8_magnetic_hardsoft_compensation/scripts/generate_config @@ -9,6 +9,7 @@ import rosbag import roslib import scipy.linalg import yaml +from mpl_toolkits.mplot3d import Axes3D from tf import transformations roslib.load_manifest("magnetic_hardsoft_compensation") @@ -20,7 +21,7 @@ def normalized_matrix(m): def calculate_error(points): - radii = map(numpy.linalg.norm, points) + radii = list(map(numpy.linalg.norm, points)) error = numpy.std(radii) / numpy.mean(radii) return error @@ -47,7 +48,7 @@ def fit_ellipsoid(points): B = numpy.ones((points.shape[0], 1)) - X = numpy.linalg.lstsq(A, B)[0].flatten() + X = numpy.linalg.lstsq(A, B, rcond=-1)[0].flatten() if X[0] < 0: X = -X # make sure ka turns out positive definite @@ -110,9 +111,7 @@ def test(): assert numpy.allclose( shift2, shift, - ), "Magnetic Hardsoft Compenstion self-test failed, shifts: {}".format( - (shift2, shift), - ) + ), f"Magnetic Hardsoft Compenstion self-test failed, shifts: {(shift2, shift)}" assert ( error < 1e-5 ), f"Magnetic Hardsoft Compenstion self-test failed, error: {error}" @@ -133,9 +132,11 @@ if __name__ == "__main__": with rosbag.Bag(sys.argv[1]) as bag: points = numpy.array( [ - mil_ros_tools.rosmsg_to_numpy(msg.magnetic_field) - if hasattr(msg, "magnetic_field") - else mil_ros_tools.rosmsg_to_numpy(msg.vector) + ( + mil_ros_tools.rosmsg_to_numpy(msg.magnetic_field) + if hasattr(msg, "magnetic_field") + else mil_ros_tools.rosmsg_to_numpy(msg.vector) + ) for topic, msg, t in bag.read_messages(topics=["/imu/mag_raw"]) ], ) @@ -152,7 +153,7 @@ if __name__ == "__main__": import matplotlib.pyplot as plt fig = plt.figure(figsize=(10, 10)) - ax = fig.add_subplot("111", projection="3d") + ax = Axes3D(fig) ax.scatter([0], [0], [0], s=100, c="r") ax.scatter(*zip(*points[::10, :])) axisEqual3D(ax) @@ -170,7 +171,7 @@ if __name__ == "__main__": import matplotlib.pyplot as plt fig = plt.figure(figsize=(10, 10)) - ax = fig.add_subplot("111", projection="3d") + ax = Axes3D(fig) ax.scatter([0], [0], [0], s=100, c="r") ax.scatter(*zip(*points[::10, :])) ax.scatter(*zip(*compensated[::10, :]), c="g") @@ -185,8 +186,8 @@ if __name__ == "__main__": print( yaml.dump( { - "scale": (map(float, x) for x in scale), - "shift": map(float, shift), + "scale": scale.tolist(), + "shift": shift.tolist(), }, ), ) diff --git a/SubjuGator/drivers/sub8_thrust_and_kill_board/sub8_thrust_and_kill_board/handle.py b/SubjuGator/drivers/sub8_thrust_and_kill_board/sub8_thrust_and_kill_board/handle.py index c62f5732b..19df02c33 100644 --- a/SubjuGator/drivers/sub8_thrust_and_kill_board/sub8_thrust_and_kill_board/handle.py +++ b/SubjuGator/drivers/sub8_thrust_and_kill_board/sub8_thrust_and_kill_board/handle.py @@ -109,9 +109,7 @@ def on_command(self, msg: Thrust) -> None: # If we don't have a mapping for this thruster, ignore it if cmd.name not in self.thrusters: rospy.logwarn( - "Command received for {}, but this is not a thruster.".format( - cmd.name, - ), + f"Command received for {cmd.name}, but this is not a thruster.", ) continue # Map commanded thrust (in newetons) to effort value (-1 to 1) diff --git a/SubjuGator/drivers/sub8_thrust_and_kill_board/sub8_thrust_and_kill_board/packets.py b/SubjuGator/drivers/sub8_thrust_and_kill_board/sub8_thrust_and_kill_board/packets.py index 8cc3a0f27..dcd1aaa0b 100644 --- a/SubjuGator/drivers/sub8_thrust_and_kill_board/sub8_thrust_and_kill_board/packets.py +++ b/SubjuGator/drivers/sub8_thrust_and_kill_board/sub8_thrust_and_kill_board/packets.py @@ -287,7 +287,4 @@ def command(self) -> float: return struct.unpack("f", self.payload[1:])[0] def __str__(self): - return "ThrustPacket(thruster_id={}, command={})".format( - self.thruster_id, - self.command, - ) + return f"ThrustPacket(thruster_id={self.thruster_id}, command={self.command})" diff --git a/SubjuGator/drivers/sub8_thrust_and_kill_board/sub8_thrust_and_kill_board/simulation.py b/SubjuGator/drivers/sub8_thrust_and_kill_board/sub8_thrust_and_kill_board/simulation.py index 5f9d0f01f..83c595815 100644 --- a/SubjuGator/drivers/sub8_thrust_and_kill_board/sub8_thrust_and_kill_board/simulation.py +++ b/SubjuGator/drivers/sub8_thrust_and_kill_board/sub8_thrust_and_kill_board/simulation.py @@ -156,4 +156,4 @@ def on_data(self, data: bytes, can_id: int) -> None: packet = HeartbeatMessage.from_bytes(data) self._last_heartbeat = rospy.Time.now() else: - assert False, "No recognized identifier" + raise Exception("No recognized identifier") diff --git a/SubjuGator/etc/motd b/SubjuGator/etc/motd new file mode 100644 index 000000000..bf6bb0855 --- /dev/null +++ b/SubjuGator/etc/motd @@ -0,0 +1,9 @@ +#-------#-------#-------#-------#-------#-------#-------#-------# + You have connected to SubjuGator 8! +#-------#-------#-------#-------#-------#-------#-------#-------# + +If you are testing the sub in the water (or are preparing to do so), please make sure to read the Subjugator Testing Procedures page on uf-mil.github.io for useful tips, advice, and checklists. + +We (the previous MIL members) will watch your testing session with great interest. + +Happy Testing! diff --git a/SubjuGator/perception/subjugator_perception/ml_classifiers/path_marker/path_localizer.py b/SubjuGator/perception/subjugator_perception/ml_classifiers/path_marker/path_localizer.py index 29665f12a..c70e5e258 100755 --- a/SubjuGator/perception/subjugator_perception/ml_classifiers/path_marker/path_localizer.py +++ b/SubjuGator/perception/subjugator_perception/ml_classifiers/path_marker/path_localizer.py @@ -17,7 +17,7 @@ rospack.get_path("subjugator_perception") + "/ml_classifiers/path_marker/utils", ) -from utils import detector_utils # noqa: manually appending sys.path +from utils import detector_utils # noqa class classifier: diff --git a/SubjuGator/perception/subjugator_perception/nodes/dice_detect.py b/SubjuGator/perception/subjugator_perception/nodes/dice_detect.py index 55d1dd5e2..312123597 100755 --- a/SubjuGator/perception/subjugator_perception/nodes/dice_detect.py +++ b/SubjuGator/perception/subjugator_perception/nodes/dice_detect.py @@ -93,7 +93,7 @@ def detect(self, dice_img): params.minConvexity = 0.8 # 1 = perfect convex hull # Filter by Inertia params.filterByInertia = True - params.minInertiaRatio = 0.4 # Defines the ellipsoid 1= detects only cirlces + params.minInertiaRatio = 0.4 # Defines the ellipsoid 1= detects only circles # 0 = Detects even lines # Create a detector with the parameters diff --git a/SubjuGator/perception/subjugator_perception/nodes/hsv_calibration.py b/SubjuGator/perception/subjugator_perception/nodes/hsv_calibration.py index 4a67f4bb7..433133431 100755 --- a/SubjuGator/perception/subjugator_perception/nodes/hsv_calibration.py +++ b/SubjuGator/perception/subjugator_perception/nodes/hsv_calibration.py @@ -36,13 +36,17 @@ def parse_string(threshes): def reconfigure(self, config, level): try: self.lower = np.array(self.parse_string(config["dyn_lower"])) - rospy.logwarn("HSV lower bound below minimum value") if ( - self.lower < 0 - ).any() else None + ( + rospy.logwarn("HSV lower bound below minimum value") + if (self.lower < 0).any() + else None + ) self.upper = np.array(self.parse_string(config["dyn_upper"])) - rospy.logwarn("HSV upper bound above maximum values") if ( - self.upper[0] > 179 - ).any() or (self.upper[1:] > 255).any() else None + ( + rospy.logwarn("HSV upper bound above maximum values") + if (self.upper[0] > 179).any() or (self.upper[1:] > 255).any() + else None + ) except ValueError as e: rospy.logwarn(f"Invalid dynamic reconfigure: {e}") diff --git a/SubjuGator/perception/subjugator_perception/nodes/orange_rectangle_finder.py b/SubjuGator/perception/subjugator_perception/nodes/orange_rectangle_finder.py index 0701c3b05..237fe94e3 100755 --- a/SubjuGator/perception/subjugator_perception/nodes/orange_rectangle_finder.py +++ b/SubjuGator/perception/subjugator_perception/nodes/orange_rectangle_finder.py @@ -52,7 +52,7 @@ class OrangeRectangleFinder: * Transform this frames pose into /map frame * Plug this frames pose in /map into a kalman filter to reduce noise - TODO: Allow for two objects to be identifed at once, both filtered through its own KF + TODO: Allow for two objects to be identified at once, both filtered through its own KF """ # Coordinate axes for debugging image diff --git a/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/HOG/HOG_SVM_trainer.py b/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/HOG/HOG_SVM_trainer.py index bbdb7aefb..01e85b3a2 100644 --- a/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/HOG/HOG_SVM_trainer.py +++ b/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/HOG/HOG_SVM_trainer.py @@ -16,8 +16,7 @@ class_list = np.array(0) # loop through the training images -count = 0 -for i in os.listdir(os.path.abspath(folder)): +for count, i in enumerate(os.listdir(os.path.abspath(folder))): # get the roi from the file path = folder + "/" + i roi_str = f.readline() @@ -72,7 +71,6 @@ class_temp = np.empty(len_myinvhog / 9) class_temp.fill(-1) class_list = np.append(class_list, class_temp) - count += 1 # hack class_list = np.delete(class_list, [0]) diff --git a/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/machine_learning/boost_auto.py b/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/machine_learning/boost_auto.py index c9027ff60..c1cf17e1a 100644 --- a/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/machine_learning/boost_auto.py +++ b/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/machine_learning/boost_auto.py @@ -100,10 +100,11 @@ def train_on_data(observation_list, label_list, split_factor=4): s_time = time.time() process_round = 0 # Split this into multiple passes in an attempt to free RAM (no idea if this works). - for x, y in zip(all_observations_split, all_labels_split): + for process_round, (x, y) in enumerate( + zip(all_observations_split, all_labels_split), + ): print(f"Training subset {process_round + 1}/{split_factor}.") boost.train(x, cv2.CV_ROW_SAMPLE, y, params=parameters) - process_round += 1 print(f"Time to complete: {time.time() - s_time}") print("Done! Saving...") diff --git a/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/marker_occ_grid.py b/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/marker_occ_grid.py index 9261de0ac..c547f7847 100644 --- a/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/marker_occ_grid.py +++ b/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/marker_occ_grid.py @@ -174,7 +174,7 @@ def return_pose(self, srv): self.poly_generator = self.polygon_generator() return [0, False, srv.intial_position] - # We search at 1.5 * r so that there is some overlay in the search feilds. + # We search at 1.5 * r so that there is some overlay in the search fields. np_pose = msg_helpers.pose_to_numpy(srv.intial_position) rot_mat = make_2D_rotation( tf.transformations.euler_from_quaternion(np_pose[1])[2], @@ -249,7 +249,6 @@ def polygon_generator(self, n=12): class MarkerOccGrid(OccGridUtils): - """ Handles updating occupancy grid when new data comes in. TODO: Upon call can return some path to go to in order to find them. diff --git a/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/rviz.py b/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/rviz.py index c46dd18ea..e6af8929a 100644 --- a/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/rviz.py +++ b/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/rviz.py @@ -9,7 +9,6 @@ class RvizVisualizer: - """Cute tool for drawing both depth and height-from-bottom in RVIZ""" def __init__(self, topic="visualization/markers"): diff --git a/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/visual_threshold_tools.py b/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/visual_threshold_tools.py index 7ec7d04c9..f30275cfc 100644 --- a/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/visual_threshold_tools.py +++ b/SubjuGator/perception/subjugator_perception/subjugator_vision_tools/visual_threshold_tools.py @@ -63,7 +63,6 @@ def denormalize(val, _min, _max): class ExtentDialog(traits.api.HasTraits): - """A dialog to graphically adjust the extents of a threshold range""" # Data extents diff --git a/SubjuGator/perception/subjugator_perception/test/test_path_marker.py b/SubjuGator/perception/subjugator_perception/test/test_path_marker.py index 4f3a621cc..5674ddf5a 100755 --- a/SubjuGator/perception/subjugator_perception/test/test_path_marker.py +++ b/SubjuGator/perception/subjugator_perception/test/test_path_marker.py @@ -17,7 +17,6 @@ class TestPathMarker(unittest.TestCase): - """ Unit test for perception service finding orange path markers Plays several bags with known pixel coordinates of path marker, diff --git a/SubjuGator/simulation/subjugator_gazebo/diagnostics/gazebo_tests/common.py b/SubjuGator/simulation/subjugator_gazebo/diagnostics/gazebo_tests/common.py index de7bc39f0..38a5baf41 100644 --- a/SubjuGator/simulation/subjugator_gazebo/diagnostics/gazebo_tests/common.py +++ b/SubjuGator/simulation/subjugator_gazebo/diagnostics/gazebo_tests/common.py @@ -8,7 +8,6 @@ class Job: - """Inherit from this!""" _job_name = "generic job" diff --git a/SubjuGator/simulation/subjugator_gazebo/urdf/sub8.urdf.xacro b/SubjuGator/simulation/subjugator_gazebo/urdf/sub8.urdf.xacro index 9290884dd..3f4517335 100644 --- a/SubjuGator/simulation/subjugator_gazebo/urdf/sub8.urdf.xacro +++ b/SubjuGator/simulation/subjugator_gazebo/urdf/sub8.urdf.xacro @@ -11,8 +11,6 @@ - - @@ -33,11 +31,6 @@ - - - - - diff --git a/SubjuGator/simulation/subjugator_simulation/subjugator_sim_tools/shaders/shader_manager.py b/SubjuGator/simulation/subjugator_simulation/subjugator_sim_tools/shaders/shader_manager.py index edfb7d12f..192755207 100644 --- a/SubjuGator/simulation/subjugator_simulation/subjugator_sim_tools/shaders/shader_manager.py +++ b/SubjuGator/simulation/subjugator_simulation/subjugator_sim_tools/shaders/shader_manager.py @@ -36,7 +36,6 @@ def add_item(self, position, intensity): class ShaderManager: - """ This class is used when you want to have an entity switch out shaders at a specific time. If you want to add another rule for when to switch out shaders: diff --git a/SubjuGator/simulation/subjugator_simulation/subjugator_sim_tools/shaders/shaders.py b/SubjuGator/simulation/subjugator_simulation/subjugator_sim_tools/shaders/shaders.py index d4a2e1f62..210a68e8e 100644 --- a/SubjuGator/simulation/subjugator_simulation/subjugator_sim_tools/shaders/shaders.py +++ b/SubjuGator/simulation/subjugator_simulation/subjugator_sim_tools/shaders/shaders.py @@ -65,7 +65,6 @@ def recursive_dictionary(self, path, text): class Shaders: - """A Shaders class, which automatically contains all of the shaders in the shaders folder WTF? diff --git a/SubjuGator/simulation/subjugator_simulation/subjugator_sim_tools/widgets/sub.py b/SubjuGator/simulation/subjugator_simulation/subjugator_sim_tools/widgets/sub.py index cbb628bad..144ec195d 100644 --- a/SubjuGator/simulation/subjugator_simulation/subjugator_sim_tools/widgets/sub.py +++ b/SubjuGator/simulation/subjugator_simulation/subjugator_sim_tools/widgets/sub.py @@ -83,7 +83,6 @@ def make_visual(self, physical, position, thrust_indicators=False): ) class ThrustGetter: - """This is a pretty garbage thing, and will be replaced by the scenegraph system""" def __init__(self, thruster_name, rdir): diff --git a/SubjuGator/utils/subjugator_diagnostics/scripts/self_check.py b/SubjuGator/utils/subjugator_diagnostics/scripts/self_check.py index 2552541cc..4db32b96c 100755 --- a/SubjuGator/utils/subjugator_diagnostics/scripts/self_check.py +++ b/SubjuGator/utils/subjugator_diagnostics/scripts/self_check.py @@ -18,7 +18,6 @@ class TemplateChecker: - """Template for how each checker class should look. This provides interface functions for the main function to use. You don't have to implement them all in each checker. diff --git a/docs/design/passive_sonar/passive_sonar.rst b/docs/design/passive_sonar/passive_sonar.rst index 522368705..6f23f38ab 100644 --- a/docs/design/passive_sonar/passive_sonar.rst +++ b/docs/design/passive_sonar/passive_sonar.rst @@ -78,8 +78,8 @@ Configuration ************* All parameters that are expected to be changed in tuining are ROS Params initialized in ``passive_sonar.yaml`` -To make a custom configation -^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +To make a custom configuration +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * ``roscd subjugator_launch`` diff --git a/docs/electrical/onboarding.md b/docs/electrical/onboarding.md index c48026aaa..45d73e7a7 100644 --- a/docs/electrical/onboarding.md +++ b/docs/electrical/onboarding.md @@ -20,7 +20,7 @@ including meeting times. ## Join the electrical GitHub Unlike the software and mechanical teams (who share a GitHub repository), we use -a separate repository for the electrical team. As a resut, you will need to be added +a separate repository for the electrical team. As a result, you will need to be added to this organization. Once you're in Slack (or you've come to the lab), ask an electrical leader to add you to the GitHub organization. The organization can be found [here](https://github.com/uf-mil-electrical). diff --git a/docs/extensions/attributetable.py b/docs/extensions/attributetable.py index bfee064d7..53372cb61 100644 --- a/docs/extensions/attributetable.py +++ b/docs/extensions/attributetable.py @@ -2,6 +2,7 @@ Credit goes to discord.py and its creators for creating most of this file: https://github.com/Rapptz/discord.py/blob/master/docs/extensions/attributetable.py """ + import importlib import inspect import re diff --git a/docs/extensions/builder.py b/docs/extensions/builder.py index 84de6d59d..881417afc 100644 --- a/docs/extensions/builder.py +++ b/docs/extensions/builder.py @@ -2,6 +2,7 @@ Credit goes to discord.py and its creators for creating most of this file: https://github.com/Rapptz/discord.py/blob/master/docs/extensions/attributetable.py """ + from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.environment.adapters.indexentries import IndexEntries from sphinx.writers.html5 import HTML5Translator diff --git a/docs/images/gazebo/Bottom_Toolbar.png b/docs/images/gazebo/Bottom_Toolbar.png new file mode 100644 index 000000000..de1fb6d98 Binary files /dev/null and b/docs/images/gazebo/Bottom_Toolbar.png differ diff --git a/docs/images/gazebo/Interface.png b/docs/images/gazebo/Interface.png new file mode 100644 index 000000000..b6f5018c4 Binary files /dev/null and b/docs/images/gazebo/Interface.png differ diff --git a/docs/images/gazebo/Labeled_Interface.png b/docs/images/gazebo/Labeled_Interface.png new file mode 100644 index 000000000..871ddca52 Binary files /dev/null and b/docs/images/gazebo/Labeled_Interface.png differ diff --git a/docs/images/gazebo/Menus.png b/docs/images/gazebo/Menus.png new file mode 100644 index 000000000..d6c39d62e Binary files /dev/null and b/docs/images/gazebo/Menus.png differ diff --git a/docs/images/gazebo/Model_Editor.png b/docs/images/gazebo/Model_Editor.png new file mode 100644 index 000000000..362f7cb16 Binary files /dev/null and b/docs/images/gazebo/Model_Editor.png differ diff --git a/docs/images/gazebo/Mouse.png b/docs/images/gazebo/Mouse.png new file mode 100644 index 000000000..728c8fc8f Binary files /dev/null and b/docs/images/gazebo/Mouse.png differ diff --git a/docs/images/gazebo/TrackPad.png b/docs/images/gazebo/TrackPad.png new file mode 100644 index 000000000..1231be57b Binary files /dev/null and b/docs/images/gazebo/TrackPad.png differ diff --git a/docs/images/gazebo/Upper_Toolbar.png b/docs/images/gazebo/Upper_Toolbar.png new file mode 100644 index 000000000..68e36e69a Binary files /dev/null and b/docs/images/gazebo/Upper_Toolbar.png differ diff --git a/docs/indyav/software/planning/indyav_path/path_recorder.rst b/docs/indyav/software/planning/indyav_path/path_recorder.rst index 77c3d4ee3..d1b5f1a47 100644 --- a/docs/indyav/software/planning/indyav_path/path_recorder.rst +++ b/docs/indyav/software/planning/indyav_path/path_recorder.rst @@ -33,7 +33,7 @@ Basic Usage Example - Visualize this new topic in rviz by clicking `Add` and then `/odom2 -> Odometry` -- Watch the red arrow advance from where the sub started to where the sub stopped updting approximately 10 times a second. +- Watch the red arrow advance from where the sub started to where the sub stopped updating approximately 10 times a second. Source Files ^^^^^^^^^^^^ diff --git a/docs/navigator/lessons22.md b/docs/navigator/lessons22.md index 1c92fc298..25607540e 100644 --- a/docs/navigator/lessons22.md +++ b/docs/navigator/lessons22.md @@ -62,7 +62,7 @@ future teams to learn from! It is quicker to tell when tools have gone missing (as each tool now has a dedicated spot in the organizer), and which tool is missing. Furthermore, it becomes easier for software members, electrical members, and mentors to find - tools, even if they maybe are not acquianted with a deep knowledge of the + tools, even if they maybe are not acquainted with a deep knowledge of the mechanical team. * **Focus on bringing less and staying more organized.** - At RobotX 2022, we were one of the teams who had brought the most equipment, yet we had a hard diff --git a/docs/software/adding_documentation.md b/docs/software/adding_documentation.md index cc1a1fd46..d91bf76e3 100644 --- a/docs/software/adding_documentation.md +++ b/docs/software/adding_documentation.md @@ -100,5 +100,5 @@ $ ./scripts/build_docs --scratch ``` ## Contributing changes -Now that you have made and verifed your changes, follow the [contributing guide](contributing) +Now that you have made and verified your changes, follow the [contributing guide](contributing) to add your changes to the repository. diff --git a/docs/software/gazebo_guide.md b/docs/software/gazebo_guide.md new file mode 100644 index 000000000..752147b10 --- /dev/null +++ b/docs/software/gazebo_guide.md @@ -0,0 +1,327 @@ +# Gazebo Guide + +This is a guide on how to use Gazebo, including launching the sub and +viewing it inside Gazebo, how Gazebo can be controlled and manipulated, how to +use Gazebo to make world files, and where you can find more info on Gazebo. + +## Brief Introduction + +Gazebo is an open-source 3D dynamic simulator, that allows us to design, model, +and test robots and their behavior in a virtual world. Similar to game engines +like Unity, Gazebo takes in scripts and models and performs physics simulations +on them. While it is similar, Gazebo offers physics simulations at a higher level +of fidelity, a suite of sensors, and interfaces for both users and programs. + +There are many versions of Gazebo, but this guide was written for **Gazebo +Classic 11** as this is the version of Gazebo currently being used at MIL. + +### Running Gazebo + +There are many ways run Gazebo. + +* Click the "Show Applications" button on Ubuntu (the apps button located in + the bottom left corner). Then search for the Gazebo Icon and press that icon + to open Gazebo. + +* You can press Alt + F2 (or Alt+Fn+F2) to bring up the "Run a Command" window. + Then type "gazebo" and press Enter to open Gazebo. + +* You can also open a terminal and type "gazebo" and it will open Gazebo. + +To launch Gazebo will all the necessary files for simulating Subjugator, +follow these steps: + +1. Open a terminal window and execute the following command. This command uses + ROS to start all the relevant ROS nodes and to load the world file for + subjugator. This also starts a Gazebo Sever. + + ```bash + roslaunch subjugator_launch gazebo.launch --screen + ``` + + :::{note} + `--screen` forces all ROS node output to the screen. It is used for debugging. + ::: + +1. Then in another terminal window run this command to start the Gazebo + graphical client, which connects to the Gazebo Sever. + + ```bash + gazebogui + ``` + +1. Then in another terminal window run this command and then press Shift-C to + unkill the sub to allow movement. + + ```bash + amonitor kill + ``` + +1. Execute the following command to start a specific mission, replacing + "StartGate2022" with the name of the desired mission: + + ```bash + mission run StartGate2022 + ``` + +## How to use Gazebo + +### User Interface + +When you launch Gazebo you will be greeted by its user interface. + +![Gazebo Interface](/images/gazebo/Interface.png) + +The Gazebo interface consists of three main sections: The **Left Panel**, the +**Scene**, and the **Right Panel**. By default the Right Panel is hidden. This +is because we do not have anything selected. To show the right panel you can +always Click and drag the bar on the right to open it. + +![Gazebo Labeled Interface](/images/gazebo/Labeled_Interface.png) + +#### Left Panel + +The Left Panel has three tabs, each with different features. You can see +these tabs at the top of the Left Panel. You can click on them to switch +between them. The tabs are: + +##### World Tab + +The World Tab displays the models that are currently in the scene. Within this +tab, you can view and modify various model parameters, like their pose (their +position and rotation). Additionally, you can expand the GUI option to adjust +the camera view angle by modifying the camera pose. + +##### Insert Tab + +The Insert Tab allows you to add new models (objects) to the Gazebo simulation. +Here, you will find a list of file paths where your models are saved. To view +the model list, click on the arrow located on the left side of each path to +expand the folder. Select the desired model and click again in the scene to +place it. + +##### Layers Tab + +The Layers tab organizes and displays different visualization groups within +the simulation. Layers can contain one or more models, and enabling or disabling +a layer will show or hide all the models within it. While not mandatory, layers +can be helpful for organizing your simulation. Note that this tab may be empty +if no layers are defined. + +To define a layer, you will need to edit a model's SDF file. To add an +object's visuals to a layer you will need to add a `` tag for information +and then a `` tag with the layer number under each `` tag. Below +is an example: + +```xml + + + 0 + + ... + +``` + +#### Scene + +The Scene is the main window where objects are animated, and you interact with +the environment. Two toolbars are available: + +##### The Upper Toolbar + +The Upper Toolbar consists of various buttons that allow you to select, move, +rotate, and scale objects. It also provides options to create simple shapes, +as well as copy and paste objects. + +![Gazebo Upper Toolbar](/images/gazebo/Upper_Toolbar.png) + +##### The Bottom Toolbar + +The Bottom Toolbar displays information about the simulation time and its +relationship to real time. It helps you track the progress of your simulation. + +![Gazebo Bottom Toolbar](/images/gazebo/Bottom_Toolbar.png) + +#### Right Panel + +The Right Panel is used to interact with the mobile parts (joints) of a +selected model. It provides controls and settings specific to manipulating +the joints of a model. + +#### Menus (File, Edit, Camera, View, Window, Help) + +Most Linux apps have menus. These menus are usually tabs (file, edit, ...) at +the top left of an application. If you don't see it move your cursor to the +top of the application window and the menus should appear. Below describes +the features of each menu that Gazebo has. + +![Gazebo Menus](/images/gazebo/Menus.png) + +#### Mouse + +It is recommended that you use a mouse when using Gazebo. Below is a diagram +showing all the mouse controls. + +![Gazebo Mouse Controls](/images/gazebo/Mouse.png) + +However, if you want to use a trackpad you can. Below are the controls for +the trackpad: + +![Gazebo Mouse Controls](/images/gazebo/TrackPad.png) + +## How to Create Models + +The structure for most models in Gazebo is that the model is a folder that +contains a .config file, .SDF file(s), and .dae or .stl file(s). The config +file contains meta information about the model. The .SDF file contains +important simulation information like model definitions, the model's +positioning, its physical properties, etc. The .dae or .stl files contain 3D +mesh information. When creating a model it's recommended that you have all +these components. + +### Model Editor + +You can use the **Model Editor** to create simple models all within Gazebo, +but for more complex models you will want to create/write your own SDF files +and .dae files. + +To enter the **Model Editor**, click on Edit in the menu bar and select Model Editor. + +The Model Editor Interface looks similar to the regular Gazebo UI with some +slight changes. The left panel and the top toolbar have been changed to +contain only buttons and features for editing and creating parts of a model. +The bottom toolbar is now hidden as the simulation is paused. + +![Gazebo Model Editor](/images/gazebo/Model_Editor.png) + +When entering the Model Editor all other models will turn white. This can make +it hard to see the model you are currently working on if you have a lot of +models in your scene. So it may be easier to open a blank Gazebo world and +create the model using the Model Editor there. Then when you exit the Model +Editor it will ask you to save the model. This will save the model as a folder +on your computer. Then you can go back to the original world and insert +this model, by going to the insert tab (note this is the regular insert tab, +not the one in the model editor) and adding that model folder's file path. + +:::{note} +When inserting a model, make sure that the file path you pick is the path to +the parent directory. This directory contains the model folder you want to +insert. Do not put the path to the model folder. Often this parent +directory will contain all the models you want to use. The file hierarchy +might look like this: where models is the parent directory and contains the +models model1 and buoys. + +``` + models/ + ├── model_1/ + │ ├── model.config + │ ├── model1.sdf + │ ├── model1.dae + │ └── ... + ├── buoys/ + │ ├── model.config + │ ├── green.sdf + │ ├── red.sdf + │ └── ... +``` + +::: + +#### Insert Tab + +The Insert Tab allows you to add new parts, including links and models, to +your model. You have two options for inserting shapes (links): + +* Simple Shapes: Click on the desired shape in the left panel and then click + again in the scene to place it. + +* Custom Shapes: You can add COLLADA (.dae), 3D Systems (.stl), Wavefront + (.obj), and W3C SVG (.svg) files as custom shapes. Create these shapes + using 3D modeling software like Blender. + +You can also insert other models into your model as nested models. These +models can be obtained from the Gazebo Model Database +(http://gazebosim.org/models/), which should be listed as one of your file +paths under Model Databases. For example, if you need a depth sensor, you can +add a depth sensor model from the database to your model. + +#### Model Tab + +The Model Tab displays the settings for the model you are creating. Here, you +can change the model's name and modify its basic parameters. Additionally, you +can add plugins to give your model functionality here as well. + +#### Placing Shapes + +Once you insert a shape, you can use the toolbar to move, rotate, and scale +it. For finer control, you can double-click the shape or right-click and +select "Open Link Inspector" to access the link inspector. In the link +inspector, you can modify the shape's position, rotation, and scale to +achieve the desired configuration. Make sure to adjust the scale in both the +Visual and Collision tabs. + +#### Adding Joints + +To constrain the motion between shapes, you can add joints. Follow these steps: + +* Click on the joint icon in the toolbar (a line connecting two points). + +* In the Joint Creation Window, select the parent and child links (shapes) + of the joint. + +* Select the type of joint you need in the Joint Types section near the top + of the window. + +* Select the joint axis. Some joints do not have an axis. + +* Align the link (shape). Use the align links section to align the parent + and the child with each other. + +#### Adding a Plugin + +To control your model, you need to create a plugin. You can do this in the +Model Tab by specifying the necessary details for the plugin. + +You can find more information on how to create your own custom plugins [here](https://classic.gazebosim.org/tutorials?tut=ros_gzplugins). + +#### Model Creation Workflow Example + +To illustrate the model creation process, let's consider creating a car model +using Blender: + +* Create .dae files for the wheels, chassis, and other parts in Blender. + +* Insert these shapes into the Model Editor. + +* Use the toolbar and link inspector to position each shape precisely. + +* Add joints between the shapes to enable motion constraints. + +* Finally, create a plugin to control the model's behavior. + +### World File + +A World in Gazebo is used to describe the collection of robots and objects, +and global parameters like the sky, ambient light, and physics properties. +A World is the entire virtual environment that you have been +working in. The World stores important information like where all the models +are, their properties, and important global properties. + +You can save the World file by selecting File and Save World As. + +:::{note} +When using roslaunch to start Gazebo, it is crucial to update the World file +if you make any changes to the simulation environment. At MIL, there is a +dedicated `worlds` folder where Gazebo World files are saved. When you update +a World file, ensure that you replace the old file in this folder. Failing +to do so will result in the continued use of the old World file when +launching Gazebo using roslaunch. +::: + +## More Info + +If you ever need more information on how any aspect of Gazebo works or how to +use ROS with Gazebo you can check out the official Gazebo Documentation [here](https://classic.gazebosim.org/tutorials). +Some of the images used in this guide are sourced from here and we are grateful +to the creators for their exceptional work, which has been instrumental in +writing this guide. diff --git a/docs/software/getting_started.md b/docs/software/getting_started.md index 6e94e1653..a40845665 100644 --- a/docs/software/getting_started.md +++ b/docs/software/getting_started.md @@ -63,8 +63,8 @@ methods. | Architecture | URL | | ------------ | --- | -| AMD64 (most Windows computers, Intel-based Mac computers) | [focal-desktop-amd64.iso](https://cdimage.ubuntu.com/focal/daily-live/current/focal-desktop-amd64.iso) | -| ARM64 (Apple Silicon Mac computers) | [focal-desktop-arm64.iso](https://cdimage.ubuntu.com/focal/daily-live/current/focal-desktop-arm64.iso) | +| AMD64 (most Windows computers, Intel-based Mac computers) | [focal-desktop-amd64.iso](https://releases.ubuntu.com/focal/ubuntu-20.04.6-desktop-amd64.iso) | +| ARM64 (Apple Silicon Mac computers) | Unfortunately, Ubuntu 20.04 no longer has an ARM-compatible ISO. While we are working on finding/building a new iso image, you may not be able to install. | The following subsections cover various installation methods. Please choose the installation option that best meets your use case. If you're not sure what the @@ -420,7 +420,7 @@ launches the Gazebo GUI - aka, the thing you will actually interact with! If all goes according to plan, you should see our robot in its own little world! ## Installing developer tools -After you have verified that your Git setup is working appopriately, take a look +After you have verified that your Git setup is working appropriately, take a look at installing some developer tools on the [Developer Tools](/software/devtools) page. diff --git a/docs/software/help.md b/docs/software/help.md index 060f8376b..f8250fa70 100644 --- a/docs/software/help.md +++ b/docs/software/help.md @@ -63,7 +63,7 @@ for examples of it being used. ## Search the internet If your problem is not MIL-specific (issue with Linux, ROS, C++, etc), -somone has most likely had the same problem and written about it on the internet. +someone has most likely had the same problem and written about it on the internet. You'll be surprised how often you can fix your issue by Googling the error. ## Search Slack diff --git a/docs/software/index.rst b/docs/software/index.rst index 61b036c7c..9e779a0eb 100644 --- a/docs/software/index.rst +++ b/docs/software/index.rst @@ -13,10 +13,12 @@ Various documentation related to practices followed by the MIL Software team. help zobelisk asyncio + rqt rostest Bash Style Guide C++ Style Guide Python Style Guide + Gazebo Guide Migrating to ROS Noetic Installing NVIDIA Drivers for RTX 2080 Installing Ubuntu 18.04 on an M-series Apple computer diff --git a/docs/software/noetic_migration.md b/docs/software/noetic_migration.md index 6a79ec10a..6a93a86cd 100644 --- a/docs/software/noetic_migration.md +++ b/docs/software/noetic_migration.md @@ -45,7 +45,7 @@ before you commit. Great, the code is now pretty! :D -If you ran `python-modernize`, it will have suggested some changes to you, indcated +If you ran `python-modernize`, it will have suggested some changes to you, indicated by `+` and `-` signs. It may look something like this: ```diff diff --git a/docs/software/rqt.md b/docs/software/rqt.md new file mode 100644 index 000000000..258c43522 --- /dev/null +++ b/docs/software/rqt.md @@ -0,0 +1,437 @@ +# Implementing GUI Based Tools Using `rqt` + +## Introduction + +RQT (ROS Qt-based GUI Framework) is a powerful tool that provides a graphical +user interface for ROS (Robot Operating System) applications. It allows users +to monitor ROS topics, interact with nodes, visualize data, and more. This +document serves as a user guide for understanding and effectively using RQT. + +### Benefits of RQT + +- **Graphical Interface**: RQT provides a user-friendly graphical interface, + making it easier to visualize data, monitor topics, and interact with nodes. + This is especially helpful for users who prefer a GUI based approach over + the command line. + +- **Centralized Tool**: RQT serves as a centralized tool for various ROS tasks, + including visualization, configuration, and debugging. This reduces the need + to switch between multiple terminals and tools, streamlining the development + process. + +- **Extensibility**: RQT's plugin architecture allows users to create custom + plugins to tailor the tool to their specific application needs. This + extensibility significantly enhances RQT's capabilities and to various + robotic systems. + +- **Integration with ROS**: RQT is tightly integrated with ROS, ensuring + seamless interaction with ROS nodes, topics, and services. This integration + simplifies the process of debugging and analyzing data in real-time. + +## Installation + +Before using RQT, make sure you have ROS installed on your system. If ROS is +not yet installed, follow the official ROS installation guide for your +operating system. Once ROS is installed, you can install RQT using the package +manager: + +```bash +sudo apt-get install ros-noetic-rqt +``` + +## Getting Started + +### Launching RQT + +To launch RQT, open a terminal and run the following command: + +```bash +rqt +``` + +This command will launch the RQT Graphical User Interface, displaying a +default layout with available plugins. + +## Monitoring Information with RQT + +RQT provides various plugins to monitor information published on specific ROS +topics. The most common plugin for this purpose is the Plot plugin. + +### Subscribing to Specific Topics + +1. Open RQT using the command mentioned in the previous section. +1. Click on the "Plugins" menu in the top toolbar and select "Topics" > + "Message Publisher." +1. A new "Message Publisher" tab will appear. Click on the "+" button to + subscribe to a specific topic. +1. Choose the desired topic from the list and click "OK." +1. Now, you can monitor the information published on the selected topic in + real-time. + +### Displaying Data with Plot Plugin + +1. Open RQT using the command mentioned earlier. +1. Click on the "Plugins" menu in the top toolbar and select + "Visualization" > "Plot." +1. A new "Plot" tab will appear. Click on the "+" button to add a plot. +1. Choose the topic you want to visualize from the list, select the message + field, and click "OK." +1. The plot will start displaying the data sent over the selected topic. + +## Configuring RQT + +RQT allows users to customize its appearance and layout to suit their preferences. + +### Theme Configuration + +1. Open RQT using the command mentioned earlier. +1. Click on the "View" menu in the top toolbar and select "Settings." +1. In the "Settings" window, go to the "Appearance" tab. +1. Here, you can change the color scheme, font size, and other visual settings. + +### Layout Configuration + +1. Open RQT using the command mentioned earlier. +1. Rearrange existing plugins by clicking on their tab and dragging them to + a new position. +1. To create a new tab, right-click on any existing tab and select "Add New Tab." +1. Drag and drop desired plugins onto the new tab. +1. Save your customized layout by going to the "View" menu and selecting + "Perspectives" > "Save Perspective." + +## Writing RQT Plugins + +RQT allows users to create their custom plugins to extend its functionality. +Writing RQT plugins is essential when the available plugins do not fully +meet your application's requirements. + +### Plugin Structure + +To write an RQT plugin, you need to follow a specific directory structure and +include Python or C++ code to implement the plugin's functionality. The +essential components of an RQT plugin are: + +- **Plugin XML (`plugin.xml`)**: This file defines the plugin and its + dependencies, specifying essential information like name, description, + and which ROS packages it depends on. + +- **Python or C++ Code**: This code contains the actual implementation of the + plugin's functionality. For Python plugins, the code should extend the + `rqt_gui_py::Plugin` class, while for C++ plugins, it should extend the + `rqt_gui_cpp::Plugin` class. + +### Implementing a Basic Plugin + +In this section, we will walk through an example of implementing a basic RQT +plugin. We will create a simple plugin to display the current time published +by a ROS topic. The plugin will consist of a label that updates with the +current time whenever a new message is received. + +#### Step 1: Create the Plugin Package + +Create a new ROS package for your plugin using the `catkin_create_pkg` command: + +```bash +catkin_create_pkg my_rqt_plugin rospy rqt_gui_py +``` + +The package dependencies `rospy` and `rqt_gui_py` are required to work with +ROS and create a Python-based RQT plugin. + +#### Step 2: Implement the Plugin Code + +Next, create a Python script for your plugin. In the `src` directory of your +package, create a file named `my_rqt_plugin.py` with the following content: + +```python +#!/usr/bin/env python + +import rospy +from rqt_gui_py.plugin import Plugin +from python_qt_binding.QtWidgets import QLabel, QVBoxLayout, QWidget +from std_msgs.msg import String +import time + +class MyRqtPlugin(Plugin): + + def __init__(self, context): + super(MyRqtPlugin, self).__init__(context) + self.setObjectName('MyRqtPlugin') + + # Create the main widget and layout + self._widget = QWidget() + layout = QVBoxLayout() + self._widget.setLayout(layout) + + # Create a label to display the current time + self._label = QLabel("Current Time: N/A") + layout.addWidget(self._label) + + # Subscribe to the topic that provides the current time + rospy.Subscriber('/current_time', String, self._update_time) + + # Add the widget to the context + context.add_widget(self._widget) + + def _update_time(self, msg): + # Update the label with the received time message + self._label.setText(f"Current Time: {msg.data}") + + def shutdown_plugin(self): + # Unregister the subscriber when the plugin is shut down + rospy.Subscriber('/current_time', String, self._update_time) + + def save_settings(self, plugin_settings, instance_settings): + # Save the plugin's settings when needed + pass + + def restore_settings(self, plugin_settings, instance_settings): + # Restore the plugin's settings when needed + pass + +``` + +In this code, we create a plugin class named `MyRqtPlugin`, which inherits +from `rqt_gui_py.Plugin`. The `__init__` method sets up the GUI elements, such +as a label, and subscribes to the `/current_time` topic to receive time updates. + +#### Step 3: Add the Plugin XML File + +Create a file named `plugin.xml` in the root of your package to define the +plugin. Add the following content to the `plugin.xml`: + +```xml + + + + A custom RQT plugin to display the current time. + + + + settings + Display the current time. + + + +``` + +This XML file defines the plugin class, its description, and the icon to be +displayed in the RQT GUI. + +#### Step 4: Build the Plugin + +Build your plugin package using `catkin_make`: + +```bash +catkin_make +``` + +#### Step 5: Launch RQT and Load the Plugin + +Launch RQT using the command mentioned earlier: + +```bash +rqt +``` + +Once RQT is open, navigate to the "Plugins" menu and select "My RQT Plugin" +from the list. The plugin will be loaded, and you should see the label +displaying the current time. + +### Adding Custom Functionality + +The example plugin we implemented is a simple demonstration of how to create +an RQT plugin. Depending on your application's requirements, you can add more +sophisticated features, such as custom data visualization, interactive +controls, and integration with other ROS elements. + +You can also improve the plugin by adding error handling, additional options +for time formatting, and the ability to pause/resume the time updates. + +## Implementing a More Advanced Plugin + +In this section, we will implement a more advanced RQT plugin that visualizes +data from multiple ROS topics using a 2D plot. This plugin will allow users to +choose which topics to plot and specify the message field to display on the X +and Y axes. Let's call this plugin "ROS Data Plotter." + +### Step 1: Create the Plugin Package + +Create a new ROS package for your plugin using the `catkin_create_pkg` command: + +```bash +catkin_create_pkg ros_data_plotter rospy rqt_gui_py matplotlib +``` + +The package dependencies `rospy`, `rqt_gui_py`, and `matplotlib` are required +to work with ROS, create a Python-based RQT plugin, and plot data, respectively. + +### Step 2: Implement the Plugin Code + +Next, create a Python script for your plugin. In the `src` directory of your +package, create a file named `ros_data_plotter.py` with the following content: + +```python +#!/usr/bin/env python + +import rospy +from rqt_gui_py.plugin import Plugin +from python_qt_binding.QtWidgets import QWidget, QVBoxLayout, QComboBox +from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas +from matplotlib.figure import Figure +from std_msgs.msg import Float32 # Modify this import based on your data type + +class ROSDataPlotter(Plugin): + + def __init__(self, context): + super(ROSDataPlotter, self).__init__(context) + self.setObjectName('ROSDataPlotter') + + # Create the main widget and layout + self._widget = QWidget() + layout = QVBoxLayout() + self._widget.setLayout(layout) + + # Create a combo box to select topics and message fields + self._topic_field_selector = QComboBox() + self._topic_field_selector.currentIndexChanged.connect(self._update_plot) + layout.addWidget(self._topic_field_selector) + + # Create the matplotlib figure and plot + self._figure = Figure() + self._canvas = FigureCanvas(self._figure) + layout.addWidget(self._canvas) + + # Initialize the plot + self._update_plot() + + # Add the widget to the context + context.add_widget(self._widget) + + def _update_plot(self): + # Clear the previous plot data + self._figure.clear() + axes = self._figure.add_subplot(111) + + # Get the selected topic and field from the combo box + selected_topic_field = self._topic_field_selector.currentText() + topic, field = selected_topic_field.split(' - ') + + # Subscribe to the selected topic + rospy.Subscriber(topic, Float32, self._plot_data) # Modify this based on your data type + + def _plot_data(self, msg): + # Get the selected topic and field from the combo box + selected_topic_field = self._topic_field_selector.currentText() + topic, field = selected_topic_field.split(' - ') + + # Plot the data on the graph + # Modify this part based on your data type and plot requirements + x_data = rospy.Time.now().to_sec() # Use timestamp as X-axis + y_data = getattr(msg, field) # Use the specified field from the message as Y-axis data + axes = self._figure.add_subplot(111) + axes.plot(x_data, y_data) + + # Refresh the plot + self._canvas.draw() + + def shutdown_plugin(self): + # Unsubscribe from the topic when the plugin is shut down + self._topic_field_selector.clear() + rospy.Subscriber(topic, Float32, self._plot_data) + + def save_settings(self, plugin_settings, instance_settings): + # Save the plugin's settings when needed + pass + + def restore_settings(self, plugin_settings, instance_settings): + # Restore the plugin's settings when needed + pass + +``` + +In this code, we create a plugin class named `ROSDataPlotter`, which inherits +from `rqt_gui_py.Plugin`. The `__init__` method sets up the GUI elements, +such as a combo box to select topics and message fields, and the matplotlib +figure to plot the data. The `_update_plot` method updates the plot whenever +a new topic or message field is selected from the combo box. The `_plot_data` +method is called when new messages are received on the selected topic, and it +plots the data on the graph. + +### Step 3: Add the Plugin XML File + +Create a file named `plugin.xml` in the root of your package to define the +plugin. Add the following content to the `plugin.xml`: + +```xml + + + + An advanced RQT plugin to plot data from multiple ROS topics. + + + + settings + Plot data from selected ROS topics. + + + +``` + +This XML file defines the plugin class, its description, and the icon +to be displayed in the RQT GUI. + +### Step 4: Build the Plugin + +Build your plugin package using `catkin_make`: + +```bash +catkin_make +``` + +### Step 5: Launch RQT and Load the Plugin + +Launch RQT + + using the command mentioned earlier: + +```bash +rqt +``` + +Once RQT is open, navigate to the "Plugins" menu and select "ROS Data Plotter" +from the list. The plugin will be loaded, and you should see a combo box to +select topics and fields, and a graph to display the plotted data. + +### Adding Custom Functionality + +In this more advanced example, we created an RQT plugin that allows users to +plot data from multiple ROS topics. The example focused on plotting Float32 +messages, but you can modify the `_plot_data` method to handle different +message types or plot multiple data series on the same graph. + +You can further enhance the plugin by adding features like legends, axis +labels, custom plot styles, data smoothing, and real-time updates. +Additionally, you can provide options to save the plotted data as CSV +or images for further analysis. + +With custom plugins, you have the freedom to tailor RQT to suit your +specific application's visualization needs, making it a versatile tool +for ROS developers. + +## External Resources + +- [ROS wiki page for rqt](https://wiki.ros.org/rqt) +- [GeorgiaTech RoboJacket's rqt tutorial](https://www.youtube.com/watch?v=o90IaCRje2I) +- [Creating Custom rqt Plugins](https://github.com/ChoKasem/rqt_tut) + +## Conclusion + +Congratulations! You have now learned the basics of using RQT, including +monitoring information sent over specific topics, configuring RQT to your +preferences, writing your custom plugins, and understanding the importance +of using RQT in ROS development. RQT provides a user-friendly and powerful +graphical interface for ROS applications, making it an essential tool for +developers and researchers working with ROS-based robotic systems. By +leveraging RQT's capabilities, you can streamline your development process +and gain valuable insights into your robot's behavior. diff --git a/docs/subjugator/index.rst b/docs/subjugator/index.rst index 28566c2ac..7d60efae4 100644 --- a/docs/subjugator/index.rst +++ b/docs/subjugator/index.rst @@ -16,6 +16,8 @@ SubjuGator 8 Enabling Cameras PID Controller + Navigation Tube + Watercooling electrical @@ -26,5 +28,6 @@ RoboSub RoboSub + Lessons from 2023 Lessons from 2022 Lessons from 2019 diff --git a/docs/subjugator/lessons23.md b/docs/subjugator/lessons23.md new file mode 100644 index 000000000..815f04766 --- /dev/null +++ b/docs/subjugator/lessons23.md @@ -0,0 +1,13 @@ +# Lessons from RoboSub 2023 + +Paraphrasing Dan Frank, “it's clear that if we had made all these mistakes back in Gainesville, we could have been in way better shape for the competition”. + +* **Make a plan and be familiar with the sub** - We should create a solid checklist that spells out all the basic stuff we need to nail before we leave. This should cover nailing down sub moves commands, getting familiar with the missions we already have written, testing those missions in the pool, and making sure our kill system is on point and integrates well with our software. Having a game plan for finals that's solid and picking out a reliable run that can get enough points to really boost our chances is really important. Let's not leave our presentation prep for the last minute – we need to make the presentation and practice at least a week before the competition hits. We should have deadlines for all of these. + +* **Make a plan and be familiar with the sub** - We need to have a Plan B when someone can't make it or falls sick. At least 2-3 people need to be able to rock the sub operation, change and charge batteries, replace mechanical things, etc. Roles in the team need to be crystal clear during the competition. + +* **Track issues and maintenance of parts** - We should track intermitten issues; investigate them, and deal with them, before leaving. The issues showed up every now and then, but we brushed them off thinking they’ll go away. They should've been solved earlier. Also we need a proper log of when we're swapping out parts or using them. That way, we know when it's time for replacements. We only made the move of MacArtney connector switch after stumbling on a Slack conversation from 2019. Having a grip on the tether's age would've helped sort things out sooner. + +* **Easier debugging and Sub Status** - When hardware kills don't unkill after rebooting and sticking the kill wand back in, we should've cracked open those CAN messages to see what was going wrong. Having all this info on a screen or sent to our computers would've made life simpler. About lights and screens, having status symbols or messages on screens for errors or warnings from each board would make debugging easier. Same goes for side lights on the sub – they'd be useful for the electrical and softwar. + +* **Document** - Since hardware takes more effort than firmware, we could try to make it easier to write working prototype firmware to have more time for making hardware. We currently have MIL written drivers, but they have inconsistent documentation and are confusing for some members to use (especially the ones for CAN). diff --git a/docs/subjugator/navtube.rst b/docs/subjugator/navtube.rst new file mode 100644 index 000000000..caf58ad2b --- /dev/null +++ b/docs/subjugator/navtube.rst @@ -0,0 +1,97 @@ +======== +Nav Tube +======== + +One of the major components of SubjuGator 8 is the navigation (nav tube). This pressure vessel is located right below the main pressure vessel and contains all of our navigation sensors and equipment. The navigation computer located inside the vessel allows access to the data from these components through a direct ethernet connection. + +.. warning:: + + This system was originally used on SubjuGator 7 and it was ported over with little to no changes in hardware. This does mean that the system will need a major overhaul for continued use of SubjuGator 8. + +Navigation Computer +=================== + +The navigation computer consists of a Gumstix Overo Computer-on-Module that mounts to a carrier board. The carrier board contains headers for the Teledyne Dopper Velocity Logger (DVL) connector board, Analog Devices Inertial Measurement Unit (IMU), and the pressure sensor. At one point, the navigation computer was also connected to a GPS antenna. +.. warning:: + + No documentation or PCB design files exist for the navigation computer carrier board and there are no more functioning spare boards. Additionally, only the newer GumStix Overo COM boards are available to purchase (with a lead time of roughly 1 year) which may not be compatible with the current system. Be very careful when working inside of the navigation tube. + +Troubleshooting The Nav Tube Connection +--------------------------------------- + +If you cannot ping the Navigation Computer (192.168.37.61), please ensure (in the following order) that: + +* You are pinging 192.168.37.61. +* The ethernet subconn cable has been connected between both pressure vessels. +* You restart the sub at least once. +* That the proper ethernet interface is configured in /etc/netplan YAML file. You may need to check ifconfig for the 'enpXs0' interface (where X is a whole number) if you have unplugged and replugged anything in the sub recently (especially the graphics card). Make sure to test the netplan with ``sudo netplan try`` so that you don't get locked out of the sub because of a bad configuration! +* The ethernet cables are properly connected inside the main pressure vessel. +* The ethernet cables and other cables are properly connected inside the Nav tube. +* The navigation computer is receiving power AND is turned on (green AND blue light on the GumStix). Make sure to be extra careful and vigilent when opening and handling the navigation computer. + +ADIS16400/16405-BMLZ IMU & Magnetometer +=========================================== + +The `ADIS16400-BMLZ `_ / `ADIS16405-BMLZ `_ is the device responsible for tracking our position and orientation in the water. Currently, there is an ADIS16400 IMU in the sub, but it previously used an ADIS16405. + +.. warning:: + + These components are obsolete! It may be difficult to find replacement parts in the future if SubjuGator 8 will see continued use... + +Calibrating the Magnetometer +---------------------------- + +The magnetometer inside of the ADIS16400/16405 measures the strength of the magnetic field at the orientation it faces. We use this data in conjunction with the IMU's gyroscopes and accelerometers to determine the orientation of the sub in the water. The process of calibrating the magnetometer is called magnetic hardsoft compensation and essentially changes how we bias the data it gives us. + +.. note:: + + Calibrating the magnetometer must be done in a pool. + +To calibrate the magnetometer you must first collect magnetometer data (``/imu/mag_raw``) to use for the calibration script. This can be done through the following: + +.. code-block:: bash + + $ roslaunch subjugator_launch sub8.launch + +or if you prefer to not launch the entire sub: + +.. code-block:: bash + + $ roslaunch subjugator_launch nav_box.launch imu:=true + +Then, in a separate terminal window, navigate to a known directory start recording the rosbag by typing: + +.. code-block:: bash + + $ rosbag record -O .bag /imu/mag_raw + +where is a substitute for whatever name you want to give to your bag (I recommend something memorable, like Frank or Penelope). This will record the bag data in the directory that the terminal window is in. + +When you have started recording the bag, have members who are in the water rotate the sub. Only the sub should move, not the members holding onto the sub. The calibration can be done in any order, but you must complete a full roll, pitch, and yaw rotation plus have a few minutes of data with all three occurring at the same time. Once you are done collecting data, kill the recording window using ``ctrl+c``. + +Next, we must run the calibration script with our data. This script is located in ``SubjuGator/drivers/magnetic_compensation/sub8_magnetic_hardsoft_compensation/scripts``. Type the following: + +.. code-block:: bash + + $ ./generate_config + +note that this is a python script, so + +.. code-block:: bash + + $ python3 generate_config + +is also valid. + +.. note:: + + If the script fails because of the ``fit_ellipsoid`` method and the points on the first figure are colinear or nearly colinear you may not have collected thorough enough data. The alternate possibility is a malfunctioning magnetometer. + +The output of the script should be a 3x3 matrix labeled ``scale`` and a length 3 vector labeled ``shift``. These values go into the ``scale`` and ``shift`` values located inside of ``subjugator_launch/launch/subsystems/nav_box.launch``. + +After running ``cm``, you will have (hopefully) successfully calibrated the magnetometer. Make sure to test the sub after calibration to see if the new configuration values are an improvement over the old ones. + +Important Links and Datasheets +============================== + +- `ADIS16400/ADIS16405 Datasheet `_ diff --git a/docs/subjugator/watercooling.rst b/docs/subjugator/watercooling.rst new file mode 100644 index 000000000..5344e68bf --- /dev/null +++ b/docs/subjugator/watercooling.rst @@ -0,0 +1,70 @@ +============ +Watercooling +============ + +SubjuGator 8's hardware requires a watercooling loop for the CPU, graphics card, and ESCs. + +Filling the Water cooling Loop +============================== + +.. note:: + + Filling the water cooling loop requires at least 2 people. + +Materials +--------- + +* Sub Shore Power Supply +* Sub battery tube cover +* Sub battery cables +* Large Funnel +* Small Funnel +* Stool or Chair +* Deionized Water w/ Biocide +* Vacuum Pump +* Extra water cooling connectors and tubing +* Water cooling reservoir +* Bucket + +.. note:: + + While deionized water with biocide is preferred for longevity, distilled water will work fine. You should not use purified water. Bonus points if the water is dyed orange :) + +No-Pump Procedure +----------------- + +These steps should be taken when there is no external pump to help with the filling process. + +.. warning:: + + Exercise caution during steps 8 and 9 as the sub will be powered on with a water hazard nearby. + +#. Move the main vessel onto the wooden platform and down to the floor. +#. Set up the environment as shown in the picture below. +#. Gravity feed the system by filling the reservoir with water and letting the bubbles come out naturally. Move on when no more bubbles come out. +#. Empty the reservoir until the water is below the "stove pipe" (metal tube inside the reservoir). +#. Blow into the tube exposed to air to force the water into the loop while extracting the air inside of the loop. Make sure to fill the reservoir until the water is below the "stove pipe" when there is an air gap inside of the water inlet tube. Move on when you cannot remove any more bubbles. +#. Attach the vacuum pump to the tube exposed to air and pump until the pressure reaches around 10 PSI. Pinch the outlet tube and break the vacuum to allow water to fill the low pressure spots. Repeat this step until at least a decent amount of water makes it past the pump. +#. With water at the ready, connect the sub to shore power and fill the reservoir with water (you do not have to worry about the "stove pipe"). +#. Wiggle the sub around while the pump is running to extract any trapped bubbles. + +Emptying the Water Cooling Loop +=============================== + +The water cooling loop should be emptied before the sub is shipped anywhere. Emptying the water cooling loop is easier than filling it up. + +.. note:: + + Emptying the water cooling loop requires at least 2 people. + +Materials +--------- + +* Vacuum pump +* Extra water cooling connectors and tubing +* Water cooling reservoir +* Bucket + + +Procedure +--------- diff --git a/docs/testingprocedures.md b/docs/testingprocedures.md index 2fcf81852..b1a6d4dc5 100644 --- a/docs/testingprocedures.md +++ b/docs/testingprocedures.md @@ -2,6 +2,8 @@ ## Before leaving +For best results, packing should be done at least one day before a testing session. This + ### Packing list * Power Strip * Table @@ -16,7 +18,6 @@ * 5/32 Allen Key * Duct tape and scissor * Buoyancy foams for the sub -* Allen Key for paintball tank * Pliers * Flat-head screwdriver * Kill wand @@ -27,22 +28,22 @@ * O'ring grease (Molykote 55) * Cable grease (Molykote 44) * Hot glue gun -* Zip ties +* Hot glue sticks +* Large and small zip ties * clippers -* Towels +* Towel(s) * [Sunscreen](https://www.youtube.com/watch?v=sTJ7AzBIJoI) - +* Tent (If going to Graham Pool or Florida Pool) +* Chairs (If going to Graham Pool) ### Software/Electrical Checklist -* Update and build code -* Verify all sensors output data -* Verify thrusters spin given command -* Verify kill (soft an hard) -* Grease all electrical connectors appropriately - +* Update (`git pull`) and build (`cm`) code. +* Verify all sensors output data. +* Verify that the correct thrusters spin given the appropriate command. +* Verify kill (soft and hard). +* Grease all electrical connectors appropriately. ## At testing site - * Get wall power to powerstrip. * Setup and connect to Network Box. * Roll tether and connect it to network box. **(DO NOT USE POE)** @@ -51,11 +52,11 @@ * SSH into sub. * Start tmux, write code. * Grease O-rings with Molykote 55 every time a pressure vessel is closed. -* Make sure ALL pneumatic tubes are inserted correctly. **(DO NOT FLOOD THE VALVE BOX)** -* Make sure all holes to paintball tank are sealed correctly. **(THIS WILL ALSO RESULT IN FLOODING IF NOT DONE)** +* * **ENSURE THAT THE RED PRESSURE RELIEF CAP ON THE BATTERY TUBE HAS BEEN SCREWED IN PLACE AFTER CHANGING BATTERIES** * Person getting into the pool must do backflip. -* Deploy sub. (check for bubbles, make sure buoyancy is correct) +* Deploy sub. (check for bubbles, make sure buoyancy is correct). * Verify odometry. -What happens when the valve box isn't closed: -![What happens when the valve box isn't closed.](/flooded_valve_box.jpg) +### Troubleshooting + +- :ref:`Troubleshooting The Nav Tube Connection` diff --git a/mil_common/axros b/mil_common/axros index 1b0399935..a4951d333 160000 --- a/mil_common/axros +++ b/mil_common/axros @@ -1 +1 @@ -Subproject commit 1b03999351fb5a61b202ff125f493229c2a1676b +Subproject commit a4951d33356c349856532ddef5c97c6ec6810c28 diff --git a/mil_common/drivers/mil_passive_sonar/README.md b/mil_common/drivers/mil_passive_sonar/README.md index 572ad4069..7010a3ae0 100644 --- a/mil_common/drivers/mil_passive_sonar/README.md +++ b/mil_common/drivers/mil_passive_sonar/README.md @@ -4,7 +4,7 @@ This package includes the main algorithm to find the direction of a pinger. It a # Running: Ensure that hydrophones -> ros is running and publishing a `mil_passive_sonar/Ping` msg. -Then run `roslaunch mil_passive_sonar mil_passive_sonar.lauch` +Then run `roslaunch mil_passive_sonar mil_passive_sonar.launch` `mil_passive_sonar/FindPinger` diff --git a/mil_common/drivers/mil_passive_sonar/scripts/triggering.py b/mil_common/drivers/mil_passive_sonar/scripts/triggering.py index 897a76949..321a20411 100755 --- a/mil_common/drivers/mil_passive_sonar/scripts/triggering.py +++ b/mil_common/drivers/mil_passive_sonar/scripts/triggering.py @@ -96,7 +96,7 @@ def get_params(self): self.enabled = rospy.get_param("~enable_on_launch") # Attributes about our target frequency range - # target Frquency in Hz + # target Frequency in Hz self.target = rospy.get_param("~target_frequency") # tolerance around that frequerncy in Hz tolerance = rospy.get_param("~frequency_tolerance") @@ -121,7 +121,7 @@ def get_params(self): self.v_sound = rospy.get_param("v_sound") # Misc attributes - # minimum gradient of the max convolution wrt time to trigger a time of arivals calculation + # minimum gradient of the max convolution wrt time to trigger a time of arrivals calculation self.threshold = rospy.get_param("~threshold") self.trigger_offset = rospy.get_param("~trigger_offset") # how far after the triggering time to make upper bound of samples at triggering in sec diff --git a/mil_common/drivers/mil_pneumatic_actuator/nodes/pneumatic_actuator_node b/mil_common/drivers/mil_pneumatic_actuator/nodes/pneumatic_actuator_node index bf8261177..920fb5a92 100755 --- a/mil_common/drivers/mil_pneumatic_actuator/nodes/pneumatic_actuator_node +++ b/mil_common/drivers/mil_pneumatic_actuator/nodes/pneumatic_actuator_node @@ -37,7 +37,7 @@ class Actuator: if isinstance(config, int): return cls.from_int(config) type_str = config["type"] - pulse_time = config["pulse_time"] if "pulse_time" in config else None + pulse_time = config.get("pulse_time") open_id = config["ports"]["open_port"]["id"] open_default = config["ports"]["open_port"]["default"] if "close_port" in config["ports"]: diff --git a/mil_common/drivers/mil_usb_to_can/mil_usb_to_can/sub8/sub8_driver.py b/mil_common/drivers/mil_usb_to_can/mil_usb_to_can/sub8/sub8_driver.py index 8236940ac..c03b318d2 100755 --- a/mil_common/drivers/mil_usb_to_can/mil_usb_to_can/sub8/sub8_driver.py +++ b/mil_common/drivers/mil_usb_to_can/mil_usb_to_can/sub8/sub8_driver.py @@ -85,9 +85,7 @@ def read_packet(self) -> bool: self.handles[packet.device].on_data(packet.data) else: rospy.logwarn( - "Message received for device {}, but no handle registered".format( - packet.device, - ), + f"Message received for device {packet.device}, but no handle registered", ) return True diff --git a/mil_common/drivers/mil_usb_to_can/mil_usb_to_can/sub8/utils.py b/mil_common/drivers/mil_usb_to_can/mil_usb_to_can/sub8/utils.py index 2d2558f57..7524e6dfe 100644 --- a/mil_common/drivers/mil_usb_to_can/mil_usb_to_can/sub8/utils.py +++ b/mil_common/drivers/mil_usb_to_can/mil_usb_to_can/sub8/utils.py @@ -26,10 +26,7 @@ class ChecksumException(USB2CANException): def __init__(self, calculated, expected): super().__init__( - "Checksum was calculated as {} but reported as {}".format( - calculated, - expected, - ), + f"Checksum was calculated as {calculated} but reported as {expected}", ) @@ -117,13 +114,11 @@ def __bytes__(self) -> bytes: @overload @classmethod - def _unpack_payload(cls, data: Literal[b""]) -> None: - ... + def _unpack_payload(cls, data: Literal[b""]) -> None: ... @overload @classmethod - def _unpack_payload(cls, data: bytes) -> bytes: - ... + def _unpack_payload(cls, data: bytes) -> bytes: ... @classmethod def _unpack_payload(cls, data: bytes) -> bytes | None: @@ -458,13 +453,11 @@ def calculate_checksum(self, data: bytes) -> int: @overload @classmethod - def from_bytes(cls, data: Literal[b""]) -> None: - ... + def from_bytes(cls, data: Literal[b""]) -> None: ... @overload @classmethod - def from_bytes(cls: type[T], data: bytes) -> T: - ... + def from_bytes(cls: type[T], data: bytes) -> T: ... @classmethod def from_bytes(cls: type[T], data: bytes) -> T | None: diff --git a/mil_common/drivers/mil_usb_to_can/mil_usb_to_can/sub9/sub9_driver.py b/mil_common/drivers/mil_usb_to_can/mil_usb_to_can/sub9/sub9_driver.py index 59db73c99..90928ff8d 100755 --- a/mil_common/drivers/mil_usb_to_can/mil_usb_to_can/sub9/sub9_driver.py +++ b/mil_common/drivers/mil_usb_to_can/mil_usb_to_can/sub9/sub9_driver.py @@ -31,8 +31,9 @@ class SimulatedUSBtoCANStream(SimulatedSerial): def __init__( self, - devices: list[tuple[type[SimulatedCANDeviceHandle], list[type[Packet]]]] - | None = None, + devices: ( + list[tuple[type[SimulatedCANDeviceHandle], list[type[Packet]]]] | None + ) = None, ): """ Args: @@ -214,16 +215,14 @@ def read_devices( self, *, simulated: Literal[True], - ) -> list[tuple[type[SimulatedCANDeviceHandle], list[type[Packet]]]]: - ... + ) -> list[tuple[type[SimulatedCANDeviceHandle], list[type[Packet]]]]: ... @overload def read_devices( self, *, simulated: Literal[False], - ) -> list[tuple[type[CANDeviceHandle], list[type[Packet]]]]: - ... + ) -> list[tuple[type[CANDeviceHandle], list[type[Packet]]]]: ... def read_devices( self, diff --git a/mil_common/drivers/mil_usb_to_can/test/test_packets_sub9.py b/mil_common/drivers/mil_usb_to_can/test/test_packets_sub9.py index 01c1dc47a..c58a8c32c 100755 --- a/mil_common/drivers/mil_usb_to_can/test/test_packets_sub9.py +++ b/mil_common/drivers/mil_usb_to_can/test/test_packets_sub9.py @@ -8,7 +8,7 @@ @dataclass -class TestPacket(Packet, msg_id=0x47, subclass_id=0x44, payload_format="BHf"): +class TestPacket(Packet, msg_id=0x47, subclass_id=0x44, payload_format="?Hd"): example_bool: bool example_int: int example_float: float @@ -23,7 +23,7 @@ def test_simple_packet(self): packet = TestPacket(False, 42, 3.14) self.assertEqual(packet.msg_id, 0x47) self.assertEqual(packet.subclass_id, 0x44) - self.assertEqual(packet.payload_format, "BHf") + self.assertEqual(packet.payload_format, "?Hd") self.assertEqual(packet.example_bool, False) self.assertEqual(packet.example_int, 42) self.assertEqual(packet.example_float, 3.14) @@ -36,6 +36,13 @@ def test_assembled_packet(self): self.assertEqual(assembled[2], packet.msg_id) self.assertEqual(assembled[3], packet.subclass_id) + def test_format(self): + packet = TestPacket(False, 42, 3.14) + self.assertEqual( + TestPacket.from_bytes(TestPacket.__bytes__(packet)), + packet, + ) + def test_comparisons(self): packet = TestPacket(False, 42, 3.14) packet_two = TestPacket(False, 42, 3.14) diff --git a/mil_common/gnc/odometry_utils/src/odometry_to_tf.cpp b/mil_common/gnc/odometry_utils/src/odometry_to_tf.cpp index d2ec5a6bf..6c2794453 100644 --- a/mil_common/gnc/odometry_utils/src/odometry_to_tf.cpp +++ b/mil_common/gnc/odometry_utils/src/odometry_to_tf.cpp @@ -4,7 +4,9 @@ #include #include +#include #include +#include namespace odometry_utils { @@ -13,11 +15,17 @@ class odometry_to_tf : public nodelet::Nodelet private: ros::Subscriber odom_sub; tf::TransformBroadcaster tf_br; + std::map _last_tf_stamps; void handle_odom(const nav_msgs::Odometry::ConstPtr& msg) { tf::Transform transform; poseMsgToTF(msg->pose.pose, transform); + if (_last_tf_stamps.count(msg->header.frame_id) && _last_tf_stamps[msg->header.frame_id] == msg->header.stamp) + { + return; + } + _last_tf_stamps[msg->header.frame_id] = msg->header.stamp; tf::StampedTransform stamped_transform(transform, msg->header.stamp, msg->header.frame_id, msg->child_frame_id); tf_br.sendTransform(stamped_transform); } diff --git a/mil_common/gnc/rawgps_common/src/rawgps_common/gps.py b/mil_common/gnc/rawgps_common/src/rawgps_common/gps.py index 81393bb3f..d8fb03d5b 100644 --- a/mil_common/gnc/rawgps_common/src/rawgps_common/gps.py +++ b/mil_common/gnc/rawgps_common/src/rawgps_common/gps.py @@ -649,9 +649,7 @@ def generate_satellite_message( for i in range(2): dt = t - eph.t_oc assert abs(dt) < week_length / 2 - deltat_SV_L1 = ( - eph.a_f0 + eph.a_f1 * dt + eph.a_f2 * dt**2 + deltat_r - eph.T_GD - ) + deltat_SV_L1 = eph.a_f0 + eph.a_f1 * dt + eph.a_f2 * dt**2 + deltat_r - eph.T_GD t = t_SV - deltat_SV_L1 if i == 1: sat_pos, deltat_r, sat_vel = eph.predict(t) @@ -691,14 +689,16 @@ def generate_satellite_message( time=-pseudo_range / c - deltat_SV_L1, T_iono=T_iono, T_tropo=T_tropo, - carrier_distance=carrier_cycles * c / L1_f0 - if carrier_cycles is not None - else nan, + carrier_distance=( + carrier_cycles * c / L1_f0 if carrier_cycles is not None else nan + ), doppler_velocity=doppler_freq * c / L1_f0, direction_enu=Vector3(*direction_enu), - velocity_plus_drift=doppler_freq * c / L1_f0 + direction.dot(sat_vel) - if doppler_freq is not None - else nan, + velocity_plus_drift=( + doppler_freq * c / L1_f0 + direction.dot(sat_vel) + if doppler_freq is not None + else nan + ), ) diff --git a/mil_common/mil_missions/mil_missions_core/__init__.py b/mil_common/mil_missions/mil_missions_core/__init__.py index f4244279d..e603f4026 100644 --- a/mil_common/mil_missions/mil_missions_core/__init__.py +++ b/mil_common/mil_missions/mil_missions_core/__init__.py @@ -4,6 +4,7 @@ from to create robot-specific mission tasks. These mission classes can be imported by the mission runner and then run. """ + from .base_mission import BaseMission from .chain_with_timeout import MakeChainWithTimeout from .exceptions import ( diff --git a/mil_common/mil_missions/mil_missions_core/base_mission.py b/mil_common/mil_missions/mil_missions_core/base_mission.py index bc41dc62c..e6e5e01df 100644 --- a/mil_common/mil_missions/mil_missions_core/base_mission.py +++ b/mil_common/mil_missions/mil_missions_core/base_mission.py @@ -121,6 +121,7 @@ def send_feedback(self, message: str) -> None: mission is a child mission, it will call the send_feedback_child of its parent, allowing missions to choose how to use the feedback from its children. """ + message = str(message) if self.parent: self.parent.send_feedback_child(message, self) else: diff --git a/mil_common/mil_missions/mil_missions_gui/dashboard.py b/mil_common/mil_missions/mil_missions_gui/dashboard.py index f3f224243..440dc85b9 100755 --- a/mil_common/mil_missions/mil_missions_gui/dashboard.py +++ b/mil_common/mil_missions/mil_missions_gui/dashboard.py @@ -195,11 +195,10 @@ def ui_log(self, string): """ self.lock.acquire() date_time = datetime.datetime.fromtimestamp(rospy.Time.now().to_time()) - time_str = "{}:{}:{}".format( - date_time.hour, - date_time.minute, - date_time.second, - ).ljust(12, " ") + time_str = f"{date_time.hour}:{date_time.minute}:{date_time.second}".ljust( + 12, + " ", + ) formatted = time_str + string self.feedback_list.addItem(formatted) self.lock.release() @@ -242,9 +241,7 @@ def transition_cb(self, goal, handler): self.current_mission_status = terminal_state self.current_mission_status_label.setText(self.current_mission_status) self.ui_log( - "FINISHED: mission finished ({})".format( - self.current_mission_status, - ), + f"FINISHED: mission finished ({self.current_mission_status})", ) def reload_available_missions(self, _): diff --git a/mil_common/mil_missions/nodes/mission_client b/mil_common/mil_missions/nodes/mission_client index 2ff81d944..230547f8e 100755 --- a/mil_common/mil_missions/nodes/mission_client +++ b/mil_common/mil_missions/nodes/mission_client @@ -30,9 +30,7 @@ class MissionClientCli: missions = MissionClient.available_missions() if not missions: print( - "{} param not set. Is mission runner running?".format( - MissionClient.LIST_PARAM, - ), + f"{MissionClient.LIST_PARAM} param not set. Is mission runner running?", ) return print("Available Missions:") diff --git a/mil_common/mil_missions/nodes/mission_server b/mil_common/mil_missions/nodes/mission_server index 3548d0b58..0009b8b8e 100755 --- a/mil_common/mil_missions/nodes/mission_server +++ b/mil_common/mil_missions/nodes/mission_server @@ -29,8 +29,10 @@ class MissionRunner: missions_loaded: bool base_mission: type[BaseMission] missions: dict[str, type[BaseMission]] + _running_tasks: set[asyncio.Task] def __init__(self): + self._running_tasks = set() pass async def init(self): @@ -213,6 +215,7 @@ class MissionRunner: self.mission = self.missions[goal.mission]() self.mission_future = asyncio.create_task(self.run_with_callback(parameters)) self.mission_future.add_done_callback(self.mission_finished_cb) + self._running_tasks.add(self.mission_future) async def run_with_callback(self, parameters): try: @@ -242,6 +245,7 @@ class MissionRunner: mission, or raises an exception. Publishes the correct result to the action clients. """ result = DoMissionResult() + self._running_tasks.remove(task) try: task_result = task.result() diff --git a/mil_common/mil_missions/test/test_import_missions.py b/mil_common/mil_missions/test/test_import_missions.py index e03fb7e82..c09c8f13b 100755 --- a/mil_common/mil_missions/test/test_import_missions.py +++ b/mil_common/mil_missions/test/test_import_missions.py @@ -21,10 +21,7 @@ def test_import_missions(self): if not hasattr(mission_module, self.base_class): self.fail( - msg="{} doesn't have base mission {}".format( - self.module, - self.base_class, - ), + msg=f"{self.module} doesn't have base mission {self.base_class}", ) base_mission = getattr(mission_module, self.base_class) diff --git a/mil_common/perception/mil_vision/include/mil_vision_lib/cv_tools.hpp b/mil_common/perception/mil_vision/include/mil_vision_lib/cv_tools.hpp index 4709fa85f..af6f30853 100644 --- a/mil_common/perception/mil_vision/include/mil_vision_lib/cv_tools.hpp +++ b/mil_common/perception/mil_vision/include/mil_vision_lib/cv_tools.hpp @@ -76,7 +76,7 @@ unsigned int select_hist_mode(std::vector &histogram_modes, unsigned // Takes in a grayscale image and segments out a semi-homogenous foreground // object with pixel intensities close to . Tuning of last three -// parameters may imrove results but default values should work well in +// parameters may improve results but default values should work well in // most cases. void statistical_image_segmentation(const cv::Mat &src, cv::Mat &dest, cv::Mat &debug_img, const int hist_size, const float **ranges, const int target, std::string image_name = "Unnamed Image", diff --git a/mil_common/perception/mil_vision/mil_vision_tools/color_classifier.py b/mil_common/perception/mil_vision/mil_vision_tools/color_classifier.py index df48a5881..3ff55caef 100755 --- a/mil_common/perception/mil_vision/mil_vision_tools/color_classifier.py +++ b/mil_common/perception/mil_vision/mil_vision_tools/color_classifier.py @@ -94,7 +94,7 @@ def classify_features(self, features: np.ndarray) -> int: def feature_probabilities(self, features: np.ndarray) -> List[float]: """ - Allows child classes to give probabilties for each possible class given + Allows child classes to give probabilities for each possible class given a features vector, instead of just one classification. By default, gives 1.0 to classified class and 0.0 to others. @@ -210,6 +210,8 @@ def read_from_csv(self, training_file: Optional[str] = None): Args: training_file (Optional[str]): The name of the training file. """ + if training_file is None: + raise NotImplementedError("Cannot read without any training file.") training_file = _get_param(training_file, self.training_file) df = pandas.read_csv(training_file) classes = df.values[:, 1] diff --git a/mil_common/perception/mil_vision/mil_vision_tools/cv_tools.py b/mil_common/perception/mil_vision/mil_vision_tools/cv_tools.py index dcfb694a1..42b6112b2 100644 --- a/mil_common/perception/mil_vision/mil_vision_tools/cv_tools.py +++ b/mil_common/perception/mil_vision/mil_vision_tools/cv_tools.py @@ -79,7 +79,7 @@ def __init__( self.conversion_code = conversion_code @classmethod - def from_dict(cls, d, in_space: str = "BGR", thresh_space: str = None): + def from_dict(cls, d, in_space: str = "BGR", thresh_space: Optional[str] = None): """ Loads thresholds from a dictionary. See examples for valid dictionaries. @@ -114,9 +114,7 @@ def from_dict(cls, d, in_space: str = "BGR", thresh_space: str = None): d.keys(), ), ) - assert thresh_space in d, "{} color space not in dictionary".format( - thresh_space, - ) + assert thresh_space in d, f"{thresh_space} color space not in dictionary" inner = d[thresh_space] if "low" in inner and "high" in inner: return cls( diff --git a/mil_common/perception/mil_vision/mil_vision_tools/shape_finder.py b/mil_common/perception/mil_vision/mil_vision_tools/shape_finder.py index 5ba5f78cb..33479a753 100644 --- a/mil_common/perception/mil_vision/mil_vision_tools/shape_finder.py +++ b/mil_common/perception/mil_vision/mil_vision_tools/shape_finder.py @@ -213,7 +213,7 @@ def get_pose_3D( cam (Optional[PinholeCameraModel]): The camera model. rectified (bool): If ``cam`` is set, set True if corners were found in an already rectified image (image_rect_color topic). - instrinsics (np.ndarray): Camera intrinisic matrix. + intrinsics (np.ndarray): Camera intrinisic matrix. dist_coeffs (np.ndarray): Camera distortion coefficients. Returns: @@ -304,12 +304,12 @@ def __init__(self, length=1.0, width=1.0): self.model_2D = np.zeros((50, 1, 2), dtype=np.int) # Approximate an ellipse with 50 points, so that verify_contour is reasonable fast still for idx, theta in enumerate(np.linspace(0.0, 2.0 * np.pi, num=50)): - self.model_2D[idx][0][ - 0 - ] = self.length * 0.5 * scale + self.length * 0.5 * scale * np.cos(theta) - self.model_2D[idx][0][ - 1 - ] = self.width * 0.5 * scale + self.width * 0.5 * scale * np.sin(theta) + self.model_2D[idx][0][0] = ( + self.length * 0.5 * scale + self.length * 0.5 * scale * np.cos(theta) + ) + self.model_2D[idx][0][1] = ( + self.width * 0.5 * scale + self.width * 0.5 * scale * np.sin(theta) + ) def get_corners(self, contour, debug_image=None): """ diff --git a/mil_common/perception/mil_vision/mil_vision_tools/vision_node.py b/mil_common/perception/mil_vision/mil_vision_tools/vision_node.py index d1c8d37e9..caaaf7fd6 100755 --- a/mil_common/perception/mil_vision/mil_vision_tools/vision_node.py +++ b/mil_common/perception/mil_vision/mil_vision_tools/vision_node.py @@ -27,7 +27,7 @@ def create_object_msg( is needed/available in your application. Args: - name (str): Name of the identifed object. + name (str): Name of the identified object. attributes (str): Attributes to attach to message, the purpose and value of this attribute will vary by application. Defaults to an empty string. confidence (Optional[float]): Float between 0 and 1 describing the confidence diff --git a/mil_common/perception/mil_vision/ros_tools/on_the_fly_thresholder.py b/mil_common/perception/mil_vision/ros_tools/on_the_fly_thresholder.py index 74fbc58dd..e70de289e 100755 --- a/mil_common/perception/mil_vision/ros_tools/on_the_fly_thresholder.py +++ b/mil_common/perception/mil_vision/ros_tools/on_the_fly_thresholder.py @@ -78,9 +78,11 @@ def __init__(self, img, thresh_type="bgr"): def update_mask(self): self.lower, self.upper = self.trackbars.get_bounds() self.mask = cv2.inRange( - self.image - if self.thresh_type == "bgr" - else cv2.cvtColor(self.image, cv2.COLOR_BGR2HSV), + ( + self.image + if self.thresh_type == "bgr" + else cv2.cvtColor(self.image, cv2.COLOR_BGR2HSV) + ), self.lower, self.upper, ) diff --git a/mil_common/perception/mil_vision/src/mil_vision_lib/colorizer/pcd_colorizer.cpp b/mil_common/perception/mil_vision/src/mil_vision_lib/colorizer/pcd_colorizer.cpp index a0bd83adb..14333e5e3 100644 --- a/mil_common/perception/mil_vision/src/mil_vision_lib/colorizer/pcd_colorizer.cpp +++ b/mil_common/perception/mil_vision/src/mil_vision_lib/colorizer/pcd_colorizer.cpp @@ -24,7 +24,7 @@ PcdColorizer::PcdColorizer(ros::NodeHandle nh, string input_pcd_topic) } catch (std::exception &e) { - _err_msg = "COLORIZER: Suscriber or publisher error caught: "_s + e.what(); + _err_msg = "COLORIZER: Subscriber or publisher error caught: "_s + e.what(); ROS_ERROR(_err_msg.c_str()); return; } diff --git a/mil_common/ros_alarms/nodes/alarm_server.py b/mil_common/ros_alarms/nodes/alarm_server.py index bb602304c..b3a023778 100755 --- a/mil_common/ros_alarms/nodes/alarm_server.py +++ b/mil_common/ros_alarms/nodes/alarm_server.py @@ -178,9 +178,9 @@ def _create_alarm_handlers(self): if alarm_name in self.alarms: self.alarms[alarm_name].update(h.initial_alarm) else: - self.alarms[ - alarm_name - ] = h.initial_alarm # Update even if already added to server + self.alarms[alarm_name] = ( + h.initial_alarm + ) # Update even if already added to server elif ( alarm_name not in self.alarms ): # Add default initial if not there already diff --git a/mil_common/ros_alarms/ros_alarms/__init__.py b/mil_common/ros_alarms/ros_alarms/__init__.py index 600cc75c8..9f257faae 100644 --- a/mil_common/ros_alarms/ros_alarms/__init__.py +++ b/mil_common/ros_alarms/ros_alarms/__init__.py @@ -39,6 +39,7 @@ Topic publishing any getting/setting updates that occur on alarms. """ + from .alarms import ( Alarm, AlarmBroadcaster, diff --git a/mil_common/ros_alarms/test/roscpp/listener_test.cpp b/mil_common/ros_alarms/test/roscpp/listener_test.cpp index 2138546e5..f365a1305 100644 --- a/mil_common/ros_alarms/test/roscpp/listener_test.cpp +++ b/mil_common/ros_alarms/test/roscpp/listener_test.cpp @@ -51,7 +51,7 @@ TEST(ListenerTest, listenerTest) ab.getAlarm() = pxy; ab.clear(); // alarm starts off cleared - // Last update time happened wehen we called ab.clear() + // Last update time happened when we called ab.clear() auto first_query = listener.getLastUpdateTime(); ab.updateSeverity(5); // This is an update to the alarm diff --git a/mil_common/ros_alarms/test/rospy/python_tests.py b/mil_common/ros_alarms/test/rospy/python_tests.py index 9c29a7305..c11b0f061 100755 --- a/mil_common/ros_alarms/test/rospy/python_tests.py +++ b/mil_common/ros_alarms/test/rospy/python_tests.py @@ -17,7 +17,7 @@ def __init__(self, *args): super().__init__(*args) """ Tests alarm client operations - Creates some listeners and some broadcasters and tests various raising and clearing conditoins + Creates some listeners and some broadcasters and tests various raising and clearing conditions Also tests various combination of parameters """ @@ -142,7 +142,7 @@ def test_callbacks(self): self.cleared = False self.both = False - # Make sure callbacks run when they're suppsed to + # Make sure callbacks run when they're supposed to ab_a.raise_alarm() rospy.sleep(0.5) diff --git a/mil_common/utils/mil_tools/mil_misc_tools/download.py b/mil_common/utils/mil_tools/mil_misc_tools/download.py index 85001f69a..fbf3fe61d 100644 --- a/mil_common/utils/mil_tools/mil_misc_tools/download.py +++ b/mil_common/utils/mil_tools/mil_misc_tools/download.py @@ -11,6 +11,7 @@ [3] Download a file via http http://stackoverflow.com/questions/22676 """ + import io as StringIO import os import urllib.request diff --git a/mil_common/utils/mil_tools/mil_ros_tools/cv_debug.py b/mil_common/utils/mil_tools/mil_ros_tools/cv_debug.py index 275abf969..b5695ded9 100644 --- a/mil_common/utils/mil_tools/mil_ros_tools/cv_debug.py +++ b/mil_common/utils/mil_tools/mil_ros_tools/cv_debug.py @@ -1,6 +1,7 @@ """ Shows images for debugging purposes. """ + import sys from typing import Optional diff --git a/mil_common/utils/mil_tools/mil_ros_tools/extract_bag_images.py b/mil_common/utils/mil_tools/mil_ros_tools/extract_bag_images.py index c243ae950..22e52987c 100755 --- a/mil_common/utils/mil_tools/mil_ros_tools/extract_bag_images.py +++ b/mil_common/utils/mil_tools/mil_ros_tools/extract_bag_images.py @@ -150,17 +150,11 @@ def get_camera_model(bag: str, topic: str): _, msg, _ = next(bag.read_messages(topics=camera_info_topic)) except StopIteration: raise Exception( - "no camera info messages found on topic {} in {}".format( - camera_info_topic, - bag, - ), + f"no camera info messages found on topic {camera_info_topic} in {bag}", ) if msg._type != "sensor_msgs/CameraInfo": raise Exception( - "msg on topic {} are not camera info in bag {}".format( - camera_info_topic, - bag, - ), + f"msg on topic {camera_info_topic} are not camera info in bag {bag}", ) model = PinholeCameraModel() model.fromCameraInfo(msg) @@ -218,10 +212,7 @@ def extract_images(self, source_dir=".", image_dir=".", verbose=False): """ if verbose: print( - "\tExtracting images from topic {} in {}".format( - self.topic, - self.filename, - ), + f"\tExtracting images from topic {self.topic} in {self.filename}", ) filename = os.path.join(source_dir, self.filename) b = rosbag.Bag(filename) diff --git a/mil_common/utils/mil_tools/mil_ros_tools/image_helpers.py b/mil_common/utils/mil_tools/mil_ros_tools/image_helpers.py index 22f8eac56..45e12b931 100644 --- a/mil_common/utils/mil_tools/mil_ros_tools/image_helpers.py +++ b/mil_common/utils/mil_tools/mil_ros_tools/image_helpers.py @@ -98,7 +98,7 @@ class Image_Subscriber: last_image_time (genpy.Time): The time of the last image received. im_sub (rospy.Subscriber): The subscriber to the image topic. The topic name and queue size are received through the constructor. - info_sub (rospy.Susbcriber): The subscriber to the camera info topic. + info_sub (rospy.Subscriber): The subscriber to the camera info topic. The topic name is derived from the root of the supplied topic and the queue size is derived from the constructor. bridge (CvBridge): The bridge between OpenCV and ROS. diff --git a/mil_common/utils/mil_tools/mil_ros_tools/init_helpers.py b/mil_common/utils/mil_tools/mil_ros_tools/init_helpers.py index 0a8541fd6..789b36153 100644 --- a/mil_common/utils/mil_tools/mil_ros_tools/init_helpers.py +++ b/mil_common/utils/mil_tools/mil_ros_tools/init_helpers.py @@ -2,6 +2,7 @@ This module provides functions which help to ensure that resources are available when needed. """ + import time from typing import Any, Optional diff --git a/mil_common/utils/mil_tools/mil_ros_tools/label_me_bag.py b/mil_common/utils/mil_tools/mil_ros_tools/label_me_bag.py index d3a98fa67..aa7f91142 100755 --- a/mil_common/utils/mil_tools/mil_ros_tools/label_me_bag.py +++ b/mil_common/utils/mil_tools/mil_ros_tools/label_me_bag.py @@ -53,13 +53,13 @@ def __init__(self, config): self.topics = config["topics"] if not isinstance(self.topics, list): self.topics = [self.topics] - self.start = config["start"] if "start" in config else None - self.stop = config["stop"] if "stop" in config else None - self.freq = config["freq"] if "freq" in config else None + self.start = config.get("start") + self.stop = config.get("stop") + self.freq = config.get("freq") self.name = ( config["name"] if "name" in config else self.default_name(self.filename) ) - self.outfile = config["outfile"] if "outfile" in config else self.filename + self.outfile = config.get("outfile", self.filename) class BagToLabelMe: @@ -263,10 +263,7 @@ def completion_report(self): total_img_count += i if total_img_count == 0: print( - "{}/{} TOTAL images labeled (0%)".format( - total_xml_count, - total_img_count, - ), + f"{total_xml_count}/{total_img_count} TOTAL images labeled (0%)", ) else: print( diff --git a/mil_common/utils/mil_tools/mil_ros_tools/msg_helpers.py b/mil_common/utils/mil_tools/mil_ros_tools/msg_helpers.py index 9ffa9b2d9..8ab315818 100644 --- a/mil_common/utils/mil_tools/mil_ros_tools/msg_helpers.py +++ b/mil_common/utils/mil_tools/mil_ros_tools/msg_helpers.py @@ -58,10 +58,7 @@ def rosmsg_to_numpy(rosmsg, keys=None): break assert ( len(output_array) != 0 - ), "Input type {} has none of these attributes {}.".format( - type(rosmsg).__name__, - keys, - ) + ), f"Input type {type(rosmsg).__name__} has none of these attributes {keys}." return np.array(output_array).astype(np.float32) else: diff --git a/mil_common/utils/mil_tools/nodes/online_bagger.py b/mil_common/utils/mil_tools/nodes/online_bagger.py index 8b9285a32..a80e5714a 100755 --- a/mil_common/utils/mil_tools/nodes/online_bagger.py +++ b/mil_common/utils/mil_tools/nodes/online_bagger.py @@ -89,10 +89,7 @@ def get_subscriber_list(self, status): sub_list = "" for topic in self.subscriber_list: if self.subscriber_list[topic][1] == status: - sub_list = sub_list + "\n{:13}, {}".format( - self.subscriber_list[topic], - topic, - ) + sub_list = sub_list + f"\n{self.subscriber_list[topic]:13}, {topic}" return sub_list def get_params(self): diff --git a/mil_common/utils/mil_tools/nodes/tf_fudger.py b/mil_common/utils/mil_tools/nodes/tf_fudger.py index 58a647757..0ae508c98 100755 --- a/mil_common/utils/mil_tools/nodes/tf_fudger.py +++ b/mil_common/utils/mil_tools/nodes/tf_fudger.py @@ -45,10 +45,7 @@ ang_res = ang_range / ang_max print( - "Distance resolution: {} meters\nAngular resolution: {} radians".format( - x_res, - ang_res, - ), + f"Distance resolution: {x_res} meters\nAngular resolution: {ang_res} radians", ) cv2.createTrackbar("x", "tf", 0, x_max, lambda x: x) diff --git a/mil_common/utils/mil_tools/nodes/tf_to_gazebo.py b/mil_common/utils/mil_tools/nodes/tf_to_gazebo.py index b587dfb88..9363d3c4f 100755 --- a/mil_common/utils/mil_tools/nodes/tf_to_gazebo.py +++ b/mil_common/utils/mil_tools/nodes/tf_to_gazebo.py @@ -25,12 +25,7 @@ def main(): if do_cam_fix: rot = tf.transformations.quaternion_multiply(rot, cam_fix_quat) print( - "(qx={}, qy={} , qz={}, qw={})".format( - rot[0], - rot[1], - rot[2], - rot[3], - ), + f"(qx={rot[0]}, qy={rot[1]} , qz={rot[2]}, qw={rot[3]})", ) print(f"(x={trans[0]}, y={trans[1]}, z={trans[2]})") euler = tf.transformations.euler_from_quaternion(rot) diff --git a/mil_common/utils/mil_tools/test/test_ros_tools.py b/mil_common/utils/mil_tools/test/test_ros_tools.py index bbcc5511b..2c0eeeca5 100644 --- a/mil_common/utils/mil_tools/test/test_ros_tools.py +++ b/mil_common/utils/mil_tools/test/test_ros_tools.py @@ -131,10 +131,7 @@ def test_make_rotation(self): [0.0, 0.0, 0.0], np.cross(p_rotated, q), atol=1e-5, - err_msg="The generated rotation matrix did not align the input vectors, {} to {}".format( - p, - q, - ), + err_msg=f"The generated rotation matrix did not align the input vectors, {p} to {q}", ) self.assertGreater( np.dot(p_rotated, q), diff --git a/requirements.txt b/requirements.txt index 90237fb22..6ff0b0ecc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,14 +15,14 @@ scipy==1.10.0 scikit-learn==1.1.1 # Computer Vision -Pillow==9.3.0 +Pillow==10.2.0 # File Handling PyYAML==6.0 urdf-parser-py==0.0.4 # Internet -aiohttp==3.8.5 +aiohttp==3.9.2 aiohttp-xmlrpc==1.5.0 # Documentation diff --git a/ruff.toml b/ruff.toml index 69b8787be..56794e48d 100644 --- a/ruff.toml +++ b/ruff.toml @@ -28,6 +28,7 @@ extend-exclude = [ target-version = "py38" +[lint] ignore = [ "E501", # Line length "F405", # Unknown import @@ -35,6 +36,7 @@ ignore = [ "D212", # we use second line! "D200", # one line docstrings are not shortened! "SIM115", # too many for now... + "RUF012", # too many for now, adds obvious ClassVar statements ] [per-file-ignores] diff --git a/scripts/install.sh b/scripts/install.sh index 8a95fdf55..94e07590c 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -185,6 +185,7 @@ EOF # Documentation dependencies mil_system_install python3-pip python3-setuptools +sudo apt reinstall -y python3-pip # Disable "automatic updates" Ubuntu prompt (thanks to https://askubuntu.com/a/610623!) sudo sed -i 's/Prompt=.*/Prompt=never/' /etc/update-manager/release-upgrades