file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
DigitalBotLab/3DRotationCalculator/Extension/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
DigitalBotLab/3DRotationCalculator/Extension/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import shutil import sys import tempfile import zipfile __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,844
Python
33.166666
108
0.703362
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "rotaiton calculator" description="A simple python extension example to use as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import rotaiton.calculator". [[python.module]] name = "rotaiton.calculator" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,583
TOML
31.999999
118
0.747315
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/docs/README.md
# Python Extension Example [rotaiton.calculator] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
178
Markdown
34.799993
126
0.792135
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/docs/index.rst
rotaiton.calculator ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"rotaiton.calculator" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
339
reStructuredText
15.190475
43
0.625369
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/numpy_utils.py
import numpy as np import math def quat_to_euler_angles(q, degrees: bool = False): """Convert quaternion to Euler XYZ angles. Args: q (np.ndarray): quaternion (w, x, y, z). degrees (bool, optional): Whether output angles are in degrees. Defaults to False. Returns: np.ndarray: Euler XYZ angles. """ q = q.reshape(-1, 4) w, x, y, z = q[:, 0], q[:, 1], q[:, 2], q[:, 3] roll = np.arctan2(2 * (w * x + y * z), 1 - 2 * (x * x + y * y)) pitch = np.arcsin(2 * (w * y - z * x)) yaw = np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)) if degrees: roll = np.degrees(roll) pitch = np.degrees(pitch) yaw = np.degrees(yaw) return np.stack([roll, pitch, yaw], axis=-1) def euler_angles_to_quat(euler_angles: np.ndarray, degrees: bool = False) -> np.ndarray: """Convert Euler XYZ angles to quaternion. Args: euler_angles (np.ndarray): Euler XYZ angles. degrees (bool, optional): Whether input angles are in degrees. Defaults to False. Returns: np.ndarray: quaternion (w, x, y, z). """ roll, pitch, yaw = euler_angles if degrees: roll = math.radians(roll) pitch = math.radians(pitch) yaw = math.radians(yaw) cr = np.cos(roll / 2.0) sr = np.sin(roll / 2.0) cy = np.cos(yaw / 2.0) sy = np.sin(yaw / 2.0) cp = np.cos(pitch / 2.0) sp = np.sin(pitch / 2.0) w = (cr * cp * cy) + (sr * sp * sy) x = (sr * cp * cy) - (cr * sp * sy) y = (cr * sp * cy) + (sr * cp * sy) z = (cr * cp * sy) - (sr * sp * cy) return np.array([w, x, y, z]) def orientation_error(desired, current): cc = quat_conjugate(current) q_r = quat_mul(desired, cc) return q_r[:, 0:3] * np.sign(q_r[:, 3])[:, None] def quat_mul(a, b): assert a.shape == b.shape shape = a.shape a = a.reshape(-1, 4) b = b.reshape(-1, 4) x1, y1, z1, w1 = a[:, 0], a[:, 1], a[:, 2], a[:, 3] x2, y2, z2, w2 = b[:, 0], b[:, 1], b[:, 2], b[:, 3] ww = (z1 + x1) * (x2 + y2) yy = (w1 - y1) * (w2 + z2) zz = (w1 + y1) * (w2 - z2) xx = ww + yy + zz qq = 0.5 * (xx + (z1 - x1) * (x2 - y2)) w = qq - ww + (z1 - y1) * (y2 - z2) x = qq - xx + (x1 + w1) * (x2 + w2) y = qq - yy + (w1 - x1) * (y2 + z2) z = qq - zz + (z1 + y1) * (w2 - x2) quat = np.stack([x, y, z, w], axis=-1).reshape(shape) return quat def normalize(x, eps: float = 1e-9): return x / np.clip(np.linalg.norm(x, axis=-1), a_min=eps, a_max=None)[:, None] def quat_unit(a): return normalize(a) def quat_from_angle_axis(angle, axis): theta = (angle / 2)[:, None] xyz = normalize(axis) * np.sin(theta) w = np.cos(theta) return quat_unit(np.concatenate([xyz, w], axis=-1)) def quat_rotate(q, v): shape = q.shape q_w = q[:, -1] q_vec = q[:, :3] a = v * (2.0 * q_w ** 2 - 1.0)[:, None] b = np.cross(q_vec, v) * q_w[:, None] * 2.0 c = q_vec * np.sum(q_vec * v, axis=1).reshape(shape[0], -1) * 2.0 return a + b + c def quat_conjugate(a): shape = a.shape a = a.reshape(-1, 4) return np.concatenate((-a[:, :3], a[:, -1:]), axis=-1).reshape(shape) def quat_axis(q, axis=0): basis_vec = np.zeros((q.shape[0], 3)) basis_vec[:, axis] = 1 return quat_rotate(q, basis_vec)
3,329
Python
27.706896
90
0.50766
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/extension.py
import omni.ext import omni.ui as ui from .ui.custom_multifield_widget import CustomMultifieldWidget from pxr import Gf import numpy as np from .numpy_utils import euler_angles_to_quat # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class RotaitonCalculatorExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[rotaiton.calculator] rotaiton calculator startup") self._count = 0 self._window = ui.Window("3D Rotation Calculator", width=300, height=100, visible=True) with self._window.frame: with ui.VStack(): with ui.CollapsableFrame("Quaternion mul", collapsed=False, height = 0): with ui.VStack(): with ui.HStack(height = 20): self.q1_widget = CustomMultifieldWidget( label="Quaternion 1:", sublabels=[ "w", "x", "y", "z"], default_vals=[1, 0, 0, 0], ) with ui.HStack(height = 20): self.q2_widget = CustomMultifieldWidget( label="Quaternion 2:", sublabels=[ "w", "x", "y", "z"], default_vals=[1, 0, 0, 0], ) ui.Line(height = 5) with ui.HStack(height = 20): self.q_widget = CustomMultifieldWidget( label="Result:", sublabels=[ "w", "x", "y", "z"], default_vals=[1, 0, 0, 0], read_only= True ) self.q_str_widget = ui.StringField(width = 200, height = 20) ui.Line(height = 5) with ui.HStack(): ui.Button("Quaternion mul", height = 20, clicked_fn=self.quaternioin_mul) with ui.CollapsableFrame("Euler to Quaternion", collapsed=False, height = 0): with ui.VStack(): with ui.HStack(height = 20): self.euler_widget = CustomMultifieldWidget( label="Euler angles (degree):", sublabels=[ "roll", "pitch", "yaw"], default_vals=[0, 0, 0], ) ui.Line(height = 5) with ui.HStack(height = 20): self.quat_widget = CustomMultifieldWidget( label="Quaternion:", sublabels=[ "w", "x", "y", "z"], default_vals=[1, 0, 0, 0], read_only= True ) ui.Button("Euler to Quat", height = 20, clicked_fn=self.euler2quat) def on_shutdown(self): print("[rotaiton.calculator] rotaiton calculator shutdown") def quaternioin_mul(self): print("quaternioin_mul") q1 = [self.q1_widget.multifields[i].model.as_float for i in range(4)] # wxyz q1 = Gf.Quatf(q1[0], q1[1], q1[2], q1[3]) q2 = [self.q2_widget.multifields[i].model.as_float for i in range(4)] # wxyz q2 = Gf.Quatf(q2[0], q2[1], q2[2], q2[3]) q = q1 * q2 self.q_widget.update([q.GetReal(), *q.GetImaginary()]) self.q_str_widget.model.set_value(str(q)) def euler2quat(self): print("euler2quat") euler = [self.euler_widget.multifields[i].model.as_float for i in range(3)] # roll pitch yaw q = euler_angles_to_quat(euler, degrees=True).tolist() self.quat_widget.update(q)
4,260
Python
49.129411
119
0.482629
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/ui/custom_radio_collection.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomRadioCollection"] from typing import List, Optional import omni.ui as ui from .style import ATTR_LABEL_WIDTH SPACING = 5 class CustomRadioCollection: """A custom collection of radio buttons. The group_name is on the first line, and each label and radio button are on subsequent lines. This one does not inherit from CustomBaseWidget because it doesn't have the same Head label, and doesn't have a Revert button at the end. """ def __init__(self, group_name: str, labels: List[str], model: ui.AbstractItemModel = None, default_value: bool = True, **kwargs): self.__group_name = group_name self.__labels = labels self.__default_val = default_value self.__images = [] self.__selection_model = ui.SimpleIntModel(default_value) self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__images = [] self.__selection_model = None self.__frame = None @property def model(self) -> Optional[ui.AbstractValueModel]: """The widget's model""" if self.__selection_model: return self.__selection_model @model.setter def model(self, value: int): """The widget's model""" self.__selection_model.set(value) def __getattr__(self, attr): """ Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__frame, attr) def _on_value_changed(self, index: int = 0): """Set states of all radio buttons so only one is On.""" self.__selection_model.set_value(index) for i, img in enumerate(self.__images): img.checked = i == index img.name = "radio_on" if img.checked else "radio_off" def _build_fn(self): """Main meat of the widget. Draw the group_name label, label and radio button for each row, and set up callbacks to keep them updated. """ with ui.VStack(spacing=SPACING): ui.Spacer(height=2) ui.Label(self.__group_name.upper(), name="radio_group_name", width=ATTR_LABEL_WIDTH) for i, label in enumerate(self.__labels): with ui.HStack(): ui.Label(label, name="attribute_name", width=ATTR_LABEL_WIDTH) with ui.HStack(): with ui.VStack(): ui.Spacer(height=2) self.__images.append( ui.Image( name=("radio_on" if self.__default_val == i else "radio_off"), fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=16, width=16, checked=self.__default_val ) ) ui.Spacer() ui.Spacer(height=2) # Set up a mouse click callback for each radio button image for i in range(len(self.__labels)): self.__images[i].set_mouse_pressed_fn( lambda x, y, b, m, i=i: self._on_value_changed(i))
3,781
Python
35.718446
98
0.556467
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/ui/controller.py
# controller import carb class UIController(): w = False s = False a = False d = False q = False e = False up = False down = False left = False right = False # Controller.scale = 0.1 left_control = False def __init__(self) -> None: self.user_control = 0.25 self.network_control = 0.25 UIController.reset_movement() @classmethod def reset_movement(cls): UIController.w = False UIController.s = False UIController.a = False UIController.d = False UIController.q = False UIController.e = False UIController.up = False UIController.down = False UIController.left = False UIController.right = False # Controller.left_control = False def handle_keyboard_event(self, event): if ( event.type == carb.input.KeyboardEventType.KEY_PRESS or event.type == carb.input.KeyboardEventType.KEY_REPEAT ): # print("event input", event.input) if event.input == carb.input.KeyboardInput.W: UIController.w = True if event.input == carb.input.KeyboardInput.S: UIController.s = True if event.input == carb.input.KeyboardInput.A: UIController.a = True if event.input == carb.input.KeyboardInput.D: UIController.d = True if event.input == carb.input.KeyboardInput.Q: UIController.q = True if event.input == carb.input.KeyboardInput.E: UIController.e = True if event.input == carb.input.KeyboardInput.UP: UIController.up = True if event.input == carb.input.KeyboardInput.DOWN: UIController.down = True if event.input == carb.input.KeyboardInput.LEFT: UIController.left = True if event.input == carb.input.KeyboardInput.RIGHT: UIController.right = True if event.input == carb.input.KeyboardInput.LEFT_CONTROL: UIController.left_control = True if event.type == carb.input.KeyboardEventType.KEY_RELEASE: # print("event release", event.input) if event.input == carb.input.KeyboardInput.W: UIController.w = False if event.input == carb.input.KeyboardInput.S: UIController.s = False if event.input == carb.input.KeyboardInput.A: UIController.a = False if event.input == carb.input.KeyboardInput.D: UIController.d = False if event.input == carb.input.KeyboardInput.Q: UIController.q = False if event.input == carb.input.KeyboardInput.E: UIController.e = False if event.input == carb.input.KeyboardInput.UP: UIController.up = False if event.input == carb.input.KeyboardInput.DOWN: UIController.down = False if event.input == carb.input.KeyboardInput.LEFT: UIController.left = False if event.input == carb.input.KeyboardInput.RIGHT: UIController.right = False if event.input == carb.input.KeyboardInput.LEFT_CONTROL: UIController.left_control = False def PoolUserControl(self): return self.user_control def PoolNetworkControl(self): return 0.1 if UIController.w else 0.25 def QueryMove(self): move = [0, 0, 0] if UIController.w: move[0] += 1 if UIController.s: move[0] -= 1 if UIController.a: move[1] += 1 if UIController.d: move[1] -= 1 if UIController.q: move[2] -= 1 if UIController.e: move[2] += 1 return move def QueryRotation(self): rotation = [0, 0] if UIController.up: rotation[0] += 1 if UIController.down: rotation[0] -= 1 if UIController.left: rotation[1] += 1 if UIController.right: rotation[1] -= 1 return rotation def QueryGripper(self): if not UIController.left_control: return 1 # open else: return -1 # close
4,435
Python
30.239436
68
0.544081
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/ui/style.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["julia_modeler_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) ATTR_LABEL_WIDTH = 150 BLOCK_HEIGHT = 22 TAIL_WIDTH = 35 WIN_WIDTH = 400 WIN_HEIGHT = 930 # Pre-defined constants. It's possible to change them at runtime. cl_window_bg_color = cl(0.2, 0.2, 0.2, 1.0) cl_window_title_text = cl(.9, .9, .9, .9) cl_collapsible_header_text = cl(.8, .8, .8, .8) cl_collapsible_header_text_hover = cl(.95, .95, .95, 1.0) cl_main_attr_label_text = cl(.65, .65, .65, 1.0) cl_main_attr_label_text_hover = cl(.9, .9, .9, 1.0) cl_multifield_label_text = cl(.65, .65, .65, 1.0) cl_combobox_label_text = cl(.65, .65, .65, 1.0) cl_field_bg = cl(0.18, 0.18, 0.18, 1.0) cl_field_border = cl(1.0, 1.0, 1.0, 0.2) cl_btn_border = cl(1.0, 1.0, 1.0, 0.4) cl_slider_fill = cl(1.0, 1.0, 1.0, 0.3) cl_revert_arrow_enabled = cl(.25, .5, .75, 1.0) cl_revert_arrow_disabled = cl(.35, .35, .35, 1.0) cl_transparent = cl(0, 0, 0, 0) fl_main_label_attr_hspacing = 10 fl_attr_label_v_spacing = 3 fl_collapsable_group_spacing = 2 fl_outer_frame_padding = 15 fl_tail_icon_width = 15 fl_border_radius = 3 fl_border_width = 1 fl_window_title_font_size = 18 fl_field_text_font_size = 14 fl_main_label_font_size = 14 fl_multi_attr_label_font_size = 14 fl_radio_group_font_size = 14 fl_collapsable_header_font_size = 13 fl_range_text_size = 10 url_closed_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/closed.svg" url_open_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/opened.svg" url_revert_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/revert_arrow.svg" url_checkbox_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/checkbox_on.svg" url_checkbox_off_icon = f"{EXTENSION_FOLDER_PATH}/icons/checkbox_off.svg" url_radio_btn_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/radio_btn_on.svg" url_radio_btn_off_icon = f"{EXTENSION_FOLDER_PATH}/icons/radio_btn_off.svg" url_diag_bg_lines_texture = f"{EXTENSION_FOLDER_PATH}/icons/diagonal_texture_screenshot.png" # D:\DBL\Robots\robot-exts-control\exts\control\icons\diagonal_texture_screenshot.png print("url_revert_arrow_icon: ", EXTENSION_FOLDER_PATH, "-", url_revert_arrow_icon) # The main style dict julia_modeler_style = { "Button::tool_button": { "background_color": cl_field_bg, "margin_height": 0, "margin_width": 6, "border_color": cl_btn_border, "border_width": fl_border_width, "font_size": fl_field_text_font_size, }, "CollapsableFrame::group": { "margin_height": fl_collapsable_group_spacing, "background_color": cl_transparent, }, # TODO: For some reason this ColorWidget style doesn't respond much, if at all (ie, border_radius, corner_flag) "ColorWidget": { "border_radius": fl_border_radius, "border_color": cl(0.0, 0.0, 0.0, 0.0), }, "Field": { "background_color": cl_field_bg, "border_radius": fl_border_radius, "border_color": cl_field_border, "border_width": fl_border_width, }, "Field::attr_field": { "corner_flag": ui.CornerFlag.RIGHT, "font_size": 2, # fl_field_text_font_size, # Hack to allow for a smaller field border until field padding works }, "Field::attribute_color": { "font_size": fl_field_text_font_size, }, "Field::multi_attr_field": { "padding": 4, # TODO: Hacky until we get padding fix "font_size": fl_field_text_font_size, }, "Field::path_field": { "corner_flag": ui.CornerFlag.RIGHT, "font_size": fl_field_text_font_size, }, "HeaderLine": {"color": cl(.5, .5, .5, .5)}, "Image::collapsable_opened": { "color": cl_collapsible_header_text, "image_url": url_open_arrow_icon, }, "Image::collapsable_opened:hovered": { "color": cl_collapsible_header_text_hover, "image_url": url_open_arrow_icon, }, "Image::collapsable_closed": { "color": cl_collapsible_header_text, "image_url": url_closed_arrow_icon, }, "Image::collapsable_closed:hovered": { "color": cl_collapsible_header_text_hover, "image_url": url_closed_arrow_icon, }, "Image::radio_on": {"image_url": url_radio_btn_on_icon}, "Image::radio_off": {"image_url": url_radio_btn_off_icon}, "Image::revert_arrow": { "image_url": url_revert_arrow_icon, "color": cl_revert_arrow_enabled, }, "Image::revert_arrow:disabled": {"color": cl_revert_arrow_disabled}, "Image::checked": {"image_url": url_checkbox_on_icon}, "Image::unchecked": {"image_url": url_checkbox_off_icon}, "Image::slider_bg_texture": { "image_url": url_diag_bg_lines_texture, "border_radius": fl_border_radius, "corner_flag": ui.CornerFlag.LEFT, }, "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_TOP, "margin_height": fl_attr_label_v_spacing, "margin_width": fl_main_label_attr_hspacing, "color": cl_main_attr_label_text, "font_size": fl_main_label_font_size, }, "Label::attribute_name:hovered": {"color": cl_main_attr_label_text_hover}, "Label::collapsable_name": {"font_size": fl_collapsable_header_font_size}, "Label::multi_attr_label": { "color": cl_multifield_label_text, "font_size": fl_multi_attr_label_font_size, }, "Label::radio_group_name": { "font_size": fl_radio_group_font_size, "alignment": ui.Alignment.CENTER, "color": cl_main_attr_label_text, }, "Label::range_text": { "font_size": fl_range_text_size, }, "Label::window_title": { "font_size": fl_window_title_font_size, "color": cl_window_title_text, }, "ScrollingFrame::window_bg": { "background_color": cl_window_bg_color, "padding": fl_outer_frame_padding, "border_radius": 20 # Not obvious in a window, but more visible with only a frame }, "Slider::attr_slider": { "draw_mode": ui.SliderDrawMode.FILLED, "padding": 0, "color": cl_transparent, # Meant to be transparent, but completely transparent shows opaque black instead. "background_color": cl(0.28, 0.28, 0.28, 0.01), "secondary_color": cl_slider_fill, "border_radius": fl_border_radius, "corner_flag": ui.CornerFlag.LEFT, # TODO: Not actually working yet OM-53727 }, # Combobox workarounds "Rectangle::combobox": { # TODO: remove when ComboBox can have a border "background_color": cl_field_bg, "border_radius": fl_border_radius, "border_color": cl_btn_border, "border_width": fl_border_width, }, "ComboBox::dropdown_menu": { "color": cl_combobox_label_text, # label color "padding_height": 1.25, "margin": 2, "background_color": cl_field_bg, "border_radius": fl_border_radius, "font_size": fl_field_text_font_size, "secondary_color": cl_transparent, # button background color }, "Rectangle::combobox_icon_cover": {"background_color": cl_field_bg}, "Button::control_button": { "background_color": cl.field_bg, "border_color": cl.btn_border, "border_width": fl.border_width, "border_radius": 4, "margin": 2, "corner_flag": ui.CornerFlag.ALL, }, "Button::control_button_disabled": { "background_color": cl(0.1, 0.7, 0.3, 0.4), "border_color": cl.btn_border, "border_width": fl.border_width, "border_radius": 4, "margin": 2, "corner_flag": ui.CornerFlag.ALL, }, "Button::control_button_pressed1": { "background_color": cl( 0.7, 0.1, 0.3, 0.3), "border_color": cl.btn_border, "border_width": fl.border_width, "border_radius": 4, "margin": 2, "corner_flag": ui.CornerFlag.ALL, }, "Button::control_button_pressed2": { "background_color": cl(0.1, 0.3, 0.7, 0.3), "border_color": cl.btn_border, "border_width": fl.border_width, "border_radius": 4, "margin": 2, "corner_flag": ui.CornerFlag.ALL, }, "Button::control_button_pressed3": { "background_color": cl(0.7, 0.3, 0.7, 0.3), "border_color": cl.btn_border, "border_width": fl.border_width, "border_radius": 4, "margin": 2, "corner_flag": ui.CornerFlag.ALL, }, }
9,045
Python
35.772358
121
0.620122
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/ui/custom_bool_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomBoolWidget"] import omni.ui as ui from .custom_base_widget import CustomBaseWidget class CustomBoolWidget(CustomBaseWidget): """A custom checkbox or switch widget""" def __init__(self, model: ui.AbstractItemModel = None, default_value: bool = True, **kwargs): self.__default_val = default_value self.bool_image = None # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) @property def value(self): """Return the current value of the widget.""" return self.bool_image.checked def destroy(self): CustomBaseWidget.destroy() self.bool_image = None def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.bool_image.checked = self.__default_val self.bool_image.name = ( "checked" if self.bool_image.checked else "unchecked" ) self.revert_img.enabled = False def _on_value_changed(self): """Swap checkbox images and set revert_img to correct state.""" self.bool_image.checked = not self.bool_image.checked self.bool_image.name = ( "checked" if self.bool_image.checked else "unchecked" ) self.revert_img.enabled = self.__default_val != self.bool_image.checked def _build_body(self): """Main meat of the widget. Draw the appropriate checkbox image, and set up callback. """ with ui.HStack(): with ui.VStack(): # Just shift the image down slightly (2 px) so it's aligned the way # all the other rows are. ui.Spacer(height=2) self.bool_image = ui.Image( name="checked" if self.__default_val else "unchecked", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=16, width=16, checked=self.__default_val ) # Let this spacer take up the rest of the Body space. ui.Spacer() self.bool_image.set_mouse_pressed_fn( lambda x, y, b, m: self._on_value_changed())
2,731
Python
35.918918
87
0.610033
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/ui/custom_multifield_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomMultifieldWidget"] from typing import List, Optional import omni.ui as ui from .custom_base_widget import CustomBaseWidget class CustomMultifieldWidget(CustomBaseWidget): """A custom multifield widget with a variable number of fields, and customizable sublabels. """ def __init__(self, model: ui.AbstractItemModel = None, sublabels: Optional[List[str]] = None, default_vals: Optional[List[float]] = None, read_only: bool = False, **kwargs): self.__field_labels = sublabels or ["X", "Y", "Z"] self.__default_vals = default_vals or [0.0] * len(self.__field_labels) self.read_only = read_only self.multifields = [] # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.multifields = [] @property def model(self, index: int = 0) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.multifields: return self.multifields[index].model @model.setter def model(self, value: ui.AbstractItemModel, index: int = 0): """The widget's model""" self.multifields[index].model = value def _restore_default(self): """Restore the default values.""" if self.revert_img.enabled: for i in range(len(self.multifields)): model = self.multifields[i].model model.as_float = self.__default_vals[i] self.revert_img.enabled = False def _on_value_changed(self, val_model: ui.SimpleFloatModel, index: int): """Set revert_img to correct state.""" val = val_model.as_float self.revert_img.enabled = self.__default_vals[index] != val def _build_body(self): """Main meat of the widget. Draw the multiple Fields with their respective labels, and set up callbacks to keep them updated. """ with ui.HStack(): for i, (label, val) in enumerate(zip(self.__field_labels, self.__default_vals)): with ui.HStack(spacing=3): ui.Label(label, name="multi_attr_label", width=0) model = ui.SimpleFloatModel(val) # TODO: Hopefully fix height after Field padding bug is merged! self.multifields.append( ui.FloatField(model=model, name="multi_attr_field")) if self.read_only: self.multifields[i].enabled = False if i < len(self.__default_vals) - 1: # Only put space between fields and not after the last one ui.Spacer(width=15) for i, f in enumerate(self.multifields): f.model.add_value_changed_fn(lambda v: self._on_value_changed(v, i)) def update(self, multi_values: list): """Update the widget.""" for i, f in enumerate(self.multifields): f.model.as_float = multi_values[i]
3,584
Python
39.280898
92
0.607422
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/ui/indoorkit_ui_widget.py
from typing import List, Optional import omni import omni.ui as ui from .style import ATTR_LABEL_WIDTH, cl, fl from .custom_base_widget import CustomBaseWidget from .controller import UIController SPACING = 5 class TaskTypeComboboxWidget(): """A customized combobox widget""" def __init__(self, model: ui.AbstractItemModel = None, options: List[str] = None, default_value=0, on_restore_fn: callable = None, **kwargs): """ Set up the take type combo box widget ::params: :on_restore_fn: call when write/restore the widget """ self.__default_val = default_value self.__options = options or ["1", "2", "3"] self.__combobox_widget = None self.on_restore_fn = on_restore_fn # Call at the end, rather than start, so build_fn runs after all the init stuff # CustomBaseWidget.__init__(self, model=model, **kwargs) self.existing_model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.revert_img = None self.__attr_label: Optional[str] = kwargs.pop("label", "") self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.existing_model = None self.revert_img = None self.__attr_label = None self.__frame = None self.__options = None self.__combobox_widget = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__combobox_widget: return self.__combobox_widget.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__combobox_widget.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" model = self.__combobox_widget.model index = model.get_item_value_model().get_value_as_int() self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: # self.__combobox_widget.model.get_item_value_model().set_value( # self.__default_val) self.revert_img.enabled = False if self.on_restore_fn: self.on_restore_fn(True) else: self.revert_img.enabled = True if self.on_restore_fn: self.on_restore_fn(False) def _build_body(self): """Main meat of the widget. Draw the Rectangle, Combobox, and set up callbacks to keep them updated. """ with ui.HStack(): with ui.ZStack(): # TODO: Simplify when borders on ComboBoxes work in Kit! # and remove style rule for "combobox" Rect # Use the outline from the Rectangle for the Combobox ui.Rectangle(name="combobox", height=22) option_list = list(self.__options) self.__combobox_widget = ui.ComboBox( 0, *option_list, name="dropdown_menu", # Abnormal height because this "transparent" combobox # has to fit inside the Rectangle behind it height=10 ) # Swap for different dropdown arrow image over current one with ui.HStack(): ui.Spacer() # Keep it on the right side with ui.VStack(width=0): # Need width=0 to keep right-aligned ui.Spacer(height=5) with ui.ZStack(): ui.Rectangle(width=15, height=15, name="combobox_icon_cover") ui.Image(name="collapsable_closed", width=12, height=12) ui.Spacer(width=2) # Right margin ui.Spacer(width=ui.Percent(5)) self.__combobox_widget.model.add_item_changed_fn(self._on_value_changed) def _build_head(self): """Build the left-most piece of the widget line (label in this case)""" ui.Label( self.__attr_label, width=80, style = {"color": "lightsteelblue", "margin_height": 2, "alignment": ui.Alignment.RIGHT_TOP} ) def _build_tail(self): """Build the right-most piece of the widget line. In this case, we have a Revert Arrow button at the end of each widget line. """ with ui.HStack(width=0): # ui.Spacer(width=5) with ui.VStack(height=0): ui.Spacer(height=3) self.revert_img = ui.Image( name="revert_arrow_task_type", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=12, height=13, enabled=False, tooltip="randomly fill (or reset) task type, object id, and house id." ) ui.Spacer(width=5) # call back for revert_img click, to restore the default value self.revert_img.set_mouse_pressed_fn( lambda x, y, b, m: self._restore_default()) def _build_fn(self): """Puts the 3 pieces together.""" with ui.HStack(): self._build_head() self._build_body() self._build_tail() class CustomRecordGroup: STYLE = { "Rectangle::image_button": { "background_color": 0x0, "border_width": 1.5, "border_radius": 2.0, "margin": 4, "border_color": cl.btn_border, "corner_flag": ui.CornerFlag.RIGHT, }, "Rectangle::image_button:hovered": { "background_color": 0xAAB8B8B8, "border_width": 0, "border_radius": 2.0, }, "Rectangle::image_button:selected": { "background_color": 0x0, "border_width": 1, "border_color": 0xFFC5911A, "border_radius": 2.0, }, } def __init__(self, width = 60, height = 60, on_click_record_fn: callable = None, on_click_stop_fn: callable = None, on_click_replay_fn: callable = None, ): self.timeline = omni.timeline.get_timeline_interface() self.on_click_record_fn = on_click_record_fn self.on_click_stop_fn = on_click_stop_fn self.on_click_replay_fn = on_click_replay_fn # another ui for control self.control_group : CustomControlGroup = None self._selected = False with ui.HStack(): with ui.HStack(): with ui.ZStack(width=0, height=0, spacing=0): # with ui.Placer(offset_x=width, offset_y=0): self.play_label = ui.Label("Record", width = 60) with ui.Placer(offset_x=0, offset_y=0): self.rect_play = ui.Rectangle(name="image_button", width=2 * width, height=height, style=CustomRecordGroup.STYLE) with ui.Placer(offset_x=5, offset_y=5): self.image_play = ui.Image( name="start_on", width=width - 10, height=height - 10, fill_policy=ui.FillPolicy.STRETCH ) self.rect_play.set_mouse_pressed_fn(lambda x, y, btn, a: self._on_mouse_pressed_play(btn)) with ui.ZStack(width=0, height=0, spacing=0): # with ui.Placer(offset_x=width, offset_y=0): self.stop_label = ui.Label("Stop", width = 60) with ui.Placer(offset_x=0, offset_y=0): self.rect_stop = ui.Rectangle(name="image_button", width=2 * width, height=height, style=CustomRecordGroup.STYLE) with ui.Placer(offset_x=5, offset_y=5): self.image_stop = ui.Image( name="stop_on", width=width - 10, height=height - 10, fill_policy=ui.FillPolicy.STRETCH ) self.rect_stop.set_mouse_pressed_fn(lambda x, y, btn, a: self._on_mouse_pressed_stop(btn)) # with ui.HStack(): with ui.ZStack(width=0, height=0, spacing=0): with ui.Placer(offset_x=width, offset_y=0): self.replay_label = ui.Label("Replay", width = 60) with ui.Placer(offset_x=0, offset_y=0): self.rect_replay = ui.Rectangle(name="image_button", width= 2 * width, height=height, style=CustomRecordGroup.STYLE) with ui.Placer(offset_x=10, offset_y=10): self.image_replay = ui.Image( name="replay_on", width=width - 20, height=height - 20, fill_policy=ui.FillPolicy.STRETCH ) self.rect_replay.set_mouse_pressed_fn(lambda x, y, btn, a: self._on_mouse_pressed_replay(btn)) def __del__(self): # set ui.Image objects to None explicitly to avoid this error: # Client omni.ui Failed to acquire interface [omni::kit::renderer::IGpuFoundation v0.2] while unloading all plugins self.image_play = None def _on_mouse_pressed_play(self, key): # 0 is for mouse left button if key == 0: if self.timeline.is_stopped(): # if stopped, start recording self.play_label.text = "Pause" self.image_play.name = "pause_on" self.on_click_record_fn() if self.control_group: self.control_group.enable() elif self.timeline.is_playing(): # if is playing, pause self.play_label.text = "Continue" self.image_play.name = "start_on" self.timeline.pause() else: # if is paused, just play self.play_label.text = "Pause" self.image_play.name = "pause_on" self.timeline.play() def _on_mouse_pressed_replay(self, key): # 0 is for mouse left button if key == 0: if self.timeline.is_stopped(): # if stopped, start recording self.replay_label.text = "Pause" self.image_replay.name = "pause_on" self.on_click_replay_fn() elif self.timeline.is_playing(): # if is playing, pause self.replay_label.text = "Continue" self.image_replay.name = "replay_on" self.timeline.pause() else: # if is paused, just play self.replay_label.text = "Pause" self.image_replay.name = "pause_on" self.timeline.play() def _on_mouse_pressed_stop(self, key): # print("press stop button", self.timeline.is_playing(), self.timeline.is_stopped()) # 0 is for mouse left button if key == 0: self.play_label.text = "Record" self.image_play.name = "start_on" self.replay_label.text = "Replay" self.image_replay.name = "replay_on" self.on_click_stop_fn() if self.control_group: self.control_group.disable() @property def selected(self): return self._selected @selected.setter def selected(self, value): self._selected = value class CustomControlGroup(): def __init__(self) -> None: self.collapse_frame = ui.CollapsableFrame("UI control") self.collapse_frame.collapsed = False self.collapse_frame.enabled = True # ui with self.collapse_frame: with ui.VStack(height=0, spacing=0): with ui.HStack(): ui.Label("position control: ") self.button_w = ui.Button("W", name = "control_button", tooltip = "move end factor forward") self.button_s = ui.Button("S", name = "control_button", tooltip = "move end factor backward") self.button_a = ui.Button("A", name = "control_button", tooltip = "move end factor to left") self.button_d = ui.Button("D", name = "control_button", tooltip = "move end factor to right") self.button_q = ui.Button("Q", name = "control_button", tooltip = "move end factor to down") self.button_e = ui.Button("E", name = "control_button", tooltip = "move end factor to up") with ui.HStack(): ui.Label("rotation control: ") self.button_up = ui.Button("UP", name = "control_button", tooltip = "Rotate hand upward") self.button_down = ui.Button("DOWN", name = "control_button", tooltip = "Rotate hand downard") self.button_left = ui.Button("LEFT", name = "control_button", tooltip = "Rotate hand to left") self.button_right = ui.Button("RIGHT", name = "control_button", tooltip = "Rotate hand to right") with ui.HStack(): ui.Label("gripper control: ") self.button_control = ui.Button("LEFT CTRL", name = "control_button", tooltip = "Close/Open gripper") self.button_list = [self.button_w, self.button_s, self.button_a, self.button_d, self.button_q, self.button_e, self.button_up, self.button_down, self.button_left, self.button_right, ] self.button_w.set_clicked_fn(lambda : self._on_button("w")) self.button_s.set_clicked_fn(lambda : self._on_button("s")) self.button_a.set_clicked_fn(lambda : self._on_button("a")) self.button_d.set_clicked_fn(lambda : self._on_button("d")) self.button_q.set_clicked_fn(lambda : self._on_button("q")) self.button_e.set_clicked_fn(lambda : self._on_button("e")) self.button_up.set_clicked_fn(lambda : self._on_button("up", 2)) self.button_down.set_clicked_fn(lambda : self._on_button("down", 2)) self.button_left.set_clicked_fn(lambda : self._on_button("left", 2)) self.button_right.set_clicked_fn(lambda : self._on_button("right", 2)) self.button_control.set_clicked_fn(lambda: self._on_button_control()) self.disable() def enable(self): """ Enable itself by showing the robot controling buttons """ self.collapse_frame.collapsed = False self.collapse_frame.enabled = True self.enable_buttons() def disable(self): """ Disable itself by closing the robot controling buttons """ self.collapse_frame.collapsed = True # self.collapse_frame.enabled = False def disable_buttons(self): for button in self.button_list: button.name = "control_button_disabled" # button.enabled = False UIController.reset_movement() def enable_buttons(self): for button in self.button_list: button.enabled = True button.name = "control_button" UIController.reset_movement() def _on_button(self, attr_name:str, style = 1): attr = getattr(UIController, attr_name) # print("attr", attr_name, attr) button = getattr(self, f"button_{attr_name}") if attr: setattr(UIController, attr_name, False) button.name = "control_button" self.enable_buttons() else: self.disable_buttons() setattr(UIController, attr_name, True) button.enabled = True button.name = f"control_button_pressed{style}" def _on_button_control(self): if UIController.left_control: UIController.left_control = False self.button_control.text = "LEFT CTRL" self.button_control.name = "control_button" else: UIController.left_control = True self.button_control.text = "Gripper closed" self.button_control.name = "control_button_pressed3" class CustomBoolWidget(CustomBaseWidget): """A custom checkbox or switch widget""" def __init__(self, model: ui.AbstractItemModel = None, default_value: bool = True, on_checked_fn: callable = None, **kwargs): self.__default_val = default_value self.__bool_image = None self.on_checked_fn = on_checked_fn # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__bool_image = None def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.__bool_image.checked = self.__default_val self.__bool_image.name = ( "checked" if self.__bool_image.checked else "unchecked" ) self.revert_img.enabled = False def _on_value_changed(self): """Swap checkbox images and set revert_img to correct state.""" self.__bool_image.checked = not self.__bool_image.checked self.__bool_image.name = ( "checked" if self.__bool_image.checked else "unchecked" ) self.revert_img.enabled = self.__default_val != self.__bool_image.checked if self.on_checked_fn: self.on_checked_fn(self.__bool_image.checked) def _build_body(self): """Main meat of the widget. Draw the appropriate checkbox image, and set up callback. """ with ui.HStack(): with ui.VStack(): # Just shift the image down slightly (2 px) so it's aligned the way # all the other rows are. ui.Spacer(height=2) self.__bool_image = ui.Image( name="checked" if self.__default_val else "unchecked", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=16, width=16, checked=self.__default_val ) # Let this spacer take up the rest of the Body space. ui.Spacer() self.__bool_image.set_mouse_pressed_fn( lambda x, y, b, m: self._on_value_changed()) NUM_FIELD_WIDTH = 50 SLIDER_WIDTH = ui.Percent(100) FIELD_HEIGHT = 22 # TODO: Once Field padding is fixed, this should be 18 SPACING = 4 TEXTURE_NAME = "slider_bg_texture" class CustomSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "int", min=0.0, max=1.0, default_val=0.0, display_range: bool = False, on_slide_fn: callable = None, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range self.on_slide_fn = on_slide_fn # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index if self.on_slide_fn: self.on_slide_fn(index) def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls( height=FIELD_HEIGHT, min=self.__min, max=self.__max, name="attr_slider" ) if self.__display_range: self._build_display_range() with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=2) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class CustomSkySelectionGroup(CustomBaseWidget): def __init__(self, on_select_fn: callable = None ) -> None: self.on_select_fn = on_select_fn self.sky_type = "" CustomBaseWidget.__init__(self, label = "Sky type:") def _build_body(self): with ui.HStack(): self.button_clear = ui.Button("Sunny", name = "control_button") self.button_cloudy = ui.Button("Cloudy", name = "control_button") self.button_overcast = ui.Button("Overcast", name = "control_button") self.button_night = ui.Button("Night", name = "control_button") self.button_clear.set_clicked_fn(lambda : self._on_button("clear")) self.button_cloudy.set_clicked_fn(lambda : self._on_button("cloudy")) self.button_overcast.set_clicked_fn(lambda : self._on_button("overcast")) self.button_night.set_clicked_fn(lambda : self._on_button("night")) self.button_list = [self.button_clear, self.button_cloudy, self.button_overcast, self.button_night] def enable_buttons(self): for button in self.button_list: button.enabled = True button.name = "control_button" def _on_button(self, sky_type:str): if self.on_select_fn: self.on_select_fn(sky_type.capitalize()) self.enable_buttons() button = getattr(self, f"button_{sky_type}") button.name = f"control_button_pressed{2}" self.revert_img.enabled = True def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.revert_img.enabled = False self.enable_buttons() self.on_select_fn("") class CustomIdNotice(): def __init__(self) -> None: self.ui = ui.HStack() with self.ui: ui.Spacer(width=4) self.task_ui = ui.Button("pickup_object", name = "control_button", style = {"color": "lightsteelblue", "border_color": "lightsteelblue"}, enabled = False) ui.Spacer(width=4) self.object_ui = ui.Button("object: 0", name = "control_button", style = {"color": "DarkSalmon", "border_color": "DarkSalmon"}, enabled = False) ui.Spacer(width=4) self.house_ui = ui.Button("house: 1", name = "control_button", style = {"color": "Plum", "border_color": "Plum"}, enabled = False) self.ui.visible = False class CustomRenderTypeSelectionGroup(CustomBaseWidget): def __init__(self, on_select_fn: callable = None ) -> None: self.on_select_fn = on_select_fn self.sky_type = "" CustomBaseWidget.__init__(self, label = "Render type:") def _build_body(self): with ui.HStack(): self.button_rgb = ui.Button("RGB", name = "control_button_pressed3") self.button_depth= ui.Button("Depth", name = "control_button") self.button_semantic = ui.Button("Semantic", name = "control_button") self.button_rgb.set_clicked_fn(lambda : self._on_button("rgb")) self.button_depth.set_clicked_fn(lambda : self._on_button("depth")) self.button_semantic.set_clicked_fn(lambda : self._on_button("semantic")) self.button_list = [self.button_rgb, self.button_depth, self.button_semantic] def enable_buttons(self): for button in self.button_list: button.enabled = True button.name = "control_button" def _on_button(self, render_type:str): if self.on_select_fn: self.on_select_fn(render_type.capitalize()) self.enable_buttons() button = getattr(self, f"button_{render_type}") button.name = f"control_button_pressed{3}" self.revert_img.enabled = True def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.revert_img.enabled = False self.enable_buttons() self._on_button("rgb") import subprocess, os, platform class CustomPathButtonWidget: """A compound widget for holding a path in a StringField, and a button that can perform an action. TODO: Get text ellision working in the path field, to start with "..." """ def __init__(self, label: str, path: str, btn_callback: callable = None): self.__attr_label = label self.__pathfield: ui.StringField = None self.__path = path self.__btn = None self.__callback = btn_callback self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__pathfield = None self.__btn = None self.__callback = None self.__frame = None @property def model(self) -> Optional[ui.AbstractItem]: """The widget's model""" if self.__pathfield: return self.__pathfield.model @model.setter def model(self, value: ui.AbstractItem): """The widget's model""" self.__pathfield.model = value def get_path(self): return self.model.as_string def _build_fn(self): """Draw all of the widget parts and set up callbacks.""" with ui.HStack(): ui.Label( self.__attr_label, name="attribute_name", width=120, ) self.__pathfield = ui.StringField( name="path_field", enabled = False, ) ui.Spacer(width = 8) # # TODO: Add clippingType=ELLIPSIS_LEFT for long paths self.__pathfield.model.set_value(self.__path) self.folder_img = ui.Image( name="open_folder", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=12, height=18, ) self.folder_img.set_mouse_pressed_fn(lambda x, y, b, m: self.open_path(self.__path)) def open_path(self, path): if platform.system() == "Darwin": # macOS subprocess.call(("open", path)) elif platform.system() == "Windows": # Windows os.startfile(path) else: # linux variants subprocess.call(("xdg-open", path))
31,184
Python
38.12798
166
0.540469
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/ui/custom_color_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomColorWidget"] from ctypes import Union import re from typing import List, Optional import omni.ui as ui from .custom_base_widget import CustomBaseWidget from .style import BLOCK_HEIGHT COLOR_PICKER_WIDTH = ui.Percent(35) FIELD_WIDTH = ui.Percent(65) COLOR_WIDGET_NAME = "color_block" SPACING = 4 class CustomColorWidget(CustomBaseWidget): """The compound widget for color input. The color picker widget model converts its 3 RGB values into a comma-separated string, to display in the StringField. And vice-versa. """ def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = [a for a in args if a is not None] self.__strfield: Optional[ui.StringField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__color_sub = None self.__strfield_sub = None # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__strfield = None self.__colorpicker = None self.__color_sub = None self.__strfield_sub = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__colorpicker: return self.__colorpicker.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__colorpicker.model = value @staticmethod def simplify_str(val): s = str(round(val, 3)) s_clean = re.sub(r'0*$', '', s) # clean trailing 0's s_clean = re.sub(r'[.]$', '', s_clean) # clean trailing . s_clean = re.sub(r'^0', '', s_clean) # clean leading 0 return s_clean def set_color_stringfield(self, item_model: ui.AbstractItemModel, children: List[ui.AbstractItem]): """Take the colorpicker model that has 3 child RGB values, convert them to a comma-separated string, and set the StringField value to that string. Args: item_model: Colorpicker model children: child Items of the colorpicker """ field_str = ", ".join([self.simplify_str(item_model.get_item_value_model(c).as_float) for c in children]) self.__strfield.model.set_value(field_str) if self.revert_img: self._on_value_changed() def set_color_widget(self, str_model: ui.SimpleStringModel, children: List[ui.AbstractItem]): """Parse the new StringField value and set the ui.ColorWidget component items to the new values. Args: str_model: SimpleStringModel for the StringField children: Child Items of the ui.ColorWidget's model """ joined_str = str_model.get_value_as_string() for model, comp_str in zip(children, joined_str.split(",")): comp_str_clean = comp_str.strip() try: self.__colorpicker.model.get_item_value_model(model).as_float = float(comp_str_clean) except ValueError: # Usually happens in the middle of typing pass def _on_value_changed(self, *args): """Set revert_img to correct state.""" default_str = ", ".join([self.simplify_str(val) for val in self.__defaults]) cur_str = self.__strfield.model.as_string self.revert_img.enabled = default_str != cur_str def _restore_default(self): """Restore the default values.""" if self.revert_img.enabled: field_str = ", ".join([self.simplify_str(val) for val in self.__defaults]) self.__strfield.model.set_value(field_str) self.revert_img.enabled = False def _build_body(self): """Main meat of the widget. Draw the colorpicker, stringfield, and set up callbacks to keep them updated. """ with ui.HStack(spacing=SPACING): # The construction of the widget depends on what the user provided, # defaults or a model if self.existing_model: # the user provided a model self.__colorpicker = ui.ColorWidget( self.existing_model, width=COLOR_PICKER_WIDTH, height=BLOCK_HEIGHT, name=COLOR_WIDGET_NAME ) color_model = self.existing_model else: # the user provided a list of default values self.__colorpicker = ui.ColorWidget( *self.__defaults, width=COLOR_PICKER_WIDTH, height=BLOCK_HEIGHT, name=COLOR_WIDGET_NAME ) color_model = self.__colorpicker.model self.__strfield = ui.StringField(width=FIELD_WIDTH, name="attribute_color") self.__color_sub = self.__colorpicker.model.subscribe_item_changed_fn( lambda m, _, children=color_model.get_item_children(): self.set_color_stringfield(m, children)) self.__strfield_sub = self.__strfield.model.subscribe_value_changed_fn( lambda m, children=color_model.get_item_children(): self.set_color_widget(m, children)) # show data at the start self.set_color_stringfield(self.__colorpicker.model, children=color_model.get_item_children())
6,076
Python
39.245033
101
0.59842
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/ui/custom_combobox_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomComboboxWidget"] from typing import List, Optional import omni.ui as ui from .custom_base_widget import CustomBaseWidget from .style import BLOCK_HEIGHT class CustomComboboxWidget(CustomBaseWidget): """A customized combobox widget""" def __init__(self, model: ui.AbstractItemModel = None, options: List[str] = None, default_value=0, **kwargs): self.__default_val = default_value self.__options = options or ["1", "2", "3"] self.__combobox_widget = None # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__options = None self.__combobox_widget = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__combobox_widget: return self.__combobox_widget.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__combobox_widget.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" model = self.__combobox_widget.model index = model.get_item_value_model().get_value_as_int() self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.__combobox_widget.model.get_item_value_model().set_value( self.__default_val) self.revert_img.enabled = False def _build_body(self): """Main meat of the widget. Draw the Rectangle, Combobox, and set up callbacks to keep them updated. """ with ui.HStack(): with ui.ZStack(): # TODO: Simplify when borders on ComboBoxes work in Kit! # and remove style rule for "combobox" Rect # Use the outline from the Rectangle for the Combobox ui.Rectangle(name="combobox", height=BLOCK_HEIGHT) option_list = list(self.__options) self.__combobox_widget = ui.ComboBox( 0, *option_list, name="dropdown_menu", # Abnormal height because this "transparent" combobox # has to fit inside the Rectangle behind it height=10 ) # Swap for different dropdown arrow image over current one with ui.HStack(): ui.Spacer() # Keep it on the right side with ui.VStack(width=0): # Need width=0 to keep right-aligned ui.Spacer(height=5) with ui.ZStack(): ui.Rectangle(width=15, height=15, name="combobox_icon_cover") ui.Image(name="collapsable_closed", width=12, height=12) ui.Spacer(width=2) # Right margin ui.Spacer(width=ui.Percent(30)) self.__combobox_widget.model.add_item_changed_fn(self._on_value_changed)
3,724
Python
37.010204
89
0.585124
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/ui/custom_path_button.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomPathButtonWidget"] from typing import Callable, Optional import omni.ui as ui from .style import ATTR_LABEL_WIDTH, BLOCK_HEIGHT class CustomPathButtonWidget: """A compound widget for holding a path in a StringField, and a button that can perform an action. TODO: Get text ellision working in the path field, to start with "..." """ def __init__(self, label: str, path: str, btn_label: str, btn_callback: Callable): self.__attr_label = label self.__pathfield: ui.StringField = None self.__path = path self.__btn_label = btn_label self.__btn = None self.__callback = btn_callback self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__pathfield = None self.__btn = None self.__callback = None self.__frame = None @property def model(self) -> Optional[ui.AbstractItem]: """The widget's model""" if self.__pathfield: return self.__pathfield.model @model.setter def model(self, value: ui.AbstractItem): """The widget's model""" self.__pathfield.model = value def get_path(self): return self.model.as_string def _build_fn(self): """Draw all of the widget parts and set up callbacks.""" with ui.HStack(): ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) self.__pathfield = ui.StringField( name="path_field", height=BLOCK_HEIGHT, width=ui.Fraction(2), ) # TODO: Add clippingType=ELLIPSIS_LEFT for long paths self.__pathfield.model.set_value(self.__path) self.__btn = ui.Button( self.__btn_label, name="tool_button", height=BLOCK_HEIGHT, width=ui.Fraction(1), clicked_fn=lambda path=self.get_path(): self.__callback(path), )
2,599
Python
30.707317
78
0.576376
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/ui/custom_slider_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomSliderWidget"] from typing import Optional import omni.ui as ui from omni.ui import color as cl from omni.ui import constant as fl from .custom_base_widget import CustomBaseWidget NUM_FIELD_WIDTH = 50 SLIDER_WIDTH = ui.Percent(100) FIELD_HEIGHT = 22 # TODO: Once Field padding is fixed, this should be 18 SPACING = 4 TEXTURE_NAME = "slider_bg_texture" class CustomSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=1.0, default_val=0.0, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls( height=FIELD_HEIGHT, min=self.__min, max=self.__max, name="attr_slider" ) if self.__display_range: self._build_display_range() with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=2) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed)
6,797
Python
40.451219
105
0.529351
DigitalBotLab/3DRotationCalculator/Extension/exts/rotaiton.calculator/rotaiton/calculator/ui/custom_base_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomBaseWidget"] from typing import Optional import omni.ui as ui from .style import ATTR_LABEL_WIDTH class CustomBaseWidget: """The base widget for custom widgets that follow the pattern of Head (Label), Body Widgets, Tail Widget""" def __init__(self, *args, model=None, **kwargs): self.existing_model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.revert_img = None self.__attr_label: Optional[str] = kwargs.pop("label", "") self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.existing_model = None self.revert_img = None self.__attr_label = None self.__frame = None def __getattr__(self, attr): """Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__frame, attr) def _build_head(self): """Build the left-most piece of the widget line (label in this case)""" ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) def _build_body(self): """Build the custom part of the widget. Most custom widgets will override this method, as it is where the meat of the custom widget is. """ ui.Spacer() def _build_tail(self): """Build the right-most piece of the widget line. In this case, we have a Revert Arrow button at the end of each widget line. """ with ui.HStack(width=0): ui.Spacer(width=5) with ui.VStack(height=0): ui.Spacer(height=3) self.revert_img = ui.Image( name="revert_arrow", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=12, height=13, enabled=False, ) ui.Spacer(width=5) # call back for revert_img click, to restore the default value self.revert_img.set_mouse_pressed_fn( lambda x, y, b, m: self._restore_default()) def _build_fn(self): """Puts the 3 pieces together.""" with ui.HStack(): self._build_head() self._build_body() self._build_tail()
2,781
Python
32.518072
87
0.591514
NVIDIA-AI-IOT/isaac_camera_benchmark/camera_benchmark.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: MIT # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import carb from omni.isaac.kit import SimulationApp import sys import csv from datetime import datetime import json import argparse parser = argparse.ArgumentParser(description="Ros2 Bridge Sample") parser.add_argument('--config_path', default='config.json', help='Path to the world to create a navigation mesh.') args, unknown = parser.parse_known_args() ROS_CAMERA_GRAPH_PATH = "/ROS_Camera" BACKGROUND_STAGE_PATH = "/background" BACKGROUND_USD_PATH = "/Isaac/Environments/Simple_Warehouse/warehouse_with_forklifts.usd" DEFAULT_CONFIG = { 'record': False, 'simulation': {"renderer": "RayTracedLighting", "headless": False}, 'camera': [ {'translate': [-1, 5, 1], 'resolution': [640, 480]}, {'translate': [-1, 1, 6], 'resolution': [640, 480]}, {'translate': [-1, 7, 3], 'resolution': [640, 480]}, # {'translate': [1, 2, 3], 'resolution': [640, 480]}, ] } def read_config(filename): try: with open(filename, 'r') as file: config_data = json.load(file) except FileNotFoundError: print( f"Config file '{filename}' not found. Using default configuration.") return DEFAULT_CONFIG # Update default config with values from the file config = DEFAULT_CONFIG.copy() config.update(config_data) return config # Load config file config = read_config(args.config_path) simulation_app = SimulationApp(config['simulation']) import omni from omni.isaac.core import SimulationContext from omni.isaac.core.utils import stage, extensions, nucleus from pxr import Gf, UsdGeom, Usd from omni.kit.viewport.utility import get_active_viewport import omni.graph.core as og # enable ROS bridge extension extensions.enable_extension("omni.isaac.ros2_bridge") simulation_app.update() import threading import rclpy from rclpy.node import Node from rclpy.qos import qos_profile_sensor_data from sensor_msgs.msg import Image def create_camera(translate=[-1, 5, 1], resolution=[640, 480], number_camera=0): camera_stage_path = "/Camera" + f"{number_camera}" ros_camera_graph_path = ROS_CAMERA_GRAPH_PATH + f"{number_camera}" # Creating a Camera prim camera_prim = UsdGeom.Camera(omni.usd.get_context().get_stage().DefinePrim(camera_stage_path, "Camera")) xform_api = UsdGeom.XformCommonAPI(camera_prim) xform_api.SetTranslate(Gf.Vec3d(translate[0], translate[1], translate[2])) xform_api.SetRotate((90, 0, 0), UsdGeom.XformCommonAPI.RotationOrderXYZ) camera_prim.GetHorizontalApertureAttr().Set(21) camera_prim.GetVerticalApertureAttr().Set(16) camera_prim.GetProjectionAttr().Set("perspective") camera_prim.GetFocalLengthAttr().Set(24) camera_prim.GetFocusDistanceAttr().Set(400) simulation_app.update() viewport_name = f"Viewport{number_camera}" if number_camera != 0 else "" # Creating an on-demand push graph with cameraHelper nodes to generate ROS image publishers keys = og.Controller.Keys (ros_camera_graph, _, _, _) = og.Controller.edit( { "graph_path": ros_camera_graph_path, "evaluator_name": "push", "pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND, }, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("createViewport", "omni.isaac.core_nodes.IsaacCreateViewport"), ("getRenderProduct", "omni.isaac.core_nodes.IsaacGetViewportRenderProduct"), ("setViewportResolution", "omni.isaac.core_nodes.IsaacSetViewportResolution"), ("setCamera", "omni.isaac.core_nodes.IsaacSetCameraOnRenderProduct"), ("cameraHelperRgb", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ("cameraHelperInfo", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ("cameraHelperDepth", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "createViewport.inputs:execIn"), ("createViewport.outputs:execOut", "getRenderProduct.inputs:execIn"), ("createViewport.outputs:execOut", "setViewportResolution.inputs:execIn"), ("createViewport.outputs:viewport", "getRenderProduct.inputs:viewport"), ("createViewport.outputs:viewport", "setViewportResolution.inputs:viewport"), ("setViewportResolution.outputs:execOut", "setCamera.inputs:execIn"), ("getRenderProduct.outputs:renderProductPath", "setCamera.inputs:renderProductPath"), ("setCamera.outputs:execOut", "cameraHelperRgb.inputs:execIn"), ("setCamera.outputs:execOut", "cameraHelperInfo.inputs:execIn"), ("setCamera.outputs:execOut", "cameraHelperDepth.inputs:execIn"), ("getRenderProduct.outputs:renderProductPath", "cameraHelperRgb.inputs:renderProductPath"), ("getRenderProduct.outputs:renderProductPath", "cameraHelperInfo.inputs:renderProductPath"), ("getRenderProduct.outputs:renderProductPath", "cameraHelperDepth.inputs:renderProductPath"), ], keys.SET_VALUES: [ ("createViewport.inputs:name", viewport_name), ("createViewport.inputs:viewportId", number_camera), ("setViewportResolution.inputs:width", resolution[0]), ("setViewportResolution.inputs:height", resolution[1]), ("setCamera.inputs:cameraPrim", f"{camera_stage_path}"), ("cameraHelperRgb.inputs:frameId", "sim_camera"), ("cameraHelperRgb.inputs:topicName", f"/Camera{number_camera}/rgb"), ("cameraHelperRgb.inputs:type", "rgb"), ("cameraHelperInfo.inputs:frameId", "sim_camera"), ("cameraHelperInfo.inputs:topicName", f"/Camera{number_camera}/camera_info"), ("cameraHelperInfo.inputs:type", "camera_info"), ("cameraHelperDepth.inputs:frameId", "sim_camera"), ("cameraHelperDepth.inputs:topicName", f"/Camera{number_camera}/depth"), ("cameraHelperDepth.inputs:type", "depth"), ], }, ) # Run the ROS Camera graph once to generate ROS image publishers in SDGPipeline og.Controller.evaluate_sync(ros_camera_graph) simulation_app.update() return xform_api class BenchmarkCamera(Node): def __init__(self, config): super().__init__("benchmark_camera_node") # Run ROS2 node in a separate thread executor = rclpy.executors.MultiThreadedExecutor() executor.add_node(self) executor_thread = threading.Thread(target=executor.spin, daemon=True) executor_thread.start() # Chech if record is enable current_date = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") self.file_path = f'benchmark_camera_{current_date}.csv' if 'record' in config and config['record'] else '' # Init variables self.last_printed_tn = 0 self.msg_t0 = -1 self.msg_tn = 0 self.window_size = 10000 # window_size self.times = [] self.fps = 0 # Get camera list from config file self.xform_api_camera = [] self.simulation_context = SimulationContext(stage_units_in_meters=1.0) # Locate Isaac Sim assets folder to load environment and robot stages assets_root_path = nucleus.get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") simulation_app.close() sys.exit() # Loading the simple_room environment stage.add_reference_to_stage(assets_root_path + BACKGROUND_USD_PATH, BACKGROUND_STAGE_PATH) if 'camera' not in config or len(config['camera']) == 0: carb.log_error("There are no camera in list, please add one in config file") simulation_app.close() sys.exit() for idx, camera in enumerate(config['camera']): self.xform_api_camera += [create_camera(translate=camera['translate'], resolution=camera['resolution'], number_camera=idx)] self.subscription = self.create_subscription( Image, # Replace with the actual message type you're subscribing to '/Camera0/rgb', # Replace with the actual topic name self.callback_hz, qos_profile_sensor_data, ) def callback_hz(self, msg): curr_rostime = self.get_clock().now() if curr_rostime.nanoseconds == 0: if len(self.times) > 0: print('time has reset, resetting counters') self.times = [] return curr = curr_rostime.nanoseconds msg_t0 = self.msg_t0 if msg_t0 < 0 or msg_t0 > curr: self.msg_t0 = curr self.msg_tn = curr self.times = [] else: self.times.append(curr - self.msg_tn) self.msg_tn = curr if len(self.times) > self.window_size: self.times.pop(0) def plot_benchmark(self, fps): if not self.times: return elif self.last_printed_tn == 0: self.last_printed_tn = self.msg_tn return elif self.msg_tn < self.last_printed_tn + 1e9: return # Get frequency every one minute n = len(self.times) mean = sum(self.times) / n rate = 1. / mean if mean > 0. else 0 self.last_printed_tn = self.msg_tn # Print benchmark rate_print = rate * 1e9 self.get_logger().info( f"ROS avg: {rate_print:.3f} Hz - Isaac SIM FPs: {fps:.2f}") # Print benchmark to csv file if self.file_path: self.csv_writer.writerow([rate_print, fps]) def run_simulation(self): # Need to initialize physics getting any articulation..etc self.simulation_context.initialize_physics() self.simulation_context.play() frame = 0 # Dock all viewports n_vieports = len(self.xform_api_camera) if n_vieports > 1: viewport = omni.ui.Workspace.get_window('Viewport') for idx in reversed(range(1, n_vieports)): viewport_idx = omni.ui.Workspace.get_window(f"Viewport{idx}") viewport_idx.dock_in(viewport, omni.ui.DockPosition.RIGHT) # Open csv file if self.file_path: csv_file = open(self.file_path, 'w', newline='') # Create a CSV writer object self.csv_writer = csv.writer(csv_file) self.get_logger().info(f'Recording benchmark to {self.file_path}') # Run simulation while simulation_app.is_running(): # Run with a fixed step size self.simulation_context.step(render=True) # rclpy.spin_once(self, timeout_sec=0.0) if self.simulation_context.is_playing(): if self.simulation_context.current_time_step_index == 0: self.simulation_context.reset() # Get viewport fps and plot benchmark viewport_api = get_active_viewport() self.plot_benchmark(viewport_api.fps) # Rotate camera by 0.5 degree every frame for xform_api in self.xform_api_camera: xform_api.SetRotate((90, 0, frame / 4.0), UsdGeom.XformCommonAPI.RotationOrderXYZ) frame = frame + 1 # Cleanup if self.file_path: csv_file.close() self.simulation_context.stop() simulation_app.close() if __name__ == "__main__": rclpy.init() # Start simulation subscriber = BenchmarkCamera(config) subscriber.run_simulation() # Cleanup rclpy.shutdown() # EOF
13,144
Python
41.540453
135
0.629793
NVIDIA-AI-IOT/isaac_camera_benchmark/README.md
# isaac_camera_benchmark This tool run a simple test to check the performance of your desktop on Isaac SIM. ![Camera benchmark](.doc/camera_benchmark.png) You can run multiple test and read: * Camera performance from 1 to more * Change resolution * ROS2 This tool will plot on your bash the ROS topic frequency average and the FPS from Isaac SIM. This tool will run a set of camera on your Isaac SIM environment and will start to rotate every camera autonomously. ## Hardware required Workstation: 1. x86/64 machine 2. Install Ubuntu 20.04 or Ubuntu 22.04 3. NVIDIA Graphic card with RTX 4. Display 5. Keyboard and Mouse ### Run demo Clone this repository and move to repository folder ```console git clone https://github.com/nvidia_iot/isaac_camera_benchmark.git cd isaac_camera_benchmark ``` Run the installer ```console ./run_camera_benchmark.sh ``` #### NVIDIA Isaac SIM Follow the documentation on NVIDIA Isaac SIM [Workstation install](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_workstation.html) 1. Download the [Omniverse Launcher](https://www.nvidia.com/en-us/omniverse/) 2. [Install Omniverse Launcher](https://docs.omniverse.nvidia.com/prod_launcher/prod_launcher/installing_launcher.html) 3. Install [Cache](https://docs.omniverse.nvidia.com/prod_nucleus/prod_utilities/cache/installation/workstation.html) from the Omniverse Launcher 4. Install [Nucleus](https://docs.omniverse.nvidia.com/prod_nucleus/prod_nucleus/workstation/installation.html) from the Omniverse Launcher Open Omniverse Launcher ![Omniverse launcher](https://docs.omniverse.nvidia.com/isaacsim/latest/_images/isaac_main_launcher_exchange.png) Move to Library and choice "Omniverse Isaac SIM" and download the latest 2023.1 version ![Omniverse library](https://docs.omniverse.nvidia.com/isaacsim/latest/_images/isaac_main_launcher_library.png) ## Setup Isaac Camera Benchmark To add a new camera or change the benchmark simulation, you can simply create a new file `config.json` that override the default configuration. ### Add a new camera Make a new field called `camera` and for each camera add these fields: * `translate` position camera inside the environment * `resolution` Camera resolution, suggested * 640 x 480 * 1024 x 768 * **FHD** - 1920 x 1080 * **2K** - 2560 x 1440 * **4K** - 3840 x 2160 Example a json file can be composed in this way ```json { "camera": [ {"translate": [-1, 5, 1], "resolution": [640, 480]}, {"translate": [0, 0, 0], "resolution": [1024, 768]}, ] } ``` ### Change simulation type On the `simulation` field you can change the simulation configuration, example make it headless like the example below ```json { "simulation": {"renderer": "RayTracedLighting", "headless": true} } ``` ### Export benchmark to csv file If you want to export the output in a csv file you can enable the option that automatically generate a file with name `benchmark_camera_<CURRENT DATE>.csv` ```json { "record": true } ``` ## Record camera output If you want to record in a ros2 bag file all camera you can simply run ```console ./ros2record.sh ``` That simply export all camera in a **rosbag2** folder, the output will be like the picture below. ![ros2 bag record](.doc/ros2record.png) All ros2bag file will be available on folder `isaac_camera_benchmark/rosbag`.
3,365
Markdown
27.525423
155
0.743239
NVIDIA-AI-IOT/isaac_demo/README.md
# isaac_demo ![isaac_demo](.docs/isaac_demo.gif) A combined set of demo working with Isaac SIM on a workstation and Isaac ROS on a NVIDIA Jetson AGX Orin ## Hardware required Workstation: 1. Internet connection 2. x86/64 machine 3. Install Ubuntu 20.04 4. NVIDIA Graphic card with RTX 5. Display 6. Keyboard and Mouse NVIDIA Jetson: 1. NVIDIA Jetson AGX Orin 2. Jetpack 5.1.2 Tools: 1. Router 2. eth cables ## Setup hardware Before to start check you have all requirements and connect the driver following this image ![hardware-setup](.docs/hardware-setup.drawio.png) It is preferable to connect workstation and the NVIDIA Jetson AGX Orin with a lan cable and not use WiFi. ## Install There are two steps to follow, Install FoxGlove and Install Isaac ROS Follow: * Install on Jetson * Install on workstation ### Install on NVIDIA Jetson Orin Install on your NVIDIA Jetson Orin [Jetpack 5+](https://developer.nvidia.com/embedded/jetpack) After installation save IP address and hostname #### Connect remotely In this section you connect to your NVIDIA Jetson with a ssh connection, open a terminal an write ```console ssh <IP or hostname.local> ``` where **IP** is the of NVIDIA Jetson or **hostname** is the hostname of your board. If you are connected the output from the terminal is: ![ssh-terminal-orin.png](.docs/ssh-terminal-orin.png) #### Install Isaac Demo Clone this repository and move to repository folder ```console git clone https://github.com/rbonghi/isaac_demo.git cd isaac_demo ``` Add docker group to your user ```console sudo usermod -aG docker $USER && newgrp docker ``` Set the default nvidia runtime You're going to be building containers, you need to set Docker's `default-runtime` to `nvidia`, so that the NVCC compiler and GPU are available during `docker build` operations. Add `"default-runtime": "nvidia"` to your `/etc/docker/daemon.json` configuration file before attempting to build the containers: ``` json { "default-runtime": "nvidia", "runtimes": { "nvidia": { "path": "nvidia-container-runtime", "runtimeArgs": [] } } } ``` Then restart the Docker service, or reboot your system before proceeding: ```console sudo systemctl restart docker ``` Run the installer ```console ./isaac_demo.sh ``` If everything is going well (need time before to be done) the terminal will show this output ![Isaac Demo installed on Orin](.docs/isaac_demo_install_orin.png) ### Install on workstation In this first part, you install different software on your workstation. * NVIDIA Isaac SIM * Foxglove * This repository #### NVIDIA Isaac SIM Follow the documentation on NVIDIA Isaac SIM [Workstation install](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_workstation.html) 1. Download the [Omniverse Launcher](https://www.nvidia.com/en-us/omniverse/) 2. [Install Omniverse Launcher](https://docs.omniverse.nvidia.com/prod_launcher/prod_launcher/installing_launcher.html) 3. Install [Cache](https://docs.omniverse.nvidia.com/prod_nucleus/prod_utilities/cache/installation/workstation.html) from the Omniverse Launcher 4. Install [Nucleus](https://docs.omniverse.nvidia.com/prod_nucleus/prod_nucleus/workstation/installation.html) from the Omniverse Launcher Open Omniverse Launcher ![Omniverse launcher](https://docs.omniverse.nvidia.com/isaacsim/latest/_images/isaac_main_launcher_exchange.png) Move to Library and choice "Omniverse Isaac SIM" and download the latest 2022.2 version ![Omniverse library](https://docs.omniverse.nvidia.com/isaacsim/latest/_images/isaac_main_launcher_library.png) #### Foxglove on Desktop Download the latest [foxglove](https://foxglove.dev/download) version for your desktop ```console sudo apt install ./foxglove-studio-*.deb sudo apt update sudo apt install -y foxglove-studio ``` #### Isaac SIM and Isaac DEMO Clone this repository and move to repository folder ```console git clone https://github.com/rbonghi/isaac_demo.git cd isaac_demo ``` Now follow the Run demo to start the simulation ## Run demo From your workstation now you need to do two extra steps ### Start Isaac SIM Start the NVIDIA Isaac SIM from script Open a terminal on your workstation and write ```console cd isaac_demo ./isaac_demo.sh ``` Now this script initialize and run NVIDIA Isaac SIM, after a while you see a new window with Isaac SIM running ![Isaac SIM demo running](.docs/isaac_sim_running.png) After this step you can complete to run the demo on your NVIDIA Jetson. ### Run simulation on Jetson If you close your terminal on the installation, you can reopen with: ```console ssh <IP or hostname.local> ``` where **IP** is the of NVIDIA Jetson or **hostname** is the hostname of your board. and run ```console cd isaac_demo ./isaac_demo.sh ``` Wait this script run the docker terminal, like the image below ![Isaac Demo installed on Orin](.docs/isaac_demo_install_orin.png) Now you can run the script below ```console bash src/isaac_demo/scripts/run_in_docker.sh ``` if you are planning to use Foxglove please run the same script with option `--foxglove` ```console bash src/isaac_demo/scripts/run_in_docker.sh --foxglove ``` Well done! Now the Isaac ROS is running on your Jetson ### Setup foxglove 1. Open foxglove 2. Set up **Open connection** ![Foxglove setup connection](.docs/01-foxglove-setup-connection.png) 3. Select **Foxglove WebSocket** and **Open** ![Foxglove ROS2](.docs/02-foxglove-connection.png) 4. Write on **WebSocket URL** ```console ws://<IP or hostname.local>:8765 ``` where **IP** is the of NVIDIA Jetson or **hostname** is the hostname of your board. 5. Setup Layout Press on "Import layout" icon and after on top press the button **Import layout** ![Import layout page](.docs/03-foxglove-import-layout.png) Select the layout on: **isaac_demo/foxglove/Default.json** 6. Output running ![Foxglove running](.docs/04-foxglove-running.png) You can drive the robot directly from the foxglove joystick ## Troubleshooting If Isaac SIM on your workstation show this message ![Isaac SIM install](.docs/warning-isaac-sim-desktop.png) just wait! :-)
6,164
Markdown
23.271653
308
0.746918
NVIDIA-AI-IOT/isaac_demo/isaac_ros/src/isaac_demo/launch/carter-foxglove.launch.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import os import launch from launch_ros.actions import ComposableNodeContainer, Node from launch.actions import DeclareLaunchArgument from launch.substitutions import LaunchConfiguration from launch.actions import IncludeLaunchDescription from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.descriptions import ComposableNode from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import ExecuteProcess LOCAL_PATH = "/workspaces/isaac_ros-dev" def generate_launch_description(): pkg_description = get_package_share_directory('carter_description') bringup_dir = get_package_share_directory('nvblox_examples_bringup') pkg_isaac_demo = get_package_share_directory('isaac_demo') use_sim_time = LaunchConfiguration('use_sim_time', default='True') # Bi3DNode parameters featnet_engine_file_path = LaunchConfiguration('featnet_engine_file_path') segnet_engine_file_path = LaunchConfiguration('segnet_engine_file_path') max_disparity_values = LaunchConfiguration('max_disparity_values') # FreespaceSegmentationNode parameters f_x_ = LaunchConfiguration('f_x') f_y_ = LaunchConfiguration('f_y') grid_height = LaunchConfiguration('grid_height') grid_width = LaunchConfiguration('grid_width') grid_resolution = LaunchConfiguration('grid_resolution') ############# ROS2 DECLARATIONS ############# # Launch Arguments run_rviz_arg = DeclareLaunchArgument( 'run_rviz', default_value='True', description='Whether to start RVIZ') use_sim_dec = DeclareLaunchArgument( 'use_sim_time', default_value='True', description='Use simulation (Omniverse Isaac Sim) clock if true') featnet_engine_file_arg = DeclareLaunchArgument( 'featnet_engine_file_path', default_value=f"{LOCAL_PATH}/bi3d/bi3dnet_featnet.plan", description='The absolute path to the Bi3D Featnet TensorRT engine plan') segnet_engine_file_arg = DeclareLaunchArgument( 'segnet_engine_file_path', default_value=f"{LOCAL_PATH}/bi3d/bi3dnet_segnet.plan", description='The absolute path to the Bi3D Segnet TensorRT engine plan') max_disparity_values_arg = DeclareLaunchArgument( 'max_disparity_values', default_value='10', description='The maximum number of disparity values given for Bi3D inference') f_x_arg = DeclareLaunchArgument( 'f_x', default_value='1465.99853515625', description='The number of pixels per distance unit in the x dimension') f_y_arg = DeclareLaunchArgument( 'f_y', default_value='1468.2335205078125', description='The number of pixels per distance unit in the y dimension') grid_height_arg = DeclareLaunchArgument( 'grid_height', default_value='2000', description='The desired height of the occupancy grid, in cells') grid_width_arg = DeclareLaunchArgument( 'grid_width', default_value='2000', description='The desired width of the occupancy grid, in cells') grid_resolution_arg = DeclareLaunchArgument( 'grid_resolution', default_value='0.01', description='The desired resolution of the occupancy grid, in m/cell') ############# ROS2 NODES ############# ############# ISAAC ROS NODES ######## apriltag_node = ComposableNode( name='apriltag', package='isaac_ros_apriltag', plugin='nvidia::isaac_ros::apriltag::AprilTagNode', remappings=[('/image', '/front/stereo_camera/left/rgb'), ('/camera_info', '/front/stereo_camera/left/camera_info'), ], parameters=[{'size': 0.32, 'max_tags': 64}], ) visual_slam_node = ComposableNode( name='visual_slam_node', package='isaac_ros_visual_slam', plugin='isaac_ros::visual_slam::VisualSlamNode', remappings=[('stereo_camera/left/camera_info', '/front/stereo_camera/left/camera_info'), ('stereo_camera/right/camera_info', '/front/stereo_camera/right/camera_info'), ('stereo_camera/left/image', '/front/stereo_camera/left/rgb'), ('stereo_camera/right/image', '/front/stereo_camera/right/rgb'), ('visual_slam/tracking/odometry', '/odom'), ], parameters=[{ # 'enable_rectified_pose': False, 'denoise_input_images': True, 'rectified_images': True, 'enable_debug_mode': False, 'enable_imu': False, 'debug_dump_path': '/tmp/elbrus', 'left_camera_frame': 'carter_camera_stereo_left', 'right_camera_frame': 'carter_camera_stereo_right', 'map_frame': 'map', 'fixed_frame': 'odom', 'odom_frame': 'odom', 'base_frame': 'base_link', 'current_smooth_frame': 'base_link_smooth', 'current_rectified_frame': 'base_link_rectified', 'enable_observations_view': True, 'enable_landmarks_view': True, 'enable_reading_slam_internals': True, 'enable_slam_visualization': True, 'enable_localization_n_mapping': True, # 'publish_odom_to_base_tf': False, 'publish_map_to_odom_tf': False, 'use_sim_time': use_sim_time }] ) bi3d_node = ComposableNode( name='bi3d_node', package='isaac_ros_bi3d', plugin='nvidia::isaac_ros::bi3d::Bi3DNode', parameters=[{ 'featnet_engine_file_path': featnet_engine_file_path, 'segnet_engine_file_path': segnet_engine_file_path, 'max_disparity_values': max_disparity_values, 'disparity_values': [3, 6, 9, 12, 15, 18, 21, 24, 27, 30], 'use_sim_time': use_sim_time}], remappings=[('bi3d_node/bi3d_output', 'bi3d_mask'), ('left_image_bi3d', '/front/stereo_camera/left/rgb'), ('right_image_bi3d', '/front/stereo_camera/right/rgb')] ) freespace_segmentation_node = ComposableNode( name='freespace_segmentation_node', package='isaac_ros_bi3d_freespace', plugin='nvidia::isaac_ros::bi3d_freespace::FreespaceSegmentationNode', parameters=[{ 'base_link_frame': 'base_link', 'camera_frame': 'carter_camera_stereo_left', 'f_x': f_x_, 'f_y': f_y_, 'grid_height': grid_height, 'grid_width': grid_width, 'grid_resolution': grid_resolution, 'use_sim_time': use_sim_time }]) isaac_ros_launch_container = ComposableNodeContainer( name='isaac_ros_launch_container', namespace='', package='rclcpp_components', executable='component_container', composable_node_descriptions=[ visual_slam_node, apriltag_node, bi3d_node, freespace_segmentation_node, ], output='screen' ) ############# OTHER ROS2 NODES ####### nav2_launch = IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join( bringup_dir, 'launch', 'nav2', 'nav2_isaac_sim.launch.py'))) # Nvblox nvblox_launch = IncludeLaunchDescription( PythonLaunchDescriptionSource([ os.path.join(bringup_dir, 'launch', 'nvblox', 'nvblox.launch.py')]), launch_arguments={'setup_for_isaac_sim': 'True'}.items()) # https://foxglove.dev/docs/studio/connection/ros2 # https://github.com/foxglove/ros-foxglove-bridge foxglove_bridge_node = Node( package='foxglove_bridge', executable='foxglove_bridge', # output='screen' ) # include another launch file in nanosaur namespace # https://docs.ros.org/en/foxy/How-To-Guides/Launch-file-different-formats.html description_launch = IncludeLaunchDescription( PythonLaunchDescriptionSource([pkg_description, '/launch/description.launch.py']), ) ############################ # Launch ROS2 packages ld = LaunchDescription() # Definitions ld.add_action(use_sim_dec) ld.add_action(featnet_engine_file_arg) ld.add_action(segnet_engine_file_arg) ld.add_action(max_disparity_values_arg) ld.add_action(f_x_arg) ld.add_action(f_y_arg) ld.add_action(grid_height_arg) ld.add_action(grid_width_arg) ld.add_action(grid_resolution_arg) # carter description launch ld.add_action(description_launch) # Foxglove ld.add_action(foxglove_bridge_node) # Isaac ROS container ld.add_action(isaac_ros_launch_container) # vSLAM and NVBLOX ld.add_action(nvblox_launch) # Navigation tool ld.add_action(nav2_launch) return ld # EOF
10,105
Python
39.262948
98
0.636813
NVIDIA-AI-IOT/isaac_demo/isaac_ros/src/isaac_demo/launch/carter.launch.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import os import launch from launch_ros.actions import ComposableNodeContainer, Node from launch.actions import DeclareLaunchArgument from launch.substitutions import LaunchConfiguration from launch.actions import IncludeLaunchDescription from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.descriptions import ComposableNode from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import ExecuteProcess LOCAL_PATH = "/workspaces/isaac_ros-dev" def generate_launch_description(): pkg_description = get_package_share_directory('carter_description') bringup_dir = get_package_share_directory('nvblox_examples_bringup') pkg_isaac_demo = get_package_share_directory('isaac_demo') use_sim_time = LaunchConfiguration('use_sim_time', default='True') # Bi3DNode parameters featnet_engine_file_path = LaunchConfiguration('featnet_engine_file_path') segnet_engine_file_path = LaunchConfiguration('segnet_engine_file_path') max_disparity_values = LaunchConfiguration('max_disparity_values') # FreespaceSegmentationNode parameters f_x_ = LaunchConfiguration('f_x') f_y_ = LaunchConfiguration('f_y') grid_height = LaunchConfiguration('grid_height') grid_width = LaunchConfiguration('grid_width') grid_resolution = LaunchConfiguration('grid_resolution') ############# ROS2 DECLARATIONS ############# # Launch Arguments run_rviz_arg = DeclareLaunchArgument( 'run_rviz', default_value='True', description='Whether to start RVIZ') use_sim_dec = DeclareLaunchArgument( 'use_sim_time', default_value='True', description='Use simulation (Omniverse Isaac Sim) clock if true') featnet_engine_file_arg = DeclareLaunchArgument( 'featnet_engine_file_path', default_value=f"{LOCAL_PATH}/bi3d/bi3dnet_featnet.plan", description='The absolute path to the Bi3D Featnet TensorRT engine plan') segnet_engine_file_arg = DeclareLaunchArgument( 'segnet_engine_file_path', default_value=f"{LOCAL_PATH}/bi3d/bi3dnet_segnet.plan", description='The absolute path to the Bi3D Segnet TensorRT engine plan') max_disparity_values_arg = DeclareLaunchArgument( 'max_disparity_values', default_value='10', description='The maximum number of disparity values given for Bi3D inference') f_x_arg = DeclareLaunchArgument( 'f_x', default_value='1465.99853515625', description='The number of pixels per distance unit in the x dimension') f_y_arg = DeclareLaunchArgument( 'f_y', default_value='1468.2335205078125', description='The number of pixels per distance unit in the y dimension') grid_height_arg = DeclareLaunchArgument( 'grid_height', default_value='2000', description='The desired height of the occupancy grid, in cells') grid_width_arg = DeclareLaunchArgument( 'grid_width', default_value='2000', description='The desired width of the occupancy grid, in cells') grid_resolution_arg = DeclareLaunchArgument( 'grid_resolution', default_value='0.01', description='The desired resolution of the occupancy grid, in m/cell') ############# ROS2 NODES ############# ############# ISAAC ROS NODES ######## apriltag_node = ComposableNode( name='apriltag', package='isaac_ros_apriltag', plugin='nvidia::isaac_ros::apriltag::AprilTagNode', remappings=[('/image', '/front/stereo_camera/left/rgb'), ('/camera_info', '/front/stereo_camera/left/camera_info'), ], parameters=[{'size': 0.32, 'max_tags': 64}], ) visual_slam_node = ComposableNode( name='visual_slam_node', package='isaac_ros_visual_slam', plugin='isaac_ros::visual_slam::VisualSlamNode', remappings=[('stereo_camera/left/camera_info', '/front/stereo_camera/left/camera_info'), ('stereo_camera/right/camera_info', '/front/stereo_camera/right/camera_info'), ('stereo_camera/left/image', '/front/stereo_camera/left/rgb'), ('stereo_camera/right/image', '/front/stereo_camera/right/rgb'), ('visual_slam/tracking/odometry', '/odom'), ], parameters=[{ # 'enable_rectified_pose': False, 'denoise_input_images': True, 'rectified_images': True, 'enable_debug_mode': False, 'enable_imu': False, 'debug_dump_path': '/tmp/elbrus', 'left_camera_frame': 'carter_camera_stereo_left', 'right_camera_frame': 'carter_camera_stereo_right', 'map_frame': 'map', 'fixed_frame': 'odom', 'odom_frame': 'odom', 'base_frame': 'base_link', 'current_smooth_frame': 'base_link_smooth', 'current_rectified_frame': 'base_link_rectified', 'enable_observations_view': True, 'enable_landmarks_view': True, 'enable_reading_slam_internals': True, 'enable_slam_visualization': True, 'enable_localization_n_mapping': True, # 'publish_odom_to_base_tf': False, 'publish_map_to_odom_tf': False, 'use_sim_time': use_sim_time }] ) bi3d_node = ComposableNode( name='bi3d_node', package='isaac_ros_bi3d', plugin='nvidia::isaac_ros::bi3d::Bi3DNode', parameters=[{ 'featnet_engine_file_path': featnet_engine_file_path, 'segnet_engine_file_path': segnet_engine_file_path, 'max_disparity_values': max_disparity_values, 'disparity_values': [3, 6, 9, 12, 15, 18, 21, 24, 27, 30], 'use_sim_time': use_sim_time}], remappings=[('bi3d_node/bi3d_output', 'bi3d_mask'), ('left_image_bi3d', '/front/stereo_camera/left/rgb'), ('right_image_bi3d', '/front/stereo_camera/right/rgb')] ) freespace_segmentation_node = ComposableNode( name='freespace_segmentation_node', package='isaac_ros_bi3d_freespace', plugin='nvidia::isaac_ros::bi3d_freespace::FreespaceSegmentationNode', parameters=[{ 'base_link_frame': 'base_link', 'camera_frame': 'carter_camera_stereo_left', 'f_x': f_x_, 'f_y': f_y_, 'grid_height': grid_height, 'grid_width': grid_width, 'grid_resolution': grid_resolution, 'use_sim_time': use_sim_time }]) isaac_ros_launch_container = ComposableNodeContainer( name='isaac_ros_launch_container', namespace='', package='rclcpp_components', executable='component_container', composable_node_descriptions=[ visual_slam_node, apriltag_node, bi3d_node, freespace_segmentation_node, ], output='screen' ) ############# OTHER ROS2 NODES ####### nav2_launch = IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join( bringup_dir, 'launch', 'nav2', 'nav2_isaac_sim.launch.py'))) # Nvblox nvblox_launch = IncludeLaunchDescription( PythonLaunchDescriptionSource([ os.path.join(bringup_dir, 'launch', 'nvblox', 'nvblox.launch.py')]), launch_arguments={'setup_for_isaac_sim': 'True'}.items()) # include another launch file in nanosaur namespace # https://docs.ros.org/en/foxy/How-To-Guides/Launch-file-different-formats.html description_launch = IncludeLaunchDescription( PythonLaunchDescriptionSource([pkg_description, '/launch/description.launch.py']), ) ############################ # Launch ROS2 packages ld = LaunchDescription() # Definitions ld.add_action(use_sim_dec) ld.add_action(featnet_engine_file_arg) ld.add_action(segnet_engine_file_arg) ld.add_action(max_disparity_values_arg) ld.add_action(f_x_arg) ld.add_action(f_y_arg) ld.add_action(grid_height_arg) ld.add_action(grid_width_arg) ld.add_action(grid_resolution_arg) # carter description launch ld.add_action(description_launch) # Isaac ROS container ld.add_action(isaac_ros_launch_container) # vSLAM and NVBLOX ld.add_action(nvblox_launch) # Navigation tool ld.add_action(nav2_launch) return ld # EOF
9,802
Python
39.676348
98
0.636605
NVIDIA-AI-IOT/isaac_demo/isaac_ros/src/isaac_demo/scripts/carter_warehouse.py
# SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES # Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 import argparse import time from omni.isaac.kit import SimulationApp def meters_to_stage_units(length_m: float) -> float: from omni.isaac.core.utils.stage import get_stage_units stage_units_in_meters = get_stage_units() return length_m / stage_units_in_meters def stage_units_to_camera_units(length_in_stage_units: float) -> float: camera_lengths_in_stage_units = 1.0 / 10.0 return length_in_stage_units / camera_lengths_in_stage_units def configure_lidar(carter_prim_path, controller): # Lidar setup carter_lidar_path = 'chassis_link/carter_lidar' import omni from pxr import Sdf # Set up Lidar for a 32 layer like configuration # omni.kit.commands.execute( # 'ChangeProperty', # prop_path=Sdf.Path( # f'{carter_prim_path}/{carter_lidar_path}.highLod'), # value=True, # prev=None) omni.kit.commands.execute( 'ChangeProperty', prop_path=Sdf.Path( f'{carter_prim_path}/{carter_lidar_path}.horizontalResolution'), value=0.2, prev=None, ) omni.kit.commands.execute( 'ChangeProperty', prop_path=Sdf.Path( f'{carter_prim_path}/{carter_lidar_path}.minRange'), value=0.7, prev=None, ) omni.kit.commands.execute( 'ChangeProperty', prop_path=Sdf.Path( f'{carter_prim_path}/{carter_lidar_path}.verticalFov'), value=30.0, prev=None, ) omni.kit.commands.execute( 'ChangeProperty', prop_path=Sdf.Path( f'{carter_prim_path}/{carter_lidar_path}.verticalResolution'), value=1.0, prev=None, ) # Disable publish odometry # publish = controller.node(f'ros2_publish_odometry', # f'{carter_prim_path}/ActionGraph') # publish.delete_node() # publish.get_attribute('inputs:execIn').set('') # Create pcl reader node read_pcl_node_path = f'{carter_prim_path}/ActionGraph/isaac_read_lidar_point_cloud_node' read_pcl_node = controller.create_node( read_pcl_node_path, 'omni.isaac.range_sensor.IsaacReadLidarPointCloud', True, ) # Add relationship to lidar prim import omni.usd stage = omni.usd.get_context().get_stage() read_pcl_prim = stage.GetPrimAtPath(read_pcl_node_path) input_rel = read_pcl_prim.GetRelationship('inputs:lidarPrim') input_rel.SetTargets([f'{carter_prim_path}/{carter_lidar_path}']) # Retrieve on playback node playback_node = controller.node('on_playback_tick', f'{carter_prim_path}/ActionGraph') # Connect the tick to the lidar pcl read controller.connect(playback_node.get_attribute('outputs:tick'), read_pcl_node.get_attribute('inputs:execIn')) # Create ros2 publisher node publish_pcl_node = controller.create_node( f'{carter_prim_path}/ActionGraph/ros2_publish_point_cloud', 'omni.isaac.ros2_bridge.ROS2PublishPointCloud', True) # Set frame id publish_pcl_node.get_attribute('inputs:frameId').set('carter_lidar') # Connect pcl read to pcl publish controller.connect(read_pcl_node.get_attribute('outputs:execOut'), publish_pcl_node.get_attribute('inputs:execIn')) controller.connect(read_pcl_node.get_attribute('outputs:pointCloudData'), publish_pcl_node.get_attribute('inputs:pointCloudData')) # Get timestamp node and connect it timestamp_node = controller.node('isaac_read_simulation_time', f'{carter_prim_path}/ActionGraph') controller.connect(timestamp_node.get_attribute('outputs:simulationTime'), publish_pcl_node.get_attribute('inputs:timeStamp')) # Get context node and connect it context_node = controller.node('ros2_context', f'{carter_prim_path}/ActionGraph') controller.connect(context_node.get_attribute('outputs:context'), publish_pcl_node.get_attribute('inputs:context')) # Get namespace node and connect it namespace_node = controller.node('node_namespace', f'{carter_prim_path}/ActionGraph') controller.connect(namespace_node.get_attribute('inputs:value'), publish_pcl_node.get_attribute('inputs:nodeNamespace')) def configure_camera(carter_prim_path, controller, name): # print(f"----------------------------- {name} -------------------------------------") # Configure camera resolution # Create camera node and set target resolution resolution_node = controller.create_node( f'{carter_prim_path}/ROS_Cameras/isaac_set_viewport_{name}_resolution', 'omni.isaac.core_nodes.IsaacSetViewportResolution', True, ) resolution_node.get_attribute('inputs:width').set(640) resolution_node.get_attribute('inputs:height').set(480) # Get viewport creation node viewport_node = controller.node(f'isaac_create_viewport_{name}', f'{carter_prim_path}/ROS_Cameras') # Connect it controller.connect(viewport_node.get_attribute('outputs:execOut'), resolution_node.get_attribute('inputs:execIn')) controller.connect(viewport_node.get_attribute('outputs:viewport'), resolution_node.get_attribute('inputs:viewport')) # Change publication topics rgb = controller.node(f'ros2_create_camera_{name}_rgb', f'{carter_prim_path}/ROS_Cameras') rgb.get_attribute('inputs:topicName').set(f'/{name}/rgb') info = controller.node(f'ros2_create_camera_{name}_info', f'{carter_prim_path}/ROS_Cameras') info.get_attribute('inputs:topicName').set(f'/{name}/camera_info') depth = controller.node(f'ros2_create_camera_{name}_depth', f'{carter_prim_path}/ROS_Cameras') depth.get_attribute('inputs:topicName').set(f'/{name}/depth') # Finally, enable rgb and depth for enable_name in [ f'enable_camera_{name}', f'enable_camera_{name}_rgb', f'enable_camera_{name}_depth' ]: enable = controller.node(enable_name, f'{carter_prim_path}/ROS_Cameras') enable.get_attribute('inputs:condition').set(True) return info def setup_carter_sensors(carter_prim_path: str, camera_focal_length_m: float = 0.009, carter_version: int = 1, enable_lidar: bool = True, enable_odometry: bool = False): # Set up variables based on carter version. left_cam_path = 'chassis_link/camera_mount/carter_camera_stereo_left' right_cam_path = 'chassis_link/camera_mount/carter_camera_stereo_right' stereo_offset = [-175.92, 0] if carter_version == 2: left_cam_path = ( 'chassis_link/stereo_cam_left/stereo_cam_left_sensor_frame/' 'camera_sensor_left') right_cam_path = ( 'chassis_link/stereo_cam_right/stereo_cam_right_sensor_frame/' 'camera_sensor_right') stereo_offset = [-175.92, 0] import omni from pxr import Sdf # Enable # Change the focal length of the camera (default in the carter model quite narrow). camera_focal_length_in_camera_units = stage_units_to_camera_units( meters_to_stage_units(camera_focal_length_m)) omni.kit.commands.execute( 'ChangeProperty', prop_path=Sdf.Path(f'{carter_prim_path}/{left_cam_path}.focalLength'), value=camera_focal_length_in_camera_units, prev=None) omni.kit.commands.execute( 'ChangeProperty', prop_path=Sdf.Path(f'{carter_prim_path}/{right_cam_path}.focalLength'), value=camera_focal_length_in_camera_units, prev=None) # Modify the omnigraph to get lidar point cloud published import omni.graph.core as og keys = og.Controller.Keys controller = og.Controller() if not enable_odometry: # Remove odometry from Carter og.Controller.edit(f'{carter_prim_path}/ActionGraph', {keys.DELETE_NODES: ['isaac_compute_odometry_node', 'ros2_publish_odometry', 'ros2_publish_raw_transform_tree', # 'ros2_publish_transform_tree_01', ]}) if enable_lidar: configure_lidar(carter_prim_path, controller) else: # Remove laser scan og.Controller.edit(f'{carter_prim_path}/ActionGraph', {keys.DELETE_NODES: ['isaac_read_lidar_beams_node', 'ros2_publish_laser_scan']}) # Configure left camera configure_camera(carter_prim_path, controller, 'left') # Configure right camera right_info = configure_camera(carter_prim_path, controller, 'right') # Set attribute right_info.get_attribute('inputs:stereoOffset').set(stereo_offset) def setup_forklifts_collision(): # Finally forklifts import omni.kit.commands from omni.isaac.core.utils.prims import is_prim_path_valid from pxr import Sdf for forklift_name in ['Forklift', 'Forklift_01']: forklift_path = f'/World/warehouse_with_forklifts/{forklift_name}' # Ignore if they do not exist if not is_prim_path_valid(forklift_path): continue # Enable collision on main body omni.kit.commands.execute( 'ChangeProperty', prop_path=Sdf.Path( f'{forklift_path}/S_ForkliftBody.physics:collisionEnabled'), value=True, prev=None, ) # Disable collision on invible main body box omni.kit.commands.execute( 'ChangeProperty', prop_path=Sdf.Path( f'{forklift_path}/chassis_collision.physics:collisionEnabled'), value=False, prev=None, ) # Enable collision on tine omni.kit.commands.execute( 'ChangeProperty', prop_path=Sdf.Path( f'{forklift_path}/S_ForkliftFork/collision_box.physics:collisionEnabled' ), value=False, prev=None, ) # Disable collision on tine box omni.kit.commands.execute( 'ChangeProperty', prop_path=Sdf.Path( f'{forklift_path}/S_ForkliftFork/S_ForkliftFork.physics:collisionEnabled' ), value=True, prev=None, ) def main(scenario_path: str, tick_rate_hz: float = 20.0, headless: bool = False, carter_prim_path: str = '/World/Carter_ROS', carter_version: int = 1): # Start up the simulator simulation_app = SimulationApp({ 'renderer': 'RayTracedLighting', 'headless': headless }) import omni from omni.isaac.core import SimulationContext # enable ROS2 bridge extension from omni.isaac.core.utils.extensions import enable_extension enable_extension('omni.isaac.ros2_bridge') from omni.isaac.core.utils.nucleus import get_assets_root_path assets_root_path = get_assets_root_path() if assets_root_path is None: import carb carb.log_error('Could not find Isaac Sim assets folder') simulation_app.close() exit() usd_path = assets_root_path + scenario_path print('------{0} n scenario_path:{1}', usd_path, scenario_path) # Load the stage omni.usd.get_context().open_stage(usd_path, None) # Wait two frames so that stage starts loading simulation_app.update() simulation_app.update() print('Loading stage...') from omni.isaac.core.utils.stage import is_stage_loading while is_stage_loading(): simulation_app.update() print('Loading Complete') time_dt = 1.0 / tick_rate_hz print(f'Running sim at {tick_rate_hz} Hz, with dt of {time_dt}') simulation_context = SimulationContext(stage_units_in_meters=1.0) # Configure sensors print( f'Configuring sensors for Carter {carter_version} at: {carter_prim_path}' ) setup_carter_sensors(carter_prim_path, carter_version=carter_version) setup_forklifts_collision() simulation_context.play() simulation_context.step() # Simulate for one second to warm up sim and let everything settle # Otherwise the resizes below sometimes don't stick. for frame in range(round(tick_rate_hz)): simulation_context.step() # Dock the second camera window right_viewport = omni.ui.Workspace.get_window('Viewport') left_viewport = omni.ui.Workspace.get_window('1') # Viewport 2 if right_viewport is not None and left_viewport is not None: left_viewport.dock_in(right_viewport, omni.ui.DockPosition.LEFT) right_viewport = None left_viewport = None # Run the sim last_frame_time = time.monotonic() while simulation_app.is_running(): simulation_context.step() current_frame_time = time.monotonic() if current_frame_time - last_frame_time < time_dt: time.sleep(time_dt - (current_frame_time - last_frame_time)) last_frame_time = time.monotonic() simulation_context.stop() simulation_app.close() if __name__ == '__main__': parser = argparse.ArgumentParser( description='Sample app for running Carter in a Warehouse for NVblox.') parser.add_argument( '--scenario_path', metavar='scenario_path', type=str, help='Path of the scenario to launch relative to the nucleus server ' 'base path. Scenario must contain a carter robot.', default='/Isaac/Samples/ROS2/Scenario/carter_warehouse_navigation.usd') # OLD /Isaac/Samples/ROS2/Scenario/carter_warehouse_navigation.usd - /Isaac/Samples/ROS2/Scenario/carter_warehouse_apriltags_worker.usd parser.add_argument( '--tick_rate_hz', metavar='tick_rate_hz', type=int, help='The rate (in hz) that we step the simulation at.', default=20) parser.add_argument('--carter_prim_path', metavar='carter_prim_path', type=str, default='/World/Carter_ROS', help='Path to Carter.') parser.add_argument('--headless', action='store_true') parser.add_argument('--carter_version', type=int, default=1, help='Version of the Carter robot (1 or 2)') args, unknown = parser.parse_known_args() main(args.scenario_path, args.tick_rate_hz, args.headless, args.carter_prim_path, args.carter_version)
15,642
Python
37.624691
216
0.619997
NVIDIA-AI-IOT/isaac_demo/isaac_ros/src/isaac_demo/scripts/start_isaac_sim.py
# SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES # Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 import argparse import os import random import time import omni ADDITIONAL_EXTENSIONS_BASE = ['omni.isaac.ros2_bridge-humble'] ADDITIONAL_EXTENSIONS_PEOPLE = [ 'omni.anim.people', 'omni.anim.navigation.bundle', 'omni.anim.timeline', 'omni.anim.graph.bundle', 'omni.anim.graph.core', 'omni.anim.graph.ui', 'omni.anim.retarget.bundle', 'omni.anim.retarget.core', 'omni.anim.retarget.ui', 'omni.kit.scripting'] def enable_extensions_for_sim(with_people: bool = False): """ Enable the required extensions for the simulation. Args: with_people (bool, optional): Loads the human animation extensions if the scene with humans is requested. Defaults to False. """ from omni.isaac.core.utils.extensions import enable_extension add_exten = ADDITIONAL_EXTENSIONS_BASE if with_people: add_exten = ADDITIONAL_EXTENSIONS_BASE + ADDITIONAL_EXTENSIONS_PEOPLE for idx in range(len(add_exten)): enable_extension(add_exten[idx]) def rebuild_nav_mesh(): """ Rebuild the navmesh with the correct settings. Used for the people to move around. Called only when the sim with people is requested. """ # Navigation mesh rebake settings import omni.kit.commands print('Rebuilding navigation mesh...') omni.kit.commands.execute( 'ChangeSetting', path='/exts/omni.anim.navigation.core/navMesh/config/height', value=1.5) omni.kit.commands.execute( 'ChangeSetting', path='/exts/omni.anim.navigation.core/navMesh/config/radius', value=0.5) omni.kit.commands.execute( 'ChangeSetting', path='/exts/omni.anim.navigation.core/navMesh/config/maxSlope', value=60.0) omni.kit.commands.execute( 'ChangeSetting', path='/exts/omni.anim.navigation.core/navMesh/config/maxClimb', value=0.2) omni.kit.commands.execute( 'ChangeSetting', path='/persistent/exts/omni.anim.navigation.core/navMesh/autoRebakeDelaySeconds', value=4) omni.kit.commands.execute( 'ChangeSetting', path='/persistent/exts/omni.anim.navigation.core/navMesh/viewNavMesh', value=False) print('Navigation mesh rebuilt.') def create_people_commands(environment_prim_path: str, anim_people_command_dir: str, max_number_tries: int, num_waypoints_per_human: int): """ Create the occupancy grid which returns the free points for the humans to move. These points are then randomly sampled and assigned to each person and is saved as a txt file which can be used as the command file for people animation. It directly gets the context of the scene once the scene is opened and played in IsaacSim. Args: environment_prim_path (str): The warehouse enviroment prim path anim_people_command_dir (str): The local directory to be used for storing the command file max_number_tries (int): The number of times the script attempts to select a new waypoint for a human. num_waypoints_per_human (int): The number of waypoints to create per human. """ from omni.isaac.occupancy_map import _occupancy_map import omni.anim.navigation.core as navcore from omni.isaac.core.prims import XFormPrim import carb navigation_interface = navcore.acquire_interface() print('Creating randomized paths for people...') bounding_box = omni.usd.get_context().compute_path_world_bounding_box( environment_prim_path) physx = omni.physx.acquire_physx_interface() stage_id = omni.usd.get_context().get_stage_id() generator = _occupancy_map.Generator(physx, stage_id) # 0.05m cell size, output buffer will have 0 for occupied cells, 1 for # unoccupied, and 6 for cells that cannot be seen # this assumes your usd stage units are in m, and not cm generator.update_settings(.05, 0, 1, 6) # Setting the transform for the generator generator.set_transform( # The starting location to map from (0, 0, 0.025), # The min bound (bounding_box[0][0], bounding_box[0][1], 0.025), # The max bound (bounding_box[1][0], bounding_box[1][1], 0.025)) generator.generate2d() # Get locations of free points free_points = generator.get_free_positions() # Find out number of humans in scene and create a list with their names human_names = [] human_prims = [] for human in omni.usd.get_context().get_stage().GetPrimAtPath( '/World/Humans').GetAllChildren(): human_name = human.GetChildren()[0].GetName() # To remove biped setup prim from the list if 'CharacterAnimation' in human_name or 'Biped_Setup' in human_name: continue human_names.append(human_name) human_prims.append(XFormPrim(human.GetPath().pathString)) random_waypoints = {} for human_name, human_prim in zip(human_names, human_prims): # Get the human initial position. start_point, _ = human_prim.get_world_pose() # Initialize target waypoints. random_waypoints[human_name] = [] for _ in range(num_waypoints_per_human): current_tries = 0 path = None # Sample for a maximum number of tries then give up. while path is None and current_tries < max_number_tries: new_waypoint = random.sample(free_points, 1) # Check that a path exists between the starting position and the destination path = navigation_interface.query_navmesh_path( carb.Float3(start_point), new_waypoint[0]) current_tries += 1 if path is not None: new_waypoint[0].z = 0.0 random_waypoints[human_name].append(new_waypoint[0]) print( f'Found path for {human_name} from {start_point} to {new_waypoint[0]} after \ {current_tries} tries') start_point = new_waypoint[0] else: print( f'Could not find path for {human_name} after {max_number_tries}, skipping') # Save as command file command_file_path = os.path.join( anim_people_command_dir, 'human_cmd_file.txt') print(f'Saving randomized commands to {command_file_path}') with open(command_file_path, 'w') as file: for human_name, waypoints in random_waypoints.items(): human_command_line = f'{human_name} GoTo ' for next_waypoint in waypoints: human_command_line += f'{next_waypoint[0]} {next_waypoint[1]} 0 ' human_command_line += '_\n' file.write(human_command_line) def update_people_command_file_path(anim_people_command_dir: str): """ Update the command file path settings in the simulation scene to the custom one. Args: anim_people_command_dir (str): The directory where the generated/custom command file is stored. """ import omni.kit.commands omni.kit.commands.execute( 'ChangeSetting', path='/exts/omni.anim.people/command_settings/command_file_path', value=anim_people_command_dir + '/human_cmd_file.txt') def configure_camera(carter_prim_path, controller, name): # print(f"----------------------------- {name} -------------------------------------") # Change publication topics rgb = controller.node(f'ros2_create_camera_{name}_rgb', f'{carter_prim_path}/ROS_Cameras') rgb.get_attribute('inputs:topicName').set(f'/front/stereo_camera/{name}/rgb') info = controller.node(f'ros2_create_camera_{name}_info', f'{carter_prim_path}/ROS_Cameras') info.get_attribute('inputs:topicName').set(f'/front/stereo_camera/{name}/camera_info') depth = controller.node(f'ros2_create_camera_{name}_depth', f'{carter_prim_path}/ROS_Cameras') depth.get_attribute('inputs:topicName').set(f'/front/stereo_camera/{name}/depth') # Finally, enable rgb and depth for enable_name in [ f'enable_camera_{name}', f'enable_camera_{name}_rgb', f'enable_camera_{name}_depth' ]: enable = controller.node(enable_name, f'{carter_prim_path}/ROS_Cameras') enable.get_attribute('inputs:condition').set(True) return info def main(scenario_path: str, anim_people_command_dir: str, environment_prim_path: str, random_command_generation: bool, num_waypoints: int, headless: bool = False, with_people: bool = True, use_generated_command_file: bool = False, tick_rate_hz: float = 60.0): # Start up the simulator from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({ 'renderer': 'RayTracedLighting', 'headless': headless, 'width': 720, 'height': 480 }) import omni.kit.commands from omni.isaac.core import SimulationContext from omni.isaac.core.utils.nucleus import get_assets_root_path # Enables the simulation extensions enable_extensions_for_sim(with_people) assets_root_path = get_assets_root_path() print(f'##### [from omni.isaac.core.utils.nucleus] get_assets_root_path() returns: {assets_root_path}') if assets_root_path is None: print( 'Could not find Isaac Sim assets folder. Make sure you have an up to date local \ Nucleus server or that you have a proper connection to the internet.' ) simulation_app.close() exit() usd_path = assets_root_path + scenario_path print(f'Opening stage {usd_path}...') # Load the stage omni.usd.get_context().open_stage(usd_path, None) # Wait two frames so that stage starts loading simulation_app.update() simulation_app.update() print('Loading stage...') from omni.isaac.core.utils.stage import is_stage_loading while is_stage_loading(): simulation_app.update() print('Loading Complete') # If the scene with people is requested we build/rebuild the navmesh # We also point to the generated/custom command file for people animation if set by user if with_people: rebuild_nav_mesh() if not random_command_generation and use_generated_command_file: update_people_command_file_path(anim_people_command_dir) # Modify the omnigraph to get lidar point cloud published import omni.graph.core as og keys = og.Controller.Keys controller = og.Controller() enable_odometry = False carter_prim_path = '/World/Carter_ROS' if not enable_odometry: # Remove odometry from Carter og.Controller.edit(f'{carter_prim_path}/ActionGraph', {keys.DELETE_NODES: ['isaac_compute_odometry_node', 'ros2_publish_odometry', 'ros2_publish_raw_transform_tree', # 'ros2_publish_transform_tree_01', ]}) # Configure left camera configure_camera(carter_prim_path, controller, 'left') # Configure right camera right_info = configure_camera(carter_prim_path, controller, 'right') stereo_offset = [-175.92, 0] # Set attribute right_info.get_attribute('inputs:stereoOffset').set(stereo_offset) time_dt = 1.0 / tick_rate_hz print(f'### Running sim at {tick_rate_hz} Hz, with dt of {time_dt}') # Run physics at 60 Hz and render time at the set frequency to see the sim as real time simulation_context = SimulationContext(stage_units_in_meters=1.0, physics_dt=1.0 / 60, rendering_dt=time_dt) simulation_context.play() simulation_context.step() # Physics can only be seen when the scene is played # If we want to generate the command file for the people simulation we call the # create_people_commands method, which stores the command file and then we close the # simulation and point the user on how to use the generated file if with_people and random_command_generation: print('Creating human animation file...') create_people_commands(environment_prim_path, anim_people_command_dir, 10, num_waypoints) print( 'Human command file has been created at {}/human_human_cmd_file.txt' .format(anim_people_command_dir)) print( 'Please restart the simulation with --with_people and \n \ --use_generated_command_file to use the generated command file in human simulation' ) simulation_context.stop() simulation_app.close() # Simulate for a few seconds to warm up sim and let everything settle for _ in range(2*round(tick_rate_hz)): simulation_context.step() # Dock the second camera window right_viewport = omni.ui.Workspace.get_window('Viewport') left_viewport = omni.ui.Workspace.get_window('1') # Viewport 2 if right_viewport is not None and left_viewport is not None: left_viewport.dock_in(right_viewport, omni.ui.DockPosition.LEFT) right_viewport = None left_viewport = None # Run the sim last_frame_time = time.monotonic() while simulation_app.is_running(): simulation_context.step() current_frame_time = time.monotonic() if current_frame_time - last_frame_time < time_dt: time.sleep(time_dt - (current_frame_time - last_frame_time)) last_frame_time = time.monotonic() simulation_context.stop() simulation_app.close() if __name__ == '__main__': parser = argparse.ArgumentParser( description='Sample app for running Carter in a Warehouse for NVblox.') parser.add_argument( '--scenario_path', help='Path of the scenario to launch relative to the nucleus server ' 'base path. Scenario must contain a carter robot. If the scene ' 'contains animated humans, the script expects to find them under /World/Humans. ' 'Example scenarios are /Isaac/Samples/NvBlox/carter_warehouse_navigation_with_people.usd ' 'or /Isaac/Samples/NvBlox/carter_warehouse_navigation.usd', #default='/Isaac/Samples/NvBlox/carter_warehouse_navigation.usd' default='/Isaac/Samples/ROS2/Scenario/carter_warehouse_apriltags_worker.usd' ) parser.add_argument('--environment_prim_path', default='/World/WareHouse', help='Path to the world to create a navigation mesh.') parser.add_argument( '--tick_rate_hz', type=int, help='The rate (in hz) that we step the simulation at.', default=60) parser.add_argument( '--anim_people_waypoint_dir', help='Directory location to save the waypoints in a yaml file') parser.add_argument('--headless', action='store_true', help='Run the simulation headless.') parser.add_argument( '--with_people', help='If used, animation extensions for humans will be enabled.', action='store_true') parser.add_argument( '--random_command_generation', help='Choose whether we generate random waypoint or run sim', action='store_true') parser.add_argument('--num_waypoints', type=int, help='Number of waypoints to generate for each human in the scene.', default=5) parser.add_argument( '--use_generated_command_file', help='Choose whether to use generated/custom command file or to use the default one to run\ the people animation', action='store_true') # This allows for IsaacSim options to be passed on the SimulationApp. args, unknown = parser.parse_known_args() # If we want to generate the command file then we run the simulation headless if args.random_command_generation: args.headless = True # Check if the command file directory is given if it has to be generated or used for the # simulation if args.random_command_generation or args.use_generated_command_file: if not args.anim_people_waypoint_dir: raise ValueError( 'Input to command file directory required if custom command file has to be \ generated/used!!' ) main(args.scenario_path, args.anim_people_waypoint_dir, args.environment_prim_path, args.random_command_generation, args.num_waypoints, args.headless, args.with_people, args.use_generated_command_file, args.tick_rate_hz)
17,704
Python
40.270396
108
0.635224
NVIDIA-AI-IOT/isaac_demo/isaac_ros/src/carter_description/launch/description.launch.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription, LaunchContext from launch.substitutions import Command, LaunchConfiguration from launch.actions import DeclareLaunchArgument, OpaqueFunction from launch_ros.actions import Node def generate_launch_description(): # URDF/xacro file to be loaded by the Robot State Publisher node default_xacro_path = os.path.join( get_package_share_directory('carter_description'), 'urdf', 'carter.urdf' ) xacro_path = LaunchConfiguration('xacro_path') declare_model_path_cmd = DeclareLaunchArgument( name='xacro_path', default_value=default_xacro_path, description='Absolute path to robot urdf file') robot_state_publisher_node = Node( package='robot_state_publisher', executable='robot_state_publisher', parameters=[{ 'robot_description': Command( [ 'xacro ', xacro_path, ' ', ]) }] ) # Define LaunchDescription variable and return it ld = LaunchDescription() ld.add_action(declare_model_path_cmd) ld.add_action(robot_state_publisher_node) return ld # EOF
2,385
Python
36.873015
76
0.716981
NVIDIA-AI-IOT/isaac_demo/isaac_ros/src/carter_description/launch/display.launch.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch_ros.actions import Node from launch.launch_description_sources import PythonLaunchDescriptionSource from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument, Shutdown from launch.conditions import IfCondition, UnlessCondition from launch.substitutions import LaunchConfiguration def generate_launch_description(): carter_description_path = get_package_share_directory('carter_description') gui = LaunchConfiguration('gui') rvizconfig = LaunchConfiguration('rvizconfig') default_rviz_config_path = os.path.join(carter_description_path, 'rviz', 'urdf.rviz') declare_gui_cmd = DeclareLaunchArgument( name='gui', default_value='False', description='Flag to enable joint_state_publisher_gui') declare_rvizconfig_cmd = DeclareLaunchArgument( name='rvizconfig', default_value=default_rviz_config_path, description='Absolute path to rviz config file') joint_state_publisher_gui_node = Node( package='joint_state_publisher_gui', executable='joint_state_publisher_gui', name='joint_state_publisher_gui', condition=IfCondition(gui), on_exit=Shutdown() ) joint_state_publisher_node = Node( package='joint_state_publisher', executable='joint_state_publisher', name='joint_state_publisher', condition=UnlessCondition(gui) ) rviz_node = Node( package='rviz2', executable='rviz2', name='rviz2', output='screen', arguments=['-d', rvizconfig], on_exit=Shutdown() ) # Nanosaur description launch # https://answers.ros.org/question/306935/ros2-include-a-launch-file-from-a-launch-file/ description_launch = IncludeLaunchDescription( PythonLaunchDescriptionSource([carter_description_path, '/launch/description.launch.py']), ) # Define LaunchDescription variable and return it ld = LaunchDescription() ld.add_action(declare_gui_cmd) ld.add_action(declare_rvizconfig_cmd) ld.add_action(description_launch) ld.add_action(joint_state_publisher_node) ld.add_action(joint_state_publisher_gui_node) ld.add_action(rviz_node) return ld # EOF
3,489
Python
37.351648
98
0.725423
RoboEagles4828/2023RobotROS/README.md
# 2023RobotROS ROS Code for the 2023 Robot ## Requirements ------- - Ubuntu 20.04 - RTX Enabled GPU # Workstation Setup steps ### 1. ROS2 Setup - **Install ROS2 Galactic** \ `sudo ./scripts/install-ros2-galactic.sh` - **Install ROS VS Code Extension** \ Go to extensions and search for ROS and click install - **Install Workspace Dependencies** \ Press F1, and run this command: \ `ROS: Install ROS Dependencies for this workspace using rosdep` - **Build the packages** \ Shortcut: `ctrl + shift + b` \ or \ Terminal: `colcon build --symlink-install` - **Done with ROS2 Setup** ### 2. Isaac Sim Setup - **Install Nvidia Drivers** \ `sudo apt-get install nvidia-driver-515` - **Download Omniverse Launcher** \ https://www.nvidia.com/en-us/omniverse/download/ - **Run Omniverse** \ `chmod +x omniverse-launcher-linux.AppImage` \ `./omniverse-launcher-linux.AppImage` - **Install Cache and Isaac Sim from the exchange** \ Wait until both are downloaded and installed. - **Make ROS2 the default bridge** \ `sudo ./scripts/use-isaac-ros2-bridge.sh` - **Launch Isaac Sim** \ Initial load can take a while - **Open the extension manager** \ `Window -> Extensions` - **Import the Swerve Bot Extension** \ Hit the gear icon near the search bar. \ Inside Extension Search Paths, Hit the + icon and put the path \ `<path-to-repo>/2023RobotROS/isaac` - **Enable the Extension** \ Search for the Swerve Bot extension. \ Click on the extension. \ Click on the enable toggle switch and Autoload checkbox - **DONE with Isaac Sim Setup** # Running Swerve Bot 1. Connect an xbox controller 2. Hit load on the *Import URDF* extension window 3. Press Play on the left hand side 4. From this repo directory run \ `source install/setup.bash` \ `ros2 launch swerve_description isaac.launch.py` 5. Use the controller to move the robot around
1,840
Markdown
23.878378
64
0.718478
RoboEagles4828/2023RobotROS/src/swerve_hardware/swerve_hardware.xml
<library path="swerve_hardware"> <class name="swerve_hardware/IsaacDriveHardware" type="swerve_hardware::IsaacDriveHardware" base_class_type="hardware_interface::SystemInterface"> <description> The ROS2 Control hardware interface to talk with Isaac Sim robot drive train. </description> </class> <class name="swerve_hardware/TestDriveHardware" type="swerve_hardware::TestDriveHardware" base_class_type="hardware_interface::SystemInterface"> <description> The ROS2 Control hardware interface for testing a connected controller. </description> </class> </library>
634
XML
36.352939
83
0.714511
RoboEagles4828/2023RobotROS/src/swerve_hardware/src/isaac_drive.cpp
// Copyright 2021 ros2_control Development Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "swerve_hardware/isaac_drive.hpp" #include <chrono> #include <cmath> #include <limits> #include <memory> #include <vector> #include "hardware_interface/types/hardware_interface_type_values.hpp" #include "rclcpp/rclcpp.hpp" #include "sensor_msgs/msg/joint_state.hpp" using std::placeholders::_1; namespace swerve_hardware { CallbackReturn IsaacDriveHardware::on_init(const hardware_interface::HardwareInfo & info) { // rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default; // custom_qos_profile.depth = 7; node_ = rclcpp::Node::make_shared("isaac_hardware_interface"); // PUBLISHER SETUP isaac_publisher_ = node_->create_publisher<sensor_msgs::msg::JointState>("isaac_joint_commands", rclcpp::SystemDefaultsQoS()); realtime_isaac_publisher_ = std::make_shared<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>( isaac_publisher_); // SUBSCRIBER SETUP const sensor_msgs::msg::JointState empty_joint_state; received_joint_msg_ptr_.set(std::make_shared<sensor_msgs::msg::JointState>(empty_joint_state)); isaac_subscriber_ = node_->create_subscription<sensor_msgs::msg::JointState>("isaac_joint_states", rclcpp::SystemDefaultsQoS(), [this](const std::shared_ptr<sensor_msgs::msg::JointState> msg) -> void { if (!subscriber_is_active_) { RCLCPP_WARN( rclcpp::get_logger("isaac_hardware_interface"), "Can't accept new commands. subscriber is inactive"); return; } received_joint_msg_ptr_.set(std::move(msg)); }); // INTERFACE SETUP if (hardware_interface::SystemInterface::on_init(info) != CallbackReturn::SUCCESS) { return CallbackReturn::ERROR; } hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); hw_command_velocity_.resize(info_.joints.size()/2, std::numeric_limits<double>::quiet_NaN()); hw_command_position_.resize(info_.joints.size()/2, std::numeric_limits<double>::quiet_NaN()); for (const hardware_interface::ComponentInfo & joint : info_.joints) { joint_names_.push_back(joint.name); if (joint.command_interfaces.size() != 1) { RCLCPP_FATAL( rclcpp::get_logger("IsaacDriveHardware"), "Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(), joint.command_interfaces.size()); return CallbackReturn::ERROR; } if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY && joint.command_interfaces[0].name != hardware_interface::HW_IF_POSITION) { RCLCPP_FATAL( rclcpp::get_logger("IsaacDriveHardware"), "Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(), joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY); return CallbackReturn::ERROR; } if (joint.state_interfaces.size() != 2) { RCLCPP_FATAL( rclcpp::get_logger("IsaacDriveHardware"), "Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(), joint.state_interfaces.size()); return CallbackReturn::ERROR; } if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION) { RCLCPP_FATAL( rclcpp::get_logger("IsaacDriveHardware"), "Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(), joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION); return CallbackReturn::ERROR; } if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY) { RCLCPP_FATAL( rclcpp::get_logger("IsaacDriveHardware"), "Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(), joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY); return CallbackReturn::ERROR; } } return CallbackReturn::SUCCESS; } std::vector<hardware_interface::StateInterface> IsaacDriveHardware::export_state_interfaces() { std::vector<hardware_interface::StateInterface> state_interfaces; for (auto i = 0u; i < info_.joints.size(); i++) { state_interfaces.emplace_back(hardware_interface::StateInterface( info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i])); state_interfaces.emplace_back(hardware_interface::StateInterface( info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i])); } return state_interfaces; } std::vector<hardware_interface::CommandInterface> IsaacDriveHardware::export_command_interfaces() { std::vector<hardware_interface::CommandInterface> command_interfaces; uint counter_position =0; uint counter_velocity =0; for (auto i = 0u; i < info_.joints.size(); i++) { RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Joint Name %s", info_.joints[i].name.c_str()); if (info_.joints[i].command_interfaces[0].name == hardware_interface::HW_IF_VELOCITY) { command_interfaces.emplace_back(hardware_interface::CommandInterface( info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_command_velocity_[counter_velocity])); RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Velocity: %s", info_.joints[i].name.c_str() ); joint_names_velocity_.emplace_back(info_.joints[i].name); counter_velocity++; } else { command_interfaces.emplace_back(hardware_interface::CommandInterface( info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_command_position_[counter_position])); RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Position: %s", info_.joints[i].name.c_str() ); joint_names_position_.emplace_back(info_.joints[i].name); counter_position++; } } return command_interfaces; } CallbackReturn IsaacDriveHardware::on_activate( const rclcpp_lifecycle::State & /*previous_state*/) { RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Activating ...please wait..."); // Set Default Values for State Interface Arrays for (auto i = 0u; i < hw_positions_.size(); i++) { hw_positions_[i] = NULL; hw_velocities_[i] = NULL; joint_names_map_[joint_names_[i]] = i + 1; // ADD 1 to differentiate null key } // Set Default Values for Command Interface Arrays for (auto i = 0u; i < hw_command_velocity_.size(); i++) { hw_command_velocity_[i] = NULL; hw_command_position_[i] = NULL; } subscriber_is_active_ = true; RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Successfully activated!"); return CallbackReturn::SUCCESS; } CallbackReturn IsaacDriveHardware::on_deactivate( const rclcpp_lifecycle::State & /*previous_state*/) { RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Deactivating ...please wait..."); subscriber_is_active_ = false; RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Successfully deactivated!"); return CallbackReturn::SUCCESS; } // || || // \/ THE STUFF THAT MATTERS \/ hardware_interface::return_type IsaacDriveHardware::read() { rclcpp::spin_some(node_); std::shared_ptr<sensor_msgs::msg::JointState> last_command_msg; received_joint_msg_ptr_.get(last_command_msg); if (last_command_msg == nullptr) { RCLCPP_WARN(rclcpp::get_logger("IsaacDriveHardware"), "Velocity message received was a nullptr."); return hardware_interface::return_type::ERROR; } auto names = last_command_msg->name; auto positions = last_command_msg->position; auto velocities = last_command_msg->velocity; for (auto i = 0u; i < names.size(); i++) { uint p = joint_names_map_[names[i]]; if (p > 0) { hw_positions_[p - 1] = positions[i]; hw_velocities_[p - 1] = velocities[i]; } } return hardware_interface::return_type::OK; } hardware_interface::return_type swerve_hardware::IsaacDriveHardware::write() { //RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Velocity: %f", hw_command_velocity_[0]); // Publish Velocity if (realtime_isaac_publisher_->trylock()) { auto & realtime_isaac_command_ = realtime_isaac_publisher_->msg_; realtime_isaac_command_.header.stamp = node_->get_clock()->now(); realtime_isaac_command_.name = joint_names_velocity_; realtime_isaac_command_.velocity = hw_command_velocity_; realtime_isaac_command_.position = empty_; realtime_isaac_publisher_->unlockAndPublish(); } rclcpp::spin_some(node_); // Publish Position if (realtime_isaac_publisher_->trylock()) { auto & realtime_isaac_command_ = realtime_isaac_publisher_->msg_; realtime_isaac_command_.header.stamp = node_->get_clock()->now(); realtime_isaac_command_.name = joint_names_position_; realtime_isaac_command_.velocity = empty_; realtime_isaac_command_.position = hw_command_position_; realtime_isaac_publisher_->unlockAndPublish(); } rclcpp::spin_some(node_); return hardware_interface::return_type::OK; } } // namespace swerve_hardware #include "pluginlib/class_list_macros.hpp" PLUGINLIB_EXPORT_CLASS( swerve_hardware::IsaacDriveHardware, hardware_interface::SystemInterface)
9,799
C++
34.379061
153
0.68558
RoboEagles4828/2023RobotROS/src/swerve_hardware/src/test_drive.cpp
// Copyright 2021 ros2_control Development Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "swerve_hardware/test_drive.hpp" #include <chrono> #include <cmath> #include <limits> #include <memory> #include <vector> #include "hardware_interface/types/hardware_interface_type_values.hpp" #include "rclcpp/rclcpp.hpp" using std::placeholders::_1; namespace swerve_hardware { CallbackReturn TestDriveHardware::on_init(const hardware_interface::HardwareInfo & info) { // INTERFACE SETUP if (hardware_interface::SystemInterface::on_init(info) != CallbackReturn::SUCCESS) { return CallbackReturn::ERROR; } // 8 positions states, 4 axle positions 4 wheel positions hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); // 8 velocity states, 4 axle velocity 4 wheel velocity hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); // 4 wheel velocity commands hw_command_velocity_.resize(info_.joints.size()/2, std::numeric_limits<double>::quiet_NaN()); // 4 axle position commands hw_command_position_.resize(info_.joints.size()/2, std::numeric_limits<double>::quiet_NaN()); for (const hardware_interface::ComponentInfo & joint : info_.joints) { joint_names_.push_back(joint.name); if (joint.command_interfaces.size() != 1) { RCLCPP_FATAL( rclcpp::get_logger("TestDriveHardware"), "Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(), joint.command_interfaces.size()); return CallbackReturn::ERROR; } if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY && joint.command_interfaces[0].name != hardware_interface::HW_IF_POSITION) { RCLCPP_FATAL( rclcpp::get_logger("TestDriveHardware"), "Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(), joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY); return CallbackReturn::ERROR; } if (joint.state_interfaces.size() != 2) { RCLCPP_FATAL( rclcpp::get_logger("TestDriveHardware"), "Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(), joint.state_interfaces.size()); return CallbackReturn::ERROR; } if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION) { RCLCPP_FATAL( rclcpp::get_logger("TestDriveHardware"), "Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(), joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION); return CallbackReturn::ERROR; } if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY) { RCLCPP_FATAL( rclcpp::get_logger("TestDriveHardware"), "Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(), joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY); return CallbackReturn::ERROR; } } return CallbackReturn::SUCCESS; } std::vector<hardware_interface::StateInterface> TestDriveHardware::export_state_interfaces() { std::vector<hardware_interface::StateInterface> state_interfaces; for (auto i = 0u; i < info_.joints.size(); i++) { state_interfaces.emplace_back(hardware_interface::StateInterface( info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i])); state_interfaces.emplace_back(hardware_interface::StateInterface( info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i])); } return state_interfaces; } std::vector<hardware_interface::CommandInterface> TestDriveHardware::export_command_interfaces() { std::vector<hardware_interface::CommandInterface> command_interfaces; uint counter_position =0; uint counter_velocity =0; for (auto i = 0u; i < info_.joints.size(); i++) { auto joint = info_.joints[i]; RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Joint Name %s", joint.name.c_str()); if (joint.command_interfaces[0].name == hardware_interface::HW_IF_VELOCITY) { RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Added Velocity Joint: %s", joint.name.c_str() ); command_interfaces.emplace_back(hardware_interface::CommandInterface( joint.name, hardware_interface::HW_IF_VELOCITY, &hw_command_velocity_[counter_velocity])); names_to_vel_cmd_map_[joint.name] = counter_velocity + 1; // ADD 1 to differentiate from a key that is not found counter_velocity++; } else { RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Added Position Joint: %s", joint.name.c_str() ); command_interfaces.emplace_back(hardware_interface::CommandInterface( joint.name, hardware_interface::HW_IF_POSITION, &hw_command_position_[counter_position])); names_to_pos_cmd_map_[joint.name] = counter_position + 1; // ADD 1 to differentiate from a key that is not found counter_position++; } } return command_interfaces; } CallbackReturn TestDriveHardware::on_activate( const rclcpp_lifecycle::State & /*previous_state*/) { RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Activating ...please wait..."); // Set Default Values for State Interface Arrays for (auto i = 0u; i < hw_positions_.size(); i++) { hw_positions_[i] = 0.0; hw_velocities_[i] = 0.0; } // Set Default Values for Command Interface Arrays for (auto i = 0u; i < hw_command_velocity_.size(); i++) { hw_command_velocity_[i] = 0.0; hw_command_position_[i] = 0.0; } RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Successfully activated!"); return CallbackReturn::SUCCESS; } CallbackReturn TestDriveHardware::on_deactivate( const rclcpp_lifecycle::State & /*previous_state*/) { RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Deactivating ...please wait..."); RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Successfully deactivated!"); return CallbackReturn::SUCCESS; } // || || // \/ THE STUFF THAT MATTERS \/ hardware_interface::return_type TestDriveHardware::read() { // Dumb Pass Through // If you give the command for x velocity then the state is x velocity // Loop through each joint name // Check if joint name is in velocity command map // If it is, use the index from the map to get the value in the velocity array // If velocity not in map, set velocity value to 0 // Perform the same for position double dt = 0.01; for (auto i = 0u; i < joint_names_.size(); i++) { auto vel_i = names_to_vel_cmd_map_[joint_names_[i]]; auto pos_i = names_to_pos_cmd_map_[joint_names_[i]]; if (vel_i > 0) { // RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "J %f", hw_command_velocity_[vel_i - 1]); auto vel = hw_command_velocity_[vel_i - 1]; hw_velocities_[i] = vel; hw_positions_[i] = hw_positions_[i] + dt * vel; } else if (pos_i > 0) { auto pos = hw_command_position_[pos_i - 1]; hw_velocities_[i] = 0.0; hw_positions_[i] = pos; } } return hardware_interface::return_type::OK; } hardware_interface::return_type swerve_hardware::TestDriveHardware::write() { // Do Nothing // Uncomment below if you want verbose messages for debugging. for (auto i = 0u; i < hw_command_velocity_.size(); i++) { // RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Wheel %u Velocity: %f", i, hw_command_velocity_[i]); } return hardware_interface::return_type::OK; } } // namespace swerve_hardware #include "pluginlib/class_list_macros.hpp" PLUGINLIB_EXPORT_CLASS( swerve_hardware::TestDriveHardware, hardware_interface::SystemInterface)
8,298
C++
33.012295
153
0.676549
RoboEagles4828/2023RobotROS/src/swerve_hardware/include/swerve_hardware/visibility_control.h
// Copyright 2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* This header must be included by all rclcpp headers which declare symbols * which are defined in the rclcpp library. When not building the rclcpp * library, i.e. when using the headers in other package's code, the contents * of this header change the visibility of certain symbols which the rclcpp * library cannot have, but the consuming code must have inorder to link. */ #ifndef SWERVE_HARDWARE__VISIBILITY_CONTROL_H_ #define SWERVE_HARDWARE__VISIBILITY_CONTROL_H_ // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define SWERVE_HARDWARE_EXPORT __attribute__((dllexport)) #define SWERVE_HARDWARE_IMPORT __attribute__((dllimport)) #else #define SWERVE_HARDWARE_EXPORT __declspec(dllexport) #define SWERVE_HARDWARE_IMPORT __declspec(dllimport) #endif #ifdef SWERVE_HARDWARE_BUILDING_DLL #define SWERVE_HARDWARE_PUBLIC SWERVE_HARDWARE_EXPORT #else #define SWERVE_HARDWARE_PUBLIC SWERVE_HARDWARE_IMPORT #endif #define SWERVE_HARDWARE_PUBLIC_TYPE SWERVE_HARDWARE_PUBLIC #define SWERVE_HARDWARE_LOCAL #else #define SWERVE_HARDWARE_EXPORT __attribute__((visibility("default"))) #define SWERVE_HARDWARE_IMPORT #if __GNUC__ >= 4 #define SWERVE_HARDWARE_PUBLIC __attribute__((visibility("default"))) #define SWERVE_HARDWARE_LOCAL __attribute__((visibility("hidden"))) #else #define SWERVE_HARDWARE_PUBLIC #define SWERVE_HARDWARE_LOCAL #endif #define SWERVE_HARDWARE_PUBLIC_TYPE #endif #endif // SWERVE_HARDWARE__VISIBILITY_CONTROL_H_
2,184
C
38.017856
79
0.763278
RoboEagles4828/2023RobotROS/src/swerve_hardware/include/swerve_hardware/test_drive.hpp
// Copyright 2021 ros2_control Development Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SWERVE_HARDWARE__TEST_DRIVE_HPP_ #define SWERVE_HARDWARE__TEST_DRIVE_HPP_ #include <memory> #include <string> #include <vector> #include <map> #include "hardware_interface/handle.hpp" #include "hardware_interface/hardware_info.hpp" #include "hardware_interface/system_interface.hpp" #include "hardware_interface/types/hardware_interface_return_values.hpp" #include "rclcpp/macros.hpp" #include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp" #include "rclcpp_lifecycle/state.hpp" #include "swerve_hardware/visibility_control.h" #include "rclcpp/rclcpp.hpp" using CallbackReturn = rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn; namespace swerve_hardware { class TestDriveHardware : public hardware_interface::SystemInterface { public: RCLCPP_SHARED_PTR_DEFINITIONS(TestDriveHardware) SWERVE_HARDWARE_PUBLIC CallbackReturn on_init(const hardware_interface::HardwareInfo & info) override; SWERVE_HARDWARE_PUBLIC std::vector<hardware_interface::StateInterface> export_state_interfaces() override; SWERVE_HARDWARE_PUBLIC std::vector<hardware_interface::CommandInterface> export_command_interfaces() override; SWERVE_HARDWARE_PUBLIC CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_HARDWARE_PUBLIC CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_HARDWARE_PUBLIC hardware_interface::return_type read() override; SWERVE_HARDWARE_PUBLIC hardware_interface::return_type write() override; private: // Store the command for the simulated robot std::vector<double> hw_command_velocity_; std::vector<double> hw_command_position_; // Map for easy lookup name -> joint command value std::map<std::string, uint> names_to_vel_cmd_map_; std::map<std::string, uint> names_to_pos_cmd_map_; // The state vectors std::vector<double> hw_positions_; std::vector<double> hw_velocities_; // Joint name array will align with state and command interface array // The command at index 3 of hw_command_ will be the joint name at index 3 of joint_names std::vector<std::string> joint_names_; }; } // namespace swerve_hardware #endif // SWERVE_HARDWARE__TEST_DRIVE_HPP_
2,857
C++
33.433735
97
0.765838
RoboEagles4828/2023RobotROS/src/swerve_hardware/include/swerve_hardware/isaac_drive.hpp
// Copyright 2021 ros2_control Development Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SWERVE_HARDWARE__ISAAC_DRIVE_HPP_ #define SWERVE_HARDWARE__ISAAC_DRIVE_HPP_ #include <memory> #include <string> #include <vector> #include <map> #include "hardware_interface/handle.hpp" #include "hardware_interface/hardware_info.hpp" #include "hardware_interface/system_interface.hpp" #include "hardware_interface/types/hardware_interface_return_values.hpp" #include "rclcpp/macros.hpp" #include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp" #include "rclcpp_lifecycle/state.hpp" #include "swerve_hardware/visibility_control.h" #include "rclcpp/rclcpp.hpp" #include "sensor_msgs/msg/joint_state.hpp" #include "realtime_tools/realtime_box.h" #include "realtime_tools/realtime_buffer.h" #include "realtime_tools/realtime_publisher.h" using CallbackReturn = rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn; namespace swerve_hardware { class IsaacDriveHardware : public hardware_interface::SystemInterface { public: RCLCPP_SHARED_PTR_DEFINITIONS(IsaacDriveHardware) SWERVE_HARDWARE_PUBLIC CallbackReturn on_init(const hardware_interface::HardwareInfo & info) override; SWERVE_HARDWARE_PUBLIC std::vector<hardware_interface::StateInterface> export_state_interfaces() override; SWERVE_HARDWARE_PUBLIC std::vector<hardware_interface::CommandInterface> export_command_interfaces() override; SWERVE_HARDWARE_PUBLIC CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_HARDWARE_PUBLIC CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_HARDWARE_PUBLIC hardware_interface::return_type read() override; SWERVE_HARDWARE_PUBLIC hardware_interface::return_type write() override; private: // Parameters for the DiffBot simulation double hw_start_sec_; double hw_stop_sec_; // Store the command for the simulated robot std::vector<double> hw_command_velocity_; std::vector<double> hw_command_position_; std::vector<double> hw_positions_; std::vector<double> hw_velocities_; std::vector<double> empty_; std::vector<std::string> joint_names_; std::vector<std::string> joint_names_velocity_; std::vector<std::string> joint_names_position_; std::map<std::string, uint> joint_names_map_; // Pub Sub to isaac rclcpp::Node::SharedPtr node_; std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::JointState>> isaac_publisher_ = nullptr; std::shared_ptr<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>> realtime_isaac_publisher_ = nullptr; bool subscriber_is_active_ = false; rclcpp::Subscription<sensor_msgs::msg::JointState>::SharedPtr isaac_subscriber_ = nullptr; realtime_tools::RealtimeBox<std::shared_ptr<sensor_msgs::msg::JointState>> received_joint_msg_ptr_{nullptr}; }; } // namespace swerve_hardware #endif // SWERVE_HARDWARE__DIFFBOT_SYSTEM_HPP_
3,480
C++
34.520408
110
0.764943
RoboEagles4828/2023RobotROS/src/swerve_description/launch/rviz_gui.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.substitutions import LaunchConfiguration from launch.actions import DeclareLaunchArgument, ExecuteProcess from launch_ros.actions import Node import xacro def generate_launch_description(): # Check if we're told to use sim time use_sim_time = LaunchConfiguration('use_sim_time') # Process the URDF file pkg_path = os.path.join(get_package_share_directory('swerve_description')) xacro_file = os.path.join(pkg_path,'urdf', 'robots','swerve.urdf.xacro') robot_description_config = xacro.process_file(xacro_file) # Save Built URDF file to Description Directory robot_description_xml = robot_description_config.toxml() source_code_path = os.path.abspath(os.path.join(pkg_path, "../../../../src/swerve_description")) urdf_save_path = os.path.join(source_code_path, "swerve.urdf") with open(urdf_save_path, 'w') as f: f.write(robot_description_xml) # Create a robot_state_publisher node params = {'robot_description': robot_description_xml, 'use_sim_time': use_sim_time} node_robot_state_publisher = Node( package='robot_state_publisher', executable='robot_state_publisher', output='screen', parameters=[params] ) # Create the publiser gui joint_state_publisher_gui = Node( package='joint_state_publisher_gui', executable='joint_state_publisher_gui', output='screen' ) # Start Rviz2 with basic view rviz2_config_path = os.path.join(get_package_share_directory('swerve_description'), 'config/view.rviz') run_rviz2 = ExecuteProcess( cmd=['rviz2', '-d', rviz2_config_path], output='screen' ) # Launch! return LaunchDescription([ DeclareLaunchArgument( 'use_sim_time', default_value='false', description='Use sim time if true'), node_robot_state_publisher, joint_state_publisher_gui, run_rviz2 ])
2,082
Python
31.546875
107
0.670509
RoboEagles4828/2023RobotROS/src/swerve_description/launch/test_hw.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.substitutions import LaunchConfiguration from launch.actions import ExecuteProcess, IncludeLaunchDescription, RegisterEventHandler from launch.event_handlers import OnProcessExit from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.actions import Node import xacro def generate_launch_description(): # SIM TIME MUST BE DISABLED # sim time relys on a simulation to handle the ros clock. # this launch uses fake hardware using the real clock. use_sim_time = False # Process the URDF file pkg_path = os.path.join(get_package_share_directory('swerve_description')) xacro_file = os.path.join(pkg_path,'urdf', 'robots','swerve.urdf.xacro') controllers_file = os.path.join(pkg_path, 'config', 'controllers.yaml') joystick_file = os.path.join(pkg_path, 'config', 'xbox-holonomic.config.yaml') rviz_file = os.path.join(pkg_path, 'config', 'view.rviz') # TODO: Make this as an arguement to the isaac launch file instead. These files are identical other than this. swerve_description_config = xacro.process_file(xacro_file, mappings={ 'hw_interface_plugin': 'swerve_hardware/TestDriveHardware' }) # Save Built URDF file to Description Directory swerve_description_xml = swerve_description_config.toxml() source_code_path = os.path.abspath(os.path.join(pkg_path, "../../../../src/swerve_description")) urdf_save_path = os.path.join(source_code_path, "swerve.urdf") with open(urdf_save_path, 'w') as f: f.write(swerve_description_xml) # Create a robot_state_publisher node params = {'robot_description': swerve_description_xml, 'use_sim_time': use_sim_time} node_robot_state_publisher = Node( package='robot_state_publisher', executable='robot_state_publisher', output='screen', parameters=[params] ) # Starts ROS2 Control control_node = Node( package="controller_manager", executable="ros2_control_node", parameters=[{'robot_description': swerve_description_xml, 'use_sim_time': use_sim_time }, controllers_file], output="screen", ) # Starts ROS2 Control Joint State Broadcaster joint_state_broadcaster_spawner = Node( package="controller_manager", executable="spawner", arguments=["joint_state_broadcaster", "--controller-manager", "/controller_manager"], ) #Starts ROS2 Control Swerve Drive Controller swerve_drive_controller_spawner = Node( package="controller_manager", executable="spawner", arguments=["swerve_controller", "-c", "/controller_manager"], ) swerve_drive_controller_delay = RegisterEventHandler( event_handler=OnProcessExit( target_action=joint_state_broadcaster_spawner, on_exit=[swerve_drive_controller_spawner], ) ) # Start Rviz2 with basic view run_rviz2_node = Node( package='rviz2', executable='rviz2', name='isaac_rviz2', output='screen', arguments=[["-d"], [rviz_file], '--ros-args', '--log-level', 'FATAL'], ) rviz2_delay = RegisterEventHandler( event_handler=OnProcessExit( target_action=joint_state_broadcaster_spawner, on_exit=[run_rviz2_node], ) ) # Start Joystick Node joy = Node( package='joy', executable='joy_node', name='joy_node', parameters=[{ 'dev': '/dev/input/js0', 'deadzone': 0.3, 'autorepeat_rate': 20.0, }]) # Start Teleop Node to translate joystick commands to robot commands joy_teleop = Node( package='teleop_twist_joy', executable='teleop_node', name='teleop_twist_joy_node', parameters=[joystick_file], remappings={('/cmd_vel', '/swerve_controller/cmd_vel_unstamped')} ) # Launch! return LaunchDescription([ control_node, node_robot_state_publisher, joint_state_broadcaster_spawner, swerve_drive_controller_delay, rviz2_delay, joy, joy_teleop ])
4,317
Python
33
135
0.646977
RoboEagles4828/2023RobotROS/src/swerve_description/launch/isaac.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.substitutions import LaunchConfiguration from launch.actions import ExecuteProcess, IncludeLaunchDescription, RegisterEventHandler from launch.event_handlers import OnProcessExit from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.actions import Node import xacro def generate_launch_description(): use_sim_time = True # Process the URDF file pkg_path = os.path.join(get_package_share_directory('swerve_description')) xacro_file = os.path.join(pkg_path,'urdf', 'robots','swerve.urdf.xacro') controllers_file = os.path.join(pkg_path, 'config', 'controllers.yaml') joystick_file = os.path.join(pkg_path, 'config', 'xbox-holonomic.config.yaml') rviz_file = os.path.join(pkg_path, 'config', 'view.rviz') swerve_description_config = xacro.process_file(xacro_file) # Save Built URDF file to Description Directory swerve_description_xml = swerve_description_config.toxml() source_code_path = os.path.abspath(os.path.join(pkg_path, "../../../../src/swerve_description")) urdf_save_path = os.path.join(source_code_path, "swerve.urdf") with open(urdf_save_path, 'w') as f: f.write(swerve_description_xml) # Create a robot_state_publisher node params = {'robot_description': swerve_description_xml, 'use_sim_time': use_sim_time} node_robot_state_publisher = Node( package='robot_state_publisher', executable='robot_state_publisher', output='screen', parameters=[params] ) # Starts ROS2 Control control_node = Node( package="controller_manager", executable="ros2_control_node", parameters=[{'robot_description': swerve_description_xml, 'use_sim_time': True }, controllers_file], output="screen", ) # Starts ROS2 Control Joint State Broadcaster joint_state_broadcaster_spawner = Node( package="controller_manager", executable="spawner", arguments=["joint_state_broadcaster", "--controller-manager", "/controller_manager"], ) #Starts ROS2 Control Swerve Drive Controller swerve_drive_controller_spawner = Node( package="controller_manager", executable="spawner", arguments=["swerve_controller", "-c", "/controller_manager"], ) swerve_drive_controller_delay = RegisterEventHandler( event_handler=OnProcessExit( target_action=joint_state_broadcaster_spawner, on_exit=[swerve_drive_controller_spawner], ) ) # Start Rviz2 with basic view run_rviz2_node = Node( package='rviz2', executable='rviz2', parameters=[{ 'use_sim_time': True }], name='isaac_rviz2', output='screen', arguments=[["-d"], [rviz_file]], ) # run_rviz2 = ExecuteProcess( # cmd=['rviz2', '-d', rviz_file], # output='screen' # ) rviz2_delay = RegisterEventHandler( event_handler=OnProcessExit( target_action=joint_state_broadcaster_spawner, on_exit=[run_rviz2_node], ) ) # Start Joystick Node joy = Node( package='joy', executable='joy_node', name='joy_node', parameters=[{ 'dev': '/dev/input/js0', 'deadzone': 0.3, 'autorepeat_rate': 20.0, }]) # Start Teleop Node to translate joystick commands to robot commands joy_teleop = Node( package='teleop_twist_joy', executable='teleop_node', name='teleop_twist_joy_node', parameters=[joystick_file], remappings={('/cmd_vel', '/swerve_controller/cmd_vel_unstamped')} ) # Launch! return LaunchDescription([ control_node, node_robot_state_publisher, joint_state_broadcaster_spawner, swerve_drive_controller_delay, rviz2_delay, joy, joy_teleop ])
4,088
Python
30.697674
108
0.633562
RoboEagles4828/2023RobotROS/src/swerve_description/config/controllers.yaml
controller_manager: ros__parameters: update_rate: 10 # Hz joint_state_broadcaster: type: joint_state_broadcaster/JointStateBroadcaster swerve_controller: type: swerve_controller/SwerveController swerve_controller: ros__parameters: front_left_wheel_joint: "front_left_wheel_joint" front_right_wheel_joint: "front_right_wheel_joint" rear_left_wheel_joint: "back_left_wheel_joint" rear_right_wheel_joint: "back_right_wheel_joint" front_left_axle_joint: "front_left_axle_joint" front_right_axle_joint: "front_right_axle_joint" rear_left_axle_joint: "back_left_axle_joint" rear_right_axle_joint: "back_right_axle_joint" chassis_length: 0.7366 chassis_width: 0.7366 wheel_radius: 0.1016 cmd_vel_timeout: 10.0 use_stamped_vel: false
810
YAML
30.192307
57
0.707407
RoboEagles4828/2023RobotROS/src/swerve_description/config/xbox-holonomic.config.yaml
teleop_twist_joy_node: ros__parameters: require_enable_button: false axis_linear: # Left thumb stick vertical x: 1 y: 0 scale_linear: x: 5.0 y: 5.0 axis_angular: # Right thumb stick horizontal yaw: 2 scale_angular: yaw: 3.14159 enable_button: 2 # Left trigger button enable_turbo_button: 5 # Right trigger button
391
YAML
20.777777
50
0.601023
RoboEagles4828/2023RobotROS/src/test_swerve_control/setup.py
from setuptools import setup package_name = 'test_swerve_control' setup( name=package_name, version='0.0.0', packages=[package_name], data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), ('share/' + package_name, ['package.xml']), ], install_requires=['setuptools'], zip_safe=True, maintainer='helios', maintainer_email='[email protected]', description='Control the robot', license='MIT', tests_require=['pytest'], entry_points={ 'console_scripts': [ 'publish-joints = test_swerve_control.publish_joint_command:main', 'publish-twist = test_swerve_control.publish_twist_command:main', ], }, )
761
Python
26.214285
78
0.609724
RoboEagles4828/2023RobotROS/src/test_swerve_control/test/test_flake8.py
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ament_flake8.main import main_with_errors import pytest @pytest.mark.flake8 @pytest.mark.linter def test_flake8(): rc, errors = main_with_errors(argv=[]) assert rc == 0, \ 'Found %d code style errors / warnings:\n' % len(errors) + \ '\n'.join(errors)
884
Python
33.03846
74
0.725113
RoboEagles4828/2023RobotROS/src/test_swerve_control/test/test_pep257.py
# Copyright 2015 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ament_pep257.main import main import pytest @pytest.mark.linter @pytest.mark.pep257 def test_pep257(): rc = main(argv=['.', 'test']) assert rc == 0, 'Found code style errors / warnings'
803
Python
32.499999
74
0.743462
RoboEagles4828/2023RobotROS/src/test_swerve_control/test/test_copyright.py
# Copyright 2015 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ament_copyright.main import main import pytest @pytest.mark.copyright @pytest.mark.linter def test_copyright(): rc = main(argv=['.', 'test']) assert rc == 0, 'Found errors'
790
Python
31.958332
74
0.74557
RoboEagles4828/2023RobotROS/src/test_swerve_control/test_swerve_control/publish_twist_command.py
import rclpy from rclpy.node import Node from geometry_msgs.msg import Twist, Vector3 class PublishTwistCmd(Node): def __init__(self): super().__init__('publish_twist_commands') self.publisher_ = self.create_publisher(Twist, 'swerve_controller/cmd_vel_unstamped', 10) timer_period = 0.5 # seconds self.timer = self.create_timer(timer_period, self.timer_callback) self.i = 0 def timer_callback(self): twist = Twist() twist.linear.x = 2.0 twist.linear.y = 100.0 twist.angular.z = 4.0 self.publisher_.publish(twist) self.get_logger().info('Publishing: ...') self.i += 1 def main(args=None): rclpy.init(args=args) node = PublishTwistCmd() rclpy.spin(node) node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
870
Python
22.54054
97
0.6
RoboEagles4828/2023RobotROS/src/test_swerve_control/test_swerve_control/publish_joint_command.py
import rclpy from rclpy.node import Node from sensor_msgs.msg import JointState class PublishJointCmd(Node): def __init__(self): super().__init__('publish_joint_commands') self.publisher_ = self.create_publisher(JointState, 'isaac_joint_commands', 10) timer_period = 0.5 # seconds self.timer = self.create_timer(timer_period, self.timer_callback) self.i = 0 def timer_callback(self): velocity_cmds = JointState() position_cmds = JointState() velocity_cmds.name = [ 'front_left_wheel_joint', 'front_right_wheel_joint', 'back_left_wheel_joint', 'back_right_wheel_joint'] position_cmds.name = [ 'front_left_axle_joint', 'front_right_axle_joint', 'back_left_axle_joint', 'back_right_axle_joint'] velocity_cmds.velocity = [ 10.0, 10.0, 10.0, 10.0 ] position_cmds.position = [45.0, 45.0, 45.0, 45.0] self.publisher_.publish(velocity_cmds) self.publisher_.publish(position_cmds) self.get_logger().info('Publishing: ...') self.i += 1 def main(args=None): rclpy.init(args=args) node = PublishJointCmd() rclpy.spin(node) # Destroy the node explicitly # (optional - otherwise it will be done automatically # when the garbage collector destroys the node object) node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
1,514
Python
26.545454
87
0.589168
RoboEagles4828/2023RobotROS/src/swerve_controller/swerve_plugin.xml
<library path="swerve_controller"> <class name="swerve_controller/SwerveController" type="swerve_controller::SwerveController" base_class_type="controller_interface::ControllerInterface"> <description> The swerve controller transforms linear and angular velocity messages into signals for each wheel(s) and swerve modules. </description> </class> </library>
370
XML
45.374994
154
0.783784
RoboEagles4828/2023RobotROS/src/swerve_controller/src/swerve_controller.cpp
// Copyright 2020 PAL Robotics S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * Author: Bence Magyar, Enrique Fernández, Manuel Meraz */ #include <memory> #include <queue> #include <string> #include <utility> #include <vector> #include <cmath> #include "swerve_controller/swerve_controller.hpp" #include "hardware_interface/types/hardware_interface_type_values.hpp" #include "lifecycle_msgs/msg/state.hpp" #include "rclcpp/logging.hpp" namespace { constexpr auto DEFAULT_COMMAND_TOPIC = "~/cmd_vel"; constexpr auto DEFAULT_COMMAND_UNSTAMPED_TOPIC = "~/cmd_vel_unstamped"; constexpr auto DEFAULT_COMMAND_OUT_TOPIC = "~/cmd_vel_out"; } // namespace namespace swerve_controller { using namespace std::chrono_literals; using controller_interface::interface_configuration_type; using controller_interface::InterfaceConfiguration; using hardware_interface::HW_IF_POSITION; using hardware_interface::HW_IF_VELOCITY; using lifecycle_msgs::msg::State; Wheel::Wheel(std::reference_wrapper<hardware_interface::LoanedCommandInterface> velocity, std::string name) : velocity_(velocity), name(std::move(name)) {} void Wheel::set_velocity(double velocity) { velocity_.get().set_value(velocity); } Axle::Axle(std::reference_wrapper<hardware_interface::LoanedCommandInterface> position, std::string name) : position_(position), name(std::move(name)) {} void Axle::set_position(double position) { position_.get().set_value(position); } SwerveController::SwerveController() : controller_interface::ControllerInterface() {} CallbackReturn SwerveController::on_init() { try { // with the lifecycle node being initialized, we can declare parameters auto_declare<std::string>("front_left_wheel_joint", front_left_wheel_joint_name_); auto_declare<std::string>("front_right_wheel_joint", front_right_wheel_joint_name_); auto_declare<std::string>("rear_left_wheel_joint", rear_left_wheel_joint_name_); auto_declare<std::string>("rear_right_wheel_joint", rear_right_wheel_joint_name_); auto_declare<std::string>("front_left_axle_joint", front_left_axle_joint_name_); auto_declare<std::string>("front_right_axle_joint", front_right_axle_joint_name_); auto_declare<std::string>("rear_left_axle_joint", rear_left_axle_joint_name_); auto_declare<std::string>("rear_right_axle_joint", rear_right_axle_joint_name_); auto_declare<double>("chassis_length", wheel_params_.x_offset); auto_declare<double>("chassis_width", wheel_params_.y_offset); auto_declare<double>("wheel_radius", wheel_params_.radius); auto_declare<double>("cmd_vel_timeout", cmd_vel_timeout_.count() / 1000.0); auto_declare<bool>("use_stamped_vel", use_stamped_vel_); } catch (const std::exception & e) { fprintf(stderr, "Exception thrown during init stage with message: %s \n", e.what()); return CallbackReturn::ERROR; } return CallbackReturn::SUCCESS; } InterfaceConfiguration SwerveController::command_interface_configuration() const { std::vector<std::string> conf_names; conf_names.push_back(front_left_wheel_joint_name_ + "/" + HW_IF_VELOCITY); conf_names.push_back(front_right_wheel_joint_name_ + "/" + HW_IF_VELOCITY); conf_names.push_back(rear_left_wheel_joint_name_ + "/" + HW_IF_VELOCITY); conf_names.push_back(rear_right_wheel_joint_name_ + "/" + HW_IF_VELOCITY); conf_names.push_back(front_left_axle_joint_name_ + "/" + HW_IF_POSITION); conf_names.push_back(front_right_axle_joint_name_ + "/" + HW_IF_POSITION); conf_names.push_back(rear_left_axle_joint_name_ + "/" + HW_IF_POSITION); conf_names.push_back(rear_right_axle_joint_name_ + "/" + HW_IF_POSITION); return {interface_configuration_type::INDIVIDUAL, conf_names}; } InterfaceConfiguration SwerveController::state_interface_configuration() const { return {interface_configuration_type::NONE}; } controller_interface::return_type SwerveController::update( const rclcpp::Time & time, const rclcpp::Duration & /*period*/) { auto logger = node_->get_logger(); if (get_state().id() == State::PRIMARY_STATE_INACTIVE) { if (!is_halted) { halt(); is_halted = true; } return controller_interface::return_type::OK; } const auto current_time = time; std::shared_ptr<Twist> last_command_msg; received_velocity_msg_ptr_.get(last_command_msg); if (last_command_msg == nullptr) { RCLCPP_WARN(logger, "Velocity message received was a nullptr."); return controller_interface::return_type::ERROR; } const auto age_of_last_command = current_time - last_command_msg->header.stamp; // Brake if cmd_vel has timeout, override the stored command if (age_of_last_command > cmd_vel_timeout_) { last_command_msg->twist.linear.x = 0.0; last_command_msg->twist.angular.z = 0.0; } Twist command = *last_command_msg; double & linear_x_cmd = command.twist.linear.x; double & linear_y_cmd = command.twist.linear.y; double & angular_cmd = command.twist.angular.z; double x_offset = wheel_params_.x_offset; double radius = wheel_params_.radius; // Compute Wheel Velocities and Positions const double a = linear_x_cmd - angular_cmd * x_offset / 2; const double b = linear_x_cmd + angular_cmd * x_offset / 2; const double c = linear_y_cmd - angular_cmd * x_offset / 2; const double d = linear_y_cmd + angular_cmd * x_offset / 2; const double front_left_velocity = (sqrt( pow( b , 2) + pow ( d , 2) ) )*(1/(radius*M_PI)); const double front_right_velocity = (sqrt( pow( b , 2) + pow( c , 2 ) ) )*(1/(radius*M_PI)); const double rear_left_velocity = (sqrt( pow( a , 2 ) + pow( d , 2) ) )*(1/(radius*M_PI)); const double rear_right_velocity = (sqrt( pow( a, 2 ) + pow( c , 2) ) )*(1/(radius*M_PI)); const double front_left_position = atan2(b,d); const double front_right_position = atan2(b,c); const double rear_left_position = atan2(a,d); const double rear_right_postition = atan2(a,c); // Set Wheel Velocities front_left_handle_->set_velocity(front_left_velocity); front_right_handle_->set_velocity(front_right_velocity); rear_left_handle_->set_velocity(rear_left_velocity); rear_right_handle_->set_velocity(rear_right_velocity); // Set Wheel Positions front_left_handle_2_->set_position(front_left_position); front_right_handle_2_->set_position(front_right_position); rear_left_handle_2_->set_position(rear_left_position); rear_right_handle_2_->set_position(rear_right_postition); // Time update const auto update_dt = current_time - previous_update_timestamp_; previous_update_timestamp_ = current_time; return controller_interface::return_type::OK; } CallbackReturn SwerveController::on_configure(const rclcpp_lifecycle::State &) { auto logger = node_->get_logger(); // Get Parameters front_left_wheel_joint_name_ = node_->get_parameter("front_left_wheel_joint").as_string(); front_right_wheel_joint_name_ = node_->get_parameter("front_right_wheel_joint").as_string(); rear_left_wheel_joint_name_ = node_->get_parameter("rear_left_wheel_joint").as_string(); rear_right_wheel_joint_name_ = node_->get_parameter("rear_right_wheel_joint").as_string(); front_left_axle_joint_name_ = node_->get_parameter("front_left_axle_joint").as_string(); front_right_axle_joint_name_ = node_->get_parameter("front_right_axle_joint").as_string(); rear_left_axle_joint_name_ = node_->get_parameter("rear_left_axle_joint").as_string(); rear_right_axle_joint_name_ = node_->get_parameter("rear_right_axle_joint").as_string(); if (front_left_wheel_joint_name_.empty()) { RCLCPP_ERROR(logger, "front_left_wheel_joint_name is not set"); return CallbackReturn::ERROR; } if (front_right_wheel_joint_name_.empty()) { RCLCPP_ERROR(logger, "front_right_wheel_joint_name is not set"); return CallbackReturn::ERROR; } if (rear_left_wheel_joint_name_.empty()) { RCLCPP_ERROR(logger, "rear_left_wheel_joint_name is not set"); return CallbackReturn::ERROR; } if (rear_right_wheel_joint_name_.empty()) { RCLCPP_ERROR(logger, "rear_right_wheel_joint_name is not set"); return CallbackReturn::ERROR; } if (front_left_axle_joint_name_.empty()) { RCLCPP_ERROR(logger, "front_left_axle_joint_name is not set"); return CallbackReturn::ERROR; } if (front_right_axle_joint_name_.empty()) { RCLCPP_ERROR(logger, "front_right_axle_joint_name is not set"); return CallbackReturn::ERROR; } if (rear_left_axle_joint_name_.empty()) { RCLCPP_ERROR(logger, "rear_left_axle_joint_name is not set"); return CallbackReturn::ERROR; } if (rear_right_axle_joint_name_.empty()) { RCLCPP_ERROR(logger, "rear_right_axle_joint_name is not set"); return CallbackReturn::ERROR; } wheel_params_.x_offset = node_->get_parameter("chassis_length").as_double(); wheel_params_.y_offset = node_->get_parameter("chassis_width").as_double(); wheel_params_.radius = node_->get_parameter("wheel_radius").as_double(); cmd_vel_timeout_ = std::chrono::milliseconds{ static_cast<int>(node_->get_parameter("cmd_vel_timeout").as_double() * 1000.0)}; use_stamped_vel_ = node_->get_parameter("use_stamped_vel").as_bool(); // Run reset to make sure everything is initialized correctly if (!reset()) { return CallbackReturn::ERROR; } const Twist empty_twist; received_velocity_msg_ptr_.set(std::make_shared<Twist>(empty_twist)); // initialize command subscriber if (use_stamped_vel_) { velocity_command_subscriber_ = node_->create_subscription<Twist>( DEFAULT_COMMAND_TOPIC, rclcpp::SystemDefaultsQoS(), [this](const std::shared_ptr<Twist> msg) -> void { if (!subscriber_is_active_) { RCLCPP_WARN(node_->get_logger(), "Can't accept new commands. subscriber is inactive"); return; } if ((msg->header.stamp.sec == 0) && (msg->header.stamp.nanosec == 0)) { RCLCPP_WARN_ONCE( node_->get_logger(), "Received TwistStamped with zero timestamp, setting it to current " "time, this message will only be shown once"); msg->header.stamp = node_->get_clock()->now(); } received_velocity_msg_ptr_.set(std::move(msg)); }); } else { velocity_command_unstamped_subscriber_ = node_->create_subscription<geometry_msgs::msg::Twist>( DEFAULT_COMMAND_UNSTAMPED_TOPIC, rclcpp::SystemDefaultsQoS(), [this](const std::shared_ptr<geometry_msgs::msg::Twist> msg) -> void { if (!subscriber_is_active_) { RCLCPP_WARN(node_->get_logger(), "Can't accept new commands. subscriber is inactive"); return; } // Write fake header in the stored stamped command std::shared_ptr<Twist> twist_stamped; received_velocity_msg_ptr_.get(twist_stamped); twist_stamped->twist = *msg; twist_stamped->header.stamp = node_->get_clock()->now(); }); } previous_update_timestamp_ = node_->get_clock()->now(); return CallbackReturn::SUCCESS; } CallbackReturn SwerveController::on_activate(const rclcpp_lifecycle::State &) { front_left_handle_ = get_wheel(front_left_wheel_joint_name_); front_right_handle_ = get_wheel(front_right_wheel_joint_name_); rear_left_handle_ = get_wheel(rear_left_wheel_joint_name_); rear_right_handle_ = get_wheel(rear_right_wheel_joint_name_); front_left_handle_2_ = get_axle(front_left_axle_joint_name_); front_right_handle_2_ = get_axle(front_right_axle_joint_name_); rear_left_handle_2_ = get_axle(rear_left_axle_joint_name_); rear_right_handle_2_ = get_axle(rear_right_axle_joint_name_); if (!front_left_handle_ || !front_right_handle_ || !rear_left_handle_ || !rear_right_handle_||!front_left_handle_2_ || !front_right_handle_2_ || !rear_left_handle_2_ || !rear_right_handle_2_) { return CallbackReturn::ERROR; } is_halted = false; subscriber_is_active_ = true; RCLCPP_DEBUG(node_->get_logger(), "Subscriber and publisher are now active."); return CallbackReturn::SUCCESS; } CallbackReturn SwerveController::on_deactivate(const rclcpp_lifecycle::State &) { subscriber_is_active_ = false; return CallbackReturn::SUCCESS; } CallbackReturn SwerveController::on_cleanup(const rclcpp_lifecycle::State &) { if (!reset()) { return CallbackReturn::ERROR; } received_velocity_msg_ptr_.set(std::make_shared<Twist>()); return CallbackReturn::SUCCESS; } CallbackReturn SwerveController::on_error(const rclcpp_lifecycle::State &) { if (!reset()) { return CallbackReturn::ERROR; } return CallbackReturn::SUCCESS; } bool SwerveController::reset() { subscriber_is_active_ = false; velocity_command_subscriber_.reset(); velocity_command_unstamped_subscriber_.reset(); received_velocity_msg_ptr_.set(nullptr); is_halted = false; return true; } CallbackReturn SwerveController::on_shutdown(const rclcpp_lifecycle::State &) { return CallbackReturn::SUCCESS; } void SwerveController::halt() { front_left_handle_->set_velocity(0.0); front_right_handle_->set_velocity(0.0); rear_left_handle_->set_velocity(0.0); rear_right_handle_->set_velocity(0.0); auto logger = node_->get_logger(); RCLCPP_WARN(logger, "-----HALT CALLED : STOPPING ALL MOTORS-----"); } std::shared_ptr<Wheel> SwerveController::get_wheel( const std::string & wheel_name ) { auto logger = node_->get_logger(); if (wheel_name.empty()) { RCLCPP_ERROR(logger, "Wheel joint name not given. Make sure all joints are specified."); return nullptr; } // Get Command Handle for joint const auto command_handle = std::find_if( command_interfaces_.begin(), command_interfaces_.end(), [&wheel_name](const auto & interface) { return interface.get_name() == wheel_name && interface.get_interface_name() == HW_IF_VELOCITY; }); if (command_handle == command_interfaces_.end()) { RCLCPP_ERROR(logger, "Unable to obtain joint command handle for %s", wheel_name.c_str()); return nullptr; } return std::make_shared<Wheel>(std::ref(*command_handle), wheel_name); } std::shared_ptr<Axle> SwerveController::get_axle( const std::string & axle_name ) { auto logger = node_->get_logger(); if (axle_name.empty()) { RCLCPP_ERROR(logger, "Wheel joint name not given. Make sure all joints are specified."); return nullptr; } // Get Command Handle for joint const auto command_handle = std::find_if( command_interfaces_.begin(), command_interfaces_.end(), [&axle_name](const auto & interface) { return interface.get_name() == axle_name && interface.get_interface_name() == HW_IF_POSITION; }); if (command_handle == command_interfaces_.end()) { RCLCPP_ERROR(logger, "Unable to obtain joint command handle for %s", axle_name.c_str()); return nullptr; } return std::make_shared<Axle>(std::ref(*command_handle), axle_name); } } // namespace swerve_controller #include "class_loader/register_macro.hpp" CLASS_LOADER_REGISTER_CLASS( swerve_controller::SwerveController, controller_interface::ControllerInterface)
15,639
C++
34.87156
193
0.684954
RoboEagles4828/2023RobotROS/src/swerve_controller/include/swerve_controller/swerve_controller.hpp
// Copyright 2020 PAL Robotics S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * Author: Bence Magyar, Enrique Fernández, Manuel Meraz */ #ifndef SWERVE_CONTROLLER__SWERVE_CONTROLLER_HPP_ #define SWERVE_CONTROLLER__SWERVE_CONTROLLER_HPP_ #include <chrono> #include <cmath> #include <memory> #include <queue> #include <string> #include <vector> #include "controller_interface/controller_interface.hpp" #include "swerve_controller/visibility_control.h" #include "geometry_msgs/msg/twist.hpp" #include "geometry_msgs/msg/twist_stamped.hpp" #include "hardware_interface/handle.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_lifecycle/state.hpp" #include "realtime_tools/realtime_box.h" #include "realtime_tools/realtime_buffer.h" #include "realtime_tools/realtime_publisher.h" #include <hardware_interface/loaned_command_interface.hpp> namespace swerve_controller { using CallbackReturn = rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn; class Wheel { public: Wheel(std::reference_wrapper<hardware_interface::LoanedCommandInterface> velocity, std::string name); void set_velocity(double velocity); private: std::reference_wrapper<hardware_interface::LoanedCommandInterface> velocity_; std::string name; }; class Axle { public: Axle(std::reference_wrapper<hardware_interface::LoanedCommandInterface> position, std::string name); void set_position(double position); private: std::reference_wrapper<hardware_interface::LoanedCommandInterface> position_; std::string name; }; class SwerveController : public controller_interface::ControllerInterface { using Twist = geometry_msgs::msg::TwistStamped; public: SWERVE_CONTROLLER_PUBLIC SwerveController(); SWERVE_CONTROLLER_PUBLIC controller_interface::InterfaceConfiguration command_interface_configuration() const override; SWERVE_CONTROLLER_PUBLIC controller_interface::InterfaceConfiguration state_interface_configuration() const override; SWERVE_CONTROLLER_PUBLIC controller_interface::return_type update( const rclcpp::Time & time, const rclcpp::Duration & period) override; SWERVE_CONTROLLER_PUBLIC CallbackReturn on_init() override; SWERVE_CONTROLLER_PUBLIC CallbackReturn on_configure(const rclcpp_lifecycle::State & previous_state) override; SWERVE_CONTROLLER_PUBLIC CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_CONTROLLER_PUBLIC CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_CONTROLLER_PUBLIC CallbackReturn on_cleanup(const rclcpp_lifecycle::State & previous_state) override; SWERVE_CONTROLLER_PUBLIC CallbackReturn on_error(const rclcpp_lifecycle::State & previous_state) override; SWERVE_CONTROLLER_PUBLIC CallbackReturn on_shutdown(const rclcpp_lifecycle::State & previous_state) override; protected: std::shared_ptr<Wheel> get_wheel(const std::string & wheel_name); std::shared_ptr<Axle> get_axle(const std::string & axle_name); std::shared_ptr<Wheel> front_left_handle_; std::shared_ptr<Wheel> front_right_handle_; std::shared_ptr<Wheel> rear_left_handle_; std::shared_ptr<Wheel> rear_right_handle_; std::shared_ptr<Axle> front_left_handle_2_; std::shared_ptr<Axle> front_right_handle_2_; std::shared_ptr<Axle> rear_left_handle_2_; std::shared_ptr<Axle> rear_right_handle_2_; std::string front_left_wheel_joint_name_; std::string front_right_wheel_joint_name_; std::string rear_left_wheel_joint_name_; std::string rear_right_wheel_joint_name_; std::string front_left_axle_joint_name_; std::string front_right_axle_joint_name_; std::string rear_left_axle_joint_name_; std::string rear_right_axle_joint_name_; struct WheelParams { double x_offset = 0.0; // Chassis Center to Axle Center double y_offset = 0.0; // Axle Center to Wheel Center double radius = 0.0; // Assumed to be the same for all wheels } wheel_params_; // Timeout to consider cmd_vel commands old std::chrono::milliseconds cmd_vel_timeout_{500}; rclcpp::Time previous_update_timestamp_{0}; // Topic Subscription bool subscriber_is_active_ = false; rclcpp::Subscription<Twist>::SharedPtr velocity_command_subscriber_ = nullptr; rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr velocity_command_unstamped_subscriber_ = nullptr; realtime_tools::RealtimeBox<std::shared_ptr<Twist>> received_velocity_msg_ptr_{nullptr}; bool is_halted = false; bool use_stamped_vel_ = true; bool reset(); void halt(); }; } // namespace swerve_controllerS #endif // Swerve_CONTROLLER__SWERVE_CONTROLLER_HPP_
5,166
C++
32.993421
105
0.753388
RoboEagles4828/2023RobotROS/src/swerve_controller/include/swerve_controller/visibility_control.h
// Copyright 2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* This header must be included by all rclcpp headers which declare symbols * which are defined in the rclcpp library. When not building the rclcpp * library, i.e. when using the headers in other package's code, the contents * of this header change the visibility of certain symbols which the rclcpp * library cannot have, but the consuming code must have inorder to link. */ #ifndef SWERVE_CONTROLLER__VISIBILITY_CONTROL_H_ #define SWERVE_CONTROLLER__VISIBILITY_CONTROL_H_ // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define SWERVE_CONTROLLER_EXPORT __attribute__((dllexport)) #define SWERVE_CONTROLLER_IMPORT __attribute__((dllimport)) #else #define SWERVE_CONTROLLER_EXPORT __declspec(dllexport) #define SWERVE_CONTROLLER_IMPORT __declspec(dllimport) #endif #ifdef SWERVE_CONTROLLER_BUILDING_DLL #define SWERVE_CONTROLLER_PUBLIC SWERVE_CONTROLLER_EXPORT #else #define SWERVE_CONTROLLER_PUBLIC SWERVE_CONTROLLER_IMPORT #endif #define SWERVE_CONTROLLER_PUBLIC_TYPE SWERVE_CONTROLLER_PUBLIC #define SWERVE_CONTROLLER_LOCAL #else #define SWERVE_CONTROLLER_EXPORT __attribute__((visibility("default"))) #define SWERVE_CONTROLLER_IMPORT #if __GNUC__ >= 4 #define SWERVE_CONTROLLER_PUBLIC __attribute__((visibility("default"))) #define SWERVE_CONTROLLER_LOCAL __attribute__((visibility("hidden"))) #else #define SWERVE_CONTROLLER_PUBLIC #define SWERVE_CONTROLLER_LOCAL #endif #define SWERVE_CONTROLLER_PUBLIC_TYPE #endif #endif // SWERVE_CONTROLLER__VISIBILITY_CONTROL_H_
2,229
C
38.122806
79
0.767609
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/config/extension.toml
[core] reloadable = true order = 0 [package] version = "1.0.0" category = "Simulation" title = "Swerve Bot" description = "Extension for running swerve bot in Isaac Sim" authors = ["Gage Miller, Nitin C"] repository = "" keywords = ["isaac", "samples", "manipulation"] changelog = "docs/CHANGELOG.md" readme = "docs/README.md" preview_image = "data/preview.png" icon = "data/icon.png" writeTarget.kit = true [dependencies] "omni.kit.uiapp" = {} "omni.physx" = {} "omni.physx.vehicle" = {} "omni.isaac.dynamic_control" = {} "omni.isaac.motion_planning" = {} "omni.isaac.synthetic_utils" = {} "omni.isaac.ui" = {} "omni.isaac.core" = {} "omni.isaac.franka" = {} "omni.isaac.dofbot" = {} "omni.isaac.universal_robots" = {} "omni.isaac.motion_generation" = {} "omni.isaac.demos" = {} "omni.graph.action" = {} "omni.graph.nodes" = {} "omni.graph.core" = {} "omni.isaac.quadruped" = {} "omni.isaac.wheeled_robots" = {} "omni.isaac.examples" = {} [[python.module]] name = "omni.isaac.swerve_bot.import_bot" [[test]] timeout = 960
1,030
TOML
21.413043
61
0.659223
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/omni/isaac/swerve_bot/base_sample/base_sample.py
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.core import World from omni.isaac.core.scenes.scene import Scene from omni.isaac.core.utils.stage import create_new_stage_async, update_stage_async import gc from abc import abstractmethod class BaseSample(object): def __init__(self) -> None: self._world = None self._current_tasks = None self._world_settings = {"physics_dt": 1.0 / 60.0, "stage_units_in_meters": 1.0, "rendering_dt": 1.0 / 60.0} # self._logging_info = "" return def get_world(self): return self._world def set_world_settings(self, physics_dt=None, stage_units_in_meters=None, rendering_dt=None): if physics_dt is not None: self._world_settings["physics_dt"] = physics_dt if stage_units_in_meters is not None: self._world_settings["stage_units_in_meters"] = stage_units_in_meters if rendering_dt is not None: self._world_settings["rendering_dt"] = rendering_dt return async def load_world_async(self): """Function called when clicking load buttton """ if World.instance() is None: await create_new_stage_async() self._world = World(**self._world_settings) await self._world.initialize_simulation_context_async() self.setup_scene() else: self._world = World.instance() self._current_tasks = self._world.get_current_tasks() await self._world.reset_async() await self._world.pause_async() await self.setup_post_load() if len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return async def reset_async(self): """Function called when clicking reset buttton """ if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.remove_physics_callback("tasks_step") await self._world.play_async() await update_stage_async() await self.setup_pre_reset() await self._world.reset_async() await self._world.pause_async() await self.setup_post_reset() if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return @abstractmethod def setup_scene(self, scene: Scene) -> None: """used to setup anything in the world, adding tasks happen here for instance. Args: scene (Scene): [description] """ return @abstractmethod async def setup_post_load(self): """called after first reset of the world when pressing load, intializing provate variables happen here. """ return @abstractmethod async def setup_pre_reset(self): """ called in reset button before resetting the world to remove a physics callback for instance or a controller reset """ return @abstractmethod async def setup_post_reset(self): """ called in reset button after resetting the world which includes one step with rendering """ return @abstractmethod async def setup_post_clear(self): """called after clicking clear button or after creating a new stage and clearing the instance of the world with its callbacks """ return # def log_info(self, info): # self._logging_info += str(info) + "\n" # return def _world_cleanup(self): self._world.stop() self._world.clear_all_callbacks() self._current_tasks = None self.world_cleanup() return def world_cleanup(self): """Function called when extension shutdowns and starts again, (hot reloading feature) """ return async def clear_async(self): """Function called when clicking clear buttton """ await create_new_stage_async() if self._world is not None: self._world_cleanup() self._world.clear_instance() self._world = None gc.collect() await self.setup_post_clear() return
4,657
Python
34.287879
115
0.624222
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/omni/isaac/swerve_bot/base_sample/base_sample_extension.py
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from abc import abstractmethod import omni.ext import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription import weakref from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder, scrolling_frame_builder import asyncio from omni.isaac.swerve_bot.base_sample import BaseSample from omni.isaac.core import World class BaseSampleExtension(omni.ext.IExt): def on_startup(self, ext_id: str): self._menu_items = None self._buttons = None self._ext_id = ext_id self._sample = None self._extra_frames = [] return def start_extension( self, menu_name: str, submenu_name: str, name: str, title: str, doc_link: str, overview: str, file_path: str, sample=None, number_of_extra_frames=1, window_width=350, ): if sample is None: self._sample = BaseSample() else: self._sample = sample menu_items = [MenuItemDescription(name=name, onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())] if menu_name == "" or menu_name is None: self._menu_items = menu_items elif submenu_name == "" or submenu_name is None: self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)] else: self._menu_items = [ MenuItemDescription( name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)] ) ] add_menu_items(self._menu_items, "Isaac Examples") self._buttons = dict() self._build_ui( name=name, title=title, doc_link=doc_link, overview=overview, file_path=file_path, number_of_extra_frames=number_of_extra_frames, window_width=window_width, ) if self.get_world() is not None: self._on_load_world() return @property def sample(self): return self._sample def get_frame(self, index): if index >= len(self._extra_frames): raise Exception("there were {} extra frames created only".format(len(self._extra_frames))) return self._extra_frames[index] def get_world(self): return World.instance() def get_buttons(self): return self._buttons def _build_ui(self, name, title, doc_link, overview, file_path, number_of_extra_frames, window_width): self._window = omni.ui.Window( name, width=window_width, height=0, visible=True, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): setup_ui_headers(self._ext_id, file_path, title, doc_link, overview) self._controls_frame = ui.CollapsableFrame( title="World Controls", width=ui.Fraction(1), height=0, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with ui.VStack(style=get_style(), spacing=5, height=0): for i in range(number_of_extra_frames): self._extra_frames.append( ui.CollapsableFrame( title="", width=ui.Fraction(0.33), height=0, visible=False, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) ) with self._controls_frame: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Load World", "type": "button", "text": "Load", "tooltip": "Load World and Task", "on_clicked_fn": self._on_load_world, } self._buttons["Load World"] = btn_builder(**dict) self._buttons["Load World"].enabled = True dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = False return def _set_button_tooltip(self, button_name, tool_tip): self._buttons[button_name].set_tooltip(tool_tip) return def _on_load_world(self): async def _on_load_world_async(): await self._sample.load_world_async() await omni.kit.app.get_app().next_update_async() self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event) self._enable_all_buttons(True) self._buttons["Load World"].enabled = False self.post_load_button_event() self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event) asyncio.ensure_future(_on_load_world_async()) return def _on_reset(self): async def _on_reset_async(): await self._sample.reset_async() await omni.kit.app.get_app().next_update_async() self.post_reset_button_event() asyncio.ensure_future(_on_reset_async()) return @abstractmethod def post_reset_button_event(self): return @abstractmethod def post_load_button_event(self): return @abstractmethod def post_clear_button_event(self): return def _enable_all_buttons(self, flag): for btn_name, btn in self._buttons.items(): if isinstance(btn, omni.ui._ui.Button): btn.enabled = flag return def _menu_callback(self): self._window.visible = not self._window.visible return def _on_window(self, status): # if status: return def on_shutdown(self): self._extra_frames = [] if self._sample._world is not None: self._sample._world_cleanup() if self._menu_items is not None: self._sample_window_cleanup() if self._buttons is not None: self._buttons["Load World"].enabled = True self._enable_all_buttons(False) self.shutdown_cleanup() return def shutdown_cleanup(self): return def _sample_window_cleanup(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None self._menu_items = None self._buttons = None return def on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.CLOSED): if World.instance() is not None: self.sample._world_cleanup() self.sample._world.clear_instance() if hasattr(self, "_buttons"): if self._buttons is not None: self._enable_all_buttons(False) self._buttons["Load World"].enabled = True return def _reset_on_stop_event(self, e): if e.type == int(omni.timeline.TimelineEventType.STOP): self._buttons["Load World"].enabled = False self._buttons["Reset"].enabled = True self.post_clear_button_event() return
8,606
Python
35.782051
114
0.541134
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/omni/isaac/swerve_bot/base_sample/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.swerve_bot.base_sample.base_sample import BaseSample from omni.isaac.swerve_bot.base_sample.base_sample_extension import BaseSampleExtension
586
Python
47.916663
87
0.819113
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/omni/isaac/swerve_bot/import_bot/__init__.py
from omni.isaac.swerve_bot.import_bot.import_bot import ImportBot from omni.isaac.swerve_bot.import_bot.import_bot_extension import ImportBotExtension
152
Python
37.249991
84
0.842105
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/omni/isaac/swerve_bot/import_bot/import_bot_extension.py
# Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import os from omni.isaac.swerve_bot.base_sample import BaseSampleExtension from omni.isaac.swerve_bot.import_bot.import_bot import ImportBot class ImportBotExtension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="Swerve Bot", submenu_name="", name="Import URDF", title="Load the URDF for Swerve Bot", doc_link="", overview="This loads the Swerve bot into Isaac Sim.", file_path=os.path.abspath(__file__), sample=ImportBot(), ) return
1,074
Python
37.392856
76
0.687151
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/omni/isaac/swerve_bot/import_bot/import_bot.py
import omni.graph.core as og import omni.usd from omni.isaac.swerve_bot.base_sample import BaseSample from omni.isaac.urdf import _urdf from omni.isaac.core.robots import Robot from omni.isaac.core.utils import prims from omni.isaac.core_nodes.scripts.utils import set_target_prims from omni.kit.viewport_legacy import get_default_viewport_window from pxr import UsdPhysics import omni.kit.commands import os import numpy as np import math import carb def set_drive_params(drive, stiffness, damping, max_force): drive.GetStiffnessAttr().Set(stiffness) drive.GetDampingAttr().Set(damping) if(max_force != 0.0): drive.GetMaxForceAttr().Set(max_force) return class ImportBot(BaseSample): def __init__(self) -> None: super().__init__() return def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() self.setup_perspective_cam() self.setup_world_action_graph() return async def setup_post_load(self): self._world = self.get_world() self.robot_name = "Swerve" self.extension_path = os.path.abspath(__file__) self.project_root_path = os.path.abspath(os.path.join(self.extension_path, "../../../../../../..")) self.path_to_urdf = os.path.join(self.project_root_path, "src/swerve_description/swerve.urdf") carb.log_info(self.path_to_urdf) self._robot_prim_path = self.import_robot(self.path_to_urdf) if self._robot_prim_path is None: print("Error: failed to import robot") return self._robot_prim = self._world.scene.add( Robot(prim_path=self._robot_prim_path, name=self.robot_name, position=np.array([0.0, 0.0, 0.3])) ) self.configure_robot(self._robot_prim_path) return def import_robot(self, urdf_path): import_config = _urdf.ImportConfig() import_config.merge_fixed_joints = False import_config.fix_base = False import_config.make_default_prim = True import_config.self_collision = False import_config.create_physics_scene = False import_config.import_inertia_tensor = True import_config.default_drive_strength = 1047.19751 import_config.default_position_drive_damping = 52.35988 import_config.default_drive_type = _urdf.UrdfJointTargetType.JOINT_DRIVE_VELOCITY import_config.distance_scale = 1.0 import_config.density = 0.0 result, prim_path = omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) if result: return prim_path return None def configure_robot(self, robot_prim_path): w_sides = ['left', 'right'] l_sides = ['front', 'back'] stage = self._world.stage chassis_name = "swerve_chassis_link" front_left_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/front_left_axle_joint"), "angular") front_right_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/front_right_axle_joint"), "angular") back_left_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/back_left_axle_joint"), "angular") back_right_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/back_right_axle_joint"), "angular") front_left_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/front_left_axle_link/front_left_wheel_joint"), "angular") front_right_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/front_right_axle_link/front_right_wheel_joint"), "angular") back_left_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/back_left_axle_link/back_left_wheel_joint"), "angular") back_right_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/back_right_axle_link/back_right_wheel_joint"), "angular") set_drive_params(front_left_axle, 10000000.0, 100000.0, 98.0) set_drive_params(front_right_axle, 10000000.0, 100000.0, 98.0) set_drive_params(back_left_axle, 10000000.0, 100000.0, 98.0) set_drive_params(back_right_axle, 10000000.0, 100000.0, 98.0) set_drive_params(front_left_wheel, 0, math.radians(1e5), 98.0) set_drive_params(front_right_wheel, 0, math.radians(1e5), 98.0) set_drive_params(back_left_wheel, 0, math.radians(1e5), 98.0) set_drive_params(back_right_wheel, 0, math.radians(1e5), 98.0) #self.create_lidar(robot_prim_path) #self.create_depth_camera() self.setup_robot_action_graph(robot_prim_path) return def create_lidar(self, robot_prim_path): lidar_parent = "{}/lidar_link".format(robot_prim_path) lidar_path = "/lidar" self.lidar_prim_path = lidar_parent + lidar_path result, prim = omni.kit.commands.execute( "RangeSensorCreateLidar", path=lidar_path, parent=lidar_parent, min_range=0.4, max_range=25.0, draw_points=False, draw_lines=True, horizontal_fov=360.0, vertical_fov=30.0, horizontal_resolution=0.4, vertical_resolution=4.0, rotation_rate=0.0, high_lod=False, yaw_offset=0.0, enable_semantics=False ) return def create_depth_camera(self): self.depth_left_camera_path = f"{self._robot_prim_path}/zed_left_camera_frame/left_cam" self.depth_right_camera_path = f"{self._robot_prim_path}/zed_right_camera_frame/right_cam" self.left_camera = prims.create_prim( prim_path=self.depth_left_camera_path, prim_type="Camera", attributes={ "focusDistance": 1, "focalLength": 24, "horizontalAperture": 20.955, "verticalAperture": 15.2908, "clippingRange": (0.1, 1000000), "clippingPlanes": np.array([1.0, 0.0, 1.0, 1.0]), }, ) self.right_camera = prims.create_prim( prim_path=self.depth_right_camera_path, prim_type="Camera", attributes={ "focusDistance": 1, "focalLength": 24, "horizontalAperture": 20.955, "verticalAperture": 15.2908, "clippingRange": (0.1, 1000000), "clippingPlanes": np.array([1.0, 0.0, 1.0, 1.0]), }, ) return def setup_world_action_graph(self): og.Controller.edit( {"graph_path": "/globalclock", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("Context", "omni.isaac.ros2_bridge.ROS2Context"), ("PublishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"), ], og.Controller.Keys.CONNECT: [ ("OnPlaybackTick.outputs:tick", "PublishClock.inputs:execIn"), ("Context.outputs:context", "PublishClock.inputs:context"), ("ReadSimTime.outputs:simulationTime", "PublishClock.inputs:timeStamp"), ], } ) return def setup_perspective_cam(self): # Get the Viewport and the Default Camera viewport_window = get_default_viewport_window() camera = self.get_world().stage.GetPrimAtPath(viewport_window.get_active_camera()) # Get Default Cam Values camAttributes = {} camOrientation = None camTranslation = None for att in camera.GetAttributes(): name = att.GetName() if not (name.startswith('omni') or name.startswith('xform')): camAttributes[att.GetName()] = att.Get() elif name == 'xformOp:orient': convertedQuat = [att.Get().GetReal()] + list(att.Get().GetImaginary()) camOrientation = np.array(convertedQuat) elif name == 'xformOp:translate': camTranslation = np.array(list(att.Get())) # Modify what we want camAttributes["clippingRange"] = (0.1, 1000000) camAttributes["clippingPlanes"] = np.array([1.0, 0.0, 1.0, 1.0]) # Create a new camera with desired values cam_path = "/World/PerspectiveCam" prims.create_prim( prim_path=cam_path, prim_type="Camera", translation=camTranslation, orientation=camOrientation, attributes=camAttributes, ) # Use the camera for our viewport viewport_window.set_active_camera(cam_path) return def setup_robot_action_graph(self, robot_prim_path): robot_controller_path = f"{robot_prim_path}/ros_interface_controller" og.Controller.edit( {"graph_path": robot_controller_path, "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("Context", "omni.isaac.ros2_bridge.ROS2Context"), ("PublishJointState", "omni.isaac.ros2_bridge.ROS2PublishJointState"), ("SubscribeJointState", "omni.isaac.ros2_bridge.ROS2SubscribeJointState"), ("articulation_controller", "omni.isaac.core_nodes.IsaacArticulationController"), ], og.Controller.Keys.SET_VALUES: [ ("PublishJointState.inputs:topicName", "isaac_joint_states"), ("SubscribeJointState.inputs:topicName", "isaac_joint_commands"), ("articulation_controller.inputs:usePath", False), ], og.Controller.Keys.CONNECT: [ ("OnPlaybackTick.outputs:tick", "PublishJointState.inputs:execIn"), ("OnPlaybackTick.outputs:tick", "SubscribeJointState.inputs:execIn"), ("OnPlaybackTick.outputs:tick", "articulation_controller.inputs:execIn"), ("ReadSimTime.outputs:simulationTime", "PublishJointState.inputs:timeStamp"), ("Context.outputs:context", "PublishJointState.inputs:context"), ("Context.outputs:context", "SubscribeJointState.inputs:context"), ("SubscribeJointState.outputs:jointNames", "articulation_controller.inputs:jointNames"), ("SubscribeJointState.outputs:velocityCommand", "articulation_controller.inputs:velocityCommand"), ("SubscribeJointState.outputs:positionCommand", "articulation_controller.inputs:positionCommand"), ], } ) set_target_prims(primPath=f"{robot_controller_path}/articulation_controller", targetPrimPaths=[robot_prim_path]) set_target_prims(primPath=f"{robot_controller_path}/PublishJointState", targetPrimPaths=[robot_prim_path]) return async def setup_pre_reset(self): return async def setup_post_reset(self): return async def setup_post_clear(self): return def world_cleanup(self): self._world.scene.remove_object(self.robot_name) return
11,794
Python
43.509434
151
0.602255
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/docs/CHANGELOG.md
********** CHANGELOG ********** [0.1.0] - 2022-6-26 [0.1.1] - 2022-10-15 ======================== Added ------- - Initial version of Swerve Bot Extension - Enhanced physX
175
Markdown
10.733333
41
0.468571
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/docs/README.md
# Usage To enable this extension, go to the Extension Manager menu and enable omni.isaac.swerve_bot extension.
113
Markdown
21.799996
102
0.787611
RoboEagles4828/offseason2023/docker-compose.yml
version: "3.6" services: main_control: # image: "ghcr.io/roboeagles4828/developer-environment:6" image: "ghcr.io/roboeagles4828/jetson:3" network_mode: "host" environment: - ROS_DOMAIN_ID=0 - FASTRTPS_DEFAULT_PROFILES_FILE=/usr/local/share/middleware_profiles/rtps_udp_profile.xml deploy: restart_policy: condition: unless-stopped delay: 2s max_attempts: 3 window: 120s entrypoint: ["/bin/bash", "-c", "/opt/workspace/docker/jetson/entrypoint.sh"] working_dir: /opt/workspace user: admin volumes: - ${HOME}/edna2023:/opt/workspace zed_cam: image: ghcr.io/roboeagles4828/jetson-zed:1 network_mode: "host" privileged: true runtime: nvidia environment: - ROS_DOMAIN_ID=0 - RMW_IMPLEMENTATION=rmw_fastrtps_cpp - FASTRTPS_DEFAULT_PROFILES_FILE=/usr/local/share/middleware_profiles/rtps_udp_profile.xml - ROS_NAMESPACE=real volumes: - /usr/bin/tegrastats:/usr/bin/tegrastats - /tmp/argus_socket:/tmp/argus_socket - /usr/local/cuda-11.4/targets/aarch64-linux/lib/libcusolver.so.11:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libcusolver.so.11 - /usr/local/cuda-11.4/targets/aarch64-linux/lib/libcusparse.so.11:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libcusparse.so.11 - /usr/local/cuda-11.4/targets/aarch64-linux/lib/libcurand.so.10:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libcurand.so.10 - /usr/local/cuda-11.4/targets/aarch64-linux/lib/libnvToolsExt.so:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libnvToolsExt.so - /usr/local/cuda-11.4/targets/aarch64-linux/lib/libcupti.so.11.4:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libcupti.so.11.4 - /usr/local/cuda-11.4/targets/aarch64-linux/include:/usr/local/cuda-11.4/targets/aarch64-linux/include - /usr/lib/aarch64-linux-gnu/tegra:/usr/lib/aarch64-linux-gnu/tegra - /usr/src/jetson_multimedia_api:/usr/src/jetson_multimedia_api - /opt/nvidia/nsight-systems-cli:/opt/nvidia/nsight-systems-cli - /opt/nvidia/vpi2:/opt/nvidia/vpi2 - /usr/share/vpi2:/usr/share/vpi2 - /run/jtop.sock:/run/jtop.sock:ro - /dev/*:/dev/* - ${HOME}/edna2023/scripts/config/SN39192289.conf:/usr/local/zed/settings/SN39192289.conf - ${HOME}/edna2023/src/edna_bringup/launch/zed2i.launch.py:/root/ros2_ws/src/zed-ros2-wrapper/zed_wrapper/launch/zed2i.launch.py depends_on: - main_control deploy: resources: reservations: devices: - driver: nvidia count: all capabilities: [gpu] command: ["ros2", "launch", "zed_wrapper", "zed2i.launch.py"]
2,714
YAML
45.016948
137
0.673545
RoboEagles4828/offseason2023/ZED.md
# Setting up the ZED Camera with ROS2 Galactic ## Chapter One: Downloading and Installing the Packages This assumes that you already have a working install of [ROS2 Galactic](https://docs.ros.org/en/galactic/index.html) and the [ZED SDK](https://www.stereolabs.com/developers/release/). You're going to need to go to the [ZED ROS2 Wrapper](https://github.com/stereolabs/zed-ros2-wrapper) and follow the installation insructions to add it here. However, before running `rosdep install`, you'll need to go into the src/ folder and move all of the packages inside of the zed-ros2-wrapper folder into the root src folder. **WARNING: INCREDIBLY HACKY FIX AHEAD** *If you're having problems with anything, this is probably the cause of it* If you try to `colcon build` at this point, you're going to run into some strange error having to do with install/zed_components/lib/libzed_camera_component.so regarding tf2::doTransform. Now, if you're willing to look into why this is erroring, please feel free to fix the code, but if you want a fast and simple solution, then just do this. Go into src/zed_components/src/zed_camera/src/zed_camera_component.cpp, and scroll down to line 6333. Comment that line out, save the file, and continue on with the rest of this. Once you've done that, you're also going to need the [ZED ROS2 Examples](https://github.com/stereolabs/zed-ros2-examples) for the 3D bounding boxes to display in RViz2. Go ahead and download their repository, making sure to take the packages out of the folder and put it in src/ directly. With all of that done, you can finally run `colcon build`. ## Chapter Two: Running RViz2 Now that everything is set up and you ran into no errors whatsoever, you can run it! Running `ros2 launch zed_wrapper zed2i.launch.py` (make sure to source ros2 and the local install at install/local_setup.bash first) will start a ROS topic publishing out the camera information! You can also run `ros2 launch zed_display_rviz2 display_zed2i.launch.py` to open RViz2 with the default ZED configuration (useful for the next step). ## Chapter Three: Ordinary Object Detection If you just want to enable object detection temporarily, then you can run `ros2 service call /zed2i/zed_node/enable_obj_det std_stvs/srv/SetBool data:\ true`. This command will enable object detection for the currently running ROS node. However, if you want object detection to be on by default, then go into src/zed_wrapper/config/common.yaml, and change line 107 to be true. (You can also mess with the other object detection settings here). Now if you open RViz2 with the default ZED settings, you can see the bounding boxes going around the real world things! (You can also add the point cloud from the topic to see it even better). ## Chapter Four: Custom Object Detection I'm working on it!
2,820
Markdown
77.361109
514
0.778723
RoboEagles4828/offseason2023/README.md
# edna2023 2023 FRC Robot ### Requirements ------- - RTX Enabled GPU # Workstation Setup steps ### 1. Install Graphics Drivers **Install Nvidia Drivers** \ `sudo apt-get install nvidia-driver-525` then restart your machine ### 2. Local Setup - **Install Docker and Nvidia Docker** \ `./scripts/local-setup.sh` then restart your machine - **Install Remote Development VS Code Extension** \ Go to extensions and search for Remote Development and click install - **Reopen in Devcontainer** \ Hit F1 and run the command Reopen in Container and wait for the post install to finsih. ### 3. Isaac Container Setup - **Create Shaders** \ This uses a lot of cpu resource and can take up to 20min \ `isaac-setup` - **Launch Isaac** \ `isaac` ### 4. Build ROS2 Packages - **Build the packages** \ Shortcut: `ctrl + shift + b` \ or \ Terminal: `colcon build --symlink-install` - **Done with Building ROS2 Packagess** ### 5. (Optional) Omniverse Setup - **Download Omniverse Launcher** \ https://www.nvidia.com/en-us/omniverse/download/ - **Run Omniverse** \ `chmod +x omniverse-launcher-linux.AppImage` \ `./omniverse-launcher-linux.AppImage` - **Install Cache and Nucleus Server** \ Wait until both are downloaded and installed. - **DONE with Omniverse Setup** # Running Edna ### Inside of Isaac 1. Connect an xbox controller 2. Open Isaac 3. Open Isaac and hit load on the *Import URDF* extension window 4. Press Play on the left hand side 5. Run `launch isaac` inside devcontainer ### In real life (TODO)
1,516
Markdown
21.984848
87
0.71438
RoboEagles4828/offseason2023/src/edna_tests/setup.py
from setuptools import setup package_name = 'edna_tests' setup( name=package_name, version='0.0.1', packages=[package_name], data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), ('share/' + package_name, ['package.xml']), ], install_requires=['setuptools'], zip_safe=True, maintainer='roboeagles', maintainer_email='[email protected]', description='Test robot functions', license='MIT', tests_require=['pytest'], entry_points={ 'console_scripts': [ 'joint-arm = edna_tests.publish_joint_arm_command:main', 'joint-drive = edna_tests.publish_joint_drive_command:main', 'publish-twist = edna_tests.publish_twist_command:main', 'run-tests = edna_tests.run_tests_command:main', 'arm-tests = edna_tests.arm_tests:main' ], }, )
926
Python
29.899999
72
0.602592
RoboEagles4828/offseason2023/src/edna_tests/edna_tests/publish_joint_drive_command.py
import rclpy from rclpy.node import Node import math from sensor_msgs.msg import JointState class PublishJointCmd(Node): def __init__(self): super().__init__('publish_drive_joint_commands') self.publisher_ = self.create_publisher(JointState, '/real/real_joint_commands', 10) timer_period = 0.5 # seconds self.timer = self.create_timer(timer_period, self.timer_callback) self.i = 0 def timer_callback(self): cmds = JointState() cmds.name = [ 'front_left_wheel_joint', 'front_right_wheel_joint', 'rear_left_wheel_joint', 'rear_right_wheel_joint', 'front_left_axle_joint', 'front_right_axle_joint', 'rear_left_axle_joint', 'rear_right_axle_joint' ] rad = math.pi cmds.velocity = [ 0.0, 0.0, 0.0, 0.0, 0.0, #ignore 0.0, #ignore 0.0, #ignore 0.0, #ignore ] cmds.position = [ 0.0, #ignore 0.0, #ignore 0.0, #ignore 0.0, #ignore rad, 0.0, 0.0, 0.0 ] # position_cmds.position = [] self.publisher_.publish(cmds) self.get_logger().info('Publishing: ...') self.i += 1 def main(args=None): rclpy.init(args=args) node = PublishJointCmd() rclpy.spin(node) # Destroy the node explicitly # (optional - otherwise it will be done automatically # when the garbage collector destroys the node object) node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
1,746
Python
23.263889
92
0.507446
RoboEagles4828/offseason2023/src/edna_tests/edna_tests/publish_twist_command.py
import rclpy from rclpy.node import Node from geometry_msgs.msg import Twist, Vector3 class PublishTwistCmd(Node): def __init__(self): super().__init__('publish_twist_commands') self.publisher_ = self.create_publisher(Twist, 'swerve_controller/cmd_vel_unstamped', 10) timer_period = 0.1 # seconds self.timer = self.create_timer(timer_period, self.timer_callback) self.i = 0 def timer_callback(self): twist = Twist() twist.linear.x = 2.0 twist.linear.y = 0.0 twist.angular.z = 0.0 self.publisher_.publish(twist) self.get_logger().info('Publishing: ...') self.i += 1 def main(args=None): rclpy.init(args=args) node = PublishTwistCmd() rclpy.spin(node) node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
868
Python
22.486486
97
0.599078
RoboEagles4828/offseason2023/src/edna_tests/edna_tests/arm_tests.py
import rclpy import time from .joint_test import TesterNode # ROS Topics SUBSCRIBE_TOPIC_NAME = '/real/real_joint_states' PUBLISH_TOPIC_NAME = '/real/real_arm_commands' PUBLISH_INTERVAL = .5 # seconds # Tolerances PASS_TOLERANCE = 0.5 WARN_TOLERANCE = 1 TESTS = [ # Here's where you define your tests, in the same style as this one. # {"positions": [0.0]*6, "time": 3.0}, # Toggle pistons one at a time (to true) {"positions": [0.0]*4 + [0.0] + [0.0], "time": 10.0}, # {"positions": [0.0]*4 + [0.5] + [0.0], "time": 10.0}, # {"positions": [0.0]*4 + [1.0] + [0.0], "time": 10.0}, # {"positions": [0.0]*6, "time": 10.0}, ] JOINT_NAMES = [ # Pneumatics 'arm_roller_bar_joint', 'top_slider_joint', 'top_gripper_left_arm_joint', # Wheels 'elevator_center_joint', 'bottom_intake_joint', ] def main(): rclpy.init() testerNode = TesterNode( tests=TESTS, joint_names=JOINT_NAMES, joint_range=[8, 14], pub_topic_name=PUBLISH_TOPIC_NAME, sub_topic_name=SUBSCRIBE_TOPIC_NAME, pub_interval=PUBLISH_INTERVAL, pass_tolerance=PASS_TOLERANCE, warn_tolerance=WARN_TOLERANCE) rclpy.spin(testerNode) if __name__ == '__main__': main()
1,267
Python
22.481481
72
0.589582
RoboEagles4828/offseason2023/src/edna_tests/edna_tests/run_tests_command.py
import rclpy from rclpy.node import Node import math import time from rclpy.action import ActionClient from action_tutorials_interfaces.action import Fibonacci from sensor_msgs.msg import JointState import logging vel_cmds = JointState() rad = math.pi vel_cmds.velocity = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] vel_cmds.position = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] vel_cmds.name = [ 'front_left_wheel_joint', 'front_left_axle_joint', 'front_right_wheel_joint', 'front_right_axle_joint', 'rear_left_wheel_joint', 'rear_left_axle_joint', 'rear_right_wheel_joint', 'rear_right_axle_joint'] test_return = JointState() class RunTests(Node): def __init__(self): super().__init__('run_tests') self.publisher_ = self.create_publisher( JointState, 'real_joint_commands', 10 ) timer_period = 0.1 self.timer = self.create_timer(timer_period, self.timer_callback) self.i = 0 self.subscription = self.create_subscription( JointState, 'real_joint_states', self.listener_callback, 10 ) self.subscription self.get_logger().info('Testing: ...') def timer_callback(self): self.publisher_.publish(vel_cmds) time.sleep(0.1) self.i+=1 def listener_callback(self, msg): test_return = msg def check(msg, test, test_fail): count = 0 working = True for x in msg.velocity: if (abs(msg.velocity[count] / 1000 - vel_cmds.velocity[count]) > 0.001 or abs(msg.position[count] / 1000 - vel_cmds.position[count]) > 0.001): working = False count+=1 if not working: print(test_fail) else: print(test) def test1(node): vel_cmds.velocity=[rad, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] t_end = time.time() + 3 while time.time() < t_end: rclpy.spin_once(node) time.sleep(1) check(test_return, 'Test Passed: Front Left Wheel is Spinning!', 'ERROR: Front Left Wheel is NOT spinning, something is wrong!') def test2(node): vel_cmds.position=[0.0, rad, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] t_end = time.time() + 3 while time.time() < t_end: rclpy.spin_once(node) time.sleep(1) check(test_return, 'Test Passed: Front Left Axle is Spinning!', 'ERROR: Front Left Axle is NOT spinning, something is wrong!') def test3(node): vel_cmds.velocity=[0.0, 0.0, rad, 0.0, 0.0, 0.0, 0.0, 0.0] t_end = time.time() + 3 while time.time() < t_end: rclpy.spin_once(node) time.sleep(1) check(test_return, 'Test Passed: Front Right Wheel is Spinning!', 'ERROR: Front Right Wheel is NOT spinning, something is wrong!') def test4(node): vel_cmds.position=[0.0, 0.0, 0.0, rad, 0.0, 0.0, 0.0, 0.0] t_end = time.time() + 3 while time.time() < t_end: rclpy.spin_once(node) time.sleep(1) check(test_return, 'Test Passed: Front Right Axle is Spinning!', 'ERROR: Front Right Axle is NOT spinning, something is wrong!') def test5(node): vel_cmds.position=[0.0, 0.0, 0.0, 0.0, rad, 0.0, 0.0, 0.0] t_end = time.time() + 3 while time.time() < t_end: rclpy.spin_once(node) time.sleep(1) check(test_return, 'Test Passed: Rear Left Wheel is Spinning!', 'ERROR: Rear Left Wheel is NOT spinning, something is wrong!') def test6(node): vel_cmds.position=[0.0, 0.0, 0.0, 0.0, 0.0, rad, 0.0, 0.0] t_end = time.time() + 3 while time.time() < t_end: rclpy.spin_once(node) time.sleep(1) check(test_return, 'Test Passed: Rear Left Axle is Spinning!', 'ERROR: Rear Left Axle is NOT spinning, something is wrong!') def test7(node): vel_cmds.position=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, rad, 0.0] t_end = time.time() + 3 while time.time() < t_end: rclpy.spin_once(node) time.sleep(1) check(test_return, 'Test Passed: Rear Right Wheel is Spinning!', 'ERROR: Rear Right Wheel is NOT spinning, something is wrong!') def test8(node): vel_cmds.position=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, rad] t_end = time.time() + 3 while time.time() < t_end: rclpy.spin_once(node) time.sleep(1) check(test_return, 'Test Passed: Rear Right Axle is Spinning!', 'ERROR: Rear Right Axle is NOT spinning, something is wrong!') def main(args=None): rclpy.init(args=args) node = RunTests() rclpy.spin_once(node) test1(node) test2(node) test3(node) test4(node) test5(node) test6(node) test7(node) test8(node) node.destroy_node() rclpy.shutdown() if __name__ == "__main__": main()
4,771
Python
32.138889
154
0.590442
RoboEagles4828/offseason2023/src/edna_tests/edna_tests/joint_test.py
import time from rclpy.node import Node from sensor_msgs.msg import JointState # COLORS GREEN = "\033[0;32m" YELLOW = "\033[1;33m" RED = "\033[0;31m" RESET = "\033[0m" # Default ROS values SUBSCRIBE_TOPIC_NAME = '/real/real_joint_states' PUBLISH_INTERVAL = .5 # seconds # Default Tolerances PASS_TOLERANCE = 0.5 WARN_TOLERANCE = 1 SCALING_FACTOR_FIX = 10000 class TesterNode(Node): def __init__(self, tests, joint_names, joint_range, pub_topic_name, sub_topic_name=SUBSCRIBE_TOPIC_NAME, pub_interval=PUBLISH_INTERVAL, pass_tolerance=PASS_TOLERANCE, warn_tolerance=WARN_TOLERANCE): super().__init__('arm_tester') # Constructor Arguments self.TESTS = tests self.JOINT_NAMES = joint_names self.JOINT_RANGE = joint_range self.SUBSCRIBE_TOPIC_NAME = sub_topic_name self.PUBLISH_TOPIC_NAME = pub_topic_name self.PUBLISH_INTERVAL = pub_interval self.PASS_TOLERANCE = pass_tolerance self.WARN_TOLERANCE = warn_tolerance self.currentTest = 0 self.testStatus = [] self.lastPositions = [None]*6 self.expectedPositions = self.TESTS[self.currentTest]["positions"] self.recieving = True self.startTime = time.time() self.subscription = self.create_subscription(JointState, self.SUBSCRIBE_TOPIC_NAME, self.recieve, 10) self.publisher = self.create_publisher(JointState, self.PUBLISH_TOPIC_NAME, 10) self.publishTimer = self.create_timer(self.PUBLISH_INTERVAL, self.publish) def publish(self): msg = JointState() msg.name = self.JOINT_NAMES msg.position = self.TESTS[self.currentTest]["positions"] self.publisher.publish(msg) self.doTests() def doTests(self): if not(self.recieving): # Start running the next test self.currentTest += 1 if self.currentTest > len(self.TESTS)-1: print("\nTests Finished") for index, test in enumerate(self.testStatus): print(f"{RED if test['fail'] > 0 else YELLOW if test['warn'] > 0 else GREEN}Test {index} {'FAILED' if test['fail'] > 0 else 'PASSED'} {'with WARNINGS' if test['warn'] > 0 else ''}{RESET}") exit(0) # shutting down rclpy just kills the node and hangs the process, without actually stopping the program else: self.expectedPositions = self.TESTS[self.currentTest]["positions"] self.lastPositions = [None]*6 self.recieving = True self.startTime = time.time() else: # Check if the current test should end... timeleft = time.time() - self.startTime print(f"\rRunning Test {self.currentTest} ({round(self.TESTS[self.currentTest]['time'] - timeleft, 2)}s remaining)", end='') if time.time() - self.startTime > self.TESTS[self.currentTest]["time"]: self.recieving = False self.testStatus.append({"pass": 0, "warn": 0, "fail": 0}) print(f"\rTest {self.currentTest} Completed ") self.printResults() print() def recieve(self, msg : JointState): if self.recieving: self.lastPositions = [i / SCALING_FACTOR_FIX for i in msg.position[self.JOINT_RANGE[0]:self.JOINT_RANGE[1]]] def testFinished(self): if not self.recieving: return self.recieving = False self.destroy_timer(self.publishTimer) self.i += 1 def printResults(self): for index, position in enumerate(self.lastPositions): if position is None: print(f"{RED}FAILED: Did not recieve any positions from the robot!{RESET}") self.testStatus[self.currentTest]["fail"] += 1 continue difference = abs(self.expectedPositions[index] - position) if difference == 0: print(f"{GREEN}Joint {index} PASSED{RESET}") self.testStatus[self.currentTest]["pass"] += 1 elif difference <= self.PASS_TOLERANCE: print(f"{GREEN}Difference of {difference} (expected {self.expectedPositions[index]}, got {position}){RESET}") self.testStatus[self.currentTest]["pass"] += 1 elif difference <= self.WARN_TOLERANCE: print(f"{YELLOW}Difference of {difference} (expected {self.expectedPositions[index]}, got {position}){RESET}") self.testStatus[self.currentTest]["warn"] += 1 else: print(f"{RED}FAILED: Expected position {self.expectedPositions[index]}, got {position}{RESET}") self.testStatus[self.currentTest]["fail"] += 1
4,791
Python
43.785046
208
0.604467
RoboEagles4828/offseason2023/src/edna_tests/edna_tests/publish_joint_arm_command.py
import rclpy from rclpy.node import Node import math from sensor_msgs.msg import JointState class PublishJointCmd(Node): def __init__(self): super().__init__('publish_arm_joint_commands') self.publisher_ = self.create_publisher(JointState, '/real/real_arm_commands', 10) timer_period = 0.5 # seconds self.timer = self.create_timer(timer_period, self.timer_callback) self.i = 0 def timer_callback(self): # velocity_cmds = JointState() position_cmds = JointState() position_cmds.name = [ # Pneumatics 'arm_roller_bar_joint', 'top_slider_joint', 'top_gripper_left_arm_joint', # Wheels 'elevator_center_joint', 'bottom_intake_joint', ] # position_cmds.name = [] # rad = math.pi # velocity_cmds.velocity = [ 0.0 ] * 8 position_cmds.position = [ 0.0, # Either a 0 (down) or a 1 (up) 0.0, # Either a 0 (fully back) or a 1 (fully extended) 0.0, # Either a 0 (open) or a 1 (closed) 0.0, # Value between 0.0 (fully back) and 2.0 (fully extended) (will be converted on their end, so just take the motor value and multiply it by two) 0.0 # Value between 0.0 (fully down) and 1.0 (fully up) ] # position_cmds.position = [] self.publisher_.publish(position_cmds) # self.publisher_.publish(position_cmds) self.get_logger().info('Publishing: ...') self.i += 1 def main(args=None): rclpy.init(args=args) node = PublishJointCmd() rclpy.spin(node) # Destroy the node explicitly # (optional - otherwise it will be done automatically # when the garbage collector destroys the node object) node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
1,931
Python
28.723076
165
0.568099
RoboEagles4828/offseason2023/src/joint_trajectory_teleop/setup.py
from setuptools import setup package_name = 'joint_trajectory_teleop' setup( name=package_name, version='0.0.0', packages=[package_name], data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), ('share/' + package_name, ['package.xml']), ], install_requires=['setuptools'], zip_safe=True, maintainer='admin', maintainer_email='[email protected]', description='TODO: Package description', license='TODO: License declaration', tests_require=['pytest'], entry_points={ 'console_scripts': [ 'joint_trajectory_teleop = joint_trajectory_teleop.joint_trajectory_teleop:main', ], }, )
728
Python
25.999999
93
0.619505
RoboEagles4828/offseason2023/src/joint_trajectory_teleop/test/test_flake8.py
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ament_flake8.main import main_with_errors import pytest @pytest.mark.flake8 @pytest.mark.linter def test_flake8(): rc, errors = main_with_errors(argv=[]) assert rc == 0, \ 'Found %d code style errors / warnings:\n' % len(errors) + \ '\n'.join(errors)
884
Python
33.03846
74
0.725113
RoboEagles4828/offseason2023/src/joint_trajectory_teleop/test/test_pep257.py
# Copyright 2015 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ament_pep257.main import main import pytest @pytest.mark.linter @pytest.mark.pep257 def test_pep257(): rc = main(argv=['.', 'test']) assert rc == 0, 'Found code style errors / warnings'
803
Python
32.499999
74
0.743462
RoboEagles4828/offseason2023/src/joint_trajectory_teleop/test/test_copyright.py
# Copyright 2015 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ament_copyright.main import main import pytest # Remove the `skip` decorator once the source file(s) have a copyright header @pytest.mark.skip(reason='No copyright header has been placed in the generated source file.') @pytest.mark.copyright @pytest.mark.linter def test_copyright(): rc = main(argv=['.', 'test']) assert rc == 0, 'Found errors'
962
Python
36.03846
93
0.751559
RoboEagles4828/offseason2023/src/joint_trajectory_teleop/joint_trajectory_teleop/yaml_test.py
import yaml yaml_path = '/workspaces/edna2023/src/edna_bringup/config/xbox-real.yaml' with open(yaml_path, 'r') as f: yaml = yaml.safe_load(f) yaml = yaml['/*']['joint_trajectory_teleop_node']['ros__parameters'] print(str(yaml['function_mapping']['elevator_loading_station']['button']))
291
Python
40.71428
74
0.707904
RoboEagles4828/offseason2023/src/joint_trajectory_teleop/joint_trajectory_teleop/joint_trajectory_teleop.py
import rclpy from rclpy.node import Node from rclpy.qos import QoSProfile, QoSHistoryPolicy, QoSDurabilityPolicy, QoSReliabilityPolicy from rclpy import logging import math from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint from sensor_msgs.msg import Joy import os from rclpy.qos import QoSDurabilityPolicy, QoSHistoryPolicy, QoSReliabilityPolicy, QoSProfile import time import yaml ENABLE_THROTTLE = True class toggleButton(): def __init__(self, button, isAxis=False): self.last_button = 0.0 self.flag = False self.button = button self.isAxis = isAxis def toggle(self, buttons_list): currentButton = buttons_list[self.button] if self.isAxis: # currentButton = currentButton / 10000 if currentButton > 1 else currentButton if currentButton == -10000.0 and self.last_button != -10000.0: self.flag = not self.flag self.last_button = currentButton return self.flag else: self.last_button = currentButton return self.flag if currentButton == 1.0 and self.last_button == 0.0: self.flag = not self.flag self.last_button = currentButton return self.flag else: self.last_button = currentButton return self.flag class PublishTrajectoryMsg(Node): def __init__(self): super().__init__('publish_trajectory_msg') # Joint Map self.joints = [ 'arm_roller_bar_joint', 'elevator_center_joint', 'elevator_outer_1_joint', 'elevator_outer_2_joint', 'top_gripper_right_arm_joint', 'top_gripper_left_arm_joint', 'top_slider_joint', 'bottom_intake_joint', ] # Publishers and Subscribers self.publisher_ = self.create_publisher(JointTrajectory, 'joint_trajectory_controller/joint_trajectory', 10) self.subscriber = self.create_subscription(Joy, 'joy', self.controller_callback, 10) self.timer_period = 0.5 # seconds # Load yaml self.curr_file_path = os.path.abspath(__file__) self.project_root_path = os.path.abspath(os.path.join(self.curr_file_path, "../../../..")) self.yaml_path = os.path.join(self.project_root_path, 'src/edna_bringup/config/teleop-control.yaml') with open(self.yaml_path, 'r') as f: self.yaml = yaml.safe_load(f) # Macros self.functions = [self.elevator_loading_station, self.skis_up, self.elevator_mid_level, self.elevator_high_level, self.top_gripper_control, self.elevator_pivot_control, self.top_slider_control] # Variables self.cmds: JointTrajectory = JointTrajectory() self.position_cmds: JointTrajectoryPoint = JointTrajectoryPoint() self.position_cmds.positions = [0.0] * len(self.joints) self.cmds.joint_names = self.joints self.joint_map = self.yaml['joint_mapping'] self.logger = logging.get_logger('JOINT-TRAJCECTORY-TELEOP') self.toggle_buttons = {} self.last_cmd = JointTrajectory() self.joint_limits = self.yaml["joint_limits"] # Create Toggle Buttons for function in self.functions: buttonName = self.yaml['function_mapping'][function.__name__]['button'] button = self.yaml['controller_mapping'][buttonName] toggle = self.yaml['function_mapping'][function.__name__]['toggle'] isAxis = "axis" in buttonName.lower() if toggle: self.toggle_buttons[function.__name__] = toggleButton(button, isAxis) def controller_callback(self, joystick: Joy): for function in self.functions: buttonName = self.yaml['function_mapping'][function.__name__]['button'] button = self.yaml['controller_mapping'][buttonName] toggle = self.yaml['function_mapping'][function.__name__]['toggle'] if toggle: tglBtn = self.toggle_buttons[function.__name__] if tglBtn.isAxis: button = tglBtn.toggle(joystick.axes) else: button = tglBtn.toggle(joystick.buttons) else: button = joystick.buttons[button] function(button) self.publisher_.publish(self.cmds) # Macros def elevator_loading_station(self, button_val: int): #TODO: Tweak the values if button_val == 1.0: self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = 0.056 self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = 0.056 self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"]["max"] elif button_val == 0.0: self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = 0.0 self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = 0.0 self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = 0.0 self.cmds.points = [self.position_cmds] def skis_up(self, button_val: int): #TODO: Tweak the values self.position_cmds.positions[int(self.joint_map['bottom_intake_joint'])] = button_val self.cmds.points = [self.position_cmds] def elevator_mid_level(self, button_val: int): #TODO: Tweak the values if button_val == 1.0: self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = 0.336 self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = 0.336 self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"]["max"] self.cmds.points = [self.position_cmds] def elevator_high_level(self, button_val: int): #TODO: Tweak the values if button_val == 1.0: self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = self.joint_limits["elevator_center_joint"]["max"] self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = self.joint_limits["elevator_outer_2_joint"]["max"] self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"]["max"] elif button_val == 0.0: self.position_cmds.positions[int(self.joint_map['elevator_outer_1_joint'])] = 0.0 self.cmds.points = [self.position_cmds] def top_gripper_control(self, button_val: int): #TODO: Tweak the values if button_val == 1.0: self.position_cmds.positions[int(self.joint_map['top_gripper_left_arm_joint'])] = self.joint_limits["top_gripper_left_arm_joint"]["max"] self.position_cmds.positions[int(self.joint_map['top_gripper_right_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"]["max"] elif button_val == 0.0: self.position_cmds.positions[int(self.joint_map['top_gripper_left_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"]["min"] self.position_cmds.positions[int(self.joint_map['top_gripper_right_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"]["min"] self.cmds.points = [self.position_cmds] def elevator_pivot_control(self, button_val: int): #TODO: Tweak the values if button_val == 1.0: self.position_cmds.positions[int(self.joint_map['arm_roller_bar_joint'])] = self.joint_limits["arm_roller_bar_joint"]["max"] self.position_cmds.positions[int(self.joint_map['elevator_outer_1_joint'])] = self.joint_limits["elevator_outer_1_joint"]["max"] else: self.position_cmds.positions[int(self.joint_map['arm_roller_bar_joint'])] = 0.0 self.position_cmds.positions[int(self.joint_map['elevator_outer_1_joint'])] = 0.0 self.cmds.points = [self.position_cmds] def top_slider_control(self, button_val: int): #TODO: Tweak the values if button_val == 1.0: self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"]["max"] self.cmds.points = [self.position_cmds] def main(args=None): rclpy.init(args=args) node = PublishTrajectoryMsg() rclpy.spin(node) node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
8,659
Python
40.238095
201
0.618778
RoboEagles4828/offseason2023/src/swerve_hardware/swerve_hardware.xml
<library path="swerve_hardware"> <class name="swerve_hardware/IsaacDriveHardware" type="swerve_hardware::IsaacDriveHardware" base_class_type="hardware_interface::SystemInterface"> <description> The ROS2 Control hardware interface to talk with Isaac Sim robot drive train. </description> </class> <class name="swerve_hardware/TestDriveHardware" type="swerve_hardware::TestDriveHardware" base_class_type="hardware_interface::SystemInterface"> <description> The ROS2 Control hardware interface for testing a connected controller. </description> </class> <class name="swerve_hardware/RealDriveHardware" type="swerve_hardware::RealDriveHardware" base_class_type="hardware_interface::SystemInterface"> <description> The ROS2 Control hardware interface for testing a connected controller. </description> </class> </library>
925
XML
37.583332
83
0.714595
RoboEagles4828/offseason2023/src/swerve_hardware/src/isaac_drive.cpp
// Copyright 2021 ros2_control Development Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "swerve_hardware/isaac_drive.hpp" #include <chrono> #include <cmath> #include <limits> #include <memory> #include <vector> #include "hardware_interface/types/hardware_interface_type_values.hpp" #include "rclcpp/rclcpp.hpp" #include "swerve_hardware/motion_magic.hpp" #include "sensor_msgs/msg/joint_state.hpp" using std::placeholders::_1; namespace swerve_hardware { hardware_interface::CallbackReturn IsaacDriveHardware::on_init(const hardware_interface::HardwareInfo & info) { node_ = rclcpp::Node::make_shared("isaac_hardware_interface"); // PUBLISHER SETUP isaac_publisher_ = node_->create_publisher<sensor_msgs::msg::JointState>(joint_command_topic_, rclcpp::SystemDefaultsQoS()); realtime_isaac_publisher_ = std::make_shared<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>( isaac_publisher_); // SUBSCRIBER SETUP const sensor_msgs::msg::JointState empty_joint_state; auto qos = rclcpp::QoS(1); qos.best_effort(); received_joint_msg_ptr_.set(std::make_shared<sensor_msgs::msg::JointState>(empty_joint_state)); isaac_subscriber_ = node_->create_subscription<sensor_msgs::msg::JointState>(joint_state_topic_, qos, [this](const std::shared_ptr<sensor_msgs::msg::JointState> msg) -> void { if (!subscriber_is_active_) { RCLCPP_WARN( rclcpp::get_logger("isaac_hardware_interface"), "Can't accept new commands. subscriber is inactive"); return; } received_joint_msg_ptr_.set(std::move(msg)); }); // COMMON INTERFACE SETUP if (hardware_interface::SystemInterface::on_init(info) != hardware_interface::CallbackReturn::SUCCESS) { return hardware_interface::CallbackReturn::ERROR; } // 8 positions states, 4 axle positions 4 wheel positions hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); // 8 velocity states, 4 axle velocity 4 wheel velocity hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); // 4 wheel velocity commands // We will keep this at 8 and make the other 4 zero to keep indexing consistent hw_command_velocity_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); // 4 axle position commands // We will keep this at 8 and make the other 4 zero to keep indexing consistent hw_command_position_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); joint_types_.resize(info_.joints.size(), ""); motion_magic_.resize(info_.joints.size(), MotionMagic(MAX_ACCELERATION, MAX_VELOCITY)); for (const hardware_interface::ComponentInfo & joint : info_.joints) { joint_names_.push_back(joint.name); if (joint.command_interfaces.size() != 1) { RCLCPP_FATAL( rclcpp::get_logger("IsaacDriveHardware"), "Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(), joint.command_interfaces.size()); return hardware_interface::CallbackReturn::ERROR; } if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY && joint.command_interfaces[0].name != hardware_interface::HW_IF_POSITION) { RCLCPP_FATAL( rclcpp::get_logger("IsaacDriveHardware"), "Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(), joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY); return hardware_interface::CallbackReturn::ERROR; } if (joint.state_interfaces.size() != 2) { RCLCPP_FATAL( rclcpp::get_logger("IsaacDriveHardware"), "Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(), joint.state_interfaces.size()); return hardware_interface::CallbackReturn::ERROR; } if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION) { RCLCPP_FATAL( rclcpp::get_logger("IsaacDriveHardware"), "Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(), joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION); return hardware_interface::CallbackReturn::ERROR; } if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY) { RCLCPP_FATAL( rclcpp::get_logger("IsaacDriveHardware"), "Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(), joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY); return hardware_interface::CallbackReturn::ERROR; } } return hardware_interface::CallbackReturn::SUCCESS; } std::vector<hardware_interface::StateInterface> IsaacDriveHardware::export_state_interfaces() { // Each joint has 2 state interfaces: position and velocity std::vector<hardware_interface::StateInterface> state_interfaces; for (auto i = 0u; i < info_.joints.size(); i++) { state_interfaces.emplace_back(hardware_interface::StateInterface( info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i])); state_interfaces.emplace_back(hardware_interface::StateInterface( info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i])); } return state_interfaces; } std::vector<hardware_interface::CommandInterface> IsaacDriveHardware::export_command_interfaces() { std::vector<hardware_interface::CommandInterface> command_interfaces; for (auto i = 0u; i < info_.joints.size(); i++) { auto joint = info_.joints[i]; RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Joint Name %s", joint.name.c_str()); if (joint.command_interfaces[0].name == hardware_interface::HW_IF_VELOCITY) { RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Added Velocity Joint: %s", joint.name.c_str() ); joint_types_[i] = hardware_interface::HW_IF_VELOCITY; // Add the command interface with a pointer to i of vel commands command_interfaces.emplace_back(hardware_interface::CommandInterface( joint.name, hardware_interface::HW_IF_VELOCITY, &hw_command_velocity_[i])); // Make i of the pos command interface 0.0 hw_command_position_[i] = 0.0; } else { RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Added Position Joint: %s", joint.name.c_str() ); joint_types_[i] = hardware_interface::HW_IF_POSITION; // Add the command interface with a pointer to i of pos commands command_interfaces.emplace_back(hardware_interface::CommandInterface( joint.name, hardware_interface::HW_IF_POSITION, &hw_command_position_[i])); // Make i of the pos command interface 0.0 hw_command_velocity_[i] = 0.0; } } return command_interfaces; } hardware_interface::CallbackReturn IsaacDriveHardware::on_activate(const rclcpp_lifecycle::State & /*previous_state*/) { RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Activating ...please wait..."); // Set Default Values for State Interface Arrays for (auto i = 0u; i < hw_positions_.size(); i++) { hw_positions_[i] = 0.0; hw_velocities_[i] = 0.0; hw_command_velocity_[i] = 0.0; hw_command_position_[i] = 0.0; } subscriber_is_active_ = true; RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Successfully activated!"); return hardware_interface::CallbackReturn::SUCCESS; } hardware_interface::CallbackReturn IsaacDriveHardware::on_deactivate( const rclcpp_lifecycle::State & /*previous_state*/) { RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Deactivating ...please wait..."); subscriber_is_active_ = false; RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Successfully deactivated!"); return hardware_interface::CallbackReturn::SUCCESS; } // || || // \/ THE STUFF THAT MATTERS \/ double IsaacDriveHardware::convertToRosPosition(double isaac_position) { // Isaac goes from -2pi to 2pi, we want -pi to pi if (isaac_position > M_PI) { return isaac_position - 2.0 * M_PI; } else if (isaac_position < -M_PI) { return isaac_position + 2.0 * M_PI; } return isaac_position; } hardware_interface::return_type IsaacDriveHardware::read(const rclcpp::Time & time, const rclcpp::Duration & /*period*/) { rclcpp::spin_some(node_); std::shared_ptr<sensor_msgs::msg::JointState> last_command_msg; received_joint_msg_ptr_.get(last_command_msg); if (last_command_msg == nullptr) { RCLCPP_WARN(rclcpp::get_logger("IsaacDriveHardware"), "[%f] Velocity message received was a nullptr.", time.seconds()); return hardware_interface::return_type::ERROR; } auto names = last_command_msg->name; auto positions = last_command_msg->position; auto velocities = last_command_msg->velocity; for (auto i = 0u; i < joint_names_.size(); i++) { for (auto j = 0u; j < names.size(); j++) { if (strcmp(names[j].c_str(), info_.joints[i].name.c_str()) == 0) { hw_positions_[i] = convertToRosPosition(positions[j]); hw_velocities_[i] = (float)velocities[j]; break; } } } return hardware_interface::return_type::OK; } hardware_interface::return_type swerve_hardware::IsaacDriveHardware::write(const rclcpp::Time & /*time*/, const rclcpp::Duration & period) { // Calculate Axle Velocities using motion magic double dt = period.seconds(); for (auto i = 0u; i < joint_names_.size(); i++) { if (joint_names_[i].find("axle") != std::string::npos) { auto vel = motion_magic_[i].getNextVelocity(hw_command_position_[i], hw_positions_[i], hw_velocities_[i], dt); // RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Current: %f, Target: %f Vel: %f", hw_positions_[i], hw_command_position_[i], vel); hw_command_velocity_[i] = vel; } if (joint_names_[i] == "front_left_wheel_joint") { auto& clk = *node_->get_clock(); RCLCPP_INFO_THROTTLE(rclcpp::get_logger("IsaacDriveHardware"), clk, 2000, "Joint: %s Current Vel: %f Target Vel: %f Pos: %f", joint_names_[i].c_str(), hw_velocities_[i], hw_command_velocity_[i], hw_positions_[i]); } } // Publish to Isaac if (realtime_isaac_publisher_->trylock()) { auto & realtime_isaac_command_ = realtime_isaac_publisher_->msg_; realtime_isaac_command_.header.stamp = node_->get_clock()->now(); realtime_isaac_command_.name = joint_names_; realtime_isaac_command_.velocity = hw_command_velocity_; realtime_isaac_command_.position = empty_; realtime_isaac_publisher_->unlockAndPublish(); } rclcpp::spin_some(node_); if (realtime_isaac_publisher_->trylock()) { auto & realtime_isaac_command_ = realtime_isaac_publisher_->msg_; realtime_isaac_command_.header.stamp = node_->get_clock()->now(); realtime_isaac_command_.name = joint_names_; realtime_isaac_command_.velocity = empty_; realtime_isaac_command_.position = hw_command_position_; realtime_isaac_publisher_->unlockAndPublish(); } rclcpp::spin_some(node_); return hardware_interface::return_type::OK; } } // namespace swerve_hardware #include "pluginlib/class_list_macros.hpp" PLUGINLIB_EXPORT_CLASS( swerve_hardware::IsaacDriveHardware, hardware_interface::SystemInterface)
11,781
C++
37.006451
153
0.683643
RoboEagles4828/offseason2023/src/swerve_hardware/src/test_drive.cpp
// Copyright 2021 ros2_control Development Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "swerve_hardware/test_drive.hpp" #include <chrono> #include <cmath> #include <limits> #include <memory> #include <vector> #include "hardware_interface/types/hardware_interface_type_values.hpp" #include "swerve_hardware/motion_magic.hpp" #include "rclcpp/rclcpp.hpp" using std::placeholders::_1; namespace swerve_hardware { hardware_interface::CallbackReturn TestDriveHardware::on_init(const hardware_interface::HardwareInfo & info) { // COMMON INTERFACE SETUP if (hardware_interface::SystemInterface::on_init(info) != hardware_interface::CallbackReturn::SUCCESS) { return hardware_interface::CallbackReturn::ERROR; } // 8 positions states, 4 axle positions 4 wheel positions hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); // 8 velocity states, 4 axle velocity 4 wheel velocity hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); // 4 wheel velocity commands // We will keep this at 8 and make the other 4 zero to keep indexing consistent hw_command_velocity_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); // 4 axle position commands // We will keep this at 8 and make the other 4 zero to keep indexing consistent hw_command_position_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); joint_types_.resize(info_.joints.size(), ""); motion_magic_.resize(info_.joints.size(), MotionMagic(MAX_ACCELERATION, MAX_VELOCITY)); for (const hardware_interface::ComponentInfo & joint : info_.joints) { joint_names_.push_back(joint.name); if (joint.command_interfaces.size() != 1) { RCLCPP_FATAL( rclcpp::get_logger("TestDriveHardware"), "Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(), joint.command_interfaces.size()); return hardware_interface::CallbackReturn::ERROR; } if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY && joint.command_interfaces[0].name != hardware_interface::HW_IF_POSITION) { RCLCPP_FATAL( rclcpp::get_logger("TestDriveHardware"), "Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(), joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY); return hardware_interface::CallbackReturn::ERROR; } if (joint.state_interfaces.size() != 2) { RCLCPP_FATAL( rclcpp::get_logger("TestDriveHardware"), "Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(), joint.state_interfaces.size()); return hardware_interface::CallbackReturn::ERROR; } if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION) { RCLCPP_FATAL( rclcpp::get_logger("TestDriveHardware"), "Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(), joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION); return hardware_interface::CallbackReturn::ERROR; } if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY) { RCLCPP_FATAL( rclcpp::get_logger("TestDriveHardware"), "Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(), joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY); return hardware_interface::CallbackReturn::ERROR; } } return hardware_interface::CallbackReturn::SUCCESS; } std::vector<hardware_interface::StateInterface> TestDriveHardware::export_state_interfaces() { // Each joint has 2 state interfaces: position and velocity std::vector<hardware_interface::StateInterface> state_interfaces; for (auto i = 0u; i < info_.joints.size(); i++) { state_interfaces.emplace_back(hardware_interface::StateInterface( info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i])); state_interfaces.emplace_back(hardware_interface::StateInterface( info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i])); } return state_interfaces; } std::vector<hardware_interface::CommandInterface> TestDriveHardware::export_command_interfaces() { std::vector<hardware_interface::CommandInterface> command_interfaces; for (auto i = 0u; i < info_.joints.size(); i++) { auto joint = info_.joints[i]; RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Joint Name %s", joint.name.c_str()); if (joint.command_interfaces[0].name == hardware_interface::HW_IF_VELOCITY) { RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Added Velocity Joint: %s", joint.name.c_str() ); joint_types_[i] = hardware_interface::HW_IF_VELOCITY; // Add the command interface with a pointer to i of vel commands command_interfaces.emplace_back(hardware_interface::CommandInterface( joint.name, hardware_interface::HW_IF_VELOCITY, &hw_command_velocity_[i])); // Make i of the pos command interface 0.0 hw_command_position_[i] = 0.0; } else { RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Added Position Joint: %s", joint.name.c_str() ); joint_types_[i] = hardware_interface::HW_IF_POSITION; // Add the command interface with a pointer to i of pos commands command_interfaces.emplace_back(hardware_interface::CommandInterface( joint.name, hardware_interface::HW_IF_POSITION, &hw_command_position_[i])); // Make i of the pos command interface 0.0 hw_command_velocity_[i] = 0.0; } } return command_interfaces; } hardware_interface::CallbackReturn TestDriveHardware::on_activate(const rclcpp_lifecycle::State & /*previous_state*/) { RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Activating ...please wait..."); // Set Default Values for State Interface Arrays for (auto i = 0u; i < hw_positions_.size(); i++) { hw_positions_[i] = 0.0; hw_velocities_[i] = 0.0; hw_command_velocity_[i] = 0.0; hw_command_position_[i] = 0.0; } RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Successfully activated!"); return hardware_interface::CallbackReturn::SUCCESS; } hardware_interface::CallbackReturn TestDriveHardware::on_deactivate(const rclcpp_lifecycle::State & /*previous_state*/) { RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Deactivating ...please wait..."); RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Successfully deactivated!"); return hardware_interface::CallbackReturn::SUCCESS; } // || || // \/ THE STUFF THAT MATTERS \/ hardware_interface::return_type TestDriveHardware::read(const rclcpp::Time & /*time*/, const rclcpp::Duration & period) { // Dumb Pass Through // If you give the command for x velocity then the state is x velocity // Loop through each joint name // Check if joint name is in velocity command map // If it is, use the index from the map to get the value in the velocity array // If velocity not in map, set velocity value to 0 // Perform the same for position double dt = period.seconds(); for (auto i = 0u; i < joint_names_.size(); i++) { if (joint_types_[i] == hardware_interface::HW_IF_VELOCITY) { hw_velocities_[i] = hw_command_velocity_[i]; hw_positions_[i] = hw_positions_[i] + dt * hw_velocities_[i]; } else if (joint_types_[i] == hardware_interface::HW_IF_POSITION) { auto vel = motion_magic_[i].getNextVelocity(hw_command_position_[i], hw_positions_[i], hw_velocities_[i], dt); // RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Current: %f, Target: %f Vel: %f", hw_positions_[i], hw_command_position_[i], vel); hw_velocities_[i] = vel; hw_positions_[i] = hw_positions_[i] + hw_velocities_[i] * dt; // Test without any velocity smoothing // RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Cmd: %f Name: %s", hw_command_position_[i], joint_names_[i].c_str()); // hw_velocities_[i] = 0.0; // hw_positions_[i] = hw_command_position_[i]; } } return hardware_interface::return_type::OK; } hardware_interface::return_type TestDriveHardware::write(const rclcpp::Time & /*time*/, const rclcpp::Duration & /*period*/) { // Do Nothing // Uncomment below if you want verbose messages for debugging. // for (auto i = 0u; i < hw_command_velocity_.size(); i++) // { // RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Wheel %u Velocity: %f", i, hw_command_velocity_[i]); // } // RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "[%f] Joint 2 Position: %f", time.seconds(), hw_command_position_[2]); return hardware_interface::return_type::OK; } } // namespace swerve_hardware #include "pluginlib/class_list_macros.hpp" PLUGINLIB_EXPORT_CLASS( swerve_hardware::TestDriveHardware, hardware_interface::SystemInterface)
9,533
C++
37.59919
153
0.683625
RoboEagles4828/offseason2023/src/swerve_hardware/src/motion_magic.cpp
#include "swerve_hardware/motion_magic.hpp" #include <chrono> #include <cmath> #include <limits> #include <memory> #include <vector> #include <ostream> #include <iostream> namespace swerve_hardware { MotionMagic::MotionMagic(double maxAcceleration, double maxVelocity) { this->MAX_ACCELERATION = maxAcceleration; this->MAX_VELOCITY = maxVelocity; } double MotionMagic::getPositionDifference(double targetPosition, double sensorPosition) { double copy_targetPosition = targetPosition; double difference = copy_targetPosition - sensorPosition; if (difference > M_PI) { copy_targetPosition -= 2 * M_PI; } else if (difference < -M_PI) { copy_targetPosition += 2 * M_PI; } return std::fmod(copy_targetPosition - sensorPosition, M_PI); } // (maxV - curr)t1 + curr // (curr - maxV)tf + b = 0 // 2 10 // 4(t1) double MotionMagic::getNextVelocity(const double targetPosition, const double sensorPosition, const double sensorVelocity, const double dt) { // method 0 double error = getPositionDifference(targetPosition, sensorPosition); double absError = std::abs(error); if (targetPosition != prevTargetPosition) { totalDistance = absError; prevTargetPosition = targetPosition; } if (absError < tolerance) { return 0.0; } double dir = 1.0; if (error < 0.0) { dir = -1.0; } if (absError <= rampWindow1) { return velocityInRampWindow1 * dir; } else if (absError <= rampWindow2) { return velocityInRampWindow2 * dir; } else { return velocityInCruiseWindow * dir; } //method 1 // double displacement = std::abs(getPositionDifference(targetPosition, sensorPosition)); // double dir = targetPosition - sensorPosition; // double slow_down_dist = (MAX_JERK/6) * pow(2*sensorVelocity/MAX_JERK, 1.5); // if(std::abs(displacement - 0.0) <= tolerance) return 0.0; // if(dir > 0) { // if(displacement <= slow_down_dist) return std::max(sensorVelocity - dt * dt * MAX_JERK, -1*MAX_VELOCITY); // // std::cout<<std::min(sensorVelocity + dt * dt * MAX_JERK, MAX_VELOCITY); // else return std::min(sensorVelocity + dt * dt * MAX_JERK, MAX_VELOCITY); // } else { // if(displacement <= slow_down_dist) return std::min(sensorVelocity + dt * dt * MAX_JERK, MAX_VELOCITY); // else return std::max(sensorVelocity - dt * dt * MAX_JERK, -1*MAX_VELOCITY); // } } } // namespace swerve_hardware
2,741
C++
33.70886
145
0.594673
RoboEagles4828/offseason2023/src/swerve_hardware/src/real_drive.cpp
// Copyright 2021 ros2_control Development Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "swerve_hardware/real_drive.hpp" #include <chrono> #include <cmath> #include <limits> #include <memory> #include <vector> #include "hardware_interface/types/hardware_interface_type_values.hpp" #include "rclcpp/rclcpp.hpp" #include "swerve_hardware/motion_magic.hpp" #include "sensor_msgs/msg/joint_state.hpp" using std::placeholders::_1; namespace swerve_hardware { double RealDriveHardware::parse_double(const std::string & text) { return std::atof(text.c_str()); } bool RealDriveHardware::parse_bool(const std::string & text) { if(strcmp(text.c_str(), "true") == 0) { return true; } else { return false; } } hardware_interface::CallbackReturn RealDriveHardware::on_init(const hardware_interface::HardwareInfo & info) { node_ = rclcpp::Node::make_shared("isaac_hardware_interface"); // PUBLISHER SETUP real_publisher_ = node_->create_publisher<sensor_msgs::msg::JointState>(joint_command_topic_, rclcpp::SystemDefaultsQoS()); realtime_real_publisher_ = std::make_shared<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>( real_publisher_); real_arm_publisher_ = node_->create_publisher<sensor_msgs::msg::JointState>(joint_arm_command_topic_, rclcpp::SystemDefaultsQoS()); realtime_real_arm_publisher_ = std::make_shared<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>( real_arm_publisher_); // SUBSCRIBER SETUP const sensor_msgs::msg::JointState empty_joint_state; auto qos = rclcpp::QoS(1); qos.best_effort(); received_joint_msg_ptr_.set(std::make_shared<sensor_msgs::msg::JointState>(empty_joint_state)); real_subscriber_ = node_->create_subscription<sensor_msgs::msg::JointState>(joint_state_topic_, qos, [this](const std::shared_ptr<sensor_msgs::msg::JointState> msg) -> void { if (!subscriber_is_active_) { RCLCPP_WARN( rclcpp::get_logger("isaac_hardware_interface"), "Can't accept new commands. subscriber is inactive"); return; } received_joint_msg_ptr_.set(std::move(msg)); }); // COMMON INTERFACE SETUP if (hardware_interface::SystemInterface::on_init(info) != hardware_interface::CallbackReturn::SUCCESS) { return hardware_interface::CallbackReturn::ERROR; } // GLOBAL VECTOR SETUP hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); hw_command_velocity_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); hw_command_position_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN()); joint_types_.resize(info_.joints.size(), ""); // JOINT GROUPS for (auto i = 0u; i < info_.joints.size(); ++i) { const auto & joint = info_.joints.at(i); bool use_percent = false; double max = parse_double(joint.command_interfaces[0].max); double min = parse_double(joint.command_interfaces[0].min); auto param_percent_it = joint.parameters.find("percent"); if (param_percent_it != joint.parameters.end()) { use_percent = parse_bool(joint.parameters.at("percent")); } // Mimics if (joint.parameters.find("mimic") != joint.parameters.cend()) { const auto mimicked_joint_it = std::find_if( info_.joints.begin(), info_.joints.end(), [&mimicked_joint = joint.parameters.at("mimic")](const hardware_interface::ComponentInfo & joint_info) { return joint_info.name == mimicked_joint; }); if (mimicked_joint_it == info_.joints.cend()) { throw std::runtime_error( std::string("Mimicked joint '") + joint.parameters.at("mimic") + "' not found"); } MimicJoint mimic_joint; mimic_joint.joint_index = i; mimic_joint.mimicked_joint_index = std::distance(info_.joints.begin(), mimicked_joint_it); // Multiplier and offset auto param_mult_it = joint.parameters.find("multiplier"); if (param_mult_it != joint.parameters.end()) { mimic_joint.multiplier = parse_double(joint.parameters.at("multiplier")); } auto param_off_it = joint.parameters.find("offset"); if (param_off_it != joint.parameters.end()) { mimic_joint.offset = parse_double(joint.parameters.at("offset")); } mimic_joints_.push_back(mimic_joint); } // else if (joint.parameters.find("arm_group") != joint.parameters.cend()) { JointGroupMember member; member.joint_index = i; member.joint_name = joint.name; member.percent = use_percent; member.max = max; member.min = min; arm_names_output_.push_back(joint.name); arm_joints_.push_back(member); } else { JointGroupMember member; member.joint_index = i; member.joint_name = joint.name; member.percent = use_percent; member.max = max; member.min = min; drive_names_output_.push_back(joint.name); drive_joints_.push_back(member); } } hw_command_arm_velocity_output_.resize(arm_joints_.size(), std::numeric_limits<double>::quiet_NaN()); hw_command_arm_position_output_.resize(arm_joints_.size(), std::numeric_limits<double>::quiet_NaN()); hw_command_drive_velocity_output_.resize(drive_joints_.size(), std::numeric_limits<double>::quiet_NaN()); hw_command_drive_position_output_.resize(drive_joints_.size(), std::numeric_limits<double>::quiet_NaN()); // Check that the info we were passed makes sense for (const hardware_interface::ComponentInfo & joint : info_.joints) { joint_names_.push_back(joint.name); if (joint.command_interfaces.size() != 1) { RCLCPP_FATAL( rclcpp::get_logger("RealDriveHardware"), "Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(), joint.command_interfaces.size()); return hardware_interface::CallbackReturn::ERROR; } if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY && joint.command_interfaces[0].name != hardware_interface::HW_IF_POSITION) { RCLCPP_FATAL( rclcpp::get_logger("RealDriveHardware"), "Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(), joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY); return hardware_interface::CallbackReturn::ERROR; } if (joint.state_interfaces.size() != 2) { RCLCPP_FATAL( rclcpp::get_logger("RealDriveHardware"), "Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(), joint.state_interfaces.size()); return hardware_interface::CallbackReturn::ERROR; } if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION) { RCLCPP_FATAL( rclcpp::get_logger("RealDriveHardware"), "Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(), joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION); return hardware_interface::CallbackReturn::ERROR; } if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY) { RCLCPP_FATAL( rclcpp::get_logger("RealDriveHardware"), "Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(), joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY); return hardware_interface::CallbackReturn::ERROR; } } return hardware_interface::CallbackReturn::SUCCESS; } std::vector<hardware_interface::StateInterface> RealDriveHardware::export_state_interfaces() { // Each joint has 2 state interfaces: position and velocity std::vector<hardware_interface::StateInterface> state_interfaces; for (auto i = 0u; i < info_.joints.size(); i++) { state_interfaces.emplace_back(hardware_interface::StateInterface( info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i])); state_interfaces.emplace_back(hardware_interface::StateInterface( info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i])); } return state_interfaces; } std::vector<hardware_interface::CommandInterface> RealDriveHardware::export_command_interfaces() { std::vector<hardware_interface::CommandInterface> command_interfaces; for (auto i = 0u; i < info_.joints.size(); i++) { auto joint = info_.joints[i]; RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Joint Name %s", joint.name.c_str()); if (joint.command_interfaces[0].name == hardware_interface::HW_IF_VELOCITY) { RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Added Velocity Joint: %s", joint.name.c_str() ); joint_types_[i] = hardware_interface::HW_IF_VELOCITY; // Add the command interface with a pointer to i of vel commands command_interfaces.emplace_back(hardware_interface::CommandInterface( joint.name, hardware_interface::HW_IF_VELOCITY, &hw_command_velocity_[i])); // Make i of the pos command interface 0.0 hw_command_position_[i] = 0.0; } else { RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Added Position Joint: %s", joint.name.c_str() ); joint_types_[i] = hardware_interface::HW_IF_POSITION; // Add the command interface with a pointer to i of pos commands command_interfaces.emplace_back(hardware_interface::CommandInterface( joint.name, hardware_interface::HW_IF_POSITION, &hw_command_position_[i])); // Make i of the pos command interface 0.0 hw_command_velocity_[i] = 0.0; } } return command_interfaces; } hardware_interface::CallbackReturn RealDriveHardware::on_activate(const rclcpp_lifecycle::State & /*previous_state*/) { RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Activating ...please wait..."); // Set Default Values for State Interface Arrays for (auto i = 0u; i < hw_positions_.size(); i++) { hw_positions_[i] = 0.0; hw_velocities_[i] = 0.0; hw_command_velocity_[i] = 0.0; hw_command_position_[i] = 0.0; } subscriber_is_active_ = true; RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Successfully activated!"); return hardware_interface::CallbackReturn::SUCCESS; } hardware_interface::CallbackReturn RealDriveHardware::on_deactivate( const rclcpp_lifecycle::State & /*previous_state*/) { RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Deactivating ...please wait..."); subscriber_is_active_ = false; RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Successfully deactivated!"); return hardware_interface::CallbackReturn::SUCCESS; } // || || // \/ THE STUFF THAT MATTERS \/ double RealDriveHardware::convertToRosPosition(double real_position) { // Convert the rio integer that has been scaled real_position /= RIO_CONVERSION_FACTOR; // Just in case we get values we are not expecting real_position = std::fmod(real_position, 2.0 * M_PI); // Real goes from -2pi to 2pi, we want -pi to pi if (real_position > M_PI) { real_position -= 2.0 * M_PI; } return real_position; } double RealDriveHardware::convertToRosVelocity(double real_velocity) { // Convert the rio integer that has been scaled return real_velocity / RIO_CONVERSION_FACTOR; } hardware_interface::return_type RealDriveHardware::read(const rclcpp::Time &time, const rclcpp::Duration & /*period*/) { rclcpp::spin_some(node_); std::shared_ptr<sensor_msgs::msg::JointState> last_command_msg; received_joint_msg_ptr_.get(last_command_msg); if (last_command_msg == nullptr) { RCLCPP_WARN(rclcpp::get_logger("IsaacDriveHardware"), "[%f] Velocity message received was a nullptr.", time.seconds()); return hardware_interface::return_type::ERROR; } auto names = last_command_msg->name; auto positions = last_command_msg->position; auto velocities = last_command_msg->velocity; // Match Arm and Drive Joints for (auto i = 0u; i < names.size(); i++) { for (const auto & arm_joint : arm_joints_) { if (strcmp(names[i].c_str(), arm_joint.joint_name.c_str()) == 0) { if (arm_joint.percent) { double scale = arm_joint.max - arm_joint.min; hw_positions_[arm_joint.joint_index] = convertToRosPosition(positions[i] * scale + arm_joint.min); hw_velocities_[arm_joint.joint_index] = convertToRosVelocity((float)velocities[i] * scale); } else { hw_positions_[arm_joint.joint_index] = convertToRosPosition(positions[i]); hw_velocities_[arm_joint.joint_index] = convertToRosVelocity((float)velocities[i]); } break; } } for (const auto & drive_joint : drive_joints_) { if (strcmp(names[i].c_str(), drive_joint.joint_name.c_str()) == 0) { hw_positions_[drive_joint.joint_index] = convertToRosPosition(positions[i]); hw_velocities_[drive_joint.joint_index] = convertToRosVelocity((float)velocities[i]); break; } } } // Apply Mimic Joints for (const auto & mimic_joint : mimic_joints_) { hw_positions_[mimic_joint.joint_index] = hw_positions_[mimic_joint.mimicked_joint_index] * mimic_joint.multiplier + mimic_joint.offset; hw_velocities_[mimic_joint.joint_index] = hw_velocities_[mimic_joint.mimicked_joint_index] * mimic_joint.multiplier; } return hardware_interface::return_type::OK; } hardware_interface::return_type swerve_hardware::RealDriveHardware::write(const rclcpp::Time & /*time*/, const rclcpp::Duration & /*period*/) { // convertToRealPositions(hw_command_position_); // convertToRealElevatorPosition(); // Publish to Real for (auto i = 0u; i < drive_joints_.size(); ++i) { auto joint = drive_joints_[i]; hw_command_drive_velocity_output_[i] = hw_command_velocity_[joint.joint_index]; hw_command_drive_position_output_[i] = hw_command_position_[joint.joint_index]; } for (auto i = 0u; i < arm_joints_.size(); ++i) { auto joint = arm_joints_[i]; hw_command_arm_velocity_output_[i] = hw_command_velocity_[joint.joint_index]; hw_command_arm_position_output_[i] = hw_command_position_[joint.joint_index]; } if (realtime_real_publisher_->trylock()) { auto &realtime_real_command_ = realtime_real_publisher_->msg_; realtime_real_command_.header.stamp = node_->get_clock()->now(); realtime_real_command_.name = drive_names_output_; realtime_real_command_.velocity = hw_command_drive_velocity_output_; realtime_real_command_.position = hw_command_drive_position_output_; realtime_real_publisher_->unlockAndPublish(); } if (realtime_real_arm_publisher_->trylock()) { auto &realtime_real_arm_command_ = realtime_real_arm_publisher_->msg_; realtime_real_arm_command_.header.stamp = node_->get_clock()->now(); realtime_real_arm_command_.name = arm_names_output_; realtime_real_arm_command_.velocity = hw_command_arm_velocity_output_; realtime_real_arm_command_.position = hw_command_arm_position_output_; realtime_real_arm_publisher_->unlockAndPublish(); } rclcpp::spin_some(node_); return hardware_interface::return_type::OK; } } // namespace swerve_hardware #include "pluginlib/class_list_macros.hpp" PLUGINLIB_EXPORT_CLASS( swerve_hardware::RealDriveHardware, hardware_interface::SystemInterface)
16,614
C++
37.820093
155
0.648429
RoboEagles4828/offseason2023/src/swerve_hardware/include/swerve_hardware/visibility_control.h
// Copyright 2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* This header must be included by all rclcpp headers which declare symbols * which are defined in the rclcpp library. When not building the rclcpp * library, i.e. when using the headers in other package's code, the contents * of this header change the visibility of certain symbols which the rclcpp * library cannot have, but the consuming code must have inorder to link. */ #ifndef SWERVE_HARDWARE__VISIBILITY_CONTROL_H_ #define SWERVE_HARDWARE__VISIBILITY_CONTROL_H_ // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define SWERVE_HARDWARE_EXPORT __attribute__((dllexport)) #define SWERVE_HARDWARE_IMPORT __attribute__((dllimport)) #else #define SWERVE_HARDWARE_EXPORT __declspec(dllexport) #define SWERVE_HARDWARE_IMPORT __declspec(dllimport) #endif #ifdef SWERVE_HARDWARE_BUILDING_DLL #define SWERVE_HARDWARE_PUBLIC SWERVE_HARDWARE_EXPORT #else #define SWERVE_HARDWARE_PUBLIC SWERVE_HARDWARE_IMPORT #endif #define SWERVE_HARDWARE_PUBLIC_TYPE SWERVE_HARDWARE_PUBLIC #define SWERVE_HARDWARE_LOCAL #else #define SWERVE_HARDWARE_EXPORT __attribute__((visibility("default"))) #define SWERVE_HARDWARE_IMPORT #if __GNUC__ >= 4 #define SWERVE_HARDWARE_PUBLIC __attribute__((visibility("default"))) #define SWERVE_HARDWARE_LOCAL __attribute__((visibility("hidden"))) #else #define SWERVE_HARDWARE_PUBLIC #define SWERVE_HARDWARE_LOCAL #endif #define SWERVE_HARDWARE_PUBLIC_TYPE #endif #endif // SWERVE_HARDWARE__VISIBILITY_CONTROL_H_
2,184
C
38.017856
79
0.763278
RoboEagles4828/offseason2023/src/swerve_hardware/include/swerve_hardware/real_drive.hpp
// Copyright 2021 ros2_control Development Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SWERVE_HARDWARE__REAL_DRIVE_HPP_ #define SWERVE_HARDWARE__REAL_DRIVE_HPP_ #include <memory> #include <string> #include <vector> #include <map> #include "hardware_interface/handle.hpp" #include "hardware_interface/hardware_info.hpp" #include "hardware_interface/system_interface.hpp" #include "hardware_interface/types/hardware_interface_return_values.hpp" #include "rclcpp/clock.hpp" #include "rclcpp/duration.hpp" #include "rclcpp/macros.hpp" #include "rclcpp/time.hpp" #include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp" #include "rclcpp_lifecycle/state.hpp" #include "rclcpp/rclcpp.hpp" #include "sensor_msgs/msg/joint_state.hpp" #include "realtime_tools/realtime_box.h" #include "realtime_tools/realtime_buffer.h" #include "realtime_tools/realtime_publisher.h" #include "swerve_hardware/visibility_control.h" namespace swerve_hardware { class RealDriveHardware : public hardware_interface::SystemInterface { public: RCLCPP_SHARED_PTR_DEFINITIONS(RealDriveHardware) SWERVE_HARDWARE_PUBLIC hardware_interface::CallbackReturn on_init(const hardware_interface::HardwareInfo & info) override; SWERVE_HARDWARE_PUBLIC std::vector<hardware_interface::StateInterface> export_state_interfaces() override; SWERVE_HARDWARE_PUBLIC std::vector<hardware_interface::CommandInterface> export_command_interfaces() override; SWERVE_HARDWARE_PUBLIC hardware_interface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_HARDWARE_PUBLIC hardware_interface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_HARDWARE_PUBLIC hardware_interface::return_type read(const rclcpp::Time & time, const rclcpp::Duration & period) override; SWERVE_HARDWARE_PUBLIC hardware_interface::return_type write(const rclcpp::Time & time, const rclcpp::Duration & period) override; private: double RIO_CONVERSION_FACTOR = 10000.0; // Store the command for the simulated robot std::vector<double> hw_command_velocity_; std::vector<double> hw_command_position_; // Output Topic Vectors std::vector<std::string> arm_names_output_; std::vector<double> hw_command_arm_velocity_output_; std::vector<double> hw_command_arm_position_output_; std::vector<std::string> drive_names_output_; std::vector<double> hw_command_drive_velocity_output_; std::vector<double> hw_command_drive_position_output_; // The state vectors std::vector<double> hw_positions_; std::vector<double> hw_velocities_; std::vector<double> hw_positions_input_; std::vector<double> hw_velocities_input_; // Mimic Joints for joints not controlled by the real robot struct MimicJoint { std::size_t joint_index; std::size_t mimicked_joint_index; double multiplier = 1.0; double offset = 0.0; }; std::vector<MimicJoint> mimic_joints_; double parse_double(const std::string & text); bool parse_bool(const std::string & text); // Keep Track of Arm vs Drive Joints struct JointGroupMember { std::size_t joint_index; std::string joint_name; bool percent = false; double min = -1.0; double max = 1.0; }; std::vector<JointGroupMember> drive_joints_; std::vector<JointGroupMember> arm_joints_; // Joint name array will align with state and command interface array // The command at index 3 of hw_command_ will be the joint name at index 3 of joint_names std::vector<std::string> joint_names_; std::vector<std::string> joint_types_; // Pub Sub to real std::string joint_state_topic_ = "real_joint_states"; std::string joint_command_topic_ = "real_joint_commands"; std::string joint_arm_command_topic_ = "real_arm_commands"; rclcpp::Node::SharedPtr node_; std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::JointState>> real_publisher_ = nullptr; std::shared_ptr<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>> realtime_real_publisher_ = nullptr; std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::JointState>> real_arm_publisher_ = nullptr; std::shared_ptr<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>> realtime_real_arm_publisher_ = nullptr; bool subscriber_is_active_ = false; rclcpp::Subscription<sensor_msgs::msg::JointState>::SharedPtr real_subscriber_ = nullptr; realtime_tools::RealtimeBox<std::shared_ptr<sensor_msgs::msg::JointState>> received_joint_msg_ptr_{nullptr}; // Converts isaac position range -2pi - 2pi into expected ros position range -pi - pi double convertToRosPosition(double real_position); double convertToRosVelocity(double real_velocity); // void convertToRealPositions(std::vector<double> ros_positions); }; } // namespace swerve_hardware #endif // SWERVE_HARDWARE__DIFFBOT_SYSTEM_HPP_
5,378
C++
37.148936
110
0.748605
RoboEagles4828/offseason2023/src/swerve_hardware/include/swerve_hardware/test_drive.hpp
// Copyright 2021 ros2_control Development Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SWERVE_HARDWARE__TEST_DRIVE_HPP_ #define SWERVE_HARDWARE__TEST_DRIVE_HPP_ #include <memory> #include <string> #include <vector> #include <map> #include "hardware_interface/handle.hpp" #include "hardware_interface/hardware_info.hpp" #include "hardware_interface/system_interface.hpp" #include "hardware_interface/types/hardware_interface_return_values.hpp" #include "rclcpp/clock.hpp" #include "rclcpp/duration.hpp" #include "rclcpp/macros.hpp" #include "rclcpp/time.hpp" #include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp" #include "rclcpp_lifecycle/state.hpp" #include "swerve_hardware/visibility_control.h" #include "swerve_hardware/motion_magic.hpp" namespace swerve_hardware { class TestDriveHardware : public hardware_interface::SystemInterface { public: RCLCPP_SHARED_PTR_DEFINITIONS(TestDriveHardware) SWERVE_HARDWARE_PUBLIC hardware_interface::CallbackReturn on_init(const hardware_interface::HardwareInfo & info) override; SWERVE_HARDWARE_PUBLIC std::vector<hardware_interface::StateInterface> export_state_interfaces() override; SWERVE_HARDWARE_PUBLIC std::vector<hardware_interface::CommandInterface> export_command_interfaces() override; SWERVE_HARDWARE_PUBLIC hardware_interface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_HARDWARE_PUBLIC hardware_interface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_HARDWARE_PUBLIC hardware_interface::return_type read(const rclcpp::Time & time, const rclcpp::Duration & period) override; SWERVE_HARDWARE_PUBLIC hardware_interface::return_type write(const rclcpp::Time & time, const rclcpp::Duration & period) override; private: // Store the command for the simulated robot std::vector<double> hw_command_velocity_; std::vector<double> hw_command_position_; // The state vectors std::vector<double> hw_positions_; std::vector<double> hw_velocities_; // Joint name array will align with state and command interface array // The command at index 3 of hw_command_ will be the joint name at index 3 of joint_names std::vector<std::string> joint_names_; std::vector<std::string> joint_types_; double MAX_VELOCITY = 20 * M_PI; double MAX_ACCELERATION = 25 * M_PI; std::vector<MotionMagic> motion_magic_; }; } // namespace swerve_hardware #endif // SWERVE_HARDWARE__TEST_DRIVE_HPP_
3,033
C++
34.694117
109
0.765249
RoboEagles4828/offseason2023/src/swerve_hardware/include/swerve_hardware/motion_magic.hpp
#ifndef SWERVE_HARDWARE__MOTION_MAGIC_HPP_ #define SWERVE_HARDWARE__MOTION_MAGIC_HPP_ #include <memory> #include <queue> #include <string> #include <utility> #include <vector> #include <cmath> #include "swerve_hardware/visibility_control.h" namespace swerve_hardware { class MotionMagic { public: SWERVE_HARDWARE_PUBLIC MotionMagic(double maxAcceleration, double maxVelocity); SWERVE_HARDWARE_PUBLIC double getNextVelocity(const double targetPosition, const double sensorPosition, const double sensorVelocity, const double dt); SWERVE_HARDWARE_PUBLIC double getPositionDifference(double targetPosition, double sensorPosition); SWERVE_HARDWARE_PUBLIC double getTotalTime(double targetPosition); private: double MAX_ACCELERATION; double MAX_VELOCITY; double MAX_JERK = 6 * M_PI; double prevVel = 0.0; double prevAcceleration = 0.0; double prevError = 0.0; double prevTargetPosition = 0.0; double totalDistance = 0.0; double zeroTime = 0.0; double tolerance = 0.15; double rampWindow1 = 0.3; double rampWindow2 = 0.8; double velocityInRampWindow1 = 0.1; double velocityInRampWindow2 = 2.0; double velocityInCruiseWindow = 3.0; }; } // namespace swerve_hardware #endif // SWERVE_HARDWARE__MOTION_MAGIC_HPP_
1,307
C++
24.153846
131
0.729151
RoboEagles4828/offseason2023/src/swerve_hardware/include/swerve_hardware/isaac_drive.hpp
// Copyright 2021 ros2_control Development Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SWERVE_HARDWARE__ISAAC_DRIVE_HPP_ #define SWERVE_HARDWARE__ISAAC_DRIVE_HPP_ #include <memory> #include <string> #include <vector> #include <map> #include "hardware_interface/handle.hpp" #include "hardware_interface/hardware_info.hpp" #include "hardware_interface/system_interface.hpp" #include "hardware_interface/types/hardware_interface_return_values.hpp" #include "rclcpp/clock.hpp" #include "rclcpp/duration.hpp" #include "rclcpp/macros.hpp" #include "rclcpp/time.hpp" #include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp" #include "rclcpp_lifecycle/state.hpp" #include "rclcpp/rclcpp.hpp" #include "sensor_msgs/msg/joint_state.hpp" #include "realtime_tools/realtime_box.h" #include "realtime_tools/realtime_buffer.h" #include "realtime_tools/realtime_publisher.h" #include "swerve_hardware/visibility_control.h" #include "swerve_hardware/motion_magic.hpp" namespace swerve_hardware { class IsaacDriveHardware : public hardware_interface::SystemInterface { public: RCLCPP_SHARED_PTR_DEFINITIONS(IsaacDriveHardware) SWERVE_HARDWARE_PUBLIC hardware_interface::CallbackReturn on_init(const hardware_interface::HardwareInfo & info) override; SWERVE_HARDWARE_PUBLIC std::vector<hardware_interface::StateInterface> export_state_interfaces() override; SWERVE_HARDWARE_PUBLIC std::vector<hardware_interface::CommandInterface> export_command_interfaces() override; SWERVE_HARDWARE_PUBLIC hardware_interface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_HARDWARE_PUBLIC hardware_interface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_HARDWARE_PUBLIC hardware_interface::return_type read(const rclcpp::Time & time, const rclcpp::Duration & period) override; SWERVE_HARDWARE_PUBLIC hardware_interface::return_type write(const rclcpp::Time & time, const rclcpp::Duration & period) override; private: // Store the command for the simulated robot std::vector<double> hw_command_velocity_; std::vector<double> hw_command_position_; std::vector<double> hw_command_velocity_converted_; // The state vectors std::vector<double> hw_positions_; std::vector<double> hw_velocities_; // Joint name array will align with state and command interface array // The command at index 3 of hw_command_ will be the joint name at index 3 of joint_names std::vector<std::string> joint_names_; std::vector<std::string> joint_types_; double MAX_VELOCITY = 2 * M_PI; double MAX_ACCELERATION = 4 * M_PI; double previous_velocity = 0.0; std::vector<MotionMagic> motion_magic_; // Pub Sub to isaac std::string joint_state_topic_ = "isaac_joint_states"; std::string joint_command_topic_ = "isaac_joint_commands"; rclcpp::Node::SharedPtr node_; std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::JointState>> isaac_publisher_ = nullptr; std::shared_ptr<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>> realtime_isaac_publisher_ = nullptr; bool subscriber_is_active_ = false; rclcpp::Subscription<sensor_msgs::msg::JointState>::SharedPtr isaac_subscriber_ = nullptr; realtime_tools::RealtimeBox<std::shared_ptr<sensor_msgs::msg::JointState>> received_joint_msg_ptr_{nullptr}; std::vector<double> empty_; // Converts isaac position range -2pi - 2pi into expected ros position range -pi - pi double convertToRosPosition(double isaac_position); double convertToRosVelocity(double isaac_velocity); void convertToIsaacVelocities(std::vector<double> ros_velocities); }; } // namespace swerve_hardware #endif // SWERVE_HARDWARE__DIFFBOT_SYSTEM_HPP_
4,262
C++
38.110091
110
0.762787
RoboEagles4828/offseason2023/src/teleop_twist_joy/src/teleop_twist_joy.cpp
/** Software License Agreement (BSD) \authors Mike Purvis <[email protected]> \copyright Copyright (c) 2014, Clearpath Robotics, Inc., All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR- RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN- DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cinttypes> #include <functional> #include <map> #include <memory> #include <set> #include <string> #include <geometry_msgs/msg/twist.hpp> #include <rclcpp/rclcpp.hpp> #include <rclcpp_components/register_node_macro.hpp> #include <rcutils/logging_macros.h> #include <sensor_msgs/msg/joy.hpp> #include "sensor_msgs/msg/imu.hpp" #include "teleop_twist_joy/teleop_twist_joy.hpp" #include "edna_interfaces/srv/set_bool.hpp" #include <functional> // for bind() using namespace std; #define ROS_INFO_NAMED RCUTILS_LOG_INFO_NAMED #define ROS_INFO_COND_NAMED RCUTILS_LOG_INFO_EXPRESSION_NAMED namespace teleop_twist_joy { /** * Internal members of class. This is the pimpl idiom, and allows more flexibility in adding * parameters later without breaking ABI compatibility, for robots which link TeleopTwistJoy * directly into base nodes. */ struct TeleopTwistJoy::Impl { void joyCallback(const sensor_msgs::msg::Joy::SharedPtr joy); void sendCmdVelMsg(const sensor_msgs::msg::Joy::SharedPtr &, const std::string &which_map); void imuCallback(const sensor_msgs::msg::Imu::SharedPtr imu_msg); void timerCallback(); void resetOrientationCallback(const std::shared_ptr<edna_interfaces::srv::SetBool::Request> request, std::shared_ptr<edna_interfaces::srv::SetBool::Response> response); rclcpp::Subscription<sensor_msgs::msg::Joy>::SharedPtr joy_sub; rclcpp::Subscription<sensor_msgs::msg::Imu>::SharedPtr imu_sub; rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr cmd_vel_pub; rclcpp::Service<edna_interfaces::srv::SetBool>::SharedPtr reset_orientation_service; rclcpp::TimerBase::SharedPtr timer_callback_; rclcpp::Client<edna_interfaces::srv::SetBool>::SharedPtr start_writer_client_; sensor_msgs::msg::Imu::SharedPtr last_msg; bool require_enable_button; int64_t enable_button; int64_t enable_turbo_button; int64_t enable_field_oriented_button; int64_t start_writer_button; int fieldOrientationButtonLastState = 0; int turboButtonLastState = 0; double last_offset = 0.0; double rotation_offset = 0.0; bool fieldOrientationEnabled = true; bool turboEnabled = false; int serviceButtonLastState = 0; bool serviceEnabled = false; std::map<std::string, int64_t> axis_linear_map; std::map<std::string, std::map<std::string, double>> scale_linear_map; std::map<std::string, int64_t> axis_angular_map; std::map<std::string, std::map<std::string, double>> scale_angular_map; bool sent_disable_msg; }; /** * Constructs TeleopTwistJoy. */ TeleopTwistJoy::TeleopTwistJoy(const rclcpp::NodeOptions &options) : Node("teleop_twist_joy_node", options) { pimpl_ = new Impl; // rclcpp::Node node = Node("teleop_twist_joy_node", options); sensor_msgs/msg/Imu pimpl_->cmd_vel_pub = this->create_publisher<geometry_msgs::msg::Twist>("cmd_vel", 10); pimpl_->imu_sub = this->create_subscription<sensor_msgs::msg::Imu>("zed/imu/data", rclcpp::QoS(10).best_effort(), std::bind(&TeleopTwistJoy::Impl::imuCallback, this->pimpl_, std::placeholders::_1)); pimpl_->joy_sub = this->create_subscription<sensor_msgs::msg::Joy>("joy", rclcpp::QoS(10).best_effort(), std::bind(&TeleopTwistJoy::Impl::joyCallback, this->pimpl_, std::placeholders::_1)); // pimpl_->client = this->create_client<writer_srv::srv::StartWriter>("start_writer"); // pimpl_->timer_callback_ = this->create_wall_timer(std::chrono::duration<double>(0.1), std::bind(&TeleopTwistJoy::Impl::timerCallback,this->pimpl_)); // pimpl_->client = create_client<writer_srv::srv::StartWriter>("start_writer", // [this](std::shared_ptr<writer_srv::srv::StartWriter::Request> /*request*/, // NOLINT // std::shared_ptr<writer_srv::srv::StartWriter::Response> response) { // NOLINT // return startServiceCallback(std::move(response)); // NOLINT pimpl_->reset_orientation_service = create_service<edna_interfaces::srv::SetBool>("reset_field_oriented", std::bind(&TeleopTwistJoy::Impl::resetOrientationCallback, this->pimpl_, std::placeholders::_1, std::placeholders::_2)); // }); pimpl_->start_writer_client_ = create_client<edna_interfaces::srv::SetBool>("set_bool"); pimpl_->require_enable_button = this->declare_parameter("require_enable_button", true); pimpl_->enable_button = this->declare_parameter("enable_button", 5); pimpl_->enable_turbo_button = this->declare_parameter("enable_turbo_button", -1); pimpl_->enable_field_oriented_button = this->declare_parameter("enable_field_oriented_button", 8); pimpl_->start_writer_button = this->declare_parameter("start_writer_button", 6); this->declare_parameter("offset", 0.0); pimpl_->last_offset = this->get_parameter("offset").as_double(); std::map<std::string, int64_t> default_linear_map{ {"x", 5L}, {"y", -1L}, {"z", -1L}, }; this->declare_parameters("axis_linear", default_linear_map); this->get_parameters("axis_linear", pimpl_->axis_linear_map); std::map<std::string, int64_t> default_angular_map{ {"yaw", 2L}, {"pitch", -1L}, {"roll", -1L}, }; this->declare_parameters("axis_angular", default_angular_map); this->get_parameters("axis_angular", pimpl_->axis_angular_map); std::map<std::string, double> default_scale_linear_normal_map{ {"x", 0.5}, {"y", 0.0}, {"z", 0.0}, }; this->declare_parameters("scale_linear", default_scale_linear_normal_map); this->get_parameters("scale_linear", pimpl_->scale_linear_map["normal"]); std::map<std::string, double> default_scale_linear_turbo_map{ {"x", 1.0}, {"y", 0.0}, {"z", 0.0}, }; this->declare_parameters("scale_linear_turbo", default_scale_linear_turbo_map); this->get_parameters("scale_linear_turbo", pimpl_->scale_linear_map["turbo"]); std::map<std::string, double> default_scale_angular_normal_map{ {"yaw", 0.5}, {"pitch", 0.0}, {"roll", 0.0}, }; this->declare_parameters("scale_angular", default_scale_angular_normal_map); this->get_parameters("scale_angular", pimpl_->scale_angular_map["normal"]); std::map<std::string, double> default_scale_angular_turbo_map{ {"yaw", 1.0}, {"pitch", 0.0}, {"roll", 0.0}, }; this->declare_parameters("scale_angular_turbo", default_scale_angular_turbo_map); this->get_parameters("scale_angular_turbo", pimpl_->scale_angular_map["turbo"]); ROS_INFO_COND_NAMED(pimpl_->require_enable_button, "TeleopTwistJoy", "Teleop enable button %" PRId64 ".", pimpl_->enable_button); ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0, "TeleopTwistJoy", "Turbo on button %" PRId64 ".", pimpl_->enable_turbo_button); for (std::map<std::string, int64_t>::iterator it = pimpl_->axis_linear_map.begin(); it != pimpl_->axis_linear_map.end(); ++it) { ROS_INFO_COND_NAMED(it->second != -1L, "TeleopTwistJoy", "Linear axis %s on %" PRId64 " at scale %f.", it->first.c_str(), it->second, pimpl_->scale_linear_map["normal"][it->first]); ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0 && it->second != -1, "TeleopTwistJoy", "Turbo for linear axis %s is scale %f.", it->first.c_str(), pimpl_->scale_linear_map["turbo"][it->first]); } for (std::map<std::string, int64_t>::iterator it = pimpl_->axis_angular_map.begin(); it != pimpl_->axis_angular_map.end(); ++it) { ROS_INFO_COND_NAMED(it->second != -1L, "TeleopTwistJoy", "Angular axis %s on %" PRId64 " at scale %f.", it->first.c_str(), it->second, pimpl_->scale_angular_map["normal"][it->first]); ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0 && it->second != -1, "TeleopTwistJoy", "Turbo for angular axis %s is scale %f.", it->first.c_str(), pimpl_->scale_angular_map["turbo"][it->first]); } pimpl_->sent_disable_msg = false; auto param_callback = [this](std::vector<rclcpp::Parameter> parameters) { static std::set<std::string> intparams = {"axis_linear.x", "axis_linear.y", "axis_linear.z", "axis_angular.yaw", "axis_angular.pitch", "axis_angular.roll", "enable_button", "enable_turbo_button", "enable_field_oriented_button", "start_writer_button", "offset"}; static std::set<std::string> doubleparams = {"scale_linear.x", "scale_linear.y", "scale_linear.z", "scale_linear_turbo.x", "scale_linear_turbo.y", "scale_linear_turbo.z", "scale_angular.yaw", "scale_angular.pitch", "scale_angular.roll", "scale_angular_turbo.yaw", "scale_angular_turbo.pitch", "scale_angular_turbo.roll"}; static std::set<std::string> boolparams = {"require_enable_button"}; auto result = rcl_interfaces::msg::SetParametersResult(); result.successful = true; // Loop to check if changed parameters are of expected data type for (const auto &parameter : parameters) { if (intparams.count(parameter.get_name()) == 1) { if (parameter.get_type() != rclcpp::ParameterType::PARAMETER_INTEGER) { result.reason = "Only integer values can be set for '" + parameter.get_name() + "'."; RCLCPP_WARN(this->get_logger(), result.reason.c_str()); result.successful = false; return result; } } else if (doubleparams.count(parameter.get_name()) == 1) { if (parameter.get_type() != rclcpp::ParameterType::PARAMETER_DOUBLE) { result.reason = "Only double values can be set for '" + parameter.get_name() + "'."; RCLCPP_WARN(this->get_logger(), result.reason.c_str()); result.successful = false; return result; } } else if (boolparams.count(parameter.get_name()) == 1) { if (parameter.get_type() != rclcpp::ParameterType::PARAMETER_BOOL) { result.reason = "Only boolean values can be set for '" + parameter.get_name() + "'."; RCLCPP_WARN(this->get_logger(), result.reason.c_str()); result.successful = false; return result; } } } // Loop to assign changed parameters to the member variables for (const auto &parameter : parameters) { if (parameter.get_name() == "require_enable_button") { this->pimpl_->require_enable_button = parameter.get_value<rclcpp::PARAMETER_BOOL>(); } if (parameter.get_name() == "enable_button") { this->pimpl_->enable_button = parameter.get_value<rclcpp::PARAMETER_INTEGER>(); } else if (parameter.get_name() == "enable_turbo_button") { this->pimpl_->enable_turbo_button = parameter.get_value<rclcpp::PARAMETER_INTEGER>(); } else if (parameter.get_name() == "enable_field_oriented_button") { this->pimpl_->enable_field_oriented_button = parameter.get_value<rclcpp::PARAMETER_INTEGER>(); } else if (parameter.get_name() == "start_writer_button") { this->pimpl_->start_writer_button = parameter.get_value<rclcpp::PARAMETER_INTEGER>(); } else if (parameter.get_name() == "axis_linear.x") { this->pimpl_->axis_linear_map["x"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>(); } else if (parameter.get_name() == "axis_linear.y") { this->pimpl_->axis_linear_map["y"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>(); } else if (parameter.get_name() == "axis_linear.z") { this->pimpl_->axis_linear_map["z"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>(); } else if (parameter.get_name() == "axis_angular.yaw") { this->pimpl_->axis_angular_map["yaw"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>(); } else if (parameter.get_name() == "axis_angular.pitch") { this->pimpl_->axis_angular_map["pitch"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>(); } else if (parameter.get_name() == "axis_angular.roll") { this->pimpl_->axis_angular_map["roll"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>(); } else if (parameter.get_name() == "scale_linear_turbo.x") { this->pimpl_->scale_linear_map["turbo"]["x"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>(); } else if (parameter.get_name() == "scale_linear_turbo.y") { this->pimpl_->scale_linear_map["turbo"]["y"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>(); } else if (parameter.get_name() == "scale_linear_turbo.z") { this->pimpl_->scale_linear_map["turbo"]["z"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>(); } else if (parameter.get_name() == "scale_linear.x") { this->pimpl_->scale_linear_map["normal"]["x"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>(); } else if (parameter.get_name() == "scale_linear.y") { this->pimpl_->scale_linear_map["normal"]["y"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>(); } else if (parameter.get_name() == "scale_linear.z") { this->pimpl_->scale_linear_map["normal"]["z"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>(); } else if (parameter.get_name() == "scale_angular_turbo.yaw") { this->pimpl_->scale_angular_map["turbo"]["yaw"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>(); } else if (parameter.get_name() == "scale_angular_turbo.pitch") { this->pimpl_->scale_angular_map["turbo"]["pitch"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>(); } else if (parameter.get_name() == "scale_angular_turbo.roll") { this->pimpl_->scale_angular_map["turbo"]["roll"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>(); } else if (parameter.get_name() == "scale_angular.yaw") { this->pimpl_->scale_angular_map["normal"]["yaw"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>(); } else if (parameter.get_name() == "scale_angular.pitch") { this->pimpl_->scale_angular_map["normal"]["pitch"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>(); } else if (parameter.get_name() == "scale_angular.roll") { this->pimpl_->scale_angular_map["normal"]["roll"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>(); } } return result; }; callback_handle = this->add_on_set_parameters_callback(param_callback); } TeleopTwistJoy::~TeleopTwistJoy() { delete pimpl_; } double getVal(sensor_msgs::msg::Joy::SharedPtr joy_msg, const std::map<std::string, int64_t> &axis_map, const std::map<std::string, double> &scale_map, const std::string &fieldname) { if (axis_map.find(fieldname) == axis_map.end() || axis_map.at(fieldname) == -1L || scale_map.find(fieldname) == scale_map.end() || static_cast<int>(joy_msg->axes.size()) <= axis_map.at(fieldname)) { return 0.0; } return joy_msg->axes[axis_map.at(fieldname)] * scale_map.at(fieldname); } double get_scale_val(const std::map<std::string, int64_t> &axis_map, const std::map<std::string, double> &scale_map, const std::string &fieldname) { if (axis_map.find(fieldname) == axis_map.end() || axis_map.at(fieldname) == -1L || scale_map.find(fieldname) == scale_map.end()) { return 0.0; } return scale_map.at(fieldname); } double get_orientation_val(sensor_msgs::msg::Imu::SharedPtr imu_msg) { if (!imu_msg) { return 0.0; } double x = imu_msg->orientation.x; double y = imu_msg->orientation.y; double z = imu_msg->orientation.z; double w = imu_msg->orientation.w; double siny_cosp = 2 * (w * z + x * y); double cosy_cosp = 1 - 2 * (y * y + z * z); double angle = std::atan2(siny_cosp, cosy_cosp); return angle; } double correct_joystick_pos(const std::map<std::string, double> &scale_map, const std::string &fieldname, double lin_x_vel, double lin_y_vel) { if (sqrt(pow(lin_x_vel, 2) + pow(lin_y_vel, 2)) > 1) { double scale = scale_map.at(fieldname); if (scale < 0.001) { scale *= 10000; } if (fieldname == "x") { double vel_to_correct = sin(atan2(lin_x_vel, lin_y_vel)) * scale; return vel_to_correct; } else if (fieldname == "y") { double vel_to_correct = cos(atan2(lin_x_vel, lin_y_vel)) * scale; return vel_to_correct; } } else { if (fieldname == "x") { double vel_to_correct = sin(atan2(lin_x_vel, lin_y_vel)) * sqrt(pow(lin_x_vel, 2) + pow(lin_y_vel, 2)); return vel_to_correct; } else if (fieldname == "y") { double vel_to_correct = cos(atan2(lin_x_vel, lin_y_vel)) * sqrt(pow(lin_x_vel, 2) + pow(lin_y_vel, 2)); return vel_to_correct; } } return 0.0; } // void TeleopTwistJoy::startServiceCallBack(const std::shared_ptr<edna_interfaces::srv::SetBool::Response> response) // { // if(joy){ // } // } void TeleopTwistJoy::Impl::timerCallback() { // it's good to firstly check if the service server is even ready to be called if (start_writer_client_->service_is_ready() && serviceEnabled && serviceButtonLastState == 1) { auto request = std::make_shared<edna_interfaces::srv::SetBool::Request>(); request->data = true; while (!start_writer_client_->wait_for_service(1s)) { if (!rclcpp::ok()) { RCLCPP_ERROR(rclcpp::get_logger("teleop_twist_joy"), "Interrupted while waiting for the service. Exiting."); break; } RCLCPP_INFO(rclcpp::get_logger("teleop_twist_joy"), "service not available, waiting again..."); } auto result = start_writer_client_->async_send_request(request); } else if (start_writer_client_->service_is_ready() && !serviceEnabled && serviceButtonLastState == 1) { auto request = std::make_shared<edna_interfaces::srv::SetBool::Request>(); request->data = false; while (!start_writer_client_->wait_for_service(1s)) { if (!rclcpp::ok()) { RCLCPP_ERROR(rclcpp::get_logger("teleop_twist_joy"), "Interrupted while waiting for the service. Exiting."); break; } RCLCPP_INFO(rclcpp::get_logger("teleop_twist_joy"), "service not available, waiting again..."); } auto result = start_writer_client_->async_send_request(request); // RCLCPP_INFO(rclcpp::get_logger("teleop_twist_joy"), "Bag recording stopped: %d", !result.get()->recording); // RCLCPP_INFO(rclcpp::get_logger("teleop_twist_joy"), "Path of Bag: %s", result.get()->path.c_str()); } else if (!start_writer_client_->service_is_ready()) RCLCPP_WARN(rclcpp::get_logger("teleop_twist_joy"), "[ServiceClientExample]: not calling service using callback, service not ready!"); } void TeleopTwistJoy::Impl::resetOrientationCallback(const std::shared_ptr<edna_interfaces::srv::SetBool::Request> request, std::shared_ptr<edna_interfaces::srv::SetBool::Response> response) { RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "received service call: %d", request->data); if (request->data) { rotation_offset=3.1415; } response->message = "succeeded"; response->success = true; } void TeleopTwistJoy::Impl::sendCmdVelMsg(const sensor_msgs::msg::Joy::SharedPtr &joy_msg, const std::string &which_map) { // Initializes with zeros by default. auto cmd_vel_msg = std::make_unique<geometry_msgs::msg::Twist>(); double lin_x_vel = getVal(joy_msg, axis_linear_map, scale_linear_map[which_map], "x"); double lin_y_vel = getVal(joy_msg, axis_linear_map, scale_linear_map[which_map], "y"); double ang_z_vel = getVal(joy_msg, axis_angular_map, scale_angular_map[which_map], "yaw"); double temp = correct_joystick_pos(scale_linear_map[which_map], "x", lin_x_vel, lin_y_vel); lin_y_vel = correct_joystick_pos(scale_linear_map[which_map], "y", lin_x_vel, lin_y_vel); lin_x_vel = temp; // RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "%f",lin_x_vel); // for( uint i =0u; i<joy_msg->buttons.size(); i++){ // RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "%d:%d:%ld",joy_msg->buttons[i],i,enable_field_oriented_button); // } if (enable_field_oriented_button >= 0 && static_cast<int>(joy_msg->buttons.size()) > enable_field_oriented_button) { auto state = joy_msg->buttons[enable_field_oriented_button]; if (state == 1 && fieldOrientationButtonLastState == 0) { fieldOrientationEnabled = !fieldOrientationEnabled; RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "Field Oriented: %d", fieldOrientationEnabled); } fieldOrientationButtonLastState = state; } if (start_writer_button >= 0 && static_cast<int>(joy_msg->buttons.size()) > start_writer_button) { auto state = joy_msg->buttons[start_writer_button]; if (state == 1 && serviceButtonLastState == 0) { serviceEnabled = !serviceEnabled; RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "Writer State: %d", serviceEnabled); } serviceButtonLastState = state; } // RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "robot_orientation: %f",last_offset); // Math for field oriented drive if (fieldOrientationEnabled) { double robot_imu_orientation = (get_orientation_val(last_msg)); robot_imu_orientation += (ang_z_vel * last_offset) + rotation_offset; // RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "robot_orientation: %f", robot_imu_orientation); double temp = lin_x_vel * cos(robot_imu_orientation) + lin_y_vel * sin(robot_imu_orientation); lin_y_vel = -1 * lin_x_vel * sin(robot_imu_orientation) + lin_y_vel * cos(robot_imu_orientation); lin_x_vel = temp; } // Set Velocities in twist msg and publish cmd_vel_msg->linear.x = lin_x_vel; cmd_vel_msg->linear.y = lin_y_vel; cmd_vel_msg->linear.z = getVal(joy_msg, axis_linear_map, scale_linear_map[which_map], "z"); cmd_vel_msg->angular.z = getVal(joy_msg, axis_angular_map, scale_angular_map[which_map], "yaw"); cmd_vel_msg->angular.y = getVal(joy_msg, axis_angular_map, scale_angular_map[which_map], "pitch"); cmd_vel_msg->angular.x = getVal(joy_msg, axis_angular_map, scale_angular_map[which_map], "roll"); cmd_vel_pub->publish(std::move(cmd_vel_msg)); sent_disable_msg = false; } void TeleopTwistJoy::Impl::joyCallback(const sensor_msgs::msg::Joy::SharedPtr joy_msg) { if (enable_turbo_button >= 0 && static_cast<int>(joy_msg->buttons.size()) > enable_turbo_button) { auto state = joy_msg->buttons[enable_turbo_button]; if (state == 1 && turboButtonLastState == 0) { turboEnabled = !turboEnabled; RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "Turbo: %d", turboEnabled); } turboButtonLastState = state; } if (turboEnabled) { sendCmdVelMsg(joy_msg, "turbo"); } else if (!require_enable_button || (static_cast<int>(joy_msg->buttons.size()) > enable_button && joy_msg->buttons[enable_button])) { sendCmdVelMsg(joy_msg, "normal"); } else { // When enable button is released, immediately send a single no-motion command // in order to stop the robot. if (!sent_disable_msg) { // Initializes with zeros by default. auto cmd_vel_msg = std::make_unique<geometry_msgs::msg::Twist>(); cmd_vel_pub->publish(std::move(cmd_vel_msg)); sent_disable_msg = true; } } } void TeleopTwistJoy::Impl::imuCallback(const sensor_msgs::msg::Imu::SharedPtr imu_msg) { // Saves current message as global pointer last_msg = imu_msg; } } // namespace teleop_twist_joy RCLCPP_COMPONENTS_REGISTER_NODE(teleop_twist_joy::TeleopTwistJoy)
26,597
C++
43.404007
230
0.615859
RoboEagles4828/offseason2023/src/teleop_twist_joy/src/teleop_node.cpp
/** Software License Agreement (BSD) \file teleop_node.cpp \authors Mike Purvis <[email protected]> \copyright Copyright (c) 2014, Clearpath Robotics, Inc., All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR- RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN- DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <memory> #include <rclcpp/rclcpp.hpp> #include "teleop_twist_joy/teleop_twist_joy.hpp" int main(int argc, char *argv[]) { rclcpp::init(argc, argv); rclcpp::spin(std::make_unique<teleop_twist_joy::TeleopTwistJoy>(rclcpp::NodeOptions())); rclcpp::shutdown(); return 0; }
1,931
C++
44.999999
110
0.785085
RoboEagles4828/offseason2023/src/teleop_twist_joy/include/teleop_twist_joy/teleop_twist_joy.hpp
/** Software License Agreement (BSD) \authors Mike Purvis <[email protected]> \copyright Copyright (c) 2014, Clearpath Robotics, Inc., All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR- RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN- DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TELEOP_TWIST_JOY_TELEOP_TWIST_JOY_H #define TELEOP_TWIST_JOY_TELEOP_TWIST_JOY_H #include <rclcpp/rclcpp.hpp> #include "teleop_twist_joy/teleop_twist_joy_export.h" namespace teleop_twist_joy { /** * Class implementing a basic Joy -> Twist translation. */ class TELEOP_TWIST_JOY_EXPORT TeleopTwistJoy : public rclcpp::Node { public: explicit TeleopTwistJoy(const rclcpp::NodeOptions& options); virtual ~TeleopTwistJoy(); private: struct Impl; Impl* pimpl_; OnSetParametersCallbackHandle::SharedPtr callback_handle; }; } // namespace teleop_twist_joy #endif // TELEOP_TWIST_JOY_TELEOP_TWIST_JOY_H
2,237
C++
41.226414
110
0.788556
RoboEagles4828/offseason2023/src/frc_auton/setup.py
from setuptools import setup package_name = 'frc_auton' setup( name=package_name, version='0.0.0', packages=[package_name], data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), ('share/' + package_name, ['package.xml']), ], install_requires=['setuptools','rosbags'], zip_safe=True, maintainer='admin', maintainer_email='[email protected]', description='TODO: Package description', license='TODO: License declaration', tests_require=['pytest'], entry_points={ 'console_scripts': [ 'reader = frc_auton.reader:main', 'writer = frc_auton.writer:main', ], }, )
721
Python
24.785713
53
0.590846
RoboEagles4828/offseason2023/src/frc_auton/test/test_flake8.py
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ament_flake8.main import main_with_errors import pytest @pytest.mark.flake8 @pytest.mark.linter def test_flake8(): rc, errors = main_with_errors(argv=[]) assert rc == 0, \ 'Found %d code style errors / warnings:\n' % len(errors) + \ '\n'.join(errors)
884
Python
33.03846
74
0.725113
RoboEagles4828/offseason2023/src/frc_auton/test/test_pep257.py
# Copyright 2015 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ament_pep257.main import main import pytest @pytest.mark.linter @pytest.mark.pep257 def test_pep257(): rc = main(argv=['.', 'test']) assert rc == 0, 'Found code style errors / warnings'
803
Python
32.499999
74
0.743462
RoboEagles4828/offseason2023/src/frc_auton/test/test_copyright.py
# Copyright 2015 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ament_copyright.main import main import pytest # Remove the `skip` decorator once the source file(s) have a copyright header @pytest.mark.skip(reason='No copyright header has been placed in the generated source file.') @pytest.mark.copyright @pytest.mark.linter def test_copyright(): rc = main(argv=['.', 'test']) assert rc == 0, 'Found errors'
962
Python
36.03846
93
0.751559
RoboEagles4828/offseason2023/src/frc_auton/frc_auton/test_frc_stage.py
import rclpy from rclpy.node import Node from std_msgs.msg import Bool, String class StagePublisher(Node): def __init__(self): super().__init__('stage_publisher') self.publisher_ = self.create_publisher(String, '/real/frc_stage', 10) timer_period = 0.5 # seconds self.timer = self.create_timer(timer_period, self.timer_callback) self.i = 0 def timer_callback(self): msg = String() msg.data = "AUTON|False|False" self.publisher_.publish(msg) self.get_logger().info('Publishing: %s' % msg.data) self.i += 1 def main(args=None): rclpy.init(args=args) minimal_publisher = StagePublisher() rclpy.spin(minimal_publisher) # Destroy the node explicitly # (optional - otherwise it will be done automatically # when the garbage collector destroys the node object) minimal_publisher.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
974
Python
23.999999
78
0.63347
RoboEagles4828/offseason2023/src/frc_auton/frc_auton/writer.py
from std_msgs.msg import String from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint from geometry_msgs.msg import Twist import rclpy from rclpy.node import Node import os import rclpy from rclpy.node import Node from rclpy.serialization import serialize_message from std_msgs.msg import String from edna_interfaces.srv import SetBool import rosbag2_py # create writer instance and open for writing class StartWriting(Node): def __init__(self): super().__init__('start_writer') self.subscription_stage =self.create_subscription(String, 'frc_stage', self.stage_callback, 10) self.srv = self.create_service(SetBool, 'set_bool', self.service_callback) self.stage = "" self.fms = "False" self.is_disabled = "True" self.service_enabled = False def service_callback(self, request, response): self.bag_writer = BagWriter() self.service_enabled = request.data if(self.service_enabled): self.start_bag_writer() self.get_logger().info(f'Service Enabled: {self.service_enabled}') response.sucess = True response.message = self.bag_writer.path return response def start_bag_writer(self): if (self.stage.lower() == "teleop" or self.stage.lower() == "auton") and (self.fms=='True' or self.service_enabled) and self.is_disabled=='False': rclpy.spin(self.bag_writer) self.bag_writer.destroy_node() rclpy.shutdown() def stage_callback(self, msg): data = str(msg.data).split('|') self.stage = (data[0]) self.fms = str(data[1]) self.is_disabled = str(data[2]) class BagWriter(Node): def __init__(self): super().__init__('bag_writer') self.curr_file_path = os.path.abspath(__file__) self.project_root_path = os.path.abspath(os.path.join(self.curr_file_path, "../../../..")) self.package_root = os.path.join(self.project_root_path, 'src/frc_auton') self.subscription_arm = self.create_subscription(JointTrajectory,'joint_trajectory_controller/joint_trajectory',self.arm_callback,10) self.subscription_swerve = self.create_subscription(Twist,'swerve_controller/cmd_vel_unstamped',self.swerve_callback,10) file_counter= int(len(os.listdir(f'{self.package_root}/frc_auton/Auto_ros_bag'))) self.path = f'{self.package_root}/frc_auton/Auto_ros_bag/bag_'+str(file_counter) self.writer = rosbag2_py.SequentialWriter() storage_options = rosbag2_py._storage.StorageOptions(uri=self.path,storage_id='sqlite3') converter_options = rosbag2_py._storage.ConverterOptions('', '') self.writer.open(storage_options, converter_options) topic_info_arm = rosbag2_py._storage.TopicMetadata(name=self.subscription_arm.topic_name,type='trajectory_msgs/msg/JointTrajectory',serialization_format='cdr') self.writer.create_topic(topic_info_arm) topic_info_swerve = rosbag2_py._storage.TopicMetadata(name=self.subscription_swerve.topic_name,type='geometry_msgs/msg/Twist',serialization_format='cdr') self.writer.create_topic(topic_info_swerve) def swerve_callback(self, msg): self.writer.write( self.subscription_swerve.topic_name, serialize_message(msg), self.get_clock().now().nanoseconds) def arm_callback(self, msg): self.writer.write( self.subscription_arm.topic_name, serialize_message(msg), self.get_clock().now().nanoseconds) def main(args=None): rclpy.init(args=args) service_writer = StartWriting() rclpy.spin(service_writer) service_writer.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
3,865
Python
39.694736
167
0.649677
RoboEagles4828/offseason2023/src/frc_auton/frc_auton/policy_runner.py
import rclpy from rclpy.node import Node from std_msgs.msg import Float32 from nav_msgs.msg import Odometry from sensor_msgs.msg import JointState from geometry_msgs.msg import Twist import numpy as np import torch from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint class Reader(Node): def __init__(self): super().__init__("reinforcement_learning_runner") # self.robot_ip = robot_ip self.policy = torch.load("/workspaces/edna2023/isaac/Swervesim/swervesim/runs/SwerveCS/nn/SwerveCS.pth") self.joint_action_pub = self.create_publisher(Twist, "cmd_vel", 10) self.joint_trajectory_action_pub = self.create_publisher(Twist, "joint_trajectory_message", 10) self.odom_sub = self.create_subscription(Float32, "odom", self.odom_callback, 10) self.joint_state_sub = self.create_subscription(Float32, "joint_state", self.joint_state_callback, 10) self.odom_msg = Odometry() self.joint_state_msg = JointState() self.twist_msg = Twist() self.cmds = JointTrajectory() self.position_cmds = JointTrajectoryPoint() self.episode_reward = 0 self.step = 0 self.joints = [ 'arm_roller_bar_joint', 'elevator_center_joint', 'elevator_outer_1_joint', 'elevator_outer_2_joint', 'top_gripper_right_arm_joint', 'top_gripper_left_arm_joint', 'top_slider_joint', 'bottom_intake_joint', ] def get_action(self, msg): obs = np.array([msg.data], dtype=np.float32) action = self.policy(torch.tensor(obs).float()) self.twist_msg.linear.x = action[0].detach().numpy() self.twist_msg.linear.y = action[1].detach().numpy() self.twist_msg.angular.z = action[2].detach().numpy() self.position_cmds.positions = [ action[3].detach().numpy(), action[4].detach().numpy(), action[5].detach().numpy(), action[4].detach().numpy(), action[6].detach().numpy(), action[6].detach().numpy(), action[7].detach().numpy(), action[6].detach().numpy(), action[8].detach().numpy(), action[8].detach().numpy(), ] self.cmds.joint_names = self.joints self.cmds.points = [self.position_cmds] self.publisher_.publish(self.cmds) self.action_pub.publish(self.twist_msg) self.step += 1 def joint_state_callback(self, msg): if(msg != None): self.joint_state_msg = msg return def odom_callback(self, msg): if(msg != None): self.odom_msg = msg return def get_reward(): return def main(args=None): # env = gym.create_env("RealRobot", ip=self.robot_ip) rclpy.init(args=args) reader = Reader() rclpy.spin(reader) # env.disconnect() if __name__ == '__main__': main()
2,977
Python
35.765432
112
0.593215
RoboEagles4828/offseason2023/src/frc_auton/frc_auton/reader.py
import rclpy from rclpy.node import Node from geometry_msgs.msg import Twist from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint from std_msgs.msg import String import rosbag2_py from pathlib import Path from rclpy.serialization import deserialize_message import rosbag2_py from std_msgs.msg import String import os from time import time import yaml import math from edna_interfaces.srv import SetBool class MinimalClientAsync(Node): def __init__(self): super().__init__('minimal_client_async') self.client = self.create_client(SetBool, 'reset_field_oriented') while not self.client.wait_for_service(timeout_sec=1.0): self.get_logger().info('service not available, waiting again...') self.request = SetBool.Request() def send_request(self, request): self.request.data = request self.future = self.client.call_async(self.request) rclpy.spin_until_future_complete(self, self.future) return self.future.result() class StageSubscriber(Node): def __init__(self): super().__init__('stage_subscriber') self.curr_file_path = os.path.abspath(__file__) self.project_root_path = os.path.abspath(os.path.join(self.curr_file_path, "../../../..")) self.package_root = os.path.join(self.project_root_path, 'src/frc_auton') # minimal_client = MinimalClientAsync() # response = minimal_client.send_request(True) # minimal_client.get_logger().info( # 'Result of add_two_ints: for %d + %d = %s' % # (True, response.success, response.message)) # rclpy.spin_once(minimal_client) # minimal_client.destroy_node() file_counter= int(len(os.listdir(f'{self.package_root}/frc_auton/Auto_ros_bag')))-1 # self.reader = rosbag2_py.SequentialReader() # self.converter_options = rosbag2_py.ConverterOptions(input_serialization_format='cdr',output_serialization_format='cdr') # self.reader.open(self.storage_options,self.converter_options) if file_counter != -1: self.subscription = self.create_subscription(String,'frc_stage',self.listener_callback,10) self.publish_twist = self.create_publisher(Twist,'swerve_controller/cmd_vel_unstamped',10) self.publish_trajectory = self.create_publisher(JointTrajectory,'joint_trajectory_controller/joint_trajectory',10) self.changed_stage = False self.stage= "" self.fms = "False" self.isdisabled = "True" self.doAuton = False self.cmd = Twist() self.cmd.linear.x = 0.0 self.cmd.linear.y = 0.0 self.cmd.angular.z = 0.0 self.timeInSeconds = 2.0 self.taxiTimeDuration = 2.0 # joint trajectory msg stuff self.joints = [ 'arm_roller_bar_joint', 'elevator_center_joint', 'elevator_outer_1_joint', 'elevator_outer_2_joint', 'top_gripper_right_arm_joint', 'top_gripper_left_arm_joint', 'top_slider_joint', 'bottom_intake_joint', ] self.cmds: JointTrajectory = JointTrajectory() self.cmds.joint_names = self.joints self.position_cmds = JointTrajectoryPoint() self.cmds.points = [self.position_cmds] self.cmds.points[0].positions = [0.0] * len(self.joints) # yaml self.curr_file_path = os.path.abspath(__file__) self.project_root_path = os.path.abspath(os.path.join(self.curr_file_path, "../../../..")) self.yaml_path = os.path.join(self.project_root_path, 'src/edna_bringup/config/teleop-control.yaml') with open(self.yaml_path, 'r') as f: self.yaml = yaml.safe_load(f) self.joint_map = self.yaml['joint_mapping'] self.joint_limits = self.yaml["joint_limits"] # task times self.tasks = [ { 'dur': 0.25, 'task': self.gripperManager, 'arg': 0 }, { 'dur': 0.5, 'task': self.armHeightManager, 'arg': 1 }, { 'dur': 3.5, 'task': self.armExtensionManager, 'arg': 1 }, { 'dur': 0.5, 'task': self.gripperManager, 'arg': 1 }, { 'dur': 2.5, 'task': self.armExtensionManager, 'arg': 0 }, { 'dur': 0.5, 'task': self.armHeightManager, 'arg': 0 }, { 'dur': 3.0, 'task': self.goBackwards, 'arg': -1.5 }, { 'dur': 0.1, 'task': self.stop, 'arg': 0 }, { 'dur': 2.1, 'task': self.turnAround, 'arg': math.pi / 2 }, { 'dur': 0.1, 'task': self.stop, 'arg': 0 }, ] self.conePlacementDuration = 0 for task in self.tasks: self.conePlacementDuration += task['dur'] # TURN AROUND STUFF self.turnCmd = Twist() self.turnCmd.linear.x = 0.0 self.turnCmd.linear.y = 0.0 self.turnCmd.angular.z = 0.0 self.turnTimeDuration = 2.0 def flip_camera(self): minimal_client = MinimalClientAsync() response = minimal_client.send_request(True) minimal_client.destroy_node() def initAuton(self): self.startTime = time() self.turnStartTime = self.startTime + self.conePlacementDuration + 2 self.changed_stage = False self.doAuton = True self.flip_camera() self.get_logger().info(f"STARTED AUTON AT {self.startTime}") def loopAuton(self): # self.taxiAuton() self.coneAuton() #self.turnAuton() # CONE AUTOMATION STUFF def publishCurrent(self): self.cmds.points = [self.position_cmds] self.publish_trajectory.publish(self.cmds) def armExtensionManager(self, pos): value = '' if(pos == 0): # RETRACT THE ARM value = 'min' self.get_logger().warn("ARM RETRACTED") elif(pos == 1): # EXTEND THE ARM value = 'max' self.get_logger().warn("ARM EXTENDED") self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = self.joint_limits["elevator_center_joint"][value] self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = self.joint_limits["elevator_outer_2_joint"][value] self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"][value] self.publishCurrent() def armHeightManager(self, pos): value = '' if(pos == 0): # LOWER THE ARM value = "min" self.get_logger().warn("ARM LOWERED") elif(pos == 1): # RAISE THE ARM value = "max" self.get_logger().warn("ARM RAISED") self.position_cmds.positions[int(self.joint_map['arm_roller_bar_joint'])] = self.joint_limits["arm_roller_bar_joint"][value] self.position_cmds.positions[int(self.joint_map['elevator_outer_1_joint'])] = self.joint_limits["elevator_outer_1_joint"][value] self.publishCurrent() def gripperManager(self, pos): value = '' if(pos == 1): # OPEN THE GRIPPER value = 'min' self.get_logger().warn("GRIPPER OPENED") elif(pos == 0): # CLOSE THE GRIPPER value = 'max' self.get_logger().warn("GRIPPER CLOSED") self.position_cmds.positions[int(self.joint_map['top_gripper_left_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"][value] self.position_cmds.positions[int(self.joint_map['top_gripper_right_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"][value] self.publishCurrent() def coneAuton(self): elapsedTime = time() - self.startTime totalDur = 0.0 for task in self.tasks: totalDur += task['dur'] if elapsedTime < totalDur: task['task'](task['arg']) return def taxiAuton(self): elapsedTime = time() - self.startTime if elapsedTime < self.taxiTimeDuration: self.cmd.linear.x = 0.5 self.publish_twist.publish(self.cmd) else: return def stop(self, x): self.cmd.linear.x = 0.0 self.cmd.linear.y = 0.0 self.cmd.angular.z = 0.0 self.publish_twist.publish(self.cmd) def goBackwards(self, speed): self.cmd.linear.x = speed self.publish_twist.publish(self.cmd) self.get_logger().warn("GOING BACKWARDS") def turnAround(self, angVel): self.turnCmd.angular.z = angVel self.publish_twist.publish(self.turnCmd) self.get_logger().warn("TURNING") def stopAuton(self): self.cmd.linear.x = 0.0 # Publish twice to just to be safe self.publish_twist.publish(self.cmd) self.publish_twist.publish(self.cmd) self.get_logger().info(f"STOPPED AUTON AT {time()}"), self.doAuton = False def listener_callback(self, msg): # Check when any state has changed, enabled, disabled, auton, teleop, etc. stage = str(msg.data).split("|")[0] isdisabled = str(msg.data).split("|")[2] if stage != self.stage or isdisabled != self.isdisabled: self.changed_stage = True self.stage = stage self.isdisabled = isdisabled # fms = str(msg.data).split("|")[1] # Execute auton actions if(stage.lower() == 'auton' and self.isdisabled == "False"):# and fms == 'True' ): if self.changed_stage: self.initAuton() if self.doAuton: self.loopAuton() # We have moved out of auton enabled mode so stop if we are still running else: if self.doAuton: self.stopAuton() def main(args=None): rclpy.init(args=args) # minimal_client = MinimalClientAsync() # response = minimal_client.send_request(True) # # minimal_client.get_logger().info( # # 'Result of add_two_ints: for %d + %d = %s' % # # (True, response.success, response.message)) # # minimal_client.destroy_node() # minimal_client.destroy_node() stage_subscriber = StageSubscriber() # stage_subscriber.send_request() rclpy.spin(stage_subscriber) # Destroy the node explicitly # (optional - otherwise it will be done automatically # when the garbage collector destroys the node object) stage_subscriber.destroy_node() rclpy.shutdown() if __name__ == '__main__': main() # create reader instance and open for reading
10,919
Python
34.454545
146
0.577617
RoboEagles4828/offseason2023/src/frc_auton/frc_auton/Auto_ros_bag/bag_0/metadata.yaml
rosbag2_bagfile_information: version: 5 storage_identifier: sqlite3 duration: nanoseconds: 33616431360 starting_time: nanoseconds_since_epoch: 1679698398612800019 message_count: 72 topics_with_message_count: - topic_metadata: name: /real/swerve_controller/cmd_vel_unstamped type: geometry_msgs/msg/Twist serialization_format: cdr offered_qos_profiles: "" message_count: 9 - topic_metadata: name: /real/joint_trajectory_controller/joint_trajectory type: trajectory_msgs/msg/JointTrajectory serialization_format: cdr offered_qos_profiles: "" message_count: 63 compression_format: "" compression_mode: "" relative_file_paths: - bag_0_0.db3 files: - path: bag_0_0.db3 starting_time: nanoseconds_since_epoch: 1679698398612800019 duration: nanoseconds: 33616431360 message_count: 72
930
YAML
28.093749
64
0.672043
RoboEagles4828/offseason2023/src/swerve_controller/swerve_plugin.xml
<library path="swerve_controller"> <class name="swerve_controller/SwerveController" type="swerve_controller::SwerveController" base_class_type="controller_interface::ControllerInterface"> <description> The swerve controller transforms linear and angular velocity messages into signals for each wheel(s) and swerve modules. </description> </class> </library>
370
XML
45.374994
154
0.783784
RoboEagles4828/offseason2023/src/swerve_controller/src/speed_limiter.cpp
// Copyright 2020 PAL Robotics S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * Author: Enrique Fernández */ #include <algorithm> #include <stdexcept> #include "swerve_controller/speed_limiter.hpp" #include "rcppmath/clamp.hpp" namespace swerve_controller { SpeedLimiter::SpeedLimiter( bool has_velocity_limits, bool has_acceleration_limits, bool has_jerk_limits, double min_velocity, double max_velocity, double min_acceleration, double max_acceleration, double min_jerk, double max_jerk) : has_velocity_limits_(has_velocity_limits), has_acceleration_limits_(has_acceleration_limits), has_jerk_limits_(has_jerk_limits), min_velocity_(min_velocity), max_velocity_(max_velocity), min_acceleration_(min_acceleration), max_acceleration_(max_acceleration), min_jerk_(min_jerk), max_jerk_(max_jerk) { // Check if limits are valid, max must be specified, min defaults to -max if unspecified if (has_velocity_limits_) { if (std::isnan(max_velocity_)) { throw std::runtime_error("Cannot apply velocity limits if max_velocity is not specified"); } if (std::isnan(min_velocity_)) { min_velocity_ = -max_velocity_; } } if (has_acceleration_limits_) { if (std::isnan(max_acceleration_)) { throw std::runtime_error( "Cannot apply acceleration limits if max_acceleration is not specified"); } if (std::isnan(min_acceleration_)) { min_acceleration_ = -max_acceleration_; } } if (has_jerk_limits_) { if (std::isnan(max_jerk_)) { throw std::runtime_error("Cannot apply jerk limits if max_jerk is not specified"); } if (std::isnan(min_jerk_)) { min_jerk_ = -max_jerk_; } } } double SpeedLimiter::limit(double & v, double v0, double v1, double dt) { const double tmp = v; limit_jerk(v, v0, v1, dt); limit_acceleration(v, v0, dt); limit_velocity(v); return tmp != 0.0 ? v / tmp : 1.0; } double SpeedLimiter::limit_velocity(double & v) { const double tmp = v; if (has_velocity_limits_) { v = rcppmath::clamp(v, min_velocity_, max_velocity_); } return tmp != 0.0 ? v / tmp : 1.0; } double SpeedLimiter::limit_acceleration(double & v, double v0, double dt) { const double tmp = v; if (has_acceleration_limits_) { const double dv_min = min_acceleration_ * dt; const double dv_max = max_acceleration_ * dt; const double dv = rcppmath::clamp(v - v0, dv_min, dv_max); v = v0 + dv; } return tmp != 0.0 ? v / tmp : 1.0; } double SpeedLimiter::limit_jerk(double & v, double v0, double v1, double dt) { const double tmp = v; if (has_jerk_limits_) { const double dv = v - v0; const double dv0 = v0 - v1; const double dt2 = 2. * dt * dt; const double da_min = min_jerk_ * dt2; const double da_max = max_jerk_ * dt2; const double da = rcppmath::clamp(dv - dv0, da_min, da_max); v = v0 + dv0 + da; } return tmp != 0.0 ? v / tmp : 1.0; } } // namespace swerve_controller
3,526
C++
24.014184
100
0.65485